@gram-ai/elements 1.18.0 → 1.18.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/Chat/stories/ColorScheme.stories.d.ts +8 -0
- package/dist/components/Chat/stories/Composer.stories.d.ts +7 -0
- package/dist/components/Chat/stories/Customization.stories.d.ts +8 -0
- package/dist/components/Chat/stories/Density.stories.d.ts +8 -0
- package/dist/components/Chat/stories/FrontendTools.stories.d.ts +6 -0
- package/dist/components/Chat/stories/Modal.stories.d.ts +11 -0
- package/dist/components/Chat/stories/Model.stories.d.ts +6 -0
- package/dist/components/Chat/stories/Plugins.stories.d.ts +6 -0
- package/dist/components/Chat/stories/Radius.stories.d.ts +8 -0
- package/dist/components/Chat/stories/ToolApproval.stories.d.ts +8 -0
- package/dist/components/Chat/stories/Tools.stories.d.ts +6 -0
- package/dist/components/Chat/stories/Variants.stories.d.ts +8 -0
- package/dist/components/Chat/stories/Welcome.stories.d.ts +6 -0
- package/dist/elements.cjs +9 -9
- package/dist/elements.css +1 -1
- package/dist/elements.js +575 -583
- package/dist/types/index.d.ts +9 -5
- package/package.json +1 -1
- package/dist/components/Chat/index.stories.d.ts +0 -42
package/dist/elements.cjs
CHANGED
|
@@ -85,16 +85,16 @@ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the toke
|
|
|
85
85
|
|
|
86
86
|
`)},flush(e){e.enqueue(`data: [DONE]
|
|
87
87
|
|
|
88
|
-
`)}})}},qx={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function LA({status:e,statusText:t,headers:n,stream:o,consumeSseStream:r}){let i=o.pipeThrough(new Fx);if(r){const[a,s]=i.tee();i=a,r({stream:s})}return new Response(i.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:Ba(n,qx)})}function ZA({originalMessages:e,responseMessageId:t}){if(e==null)return;const n=e[e.length-1];return n?.role==="assistant"?n.id:typeof t=="function"?t():t}function FA(e){return e.type.startsWith("data-")}function Vx(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const o in t)if(Object.prototype.hasOwnProperty.call(t,o)){const r=t[o];if(r===void 0)continue;const i=o in e?e[o]:void 0,a=r!==null&&typeof r=="object"&&!Array.isArray(r)&&!(r instanceof Date)&&!(r instanceof RegExp),s=i!=null&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof Date)&&!(i instanceof RegExp);a&&s?n[o]=Vx(i,r):n[o]=r}return n}function qA(e){const t=["ROOT"];let n=-1,o=null;function r(l,u,c){switch(l){case'"':{n=u,t.pop(),t.push(c),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,o=u,t.pop(),t.push(c),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(c),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u,t.pop(),t.push(c),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(c),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(c),t.push("INSIDE_ARRAY_START");break}}}function i(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function a(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let l=0;l<e.length;l++){const u=e[l];switch(t[t.length-1]){case"ROOT":r(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{r(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{i(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=l,t.pop();break}default:{n=l,r(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{r(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(u,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const d=e.substring(o,l+1);!"false".startsWith(d)&&!"true".startsWith(d)&&!"null".startsWith(d)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?i(u,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,l)):n=l;break}}}let s=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{s+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{s+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{s+="]";break}case"INSIDE_LITERAL":{const c=e.substring(o,e.length);"true".startsWith(c)?s+="true".slice(c.length):"false".startsWith(c)?s+="false".slice(c.length):"null".startsWith(c)&&(s+="null".slice(c.length))}}return s}async function Bx(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await wr({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await wr({text:qA(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function As(e){return e.type.startsWith("data-")}function Rs(e){return e.type==="text"}function zs(e){return e.type==="file"}function df(e){return e.type==="reasoning"}function Fr(e){return e.type.startsWith("tool-")}function Lc(e){return e.type==="dynamic-tool"}function pf(e){return Fr(e)||Lc(e)}function Ti(e){return e.type.split("-").slice(1).join("-")}function VA(e){return Lc(e)?e.toolName:Ti(e)}function BA({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function JA({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:o,onError:r,onToolCall:i,onData:a}){return e.pipeThrough(new TransformStream({async transform(s,l){await o(async({state:u,write:c})=>{var d,f,p,g;function h(v){const N=u.message.parts.filter(Fr).find(I=>I.toolCallId===v);if(N==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return N}function b(v){const N=u.message.parts.filter(I=>I.type==="dynamic-tool").find(I=>I.toolCallId===v);if(N==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return N}function y(v){var k;const N=u.message.parts.find(z=>Fr(z)&&z.toolCallId===v.toolCallId),I=v,O=N;N!=null?(N.state=v.state,O.input=I.input,O.output=I.output,O.errorText=I.errorText,O.rawInput=I.rawInput,O.preliminary=I.preliminary,O.providerExecuted=(k=I.providerExecuted)!=null?k:N.providerExecuted,I.providerMetadata!=null&&N.state==="input-available"&&(N.callProviderMetadata=I.providerMetadata)):u.message.parts.push({type:`tool-${v.toolName}`,toolCallId:v.toolCallId,state:v.state,input:I.input,output:I.output,rawInput:I.rawInput,errorText:I.errorText,providerExecuted:I.providerExecuted,preliminary:I.preliminary,...I.providerMetadata!=null?{callProviderMetadata:I.providerMetadata}:{}})}function x(v){var k,N;const I=u.message.parts.find(F=>F.type==="dynamic-tool"&&F.toolCallId===v.toolCallId),O=v,z=I;I!=null?(I.state=v.state,z.toolName=v.toolName,z.input=O.input,z.output=O.output,z.errorText=O.errorText,z.rawInput=(k=O.rawInput)!=null?k:z.rawInput,z.preliminary=O.preliminary,z.providerExecuted=(N=O.providerExecuted)!=null?N:I.providerExecuted,O.providerMetadata!=null&&I.state==="input-available"&&(I.callProviderMetadata=O.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:v.toolName,toolCallId:v.toolCallId,state:v.state,input:O.input,output:O.output,errorText:O.errorText,preliminary:O.preliminary,providerExecuted:O.providerExecuted,...O.providerMetadata!=null?{callProviderMetadata:O.providerMetadata}:{}})}async function $(v){if(v!=null){const k=u.message.metadata!=null?Vx(u.message.metadata,v):v;t!=null&&await fu({value:k,schema:t}),u.message.metadata=k}}switch(s.type){case"text-start":{const v={type:"text",text:"",providerMetadata:s.providerMetadata,state:"streaming"};u.activeTextParts[s.id]=v,u.message.parts.push(v),c();break}case"text-delta":{const v=u.activeTextParts[s.id];v.text+=s.delta,v.providerMetadata=(d=s.providerMetadata)!=null?d:v.providerMetadata,c();break}case"text-end":{const v=u.activeTextParts[s.id];v.state="done",v.providerMetadata=(f=s.providerMetadata)!=null?f:v.providerMetadata,delete u.activeTextParts[s.id],c();break}case"reasoning-start":{const v={type:"reasoning",text:"",providerMetadata:s.providerMetadata,state:"streaming"};u.activeReasoningParts[s.id]=v,u.message.parts.push(v),c();break}case"reasoning-delta":{const v=u.activeReasoningParts[s.id];v.text+=s.delta,v.providerMetadata=(p=s.providerMetadata)!=null?p:v.providerMetadata,c();break}case"reasoning-end":{const v=u.activeReasoningParts[s.id];v.providerMetadata=(g=s.providerMetadata)!=null?g:v.providerMetadata,v.state="done",delete u.activeReasoningParts[s.id],c();break}case"file":{u.message.parts.push({type:"file",mediaType:s.mediaType,url:s.url}),c();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:s.sourceId,url:s.url,title:s.title,providerMetadata:s.providerMetadata}),c();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:s.sourceId,mediaType:s.mediaType,title:s.title,filename:s.filename,providerMetadata:s.providerMetadata}),c();break}case"tool-input-start":{const v=u.message.parts.filter(Fr);u.partialToolCalls[s.toolCallId]={text:"",toolName:s.toolName,index:v.length,dynamic:s.dynamic},s.dynamic?x({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-streaming",input:void 0,providerExecuted:s.providerExecuted}):y({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-streaming",input:void 0,providerExecuted:s.providerExecuted}),c();break}case"tool-input-delta":{const v=u.partialToolCalls[s.toolCallId];v.text+=s.inputTextDelta;const{value:k}=await Bx(v.text);v.dynamic?x({toolCallId:s.toolCallId,toolName:v.toolName,state:"input-streaming",input:k}):y({toolCallId:s.toolCallId,toolName:v.toolName,state:"input-streaming",input:k}),c();break}case"tool-input-available":{s.dynamic?x({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-available",input:s.input,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}):y({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-available",input:s.input,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}),c(),i&&!s.providerExecuted&&await i({toolCall:s});break}case"tool-input-error":{s.dynamic?x({toolCallId:s.toolCallId,toolName:s.toolName,state:"output-error",input:s.input,errorText:s.errorText,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}):y({toolCallId:s.toolCallId,toolName:s.toolName,state:"output-error",input:void 0,rawInput:s.input,errorText:s.errorText,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}),c();break}case"tool-output-available":{if(s.dynamic){const v=b(s.toolCallId);x({toolCallId:s.toolCallId,toolName:v.toolName,state:"output-available",input:v.input,output:s.output,preliminary:s.preliminary})}else{const v=h(s.toolCallId);y({toolCallId:s.toolCallId,toolName:Ti(v),state:"output-available",input:v.input,output:s.output,providerExecuted:s.providerExecuted,preliminary:s.preliminary})}c();break}case"tool-output-error":{if(s.dynamic){const v=b(s.toolCallId);x({toolCallId:s.toolCallId,toolName:v.toolName,state:"output-error",input:v.input,errorText:s.errorText,providerExecuted:s.providerExecuted})}else{const v=h(s.toolCallId);y({toolCallId:s.toolCallId,toolName:Ti(v),state:"output-error",input:v.input,rawInput:v.rawInput,errorText:s.errorText,providerExecuted:s.providerExecuted})}c();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{s.messageId!=null&&(u.message.id=s.messageId),await $(s.messageMetadata),(s.messageId!=null||s.messageMetadata!=null)&&c();break}case"finish":{await $(s.messageMetadata),s.messageMetadata!=null&&c();break}case"message-metadata":{await $(s.messageMetadata),s.messageMetadata!=null&&c();break}case"error":{r?.(new Error(s.errorText));break}default:if(FA(s)){n?.[s.type]!=null&&await fu({value:s.data,schema:n[s.type]});const v=s;if(v.transient){a?.(v);break}const k=v.id!=null?u.message.parts.find(N=>v.type===N.type&&v.id===N.id):void 0;k!=null?k.data=v.data:u.message.parts.push(v),a?.(v),c()}}l.enqueue(s)})}}))}function WA({messageId:e,originalMessages:t=[],onFinish:n,onError:o,stream:r}){let i=t?.[t.length-1];i?.role!=="assistant"?i=void 0:e=i.id;let a=!1;const s=r.pipeThrough(new TransformStream({transform(f,p){if(f.type==="start"){const g=f;g.messageId==null&&e!=null&&(g.messageId=e)}f.type==="abort"&&(a=!0),p.enqueue(f)}}));if(n==null)return s;const l=BA({lastMessage:i?structuredClone(i):void 0,messageId:e??""}),u=async f=>{await f({state:l,write:()=>{}})};let c=!1;const d=async()=>{if(c||!n)return;c=!0;const f=l.message.id===i?.id;await n({isAborted:a,isContinuation:f,responseMessage:l.message,messages:[...f?t.slice(0,-1):t,l.message]})};return JA({stream:s,runUpdateMessageJob:u,onError:o}).pipeThrough(new TransformStream({transform(f,p){p.enqueue(f)},async cancel(){await d()},async flush(){await d()}}))}function HA({response:e,status:t,statusText:n,headers:o,stream:r,consumeSseStream:i}){let a=r.pipeThrough(new Fx);if(i){const[s,l]=a.tee();a=s,i({stream:l})}Zx({response:e,status:t,statusText:n,headers:Object.fromEntries(Ba(o,qx).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function Jo(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){const n=this.getReader();let o=!1;async function r(i){var a;o=!0;try{i&&await((a=n.cancel)==null?void 0:a.call(n))}finally{try{n.releaseLock()}catch{}}}return{async next(){if(o)return{done:!0,value:void 0};const{done:i,value:a}=await n.read();return i?(await r(!0),{done:!0,value:void 0}):{done:!1,value:a}},async return(){return await r(!0),{done:!0,value:void 0}},async throw(i){throw await r(!0),i}}},t}async function GA({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:o}=await n.read();if(o)break}}catch(o){t?.(o)}finally{n.releaseLock()}}function ff(){let e,t;return{promise:new Promise((o,r)=>{e=o,t=r}),resolve:e,reject:t}}function KA(){let e=[],t=null,n=!1,o=ff();const r=()=>{n=!0,o.resolve(),e.forEach(a=>a.cancel()),e=[],t?.close()},i=async()=>{if(n&&e.length===0){t?.close();return}if(e.length===0)return o=ff(),await o.promise,i();try{const{value:a,done:s}=await e[0].read();s?(e.shift(),e.length>0?await i():n&&t?.close()):t?.enqueue(a)}catch(a){t?.error(a),e.shift(),r()}};return{stream:new ReadableStream({start(a){t=a},pull:i,async cancel(){for(const a of e)await a.cancel();e=[],n=!0}}),addStream:a=>{if(n)throw new Error("Cannot add inner stream: outer stream is closed");e.push(a.getReader()),o.resolve()},close:()=>{n=!0,o.resolve(),e.length===0&&t?.close()},terminate:r}}var Wo=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((e,t)=>{this.status.type==="resolved"?e(this.status.value):this.status.type==="rejected"&&t(this.status.error),this._resolve=e,this._reject=t}),this._promise)}resolve(e){var t;this.status={type:"resolved",value:e},this._promise&&((t=this._resolve)==null||t.call(this,e))}reject(e){var t;this.status={type:"rejected",error:e},this._promise&&((t=this._reject)==null||t.call(this,e))}};function YA(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}function QA({tools:e,generatorStream:t,tracer:n,telemetry:o,system:r,messages:i,abortSignal:a,repairToolCall:s,experimental_context:l}){let u=null;const c=new ReadableStream({start(y){u=y}}),d=new Set,f=new Map;let p=!1,g;function h(){p&&d.size===0&&(g!=null&&u.enqueue(g),u.close())}const b=new TransformStream({async transform(y,x){const $=y.type;switch($){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{x.enqueue(y);break}case"file":{x.enqueue({type:"file",file:new AA({data:y.data,mediaType:y.mediaType})});break}case"finish":{g={type:"finish",finishReason:y.finishReason,usage:y.usage,providerMetadata:y.providerMetadata};break}case"tool-call":{try{const v=await RA({toolCall:y,tools:e,repairToolCall:s,system:r,messages:i});if(x.enqueue(v),v.invalid){u.enqueue({type:"tool-error",toolCallId:v.toolCallId,toolName:v.toolName,input:v.input,error:jw(v.error),dynamic:!0});break}const k=e[v.toolName];if(f.set(v.toolCallId,v.input),k.onInputAvailable!=null&&await k.onInputAvailable({input:v.input,toolCallId:v.toolCallId,messages:i,abortSignal:a,experimental_context:l}),k.execute!=null&&v.providerExecuted!==!0){const N=ZC();d.add(N),_u({name:"ai.toolCall",attributes:Lr({telemetry:o,attributes:{...bu({operationId:"ai.toolCall",telemetry:o}),"ai.toolCall.name":v.toolName,"ai.toolCall.id":v.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(v.input)}}}),tracer:n,fn:async I=>{let O;try{const z=e1({execute:k.execute.bind(k),input:v.input,options:{toolCallId:v.toolCallId,messages:i,abortSignal:a,experimental_context:l}});for await(const F of z)u.enqueue({...v,type:"tool-result",output:F.output,...F.type==="preliminary"&&{preliminary:!0}}),F.type==="final"&&(O=F.output)}catch(z){Dx(I,z),u.enqueue({...v,type:"tool-error",error:z}),d.delete(N),h();return}d.delete(N),h();try{I.setAttributes(Lr({telemetry:o,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(O)}}}))}catch{}}})}}catch(v){u.enqueue({type:"error",error:v})}break}case"tool-result":{const v=y.toolName;y.isError?u.enqueue({type:"tool-error",toolCallId:y.toolCallId,toolName:v,input:f.get(y.toolCallId),providerExecuted:y.providerExecuted,error:y.result}):x.enqueue({type:"tool-result",toolCallId:y.toolCallId,toolName:v,input:f.get(y.toolCallId),output:y.result,providerExecuted:y.providerExecuted});break}default:{const v=$;throw new Error(`Unhandled chunk type: ${v}`)}}},flush(){p=!0,h()}});return new ReadableStream({async start(y){return Promise.all([t.pipeThrough(b).pipeTo(new WritableStream({write(x){y.enqueue(x)},close(){}})),c.pipeTo(new WritableStream({write(x){y.enqueue(x)},close(){y.close()}}))])}})}var XA=To({prefix:"aitxt",size:24});function eR({model:e,tools:t,toolChoice:n,system:o,prompt:r,messages:i,maxRetries:a,abortSignal:s,headers:l,stopWhen:u=Lx(1),experimental_output:c,experimental_telemetry:d,prepareStep:f,providerOptions:p,experimental_activeTools:g,activeTools:h=g,experimental_repairToolCall:b,experimental_transform:y,experimental_download:x,includeRawChunks:$=!1,onChunk:v,onError:k=({error:q})=>{console.error(q)},onFinish:N,onAbort:I,onStepFinish:O,experimental_context:z,_internal:{now:F=YA,generateId:te=XA,currentDate:ce=()=>new Date}={},...B}){return new rR({model:Cx(e),telemetry:d,headers:l,settings:B,maxRetries:a,abortSignal:s,system:o,prompt:r,messages:i,tools:t,toolChoice:n,transforms:sf(y),activeTools:h,repairToolCall:b,stopConditions:sf(u),output:c,providerOptions:p,prepareStep:f,includeRawChunks:$,onChunk:v,onError:k,onFinish:N,onAbort:I,onStepFinish:O,now:F,currentDate:ce,generateId:te,experimental_context:z,download:x})}function tR(e){if(!e)return new TransformStream({transform(a,s){s.enqueue({part:a,partialOutput:void 0})}});let t,n="",o="",r="";function i({controller:a,partialOutput:s=void 0}){a.enqueue({part:{type:"text-delta",id:t,text:o},partialOutput:s}),o=""}return new TransformStream({async transform(a,s){if(a.type==="finish-step"&&o.length>0&&i({controller:s}),a.type!=="text-delta"&&a.type!=="text-start"&&a.type!=="text-end"){s.enqueue({part:a,partialOutput:void 0});return}if(t==null)t=a.id;else if(a.id!==t){s.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-start"){s.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-end"){o.length>0&&i({controller:s}),s.enqueue({part:a,partialOutput:void 0});return}n+=a.text,o+=a.text;const l=await e.parsePartial({text:n});if(l!=null){const u=JSON.stringify(l.partial);u!==r&&(i({controller:s,partialOutput:l.partial}),r=u)}}})}var rR=class{constructor({model:e,telemetry:t,headers:n,settings:o,maxRetries:r,abortSignal:i,system:a,prompt:s,messages:l,tools:u,toolChoice:c,transforms:d,activeTools:f,repairToolCall:p,stopConditions:g,output:h,providerOptions:b,prepareStep:y,includeRawChunks:x,now:$,currentDate:v,generateId:k,onChunk:N,onError:I,onFinish:O,onAbort:z,onStepFinish:F,experimental_context:te,download:ce}){this._totalUsage=new Wo,this._finishReason=new Wo,this._steps=new Wo,this.output=h,this.includeRawChunks=x,this.tools=u;let B,q=[];const we=[];let oe,de,K={},fe=[];const J=[];let Ue,ye={},Le={};const U=new TransformStream({async transform(Ee,Te){var Ae,ie,ft,mn;Te.enqueue(Ee);const{part:Z}=Ee;if((Z.type==="text-delta"||Z.type==="reasoning-delta"||Z.type==="source"||Z.type==="tool-call"||Z.type==="tool-result"||Z.type==="tool-input-start"||Z.type==="tool-input-delta"||Z.type==="raw")&&await N?.({chunk:Z}),Z.type==="error"&&await I({error:$A(Z.error)}),Z.type==="text-start"&&(ye[Z.id]={type:"text",text:"",providerMetadata:Z.providerMetadata},q.push(ye[Z.id])),Z.type==="text-delta"){const Ie=ye[Z.id];if(Ie==null){Te.enqueue({part:{type:"error",error:`text part ${Z.id} not found`},partialOutput:void 0});return}Ie.text+=Z.text,Ie.providerMetadata=(Ae=Z.providerMetadata)!=null?Ae:Ie.providerMetadata}if(Z.type==="text-end"){const Ie=ye[Z.id];if(Ie==null){Te.enqueue({part:{type:"error",error:`text part ${Z.id} not found`},partialOutput:void 0});return}Ie.providerMetadata=(ie=Z.providerMetadata)!=null?ie:Ie.providerMetadata,delete ye[Z.id]}if(Z.type==="reasoning-start"&&(Le[Z.id]={type:"reasoning",text:"",providerMetadata:Z.providerMetadata},q.push(Le[Z.id])),Z.type==="reasoning-delta"){const Ie=Le[Z.id];if(Ie==null){Te.enqueue({part:{type:"error",error:`reasoning part ${Z.id} not found`},partialOutput:void 0});return}Ie.text+=Z.text,Ie.providerMetadata=(ft=Z.providerMetadata)!=null?ft:Ie.providerMetadata}if(Z.type==="reasoning-end"){const Ie=Le[Z.id];if(Ie==null){Te.enqueue({part:{type:"error",error:`reasoning part ${Z.id} not found`},partialOutput:void 0});return}Ie.providerMetadata=(mn=Z.providerMetadata)!=null?mn:Ie.providerMetadata,delete Le[Z.id]}if(Z.type==="file"&&q.push({type:"file",file:Z.file}),Z.type==="source"&&q.push(Z),Z.type==="tool-call"&&q.push(Z),Z.type==="tool-result"&&!Z.preliminary&&q.push(Z),Z.type==="tool-error"&&q.push(Z),Z.type==="start-step"&&(K=Z.request,fe=Z.warnings),Z.type==="finish-step"){const Ie=cf({content:q,tools:u}),hn=new zA({content:q,finishReason:Z.finishReason,usage:Z.usage,warnings:fe,request:K,response:{...Z.response,messages:[...we,...Ie]},providerMetadata:Z.providerMetadata});await F?.(hn),A1(fe),J.push(hn),q=[],Le={},ye={},we.push(...Ie),B.resolve()}Z.type==="finish"&&(de=Z.totalUsage,oe=Z.finishReason)},async flush(Ee){try{if(J.length===0){const ft=new U1({message:"No output generated. Check the stream for errors."});je._finishReason.reject(ft),je._totalUsage.reject(ft),je._steps.reject(ft);return}const Te=oe??"unknown",Ae=de??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};je._finishReason.resolve(Te),je._totalUsage.resolve(Ae),je._steps.resolve(J);const ie=J[J.length-1];await O?.({finishReason:Te,totalUsage:Ae,usage:ie.usage,content:ie.content,text:ie.text,reasoningText:ie.reasoningText,reasoning:ie.reasoning,files:ie.files,sources:ie.sources,toolCalls:ie.toolCalls,staticToolCalls:ie.staticToolCalls,dynamicToolCalls:ie.dynamicToolCalls,toolResults:ie.toolResults,staticToolResults:ie.staticToolResults,dynamicToolResults:ie.dynamicToolResults,request:ie.request,response:ie.response,warnings:ie.warnings,providerMetadata:ie.providerMetadata,steps:J}),Ue.setAttributes(Lr({telemetry:t,attributes:{"ai.response.finishReason":Te,"ai.response.text":{output:()=>ie.text},"ai.response.toolCalls":{output:()=>{var ft;return(ft=ie.toolCalls)!=null&&ft.length?JSON.stringify(ie.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(ie.providerMetadata),"ai.usage.inputTokens":Ae.inputTokens,"ai.usage.outputTokens":Ae.outputTokens,"ai.usage.totalTokens":Ae.totalTokens,"ai.usage.reasoningTokens":Ae.reasoningTokens,"ai.usage.cachedInputTokens":Ae.cachedInputTokens}}))}catch(Te){Ee.error(Te)}finally{Ue.end()}}}),Q=KA();this.addStream=Q.addStream,this.closeStream=Q.close;const me=Q.stream.getReader();let xe=new ReadableStream({async start(Ee){Ee.enqueue({type:"start"})},async pull(Ee){function Te(){z?.({steps:J}),Ee.enqueue({type:"abort"}),Ee.close()}try{const{done:Ae,value:ie}=await me.read();if(Ae){Ee.close();return}if(i?.aborted){Te();return}Ee.enqueue(ie)}catch(Ae){_r(Ae)&&i?.aborted?Te():Ee.error(Ae)}},cancel(Ee){return Q.stream.cancel(Ee)}});for(const Ee of d)xe=xe.pipeThrough(Ee({tools:u,stopStream(){Q.terminate()}}));this.baseStream=xe.pipeThrough(tR(h)).pipeThrough(U);const{maxRetries:Ro,retry:ss}=CA({maxRetries:r,abortSignal:i}),fn=EA(t),pt=cA(o),zo=SA({model:e,telemetry:t,headers:n,settings:{...pt,maxRetries:Ro}}),je=this;_u({name:"ai.streamText",attributes:Lr({telemetry:t,attributes:{...bu({operationId:"ai.streamText",telemetry:t}),...zo,"ai.prompt":{input:()=>JSON.stringify({system:a,prompt:s,messages:l})}}}),tracer:fn,endWhenDone:!1,fn:async Ee=>{Ue=Ee;async function Te({currentStep:Ae,responseMessages:ie,usage:ft}){var mn,Z,Ie,hn,Sd;const Id=je.includeRawChunks;B=new Wo;const kd=await xA({system:a,prompt:s,messages:l}),gn=[...kd.messages,...ie],Et=await y?.({model:e,steps:J,stepNumber:J.length,messages:gn}),Nr=Cx((mn=Et?.model)!=null?mn:e),Ed=await aA({prompt:{system:(Z=Et?.system)!=null?Z:kd.system,messages:(Ie=Et?.messages)!=null?Ie:gn},supportedUrls:await Nr.supportedUrls,download:ce}),{toolChoice:us,tools:ls}=pA({tools:u,toolChoice:(hn=Et?.toolChoice)!=null?hn:c,activeTools:(Sd=Et?.activeTools)!=null?Sd:f}),{result:{stream:g0,response:Td,request:Od},doStreamSpan:Pr,startTimestampMs:Nd}=await ss(()=>_u({name:"ai.streamText.doStream",attributes:Lr({telemetry:t,attributes:{...bu({operationId:"ai.streamText.doStream",telemetry:t}),...zo,"ai.model.provider":Nr.provider,"ai.model.id":Nr.modelId,"ai.prompt.messages":{input:()=>TA(Ed)},"ai.prompt.tools":{input:()=>ls?.map(W=>JSON.stringify(W))},"ai.prompt.toolChoice":{input:()=>us!=null?JSON.stringify(us):void 0},"gen_ai.system":Nr.provider,"gen_ai.request.model":Nr.modelId,"gen_ai.request.frequency_penalty":pt.frequencyPenalty,"gen_ai.request.max_tokens":pt.maxOutputTokens,"gen_ai.request.presence_penalty":pt.presencePenalty,"gen_ai.request.stop_sequences":pt.stopSequences,"gen_ai.request.temperature":pt.temperature,"gen_ai.request.top_k":pt.topK,"gen_ai.request.top_p":pt.topP}}),tracer:fn,endWhenDone:!1,fn:async W=>({startTimestampMs:$(),doStreamSpan:W,result:await Nr.doStream({...pt,tools:ls,toolChoice:us,responseFormat:h?.responseFormat,prompt:Ed,providerOptions:b,abortSignal:i,headers:n,includeRawChunks:Id})})})),v0=QA({tools:u,generatorStream:g0,tracer:fn,telemetry:t,system:a,messages:gn,repairToolCall:p,abortSignal:i,experimental_context:te}),y0=Od??{},Mo=[],cs=[];let ds;const ps={};let Cr="unknown",mt={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},fs,Pd=!0,Tt={id:k(),timestamp:v(),modelId:e.modelId},Cd="";je.addStream(v0.pipeThrough(new TransformStream({async transform(W,Re){var vn,yn,Do,Ut;if(W.type==="stream-start"){ds=W.warnings;return}if(Pd){const Ze=$()-Nd;Pd=!1,Pr.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":Ze}),Pr.setAttributes({"ai.response.msToFirstChunk":Ze}),Re.enqueue({type:"start-step",request:y0,warnings:ds??[]})}const jd=W.type;switch(jd){case"text-start":case"text-end":{Re.enqueue(W);break}case"text-delta":{W.delta.length>0&&(Re.enqueue({type:"text-delta",id:W.id,text:W.delta,providerMetadata:W.providerMetadata}),Cd+=W.delta);break}case"reasoning-start":case"reasoning-end":{Re.enqueue(W);break}case"reasoning-delta":{Re.enqueue({type:"reasoning-delta",id:W.id,text:W.delta,providerMetadata:W.providerMetadata});break}case"tool-call":{Re.enqueue(W),Mo.push(W);break}case"tool-result":{Re.enqueue(W),W.preliminary||cs.push(W);break}case"tool-error":{Re.enqueue(W),cs.push(W);break}case"response-metadata":{Tt={id:(vn=W.id)!=null?vn:Tt.id,timestamp:(yn=W.timestamp)!=null?yn:Tt.timestamp,modelId:(Do=W.modelId)!=null?Do:Tt.modelId};break}case"finish":{mt=W.usage,Cr=W.finishReason,fs=W.providerMetadata;const Ze=$()-Nd;Pr.addEvent("ai.stream.finish"),Pr.setAttributes({"ai.response.msToFinish":Ze,"ai.response.avgOutputTokensPerSecond":1e3*((Ut=mt.outputTokens)!=null?Ut:0)/Ze});break}case"file":{Re.enqueue(W);break}case"source":{Re.enqueue(W);break}case"tool-input-start":{ps[W.id]=W.toolName;const Ze=u?.[W.toolName];Ze?.onInputStart!=null&&await Ze.onInputStart({toolCallId:W.id,messages:gn,abortSignal:i,experimental_context:te}),Re.enqueue({...W,dynamic:Ze?.type==="dynamic"});break}case"tool-input-end":{delete ps[W.id],Re.enqueue(W);break}case"tool-input-delta":{const Ze=ps[W.id],ms=u?.[Ze];ms?.onInputDelta!=null&&await ms.onInputDelta({inputTextDelta:W.delta,toolCallId:W.id,messages:gn,abortSignal:i,experimental_context:te}),Re.enqueue(W);break}case"error":{Re.enqueue(W),Cr="error";break}case"raw":{Id&&Re.enqueue(W);break}default:{const Ze=jd;throw new Error(`Unknown chunk type: ${Ze}`)}}},async flush(W){const Re=Mo.length>0?JSON.stringify(Mo):void 0;try{Pr.setAttributes(Lr({telemetry:t,attributes:{"ai.response.finishReason":Cr,"ai.response.text":{output:()=>Cd},"ai.response.toolCalls":{output:()=>Re},"ai.response.id":Tt.id,"ai.response.model":Tt.modelId,"ai.response.timestamp":Tt.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(fs),"ai.usage.inputTokens":mt.inputTokens,"ai.usage.outputTokens":mt.outputTokens,"ai.usage.totalTokens":mt.totalTokens,"ai.usage.reasoningTokens":mt.reasoningTokens,"ai.usage.cachedInputTokens":mt.cachedInputTokens,"gen_ai.response.finish_reasons":[Cr],"gen_ai.response.id":Tt.id,"gen_ai.response.model":Tt.modelId,"gen_ai.usage.input_tokens":mt.inputTokens,"gen_ai.usage.output_tokens":mt.outputTokens}}))}catch{}finally{Pr.end()}W.enqueue({type:"finish-step",finishReason:Cr,usage:mt,providerMetadata:fs,response:{...Tt,headers:Td?.headers}});const vn=OA(ft,mt);await B.promise;const yn=Mo.filter(Ut=>Ut.providerExecuted!==!0),Do=cs.filter(Ut=>Ut.providerExecuted!==!0);if(yn.length>0&&Do.length===yn.length&&!await MA({stopConditions:g,steps:J})){ie.push(...cf({content:J[J.length-1].content,tools:u}));try{await Te({currentStep:Ae+1,responseMessages:ie,usage:vn})}catch(Ut){W.enqueue({type:"error",error:Ut}),je.closeStream()}}else W.enqueue({type:"finish",finishReason:Cr,totalUsage:vn}),je.closeStream()}})))}await Te({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(Ee=>{je.addStream(new ReadableStream({start(Te){Te.enqueue({type:"error",error:Ee}),Te.close()}})),je.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){const[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return Jo(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return Jo(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await GA({stream:this.fullStream,onError:e?.onError})}catch(n){(t=e?.onError)==null||t.call(e,n)}}get experimental_partialOutputStream(){if(this.output==null)throw new P1;return Jo(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:o,sendReasoning:r=!0,sendSources:i=!1,sendStart:a=!0,sendFinish:s=!0,onError:l=sn}={}){const u=t!=null?ZA({originalMessages:e,responseMessageId:t}):void 0,c={},d=p=>{var g,h;const b=c[p];return((h=(g=this.tools)==null?void 0:g[b])==null?void 0:h.type)==="dynamic"?!0:void 0},f=this.fullStream.pipeThrough(new TransformStream({transform:async(p,g)=>{const h=o?.({part:p}),b=p.type;switch(b){case"text-start":{g.enqueue({type:"text-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-delta":{g.enqueue({type:"text-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-end":{g.enqueue({type:"text-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-start":{g.enqueue({type:"reasoning-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-delta":{r&&g.enqueue({type:"reasoning-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-end":{g.enqueue({type:"reasoning-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"file":{g.enqueue({type:"file",mediaType:p.file.mediaType,url:`data:${p.file.mediaType};base64,${p.file.base64}`});break}case"source":{i&&p.sourceType==="url"&&g.enqueue({type:"source-url",sourceId:p.id,url:p.url,title:p.title,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}}),i&&p.sourceType==="document"&&g.enqueue({type:"source-document",sourceId:p.id,mediaType:p.mediaType,title:p.title,filename:p.filename,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"tool-input-start":{c[p.id]=p.toolName;const y=d(p.id);g.enqueue({type:"tool-input-start",toolCallId:p.id,toolName:p.toolName,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...y!=null?{dynamic:y}:{}});break}case"tool-input-delta":{g.enqueue({type:"tool-input-delta",toolCallId:p.id,inputTextDelta:p.delta});break}case"tool-call":{c[p.toolCallId]=p.toolName;const y=d(p.toolCallId);p.invalid?g.enqueue({type:"tool-input-error",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...y!=null?{dynamic:y}:{},errorText:l(p.error)}):g.enqueue({type:"tool-input-available",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...y!=null?{dynamic:y}:{}});break}case"tool-result":{const y=d(p.toolCallId);g.enqueue({type:"tool-output-available",toolCallId:p.toolCallId,output:p.output,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.preliminary!=null?{preliminary:p.preliminary}:{},...y!=null?{dynamic:y}:{}});break}case"tool-error":{const y=d(p.toolCallId);g.enqueue({type:"tool-output-error",toolCallId:p.toolCallId,errorText:l(p.error),...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...y!=null?{dynamic:y}:{}});break}case"error":{g.enqueue({type:"error",errorText:l(p.error)});break}case"start-step":{g.enqueue({type:"start-step"});break}case"finish-step":{g.enqueue({type:"finish-step"});break}case"start":{a&&g.enqueue({type:"start",...h!=null?{messageMetadata:h}:{},...u!=null?{messageId:u}:{}});break}case"finish":{s&&g.enqueue({type:"finish",...h!=null?{messageMetadata:h}:{}});break}case"abort":{g.enqueue(p);break}case"tool-input-end":break;case"raw":break;default:{const y=b;throw new Error(`Unknown chunk type: ${y}`)}}h!=null&&b!=="start"&&b!=="finish"&&g.enqueue({type:"message-metadata",messageMetadata:h})}}));return Jo(WA({stream:f,messageId:u??t?.(),originalMessages:e,onFinish:n,onError:l}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:n,onFinish:o,messageMetadata:r,sendReasoning:i,sendSources:a,sendFinish:s,sendStart:l,onError:u,...c}={}){HA({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:n,onFinish:o,messageMetadata:r,sendReasoning:i,sendSources:a,sendFinish:s,sendStart:l,onError:u}),...c})}pipeTextStreamToResponse(e,t){UA({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:o,sendReasoning:r,sendSources:i,sendFinish:a,sendStart:s,onError:l,...u}={}){return LA({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:o,sendReasoning:r,sendSources:i,sendFinish:a,sendStart:s,onError:l}),...u})}toTextStreamResponse(e){return DA({textStream:this.textStream,...e})}};function nR(e,t){const n=[];t?.ignoreIncompleteToolCalls&&(e=e.map(o=>({...o,parts:o.parts.filter(r=>!pf(r)||r.state!=="input-streaming"&&r.state!=="input-available")})));for(const o of e)switch(o.role){case"system":{const r=o.parts.filter(a=>a.type==="text"),i=r.reduce((a,s)=>s.providerMetadata!=null?{...a,...s.providerMetadata}:a,{});n.push({role:"system",content:r.map(a=>a.text).join(""),...Object.keys(i).length>0?{providerOptions:i}:{}});break}case"user":{n.push({role:"user",content:o.parts.map(r=>{var i;if(Rs(r))return{type:"text",text:r.text,...r.providerMetadata!=null?{providerOptions:r.providerMetadata}:{}};if(zs(r))return{type:"file",mediaType:r.mediaType,filename:r.filename,data:r.url,...r.providerMetadata!=null?{providerOptions:r.providerMetadata}:{}};if(As(r))return(i=t?.convertDataPart)==null?void 0:i.call(t,r)}).filter(r=>r!=null)});break}case"assistant":{if(o.parts!=null){let r=function(){var a,s,l;if(i.length===0)return;const u=[];for(const d of i)if(Rs(d))u.push({type:"text",text:d.text,...d.providerMetadata!=null?{providerOptions:d.providerMetadata}:{}});else if(zs(d))u.push({type:"file",mediaType:d.mediaType,filename:d.filename,data:d.url});else if(df(d))u.push({type:"reasoning",text:d.text,providerOptions:d.providerMetadata});else if(Lc(d)){const f=d.toolName;d.state!=="input-streaming"&&u.push({type:"tool-call",toolCallId:d.toolCallId,toolName:f,input:d.input,...d.callProviderMetadata!=null?{providerOptions:d.callProviderMetadata}:{}})}else if(Fr(d)){const f=Ti(d);d.state!=="input-streaming"&&(u.push({type:"tool-call",toolCallId:d.toolCallId,toolName:f,input:d.state==="output-error"?(a=d.input)!=null?a:d.rawInput:d.input,providerExecuted:d.providerExecuted,...d.callProviderMetadata!=null?{providerOptions:d.callProviderMetadata}:{}}),d.providerExecuted===!0&&(d.state==="output-available"||d.state==="output-error")&&u.push({type:"tool-result",toolCallId:d.toolCallId,toolName:f,output:Nn({output:d.state==="output-error"?d.errorText:d.output,tool:(s=t?.tools)==null?void 0:s[f],errorMode:d.state==="output-error"?"json":"none"})}))}else if(As(d)){const f=(l=t?.convertDataPart)==null?void 0:l.call(t,d);f!=null&&u.push(f)}else{const f=d;throw new Error(`Unsupported part: ${f}`)}n.push({role:"assistant",content:u});const c=i.filter(d=>Fr(d)&&d.providerExecuted!==!0||d.type==="dynamic-tool");c.length>0&&n.push({role:"tool",content:c.map(d=>{var f;switch(d.state){case"output-error":case"output-available":{const p=VA(d);return{type:"tool-result",toolCallId:d.toolCallId,toolName:p,output:Nn({output:d.state==="output-error"?d.errorText:d.output,tool:(f=t?.tools)==null?void 0:f[p],errorMode:d.state==="output-error"?"text":"none"})}}default:return null}}).filter(d=>d!=null)}),i=[]},i=[];for(const a of o.parts)Rs(a)||df(a)||zs(a)||pf(a)||As(a)?i.push(a):a.type==="step-start"&&r();r();break}break}default:{const r=o.role;throw new W1({originalMessage:o,message:`Unsupported role: ${r}`})}}return n}To({prefix:"aiobj",size:24});To({prefix:"aiobj",size:24});var oR={};O1(oR,{object:()=>aR,text:()=>iR});var iR=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),aR=({schema:e})=>{const t=Va(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const o=await Bx(n);switch(o.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:o.value};default:{const r=o.state;throw new Error(`Unsupported parse state: ${r}`)}}},async parseOutput({text:n},o){const r=await wr({text:n});if(!r.success)throw new of({message:"No object generated: could not parse the response.",cause:r.error,text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});const i=await sr({value:r.value,schema:t});if(!i.success)throw new of({message:"No object generated: response did not match schema.",cause:i.error,text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});return i.value}}},sR={word:/\S+\s+/m,line:/\n+/m};function uR({delayInMs:e=10,chunking:t="word",_internal:{delay:n=Cw}={}}={}){let o;if(typeof t=="function")o=r=>{const i=t(r);if(i==null)return null;if(!i.length)throw new Error("Chunking function must return a non-empty string.");if(!r.startsWith(i))throw new Error(`Chunking function must return a match that is a prefix of the buffer. Received: "${i}" expected to start with "${r}"`);return i};else{const r=typeof t=="string"?sR[t]:t;if(r==null)throw new Vi({argument:"chunking",message:`Chunking must be "word" or "line" or a RegExp. Received: ${t}`});o=i=>{const a=r.exec(i);return a?i.slice(0,a.index)+a?.[0]:null}}return()=>{let r="",i="";return new TransformStream({async transform(a,s){if(a.type!=="text-delta"){r.length>0&&(s.enqueue({type:"text-delta",text:r,id:i}),r=""),s.enqueue(a);return}a.id!==i&&r.length>0&&(s.enqueue({type:"text-delta",text:r,id:i}),r=""),r+=a.text,i=a.id;let l;for(;(l=o(r))!=null;)s.enqueue({type:"text-delta",text:l,id:i}),r=r.slice(l.length),await n(e)}})}}const lR=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,{...n.description?{description:n.description}:void 0,parameters:n.parameters instanceof vi.ZodType?vi.toJSONSchema(n.parameters):n.parameters}])),cR=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>!t.disabled&&t.type!=="backend"));let Oi=null;function dR(e,t){Oi={helpers:e,toolsRequiringApproval:new Set(t)}}function pR(){Oi=null}const fR=(e,t)=>L.makeAssistantTool({...e,execute:async(n,o)=>{if(Oi?.toolsRequiringApproval.has(t)){const{helpers:r}=Oi,i=o.toolCallId??"";if(!r.isToolApproved(t)&&!await r.requestApproval(t,i,n))return{content:[{type:"text",text:`Tool "${t}" execution was denied by the user. Please acknowledge this and continue without using this tool's result.`}],isError:!0}}return e.execute?.(n,o)},toolName:t});function mR(e,t,n){if(!t||t.length===0)return e;const o=new Set(t);return Object.fromEntries(Object.entries(e).map(([r,i])=>{if(!o.has(r))return[r,i];const a=i.execute;return a?[r,{...i,execute:async(s,l)=>{const u=l??{},c=u.toolCallId??"";return n.isToolApproved(r)||await n.requestApproval(r,c,s)?a(s,u):{content:[{type:"text",text:`Tool "${r}" execution was denied by the user. Please acknowledge this and continue without using this tool's result.`}],isError:!0}}}]:[r,i]}))}var Oo=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},hR={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},gR=class{#e=hR;#t=!1;setTimeoutProvider(e){process.env.NODE_ENV!=="production"&&this.#t&&e!==this.#e&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:this.#e,provider:e}),this.#e=e,process.env.NODE_ENV!=="production"&&(this.#t=!1)}setTimeout(e,t){return process.env.NODE_ENV!=="production"&&(this.#t=!0),this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return process.env.NODE_ENV!=="production"&&(this.#t=!0),this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},gr=new gR;function vR(e){setTimeout(e,0)}var $r=typeof window>"u"||"Deno"in globalThis;function Je(){}function yR(e,t){return typeof e=="function"?e(t):e}function wu(e){return typeof e=="number"&&e>=0&&e!==1/0}function Jx(e,t){return Math.max(e+(t||0)-Date.now(),0)}function nr(e,t){return typeof e=="function"?e(t):e}function at(e,t){return typeof e=="function"?e(t):e}function mf(e,t){const{type:n="all",exact:o,fetchStatus:r,predicate:i,queryKey:a,stale:s}=e;if(a){if(o){if(t.queryHash!==Zc(a,t.options))return!1}else if(!Gn(t.queryKey,a))return!1}if(n!=="all"){const l=t.isActive();if(n==="active"&&!l||n==="inactive"&&l)return!1}return!(typeof s=="boolean"&&t.isStale()!==s||r&&r!==t.state.fetchStatus||i&&!i(t))}function hf(e,t){const{exact:n,status:o,predicate:r,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Hn(t.options.mutationKey)!==Hn(i))return!1}else if(!Gn(t.options.mutationKey,i))return!1}return!(o&&t.state.status!==o||r&&!r(t))}function Zc(e,t){return(t?.queryKeyHashFn||Hn)(e)}function Hn(e){return JSON.stringify(e,(t,n)=>Su(n)?Object.keys(n).sort().reduce((o,r)=>(o[r]=n[r],o),{}):n)}function Gn(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>Gn(e[n],t[n])):!1}var bR=Object.prototype.hasOwnProperty;function xu(e,t){if(e===t)return e;const n=gf(e)&&gf(t);if(!n&&!(Su(e)&&Su(t)))return t;const r=(n?e:Object.keys(e)).length,i=n?t:Object.keys(t),a=i.length,s=n?new Array(a):{};let l=0;for(let u=0;u<a;u++){const c=n?u:i[u],d=e[c],f=t[c];if(d===f){s[c]=d,(n?u<r:bR.call(e,c))&&l++;continue}if(d===null||f===null||typeof d!="object"||typeof f!="object"){s[c]=f;continue}const p=xu(d,f);s[c]=p,p===d&&l++}return r===a&&l===r?e:s}function $u(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function gf(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Su(e){if(!vf(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!vf(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function vf(e){return Object.prototype.toString.call(e)==="[object Object]"}function _R(e){return new Promise(t=>{gr.setTimeout(t,e)})}function Iu(e,t,n){if(typeof n.structuralSharing=="function")return n.structuralSharing(e,t);if(n.structuralSharing!==!1){if(process.env.NODE_ENV!=="production")try{return xu(e,t)}catch(o){throw console.error(`Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${n.queryHash}]: ${o}`),o}return xu(e,t)}return t}function wR(e,t,n=0){const o=[...e,t];return n&&o.length>n?o.slice(1):o}function xR(e,t,n=0){const o=[t,...e];return n&&o.length>n?o.slice(0,-1):o}var Ni=Symbol();function Wx(e,t){return process.env.NODE_ENV!=="production"&&e.queryFn===Ni&&console.error(`Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${e.queryHash}'`),!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Ni?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function $R(e,t){return typeof e=="function"?e(...t):!!e}var SR=class extends Oo{#e;#t;#r;constructor(){super(),this.#r=e=>{if(!$r&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#r=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},Fc=new SR;function ku(){let e,t;const n=new Promise((r,i)=>{e=r,t=i});n.status="pending",n.catch(()=>{});function o(r){Object.assign(n,r),delete n.resolve,delete n.reject}return n.resolve=r=>{o({status:"fulfilled",value:r}),e(r)},n.reject=r=>{o({status:"rejected",reason:r}),t(r)},n}var IR=vR;function kR(){let e=[],t=0,n=s=>{s()},o=s=>{s()},r=IR;const i=s=>{t?e.push(s):r(()=>{n(s)})},a=()=>{const s=e;e=[],s.length&&r(()=>{o(()=>{s.forEach(l=>{n(l)})})})};return{batch:s=>{let l;t++;try{l=s()}finally{t--,t||a()}return l},batchCalls:s=>(...l)=>{i(()=>{s(...l)})},schedule:i,setNotifyFunction:s=>{n=s},setBatchNotifyFunction:s=>{o=s},setScheduler:s=>{r=s}}}var ze=kR(),ER=class extends Oo{#e=!0;#t;#r;constructor(){super(),this.#r=e=>{if(!$r&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#r=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#e}},Pi=new ER;function TR(e){return Math.min(1e3*2**e,3e4)}function Hx(e){return(e??"online")==="online"?Pi.isOnline():!0}var Eu=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Gx(e){let t=!1,n=0,o;const r=ku(),i=()=>r.status!=="pending",a=h=>{if(!i()){const b=new Eu(h);f(b),e.onCancel?.(b)}},s=()=>{t=!0},l=()=>{t=!1},u=()=>Fc.isFocused()&&(e.networkMode==="always"||Pi.isOnline())&&e.canRun(),c=()=>Hx(e.networkMode)&&e.canRun(),d=h=>{i()||(o?.(),r.resolve(h))},f=h=>{i()||(o?.(),r.reject(h))},p=()=>new Promise(h=>{o=b=>{(i()||u())&&h(b)},e.onPause?.()}).then(()=>{o=void 0,i()||e.onContinue?.()}),g=()=>{if(i())return;let h;const b=n===0?e.initialPromise:void 0;try{h=b??e.fn()}catch(y){h=Promise.reject(y)}Promise.resolve(h).then(d).catch(y=>{if(i())return;const x=e.retry??($r?0:3),$=e.retryDelay??TR,v=typeof $=="function"?$(n,y):$,k=x===!0||typeof x=="number"&&n<x||typeof x=="function"&&x(n,y);if(t||!k){f(y);return}n++,e.onFail?.(n,y),_R(v).then(()=>u()?void 0:p()).then(()=>{t?f(y):g()})})};return{promise:r,status:()=>r.status,cancel:a,continue:()=>(o?.(),r),cancelRetry:s,continueRetry:l,canStart:c,start:()=>(c()?g():p().then(g),r)}}var Kx=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),wu(this.gcTime)&&(this.#e=gr.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??($r?1/0:300*1e3))}clearGcTimeout(){this.#e&&(gr.clearTimeout(this.#e),this.#e=void 0)}},OR=class extends Kx{#e;#t;#r;#o;#n;#s;#a;constructor(e){super(),this.#a=!1,this.#s=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#o=e.client,this.#r=this.#o.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#e=bf(this.options),this.state=e.state??this.#e,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#n?.promise}setOptions(e){if(this.options={...this.#s,...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=bf(this.options);t.data!==void 0&&(this.setState(yf(t.data,t.dataUpdatedAt)),this.#e=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#r.remove(this)}setData(e,t){const n=Iu(this.state.data,e,this.options);return this.#i({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#i({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#n?.promise;return this.#n?.cancel(e),t?t.then(Je).catch(Je):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#e)}isActive(){return this.observers.some(e=>at(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Ni||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>nr(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!Jx(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#n?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#n?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#n&&(this.#a?this.#n.cancel({revert:!0}):this.#n.cancelRetry()),this.scheduleGc()),this.#r.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#i({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#n?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#n)return this.#n.continueRetry(),this.#n.promise}if(e&&this.setOptions(e),!this.options.queryFn){const s=this.observers.find(l=>l.options.queryFn);s&&this.setOptions(s.options)}process.env.NODE_ENV!=="production"&&(Array.isArray(this.options.queryKey)||console.error("As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']"));const n=new AbortController,o=s=>{Object.defineProperty(s,"signal",{enumerable:!0,get:()=>(this.#a=!0,n.signal)})},r=()=>{const s=Wx(this.options,t),u=(()=>{const c={client:this.#o,queryKey:this.queryKey,meta:this.meta};return o(c),c})();return this.#a=!1,this.options.persister?this.options.persister(s,u,this):s(u)},a=(()=>{const s={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#o,state:this.state,fetchFn:r};return o(s),s})();this.options.behavior?.onFetch(a,this),this.#t=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#i({type:"fetch",meta:a.fetchOptions?.meta}),this.#n=Gx({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:s=>{s instanceof Eu&&s.revert&&this.setState({...this.#t,fetchStatus:"idle"}),n.abort()},onFail:(s,l)=>{this.#i({type:"failed",failureCount:s,error:l})},onPause:()=>{this.#i({type:"pause"})},onContinue:()=>{this.#i({type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{const s=await this.#n.start();if(s===void 0)throw process.env.NODE_ENV!=="production"&&console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`),new Error(`${this.queryHash} data is undefined`);return this.setData(s),this.#r.config.onSuccess?.(s,this),this.#r.config.onSettled?.(s,this.state.error,this),s}catch(s){if(s instanceof Eu){if(s.silent)return this.#n.promise;if(s.revert){if(this.state.data===void 0)throw s;return this.state.data}}throw this.#i({type:"error",error:s}),this.#r.config.onError?.(s,this),this.#r.config.onSettled?.(this.state.data,s,this),s}finally{this.scheduleGc()}}#i(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...Yx(n.data,this.options),fetchMeta:e.meta??null};case"success":const o={...n,...yf(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#t=e.manual?o:void 0,o;case"error":const r=e.error;return{...n,error:r,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:"idle",status:"error"};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),ze.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#r.notify({query:this,type:"updated",action:e})})}};function Yx(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Hx(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function yf(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function bf(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,o=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?o??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var NR=class extends Oo{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#a=ku(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#r=void 0;#o=void 0;#n;#s;#a;#i;#h;#p;#f;#l;#c;#u;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),_f(this.#t,this.options)?this.#d():this.updateResult(),this.#b())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Tu(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Tu(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#_(),this.#w(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof at(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#x(),this.#t.setOptions(this.options),t._defaulted&&!$u(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const o=this.hasListeners();o&&wf(this.#t,n,this.options,t)&&this.#d(),this.updateResult(),o&&(this.#t!==n||at(this.options.enabled,this.#t)!==at(t.enabled,this.#t)||nr(this.options.staleTime,this.#t)!==nr(t.staleTime,this.#t))&&this.#g();const r=this.#v();o&&(this.#t!==n||at(this.options.enabled,this.#t)!==at(t.enabled,this.#t)||r!==this.#u)&&this.#y(r)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return CR(this,n)&&(this.#o=n,this.#s=this.options,this.#n=this.#t.state),n}getCurrentResult(){return this.#o}trackResult(e,t){return new Proxy(e,{get:(n,o)=>(this.trackProp(o),t?.(o),o==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#a.status==="pending"&&this.#a.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,o))})}trackProp(e){this.#m.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#d({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#o))}#d(e){this.#x();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Je)),t}#g(){this.#_();const e=nr(this.options.staleTime,this.#t);if($r||this.#o.isStale||!wu(e))return;const n=Jx(this.#o.dataUpdatedAt,e)+1;this.#l=gr.setTimeout(()=>{this.#o.isStale||this.updateResult()},n)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#y(e){this.#w(),this.#u=e,!($r||at(this.options.enabled,this.#t)===!1||!wu(this.#u)||this.#u===0)&&(this.#c=gr.setInterval(()=>{(this.options.refetchIntervalInBackground||Fc.isFocused())&&this.#d()},this.#u))}#b(){this.#g(),this.#y(this.#v())}#_(){this.#l&&(gr.clearTimeout(this.#l),this.#l=void 0)}#w(){this.#c&&(gr.clearInterval(this.#c),this.#c=void 0)}createResult(e,t){const n=this.#t,o=this.options,r=this.#o,i=this.#n,a=this.#s,l=e!==n?e.state:this.#r,{state:u}=e;let c={...u},d=!1,f;if(t._optimisticResults){const O=this.hasListeners(),z=!O&&_f(e,t),F=O&&wf(e,n,t,o);(z||F)&&(c={...c,...Yx(u.data,e.options)}),t._optimisticResults==="isRestoring"&&(c.fetchStatus="idle")}let{error:p,errorUpdatedAt:g,status:h}=c;f=c.data;let b=!1;if(t.placeholderData!==void 0&&f===void 0&&h==="pending"){let O;r?.isPlaceholderData&&t.placeholderData===a?.placeholderData?(O=r.data,b=!0):O=typeof t.placeholderData=="function"?t.placeholderData(this.#f?.state.data,this.#f):t.placeholderData,O!==void 0&&(h="success",f=Iu(r?.data,O,t),d=!0)}if(t.select&&f!==void 0&&!b)if(r&&f===i?.data&&t.select===this.#h)f=this.#p;else try{this.#h=t.select,f=t.select(f),f=Iu(r?.data,f,t),this.#p=f,this.#i=null}catch(O){this.#i=O}this.#i&&(p=this.#i,f=this.#p,g=Date.now(),h="error");const y=c.fetchStatus==="fetching",x=h==="pending",$=h==="error",v=x&&y,k=f!==void 0,I={status:h,fetchStatus:c.fetchStatus,isPending:x,isSuccess:h==="success",isError:$,isInitialLoading:v,isLoading:v,data:f,dataUpdatedAt:c.dataUpdatedAt,error:p,errorUpdatedAt:g,failureCount:c.fetchFailureCount,failureReason:c.fetchFailureReason,errorUpdateCount:c.errorUpdateCount,isFetched:c.dataUpdateCount>0||c.errorUpdateCount>0,isFetchedAfterMount:c.dataUpdateCount>l.dataUpdateCount||c.errorUpdateCount>l.errorUpdateCount,isFetching:y,isRefetching:y&&!x,isLoadingError:$&&!k,isPaused:c.fetchStatus==="paused",isPlaceholderData:d,isRefetchError:$&&k,isStale:qc(e,t),refetch:this.refetch,promise:this.#a,isEnabled:at(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const O=te=>{I.status==="error"?te.reject(I.error):I.data!==void 0&&te.resolve(I.data)},z=()=>{const te=this.#a=I.promise=ku();O(te)},F=this.#a;switch(F.status){case"pending":e.queryHash===n.queryHash&&O(F);break;case"fulfilled":(I.status==="error"||I.data!==F.value)&&z();break;case"rejected":(I.status!=="error"||I.error!==F.reason)&&z();break}}return I}updateResult(){const e=this.#o,t=this.createResult(this.#t,this.options);if(this.#n=this.#t.state,this.#s=this.options,this.#n.data!==void 0&&(this.#f=this.#t),$u(t,e))return;this.#o=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:o}=this.options,r=typeof o=="function"?o():o;if(r==="all"||!r&&!this.#m.size)return!0;const i=new Set(r??this.#m);return this.options.throwOnError&&i.add("error"),Object.keys(this.#o).some(a=>{const s=a;return this.#o[s]!==e[s]&&i.has(s)})};this.#$({listeners:n()})}#x(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#r=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#b()}#$(e){ze.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#o)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function PR(e,t){return at(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function _f(e,t){return PR(e,t)||e.state.data!==void 0&&Tu(e,t,t.refetchOnMount)}function Tu(e,t,n){if(at(t.enabled,e)!==!1&&nr(t.staleTime,e)!=="static"){const o=typeof n=="function"?n(e):n;return o==="always"||o!==!1&&qc(e,t)}return!1}function wf(e,t,n,o){return(e!==t||at(o.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&qc(e,n)}function qc(e,t){return at(t.enabled,e)!==!1&&e.isStaleByTime(nr(t.staleTime,e))}function CR(e,t){return!$u(e.getCurrentResult(),t)}function xf(e){return{onFetch:(t,n)=>{const o=t.options,r=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],a=t.state.data?.pageParams||[];let s={pages:[],pageParams:[]},l=0;const u=async()=>{let c=!1;const d=g=>{Object.defineProperty(g,"signal",{enumerable:!0,get:()=>(t.signal.aborted?c=!0:t.signal.addEventListener("abort",()=>{c=!0}),t.signal)})},f=Wx(t.options,t.fetchOptions),p=async(g,h,b)=>{if(c)return Promise.reject();if(h==null&&g.pages.length)return Promise.resolve(g);const x=(()=>{const N={client:t.client,queryKey:t.queryKey,pageParam:h,direction:b?"backward":"forward",meta:t.options.meta};return d(N),N})(),$=await f(x),{maxPages:v}=t.options,k=b?xR:wR;return{pages:k(g.pages,$,v),pageParams:k(g.pageParams,h,v)}};if(r&&i.length){const g=r==="backward",h=g?jR:$f,b={pages:i,pageParams:a},y=h(o,b);s=await p(b,y,g)}else{const g=e??i.length;do{const h=l===0?a[0]??o.initialPageParam:$f(o,s);if(l>0&&h==null)break;s=await p(s,h),l++}while(l<g)}return s};t.options.persister?t.fetchFn=()=>t.options.persister?.(u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=u}}}function $f(e,{pages:t,pageParams:n}){const o=t.length-1;return t.length>0?e.getNextPageParam(t[o],t,n[o],n):void 0}function jR(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var AR=class extends Kx{#e;#t;#r;#o;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#r=e.mutationCache,this.#t=[],this.state=e.state||RR(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#r.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#r.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#r.remove(this))}continue(){return this.#o?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#n({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#o=Gx({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(i,a)=>{this.#n({type:"failed",failureCount:i,error:a})},onPause:()=>{this.#n({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#r.canRun(this)});const o=this.state.status==="pending",r=!this.#o.canStart();try{if(o)t();else{this.#n({type:"pending",variables:e,isPaused:r}),await this.#r.config.onMutate?.(e,this,n);const a=await this.options.onMutate?.(e,n);a!==this.state.context&&this.#n({type:"pending",context:a,variables:e,isPaused:r})}const i=await this.#o.start();return await this.#r.config.onSuccess?.(i,e,this.state.context,this,n),await this.options.onSuccess?.(i,e,this.state.context,n),await this.#r.config.onSettled?.(i,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(i,null,e,this.state.context,n),this.#n({type:"success",data:i}),i}catch(i){try{throw await this.#r.config.onError?.(i,e,this.state.context,this,n),await this.options.onError?.(i,e,this.state.context,n),await this.#r.config.onSettled?.(void 0,i,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(void 0,i,e,this.state.context,n),i}finally{this.#n({type:"error",error:i})}}finally{this.#r.runNext(this)}}#n(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),ze.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#r.notify({mutation:this,type:"updated",action:e})})}};function RR(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var zR=class extends Oo{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#r=0}#e;#t;#r;build(e,t,n){const o=new AR({client:e,mutationCache:this,mutationId:++this.#r,options:e.defaultMutationOptions(t),state:n});return this.add(o),o}add(e){this.#e.add(e);const t=Ho(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=Ho(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const o=n.indexOf(e);o!==-1&&n.splice(o,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Ho(e);if(typeof t=="string"){const o=this.#t.get(t)?.find(r=>r.state.status==="pending");return!o||o===e}else return!0}runNext(e){const t=Ho(e);return typeof t=="string"?this.#t.get(t)?.find(o=>o!==e&&o.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){ze.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>hf(t,n))}findAll(e={}){return this.getAll().filter(t=>hf(e,t))}notify(e){ze.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return ze.batch(()=>Promise.all(e.map(t=>t.continue().catch(Je))))}};function Ho(e){return e.options.scope?.id}var MR=class extends Oo{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){const o=t.queryKey,r=t.queryHash??Zc(o,t);let i=this.get(r);return i||(i=new OR({client:e,queryKey:o,queryHash:r,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(o)}),this.add(i)),i}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){ze.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>mf(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>mf(e,n)):t}notify(e){ze.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){ze.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){ze.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},DR=class{#e;#t;#r;#o;#n;#s;#a;#i;constructor(e={}){this.#e=e.queryCache||new MR,this.#t=e.mutationCache||new zR,this.#r=e.defaultOptions||{},this.#o=new Map,this.#n=new Map,this.#s=0}mount(){this.#s++,this.#s===1&&(this.#a=Fc.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=Pi.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#s--,this.#s===0&&(this.#a?.(),this.#a=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),o=n.state.data;return o===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(nr(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(o))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>{const o=n.data;return[t,o]})}setQueryData(e,t,n){const o=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(o.queryHash)?.state.data,a=yR(t,i);if(a!==void 0)return this.#e.build(this,o).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return ze.batch(()=>this.#e.findAll(e).map(({queryKey:o})=>[o,this.setQueryData(o,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;ze.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return ze.batch(()=>(n.findAll(e).forEach(o=>{o.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},o=ze.batch(()=>this.#e.findAll(e).map(r=>r.cancel(n)));return Promise.all(o).then(Je).catch(Je)}invalidateQueries(e,t={}){return ze.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},o=ze.batch(()=>this.#e.findAll(e).filter(r=>!r.isDisabled()&&!r.isStatic()).map(r=>{let i=r.fetch(void 0,n);return n.throwOnError||(i=i.catch(Je)),r.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(o).then(Je)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(nr(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Je).catch(Je)}fetchInfiniteQuery(e){return e.behavior=xf(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Je).catch(Je)}ensureInfiniteQueryData(e){return e.behavior=xf(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Pi.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#r}setDefaultOptions(e){this.#r=e}setQueryDefaults(e,t){this.#o.set(Hn(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#o.values()],n={};return t.forEach(o=>{Gn(e,o.queryKey)&&Object.assign(n,o.defaultOptions)}),n}setMutationDefaults(e,t){this.#n.set(Hn(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#n.values()],n={};return t.forEach(o=>{Gn(e,o.mutationKey)&&Object.assign(n,o.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#r.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Zc(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Ni&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#r.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},Qx=_.createContext(void 0),Xx=e=>{const t=_.useContext(Qx);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},UR=({client:e,children:t})=>(_.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),m.jsx(Qx.Provider,{value:e,children:t})),e$=_.createContext(!1),LR=()=>_.useContext(e$);e$.Provider;function ZR(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var FR=_.createContext(ZR()),qR=()=>_.useContext(FR),VR=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},BR=e=>{_.useEffect(()=>{e.clearReset()},[e])},JR=({result:e,errorResetBoundary:t,throwOnError:n,query:o,suspense:r})=>e.isError&&!t.isReset()&&!e.isFetching&&o&&(r&&e.data===void 0||$R(n,[e.error,o])),WR=e=>{if(e.suspense){const n=r=>r==="static"?r:Math.max(r??1e3,1e3),o=e.staleTime;e.staleTime=typeof o=="function"?(...r)=>n(o(...r)):n(o),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},HR=(e,t)=>e.isLoading&&e.isFetching&&!t,GR=(e,t)=>e?.suspense&&t.isPending,Sf=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function KR(e,t,n){if(process.env.NODE_ENV!=="production"&&(typeof e!="object"||Array.isArray(e)))throw new Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');const o=LR(),r=qR(),i=Xx(),a=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(a),process.env.NODE_ENV!=="production"&&(a.queryFn||console.error(`[${a.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`)),a._optimisticResults=o?"isRestoring":"optimistic",WR(a),VR(a,r),BR(r);const s=!i.getQueryCache().get(a.queryHash),[l]=_.useState(()=>new t(i,a)),u=l.getOptimisticResult(a),c=!o&&e.subscribed!==!1;if(_.useSyncExternalStore(_.useCallback(d=>{const f=c?l.subscribe(ze.batchCalls(d)):Je;return l.updateResult(),f},[l,c]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),_.useEffect(()=>{l.setOptions(a)},[a,l]),GR(a,u))throw Sf(a,l,r);if(JR({result:u,errorResetBoundary:r,throwOnError:a.throwOnError,query:i.getQueryCache().get(a.queryHash),suspense:a.suspense}))throw u.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(a,u),a.experimental_prefetchInRender&&!$r&&HR(u,o)&&(s?Sf(a,l,r):i.getQueryCache().get(a.queryHash)?.promise)?.catch(Je).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?u:l.trackResult(u)}function t$(e,t){return KR(e,NR)}const r$=({getSession:e,projectSlug:t})=>{const n=Xx(),o=["chatSession",t],r=n.getQueryState(o),i=r?.data!==void 0,a=r?.dataUpdatedAt??0,l=i&&Date.now()-a>1/0,u=!i||l,{data:c}=t$({queryKey:o,queryFn:()=>e({projectSlug:t}),enabled:u,staleTime:1/0,gcTime:1/0});return c??null};var YR=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:o="-"}={})=>{const r=()=>{const i=n.length,a=new Array(t);for(let s=0;s<t;s++)a[s]=n[Math.random()*i|0];return a.join("")};if(e==null)return r;if(n.includes(o))throw new Vi({argument:"separator",message:`The separator "${o}" must not be part of the alphabet "${n}".`});return()=>`${e}${o}${r()}`};YR();function n$(e=globalThis){var t,n,o;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(o=(n=e.process)==null?void 0:n.versions)!=null&&o.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function QR(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((n,o)=>{t[o.toLowerCase()]=n});else{Array.isArray(e)||(e=Object.entries(e));for(const[n,o]of e)o!=null&&(t[n.toLowerCase()]=o)}return t}function o$(e,...t){const n=new Headers(QR(e)),o=n.get("user-agent")||"";return n.set("user-agent",[o,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}var XR=Symbol.for("vercel.ai.validator");function ez(e){return{...e,type:"dynamic"}}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var tz=Symbol.for("vercel.ai.schema");function rz(e,{validate:t}={}){return{[tz]:!0,_type:void 0,[XR]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}let Vc;Vc=globalThis.crypto;async function nz(e){return(await Vc).getRandomValues(new Uint8Array(e))}async function oz(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";let n="";const o=await nz(e);for(let r=0;r<e;r++){const i=o[r]%t.length;n+=t[i]}return n}async function iz(e){return await oz(e)}async function az(e){const t=await(await Vc).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function sz(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await iz(e),n=await az(t);return{code_verifier:t,code_challenge:n}}var uz="AI_MCPClientError",i$=`vercel.ai.error.${uz}`,lz=Symbol.for(i$),If,kf,se=class extends(kf=Y,If=lz,kf){constructor({name:e="MCPClientError",message:t,cause:n,data:o,code:r}){super({name:e,message:t,cause:n}),this[If]=!0,this.data=o,this.code=r}static isInstance(e){return Y.hasMarker(e,i$)}},cn="2025-06-18",cz=[cn,"2025-03-26","2024-11-05"],dz=er({name:w(),version:w()}),Ja=er({_meta:ee(E({}).loose())}),Vt=Ja,a$=E({method:w(),params:ee(Ja)}),s$=E({applyDefaults:ee(pe())}).loose(),pz=er({experimental:ee(E({}).loose()),logging:ee(E({}).loose()),prompts:ee(er({listChanged:ee(pe())})),resources:ee(er({subscribe:ee(pe()),listChanged:ee(pe())})),tools:ee(er({listChanged:ee(pe())})),elicitation:ee(s$)});E({elicitation:ee(s$)}).loose();var fz=Vt.extend({protocolVersion:w(),capabilities:pz,serverInfo:dz,instructions:ee(w())}),Bc=Vt.extend({nextCursor:ee(w())}),mz=E({name:w(),description:ee(w()),inputSchema:E({type:C("object"),properties:ee(E({}).loose())}).loose()}).loose(),hz=Bc.extend({tools:R(mz)}),u$=E({type:C("text"),text:w()}).loose(),l$=E({type:C("image"),data:Ea(),mimeType:w()}).loose(),gz=E({uri:w(),name:w(),title:ee(w()),description:ee(w()),mimeType:ee(w()),size:ee(V())}).loose(),vz=Bc.extend({resources:R(gz)}),c$=E({uri:w(),name:ee(w()),title:ee(w()),mimeType:ee(w())}).loose(),d$=c$.extend({text:w()}),p$=c$.extend({blob:Ea()}),f$=E({type:C("resource"),resource:G([d$,p$])}).loose(),yz=Vt.extend({content:R(G([u$,l$,f$])),isError:pe().default(!1).optional()}).or(Vt.extend({toolResult:$e()})),bz=E({uriTemplate:w(),name:w(),title:ee(w()),description:ee(w()),mimeType:ee(w())}).loose(),_z=Vt.extend({resourceTemplates:R(bz)}),wz=Vt.extend({contents:R(G([d$,p$]))}),xz=E({name:w(),description:ee(w()),required:ee(pe())}).loose(),$z=E({name:w(),title:ee(w()),description:ee(w()),arguments:ee(R(xz))}).loose(),Sz=Bc.extend({prompts:R($z)}),Iz=E({role:G([C("user"),C("assistant")]),content:G([u$,l$,f$])}).loose(),kz=Vt.extend({description:ee(w()),messages:R(Iz)}),Ez=Ja.extend({message:w(),requestedSchema:$e()}),Ef=a$.extend({method:C("elicitation/create"),params:Ez}),Tz=Vt.extend({action:G([C("accept"),C("decline"),C("cancel")]),content:ee(Xe(w(),$e()))}),Wa="2.0",Oz=E({jsonrpc:C(Wa),id:G([w(),V().int()])}).merge(a$).strict(),Nz=E({jsonrpc:C(Wa),id:G([w(),V().int()]),result:Vt}).strict(),Pz=E({jsonrpc:C(Wa),id:G([w(),V().int()]),error:E({code:V().int(),message:w(),data:ee($e())})}).strict(),Cz=E({jsonrpc:C(Wa)}).merge(E({method:w(),params:ee(Ja)})).strict(),Tn=G([Oz,Cz,Nz,Pz]),m$=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",h$=E({access_token:w(),id_token:w().optional(),token_type:w(),expires_in:V().optional(),scope:w().optional(),refresh_token:w().optional()}).strip(),He=w().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:v_.custom,message:"URL must be parseable",fatal:!0}),Uu}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),jz=E({resource:w().url(),authorization_servers:R(He).optional(),jwks_uri:w().url().optional(),scopes_supported:R(w()).optional(),bearer_methods_supported:R(w()).optional(),resource_signing_alg_values_supported:R(w()).optional(),resource_name:w().optional(),resource_documentation:w().optional(),resource_policy_uri:w().url().optional(),resource_tos_uri:w().url().optional(),tls_client_certificate_bound_access_tokens:pe().optional(),authorization_details_types_supported:R(w()).optional(),dpop_signing_alg_values_supported:R(w()).optional(),dpop_bound_access_tokens_required:pe().optional()}).passthrough(),g$=E({issuer:w(),authorization_endpoint:He,token_endpoint:He,registration_endpoint:He.optional(),scopes_supported:R(w()).optional(),response_types_supported:R(w()),grant_types_supported:R(w()).optional(),code_challenge_methods_supported:R(w()),token_endpoint_auth_methods_supported:R(w()).optional(),token_endpoint_auth_signing_alg_values_supported:R(w()).optional()}).passthrough(),Az=E({issuer:w(),authorization_endpoint:He,token_endpoint:He,userinfo_endpoint:He.optional(),jwks_uri:He,registration_endpoint:He.optional(),scopes_supported:R(w()).optional(),response_types_supported:R(w()),grant_types_supported:R(w()).optional(),subject_types_supported:R(w()),id_token_signing_alg_values_supported:R(w()),claims_supported:R(w()).optional(),token_endpoint_auth_methods_supported:R(w()).optional()}).passthrough(),Rz=Az.merge(g$.pick({code_challenge_methods_supported:!0})),zz=E({client_id:w(),client_secret:w().optional(),client_id_issued_at:V().optional(),client_secret_expires_at:V().optional()}).strip(),Mz=E({redirect_uris:R(He),token_endpoint_auth_method:w().optional(),grant_types:R(w()).optional(),response_types:R(w()).optional(),client_name:w().optional(),client_uri:He.optional(),logo_uri:He.optional(),scope:w().optional(),contacts:R(w()).optional(),tos_uri:He.optional(),policy_uri:w().optional(),jwks_uri:He.optional(),jwks:Pe().optional(),software_id:w().optional(),software_version:w().optional(),software_statement:w().optional()}).strip(),Dz=E({error:w(),error_description:w().optional(),error_uri:w().optional()}),Uz=Mz.merge(zz),Lz="AI_MCPClientOAuthError",v$=`vercel.ai.error.${Lz}`,Zz=Symbol.for(v$),Tf,Of,No=class extends(Of=Y,Tf=Zz,Of){constructor({name:e="MCPClientOAuthError",message:t,cause:n}){super({name:e,message:t,cause:n}),this[Tf]=!0}static isInstance(e){return Y.hasMarker(e,v$)}},rn=class extends No{};rn.errorCode="server_error";var Ci=class extends No{};Ci.errorCode="invalid_client";var ji=class extends No{};ji.errorCode="invalid_grant";var Ai=class extends No{};Ai.errorCode="unauthorized_client";var Fz={[rn.errorCode]:rn,[Ci.errorCode]:Ci,[ji.errorCode]:ji,[Ai.errorCode]:Ai};function qz(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function Vz({requestedResource:e,configuredResource:t}){const n=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.href);if(n.origin!==o.origin||n.pathname.length<o.pathname.length)return!1;const r=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",i=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return r.startsWith(i)}var Ri=class extends Error{constructor(e="Unauthorized"){super(e),this.name="UnauthorizedError"}};function zi(e){var t;const n=(t=e.headers.get("www-authenticate"))!=null?t:e.headers.get("WWW-Authenticate");if(!n)return;const[o,r]=n.split(" ");if(o.toLowerCase()!=="bearer"||!r)return;const i=/resource_metadata="([^"]*)"/,a=n.match(i);if(a)try{return new URL(a[1])}catch{return}}function Bz(e,t="",n={}){return t.endsWith("/")&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Jc(e,t,n=fetch){try{return await n(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?Jc(e,void 0,n):void 0;throw o}}async function Nf(e,t,n=fetch){return await Jc(e,{"MCP-Protocol-Version":t},n)}function Jz(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function Wz(e,t,n,o){var r,i;const a=new URL(e),s=(r=o?.protocolVersion)!=null?r:cn;let l;if(o?.metadataUrl)l=new URL(o.metadataUrl);else{const c=Bz(t,a.pathname);l=new URL(c,(i=o?.metadataServerUrl)!=null?i:a),l.search=a.search}let u=await Nf(l,s,n);if(!o?.metadataUrl&&Jz(u,a.pathname)){const c=new URL(`/.well-known/${t}`,a);u=await Nf(c,s,n)}return u}async function Hz(e,t,n=fetch){const o=await Wz(e,"oauth-protected-resource",n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return jz.parse(await o.json())}function Gz(e){const t=typeof e=="string"?new URL(e):e,n=t.pathname!=="/",o=[];if(!n)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let r=t.pathname;return r.endsWith("/")&&(r=r.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${r}`,t.origin),type:"oauth"}),o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${r}`,t.origin),type:"oidc"}),o.push({url:new URL(`${r}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}async function Kz(e,{fetchFn:t=fetch,protocolVersion:n=cn}={}){var o;const r={"MCP-Protocol-Version":n},i=Gz(e);for(const{url:a,type:s}of i){const l=await Jc(a,r,t);if(l){if(!l.ok){if(l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}if(s==="oauth")return g$.parse(await l.json());{const u=Rz.parse(await l.json());if(!((o=u.code_challenge_methods_supported)!=null&&o.includes("S256")))throw new Error(`Incompatible OIDC provider at ${a}: does not support S256 code challenge method required by MCP specification`);return u}}}}async function Yz(e,{metadata:t,clientInformation:n,redirectUrl:o,scope:r,state:i,resource:a}){const s="code",l="S256";let u;if(t){if(u=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw new Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(l))throw new Error(`Incompatible auth server: does not support code challenge method ${l}`)}else u=new URL("/authorize",e);const c=await sz(),d=c.code_verifier,f=c.code_challenge;return u.searchParams.set("response_type",s),u.searchParams.set("client_id",n.client_id),u.searchParams.set("code_challenge",f),u.searchParams.set("code_challenge_method",l),u.searchParams.set("redirect_uri",String(o)),i&&u.searchParams.set("state",i),r&&u.searchParams.set("scope",r),r?.includes("offline_access")&&u.searchParams.append("prompt","consent"),a&&u.searchParams.set("resource",a.href),{authorizationUrl:u,codeVerifier:d}}function y$(e,t){const n=e.client_secret!==void 0;return t.length===0?n?"client_secret_post":"none":n&&t.includes("client_secret_basic")?"client_secret_basic":n&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":n?"client_secret_post":"none"}function b$(e,t,n,o){const{client_id:r,client_secret:i}=t;switch(e){case"client_secret_basic":Qz(r,i,n);return;case"client_secret_post":Xz(r,i,o);return;case"none":eM(r,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function Qz(e,t,n){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const o=btoa(`${e}:${t}`);n.set("Authorization",`Basic ${o}`)}function Xz(e,t,n){n.set("client_id",e),t&&n.set("client_secret",t)}function eM(e,t){t.set("client_id",e)}async function Wc(e){const t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{const o=Dz.parse(JSON.parse(n)),{error:r,error_description:i,error_uri:a}=o,s=Fz[r]||rn;return new s({message:i||"",cause:a})}catch(o){const r=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${n}`;return new rn({message:r})}}async function tM(e,{metadata:t,clientInformation:n,authorizationCode:o,codeVerifier:r,redirectUri:i,resource:a,addClientAuthentication:s,fetchFn:l}){var u;const c="authorization_code",d=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`);const f=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),p=new URLSearchParams({grant_type:c,code:o,code_verifier:r,redirect_uri:String(i)});if(s)s(f,p,e,t);else{const h=(u=t?.token_endpoint_auth_methods_supported)!=null?u:[],b=y$(n,h);b$(b,n,f,p)}a&&p.set("resource",a.href);const g=await(l??fetch)(d,{method:"POST",headers:f,body:p});if(!g.ok)throw await Wc(g);return h$.parse(await g.json())}async function rM(e,{metadata:t,clientInformation:n,refreshToken:o,resource:r,addClientAuthentication:i,fetchFn:a}){var s;const l="refresh_token";let u;if(t){if(u=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`)}else u=new URL("/token",e);const c=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),d=new URLSearchParams({grant_type:l,refresh_token:o});if(i)i(c,d,e,t);else{const p=(s=t?.token_endpoint_auth_methods_supported)!=null?s:[],g=y$(n,p);b$(g,n,c,d)}r&&d.set("resource",r.href);const f=await(a??fetch)(u,{method:"POST",headers:c,body:d});if(!f.ok)throw await Wc(f);return h$.parse({refresh_token:o,...await f.json()})}async function nM(e,{metadata:t,clientMetadata:n,fetchFn:o}){let r;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");r=new URL(t.registration_endpoint)}else r=new URL("/register",e);const i=await(o??fetch)(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!i.ok)throw await Wc(i);return Uz.parse(await i.json())}async function Mi(e,t){var n,o;try{return await Ms(e,t)}catch(r){if(r instanceof Ci||r instanceof Ai)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"all")),await Ms(e,t);if(r instanceof ji)return await((o=e.invalidateCredentials)==null?void 0:o.call(e,"tokens")),await Ms(e,t);throw r}}async function oM(e,t,n){const o=qz(e);if(t.validateResourceURL)return await t.validateResourceURL(o,n?.resource);if(n){if(!Vz({requestedResource:o,configuredResource:n.resource}))throw new Error(`Protected resource ${n.resource} does not match expected ${o} (or origin)`);return new URL(n.resource)}}async function Ms(e,{serverUrl:t,authorizationCode:n,scope:o,resourceMetadataUrl:r,fetchFn:i}){let a,s;try{a=await Hz(t,{resourceMetadataUrl:r},i),a.authorization_servers&&a.authorization_servers.length>0&&(s=a.authorization_servers[0])}catch{}s||(s=t);const l=await oM(t,e,a),u=await Kz(s,{fetchFn:i});let c=await Promise.resolve(e.clientInformation());if(!c){if(n!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const h=await nM(s,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:i});await e.saveClientInformation(h),c=h}if(n!==void 0){const h=await e.codeVerifier(),b=await tM(s,{metadata:u,clientInformation:c,authorizationCode:n,codeVerifier:h,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(b),"AUTHORIZED"}const d=await e.tokens();if(d?.refresh_token)try{const h=await rM(s,{metadata:u,clientInformation:c,refreshToken:d.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(h),"AUTHORIZED"}catch(h){if(!(!(h instanceof No)||h instanceof rn))throw h}const f=e.state?await e.state():void 0,{authorizationUrl:p,codeVerifier:g}=await Yz(s,{metadata:u,clientInformation:c,state:f,redirectUrl:e.redirectUrl,scope:o||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(g),await e.redirectToAuthorization(p),"REDIRECT"}var iM=class{constructor({url:e,headers:t,authProvider:n}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=n}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":cn};if(this.authProvider){const n=await this.authProvider.tokens();n?.access_token&&(t.Authorization=`Bearer ${n.access_token}`)}return o$(t,`ai-sdk/${m$}`,n$())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;const n=async(o=!1)=>{var r,i,a,s,l;try{const u=await this.commonHeaders({Accept:"text/event-stream"}),c=await fetch(this.url.href,{headers:u,signal:(r=this.abortController)==null?void 0:r.signal});if(c.status===401&&this.authProvider&&!o){this.resourceMetadataUrl=zi(c);try{if(await Mi(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const h=new Ri;return(i=this.onerror)==null||i.call(this,h),t(h)}}catch(g){return(a=this.onerror)==null||a.call(this,g),t(g)}return n(!0)}if(!c.ok||!c.body){let g=`MCP SSE Transport Error: ${c.status} ${c.statusText}`;c.status===405&&(g+=". This server does not support SSE transport. Try using `http` transport instead");const h=new se({message:g});return(s=this.onerror)==null||s.call(this,h),t(h)}const f=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new Pn).getReader(),p=async()=>{var g,h,b;try{for(;;){const{done:y,value:x}=await f.read();if(y){if(this.connected)throw this.connected=!1,new se({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:$,data:v}=x;if($==="endpoint"){if(this.endpoint=new URL(v,this.url),this.endpoint.origin!==this.url.origin)throw new se({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if($==="message")try{const k=Tn.parse(JSON.parse(v));(g=this.onmessage)==null||g.call(this,k)}catch(k){const N=new se({message:"MCP SSE Transport Error: Failed to parse message",cause:k});(h=this.onerror)==null||h.call(this,N)}}}catch(y){if(y instanceof Error&&y.name==="AbortError")return;(b=this.onerror)==null||b.call(this,y),t(y)}};this.sseConnection={close:()=>f.cancel()},p()}catch(u){if(u instanceof Error&&u.name==="AbortError")return;(l=this.onerror)==null||l.call(this,u),t(u)}};n()})}async close(){var e,t,n;this.connected=!1,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new se({message:"MCP SSE Transport Error: Not connected"});const t=this.endpoint,n=async(o=!1)=>{var r,i,a,s,l;try{const c={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:(r=this.abortController)==null?void 0:r.signal},d=await fetch(t,c);if(d.status===401&&this.authProvider&&!o){this.resourceMetadataUrl=zi(d);try{if(await Mi(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const p=new Ri;(i=this.onerror)==null||i.call(this,p);return}}catch(f){(a=this.onerror)==null||a.call(this,f);return}return n(!0)}if(!d.ok){const f=await d.text().catch(()=>null),p=new se({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${d.status}): ${f}`});(s=this.onerror)==null||s.call(this,p);return}}catch(u){(l=this.onerror)==null||l.call(this,u);return}};await n()}},aM=class{constructor({url:e,headers:t,authProvider:n}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":cn};if(this.sessionId&&(t["mcp-session-id"]=this.sessionId),this.authProvider){const n=await this.authProvider.tokens();n?.access_token&&(t.Authorization=`Bearer ${n.access_token}`)}return o$(t,`ai-sdk/${m$}`,n$())}async start(){if(this.abortController)throw new se({message:"MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){const o=await this.commonHeaders({});await fetch(this.url,{method:"DELETE",headers:o,signal:this.abortController.signal}).catch(()=>{})}}catch{}(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){const t=async(n=!1)=>{var o,r,i,a,s,l,u;try{const d={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(e),signal:(o=this.abortController)==null?void 0:o.signal},f=await fetch(this.url,d),p=f.headers.get("mcp-session-id");if(p&&(this.sessionId=p),f.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=zi(f);try{if(await Mi(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new Ri}catch(b){throw(r=this.onerror)==null||r.call(this,b),b}return t(!0)}if(f.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!f.ok){const b=await f.text().catch(()=>null);let y=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${f.status}): ${b}`;f.status===404&&(y+=". This server does not support HTTP transport. Try using `sse` transport instead");const x=new se({message:y});throw(i=this.onerror)==null||i.call(this,x),x}const g=f.headers.get("content-type")||"";if(g.includes("application/json")){const b=await f.json(),y=Array.isArray(b)?b.map(x=>Tn.parse(x)):[Tn.parse(b)];for(const x of y)(a=this.onmessage)==null||a.call(this,x);return}if(g.includes("text/event-stream")){if(!f.body){const $=new se({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(s=this.onerror)==null||s.call(this,$),$}const y=f.body.pipeThrough(new TextDecoderStream).pipeThrough(new Pn).getReader();(async()=>{var $,v,k;try{for(;;){const{done:N,value:I}=await y.read();if(N)return;const{event:O,data:z}=I;if(O==="message")try{const F=Tn.parse(JSON.parse(z));($=this.onmessage)==null||$.call(this,F)}catch(F){const te=new se({message:"MCP HTTP Transport Error: Failed to parse message",cause:F});(v=this.onerror)==null||v.call(this,te)}}}catch(N){if(N instanceof Error&&N.name==="AbortError")return;(k=this.onerror)==null||k.call(this,N)}})();return}const h=new se({message:`MCP HTTP Transport Error: Unexpected content type: ${g}`});throw(l=this.onerror)==null||l.call(this,h),h}catch(c){throw(u=this.onerror)==null||u.call(this,c),c}};await t()}getNextReconnectionDelay(e){const{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:o}=this.reconnectionOptions;return Math.min(t*Math.pow(n,e),o)}scheduleInboundSseReconnection(){var e;const{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new se({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}const n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{var o;(o=this.abortController)!=null&&o.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},n)}async openInboundSse(e=!1,t){var n,o,r,i,a,s;try{const l=await this.commonHeaders({Accept:"text/event-stream"});t&&(l["last-event-id"]=t);const u=await fetch(this.url.href,{method:"GET",headers:l,signal:(n=this.abortController)==null?void 0:n.signal}),c=u.headers.get("mcp-session-id");if(c&&(this.sessionId=c),u.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=zi(u);try{if(await Mi(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const h=new Ri;(o=this.onerror)==null||o.call(this,h);return}}catch(g){(r=this.onerror)==null||r.call(this,g);return}return this.openInboundSse(!0,t)}if(u.status===405)return;if(!u.ok||!u.body){const g=new se({message:`MCP HTTP Transport Error: GET SSE failed: ${u.status} ${u.statusText}`});(i=this.onerror)==null||i.call(this,g);return}const f=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new Pn).getReader(),p=async()=>{var g,h,b,y;try{for(;;){const{done:x,value:$}=await f.read();if(x)return;const{event:v,data:k,id:N}=$;if(N&&(this.lastInboundEventId=N),v==="message")try{const I=Tn.parse(JSON.parse(k));(g=this.onmessage)==null||g.call(this,I)}catch(I){const O=new se({message:"MCP HTTP Transport Error: Failed to parse message",cause:I});(h=this.onerror)==null||h.call(this,O)}}}catch(x){if(x instanceof Error&&x.name==="AbortError")return;(b=this.onerror)==null||b.call(this,x),(y=this.abortController)!=null&&y.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>f.cancel()},this.inboundReconnectAttempts=0,p()}catch(l){if(l instanceof Error&&l.name==="AbortError")return;(a=this.onerror)==null||a.call(this,l),(s=this.abortController)!=null&&s.signal.aborted||this.scheduleInboundSseReconnection()}}};function sM(e){switch(e.type){case"sse":return new iM(e);case"http":return new aM(e);default:throw new se({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function uM(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var lM="1.0.0";async function cM(e){const t=new dM(e);return await t.init(),t}var dM=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:n=lM,onUncaughtError:o,capabilities:r}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=o,this.clientCapabilities=r??{},uM(e)?this.transport=e:this.transport=sM(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=i=>this.onError(i),this.transport.onmessage=i=>{if("method"in i){"id"in i?this.onRequestMessage(i):this.onError(new se({message:"Unsupported message type"}));return}this.onResponse(i)},this.clientInfo={name:t,version:n}}async init(){try{await this.transport.start(),this.isClosed=!1;const e=await this.request({request:{method:"initialize",params:{protocolVersion:cn,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:fz});if(e===void 0)throw new se({message:"Server sent invalid initialize result"});if(!cz.includes(e.protocolVersion))throw new se({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(e){throw await this.close(),e}}async close(){var e;this.isClosed||(await((e=this.transport)==null?void 0:e.close()),this.onClose())}assertCapability(e){switch(e){case"initialize":break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new se({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new se({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new se({message:"Server does not support prompts"});break;default:throw new se({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((o,r)=>{if(this.isClosed)return r(new se({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const i=n?.signal;i?.throwIfAborted();const a=this.requestMessageId++,s={...e,jsonrpc:"2.0",id:a},l=()=>{this.responseHandlers.delete(a)};this.responseHandlers.set(a,u=>{if(i?.aborted)return r(new se({message:"Request was aborted",cause:i.reason}));if(u instanceof Error)return r(u);try{const c=t.parse(u.result);o(c)}catch(c){const d=new se({message:"Failed to parse server response",cause:c});r(d)}}),this.transport.send(s).catch(u=>{l(),r(u)})})}async listTools({params:e,options:t}={}){try{return this.request({request:{method:"tools/list",params:e},resultSchema:hz,options:t})}catch(n){throw n}}async callTool({name:e,args:t,options:n}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:yz,options:{signal:n?.abortSignal}})}catch(o){throw o}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:"resources/list",params:e},resultSchema:vz,options:t})}catch(n){throw n}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:wz,options:t})}catch(n){throw n}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:_z,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:Sz,options:t})}catch(n){throw n}}async getPromptInternal({name:e,args:t,options:n}){try{return this.request({request:{method:"prompts/get",params:{name:e,arguments:t}},resultSchema:kz,options:n})}catch(o){throw o}}async notification(e){const t={...e,jsonrpc:"2.0"};await this.transport.send(t)}async tools({schemas:e="automatic"}={}){var t;const n={};try{const o=await this.listTools();for(const{name:r,description:i,inputSchema:a}of o.tools){if(e!=="automatic"&&!(r in e))continue;const s=this,l=async(c,d)=>{var f;return(f=d?.abortSignal)==null||f.throwIfAborted(),s.callTool({name:r,args:c,options:d})},u=e==="automatic"?ez({description:i,inputSchema:rz({...a,properties:(t=a.properties)!=null?t:{},additionalProperties:!1}),execute:l}):{description:i,inputSchema:e[r].inputSchema,execute:l};n[r]=u}return n}catch(o){throw o}}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}getPrompt({name:e,arguments:t,options:n}){return this.getPromptInternal({name:e,args:t,options:n})}onElicitationRequest(e,t){if(e!==Ef)throw new se({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method!=="elicitation/create"){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:"No elicitation handler registered on client"}});return}const t=Ef.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{const n=await this.elicitationRequestHandler(t.data),o=Tz.parse(n);await this.transport.send({jsonrpc:"2.0",id:e.id,result:o})}catch(n){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:n instanceof Error?n.message:"Failed to handle elicitation request"}}),this.onError(n)}}catch(t){this.onError(t)}}onClose(){if(this.isClosed)return;this.isClosed=!0;const e=new se({message:"Connection closed"});for(const t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){const t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new se({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n("result"in e?e:new se({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};function pM({getSession:e,projectSlug:t,mcp:n,environment:o}){const r=r$({getSession:e,projectSlug:t});return t$({queryKey:["mcpTools",t,n,r],queryFn:async()=>(T.assert(r,"No session found"),T.assert(n,"No MCP URL found"),await(await cM({name:"gram-elements-mcp-client",transport:{type:"http",url:n,headers:{...fM(o??{}),"Gram-Chat-Session":r}}})).tools()),enabled:!!r&&!!n,staleTime:1/0,gcTime:1/0})}const Pf="MCP-";function fM(e){return typeof e!="object"||e===null?{}:Object.entries(e).reduce((t,[n,o])=>{const r=n.replace(/_/g,"-"),i=r.startsWith(Pf)?r:`${Pf}${r}`;return t[i]=o,t},{})}function mM({children:e}){const[t,n]=D.useState(new Map),[o,r]=D.useState(new Set),i=D.useCallback((d,f,p)=>new Promise(g=>{const h={toolCallId:f,toolName:d,args:p,resolve:g};n(b=>{const y=new Map(b);return y.set(f,h),y})}),[]),a=D.useCallback(d=>{r(f=>{const p=new Set(f);return p.add(d),p})},[]),s=D.useCallback(d=>{n(f=>{const p=f.get(d);if(p){p.resolve(!0);const g=new Map(f);return g.delete(d),g}return f})},[]),l=D.useCallback(d=>{n(f=>{const p=f.get(d);if(p){p.resolve(!1);const g=new Map(f);return g.delete(d),g}return f})},[]),u=D.useCallback(d=>o.has(d),[o]),c=D.useCallback(d=>t.get(d),[t]);return m.jsx(T.ToolApprovalContext.Provider,{value:{pendingApprovals:t,approvedTools:o,requestApproval:i,whitelistTool:a,confirmPendingApproval:s,rejectPendingApproval:l,isToolApproved:u,getPendingApproval:c},children:e})}const _$=()=>{const e=D.useContext(T.ToolApprovalContext);if(!e)throw new Error("useToolApproval must be used within a ToolApprovalProvider");return e},hM="https://app.getgram.ai",gM="You are a helpful assistant that can answer questions and help with tasks.";function vM(e,t){return`
|
|
89
|
-
${
|
|
88
|
+
`)}})}},qx={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function LA({status:e,statusText:t,headers:n,stream:o,consumeSseStream:r}){let i=o.pipeThrough(new Fx);if(r){const[a,s]=i.tee();i=a,r({stream:s})}return new Response(i.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:Ba(n,qx)})}function ZA({originalMessages:e,responseMessageId:t}){if(e==null)return;const n=e[e.length-1];return n?.role==="assistant"?n.id:typeof t=="function"?t():t}function FA(e){return e.type.startsWith("data-")}function Vx(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const o in t)if(Object.prototype.hasOwnProperty.call(t,o)){const r=t[o];if(r===void 0)continue;const i=o in e?e[o]:void 0,a=r!==null&&typeof r=="object"&&!Array.isArray(r)&&!(r instanceof Date)&&!(r instanceof RegExp),s=i!=null&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof Date)&&!(i instanceof RegExp);a&&s?n[o]=Vx(i,r):n[o]=r}return n}function qA(e){const t=["ROOT"];let n=-1,o=null;function r(l,u,c){switch(l){case'"':{n=u,t.pop(),t.push(c),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,o=u,t.pop(),t.push(c),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(c),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u,t.pop(),t.push(c),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(c),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(c),t.push("INSIDE_ARRAY_START");break}}}function i(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function a(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let l=0;l<e.length;l++){const u=e[l];switch(t[t.length-1]){case"ROOT":r(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{r(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{i(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=l,t.pop();break}default:{n=l,r(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{r(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(u,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const d=e.substring(o,l+1);!"false".startsWith(d)&&!"true".startsWith(d)&&!"null".startsWith(d)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?i(u,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,l)):n=l;break}}}let s=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{s+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{s+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{s+="]";break}case"INSIDE_LITERAL":{const c=e.substring(o,e.length);"true".startsWith(c)?s+="true".slice(c.length):"false".startsWith(c)?s+="false".slice(c.length):"null".startsWith(c)&&(s+="null".slice(c.length))}}return s}async function Bx(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await wr({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await wr({text:qA(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function As(e){return e.type.startsWith("data-")}function Rs(e){return e.type==="text"}function zs(e){return e.type==="file"}function df(e){return e.type==="reasoning"}function Fr(e){return e.type.startsWith("tool-")}function Lc(e){return e.type==="dynamic-tool"}function pf(e){return Fr(e)||Lc(e)}function Ti(e){return e.type.split("-").slice(1).join("-")}function VA(e){return Lc(e)?e.toolName:Ti(e)}function BA({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function JA({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:o,onError:r,onToolCall:i,onData:a}){return e.pipeThrough(new TransformStream({async transform(s,l){await o(async({state:u,write:c})=>{var d,f,p,g;function h(v){const N=u.message.parts.filter(Fr).find(I=>I.toolCallId===v);if(N==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return N}function b(v){const N=u.message.parts.filter(I=>I.type==="dynamic-tool").find(I=>I.toolCallId===v);if(N==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return N}function y(v){var k;const N=u.message.parts.find(z=>Fr(z)&&z.toolCallId===v.toolCallId),I=v,O=N;N!=null?(N.state=v.state,O.input=I.input,O.output=I.output,O.errorText=I.errorText,O.rawInput=I.rawInput,O.preliminary=I.preliminary,O.providerExecuted=(k=I.providerExecuted)!=null?k:N.providerExecuted,I.providerMetadata!=null&&N.state==="input-available"&&(N.callProviderMetadata=I.providerMetadata)):u.message.parts.push({type:`tool-${v.toolName}`,toolCallId:v.toolCallId,state:v.state,input:I.input,output:I.output,rawInput:I.rawInput,errorText:I.errorText,providerExecuted:I.providerExecuted,preliminary:I.preliminary,...I.providerMetadata!=null?{callProviderMetadata:I.providerMetadata}:{}})}function x(v){var k,N;const I=u.message.parts.find(F=>F.type==="dynamic-tool"&&F.toolCallId===v.toolCallId),O=v,z=I;I!=null?(I.state=v.state,z.toolName=v.toolName,z.input=O.input,z.output=O.output,z.errorText=O.errorText,z.rawInput=(k=O.rawInput)!=null?k:z.rawInput,z.preliminary=O.preliminary,z.providerExecuted=(N=O.providerExecuted)!=null?N:I.providerExecuted,O.providerMetadata!=null&&I.state==="input-available"&&(I.callProviderMetadata=O.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:v.toolName,toolCallId:v.toolCallId,state:v.state,input:O.input,output:O.output,errorText:O.errorText,preliminary:O.preliminary,providerExecuted:O.providerExecuted,...O.providerMetadata!=null?{callProviderMetadata:O.providerMetadata}:{}})}async function $(v){if(v!=null){const k=u.message.metadata!=null?Vx(u.message.metadata,v):v;t!=null&&await fu({value:k,schema:t}),u.message.metadata=k}}switch(s.type){case"text-start":{const v={type:"text",text:"",providerMetadata:s.providerMetadata,state:"streaming"};u.activeTextParts[s.id]=v,u.message.parts.push(v),c();break}case"text-delta":{const v=u.activeTextParts[s.id];v.text+=s.delta,v.providerMetadata=(d=s.providerMetadata)!=null?d:v.providerMetadata,c();break}case"text-end":{const v=u.activeTextParts[s.id];v.state="done",v.providerMetadata=(f=s.providerMetadata)!=null?f:v.providerMetadata,delete u.activeTextParts[s.id],c();break}case"reasoning-start":{const v={type:"reasoning",text:"",providerMetadata:s.providerMetadata,state:"streaming"};u.activeReasoningParts[s.id]=v,u.message.parts.push(v),c();break}case"reasoning-delta":{const v=u.activeReasoningParts[s.id];v.text+=s.delta,v.providerMetadata=(p=s.providerMetadata)!=null?p:v.providerMetadata,c();break}case"reasoning-end":{const v=u.activeReasoningParts[s.id];v.providerMetadata=(g=s.providerMetadata)!=null?g:v.providerMetadata,v.state="done",delete u.activeReasoningParts[s.id],c();break}case"file":{u.message.parts.push({type:"file",mediaType:s.mediaType,url:s.url}),c();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:s.sourceId,url:s.url,title:s.title,providerMetadata:s.providerMetadata}),c();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:s.sourceId,mediaType:s.mediaType,title:s.title,filename:s.filename,providerMetadata:s.providerMetadata}),c();break}case"tool-input-start":{const v=u.message.parts.filter(Fr);u.partialToolCalls[s.toolCallId]={text:"",toolName:s.toolName,index:v.length,dynamic:s.dynamic},s.dynamic?x({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-streaming",input:void 0,providerExecuted:s.providerExecuted}):y({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-streaming",input:void 0,providerExecuted:s.providerExecuted}),c();break}case"tool-input-delta":{const v=u.partialToolCalls[s.toolCallId];v.text+=s.inputTextDelta;const{value:k}=await Bx(v.text);v.dynamic?x({toolCallId:s.toolCallId,toolName:v.toolName,state:"input-streaming",input:k}):y({toolCallId:s.toolCallId,toolName:v.toolName,state:"input-streaming",input:k}),c();break}case"tool-input-available":{s.dynamic?x({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-available",input:s.input,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}):y({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-available",input:s.input,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}),c(),i&&!s.providerExecuted&&await i({toolCall:s});break}case"tool-input-error":{s.dynamic?x({toolCallId:s.toolCallId,toolName:s.toolName,state:"output-error",input:s.input,errorText:s.errorText,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}):y({toolCallId:s.toolCallId,toolName:s.toolName,state:"output-error",input:void 0,rawInput:s.input,errorText:s.errorText,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}),c();break}case"tool-output-available":{if(s.dynamic){const v=b(s.toolCallId);x({toolCallId:s.toolCallId,toolName:v.toolName,state:"output-available",input:v.input,output:s.output,preliminary:s.preliminary})}else{const v=h(s.toolCallId);y({toolCallId:s.toolCallId,toolName:Ti(v),state:"output-available",input:v.input,output:s.output,providerExecuted:s.providerExecuted,preliminary:s.preliminary})}c();break}case"tool-output-error":{if(s.dynamic){const v=b(s.toolCallId);x({toolCallId:s.toolCallId,toolName:v.toolName,state:"output-error",input:v.input,errorText:s.errorText,providerExecuted:s.providerExecuted})}else{const v=h(s.toolCallId);y({toolCallId:s.toolCallId,toolName:Ti(v),state:"output-error",input:v.input,rawInput:v.rawInput,errorText:s.errorText,providerExecuted:s.providerExecuted})}c();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{s.messageId!=null&&(u.message.id=s.messageId),await $(s.messageMetadata),(s.messageId!=null||s.messageMetadata!=null)&&c();break}case"finish":{await $(s.messageMetadata),s.messageMetadata!=null&&c();break}case"message-metadata":{await $(s.messageMetadata),s.messageMetadata!=null&&c();break}case"error":{r?.(new Error(s.errorText));break}default:if(FA(s)){n?.[s.type]!=null&&await fu({value:s.data,schema:n[s.type]});const v=s;if(v.transient){a?.(v);break}const k=v.id!=null?u.message.parts.find(N=>v.type===N.type&&v.id===N.id):void 0;k!=null?k.data=v.data:u.message.parts.push(v),a?.(v),c()}}l.enqueue(s)})}}))}function WA({messageId:e,originalMessages:t=[],onFinish:n,onError:o,stream:r}){let i=t?.[t.length-1];i?.role!=="assistant"?i=void 0:e=i.id;let a=!1;const s=r.pipeThrough(new TransformStream({transform(f,p){if(f.type==="start"){const g=f;g.messageId==null&&e!=null&&(g.messageId=e)}f.type==="abort"&&(a=!0),p.enqueue(f)}}));if(n==null)return s;const l=BA({lastMessage:i?structuredClone(i):void 0,messageId:e??""}),u=async f=>{await f({state:l,write:()=>{}})};let c=!1;const d=async()=>{if(c||!n)return;c=!0;const f=l.message.id===i?.id;await n({isAborted:a,isContinuation:f,responseMessage:l.message,messages:[...f?t.slice(0,-1):t,l.message]})};return JA({stream:s,runUpdateMessageJob:u,onError:o}).pipeThrough(new TransformStream({transform(f,p){p.enqueue(f)},async cancel(){await d()},async flush(){await d()}}))}function HA({response:e,status:t,statusText:n,headers:o,stream:r,consumeSseStream:i}){let a=r.pipeThrough(new Fx);if(i){const[s,l]=a.tee();a=s,i({stream:l})}Zx({response:e,status:t,statusText:n,headers:Object.fromEntries(Ba(o,qx).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function Jo(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){const n=this.getReader();let o=!1;async function r(i){var a;o=!0;try{i&&await((a=n.cancel)==null?void 0:a.call(n))}finally{try{n.releaseLock()}catch{}}}return{async next(){if(o)return{done:!0,value:void 0};const{done:i,value:a}=await n.read();return i?(await r(!0),{done:!0,value:void 0}):{done:!1,value:a}},async return(){return await r(!0),{done:!0,value:void 0}},async throw(i){throw await r(!0),i}}},t}async function GA({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:o}=await n.read();if(o)break}}catch(o){t?.(o)}finally{n.releaseLock()}}function ff(){let e,t;return{promise:new Promise((o,r)=>{e=o,t=r}),resolve:e,reject:t}}function KA(){let e=[],t=null,n=!1,o=ff();const r=()=>{n=!0,o.resolve(),e.forEach(a=>a.cancel()),e=[],t?.close()},i=async()=>{if(n&&e.length===0){t?.close();return}if(e.length===0)return o=ff(),await o.promise,i();try{const{value:a,done:s}=await e[0].read();s?(e.shift(),e.length>0?await i():n&&t?.close()):t?.enqueue(a)}catch(a){t?.error(a),e.shift(),r()}};return{stream:new ReadableStream({start(a){t=a},pull:i,async cancel(){for(const a of e)await a.cancel();e=[],n=!0}}),addStream:a=>{if(n)throw new Error("Cannot add inner stream: outer stream is closed");e.push(a.getReader()),o.resolve()},close:()=>{n=!0,o.resolve(),e.length===0&&t?.close()},terminate:r}}var Wo=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((e,t)=>{this.status.type==="resolved"?e(this.status.value):this.status.type==="rejected"&&t(this.status.error),this._resolve=e,this._reject=t}),this._promise)}resolve(e){var t;this.status={type:"resolved",value:e},this._promise&&((t=this._resolve)==null||t.call(this,e))}reject(e){var t;this.status={type:"rejected",error:e},this._promise&&((t=this._reject)==null||t.call(this,e))}};function YA(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}function QA({tools:e,generatorStream:t,tracer:n,telemetry:o,system:r,messages:i,abortSignal:a,repairToolCall:s,experimental_context:l}){let u=null;const c=new ReadableStream({start(y){u=y}}),d=new Set,f=new Map;let p=!1,g;function h(){p&&d.size===0&&(g!=null&&u.enqueue(g),u.close())}const b=new TransformStream({async transform(y,x){const $=y.type;switch($){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{x.enqueue(y);break}case"file":{x.enqueue({type:"file",file:new AA({data:y.data,mediaType:y.mediaType})});break}case"finish":{g={type:"finish",finishReason:y.finishReason,usage:y.usage,providerMetadata:y.providerMetadata};break}case"tool-call":{try{const v=await RA({toolCall:y,tools:e,repairToolCall:s,system:r,messages:i});if(x.enqueue(v),v.invalid){u.enqueue({type:"tool-error",toolCallId:v.toolCallId,toolName:v.toolName,input:v.input,error:jw(v.error),dynamic:!0});break}const k=e[v.toolName];if(f.set(v.toolCallId,v.input),k.onInputAvailable!=null&&await k.onInputAvailable({input:v.input,toolCallId:v.toolCallId,messages:i,abortSignal:a,experimental_context:l}),k.execute!=null&&v.providerExecuted!==!0){const N=ZC();d.add(N),_u({name:"ai.toolCall",attributes:Lr({telemetry:o,attributes:{...bu({operationId:"ai.toolCall",telemetry:o}),"ai.toolCall.name":v.toolName,"ai.toolCall.id":v.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(v.input)}}}),tracer:n,fn:async I=>{let O;try{const z=e1({execute:k.execute.bind(k),input:v.input,options:{toolCallId:v.toolCallId,messages:i,abortSignal:a,experimental_context:l}});for await(const F of z)u.enqueue({...v,type:"tool-result",output:F.output,...F.type==="preliminary"&&{preliminary:!0}}),F.type==="final"&&(O=F.output)}catch(z){Dx(I,z),u.enqueue({...v,type:"tool-error",error:z}),d.delete(N),h();return}d.delete(N),h();try{I.setAttributes(Lr({telemetry:o,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(O)}}}))}catch{}}})}}catch(v){u.enqueue({type:"error",error:v})}break}case"tool-result":{const v=y.toolName;y.isError?u.enqueue({type:"tool-error",toolCallId:y.toolCallId,toolName:v,input:f.get(y.toolCallId),providerExecuted:y.providerExecuted,error:y.result}):x.enqueue({type:"tool-result",toolCallId:y.toolCallId,toolName:v,input:f.get(y.toolCallId),output:y.result,providerExecuted:y.providerExecuted});break}default:{const v=$;throw new Error(`Unhandled chunk type: ${v}`)}}},flush(){p=!0,h()}});return new ReadableStream({async start(y){return Promise.all([t.pipeThrough(b).pipeTo(new WritableStream({write(x){y.enqueue(x)},close(){}})),c.pipeTo(new WritableStream({write(x){y.enqueue(x)},close(){y.close()}}))])}})}var XA=To({prefix:"aitxt",size:24});function eR({model:e,tools:t,toolChoice:n,system:o,prompt:r,messages:i,maxRetries:a,abortSignal:s,headers:l,stopWhen:u=Lx(1),experimental_output:c,experimental_telemetry:d,prepareStep:f,providerOptions:p,experimental_activeTools:g,activeTools:h=g,experimental_repairToolCall:b,experimental_transform:y,experimental_download:x,includeRawChunks:$=!1,onChunk:v,onError:k=({error:q})=>{console.error(q)},onFinish:N,onAbort:I,onStepFinish:O,experimental_context:z,_internal:{now:F=YA,generateId:te=XA,currentDate:ce=()=>new Date}={},...B}){return new rR({model:Cx(e),telemetry:d,headers:l,settings:B,maxRetries:a,abortSignal:s,system:o,prompt:r,messages:i,tools:t,toolChoice:n,transforms:sf(y),activeTools:h,repairToolCall:b,stopConditions:sf(u),output:c,providerOptions:p,prepareStep:f,includeRawChunks:$,onChunk:v,onError:k,onFinish:N,onAbort:I,onStepFinish:O,now:F,currentDate:ce,generateId:te,experimental_context:z,download:x})}function tR(e){if(!e)return new TransformStream({transform(a,s){s.enqueue({part:a,partialOutput:void 0})}});let t,n="",o="",r="";function i({controller:a,partialOutput:s=void 0}){a.enqueue({part:{type:"text-delta",id:t,text:o},partialOutput:s}),o=""}return new TransformStream({async transform(a,s){if(a.type==="finish-step"&&o.length>0&&i({controller:s}),a.type!=="text-delta"&&a.type!=="text-start"&&a.type!=="text-end"){s.enqueue({part:a,partialOutput:void 0});return}if(t==null)t=a.id;else if(a.id!==t){s.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-start"){s.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-end"){o.length>0&&i({controller:s}),s.enqueue({part:a,partialOutput:void 0});return}n+=a.text,o+=a.text;const l=await e.parsePartial({text:n});if(l!=null){const u=JSON.stringify(l.partial);u!==r&&(i({controller:s,partialOutput:l.partial}),r=u)}}})}var rR=class{constructor({model:e,telemetry:t,headers:n,settings:o,maxRetries:r,abortSignal:i,system:a,prompt:s,messages:l,tools:u,toolChoice:c,transforms:d,activeTools:f,repairToolCall:p,stopConditions:g,output:h,providerOptions:b,prepareStep:y,includeRawChunks:x,now:$,currentDate:v,generateId:k,onChunk:N,onError:I,onFinish:O,onAbort:z,onStepFinish:F,experimental_context:te,download:ce}){this._totalUsage=new Wo,this._finishReason=new Wo,this._steps=new Wo,this.output=h,this.includeRawChunks=x,this.tools=u;let B,q=[];const we=[];let oe,de,K={},fe=[];const J=[];let Ue,ye={},Le={};const U=new TransformStream({async transform(Ee,Te){var Ae,ie,ft,mn;Te.enqueue(Ee);const{part:Z}=Ee;if((Z.type==="text-delta"||Z.type==="reasoning-delta"||Z.type==="source"||Z.type==="tool-call"||Z.type==="tool-result"||Z.type==="tool-input-start"||Z.type==="tool-input-delta"||Z.type==="raw")&&await N?.({chunk:Z}),Z.type==="error"&&await I({error:$A(Z.error)}),Z.type==="text-start"&&(ye[Z.id]={type:"text",text:"",providerMetadata:Z.providerMetadata},q.push(ye[Z.id])),Z.type==="text-delta"){const Ie=ye[Z.id];if(Ie==null){Te.enqueue({part:{type:"error",error:`text part ${Z.id} not found`},partialOutput:void 0});return}Ie.text+=Z.text,Ie.providerMetadata=(Ae=Z.providerMetadata)!=null?Ae:Ie.providerMetadata}if(Z.type==="text-end"){const Ie=ye[Z.id];if(Ie==null){Te.enqueue({part:{type:"error",error:`text part ${Z.id} not found`},partialOutput:void 0});return}Ie.providerMetadata=(ie=Z.providerMetadata)!=null?ie:Ie.providerMetadata,delete ye[Z.id]}if(Z.type==="reasoning-start"&&(Le[Z.id]={type:"reasoning",text:"",providerMetadata:Z.providerMetadata},q.push(Le[Z.id])),Z.type==="reasoning-delta"){const Ie=Le[Z.id];if(Ie==null){Te.enqueue({part:{type:"error",error:`reasoning part ${Z.id} not found`},partialOutput:void 0});return}Ie.text+=Z.text,Ie.providerMetadata=(ft=Z.providerMetadata)!=null?ft:Ie.providerMetadata}if(Z.type==="reasoning-end"){const Ie=Le[Z.id];if(Ie==null){Te.enqueue({part:{type:"error",error:`reasoning part ${Z.id} not found`},partialOutput:void 0});return}Ie.providerMetadata=(mn=Z.providerMetadata)!=null?mn:Ie.providerMetadata,delete Le[Z.id]}if(Z.type==="file"&&q.push({type:"file",file:Z.file}),Z.type==="source"&&q.push(Z),Z.type==="tool-call"&&q.push(Z),Z.type==="tool-result"&&!Z.preliminary&&q.push(Z),Z.type==="tool-error"&&q.push(Z),Z.type==="start-step"&&(K=Z.request,fe=Z.warnings),Z.type==="finish-step"){const Ie=cf({content:q,tools:u}),hn=new zA({content:q,finishReason:Z.finishReason,usage:Z.usage,warnings:fe,request:K,response:{...Z.response,messages:[...we,...Ie]},providerMetadata:Z.providerMetadata});await F?.(hn),A1(fe),J.push(hn),q=[],Le={},ye={},we.push(...Ie),B.resolve()}Z.type==="finish"&&(de=Z.totalUsage,oe=Z.finishReason)},async flush(Ee){try{if(J.length===0){const ft=new U1({message:"No output generated. Check the stream for errors."});je._finishReason.reject(ft),je._totalUsage.reject(ft),je._steps.reject(ft);return}const Te=oe??"unknown",Ae=de??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};je._finishReason.resolve(Te),je._totalUsage.resolve(Ae),je._steps.resolve(J);const ie=J[J.length-1];await O?.({finishReason:Te,totalUsage:Ae,usage:ie.usage,content:ie.content,text:ie.text,reasoningText:ie.reasoningText,reasoning:ie.reasoning,files:ie.files,sources:ie.sources,toolCalls:ie.toolCalls,staticToolCalls:ie.staticToolCalls,dynamicToolCalls:ie.dynamicToolCalls,toolResults:ie.toolResults,staticToolResults:ie.staticToolResults,dynamicToolResults:ie.dynamicToolResults,request:ie.request,response:ie.response,warnings:ie.warnings,providerMetadata:ie.providerMetadata,steps:J}),Ue.setAttributes(Lr({telemetry:t,attributes:{"ai.response.finishReason":Te,"ai.response.text":{output:()=>ie.text},"ai.response.toolCalls":{output:()=>{var ft;return(ft=ie.toolCalls)!=null&&ft.length?JSON.stringify(ie.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(ie.providerMetadata),"ai.usage.inputTokens":Ae.inputTokens,"ai.usage.outputTokens":Ae.outputTokens,"ai.usage.totalTokens":Ae.totalTokens,"ai.usage.reasoningTokens":Ae.reasoningTokens,"ai.usage.cachedInputTokens":Ae.cachedInputTokens}}))}catch(Te){Ee.error(Te)}finally{Ue.end()}}}),Q=KA();this.addStream=Q.addStream,this.closeStream=Q.close;const me=Q.stream.getReader();let xe=new ReadableStream({async start(Ee){Ee.enqueue({type:"start"})},async pull(Ee){function Te(){z?.({steps:J}),Ee.enqueue({type:"abort"}),Ee.close()}try{const{done:Ae,value:ie}=await me.read();if(Ae){Ee.close();return}if(i?.aborted){Te();return}Ee.enqueue(ie)}catch(Ae){_r(Ae)&&i?.aborted?Te():Ee.error(Ae)}},cancel(Ee){return Q.stream.cancel(Ee)}});for(const Ee of d)xe=xe.pipeThrough(Ee({tools:u,stopStream(){Q.terminate()}}));this.baseStream=xe.pipeThrough(tR(h)).pipeThrough(U);const{maxRetries:Ro,retry:ss}=CA({maxRetries:r,abortSignal:i}),fn=EA(t),pt=cA(o),zo=SA({model:e,telemetry:t,headers:n,settings:{...pt,maxRetries:Ro}}),je=this;_u({name:"ai.streamText",attributes:Lr({telemetry:t,attributes:{...bu({operationId:"ai.streamText",telemetry:t}),...zo,"ai.prompt":{input:()=>JSON.stringify({system:a,prompt:s,messages:l})}}}),tracer:fn,endWhenDone:!1,fn:async Ee=>{Ue=Ee;async function Te({currentStep:Ae,responseMessages:ie,usage:ft}){var mn,Z,Ie,hn,Sd;const Id=je.includeRawChunks;B=new Wo;const kd=await xA({system:a,prompt:s,messages:l}),gn=[...kd.messages,...ie],Et=await y?.({model:e,steps:J,stepNumber:J.length,messages:gn}),Nr=Cx((mn=Et?.model)!=null?mn:e),Ed=await aA({prompt:{system:(Z=Et?.system)!=null?Z:kd.system,messages:(Ie=Et?.messages)!=null?Ie:gn},supportedUrls:await Nr.supportedUrls,download:ce}),{toolChoice:us,tools:ls}=pA({tools:u,toolChoice:(hn=Et?.toolChoice)!=null?hn:c,activeTools:(Sd=Et?.activeTools)!=null?Sd:f}),{result:{stream:g0,response:Td,request:Od},doStreamSpan:Pr,startTimestampMs:Nd}=await ss(()=>_u({name:"ai.streamText.doStream",attributes:Lr({telemetry:t,attributes:{...bu({operationId:"ai.streamText.doStream",telemetry:t}),...zo,"ai.model.provider":Nr.provider,"ai.model.id":Nr.modelId,"ai.prompt.messages":{input:()=>TA(Ed)},"ai.prompt.tools":{input:()=>ls?.map(W=>JSON.stringify(W))},"ai.prompt.toolChoice":{input:()=>us!=null?JSON.stringify(us):void 0},"gen_ai.system":Nr.provider,"gen_ai.request.model":Nr.modelId,"gen_ai.request.frequency_penalty":pt.frequencyPenalty,"gen_ai.request.max_tokens":pt.maxOutputTokens,"gen_ai.request.presence_penalty":pt.presencePenalty,"gen_ai.request.stop_sequences":pt.stopSequences,"gen_ai.request.temperature":pt.temperature,"gen_ai.request.top_k":pt.topK,"gen_ai.request.top_p":pt.topP}}),tracer:fn,endWhenDone:!1,fn:async W=>({startTimestampMs:$(),doStreamSpan:W,result:await Nr.doStream({...pt,tools:ls,toolChoice:us,responseFormat:h?.responseFormat,prompt:Ed,providerOptions:b,abortSignal:i,headers:n,includeRawChunks:Id})})})),v0=QA({tools:u,generatorStream:g0,tracer:fn,telemetry:t,system:a,messages:gn,repairToolCall:p,abortSignal:i,experimental_context:te}),y0=Od??{},Mo=[],cs=[];let ds;const ps={};let Cr="unknown",mt={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},fs,Pd=!0,Tt={id:k(),timestamp:v(),modelId:e.modelId},Cd="";je.addStream(v0.pipeThrough(new TransformStream({async transform(W,Re){var vn,yn,Do,Ut;if(W.type==="stream-start"){ds=W.warnings;return}if(Pd){const Ze=$()-Nd;Pd=!1,Pr.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":Ze}),Pr.setAttributes({"ai.response.msToFirstChunk":Ze}),Re.enqueue({type:"start-step",request:y0,warnings:ds??[]})}const jd=W.type;switch(jd){case"text-start":case"text-end":{Re.enqueue(W);break}case"text-delta":{W.delta.length>0&&(Re.enqueue({type:"text-delta",id:W.id,text:W.delta,providerMetadata:W.providerMetadata}),Cd+=W.delta);break}case"reasoning-start":case"reasoning-end":{Re.enqueue(W);break}case"reasoning-delta":{Re.enqueue({type:"reasoning-delta",id:W.id,text:W.delta,providerMetadata:W.providerMetadata});break}case"tool-call":{Re.enqueue(W),Mo.push(W);break}case"tool-result":{Re.enqueue(W),W.preliminary||cs.push(W);break}case"tool-error":{Re.enqueue(W),cs.push(W);break}case"response-metadata":{Tt={id:(vn=W.id)!=null?vn:Tt.id,timestamp:(yn=W.timestamp)!=null?yn:Tt.timestamp,modelId:(Do=W.modelId)!=null?Do:Tt.modelId};break}case"finish":{mt=W.usage,Cr=W.finishReason,fs=W.providerMetadata;const Ze=$()-Nd;Pr.addEvent("ai.stream.finish"),Pr.setAttributes({"ai.response.msToFinish":Ze,"ai.response.avgOutputTokensPerSecond":1e3*((Ut=mt.outputTokens)!=null?Ut:0)/Ze});break}case"file":{Re.enqueue(W);break}case"source":{Re.enqueue(W);break}case"tool-input-start":{ps[W.id]=W.toolName;const Ze=u?.[W.toolName];Ze?.onInputStart!=null&&await Ze.onInputStart({toolCallId:W.id,messages:gn,abortSignal:i,experimental_context:te}),Re.enqueue({...W,dynamic:Ze?.type==="dynamic"});break}case"tool-input-end":{delete ps[W.id],Re.enqueue(W);break}case"tool-input-delta":{const Ze=ps[W.id],ms=u?.[Ze];ms?.onInputDelta!=null&&await ms.onInputDelta({inputTextDelta:W.delta,toolCallId:W.id,messages:gn,abortSignal:i,experimental_context:te}),Re.enqueue(W);break}case"error":{Re.enqueue(W),Cr="error";break}case"raw":{Id&&Re.enqueue(W);break}default:{const Ze=jd;throw new Error(`Unknown chunk type: ${Ze}`)}}},async flush(W){const Re=Mo.length>0?JSON.stringify(Mo):void 0;try{Pr.setAttributes(Lr({telemetry:t,attributes:{"ai.response.finishReason":Cr,"ai.response.text":{output:()=>Cd},"ai.response.toolCalls":{output:()=>Re},"ai.response.id":Tt.id,"ai.response.model":Tt.modelId,"ai.response.timestamp":Tt.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(fs),"ai.usage.inputTokens":mt.inputTokens,"ai.usage.outputTokens":mt.outputTokens,"ai.usage.totalTokens":mt.totalTokens,"ai.usage.reasoningTokens":mt.reasoningTokens,"ai.usage.cachedInputTokens":mt.cachedInputTokens,"gen_ai.response.finish_reasons":[Cr],"gen_ai.response.id":Tt.id,"gen_ai.response.model":Tt.modelId,"gen_ai.usage.input_tokens":mt.inputTokens,"gen_ai.usage.output_tokens":mt.outputTokens}}))}catch{}finally{Pr.end()}W.enqueue({type:"finish-step",finishReason:Cr,usage:mt,providerMetadata:fs,response:{...Tt,headers:Td?.headers}});const vn=OA(ft,mt);await B.promise;const yn=Mo.filter(Ut=>Ut.providerExecuted!==!0),Do=cs.filter(Ut=>Ut.providerExecuted!==!0);if(yn.length>0&&Do.length===yn.length&&!await MA({stopConditions:g,steps:J})){ie.push(...cf({content:J[J.length-1].content,tools:u}));try{await Te({currentStep:Ae+1,responseMessages:ie,usage:vn})}catch(Ut){W.enqueue({type:"error",error:Ut}),je.closeStream()}}else W.enqueue({type:"finish",finishReason:Cr,totalUsage:vn}),je.closeStream()}})))}await Te({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(Ee=>{je.addStream(new ReadableStream({start(Te){Te.enqueue({type:"error",error:Ee}),Te.close()}})),je.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){const[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return Jo(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return Jo(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await GA({stream:this.fullStream,onError:e?.onError})}catch(n){(t=e?.onError)==null||t.call(e,n)}}get experimental_partialOutputStream(){if(this.output==null)throw new P1;return Jo(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:o,sendReasoning:r=!0,sendSources:i=!1,sendStart:a=!0,sendFinish:s=!0,onError:l=sn}={}){const u=t!=null?ZA({originalMessages:e,responseMessageId:t}):void 0,c={},d=p=>{var g,h;const b=c[p];return((h=(g=this.tools)==null?void 0:g[b])==null?void 0:h.type)==="dynamic"?!0:void 0},f=this.fullStream.pipeThrough(new TransformStream({transform:async(p,g)=>{const h=o?.({part:p}),b=p.type;switch(b){case"text-start":{g.enqueue({type:"text-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-delta":{g.enqueue({type:"text-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-end":{g.enqueue({type:"text-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-start":{g.enqueue({type:"reasoning-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-delta":{r&&g.enqueue({type:"reasoning-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-end":{g.enqueue({type:"reasoning-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"file":{g.enqueue({type:"file",mediaType:p.file.mediaType,url:`data:${p.file.mediaType};base64,${p.file.base64}`});break}case"source":{i&&p.sourceType==="url"&&g.enqueue({type:"source-url",sourceId:p.id,url:p.url,title:p.title,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}}),i&&p.sourceType==="document"&&g.enqueue({type:"source-document",sourceId:p.id,mediaType:p.mediaType,title:p.title,filename:p.filename,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"tool-input-start":{c[p.id]=p.toolName;const y=d(p.id);g.enqueue({type:"tool-input-start",toolCallId:p.id,toolName:p.toolName,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...y!=null?{dynamic:y}:{}});break}case"tool-input-delta":{g.enqueue({type:"tool-input-delta",toolCallId:p.id,inputTextDelta:p.delta});break}case"tool-call":{c[p.toolCallId]=p.toolName;const y=d(p.toolCallId);p.invalid?g.enqueue({type:"tool-input-error",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...y!=null?{dynamic:y}:{},errorText:l(p.error)}):g.enqueue({type:"tool-input-available",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...y!=null?{dynamic:y}:{}});break}case"tool-result":{const y=d(p.toolCallId);g.enqueue({type:"tool-output-available",toolCallId:p.toolCallId,output:p.output,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.preliminary!=null?{preliminary:p.preliminary}:{},...y!=null?{dynamic:y}:{}});break}case"tool-error":{const y=d(p.toolCallId);g.enqueue({type:"tool-output-error",toolCallId:p.toolCallId,errorText:l(p.error),...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...y!=null?{dynamic:y}:{}});break}case"error":{g.enqueue({type:"error",errorText:l(p.error)});break}case"start-step":{g.enqueue({type:"start-step"});break}case"finish-step":{g.enqueue({type:"finish-step"});break}case"start":{a&&g.enqueue({type:"start",...h!=null?{messageMetadata:h}:{},...u!=null?{messageId:u}:{}});break}case"finish":{s&&g.enqueue({type:"finish",...h!=null?{messageMetadata:h}:{}});break}case"abort":{g.enqueue(p);break}case"tool-input-end":break;case"raw":break;default:{const y=b;throw new Error(`Unknown chunk type: ${y}`)}}h!=null&&b!=="start"&&b!=="finish"&&g.enqueue({type:"message-metadata",messageMetadata:h})}}));return Jo(WA({stream:f,messageId:u??t?.(),originalMessages:e,onFinish:n,onError:l}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:n,onFinish:o,messageMetadata:r,sendReasoning:i,sendSources:a,sendFinish:s,sendStart:l,onError:u,...c}={}){HA({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:n,onFinish:o,messageMetadata:r,sendReasoning:i,sendSources:a,sendFinish:s,sendStart:l,onError:u}),...c})}pipeTextStreamToResponse(e,t){UA({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:o,sendReasoning:r,sendSources:i,sendFinish:a,sendStart:s,onError:l,...u}={}){return LA({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:o,sendReasoning:r,sendSources:i,sendFinish:a,sendStart:s,onError:l}),...u})}toTextStreamResponse(e){return DA({textStream:this.textStream,...e})}};function nR(e,t){const n=[];t?.ignoreIncompleteToolCalls&&(e=e.map(o=>({...o,parts:o.parts.filter(r=>!pf(r)||r.state!=="input-streaming"&&r.state!=="input-available")})));for(const o of e)switch(o.role){case"system":{const r=o.parts.filter(a=>a.type==="text"),i=r.reduce((a,s)=>s.providerMetadata!=null?{...a,...s.providerMetadata}:a,{});n.push({role:"system",content:r.map(a=>a.text).join(""),...Object.keys(i).length>0?{providerOptions:i}:{}});break}case"user":{n.push({role:"user",content:o.parts.map(r=>{var i;if(Rs(r))return{type:"text",text:r.text,...r.providerMetadata!=null?{providerOptions:r.providerMetadata}:{}};if(zs(r))return{type:"file",mediaType:r.mediaType,filename:r.filename,data:r.url,...r.providerMetadata!=null?{providerOptions:r.providerMetadata}:{}};if(As(r))return(i=t?.convertDataPart)==null?void 0:i.call(t,r)}).filter(r=>r!=null)});break}case"assistant":{if(o.parts!=null){let r=function(){var a,s,l;if(i.length===0)return;const u=[];for(const d of i)if(Rs(d))u.push({type:"text",text:d.text,...d.providerMetadata!=null?{providerOptions:d.providerMetadata}:{}});else if(zs(d))u.push({type:"file",mediaType:d.mediaType,filename:d.filename,data:d.url});else if(df(d))u.push({type:"reasoning",text:d.text,providerOptions:d.providerMetadata});else if(Lc(d)){const f=d.toolName;d.state!=="input-streaming"&&u.push({type:"tool-call",toolCallId:d.toolCallId,toolName:f,input:d.input,...d.callProviderMetadata!=null?{providerOptions:d.callProviderMetadata}:{}})}else if(Fr(d)){const f=Ti(d);d.state!=="input-streaming"&&(u.push({type:"tool-call",toolCallId:d.toolCallId,toolName:f,input:d.state==="output-error"?(a=d.input)!=null?a:d.rawInput:d.input,providerExecuted:d.providerExecuted,...d.callProviderMetadata!=null?{providerOptions:d.callProviderMetadata}:{}}),d.providerExecuted===!0&&(d.state==="output-available"||d.state==="output-error")&&u.push({type:"tool-result",toolCallId:d.toolCallId,toolName:f,output:Nn({output:d.state==="output-error"?d.errorText:d.output,tool:(s=t?.tools)==null?void 0:s[f],errorMode:d.state==="output-error"?"json":"none"})}))}else if(As(d)){const f=(l=t?.convertDataPart)==null?void 0:l.call(t,d);f!=null&&u.push(f)}else{const f=d;throw new Error(`Unsupported part: ${f}`)}n.push({role:"assistant",content:u});const c=i.filter(d=>Fr(d)&&d.providerExecuted!==!0||d.type==="dynamic-tool");c.length>0&&n.push({role:"tool",content:c.map(d=>{var f;switch(d.state){case"output-error":case"output-available":{const p=VA(d);return{type:"tool-result",toolCallId:d.toolCallId,toolName:p,output:Nn({output:d.state==="output-error"?d.errorText:d.output,tool:(f=t?.tools)==null?void 0:f[p],errorMode:d.state==="output-error"?"text":"none"})}}default:return null}}).filter(d=>d!=null)}),i=[]},i=[];for(const a of o.parts)Rs(a)||df(a)||zs(a)||pf(a)||As(a)?i.push(a):a.type==="step-start"&&r();r();break}break}default:{const r=o.role;throw new W1({originalMessage:o,message:`Unsupported role: ${r}`})}}return n}To({prefix:"aiobj",size:24});To({prefix:"aiobj",size:24});var oR={};O1(oR,{object:()=>aR,text:()=>iR});var iR=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),aR=({schema:e})=>{const t=Va(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const o=await Bx(n);switch(o.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:o.value};default:{const r=o.state;throw new Error(`Unsupported parse state: ${r}`)}}},async parseOutput({text:n},o){const r=await wr({text:n});if(!r.success)throw new of({message:"No object generated: could not parse the response.",cause:r.error,text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});const i=await sr({value:r.value,schema:t});if(!i.success)throw new of({message:"No object generated: response did not match schema.",cause:i.error,text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});return i.value}}},sR={word:/\S+\s+/m,line:/\n+/m};function uR({delayInMs:e=10,chunking:t="word",_internal:{delay:n=Cw}={}}={}){let o;if(typeof t=="function")o=r=>{const i=t(r);if(i==null)return null;if(!i.length)throw new Error("Chunking function must return a non-empty string.");if(!r.startsWith(i))throw new Error(`Chunking function must return a match that is a prefix of the buffer. Received: "${i}" expected to start with "${r}"`);return i};else{const r=typeof t=="string"?sR[t]:t;if(r==null)throw new Vi({argument:"chunking",message:`Chunking must be "word" or "line" or a RegExp. Received: ${t}`});o=i=>{const a=r.exec(i);return a?i.slice(0,a.index)+a?.[0]:null}}return()=>{let r="",i="";return new TransformStream({async transform(a,s){if(a.type!=="text-delta"){r.length>0&&(s.enqueue({type:"text-delta",text:r,id:i}),r=""),s.enqueue(a);return}a.id!==i&&r.length>0&&(s.enqueue({type:"text-delta",text:r,id:i}),r=""),r+=a.text,i=a.id;let l;for(;(l=o(r))!=null;)s.enqueue({type:"text-delta",text:l,id:i}),r=r.slice(l.length),await n(e)}})}}const lR=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,{...n.description?{description:n.description}:void 0,parameters:n.parameters instanceof vi.ZodType?vi.toJSONSchema(n.parameters):n.parameters}])),cR=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>!t.disabled&&t.type!=="backend"));let Oi=null;function dR(e,t){Oi={helpers:e,toolsRequiringApproval:new Set(t)}}function pR(){Oi=null}const fR=(e,t)=>L.makeAssistantTool({...e,execute:async(n,o)=>{if(Oi?.toolsRequiringApproval.has(t)){const{helpers:r}=Oi,i=o.toolCallId??"";if(!r.isToolApproved(t)&&!await r.requestApproval(t,i,n))return{content:[{type:"text",text:`Tool "${t}" execution was denied by the user. Please acknowledge this and continue without using this tool's result.`}],isError:!0}}return e.execute?.(n,o)},toolName:t});function mR(e,t,n){if(!t||t.length===0)return e;const o=new Set(t);return Object.fromEntries(Object.entries(e).map(([r,i])=>{if(!o.has(r))return[r,i];const a=i.execute;return a?[r,{...i,execute:async(s,l)=>{const u=l??{},c=u.toolCallId??"";return n.isToolApproved(r)||await n.requestApproval(r,c,s)?a(s,u):{content:[{type:"text",text:`Tool "${r}" execution was denied by the user. Please acknowledge this and continue without using this tool's result.`}],isError:!0}}}]:[r,i]}))}var Oo=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},hR={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},gR=class{#e=hR;#t=!1;setTimeoutProvider(e){process.env.NODE_ENV!=="production"&&this.#t&&e!==this.#e&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:this.#e,provider:e}),this.#e=e,process.env.NODE_ENV!=="production"&&(this.#t=!1)}setTimeout(e,t){return process.env.NODE_ENV!=="production"&&(this.#t=!0),this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return process.env.NODE_ENV!=="production"&&(this.#t=!0),this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},gr=new gR;function vR(e){setTimeout(e,0)}var $r=typeof window>"u"||"Deno"in globalThis;function Je(){}function yR(e,t){return typeof e=="function"?e(t):e}function wu(e){return typeof e=="number"&&e>=0&&e!==1/0}function Jx(e,t){return Math.max(e+(t||0)-Date.now(),0)}function nr(e,t){return typeof e=="function"?e(t):e}function at(e,t){return typeof e=="function"?e(t):e}function mf(e,t){const{type:n="all",exact:o,fetchStatus:r,predicate:i,queryKey:a,stale:s}=e;if(a){if(o){if(t.queryHash!==Zc(a,t.options))return!1}else if(!Gn(t.queryKey,a))return!1}if(n!=="all"){const l=t.isActive();if(n==="active"&&!l||n==="inactive"&&l)return!1}return!(typeof s=="boolean"&&t.isStale()!==s||r&&r!==t.state.fetchStatus||i&&!i(t))}function hf(e,t){const{exact:n,status:o,predicate:r,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Hn(t.options.mutationKey)!==Hn(i))return!1}else if(!Gn(t.options.mutationKey,i))return!1}return!(o&&t.state.status!==o||r&&!r(t))}function Zc(e,t){return(t?.queryKeyHashFn||Hn)(e)}function Hn(e){return JSON.stringify(e,(t,n)=>Su(n)?Object.keys(n).sort().reduce((o,r)=>(o[r]=n[r],o),{}):n)}function Gn(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>Gn(e[n],t[n])):!1}var bR=Object.prototype.hasOwnProperty;function xu(e,t){if(e===t)return e;const n=gf(e)&&gf(t);if(!n&&!(Su(e)&&Su(t)))return t;const r=(n?e:Object.keys(e)).length,i=n?t:Object.keys(t),a=i.length,s=n?new Array(a):{};let l=0;for(let u=0;u<a;u++){const c=n?u:i[u],d=e[c],f=t[c];if(d===f){s[c]=d,(n?u<r:bR.call(e,c))&&l++;continue}if(d===null||f===null||typeof d!="object"||typeof f!="object"){s[c]=f;continue}const p=xu(d,f);s[c]=p,p===d&&l++}return r===a&&l===r?e:s}function $u(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function gf(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Su(e){if(!vf(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!vf(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function vf(e){return Object.prototype.toString.call(e)==="[object Object]"}function _R(e){return new Promise(t=>{gr.setTimeout(t,e)})}function Iu(e,t,n){if(typeof n.structuralSharing=="function")return n.structuralSharing(e,t);if(n.structuralSharing!==!1){if(process.env.NODE_ENV!=="production")try{return xu(e,t)}catch(o){throw console.error(`Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${n.queryHash}]: ${o}`),o}return xu(e,t)}return t}function wR(e,t,n=0){const o=[...e,t];return n&&o.length>n?o.slice(1):o}function xR(e,t,n=0){const o=[t,...e];return n&&o.length>n?o.slice(0,-1):o}var Ni=Symbol();function Wx(e,t){return process.env.NODE_ENV!=="production"&&e.queryFn===Ni&&console.error(`Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${e.queryHash}'`),!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Ni?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function $R(e,t){return typeof e=="function"?e(...t):!!e}var SR=class extends Oo{#e;#t;#r;constructor(){super(),this.#r=e=>{if(!$r&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#r=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},Fc=new SR;function ku(){let e,t;const n=new Promise((r,i)=>{e=r,t=i});n.status="pending",n.catch(()=>{});function o(r){Object.assign(n,r),delete n.resolve,delete n.reject}return n.resolve=r=>{o({status:"fulfilled",value:r}),e(r)},n.reject=r=>{o({status:"rejected",reason:r}),t(r)},n}var IR=vR;function kR(){let e=[],t=0,n=s=>{s()},o=s=>{s()},r=IR;const i=s=>{t?e.push(s):r(()=>{n(s)})},a=()=>{const s=e;e=[],s.length&&r(()=>{o(()=>{s.forEach(l=>{n(l)})})})};return{batch:s=>{let l;t++;try{l=s()}finally{t--,t||a()}return l},batchCalls:s=>(...l)=>{i(()=>{s(...l)})},schedule:i,setNotifyFunction:s=>{n=s},setBatchNotifyFunction:s=>{o=s},setScheduler:s=>{r=s}}}var ze=kR(),ER=class extends Oo{#e=!0;#t;#r;constructor(){super(),this.#r=e=>{if(!$r&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#r=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#e}},Pi=new ER;function TR(e){return Math.min(1e3*2**e,3e4)}function Hx(e){return(e??"online")==="online"?Pi.isOnline():!0}var Eu=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Gx(e){let t=!1,n=0,o;const r=ku(),i=()=>r.status!=="pending",a=h=>{if(!i()){const b=new Eu(h);f(b),e.onCancel?.(b)}},s=()=>{t=!0},l=()=>{t=!1},u=()=>Fc.isFocused()&&(e.networkMode==="always"||Pi.isOnline())&&e.canRun(),c=()=>Hx(e.networkMode)&&e.canRun(),d=h=>{i()||(o?.(),r.resolve(h))},f=h=>{i()||(o?.(),r.reject(h))},p=()=>new Promise(h=>{o=b=>{(i()||u())&&h(b)},e.onPause?.()}).then(()=>{o=void 0,i()||e.onContinue?.()}),g=()=>{if(i())return;let h;const b=n===0?e.initialPromise:void 0;try{h=b??e.fn()}catch(y){h=Promise.reject(y)}Promise.resolve(h).then(d).catch(y=>{if(i())return;const x=e.retry??($r?0:3),$=e.retryDelay??TR,v=typeof $=="function"?$(n,y):$,k=x===!0||typeof x=="number"&&n<x||typeof x=="function"&&x(n,y);if(t||!k){f(y);return}n++,e.onFail?.(n,y),_R(v).then(()=>u()?void 0:p()).then(()=>{t?f(y):g()})})};return{promise:r,status:()=>r.status,cancel:a,continue:()=>(o?.(),r),cancelRetry:s,continueRetry:l,canStart:c,start:()=>(c()?g():p().then(g),r)}}var Kx=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),wu(this.gcTime)&&(this.#e=gr.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??($r?1/0:300*1e3))}clearGcTimeout(){this.#e&&(gr.clearTimeout(this.#e),this.#e=void 0)}},OR=class extends Kx{#e;#t;#r;#o;#n;#s;#a;constructor(e){super(),this.#a=!1,this.#s=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#o=e.client,this.#r=this.#o.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#e=bf(this.options),this.state=e.state??this.#e,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#n?.promise}setOptions(e){if(this.options={...this.#s,...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=bf(this.options);t.data!==void 0&&(this.setState(yf(t.data,t.dataUpdatedAt)),this.#e=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#r.remove(this)}setData(e,t){const n=Iu(this.state.data,e,this.options);return this.#i({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#i({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#n?.promise;return this.#n?.cancel(e),t?t.then(Je).catch(Je):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#e)}isActive(){return this.observers.some(e=>at(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Ni||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>nr(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!Jx(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#n?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#n?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#n&&(this.#a?this.#n.cancel({revert:!0}):this.#n.cancelRetry()),this.scheduleGc()),this.#r.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#i({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#n?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#n)return this.#n.continueRetry(),this.#n.promise}if(e&&this.setOptions(e),!this.options.queryFn){const s=this.observers.find(l=>l.options.queryFn);s&&this.setOptions(s.options)}process.env.NODE_ENV!=="production"&&(Array.isArray(this.options.queryKey)||console.error("As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']"));const n=new AbortController,o=s=>{Object.defineProperty(s,"signal",{enumerable:!0,get:()=>(this.#a=!0,n.signal)})},r=()=>{const s=Wx(this.options,t),u=(()=>{const c={client:this.#o,queryKey:this.queryKey,meta:this.meta};return o(c),c})();return this.#a=!1,this.options.persister?this.options.persister(s,u,this):s(u)},a=(()=>{const s={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#o,state:this.state,fetchFn:r};return o(s),s})();this.options.behavior?.onFetch(a,this),this.#t=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#i({type:"fetch",meta:a.fetchOptions?.meta}),this.#n=Gx({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:s=>{s instanceof Eu&&s.revert&&this.setState({...this.#t,fetchStatus:"idle"}),n.abort()},onFail:(s,l)=>{this.#i({type:"failed",failureCount:s,error:l})},onPause:()=>{this.#i({type:"pause"})},onContinue:()=>{this.#i({type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{const s=await this.#n.start();if(s===void 0)throw process.env.NODE_ENV!=="production"&&console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`),new Error(`${this.queryHash} data is undefined`);return this.setData(s),this.#r.config.onSuccess?.(s,this),this.#r.config.onSettled?.(s,this.state.error,this),s}catch(s){if(s instanceof Eu){if(s.silent)return this.#n.promise;if(s.revert){if(this.state.data===void 0)throw s;return this.state.data}}throw this.#i({type:"error",error:s}),this.#r.config.onError?.(s,this),this.#r.config.onSettled?.(this.state.data,s,this),s}finally{this.scheduleGc()}}#i(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...Yx(n.data,this.options),fetchMeta:e.meta??null};case"success":const o={...n,...yf(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#t=e.manual?o:void 0,o;case"error":const r=e.error;return{...n,error:r,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:"idle",status:"error"};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),ze.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#r.notify({query:this,type:"updated",action:e})})}};function Yx(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Hx(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function yf(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function bf(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,o=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?o??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var NR=class extends Oo{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#a=ku(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#r=void 0;#o=void 0;#n;#s;#a;#i;#h;#p;#f;#l;#c;#u;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),_f(this.#t,this.options)?this.#d():this.updateResult(),this.#b())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Tu(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Tu(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#_(),this.#w(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof at(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#x(),this.#t.setOptions(this.options),t._defaulted&&!$u(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const o=this.hasListeners();o&&wf(this.#t,n,this.options,t)&&this.#d(),this.updateResult(),o&&(this.#t!==n||at(this.options.enabled,this.#t)!==at(t.enabled,this.#t)||nr(this.options.staleTime,this.#t)!==nr(t.staleTime,this.#t))&&this.#g();const r=this.#v();o&&(this.#t!==n||at(this.options.enabled,this.#t)!==at(t.enabled,this.#t)||r!==this.#u)&&this.#y(r)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return CR(this,n)&&(this.#o=n,this.#s=this.options,this.#n=this.#t.state),n}getCurrentResult(){return this.#o}trackResult(e,t){return new Proxy(e,{get:(n,o)=>(this.trackProp(o),t?.(o),o==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#a.status==="pending"&&this.#a.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,o))})}trackProp(e){this.#m.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#d({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#o))}#d(e){this.#x();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Je)),t}#g(){this.#_();const e=nr(this.options.staleTime,this.#t);if($r||this.#o.isStale||!wu(e))return;const n=Jx(this.#o.dataUpdatedAt,e)+1;this.#l=gr.setTimeout(()=>{this.#o.isStale||this.updateResult()},n)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#y(e){this.#w(),this.#u=e,!($r||at(this.options.enabled,this.#t)===!1||!wu(this.#u)||this.#u===0)&&(this.#c=gr.setInterval(()=>{(this.options.refetchIntervalInBackground||Fc.isFocused())&&this.#d()},this.#u))}#b(){this.#g(),this.#y(this.#v())}#_(){this.#l&&(gr.clearTimeout(this.#l),this.#l=void 0)}#w(){this.#c&&(gr.clearInterval(this.#c),this.#c=void 0)}createResult(e,t){const n=this.#t,o=this.options,r=this.#o,i=this.#n,a=this.#s,l=e!==n?e.state:this.#r,{state:u}=e;let c={...u},d=!1,f;if(t._optimisticResults){const O=this.hasListeners(),z=!O&&_f(e,t),F=O&&wf(e,n,t,o);(z||F)&&(c={...c,...Yx(u.data,e.options)}),t._optimisticResults==="isRestoring"&&(c.fetchStatus="idle")}let{error:p,errorUpdatedAt:g,status:h}=c;f=c.data;let b=!1;if(t.placeholderData!==void 0&&f===void 0&&h==="pending"){let O;r?.isPlaceholderData&&t.placeholderData===a?.placeholderData?(O=r.data,b=!0):O=typeof t.placeholderData=="function"?t.placeholderData(this.#f?.state.data,this.#f):t.placeholderData,O!==void 0&&(h="success",f=Iu(r?.data,O,t),d=!0)}if(t.select&&f!==void 0&&!b)if(r&&f===i?.data&&t.select===this.#h)f=this.#p;else try{this.#h=t.select,f=t.select(f),f=Iu(r?.data,f,t),this.#p=f,this.#i=null}catch(O){this.#i=O}this.#i&&(p=this.#i,f=this.#p,g=Date.now(),h="error");const y=c.fetchStatus==="fetching",x=h==="pending",$=h==="error",v=x&&y,k=f!==void 0,I={status:h,fetchStatus:c.fetchStatus,isPending:x,isSuccess:h==="success",isError:$,isInitialLoading:v,isLoading:v,data:f,dataUpdatedAt:c.dataUpdatedAt,error:p,errorUpdatedAt:g,failureCount:c.fetchFailureCount,failureReason:c.fetchFailureReason,errorUpdateCount:c.errorUpdateCount,isFetched:c.dataUpdateCount>0||c.errorUpdateCount>0,isFetchedAfterMount:c.dataUpdateCount>l.dataUpdateCount||c.errorUpdateCount>l.errorUpdateCount,isFetching:y,isRefetching:y&&!x,isLoadingError:$&&!k,isPaused:c.fetchStatus==="paused",isPlaceholderData:d,isRefetchError:$&&k,isStale:qc(e,t),refetch:this.refetch,promise:this.#a,isEnabled:at(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const O=te=>{I.status==="error"?te.reject(I.error):I.data!==void 0&&te.resolve(I.data)},z=()=>{const te=this.#a=I.promise=ku();O(te)},F=this.#a;switch(F.status){case"pending":e.queryHash===n.queryHash&&O(F);break;case"fulfilled":(I.status==="error"||I.data!==F.value)&&z();break;case"rejected":(I.status!=="error"||I.error!==F.reason)&&z();break}}return I}updateResult(){const e=this.#o,t=this.createResult(this.#t,this.options);if(this.#n=this.#t.state,this.#s=this.options,this.#n.data!==void 0&&(this.#f=this.#t),$u(t,e))return;this.#o=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:o}=this.options,r=typeof o=="function"?o():o;if(r==="all"||!r&&!this.#m.size)return!0;const i=new Set(r??this.#m);return this.options.throwOnError&&i.add("error"),Object.keys(this.#o).some(a=>{const s=a;return this.#o[s]!==e[s]&&i.has(s)})};this.#$({listeners:n()})}#x(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#r=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#b()}#$(e){ze.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#o)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function PR(e,t){return at(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function _f(e,t){return PR(e,t)||e.state.data!==void 0&&Tu(e,t,t.refetchOnMount)}function Tu(e,t,n){if(at(t.enabled,e)!==!1&&nr(t.staleTime,e)!=="static"){const o=typeof n=="function"?n(e):n;return o==="always"||o!==!1&&qc(e,t)}return!1}function wf(e,t,n,o){return(e!==t||at(o.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&qc(e,n)}function qc(e,t){return at(t.enabled,e)!==!1&&e.isStaleByTime(nr(t.staleTime,e))}function CR(e,t){return!$u(e.getCurrentResult(),t)}function xf(e){return{onFetch:(t,n)=>{const o=t.options,r=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],a=t.state.data?.pageParams||[];let s={pages:[],pageParams:[]},l=0;const u=async()=>{let c=!1;const d=g=>{Object.defineProperty(g,"signal",{enumerable:!0,get:()=>(t.signal.aborted?c=!0:t.signal.addEventListener("abort",()=>{c=!0}),t.signal)})},f=Wx(t.options,t.fetchOptions),p=async(g,h,b)=>{if(c)return Promise.reject();if(h==null&&g.pages.length)return Promise.resolve(g);const x=(()=>{const N={client:t.client,queryKey:t.queryKey,pageParam:h,direction:b?"backward":"forward",meta:t.options.meta};return d(N),N})(),$=await f(x),{maxPages:v}=t.options,k=b?xR:wR;return{pages:k(g.pages,$,v),pageParams:k(g.pageParams,h,v)}};if(r&&i.length){const g=r==="backward",h=g?jR:$f,b={pages:i,pageParams:a},y=h(o,b);s=await p(b,y,g)}else{const g=e??i.length;do{const h=l===0?a[0]??o.initialPageParam:$f(o,s);if(l>0&&h==null)break;s=await p(s,h),l++}while(l<g)}return s};t.options.persister?t.fetchFn=()=>t.options.persister?.(u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=u}}}function $f(e,{pages:t,pageParams:n}){const o=t.length-1;return t.length>0?e.getNextPageParam(t[o],t,n[o],n):void 0}function jR(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var AR=class extends Kx{#e;#t;#r;#o;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#r=e.mutationCache,this.#t=[],this.state=e.state||RR(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#r.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#r.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#r.remove(this))}continue(){return this.#o?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#n({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#o=Gx({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(i,a)=>{this.#n({type:"failed",failureCount:i,error:a})},onPause:()=>{this.#n({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#r.canRun(this)});const o=this.state.status==="pending",r=!this.#o.canStart();try{if(o)t();else{this.#n({type:"pending",variables:e,isPaused:r}),await this.#r.config.onMutate?.(e,this,n);const a=await this.options.onMutate?.(e,n);a!==this.state.context&&this.#n({type:"pending",context:a,variables:e,isPaused:r})}const i=await this.#o.start();return await this.#r.config.onSuccess?.(i,e,this.state.context,this,n),await this.options.onSuccess?.(i,e,this.state.context,n),await this.#r.config.onSettled?.(i,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(i,null,e,this.state.context,n),this.#n({type:"success",data:i}),i}catch(i){try{throw await this.#r.config.onError?.(i,e,this.state.context,this,n),await this.options.onError?.(i,e,this.state.context,n),await this.#r.config.onSettled?.(void 0,i,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(void 0,i,e,this.state.context,n),i}finally{this.#n({type:"error",error:i})}}finally{this.#r.runNext(this)}}#n(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),ze.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#r.notify({mutation:this,type:"updated",action:e})})}};function RR(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var zR=class extends Oo{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#r=0}#e;#t;#r;build(e,t,n){const o=new AR({client:e,mutationCache:this,mutationId:++this.#r,options:e.defaultMutationOptions(t),state:n});return this.add(o),o}add(e){this.#e.add(e);const t=Ho(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=Ho(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const o=n.indexOf(e);o!==-1&&n.splice(o,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Ho(e);if(typeof t=="string"){const o=this.#t.get(t)?.find(r=>r.state.status==="pending");return!o||o===e}else return!0}runNext(e){const t=Ho(e);return typeof t=="string"?this.#t.get(t)?.find(o=>o!==e&&o.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){ze.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>hf(t,n))}findAll(e={}){return this.getAll().filter(t=>hf(e,t))}notify(e){ze.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return ze.batch(()=>Promise.all(e.map(t=>t.continue().catch(Je))))}};function Ho(e){return e.options.scope?.id}var MR=class extends Oo{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){const o=t.queryKey,r=t.queryHash??Zc(o,t);let i=this.get(r);return i||(i=new OR({client:e,queryKey:o,queryHash:r,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(o)}),this.add(i)),i}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){ze.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>mf(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>mf(e,n)):t}notify(e){ze.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){ze.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){ze.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},DR=class{#e;#t;#r;#o;#n;#s;#a;#i;constructor(e={}){this.#e=e.queryCache||new MR,this.#t=e.mutationCache||new zR,this.#r=e.defaultOptions||{},this.#o=new Map,this.#n=new Map,this.#s=0}mount(){this.#s++,this.#s===1&&(this.#a=Fc.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=Pi.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#s--,this.#s===0&&(this.#a?.(),this.#a=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),o=n.state.data;return o===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(nr(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(o))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>{const o=n.data;return[t,o]})}setQueryData(e,t,n){const o=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(o.queryHash)?.state.data,a=yR(t,i);if(a!==void 0)return this.#e.build(this,o).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return ze.batch(()=>this.#e.findAll(e).map(({queryKey:o})=>[o,this.setQueryData(o,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;ze.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return ze.batch(()=>(n.findAll(e).forEach(o=>{o.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},o=ze.batch(()=>this.#e.findAll(e).map(r=>r.cancel(n)));return Promise.all(o).then(Je).catch(Je)}invalidateQueries(e,t={}){return ze.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},o=ze.batch(()=>this.#e.findAll(e).filter(r=>!r.isDisabled()&&!r.isStatic()).map(r=>{let i=r.fetch(void 0,n);return n.throwOnError||(i=i.catch(Je)),r.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(o).then(Je)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(nr(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Je).catch(Je)}fetchInfiniteQuery(e){return e.behavior=xf(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Je).catch(Je)}ensureInfiniteQueryData(e){return e.behavior=xf(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Pi.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#r}setDefaultOptions(e){this.#r=e}setQueryDefaults(e,t){this.#o.set(Hn(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#o.values()],n={};return t.forEach(o=>{Gn(e,o.queryKey)&&Object.assign(n,o.defaultOptions)}),n}setMutationDefaults(e,t){this.#n.set(Hn(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#n.values()],n={};return t.forEach(o=>{Gn(e,o.mutationKey)&&Object.assign(n,o.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#r.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Zc(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Ni&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#r.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},Qx=_.createContext(void 0),Xx=e=>{const t=_.useContext(Qx);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},UR=({client:e,children:t})=>(_.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),m.jsx(Qx.Provider,{value:e,children:t})),e$=_.createContext(!1),LR=()=>_.useContext(e$);e$.Provider;function ZR(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var FR=_.createContext(ZR()),qR=()=>_.useContext(FR),VR=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},BR=e=>{_.useEffect(()=>{e.clearReset()},[e])},JR=({result:e,errorResetBoundary:t,throwOnError:n,query:o,suspense:r})=>e.isError&&!t.isReset()&&!e.isFetching&&o&&(r&&e.data===void 0||$R(n,[e.error,o])),WR=e=>{if(e.suspense){const n=r=>r==="static"?r:Math.max(r??1e3,1e3),o=e.staleTime;e.staleTime=typeof o=="function"?(...r)=>n(o(...r)):n(o),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},HR=(e,t)=>e.isLoading&&e.isFetching&&!t,GR=(e,t)=>e?.suspense&&t.isPending,Sf=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function KR(e,t,n){if(process.env.NODE_ENV!=="production"&&(typeof e!="object"||Array.isArray(e)))throw new Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');const o=LR(),r=qR(),i=Xx(),a=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(a),process.env.NODE_ENV!=="production"&&(a.queryFn||console.error(`[${a.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`)),a._optimisticResults=o?"isRestoring":"optimistic",WR(a),VR(a,r),BR(r);const s=!i.getQueryCache().get(a.queryHash),[l]=_.useState(()=>new t(i,a)),u=l.getOptimisticResult(a),c=!o&&e.subscribed!==!1;if(_.useSyncExternalStore(_.useCallback(d=>{const f=c?l.subscribe(ze.batchCalls(d)):Je;return l.updateResult(),f},[l,c]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),_.useEffect(()=>{l.setOptions(a)},[a,l]),GR(a,u))throw Sf(a,l,r);if(JR({result:u,errorResetBoundary:r,throwOnError:a.throwOnError,query:i.getQueryCache().get(a.queryHash),suspense:a.suspense}))throw u.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(a,u),a.experimental_prefetchInRender&&!$r&&HR(u,o)&&(s?Sf(a,l,r):i.getQueryCache().get(a.queryHash)?.promise)?.catch(Je).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?u:l.trackResult(u)}function t$(e,t){return KR(e,NR)}const r$=({getSession:e,projectSlug:t})=>{const n=Xx(),o=["chatSession",t],r=n.getQueryState(o),i=r?.data!==void 0,a=r?.dataUpdatedAt??0,l=i&&Date.now()-a>1/0,u=!i||l,{data:c}=t$({queryKey:o,queryFn:()=>e({projectSlug:t}),enabled:u,staleTime:1/0,gcTime:1/0});return c??null};var YR=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:o="-"}={})=>{const r=()=>{const i=n.length,a=new Array(t);for(let s=0;s<t;s++)a[s]=n[Math.random()*i|0];return a.join("")};if(e==null)return r;if(n.includes(o))throw new Vi({argument:"separator",message:`The separator "${o}" must not be part of the alphabet "${n}".`});return()=>`${e}${o}${r()}`};YR();function n$(e=globalThis){var t,n,o;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(o=(n=e.process)==null?void 0:n.versions)!=null&&o.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function QR(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((n,o)=>{t[o.toLowerCase()]=n});else{Array.isArray(e)||(e=Object.entries(e));for(const[n,o]of e)o!=null&&(t[n.toLowerCase()]=o)}return t}function o$(e,...t){const n=new Headers(QR(e)),o=n.get("user-agent")||"";return n.set("user-agent",[o,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}var XR=Symbol.for("vercel.ai.validator");function ez(e){return{...e,type:"dynamic"}}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var tz=Symbol.for("vercel.ai.schema");function rz(e,{validate:t}={}){return{[tz]:!0,_type:void 0,[XR]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}let Vc;Vc=globalThis.crypto;async function nz(e){return(await Vc).getRandomValues(new Uint8Array(e))}async function oz(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";let n="";const o=await nz(e);for(let r=0;r<e;r++){const i=o[r]%t.length;n+=t[i]}return n}async function iz(e){return await oz(e)}async function az(e){const t=await(await Vc).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function sz(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await iz(e),n=await az(t);return{code_verifier:t,code_challenge:n}}var uz="AI_MCPClientError",i$=`vercel.ai.error.${uz}`,lz=Symbol.for(i$),If,kf,se=class extends(kf=Y,If=lz,kf){constructor({name:e="MCPClientError",message:t,cause:n,data:o,code:r}){super({name:e,message:t,cause:n}),this[If]=!0,this.data=o,this.code=r}static isInstance(e){return Y.hasMarker(e,i$)}},cn="2025-06-18",cz=[cn,"2025-03-26","2024-11-05"],dz=er({name:w(),version:w()}),Ja=er({_meta:ee(E({}).loose())}),Vt=Ja,a$=E({method:w(),params:ee(Ja)}),s$=E({applyDefaults:ee(pe())}).loose(),pz=er({experimental:ee(E({}).loose()),logging:ee(E({}).loose()),prompts:ee(er({listChanged:ee(pe())})),resources:ee(er({subscribe:ee(pe()),listChanged:ee(pe())})),tools:ee(er({listChanged:ee(pe())})),elicitation:ee(s$)});E({elicitation:ee(s$)}).loose();var fz=Vt.extend({protocolVersion:w(),capabilities:pz,serverInfo:dz,instructions:ee(w())}),Bc=Vt.extend({nextCursor:ee(w())}),mz=E({name:w(),description:ee(w()),inputSchema:E({type:C("object"),properties:ee(E({}).loose())}).loose()}).loose(),hz=Bc.extend({tools:R(mz)}),u$=E({type:C("text"),text:w()}).loose(),l$=E({type:C("image"),data:Ea(),mimeType:w()}).loose(),gz=E({uri:w(),name:w(),title:ee(w()),description:ee(w()),mimeType:ee(w()),size:ee(V())}).loose(),vz=Bc.extend({resources:R(gz)}),c$=E({uri:w(),name:ee(w()),title:ee(w()),mimeType:ee(w())}).loose(),d$=c$.extend({text:w()}),p$=c$.extend({blob:Ea()}),f$=E({type:C("resource"),resource:G([d$,p$])}).loose(),yz=Vt.extend({content:R(G([u$,l$,f$])),isError:pe().default(!1).optional()}).or(Vt.extend({toolResult:$e()})),bz=E({uriTemplate:w(),name:w(),title:ee(w()),description:ee(w()),mimeType:ee(w())}).loose(),_z=Vt.extend({resourceTemplates:R(bz)}),wz=Vt.extend({contents:R(G([d$,p$]))}),xz=E({name:w(),description:ee(w()),required:ee(pe())}).loose(),$z=E({name:w(),title:ee(w()),description:ee(w()),arguments:ee(R(xz))}).loose(),Sz=Bc.extend({prompts:R($z)}),Iz=E({role:G([C("user"),C("assistant")]),content:G([u$,l$,f$])}).loose(),kz=Vt.extend({description:ee(w()),messages:R(Iz)}),Ez=Ja.extend({message:w(),requestedSchema:$e()}),Ef=a$.extend({method:C("elicitation/create"),params:Ez}),Tz=Vt.extend({action:G([C("accept"),C("decline"),C("cancel")]),content:ee(Xe(w(),$e()))}),Wa="2.0",Oz=E({jsonrpc:C(Wa),id:G([w(),V().int()])}).merge(a$).strict(),Nz=E({jsonrpc:C(Wa),id:G([w(),V().int()]),result:Vt}).strict(),Pz=E({jsonrpc:C(Wa),id:G([w(),V().int()]),error:E({code:V().int(),message:w(),data:ee($e())})}).strict(),Cz=E({jsonrpc:C(Wa)}).merge(E({method:w(),params:ee(Ja)})).strict(),Tn=G([Oz,Cz,Nz,Pz]),m$=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",h$=E({access_token:w(),id_token:w().optional(),token_type:w(),expires_in:V().optional(),scope:w().optional(),refresh_token:w().optional()}).strip(),He=w().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:v_.custom,message:"URL must be parseable",fatal:!0}),Uu}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),jz=E({resource:w().url(),authorization_servers:R(He).optional(),jwks_uri:w().url().optional(),scopes_supported:R(w()).optional(),bearer_methods_supported:R(w()).optional(),resource_signing_alg_values_supported:R(w()).optional(),resource_name:w().optional(),resource_documentation:w().optional(),resource_policy_uri:w().url().optional(),resource_tos_uri:w().url().optional(),tls_client_certificate_bound_access_tokens:pe().optional(),authorization_details_types_supported:R(w()).optional(),dpop_signing_alg_values_supported:R(w()).optional(),dpop_bound_access_tokens_required:pe().optional()}).passthrough(),g$=E({issuer:w(),authorization_endpoint:He,token_endpoint:He,registration_endpoint:He.optional(),scopes_supported:R(w()).optional(),response_types_supported:R(w()),grant_types_supported:R(w()).optional(),code_challenge_methods_supported:R(w()),token_endpoint_auth_methods_supported:R(w()).optional(),token_endpoint_auth_signing_alg_values_supported:R(w()).optional()}).passthrough(),Az=E({issuer:w(),authorization_endpoint:He,token_endpoint:He,userinfo_endpoint:He.optional(),jwks_uri:He,registration_endpoint:He.optional(),scopes_supported:R(w()).optional(),response_types_supported:R(w()),grant_types_supported:R(w()).optional(),subject_types_supported:R(w()),id_token_signing_alg_values_supported:R(w()),claims_supported:R(w()).optional(),token_endpoint_auth_methods_supported:R(w()).optional()}).passthrough(),Rz=Az.merge(g$.pick({code_challenge_methods_supported:!0})),zz=E({client_id:w(),client_secret:w().optional(),client_id_issued_at:V().optional(),client_secret_expires_at:V().optional()}).strip(),Mz=E({redirect_uris:R(He),token_endpoint_auth_method:w().optional(),grant_types:R(w()).optional(),response_types:R(w()).optional(),client_name:w().optional(),client_uri:He.optional(),logo_uri:He.optional(),scope:w().optional(),contacts:R(w()).optional(),tos_uri:He.optional(),policy_uri:w().optional(),jwks_uri:He.optional(),jwks:Pe().optional(),software_id:w().optional(),software_version:w().optional(),software_statement:w().optional()}).strip(),Dz=E({error:w(),error_description:w().optional(),error_uri:w().optional()}),Uz=Mz.merge(zz),Lz="AI_MCPClientOAuthError",v$=`vercel.ai.error.${Lz}`,Zz=Symbol.for(v$),Tf,Of,No=class extends(Of=Y,Tf=Zz,Of){constructor({name:e="MCPClientOAuthError",message:t,cause:n}){super({name:e,message:t,cause:n}),this[Tf]=!0}static isInstance(e){return Y.hasMarker(e,v$)}},rn=class extends No{};rn.errorCode="server_error";var Ci=class extends No{};Ci.errorCode="invalid_client";var ji=class extends No{};ji.errorCode="invalid_grant";var Ai=class extends No{};Ai.errorCode="unauthorized_client";var Fz={[rn.errorCode]:rn,[Ci.errorCode]:Ci,[ji.errorCode]:ji,[Ai.errorCode]:Ai};function qz(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function Vz({requestedResource:e,configuredResource:t}){const n=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.href);if(n.origin!==o.origin||n.pathname.length<o.pathname.length)return!1;const r=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",i=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return r.startsWith(i)}var Ri=class extends Error{constructor(e="Unauthorized"){super(e),this.name="UnauthorizedError"}};function zi(e){var t;const n=(t=e.headers.get("www-authenticate"))!=null?t:e.headers.get("WWW-Authenticate");if(!n)return;const[o,r]=n.split(" ");if(o.toLowerCase()!=="bearer"||!r)return;const i=/resource_metadata="([^"]*)"/,a=n.match(i);if(a)try{return new URL(a[1])}catch{return}}function Bz(e,t="",n={}){return t.endsWith("/")&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Jc(e,t,n=fetch){try{return await n(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?Jc(e,void 0,n):void 0;throw o}}async function Nf(e,t,n=fetch){return await Jc(e,{"MCP-Protocol-Version":t},n)}function Jz(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function Wz(e,t,n,o){var r,i;const a=new URL(e),s=(r=o?.protocolVersion)!=null?r:cn;let l;if(o?.metadataUrl)l=new URL(o.metadataUrl);else{const c=Bz(t,a.pathname);l=new URL(c,(i=o?.metadataServerUrl)!=null?i:a),l.search=a.search}let u=await Nf(l,s,n);if(!o?.metadataUrl&&Jz(u,a.pathname)){const c=new URL(`/.well-known/${t}`,a);u=await Nf(c,s,n)}return u}async function Hz(e,t,n=fetch){const o=await Wz(e,"oauth-protected-resource",n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return jz.parse(await o.json())}function Gz(e){const t=typeof e=="string"?new URL(e):e,n=t.pathname!=="/",o=[];if(!n)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let r=t.pathname;return r.endsWith("/")&&(r=r.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${r}`,t.origin),type:"oauth"}),o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${r}`,t.origin),type:"oidc"}),o.push({url:new URL(`${r}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}async function Kz(e,{fetchFn:t=fetch,protocolVersion:n=cn}={}){var o;const r={"MCP-Protocol-Version":n},i=Gz(e);for(const{url:a,type:s}of i){const l=await Jc(a,r,t);if(l){if(!l.ok){if(l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}if(s==="oauth")return g$.parse(await l.json());{const u=Rz.parse(await l.json());if(!((o=u.code_challenge_methods_supported)!=null&&o.includes("S256")))throw new Error(`Incompatible OIDC provider at ${a}: does not support S256 code challenge method required by MCP specification`);return u}}}}async function Yz(e,{metadata:t,clientInformation:n,redirectUrl:o,scope:r,state:i,resource:a}){const s="code",l="S256";let u;if(t){if(u=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw new Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(l))throw new Error(`Incompatible auth server: does not support code challenge method ${l}`)}else u=new URL("/authorize",e);const c=await sz(),d=c.code_verifier,f=c.code_challenge;return u.searchParams.set("response_type",s),u.searchParams.set("client_id",n.client_id),u.searchParams.set("code_challenge",f),u.searchParams.set("code_challenge_method",l),u.searchParams.set("redirect_uri",String(o)),i&&u.searchParams.set("state",i),r&&u.searchParams.set("scope",r),r?.includes("offline_access")&&u.searchParams.append("prompt","consent"),a&&u.searchParams.set("resource",a.href),{authorizationUrl:u,codeVerifier:d}}function y$(e,t){const n=e.client_secret!==void 0;return t.length===0?n?"client_secret_post":"none":n&&t.includes("client_secret_basic")?"client_secret_basic":n&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":n?"client_secret_post":"none"}function b$(e,t,n,o){const{client_id:r,client_secret:i}=t;switch(e){case"client_secret_basic":Qz(r,i,n);return;case"client_secret_post":Xz(r,i,o);return;case"none":eM(r,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function Qz(e,t,n){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const o=btoa(`${e}:${t}`);n.set("Authorization",`Basic ${o}`)}function Xz(e,t,n){n.set("client_id",e),t&&n.set("client_secret",t)}function eM(e,t){t.set("client_id",e)}async function Wc(e){const t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{const o=Dz.parse(JSON.parse(n)),{error:r,error_description:i,error_uri:a}=o,s=Fz[r]||rn;return new s({message:i||"",cause:a})}catch(o){const r=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${n}`;return new rn({message:r})}}async function tM(e,{metadata:t,clientInformation:n,authorizationCode:o,codeVerifier:r,redirectUri:i,resource:a,addClientAuthentication:s,fetchFn:l}){var u;const c="authorization_code",d=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`);const f=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),p=new URLSearchParams({grant_type:c,code:o,code_verifier:r,redirect_uri:String(i)});if(s)s(f,p,e,t);else{const h=(u=t?.token_endpoint_auth_methods_supported)!=null?u:[],b=y$(n,h);b$(b,n,f,p)}a&&p.set("resource",a.href);const g=await(l??fetch)(d,{method:"POST",headers:f,body:p});if(!g.ok)throw await Wc(g);return h$.parse(await g.json())}async function rM(e,{metadata:t,clientInformation:n,refreshToken:o,resource:r,addClientAuthentication:i,fetchFn:a}){var s;const l="refresh_token";let u;if(t){if(u=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`)}else u=new URL("/token",e);const c=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),d=new URLSearchParams({grant_type:l,refresh_token:o});if(i)i(c,d,e,t);else{const p=(s=t?.token_endpoint_auth_methods_supported)!=null?s:[],g=y$(n,p);b$(g,n,c,d)}r&&d.set("resource",r.href);const f=await(a??fetch)(u,{method:"POST",headers:c,body:d});if(!f.ok)throw await Wc(f);return h$.parse({refresh_token:o,...await f.json()})}async function nM(e,{metadata:t,clientMetadata:n,fetchFn:o}){let r;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");r=new URL(t.registration_endpoint)}else r=new URL("/register",e);const i=await(o??fetch)(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!i.ok)throw await Wc(i);return Uz.parse(await i.json())}async function Mi(e,t){var n,o;try{return await Ms(e,t)}catch(r){if(r instanceof Ci||r instanceof Ai)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"all")),await Ms(e,t);if(r instanceof ji)return await((o=e.invalidateCredentials)==null?void 0:o.call(e,"tokens")),await Ms(e,t);throw r}}async function oM(e,t,n){const o=qz(e);if(t.validateResourceURL)return await t.validateResourceURL(o,n?.resource);if(n){if(!Vz({requestedResource:o,configuredResource:n.resource}))throw new Error(`Protected resource ${n.resource} does not match expected ${o} (or origin)`);return new URL(n.resource)}}async function Ms(e,{serverUrl:t,authorizationCode:n,scope:o,resourceMetadataUrl:r,fetchFn:i}){let a,s;try{a=await Hz(t,{resourceMetadataUrl:r},i),a.authorization_servers&&a.authorization_servers.length>0&&(s=a.authorization_servers[0])}catch{}s||(s=t);const l=await oM(t,e,a),u=await Kz(s,{fetchFn:i});let c=await Promise.resolve(e.clientInformation());if(!c){if(n!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const h=await nM(s,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:i});await e.saveClientInformation(h),c=h}if(n!==void 0){const h=await e.codeVerifier(),b=await tM(s,{metadata:u,clientInformation:c,authorizationCode:n,codeVerifier:h,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(b),"AUTHORIZED"}const d=await e.tokens();if(d?.refresh_token)try{const h=await rM(s,{metadata:u,clientInformation:c,refreshToken:d.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(h),"AUTHORIZED"}catch(h){if(!(!(h instanceof No)||h instanceof rn))throw h}const f=e.state?await e.state():void 0,{authorizationUrl:p,codeVerifier:g}=await Yz(s,{metadata:u,clientInformation:c,state:f,redirectUrl:e.redirectUrl,scope:o||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(g),await e.redirectToAuthorization(p),"REDIRECT"}var iM=class{constructor({url:e,headers:t,authProvider:n}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=n}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":cn};if(this.authProvider){const n=await this.authProvider.tokens();n?.access_token&&(t.Authorization=`Bearer ${n.access_token}`)}return o$(t,`ai-sdk/${m$}`,n$())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;const n=async(o=!1)=>{var r,i,a,s,l;try{const u=await this.commonHeaders({Accept:"text/event-stream"}),c=await fetch(this.url.href,{headers:u,signal:(r=this.abortController)==null?void 0:r.signal});if(c.status===401&&this.authProvider&&!o){this.resourceMetadataUrl=zi(c);try{if(await Mi(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const h=new Ri;return(i=this.onerror)==null||i.call(this,h),t(h)}}catch(g){return(a=this.onerror)==null||a.call(this,g),t(g)}return n(!0)}if(!c.ok||!c.body){let g=`MCP SSE Transport Error: ${c.status} ${c.statusText}`;c.status===405&&(g+=". This server does not support SSE transport. Try using `http` transport instead");const h=new se({message:g});return(s=this.onerror)==null||s.call(this,h),t(h)}const f=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new Pn).getReader(),p=async()=>{var g,h,b;try{for(;;){const{done:y,value:x}=await f.read();if(y){if(this.connected)throw this.connected=!1,new se({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:$,data:v}=x;if($==="endpoint"){if(this.endpoint=new URL(v,this.url),this.endpoint.origin!==this.url.origin)throw new se({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if($==="message")try{const k=Tn.parse(JSON.parse(v));(g=this.onmessage)==null||g.call(this,k)}catch(k){const N=new se({message:"MCP SSE Transport Error: Failed to parse message",cause:k});(h=this.onerror)==null||h.call(this,N)}}}catch(y){if(y instanceof Error&&y.name==="AbortError")return;(b=this.onerror)==null||b.call(this,y),t(y)}};this.sseConnection={close:()=>f.cancel()},p()}catch(u){if(u instanceof Error&&u.name==="AbortError")return;(l=this.onerror)==null||l.call(this,u),t(u)}};n()})}async close(){var e,t,n;this.connected=!1,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new se({message:"MCP SSE Transport Error: Not connected"});const t=this.endpoint,n=async(o=!1)=>{var r,i,a,s,l;try{const c={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:(r=this.abortController)==null?void 0:r.signal},d=await fetch(t,c);if(d.status===401&&this.authProvider&&!o){this.resourceMetadataUrl=zi(d);try{if(await Mi(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const p=new Ri;(i=this.onerror)==null||i.call(this,p);return}}catch(f){(a=this.onerror)==null||a.call(this,f);return}return n(!0)}if(!d.ok){const f=await d.text().catch(()=>null),p=new se({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${d.status}): ${f}`});(s=this.onerror)==null||s.call(this,p);return}}catch(u){(l=this.onerror)==null||l.call(this,u);return}};await n()}},aM=class{constructor({url:e,headers:t,authProvider:n}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":cn};if(this.sessionId&&(t["mcp-session-id"]=this.sessionId),this.authProvider){const n=await this.authProvider.tokens();n?.access_token&&(t.Authorization=`Bearer ${n.access_token}`)}return o$(t,`ai-sdk/${m$}`,n$())}async start(){if(this.abortController)throw new se({message:"MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){const o=await this.commonHeaders({});await fetch(this.url,{method:"DELETE",headers:o,signal:this.abortController.signal}).catch(()=>{})}}catch{}(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){const t=async(n=!1)=>{var o,r,i,a,s,l,u;try{const d={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(e),signal:(o=this.abortController)==null?void 0:o.signal},f=await fetch(this.url,d),p=f.headers.get("mcp-session-id");if(p&&(this.sessionId=p),f.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=zi(f);try{if(await Mi(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new Ri}catch(b){throw(r=this.onerror)==null||r.call(this,b),b}return t(!0)}if(f.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!f.ok){const b=await f.text().catch(()=>null);let y=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${f.status}): ${b}`;f.status===404&&(y+=". This server does not support HTTP transport. Try using `sse` transport instead");const x=new se({message:y});throw(i=this.onerror)==null||i.call(this,x),x}const g=f.headers.get("content-type")||"";if(g.includes("application/json")){const b=await f.json(),y=Array.isArray(b)?b.map(x=>Tn.parse(x)):[Tn.parse(b)];for(const x of y)(a=this.onmessage)==null||a.call(this,x);return}if(g.includes("text/event-stream")){if(!f.body){const $=new se({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(s=this.onerror)==null||s.call(this,$),$}const y=f.body.pipeThrough(new TextDecoderStream).pipeThrough(new Pn).getReader();(async()=>{var $,v,k;try{for(;;){const{done:N,value:I}=await y.read();if(N)return;const{event:O,data:z}=I;if(O==="message")try{const F=Tn.parse(JSON.parse(z));($=this.onmessage)==null||$.call(this,F)}catch(F){const te=new se({message:"MCP HTTP Transport Error: Failed to parse message",cause:F});(v=this.onerror)==null||v.call(this,te)}}}catch(N){if(N instanceof Error&&N.name==="AbortError")return;(k=this.onerror)==null||k.call(this,N)}})();return}const h=new se({message:`MCP HTTP Transport Error: Unexpected content type: ${g}`});throw(l=this.onerror)==null||l.call(this,h),h}catch(c){throw(u=this.onerror)==null||u.call(this,c),c}};await t()}getNextReconnectionDelay(e){const{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:o}=this.reconnectionOptions;return Math.min(t*Math.pow(n,e),o)}scheduleInboundSseReconnection(){var e;const{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new se({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}const n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{var o;(o=this.abortController)!=null&&o.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},n)}async openInboundSse(e=!1,t){var n,o,r,i,a,s;try{const l=await this.commonHeaders({Accept:"text/event-stream"});t&&(l["last-event-id"]=t);const u=await fetch(this.url.href,{method:"GET",headers:l,signal:(n=this.abortController)==null?void 0:n.signal}),c=u.headers.get("mcp-session-id");if(c&&(this.sessionId=c),u.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=zi(u);try{if(await Mi(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const h=new Ri;(o=this.onerror)==null||o.call(this,h);return}}catch(g){(r=this.onerror)==null||r.call(this,g);return}return this.openInboundSse(!0,t)}if(u.status===405)return;if(!u.ok||!u.body){const g=new se({message:`MCP HTTP Transport Error: GET SSE failed: ${u.status} ${u.statusText}`});(i=this.onerror)==null||i.call(this,g);return}const f=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new Pn).getReader(),p=async()=>{var g,h,b,y;try{for(;;){const{done:x,value:$}=await f.read();if(x)return;const{event:v,data:k,id:N}=$;if(N&&(this.lastInboundEventId=N),v==="message")try{const I=Tn.parse(JSON.parse(k));(g=this.onmessage)==null||g.call(this,I)}catch(I){const O=new se({message:"MCP HTTP Transport Error: Failed to parse message",cause:I});(h=this.onerror)==null||h.call(this,O)}}}catch(x){if(x instanceof Error&&x.name==="AbortError")return;(b=this.onerror)==null||b.call(this,x),(y=this.abortController)!=null&&y.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>f.cancel()},this.inboundReconnectAttempts=0,p()}catch(l){if(l instanceof Error&&l.name==="AbortError")return;(a=this.onerror)==null||a.call(this,l),(s=this.abortController)!=null&&s.signal.aborted||this.scheduleInboundSseReconnection()}}};function sM(e){switch(e.type){case"sse":return new iM(e);case"http":return new aM(e);default:throw new se({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function uM(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var lM="1.0.0";async function cM(e){const t=new dM(e);return await t.init(),t}var dM=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:n=lM,onUncaughtError:o,capabilities:r}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=o,this.clientCapabilities=r??{},uM(e)?this.transport=e:this.transport=sM(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=i=>this.onError(i),this.transport.onmessage=i=>{if("method"in i){"id"in i?this.onRequestMessage(i):this.onError(new se({message:"Unsupported message type"}));return}this.onResponse(i)},this.clientInfo={name:t,version:n}}async init(){try{await this.transport.start(),this.isClosed=!1;const e=await this.request({request:{method:"initialize",params:{protocolVersion:cn,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:fz});if(e===void 0)throw new se({message:"Server sent invalid initialize result"});if(!cz.includes(e.protocolVersion))throw new se({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(e){throw await this.close(),e}}async close(){var e;this.isClosed||(await((e=this.transport)==null?void 0:e.close()),this.onClose())}assertCapability(e){switch(e){case"initialize":break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new se({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new se({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new se({message:"Server does not support prompts"});break;default:throw new se({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((o,r)=>{if(this.isClosed)return r(new se({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const i=n?.signal;i?.throwIfAborted();const a=this.requestMessageId++,s={...e,jsonrpc:"2.0",id:a},l=()=>{this.responseHandlers.delete(a)};this.responseHandlers.set(a,u=>{if(i?.aborted)return r(new se({message:"Request was aborted",cause:i.reason}));if(u instanceof Error)return r(u);try{const c=t.parse(u.result);o(c)}catch(c){const d=new se({message:"Failed to parse server response",cause:c});r(d)}}),this.transport.send(s).catch(u=>{l(),r(u)})})}async listTools({params:e,options:t}={}){try{return this.request({request:{method:"tools/list",params:e},resultSchema:hz,options:t})}catch(n){throw n}}async callTool({name:e,args:t,options:n}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:yz,options:{signal:n?.abortSignal}})}catch(o){throw o}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:"resources/list",params:e},resultSchema:vz,options:t})}catch(n){throw n}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:wz,options:t})}catch(n){throw n}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:_z,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:Sz,options:t})}catch(n){throw n}}async getPromptInternal({name:e,args:t,options:n}){try{return this.request({request:{method:"prompts/get",params:{name:e,arguments:t}},resultSchema:kz,options:n})}catch(o){throw o}}async notification(e){const t={...e,jsonrpc:"2.0"};await this.transport.send(t)}async tools({schemas:e="automatic"}={}){var t;const n={};try{const o=await this.listTools();for(const{name:r,description:i,inputSchema:a}of o.tools){if(e!=="automatic"&&!(r in e))continue;const s=this,l=async(c,d)=>{var f;return(f=d?.abortSignal)==null||f.throwIfAborted(),s.callTool({name:r,args:c,options:d})},u=e==="automatic"?ez({description:i,inputSchema:rz({...a,properties:(t=a.properties)!=null?t:{},additionalProperties:!1}),execute:l}):{description:i,inputSchema:e[r].inputSchema,execute:l};n[r]=u}return n}catch(o){throw o}}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}getPrompt({name:e,arguments:t,options:n}){return this.getPromptInternal({name:e,args:t,options:n})}onElicitationRequest(e,t){if(e!==Ef)throw new se({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method!=="elicitation/create"){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:"No elicitation handler registered on client"}});return}const t=Ef.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{const n=await this.elicitationRequestHandler(t.data),o=Tz.parse(n);await this.transport.send({jsonrpc:"2.0",id:e.id,result:o})}catch(n){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:n instanceof Error?n.message:"Failed to handle elicitation request"}}),this.onError(n)}}catch(t){this.onError(t)}}onClose(){if(this.isClosed)return;this.isClosed=!0;const e=new se({message:"Connection closed"});for(const t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){const t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new se({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n("result"in e?e:new se({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};function pM({getSession:e,projectSlug:t,mcp:n,environment:o}){const r=r$({getSession:e,projectSlug:t});return t$({queryKey:["mcpTools",t,n,r],queryFn:async()=>(T.assert(r,"No session found"),T.assert(n,"No MCP URL found"),await(await cM({name:"gram-elements-mcp-client",transport:{type:"http",url:n,headers:{...fM(o??{}),"Gram-Chat-Session":r}}})).tools()),enabled:!!r&&!!n,staleTime:1/0,gcTime:1/0})}const Pf="MCP-";function fM(e){return typeof e!="object"||e===null?{}:Object.entries(e).reduce((t,[n,o])=>{const r=n.replace(/_/g,"-"),i=r.startsWith(Pf)?r:`${Pf}${r}`;return t[i]=o,t},{})}function mM({children:e}){const[t,n]=D.useState(new Map),[o,r]=D.useState(new Set),i=D.useCallback((d,f,p)=>new Promise(g=>{const h={toolCallId:f,toolName:d,args:p,resolve:g};n(b=>{const y=new Map(b);return y.set(f,h),y})}),[]),a=D.useCallback(d=>{r(f=>{const p=new Set(f);return p.add(d),p})},[]),s=D.useCallback(d=>{n(f=>{const p=f.get(d);if(p){p.resolve(!0);const g=new Map(f);return g.delete(d),g}return f})},[]),l=D.useCallback(d=>{n(f=>{const p=f.get(d);if(p){p.resolve(!1);const g=new Map(f);return g.delete(d),g}return f})},[]),u=D.useCallback(d=>o.has(d),[o]),c=D.useCallback(d=>t.get(d),[t]);return m.jsx(T.ToolApprovalContext.Provider,{value:{pendingApprovals:t,approvedTools:o,requestApproval:i,whitelistTool:a,confirmPendingApproval:s,rejectPendingApproval:l,isToolApproved:u,getPendingApproval:c},children:e})}const _$=()=>{const e=D.useContext(T.ToolApprovalContext);if(!e)throw new Error("useToolApproval must be used within a ToolApprovalProvider");return e},hM="You are a helpful assistant that can answer questions and help with tasks.";function gM(e,t){return`
|
|
89
|
+
${hM}
|
|
90
90
|
|
|
91
91
|
User-provided System Prompt:
|
|
92
92
|
${e??"None provided"}
|
|
93
93
|
|
|
94
94
|
Utilities:
|
|
95
95
|
${t.map(n=>`- ${n.language}: ${n.prompt}`).join(`
|
|
96
|
-
`)}`}async function yM(e){return(await(await fetch("/chat/session",{method:"POST",headers:{"Gram-Project":e.projectSlug}})).json()).client_token}const bM=({children:e,config:t,getSession:n=yM})=>{const o=r$({getSession:n,projectSlug:t.projectSlug}),r=_$(),[i,a]=D.useState(t.model?.defaultModel??Mu[0]),[s,l]=D.useState(t.modal?.defaultExpanded??!1),[u,c]=D.useState(t.modal?.defaultOpen),d=t.plugins??T.recommended,f=vM(t.systemPrompt,d),{data:p,isLoading:g}=pM({getSession:n,projectSlug:t.projectSlug,mcp:t.mcp,environment:t.environment??{}}),h=!p||g,b=D.useRef({requestApproval:r.requestApproval,isToolApproved:r.isToolApproved,whitelistTool:r.whitelistTool});b.current={requestApproval:r.requestApproval,isToolApproved:r.isToolApproved,whitelistTool:r.whitelistTool};const y=D.useCallback(()=>({requestApproval:(...v)=>b.current.requestApproval(...v),isToolApproved:(...v)=>b.current.isToolApproved(...v),whitelistTool:(...v)=>b.current.whitelistTool(...v)}),[]);D.useEffect(()=>(t.tools?.toolsRequiringApproval?.length&&dR(y(),t.tools.toolsRequiringApproval),()=>{pR()}),[t.tools?.toolsRequiringApproval,y]);const x=D.useMemo(()=>({sendMessages:async({messages:v,abortSignal:k})=>{const N=!!t.languageModel;if(!o)throw new Error("No session found");if(g||!p)throw new Error("MCP tools are still being discovered");const I=$.thread.getModelContext(),O=lR(cR(I?.tools??{})),z=N?null:Pw({baseURL:hM,apiKey:"unused, but must be set",headers:{"Gram-Project":t.projectSlug,"Gram-Chat-Session":o}});t.languageModel&&console.log("Using custom language model",t.languageModel);const F={...p,...IP(O)},te=mR(F,t.tools?.toolsRequiringApproval,y()),ce=t.languageModel?t.languageModel:z.chat(i);try{return eR({system:f,model:ce,messages:nR(v),tools:te,stopWhen:Lx(10),experimental_transform:uR({delayInMs:15}),abortSignal:k,onError:({error:q})=>{console.error("Stream error in onError callback:",q)}}).toUIMessageStream()}catch(B){throw console.error("Error creating stream:",B),B}},reconnectToStream:async()=>{throw new Error("Stream reconnection not supported")}}),[t,t.languageModel,i,f,o,p,g,y]),$=SP({transport:x});return m.jsx(L.AssistantRuntimeProvider,{runtime:$,children:m.jsxs(T.ElementsContext.Provider,{value:{config:t,setModel:a,model:i,isExpanded:s,setIsExpanded:l,isOpen:u??!1,setIsOpen:c,plugins:d,isLoadingMCPTools:h},children:[e,m.jsx($0,{tools:t.tools?.frontendTools??{}})]})})},_M=e=>{const t=new DR;return m.jsx(UR,{client:t,children:m.jsx(mM,{children:m.jsx(bM,{...e})})})};function Cf(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Hc(...e){return t=>{let n=!1;const o=e.map(r=>{const i=Cf(r,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let r=0;r<o.length;r++){const i=o[r];typeof i=="function"?i():Cf(e[r],null)}}}}function Ge(...e){return _.useCallback(Hc(...e),e)}var wM=Symbol.for("react.lazy"),Di=_[" use ".trim().toString()];function xM(e){return typeof e=="object"&&e!==null&&"then"in e}function w$(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===wM&&"_payload"in e&&xM(e._payload)}function x$(e){const t=SM(e),n=_.forwardRef((o,r)=>{let{children:i,...a}=o;w$(i)&&typeof Di=="function"&&(i=Di(i._payload));const s=_.Children.toArray(i),l=s.find(EM);if(l){const u=l.props.children,c=s.map(d=>d===l?_.Children.count(u)>1?_.Children.only(null):_.isValidElement(u)?u.props.children:null:d);return m.jsx(t,{...a,ref:r,children:_.isValidElement(u)?_.cloneElement(u,void 0,c):null})}return m.jsx(t,{...a,ref:r,children:i})});return n.displayName=`${e}.Slot`,n}var $M=x$("Slot");function SM(e){const t=_.forwardRef((n,o)=>{let{children:r,...i}=n;if(w$(r)&&typeof Di=="function"&&(r=Di(r._payload)),_.isValidElement(r)){const a=OM(r),s=TM(i,r.props);return r.type!==_.Fragment&&(s.ref=o?Hc(o,a):a),_.cloneElement(r,s)}return _.Children.count(r)>1?_.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var $$=Symbol("radix.slottable");function IM(e){const t=({children:n})=>m.jsx(m.Fragment,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=$$,t}var kM=IM("Slottable");function EM(e){return _.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===$$}function TM(e,t){const n={...t};for(const o in t){const r=e[o],i=t[o];/^on[A-Z]/.test(o)?r&&i?n[o]=(...s)=>{const l=i(...s);return r(...s),l}:r&&(n[o]=r):o==="style"?n[o]={...r,...i}:o==="className"&&(n[o]=[r,i].filter(Boolean).join(" "))}return{...e,...n}}function OM(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}const jf=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,Af=T.clsx,S$=(e,t)=>n=>{var o;if(t?.variants==null)return Af(e,n?.class,n?.className);const{variants:r,defaultVariants:i}=t,a=Object.keys(r).map(u=>{const c=n?.[u],d=i?.[u];if(c===null)return null;const f=jf(c)||jf(d);return r[u][f]}),s=n&&Object.entries(n).reduce((u,c)=>{let[d,f]=c;return f===void 0||(u[d]=f),u},{}),l=t==null||(o=t.compoundVariants)===null||o===void 0?void 0:o.reduce((u,c)=>{let{class:d,className:f,...p}=c;return Object.entries(p).every(g=>{let[h,b]=g;return Array.isArray(b)?b.includes({...i,...s}[h]):{...i,...s}[h]===b})?[...u,d,f]:u},[]);return Af(e,a,l,n?.class,n?.className)},NM=S$("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}}),$t=_.forwardRef(({className:e,variant:t,size:n,asChild:o=!1,...r},i)=>{const a=o?$M:"button";return m.jsx(a,{"data-slot":"button",className:T.cn(NM({variant:t,size:n,className:e})),ref:i,...r})});$t.displayName="Button";function Oe(e,t,{checkForDefaultPrevented:n=!0}={}){return function(r){if(e?.(r),n===!1||!r.defaultPrevented)return t?.(r)}}function PM(e,t){const n=_.createContext(t),o=i=>{const{children:a,...s}=i,l=_.useMemo(()=>s,Object.values(s));return m.jsx(n.Provider,{value:l,children:a})};o.displayName=e+"Provider";function r(i){const a=_.useContext(n);if(a)return a;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return[o,r]}function Po(e,t=[]){let n=[];function o(i,a){const s=_.createContext(a),l=n.length;n=[...n,a];const u=d=>{const{scope:f,children:p,...g}=d,h=f?.[e]?.[l]||s,b=_.useMemo(()=>g,Object.values(g));return m.jsx(h.Provider,{value:b,children:p})};u.displayName=i+"Provider";function c(d,f){const p=f?.[e]?.[l]||s,g=_.useContext(p);if(g)return g;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[u,c]}const r=()=>{const i=n.map(a=>_.createContext(a));return function(s){const l=s?.[e]||i;return _.useMemo(()=>({[`__scope${e}`]:{...s,[e]:l}}),[s,l])}};return r.scopeName=e,[o,CM(r,...t)]}function CM(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const o=e.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(i){const a=o.reduce((s,{useScope:l,scopeName:u})=>{const d=l(i)[`__scope${u}`];return{...s,...d}},{});return _.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return n.scopeName=t.scopeName,n}function Gc(e){const t=jM(e),n=_.forwardRef((o,r)=>{const{children:i,...a}=o,s=_.Children.toArray(i),l=s.find(RM);if(l){const u=l.props.children,c=s.map(d=>d===l?_.Children.count(u)>1?_.Children.only(null):_.isValidElement(u)?u.props.children:null:d);return m.jsx(t,{...a,ref:r,children:_.isValidElement(u)?_.cloneElement(u,void 0,c):null})}return m.jsx(t,{...a,ref:r,children:i})});return n.displayName=`${e}.Slot`,n}function jM(e){const t=_.forwardRef((n,o)=>{const{children:r,...i}=n;if(_.isValidElement(r)){const a=MM(r),s=zM(i,r.props);return r.type!==_.Fragment&&(s.ref=o?Hc(o,a):a),_.cloneElement(r,s)}return _.Children.count(r)>1?_.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var I$=Symbol("radix.slottable");function AM(e){const t=({children:n})=>m.jsx(m.Fragment,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=I$,t}function RM(e){return _.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===I$}function zM(e,t){const n={...t};for(const o in t){const r=e[o],i=t[o];/^on[A-Z]/.test(o)?r&&i?n[o]=(...s)=>{const l=i(...s);return r(...s),l}:r&&(n[o]=r):o==="style"?n[o]={...r,...i}:o==="className"&&(n[o]=[r,i].filter(Boolean).join(" "))}return{...e,...n}}function MM(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var DM=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Ce=DM.reduce((e,t)=>{const n=Gc(`Primitive.${t}`),o=_.forwardRef((r,i)=>{const{asChild:a,...s}=r,l=a?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),m.jsx(l,{...s,ref:i})});return o.displayName=`Primitive.${t}`,{...e,[t]:o}},{});function UM(e,t){e&&sm.flushSync(()=>e.dispatchEvent(t))}function Sr(e){const t=_.useRef(e);return _.useEffect(()=>{t.current=e}),_.useMemo(()=>(...n)=>t.current?.(...n),[])}function LM(e,t=globalThis?.document){const n=Sr(e);_.useEffect(()=>{const o=r=>{r.key==="Escape"&&n(r)};return t.addEventListener("keydown",o,{capture:!0}),()=>t.removeEventListener("keydown",o,{capture:!0})},[n,t])}var ZM="DismissableLayer",Ou="dismissableLayer.update",FM="dismissableLayer.pointerDownOutside",qM="dismissableLayer.focusOutside",Rf,k$=_.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Ha=_.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:o,onPointerDownOutside:r,onFocusOutside:i,onInteractOutside:a,onDismiss:s,...l}=e,u=_.useContext(k$),[c,d]=_.useState(null),f=c?.ownerDocument??globalThis?.document,[,p]=_.useState({}),g=Ge(t,I=>d(I)),h=Array.from(u.layers),[b]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),y=h.indexOf(b),x=c?h.indexOf(c):-1,$=u.layersWithOutsidePointerEventsDisabled.size>0,v=x>=y,k=JM(I=>{const O=I.target,z=[...u.branches].some(F=>F.contains(O));!v||z||(r?.(I),a?.(I),I.defaultPrevented||s?.())},f),N=WM(I=>{const O=I.target;[...u.branches].some(F=>F.contains(O))||(i?.(I),a?.(I),I.defaultPrevented||s?.())},f);return LM(I=>{x===u.layers.size-1&&(o?.(I),!I.defaultPrevented&&s&&(I.preventDefault(),s()))},f),_.useEffect(()=>{if(c)return n&&(u.layersWithOutsidePointerEventsDisabled.size===0&&(Rf=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(c)),u.layers.add(c),zf(),()=>{n&&u.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=Rf)}},[c,f,n,u]),_.useEffect(()=>()=>{c&&(u.layers.delete(c),u.layersWithOutsidePointerEventsDisabled.delete(c),zf())},[c,u]),_.useEffect(()=>{const I=()=>p({});return document.addEventListener(Ou,I),()=>document.removeEventListener(Ou,I)},[]),m.jsx(Ce.div,{...l,ref:g,style:{pointerEvents:$?v?"auto":"none":void 0,...e.style},onFocusCapture:Oe(e.onFocusCapture,N.onFocusCapture),onBlurCapture:Oe(e.onBlurCapture,N.onBlurCapture),onPointerDownCapture:Oe(e.onPointerDownCapture,k.onPointerDownCapture)})});Ha.displayName=ZM;var VM="DismissableLayerBranch",BM=_.forwardRef((e,t)=>{const n=_.useContext(k$),o=_.useRef(null),r=Ge(t,o);return _.useEffect(()=>{const i=o.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),m.jsx(Ce.div,{...e,ref:r})});BM.displayName=VM;function JM(e,t=globalThis?.document){const n=Sr(e),o=_.useRef(!1),r=_.useRef(()=>{});return _.useEffect(()=>{const i=s=>{if(s.target&&!o.current){let l=function(){E$(FM,n,u,{discrete:!0})};const u={originalEvent:s};s.pointerType==="touch"?(t.removeEventListener("click",r.current),r.current=l,t.addEventListener("click",r.current,{once:!0})):l()}else t.removeEventListener("click",r.current);o.current=!1},a=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(a),t.removeEventListener("pointerdown",i),t.removeEventListener("click",r.current)}},[t,n]),{onPointerDownCapture:()=>o.current=!0}}function WM(e,t=globalThis?.document){const n=Sr(e),o=_.useRef(!1);return _.useEffect(()=>{const r=i=>{i.target&&!o.current&&E$(qM,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",r),()=>t.removeEventListener("focusin",r)},[t,n]),{onFocusCapture:()=>o.current=!0,onBlurCapture:()=>o.current=!1}}function zf(){const e=new CustomEvent(Ou);document.dispatchEvent(e)}function E$(e,t,n,{discrete:o}){const r=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&r.addEventListener(e,t,{once:!0}),o?UM(r,i):r.dispatchEvent(i)}var lt=globalThis?.document?_.useLayoutEffect:()=>{},HM=_[" useId ".trim().toString()]||(()=>{}),GM=0;function qr(e){const[t,n]=_.useState(HM());return lt(()=>{n(o=>o??String(GM++))},[e]),t?`radix-${t}`:""}const KM=["top","right","bottom","left"],ur=Math.min,Ye=Math.max,Ui=Math.round,Go=Math.floor,At=e=>({x:e,y:e}),YM={left:"right",right:"left",bottom:"top",top:"bottom"},QM={start:"end",end:"start"};function Nu(e,t,n){return Ye(e,ur(t,n))}function Bt(e,t){return typeof e=="function"?e(t):e}function Jt(e){return e.split("-")[0]}function dn(e){return e.split("-")[1]}function Kc(e){return e==="x"?"y":"x"}function Yc(e){return e==="y"?"height":"width"}const XM=new Set(["top","bottom"]);function jt(e){return XM.has(Jt(e))?"y":"x"}function Qc(e){return Kc(jt(e))}function e4(e,t,n){n===void 0&&(n=!1);const o=dn(e),r=Qc(e),i=Yc(r);let a=r==="x"?o===(n?"end":"start")?"right":"left":o==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(a=Li(a)),[a,Li(a)]}function t4(e){const t=Li(e);return[Pu(e),t,Pu(t)]}function Pu(e){return e.replace(/start|end/g,t=>QM[t])}const Mf=["left","right"],Df=["right","left"],r4=["top","bottom"],n4=["bottom","top"];function o4(e,t,n){switch(e){case"top":case"bottom":return n?t?Df:Mf:t?Mf:Df;case"left":case"right":return t?r4:n4;default:return[]}}function i4(e,t,n,o){const r=dn(e);let i=o4(Jt(e),n==="start",o);return r&&(i=i.map(a=>a+"-"+r),t&&(i=i.concat(i.map(Pu)))),i}function Li(e){return e.replace(/left|right|bottom|top/g,t=>YM[t])}function a4(e){return{top:0,right:0,bottom:0,left:0,...e}}function T$(e){return typeof e!="number"?a4(e):{top:e,right:e,bottom:e,left:e}}function Zi(e){const{x:t,y:n,width:o,height:r}=e;return{width:o,height:r,top:n,left:t,right:t+o,bottom:n+r,x:t,y:n}}function Uf(e,t,n){let{reference:o,floating:r}=e;const i=jt(t),a=Qc(t),s=Yc(a),l=Jt(t),u=i==="y",c=o.x+o.width/2-r.width/2,d=o.y+o.height/2-r.height/2,f=o[s]/2-r[s]/2;let p;switch(l){case"top":p={x:c,y:o.y-r.height};break;case"bottom":p={x:c,y:o.y+o.height};break;case"right":p={x:o.x+o.width,y:d};break;case"left":p={x:o.x-r.width,y:d};break;default:p={x:o.x,y:o.y}}switch(dn(t)){case"start":p[a]-=f*(n&&u?-1:1);break;case"end":p[a]+=f*(n&&u?-1:1);break}return p}const s4=async(e,t,n)=>{const{placement:o="bottom",strategy:r="absolute",middleware:i=[],platform:a}=n,s=i.filter(Boolean),l=await(a.isRTL==null?void 0:a.isRTL(t));let u=await a.getElementRects({reference:e,floating:t,strategy:r}),{x:c,y:d}=Uf(u,o,l),f=o,p={},g=0;for(let h=0;h<s.length;h++){const{name:b,fn:y}=s[h],{x,y:$,data:v,reset:k}=await y({x:c,y:d,initialPlacement:o,placement:f,strategy:r,middlewareData:p,rects:u,platform:a,elements:{reference:e,floating:t}});c=x??c,d=$??d,p={...p,[b]:{...p[b],...v}},k&&g<=50&&(g++,typeof k=="object"&&(k.placement&&(f=k.placement),k.rects&&(u=k.rects===!0?await a.getElementRects({reference:e,floating:t,strategy:r}):k.rects),{x:c,y:d}=Uf(u,f,l)),h=-1)}return{x:c,y:d,placement:f,strategy:r,middlewareData:p}};async function Kn(e,t){var n;t===void 0&&(t={});const{x:o,y:r,platform:i,rects:a,elements:s,strategy:l}=e,{boundary:u="clippingAncestors",rootBoundary:c="viewport",elementContext:d="floating",altBoundary:f=!1,padding:p=0}=Bt(t,e),g=T$(p),b=s[f?d==="floating"?"reference":"floating":d],y=Zi(await i.getClippingRect({element:(n=await(i.isElement==null?void 0:i.isElement(b)))==null||n?b:b.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(s.floating)),boundary:u,rootBoundary:c,strategy:l})),x=d==="floating"?{x:o,y:r,width:a.floating.width,height:a.floating.height}:a.reference,$=await(i.getOffsetParent==null?void 0:i.getOffsetParent(s.floating)),v=await(i.isElement==null?void 0:i.isElement($))?await(i.getScale==null?void 0:i.getScale($))||{x:1,y:1}:{x:1,y:1},k=Zi(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:x,offsetParent:$,strategy:l}):x);return{top:(y.top-k.top+g.top)/v.y,bottom:(k.bottom-y.bottom+g.bottom)/v.y,left:(y.left-k.left+g.left)/v.x,right:(k.right-y.right+g.right)/v.x}}const u4=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:o,placement:r,rects:i,platform:a,elements:s,middlewareData:l}=t,{element:u,padding:c=0}=Bt(e,t)||{};if(u==null)return{};const d=T$(c),f={x:n,y:o},p=Qc(r),g=Yc(p),h=await a.getDimensions(u),b=p==="y",y=b?"top":"left",x=b?"bottom":"right",$=b?"clientHeight":"clientWidth",v=i.reference[g]+i.reference[p]-f[p]-i.floating[g],k=f[p]-i.reference[p],N=await(a.getOffsetParent==null?void 0:a.getOffsetParent(u));let I=N?N[$]:0;(!I||!await(a.isElement==null?void 0:a.isElement(N)))&&(I=s.floating[$]||i.floating[g]);const O=v/2-k/2,z=I/2-h[g]/2-1,F=ur(d[y],z),te=ur(d[x],z),ce=F,B=I-h[g]-te,q=I/2-h[g]/2+O,we=Nu(ce,q,B),oe=!l.arrow&&dn(r)!=null&&q!==we&&i.reference[g]/2-(q<ce?F:te)-h[g]/2<0,de=oe?q<ce?q-ce:q-B:0;return{[p]:f[p]+de,data:{[p]:we,centerOffset:q-we-de,...oe&&{alignmentOffset:de}},reset:oe}}}),l4=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,o;const{placement:r,middlewareData:i,rects:a,initialPlacement:s,platform:l,elements:u}=t,{mainAxis:c=!0,crossAxis:d=!0,fallbackPlacements:f,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:h=!0,...b}=Bt(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};const y=Jt(r),x=jt(s),$=Jt(s)===s,v=await(l.isRTL==null?void 0:l.isRTL(u.floating)),k=f||($||!h?[Li(s)]:t4(s)),N=g!=="none";!f&&N&&k.push(...i4(s,h,g,v));const I=[s,...k],O=await Kn(t,b),z=[];let F=((o=i.flip)==null?void 0:o.overflows)||[];if(c&&z.push(O[y]),d){const q=e4(r,a,v);z.push(O[q[0]],O[q[1]])}if(F=[...F,{placement:r,overflows:z}],!z.every(q=>q<=0)){var te,ce;const q=(((te=i.flip)==null?void 0:te.index)||0)+1,we=I[q];if(we&&(!(d==="alignment"?x!==jt(we):!1)||F.every(K=>jt(K.placement)===x?K.overflows[0]>0:!0)))return{data:{index:q,overflows:F},reset:{placement:we}};let oe=(ce=F.filter(de=>de.overflows[0]<=0).sort((de,K)=>de.overflows[1]-K.overflows[1])[0])==null?void 0:ce.placement;if(!oe)switch(p){case"bestFit":{var B;const de=(B=F.filter(K=>{if(N){const fe=jt(K.placement);return fe===x||fe==="y"}return!0}).map(K=>[K.placement,K.overflows.filter(fe=>fe>0).reduce((fe,J)=>fe+J,0)]).sort((K,fe)=>K[1]-fe[1])[0])==null?void 0:B[0];de&&(oe=de);break}case"initialPlacement":oe=s;break}if(r!==oe)return{reset:{placement:oe}}}return{}}}};function Lf(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Zf(e){return KM.some(t=>e[t]>=0)}const c4=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:o="referenceHidden",...r}=Bt(e,t);switch(o){case"referenceHidden":{const i=await Kn(t,{...r,elementContext:"reference"}),a=Lf(i,n.reference);return{data:{referenceHiddenOffsets:a,referenceHidden:Zf(a)}}}case"escaped":{const i=await Kn(t,{...r,altBoundary:!0}),a=Lf(i,n.floating);return{data:{escapedOffsets:a,escaped:Zf(a)}}}default:return{}}}}},O$=new Set(["left","top"]);async function d4(e,t){const{placement:n,platform:o,elements:r}=e,i=await(o.isRTL==null?void 0:o.isRTL(r.floating)),a=Jt(n),s=dn(n),l=jt(n)==="y",u=O$.has(a)?-1:1,c=i&&l?-1:1,d=Bt(t,e);let{mainAxis:f,crossAxis:p,alignmentAxis:g}=typeof d=="number"?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return s&&typeof g=="number"&&(p=s==="end"?g*-1:g),l?{x:p*c,y:f*u}:{x:f*u,y:p*c}}const p4=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,o;const{x:r,y:i,placement:a,middlewareData:s}=t,l=await d4(t,e);return a===((n=s.offset)==null?void 0:n.placement)&&(o=s.arrow)!=null&&o.alignmentOffset?{}:{x:r+l.x,y:i+l.y,data:{...l,placement:a}}}}},f4=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:o,placement:r}=t,{mainAxis:i=!0,crossAxis:a=!1,limiter:s={fn:b=>{let{x:y,y:x}=b;return{x:y,y:x}}},...l}=Bt(e,t),u={x:n,y:o},c=await Kn(t,l),d=jt(Jt(r)),f=Kc(d);let p=u[f],g=u[d];if(i){const b=f==="y"?"top":"left",y=f==="y"?"bottom":"right",x=p+c[b],$=p-c[y];p=Nu(x,p,$)}if(a){const b=d==="y"?"top":"left",y=d==="y"?"bottom":"right",x=g+c[b],$=g-c[y];g=Nu(x,g,$)}const h=s.fn({...t,[f]:p,[d]:g});return{...h,data:{x:h.x-n,y:h.y-o,enabled:{[f]:i,[d]:a}}}}}},m4=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:o,placement:r,rects:i,middlewareData:a}=t,{offset:s=0,mainAxis:l=!0,crossAxis:u=!0}=Bt(e,t),c={x:n,y:o},d=jt(r),f=Kc(d);let p=c[f],g=c[d];const h=Bt(s,t),b=typeof h=="number"?{mainAxis:h,crossAxis:0}:{mainAxis:0,crossAxis:0,...h};if(l){const $=f==="y"?"height":"width",v=i.reference[f]-i.floating[$]+b.mainAxis,k=i.reference[f]+i.reference[$]-b.mainAxis;p<v?p=v:p>k&&(p=k)}if(u){var y,x;const $=f==="y"?"width":"height",v=O$.has(Jt(r)),k=i.reference[d]-i.floating[$]+(v&&((y=a.offset)==null?void 0:y[d])||0)+(v?0:b.crossAxis),N=i.reference[d]+i.reference[$]+(v?0:((x=a.offset)==null?void 0:x[d])||0)-(v?b.crossAxis:0);g<k?g=k:g>N&&(g=N)}return{[f]:p,[d]:g}}}},h4=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,o;const{placement:r,rects:i,platform:a,elements:s}=t,{apply:l=()=>{},...u}=Bt(e,t),c=await Kn(t,u),d=Jt(r),f=dn(r),p=jt(r)==="y",{width:g,height:h}=i.floating;let b,y;d==="top"||d==="bottom"?(b=d,y=f===(await(a.isRTL==null?void 0:a.isRTL(s.floating))?"start":"end")?"left":"right"):(y=d,b=f==="end"?"top":"bottom");const x=h-c.top-c.bottom,$=g-c.left-c.right,v=ur(h-c[b],x),k=ur(g-c[y],$),N=!t.middlewareData.shift;let I=v,O=k;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(O=$),(o=t.middlewareData.shift)!=null&&o.enabled.y&&(I=x),N&&!f){const F=Ye(c.left,0),te=Ye(c.right,0),ce=Ye(c.top,0),B=Ye(c.bottom,0);p?O=g-2*(F!==0||te!==0?F+te:Ye(c.left,c.right)):I=h-2*(ce!==0||B!==0?ce+B:Ye(c.top,c.bottom))}await l({...t,availableWidth:O,availableHeight:I});const z=await a.getDimensions(s.floating);return g!==z.width||h!==z.height?{reset:{rects:!0}}:{}}}};function Ga(){return typeof window<"u"}function pn(e){return N$(e)?(e.nodeName||"").toLowerCase():"#document"}function Qe(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Dt(e){var t;return(t=(N$(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function N$(e){return Ga()?e instanceof Node||e instanceof Qe(e).Node:!1}function St(e){return Ga()?e instanceof Element||e instanceof Qe(e).Element:!1}function zt(e){return Ga()?e instanceof HTMLElement||e instanceof Qe(e).HTMLElement:!1}function Ff(e){return!Ga()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Qe(e).ShadowRoot}const g4=new Set(["inline","contents"]);function Co(e){const{overflow:t,overflowX:n,overflowY:o,display:r}=It(e);return/auto|scroll|overlay|hidden|clip/.test(t+o+n)&&!g4.has(r)}const v4=new Set(["table","td","th"]);function y4(e){return v4.has(pn(e))}const b4=[":popover-open",":modal"];function Ka(e){return b4.some(t=>{try{return e.matches(t)}catch{return!1}})}const _4=["transform","translate","scale","rotate","perspective"],w4=["transform","translate","scale","rotate","perspective","filter"],x4=["paint","layout","strict","content"];function Xc(e){const t=ed(),n=St(e)?It(e):e;return _4.some(o=>n[o]?n[o]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||w4.some(o=>(n.willChange||"").includes(o))||x4.some(o=>(n.contain||"").includes(o))}function $4(e){let t=lr(e);for(;zt(t)&&!nn(t);){if(Xc(t))return t;if(Ka(t))return null;t=lr(t)}return null}function ed(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const S4=new Set(["html","body","#document"]);function nn(e){return S4.has(pn(e))}function It(e){return Qe(e).getComputedStyle(e)}function Ya(e){return St(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function lr(e){if(pn(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Ff(e)&&e.host||Dt(e);return Ff(t)?t.host:t}function P$(e){const t=lr(e);return nn(t)?e.ownerDocument?e.ownerDocument.body:e.body:zt(t)&&Co(t)?t:P$(t)}function Yn(e,t,n){var o;t===void 0&&(t=[]),n===void 0&&(n=!0);const r=P$(e),i=r===((o=e.ownerDocument)==null?void 0:o.body),a=Qe(r);if(i){const s=Cu(a);return t.concat(a,a.visualViewport||[],Co(r)?r:[],s&&n?Yn(s):[])}return t.concat(r,Yn(r,[],n))}function Cu(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function C$(e){const t=It(e);let n=parseFloat(t.width)||0,o=parseFloat(t.height)||0;const r=zt(e),i=r?e.offsetWidth:n,a=r?e.offsetHeight:o,s=Ui(n)!==i||Ui(o)!==a;return s&&(n=i,o=a),{width:n,height:o,$:s}}function td(e){return St(e)?e:e.contextElement}function Vr(e){const t=td(e);if(!zt(t))return At(1);const n=t.getBoundingClientRect(),{width:o,height:r,$:i}=C$(t);let a=(i?Ui(n.width):n.width)/o,s=(i?Ui(n.height):n.height)/r;return(!a||!Number.isFinite(a))&&(a=1),(!s||!Number.isFinite(s))&&(s=1),{x:a,y:s}}const I4=At(0);function j$(e){const t=Qe(e);return!ed()||!t.visualViewport?I4:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function k4(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Qe(e)?!1:t}function Ir(e,t,n,o){t===void 0&&(t=!1),n===void 0&&(n=!1);const r=e.getBoundingClientRect(),i=td(e);let a=At(1);t&&(o?St(o)&&(a=Vr(o)):a=Vr(e));const s=k4(i,n,o)?j$(i):At(0);let l=(r.left+s.x)/a.x,u=(r.top+s.y)/a.y,c=r.width/a.x,d=r.height/a.y;if(i){const f=Qe(i),p=o&&St(o)?Qe(o):o;let g=f,h=Cu(g);for(;h&&o&&p!==g;){const b=Vr(h),y=h.getBoundingClientRect(),x=It(h),$=y.left+(h.clientLeft+parseFloat(x.paddingLeft))*b.x,v=y.top+(h.clientTop+parseFloat(x.paddingTop))*b.y;l*=b.x,u*=b.y,c*=b.x,d*=b.y,l+=$,u+=v,g=Qe(h),h=Cu(g)}}return Zi({width:c,height:d,x:l,y:u})}function rd(e,t){const n=Ya(e).scrollLeft;return t?t.left+n:Ir(Dt(e)).left+n}function A$(e,t,n){n===void 0&&(n=!1);const o=e.getBoundingClientRect(),r=o.left+t.scrollLeft-(n?0:rd(e,o)),i=o.top+t.scrollTop;return{x:r,y:i}}function E4(e){let{elements:t,rect:n,offsetParent:o,strategy:r}=e;const i=r==="fixed",a=Dt(o),s=t?Ka(t.floating):!1;if(o===a||s&&i)return n;let l={scrollLeft:0,scrollTop:0},u=At(1);const c=At(0),d=zt(o);if((d||!d&&!i)&&((pn(o)!=="body"||Co(a))&&(l=Ya(o)),zt(o))){const p=Ir(o);u=Vr(o),c.x=p.x+o.clientLeft,c.y=p.y+o.clientTop}const f=a&&!d&&!i?A$(a,l,!0):At(0);return{width:n.width*u.x,height:n.height*u.y,x:n.x*u.x-l.scrollLeft*u.x+c.x+f.x,y:n.y*u.y-l.scrollTop*u.y+c.y+f.y}}function T4(e){return Array.from(e.getClientRects())}function O4(e){const t=Dt(e),n=Ya(e),o=e.ownerDocument.body,r=Ye(t.scrollWidth,t.clientWidth,o.scrollWidth,o.clientWidth),i=Ye(t.scrollHeight,t.clientHeight,o.scrollHeight,o.clientHeight);let a=-n.scrollLeft+rd(e);const s=-n.scrollTop;return It(o).direction==="rtl"&&(a+=Ye(t.clientWidth,o.clientWidth)-r),{width:r,height:i,x:a,y:s}}function N4(e,t){const n=Qe(e),o=Dt(e),r=n.visualViewport;let i=o.clientWidth,a=o.clientHeight,s=0,l=0;if(r){i=r.width,a=r.height;const u=ed();(!u||u&&t==="fixed")&&(s=r.offsetLeft,l=r.offsetTop)}return{width:i,height:a,x:s,y:l}}const P4=new Set(["absolute","fixed"]);function C4(e,t){const n=Ir(e,!0,t==="fixed"),o=n.top+e.clientTop,r=n.left+e.clientLeft,i=zt(e)?Vr(e):At(1),a=e.clientWidth*i.x,s=e.clientHeight*i.y,l=r*i.x,u=o*i.y;return{width:a,height:s,x:l,y:u}}function qf(e,t,n){let o;if(t==="viewport")o=N4(e,n);else if(t==="document")o=O4(Dt(e));else if(St(t))o=C4(t,n);else{const r=j$(e);o={x:t.x-r.x,y:t.y-r.y,width:t.width,height:t.height}}return Zi(o)}function R$(e,t){const n=lr(e);return n===t||!St(n)||nn(n)?!1:It(n).position==="fixed"||R$(n,t)}function j4(e,t){const n=t.get(e);if(n)return n;let o=Yn(e,[],!1).filter(s=>St(s)&&pn(s)!=="body"),r=null;const i=It(e).position==="fixed";let a=i?lr(e):e;for(;St(a)&&!nn(a);){const s=It(a),l=Xc(a);!l&&s.position==="fixed"&&(r=null),(i?!l&&!r:!l&&s.position==="static"&&!!r&&P4.has(r.position)||Co(a)&&!l&&R$(e,a))?o=o.filter(c=>c!==a):r=s,a=lr(a)}return t.set(e,o),o}function A4(e){let{element:t,boundary:n,rootBoundary:o,strategy:r}=e;const a=[...n==="clippingAncestors"?Ka(t)?[]:j4(t,this._c):[].concat(n),o],s=a[0],l=a.reduce((u,c)=>{const d=qf(t,c,r);return u.top=Ye(d.top,u.top),u.right=ur(d.right,u.right),u.bottom=ur(d.bottom,u.bottom),u.left=Ye(d.left,u.left),u},qf(t,s,r));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function R4(e){const{width:t,height:n}=C$(e);return{width:t,height:n}}function z4(e,t,n){const o=zt(t),r=Dt(t),i=n==="fixed",a=Ir(e,!0,i,t);let s={scrollLeft:0,scrollTop:0};const l=At(0);function u(){l.x=rd(r)}if(o||!o&&!i)if((pn(t)!=="body"||Co(r))&&(s=Ya(t)),o){const p=Ir(t,!0,i,t);l.x=p.x+t.clientLeft,l.y=p.y+t.clientTop}else r&&u();i&&!o&&r&&u();const c=r&&!o&&!i?A$(r,s):At(0),d=a.left+s.scrollLeft-l.x-c.x,f=a.top+s.scrollTop-l.y-c.y;return{x:d,y:f,width:a.width,height:a.height}}function Ds(e){return It(e).position==="static"}function Vf(e,t){if(!zt(e)||It(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Dt(e)===n&&(n=n.ownerDocument.body),n}function z$(e,t){const n=Qe(e);if(Ka(e))return n;if(!zt(e)){let r=lr(e);for(;r&&!nn(r);){if(St(r)&&!Ds(r))return r;r=lr(r)}return n}let o=Vf(e,t);for(;o&&y4(o)&&Ds(o);)o=Vf(o,t);return o&&nn(o)&&Ds(o)&&!Xc(o)?n:o||$4(e)||n}const M4=async function(e){const t=this.getOffsetParent||z$,n=this.getDimensions,o=await n(e.floating);return{reference:z4(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:o.width,height:o.height}}};function D4(e){return It(e).direction==="rtl"}const U4={convertOffsetParentRelativeRectToViewportRelativeRect:E4,getDocumentElement:Dt,getClippingRect:A4,getOffsetParent:z$,getElementRects:M4,getClientRects:T4,getDimensions:R4,getScale:Vr,isElement:St,isRTL:D4};function M$(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function L4(e,t){let n=null,o;const r=Dt(e);function i(){var s;clearTimeout(o),(s=n)==null||s.disconnect(),n=null}function a(s,l){s===void 0&&(s=!1),l===void 0&&(l=1),i();const u=e.getBoundingClientRect(),{left:c,top:d,width:f,height:p}=u;if(s||t(),!f||!p)return;const g=Go(d),h=Go(r.clientWidth-(c+f)),b=Go(r.clientHeight-(d+p)),y=Go(c),$={rootMargin:-g+"px "+-h+"px "+-b+"px "+-y+"px",threshold:Ye(0,ur(1,l))||1};let v=!0;function k(N){const I=N[0].intersectionRatio;if(I!==l){if(!v)return a();I?a(!1,I):o=setTimeout(()=>{a(!1,1e-7)},1e3)}I===1&&!M$(u,e.getBoundingClientRect())&&a(),v=!1}try{n=new IntersectionObserver(k,{...$,root:r.ownerDocument})}catch{n=new IntersectionObserver(k,$)}n.observe(e)}return a(!0),i}function Z4(e,t,n,o){o===void 0&&(o={});const{ancestorScroll:r=!0,ancestorResize:i=!0,elementResize:a=typeof ResizeObserver=="function",layoutShift:s=typeof IntersectionObserver=="function",animationFrame:l=!1}=o,u=td(e),c=r||i?[...u?Yn(u):[],...Yn(t)]:[];c.forEach(y=>{r&&y.addEventListener("scroll",n,{passive:!0}),i&&y.addEventListener("resize",n)});const d=u&&s?L4(u,n):null;let f=-1,p=null;a&&(p=new ResizeObserver(y=>{let[x]=y;x&&x.target===u&&p&&(p.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var $;($=p)==null||$.observe(t)})),n()}),u&&!l&&p.observe(u),p.observe(t));let g,h=l?Ir(e):null;l&&b();function b(){const y=Ir(e);h&&!M$(h,y)&&n(),h=y,g=requestAnimationFrame(b)}return n(),()=>{var y;c.forEach(x=>{r&&x.removeEventListener("scroll",n),i&&x.removeEventListener("resize",n)}),d?.(),(y=p)==null||y.disconnect(),p=null,l&&cancelAnimationFrame(g)}}const F4=p4,q4=f4,V4=l4,B4=h4,J4=c4,Bf=u4,W4=m4,H4=(e,t,n)=>{const o=new Map,r={platform:U4,...n},i={...r.platform,_c:o};return s4(e,t,{...r,platform:i})};var G4=typeof document<"u",K4=function(){},ai=G4?D.useLayoutEffect:K4;function Fi(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,o,r;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(o=n;o--!==0;)if(!Fi(e[o],t[o]))return!1;return!0}if(r=Object.keys(e),n=r.length,n!==Object.keys(t).length)return!1;for(o=n;o--!==0;)if(!{}.hasOwnProperty.call(t,r[o]))return!1;for(o=n;o--!==0;){const i=r[o];if(!(i==="_owner"&&e.$$typeof)&&!Fi(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function D$(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Jf(e,t){const n=D$(e);return Math.round(t*n)/n}function Us(e){const t=_.useRef(e);return ai(()=>{t.current=e}),t}function Y4(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:o=[],platform:r,elements:{reference:i,floating:a}={},transform:s=!0,whileElementsMounted:l,open:u}=e,[c,d]=_.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,p]=_.useState(o);Fi(f,o)||p(o);const[g,h]=_.useState(null),[b,y]=_.useState(null),x=_.useCallback(K=>{K!==N.current&&(N.current=K,h(K))},[]),$=_.useCallback(K=>{K!==I.current&&(I.current=K,y(K))},[]),v=i||g,k=a||b,N=_.useRef(null),I=_.useRef(null),O=_.useRef(c),z=l!=null,F=Us(l),te=Us(r),ce=Us(u),B=_.useCallback(()=>{if(!N.current||!I.current)return;const K={placement:t,strategy:n,middleware:f};te.current&&(K.platform=te.current),H4(N.current,I.current,K).then(fe=>{const J={...fe,isPositioned:ce.current!==!1};q.current&&!Fi(O.current,J)&&(O.current=J,sm.flushSync(()=>{d(J)}))})},[f,t,n,te,ce]);ai(()=>{u===!1&&O.current.isPositioned&&(O.current.isPositioned=!1,d(K=>({...K,isPositioned:!1})))},[u]);const q=_.useRef(!1);ai(()=>(q.current=!0,()=>{q.current=!1}),[]),ai(()=>{if(v&&(N.current=v),k&&(I.current=k),v&&k){if(F.current)return F.current(v,k,B);B()}},[v,k,B,F,z]);const we=_.useMemo(()=>({reference:N,floating:I,setReference:x,setFloating:$}),[x,$]),oe=_.useMemo(()=>({reference:v,floating:k}),[v,k]),de=_.useMemo(()=>{const K={position:n,left:0,top:0};if(!oe.floating)return K;const fe=Jf(oe.floating,c.x),J=Jf(oe.floating,c.y);return s?{...K,transform:"translate("+fe+"px, "+J+"px)",...D$(oe.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:fe,top:J}},[n,s,oe.floating,c.x,c.y]);return _.useMemo(()=>({...c,update:B,refs:we,elements:oe,floatingStyles:de}),[c,B,we,oe,de])}const Q4=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:o,padding:r}=typeof e=="function"?e(n):e;return o&&t(o)?o.current!=null?Bf({element:o.current,padding:r}).fn(n):{}:o?Bf({element:o,padding:r}).fn(n):{}}}},X4=(e,t)=>({...F4(e),options:[e,t]}),eD=(e,t)=>({...q4(e),options:[e,t]}),tD=(e,t)=>({...W4(e),options:[e,t]}),rD=(e,t)=>({...V4(e),options:[e,t]}),nD=(e,t)=>({...B4(e),options:[e,t]}),oD=(e,t)=>({...J4(e),options:[e,t]}),iD=(e,t)=>({...Q4(e),options:[e,t]});var aD="Arrow",U$=_.forwardRef((e,t)=>{const{children:n,width:o=10,height:r=5,...i}=e;return m.jsx(Ce.svg,{...i,ref:t,width:o,height:r,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:m.jsx("polygon",{points:"0,0 30,0 15,10"})})});U$.displayName=aD;var sD=U$;function uD(e){const[t,n]=_.useState(void 0);return lt(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const o=new ResizeObserver(r=>{if(!Array.isArray(r)||!r.length)return;const i=r[0];let a,s;if("borderBoxSize"in i){const l=i.borderBoxSize,u=Array.isArray(l)?l[0]:l;a=u.inlineSize,s=u.blockSize}else a=e.offsetWidth,s=e.offsetHeight;n({width:a,height:s})});return o.observe(e,{box:"border-box"}),()=>o.unobserve(e)}else n(void 0)},[e]),t}var nd="Popper",[L$,Qa]=Po(nd),[lD,Z$]=L$(nd),F$=e=>{const{__scopePopper:t,children:n}=e,[o,r]=_.useState(null);return m.jsx(lD,{scope:t,anchor:o,onAnchorChange:r,children:n})};F$.displayName=nd;var q$="PopperAnchor",V$=_.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:o,...r}=e,i=Z$(q$,n),a=_.useRef(null),s=Ge(t,a),l=_.useRef(null);return _.useEffect(()=>{const u=l.current;l.current=o?.current||a.current,u!==l.current&&i.onAnchorChange(l.current)}),o?null:m.jsx(Ce.div,{...r,ref:s})});V$.displayName=q$;var od="PopperContent",[cD,dD]=L$(od),B$=_.forwardRef((e,t)=>{const{__scopePopper:n,side:o="bottom",sideOffset:r=0,align:i="center",alignOffset:a=0,arrowPadding:s=0,avoidCollisions:l=!0,collisionBoundary:u=[],collisionPadding:c=0,sticky:d="partial",hideWhenDetached:f=!1,updatePositionStrategy:p="optimized",onPlaced:g,...h}=e,b=Z$(od,n),[y,x]=_.useState(null),$=Ge(t,xe=>x(xe)),[v,k]=_.useState(null),N=uD(v),I=N?.width??0,O=N?.height??0,z=o+(i!=="center"?"-"+i:""),F=typeof c=="number"?c:{top:0,right:0,bottom:0,left:0,...c},te=Array.isArray(u)?u:[u],ce=te.length>0,B={padding:F,boundary:te.filter(fD),altBoundary:ce},{refs:q,floatingStyles:we,placement:oe,isPositioned:de,middlewareData:K}=Y4({strategy:"fixed",placement:z,whileElementsMounted:(...xe)=>Z4(...xe,{animationFrame:p==="always"}),elements:{reference:b.anchor},middleware:[X4({mainAxis:r+O,alignmentAxis:a}),l&&eD({mainAxis:!0,crossAxis:!1,limiter:d==="partial"?tD():void 0,...B}),l&&rD({...B}),nD({...B,apply:({elements:xe,rects:Ro,availableWidth:ss,availableHeight:fn})=>{const{width:pt,height:zo}=Ro.reference,je=xe.floating.style;je.setProperty("--radix-popper-available-width",`${ss}px`),je.setProperty("--radix-popper-available-height",`${fn}px`),je.setProperty("--radix-popper-anchor-width",`${pt}px`),je.setProperty("--radix-popper-anchor-height",`${zo}px`)}}),v&&iD({element:v,padding:s}),mD({arrowWidth:I,arrowHeight:O}),f&&oD({strategy:"referenceHidden",...B})]}),[fe,J]=H$(oe),Ue=Sr(g);lt(()=>{de&&Ue?.()},[de,Ue]);const ye=K.arrow?.x,Le=K.arrow?.y,U=K.arrow?.centerOffset!==0,[Q,me]=_.useState();return lt(()=>{y&&me(window.getComputedStyle(y).zIndex)},[y]),m.jsx("div",{ref:q.setFloating,"data-radix-popper-content-wrapper":"",style:{...we,transform:de?we.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Q,"--radix-popper-transform-origin":[K.transformOrigin?.x,K.transformOrigin?.y].join(" "),...K.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:m.jsx(cD,{scope:n,placedSide:fe,onArrowChange:k,arrowX:ye,arrowY:Le,shouldHideArrow:U,children:m.jsx(Ce.div,{"data-side":fe,"data-align":J,...h,ref:$,style:{...h.style,animation:de?void 0:"none"}})})})});B$.displayName=od;var J$="PopperArrow",pD={top:"bottom",right:"left",bottom:"top",left:"right"},W$=_.forwardRef(function(t,n){const{__scopePopper:o,...r}=t,i=dD(J$,o),a=pD[i.placedSide];return m.jsx("span",{ref:i.onArrowChange,style:{position:"absolute",left:i.arrowX,top:i.arrowY,[a]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[i.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[i.placedSide],visibility:i.shouldHideArrow?"hidden":void 0},children:m.jsx(sD,{...r,ref:n,style:{...r.style,display:"block"}})})});W$.displayName=J$;function fD(e){return e!==null}var mD=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:o,middlewareData:r}=t,a=r.arrow?.centerOffset!==0,s=a?0:e.arrowWidth,l=a?0:e.arrowHeight,[u,c]=H$(n),d={start:"0%",center:"50%",end:"100%"}[c],f=(r.arrow?.x??0)+s/2,p=(r.arrow?.y??0)+l/2;let g="",h="";return u==="bottom"?(g=a?d:`${f}px`,h=`${-l}px`):u==="top"?(g=a?d:`${f}px`,h=`${o.floating.height+l}px`):u==="right"?(g=`${-l}px`,h=a?d:`${p}px`):u==="left"&&(g=`${o.floating.width+l}px`,h=a?d:`${p}px`),{data:{x:g,y:h}}}});function H$(e){const[t,n="center"]=e.split("-");return[t,n]}var G$=F$,id=V$,K$=B$,Y$=W$,hD="Portal",Xa=_.forwardRef((e,t)=>{const{container:n,...o}=e,[r,i]=_.useState(!1);lt(()=>i(!0),[]);const a=n||r&&globalThis?.document?.body;return a?am.createPortal(m.jsx(Ce.div,{...o,ref:t}),a):null});Xa.displayName=hD;function gD(e,t){return _.useReducer((n,o)=>t[n][o]??n,e)}var Gt=e=>{const{present:t,children:n}=e,o=vD(t),r=typeof n=="function"?n({present:o.isPresent}):_.Children.only(n),i=Ge(o.ref,yD(r));return typeof n=="function"||o.isPresent?_.cloneElement(r,{ref:i}):null};Gt.displayName="Presence";function vD(e){const[t,n]=_.useState(),o=_.useRef(null),r=_.useRef(e),i=_.useRef("none"),a=e?"mounted":"unmounted",[s,l]=gD(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return _.useEffect(()=>{const u=Ko(o.current);i.current=s==="mounted"?u:"none"},[s]),lt(()=>{const u=o.current,c=r.current;if(c!==e){const f=i.current,p=Ko(u);e?l("MOUNT"):p==="none"||u?.display==="none"?l("UNMOUNT"):l(c&&f!==p?"ANIMATION_OUT":"UNMOUNT"),r.current=e}},[e,l]),lt(()=>{if(t){let u;const c=t.ownerDocument.defaultView??window,d=p=>{const h=Ko(o.current).includes(CSS.escape(p.animationName));if(p.target===t&&h&&(l("ANIMATION_END"),!r.current)){const b=t.style.animationFillMode;t.style.animationFillMode="forwards",u=c.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=b)})}},f=p=>{p.target===t&&(i.current=Ko(o.current))};return t.addEventListener("animationstart",f),t.addEventListener("animationcancel",d),t.addEventListener("animationend",d),()=>{c.clearTimeout(u),t.removeEventListener("animationstart",f),t.removeEventListener("animationcancel",d),t.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(s),ref:_.useCallback(u=>{o.current=u?getComputedStyle(u):null,n(u)},[])}}function Ko(e){return e?.animationName||"none"}function yD(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var bD=_[" useInsertionEffect ".trim().toString()]||lt;function es({prop:e,defaultProp:t,onChange:n=()=>{},caller:o}){const[r,i,a]=_D({defaultProp:t,onChange:n}),s=e!==void 0,l=s?e:r;{const c=_.useRef(e!==void 0);_.useEffect(()=>{const d=c.current;d!==s&&console.warn(`${o} is changing from ${d?"controlled":"uncontrolled"} to ${s?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),c.current=s},[s,o])}const u=_.useCallback(c=>{if(s){const d=wD(c)?c(e):c;d!==e&&a.current?.(d)}else i(c)},[s,e,i,a]);return[l,u]}function _D({defaultProp:e,onChange:t}){const[n,o]=_.useState(e),r=_.useRef(n),i=_.useRef(t);return bD(()=>{i.current=t},[t]),_.useEffect(()=>{r.current!==n&&(i.current?.(n),r.current=n)},[n,r]),[n,o,i]}function wD(e){return typeof e=="function"}var xD=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),$D="VisuallyHidden",Q$=_.forwardRef((e,t)=>m.jsx(Ce.span,{...e,ref:t,style:{...xD,...e.style}}));Q$.displayName=$D;var SD=Q$,[ts]=Po("Tooltip",[Qa]),rs=Qa(),X$="TooltipProvider",ID=700,ju="tooltip.open",[kD,ad]=ts(X$),eS=e=>{const{__scopeTooltip:t,delayDuration:n=ID,skipDelayDuration:o=300,disableHoverableContent:r=!1,children:i}=e,a=_.useRef(!0),s=_.useRef(!1),l=_.useRef(0);return _.useEffect(()=>{const u=l.current;return()=>window.clearTimeout(u)},[]),m.jsx(kD,{scope:t,isOpenDelayedRef:a,delayDuration:n,onOpen:_.useCallback(()=>{window.clearTimeout(l.current),a.current=!1},[]),onClose:_.useCallback(()=>{window.clearTimeout(l.current),l.current=window.setTimeout(()=>a.current=!0,o)},[o]),isPointerInTransitRef:s,onPointerInTransitChange:_.useCallback(u=>{s.current=u},[]),disableHoverableContent:r,children:i})};eS.displayName=X$;var Qn="Tooltip",[ED,jo]=ts(Qn),tS=e=>{const{__scopeTooltip:t,children:n,open:o,defaultOpen:r,onOpenChange:i,disableHoverableContent:a,delayDuration:s}=e,l=ad(Qn,e.__scopeTooltip),u=rs(t),[c,d]=_.useState(null),f=qr(),p=_.useRef(0),g=a??l.disableHoverableContent,h=s??l.delayDuration,b=_.useRef(!1),[y,x]=es({prop:o,defaultProp:r??!1,onChange:I=>{I?(l.onOpen(),document.dispatchEvent(new CustomEvent(ju))):l.onClose(),i?.(I)},caller:Qn}),$=_.useMemo(()=>y?b.current?"delayed-open":"instant-open":"closed",[y]),v=_.useCallback(()=>{window.clearTimeout(p.current),p.current=0,b.current=!1,x(!0)},[x]),k=_.useCallback(()=>{window.clearTimeout(p.current),p.current=0,x(!1)},[x]),N=_.useCallback(()=>{window.clearTimeout(p.current),p.current=window.setTimeout(()=>{b.current=!0,x(!0),p.current=0},h)},[h,x]);return _.useEffect(()=>()=>{p.current&&(window.clearTimeout(p.current),p.current=0)},[]),m.jsx(G$,{...u,children:m.jsx(ED,{scope:t,contentId:f,open:y,stateAttribute:$,trigger:c,onTriggerChange:d,onTriggerEnter:_.useCallback(()=>{l.isOpenDelayedRef.current?N():v()},[l.isOpenDelayedRef,N,v]),onTriggerLeave:_.useCallback(()=>{g?k():(window.clearTimeout(p.current),p.current=0)},[k,g]),onOpen:v,onClose:k,disableHoverableContent:g,children:n})})};tS.displayName=Qn;var Au="TooltipTrigger",rS=_.forwardRef((e,t)=>{const{__scopeTooltip:n,...o}=e,r=jo(Au,n),i=ad(Au,n),a=rs(n),s=_.useRef(null),l=Ge(t,s,r.onTriggerChange),u=_.useRef(!1),c=_.useRef(!1),d=_.useCallback(()=>u.current=!1,[]);return _.useEffect(()=>()=>document.removeEventListener("pointerup",d),[d]),m.jsx(id,{asChild:!0,...a,children:m.jsx(Ce.button,{"aria-describedby":r.open?r.contentId:void 0,"data-state":r.stateAttribute,...o,ref:l,onPointerMove:Oe(e.onPointerMove,f=>{f.pointerType!=="touch"&&!c.current&&!i.isPointerInTransitRef.current&&(r.onTriggerEnter(),c.current=!0)}),onPointerLeave:Oe(e.onPointerLeave,()=>{r.onTriggerLeave(),c.current=!1}),onPointerDown:Oe(e.onPointerDown,()=>{r.open&&r.onClose(),u.current=!0,document.addEventListener("pointerup",d,{once:!0})}),onFocus:Oe(e.onFocus,()=>{u.current||r.onOpen()}),onBlur:Oe(e.onBlur,r.onClose),onClick:Oe(e.onClick,r.onClose)})})});rS.displayName=Au;var sd="TooltipPortal",[TD,OD]=ts(sd,{forceMount:void 0}),nS=e=>{const{__scopeTooltip:t,forceMount:n,children:o,container:r}=e,i=jo(sd,t);return m.jsx(TD,{scope:t,forceMount:n,children:m.jsx(Gt,{present:n||i.open,children:m.jsx(Xa,{asChild:!0,container:r,children:o})})})};nS.displayName=sd;var on="TooltipContent",oS=_.forwardRef((e,t)=>{const n=OD(on,e.__scopeTooltip),{forceMount:o=n.forceMount,side:r="top",...i}=e,a=jo(on,e.__scopeTooltip);return m.jsx(Gt,{present:o||a.open,children:a.disableHoverableContent?m.jsx(iS,{side:r,...i,ref:t}):m.jsx(ND,{side:r,...i,ref:t})})}),ND=_.forwardRef((e,t)=>{const n=jo(on,e.__scopeTooltip),o=ad(on,e.__scopeTooltip),r=_.useRef(null),i=Ge(t,r),[a,s]=_.useState(null),{trigger:l,onClose:u}=n,c=r.current,{onPointerInTransitChange:d}=o,f=_.useCallback(()=>{s(null),d(!1)},[d]),p=_.useCallback((g,h)=>{const b=g.currentTarget,y={x:g.clientX,y:g.clientY},x=AD(y,b.getBoundingClientRect()),$=RD(y,x),v=zD(h.getBoundingClientRect()),k=DD([...$,...v]);s(k),d(!0)},[d]);return _.useEffect(()=>()=>f(),[f]),_.useEffect(()=>{if(l&&c){const g=b=>p(b,c),h=b=>p(b,l);return l.addEventListener("pointerleave",g),c.addEventListener("pointerleave",h),()=>{l.removeEventListener("pointerleave",g),c.removeEventListener("pointerleave",h)}}},[l,c,p,f]),_.useEffect(()=>{if(a){const g=h=>{const b=h.target,y={x:h.clientX,y:h.clientY},x=l?.contains(b)||c?.contains(b),$=!MD(y,a);x?f():$&&(f(),u())};return document.addEventListener("pointermove",g),()=>document.removeEventListener("pointermove",g)}},[l,c,a,u,f]),m.jsx(iS,{...e,ref:i})}),[PD,CD]=ts(Qn,{isInside:!1}),jD=AM("TooltipContent"),iS=_.forwardRef((e,t)=>{const{__scopeTooltip:n,children:o,"aria-label":r,onEscapeKeyDown:i,onPointerDownOutside:a,...s}=e,l=jo(on,n),u=rs(n),{onClose:c}=l;return _.useEffect(()=>(document.addEventListener(ju,c),()=>document.removeEventListener(ju,c)),[c]),_.useEffect(()=>{if(l.trigger){const d=f=>{f.target?.contains(l.trigger)&&c()};return window.addEventListener("scroll",d,{capture:!0}),()=>window.removeEventListener("scroll",d,{capture:!0})}},[l.trigger,c]),m.jsx(Ha,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:a,onFocusOutside:d=>d.preventDefault(),onDismiss:c,children:m.jsxs(K$,{"data-state":l.stateAttribute,...u,...s,ref:t,style:{...s.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[m.jsx(jD,{children:o}),m.jsx(PD,{scope:n,isInside:!0,children:m.jsx(SD,{id:l.contentId,role:"tooltip",children:r||o})})]})})});oS.displayName=on;var aS="TooltipArrow",sS=_.forwardRef((e,t)=>{const{__scopeTooltip:n,...o}=e,r=rs(n);return CD(aS,n).isInside?null:m.jsx(Y$,{...r,...o,ref:t})});sS.displayName=aS;function AD(e,t){const n=Math.abs(t.top-e.y),o=Math.abs(t.bottom-e.y),r=Math.abs(t.right-e.x),i=Math.abs(t.left-e.x);switch(Math.min(n,o,r,i)){case i:return"left";case r:return"right";case n:return"top";case o:return"bottom";default:throw new Error("unreachable")}}function RD(e,t,n=5){const o=[];switch(t){case"top":o.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":o.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":o.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":o.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return o}function zD(e){const{top:t,right:n,bottom:o,left:r}=e;return[{x:r,y:t},{x:n,y:t},{x:n,y:o},{x:r,y:o}]}function MD(e,t){const{x:n,y:o}=e;let r=!1;for(let i=0,a=t.length-1;i<t.length;a=i++){const s=t[i],l=t[a],u=s.x,c=s.y,d=l.x,f=l.y;c>o!=f>o&&n<(d-u)*(o-c)/(f-c)+u&&(r=!r)}return r}function DD(e){const t=e.slice();return t.sort((n,o)=>n.x<o.x?-1:n.x>o.x?1:n.y<o.y?-1:n.y>o.y?1:0),UD(t)}function UD(e){if(e.length<=1)return e.slice();const t=[];for(let o=0;o<e.length;o++){const r=e[o];for(;t.length>=2;){const i=t[t.length-1],a=t[t.length-2];if((i.x-a.x)*(r.y-a.y)>=(i.y-a.y)*(r.x-a.x))t.pop();else break}t.push(r)}t.pop();const n=[];for(let o=e.length-1;o>=0;o--){const r=e[o];for(;n.length>=2;){const i=n[n.length-1],a=n[n.length-2];if((i.x-a.x)*(r.y-a.y)>=(i.y-a.y)*(r.x-a.x))n.pop();else break}n.push(r)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var LD=eS,ZD=tS,FD=rS,qD=nS,VD=oS,BD=sS;function uS({delayDuration:e=0,...t}){return m.jsx(LD,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function ud({...e}){return m.jsx(uS,{children:m.jsx(ZD,{"data-slot":"tooltip",...e})})}function ld({...e}){return m.jsx(FD,{"data-slot":"tooltip-trigger",...e})}function cd({className:e,sideOffset:t=0,children:n,...o}){return m.jsx(qD,{children:m.jsxs(VD,{"data-slot":"tooltip-content",sideOffset:t,className:T.cn("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-20 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...o,children:[n,m.jsx(BD,{className:"bg-foreground fill-foreground z-20 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-[2px]"})]})})}const ct=D.forwardRef(({children:e,tooltip:t,side:n="bottom",align:o="center",className:r,...i},a)=>m.jsxs(ud,{children:[m.jsx(ld,{asChild:!0,children:m.jsxs($t,{variant:"ghost",size:"icon",...i,className:T.cn("aui-button-icon size-6 p-1",r),ref:a,children:[m.jsx(kM,{children:e}),m.jsx("span",{className:"aui-sr-only sr-only",children:t})]})}),m.jsx(cd,{side:n,align:o,children:t})]}));ct.displayName="TooltipIconButton";function JD(e){return D.useMemo(()=>e.reduce((t,n)=>(t?.[n.language]&&!n.overrideExisting||(t={...t,[n.language]:{CodeHeader:n.Header??(()=>null),SyntaxHighlighter:n.Component??void 0}}),t),{}),[e])}const WD=()=>{const{plugins:e}=T.useElements(),t=JD(e);return m.jsx(Ws.MarkdownTextPrimitive,{remarkPlugins:[_0],className:"aui-md",components:KD,componentsByLanguage:t})},lS=D.memo(WD),HD=({language:e,code:t})=>{const o=L.useAssistantState(({message:s})=>s).status?.type==="complete",{isCopied:r,copyToClipboard:i}=GD(),a=()=>{!t||r||i(t)};return o?m.jsxs("div",{className:"aui-code-header-root bg-muted-foreground/15 text-foreground dark:bg-muted-foreground/20 mt-4 flex items-center justify-between gap-4 rounded-t-lg px-4 py-2 text-sm font-semibold",children:[m.jsx("span",{className:"aui-code-header-language lowercase [&>span]:text-xs",children:e}),m.jsxs(ct,{tooltip:"Copy",onClick:a,children:[!r&&m.jsx(Du,{}),r&&m.jsx(rr,{})]})]}):null},GD=({copiedDuration:e=3e3}={})=>{const[t,n]=D.useState(!1);return{isCopied:t,copyToClipboard:r=>{r&&navigator.clipboard.writeText(r).then(()=>{n(!0),setTimeout(()=>n(!1),e)})}}},KD=Ws.unstable_memoizeMarkdownComponents({h1:({className:e,...t})=>m.jsx("h1",{className:T.cn("aui-md-h1 mb-8 scroll-m-20 text-4xl font-extrabold tracking-tight last:mb-0",e),...t}),h2:({className:e,...t})=>m.jsx("h2",{className:T.cn("aui-md-h2 mt-8 mb-4 scroll-m-20 text-3xl font-semibold tracking-tight first:mt-0 last:mb-0",e),...t}),h3:({className:e,...t})=>m.jsx("h3",{className:T.cn("aui-md-h3 mt-6 mb-4 scroll-m-20 text-2xl font-semibold tracking-tight first:mt-0 last:mb-0",e),...t}),h4:({className:e,...t})=>m.jsx("h4",{className:T.cn("aui-md-h4 mt-6 mb-4 scroll-m-20 text-xl font-semibold tracking-tight first:mt-0 last:mb-0",e),...t}),h5:({className:e,...t})=>m.jsx("h5",{className:T.cn("aui-md-h5 my-4 text-lg font-semibold first:mt-0 last:mb-0",e),...t}),h6:({className:e,...t})=>m.jsx("h6",{className:T.cn("aui-md-h6 my-4 font-semibold first:mt-0 last:mb-0",e),...t}),p:({className:e,...t})=>m.jsx("p",{className:T.cn("aui-md-p mt-5 mb-5 leading-7 first:mt-0 last:mb-0",e),...t}),a:({className:e,...t})=>m.jsx("a",{className:T.cn("aui-md-a text-primary font-medium underline underline-offset-4",e),...t}),blockquote:({className:e,...t})=>m.jsx("blockquote",{className:T.cn("aui-md-blockquote border-l-2 pl-6 italic",e),...t}),ul:({className:e,...t})=>m.jsx("ul",{className:T.cn("aui-md-ul my-5 ml-6 list-disc [&>li]:mt-2",e),...t}),ol:({className:e,...t})=>m.jsx("ol",{className:T.cn("aui-md-ol my-5 ml-6 list-decimal [&>li]:mt-2",e),...t}),hr:({className:e,...t})=>m.jsx("hr",{className:T.cn("aui-md-hr my-5 border-b",e),...t}),table:({className:e,...t})=>m.jsx("table",{className:T.cn("aui-md-table my-5 w-full border-separate border-spacing-0 overflow-y-auto",e),...t}),th:({className:e,...t})=>m.jsx("th",{className:T.cn("aui-md-th bg-muted px-4 py-2 text-left font-bold first:rounded-tl-lg last:rounded-tr-lg [[align=center]]:text-center [[align=right]]:text-right",e),...t}),td:({className:e,...t})=>m.jsx("td",{className:T.cn("aui-md-td border-b border-l px-4 py-2 text-left last:border-r [[align=center]]:text-center [[align=right]]:text-right",e),...t}),tr:({className:e,...t})=>m.jsx("tr",{className:T.cn("aui-md-tr m-0 border-b p-0 first:border-t [&:last-child>td:first-child]:rounded-bl-lg [&:last-child>td:last-child]:rounded-br-lg",e),...t}),sup:({className:e,...t})=>m.jsx("sup",{className:T.cn("aui-md-sup [&>a]:text-xs [&>a]:no-underline",e),...t}),pre:({className:e,...t})=>m.jsx("pre",{className:T.cn("aui-md-pre text-foreground bg-muted overflow-x-auto rounded-t-none! rounded-b-lg border border-t-0 p-4",e),...t}),code:function({className:t,...n}){const o=Ws.useIsMarkdownCodeBlock();return m.jsx("code",{className:T.cn(!o&&"aui-md-inline-code bg-muted rounded border font-semibold",t),...n})},CodeHeader:HD});var Ls=0;function cS(){_.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Wf()),document.body.insertAdjacentElement("beforeend",e[1]??Wf()),Ls++,()=>{Ls===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Ls--}},[])}function Wf(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Zs="focusScope.autoFocusOnMount",Fs="focusScope.autoFocusOnUnmount",Hf={bubbles:!1,cancelable:!0},YD="FocusScope",dd=_.forwardRef((e,t)=>{const{loop:n=!1,trapped:o=!1,onMountAutoFocus:r,onUnmountAutoFocus:i,...a}=e,[s,l]=_.useState(null),u=Sr(r),c=Sr(i),d=_.useRef(null),f=Ge(t,h=>l(h)),p=_.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;_.useEffect(()=>{if(o){let h=function($){if(p.paused||!s)return;const v=$.target;s.contains(v)?d.current=v:Qt(d.current,{select:!0})},b=function($){if(p.paused||!s)return;const v=$.relatedTarget;v!==null&&(s.contains(v)||Qt(d.current,{select:!0}))},y=function($){if(document.activeElement===document.body)for(const k of $)k.removedNodes.length>0&&Qt(s)};document.addEventListener("focusin",h),document.addEventListener("focusout",b);const x=new MutationObserver(y);return s&&x.observe(s,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",h),document.removeEventListener("focusout",b),x.disconnect()}}},[o,s,p.paused]),_.useEffect(()=>{if(s){Kf.add(p);const h=document.activeElement;if(!s.contains(h)){const y=new CustomEvent(Zs,Hf);s.addEventListener(Zs,u),s.dispatchEvent(y),y.defaultPrevented||(QD(nU(dS(s)),{select:!0}),document.activeElement===h&&Qt(s))}return()=>{s.removeEventListener(Zs,u),setTimeout(()=>{const y=new CustomEvent(Fs,Hf);s.addEventListener(Fs,c),s.dispatchEvent(y),y.defaultPrevented||Qt(h??document.body,{select:!0}),s.removeEventListener(Fs,c),Kf.remove(p)},0)}}},[s,u,c,p]);const g=_.useCallback(h=>{if(!n&&!o||p.paused)return;const b=h.key==="Tab"&&!h.altKey&&!h.ctrlKey&&!h.metaKey,y=document.activeElement;if(b&&y){const x=h.currentTarget,[$,v]=XD(x);$&&v?!h.shiftKey&&y===v?(h.preventDefault(),n&&Qt($,{select:!0})):h.shiftKey&&y===$&&(h.preventDefault(),n&&Qt(v,{select:!0})):y===x&&h.preventDefault()}},[n,o,p.paused]);return m.jsx(Ce.div,{tabIndex:-1,...a,ref:f,onKeyDown:g})});dd.displayName=YD;function QD(e,{select:t=!1}={}){const n=document.activeElement;for(const o of e)if(Qt(o,{select:t}),document.activeElement!==n)return}function XD(e){const t=dS(e),n=Gf(t,e),o=Gf(t.reverse(),e);return[n,o]}function dS(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:o=>{const r=o.tagName==="INPUT"&&o.type==="hidden";return o.disabled||o.hidden||r?NodeFilter.FILTER_SKIP:o.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Gf(e,t){for(const n of e)if(!eU(n,{upTo:t}))return n}function eU(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function tU(e){return e instanceof HTMLInputElement&&"select"in e}function Qt(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&tU(e)&&t&&e.select()}}var Kf=rU();function rU(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Yf(e,t),e.unshift(t)},remove(t){e=Yf(e,t),e[0]?.resume()}}}function Yf(e,t){const n=[...e],o=n.indexOf(t);return o!==-1&&n.splice(o,1),n}function nU(e){return e.filter(t=>t.tagName!=="A")}var oU=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Rr=new WeakMap,Yo=new WeakMap,Qo={},qs=0,pS=function(e){return e&&(e.host||pS(e.parentNode))},iU=function(e,t){return t.map(function(n){if(e.contains(n))return n;var o=pS(n);return o&&e.contains(o)?o:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},aU=function(e,t,n,o){var r=iU(t,Array.isArray(e)?e:[e]);Qo[n]||(Qo[n]=new WeakMap);var i=Qo[n],a=[],s=new Set,l=new Set(r),u=function(d){!d||s.has(d)||(s.add(d),u(d.parentNode))};r.forEach(u);var c=function(d){!d||l.has(d)||Array.prototype.forEach.call(d.children,function(f){if(s.has(f))c(f);else try{var p=f.getAttribute(o),g=p!==null&&p!=="false",h=(Rr.get(f)||0)+1,b=(i.get(f)||0)+1;Rr.set(f,h),i.set(f,b),a.push(f),h===1&&g&&Yo.set(f,!0),b===1&&f.setAttribute(n,"true"),g||f.setAttribute(o,"true")}catch(y){console.error("aria-hidden: cannot operate on ",f,y)}})};return c(t),s.clear(),qs++,function(){a.forEach(function(d){var f=Rr.get(d)-1,p=i.get(d)-1;Rr.set(d,f),i.set(d,p),f||(Yo.has(d)||d.removeAttribute(o),Yo.delete(d)),p||d.removeAttribute(n)}),qs--,qs||(Rr=new WeakMap,Rr=new WeakMap,Yo=new WeakMap,Qo={})}},fS=function(e,t,n){n===void 0&&(n="data-aria-hidden");var o=Array.from(Array.isArray(e)?e:[e]),r=oU(e);return r?(o.push.apply(o,Array.from(r.querySelectorAll("[aria-live], script"))),aU(o,r,n,"aria-hidden")):function(){return null}},Pt=function(){return Pt=Object.assign||function(t){for(var n,o=1,r=arguments.length;o<r;o++){n=arguments[o];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},Pt.apply(this,arguments)};function mS(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]]);return n}function sU(e,t,n){if(n||arguments.length===2)for(var o=0,r=t.length,i;o<r;o++)(i||!(o in t))&&(i||(i=Array.prototype.slice.call(t,0,o)),i[o]=t[o]);return e.concat(i||Array.prototype.slice.call(t))}var si="right-scroll-bar-position",ui="width-before-scroll-bar",uU="with-scroll-bars-hidden",lU="--removed-body-scroll-bar-size";function Vs(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function cU(e,t){var n=D.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(o){var r=n.value;r!==o&&(n.value=o,n.callback(o,r))}}}})[0];return n.callback=t,n.facade}var dU=typeof window<"u"?_.useLayoutEffect:_.useEffect,Qf=new WeakMap;function pU(e,t){var n=cU(null,function(o){return e.forEach(function(r){return Vs(r,o)})});return dU(function(){var o=Qf.get(n);if(o){var r=new Set(o),i=new Set(e),a=n.current;r.forEach(function(s){i.has(s)||Vs(s,null)}),i.forEach(function(s){r.has(s)||Vs(s,a)})}Qf.set(n,e)},[e]),n}function fU(e){return e}function mU(e,t){t===void 0&&(t=fU);var n=[],o=!1,r={read:function(){if(o)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(i){var a=t(i,o);return n.push(a),function(){n=n.filter(function(s){return s!==a})}},assignSyncMedium:function(i){for(o=!0;n.length;){var a=n;n=[],a.forEach(i)}n={push:function(s){return i(s)},filter:function(){return n}}},assignMedium:function(i){o=!0;var a=[];if(n.length){var s=n;n=[],s.forEach(i),a=n}var l=function(){var c=a;a=[],c.forEach(i)},u=function(){return Promise.resolve().then(l)};u(),n={push:function(c){a.push(c),u()},filter:function(c){return a=a.filter(c),n}}}};return r}function hU(e){e===void 0&&(e={});var t=mU(null);return t.options=Pt({async:!0,ssr:!1},e),t}var hS=function(e){var t=e.sideCar,n=mS(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var o=t.read();if(!o)throw new Error("Sidecar medium not found");return _.createElement(o,Pt({},n))};hS.isSideCarExport=!0;function gU(e,t){return e.useMedium(t),hS}var gS=hU(),Bs=function(){},ns=_.forwardRef(function(e,t){var n=_.useRef(null),o=_.useState({onScrollCapture:Bs,onWheelCapture:Bs,onTouchMoveCapture:Bs}),r=o[0],i=o[1],a=e.forwardProps,s=e.children,l=e.className,u=e.removeScrollBar,c=e.enabled,d=e.shards,f=e.sideCar,p=e.noRelative,g=e.noIsolation,h=e.inert,b=e.allowPinchZoom,y=e.as,x=y===void 0?"div":y,$=e.gapMode,v=mS(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),k=f,N=pU([n,t]),I=Pt(Pt({},v),r);return _.createElement(_.Fragment,null,c&&_.createElement(k,{sideCar:gS,removeScrollBar:u,shards:d,noRelative:p,noIsolation:g,inert:h,setCallbacks:i,allowPinchZoom:!!b,lockRef:n,gapMode:$}),a?_.cloneElement(_.Children.only(s),Pt(Pt({},I),{ref:N})):_.createElement(x,Pt({},I,{className:l,ref:N}),s))});ns.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};ns.classNames={fullWidth:ui,zeroRight:si};var vU=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function yU(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=vU();return t&&e.setAttribute("nonce",t),e}function bU(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function _U(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var wU=function(){var e=0,t=null;return{add:function(n){e==0&&(t=yU())&&(bU(t,n),_U(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},xU=function(){var e=wU();return function(t,n){_.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},vS=function(){var e=xU(),t=function(n){var o=n.styles,r=n.dynamic;return e(o,r),null};return t},$U={left:0,top:0,right:0,gap:0},Js=function(e){return parseInt(e||"",10)||0},SU=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],o=t[e==="padding"?"paddingTop":"marginTop"],r=t[e==="padding"?"paddingRight":"marginRight"];return[Js(n),Js(o),Js(r)]},IU=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return $U;var t=SU(e),n=document.documentElement.clientWidth,o=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,o-n+t[2]-t[0])}},kU=vS(),Br="data-scroll-locked",EU=function(e,t,n,o){var r=e.left,i=e.top,a=e.right,s=e.gap;return n===void 0&&(n="margin"),`
|
|
97
|
-
.`.concat(
|
|
96
|
+
`)}`}async function vM(e){return(await(await fetch("/chat/session",{method:"POST",headers:{"Gram-Project":e.projectSlug}})).json()).client_token}const yM=({children:e,config:t,getSession:n=vM})=>{const o=r$({getSession:n,projectSlug:t.projectSlug}),r=_$(),[i,a]=D.useState(t.model?.defaultModel??Mu[0]),[s,l]=D.useState(t.modal?.defaultExpanded??!1),[u,c]=D.useState(t.modal?.defaultOpen),d=t.plugins??T.recommended,f=gM(t.systemPrompt,d),{data:p,isLoading:g}=pM({getSession:n,projectSlug:t.projectSlug,mcp:t.mcp,environment:t.environment??{}}),h=D.useRef({requestApproval:r.requestApproval,isToolApproved:r.isToolApproved,whitelistTool:r.whitelistTool});h.current={requestApproval:r.requestApproval,isToolApproved:r.isToolApproved,whitelistTool:r.whitelistTool};const b=D.useCallback(()=>({requestApproval:(...v)=>h.current.requestApproval(...v),isToolApproved:(...v)=>h.current.isToolApproved(...v),whitelistTool:(...v)=>h.current.whitelistTool(...v)}),[]);D.useEffect(()=>(t.tools?.toolsRequiringApproval?.length&&dR(b(),t.tools.toolsRequiringApproval),()=>{pR()}),[t.tools?.toolsRequiringApproval,b]);let y="https://localhost:8080";y=y.replace(/\/+$/,"");const x=D.useMemo(()=>({sendMessages:async({messages:v,abortSignal:k})=>{const N=!!t.languageModel;if(!o)throw new Error("No session found");if(g||!p)throw new Error("MCP tools are still being discovered");const I=$.thread.getModelContext(),O=lR(cR(I?.tools??{})),z=N?null:Pw({baseURL:y,apiKey:"unused, but must be set",headers:{"Gram-Project":t.projectSlug,"Gram-Chat-Session":o}});t.languageModel&&console.log("Using custom language model",t.languageModel);const F={...p,...IP(O)},te=mR(F,t.tools?.toolsRequiringApproval,b()),ce=t.languageModel?t.languageModel:z.chat(i);try{return eR({system:f,model:ce,messages:nR(v),tools:te,stopWhen:Lx(10),experimental_transform:uR({delayInMs:15}),abortSignal:k,onError:({error:q})=>{console.error("Stream error in onError callback:",q)}}).toUIMessageStream()}catch(B){throw console.error("Error creating stream:",B),B}},reconnectToStream:async()=>{throw new Error("Stream reconnection not supported")}}),[t,t.languageModel,i,f,o,p,g,b,y]),$=SP({transport:x});return m.jsx(L.AssistantRuntimeProvider,{runtime:$,children:m.jsxs(T.ElementsContext.Provider,{value:{config:t,setModel:a,model:i,isExpanded:s,setIsExpanded:l,isOpen:u??!1,setIsOpen:c,plugins:d},children:[e,m.jsx($0,{tools:t.tools?.frontendTools??{}})]})})},bM=e=>{const t=new DR;return m.jsx(UR,{client:t,children:m.jsx(mM,{children:m.jsx(yM,{...e})})})};function Cf(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Hc(...e){return t=>{let n=!1;const o=e.map(r=>{const i=Cf(r,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let r=0;r<o.length;r++){const i=o[r];typeof i=="function"?i():Cf(e[r],null)}}}}function Ge(...e){return _.useCallback(Hc(...e),e)}var _M=Symbol.for("react.lazy"),Di=_[" use ".trim().toString()];function wM(e){return typeof e=="object"&&e!==null&&"then"in e}function w$(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===_M&&"_payload"in e&&wM(e._payload)}function x$(e){const t=$M(e),n=_.forwardRef((o,r)=>{let{children:i,...a}=o;w$(i)&&typeof Di=="function"&&(i=Di(i._payload));const s=_.Children.toArray(i),l=s.find(kM);if(l){const u=l.props.children,c=s.map(d=>d===l?_.Children.count(u)>1?_.Children.only(null):_.isValidElement(u)?u.props.children:null:d);return m.jsx(t,{...a,ref:r,children:_.isValidElement(u)?_.cloneElement(u,void 0,c):null})}return m.jsx(t,{...a,ref:r,children:i})});return n.displayName=`${e}.Slot`,n}var xM=x$("Slot");function $M(e){const t=_.forwardRef((n,o)=>{let{children:r,...i}=n;if(w$(r)&&typeof Di=="function"&&(r=Di(r._payload)),_.isValidElement(r)){const a=TM(r),s=EM(i,r.props);return r.type!==_.Fragment&&(s.ref=o?Hc(o,a):a),_.cloneElement(r,s)}return _.Children.count(r)>1?_.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var $$=Symbol("radix.slottable");function SM(e){const t=({children:n})=>m.jsx(m.Fragment,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=$$,t}var IM=SM("Slottable");function kM(e){return _.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===$$}function EM(e,t){const n={...t};for(const o in t){const r=e[o],i=t[o];/^on[A-Z]/.test(o)?r&&i?n[o]=(...s)=>{const l=i(...s);return r(...s),l}:r&&(n[o]=r):o==="style"?n[o]={...r,...i}:o==="className"&&(n[o]=[r,i].filter(Boolean).join(" "))}return{...e,...n}}function TM(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}const jf=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,Af=T.clsx,S$=(e,t)=>n=>{var o;if(t?.variants==null)return Af(e,n?.class,n?.className);const{variants:r,defaultVariants:i}=t,a=Object.keys(r).map(u=>{const c=n?.[u],d=i?.[u];if(c===null)return null;const f=jf(c)||jf(d);return r[u][f]}),s=n&&Object.entries(n).reduce((u,c)=>{let[d,f]=c;return f===void 0||(u[d]=f),u},{}),l=t==null||(o=t.compoundVariants)===null||o===void 0?void 0:o.reduce((u,c)=>{let{class:d,className:f,...p}=c;return Object.entries(p).every(g=>{let[h,b]=g;return Array.isArray(b)?b.includes({...i,...s}[h]):{...i,...s}[h]===b})?[...u,d,f]:u},[]);return Af(e,a,l,n?.class,n?.className)},OM=S$("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}}),$t=_.forwardRef(({className:e,variant:t,size:n,asChild:o=!1,...r},i)=>{const a=o?xM:"button";return m.jsx(a,{"data-slot":"button",className:T.cn(OM({variant:t,size:n,className:e})),ref:i,...r})});$t.displayName="Button";function Oe(e,t,{checkForDefaultPrevented:n=!0}={}){return function(r){if(e?.(r),n===!1||!r.defaultPrevented)return t?.(r)}}function NM(e,t){const n=_.createContext(t),o=i=>{const{children:a,...s}=i,l=_.useMemo(()=>s,Object.values(s));return m.jsx(n.Provider,{value:l,children:a})};o.displayName=e+"Provider";function r(i){const a=_.useContext(n);if(a)return a;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return[o,r]}function Po(e,t=[]){let n=[];function o(i,a){const s=_.createContext(a),l=n.length;n=[...n,a];const u=d=>{const{scope:f,children:p,...g}=d,h=f?.[e]?.[l]||s,b=_.useMemo(()=>g,Object.values(g));return m.jsx(h.Provider,{value:b,children:p})};u.displayName=i+"Provider";function c(d,f){const p=f?.[e]?.[l]||s,g=_.useContext(p);if(g)return g;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[u,c]}const r=()=>{const i=n.map(a=>_.createContext(a));return function(s){const l=s?.[e]||i;return _.useMemo(()=>({[`__scope${e}`]:{...s,[e]:l}}),[s,l])}};return r.scopeName=e,[o,PM(r,...t)]}function PM(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const o=e.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(i){const a=o.reduce((s,{useScope:l,scopeName:u})=>{const d=l(i)[`__scope${u}`];return{...s,...d}},{});return _.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return n.scopeName=t.scopeName,n}function Gc(e){const t=CM(e),n=_.forwardRef((o,r)=>{const{children:i,...a}=o,s=_.Children.toArray(i),l=s.find(AM);if(l){const u=l.props.children,c=s.map(d=>d===l?_.Children.count(u)>1?_.Children.only(null):_.isValidElement(u)?u.props.children:null:d);return m.jsx(t,{...a,ref:r,children:_.isValidElement(u)?_.cloneElement(u,void 0,c):null})}return m.jsx(t,{...a,ref:r,children:i})});return n.displayName=`${e}.Slot`,n}function CM(e){const t=_.forwardRef((n,o)=>{const{children:r,...i}=n;if(_.isValidElement(r)){const a=zM(r),s=RM(i,r.props);return r.type!==_.Fragment&&(s.ref=o?Hc(o,a):a),_.cloneElement(r,s)}return _.Children.count(r)>1?_.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var I$=Symbol("radix.slottable");function jM(e){const t=({children:n})=>m.jsx(m.Fragment,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=I$,t}function AM(e){return _.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===I$}function RM(e,t){const n={...t};for(const o in t){const r=e[o],i=t[o];/^on[A-Z]/.test(o)?r&&i?n[o]=(...s)=>{const l=i(...s);return r(...s),l}:r&&(n[o]=r):o==="style"?n[o]={...r,...i}:o==="className"&&(n[o]=[r,i].filter(Boolean).join(" "))}return{...e,...n}}function zM(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var MM=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Ce=MM.reduce((e,t)=>{const n=Gc(`Primitive.${t}`),o=_.forwardRef((r,i)=>{const{asChild:a,...s}=r,l=a?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),m.jsx(l,{...s,ref:i})});return o.displayName=`Primitive.${t}`,{...e,[t]:o}},{});function DM(e,t){e&&sm.flushSync(()=>e.dispatchEvent(t))}function Sr(e){const t=_.useRef(e);return _.useEffect(()=>{t.current=e}),_.useMemo(()=>(...n)=>t.current?.(...n),[])}function UM(e,t=globalThis?.document){const n=Sr(e);_.useEffect(()=>{const o=r=>{r.key==="Escape"&&n(r)};return t.addEventListener("keydown",o,{capture:!0}),()=>t.removeEventListener("keydown",o,{capture:!0})},[n,t])}var LM="DismissableLayer",Ou="dismissableLayer.update",ZM="dismissableLayer.pointerDownOutside",FM="dismissableLayer.focusOutside",Rf,k$=_.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Ha=_.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:o,onPointerDownOutside:r,onFocusOutside:i,onInteractOutside:a,onDismiss:s,...l}=e,u=_.useContext(k$),[c,d]=_.useState(null),f=c?.ownerDocument??globalThis?.document,[,p]=_.useState({}),g=Ge(t,I=>d(I)),h=Array.from(u.layers),[b]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),y=h.indexOf(b),x=c?h.indexOf(c):-1,$=u.layersWithOutsidePointerEventsDisabled.size>0,v=x>=y,k=BM(I=>{const O=I.target,z=[...u.branches].some(F=>F.contains(O));!v||z||(r?.(I),a?.(I),I.defaultPrevented||s?.())},f),N=JM(I=>{const O=I.target;[...u.branches].some(F=>F.contains(O))||(i?.(I),a?.(I),I.defaultPrevented||s?.())},f);return UM(I=>{x===u.layers.size-1&&(o?.(I),!I.defaultPrevented&&s&&(I.preventDefault(),s()))},f),_.useEffect(()=>{if(c)return n&&(u.layersWithOutsidePointerEventsDisabled.size===0&&(Rf=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(c)),u.layers.add(c),zf(),()=>{n&&u.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=Rf)}},[c,f,n,u]),_.useEffect(()=>()=>{c&&(u.layers.delete(c),u.layersWithOutsidePointerEventsDisabled.delete(c),zf())},[c,u]),_.useEffect(()=>{const I=()=>p({});return document.addEventListener(Ou,I),()=>document.removeEventListener(Ou,I)},[]),m.jsx(Ce.div,{...l,ref:g,style:{pointerEvents:$?v?"auto":"none":void 0,...e.style},onFocusCapture:Oe(e.onFocusCapture,N.onFocusCapture),onBlurCapture:Oe(e.onBlurCapture,N.onBlurCapture),onPointerDownCapture:Oe(e.onPointerDownCapture,k.onPointerDownCapture)})});Ha.displayName=LM;var qM="DismissableLayerBranch",VM=_.forwardRef((e,t)=>{const n=_.useContext(k$),o=_.useRef(null),r=Ge(t,o);return _.useEffect(()=>{const i=o.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),m.jsx(Ce.div,{...e,ref:r})});VM.displayName=qM;function BM(e,t=globalThis?.document){const n=Sr(e),o=_.useRef(!1),r=_.useRef(()=>{});return _.useEffect(()=>{const i=s=>{if(s.target&&!o.current){let l=function(){E$(ZM,n,u,{discrete:!0})};const u={originalEvent:s};s.pointerType==="touch"?(t.removeEventListener("click",r.current),r.current=l,t.addEventListener("click",r.current,{once:!0})):l()}else t.removeEventListener("click",r.current);o.current=!1},a=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(a),t.removeEventListener("pointerdown",i),t.removeEventListener("click",r.current)}},[t,n]),{onPointerDownCapture:()=>o.current=!0}}function JM(e,t=globalThis?.document){const n=Sr(e),o=_.useRef(!1);return _.useEffect(()=>{const r=i=>{i.target&&!o.current&&E$(FM,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",r),()=>t.removeEventListener("focusin",r)},[t,n]),{onFocusCapture:()=>o.current=!0,onBlurCapture:()=>o.current=!1}}function zf(){const e=new CustomEvent(Ou);document.dispatchEvent(e)}function E$(e,t,n,{discrete:o}){const r=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&r.addEventListener(e,t,{once:!0}),o?DM(r,i):r.dispatchEvent(i)}var lt=globalThis?.document?_.useLayoutEffect:()=>{},WM=_[" useId ".trim().toString()]||(()=>{}),HM=0;function qr(e){const[t,n]=_.useState(WM());return lt(()=>{n(o=>o??String(HM++))},[e]),t?`radix-${t}`:""}const GM=["top","right","bottom","left"],ur=Math.min,Ye=Math.max,Ui=Math.round,Go=Math.floor,At=e=>({x:e,y:e}),KM={left:"right",right:"left",bottom:"top",top:"bottom"},YM={start:"end",end:"start"};function Nu(e,t,n){return Ye(e,ur(t,n))}function Bt(e,t){return typeof e=="function"?e(t):e}function Jt(e){return e.split("-")[0]}function dn(e){return e.split("-")[1]}function Kc(e){return e==="x"?"y":"x"}function Yc(e){return e==="y"?"height":"width"}const QM=new Set(["top","bottom"]);function jt(e){return QM.has(Jt(e))?"y":"x"}function Qc(e){return Kc(jt(e))}function XM(e,t,n){n===void 0&&(n=!1);const o=dn(e),r=Qc(e),i=Yc(r);let a=r==="x"?o===(n?"end":"start")?"right":"left":o==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(a=Li(a)),[a,Li(a)]}function e4(e){const t=Li(e);return[Pu(e),t,Pu(t)]}function Pu(e){return e.replace(/start|end/g,t=>YM[t])}const Mf=["left","right"],Df=["right","left"],t4=["top","bottom"],r4=["bottom","top"];function n4(e,t,n){switch(e){case"top":case"bottom":return n?t?Df:Mf:t?Mf:Df;case"left":case"right":return t?t4:r4;default:return[]}}function o4(e,t,n,o){const r=dn(e);let i=n4(Jt(e),n==="start",o);return r&&(i=i.map(a=>a+"-"+r),t&&(i=i.concat(i.map(Pu)))),i}function Li(e){return e.replace(/left|right|bottom|top/g,t=>KM[t])}function i4(e){return{top:0,right:0,bottom:0,left:0,...e}}function T$(e){return typeof e!="number"?i4(e):{top:e,right:e,bottom:e,left:e}}function Zi(e){const{x:t,y:n,width:o,height:r}=e;return{width:o,height:r,top:n,left:t,right:t+o,bottom:n+r,x:t,y:n}}function Uf(e,t,n){let{reference:o,floating:r}=e;const i=jt(t),a=Qc(t),s=Yc(a),l=Jt(t),u=i==="y",c=o.x+o.width/2-r.width/2,d=o.y+o.height/2-r.height/2,f=o[s]/2-r[s]/2;let p;switch(l){case"top":p={x:c,y:o.y-r.height};break;case"bottom":p={x:c,y:o.y+o.height};break;case"right":p={x:o.x+o.width,y:d};break;case"left":p={x:o.x-r.width,y:d};break;default:p={x:o.x,y:o.y}}switch(dn(t)){case"start":p[a]-=f*(n&&u?-1:1);break;case"end":p[a]+=f*(n&&u?-1:1);break}return p}const a4=async(e,t,n)=>{const{placement:o="bottom",strategy:r="absolute",middleware:i=[],platform:a}=n,s=i.filter(Boolean),l=await(a.isRTL==null?void 0:a.isRTL(t));let u=await a.getElementRects({reference:e,floating:t,strategy:r}),{x:c,y:d}=Uf(u,o,l),f=o,p={},g=0;for(let h=0;h<s.length;h++){const{name:b,fn:y}=s[h],{x,y:$,data:v,reset:k}=await y({x:c,y:d,initialPlacement:o,placement:f,strategy:r,middlewareData:p,rects:u,platform:a,elements:{reference:e,floating:t}});c=x??c,d=$??d,p={...p,[b]:{...p[b],...v}},k&&g<=50&&(g++,typeof k=="object"&&(k.placement&&(f=k.placement),k.rects&&(u=k.rects===!0?await a.getElementRects({reference:e,floating:t,strategy:r}):k.rects),{x:c,y:d}=Uf(u,f,l)),h=-1)}return{x:c,y:d,placement:f,strategy:r,middlewareData:p}};async function Kn(e,t){var n;t===void 0&&(t={});const{x:o,y:r,platform:i,rects:a,elements:s,strategy:l}=e,{boundary:u="clippingAncestors",rootBoundary:c="viewport",elementContext:d="floating",altBoundary:f=!1,padding:p=0}=Bt(t,e),g=T$(p),b=s[f?d==="floating"?"reference":"floating":d],y=Zi(await i.getClippingRect({element:(n=await(i.isElement==null?void 0:i.isElement(b)))==null||n?b:b.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(s.floating)),boundary:u,rootBoundary:c,strategy:l})),x=d==="floating"?{x:o,y:r,width:a.floating.width,height:a.floating.height}:a.reference,$=await(i.getOffsetParent==null?void 0:i.getOffsetParent(s.floating)),v=await(i.isElement==null?void 0:i.isElement($))?await(i.getScale==null?void 0:i.getScale($))||{x:1,y:1}:{x:1,y:1},k=Zi(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:x,offsetParent:$,strategy:l}):x);return{top:(y.top-k.top+g.top)/v.y,bottom:(k.bottom-y.bottom+g.bottom)/v.y,left:(y.left-k.left+g.left)/v.x,right:(k.right-y.right+g.right)/v.x}}const s4=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:o,placement:r,rects:i,platform:a,elements:s,middlewareData:l}=t,{element:u,padding:c=0}=Bt(e,t)||{};if(u==null)return{};const d=T$(c),f={x:n,y:o},p=Qc(r),g=Yc(p),h=await a.getDimensions(u),b=p==="y",y=b?"top":"left",x=b?"bottom":"right",$=b?"clientHeight":"clientWidth",v=i.reference[g]+i.reference[p]-f[p]-i.floating[g],k=f[p]-i.reference[p],N=await(a.getOffsetParent==null?void 0:a.getOffsetParent(u));let I=N?N[$]:0;(!I||!await(a.isElement==null?void 0:a.isElement(N)))&&(I=s.floating[$]||i.floating[g]);const O=v/2-k/2,z=I/2-h[g]/2-1,F=ur(d[y],z),te=ur(d[x],z),ce=F,B=I-h[g]-te,q=I/2-h[g]/2+O,we=Nu(ce,q,B),oe=!l.arrow&&dn(r)!=null&&q!==we&&i.reference[g]/2-(q<ce?F:te)-h[g]/2<0,de=oe?q<ce?q-ce:q-B:0;return{[p]:f[p]+de,data:{[p]:we,centerOffset:q-we-de,...oe&&{alignmentOffset:de}},reset:oe}}}),u4=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,o;const{placement:r,middlewareData:i,rects:a,initialPlacement:s,platform:l,elements:u}=t,{mainAxis:c=!0,crossAxis:d=!0,fallbackPlacements:f,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:h=!0,...b}=Bt(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};const y=Jt(r),x=jt(s),$=Jt(s)===s,v=await(l.isRTL==null?void 0:l.isRTL(u.floating)),k=f||($||!h?[Li(s)]:e4(s)),N=g!=="none";!f&&N&&k.push(...o4(s,h,g,v));const I=[s,...k],O=await Kn(t,b),z=[];let F=((o=i.flip)==null?void 0:o.overflows)||[];if(c&&z.push(O[y]),d){const q=XM(r,a,v);z.push(O[q[0]],O[q[1]])}if(F=[...F,{placement:r,overflows:z}],!z.every(q=>q<=0)){var te,ce;const q=(((te=i.flip)==null?void 0:te.index)||0)+1,we=I[q];if(we&&(!(d==="alignment"?x!==jt(we):!1)||F.every(K=>jt(K.placement)===x?K.overflows[0]>0:!0)))return{data:{index:q,overflows:F},reset:{placement:we}};let oe=(ce=F.filter(de=>de.overflows[0]<=0).sort((de,K)=>de.overflows[1]-K.overflows[1])[0])==null?void 0:ce.placement;if(!oe)switch(p){case"bestFit":{var B;const de=(B=F.filter(K=>{if(N){const fe=jt(K.placement);return fe===x||fe==="y"}return!0}).map(K=>[K.placement,K.overflows.filter(fe=>fe>0).reduce((fe,J)=>fe+J,0)]).sort((K,fe)=>K[1]-fe[1])[0])==null?void 0:B[0];de&&(oe=de);break}case"initialPlacement":oe=s;break}if(r!==oe)return{reset:{placement:oe}}}return{}}}};function Lf(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Zf(e){return GM.some(t=>e[t]>=0)}const l4=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:o="referenceHidden",...r}=Bt(e,t);switch(o){case"referenceHidden":{const i=await Kn(t,{...r,elementContext:"reference"}),a=Lf(i,n.reference);return{data:{referenceHiddenOffsets:a,referenceHidden:Zf(a)}}}case"escaped":{const i=await Kn(t,{...r,altBoundary:!0}),a=Lf(i,n.floating);return{data:{escapedOffsets:a,escaped:Zf(a)}}}default:return{}}}}},O$=new Set(["left","top"]);async function c4(e,t){const{placement:n,platform:o,elements:r}=e,i=await(o.isRTL==null?void 0:o.isRTL(r.floating)),a=Jt(n),s=dn(n),l=jt(n)==="y",u=O$.has(a)?-1:1,c=i&&l?-1:1,d=Bt(t,e);let{mainAxis:f,crossAxis:p,alignmentAxis:g}=typeof d=="number"?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return s&&typeof g=="number"&&(p=s==="end"?g*-1:g),l?{x:p*c,y:f*u}:{x:f*u,y:p*c}}const d4=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,o;const{x:r,y:i,placement:a,middlewareData:s}=t,l=await c4(t,e);return a===((n=s.offset)==null?void 0:n.placement)&&(o=s.arrow)!=null&&o.alignmentOffset?{}:{x:r+l.x,y:i+l.y,data:{...l,placement:a}}}}},p4=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:o,placement:r}=t,{mainAxis:i=!0,crossAxis:a=!1,limiter:s={fn:b=>{let{x:y,y:x}=b;return{x:y,y:x}}},...l}=Bt(e,t),u={x:n,y:o},c=await Kn(t,l),d=jt(Jt(r)),f=Kc(d);let p=u[f],g=u[d];if(i){const b=f==="y"?"top":"left",y=f==="y"?"bottom":"right",x=p+c[b],$=p-c[y];p=Nu(x,p,$)}if(a){const b=d==="y"?"top":"left",y=d==="y"?"bottom":"right",x=g+c[b],$=g-c[y];g=Nu(x,g,$)}const h=s.fn({...t,[f]:p,[d]:g});return{...h,data:{x:h.x-n,y:h.y-o,enabled:{[f]:i,[d]:a}}}}}},f4=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:o,placement:r,rects:i,middlewareData:a}=t,{offset:s=0,mainAxis:l=!0,crossAxis:u=!0}=Bt(e,t),c={x:n,y:o},d=jt(r),f=Kc(d);let p=c[f],g=c[d];const h=Bt(s,t),b=typeof h=="number"?{mainAxis:h,crossAxis:0}:{mainAxis:0,crossAxis:0,...h};if(l){const $=f==="y"?"height":"width",v=i.reference[f]-i.floating[$]+b.mainAxis,k=i.reference[f]+i.reference[$]-b.mainAxis;p<v?p=v:p>k&&(p=k)}if(u){var y,x;const $=f==="y"?"width":"height",v=O$.has(Jt(r)),k=i.reference[d]-i.floating[$]+(v&&((y=a.offset)==null?void 0:y[d])||0)+(v?0:b.crossAxis),N=i.reference[d]+i.reference[$]+(v?0:((x=a.offset)==null?void 0:x[d])||0)-(v?b.crossAxis:0);g<k?g=k:g>N&&(g=N)}return{[f]:p,[d]:g}}}},m4=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,o;const{placement:r,rects:i,platform:a,elements:s}=t,{apply:l=()=>{},...u}=Bt(e,t),c=await Kn(t,u),d=Jt(r),f=dn(r),p=jt(r)==="y",{width:g,height:h}=i.floating;let b,y;d==="top"||d==="bottom"?(b=d,y=f===(await(a.isRTL==null?void 0:a.isRTL(s.floating))?"start":"end")?"left":"right"):(y=d,b=f==="end"?"top":"bottom");const x=h-c.top-c.bottom,$=g-c.left-c.right,v=ur(h-c[b],x),k=ur(g-c[y],$),N=!t.middlewareData.shift;let I=v,O=k;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(O=$),(o=t.middlewareData.shift)!=null&&o.enabled.y&&(I=x),N&&!f){const F=Ye(c.left,0),te=Ye(c.right,0),ce=Ye(c.top,0),B=Ye(c.bottom,0);p?O=g-2*(F!==0||te!==0?F+te:Ye(c.left,c.right)):I=h-2*(ce!==0||B!==0?ce+B:Ye(c.top,c.bottom))}await l({...t,availableWidth:O,availableHeight:I});const z=await a.getDimensions(s.floating);return g!==z.width||h!==z.height?{reset:{rects:!0}}:{}}}};function Ga(){return typeof window<"u"}function pn(e){return N$(e)?(e.nodeName||"").toLowerCase():"#document"}function Qe(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Dt(e){var t;return(t=(N$(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function N$(e){return Ga()?e instanceof Node||e instanceof Qe(e).Node:!1}function St(e){return Ga()?e instanceof Element||e instanceof Qe(e).Element:!1}function zt(e){return Ga()?e instanceof HTMLElement||e instanceof Qe(e).HTMLElement:!1}function Ff(e){return!Ga()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Qe(e).ShadowRoot}const h4=new Set(["inline","contents"]);function Co(e){const{overflow:t,overflowX:n,overflowY:o,display:r}=It(e);return/auto|scroll|overlay|hidden|clip/.test(t+o+n)&&!h4.has(r)}const g4=new Set(["table","td","th"]);function v4(e){return g4.has(pn(e))}const y4=[":popover-open",":modal"];function Ka(e){return y4.some(t=>{try{return e.matches(t)}catch{return!1}})}const b4=["transform","translate","scale","rotate","perspective"],_4=["transform","translate","scale","rotate","perspective","filter"],w4=["paint","layout","strict","content"];function Xc(e){const t=ed(),n=St(e)?It(e):e;return b4.some(o=>n[o]?n[o]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||_4.some(o=>(n.willChange||"").includes(o))||w4.some(o=>(n.contain||"").includes(o))}function x4(e){let t=lr(e);for(;zt(t)&&!nn(t);){if(Xc(t))return t;if(Ka(t))return null;t=lr(t)}return null}function ed(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const $4=new Set(["html","body","#document"]);function nn(e){return $4.has(pn(e))}function It(e){return Qe(e).getComputedStyle(e)}function Ya(e){return St(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function lr(e){if(pn(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Ff(e)&&e.host||Dt(e);return Ff(t)?t.host:t}function P$(e){const t=lr(e);return nn(t)?e.ownerDocument?e.ownerDocument.body:e.body:zt(t)&&Co(t)?t:P$(t)}function Yn(e,t,n){var o;t===void 0&&(t=[]),n===void 0&&(n=!0);const r=P$(e),i=r===((o=e.ownerDocument)==null?void 0:o.body),a=Qe(r);if(i){const s=Cu(a);return t.concat(a,a.visualViewport||[],Co(r)?r:[],s&&n?Yn(s):[])}return t.concat(r,Yn(r,[],n))}function Cu(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function C$(e){const t=It(e);let n=parseFloat(t.width)||0,o=parseFloat(t.height)||0;const r=zt(e),i=r?e.offsetWidth:n,a=r?e.offsetHeight:o,s=Ui(n)!==i||Ui(o)!==a;return s&&(n=i,o=a),{width:n,height:o,$:s}}function td(e){return St(e)?e:e.contextElement}function Vr(e){const t=td(e);if(!zt(t))return At(1);const n=t.getBoundingClientRect(),{width:o,height:r,$:i}=C$(t);let a=(i?Ui(n.width):n.width)/o,s=(i?Ui(n.height):n.height)/r;return(!a||!Number.isFinite(a))&&(a=1),(!s||!Number.isFinite(s))&&(s=1),{x:a,y:s}}const S4=At(0);function j$(e){const t=Qe(e);return!ed()||!t.visualViewport?S4:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function I4(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Qe(e)?!1:t}function Ir(e,t,n,o){t===void 0&&(t=!1),n===void 0&&(n=!1);const r=e.getBoundingClientRect(),i=td(e);let a=At(1);t&&(o?St(o)&&(a=Vr(o)):a=Vr(e));const s=I4(i,n,o)?j$(i):At(0);let l=(r.left+s.x)/a.x,u=(r.top+s.y)/a.y,c=r.width/a.x,d=r.height/a.y;if(i){const f=Qe(i),p=o&&St(o)?Qe(o):o;let g=f,h=Cu(g);for(;h&&o&&p!==g;){const b=Vr(h),y=h.getBoundingClientRect(),x=It(h),$=y.left+(h.clientLeft+parseFloat(x.paddingLeft))*b.x,v=y.top+(h.clientTop+parseFloat(x.paddingTop))*b.y;l*=b.x,u*=b.y,c*=b.x,d*=b.y,l+=$,u+=v,g=Qe(h),h=Cu(g)}}return Zi({width:c,height:d,x:l,y:u})}function rd(e,t){const n=Ya(e).scrollLeft;return t?t.left+n:Ir(Dt(e)).left+n}function A$(e,t,n){n===void 0&&(n=!1);const o=e.getBoundingClientRect(),r=o.left+t.scrollLeft-(n?0:rd(e,o)),i=o.top+t.scrollTop;return{x:r,y:i}}function k4(e){let{elements:t,rect:n,offsetParent:o,strategy:r}=e;const i=r==="fixed",a=Dt(o),s=t?Ka(t.floating):!1;if(o===a||s&&i)return n;let l={scrollLeft:0,scrollTop:0},u=At(1);const c=At(0),d=zt(o);if((d||!d&&!i)&&((pn(o)!=="body"||Co(a))&&(l=Ya(o)),zt(o))){const p=Ir(o);u=Vr(o),c.x=p.x+o.clientLeft,c.y=p.y+o.clientTop}const f=a&&!d&&!i?A$(a,l,!0):At(0);return{width:n.width*u.x,height:n.height*u.y,x:n.x*u.x-l.scrollLeft*u.x+c.x+f.x,y:n.y*u.y-l.scrollTop*u.y+c.y+f.y}}function E4(e){return Array.from(e.getClientRects())}function T4(e){const t=Dt(e),n=Ya(e),o=e.ownerDocument.body,r=Ye(t.scrollWidth,t.clientWidth,o.scrollWidth,o.clientWidth),i=Ye(t.scrollHeight,t.clientHeight,o.scrollHeight,o.clientHeight);let a=-n.scrollLeft+rd(e);const s=-n.scrollTop;return It(o).direction==="rtl"&&(a+=Ye(t.clientWidth,o.clientWidth)-r),{width:r,height:i,x:a,y:s}}function O4(e,t){const n=Qe(e),o=Dt(e),r=n.visualViewport;let i=o.clientWidth,a=o.clientHeight,s=0,l=0;if(r){i=r.width,a=r.height;const u=ed();(!u||u&&t==="fixed")&&(s=r.offsetLeft,l=r.offsetTop)}return{width:i,height:a,x:s,y:l}}const N4=new Set(["absolute","fixed"]);function P4(e,t){const n=Ir(e,!0,t==="fixed"),o=n.top+e.clientTop,r=n.left+e.clientLeft,i=zt(e)?Vr(e):At(1),a=e.clientWidth*i.x,s=e.clientHeight*i.y,l=r*i.x,u=o*i.y;return{width:a,height:s,x:l,y:u}}function qf(e,t,n){let o;if(t==="viewport")o=O4(e,n);else if(t==="document")o=T4(Dt(e));else if(St(t))o=P4(t,n);else{const r=j$(e);o={x:t.x-r.x,y:t.y-r.y,width:t.width,height:t.height}}return Zi(o)}function R$(e,t){const n=lr(e);return n===t||!St(n)||nn(n)?!1:It(n).position==="fixed"||R$(n,t)}function C4(e,t){const n=t.get(e);if(n)return n;let o=Yn(e,[],!1).filter(s=>St(s)&&pn(s)!=="body"),r=null;const i=It(e).position==="fixed";let a=i?lr(e):e;for(;St(a)&&!nn(a);){const s=It(a),l=Xc(a);!l&&s.position==="fixed"&&(r=null),(i?!l&&!r:!l&&s.position==="static"&&!!r&&N4.has(r.position)||Co(a)&&!l&&R$(e,a))?o=o.filter(c=>c!==a):r=s,a=lr(a)}return t.set(e,o),o}function j4(e){let{element:t,boundary:n,rootBoundary:o,strategy:r}=e;const a=[...n==="clippingAncestors"?Ka(t)?[]:C4(t,this._c):[].concat(n),o],s=a[0],l=a.reduce((u,c)=>{const d=qf(t,c,r);return u.top=Ye(d.top,u.top),u.right=ur(d.right,u.right),u.bottom=ur(d.bottom,u.bottom),u.left=Ye(d.left,u.left),u},qf(t,s,r));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function A4(e){const{width:t,height:n}=C$(e);return{width:t,height:n}}function R4(e,t,n){const o=zt(t),r=Dt(t),i=n==="fixed",a=Ir(e,!0,i,t);let s={scrollLeft:0,scrollTop:0};const l=At(0);function u(){l.x=rd(r)}if(o||!o&&!i)if((pn(t)!=="body"||Co(r))&&(s=Ya(t)),o){const p=Ir(t,!0,i,t);l.x=p.x+t.clientLeft,l.y=p.y+t.clientTop}else r&&u();i&&!o&&r&&u();const c=r&&!o&&!i?A$(r,s):At(0),d=a.left+s.scrollLeft-l.x-c.x,f=a.top+s.scrollTop-l.y-c.y;return{x:d,y:f,width:a.width,height:a.height}}function Ds(e){return It(e).position==="static"}function Vf(e,t){if(!zt(e)||It(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Dt(e)===n&&(n=n.ownerDocument.body),n}function z$(e,t){const n=Qe(e);if(Ka(e))return n;if(!zt(e)){let r=lr(e);for(;r&&!nn(r);){if(St(r)&&!Ds(r))return r;r=lr(r)}return n}let o=Vf(e,t);for(;o&&v4(o)&&Ds(o);)o=Vf(o,t);return o&&nn(o)&&Ds(o)&&!Xc(o)?n:o||x4(e)||n}const z4=async function(e){const t=this.getOffsetParent||z$,n=this.getDimensions,o=await n(e.floating);return{reference:R4(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:o.width,height:o.height}}};function M4(e){return It(e).direction==="rtl"}const D4={convertOffsetParentRelativeRectToViewportRelativeRect:k4,getDocumentElement:Dt,getClippingRect:j4,getOffsetParent:z$,getElementRects:z4,getClientRects:E4,getDimensions:A4,getScale:Vr,isElement:St,isRTL:M4};function M$(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function U4(e,t){let n=null,o;const r=Dt(e);function i(){var s;clearTimeout(o),(s=n)==null||s.disconnect(),n=null}function a(s,l){s===void 0&&(s=!1),l===void 0&&(l=1),i();const u=e.getBoundingClientRect(),{left:c,top:d,width:f,height:p}=u;if(s||t(),!f||!p)return;const g=Go(d),h=Go(r.clientWidth-(c+f)),b=Go(r.clientHeight-(d+p)),y=Go(c),$={rootMargin:-g+"px "+-h+"px "+-b+"px "+-y+"px",threshold:Ye(0,ur(1,l))||1};let v=!0;function k(N){const I=N[0].intersectionRatio;if(I!==l){if(!v)return a();I?a(!1,I):o=setTimeout(()=>{a(!1,1e-7)},1e3)}I===1&&!M$(u,e.getBoundingClientRect())&&a(),v=!1}try{n=new IntersectionObserver(k,{...$,root:r.ownerDocument})}catch{n=new IntersectionObserver(k,$)}n.observe(e)}return a(!0),i}function L4(e,t,n,o){o===void 0&&(o={});const{ancestorScroll:r=!0,ancestorResize:i=!0,elementResize:a=typeof ResizeObserver=="function",layoutShift:s=typeof IntersectionObserver=="function",animationFrame:l=!1}=o,u=td(e),c=r||i?[...u?Yn(u):[],...Yn(t)]:[];c.forEach(y=>{r&&y.addEventListener("scroll",n,{passive:!0}),i&&y.addEventListener("resize",n)});const d=u&&s?U4(u,n):null;let f=-1,p=null;a&&(p=new ResizeObserver(y=>{let[x]=y;x&&x.target===u&&p&&(p.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var $;($=p)==null||$.observe(t)})),n()}),u&&!l&&p.observe(u),p.observe(t));let g,h=l?Ir(e):null;l&&b();function b(){const y=Ir(e);h&&!M$(h,y)&&n(),h=y,g=requestAnimationFrame(b)}return n(),()=>{var y;c.forEach(x=>{r&&x.removeEventListener("scroll",n),i&&x.removeEventListener("resize",n)}),d?.(),(y=p)==null||y.disconnect(),p=null,l&&cancelAnimationFrame(g)}}const Z4=d4,F4=p4,q4=u4,V4=m4,B4=l4,Bf=s4,J4=f4,W4=(e,t,n)=>{const o=new Map,r={platform:D4,...n},i={...r.platform,_c:o};return a4(e,t,{...r,platform:i})};var H4=typeof document<"u",G4=function(){},ai=H4?D.useLayoutEffect:G4;function Fi(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,o,r;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(o=n;o--!==0;)if(!Fi(e[o],t[o]))return!1;return!0}if(r=Object.keys(e),n=r.length,n!==Object.keys(t).length)return!1;for(o=n;o--!==0;)if(!{}.hasOwnProperty.call(t,r[o]))return!1;for(o=n;o--!==0;){const i=r[o];if(!(i==="_owner"&&e.$$typeof)&&!Fi(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function D$(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Jf(e,t){const n=D$(e);return Math.round(t*n)/n}function Us(e){const t=_.useRef(e);return ai(()=>{t.current=e}),t}function K4(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:o=[],platform:r,elements:{reference:i,floating:a}={},transform:s=!0,whileElementsMounted:l,open:u}=e,[c,d]=_.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,p]=_.useState(o);Fi(f,o)||p(o);const[g,h]=_.useState(null),[b,y]=_.useState(null),x=_.useCallback(K=>{K!==N.current&&(N.current=K,h(K))},[]),$=_.useCallback(K=>{K!==I.current&&(I.current=K,y(K))},[]),v=i||g,k=a||b,N=_.useRef(null),I=_.useRef(null),O=_.useRef(c),z=l!=null,F=Us(l),te=Us(r),ce=Us(u),B=_.useCallback(()=>{if(!N.current||!I.current)return;const K={placement:t,strategy:n,middleware:f};te.current&&(K.platform=te.current),W4(N.current,I.current,K).then(fe=>{const J={...fe,isPositioned:ce.current!==!1};q.current&&!Fi(O.current,J)&&(O.current=J,sm.flushSync(()=>{d(J)}))})},[f,t,n,te,ce]);ai(()=>{u===!1&&O.current.isPositioned&&(O.current.isPositioned=!1,d(K=>({...K,isPositioned:!1})))},[u]);const q=_.useRef(!1);ai(()=>(q.current=!0,()=>{q.current=!1}),[]),ai(()=>{if(v&&(N.current=v),k&&(I.current=k),v&&k){if(F.current)return F.current(v,k,B);B()}},[v,k,B,F,z]);const we=_.useMemo(()=>({reference:N,floating:I,setReference:x,setFloating:$}),[x,$]),oe=_.useMemo(()=>({reference:v,floating:k}),[v,k]),de=_.useMemo(()=>{const K={position:n,left:0,top:0};if(!oe.floating)return K;const fe=Jf(oe.floating,c.x),J=Jf(oe.floating,c.y);return s?{...K,transform:"translate("+fe+"px, "+J+"px)",...D$(oe.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:fe,top:J}},[n,s,oe.floating,c.x,c.y]);return _.useMemo(()=>({...c,update:B,refs:we,elements:oe,floatingStyles:de}),[c,B,we,oe,de])}const Y4=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:o,padding:r}=typeof e=="function"?e(n):e;return o&&t(o)?o.current!=null?Bf({element:o.current,padding:r}).fn(n):{}:o?Bf({element:o,padding:r}).fn(n):{}}}},Q4=(e,t)=>({...Z4(e),options:[e,t]}),X4=(e,t)=>({...F4(e),options:[e,t]}),eD=(e,t)=>({...J4(e),options:[e,t]}),tD=(e,t)=>({...q4(e),options:[e,t]}),rD=(e,t)=>({...V4(e),options:[e,t]}),nD=(e,t)=>({...B4(e),options:[e,t]}),oD=(e,t)=>({...Y4(e),options:[e,t]});var iD="Arrow",U$=_.forwardRef((e,t)=>{const{children:n,width:o=10,height:r=5,...i}=e;return m.jsx(Ce.svg,{...i,ref:t,width:o,height:r,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:m.jsx("polygon",{points:"0,0 30,0 15,10"})})});U$.displayName=iD;var aD=U$;function sD(e){const[t,n]=_.useState(void 0);return lt(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const o=new ResizeObserver(r=>{if(!Array.isArray(r)||!r.length)return;const i=r[0];let a,s;if("borderBoxSize"in i){const l=i.borderBoxSize,u=Array.isArray(l)?l[0]:l;a=u.inlineSize,s=u.blockSize}else a=e.offsetWidth,s=e.offsetHeight;n({width:a,height:s})});return o.observe(e,{box:"border-box"}),()=>o.unobserve(e)}else n(void 0)},[e]),t}var nd="Popper",[L$,Qa]=Po(nd),[uD,Z$]=L$(nd),F$=e=>{const{__scopePopper:t,children:n}=e,[o,r]=_.useState(null);return m.jsx(uD,{scope:t,anchor:o,onAnchorChange:r,children:n})};F$.displayName=nd;var q$="PopperAnchor",V$=_.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:o,...r}=e,i=Z$(q$,n),a=_.useRef(null),s=Ge(t,a),l=_.useRef(null);return _.useEffect(()=>{const u=l.current;l.current=o?.current||a.current,u!==l.current&&i.onAnchorChange(l.current)}),o?null:m.jsx(Ce.div,{...r,ref:s})});V$.displayName=q$;var od="PopperContent",[lD,cD]=L$(od),B$=_.forwardRef((e,t)=>{const{__scopePopper:n,side:o="bottom",sideOffset:r=0,align:i="center",alignOffset:a=0,arrowPadding:s=0,avoidCollisions:l=!0,collisionBoundary:u=[],collisionPadding:c=0,sticky:d="partial",hideWhenDetached:f=!1,updatePositionStrategy:p="optimized",onPlaced:g,...h}=e,b=Z$(od,n),[y,x]=_.useState(null),$=Ge(t,xe=>x(xe)),[v,k]=_.useState(null),N=sD(v),I=N?.width??0,O=N?.height??0,z=o+(i!=="center"?"-"+i:""),F=typeof c=="number"?c:{top:0,right:0,bottom:0,left:0,...c},te=Array.isArray(u)?u:[u],ce=te.length>0,B={padding:F,boundary:te.filter(pD),altBoundary:ce},{refs:q,floatingStyles:we,placement:oe,isPositioned:de,middlewareData:K}=K4({strategy:"fixed",placement:z,whileElementsMounted:(...xe)=>L4(...xe,{animationFrame:p==="always"}),elements:{reference:b.anchor},middleware:[Q4({mainAxis:r+O,alignmentAxis:a}),l&&X4({mainAxis:!0,crossAxis:!1,limiter:d==="partial"?eD():void 0,...B}),l&&tD({...B}),rD({...B,apply:({elements:xe,rects:Ro,availableWidth:ss,availableHeight:fn})=>{const{width:pt,height:zo}=Ro.reference,je=xe.floating.style;je.setProperty("--radix-popper-available-width",`${ss}px`),je.setProperty("--radix-popper-available-height",`${fn}px`),je.setProperty("--radix-popper-anchor-width",`${pt}px`),je.setProperty("--radix-popper-anchor-height",`${zo}px`)}}),v&&oD({element:v,padding:s}),fD({arrowWidth:I,arrowHeight:O}),f&&nD({strategy:"referenceHidden",...B})]}),[fe,J]=H$(oe),Ue=Sr(g);lt(()=>{de&&Ue?.()},[de,Ue]);const ye=K.arrow?.x,Le=K.arrow?.y,U=K.arrow?.centerOffset!==0,[Q,me]=_.useState();return lt(()=>{y&&me(window.getComputedStyle(y).zIndex)},[y]),m.jsx("div",{ref:q.setFloating,"data-radix-popper-content-wrapper":"",style:{...we,transform:de?we.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Q,"--radix-popper-transform-origin":[K.transformOrigin?.x,K.transformOrigin?.y].join(" "),...K.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:m.jsx(lD,{scope:n,placedSide:fe,onArrowChange:k,arrowX:ye,arrowY:Le,shouldHideArrow:U,children:m.jsx(Ce.div,{"data-side":fe,"data-align":J,...h,ref:$,style:{...h.style,animation:de?void 0:"none"}})})})});B$.displayName=od;var J$="PopperArrow",dD={top:"bottom",right:"left",bottom:"top",left:"right"},W$=_.forwardRef(function(t,n){const{__scopePopper:o,...r}=t,i=cD(J$,o),a=dD[i.placedSide];return m.jsx("span",{ref:i.onArrowChange,style:{position:"absolute",left:i.arrowX,top:i.arrowY,[a]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[i.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[i.placedSide],visibility:i.shouldHideArrow?"hidden":void 0},children:m.jsx(aD,{...r,ref:n,style:{...r.style,display:"block"}})})});W$.displayName=J$;function pD(e){return e!==null}var fD=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:o,middlewareData:r}=t,a=r.arrow?.centerOffset!==0,s=a?0:e.arrowWidth,l=a?0:e.arrowHeight,[u,c]=H$(n),d={start:"0%",center:"50%",end:"100%"}[c],f=(r.arrow?.x??0)+s/2,p=(r.arrow?.y??0)+l/2;let g="",h="";return u==="bottom"?(g=a?d:`${f}px`,h=`${-l}px`):u==="top"?(g=a?d:`${f}px`,h=`${o.floating.height+l}px`):u==="right"?(g=`${-l}px`,h=a?d:`${p}px`):u==="left"&&(g=`${o.floating.width+l}px`,h=a?d:`${p}px`),{data:{x:g,y:h}}}});function H$(e){const[t,n="center"]=e.split("-");return[t,n]}var G$=F$,id=V$,K$=B$,Y$=W$,mD="Portal",Xa=_.forwardRef((e,t)=>{const{container:n,...o}=e,[r,i]=_.useState(!1);lt(()=>i(!0),[]);const a=n||r&&globalThis?.document?.body;return a?am.createPortal(m.jsx(Ce.div,{...o,ref:t}),a):null});Xa.displayName=mD;function hD(e,t){return _.useReducer((n,o)=>t[n][o]??n,e)}var Gt=e=>{const{present:t,children:n}=e,o=gD(t),r=typeof n=="function"?n({present:o.isPresent}):_.Children.only(n),i=Ge(o.ref,vD(r));return typeof n=="function"||o.isPresent?_.cloneElement(r,{ref:i}):null};Gt.displayName="Presence";function gD(e){const[t,n]=_.useState(),o=_.useRef(null),r=_.useRef(e),i=_.useRef("none"),a=e?"mounted":"unmounted",[s,l]=hD(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return _.useEffect(()=>{const u=Ko(o.current);i.current=s==="mounted"?u:"none"},[s]),lt(()=>{const u=o.current,c=r.current;if(c!==e){const f=i.current,p=Ko(u);e?l("MOUNT"):p==="none"||u?.display==="none"?l("UNMOUNT"):l(c&&f!==p?"ANIMATION_OUT":"UNMOUNT"),r.current=e}},[e,l]),lt(()=>{if(t){let u;const c=t.ownerDocument.defaultView??window,d=p=>{const h=Ko(o.current).includes(CSS.escape(p.animationName));if(p.target===t&&h&&(l("ANIMATION_END"),!r.current)){const b=t.style.animationFillMode;t.style.animationFillMode="forwards",u=c.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=b)})}},f=p=>{p.target===t&&(i.current=Ko(o.current))};return t.addEventListener("animationstart",f),t.addEventListener("animationcancel",d),t.addEventListener("animationend",d),()=>{c.clearTimeout(u),t.removeEventListener("animationstart",f),t.removeEventListener("animationcancel",d),t.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(s),ref:_.useCallback(u=>{o.current=u?getComputedStyle(u):null,n(u)},[])}}function Ko(e){return e?.animationName||"none"}function vD(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var yD=_[" useInsertionEffect ".trim().toString()]||lt;function es({prop:e,defaultProp:t,onChange:n=()=>{},caller:o}){const[r,i,a]=bD({defaultProp:t,onChange:n}),s=e!==void 0,l=s?e:r;{const c=_.useRef(e!==void 0);_.useEffect(()=>{const d=c.current;d!==s&&console.warn(`${o} is changing from ${d?"controlled":"uncontrolled"} to ${s?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),c.current=s},[s,o])}const u=_.useCallback(c=>{if(s){const d=_D(c)?c(e):c;d!==e&&a.current?.(d)}else i(c)},[s,e,i,a]);return[l,u]}function bD({defaultProp:e,onChange:t}){const[n,o]=_.useState(e),r=_.useRef(n),i=_.useRef(t);return yD(()=>{i.current=t},[t]),_.useEffect(()=>{r.current!==n&&(i.current?.(n),r.current=n)},[n,r]),[n,o,i]}function _D(e){return typeof e=="function"}var wD=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),xD="VisuallyHidden",Q$=_.forwardRef((e,t)=>m.jsx(Ce.span,{...e,ref:t,style:{...wD,...e.style}}));Q$.displayName=xD;var $D=Q$,[ts]=Po("Tooltip",[Qa]),rs=Qa(),X$="TooltipProvider",SD=700,ju="tooltip.open",[ID,ad]=ts(X$),eS=e=>{const{__scopeTooltip:t,delayDuration:n=SD,skipDelayDuration:o=300,disableHoverableContent:r=!1,children:i}=e,a=_.useRef(!0),s=_.useRef(!1),l=_.useRef(0);return _.useEffect(()=>{const u=l.current;return()=>window.clearTimeout(u)},[]),m.jsx(ID,{scope:t,isOpenDelayedRef:a,delayDuration:n,onOpen:_.useCallback(()=>{window.clearTimeout(l.current),a.current=!1},[]),onClose:_.useCallback(()=>{window.clearTimeout(l.current),l.current=window.setTimeout(()=>a.current=!0,o)},[o]),isPointerInTransitRef:s,onPointerInTransitChange:_.useCallback(u=>{s.current=u},[]),disableHoverableContent:r,children:i})};eS.displayName=X$;var Qn="Tooltip",[kD,jo]=ts(Qn),tS=e=>{const{__scopeTooltip:t,children:n,open:o,defaultOpen:r,onOpenChange:i,disableHoverableContent:a,delayDuration:s}=e,l=ad(Qn,e.__scopeTooltip),u=rs(t),[c,d]=_.useState(null),f=qr(),p=_.useRef(0),g=a??l.disableHoverableContent,h=s??l.delayDuration,b=_.useRef(!1),[y,x]=es({prop:o,defaultProp:r??!1,onChange:I=>{I?(l.onOpen(),document.dispatchEvent(new CustomEvent(ju))):l.onClose(),i?.(I)},caller:Qn}),$=_.useMemo(()=>y?b.current?"delayed-open":"instant-open":"closed",[y]),v=_.useCallback(()=>{window.clearTimeout(p.current),p.current=0,b.current=!1,x(!0)},[x]),k=_.useCallback(()=>{window.clearTimeout(p.current),p.current=0,x(!1)},[x]),N=_.useCallback(()=>{window.clearTimeout(p.current),p.current=window.setTimeout(()=>{b.current=!0,x(!0),p.current=0},h)},[h,x]);return _.useEffect(()=>()=>{p.current&&(window.clearTimeout(p.current),p.current=0)},[]),m.jsx(G$,{...u,children:m.jsx(kD,{scope:t,contentId:f,open:y,stateAttribute:$,trigger:c,onTriggerChange:d,onTriggerEnter:_.useCallback(()=>{l.isOpenDelayedRef.current?N():v()},[l.isOpenDelayedRef,N,v]),onTriggerLeave:_.useCallback(()=>{g?k():(window.clearTimeout(p.current),p.current=0)},[k,g]),onOpen:v,onClose:k,disableHoverableContent:g,children:n})})};tS.displayName=Qn;var Au="TooltipTrigger",rS=_.forwardRef((e,t)=>{const{__scopeTooltip:n,...o}=e,r=jo(Au,n),i=ad(Au,n),a=rs(n),s=_.useRef(null),l=Ge(t,s,r.onTriggerChange),u=_.useRef(!1),c=_.useRef(!1),d=_.useCallback(()=>u.current=!1,[]);return _.useEffect(()=>()=>document.removeEventListener("pointerup",d),[d]),m.jsx(id,{asChild:!0,...a,children:m.jsx(Ce.button,{"aria-describedby":r.open?r.contentId:void 0,"data-state":r.stateAttribute,...o,ref:l,onPointerMove:Oe(e.onPointerMove,f=>{f.pointerType!=="touch"&&!c.current&&!i.isPointerInTransitRef.current&&(r.onTriggerEnter(),c.current=!0)}),onPointerLeave:Oe(e.onPointerLeave,()=>{r.onTriggerLeave(),c.current=!1}),onPointerDown:Oe(e.onPointerDown,()=>{r.open&&r.onClose(),u.current=!0,document.addEventListener("pointerup",d,{once:!0})}),onFocus:Oe(e.onFocus,()=>{u.current||r.onOpen()}),onBlur:Oe(e.onBlur,r.onClose),onClick:Oe(e.onClick,r.onClose)})})});rS.displayName=Au;var sd="TooltipPortal",[ED,TD]=ts(sd,{forceMount:void 0}),nS=e=>{const{__scopeTooltip:t,forceMount:n,children:o,container:r}=e,i=jo(sd,t);return m.jsx(ED,{scope:t,forceMount:n,children:m.jsx(Gt,{present:n||i.open,children:m.jsx(Xa,{asChild:!0,container:r,children:o})})})};nS.displayName=sd;var on="TooltipContent",oS=_.forwardRef((e,t)=>{const n=TD(on,e.__scopeTooltip),{forceMount:o=n.forceMount,side:r="top",...i}=e,a=jo(on,e.__scopeTooltip);return m.jsx(Gt,{present:o||a.open,children:a.disableHoverableContent?m.jsx(iS,{side:r,...i,ref:t}):m.jsx(OD,{side:r,...i,ref:t})})}),OD=_.forwardRef((e,t)=>{const n=jo(on,e.__scopeTooltip),o=ad(on,e.__scopeTooltip),r=_.useRef(null),i=Ge(t,r),[a,s]=_.useState(null),{trigger:l,onClose:u}=n,c=r.current,{onPointerInTransitChange:d}=o,f=_.useCallback(()=>{s(null),d(!1)},[d]),p=_.useCallback((g,h)=>{const b=g.currentTarget,y={x:g.clientX,y:g.clientY},x=jD(y,b.getBoundingClientRect()),$=AD(y,x),v=RD(h.getBoundingClientRect()),k=MD([...$,...v]);s(k),d(!0)},[d]);return _.useEffect(()=>()=>f(),[f]),_.useEffect(()=>{if(l&&c){const g=b=>p(b,c),h=b=>p(b,l);return l.addEventListener("pointerleave",g),c.addEventListener("pointerleave",h),()=>{l.removeEventListener("pointerleave",g),c.removeEventListener("pointerleave",h)}}},[l,c,p,f]),_.useEffect(()=>{if(a){const g=h=>{const b=h.target,y={x:h.clientX,y:h.clientY},x=l?.contains(b)||c?.contains(b),$=!zD(y,a);x?f():$&&(f(),u())};return document.addEventListener("pointermove",g),()=>document.removeEventListener("pointermove",g)}},[l,c,a,u,f]),m.jsx(iS,{...e,ref:i})}),[ND,PD]=ts(Qn,{isInside:!1}),CD=jM("TooltipContent"),iS=_.forwardRef((e,t)=>{const{__scopeTooltip:n,children:o,"aria-label":r,onEscapeKeyDown:i,onPointerDownOutside:a,...s}=e,l=jo(on,n),u=rs(n),{onClose:c}=l;return _.useEffect(()=>(document.addEventListener(ju,c),()=>document.removeEventListener(ju,c)),[c]),_.useEffect(()=>{if(l.trigger){const d=f=>{f.target?.contains(l.trigger)&&c()};return window.addEventListener("scroll",d,{capture:!0}),()=>window.removeEventListener("scroll",d,{capture:!0})}},[l.trigger,c]),m.jsx(Ha,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:a,onFocusOutside:d=>d.preventDefault(),onDismiss:c,children:m.jsxs(K$,{"data-state":l.stateAttribute,...u,...s,ref:t,style:{...s.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[m.jsx(CD,{children:o}),m.jsx(ND,{scope:n,isInside:!0,children:m.jsx($D,{id:l.contentId,role:"tooltip",children:r||o})})]})})});oS.displayName=on;var aS="TooltipArrow",sS=_.forwardRef((e,t)=>{const{__scopeTooltip:n,...o}=e,r=rs(n);return PD(aS,n).isInside?null:m.jsx(Y$,{...r,...o,ref:t})});sS.displayName=aS;function jD(e,t){const n=Math.abs(t.top-e.y),o=Math.abs(t.bottom-e.y),r=Math.abs(t.right-e.x),i=Math.abs(t.left-e.x);switch(Math.min(n,o,r,i)){case i:return"left";case r:return"right";case n:return"top";case o:return"bottom";default:throw new Error("unreachable")}}function AD(e,t,n=5){const o=[];switch(t){case"top":o.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":o.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":o.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":o.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return o}function RD(e){const{top:t,right:n,bottom:o,left:r}=e;return[{x:r,y:t},{x:n,y:t},{x:n,y:o},{x:r,y:o}]}function zD(e,t){const{x:n,y:o}=e;let r=!1;for(let i=0,a=t.length-1;i<t.length;a=i++){const s=t[i],l=t[a],u=s.x,c=s.y,d=l.x,f=l.y;c>o!=f>o&&n<(d-u)*(o-c)/(f-c)+u&&(r=!r)}return r}function MD(e){const t=e.slice();return t.sort((n,o)=>n.x<o.x?-1:n.x>o.x?1:n.y<o.y?-1:n.y>o.y?1:0),DD(t)}function DD(e){if(e.length<=1)return e.slice();const t=[];for(let o=0;o<e.length;o++){const r=e[o];for(;t.length>=2;){const i=t[t.length-1],a=t[t.length-2];if((i.x-a.x)*(r.y-a.y)>=(i.y-a.y)*(r.x-a.x))t.pop();else break}t.push(r)}t.pop();const n=[];for(let o=e.length-1;o>=0;o--){const r=e[o];for(;n.length>=2;){const i=n[n.length-1],a=n[n.length-2];if((i.x-a.x)*(r.y-a.y)>=(i.y-a.y)*(r.x-a.x))n.pop();else break}n.push(r)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var UD=eS,LD=tS,ZD=rS,FD=nS,qD=oS,VD=sS;function uS({delayDuration:e=0,...t}){return m.jsx(UD,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function ud({...e}){return m.jsx(uS,{children:m.jsx(LD,{"data-slot":"tooltip",...e})})}function ld({...e}){return m.jsx(ZD,{"data-slot":"tooltip-trigger",...e})}function cd({className:e,sideOffset:t=0,children:n,...o}){return m.jsx(FD,{children:m.jsxs(qD,{"data-slot":"tooltip-content",sideOffset:t,className:T.cn("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-20 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...o,children:[n,m.jsx(VD,{className:"bg-foreground fill-foreground z-20 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-[2px]"})]})})}const ct=D.forwardRef(({children:e,tooltip:t,side:n="bottom",align:o="center",className:r,...i},a)=>m.jsxs(ud,{children:[m.jsx(ld,{asChild:!0,children:m.jsxs($t,{variant:"ghost",size:"icon",...i,className:T.cn("aui-button-icon size-6 p-1",r),ref:a,children:[m.jsx(IM,{children:e}),m.jsx("span",{className:"aui-sr-only sr-only",children:t})]})}),m.jsx(cd,{side:n,align:o,children:t})]}));ct.displayName="TooltipIconButton";function BD(e){return D.useMemo(()=>e.reduce((t,n)=>(t?.[n.language]&&!n.overrideExisting||(t={...t,[n.language]:{CodeHeader:n.Header??(()=>null),SyntaxHighlighter:n.Component??void 0}}),t),{}),[e])}const JD=()=>{const{plugins:e}=T.useElements(),t=BD(e);return m.jsx(Ws.MarkdownTextPrimitive,{remarkPlugins:[_0],className:"aui-md",components:GD,componentsByLanguage:t})},lS=D.memo(JD),WD=({language:e,code:t})=>{const o=L.useAssistantState(({message:s})=>s).status?.type==="complete",{isCopied:r,copyToClipboard:i}=HD(),a=()=>{!t||r||i(t)};return o?m.jsxs("div",{className:"aui-code-header-root bg-muted-foreground/15 text-foreground dark:bg-muted-foreground/20 mt-4 flex items-center justify-between gap-4 rounded-t-lg px-4 py-2 text-sm font-semibold",children:[m.jsx("span",{className:"aui-code-header-language lowercase [&>span]:text-xs",children:e}),m.jsxs(ct,{tooltip:"Copy",onClick:a,children:[!r&&m.jsx(Du,{}),r&&m.jsx(rr,{})]})]}):null},HD=({copiedDuration:e=3e3}={})=>{const[t,n]=D.useState(!1);return{isCopied:t,copyToClipboard:r=>{r&&navigator.clipboard.writeText(r).then(()=>{n(!0),setTimeout(()=>n(!1),e)})}}},GD=Ws.unstable_memoizeMarkdownComponents({h1:({className:e,...t})=>m.jsx("h1",{className:T.cn("aui-md-h1 mb-8 scroll-m-20 text-4xl font-extrabold tracking-tight last:mb-0",e),...t}),h2:({className:e,...t})=>m.jsx("h2",{className:T.cn("aui-md-h2 mt-8 mb-4 scroll-m-20 text-3xl font-semibold tracking-tight first:mt-0 last:mb-0",e),...t}),h3:({className:e,...t})=>m.jsx("h3",{className:T.cn("aui-md-h3 mt-6 mb-4 scroll-m-20 text-2xl font-semibold tracking-tight first:mt-0 last:mb-0",e),...t}),h4:({className:e,...t})=>m.jsx("h4",{className:T.cn("aui-md-h4 mt-6 mb-4 scroll-m-20 text-xl font-semibold tracking-tight first:mt-0 last:mb-0",e),...t}),h5:({className:e,...t})=>m.jsx("h5",{className:T.cn("aui-md-h5 my-4 text-lg font-semibold first:mt-0 last:mb-0",e),...t}),h6:({className:e,...t})=>m.jsx("h6",{className:T.cn("aui-md-h6 my-4 font-semibold first:mt-0 last:mb-0",e),...t}),p:({className:e,...t})=>m.jsx("p",{className:T.cn("aui-md-p mt-5 mb-5 leading-7 first:mt-0 last:mb-0",e),...t}),a:({className:e,...t})=>m.jsx("a",{className:T.cn("aui-md-a text-primary font-medium underline underline-offset-4",e),...t}),blockquote:({className:e,...t})=>m.jsx("blockquote",{className:T.cn("aui-md-blockquote border-l-2 pl-6 italic",e),...t}),ul:({className:e,...t})=>m.jsx("ul",{className:T.cn("aui-md-ul my-5 ml-6 list-disc [&>li]:mt-2",e),...t}),ol:({className:e,...t})=>m.jsx("ol",{className:T.cn("aui-md-ol my-5 ml-6 list-decimal [&>li]:mt-2",e),...t}),hr:({className:e,...t})=>m.jsx("hr",{className:T.cn("aui-md-hr my-5 border-b",e),...t}),table:({className:e,...t})=>m.jsx("table",{className:T.cn("aui-md-table my-5 w-full border-separate border-spacing-0 overflow-y-auto",e),...t}),th:({className:e,...t})=>m.jsx("th",{className:T.cn("aui-md-th bg-muted px-4 py-2 text-left font-bold first:rounded-tl-lg last:rounded-tr-lg [[align=center]]:text-center [[align=right]]:text-right",e),...t}),td:({className:e,...t})=>m.jsx("td",{className:T.cn("aui-md-td border-b border-l px-4 py-2 text-left last:border-r [[align=center]]:text-center [[align=right]]:text-right",e),...t}),tr:({className:e,...t})=>m.jsx("tr",{className:T.cn("aui-md-tr m-0 border-b p-0 first:border-t [&:last-child>td:first-child]:rounded-bl-lg [&:last-child>td:last-child]:rounded-br-lg",e),...t}),sup:({className:e,...t})=>m.jsx("sup",{className:T.cn("aui-md-sup [&>a]:text-xs [&>a]:no-underline",e),...t}),pre:({className:e,...t})=>m.jsx("pre",{className:T.cn("aui-md-pre text-foreground bg-muted overflow-x-auto rounded-t-none! rounded-b-lg border border-t-0 p-4",e),...t}),code:function({className:t,...n}){const o=Ws.useIsMarkdownCodeBlock();return m.jsx("code",{className:T.cn(!o&&"aui-md-inline-code bg-muted rounded border font-semibold",t),...n})},CodeHeader:WD});var Ls=0;function cS(){_.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Wf()),document.body.insertAdjacentElement("beforeend",e[1]??Wf()),Ls++,()=>{Ls===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Ls--}},[])}function Wf(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Zs="focusScope.autoFocusOnMount",Fs="focusScope.autoFocusOnUnmount",Hf={bubbles:!1,cancelable:!0},KD="FocusScope",dd=_.forwardRef((e,t)=>{const{loop:n=!1,trapped:o=!1,onMountAutoFocus:r,onUnmountAutoFocus:i,...a}=e,[s,l]=_.useState(null),u=Sr(r),c=Sr(i),d=_.useRef(null),f=Ge(t,h=>l(h)),p=_.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;_.useEffect(()=>{if(o){let h=function($){if(p.paused||!s)return;const v=$.target;s.contains(v)?d.current=v:Qt(d.current,{select:!0})},b=function($){if(p.paused||!s)return;const v=$.relatedTarget;v!==null&&(s.contains(v)||Qt(d.current,{select:!0}))},y=function($){if(document.activeElement===document.body)for(const k of $)k.removedNodes.length>0&&Qt(s)};document.addEventListener("focusin",h),document.addEventListener("focusout",b);const x=new MutationObserver(y);return s&&x.observe(s,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",h),document.removeEventListener("focusout",b),x.disconnect()}}},[o,s,p.paused]),_.useEffect(()=>{if(s){Kf.add(p);const h=document.activeElement;if(!s.contains(h)){const y=new CustomEvent(Zs,Hf);s.addEventListener(Zs,u),s.dispatchEvent(y),y.defaultPrevented||(YD(rU(dS(s)),{select:!0}),document.activeElement===h&&Qt(s))}return()=>{s.removeEventListener(Zs,u),setTimeout(()=>{const y=new CustomEvent(Fs,Hf);s.addEventListener(Fs,c),s.dispatchEvent(y),y.defaultPrevented||Qt(h??document.body,{select:!0}),s.removeEventListener(Fs,c),Kf.remove(p)},0)}}},[s,u,c,p]);const g=_.useCallback(h=>{if(!n&&!o||p.paused)return;const b=h.key==="Tab"&&!h.altKey&&!h.ctrlKey&&!h.metaKey,y=document.activeElement;if(b&&y){const x=h.currentTarget,[$,v]=QD(x);$&&v?!h.shiftKey&&y===v?(h.preventDefault(),n&&Qt($,{select:!0})):h.shiftKey&&y===$&&(h.preventDefault(),n&&Qt(v,{select:!0})):y===x&&h.preventDefault()}},[n,o,p.paused]);return m.jsx(Ce.div,{tabIndex:-1,...a,ref:f,onKeyDown:g})});dd.displayName=KD;function YD(e,{select:t=!1}={}){const n=document.activeElement;for(const o of e)if(Qt(o,{select:t}),document.activeElement!==n)return}function QD(e){const t=dS(e),n=Gf(t,e),o=Gf(t.reverse(),e);return[n,o]}function dS(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:o=>{const r=o.tagName==="INPUT"&&o.type==="hidden";return o.disabled||o.hidden||r?NodeFilter.FILTER_SKIP:o.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Gf(e,t){for(const n of e)if(!XD(n,{upTo:t}))return n}function XD(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function eU(e){return e instanceof HTMLInputElement&&"select"in e}function Qt(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&eU(e)&&t&&e.select()}}var Kf=tU();function tU(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Yf(e,t),e.unshift(t)},remove(t){e=Yf(e,t),e[0]?.resume()}}}function Yf(e,t){const n=[...e],o=n.indexOf(t);return o!==-1&&n.splice(o,1),n}function rU(e){return e.filter(t=>t.tagName!=="A")}var nU=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Rr=new WeakMap,Yo=new WeakMap,Qo={},qs=0,pS=function(e){return e&&(e.host||pS(e.parentNode))},oU=function(e,t){return t.map(function(n){if(e.contains(n))return n;var o=pS(n);return o&&e.contains(o)?o:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},iU=function(e,t,n,o){var r=oU(t,Array.isArray(e)?e:[e]);Qo[n]||(Qo[n]=new WeakMap);var i=Qo[n],a=[],s=new Set,l=new Set(r),u=function(d){!d||s.has(d)||(s.add(d),u(d.parentNode))};r.forEach(u);var c=function(d){!d||l.has(d)||Array.prototype.forEach.call(d.children,function(f){if(s.has(f))c(f);else try{var p=f.getAttribute(o),g=p!==null&&p!=="false",h=(Rr.get(f)||0)+1,b=(i.get(f)||0)+1;Rr.set(f,h),i.set(f,b),a.push(f),h===1&&g&&Yo.set(f,!0),b===1&&f.setAttribute(n,"true"),g||f.setAttribute(o,"true")}catch(y){console.error("aria-hidden: cannot operate on ",f,y)}})};return c(t),s.clear(),qs++,function(){a.forEach(function(d){var f=Rr.get(d)-1,p=i.get(d)-1;Rr.set(d,f),i.set(d,p),f||(Yo.has(d)||d.removeAttribute(o),Yo.delete(d)),p||d.removeAttribute(n)}),qs--,qs||(Rr=new WeakMap,Rr=new WeakMap,Yo=new WeakMap,Qo={})}},fS=function(e,t,n){n===void 0&&(n="data-aria-hidden");var o=Array.from(Array.isArray(e)?e:[e]),r=nU(e);return r?(o.push.apply(o,Array.from(r.querySelectorAll("[aria-live], script"))),iU(o,r,n,"aria-hidden")):function(){return null}},Pt=function(){return Pt=Object.assign||function(t){for(var n,o=1,r=arguments.length;o<r;o++){n=arguments[o];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},Pt.apply(this,arguments)};function mS(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]]);return n}function aU(e,t,n){if(n||arguments.length===2)for(var o=0,r=t.length,i;o<r;o++)(i||!(o in t))&&(i||(i=Array.prototype.slice.call(t,0,o)),i[o]=t[o]);return e.concat(i||Array.prototype.slice.call(t))}var si="right-scroll-bar-position",ui="width-before-scroll-bar",sU="with-scroll-bars-hidden",uU="--removed-body-scroll-bar-size";function Vs(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function lU(e,t){var n=D.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(o){var r=n.value;r!==o&&(n.value=o,n.callback(o,r))}}}})[0];return n.callback=t,n.facade}var cU=typeof window<"u"?_.useLayoutEffect:_.useEffect,Qf=new WeakMap;function dU(e,t){var n=lU(null,function(o){return e.forEach(function(r){return Vs(r,o)})});return cU(function(){var o=Qf.get(n);if(o){var r=new Set(o),i=new Set(e),a=n.current;r.forEach(function(s){i.has(s)||Vs(s,null)}),i.forEach(function(s){r.has(s)||Vs(s,a)})}Qf.set(n,e)},[e]),n}function pU(e){return e}function fU(e,t){t===void 0&&(t=pU);var n=[],o=!1,r={read:function(){if(o)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(i){var a=t(i,o);return n.push(a),function(){n=n.filter(function(s){return s!==a})}},assignSyncMedium:function(i){for(o=!0;n.length;){var a=n;n=[],a.forEach(i)}n={push:function(s){return i(s)},filter:function(){return n}}},assignMedium:function(i){o=!0;var a=[];if(n.length){var s=n;n=[],s.forEach(i),a=n}var l=function(){var c=a;a=[],c.forEach(i)},u=function(){return Promise.resolve().then(l)};u(),n={push:function(c){a.push(c),u()},filter:function(c){return a=a.filter(c),n}}}};return r}function mU(e){e===void 0&&(e={});var t=fU(null);return t.options=Pt({async:!0,ssr:!1},e),t}var hS=function(e){var t=e.sideCar,n=mS(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var o=t.read();if(!o)throw new Error("Sidecar medium not found");return _.createElement(o,Pt({},n))};hS.isSideCarExport=!0;function hU(e,t){return e.useMedium(t),hS}var gS=mU(),Bs=function(){},ns=_.forwardRef(function(e,t){var n=_.useRef(null),o=_.useState({onScrollCapture:Bs,onWheelCapture:Bs,onTouchMoveCapture:Bs}),r=o[0],i=o[1],a=e.forwardProps,s=e.children,l=e.className,u=e.removeScrollBar,c=e.enabled,d=e.shards,f=e.sideCar,p=e.noRelative,g=e.noIsolation,h=e.inert,b=e.allowPinchZoom,y=e.as,x=y===void 0?"div":y,$=e.gapMode,v=mS(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),k=f,N=dU([n,t]),I=Pt(Pt({},v),r);return _.createElement(_.Fragment,null,c&&_.createElement(k,{sideCar:gS,removeScrollBar:u,shards:d,noRelative:p,noIsolation:g,inert:h,setCallbacks:i,allowPinchZoom:!!b,lockRef:n,gapMode:$}),a?_.cloneElement(_.Children.only(s),Pt(Pt({},I),{ref:N})):_.createElement(x,Pt({},I,{className:l,ref:N}),s))});ns.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};ns.classNames={fullWidth:ui,zeroRight:si};var gU=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function vU(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=gU();return t&&e.setAttribute("nonce",t),e}function yU(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function bU(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var _U=function(){var e=0,t=null;return{add:function(n){e==0&&(t=vU())&&(yU(t,n),bU(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},wU=function(){var e=_U();return function(t,n){_.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},vS=function(){var e=wU(),t=function(n){var o=n.styles,r=n.dynamic;return e(o,r),null};return t},xU={left:0,top:0,right:0,gap:0},Js=function(e){return parseInt(e||"",10)||0},$U=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],o=t[e==="padding"?"paddingTop":"marginTop"],r=t[e==="padding"?"paddingRight":"marginRight"];return[Js(n),Js(o),Js(r)]},SU=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return xU;var t=$U(e),n=document.documentElement.clientWidth,o=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,o-n+t[2]-t[0])}},IU=vS(),Br="data-scroll-locked",kU=function(e,t,n,o){var r=e.left,i=e.top,a=e.right,s=e.gap;return n===void 0&&(n="margin"),`
|
|
97
|
+
.`.concat(sU,` {
|
|
98
98
|
overflow: hidden `).concat(o,`;
|
|
99
99
|
padding-right: `).concat(s,"px ").concat(o,`;
|
|
100
100
|
}
|
|
@@ -128,16 +128,16 @@ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the toke
|
|
|
128
128
|
}
|
|
129
129
|
|
|
130
130
|
body[`).concat(Br,`] {
|
|
131
|
-
`).concat(
|
|
131
|
+
`).concat(uU,": ").concat(s,`px;
|
|
132
132
|
}
|
|
133
|
-
`)},Xf=function(){var e=parseInt(document.body.getAttribute(Br)||"0",10);return isFinite(e)?e:0},
|
|
133
|
+
`)},Xf=function(){var e=parseInt(document.body.getAttribute(Br)||"0",10);return isFinite(e)?e:0},EU=function(){_.useEffect(function(){return document.body.setAttribute(Br,(Xf()+1).toString()),function(){var e=Xf()-1;e<=0?document.body.removeAttribute(Br):document.body.setAttribute(Br,e.toString())}},[])},TU=function(e){var t=e.noRelative,n=e.noImportant,o=e.gapMode,r=o===void 0?"margin":o;EU();var i=_.useMemo(function(){return SU(r)},[r]);return _.createElement(IU,{styles:kU(i,!t,r,n?"":"!important")})},Ru=!1;if(typeof window<"u")try{var Xo=Object.defineProperty({},"passive",{get:function(){return Ru=!0,!0}});window.addEventListener("test",Xo,Xo),window.removeEventListener("test",Xo,Xo)}catch{Ru=!1}var zr=Ru?{passive:!1}:!1,OU=function(e){return e.tagName==="TEXTAREA"},yS=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!OU(e)&&n[t]==="visible")},NU=function(e){return yS(e,"overflowY")},PU=function(e){return yS(e,"overflowX")},em=function(e,t){var n=t.ownerDocument,o=t;do{typeof ShadowRoot<"u"&&o instanceof ShadowRoot&&(o=o.host);var r=bS(e,o);if(r){var i=_S(e,o),a=i[1],s=i[2];if(a>s)return!0}o=o.parentNode}while(o&&o!==n.body);return!1},CU=function(e){var t=e.scrollTop,n=e.scrollHeight,o=e.clientHeight;return[t,n,o]},jU=function(e){var t=e.scrollLeft,n=e.scrollWidth,o=e.clientWidth;return[t,n,o]},bS=function(e,t){return e==="v"?NU(t):PU(t)},_S=function(e,t){return e==="v"?CU(t):jU(t)},AU=function(e,t){return e==="h"&&t==="rtl"?-1:1},RU=function(e,t,n,o,r){var i=AU(e,window.getComputedStyle(t).direction),a=i*o,s=n.target,l=t.contains(s),u=!1,c=a>0,d=0,f=0;do{if(!s)break;var p=_S(e,s),g=p[0],h=p[1],b=p[2],y=h-b-i*g;(g||y)&&bS(e,s)&&(d+=y,f+=g);var x=s.parentNode;s=x&&x.nodeType===Node.DOCUMENT_FRAGMENT_NODE?x.host:x}while(!l&&s!==document.body||l&&(t.contains(s)||t===s));return(c&&Math.abs(d)<1||!c&&Math.abs(f)<1)&&(u=!0),u},ei=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},tm=function(e){return[e.deltaX,e.deltaY]},rm=function(e){return e&&"current"in e?e.current:e},zU=function(e,t){return e[0]===t[0]&&e[1]===t[1]},MU=function(e){return`
|
|
134
134
|
.block-interactivity-`.concat(e,` {pointer-events: none;}
|
|
135
135
|
.allow-interactivity-`).concat(e,` {pointer-events: all;}
|
|
136
|
-
`)},UU=0,Mr=[];function LU(e){var t=_.useRef([]),n=_.useRef([0,0]),o=_.useRef(),r=_.useState(UU++)[0],i=_.useState(vS)[0],a=_.useRef(e);_.useEffect(function(){a.current=e},[e]),_.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(r));var h=sU([e.lockRef.current],(e.shards||[]).map(rm),!0).filter(Boolean);return h.forEach(function(b){return b.classList.add("allow-interactivity-".concat(r))}),function(){document.body.classList.remove("block-interactivity-".concat(r)),h.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(r))})}}},[e.inert,e.lockRef.current,e.shards]);var s=_.useCallback(function(h,b){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!a.current.allowPinchZoom;var y=ei(h),x=n.current,$="deltaX"in h?h.deltaX:x[0]-y[0],v="deltaY"in h?h.deltaY:x[1]-y[1],k,N=h.target,I=Math.abs($)>Math.abs(v)?"h":"v";if("touches"in h&&I==="h"&&N.type==="range")return!1;var O=em(I,N);if(!O)return!0;if(O?k=I:(k=I==="v"?"h":"v",O=em(I,N)),!O)return!1;if(!o.current&&"changedTouches"in h&&($||v)&&(o.current=k),!k)return!0;var z=o.current||k;return zU(z,b,h,z==="h"?$:v)},[]),l=_.useCallback(function(h){var b=h;if(!(!Mr.length||Mr[Mr.length-1]!==i)){var y="deltaY"in b?tm(b):ei(b),x=t.current.filter(function(k){return k.name===b.type&&(k.target===b.target||b.target===k.shadowParent)&&MU(k.delta,y)})[0];if(x&&x.should){b.cancelable&&b.preventDefault();return}if(!x){var $=(a.current.shards||[]).map(rm).filter(Boolean).filter(function(k){return k.contains(b.target)}),v=$.length>0?s(b,$[0]):!a.current.noIsolation;v&&b.cancelable&&b.preventDefault()}}},[]),u=_.useCallback(function(h,b,y,x){var $={name:h,delta:b,target:y,should:x,shadowParent:ZU(y)};t.current.push($),setTimeout(function(){t.current=t.current.filter(function(v){return v!==$})},1)},[]),c=_.useCallback(function(h){n.current=ei(h),o.current=void 0},[]),d=_.useCallback(function(h){u(h.type,tm(h),h.target,s(h,e.lockRef.current))},[]),f=_.useCallback(function(h){u(h.type,ei(h),h.target,s(h,e.lockRef.current))},[]);_.useEffect(function(){return Mr.push(i),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",l,zr),document.addEventListener("touchmove",l,zr),document.addEventListener("touchstart",c,zr),function(){Mr=Mr.filter(function(h){return h!==i}),document.removeEventListener("wheel",l,zr),document.removeEventListener("touchmove",l,zr),document.removeEventListener("touchstart",c,zr)}},[]);var p=e.removeScrollBar,g=e.inert;return _.createElement(_.Fragment,null,g?_.createElement(i,{styles:DU(r)}):null,p?_.createElement(OU,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function ZU(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const FU=gU(gS,LU);var pd=_.forwardRef(function(e,t){return _.createElement(ns,Pt({},e,{ref:t,sideCar:FU}))});pd.classNames=ns.classNames;var os="Popover",[wS]=Po(os,[Qa]),Ao=Qa(),[qU,pr]=wS(os),xS=e=>{const{__scopePopover:t,children:n,open:o,defaultOpen:r,onOpenChange:i,modal:a=!1}=e,s=Ao(t),l=_.useRef(null),[u,c]=_.useState(!1),[d,f]=es({prop:o,defaultProp:r??!1,onChange:i,caller:os});return m.jsx(G$,{...s,children:m.jsx(qU,{scope:t,contentId:qr(),triggerRef:l,open:d,onOpenChange:f,onOpenToggle:_.useCallback(()=>f(p=>!p),[f]),hasCustomAnchor:u,onCustomAnchorAdd:_.useCallback(()=>c(!0),[]),onCustomAnchorRemove:_.useCallback(()=>c(!1),[]),modal:a,children:n})})};xS.displayName=os;var $S="PopoverAnchor",VU=_.forwardRef((e,t)=>{const{__scopePopover:n,...o}=e,r=pr($S,n),i=Ao(n),{onCustomAnchorAdd:a,onCustomAnchorRemove:s}=r;return _.useEffect(()=>(a(),()=>s()),[a,s]),m.jsx(id,{...i,...o,ref:t})});VU.displayName=$S;var SS="PopoverTrigger",IS=_.forwardRef((e,t)=>{const{__scopePopover:n,...o}=e,r=pr(SS,n),i=Ao(n),a=Ge(t,r.triggerRef),s=m.jsx(Ce.button,{type:"button","aria-haspopup":"dialog","aria-expanded":r.open,"aria-controls":r.contentId,"data-state":NS(r.open),...o,ref:a,onClick:Oe(e.onClick,r.onOpenToggle)});return r.hasCustomAnchor?s:m.jsx(id,{asChild:!0,...i,children:s})});IS.displayName=SS;var fd="PopoverPortal",[BU,JU]=wS(fd,{forceMount:void 0}),kS=e=>{const{__scopePopover:t,forceMount:n,children:o,container:r}=e,i=pr(fd,t);return m.jsx(BU,{scope:t,forceMount:n,children:m.jsx(Gt,{present:n||i.open,children:m.jsx(Xa,{asChild:!0,container:r,children:o})})})};kS.displayName=fd;var an="PopoverContent",ES=_.forwardRef((e,t)=>{const n=JU(an,e.__scopePopover),{forceMount:o=n.forceMount,...r}=e,i=pr(an,e.__scopePopover);return m.jsx(Gt,{present:o||i.open,children:i.modal?m.jsx(HU,{...r,ref:t}):m.jsx(GU,{...r,ref:t})})});ES.displayName=an;var WU=Gc("PopoverContent.RemoveScroll"),HU=_.forwardRef((e,t)=>{const n=pr(an,e.__scopePopover),o=_.useRef(null),r=Ge(t,o),i=_.useRef(!1);return _.useEffect(()=>{const a=o.current;if(a)return fS(a)},[]),m.jsx(pd,{as:WU,allowPinchZoom:!0,children:m.jsx(TS,{...e,ref:r,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Oe(e.onCloseAutoFocus,a=>{a.preventDefault(),i.current||n.triggerRef.current?.focus()}),onPointerDownOutside:Oe(e.onPointerDownOutside,a=>{const s=a.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0,u=s.button===2||l;i.current=u},{checkForDefaultPrevented:!1}),onFocusOutside:Oe(e.onFocusOutside,a=>a.preventDefault(),{checkForDefaultPrevented:!1})})})}),GU=_.forwardRef((e,t)=>{const n=pr(an,e.__scopePopover),o=_.useRef(!1),r=_.useRef(!1);return m.jsx(TS,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{e.onCloseAutoFocus?.(i),i.defaultPrevented||(o.current||n.triggerRef.current?.focus(),i.preventDefault()),o.current=!1,r.current=!1},onInteractOutside:i=>{e.onInteractOutside?.(i),i.defaultPrevented||(o.current=!0,i.detail.originalEvent.type==="pointerdown"&&(r.current=!0));const a=i.target;n.triggerRef.current?.contains(a)&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&r.current&&i.preventDefault()}})}),TS=_.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:o,onOpenAutoFocus:r,onCloseAutoFocus:i,disableOutsidePointerEvents:a,onEscapeKeyDown:s,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:c,...d}=e,f=pr(an,n),p=Ao(n);return cS(),m.jsx(dd,{asChild:!0,loop:!0,trapped:o,onMountAutoFocus:r,onUnmountAutoFocus:i,children:m.jsx(Ha,{asChild:!0,disableOutsidePointerEvents:a,onInteractOutside:c,onEscapeKeyDown:s,onPointerDownOutside:l,onFocusOutside:u,onDismiss:()=>f.onOpenChange(!1),children:m.jsx(K$,{"data-state":NS(f.open),role:"dialog",id:f.contentId,...p,...d,ref:t,style:{...d.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),OS="PopoverClose",KU=_.forwardRef((e,t)=>{const{__scopePopover:n,...o}=e,r=pr(OS,n);return m.jsx(Ce.button,{type:"button",...o,ref:t,onClick:Oe(e.onClick,()=>r.onOpenChange(!1))})});KU.displayName=OS;var YU="PopoverArrow",QU=_.forwardRef((e,t)=>{const{__scopePopover:n,...o}=e,r=Ao(n);return m.jsx(Y$,{...r,...o,ref:t})});QU.displayName=YU;function NS(e){return e?"open":"closed"}var XU=xS,e6=IS,t6=kS,r6=ES;function PS({...e}){return m.jsx(XU,{"data-slot":"popover",...e})}function CS({...e}){return m.jsx(e6,{"data-slot":"popover-trigger",...e})}function jS({className:e,align:t="center",sideOffset:n=4,...o}){return m.jsx(t6,{children:m.jsx(r6,{"data-slot":"popover-content",align:t,sideOffset:n,className:T.cn("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-20 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",e),...o})})}const n6=S$("flex size-5 items-center justify-center rounded-full",{variants:{status:{pending:"border border-dashed border-muted-foreground/50",running:"text-primary",complete:"text-green-600 dark:text-green-500",error:"text-destructive",approval:"text-amber-500"}},defaultVariants:{status:"pending"}});function o6(e){switch(e){case"text/markdown":return"markdown";case"text/html":return"html";case"text/css":return"css";case"application/json":return"json";case"text/javascript":return"javascript";case"text/typescript":return"typescript";case"text/python":return"python";default:return}}function i6(e,t){if(t==="json")try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}return e}function a6(e){return typeof e=="object"&&e!==null&&"content"in e&&Array.isArray(e.content)}function AS({status:e}){return m.jsxs("div",{className:T.cn(n6({status:e})),children:[e==="pending"&&null,e==="running"&&m.jsx(Hs,{className:"size-4 animate-spin"}),e==="complete"&&m.jsx(rr,{className:"size-4"}),e==="error"&&m.jsx(Xn,{className:"size-4"}),e==="approval"&&m.jsx(Hs,{className:"text-muted-foreground size-4 animate-spin"})]})}function s6({content:e}){const[t,n]=D.useState(!1),o=async r=>{r.stopPropagation(),await navigator.clipboard.writeText(e),n(!0),setTimeout(()=>n(!1),2e3)};return m.jsx("button",{onClick:o,className:"text-muted-foreground hover:bg-accent hover:text-foreground rounded p-1 transition-colors","aria-label":"Copy to clipboard",children:t?m.jsx(rr,{className:"size-4"}):m.jsx(Du,{className:"size-4"})})}function RS({text:e,language:t,className:n}){const[o,r]=D.useState(null);return D.useEffect(()=>{t&&w0.codeToHtml(e,{lang:t,theme:"github-dark-default",rootStyle:"background-color: transparent;",transformers:[{pre(i){i.properties.class="w-full py-3 px-4 max-h-[300px] overflow-y-auto whitespace-pre-wrap text-left text-sm"}}]}).then(r)},[e,t]),o?m.jsx("div",{className:T.cn("w-full bg-slate-800/90",n),dangerouslySetInnerHTML:{__html:o}}):m.jsx("pre",{className:T.cn("w-full bg-slate-800/90 px-4 py-3 text-sm whitespace-pre-wrap text-slate-100",n),children:e})}function u6({data:e}){const t=`data:image/png;base64,${e}`;return m.jsx("div",{className:"flex items-center justify-center rounded-lg p-5",style:{backgroundImage:`linear-gradient(45deg, #ccc 25%, transparent 25%),
|
|
136
|
+
`)},DU=0,Mr=[];function UU(e){var t=_.useRef([]),n=_.useRef([0,0]),o=_.useRef(),r=_.useState(DU++)[0],i=_.useState(vS)[0],a=_.useRef(e);_.useEffect(function(){a.current=e},[e]),_.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(r));var h=aU([e.lockRef.current],(e.shards||[]).map(rm),!0).filter(Boolean);return h.forEach(function(b){return b.classList.add("allow-interactivity-".concat(r))}),function(){document.body.classList.remove("block-interactivity-".concat(r)),h.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(r))})}}},[e.inert,e.lockRef.current,e.shards]);var s=_.useCallback(function(h,b){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!a.current.allowPinchZoom;var y=ei(h),x=n.current,$="deltaX"in h?h.deltaX:x[0]-y[0],v="deltaY"in h?h.deltaY:x[1]-y[1],k,N=h.target,I=Math.abs($)>Math.abs(v)?"h":"v";if("touches"in h&&I==="h"&&N.type==="range")return!1;var O=em(I,N);if(!O)return!0;if(O?k=I:(k=I==="v"?"h":"v",O=em(I,N)),!O)return!1;if(!o.current&&"changedTouches"in h&&($||v)&&(o.current=k),!k)return!0;var z=o.current||k;return RU(z,b,h,z==="h"?$:v)},[]),l=_.useCallback(function(h){var b=h;if(!(!Mr.length||Mr[Mr.length-1]!==i)){var y="deltaY"in b?tm(b):ei(b),x=t.current.filter(function(k){return k.name===b.type&&(k.target===b.target||b.target===k.shadowParent)&&zU(k.delta,y)})[0];if(x&&x.should){b.cancelable&&b.preventDefault();return}if(!x){var $=(a.current.shards||[]).map(rm).filter(Boolean).filter(function(k){return k.contains(b.target)}),v=$.length>0?s(b,$[0]):!a.current.noIsolation;v&&b.cancelable&&b.preventDefault()}}},[]),u=_.useCallback(function(h,b,y,x){var $={name:h,delta:b,target:y,should:x,shadowParent:LU(y)};t.current.push($),setTimeout(function(){t.current=t.current.filter(function(v){return v!==$})},1)},[]),c=_.useCallback(function(h){n.current=ei(h),o.current=void 0},[]),d=_.useCallback(function(h){u(h.type,tm(h),h.target,s(h,e.lockRef.current))},[]),f=_.useCallback(function(h){u(h.type,ei(h),h.target,s(h,e.lockRef.current))},[]);_.useEffect(function(){return Mr.push(i),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",l,zr),document.addEventListener("touchmove",l,zr),document.addEventListener("touchstart",c,zr),function(){Mr=Mr.filter(function(h){return h!==i}),document.removeEventListener("wheel",l,zr),document.removeEventListener("touchmove",l,zr),document.removeEventListener("touchstart",c,zr)}},[]);var p=e.removeScrollBar,g=e.inert;return _.createElement(_.Fragment,null,g?_.createElement(i,{styles:MU(r)}):null,p?_.createElement(TU,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function LU(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const ZU=hU(gS,UU);var pd=_.forwardRef(function(e,t){return _.createElement(ns,Pt({},e,{ref:t,sideCar:ZU}))});pd.classNames=ns.classNames;var os="Popover",[wS]=Po(os,[Qa]),Ao=Qa(),[FU,pr]=wS(os),xS=e=>{const{__scopePopover:t,children:n,open:o,defaultOpen:r,onOpenChange:i,modal:a=!1}=e,s=Ao(t),l=_.useRef(null),[u,c]=_.useState(!1),[d,f]=es({prop:o,defaultProp:r??!1,onChange:i,caller:os});return m.jsx(G$,{...s,children:m.jsx(FU,{scope:t,contentId:qr(),triggerRef:l,open:d,onOpenChange:f,onOpenToggle:_.useCallback(()=>f(p=>!p),[f]),hasCustomAnchor:u,onCustomAnchorAdd:_.useCallback(()=>c(!0),[]),onCustomAnchorRemove:_.useCallback(()=>c(!1),[]),modal:a,children:n})})};xS.displayName=os;var $S="PopoverAnchor",qU=_.forwardRef((e,t)=>{const{__scopePopover:n,...o}=e,r=pr($S,n),i=Ao(n),{onCustomAnchorAdd:a,onCustomAnchorRemove:s}=r;return _.useEffect(()=>(a(),()=>s()),[a,s]),m.jsx(id,{...i,...o,ref:t})});qU.displayName=$S;var SS="PopoverTrigger",IS=_.forwardRef((e,t)=>{const{__scopePopover:n,...o}=e,r=pr(SS,n),i=Ao(n),a=Ge(t,r.triggerRef),s=m.jsx(Ce.button,{type:"button","aria-haspopup":"dialog","aria-expanded":r.open,"aria-controls":r.contentId,"data-state":NS(r.open),...o,ref:a,onClick:Oe(e.onClick,r.onOpenToggle)});return r.hasCustomAnchor?s:m.jsx(id,{asChild:!0,...i,children:s})});IS.displayName=SS;var fd="PopoverPortal",[VU,BU]=wS(fd,{forceMount:void 0}),kS=e=>{const{__scopePopover:t,forceMount:n,children:o,container:r}=e,i=pr(fd,t);return m.jsx(VU,{scope:t,forceMount:n,children:m.jsx(Gt,{present:n||i.open,children:m.jsx(Xa,{asChild:!0,container:r,children:o})})})};kS.displayName=fd;var an="PopoverContent",ES=_.forwardRef((e,t)=>{const n=BU(an,e.__scopePopover),{forceMount:o=n.forceMount,...r}=e,i=pr(an,e.__scopePopover);return m.jsx(Gt,{present:o||i.open,children:i.modal?m.jsx(WU,{...r,ref:t}):m.jsx(HU,{...r,ref:t})})});ES.displayName=an;var JU=Gc("PopoverContent.RemoveScroll"),WU=_.forwardRef((e,t)=>{const n=pr(an,e.__scopePopover),o=_.useRef(null),r=Ge(t,o),i=_.useRef(!1);return _.useEffect(()=>{const a=o.current;if(a)return fS(a)},[]),m.jsx(pd,{as:JU,allowPinchZoom:!0,children:m.jsx(TS,{...e,ref:r,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Oe(e.onCloseAutoFocus,a=>{a.preventDefault(),i.current||n.triggerRef.current?.focus()}),onPointerDownOutside:Oe(e.onPointerDownOutside,a=>{const s=a.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0,u=s.button===2||l;i.current=u},{checkForDefaultPrevented:!1}),onFocusOutside:Oe(e.onFocusOutside,a=>a.preventDefault(),{checkForDefaultPrevented:!1})})})}),HU=_.forwardRef((e,t)=>{const n=pr(an,e.__scopePopover),o=_.useRef(!1),r=_.useRef(!1);return m.jsx(TS,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{e.onCloseAutoFocus?.(i),i.defaultPrevented||(o.current||n.triggerRef.current?.focus(),i.preventDefault()),o.current=!1,r.current=!1},onInteractOutside:i=>{e.onInteractOutside?.(i),i.defaultPrevented||(o.current=!0,i.detail.originalEvent.type==="pointerdown"&&(r.current=!0));const a=i.target;n.triggerRef.current?.contains(a)&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&r.current&&i.preventDefault()}})}),TS=_.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:o,onOpenAutoFocus:r,onCloseAutoFocus:i,disableOutsidePointerEvents:a,onEscapeKeyDown:s,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:c,...d}=e,f=pr(an,n),p=Ao(n);return cS(),m.jsx(dd,{asChild:!0,loop:!0,trapped:o,onMountAutoFocus:r,onUnmountAutoFocus:i,children:m.jsx(Ha,{asChild:!0,disableOutsidePointerEvents:a,onInteractOutside:c,onEscapeKeyDown:s,onPointerDownOutside:l,onFocusOutside:u,onDismiss:()=>f.onOpenChange(!1),children:m.jsx(K$,{"data-state":NS(f.open),role:"dialog",id:f.contentId,...p,...d,ref:t,style:{...d.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),OS="PopoverClose",GU=_.forwardRef((e,t)=>{const{__scopePopover:n,...o}=e,r=pr(OS,n);return m.jsx(Ce.button,{type:"button",...o,ref:t,onClick:Oe(e.onClick,()=>r.onOpenChange(!1))})});GU.displayName=OS;var KU="PopoverArrow",YU=_.forwardRef((e,t)=>{const{__scopePopover:n,...o}=e,r=Ao(n);return m.jsx(Y$,{...r,...o,ref:t})});YU.displayName=KU;function NS(e){return e?"open":"closed"}var QU=xS,XU=IS,e6=kS,t6=ES;function PS({...e}){return m.jsx(QU,{"data-slot":"popover",...e})}function CS({...e}){return m.jsx(XU,{"data-slot":"popover-trigger",...e})}function jS({className:e,align:t="center",sideOffset:n=4,...o}){return m.jsx(e6,{children:m.jsx(t6,{"data-slot":"popover-content",align:t,sideOffset:n,className:T.cn("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-20 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",e),...o})})}const r6=S$("flex size-5 items-center justify-center rounded-full",{variants:{status:{pending:"border border-dashed border-muted-foreground/50",running:"text-primary",complete:"text-green-600 dark:text-green-500",error:"text-destructive",approval:"text-amber-500"}},defaultVariants:{status:"pending"}});function n6(e){switch(e){case"text/markdown":return"markdown";case"text/html":return"html";case"text/css":return"css";case"application/json":return"json";case"text/javascript":return"javascript";case"text/typescript":return"typescript";case"text/python":return"python";default:return}}function o6(e,t){if(t==="json")try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}return e}function i6(e){return typeof e=="object"&&e!==null&&"content"in e&&Array.isArray(e.content)}function AS({status:e}){return m.jsxs("div",{className:T.cn(r6({status:e})),children:[e==="pending"&&null,e==="running"&&m.jsx(Hs,{className:"size-4 animate-spin"}),e==="complete"&&m.jsx(rr,{className:"size-4"}),e==="error"&&m.jsx(Xn,{className:"size-4"}),e==="approval"&&m.jsx(Hs,{className:"text-muted-foreground size-4 animate-spin"})]})}function a6({content:e}){const[t,n]=D.useState(!1),o=async r=>{r.stopPropagation(),await navigator.clipboard.writeText(e),n(!0),setTimeout(()=>n(!1),2e3)};return m.jsx("button",{onClick:o,className:"text-muted-foreground hover:bg-accent hover:text-foreground rounded p-1 transition-colors","aria-label":"Copy to clipboard",children:t?m.jsx(rr,{className:"size-4"}):m.jsx(Du,{className:"size-4"})})}function RS({text:e,language:t,className:n}){const[o,r]=D.useState(null);return D.useEffect(()=>{t&&w0.codeToHtml(e,{lang:t,theme:"github-dark-default",rootStyle:"background-color: transparent;",transformers:[{pre(i){i.properties.class="w-full py-3 px-4 max-h-[300px] overflow-y-auto whitespace-pre-wrap text-left text-sm"}}]}).then(r)},[e,t]),o?m.jsx("div",{className:T.cn("w-full bg-slate-800/90",n),dangerouslySetInnerHTML:{__html:o}}):m.jsx("pre",{className:T.cn("w-full bg-slate-800/90 px-4 py-3 text-sm whitespace-pre-wrap text-slate-100",n),children:e})}function s6({data:e}){const t=`data:image/png;base64,${e}`;return m.jsx("div",{className:"flex items-center justify-center rounded-lg p-5",style:{backgroundImage:`linear-gradient(45deg, #ccc 25%, transparent 25%),
|
|
137
137
|
linear-gradient(135deg, #ccc 25%, transparent 25%),
|
|
138
138
|
linear-gradient(45deg, transparent 75%, #ccc 75%),
|
|
139
|
-
linear-gradient(135deg, transparent 75%, #ccc 75%)`,backgroundSize:"25px 25px",backgroundPosition:"0 0, 12.5px 0, 12.5px -12.5px, 0px 12.5px"},children:m.jsx("img",{src:t,className:"max-h-[300px] max-w-full object-contain"})})}function l6({content:e}){return m.jsx("div",{className:"w-full",children:e.content.map((t,n)=>{switch(t.type){case"text":{const o=o6(t._meta?.["getgram.ai/mime-type"]??"text/plain"),r=i6(t.text,o);return m.jsx(RS,{text:r,language:o},n)}case"image":return m.jsx(u6,{data:t.data},n);default:return m.jsx("pre",{className:"px-4 py-3 text-sm whitespace-pre-wrap",children:JSON.stringify(t,null,2)},n)}})})}function nm({title:e,content:t,defaultExpanded:n=!1,highlightSyntax:o=!0,language:r="json"}){const[i,a]=D.useState(n),s=a6(t),l=s?JSON.stringify(t,null,2):typeof t=="string"?t:JSON.stringify(t,null,2);return m.jsxs("div",{"data-slot":"tool-ui-section",className:"border-border border-t",children:[m.jsxs("button",{onClick:()=>a(!i),className:"hover:bg-accent/50 flex w-full cursor-pointer items-center justify-between px-4 py-2.5 text-left transition-colors",children:[m.jsx("span",{className:"text-muted-foreground text-sm",children:e}),m.jsxs("div",{className:"flex items-center gap-1",children:[m.jsx(s6,{content:l}),m.jsx(um,{className:T.cn("text-muted-foreground size-4 transition-transform duration-200",i&&"rotate-90")})]})]}),i&&m.jsx("div",{className:"border-border border-t",children:s?m.jsx(l6,{content:t}):o?m.jsx(RS,{text:l,language:r}):m.jsx("pre",{className:"text-foreground overflow-x-auto px-4 py-3 text-sm whitespace-pre-wrap",children:l})})]})}function c6({name:e,icon:t,provider:n,status:o="complete",request:r,result:i,defaultExpanded:a=!1,className:s,onApproveOnce:l,onApproveForSession:u,onDeny:c}){const d=o==="approval"&&l!==void 0&&c!==void 0,[f,p]=D.useState(a),g=r!==void 0||i!==void 0,[h,b]=D.useState("one-time"),[y,x]=D.useState(!1);D.useEffect(()=>{!d&&f&&!a&&p(!1)},[d]);const $=()=>{h==="for-session"&&u?u():l&&l()};return m.jsxs("div",{"data-slot":"tool-ui",className:T.cn("border-border bg-card overflow-hidden rounded-lg border",s),children:[n&&m.jsxs("div",{"data-slot":"tool-ui-provider",className:T.cn("border-border flex items-center gap-2 border-b px-4 py-2.5"),children:[t?m.jsx("span",{className:"flex size-5 items-center justify-center",children:t}):m.jsx("span",{className:"bg-muted flex size-5 items-center justify-center rounded text-xs font-medium",children:n.charAt(0).toUpperCase()}),m.jsx("span",{className:"text-sm font-medium",children:n})]}),m.jsxs("button",{onClick:()=>g&&p(!f),disabled:!g,className:T.cn("flex w-full items-center gap-2 px-4 py-3 text-left",g&&"hover:bg-accent/50 cursor-pointer transition-colors"),children:[m.jsx(AS,{status:o}),m.jsx("span",{className:T.cn("flex-1 text-sm",!n&&d&&"shimmer"),children:e}),g&&m.jsx(li,{className:T.cn("text-muted-foreground size-4 transition-transform duration-200",f&&"rotate-180")})]}),f&&g&&m.jsxs("div",{"data-slot":"tool-ui-content",children:[r!==void 0&&m.jsx(nm,{title:"Arguments",content:r,highlightSyntax:!0,language:"json"}),i!==void 0&&m.jsx(nm,{title:"Output",content:i,highlightSyntax:!0,language:"json"})]}),d&&m.jsxs("div",{"data-slot":"tool-ui-approval-actions",className:"border-border flex items-center justify-end gap-2 border-t px-4 py-3",children:[m.jsx("div",{children:m.jsx("span",{className:"text-muted-foreground text-sm",children:"This tool requires approval"})}),m.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[m.jsxs($t,{variant:"outline",size:"sm",onClick:c,className:"text-destructive hover:bg-destructive/10",children:[m.jsx(Xn,{className:"mr-1 size-3"}),"Deny"]}),m.jsxs("div",{className:"flex items-center",children:[m.jsxs($t,{variant:"default",size:"sm",onClick:$,className:"flex cursor-pointer justify-between gap-1 rounded-r-none bg-emerald-600 hover:bg-emerald-700",children:[m.jsx(rr,{className:"mr-1 size-3"}),m.jsx("span",{className:"min-w-[110px]",children:h==="one-time"?"Approve this time":"Approve always"})]}),m.jsxs(PS,{open:y,onOpenChange:x,children:[m.jsx(CS,{asChild:!0,children:m.jsx($t,{variant:"default",size:"sm",className:"cursor-pointer rounded-l-none border-l border-emerald-700 bg-emerald-600 px-2 hover:bg-emerald-700",children:m.jsx(li,{className:"size-3"})})}),m.jsxs(jS,{align:"end",className:"w-64 p-1",sideOffset:4,children:[m.jsxs("button",{onClick:()=>{b("one-time"),x(!1)},className:"hover:bg-accent relative flex w-full items-start gap-2 rounded-sm px-2 py-2 text-left",children:[m.jsx(rr,{className:T.cn("relative top-1 mt-0.5 size-3 shrink-0",h!=="one-time"&&"invisible")}),m.jsxs("div",{className:"flex flex-col gap-0.5",children:[m.jsx("span",{className:"text-sm",children:"Approve only once"}),m.jsx("span",{className:"text-muted-foreground text-xs",children:"You'll be asked again next time"})]})]}),u&&m.jsxs("button",{onClick:()=>{b("for-session"),x(!1)},className:"hover:bg-accent relative flex w-full items-start gap-2 rounded-sm px-2 py-2 text-left",children:[m.jsx(rr,{className:T.cn("relative top-1 mt-0.5 size-3 shrink-0",h!=="for-session"&&"invisible")}),m.jsxs("div",{className:"flex flex-col gap-0.5",children:[m.jsx("span",{className:"text-sm",children:"Approve always"}),m.jsx("span",{className:"text-muted-foreground text-xs",children:"Trust this tool for the session"})]})]})]})]})]})]})]})]})}function d6({title:e,icon:t,status:n="complete",defaultExpanded:o=!1,children:r,className:i}){const[a,s]=D.useState(o);return m.jsxs("div",{"data-slot":"tool-ui-group",className:T.cn("border-border bg-card overflow-hidden rounded-lg border",i),children:[m.jsxs("button",{onClick:()=>s(!a),className:"hover:bg-accent/50 flex w-full items-center gap-2 px-4 py-3 text-left transition-colors",children:[t||m.jsx(AS,{status:n==="running"?"running":"complete"}),m.jsx("span",{className:T.cn("flex-1 text-sm font-medium",n==="running"&&"shimmer"),children:e}),m.jsx(li,{className:T.cn("text-muted-foreground size-4 transition-transform duration-200",a&&"rotate-180")})]}),a&&m.jsx("div",{"data-slot":"tool-ui-group-content",className:"border-border border-t",children:r})]})}const p6=({toolName:e,toolCallId:t,status:n,result:o,args:r})=>{const{pendingApprovals:i,whitelistTool:a,confirmPendingApproval:s,rejectPendingApproval:l}=_$(),u=i.get(t),d=L.useAssistantState(({message:x})=>x).parts.filter(x=>x.type==="tool-call"),f=d.findIndex(x=>x.toolName===e),p=()=>{s(t)},g=()=>{a(e),s(t)},h=()=>{l(t)},b=()=>u?"approval":n.type==="incomplete"?"error":n.type==="complete"?o&&typeof o=="object"&&"isError"in o&&o.isError?"error":"complete":"running",y=()=>{if(o!==void 0)return typeof o=="object"&&o!==null&&"content"in o&&Array.isArray(o.content)||typeof o=="string",o};return m.jsx("div",{className:T.cn("aui-tool-fallback-root flex w-full flex-col",f!==-1&&f!==d.length-1&&"border-b"),children:m.jsx(c6,{name:e,status:b(),request:r,result:y(),onApproveOnce:u?p:void 0,onApproveForSession:u?g:void 0,onDeny:u?h:void 0,className:"rounded-none border-0"})})};var is="Collapsible",[f6]=Po(is),[m6,md]=f6(is),zS=_.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:o,defaultOpen:r,disabled:i,onOpenChange:a,...s}=e,[l,u]=es({prop:o,defaultProp:r??!1,onChange:a,caller:is});return m.jsx(m6,{scope:n,disabled:i,contentId:qr(),open:l,onOpenToggle:_.useCallback(()=>u(c=>!c),[u]),children:m.jsx(Ce.div,{"data-state":gd(l),"data-disabled":i?"":void 0,...s,ref:t})})});zS.displayName=is;var MS="CollapsibleTrigger",DS=_.forwardRef((e,t)=>{const{__scopeCollapsible:n,...o}=e,r=md(MS,n);return m.jsx(Ce.button,{type:"button","aria-controls":r.contentId,"aria-expanded":r.open||!1,"data-state":gd(r.open),"data-disabled":r.disabled?"":void 0,disabled:r.disabled,...o,ref:t,onClick:Oe(e.onClick,r.onOpenToggle)})});DS.displayName=MS;var hd="CollapsibleContent",US=_.forwardRef((e,t)=>{const{forceMount:n,...o}=e,r=md(hd,e.__scopeCollapsible);return m.jsx(Gt,{present:n||r.open,children:({present:i})=>m.jsx(h6,{...o,ref:t,present:i})})});US.displayName=hd;var h6=_.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:o,children:r,...i}=e,a=md(hd,n),[s,l]=_.useState(o),u=_.useRef(null),c=Ge(t,u),d=_.useRef(0),f=d.current,p=_.useRef(0),g=p.current,h=a.open||s,b=_.useRef(h),y=_.useRef(void 0);return _.useEffect(()=>{const x=requestAnimationFrame(()=>b.current=!1);return()=>cancelAnimationFrame(x)},[]),lt(()=>{const x=u.current;if(x){y.current=y.current||{transitionDuration:x.style.transitionDuration,animationName:x.style.animationName},x.style.transitionDuration="0s",x.style.animationName="none";const $=x.getBoundingClientRect();d.current=$.height,p.current=$.width,b.current||(x.style.transitionDuration=y.current.transitionDuration,x.style.animationName=y.current.animationName),l(o)}},[a.open,o]),m.jsx(Ce.div,{"data-state":gd(a.open),"data-disabled":a.disabled?"":void 0,id:a.contentId,hidden:!h,...i,ref:c,style:{"--radix-collapsible-content-height":f?`${f}px`:void 0,"--radix-collapsible-content-width":g?`${g}px`:void 0,...e.style},children:h&&r})});function gd(e){return e?"open":"closed"}var g6=zS;function v6({...e}){return m.jsx(g6,{"data-slot":"collapsible",...e})}function y6({...e}){return m.jsx(DS,{"data-slot":"collapsible-trigger",...e})}function b6({...e}){return m.jsx(US,{"data-slot":"collapsible-content",...e})}const om=200,LS=({className:e,children:t})=>{const n=D.useRef(null),[o,r]=D.useState(!1),i=L.useScrollLock(n,om),a=D.useCallback(s=>{s||i(),r(s)},[i]);return m.jsx(v6,{ref:n,open:o,onOpenChange:a,className:T.cn("aui-reasoning-root mb-4 w-full",e),style:{"--animation-duration":`${om}ms`},children:t})};LS.displayName="ReasoningRoot";const _6=({className:e})=>m.jsx("div",{className:T.cn("aui-reasoning-fade pointer-events-none absolute inset-x-0 bottom-0 z-10 h-16","bg-[linear-gradient(to_top,var(--color-background),transparent)]","fade-in-0 animate-in","group-data-[state=open]/collapsible-content:animate-out","group-data-[state=open]/collapsible-content:fade-out-0","group-data-[state=open]/collapsible-content:delay-[calc(var(--animation-duration)*0.75)]","group-data-[state=open]/collapsible-content:fill-mode-forwards","duration-(--animation-duration)","group-data-[state=open]/collapsible-content:duration-(--animation-duration)",e)}),w6=({active:e,className:t})=>m.jsxs(y6,{className:T.cn("aui-reasoning-trigger group/trigger text-muted-foreground hover:text-foreground -mb-2 flex max-w-[75%] items-center gap-2 py-2 text-sm transition-colors",t,e&&"shimmer"),children:[m.jsx(O0,{className:"aui-reasoning-trigger-icon size-4 shrink-0"}),m.jsxs("span",{className:"aui-reasoning-trigger-label-wrapper relative inline-block leading-none",children:[m.jsx("span",{children:"Reasoning"}),e?m.jsx("span",{"aria-hidden":!0,className:"aui-reasoning-trigger-shimmer shimmer pointer-events-none absolute inset-0 motion-reduce:animate-none",children:"Reasoning"}):null]}),m.jsx(li,{className:T.cn("aui-reasoning-trigger-chevron mt-0.5 size-4 shrink-0","transition-transform duration-(--animation-duration) ease-out","group-data-[state=closed]/trigger:-rotate-90","group-data-[state=open]/trigger:rotate-0")})]}),ZS=({className:e,children:t,"aria-busy":n})=>m.jsxs(b6,{className:T.cn("aui-reasoning-content text-muted-foreground relative overflow-hidden text-sm outline-none","group/collapsible-content ease-out","data-[state=closed]:animate-collapsible-up","data-[state=open]:animate-collapsible-down","data-[state=closed]:fill-mode-forwards","data-[state=closed]:pointer-events-none","data-[state=open]:duration-(--animation-duration)","data-[state=closed]:duration-(--animation-duration)",e),"aria-busy":n,children:[t,m.jsx(_6,{})]});ZS.displayName="ReasoningContent";const FS=({className:e,children:t})=>m.jsx("div",{className:T.cn("aui-reasoning-text relative z-0 space-y-4 pt-4 pl-6 leading-relaxed","transform-gpu transition-[transform,opacity]","group-data-[state=open]/collapsible-content:animate-in","group-data-[state=closed]/collapsible-content:animate-out","group-data-[state=open]/collapsible-content:fade-in-0","group-data-[state=closed]/collapsible-content:fade-out-0","group-data-[state=open]/collapsible-content:slide-in-from-top-4","group-data-[state=closed]/collapsible-content:slide-out-to-top-4","group-data-[state=open]/collapsible-content:duration-(--animation-duration)","group-data-[state=closed]/collapsible-content:duration-(--animation-duration)","[&_p]:-mb-2",e),children:t});FS.displayName="ReasoningText";const x6=()=>m.jsx(lS,{}),$6=({children:e,startIndex:t,endIndex:n})=>{const o=L.useAssistantState(({message:r})=>{if(r.status?.type!=="running")return!1;const i=r.parts.length-1;return i<0||r.parts[i]?.type!=="reasoning"?!1:i>=t&&i<=n});return m.jsxs(LS,{children:[m.jsx(w6,{active:o}),m.jsx(ZS,{"aria-busy":o,children:m.jsx(FS,{children:e})})]})},qS=D.memo(x6);qS.displayName="Reasoning";const VS=D.memo($6);VS.displayName="ReasoningGroup";var as="Dialog",[BS]=Po(as),[S6,kt]=BS(as),JS=e=>{const{__scopeDialog:t,children:n,open:o,defaultOpen:r,onOpenChange:i,modal:a=!0}=e,s=_.useRef(null),l=_.useRef(null),[u,c]=es({prop:o,defaultProp:r??!1,onChange:i,caller:as});return m.jsx(S6,{scope:t,triggerRef:s,contentRef:l,contentId:qr(),titleId:qr(),descriptionId:qr(),open:u,onOpenChange:c,onOpenToggle:_.useCallback(()=>c(d=>!d),[c]),modal:a,children:n})};JS.displayName=as;var WS="DialogTrigger",HS=_.forwardRef((e,t)=>{const{__scopeDialog:n,...o}=e,r=kt(WS,n),i=Ge(t,r.triggerRef);return m.jsx(Ce.button,{type:"button","aria-haspopup":"dialog","aria-expanded":r.open,"aria-controls":r.contentId,"data-state":bd(r.open),...o,ref:i,onClick:Oe(e.onClick,r.onOpenToggle)})});HS.displayName=WS;var vd="DialogPortal",[I6,GS]=BS(vd,{forceMount:void 0}),KS=e=>{const{__scopeDialog:t,forceMount:n,children:o,container:r}=e,i=kt(vd,t);return m.jsx(I6,{scope:t,forceMount:n,children:_.Children.map(o,a=>m.jsx(Gt,{present:n||i.open,children:m.jsx(Xa,{asChild:!0,container:r,children:a})}))})};KS.displayName=vd;var qi="DialogOverlay",YS=_.forwardRef((e,t)=>{const n=GS(qi,e.__scopeDialog),{forceMount:o=n.forceMount,...r}=e,i=kt(qi,e.__scopeDialog);return i.modal?m.jsx(Gt,{present:o||i.open,children:m.jsx(E6,{...r,ref:t})}):null});YS.displayName=qi;var k6=Gc("DialogOverlay.RemoveScroll"),E6=_.forwardRef((e,t)=>{const{__scopeDialog:n,...o}=e,r=kt(qi,n);return m.jsx(pd,{as:k6,allowPinchZoom:!0,shards:[r.contentRef],children:m.jsx(Ce.div,{"data-state":bd(r.open),...o,ref:t,style:{pointerEvents:"auto",...o.style}})})}),kr="DialogContent",QS=_.forwardRef((e,t)=>{const n=GS(kr,e.__scopeDialog),{forceMount:o=n.forceMount,...r}=e,i=kt(kr,e.__scopeDialog);return m.jsx(Gt,{present:o||i.open,children:i.modal?m.jsx(T6,{...r,ref:t}):m.jsx(O6,{...r,ref:t})})});QS.displayName=kr;var T6=_.forwardRef((e,t)=>{const n=kt(kr,e.__scopeDialog),o=_.useRef(null),r=Ge(t,n.contentRef,o);return _.useEffect(()=>{const i=o.current;if(i)return fS(i)},[]),m.jsx(XS,{...e,ref:r,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Oe(e.onCloseAutoFocus,i=>{i.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Oe(e.onPointerDownOutside,i=>{const a=i.detail.originalEvent,s=a.button===0&&a.ctrlKey===!0;(a.button===2||s)&&i.preventDefault()}),onFocusOutside:Oe(e.onFocusOutside,i=>i.preventDefault())})}),O6=_.forwardRef((e,t)=>{const n=kt(kr,e.__scopeDialog),o=_.useRef(!1),r=_.useRef(!1);return m.jsx(XS,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{e.onCloseAutoFocus?.(i),i.defaultPrevented||(o.current||n.triggerRef.current?.focus(),i.preventDefault()),o.current=!1,r.current=!1},onInteractOutside:i=>{e.onInteractOutside?.(i),i.defaultPrevented||(o.current=!0,i.detail.originalEvent.type==="pointerdown"&&(r.current=!0));const a=i.target;n.triggerRef.current?.contains(a)&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&r.current&&i.preventDefault()}})}),XS=_.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:o,onOpenAutoFocus:r,onCloseAutoFocus:i,...a}=e,s=kt(kr,n),l=_.useRef(null),u=Ge(t,l);return cS(),m.jsxs(m.Fragment,{children:[m.jsx(dd,{asChild:!0,loop:!0,trapped:o,onMountAutoFocus:r,onUnmountAutoFocus:i,children:m.jsx(Ha,{role:"dialog",id:s.contentId,"aria-describedby":s.descriptionId,"aria-labelledby":s.titleId,"data-state":bd(s.open),...a,ref:u,onDismiss:()=>s.onOpenChange(!1)})}),m.jsxs(m.Fragment,{children:[m.jsx(P6,{titleId:s.titleId}),m.jsx(j6,{contentRef:l,descriptionId:s.descriptionId})]})]})}),yd="DialogTitle",e0=_.forwardRef((e,t)=>{const{__scopeDialog:n,...o}=e,r=kt(yd,n);return m.jsx(Ce.h2,{id:r.titleId,...o,ref:t})});e0.displayName=yd;var t0="DialogDescription",N6=_.forwardRef((e,t)=>{const{__scopeDialog:n,...o}=e,r=kt(t0,n);return m.jsx(Ce.p,{id:r.descriptionId,...o,ref:t})});N6.displayName=t0;var r0="DialogClose",n0=_.forwardRef((e,t)=>{const{__scopeDialog:n,...o}=e,r=kt(r0,n);return m.jsx(Ce.button,{type:"button",...o,ref:t,onClick:Oe(e.onClick,()=>r.onOpenChange(!1))})});n0.displayName=r0;function bd(e){return e?"open":"closed"}var o0="DialogTitleWarning",[B2,i0]=PM(o0,{contentName:kr,titleName:yd,docsSlug:"dialog"}),P6=({titleId:e})=>{const t=i0(o0),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
|
|
139
|
+
linear-gradient(135deg, transparent 75%, #ccc 75%)`,backgroundSize:"25px 25px",backgroundPosition:"0 0, 12.5px 0, 12.5px -12.5px, 0px 12.5px"},children:m.jsx("img",{src:t,className:"max-h-[300px] max-w-full object-contain"})})}function u6({content:e}){return m.jsx("div",{className:"w-full",children:e.content.map((t,n)=>{switch(t.type){case"text":{const o=n6(t._meta?.["getgram.ai/mime-type"]??"text/plain"),r=o6(t.text,o);return m.jsx(RS,{text:r,language:o},n)}case"image":return m.jsx(s6,{data:t.data},n);default:return m.jsx("pre",{className:"px-4 py-3 text-sm whitespace-pre-wrap",children:JSON.stringify(t,null,2)},n)}})})}function nm({title:e,content:t,defaultExpanded:n=!1,highlightSyntax:o=!0,language:r="json"}){const[i,a]=D.useState(n),s=i6(t),l=s?JSON.stringify(t,null,2):typeof t=="string"?t:JSON.stringify(t,null,2);return m.jsxs("div",{"data-slot":"tool-ui-section",className:"border-border border-t",children:[m.jsxs("button",{onClick:()=>a(!i),className:"hover:bg-accent/50 flex w-full cursor-pointer items-center justify-between px-4 py-2.5 text-left transition-colors",children:[m.jsx("span",{className:"text-muted-foreground text-sm",children:e}),m.jsxs("div",{className:"flex items-center gap-1",children:[m.jsx(a6,{content:l}),m.jsx(um,{className:T.cn("text-muted-foreground size-4 transition-transform duration-200",i&&"rotate-90")})]})]}),i&&m.jsx("div",{className:"border-border border-t",children:s?m.jsx(u6,{content:t}):o?m.jsx(RS,{text:l,language:r}):m.jsx("pre",{className:"text-foreground overflow-x-auto px-4 py-3 text-sm whitespace-pre-wrap",children:l})})]})}function l6({name:e,icon:t,provider:n,status:o="complete",request:r,result:i,defaultExpanded:a=!1,className:s,onApproveOnce:l,onApproveForSession:u,onDeny:c}){const d=o==="approval"&&l!==void 0&&c!==void 0,[f,p]=D.useState(a),g=r!==void 0||i!==void 0,[h,b]=D.useState("one-time"),[y,x]=D.useState(!1);D.useEffect(()=>{!d&&f&&!a&&p(!1)},[d]);const $=()=>{h==="for-session"&&u?u():l&&l()};return m.jsxs("div",{"data-slot":"tool-ui",className:T.cn("border-border bg-card overflow-hidden rounded-lg border",s),children:[n&&m.jsxs("div",{"data-slot":"tool-ui-provider",className:T.cn("border-border flex items-center gap-2 border-b px-4 py-2.5"),children:[t?m.jsx("span",{className:"flex size-5 items-center justify-center",children:t}):m.jsx("span",{className:"bg-muted flex size-5 items-center justify-center rounded text-xs font-medium",children:n.charAt(0).toUpperCase()}),m.jsx("span",{className:"text-sm font-medium",children:n})]}),m.jsxs("button",{onClick:()=>g&&p(!f),disabled:!g,className:T.cn("flex w-full items-center gap-2 px-4 py-3 text-left",g&&"hover:bg-accent/50 cursor-pointer transition-colors"),children:[m.jsx(AS,{status:o}),m.jsx("span",{className:T.cn("flex-1 text-sm",!n&&d&&"shimmer"),children:e}),g&&m.jsx(li,{className:T.cn("text-muted-foreground size-4 transition-transform duration-200",f&&"rotate-180")})]}),f&&g&&m.jsxs("div",{"data-slot":"tool-ui-content",children:[r!==void 0&&m.jsx(nm,{title:"Arguments",content:r,highlightSyntax:!0,language:"json"}),i!==void 0&&m.jsx(nm,{title:"Output",content:i,highlightSyntax:!0,language:"json"})]}),d&&m.jsxs("div",{"data-slot":"tool-ui-approval-actions",className:"border-border flex items-center justify-end gap-2 border-t px-4 py-3",children:[m.jsx("div",{children:m.jsx("span",{className:"text-muted-foreground text-sm",children:"This tool requires approval"})}),m.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[m.jsxs($t,{variant:"outline",size:"sm",onClick:c,className:"text-destructive hover:bg-destructive/10",children:[m.jsx(Xn,{className:"mr-1 size-3"}),"Deny"]}),m.jsxs("div",{className:"flex items-center",children:[m.jsxs($t,{variant:"default",size:"sm",onClick:$,className:"flex cursor-pointer justify-between gap-1 rounded-r-none bg-emerald-600 hover:bg-emerald-700",children:[m.jsx(rr,{className:"mr-1 size-3"}),m.jsx("span",{className:"min-w-[110px]",children:h==="one-time"?"Approve this time":"Approve always"})]}),m.jsxs(PS,{open:y,onOpenChange:x,children:[m.jsx(CS,{asChild:!0,children:m.jsx($t,{variant:"default",size:"sm",className:"cursor-pointer rounded-l-none border-l border-emerald-700 bg-emerald-600 px-2 hover:bg-emerald-700",children:m.jsx(li,{className:"size-3"})})}),m.jsxs(jS,{align:"end",className:"w-64 p-1",sideOffset:4,children:[m.jsxs("button",{onClick:()=>{b("one-time"),x(!1)},className:"hover:bg-accent relative flex w-full items-start gap-2 rounded-sm px-2 py-2 text-left",children:[m.jsx(rr,{className:T.cn("relative top-1 mt-0.5 size-3 shrink-0",h!=="one-time"&&"invisible")}),m.jsxs("div",{className:"flex flex-col gap-0.5",children:[m.jsx("span",{className:"text-sm",children:"Approve only once"}),m.jsx("span",{className:"text-muted-foreground text-xs",children:"You'll be asked again next time"})]})]}),u&&m.jsxs("button",{onClick:()=>{b("for-session"),x(!1)},className:"hover:bg-accent relative flex w-full items-start gap-2 rounded-sm px-2 py-2 text-left",children:[m.jsx(rr,{className:T.cn("relative top-1 mt-0.5 size-3 shrink-0",h!=="for-session"&&"invisible")}),m.jsxs("div",{className:"flex flex-col gap-0.5",children:[m.jsx("span",{className:"text-sm",children:"Approve always"}),m.jsx("span",{className:"text-muted-foreground text-xs",children:"Trust this tool for the session"})]})]})]})]})]})]})]})]})}function c6({title:e,icon:t,status:n="complete",defaultExpanded:o=!1,children:r,className:i}){const[a,s]=D.useState(o);return m.jsxs("div",{"data-slot":"tool-ui-group",className:T.cn("border-border bg-card overflow-hidden rounded-lg border",i),children:[m.jsxs("button",{onClick:()=>s(!a),className:"hover:bg-accent/50 flex w-full items-center gap-2 px-4 py-3 text-left transition-colors",children:[t||m.jsx(AS,{status:n==="running"?"running":"complete"}),m.jsx("span",{className:T.cn("flex-1 text-sm font-medium",n==="running"&&"shimmer"),children:e}),m.jsx(li,{className:T.cn("text-muted-foreground size-4 transition-transform duration-200",a&&"rotate-180")})]}),a&&m.jsx("div",{"data-slot":"tool-ui-group-content",className:"border-border border-t",children:r})]})}const d6=({toolName:e,toolCallId:t,status:n,result:o,args:r})=>{const{pendingApprovals:i,whitelistTool:a,confirmPendingApproval:s,rejectPendingApproval:l}=_$(),u=i.get(t),d=L.useAssistantState(({message:x})=>x).parts.filter(x=>x.type==="tool-call"),f=d.findIndex(x=>x.toolName===e),p=()=>{s(t)},g=()=>{a(e),s(t)},h=()=>{l(t)},b=()=>u?"approval":n.type==="incomplete"?"error":n.type==="complete"?o&&typeof o=="object"&&"isError"in o&&o.isError?"error":"complete":"running",y=()=>{if(o!==void 0)return typeof o=="object"&&o!==null&&"content"in o&&Array.isArray(o.content)||typeof o=="string",o};return m.jsx("div",{className:T.cn("aui-tool-fallback-root flex w-full flex-col",f!==-1&&f!==d.length-1&&"border-b"),children:m.jsx(l6,{name:e,status:b(),request:r,result:y(),onApproveOnce:u?p:void 0,onApproveForSession:u?g:void 0,onDeny:u?h:void 0,className:"rounded-none border-0"})})};var is="Collapsible",[p6]=Po(is),[f6,md]=p6(is),zS=_.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:o,defaultOpen:r,disabled:i,onOpenChange:a,...s}=e,[l,u]=es({prop:o,defaultProp:r??!1,onChange:a,caller:is});return m.jsx(f6,{scope:n,disabled:i,contentId:qr(),open:l,onOpenToggle:_.useCallback(()=>u(c=>!c),[u]),children:m.jsx(Ce.div,{"data-state":gd(l),"data-disabled":i?"":void 0,...s,ref:t})})});zS.displayName=is;var MS="CollapsibleTrigger",DS=_.forwardRef((e,t)=>{const{__scopeCollapsible:n,...o}=e,r=md(MS,n);return m.jsx(Ce.button,{type:"button","aria-controls":r.contentId,"aria-expanded":r.open||!1,"data-state":gd(r.open),"data-disabled":r.disabled?"":void 0,disabled:r.disabled,...o,ref:t,onClick:Oe(e.onClick,r.onOpenToggle)})});DS.displayName=MS;var hd="CollapsibleContent",US=_.forwardRef((e,t)=>{const{forceMount:n,...o}=e,r=md(hd,e.__scopeCollapsible);return m.jsx(Gt,{present:n||r.open,children:({present:i})=>m.jsx(m6,{...o,ref:t,present:i})})});US.displayName=hd;var m6=_.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:o,children:r,...i}=e,a=md(hd,n),[s,l]=_.useState(o),u=_.useRef(null),c=Ge(t,u),d=_.useRef(0),f=d.current,p=_.useRef(0),g=p.current,h=a.open||s,b=_.useRef(h),y=_.useRef(void 0);return _.useEffect(()=>{const x=requestAnimationFrame(()=>b.current=!1);return()=>cancelAnimationFrame(x)},[]),lt(()=>{const x=u.current;if(x){y.current=y.current||{transitionDuration:x.style.transitionDuration,animationName:x.style.animationName},x.style.transitionDuration="0s",x.style.animationName="none";const $=x.getBoundingClientRect();d.current=$.height,p.current=$.width,b.current||(x.style.transitionDuration=y.current.transitionDuration,x.style.animationName=y.current.animationName),l(o)}},[a.open,o]),m.jsx(Ce.div,{"data-state":gd(a.open),"data-disabled":a.disabled?"":void 0,id:a.contentId,hidden:!h,...i,ref:c,style:{"--radix-collapsible-content-height":f?`${f}px`:void 0,"--radix-collapsible-content-width":g?`${g}px`:void 0,...e.style},children:h&&r})});function gd(e){return e?"open":"closed"}var h6=zS;function g6({...e}){return m.jsx(h6,{"data-slot":"collapsible",...e})}function v6({...e}){return m.jsx(DS,{"data-slot":"collapsible-trigger",...e})}function y6({...e}){return m.jsx(US,{"data-slot":"collapsible-content",...e})}const om=200,LS=({className:e,children:t})=>{const n=D.useRef(null),[o,r]=D.useState(!1),i=L.useScrollLock(n,om),a=D.useCallback(s=>{s||i(),r(s)},[i]);return m.jsx(g6,{ref:n,open:o,onOpenChange:a,className:T.cn("aui-reasoning-root mb-4 w-full",e),style:{"--animation-duration":`${om}ms`},children:t})};LS.displayName="ReasoningRoot";const b6=({className:e})=>m.jsx("div",{className:T.cn("aui-reasoning-fade pointer-events-none absolute inset-x-0 bottom-0 z-10 h-16","bg-[linear-gradient(to_top,var(--color-background),transparent)]","fade-in-0 animate-in","group-data-[state=open]/collapsible-content:animate-out","group-data-[state=open]/collapsible-content:fade-out-0","group-data-[state=open]/collapsible-content:delay-[calc(var(--animation-duration)*0.75)]","group-data-[state=open]/collapsible-content:fill-mode-forwards","duration-(--animation-duration)","group-data-[state=open]/collapsible-content:duration-(--animation-duration)",e)}),_6=({active:e,className:t})=>m.jsxs(v6,{className:T.cn("aui-reasoning-trigger group/trigger text-muted-foreground hover:text-foreground -mb-2 flex max-w-[75%] items-center gap-2 py-2 text-sm transition-colors",t,e&&"shimmer"),children:[m.jsx(O0,{className:"aui-reasoning-trigger-icon size-4 shrink-0"}),m.jsxs("span",{className:"aui-reasoning-trigger-label-wrapper relative inline-block leading-none",children:[m.jsx("span",{children:"Reasoning"}),e?m.jsx("span",{"aria-hidden":!0,className:"aui-reasoning-trigger-shimmer shimmer pointer-events-none absolute inset-0 motion-reduce:animate-none",children:"Reasoning"}):null]}),m.jsx(li,{className:T.cn("aui-reasoning-trigger-chevron mt-0.5 size-4 shrink-0","transition-transform duration-(--animation-duration) ease-out","group-data-[state=closed]/trigger:-rotate-90","group-data-[state=open]/trigger:rotate-0")})]}),ZS=({className:e,children:t,"aria-busy":n})=>m.jsxs(y6,{className:T.cn("aui-reasoning-content text-muted-foreground relative overflow-hidden text-sm outline-none","group/collapsible-content ease-out","data-[state=closed]:animate-collapsible-up","data-[state=open]:animate-collapsible-down","data-[state=closed]:fill-mode-forwards","data-[state=closed]:pointer-events-none","data-[state=open]:duration-(--animation-duration)","data-[state=closed]:duration-(--animation-duration)",e),"aria-busy":n,children:[t,m.jsx(b6,{})]});ZS.displayName="ReasoningContent";const FS=({className:e,children:t})=>m.jsx("div",{className:T.cn("aui-reasoning-text relative z-0 space-y-4 pt-4 pl-6 leading-relaxed","transform-gpu transition-[transform,opacity]","group-data-[state=open]/collapsible-content:animate-in","group-data-[state=closed]/collapsible-content:animate-out","group-data-[state=open]/collapsible-content:fade-in-0","group-data-[state=closed]/collapsible-content:fade-out-0","group-data-[state=open]/collapsible-content:slide-in-from-top-4","group-data-[state=closed]/collapsible-content:slide-out-to-top-4","group-data-[state=open]/collapsible-content:duration-(--animation-duration)","group-data-[state=closed]/collapsible-content:duration-(--animation-duration)","[&_p]:-mb-2",e),children:t});FS.displayName="ReasoningText";const w6=()=>m.jsx(lS,{}),x6=({children:e,startIndex:t,endIndex:n})=>{const o=L.useAssistantState(({message:r})=>{if(r.status?.type!=="running")return!1;const i=r.parts.length-1;return i<0||r.parts[i]?.type!=="reasoning"?!1:i>=t&&i<=n});return m.jsxs(LS,{children:[m.jsx(_6,{active:o}),m.jsx(ZS,{"aria-busy":o,children:m.jsx(FS,{children:e})})]})},qS=D.memo(w6);qS.displayName="Reasoning";const VS=D.memo(x6);VS.displayName="ReasoningGroup";var as="Dialog",[BS]=Po(as),[$6,kt]=BS(as),JS=e=>{const{__scopeDialog:t,children:n,open:o,defaultOpen:r,onOpenChange:i,modal:a=!0}=e,s=_.useRef(null),l=_.useRef(null),[u,c]=es({prop:o,defaultProp:r??!1,onChange:i,caller:as});return m.jsx($6,{scope:t,triggerRef:s,contentRef:l,contentId:qr(),titleId:qr(),descriptionId:qr(),open:u,onOpenChange:c,onOpenToggle:_.useCallback(()=>c(d=>!d),[c]),modal:a,children:n})};JS.displayName=as;var WS="DialogTrigger",HS=_.forwardRef((e,t)=>{const{__scopeDialog:n,...o}=e,r=kt(WS,n),i=Ge(t,r.triggerRef);return m.jsx(Ce.button,{type:"button","aria-haspopup":"dialog","aria-expanded":r.open,"aria-controls":r.contentId,"data-state":bd(r.open),...o,ref:i,onClick:Oe(e.onClick,r.onOpenToggle)})});HS.displayName=WS;var vd="DialogPortal",[S6,GS]=BS(vd,{forceMount:void 0}),KS=e=>{const{__scopeDialog:t,forceMount:n,children:o,container:r}=e,i=kt(vd,t);return m.jsx(S6,{scope:t,forceMount:n,children:_.Children.map(o,a=>m.jsx(Gt,{present:n||i.open,children:m.jsx(Xa,{asChild:!0,container:r,children:a})}))})};KS.displayName=vd;var qi="DialogOverlay",YS=_.forwardRef((e,t)=>{const n=GS(qi,e.__scopeDialog),{forceMount:o=n.forceMount,...r}=e,i=kt(qi,e.__scopeDialog);return i.modal?m.jsx(Gt,{present:o||i.open,children:m.jsx(k6,{...r,ref:t})}):null});YS.displayName=qi;var I6=Gc("DialogOverlay.RemoveScroll"),k6=_.forwardRef((e,t)=>{const{__scopeDialog:n,...o}=e,r=kt(qi,n);return m.jsx(pd,{as:I6,allowPinchZoom:!0,shards:[r.contentRef],children:m.jsx(Ce.div,{"data-state":bd(r.open),...o,ref:t,style:{pointerEvents:"auto",...o.style}})})}),kr="DialogContent",QS=_.forwardRef((e,t)=>{const n=GS(kr,e.__scopeDialog),{forceMount:o=n.forceMount,...r}=e,i=kt(kr,e.__scopeDialog);return m.jsx(Gt,{present:o||i.open,children:i.modal?m.jsx(E6,{...r,ref:t}):m.jsx(T6,{...r,ref:t})})});QS.displayName=kr;var E6=_.forwardRef((e,t)=>{const n=kt(kr,e.__scopeDialog),o=_.useRef(null),r=Ge(t,n.contentRef,o);return _.useEffect(()=>{const i=o.current;if(i)return fS(i)},[]),m.jsx(XS,{...e,ref:r,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Oe(e.onCloseAutoFocus,i=>{i.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Oe(e.onPointerDownOutside,i=>{const a=i.detail.originalEvent,s=a.button===0&&a.ctrlKey===!0;(a.button===2||s)&&i.preventDefault()}),onFocusOutside:Oe(e.onFocusOutside,i=>i.preventDefault())})}),T6=_.forwardRef((e,t)=>{const n=kt(kr,e.__scopeDialog),o=_.useRef(!1),r=_.useRef(!1);return m.jsx(XS,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{e.onCloseAutoFocus?.(i),i.defaultPrevented||(o.current||n.triggerRef.current?.focus(),i.preventDefault()),o.current=!1,r.current=!1},onInteractOutside:i=>{e.onInteractOutside?.(i),i.defaultPrevented||(o.current=!0,i.detail.originalEvent.type==="pointerdown"&&(r.current=!0));const a=i.target;n.triggerRef.current?.contains(a)&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&r.current&&i.preventDefault()}})}),XS=_.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:o,onOpenAutoFocus:r,onCloseAutoFocus:i,...a}=e,s=kt(kr,n),l=_.useRef(null),u=Ge(t,l);return cS(),m.jsxs(m.Fragment,{children:[m.jsx(dd,{asChild:!0,loop:!0,trapped:o,onMountAutoFocus:r,onUnmountAutoFocus:i,children:m.jsx(Ha,{role:"dialog",id:s.contentId,"aria-describedby":s.descriptionId,"aria-labelledby":s.titleId,"data-state":bd(s.open),...a,ref:u,onDismiss:()=>s.onOpenChange(!1)})}),m.jsxs(m.Fragment,{children:[m.jsx(N6,{titleId:s.titleId}),m.jsx(C6,{contentRef:l,descriptionId:s.descriptionId})]})]})}),yd="DialogTitle",e0=_.forwardRef((e,t)=>{const{__scopeDialog:n,...o}=e,r=kt(yd,n);return m.jsx(Ce.h2,{id:r.titleId,...o,ref:t})});e0.displayName=yd;var t0="DialogDescription",O6=_.forwardRef((e,t)=>{const{__scopeDialog:n,...o}=e,r=kt(t0,n);return m.jsx(Ce.p,{id:r.descriptionId,...o,ref:t})});O6.displayName=t0;var r0="DialogClose",n0=_.forwardRef((e,t)=>{const{__scopeDialog:n,...o}=e,r=kt(r0,n);return m.jsx(Ce.button,{type:"button",...o,ref:t,onClick:Oe(e.onClick,()=>r.onOpenChange(!1))})});n0.displayName=r0;function bd(e){return e?"open":"closed"}var o0="DialogTitleWarning",[V2,i0]=NM(o0,{contentName:kr,titleName:yd,docsSlug:"dialog"}),N6=({titleId:e})=>{const t=i0(o0),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
|
|
140
140
|
|
|
141
141
|
If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
|
|
142
142
|
|
|
143
|
-
For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return _.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},C6="DialogDescriptionWarning",j6=({contentRef:e,descriptionId:t})=>{const o=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${i0(C6).contentName}}.`;return _.useEffect(()=>{const r=e.current?.getAttribute("aria-describedby");t&&r&&(document.getElementById(t)||console.warn(o))},[o,e,t]),null},A6=JS,R6=HS,z6=KS,M6=YS,D6=QS,U6=e0,L6=n0;function Z6({...e}){return m.jsx(A6,{"data-slot":"dialog",...e})}function F6({...e}){return m.jsx(R6,{"data-slot":"dialog-trigger",...e})}function q6({...e}){return m.jsx(z6,{"data-slot":"dialog-portal",...e})}function V6({className:e,...t}){return m.jsx(M6,{"data-slot":"dialog-overlay",className:T.cn("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function B6({className:e,children:t,showCloseButton:n=!0,...o}){return m.jsxs(q6,{"data-slot":"dialog-portal",children:[m.jsx(V6,{}),m.jsxs(D6,{"data-slot":"dialog-content",className:T.cn("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...o,children:[t,n&&m.jsxs(L6,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[m.jsx(Xn,{}),m.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function J6({className:e,...t}){return m.jsx(U6,{"data-slot":"dialog-title",className:T.cn("text-lg leading-none font-semibold",e),...t})}function W6(e,t=[]){let n=[];function o(i,a){const s=_.createContext(a);s.displayName=i+"Context";const l=n.length;n=[...n,a];const u=d=>{const{scope:f,children:p,...g}=d,h=f?.[e]?.[l]||s,b=_.useMemo(()=>g,Object.values(g));return m.jsx(h.Provider,{value:b,children:p})};u.displayName=i+"Provider";function c(d,f){const p=f?.[e]?.[l]||s,g=_.useContext(p);if(g)return g;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[u,c]}const r=()=>{const i=n.map(a=>_.createContext(a));return function(s){const l=s?.[e]||i;return _.useMemo(()=>({[`__scope${e}`]:{...s,[e]:l}}),[s,l])}};return r.scopeName=e,[o,H6(r,...t)]}function H6(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const o=e.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(i){const a=o.reduce((s,{useScope:l,scopeName:u})=>{const d=l(i)[`__scope${u}`];return{...s,...d}},{});return _.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return n.scopeName=t.scopeName,n}var G6=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],_d=G6.reduce((e,t)=>{const n=x$(`Primitive.${t}`),o=_.forwardRef((r,i)=>{const{asChild:a,...s}=r,l=a?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),m.jsx(l,{...s,ref:i})});return o.displayName=`Primitive.${t}`,{...e,[t]:o}},{});function K6(){return gP.useSyncExternalStore(Y6,()=>!0,()=>!1)}function Y6(){return()=>{}}var wd="Avatar",[Q6]=W6(wd),[X6,a0]=Q6(wd),s0=_.forwardRef((e,t)=>{const{__scopeAvatar:n,...o}=e,[r,i]=_.useState("idle");return m.jsx(X6,{scope:n,imageLoadingStatus:r,onImageLoadingStatusChange:i,children:m.jsx(_d.span,{...o,ref:t})})});s0.displayName=wd;var u0="AvatarImage",l0=_.forwardRef((e,t)=>{const{__scopeAvatar:n,src:o,onLoadingStatusChange:r=()=>{},...i}=e,a=a0(u0,n),s=e2(o,i),l=Sr(u=>{r(u),a.onImageLoadingStatusChange(u)});return lt(()=>{s!=="idle"&&l(s)},[s,l]),s==="loaded"?m.jsx(_d.img,{...i,ref:t,src:o}):null});l0.displayName=u0;var c0="AvatarFallback",d0=_.forwardRef((e,t)=>{const{__scopeAvatar:n,delayMs:o,...r}=e,i=a0(c0,n),[a,s]=_.useState(o===void 0);return _.useEffect(()=>{if(o!==void 0){const l=window.setTimeout(()=>s(!0),o);return()=>window.clearTimeout(l)}},[o]),a&&i.imageLoadingStatus!=="loaded"?m.jsx(_d.span,{...r,ref:t}):null});d0.displayName=c0;function im(e,t){return e?t?(e.src!==t&&(e.src=t),e.complete&&e.naturalWidth>0?"loaded":"loading"):"error":"idle"}function e2(e,{referrerPolicy:t,crossOrigin:n}){const o=K6(),r=_.useRef(null),i=o?(r.current||(r.current=new window.Image),r.current):null,[a,s]=_.useState(()=>im(i,e));return lt(()=>{s(im(i,e))},[i,e]),lt(()=>{const l=d=>()=>{s(d)};if(!i)return;const u=l("loaded"),c=l("error");return i.addEventListener("load",u),i.addEventListener("error",c),t&&(i.referrerPolicy=t),typeof n=="string"&&(i.crossOrigin=n),()=>{i.removeEventListener("load",u),i.removeEventListener("error",c)}},[i,n,t]),a}var t2=s0,r2=l0,n2=d0;function o2({className:e,...t}){return m.jsx(t2,{"data-slot":"avatar",className:T.cn("relative flex size-8 shrink-0 overflow-hidden rounded-full",e),...t})}function i2({className:e,...t}){return m.jsx(r2,{"data-slot":"avatar-image",className:T.cn("aspect-square size-full",e),...t})}function a2({className:e,...t}){return m.jsx(n2,{"data-slot":"avatar-fallback",className:T.cn("bg-muted flex size-full items-center justify-center rounded-full",e),...t})}const s2=e=>{const[t,n]=D.useState(void 0);return D.useEffect(()=>{if(!e){n(void 0);return}const o=URL.createObjectURL(e);return n(o),()=>{URL.revokeObjectURL(o)}},[e]),t},p0=()=>{const{file:e,src:t}=L.useAssistantState(x0.useShallow(({attachment:n})=>{if(n.type!=="image")return{};if(n.file)return{file:n.file};const o=n.content?.filter(r=>r.type==="image")[0]?.image;return o?{src:o}:{}}));return s2(e)??t},u2=({src:e})=>{const[t,n]=D.useState(!1);return m.jsx("img",{src:e,alt:"Image Preview",className:t?"aui-attachment-preview-image-loaded block h-auto max-h-[80vh] w-auto max-w-full object-contain":"aui-attachment-preview-image-loading hidden",onLoad:()=>n(!0)})},l2=({children:e})=>{const t=p0();return t?m.jsxs(Z6,{children:[m.jsx(F6,{className:"aui-attachment-preview-trigger hover:bg-accent/50 cursor-pointer transition-colors",asChild:!0,children:e}),m.jsxs(B6,{className:"aui-attachment-preview-dialog-content [&_svg]:text-background [&>button]:bg-foreground/60 [&>button]:hover:[&_svg]:text-destructive p-2 sm:max-w-3xl [&>button]:rounded-full [&>button]:p-1 [&>button]:opacity-100 [&>button]:!ring-0",children:[m.jsx(J6,{className:"aui-sr-only sr-only",children:"Image Attachment Preview"}),m.jsx("div",{className:"aui-attachment-preview bg-background relative mx-auto flex max-h-[80dvh] w-full items-center justify-center overflow-hidden",children:m.jsx(u2,{src:t})})]})]}):e},c2=()=>{const e=L.useAssistantState(({attachment:n})=>n.type==="image"),t=p0();return m.jsxs(o2,{className:"aui-attachment-tile-avatar h-full w-full rounded-none",children:[m.jsx(i2,{src:t,alt:"Attachment preview",className:"aui-attachment-tile-image object-cover"}),m.jsx(a2,{delayMs:e?200:0,children:m.jsx(M0,{className:"aui-attachment-tile-fallback-icon text-muted-foreground size-8"})})]})},f0=()=>{const t=L.useAssistantApi().attachment.source==="composer",n=L.useAssistantState(({attachment:r})=>r.type==="image"),o=L.useAssistantState(({attachment:r})=>{const i=r.type;switch(i){case"image":return"Image";case"document":return"Document";case"file":return"File";default:{const a=i;throw new Error(`Unknown attachment type: ${a}`)}}});return m.jsxs(ud,{children:[m.jsxs(L.AttachmentPrimitive.Root,{className:T.cn("aui-attachment-root relative",n&&"aui-attachment-root-composer only:[&>#attachment-tile]:size-24"),children:[m.jsx(l2,{children:m.jsx(ld,{asChild:!0,children:m.jsx("div",{className:T.cn("aui-attachment-tile bg-muted size-14 cursor-pointer overflow-hidden rounded-[14px] border transition-opacity hover:opacity-75",t&&"aui-attachment-tile-composer border-foreground/20"),role:"button",id:"attachment-tile","aria-label":`${o} attachment`,children:m.jsx(c2,{})})})}),t&&m.jsx(d2,{})]}),m.jsx(cd,{side:"top",children:m.jsx(L.AttachmentPrimitive.Name,{})})]})},d2=()=>m.jsx(L.AttachmentPrimitive.Remove,{asChild:!0,children:m.jsx(ct,{tooltip:"Remove file",className:"aui-attachment-tile-remove text-muted-foreground hover:[&_svg]:text-destructive absolute top-1.5 right-1.5 size-3.5 rounded-full bg-white opacity-100 shadow-sm hover:!bg-white [&_svg]:text-black",side:"top",children:m.jsx(Xn,{className:"aui-attachment-remove-icon size-3 dark:stroke-[2.5px]"})})}),p2=()=>m.jsx("div",{className:"aui-user-message-attachments-end col-span-full col-start-1 row-start-1 flex w-full flex-row justify-end gap-2",children:m.jsx(L.MessagePrimitive.Attachments,{components:{Attachment:f0}})}),f2=()=>m.jsx("div",{className:"aui-composer-attachments mb-2 flex w-full flex-row items-center gap-2 overflow-x-auto px-1.5 pt-0.5 pb-1 empty:hidden",children:m.jsx(L.ComposerPrimitive.Attachments,{components:{Attachment:f0}})}),m2=()=>m.jsx(L.ComposerPrimitive.AddAttachment,{asChild:!0,children:m.jsx(ct,{tooltip:"Add Attachment",side:"top",variant:"ghost",size:"icon",align:"start",className:"aui-composer-add-attachment hover:bg-muted-foreground/15 dark:border-muted-foreground/15 dark:hover:bg-muted-foreground/30 size-[34px] rounded-full p-1 text-xs font-semibold","aria-label":"Add Attachment",children:m.jsx(Q0,{className:"aui-attachment-add-icon size-5 stroke-[1.5px]"})})}),xd=()=>{const{config:e}=T.useElements(),t=e.theme??{};return D.useMemo(()=>{const{colorScheme:n="light"}=t;return{className:n==="dark"||n==="system"&&typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":void 0}},[t])},or=[.23,1,.32,1];function h2(e){return e.replace(/[-_]/g," ").split(/(?=[A-Z])/).join(" ").split(/\s+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" ")}const g2=({children:e})=>{const t=L.useAssistantState(({message:s})=>s).parts,n=t.filter(s=>s.type==="tool-call"),o=n.some(s=>s.status?.type==="running"),{config:r}=T.useElements(),i=r.tools?.expandToolGroupsByDefault??!1,a=D.useMemo(()=>{const s=t.filter(l=>l.type==="tool-call");return s.length===0?"No tools called":s.length===1?`Calling ${h2(s[0].toolName)}...`:o?`Calling ${s.length} tools...`:`Executed ${s.length} tools`},[t,o]);return r.tools?.components?.[n[0]?.toolName]?e:n.length===1?m.jsx("div",{className:T.cn("my-4 w-full max-w-xl"),children:m.jsx("div",{className:"border-border bg-card overflow-hidden rounded-lg border",children:e})}):m.jsx("div",{className:"my-4 w-full max-w-xl",children:m.jsx(d6,{title:a,status:o?"running":"complete",defaultExpanded:i,children:e})})},$d=()=>{const e=xd(),t=T.useDensity(),{config:n}=T.useElements(),o=n.components??{};return m.jsx(Zt.LazyMotion,{features:Zt.domAnimation,children:m.jsx(Zt.MotionConfig,{reducedMotion:"user",children:m.jsx(L.ThreadPrimitive.Root,{className:T.cn("aui-root aui-thread-root bg-background @container flex h-full flex-col",e.className),children:m.jsxs(L.ThreadPrimitive.Viewport,{className:T.cn("aui-thread-viewport relative mx-auto flex w-full flex-1 flex-col overflow-x-auto overflow-y-scroll pb-0!",t("p-lg")),children:[m.jsx(L.ThreadPrimitive.If,{empty:!0,children:o.ThreadWelcome?m.jsx(o.ThreadWelcome,{}):m.jsx(y2,{})}),m.jsx(L.ThreadPrimitive.Messages,{components:{UserMessage:o.UserMessage??E2,EditComposer:o.EditComposer??O2,AssistantMessage:o.AssistantMessage??S2}}),m.jsx(L.ThreadPrimitive.If,{empty:!1,children:m.jsx("div",{className:"aui-thread-viewport-spacer min-h-8 grow"})}),m.jsx(_2,{})]})})})})},v2=()=>m.jsx(L.ThreadPrimitive.ScrollToBottom,{asChild:!0,children:m.jsx(ct,{tooltip:"Scroll to bottom",variant:"outline",className:"aui-thread-scroll-to-bottom dark:bg-background dark:hover:bg-accent absolute -top-12 z-10 self-center rounded-full p-4 disabled:invisible",children:m.jsx(I0,{})})}),y2=()=>{const{config:e}=T.useElements(),t=T.useDensity(),{title:n,subtitle:o}=e.welcome??{},r=e.variant==="standalone";return m.jsxs("div",{className:T.cn("aui-thread-welcome-root my-auto flex w-full grow flex-col",r?"items-center justify-center":"",t("gap-lg")),children:[m.jsx("div",{className:T.cn("aui-thread-welcome-center flex w-full grow flex-col items-center justify-start"),children:m.jsxs("div",{className:T.cn("aui-thread-welcome-message flex flex-col",r?"items-center text-center":"size-full justify-start",t("gap-sm"),!r&&t("py-md")),children:[m.jsx(Lt.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},transition:{duration:.25,ease:or},className:T.cn("aui-thread-welcome-message-motion-1 font-semibold",t("text-title")),children:n}),m.jsx(Lt.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},transition:{duration:.25,delay:.05,ease:or},className:T.cn("aui-thread-welcome-message-motion-2 text-muted-foreground/65",t("text-subtitle")),children:o})]})}),m.jsx(b2,{})]})},b2=()=>{const{config:e,isLoadingMCPTools:t}=T.useElements(),n=T.useRadius(),o=T.useDensity(),r=e.welcome?.suggestions??[],i=e.variant==="standalone";return r.length===0?null:m.jsx("div",{className:T.cn("aui-thread-welcome-suggestions w-full",o("gap-md"),o("py-lg"),i?"flex flex-wrap items-center justify-center":r.length===1?"flex":"grid max-w-fit @md:grid-cols-2"),children:r.map((a,s)=>m.jsx(Lt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:20},transition:{duration:.25,delay:.03*s,ease:or},className:T.cn("aui-thread-welcome-suggestion-display",!i&&"nth-[n+3]:hidden @md:nth-[n+3]:block"),children:m.jsx(L.ThreadPrimitive.Suggestion,{disabled:t,prompt:a.action,send:!0,asChild:!0,children:m.jsxs($t,{variant:"ghost",className:T.cn("aui-thread-welcome-suggestion dark:hover:bg-accent/60 h-auto w-full border text-left whitespace-break-spaces",o("text-base"),i?`flex-row items-center ${o("gap-sm")} ${o("px-md")} ${o("py-sm")} ${n("full")}`:`w-full flex-1 flex-col flex-wrap items-start justify-start ${o("gap-sm")} ${o("px-lg")} ${o("py-md")} ${n("xl")}`),"aria-label":a.action,children:[m.jsx("span",{className:"aui-thread-welcome-suggestion-text-1 text-sm font-medium",children:a.title}),m.jsx("span",{className:"aui-thread-welcome-suggestion-text-2 text-muted-foreground text-sm",children:a.label})]})})},`suggested-action-${a.title}-${s}`))})},_2=()=>{const{config:e}=T.useElements(),t=T.useRadius(),n=T.useDensity(),o=e.composer??{placeholder:"Send a message...",attachments:!0},r=e.components??{},{isLoadingMCPTools:i}=T.useElements();return r.Composer?m.jsx(r.Composer,{}):m.jsxs("div",{className:T.cn("aui-composer-wrapper bg-background sticky bottom-0 flex w-full flex-col overflow-visible",n("gap-md"),n("py-md"),t("xl")),children:[m.jsx(v2,{}),m.jsxs(L.ComposerPrimitive.Root,{className:T.cn("aui-composer-root group/input-group border-input bg-background has-[textarea:focus-visible]:border-ring has-[textarea:focus-visible]:ring-ring/5 dark:bg-background relative flex w-full flex-col border px-1 pt-2 shadow-xs transition-[color,box-shadow] outline-none has-[textarea:focus-visible]:ring-1",t("xl")),children:[o.attachments&&m.jsx(f2,{}),m.jsx(L.ComposerPrimitive.Input,{placeholder:o.placeholder,className:T.cn("aui-composer-input placeholder:text-muted-foreground mb-1 max-h-32 w-full resize-none bg-transparent px-3.5 pt-1.5 pb-3 outline-none focus-visible:ring-0",n("h-input"),n("text-base")),rows:1,autoFocus:!0,disabled:i,"aria-label":"Message input"}),m.jsx(x2,{})]})]})},w2=()=>{const{model:e,setModel:t}=T.useElements(),[n,o]=D.useState(!1),[r,i]=D.useState(!1),a=D.useRef(null),s=D.useRef(0),l=D.useRef(!1);D.useEffect(()=>{n&&!l.current&&requestAnimationFrame(()=>{const c=a.current;c&&c.scrollHeight>0&&(c.scrollTop=s.current)}),l.current=n},[n]),D.useEffect(()=>{n&&i(!1)},[n]);const u=c=>{s.current=c.currentTarget.scrollTop};return m.jsx(uS,{children:m.jsxs(ud,{open:r&&!n,onOpenChange:i,children:[m.jsxs(PS,{open:n,onOpenChange:o,children:[m.jsx(ld,{asChild:!0,children:m.jsx(CS,{asChild:!0,children:m.jsx($t,{variant:"ghost",size:"icon","data-state":n?"open":"closed",className:"aui-composer-model-picker data-[state=open]:bg-muted-foreground/15 dark:border-muted-foreground/15 dark:hover:bg-muted-foreground/30 flex w-fit items-center gap-2 rounded-full px-2.5 py-1 text-xs font-semibold","aria-label":"Model Settings",children:m.jsx(rI,{className:"aui-attachment-add-icon size-5 stroke-[1.5px]"})})})}),m.jsx(jS,{side:"top",align:"start",className:"w-min p-0 shadow-none",children:m.jsx("div",{ref:a,className:"max-h-48 overflow-y-auto",onScroll:u,children:Mu.map(c=>m.jsxs($t,{onClick:()=>{t(c)},variant:"ghost",className:"w-full justify-start gap-2 rounded-none px-2",children:[c===e?m.jsx("div",{children:m.jsx(rr,{className:"size-4 text-emerald-500"})}):m.jsx("div",{className:"size-4",children:" "}),c]},c))})})]}),m.jsx(cd,{side:"bottom",align:"start",children:"Model Settings"})]})})},x2=()=>{const{config:e}=T.useElements(),t=T.useRadius(),n=e.composer??{attachments:!0};return m.jsxs("div",{className:"aui-composer-action-wrapper relative mx-1 mt-2 mb-2 flex items-center justify-between",children:[m.jsxs("div",{className:"aui-composer-action-wrapper-inner flex items-center",children:[n.attachments?m.jsx(m2,{}):m.jsx("div",{className:"aui-composer-add-attachment-placeholder"}),e.model?.showModelPicker&&!e.languageModel&&m.jsx(w2,{})]}),m.jsx(L.ThreadPrimitive.If,{running:!1,children:m.jsx(L.ComposerPrimitive.Send,{asChild:!0,children:m.jsx(ct,{tooltip:"Send message",side:"bottom",type:"submit",variant:"default",size:"icon",className:T.cn("aui-composer-send size-[34px] p-1",t("full")),"aria-label":"Send message",children:m.jsx(E0,{className:"aui-composer-send-icon size-5"})})})}),m.jsx(L.ThreadPrimitive.If,{running:!0,children:m.jsx(L.ComposerPrimitive.Cancel,{asChild:!0,children:m.jsx($t,{type:"button",variant:"default",size:"icon",className:T.cn("aui-composer-cancel border-muted-foreground/60 hover:bg-primary/75 dark:border-muted-foreground/90 size-[34px] border",t("full")),"aria-label":"Stop generating",children:m.jsx(oI,{className:"aui-composer-cancel-icon size-3.5 fill-white dark:fill-black"})})})})]})},$2=()=>m.jsx(L.MessagePrimitive.Error,{children:m.jsx(L.ErrorPrimitive.Root,{className:"aui-message-error-root border-destructive bg-destructive/10 text-destructive dark:bg-destructive/5 mt-2 rounded-md border p-3 text-sm dark:text-red-200",children:m.jsx(L.ErrorPrimitive.Message,{className:"aui-message-error-message line-clamp-2"})})}),S2=()=>{const{config:e}=T.useElements(),t=e.tools??{},n=e.components??{};return m.jsx(L.MessagePrimitive.Root,{asChild:!0,children:m.jsxs("div",{className:"aui-assistant-message-root animate-in fade-in slide-in-from-bottom-1 relative mx-auto w-full py-4 duration-150 ease-out last:mb-24","data-role":"assistant",children:[m.jsxs("div",{className:"aui-assistant-message-content text-foreground mx-2 leading-7 wrap-break-word",children:[m.jsx(L.MessagePrimitive.Parts,{components:{Text:n.Text??lS,Image:n.Image??I2,tools:{by_name:t.components,Fallback:n.ToolFallback??p6},Reasoning:n.Reasoning??qS,ReasoningGroup:n.ReasoningGroup??VS,ToolGroup:n.ToolGroup??g2}}),m.jsx($2,{})]}),m.jsxs("div",{className:"aui-assistant-message-footer mt-2 ml-2 flex",children:[m.jsx(m0,{}),m.jsx(k2,{})]})]})})},I2=e=>m.jsx("img",{src:e.image}),k2=()=>m.jsxs(L.ActionBarPrimitive.Root,{hideWhenRunning:!0,autohide:"not-last",autohideFloat:"single-branch",className:"aui-assistant-action-bar-root text-muted-foreground data-floating:bg-background col-start-3 row-start-2 -ml-1 flex gap-1 data-floating:absolute data-floating:rounded-md data-floating:border data-floating:p-1 data-floating:shadow-sm",children:[m.jsx(L.ActionBarPrimitive.Copy,{asChild:!0,children:m.jsxs(ct,{tooltip:"Copy",children:[m.jsx(L.MessagePrimitive.If,{copied:!0,children:m.jsx(rr,{})}),m.jsx(L.MessagePrimitive.If,{copied:!1,children:m.jsx(Du,{})})]})}),m.jsx(L.ActionBarPrimitive.Reload,{asChild:!0,children:m.jsx(ct,{tooltip:"Refresh",children:m.jsx(eI,{})})})]}),E2=()=>{const e=T.useRadius();return m.jsx(L.MessagePrimitive.Root,{asChild:!0,children:m.jsxs("div",{className:"aui-user-message-root animate-in fade-in slide-in-from-bottom-1 mx-auto grid w-full auto-rows-auto grid-cols-[minmax(72px,1fr)_auto] gap-y-2 px-2 py-4 duration-150 ease-out first:mt-3 last:mb-5 [&:where(>*)]:col-start-2","data-role":"user",children:[m.jsx(p2,{}),m.jsxs("div",{className:"aui-user-message-content-wrapper relative col-start-2 min-w-0",children:[m.jsx("div",{className:T.cn("aui-user-message-content bg-muted text-foreground px-5 py-2.5 wrap-break-word",e("xl")),children:m.jsx(L.MessagePrimitive.Parts,{})}),m.jsx("div",{className:"aui-user-action-bar-wrapper absolute top-1/2 left-0 -translate-x-full -translate-y-1/2 pr-2",children:m.jsx(T2,{})})]}),m.jsx(m0,{className:"aui-user-branch-picker col-span-full col-start-1 row-start-3 -mr-1 justify-end"})]})})},T2=()=>m.jsx(L.ActionBarPrimitive.Root,{hideWhenRunning:!0,autohide:"not-last",className:"aui-user-action-bar-root flex flex-col items-end",children:m.jsx(L.ActionBarPrimitive.Edit,{asChild:!0,children:m.jsx(ct,{tooltip:"Edit",className:"aui-user-action-edit p-4",children:m.jsx(K0,{})})})}),O2=()=>m.jsx("div",{className:"aui-edit-composer-wrapper mx-auto flex w-full flex-col gap-4 px-2 first:mt-4",children:m.jsxs(L.ComposerPrimitive.Root,{className:"aui-edit-composer-root bg-muted ml-auto flex w-full max-w-7/8 flex-col rounded-xl",children:[m.jsx(L.ComposerPrimitive.Input,{className:"aui-edit-composer-input text-foreground flex min-h-[60px] w-full resize-none bg-transparent p-4 outline-none",autoFocus:!0}),m.jsxs("div",{className:"aui-edit-composer-footer mx-3 mb-3 flex items-center justify-center gap-2 self-end",children:[m.jsx(L.ComposerPrimitive.Cancel,{asChild:!0,children:m.jsx($t,{variant:"ghost",size:"sm","aria-label":"Cancel edit",children:"Cancel"})}),m.jsx(L.ComposerPrimitive.Send,{asChild:!0,children:m.jsx($t,{size:"sm","aria-label":"Update message",children:"Update"})})]})]})}),m0=({className:e,...t})=>m.jsxs(L.BranchPickerPrimitive.Root,{hideWhenSingleBranch:!0,className:T.cn("aui-branch-picker-root text-muted-foreground mr-2 -ml-2 inline-flex items-center text-xs",e),...t,children:[m.jsx(L.BranchPickerPrimitive.Previous,{asChild:!0,children:m.jsx(ct,{tooltip:"Previous",children:m.jsx(j0,{})})}),m.jsxs("span",{className:"aui-branch-picker-state font-medium",children:[m.jsx(L.BranchPickerPrimitive.Number,{})," / ",m.jsx(L.BranchPickerPrimitive.Count,{})]}),m.jsx(L.BranchPickerPrimitive.Next,{asChild:!0,children:m.jsx(ct,{tooltip:"Next",children:m.jsx(um,{})})})]}),h0=()=>{const{config:e,isExpanded:t,setIsExpanded:n}=T.useElements(),o=e.modal?.defaultExpanded??!1;return{expandable:e.modal?.expandable??!1,isExpanded:t,setIsExpanded:n,defaultExpanded:o}},N2={layout:{duration:.25,ease:or}},P2=()=>{const{config:e}=T.useElements(),t=xd(),n=T.useRadius(),o=T.useDensity(),[r,i]=D.useState(e.modal?.defaultOpen??!1),{expandable:a,isExpanded:s,setIsExpanded:l}=h0(),u=e.modal?.title,c=e.modal?.icon,d=e.modal?.position??"bottom-right",f=C2(d),p=D.useMemo(()=>e.modal?.dimensions?.default??{width:"500px",height:"600px",maxHeight:"95vh"},[e.modal?.dimensions?.default]),g=D.useMemo(()=>e.modal?.dimensions?.expanded??{width:"70vw",height:"90vh"},[e.modal?.dimensions?.expanded]),b=L.useAssistantState(({thread:v})=>v).messages.some(v=>v.status?.type==="running"),y=s?g.width:p.width,x=s?g.height:p.height,$=p.maxHeight;return m.jsx(Zt.LazyMotion,{features:Zt.domMax,children:m.jsx(Zt.MotionConfig,{reducedMotion:"user",transition:N2,children:m.jsx("div",{className:T.cn("aui-root aui-modal-anchor fixed z-10",f,t.className,n("lg"),r&&"shadow-xl"),children:m.jsx(Zt.AnimatePresence,{mode:"wait",children:r?m.jsxs(Lt.div,{layout:!0,layoutId:"chat-container",className:T.cn("aui-modal-content bg-popover text-popover-foreground flex flex-col overflow-hidden border [&>.aui-thread-root]:bg-inherit",n("lg")),initial:!1,style:{originX:d.includes("left")?0:1,originY:d.includes("top")?0:1,width:y,height:x,maxHeight:$},children:[m.jsxs(Lt.div,{className:T.cn("aui-modal-header flex shrink-0 items-center justify-between border-b",o("h-header"),o("px-lg")),initial:{opacity:0},animate:{opacity:1},transition:{duration:.2,delay:.1,ease:or},children:[m.jsx("div",{className:T.cn("flex min-w-0 items-center"),children:m.jsxs("span",{className:T.cn("text-md flex items-center gap-2 truncate font-medium",b&&"shimmer"),children:[m.jsx("span",{className:"truncate",children:u}),b&&m.jsx(Hs,{className:"text-muted-foreground size-4.5 animate-spin",strokeWidth:1.25})]})}),m.jsxs("div",{className:"flex flex-row items-center justify-end gap-1",children:[a?m.jsx("button",{type:"button",onClick:()=>l(v=>!v),className:T.cn("text-muted-foreground hover:text-foreground hover:bg-accent flex h-8 cursor-pointer items-center rounded-md px-2 text-xs transition-colors"),"aria-pressed":s,"aria-label":s?"Collapse assistant":"Expand assistant",children:s?m.jsx(V0,{strokeWidth:2,className:"size-3.5 rotate-90"}):m.jsx(L0,{strokeWidth:2,className:"size-3.5 rotate-90"})}):null,m.jsx("button",{onClick:()=>{i(!1),l(!1)},className:"text-muted-foreground hover:text-foreground hover:bg-accent -mr-1 flex size-8 cursor-pointer items-center justify-center rounded-md transition-colors","aria-label":`Close ${u}`,children:m.jsx(Xn,{className:"size-4.5"})})]})]}),m.jsx(Lt.div,{className:"aui-modal-thread w-full flex-1 overflow-hidden",initial:{opacity:0},animate:{opacity:1},transition:{duration:.2,delay:.05,ease:or},children:m.jsx($d,{})})]},"chat"):m.jsx(Lt.button,{layout:!0,layoutId:"chat-container",onClick:()=>i(!0),className:T.cn("aui-modal-button bg-primary text-primary-foreground flex size-12 cursor-pointer items-center justify-center border shadow-lg transition-shadow hover:shadow-xl",n("full")),initial:!1,"aria-label":`Open ${u}`,style:{originX:1,originY:1},children:m.jsx(Lt.div,{initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.8},transition:{duration:.2,ease:or},className:"flex size-full items-center justify-center",children:c?c("closed"):m.jsx(F0,{className:"size-6"})})},"button")})})})})};function C2(e){switch(e){case"bottom-left":return"left-4 bottom-4";case"top-right":return"right-4 top-4";case"top-left":return"left-4 top-4";case"bottom-right":return"right-4 bottom-4";default:T.assertNever(e)}}const j2=()=>{const{config:e}=T.useElements(),t=xd(),n=e.sidecar??{},{title:o,dimensions:r}=n,{isExpanded:i,setIsExpanded:a}=h0(),l=L.useAssistantState(({thread:u})=>u).messages.some(u=>u.status?.type==="running");return m.jsx(Zt.LazyMotion,{features:Zt.domMax,children:m.jsxs(Lt.div,{initial:{width:r?.default?.width??"400px",height:r?.default?.height??"100vh"},animate:{width:i?r?.expanded?.width??"800px":r?.default?.width??"400px",height:i?r?.expanded?.height??"100%":r?.default?.height??"100vh"},transition:{duration:.3,ease:or},className:T.cn("aui-root aui-sidecar bg-popover text-popover-foreground fixed top-0 right-0 border-l",t.className),children:[m.jsxs("div",{className:"aui-sidecar-header flex h-14 items-center justify-between border-b px-4",children:[m.jsx("span",{className:T.cn("flex items-center gap-2 text-sm font-medium",l&&"shimmer"),children:o}),m.jsx("div",{className:"aui-sidecar-header-actions flex items-center gap-1",children:m.jsx(ct,{tooltip:i?"Collapse":"Pop out",variant:"ghost",className:"aui-sidecar-popout size-8",onClick:()=>a(u=>!u),children:i?m.jsx(J0,{className:"size-4.5"}):m.jsx(H0,{className:"size-4.5"})})})]}),m.jsx("div",{className:"aui-sidecar-content h-[calc(100%-3.5rem)] overflow-hidden",children:m.jsx($d,{})})]})})},A2=()=>{const{config:e}=T.useElements();switch(e.variant){case"standalone":return m.jsx($d,{});case"sidecar":return m.jsx(j2,{});case"widget":return m.jsx(P2,{});default:T.assertNever(e.variant)}};exports.useGramElements=T.useElements;exports.Chat=A2;exports.GramElementsProvider=_M;exports.MODELS=Mu;exports.defineFrontendTool=fR;
|
|
143
|
+
For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return _.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},P6="DialogDescriptionWarning",C6=({contentRef:e,descriptionId:t})=>{const o=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${i0(P6).contentName}}.`;return _.useEffect(()=>{const r=e.current?.getAttribute("aria-describedby");t&&r&&(document.getElementById(t)||console.warn(o))},[o,e,t]),null},j6=JS,A6=HS,R6=KS,z6=YS,M6=QS,D6=e0,U6=n0;function L6({...e}){return m.jsx(j6,{"data-slot":"dialog",...e})}function Z6({...e}){return m.jsx(A6,{"data-slot":"dialog-trigger",...e})}function F6({...e}){return m.jsx(R6,{"data-slot":"dialog-portal",...e})}function q6({className:e,...t}){return m.jsx(z6,{"data-slot":"dialog-overlay",className:T.cn("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function V6({className:e,children:t,showCloseButton:n=!0,...o}){return m.jsxs(F6,{"data-slot":"dialog-portal",children:[m.jsx(q6,{}),m.jsxs(M6,{"data-slot":"dialog-content",className:T.cn("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...o,children:[t,n&&m.jsxs(U6,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[m.jsx(Xn,{}),m.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function B6({className:e,...t}){return m.jsx(D6,{"data-slot":"dialog-title",className:T.cn("text-lg leading-none font-semibold",e),...t})}function J6(e,t=[]){let n=[];function o(i,a){const s=_.createContext(a);s.displayName=i+"Context";const l=n.length;n=[...n,a];const u=d=>{const{scope:f,children:p,...g}=d,h=f?.[e]?.[l]||s,b=_.useMemo(()=>g,Object.values(g));return m.jsx(h.Provider,{value:b,children:p})};u.displayName=i+"Provider";function c(d,f){const p=f?.[e]?.[l]||s,g=_.useContext(p);if(g)return g;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[u,c]}const r=()=>{const i=n.map(a=>_.createContext(a));return function(s){const l=s?.[e]||i;return _.useMemo(()=>({[`__scope${e}`]:{...s,[e]:l}}),[s,l])}};return r.scopeName=e,[o,W6(r,...t)]}function W6(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const o=e.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(i){const a=o.reduce((s,{useScope:l,scopeName:u})=>{const d=l(i)[`__scope${u}`];return{...s,...d}},{});return _.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return n.scopeName=t.scopeName,n}var H6=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],_d=H6.reduce((e,t)=>{const n=x$(`Primitive.${t}`),o=_.forwardRef((r,i)=>{const{asChild:a,...s}=r,l=a?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),m.jsx(l,{...s,ref:i})});return o.displayName=`Primitive.${t}`,{...e,[t]:o}},{});function G6(){return gP.useSyncExternalStore(K6,()=>!0,()=>!1)}function K6(){return()=>{}}var wd="Avatar",[Y6]=J6(wd),[Q6,a0]=Y6(wd),s0=_.forwardRef((e,t)=>{const{__scopeAvatar:n,...o}=e,[r,i]=_.useState("idle");return m.jsx(Q6,{scope:n,imageLoadingStatus:r,onImageLoadingStatusChange:i,children:m.jsx(_d.span,{...o,ref:t})})});s0.displayName=wd;var u0="AvatarImage",l0=_.forwardRef((e,t)=>{const{__scopeAvatar:n,src:o,onLoadingStatusChange:r=()=>{},...i}=e,a=a0(u0,n),s=X6(o,i),l=Sr(u=>{r(u),a.onImageLoadingStatusChange(u)});return lt(()=>{s!=="idle"&&l(s)},[s,l]),s==="loaded"?m.jsx(_d.img,{...i,ref:t,src:o}):null});l0.displayName=u0;var c0="AvatarFallback",d0=_.forwardRef((e,t)=>{const{__scopeAvatar:n,delayMs:o,...r}=e,i=a0(c0,n),[a,s]=_.useState(o===void 0);return _.useEffect(()=>{if(o!==void 0){const l=window.setTimeout(()=>s(!0),o);return()=>window.clearTimeout(l)}},[o]),a&&i.imageLoadingStatus!=="loaded"?m.jsx(_d.span,{...r,ref:t}):null});d0.displayName=c0;function im(e,t){return e?t?(e.src!==t&&(e.src=t),e.complete&&e.naturalWidth>0?"loaded":"loading"):"error":"idle"}function X6(e,{referrerPolicy:t,crossOrigin:n}){const o=G6(),r=_.useRef(null),i=o?(r.current||(r.current=new window.Image),r.current):null,[a,s]=_.useState(()=>im(i,e));return lt(()=>{s(im(i,e))},[i,e]),lt(()=>{const l=d=>()=>{s(d)};if(!i)return;const u=l("loaded"),c=l("error");return i.addEventListener("load",u),i.addEventListener("error",c),t&&(i.referrerPolicy=t),typeof n=="string"&&(i.crossOrigin=n),()=>{i.removeEventListener("load",u),i.removeEventListener("error",c)}},[i,n,t]),a}var e2=s0,t2=l0,r2=d0;function n2({className:e,...t}){return m.jsx(e2,{"data-slot":"avatar",className:T.cn("relative flex size-8 shrink-0 overflow-hidden rounded-full",e),...t})}function o2({className:e,...t}){return m.jsx(t2,{"data-slot":"avatar-image",className:T.cn("aspect-square size-full",e),...t})}function i2({className:e,...t}){return m.jsx(r2,{"data-slot":"avatar-fallback",className:T.cn("bg-muted flex size-full items-center justify-center rounded-full",e),...t})}const a2=e=>{const[t,n]=D.useState(void 0);return D.useEffect(()=>{if(!e){n(void 0);return}const o=URL.createObjectURL(e);return n(o),()=>{URL.revokeObjectURL(o)}},[e]),t},p0=()=>{const{file:e,src:t}=L.useAssistantState(x0.useShallow(({attachment:n})=>{if(n.type!=="image")return{};if(n.file)return{file:n.file};const o=n.content?.filter(r=>r.type==="image")[0]?.image;return o?{src:o}:{}}));return a2(e)??t},s2=({src:e})=>{const[t,n]=D.useState(!1);return m.jsx("img",{src:e,alt:"Image Preview",className:t?"aui-attachment-preview-image-loaded block h-auto max-h-[80vh] w-auto max-w-full object-contain":"aui-attachment-preview-image-loading hidden",onLoad:()=>n(!0)})},u2=({children:e})=>{const t=p0();return t?m.jsxs(L6,{children:[m.jsx(Z6,{className:"aui-attachment-preview-trigger hover:bg-accent/50 cursor-pointer transition-colors",asChild:!0,children:e}),m.jsxs(V6,{className:"aui-attachment-preview-dialog-content [&_svg]:text-background [&>button]:bg-foreground/60 [&>button]:hover:[&_svg]:text-destructive p-2 sm:max-w-3xl [&>button]:rounded-full [&>button]:p-1 [&>button]:opacity-100 [&>button]:!ring-0",children:[m.jsx(B6,{className:"aui-sr-only sr-only",children:"Image Attachment Preview"}),m.jsx("div",{className:"aui-attachment-preview bg-background relative mx-auto flex max-h-[80dvh] w-full items-center justify-center overflow-hidden",children:m.jsx(s2,{src:t})})]})]}):e},l2=()=>{const e=L.useAssistantState(({attachment:n})=>n.type==="image"),t=p0();return m.jsxs(n2,{className:"aui-attachment-tile-avatar h-full w-full rounded-none",children:[m.jsx(o2,{src:t,alt:"Attachment preview",className:"aui-attachment-tile-image object-cover"}),m.jsx(i2,{delayMs:e?200:0,children:m.jsx(M0,{className:"aui-attachment-tile-fallback-icon text-muted-foreground size-8"})})]})},f0=()=>{const t=L.useAssistantApi().attachment.source==="composer",n=L.useAssistantState(({attachment:r})=>r.type==="image"),o=L.useAssistantState(({attachment:r})=>{const i=r.type;switch(i){case"image":return"Image";case"document":return"Document";case"file":return"File";default:{const a=i;throw new Error(`Unknown attachment type: ${a}`)}}});return m.jsxs(ud,{children:[m.jsxs(L.AttachmentPrimitive.Root,{className:T.cn("aui-attachment-root relative",n&&"aui-attachment-root-composer only:[&>#attachment-tile]:size-24"),children:[m.jsx(u2,{children:m.jsx(ld,{asChild:!0,children:m.jsx("div",{className:T.cn("aui-attachment-tile bg-muted size-14 cursor-pointer overflow-hidden rounded-[14px] border transition-opacity hover:opacity-75",t&&"aui-attachment-tile-composer border-foreground/20"),role:"button",id:"attachment-tile","aria-label":`${o} attachment`,children:m.jsx(l2,{})})})}),t&&m.jsx(c2,{})]}),m.jsx(cd,{side:"top",children:m.jsx(L.AttachmentPrimitive.Name,{})})]})},c2=()=>m.jsx(L.AttachmentPrimitive.Remove,{asChild:!0,children:m.jsx(ct,{tooltip:"Remove file",className:"aui-attachment-tile-remove text-muted-foreground hover:[&_svg]:text-destructive absolute top-1.5 right-1.5 size-3.5 rounded-full bg-white opacity-100 shadow-sm hover:!bg-white [&_svg]:text-black",side:"top",children:m.jsx(Xn,{className:"aui-attachment-remove-icon size-3 dark:stroke-[2.5px]"})})}),d2=()=>m.jsx("div",{className:"aui-user-message-attachments-end col-span-full col-start-1 row-start-1 flex w-full flex-row justify-end gap-2",children:m.jsx(L.MessagePrimitive.Attachments,{components:{Attachment:f0}})}),p2=()=>m.jsx("div",{className:"aui-composer-attachments mb-2 flex w-full flex-row items-center gap-2 overflow-x-auto px-1.5 pt-0.5 pb-1 empty:hidden",children:m.jsx(L.ComposerPrimitive.Attachments,{components:{Attachment:f0}})}),f2=()=>m.jsx(L.ComposerPrimitive.AddAttachment,{asChild:!0,children:m.jsx(ct,{tooltip:"Add Attachment",side:"top",variant:"ghost",size:"icon",align:"start",className:"aui-composer-add-attachment hover:bg-muted-foreground/15 dark:border-muted-foreground/15 dark:hover:bg-muted-foreground/30 size-[34px] rounded-full p-1 text-xs font-semibold","aria-label":"Add Attachment",children:m.jsx(Q0,{className:"aui-attachment-add-icon size-5 stroke-[1.5px]"})})}),xd=()=>{const{config:e}=T.useElements(),t=e.theme??{};return D.useMemo(()=>{const{colorScheme:n="light"}=t;return{className:n==="dark"||n==="system"&&typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":void 0}},[t])},or=[.23,1,.32,1];function m2(e){return e.replace(/[-_]/g," ").split(/(?=[A-Z])/).join(" ").split(/\s+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" ")}const h2=({children:e})=>{const t=L.useAssistantState(({message:s})=>s).parts,n=t.filter(s=>s.type==="tool-call"),o=n.some(s=>s.status?.type==="running"),{config:r}=T.useElements(),i=r.tools?.expandToolGroupsByDefault??!1,a=D.useMemo(()=>{const s=t.filter(l=>l.type==="tool-call");return s.length===0?"No tools called":s.length===1?`Calling ${m2(s[0].toolName)}...`:o?`Calling ${s.length} tools...`:`Executed ${s.length} tools`},[t,o]);return r.tools?.components?.[n[0]?.toolName]?e:n.length===1?m.jsx("div",{className:T.cn("my-4 w-full max-w-xl"),children:m.jsx("div",{className:"border-border bg-card overflow-hidden rounded-lg border",children:e})}):m.jsx("div",{className:"my-4 w-full max-w-xl",children:m.jsx(c6,{title:a,status:o?"running":"complete",defaultExpanded:i,children:e})})},$d=()=>{const e=xd(),t=T.useDensity(),{config:n}=T.useElements(),o=n.components??{};return m.jsx(Zt.LazyMotion,{features:Zt.domAnimation,children:m.jsx(Zt.MotionConfig,{reducedMotion:"user",children:m.jsx(L.ThreadPrimitive.Root,{className:T.cn("aui-root aui-thread-root bg-background @container flex h-full flex-col",e.className),children:m.jsxs(L.ThreadPrimitive.Viewport,{className:T.cn("aui-thread-viewport relative mx-auto flex w-full flex-1 flex-col overflow-x-auto overflow-y-scroll pb-0!",t("p-lg")),children:[m.jsx(L.ThreadPrimitive.If,{empty:!0,children:o.ThreadWelcome?m.jsx(o.ThreadWelcome,{}):m.jsx(v2,{})}),m.jsx(L.ThreadPrimitive.Messages,{components:{UserMessage:o.UserMessage??k2,EditComposer:o.EditComposer??T2,AssistantMessage:o.AssistantMessage??$2}}),m.jsx(L.ThreadPrimitive.If,{empty:!1,children:m.jsx("div",{className:"aui-thread-viewport-spacer min-h-8 grow"})}),m.jsx(b2,{})]})})})})},g2=()=>m.jsx(L.ThreadPrimitive.ScrollToBottom,{asChild:!0,children:m.jsx(ct,{tooltip:"Scroll to bottom",variant:"outline",className:"aui-thread-scroll-to-bottom dark:bg-background dark:hover:bg-accent absolute -top-12 z-10 self-center rounded-full p-4 disabled:invisible",children:m.jsx(I0,{})})}),v2=()=>{const{config:e}=T.useElements(),t=T.useDensity(),{title:n,subtitle:o}=e.welcome??{},r=e.variant==="standalone";return m.jsxs("div",{className:T.cn("aui-thread-welcome-root my-auto flex w-full grow flex-col",r?"items-center justify-center":"",t("gap-lg")),children:[m.jsx("div",{className:T.cn("aui-thread-welcome-center flex w-full grow flex-col items-center justify-start"),children:m.jsxs("div",{className:T.cn("aui-thread-welcome-message flex flex-col",r?"items-center text-center":"size-full justify-start",t("gap-sm"),!r&&t("py-md")),children:[m.jsx(Lt.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},transition:{duration:.25,ease:or},className:T.cn("aui-thread-welcome-message-motion-1 text-foreground font-semibold",t("text-title")),children:n}),m.jsx(Lt.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},transition:{duration:.25,delay:.05,ease:or},className:T.cn("aui-thread-welcome-message-motion-2 text-muted-foreground/65",t("text-subtitle")),children:o})]})}),m.jsx(y2,{})]})},y2=()=>{const{config:e}=T.useElements(),t=T.useRadius(),n=T.useDensity(),o=e.welcome?.suggestions??[],r=e.variant==="standalone";return o.length===0?null:m.jsx("div",{className:T.cn("aui-thread-welcome-suggestions w-full",n("gap-md"),n("py-lg"),r?"flex flex-wrap items-center justify-center":o.length===1?"flex":"grid max-w-fit @md:grid-cols-2"),children:o.map((i,a)=>m.jsx(Lt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:20},transition:{duration:.25,delay:.03*a,ease:or},className:T.cn("aui-thread-welcome-suggestion-display",!r&&"nth-[n+3]:hidden @md:nth-[n+3]:block"),children:m.jsx(L.ThreadPrimitive.Suggestion,{prompt:i.action,send:!0,asChild:!0,children:m.jsxs($t,{variant:"ghost",className:T.cn("aui-thread-welcome-suggestion dark:hover:bg-accent/60 h-auto w-full border text-left whitespace-break-spaces",n("text-base"),r?`flex-row items-center ${n("gap-sm")} ${n("px-md")} ${n("py-sm")} ${t("full")}`:`w-full flex-1 flex-col flex-wrap items-start justify-start ${n("gap-sm")} ${n("px-lg")} ${n("py-md")} ${t("xl")}`),"aria-label":i.action,children:[m.jsx("span",{className:"aui-thread-welcome-suggestion-text-1 text-foreground text-sm font-medium",children:i.title}),m.jsx("span",{className:"aui-thread-welcome-suggestion-text-2 text-muted-foreground text-sm",children:i.label})]})})},`suggested-action-${i.title}-${a}`))})},b2=()=>{const{config:e}=T.useElements(),t=T.useRadius(),n=T.useDensity(),o=e.composer??{placeholder:"Send a message...",attachments:!0},r=e.components??{};return r.Composer?m.jsx(r.Composer,{}):m.jsxs("div",{className:T.cn("aui-composer-wrapper bg-background sticky bottom-0 flex w-full flex-col overflow-visible",n("gap-md"),n("py-md"),t("xl")),children:[m.jsx(g2,{}),m.jsxs(L.ComposerPrimitive.Root,{className:T.cn("aui-composer-root group/input-group border-input bg-background has-[textarea:focus-visible]:border-ring has-[textarea:focus-visible]:ring-ring/5 dark:bg-background relative flex w-full flex-col border px-1 pt-2 shadow-xs transition-[color,box-shadow] outline-none has-[textarea:focus-visible]:ring-1",t("xl")),children:[o.attachments&&m.jsx(p2,{}),m.jsx(L.ComposerPrimitive.Input,{placeholder:o.placeholder,className:T.cn("aui-composer-input placeholder:text-muted-foreground mb-1 max-h-32 w-full resize-none bg-transparent px-3.5 pt-1.5 pb-3 outline-none focus-visible:ring-0",n("h-input"),n("text-base")),rows:1,autoFocus:!0,"aria-label":"Message input"}),m.jsx(w2,{})]})]})},_2=()=>{const{model:e,setModel:t}=T.useElements(),[n,o]=D.useState(!1),[r,i]=D.useState(!1),a=D.useRef(null),s=D.useRef(0),l=D.useRef(!1);D.useEffect(()=>{n&&!l.current&&requestAnimationFrame(()=>{const c=a.current;c&&c.scrollHeight>0&&(c.scrollTop=s.current)}),l.current=n},[n]),D.useEffect(()=>{n&&i(!1)},[n]);const u=c=>{s.current=c.currentTarget.scrollTop};return m.jsx(uS,{children:m.jsxs(ud,{open:r&&!n,onOpenChange:i,children:[m.jsxs(PS,{open:n,onOpenChange:o,children:[m.jsx(ld,{asChild:!0,children:m.jsx(CS,{asChild:!0,children:m.jsx($t,{variant:"ghost",size:"icon","data-state":n?"open":"closed",className:"aui-composer-model-picker data-[state=open]:bg-muted-foreground/15 dark:border-muted-foreground/15 dark:hover:bg-muted-foreground/30 flex w-fit items-center gap-2 rounded-full px-2.5 py-1 text-xs font-semibold","aria-label":"Model Settings",children:m.jsx(rI,{className:"aui-attachment-add-icon size-5 stroke-[1.5px]"})})})}),m.jsx(jS,{side:"top",align:"start",className:"w-min p-0 shadow-none",children:m.jsx("div",{ref:a,className:"max-h-48 overflow-y-auto",onScroll:u,children:Mu.map(c=>m.jsxs($t,{onClick:()=>{t(c)},variant:"ghost",className:"w-full justify-start gap-2 rounded-none px-2",children:[c===e?m.jsx("div",{children:m.jsx(rr,{className:"size-4 text-emerald-500"})}):m.jsx("div",{className:"size-4",children:" "}),c]},c))})})]}),m.jsx(cd,{side:"bottom",align:"start",children:"Model Settings"})]})})},w2=()=>{const{config:e}=T.useElements(),t=T.useRadius(),n=e.composer??{attachments:!0};return m.jsxs("div",{className:"aui-composer-action-wrapper relative mx-1 mt-2 mb-2 flex items-center justify-between",children:[m.jsxs("div",{className:"aui-composer-action-wrapper-inner flex items-center",children:[n.attachments?m.jsx(f2,{}):m.jsx("div",{className:"aui-composer-add-attachment-placeholder"}),e.model?.showModelPicker&&!e.languageModel&&m.jsx(_2,{})]}),m.jsx(L.ThreadPrimitive.If,{running:!1,children:m.jsx(L.ComposerPrimitive.Send,{asChild:!0,children:m.jsx(ct,{tooltip:"Send message",side:"bottom",type:"submit",variant:"default",size:"icon",className:T.cn("aui-composer-send size-[34px] p-1",t("full")),"aria-label":"Send message",children:m.jsx(E0,{className:"aui-composer-send-icon size-5"})})})}),m.jsx(L.ThreadPrimitive.If,{running:!0,children:m.jsx(L.ComposerPrimitive.Cancel,{asChild:!0,children:m.jsx($t,{type:"button",variant:"default",size:"icon",className:T.cn("aui-composer-cancel border-muted-foreground/60 hover:bg-primary/75 dark:border-muted-foreground/90 size-[34px] border",t("full")),"aria-label":"Stop generating",children:m.jsx(oI,{className:"aui-composer-cancel-icon size-3.5 fill-white dark:fill-black"})})})})]})},x2=()=>m.jsx(L.MessagePrimitive.Error,{children:m.jsx(L.ErrorPrimitive.Root,{className:"aui-message-error-root border-destructive bg-destructive/10 text-destructive dark:bg-destructive/5 mt-2 rounded-md border p-3 text-sm dark:text-red-200",children:m.jsx(L.ErrorPrimitive.Message,{className:"aui-message-error-message line-clamp-2"})})}),$2=()=>{const{config:e}=T.useElements(),t=e.tools??{},n=e.components??{};return m.jsx(L.MessagePrimitive.Root,{asChild:!0,children:m.jsxs("div",{className:"aui-assistant-message-root animate-in fade-in slide-in-from-bottom-1 relative mx-auto w-full py-4 duration-150 ease-out last:mb-24","data-role":"assistant",children:[m.jsxs("div",{className:"aui-assistant-message-content text-foreground mx-2 leading-7 wrap-break-word",children:[m.jsx(L.MessagePrimitive.Parts,{components:{Text:n.Text??lS,Image:n.Image??S2,tools:{by_name:t.components,Fallback:n.ToolFallback??d6},Reasoning:n.Reasoning??qS,ReasoningGroup:n.ReasoningGroup??VS,ToolGroup:n.ToolGroup??h2}}),m.jsx(x2,{})]}),m.jsxs("div",{className:"aui-assistant-message-footer mt-2 ml-2 flex",children:[m.jsx(m0,{}),m.jsx(I2,{})]})]})})},S2=e=>m.jsx("img",{src:e.image}),I2=()=>m.jsxs(L.ActionBarPrimitive.Root,{hideWhenRunning:!0,autohide:"not-last",autohideFloat:"single-branch",className:"aui-assistant-action-bar-root text-muted-foreground data-floating:bg-background col-start-3 row-start-2 -ml-1 flex gap-1 data-floating:absolute data-floating:rounded-md data-floating:border data-floating:p-1 data-floating:shadow-sm",children:[m.jsx(L.ActionBarPrimitive.Copy,{asChild:!0,children:m.jsxs(ct,{tooltip:"Copy",children:[m.jsx(L.MessagePrimitive.If,{copied:!0,children:m.jsx(rr,{})}),m.jsx(L.MessagePrimitive.If,{copied:!1,children:m.jsx(Du,{})})]})}),m.jsx(L.ActionBarPrimitive.Reload,{asChild:!0,children:m.jsx(ct,{tooltip:"Refresh",children:m.jsx(eI,{})})})]}),k2=()=>{const e=T.useRadius();return m.jsx(L.MessagePrimitive.Root,{asChild:!0,children:m.jsxs("div",{className:"aui-user-message-root animate-in fade-in slide-in-from-bottom-1 mx-auto grid w-full auto-rows-auto grid-cols-[minmax(72px,1fr)_auto] gap-y-2 px-2 py-4 duration-150 ease-out first:mt-3 last:mb-5 [&:where(>*)]:col-start-2","data-role":"user",children:[m.jsx(d2,{}),m.jsxs("div",{className:"aui-user-message-content-wrapper relative col-start-2 min-w-0",children:[m.jsx("div",{className:T.cn("aui-user-message-content bg-muted text-foreground px-5 py-2.5 wrap-break-word",e("xl")),children:m.jsx(L.MessagePrimitive.Parts,{})}),m.jsx("div",{className:"aui-user-action-bar-wrapper absolute top-1/2 left-0 -translate-x-full -translate-y-1/2 pr-2",children:m.jsx(E2,{})})]}),m.jsx(m0,{className:"aui-user-branch-picker col-span-full col-start-1 row-start-3 -mr-1 justify-end"})]})})},E2=()=>m.jsx(L.ActionBarPrimitive.Root,{hideWhenRunning:!0,autohide:"not-last",className:"aui-user-action-bar-root flex flex-col items-end",children:m.jsx(L.ActionBarPrimitive.Edit,{asChild:!0,children:m.jsx(ct,{tooltip:"Edit",className:"aui-user-action-edit p-4",children:m.jsx(K0,{})})})}),T2=()=>m.jsx("div",{className:"aui-edit-composer-wrapper mx-auto flex w-full flex-col gap-4 px-2 first:mt-4",children:m.jsxs(L.ComposerPrimitive.Root,{className:"aui-edit-composer-root bg-muted ml-auto flex w-full max-w-7/8 flex-col rounded-xl",children:[m.jsx(L.ComposerPrimitive.Input,{className:"aui-edit-composer-input text-foreground flex min-h-[60px] w-full resize-none bg-transparent p-4 outline-none",autoFocus:!0}),m.jsxs("div",{className:"aui-edit-composer-footer mx-3 mb-3 flex items-center justify-center gap-2 self-end",children:[m.jsx(L.ComposerPrimitive.Cancel,{asChild:!0,children:m.jsx($t,{variant:"ghost",size:"sm","aria-label":"Cancel edit",children:"Cancel"})}),m.jsx(L.ComposerPrimitive.Send,{asChild:!0,children:m.jsx($t,{size:"sm","aria-label":"Update message",children:"Update"})})]})]})}),m0=({className:e,...t})=>m.jsxs(L.BranchPickerPrimitive.Root,{hideWhenSingleBranch:!0,className:T.cn("aui-branch-picker-root text-muted-foreground mr-2 -ml-2 inline-flex items-center text-xs",e),...t,children:[m.jsx(L.BranchPickerPrimitive.Previous,{asChild:!0,children:m.jsx(ct,{tooltip:"Previous",children:m.jsx(j0,{})})}),m.jsxs("span",{className:"aui-branch-picker-state font-medium",children:[m.jsx(L.BranchPickerPrimitive.Number,{})," / ",m.jsx(L.BranchPickerPrimitive.Count,{})]}),m.jsx(L.BranchPickerPrimitive.Next,{asChild:!0,children:m.jsx(ct,{tooltip:"Next",children:m.jsx(um,{})})})]}),h0=()=>{const{config:e,isExpanded:t,setIsExpanded:n}=T.useElements(),o=e.modal?.defaultExpanded??!1;return{expandable:e.modal?.expandable??!1,isExpanded:t,setIsExpanded:n,defaultExpanded:o}},O2={layout:{duration:.25,ease:or}},N2=()=>{const{config:e}=T.useElements(),t=xd(),n=T.useRadius(),o=T.useDensity(),[r,i]=D.useState(e.modal?.defaultOpen??!1),{expandable:a,isExpanded:s,setIsExpanded:l}=h0(),u=e.modal?.title,c=e.modal?.icon,d=e.modal?.position??"bottom-right",f=P2(d),p=D.useMemo(()=>e.modal?.dimensions?.default??{width:"500px",height:"600px",maxHeight:"95vh"},[e.modal?.dimensions?.default]),g=D.useMemo(()=>e.modal?.dimensions?.expanded??{width:"70vw",height:"90vh"},[e.modal?.dimensions?.expanded]),b=L.useAssistantState(({thread:v})=>v).messages.some(v=>v.status?.type==="running"),y=s?g.width:p.width,x=s?g.height:p.height,$=p.maxHeight;return m.jsx(Zt.LazyMotion,{features:Zt.domMax,children:m.jsx(Zt.MotionConfig,{reducedMotion:"user",transition:O2,children:m.jsx("div",{className:T.cn("aui-root aui-modal-anchor fixed z-10",f,t.className,n("lg"),r&&"shadow-xl"),children:m.jsx(Zt.AnimatePresence,{mode:"wait",children:r?m.jsxs(Lt.div,{layout:!0,layoutId:"chat-container",className:T.cn("aui-modal-content bg-popover text-popover-foreground flex flex-col overflow-hidden border [&>.aui-thread-root]:bg-inherit",n("lg")),initial:!1,style:{originX:d.includes("left")?0:1,originY:d.includes("top")?0:1,width:y,height:x,maxHeight:$},children:[m.jsxs(Lt.div,{className:T.cn("aui-modal-header flex shrink-0 items-center justify-between border-b",o("h-header"),o("px-lg")),initial:{opacity:0},animate:{opacity:1},transition:{duration:.2,delay:.1,ease:or},children:[m.jsx("div",{className:T.cn("flex min-w-0 items-center"),children:m.jsxs("span",{className:T.cn("text-md flex items-center gap-2 truncate font-medium",b&&"shimmer"),children:[m.jsx("span",{className:"truncate",children:u}),b&&m.jsx(Hs,{className:"text-muted-foreground size-4.5 animate-spin",strokeWidth:1.25})]})}),m.jsxs("div",{className:"flex flex-row items-center justify-end gap-1",children:[a?m.jsx("button",{type:"button",onClick:()=>l(v=>!v),className:T.cn("text-muted-foreground hover:text-foreground hover:bg-accent flex h-8 cursor-pointer items-center rounded-md px-2 text-xs transition-colors"),"aria-pressed":s,"aria-label":s?"Collapse assistant":"Expand assistant",children:s?m.jsx(V0,{strokeWidth:2,className:"size-3.5 rotate-90"}):m.jsx(L0,{strokeWidth:2,className:"size-3.5 rotate-90"})}):null,m.jsx("button",{onClick:()=>{i(!1),l(!1)},className:"text-muted-foreground hover:text-foreground hover:bg-accent -mr-1 flex size-8 cursor-pointer items-center justify-center rounded-md transition-colors","aria-label":`Close ${u}`,children:m.jsx(Xn,{className:"size-4.5"})})]})]}),m.jsx(Lt.div,{className:"aui-modal-thread w-full flex-1 overflow-hidden",initial:{opacity:0},animate:{opacity:1},transition:{duration:.2,delay:.05,ease:or},children:m.jsx($d,{})})]},"chat"):m.jsx(Lt.button,{layout:!0,layoutId:"chat-container",onClick:()=>i(!0),className:T.cn("aui-modal-button bg-primary text-primary-foreground flex size-12 cursor-pointer items-center justify-center border shadow-lg transition-shadow hover:shadow-xl",n("full")),initial:!1,"aria-label":`Open ${u}`,style:{originX:1,originY:1},children:m.jsx(Lt.div,{initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.8},transition:{duration:.2,ease:or},className:"flex size-full items-center justify-center",children:c?c("closed"):m.jsx(F0,{className:"size-6"})})},"button")})})})})};function P2(e){switch(e){case"bottom-left":return"left-4 bottom-4";case"top-right":return"right-4 top-4";case"top-left":return"left-4 top-4";case"bottom-right":return"right-4 bottom-4";default:T.assertNever(e)}}const C2=()=>{const{config:e}=T.useElements(),t=xd(),n=e.sidecar??{},{title:o,dimensions:r}=n,{isExpanded:i,setIsExpanded:a}=h0(),l=L.useAssistantState(({thread:u})=>u).messages.some(u=>u.status?.type==="running");return m.jsx(Zt.LazyMotion,{features:Zt.domMax,children:m.jsxs(Lt.div,{initial:{width:r?.default?.width??"400px",height:r?.default?.height??"100vh"},animate:{width:i?r?.expanded?.width??"800px":r?.default?.width??"400px",height:i?r?.expanded?.height??"100%":r?.default?.height??"100vh"},transition:{duration:.3,ease:or},className:T.cn("aui-root aui-sidecar bg-popover text-popover-foreground fixed top-0 right-0 border-l",t.className),children:[m.jsxs("div",{className:"aui-sidecar-header flex h-14 items-center justify-between border-b px-4",children:[m.jsx("span",{className:T.cn("flex items-center gap-2 text-sm font-medium",l&&"shimmer"),children:o}),m.jsx("div",{className:"aui-sidecar-header-actions flex items-center gap-1",children:m.jsx(ct,{tooltip:i?"Collapse":"Pop out",variant:"ghost",className:"aui-sidecar-popout size-8",onClick:()=>a(u=>!u),children:i?m.jsx(J0,{className:"size-4.5"}):m.jsx(H0,{className:"size-4.5"})})})]}),m.jsx("div",{className:"aui-sidecar-content h-[calc(100%-3.5rem)] overflow-hidden",children:m.jsx($d,{})})]})})},j2=()=>{const{config:e}=T.useElements();switch(e.variant){case"standalone":return m.jsx($d,{});case"sidecar":return m.jsx(C2,{});case"widget":return m.jsx(N2,{});default:T.assertNever(e.variant)}};exports.useGramElements=T.useElements;exports.Chat=j2;exports.GramElementsProvider=bM;exports.MODELS=Mu;exports.defineFrontendTool=fR;
|