@mastra/deployer-cloud 1.85.0-alpha.0 → 1.85.0-alpha.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/studio/assets/{index-DzQW0EuW.js → index-BvRP7JbU.js} +2 -2
- package/dist/studio/assets/{main-DxjtVe-P.js → main-CyhmAJ0d.js} +2 -2
- package/dist/studio/assets/style-ChH3r-n6.css +3 -0
- package/dist/studio/index.html +2 -2
- package/package.json +4 -4
- package/dist/studio/assets/style-ivTe6uHs.css +0 -3
|
@@ -170,7 +170,7 @@ Error message: ${NTe(t)}`,cause:t}),this[qTe]=!0,this.value=e}static isInstance(
|
|
|
170
170
|
`)}Wh({prefix:`aiobj`,size:24}),Wh({prefix:`aiobj`,size:24}),Wh({prefix:`aitxt`,size:24}),Wh({prefix:`msg`,size:24}),gOe({},{object:()=>QOe,text:()=>ZOe});var ZOe=()=>({type:`text`,responseFormat:()=>({type:`text`}),injectIntoSystemPrompt({system:e}){return e},parsePartial({text:e}){return{partial:e}},parseOutput({text:e}){return e}}),QOe=({schema:e})=>{let t=bDe(e);return{type:`object`,responseFormat:({model:e})=>({type:`json`,schema:e.supportsStructuredOutputs?t.jsonSchema:void 0}),injectIntoSystemPrompt({system:e,model:n}){return n.supportsStructuredOutputs?e:XOe({prompt:e,schema:t.jsonSchema})},parsePartial({text:e}){let t=mDe(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:return{partial:t.value};default:{let e=t.state;throw Error(`Unsupported parse state: ${e}`)}}},parseOutput({text:e},n){let r=pEe({text:e});if(!r.success)throw new SOe({message:`No object generated: could not parse the response.`,cause:r.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});let i=fEe({value:r.value,schema:t});if(!i.success)throw new SOe({message:`No object generated: response did not match schema.`,cause:i.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});return i.value}}};function $Oe(e,t){let n=e.getReader(),r=t.getReader(),i,a,o=!1,s=!1;async function c(e){try{i??=n.read();let t=await i;i=void 0,t.done?e.close():e.enqueue(t.value)}catch(t){e.error(t)}}async function l(e){try{a??=r.read();let t=await a;a=void 0,t.done?e.close():e.enqueue(t.value)}catch(t){e.error(t)}}return new ReadableStream({async pull(e){try{if(o){await l(e);return}if(s){await c(e);return}i??=n.read(),a??=r.read();let{result:t,reader:u}=await Promise.race([i.then(e=>({result:e,reader:n})),a.then(e=>({result:e,reader:r}))]);t.done||e.enqueue(t.value),u===n?(i=void 0,t.done&&(await l(e),o=!0)):(a=void 0,t.done&&(s=!0,await c(e)))}catch(t){e.error(t)}},cancel(){n.cancel(),r.cancel()}})}Wh({prefix:`aitxt`,size:24}),Wh({prefix:`msg`,size:24});var eke=J({name:q(),version:q()}).passthrough(),tke=J({_meta:Rd(J({}).passthrough())}).passthrough(),mg=tke,nke=J({method:q(),params:Rd(tke)}),rke=J({experimental:Rd(J({}).passthrough()),logging:Rd(J({}).passthrough()),prompts:Rd(J({listChanged:Rd(dd())}).passthrough()),resources:Rd(J({subscribe:Rd(dd()),listChanged:Rd(dd())}).passthrough()),tools:Rd(J({listChanged:Rd(dd())}).passthrough())}).passthrough();mg.extend({protocolVersion:q(),capabilities:rke,serverInfo:eke,instructions:Rd(q())});var ike=mg.extend({nextCursor:Rd(q())}),ake=J({name:q(),description:Rd(q()),inputSchema:J({type:Pd(`object`),properties:Rd(J({}).passthrough())}).passthrough()}).passthrough();ike.extend({tools:bd(ake)});var oke=J({type:Pd(`text`),text:q()}).passthrough(),ske=J({type:Pd(`image`),data:q().base64(),mimeType:q()}).passthrough(),cke=J({uri:q(),mimeType:Rd(q())}).passthrough(),lke=cke.extend({text:q()}),uke=cke.extend({blob:q().base64()}),dke=J({type:Pd(`resource`),resource:Td([lke,uke])}).passthrough();mg.extend({content:bd(Td([oke,ske,dke])),isError:dd().default(!1).optional()}).or(mg.extend({toolResult:hd()}));var hg=`2.0`,fke=J({jsonrpc:Pd(hg),id:Td([q(),sd().int()])}).merge(nke).strict(),pke=J({jsonrpc:Pd(hg),id:Td([q(),sd().int()]),result:mg}).strict(),mke=J({jsonrpc:Pd(hg),id:Td([q(),sd().int()]),error:J({code:sd().int(),message:q(),data:Rd(hd())})}).strict();Td([fke,J({jsonrpc:Pd(hg)}).merge(J({method:q(),params:Rd(tke)})).strict(),pke,mke]),gOe({},{mergeIntoDataStream:()=>yke,toDataStream:()=>_ke,toDataStreamResponse:()=>vke});function hke(e={}){let t=new TextEncoder,n=``;return new TransformStream({async start(){e.onStart&&await e.onStart()},async transform(r,i){i.enqueue(t.encode(r)),n+=r,e.onToken&&await e.onToken(r),e.onText&&typeof r==`string`&&await e.onText(r)},async flush(){e.onCompletion&&await e.onCompletion(n),e.onFinal&&await e.onFinal(n)}})}function gke(e,t){return e.pipeThrough(new TransformStream({transform:async(e,t)=>{typeof e==`string`?t.enqueue(e):`event`in e?e.event===`on_chat_model_stream`&&bke(e.data?.chunk,t):bke(e,t)}})).pipeThrough(hke(t)).pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform:async(e,t)=>{t.enqueue(hDe(`text`,e))}}))}function _ke(e,t){return gke(e,t).pipeThrough(new TextEncoderStream)}function vke(e,t){let n=gke(e,t?.callbacks).pipeThrough(new TextEncoderStream),r=t?.data,i=t?.init,a=r?$Oe(r.stream,n):n;return new Response(a,{status:i?.status??200,statusText:i?.statusText,headers:_Oe(i?.headers,{contentType:`text/plain; charset=utf-8`,dataStreamVersion:`v1`})})}function yke(e,t){t.dataStream.merge(gke(e,t.callbacks))}function bke(e,t){if(typeof e.content==`string`)t.enqueue(e.content);else{let n=e.content;for(let e of n)e.type===`text`&&t.enqueue(e.text)}}gOe({},{mergeIntoDataStream:()=>wke,toDataStream:()=>Ske,toDataStreamResponse:()=>Cke});function xke(e,t){let n=Tke();return sEe(e[Symbol.asyncIterator]()).pipeThrough(new TransformStream({async transform(e,t){t.enqueue(n(e.delta))}})).pipeThrough(hke(t)).pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform:async(e,t)=>{t.enqueue(hDe(`text`,e))}}))}function Ske(e,t){return xke(e,t).pipeThrough(new TextEncoderStream)}function Cke(e,t={}){let{init:n,data:r,callbacks:i}=t,a=xke(e,i).pipeThrough(new TextEncoderStream),o=r?$Oe(r.stream,a):a;return new Response(o,{status:n?.status??200,statusText:n?.statusText,headers:_Oe(n?.headers,{contentType:`text/plain; charset=utf-8`,dataStreamVersion:`v1`})})}function wke(e,t){t.dataStream.merge(xke(e,t.callbacks))}function Tke(){let e=!0;return t=>(e&&(t=t.trimStart(),t&&(e=!1)),t)}function Eke(e,t){if(e===t)return!0;if(e==null||t==null)return e===t;if(typeof e!=typeof t||Array.isArray(e)!==Array.isArray(t)||e instanceof Date!=t instanceof Date)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>Eke(e,t[n]));if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(typeof e==`object`&&typeof t==`object`){let n=e,r=t,i=Object.keys(n),a=Object.keys(r);return i.length===a.length&&i.every(e=>Object.prototype.hasOwnProperty.call(r,e)&&Eke(n[e],r[e]))}return!1}function Dke(e){try{let[t,n]=e.split(`,`);return{mediaType:t?.split(`;`)[0]?.split(`:`)[1],base64Content:n}}catch{return{mediaType:void 0,base64Content:void 0}}}function Oke(e){if(!e.startsWith(`http://`)&&!e.startsWith(`https://`))return!1;try{return new URL(e),!0}catch{return!1}}function kke(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if(typeof e==`string`)try{e=new URL(e)}catch{}if(e instanceof URL&&e.protocol===`data:`){let{mediaType:t,base64Content:n}=Dke(e.toString());if(t==null||n==null)throw new yn({id:`INVALID_DATA_URL_FORMAT`,text:`Invalid data URL format in content ${e.toString()}`,domain:gn.LLM,category:_n.USER});return{data:n,mediaType:t}}return{data:e,mediaType:void 0}}var Ake=class{base64Data;uint8ArrayData;mediaType;constructor({data:e,mediaType:t}){let n=e instanceof Uint8Array;this.base64Data=n?void 0:e,this.uint8ArrayData=n?e:void 0,this.mediaType=t}get base64(){return this.base64Data??=fm(this.uint8ArrayData),this.base64Data}get uint8Array(){if(this.uint8ArrayData==null){if(Oke(this.base64Data))throw Error(`Cannot convert URL-backed generated file to Uint8Array. Download the file from ${this.base64Data} instead.`);this.uint8ArrayData=Xfe(this.base64Data)}return this.uint8ArrayData}},jke=class extends Ake{type=`file`;constructor(e){super(e)}};function Mke(e){return Number.isFinite(e)&&e>0?e:0}async function Nke(e,t){let n=Mke(e);n<=0||(t?await new Promise(e=>{let r,i=()=>{r&&clearTimeout(r),t.removeEventListener(`abort`,i),e()};t.addEventListener(`abort`,i,{once:!0}),t.aborted?i():r=setTimeout(()=>{t.removeEventListener(`abort`,i),e()},n)}):await new Promise(e=>setTimeout(e,n)))}var Pke=()=>!0;async function Fke(e,t={},n=3,r={}){let i=0,a=null,o=r.shouldRetryResponse??Pke,s=t.signal??void 0;for(;i<n;){s?.throwIfAborted();let r;try{r=await fetch(e,t)}catch(e){if(s?.aborted)throw s.reason;a=e instanceof Error?e:Error(String(e))}if(r){if(r.ok)return r;{a=Error(`Request failed with status: ${r.status} ${r.statusText}`);let e=o(r);if(await r.body?.cancel().catch(()=>{}),!e)throw a}}if(i++,i>=n)break;let c=Math.min(1e3*2**i,1e4);s?.throwIfAborted(),await Nke(c,s),s?.throwIfAborted()}throw a||Error(`Request failed after multiple retry attempts`)}var Ike=new Set([`text`,`json`,`error-text`,`error-json`,`content`]);function gg(e){if(typeof e!=`object`||!e)return e;let t=Object.keys(e);return t.length===1&&t[0]===`value`?e.value:e}function Lke(e,{unwrapContent:t=!0}={}){if(typeof e!=`object`||!e)return{isError:!1,output:e};let n=e,r=Object.keys(n);return r.length===2&&r.includes(`type`)&&r.includes(`value`)&&typeof n.type==`string`&&Ike.has(n.type)?{isError:n.type===`error-text`||n.type===`error-json`,output:n.type===`content`&&!t?e:n.value}:{isError:!1,output:gg(e)}}var _g=class e{static isMastraDBMessage(e){return!!(`content`in e&&e.content&&!Array.isArray(e.content)&&typeof e.content!=`string`&&`format`in e.content&&e.content.format===2)}static isMastraMessageV1(t){return!e.isMastraDBMessage(t)&&(`threadId`in t||`resourceId`in t)}static isMastraMessage(t){return e.isMastraDBMessage(t)||e.isMastraMessageV1(t)}static isAIV4UIMessage(t){return!e.isMastraMessage(t)&&!e.isAIV4CoreMessage(t)&&`parts`in t&&!e.hasAIV5UIMessageCharacteristics(t)}static isAIV6UIMessage(t){return!e.isMastraMessage(t)&&!e.isAIV4CoreMessage(t)&&`parts`in t&&e.hasAIV6UIMessageCharacteristics(t)}static isAIV5UIMessage(t){return!e.isMastraMessage(t)&&!e.isAIV6UIMessage(t)&&!e.isAIV5CoreMessage(t)&&`parts`in t&&e.hasAIV5UIMessageCharacteristics(t)}static isAIV4CoreMessage(t){return!e.isMastraMessage(t)&&!(`parts`in t)&&`content`in t&&!e.hasAIV5CoreMessageCharacteristics(t)}static isAIV6CoreMessage(t){return!e.isMastraMessage(t)&&!(`parts`in t)&&`content`in t&&e.hasAIV6CoreMessageCharacteristics(t)}static isAIV5CoreMessage(t){return!e.isMastraMessage(t)&&!e.isAIV6CoreMessage(t)&&!(`parts`in t)&&`content`in t&&e.hasAIV5CoreMessageCharacteristics(t)}static hasAIV6UIMessageCharacteristics(e){if(!(`parts`in e)||!e.parts)return!1;for(let t of e.parts)if(t.type===`source-document`||t.type===`dynamic-tool`||`resultProviderMetadata`in t||`toolCallId`in t&&`state`in t&&(t.state===`approval-requested`||t.state===`approval-responded`||t.state===`output-denied`))return!0;return!1}static hasAIV5UIMessageCharacteristics(e){if(`toolInvocations`in e||`reasoning`in e||`experimental_attachments`in e||`data`in e||`annotations`in e||!e.parts)return!1;for(let t of e.parts){if(`metadata`in t)return!0;if(`toolInvocation`in t)return!1;if(`toolCallId`in t)return!0;if(t.type===`source`)return!1;if(t.type===`source-url`)return!0;if(t.type===`reasoning`){if(`state`in t||`text`in t)return!0;if(`reasoning`in t||`details`in t)return!1}if(t.type===`file`&&`mediaType`in t)return!0}return!1}static hasAIV6CoreMessageCharacteristics(e){return`parts`in e||!Array.isArray(e.content)?!1:e.content.some(e=>typeof e==`object`&&!!e&&(e.type===`tool-approval-request`||e.type===`tool-approval-response`))}static hasAIV5CoreMessageCharacteristics(e){if(`experimental_providerMetadata`in e)return!1;if(!Array.isArray(e.content))return!0;for(let t of e.content)if(typeof t==`object`&&t){if(t.type===`tool-result`&&`output`in t||t.type===`tool-call`&&`input`in t)return!0;if(t.type===`tool-result`&&`result`in t||t.type===`tool-call`&&`args`in t)return!1;if(`mediaType`in t)return!0;if(`mimeType`in t||`experimental_providerMetadata`in t||t.type===`reasoning`&&`signature`in t||t.type===`redacted-reasoning`)return!1}return!0}static getRole(e){if(e.role===`assistant`||e.role===`tool`)return`assistant`;if(e.role===`user`)return`user`;if(e.role===`system`)return`system`;throw Error(`BUG: add handling for message role ${e.role} in message ${JSON.stringify(e,null,2)}`)}},vg=[`openai`,`azure`],yg=`resultItemId`;function Rke(e,t){return`${e}:${t}`}function zke(e){return Vke(e)[0]}function Bke(e){let t=zke(e);return t?Rke(t.provider,t.itemId):void 0}function Vke(e){if(!e)return[];let t=e.azure?.itemId,n=e.openai?.itemId;return typeof t==`string`&&t===n?[{provider:`azure`,itemId:t}]:vg.flatMap(t=>{let n=e[t]?.itemId;return typeof n==`string`?[{provider:t,itemId:n}]:[]})}function Hke(e,t,n){let r=n;for(let n of vg){let i=e?.[n]?.itemId,a=t?.[n]?.itemId;if(typeof i!=`string`||typeof a!=`string`||i===a)continue;let o=r?.[n]??{};r={...r,[n]:{...o,itemId:i,[yg]:a}}}return r}function Uke(e){if(!e)return;let t;for(let n of vg){let r=e[n]?.[yg];typeof r==`string`&&(t={...t,[n]:{itemId:r}})}return t}function Wke(e,t){let n=e?.[t]?.[yg];return typeof n==`string`?n:void 0}function Gke(e){if(!e)return e;let t=e;for(let e of vg){let n=t[e];if(!n||!(`resultItemId`in n))continue;let{[yg]:r,...i}=n;t={...t,[e]:i}}return t}function Kke(e){return Vke(e).map(({provider:e,itemId:t})=>Rke(e,t))}function qke(e,t,n,r){if(!n)return e;let i=new Map;for(let e of t){if(e.role!==`assistant`||e.content?.format!==2)continue;let t=e.content.metadata?.provider;if(typeof t==`string`&&t!==n)for(let n of e.content.parts??[])n.type===`tool-invocation`&&n.providerExecuted&&i.set(n.toolInvocation.toolCallId,{toolName:n.toolInvocation.toolName,provider:t})}if(i.size===0)return e;let a=e=>{let t=e;return(t.type===`tool-call`||t.type===`tool-result`)&&typeof t.toolCallId==`string`&&i.has(t.toolCallId)},o=new Set,s=e=>{if(o.has(e))return;o.add(e);let{toolName:t,provider:a}=i.get(e);r?.warn(`Dropping provider-executed "${t}" result from an earlier turn: it was produced by "${a}" and this request goes to "${n}", which cannot read the other provider's payload.`,{toolCallId:e})},c=!1,l=e.map(e=>!Array.isArray(e.content)||!e.content.some(a)?e:(c=!0,{...e,content:e.content.filter(e=>!a(e)||(s(e.toolCallId),!1))}));return c?l:e}function Jke(e,t){return e.map(e=>Qke(e,t))}function Yke(e,t){let n=e[t];if(!Array.isArray(n.content))return new Set;let r=new Set,i=new Set;for(let e of n.content)e.type===`tool-call`?r.add(e.toolCallId):e.type===`tool-result`&&i.add(e.toolCallId);let a=e[t+1];if(a&&a.role===`tool`&&Array.isArray(a.content))for(let e of a.content)e.type===`tool-result`&&i.add(e.toolCallId);return new Set([...r].filter(e=>i.has(e)))}function Xke(e){let t=e.map(e=>Array.isArray(e.content)?[...e.content]:null);for(let n=0;n<e.length;n++){let r=e[n];if(r.role===`assistant`&&Array.isArray(r.content)){let r=Yke(e,n),i=e[n+1];t[n]=t[n].filter(e=>{if(e.type!==`tool-call`)return!0;let t=e;return t.providerExecuted===!0||r.has(t.toolCallId)}),i&&i.role===`tool`&&Array.isArray(i.content)&&(t[n+1]=t[n+1].filter(e=>e.type!==`tool-result`||r.has(e.toolCallId)))}else if(r.role===`tool`&&Array.isArray(r.content)){let r=e[n-1];r&&r.role===`assistant`&&Array.isArray(r.content)||(t[n]=t[n].filter(e=>e.type!==`tool-result`))}}let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r];a==null?n.push(i):a.length!==0&&(Array.isArray(i.content)&&a.length===i.content.length?n.push(i):n.push({...i,content:a}))}return n}function Zke(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(t.push(r),r.role!==`assistant`||!Array.isArray(r.content))continue;let i=Yke(e,n),a=[];for(let e of r.content){if(e.type!==`tool-call`)continue;let t=e;t.providerExecuted===!0||i.has(t.toolCallId)||a.push({type:`tool-result`,toolCallId:t.toolCallId,toolName:t.toolName,output:{type:`json`,value:{status:`pending`}}})}if(a.length===0)continue;let o=e[n+1];o&&o.role===`tool`&&Array.isArray(o.content)?(t.push({...o,content:[...o.content,...a]}),n++):t.push({role:`tool`,content:a})}return Xke(t)}function Qke(e,t){return e.role!==`tool`||!Array.isArray(e.content)?e:{...e,content:e.content.map(e=>e.type===`tool-result`?{...e,input:bg(t,e.toolCallId)}:e)}}function bg(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if(r&&r.role===`assistant`){if(r.content.parts){let e=r.content.parts.find(e=>e.type===`tool-invocation`&&e.toolInvocation.toolCallId===t);if(e&&e.type===`tool-invocation`){let t=e.toolInvocation.args||{};if(typeof t==`object`&&Object.keys(t).length>0)return t}}if(r.content.toolInvocations){let e=r.content.toolInvocations.find(e=>e.toolCallId===t);if(e){let t=e.args||{};if(typeof t==`object`&&Object.keys(t).length>0)return t}}}}return{}}function xg(e,t,n,r=!0){if(!r)return n;let i=lm(e,`display`,t);return um(i)?i.transformed:n}function $ke(e,t,n){return{...e,args:xg(t,`input-available`,e.args,n),...e.state===`result`?{result:xg(t,`output-available`,xg(t,`error`,e.result,n),n)}:{}}}function eAe(e){return e}function tAe(e){return e.some(e=>e.type!==`text`||e.text!==``)?e.filter(e=>e.type!==`text`||e.text!==``):e}function nAe(e){let t=e.content.metadata?.signal;if(t&&typeof t==`object`&&!Array.isArray(t)){let n=t.type;return typeof n==`string`?n:e.type}return e.type}function rAe(e){let t=e.content.metadata?.signal;if(t&&typeof t==`object`&&!Array.isArray(t)){let e=t.tagName;if(typeof e==`string`)return e}let n=nAe(e);return n===`user`?`user`:n===`reactive`?e.type:n}function iAe(e){return e===`user`||e===`user-message`}function aAe(e,t){let n=e.content.metadata?.signal&&typeof e.content.metadata.signal==`object`?e.content.metadata.signal:{},r=n.metadata&&typeof n.metadata==`object`&&!Array.isArray(n.metadata)?n.metadata:{},i=n.attributes&&typeof n.attributes==`object`&&!Array.isArray(n.attributes)?n.attributes:{},a=nAe(e)??`signal`,o=rAe(e)??a;return{type:a===`user`?`data-user-message`:`data-signal`,data:{id:typeof n.id==`string`?n.id:e.id,type:a,tagName:o,contents:`contents`in n?n.contents:t,createdAt:typeof n.createdAt==`string`?n.createdAt:e.createdAt.toISOString(),...typeof n.acceptedAt==`string`?{acceptedAt:n.acceptedAt}:{},...Object.keys(i).length?{attributes:i}:{},...Object.keys(r).length?{metadata:r}:{}}}}var Sg=class{static toUIMessage(e,t){let n=t?.transformToolPayloads??!0,r=e.content.experimental_attachments?[...e.content.experimental_attachments]:[],i=typeof e.content.content==`string`&&e.content.content!==``?e.content.content:(e.content.parts??[]).reduce((e,t)=>t.type===`text`?t.text:e,``),a=[],o=e.content.parts??[];if(o.length)for(let e of o)if(e.type===`file`){let{mediaType:t,data:n}=_m(e),i;i=typeof n==`string`?gm(n,t).type===`raw`?Ope(n,t||`application/octet-stream`):n:kpe(n,t),r.push({contentType:t??`application/octet-stream`,url:i})}else if(e.type===`tool-invocation`&&(e.toolInvocation.state===`call`||e.toolInvocation.state===`partial-call`))continue;else if(e.type===`tool-invocation`){let t=e.toolInvocation.state===`output-denied`,r=e.toolInvocation.state===`output-error`,i={...e.toolInvocation,...t||r?{state:`result`}:{},...r?{isError:!0}:{},args:xg(e.providerMetadata,`input-available`,e.toolInvocation.args,n),...e.toolInvocation.state===`result`?{result:xg(e.providerMetadata,`output-available`,xg(e.providerMetadata,`error`,e.toolInvocation.result,n),n)}:t?{result:e.toolInvocation.approval?.reason??`Tool call was not approved by the user`}:r?{result:e.toolInvocation.errorText}:{}},s=-1,c=-1;for(let t of o)if(t.type===`step-start`&&s++,t.type===`tool-invocation`&&t.toolInvocation.toolCallId===e.toolInvocation.toolCallId){c=s;break}if(c>=0){let e={step:c,...i};a.push({type:`tool-invocation`,toolInvocation:e})}else a.push({type:`tool-invocation`,toolInvocation:i})}else a.push(e);a.length===0&&r.length>0&&a.push({type:`text`,text:``});let s=iAe(e.role===`signal`?nAe(e):void 0),c=eAe(e.role===`signal`&&!s?[aAe(e,e.content.content||i)]:a);if(e.role===`user`){let t={id:e.id,role:e.role,content:e.content.content||i,createdAt:e.createdAt,parts:c,experimental_attachments:r};return e.content.metadata&&(t.metadata=e.content.metadata),t}if(e.role===`assistant`){let t=Array.isArray(e.content.content)&&e.content.content.length===1&&e.content.content[0].type===`text`,r={id:e.id,role:e.role,content:t?i:e.content.content||i,createdAt:e.createdAt,parts:c,reasoning:void 0,toolInvocations:`toolInvocations`in e.content?e.content.toolInvocations?.filter(e=>e.state===`result`).map(t=>{let r=e.content.parts?.find(e=>e.type===`tool-invocation`&&e.toolInvocation.toolCallId===t.toolCallId)?.providerMetadata;return $ke(t,r,n)}):void 0};return e.content.metadata&&(r.metadata=e.content.metadata),r}let l={id:e.id,role:e.role===`signal`?s?`user`:`system`:e.role,content:e.role===`signal`&&!s?``:e.content.content||i,createdAt:e.createdAt,parts:c,experimental_attachments:r};return e.content.metadata&&(l.metadata=e.content.metadata),l}static systemToV4Core(e){if(e.role!==`system`||!e.content.content)throw new yn({id:`INVALID_SYSTEM_MESSAGE_FORMAT`,domain:gn.AGENT,category:_n.USER,text:`Invalid system message format. System messages must include 'role' and 'content' properties. The content should be a string.`,details:{receivedMessage:JSON.stringify(e,null,2)}});let t={role:`system`,content:e.content.content};return e.content.providerMetadata&&(t.experimental_providerMetadata=e.content.providerMetadata),t}static fromUIMessage(e,t,n){let r={format:2,parts:e.parts?tAe(e.parts):[]};return e.toolInvocations&&(r.toolInvocations=e.toolInvocations),e.reasoning&&(r.reasoning=e.reasoning),e.annotations&&(r.annotations=e.annotations),e.experimental_attachments&&(r.experimental_attachments=e.experimental_attachments),`metadata`in e&&e.metadata!==null&&e.metadata!==void 0&&(r.metadata=e.metadata),{id:e.id||t.newMessageId(),role:_g.getRole(e),createdAt:t.generateCreatedAt(n,e.createdAt),threadId:t.memoryInfo?.threadId,resourceId:t.memoryInfo?.resourceId,content:r}}static fromCoreMessage(e,t,n){let r=`id`in e?e.id:t.newMessageId(),i=[],a=[],o=[],s=n===`response`&&Array.isArray(e.content)&&e.content.length===1&&e.content[0]&&e.content[0].type===`text`&&`text`in e.content[0]&&e.content[0].text;if(s&&n===`response`&&(e.content=s),typeof e.content==`string`)i.push({type:`text`,text:e.content});else if(Array.isArray(e.content))for(let n of e.content)switch(n.type){case`text`:{let t=i.at(-1);e.role===`assistant`&&t&&t.type===`tool-invocation`&&i.push({type:`step-start`});let r={type:`text`,text:n.text};n.providerOptions&&(r.providerMetadata=n.providerOptions),i.push(r);break}case`tool-call`:{let e={type:`tool-invocation`,toolInvocation:{state:`call`,toolCallId:n.toolCallId,toolName:n.toolName,args:n.args}};n.providerOptions&&(e.providerMetadata=n.providerOptions),i.push(e);break}case`tool-result`:{let r={},a=e.content.find(e=>e.type===`tool-call`&&e.toolCallId===n.toolCallId);a&&a.type===`tool-call`&&(r=a.args),Object.keys(r).length===0&&t.dbMessages&&(r=bg(t.dbMessages,n.toolCallId));let s={state:`result`,toolCallId:n.toolCallId,toolName:n.toolName,result:n.result??``,args:r},c={type:`tool-invocation`,toolInvocation:s};n.providerOptions&&(c.providerMetadata=n.providerOptions),i.push(c),o.push(s)}break;case`reasoning`:{let e={type:`reasoning`,reasoning:n.text,details:[{type:`text`,text:n.text,signature:n.signature}]};n.providerOptions&&(e.providerMetadata=n.providerOptions),i.push(e)}break;case`redacted-reasoning`:{let e={type:`reasoning`,reasoning:``,details:[{type:`redacted`,data:n.data}]};n.providerOptions&&(e.providerMetadata=n.providerOptions),i.push(e)}break;case`image`:{let e={type:`file`,data:kpe(n.image),mimeType:n.mimeType};n.providerOptions&&(e.providerMetadata=n.providerOptions),i.push(e);break}case`file`:if(n.data instanceof URL){let e={type:`file`,data:n.data.toString(),mimeType:n.mimeType};n.providerOptions&&(e.providerMetadata=n.providerOptions),n.filename&&(e.filename=n.filename),i.push(e)}else if(typeof n.data==`string`){let e=gm(n.data,n.mimeType);if(e.type===`url`||e.type===`dataUri`||e.type===`providerFileId`){let t={type:`file`,data:n.data,mimeType:e.mimeType||`image/png`};n.providerOptions&&(t.providerMetadata=n.providerOptions),n.filename&&(t.filename=n.filename),i.push(t)}else try{let t={type:`file`,mimeType:e.mimeType||`image/png`,data:pm(n.data)};n.providerOptions&&(t.providerMetadata=n.providerOptions),n.filename&&(t.filename=n.filename),i.push(t)}catch(e){console.error(`Failed to convert binary data to base64 in CoreMessage file part: ${e}`,e)}}else try{let e={type:`file`,mimeType:n.mimeType,data:pm(n.data)};n.providerOptions&&(e.providerMetadata=n.providerOptions),n.filename&&(e.filename=n.filename),i.push(e)}catch(e){console.error(`Failed to convert binary data to base64 in CoreMessage file part: ${e}`,e)}}let c={format:2,parts:tAe(i)};o.length&&(c.toolInvocations=o),typeof e.content==`string`&&(c.content=e.content),a.length&&(c.experimental_attachments=a),e.providerOptions?c.providerMetadata=e.providerOptions:`experimental_providerMetadata`in e&&e.experimental_providerMetadata&&(c.providerMetadata=e.experimental_providerMetadata),`metadata`in e&&e.metadata!==null&&e.metadata!==void 0&&(c.metadata=e.metadata);let l=`metadata`in e&&e.metadata&&typeof e.metadata==`object`&&`createdAt`in e.metadata?e.metadata.createdAt:void 0;return{id:r,role:_g.getRole(e),createdAt:t.generateCreatedAt(n,l),threadId:t.memoryInfo?.threadId,resourceId:t.memoryInfo?.resourceId,content:c}}},Cg=`1.10.0`,oAe=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function sAe(e){let t=new Set([e]),n=new Set,r=e.match(oAe);if(!r)return()=>!1;let i={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(i.prerelease!=null)return function(t){return t===e};function a(e){return n.add(e),!1}function o(e){return t.add(e),!0}return function(e){if(t.has(e))return!0;if(n.has(e))return!1;let r=e.match(oAe);if(!r)return a(e);let s={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};return s.prerelease!=null||i.major!==s.major?a(e):i.major===0?i.minor===s.minor&&i.patch<=s.patch?o(e):a(e):i.minor<=s.minor?o(e):a(e)}}var cAe=sAe(Cg),lAe=Cg.split(`.`)[0],wg=Symbol.for(`opentelemetry.js.api.${lAe}`),Tg=typeof globalThis==`object`?globalThis:typeof self==`object`?self:typeof window==`object`?window:typeof global==`object`?global:{};function uAe(){return Object.defineProperty({},"version",{value:Cg,enumerable:!0,writable:!1,configurable:!1})}function dAe(e,t,n,r=!1){let i=Tg[wg]=Tg[wg]??uAe();if(!r&&i[e]){let t=Error(`@opentelemetry/api: Attempted duplicate registration of API: ${e}`);return n.error(t.stack||t.message),!1}if(i.version!==`1.10.0`){let t=Error(`@opentelemetry/api: Registration of version v${i.version} for ${e} does not match previously registered API v${Cg}`);return n.error(t.stack||t.message),!1}return i[e]=t,n.debug(`@opentelemetry/api: Registered a global for ${e} v${Cg}.`),!0}var fAe;function Eg(e){let t=Tg[wg];if(t!=null){if(t!==fAe){if(!t.version||!cAe(t.version))return;fAe=t}return t[e]}}function pAe(e,t){t.debug(`@opentelemetry/api: Unregistering a global for ${e} v${Cg}.`);let n=Tg[wg];n&&delete n[e]}var mAe=class{constructor(e){this._namespace=e.namespace||`DiagComponentLogger`}debug(...e){return Dg(`debug`,this._namespace,e)}error(...e){return Dg(`error`,this._namespace,e)}info(...e){return Dg(`info`,this._namespace,e)}warn(...e){return Dg(`warn`,this._namespace,e)}verbose(...e){return Dg(`verbose`,this._namespace,e)}};function Dg(e,t,n){let r=Eg(`diag`);if(r)return r[e](t,...n)}function hAe(e,t){e<0?e=0:e>9999&&(e=9999),t||={};function n(n,r){let i=t[n];return typeof i==`function`&&e>=r?i.bind(t):function(){}}return{error:n(`error`,30),warn:n(`warn`,50),info:n(`info`,60),debug:n(`debug`,70),verbose:n(`verbose`,80)}}var gAe=`diag`,Og=class e{static instance(){return this._instance||=new e,this._instance}constructor(){function e(e){return function(...t){let n=Eg(`diag`);if(n)return n[e](...t)}}let t=this;t.setLogger=(e,n={logLevel:60})=>{if(e===t){let e=Error(`Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation`);return t.error(e.stack??e.message),!1}typeof n==`number`&&(n={logLevel:n});let r=Eg(`diag`),i=hAe(n.logLevel??60,e);if(r&&!n.suppressOverrideMessage){let e=Error().stack??`<failed to generate stacktrace>`;r.warn(`Current logger will be overwritten from ${e}`),i.warn(`Current logger will overwrite one already registered from ${e}`)}return dAe(`diag`,i,t,!0)},t.disable=()=>{pAe(gAe,t)},t.createComponentLogger=e=>new mAe(e),t.verbose=e(`verbose`),t.debug=e(`debug`),t.info=e(`info`),t.warn=e(`warn`),t.error=e(`error`)}};function _Ae(e){return Symbol.for(e)}var vAe=new class e{constructor(t){let n=this;n._currentContext=t?new Map(t):new Map,n.getValue=e=>n._currentContext.get(e),n.setValue=(t,r)=>{let i=new e(n._currentContext);return i._currentContext.set(t,r),i},n.deleteValue=t=>{let r=new e(n._currentContext);return r._currentContext.delete(t),r}}},yAe={traceId:`00000000000000000000000000000000`,spanId:`0000000000000000`,traceFlags:0},kg=class{constructor(e=yAe){this._spanContext=e}spanContext(){return this._spanContext}setAttribute(e,t){return this}setAttributes(e){return this}addEvent(e,t){return this}addLink(e){return this}addLinks(e){return this}setStatus(e){return this}updateName(e){return this}end(e){}isRecording(){return!1}recordException(e,t){}},Ag=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1]);function bAe(e,t){if(typeof e!=`string`||e.length!==t)return!1;let n=0;for(let t=0;t<e.length;t+=4)n+=(Ag[e.charCodeAt(t)]|0)+(Ag[e.charCodeAt(t+1)]|0)+(Ag[e.charCodeAt(t+2)]|0)+(Ag[e.charCodeAt(t+3)]|0);return n===t}function xAe(e){return bAe(e,32)&&e!==`00000000000000000000000000000000`}function SAe(e){return bAe(e,16)&&e!==`0000000000000000`}function CAe(e){return xAe(e.traceId)&&SAe(e.spanId)}function wAe(e){return new kg(e)}var TAe=class{active(){return vAe}with(e,t,n,...r){return t.call(n,...r)}bind(e,t){return t}enable(){return this}disable(){return this}attach(e){return{dispose(){}}}},EAe=`context`,DAe=new TAe,OAe=Object.freeze({dispose:()=>{}}),kAe=class e{constructor(){this._attachUnsupportedWarned=!1}static getInstance(){return this._instance||=new e,this._instance}setGlobalContextManager(e){return dAe(EAe,e,Og.instance())}active(){return this._getContextManager().active()}with(e,t,n,...r){return this._getContextManager().with(e,t,n,...r)}bind(e,t){return this._getContextManager().bind(e,t)}attach(e){let t=this._getContextManager();return t.attach?t.attach(e):(this._attachUnsupportedWarned||(this._attachUnsupportedWarned=!0,Og.instance().warn(`The current ContextManager does not implement attach(). The context will not be attached. Use a ContextManager that supports attach() (e.g. AsyncLocalStorageContextManager) or use with()/bind() instead.`)),OAe)}_getContextManager(){return Eg(EAe)||DAe}disable(){this._getContextManager().disable(),pAe(EAe,Og.instance())}},AAe=_Ae(`OpenTelemetry Context Key SPAN`);function jAe(e){return e.getValue(AAe)||void 0}function MAe(){return jAe(kAe.getInstance().active())}function NAe(e,t){return e.setValue(AAe,t)}function PAe(e){return e.deleteValue(AAe)}function FAe(e,t){return NAe(e,new kg(t))}function IAe(e){return jAe(e)?.spanContext()}var LAe=kAe.getInstance(),RAe=class{startSpan(e,t,n=LAe.active()){if(t?.root)return new kg;let r=n&&IAe(n);return zAe(r)&&CAe(r)?new kg(r):new kg}startActiveSpan(e,t,n,r){let i,a,o;if(arguments.length<2)return;arguments.length===2?o=t:arguments.length===3?(i=t,o=n):(i=t,a=n,o=r);let s=a??LAe.active(),c=this.startSpan(e,i,s),l=NAe(s,c);return LAe.with(l,o,void 0,c)}};function zAe(e){return typeof e==`object`&&!!e&&`spanId`in e&&typeof e.spanId==`string`&&`traceId`in e&&typeof e.traceId==`string`&&`traceFlags`in e&&typeof e.traceFlags==`number`}var BAe=new RAe,VAe=class{constructor(e,t,n,r){this._provider=e,this.name=t,this.version=n,this.options=r}startSpan(e,t,n){return this._getTracer().startSpan(e,t,n)}startActiveSpan(e,t,n,r){let i=this._getTracer();return Reflect.apply(i.startActiveSpan,i,arguments)}_getTracer(){if(this._delegate)return this._delegate;let e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):BAe}},HAe=new class{getTracer(e,t,n){return new RAe}},UAe=class{getTracer(e,t,n){return this.getDelegateTracer(e,t,n)??new VAe(this,e,t,n)}getDelegate(){return this._delegate??HAe}setDelegate(e){this._delegate=e}getDelegateTracer(e,t,n){return this._delegate?.getTracer(e,t,n)}};kAe.getInstance();var WAe=`trace`;(class e{constructor(){this._proxyTracerProvider=new UAe,this.wrapSpanContext=wAe,this.isSpanContextValid=CAe,this.deleteSpan=PAe,this.getSpan=jAe,this.getActiveSpan=MAe,this.getSpanContext=IAe,this.setSpan=NAe,this.setSpanContext=FAe}static getInstance(){return this._instance||=new e,this._instance}setGlobalTracerProvider(e){let t=dAe(WAe,this._proxyTracerProvider,Og.instance());return t&&this._proxyTracerProvider.setDelegate(e),t}getTracerProvider(){return Eg(WAe)||this._proxyTracerProvider}getTracer(e,t){return this.getTracerProvider().getTracer(e,t)}disable(){pAe(WAe,Og.instance()),this._proxyTracerProvider=new UAe}}).getInstance();var GAe=Object.defineProperty,KAe=(e,t)=>{for(var n in t)GAe(e,n,{get:t[n],enumerable:!0})},qAe=`AI_NoObjectGeneratedError`,JAe=`vercel.ai.error.${qAe}`,YAe=Symbol.for(JAe),XAe,jg=class extends lh{constructor({message:e=`No object generated.`,cause:t,text:n,response:r,usage:i,finishReason:a}){super({name:qAe,message:e,cause:t}),this[XAe]=!0,this.text=n,this.response=r,this.usage=i,this.finishReason=a}static isInstance(e){return lh.hasMarker(e,JAe)}};XAe=YAe;var ZAe=Td([q(),ef($be,{message:`Must be a Uint8Array`}),ef(exe,{message:`Must be an ArrayBuffer`}),ef(e=>globalThis.Buffer?.isBuffer(e)??!1,{message:`Must be a Buffer`})]),Mg=Qd(()=>Td([pd(),q(),sd(),dd(),Ad(q(),Mg.optional()),bd(Mg)])),Ng=Ad(q(),Ad(q(),Mg.optional())),QAe=J({type:Pd(`text`),text:q(),providerOptions:Ng.optional()}),$Ae=J({type:Pd(`image`),image:Td([ZAe,nf(URL)]),mediaType:q().optional(),providerOptions:Ng.optional()}),eje=J({type:Pd(`file`),data:Td([ZAe,nf(URL)]),filename:q().optional(),mediaType:q(),providerOptions:Ng.optional()}),tje=J({type:Pd(`reasoning`),text:q(),providerOptions:Ng.optional()}),nje=J({type:Pd(`tool-call`),toolCallId:q(),toolName:q(),input:hd(),providerOptions:Ng.optional(),providerExecuted:dd().optional()}),rje=Dd(`type`,[J({type:Pd(`text`),value:q(),providerOptions:Ng.optional()}),J({type:Pd(`json`),value:Mg,providerOptions:Ng.optional()}),J({type:Pd(`execution-denied`),reason:q().optional(),providerOptions:Ng.optional()}),J({type:Pd(`error-text`),value:q(),providerOptions:Ng.optional()}),J({type:Pd(`error-json`),value:Mg,providerOptions:Ng.optional()}),J({type:Pd(`content`),value:bd(Td([J({type:Pd(`text`),text:q(),providerOptions:Ng.optional()}),J({type:Pd(`media`),data:q(),mediaType:q()}),J({type:Pd(`file-data`),data:q(),mediaType:q(),filename:q().optional(),providerOptions:Ng.optional()}),J({type:Pd(`file-url`),url:q(),mediaType:q().optional(),providerOptions:Ng.optional()}),J({type:Pd(`file-id`),fileId:Td([q(),Ad(q(),q())]),providerOptions:Ng.optional()}),J({type:Pd(`image-data`),data:q(),mediaType:q(),providerOptions:Ng.optional()}),J({type:Pd(`image-url`),url:q(),providerOptions:Ng.optional()}),J({type:Pd(`image-file-id`),fileId:Td([q(),Ad(q(),q())]),providerOptions:Ng.optional()}),J({type:Pd(`custom`),providerOptions:Ng.optional()})]))})]),ije=J({type:Pd(`tool-result`),toolCallId:q(),toolName:q(),output:rje,providerOptions:Ng.optional()}),aje=J({type:Pd(`tool-approval-request`),approvalId:q(),toolCallId:q(),signature:q().optional(),inputSchemaInput:hd().optional()}),oje=J({type:Pd(`tool-approval-response`),approvalId:q(),approved:dd(),reason:q().optional()});Td([J({role:Pd(`system`),content:q(),providerOptions:Ng.optional()}),J({role:Pd(`user`),content:Td([q(),bd(Td([QAe,$Ae,eje]))]),providerOptions:Ng.optional()}),J({role:Pd(`assistant`),content:Td([q(),bd(Td([QAe,eje,tje,nje,ije,aje]))]),providerOptions:Ng.optional()}),J({role:Pd(`tool`),content:bd(Td([ije,oje])),providerOptions:Ng.optional()})]),new TextEncoder,KAe({},{array:()=>uje,choice:()=>dje,json:()=>fje,object:()=>lje,text:()=>cje});function sje(e){let t=[`ROOT`],n=-1,r=null,i=0;function a(e){return e>=`0`&&e<=`9`||e>=`A`&&e<=`F`||e>=`a`&&e<=`f`}function o(e,i,a){switch(e){case`"`:n=i,t.pop(),t.push(a),t.push(`INSIDE_STRING`);break;case`f`:case`t`:case`n`:n=i,r=i,t.pop(),t.push(a),t.push(`INSIDE_LITERAL`);break;case`-`:t.pop(),t.push(a),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=i,t.pop(),t.push(a),t.push(`INSIDE_NUMBER`);break;case`{`:n=i,t.pop(),t.push(a),t.push(`INSIDE_OBJECT_START`);break;case`[`:n=i,t.pop(),t.push(a),t.push(`INSIDE_ARRAY_START`)}}function s(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_COMMA`);break;case`}`:n=r,t.pop()}}function c(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=r,t.pop()}}for(let l=0;l<e.length;l++){let u=e[l];switch(t[t.length-1]){case`ROOT`:o(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;case`INSIDE_OBJECT_AFTER_COMMA`:u===`"`&&(t.pop(),t.push(`INSIDE_OBJECT_KEY`));break;case`INSIDE_OBJECT_KEY`:u===`"`&&(t.pop(),t.push(`INSIDE_OBJECT_AFTER_KEY`));break;case`INSIDE_OBJECT_AFTER_KEY`:u===`:`&&(t.pop(),t.push(`INSIDE_OBJECT_BEFORE_VALUE`));break;case`INSIDE_OBJECT_BEFORE_VALUE`:o(u,l,`INSIDE_OBJECT_AFTER_VALUE`);break;case`INSIDE_OBJECT_AFTER_VALUE`:s(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,o(u,l,`INSIDE_ARRAY_AFTER_VALUE`)}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;case`INSIDE_ARRAY_AFTER_COMMA`:o(u,l,`INSIDE_ARRAY_AFTER_VALUE`);break;case`INSIDE_STRING_ESCAPE`:t.pop(),u===`u`?(i=0,t.push(`INSIDE_STRING_UNICODE_ESCAPE`)):n=l;break;case`INSIDE_STRING_UNICODE_ESCAPE`:a(u)&&(i++,i===4&&(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`&&c(u,l),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&s(u,l);break;case`}`:t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&s(u,l);break;case`]`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&c(u,l);break;default:t.pop()}break;case`INSIDE_LITERAL`:{let i=e.substring(r,l+1);!`false`.startsWith(i)&&!`true`.startsWith(i)&&!`null`.startsWith(i)?(t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`?s(u,l):t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&c(u,l)):n=l;break}}}let l=e.slice(0,n+1);for(let n=t.length-1;n>=0;n--)switch(t[n]){case`INSIDE_STRING`:l+=`"`;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`:l+=`}`;break;case`INSIDE_ARRAY_START`:case`INSIDE_ARRAY_AFTER_COMMA`:case`INSIDE_ARRAY_AFTER_VALUE`:l+=`]`;break;case`INSIDE_LITERAL`:{let t=e.substring(r,e.length);`true`.startsWith(t)?l+=`true`.slice(t.length):`false`.startsWith(t)?l+=`false`.slice(t.length):`null`.startsWith(t)&&(l+=`null`.slice(t.length))}}return l}async function Pg(e){if(e===void 0)return{value:void 0,state:`undefined-input`};let t=await Mh({text:e});return t.success?{value:t.value,state:`successful-parse`}:(t=await Mh({text:sje(e)}),t.success?{value:t.value,state:`repaired-parse`}:{value:void 0,state:`failed-parse`})}var cje=()=>({name:`text`,responseFormat:Promise.resolve({type:`text`}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),lje=({schema:e,name:t,description:n})=>{let r=HSe(e);return{name:`object`,responseFormat:Fh(r.jsonSchema).then(e=>({type:`json`,schema:e,...t!=null&&{name:t},...n!=null&&{description:n}})),async parseCompleteOutput({text:e},t){let n=await Mh({text:e});if(!n.success)throw new jg({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let i=await jh({value:n.value,schema:r});if(!i.success)throw new jg({message:`No object generated: response did not match schema.`,cause:i.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return i.value},async parsePartialOutput({text:e}){let t=await Pg(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:return{partial:t.value}}},createElementStreamTransform(){}}},uje=({element:e,name:t,description:n})=>{let r=HSe(e);return{name:`array`,responseFormat:Fh(r.jsonSchema).then(e=>{let{$schema:r,...i}=e;return{type:`json`,schema:{$schema:`http://json-schema.org/draft-07/schema#`,type:`object`,properties:{elements:{type:`array`,items:i}},required:[`elements`],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}}),async parseCompleteOutput({text:e},t){let n=await Mh({text:e});if(!n.success)throw new jg({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let i=n.value;if(typeof i!=`object`||!i||!(`elements`in i)||!Array.isArray(i.elements))throw new jg({message:`No object generated: response did not match schema.`,cause:new fh({value:i,cause:`response must be an object with an elements array`}),text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let a=[];for(let n of i.elements){let i=await jh({value:n,schema:r});if(!i.success)throw new jg({message:`No object generated: response did not match schema.`,cause:i.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});a.push(i.value)}return a},async parsePartialOutput({text:e}){let t=await Pg(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:{let e=t.value;if(typeof e!=`object`||!e||!(`elements`in e)||!Array.isArray(e.elements))return;let n=t.state===`repaired-parse`&&e.elements.length>0?e.elements.slice(0,-1):e.elements,i=[];for(let e of n){let t=await jh({value:e,schema:r});t.success&&i.push(t.value)}return{partial:i}}}},createElementStreamTransform(){let e=0;return new TransformStream({transform({partialOutput:t},n){if(t!=null)for(;e<t.length;e++)n.enqueue(t[e])}})}}},dje=({options:e,name:t,description:n})=>({name:`choice`,responseFormat:Promise.resolve({type:`json`,schema:{$schema:`http://json-schema.org/draft-07/schema#`,type:`object`,properties:{result:{type:`string`,enum:e}},required:[`result`],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}),async parseCompleteOutput({text:t},n){let r=await Mh({text:t});if(!r.success)throw new jg({message:`No object generated: could not parse the response.`,cause:r.error,text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});let i=r.value;if(typeof i!=`object`||!i||!(`result`in i)||typeof i.result!=`string`||!e.includes(i.result))throw new jg({message:`No object generated: response did not match schema.`,cause:new fh({value:i,cause:`response must be an object that contains a choice value.`}),text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});return i.result},async parsePartialOutput({text:t}){let n=await Pg(t);switch(n.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:{let t=n.value;if(typeof t!=`object`||!t||!(`result`in t)||typeof t.result!=`string`)return;let r=e.filter(e=>e.startsWith(t.result));return n.state===`successful-parse`?r.includes(t.result)?{partial:t.result}:void 0:r.length===1?{partial:r[0]}:void 0}}},createElementStreamTransform(){}}),fje=({name:e,description:t}={})=>({name:`json`,responseFormat:Promise.resolve({type:`json`,...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:e},t){let n=await Mh({text:e});if(!n.success)throw new jg({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return n.value},async parsePartialOutput({text:e}){let t=await Pg(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:return t.value===void 0?void 0:{partial:t.value}}},createElementStreamTransform(){}});_h({prefix:`aitxt`,size:24}),TransformStream,Ad(q(),Mg.optional());function pje(e){return e.type.startsWith(`tool-`)}function mje(e){return e.type===`dynamic-tool`}function Fg(e){return pje(e)||mje(e)}_h({prefix:`aitxt`,size:24}),Ad(q(),Mg.optional()),new TextEncoder,_h({prefix:`aiobj`,size:24});var{atob:hje}=globalThis;_h({prefix:`aiobj`,size:24});function gje(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e):[]}function _je(e){let t=gje(e);return t.some(e=>e.type!==`text`||e.text!==``)?t.filter(e=>e.type!==`text`||e.text!==``):t}function vje(e){let t=e.content.metadata?.signal;if(t&&typeof t==`object`&&!Array.isArray(t)){let n=t.type;return typeof n==`string`?n:e.type}return e.type}function yje(e){let t=e.content.metadata?.signal;if(t&&typeof t==`object`&&!Array.isArray(t)){let e=t.tagName;if(typeof e==`string`)return e}let n=vje(e);return n===`user`?`user`:n===`reactive`?e.type:n}function bje(e){return e===`user`||e===`user-message`}function xje(e){return typeof e.content.content==`string`?e.content.content:gje(e.content.parts).find(e=>e.type===`text`)?.text??``}function Sje(e){let t=e.content.metadata?.signal&&typeof e.content.metadata.signal==`object`?e.content.metadata.signal:{},n=t.metadata&&typeof t.metadata==`object`&&!Array.isArray(t.metadata)?t.metadata:{},r=t.attributes&&typeof t.attributes==`object`&&!Array.isArray(t.attributes)?t.attributes:{},i=vje(e)??`signal`,a=yje(e)??i;return{type:i===`user`?`data-user-message`:`data-signal`,data:{id:typeof t.id==`string`?t.id:e.id,type:i,tagName:a,contents:`contents`in t?t.contents:xje(e),createdAt:typeof t.createdAt==`string`?t.createdAt:e.createdAt.toISOString(),...typeof t.acceptedAt==`string`?{acceptedAt:t.acceptedAt}:{},...Object.keys(r).length?{attributes:r}:{},...Object.keys(n).length?{metadata:n}:{}}}}function Cje(e){return typeof e==`object`&&e&&`type`in e&&(e=e.type),typeof e==`string`?e===`dynamic-tool`?`dynamic-tool`:e.startsWith(`tool-`)?vm(e.slice(5)):vm(e):vm(e)}function Ig(e,t){return t==null?e:{...e||{},mastra:{...(e||{}).mastra||{},createdAt:t}}}function Lg(e){let t=e?.mastra;if(!t||typeof t!=`object`)return;let n=t.createdAt;return typeof n==`number`?n:void 0}function Rg(e,t,n,r=!0){if(!r)return n;let i=lm(e,`display`,t);return um(i)?i.transformed:n}function wje(e,t,n=!0){if(!n||!e||typeof e!=`object`)return e;let r=e,i=r.metadata??r.providerMetadata,a=lm(i,`display`,t),o=lm(i,`display`,`input-available`),s=t===`approval`?um(a)?a.transformed:um(o)?o.transformed:void 0:um(o)?o.transformed:um(a)?a.transformed:void 0,c=t===`suspend`&&um(a)?a.transformed:void 0;return{...r,...s===void 0?{}:{args:s},...c===void 0?{}:{suspendPayload:c}}}var zg=class{static toUIMessage(e,t){let n=bje(e.role===`signal`?vje(e):void 0),r=t?.transformToolPayloads??!0,i=[],a={...e.content.metadata||{}};if(e.role===`signal`&&!n&&i.push(Sje(e)),e.createdAt&&(a.createdAt=e.createdAt),e.threadId&&(a.threadId=e.threadId),e.resourceId&&(a.resourceId=e.resourceId),e.content.providerMetadata&&(a.providerMetadata=e.content.providerMetadata),e.role===`signal`&&!n)return{id:e.id,role:`system`,metadata:a,parts:i};let o=gje(e.content.parts),s=o.some(e=>e.type===`tool-invocation`);if(e.content.toolInvocations&&!s)for(let t of e.content.toolInvocations)t.state===`result`?i.push({type:`tool-${t.toolName}`,toolCallId:t.toolCallId,state:`output-available`,input:t.args,output:t.result}):i.push({type:`tool-${t.toolName}`,toolCallId:t.toolCallId,state:t.state===`call`?`input-available`:`input-streaming`,input:t.args});let c=o.some(e=>e.type===`reasoning`),l=o.some(e=>e.type===`file`);e.content.reasoning&&!c&&i.push({type:`reasoning`,text:e.content.reasoning});let u=new Set;if(e.content.experimental_attachments&&!l)for(let t of e.content.experimental_attachments)u.add(t.url),i.push({type:`file`,url:t.url,mediaType:t.contentType||`unknown`});let d=!1;if(o.length>0){for(let e of o)if(e.type===`tool-invocation`&&e.toolInvocation){let t=e.toolInvocation;t.state===`result`?i.push({type:`tool-${t.toolName}`,toolCallId:t.toolCallId,input:Rg(e.providerMetadata,`input-available`,t.args,r),output:Rg(e.providerMetadata,`output-available`,Rg(e.providerMetadata,`error`,t.result,r),r),state:`output-available`,callProviderMetadata:Ig(e.providerMetadata,e.createdAt),providerExecuted:e.providerExecuted}):t.state===`output-error`?i.push({type:`tool-${t.toolName}`,toolCallId:t.toolCallId,input:Rg(e.providerMetadata,`input-available`,t.args,r),errorText:Rg(e.providerMetadata,`error`,t.errorText||``,r),state:`output-error`,callProviderMetadata:Ig(e.providerMetadata,e.createdAt),providerExecuted:e.providerExecuted}):t.state===`output-denied`?i.push({type:`tool-${t.toolName}`,toolCallId:t.toolCallId,input:Rg(e.providerMetadata,`input-available`,t.args,r),output:t.approval?.reason??`Tool call was not approved by the user`,state:`output-available`,callProviderMetadata:Ig(e.providerMetadata,e.createdAt),providerExecuted:e.providerExecuted}):i.push({type:`tool-${t.toolName}`,toolCallId:t.toolCallId,input:Rg(e.providerMetadata,`input-available`,t.args,r),state:`input-available`,callProviderMetadata:Ig(e.providerMetadata,e.createdAt),providerExecuted:e.providerExecuted})}else if(e.type===`reasoning`){let t=e.reasoning||(e.details?.reduce((e,t)=>t.type===`text`&&t.text?e+t.text:e,``)??``);if(t||e.details?.length){let n={type:`reasoning`,text:t||``,state:`done`};n.providerMetadata=Ig(e.providerMetadata,e.createdAt),i.push(n)}}else if(!(e.type===`tool-invocation`||e.type.startsWith(`tool-`))){if(e.type===`file`){let{mediaType:t,data:n}=_m(e),r=e.filename;if(typeof n==`string`&&u.has(n))continue;let a=typeof n==`string`?gm(n,t):{type:`raw`,mimeType:t,data:n};if(typeof n==`string`&&(a.type===`url`||a.type===`providerFileId`||a.type===`raw`&&!Npe(n))){let t={type:`file`,url:n,mediaType:a.mimeType||`image/png`,...r?{filename:r}:{}};t.providerMetadata=Ig(e.providerMetadata,e.createdAt),i.push(t)}else{let a,o=t;if(typeof n==`string`){let e=mm(n);e.isDataUri&&!Vpe(n)?a=Hpe(n)??n:e.isDataUri?(a=e.base64Content,e.mimeType&&(o||=e.mimeType)):a=n}else a=kpe(n,o);let s=o||`image/png`,c;c=typeof a==`string`&&a.startsWith(`data:`)?a:Ope(a,s);let l={type:`file`,url:c,mediaType:s,...r?{filename:r}:{}};l.providerMetadata=Ig(e.providerMetadata,e.createdAt),i.push(l)}}else if(e.type===`source`){let t={type:`source-url`,url:e.source.url,sourceId:e.source.id,title:e.source.title};t.providerMetadata=Ig(e.providerMetadata,e.createdAt),i.push(t)}else if(e.type===`source-document`){let t={type:`source-document`,sourceId:e.sourceId,mediaType:e.mediaType,title:e.title,...e.filename?{filename:e.filename}:{}};t.providerMetadata=Ig(e.providerMetadata,e.createdAt),i.push(t)}else if(e.type===`text`){let t={type:`text`,text:e.text};t.providerMetadata=Ig(e.providerMetadata,e.createdAt),i.push(t),d=!0}else e.type===`data-tool-call-suspended`||e.type===`data-tool-call-approval`?i.push({...e,data:wje(e.data,e.type===`data-tool-call-suspended`?`suspend`:`approval`,r)}):(e.type,i.push(e),d=!0)}}e.content.content&&!d&&i.push({type:`text`,text:e.content.content});let f=new Set(i.filter(e=>e.type===`data-tool-call-suspended`||e.type===`data-tool-call-approval`).map(e=>{let t=e.data;return typeof t?.toolCallId==`string`?t.toolCallId:void 0}).filter(e=>typeof e==`string`)),p=(e,t)=>{let n=i.findIndex(t=>t.type.startsWith(`tool-`)&&t.toolCallId===e);n===-1?i.push(t):i.splice(n+1,0,t)},m=a.suspendedTools;if(m&&typeof m==`object`)for(let e of Object.values(m)){if(!e||typeof e!=`object`)continue;let t=`toolCallId`in e?e.toolCallId:void 0;typeof t!=`string`||f.has(t)||(p(t,{type:`data-tool-call-suspended`,data:wje(e,`suspend`,r)}),f.add(t))}let h=a.pendingToolApprovals;if(h&&typeof h==`object`)for(let e of Object.values(h)){if(!e||typeof e!=`object`)continue;let t=`toolCallId`in e?e.toolCallId:void 0;typeof t!=`string`||f.has(t)||(p(t,{type:`data-tool-call-approval`,data:wje(e,`approval`,r)}),f.add(t))}return{id:e.id,role:e.role===`signal`?n?`user`:`system`:e.role,metadata:a,parts:i}}static fromUIMessage(e){let{parts:t,metadata:n}=e,r=n||{},i=r.createdAt,a=i?typeof i==`string`?new Date(i):i instanceof Date?i:new Date:new Date,o=r.threadId,s=r.resourceId,c={...r};delete c.createdAt,delete c.threadId,delete c.resourceId;let l=t.filter(e=>ch(e)),u=t.filter(e=>e.type===`reasoning`),d=t.filter(e=>e.type===`file`),f=t.filter(e=>e.type===`text`),p;l.length>0&&(p=l.map(e=>{let t=Cje(e);return e.state===`output-available`?{args:e.input,result:gg(e.output),toolCallId:e.toolCallId,toolName:t,state:`result`}:{args:e.input,toolCallId:e.toolCallId,toolName:t,state:`call`}}));let m;u.length>0&&(m=u.map(e=>e.text).join(`
|
|
171
171
|
`));let h;d.length>0&&(h=d.map(e=>({url:e.url||``,contentType:e.mediaType})));let g;f.length>0&&(g=f.map(e=>e.text).join(``));let _=_je(t.map(e=>{if(ch(e)){let t=Cje(e),n=`callProviderMetadata`in e?e.callProviderMetadata:void 0,r=e.providerExecuted;if(e.state===`output-available`){let i={type:`tool-invocation`,toolInvocation:{toolCallId:e.toolCallId,toolName:t,args:e.input,result:gg(e.output),state:`result`},providerMetadata:n,createdAt:Lg(n)};return r!==void 0&&(i.providerExecuted=r),i}if(e.state===`output-error`){let i={type:`tool-invocation`,toolInvocation:{toolCallId:e.toolCallId,toolName:t,args:e.input,state:`output-error`,errorText:e.errorText,...`rawInput`in e&&e.rawInput!==void 0?{rawInput:e.rawInput}:{}},providerMetadata:n,createdAt:Lg(n)};return r!==void 0&&(i.providerExecuted=r),i}let i={type:`tool-invocation`,toolInvocation:{toolCallId:e.toolCallId,toolName:t,args:e.input,state:`call`},providerMetadata:n,createdAt:Lg(n)};return r!==void 0&&(i.providerExecuted=r),i}return e.type===`reasoning`?{type:`reasoning`,reasoning:e.text,details:[{type:`text`,text:e.text}],providerMetadata:e.providerMetadata,createdAt:Lg(e.providerMetadata)}:e.type===`file`?{type:`file`,mimeType:e.mediaType,data:e.url||``,providerMetadata:e.providerMetadata,createdAt:Lg(e.providerMetadata),...e.filename?{filename:e.filename}:{}}:e.type===`source-url`?{type:`source`,source:{url:e.url,sourceType:`url`,id:e.sourceId??e.url,...e.title?{title:e.title}:{},providerMetadata:e.providerMetadata},providerMetadata:e.providerMetadata,createdAt:Lg(e.providerMetadata)}:e.type===`source-document`?{type:`source-document`,sourceId:e.sourceId,mediaType:e.mediaType,title:e.title,...e.filename?{filename:e.filename}:{},providerMetadata:e.providerMetadata,createdAt:Lg(e.providerMetadata)}:e.type===`text`?{type:`text`,text:e.text,providerMetadata:e.providerMetadata,createdAt:Lg(e.providerMetadata)}:e.type===`step-start`||e.type===`error`?e:typeof e.type==`string`&&e.type.startsWith(`data-`)?{type:e.type,data:`data`in e?e.data:void 0}:null}).filter(e=>e!==null));return{id:e.id,role:e.role,createdAt:a,threadId:o,resourceId:s,content:{format:2,parts:_,toolInvocations:p,reasoning:m,experimental_attachments:h,content:g,metadata:Object.keys(c).length>0?c:void 0}}}static getDataStringFromAIV5DataPart(e){let t,n;if(`data`in e)t=e.mediaType||`application/octet-stream`,n=e.data;else if(`image`in e)t=e.mediaType||`image/jpeg`,n=e.image;else if(`url`in e&&typeof e.url==`string`)return e.url;else throw new yn({id:`MASTRA_AIV5_DATA_PART_INVALID`,domain:gn.AGENT,category:_n.USER,text:`Invalid AIV5 data part in getDataStringFromAIV5DataPart`,details:{part:e}});if(n&&typeof n==`object`&&!(n instanceof URL)&&!(n instanceof Uint8Array)&&!(n instanceof ArrayBuffer)&&typeof n.type==`string`){let e=n;if(e.type===`url`&&(typeof e.url==`string`||e.url instanceof URL))n=e.url;else if(e.type===`data`&&e.data!=null)n=e.data;else if(e.type===`text`&&typeof e.text==`string`)return`data:${t};base64,${Buffer.from(e.text,`utf8`).toString(`base64`)}`;else throw new yn({id:`MASTRA_AIV5_DATA_PART_INVALID`,domain:gn.AGENT,category:_n.USER,text:e.type===`reference`?`Provider file references are not supported as message input.`:`Invalid "${e.type}" file data in message part.`,details:{type:e.type}})}if(n instanceof URL)return n.toString();if(n instanceof Buffer){let e=n.toString(`base64`);return`data:${t};base64,${e}`}if(typeof n==`string`)return n.startsWith(`data:`)||n.startsWith(`file-`)||Gpe(n)||!Npe(n)?n:`data:${t};base64,${n}`;if(n instanceof Uint8Array||n instanceof ArrayBuffer){let e=Buffer.from(n).toString(`base64`);return`data:${t};base64,${e}`}throw new yn({id:`MASTRA_AIV5_DATA_PART_INVALID`,domain:gn.AGENT,category:_n.USER,text:`Unrecognized file data in message part`,details:{dataType:typeof n}})}static fromModelMessage(e,t,n={}){let r=Array.isArray(e.content)?e.content.filter(e=>typeof e==`object`&&!!e):typeof e.content==`string`?[{type:`text`,text:e.content}]:[],i=[],a=[],o=[],s=[];for(let e of r)if(e.type===`text`){let t={type:`text`,text:e.text};e.providerOptions&&(t.providerMetadata=e.providerOptions,t.createdAt=Lg(e.providerOptions)),i.push(t)}else if(e.type===`tool-call`){let t=e,n={type:`tool-invocation`,toolInvocation:{toolCallId:t.toolCallId,toolName:vm(t.toolName),args:t.input,state:`call`}};e.providerOptions&&(n.providerMetadata=e.providerOptions,n.createdAt=Lg(e.providerOptions));let r=e.providerExecuted;r!==void 0&&(n.providerExecuted=r),i.push(n),a.push({toolCallId:t.toolCallId,toolName:vm(t.toolName),args:t.input,state:`call`})}else if(e.type===`tool-result`){let t=e,r=a.find(e=>e.toolCallId===t.toolCallId),o=i.find(e=>e.type===`tool-invocation`&&`toolInvocation`in e&&e.toolInvocation.toolCallId===t.toolCallId),s=(e,t)=>{let n=Lke(e.output);t.state=n.isError?`output-error`:`result`,t.result=n.output,n.isError&&(t.errorText=typeof n.output==`string`?n.output:JSON.stringify(n.output))},c=n.dbMessages?bg(n.dbMessages,t.toolCallId):void 0,l=c&&Object.keys(c).length>0?c:t.input??{};if(r)s(t,r);else{let e={state:`call`,toolCallId:t.toolCallId,toolName:vm(t.toolName),args:l};s(t,e),a.push(e)}let u=t.providerExecuted;if(o&&o.type===`tool-invocation`)s(t,o.toolInvocation),u!==void 0&&(o.providerExecuted=u),t.providerOptions&&(o.providerMetadata=Hke(o.providerMetadata,t.providerOptions,t.providerOptions),o.createdAt=Lg(t.providerOptions)??o.createdAt);else{let e={type:`tool-invocation`,toolInvocation:{toolCallId:t.toolCallId,toolName:vm(t.toolName),args:l,state:`call`}};s(t,e.toolInvocation),u!==void 0&&(e.providerExecuted=u),t.providerOptions&&(e.providerMetadata=t.providerOptions,e.createdAt=Lg(t.providerOptions)),i.push(e)}}else if(e.type===`reasoning`){let t={type:`reasoning`,reasoning:e.text,details:[{type:`text`,text:e.text}]};e.providerOptions&&(t.providerMetadata=e.providerOptions,t.createdAt=Lg(e.providerOptions)),i.push(t),o.push(e.text)}else if(e.type===`image`){let t=e,n=t.mediaType||`image/jpeg`,r=this.getDataStringFromAIV5DataPart(t),a={type:`file`,data:r,mimeType:n};e.providerOptions&&(a.providerMetadata=e.providerOptions,a.createdAt=Lg(e.providerOptions)),i.push(a),s.push({url:r,contentType:n})}else if(e.type===`file`){let t=e,n=t.mediaType||`application/octet-stream`,r=this.getDataStringFromAIV5DataPart(t),a={type:`file`,data:r,mimeType:n};e.providerOptions&&(a.providerMetadata=e.providerOptions,a.createdAt=Lg(e.providerOptions)),t.filename&&(a.filename=t.filename),i.push(a),s.push({url:r,contentType:n})}let c=_je(i),l=c.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
172
172
|
`),u=`metadata`in e&&e.metadata!==null&&e.metadata!==void 0?e.metadata:{},d={id:`id`in e&&typeof e.id==`string`?e.id:`msg-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,role:e.role===`tool`?`assistant`:e.role,createdAt:new Date,content:{format:2,parts:c,toolInvocations:a.length>0?a:void 0,reasoning:o.length>0?o.join(`
|
|
173
|
-
`):void 0,experimental_attachments:s.length>0?s:void 0,content:l||void 0,metadata:Object.keys(u).length>0?u:void 0}};return e.providerOptions&&(d.content.providerMetadata=e.providerOptions),d}};function Bg(e,t){for(let[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}function Vg(e,t,n){let r=lm(e,`display`,t);return um(r)?r.transformed:n}function Tje(e){return e.startsWith(`tool-`)?vm(e.slice(5)):vm(e)}function Eje(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}function Dje(e){return e===`approval-requested`||e===`approval-responded`||e===`output-denied`}function Oje(e){if(e)return{id:e.id,approved:`approved`in e?e.approved:void 0,reason:`reason`in e?e.reason:void 0}}function Hg(e){return e}function kje(e){return e.type===`dynamic-tool`?vm(e.toolName):Tje(e.type)}function Aje(e){let t=`callProviderMetadata`in e?e.callProviderMetadata:void 0,n=`resultProviderMetadata`in e?e.resultProviderMetadata:void 0;if(!n)return Hg(t);if(!t)return Hg(n);let r={...t};for(let[e,t]of Object.entries(n)){let n=r[e];r[e]=n?{...n,...t}:t}return Hg(Hke(t,n,r))}function jje(e){let t={toolCallId:e.toolCallId,toolName:kje(e),args:Eje(e.input),approval:`approval`in e?Oje(e.approval):void 0,providerMetadata:Aje(e),providerExecuted:e.providerExecuted,title:e.title,preliminary:`preliminary`in e?e.preliminary:void 0};switch(e.state){case`input-streaming`:return Ug({...t,state:`partial-call`});case`input-available`:return Ug({...t,state:`call`});case`output-available`:return Ug({...t,state:`result`,result:gg(e.output)});case`output-error`:return Ug({...t,state:`output-error`,errorText:e.errorText,rawInput:`rawInput`in e?e.rawInput:void 0});case`approval-requested`:case`approval-responded`:case`output-denied`:return Ug({...t,state:e.state})}}function Mje(e){return e.type===`dynamic-tool`&&!Dje(e.state)?{...e,type:`tool-${vm(e.toolName)}`}:e}function Nje(e){return Fg(e)||e.type.startsWith(`data-`)||[`text`,`reasoning`,`file`,`source-url`,`source-document`,`step-start`,`error`].includes(e.type)}function Pje(e){if(e.type!==`data-tool-call-suspended`||!(`data`in e))return;let t=e.data;if(t&&typeof t==`object`&&`toolCallId`in t)return typeof t.toolCallId==`string`?t.toolCallId:void 0}function Ug({toolCallId:e,toolName:t,args:n,state:r,approval:i,result:a,errorText:o,rawInput:s,providerMetadata:c,providerExecuted:l,title:u,preliminary:d}){return Bg({type:`tool-invocation`,toolInvocation:Bg({toolCallId:e,toolName:t,args:n,state:r},{approval:i,result:a,errorText:o,rawInput:s})},{providerMetadata:c,providerExecuted:l,title:u,preliminary:d})}function Fje(e,t){for(let n of e)if(n.type===`tool-invocation`&&n.toolInvocation.toolCallId===t)return n}function Ije(e,t){if(e)for(let n of[...e].reverse()){for(let e of[...n.content.parts||[]].reverse())if(e.type===`tool-invocation`&&e.toolInvocation.approval?.id===t&&e.toolInvocation.state===`approval-requested`)return e;let e=n.content.metadata?.pendingToolApprovals;if(e&&typeof e==`object`)for(let r of Object.values(e)){if(!r||typeof r!=`object`)continue;let e=`toolCallId`in r?r.toolCallId:void 0;if(typeof e!=`string`)continue;let i=`runId`in r?r.runId:void 0,a=typeof i==`string`?`${i}::${e}`:e;if(a!==t)continue;let o=Fje(n.content.parts||[],e);if(o)return Ug({toolCallId:o.toolInvocation.toolCallId,toolName:o.toolInvocation.toolName,args:o.toolInvocation.args,state:`approval-requested`,approval:{id:a},providerMetadata:o.providerMetadata,providerExecuted:o.providerExecuted,title:o.title,preliminary:o.preliminary})}}}function Lje(e,t){let n=t.pendingToolApprovals;if(n&&typeof n==`object`)for(let t of Object.values(n)){if(!t||typeof t!=`object`)continue;let n=`toolCallId`in t?t.toolCallId:void 0;if(typeof n!=`string`)continue;let r=`runId`in t?t.runId:void 0,i=typeof r==`string`?`${r}::${n}`:n,a=e.findIndex(e=>Fg(e)&&e.toolCallId===n&&e.state===`input-available`);if(a===-1)continue;let o=e[a];o&&Fg(o)&&o.state===`input-available`&&(e[a]={...o,state:`approval-requested`,approval:{id:i}})}}function Rje(e){let t=[];for(let n of e){if(n.type!==`tool-invocation`)continue;let e=n.toolInvocation;e.state===`result`?t.push({args:e.args,result:e.result,toolCallId:e.toolCallId,toolName:e.toolName,state:`result`}):(e.state===`call`||e.state===`partial-call`)&&t.push({args:e.args,toolCallId:e.toolCallId,toolName:e.toolName,state:e.state})}return t.length>0?t:void 0}var Wg=class e{static toUIMessage(t){let n=zg.toUIMessage(t),r=n.metadata||{},i=[];if(t.role===`signal`&&n.role!==`user`)return{id:t.id,role:`system`,metadata:Object.keys(r).length>0?r:void 0,parts:n.parts.map(t=>e.toUIPartFromV5(t))};let a=t.content.parts||[],o=a.some(e=>e.type===`tool-invocation`),s=a.some(e=>e.type===`reasoning`),c=a.some(e=>e.type===`file`),l=a.some(e=>e.type===`text`);for(let t of a){let n=e.toUIPart(t);n&&i.push(n)}if(!o||!s||!c||!l)for(let t of n.parts)ch(t)?o||i.push(e.toUIPartFromV5(t)):t.type===`reasoning`?s||i.push(e.toUIPartFromV5(t)):t.type===`file`?c||i.push(e.toUIPartFromV5(t)):t.type===`text`&&!l&&i.push(e.toUIPartFromV5(t));return e.rehydrateSuspendedToolParts(i,n.parts),Lje(i,r),{id:t.id,role:t.role===`signal`?n.role:t.role,metadata:Object.keys(r).length>0?r:void 0,parts:i}}static fromUIMessage(e){let t=e=>e.type!==`source-document`&&!Fg(e),n=e=>e.type===`text`&&e.text===``,r=e.parts.filter(Nje),i=r.some(e=>t(e)&&!n(e));e={...e,parts:i?r.filter(e=>!n(e)):r};let a=e.parts.filter(t),o=zg.fromUIMessage({...e,parts:a.map(e=>Mje(e))}),s=o.content.parts||[],c=[],l=0;for(let t of e.parts)if(t.type===`source-document`)c.push(Bg({type:`source-document`,sourceId:t.sourceId,mediaType:t.mediaType,title:t.title},{filename:t.filename,providerMetadata:Hg(t.providerMetadata)}));else if(Fg(t))c.push(jje(t));else{let e=s[l++];e&&c.push(e)}return{...o,content:{...o.content,parts:c,toolInvocations:Rje(c)||o.content.toolInvocations}}}static fromModelMessage(e,t,n={}){let r=Array.isArray(e.content)?e.content:[{type:`text`,text:e.content}],i=r.filter(e=>e.type!==`tool-approval-request`&&e.type!==`tool-approval-response`),a=zg.fromModelMessage({...e,content:i},t,n),o=[...a.content.parts];if(e.role===`assistant`){let e=new Map;for(let t of r){if(t.type===`tool-call`){e.set(t.toolCallId,{toolName:vm(t.toolName),args:Eje(t.input)});continue}if(t.type!==`tool-approval-request`)continue;let n=e.get(t.toolCallId),r=Fje(o,t.toolCallId);r?(r.toolInvocation.state=`approval-requested`,r.toolInvocation.approval={id:t.approvalId}):o.push(Ug({toolCallId:t.toolCallId,toolName:n?.toolName||`unknown`,args:n?.args||{},state:`approval-requested`,approval:{id:t.approvalId}}))}}else if(e.role===`tool`)for(let e of r){if(e.type!==`tool-approval-response`)continue;let t=Ije(n.dbMessages,e.approvalId);t&&o.push(Ug({toolCallId:t.toolInvocation.toolCallId,toolName:t.toolInvocation.toolName,args:t.toolInvocation.args,state:`approval-responded`,approval:{id:e.approvalId,approved:e.approved,reason:e.reason},providerMetadata:t.providerMetadata,providerExecuted:t.providerExecuted,title:t.title}))}return{...a,content:{...a.content,parts:o}}}static toUIPart(t){if(t.type===`tool-invocation`){let e=Bg({type:`tool-${vm(t.toolInvocation.toolName)}`,toolCallId:t.toolInvocation.toolCallId,providerExecuted:t.providerExecuted},{callProviderMetadata:Gke(t.providerMetadata),title:t.title});switch(t.toolInvocation.state){case`partial-call`:return{...e,state:`input-streaming`,input:Vg(t.providerMetadata,`input-available`,t.toolInvocation.args)};case`call`:return{...e,state:`input-available`,input:Vg(t.providerMetadata,`input-available`,t.toolInvocation.args)};case`approval-requested`:return{...e,state:`approval-requested`,input:Vg(t.providerMetadata,`input-available`,t.toolInvocation.args),approval:{id:t.toolInvocation.approval?.id||t.toolInvocation.toolCallId}};case`approval-responded`:return{...e,state:`approval-responded`,input:Vg(t.providerMetadata,`input-available`,t.toolInvocation.args),approval:{id:t.toolInvocation.approval?.id||t.toolInvocation.toolCallId,approved:t.toolInvocation.approval?.approved??!1,reason:t.toolInvocation.approval?.reason}};case`output-error`:return Bg({...e,state:`output-error`,input:Vg(t.providerMetadata,`input-available`,t.toolInvocation.args),errorText:Vg(t.providerMetadata,`error`,t.toolInvocation.errorText||``)},{rawInput:t.toolInvocation.rawInput,resultProviderMetadata:Uke(t.providerMetadata),approval:t.toolInvocation.approval?.approved===!0?{id:t.toolInvocation.approval.id,approved:!0,reason:t.toolInvocation.approval.reason}:void 0});case`output-denied`:return{...e,state:`output-denied`,input:Vg(t.providerMetadata,`input-available`,t.toolInvocation.args),approval:{id:t.toolInvocation.approval?.id||t.toolInvocation.toolCallId,approved:!1,reason:t.toolInvocation.approval?.reason}};case`result`:return Bg({...e,state:`output-available`,input:Vg(t.providerMetadata,`input-available`,t.toolInvocation.args),output:Vg(t.providerMetadata,`output-available`,Vg(t.providerMetadata,`error`,t.toolInvocation.result))},{preliminary:t.preliminary,resultProviderMetadata:Uke(t.providerMetadata),approval:t.toolInvocation.approval?.approved===!0?{id:t.toolInvocation.approval.id,approved:!0,reason:t.toolInvocation.approval.reason}:void 0});default:throw Error(`Unhandled toolInvocation.state: ${String(t.toolInvocation.state)}`)}}if(t.type===`source-document`)return Bg({type:`source-document`,sourceId:t.sourceId,mediaType:t.mediaType,title:t.title},{filename:t.filename,providerMetadata:t.providerMetadata});let n=zg.toUIMessage({id:`tmp`,role:`assistant`,createdAt:new Date,content:{format:2,parts:[t]}}).parts[0];return n?e.toUIPartFromV5(n):void 0}static rehydrateSuspendedToolParts(t,n){let r=new Set(t.map(Pje).filter(e=>e!==void 0));for(let i of n){let n=Pje(i);if(!n||r.has(n))continue;let a=t.findIndex(e=>Fg(e)&&e.toolCallId===n),o=e.toUIPartFromV5(i);a===-1?t.push(o):t.splice(a+1,0,o),r.add(n)}}static toUIPartFromV5(e){if(ch(e)){let t={type:e.type,toolCallId:e.toolCallId,providerExecuted:e.providerExecuted};switch(e.state){case`input-streaming`:return Bg({...t,state:`input-streaming`,input:e.input},{callProviderMetadata:`callProviderMetadata`in e?e.callProviderMetadata:void 0,title:`title`in e?e.title:void 0});case`input-available`:return Bg({...t,state:`input-available`,input:e.input},{callProviderMetadata:`callProviderMetadata`in e?e.callProviderMetadata:void 0,title:`title`in e?e.title:void 0});case`output-available`:return Bg({...t,state:`output-available`,input:e.input,output:e.output},{callProviderMetadata:`callProviderMetadata`in e?e.callProviderMetadata:void 0,preliminary:`preliminary`in e?e.preliminary:void 0,title:`title`in e?e.title:void 0});case`output-error`:return Bg({...t,state:`output-error`,input:e.input,errorText:e.errorText},{rawInput:`rawInput`in e?e.rawInput:void 0,callProviderMetadata:`callProviderMetadata`in e?e.callProviderMetadata:void 0,title:`title`in e?e.title:void 0})}}switch(e.type){case`text`:return Bg({type:`text`,text:e.text},{providerMetadata:e.providerMetadata});case`reasoning`:return Bg({type:`reasoning`,text:e.text,state:e.state},{providerMetadata:e.providerMetadata});case`file`:return Bg({type:`file`,url:e.url,mediaType:e.mediaType},{filename:`filename`in e?e.filename:void 0,providerMetadata:e.providerMetadata});case`source-url`:return Bg({type:`source-url`,sourceId:e.sourceId,url:e.url},{title:e.title,providerMetadata:e.providerMetadata});case`step-start`:return{type:`step-start`};default:return typeof e.type==`string`&&e.type.startsWith(`data-`)?{type:e.type,data:`data`in e?e.data:void 0}:e}}},zje=/^(itemId|signature|redactedData|encryptedContent|reasoningEncryptedContent|\w*Signature|\w*Digest)$/;function Bje(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Gg(e){let t=3735928559,n=1103547991;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);t=Math.imul(t^i,2654435761),n=Math.imul(n^i,1597334677)}return t=Math.imul(t^t>>>16,2246822507)^Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),(4294967296*(2097151&n)+(t>>>0)).toString(36)}function Vje(...e){let t=new Set;for(let n of e)if(Bje(n)){for(let e of Object.values(n))if(Bje(e))for(let[n,r]of Object.entries(e))typeof r==`string`&&r.length!==0&&zje.test(n)&&t.add(`${n}:${Gg(r)}`)}return[...t].sort()}function Kg(e,...t){for(let n of Vje(...t))e+=`|${n}`;return e}function Hje(e){return JSON.stringify(e,(e,t)=>{if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.create(null);for(let n of Object.keys(t).sort())e[n]=t[n];return e}return t})}function qg(e,...t){let n=new Set(t.flatMap(e=>Kke(e)));for(let t of n)e+=`|${t}`;return e}var Jg=class e{static fromAIV4Parts(t){let n=``;for(let r of t)n+=r.type,n+=e.fromAIV4Part(r);return n}static fromAIV4Part(e){let t=``;if(e.type===`text`&&(t+=e.text,t=qg(t,e.providerMetadata)),e.type===`tool-invocation`){if(!e.toolInvocation)return t;t+=e.toolInvocation.toolCallId,t+=e.toolInvocation.state}if(e.type===`reasoning`){t+=e.reasoning,t+=(e.details??[]).reduce((e,t)=>t.type===`text`?e+(t.text?.length??0)+(t.signature?.length||0):e,0);let n=e;n&&Object.hasOwn(n,`providerMetadata`)&&(t=qg(t,n.providerMetadata)),t=Kg(t,n?.providerMetadata);for(let n of e.details??[]){let e=n.type===`text`?n.signature:n.data;e&&(t+=`|${n.type}:${Gg(e)}`)}}if(e.type===`file`){let{mediaType:n,data:r}=_m(e);t+=r,t+=n}return t}static fromDBParts(t){let n=``;for(let r of t)if(n+=r.type,r.type.startsWith(`data-`)){let e=r.data;n+=Hje(e)}else n+=e.fromAIV4Part(r);return n}static fromAIV4CoreMessageContent(e){if(typeof e==`string`)return e;let t=``;for(let n of e){if(t+=n.type,n.type===`text`){t+=n.text.length;let e=n;t=qg(t,e.providerMetadata,e.providerOptions)}if(n.type===`reasoning`){t+=n.text.length;let e=n;t=qg(t,e.providerMetadata,e.providerOptions),t=Kg(t,e.providerMetadata,e.providerOptions),n.signature&&(t+=`|signature:${Gg(n.signature)}`)}n.type===`tool-call`&&(t+=n.toolCallId,t+=n.toolName),n.type===`tool-result`&&(t+=n.toolCallId,t+=n.toolName),n.type===`file`&&(t+=n.filename,t+=n.mimeType),n.type===`image`&&(t+=Ape(n.image),t+=n.mimeType),n.type===`redacted-reasoning`&&(t+=n.data.length,t+=`|${Gg(n.data)}`)}return t}static fromAIV5Parts(e){let t=``;for(let n of e)t+=n.type,n.type===`text`&&(t+=n.text,t=qg(t,n.providerMetadata)),(ch(n)||n.type===`dynamic-tool`)&&(t+=n.toolCallId,t+=n.state),n.type===`reasoning`&&(t+=n.text,t=qg(t,n.providerMetadata),t=Kg(t,n.providerMetadata)),n.type===`file`&&(t+=n.url.length,t+=n.mediaType,t+=n.filename||``);return t}static fromAIV5ModelMessageContent(e){if(typeof e==`string`)return e;let t=``;for(let n of e)t+=n.type,n.type===`text`&&(t+=n.text.length,t=qg(t,n.providerOptions)),n.type===`reasoning`&&(t+=n.text.length,t=qg(t,n.providerOptions),t=Kg(t,n.providerOptions)),n.type===`tool-call`&&(t+=n.toolCallId,t+=n.toolName),n.type===`tool-result`&&(t+=n.toolCallId,t+=n.toolName),n.type===`file`&&(t+=n.filename,t+=n.mediaType),n.type===`image`&&(t+=Ape(n.image),t+=n.mediaType);return t}},Uje=`<working_memory>`,Wje=`</working_memory>`,Gje=`updateWorkingMemory`;function Yg(e){let t=``,n=0;for(;n<e.length;){let r=e.indexOf(Uje,n);if(r===-1){t+=e.substring(n);break}t+=e.substring(n,r);let i=e.indexOf(Wje,r+16);if(i===-1){t+=e.substring(r);break}n=i+17}return t}var Kje=`skip_thought_signature_validator`;function qje(e){let t=e=>e?.type===`tool-invocation`&&e.toolInvocation?.toolName===`updateWorkingMemory`;if(!e.some(t))return e;let n=[];return e.forEach((t,r)=>{let i=e[r-1];(t?.type===`step-start`||i?.type===`tool-invocation`&&t?.type!==`tool-invocation`||n.length===0)&&n.push([]),n[n.length-1].push(t)}),n.flatMap(e=>{if(!e.some(t))return e;let n=e.filter(e=>!t(e)),r=n.findIndex(e=>e?.type===`tool-invocation`),i=n[r];if(i?.type===`tool-invocation`){let a=i.providerMetadata;for(let n of e)if(t(n))for(let[e,t]of Object.entries(n.providerMetadata??{}))t?.thoughtSignature!==void 0&&a?.[e]?.thoughtSignature===void 0&&(a={...a,[e]:{...a?.[e],thoughtSignature:Kje}});a!==i.providerMetadata&&(n[r]={...i,providerMetadata:a})}return n.every(e=>e?.type===`step-start`||e?.type===`reasoning`||e?.type===`text`&&!Yg(e.text??``).trim())?[]:n})}function Jje(e){if(!e?.some(e=>e.toolName===`updateWorkingMemory`))return e;let t=e.filter(e=>e.toolName!==Gje);return t.length>0?t:void 0}function Yje(e){return e.filter(e=>e.role!==`system`&&!epe(e)).map(e=>{let t={...e};if(e.content&&typeof e.content==`object`&&!Array.isArray(e.content)&&(t.content={...e.content}),typeof t.content?.content==`string`&&t.content.content.length>0){let e=Yg(t.content.content);t.content.content=e===t.content.content?t.content.content:e.trim()}return Array.isArray(t.content?.parts)&&(Array.isArray(t.content.toolInvocations)&&(t.content.toolInvocations=Jje(t.content.toolInvocations)),t.content.parts=qje(t.content.parts).map(e=>{if(e.type===`tool-invocation`&&e.toolInvocation.state===`partial-call`)return null;if(e.type===`text`){let t=typeof e.text==`string`?e.text:``,n=Yg(t);return{...e,text:n===t?t:n.trim()}}return e}).filter(e=>!!e),t.content.parts.length===0)?null:t}).filter(e=>!!e)}function Xje(e){return typeof e==`string`?e:e.reduce((e,t)=>(t.type===`text`&&(e+=t.text),e),``)}function Zje(e,t){let n=_g.isAIV4UIMessage(e)&&e,r=_g.isAIV4UIMessage(t)&&t;if(n&&!r)return!1;if(n&&r)return Jg.fromAIV4Parts(e.parts)===Jg.fromAIV4Parts(t.parts);let i=_g.isAIV4CoreMessage(e)&&e,a=_g.isAIV4CoreMessage(t)&&t;if(i&&!a)return!1;if(i&&a)return Jg.fromAIV4CoreMessageContent(i.content)===Jg.fromAIV4CoreMessageContent(a.content);let o=_g.isMastraMessageV1(e)&&e,s=_g.isMastraMessageV1(t)&&t;if(o&&!s)return!1;if(o&&s)return o.id===s.id&&Jg.fromAIV4CoreMessageContent(o.content)===Jg.fromAIV4CoreMessageContent(s.content);let c=_g.isMastraDBMessage(e)&&e,l=_g.isMastraDBMessage(t)&&t;if(c&&!l)return!1;if(c&&l)return c.id===l.id&&Jg.fromDBParts(c.content.parts)===Jg.fromDBParts(l.content.parts);let u=_g.isAIV5UIMessage(e)&&e,d=_g.isAIV5UIMessage(t)&&t;if(u&&!d)return!1;if(u&&d)return Jg.fromAIV5Parts(e.parts)===Jg.fromAIV5Parts(t.parts);let f=_g.isAIV5CoreMessage(e)&&e,p=_g.isAIV5CoreMessage(t)&&t;return f&&!p?!1:f&&p?Jg.fromAIV5ModelMessageContent(f.content)===Jg.fromAIV5ModelMessageContent(p.content):!0}function Qje(e){return qje(e).map(e=>e.type===`text`?{...e,text:Yg(typeof e.text==`string`?e.text:``).trim()}:e)}function $je(e,t){if(e.id!==t.id)return!1;let n=Jg.fromDBParts(Qje(t.content.parts)),[r]=Yje([e]);return[e,r].some(e=>e!==void 0&&Jg.fromDBParts(Qje(e.content.parts))===n)}function eMe(e){return e.createdAt??=Date.now(),e}function Xg(e,t){return t===`memory`||!Array.isArray(e.content.parts)||(e.content.parts=e.content.parts.map(e=>eMe(e))),e}function tMe(e,t,n){n===void 0?(e.updatedAt===void 0||JSON.stringify(t)!==JSON.stringify(e.toolInvocation))&&(e.updatedAt=Date.now()):e.updatedAt=n}function nMe(e,t,n){if(t!==`memory`&&`threadId`in e&&e.threadId&&n.memoryInfo&&e.threadId!==n.memoryInfo.threadId)throw Error(`Received input message with wrong threadId. Input ${e.threadId}, expected ${n.memoryInfo.threadId}`);if(t!==`memory`&&`resourceId`in e&&e.resourceId&&n.memoryInfo?.resourceId&&e.resourceId!==n.memoryInfo.resourceId)throw Error(`Received input message with wrong resourceId. Input ${e.resourceId}, expected ${n.memoryInfo.resourceId}`);if(_g.isMastraMessageV1(e))return Xg(rMe(e,t,n),t);if(_g.isMastraDBMessage(e))return Xg(iMe(e,n,t),t);if(_g.isAIV4CoreMessage(e))return Xg(Sg.fromCoreMessage(e,n,t),t);if(_g.isAIV4UIMessage(e))return Xg(Sg.fromUIMessage(e,n,t),t);let r=`id`in e&&typeof e.id==`string`?e.id:n.newMessageId();if(_g.isAIV6CoreMessage(e)){let i=Wg.fromModelMessage(e,t,n),a=`metadata`in e&&e.metadata&&typeof e.metadata==`object`&&`createdAt`in e.metadata?e.metadata.createdAt:void 0;return{...i,id:r,createdAt:n.generateCreatedAt(t,a),threadId:n.memoryInfo?.threadId,resourceId:n.memoryInfo?.resourceId}}if(_g.isAIV6UIMessage(e)){let i=Wg.fromUIMessage(e),a=`createdAt`in e?e.createdAt:void 0;return{...i,id:r,createdAt:n.generateCreatedAt(t,a),threadId:n.memoryInfo?.threadId,resourceId:n.memoryInfo?.resourceId}}if(_g.isAIV5CoreMessage(e)){let i=zg.fromModelMessage(e,t,n),a=`metadata`in e&&e.metadata&&typeof e.metadata==`object`&&`createdAt`in e.metadata?e.metadata.createdAt:void 0;return Xg({...i,id:r,createdAt:n.generateCreatedAt(t,a),threadId:n.memoryInfo?.threadId,resourceId:n.memoryInfo?.resourceId},t)}if(_g.isAIV5UIMessage(e)){let i=zg.fromUIMessage(e),a=`createdAt`in e?e.createdAt:void 0;return Xg({...i,id:r,createdAt:n.generateCreatedAt(t,a),threadId:n.memoryInfo?.threadId,resourceId:n.memoryInfo?.resourceId},t)}throw Error(`Found unhandled message ${JSON.stringify(e)}`)}function rMe(e,t,n){let r=Sg.fromCoreMessage({content:e.content,role:e.role},n,t);return{id:e.id,role:r.role,createdAt:n.generateCreatedAt(t,e.createdAt),threadId:e.threadId,resourceId:e.resourceId,content:r.content}}function iMe(e,t,n){return e.content.parts=Array.isArray(e.content.parts)?e.content.parts.filter(e=>typeof e==`object`&&!!e):[],e.id||=t.newMessageId(),e.createdAt===void 0||e.createdAt===null?e.createdAt=t.generateCreatedAt(n):e.createdAt instanceof Date||(e.createdAt=new Date(e.createdAt)),e.content.toolInvocations&&e.content.parts&&(e.content.toolInvocations=e.content.toolInvocations.map(t=>{if(!t.args||Object.keys(t.args).length===0){let n=e.content.parts.find(e=>e.type===`tool-invocation`&&e.toolInvocation&&e.toolInvocation.toolCallId===t.toolCallId&&e.toolInvocation.args&&Object.keys(e.toolInvocation.args).length>0);if(n&&n.type===`tool-invocation`)return{...t,args:n.toolInvocation.args}}return t})),!e.threadId&&t.memoryInfo?.threadId&&(e.threadId=t.memoryInfo.threadId),!e.resourceId&&t.memoryInfo?.resourceId&&(e.resourceId=t.memoryInfo.resourceId),e}function aMe(e){return e.type.startsWith(`source-`)}function oMe(e){let t=[];for(let n of e){if(n.type!==`text`){t.push(n);continue}let e=n,r=Bke(e.providerMetadata);if(!r){t.push(n);continue}let i=!1;for(let n=t.length-1;n>=0;n--){let a=t[n];if(a.type===`text`){let o=a;Bke(o.providerMetadata)===r&&(t[n]={...o,text:o.text+e.text},i=!0);break}if(!aMe(a))break}i||t.push(n)}return t}function sMe(e){if(ebe(e)!==`tool_search`||!e.providerExecuted)return!1;let t=`callProviderMetadata`in e?e.callProviderMetadata:void 0,n=zke(t);if(n&&(e.state!==`output-available`&&e.state!==`output-error`||Wke(t,n.provider)))return!1;let r=e.input;return!(r&&typeof r==`object`&&typeof r.call_id==`string`)}function cMe(e){return e.map(e=>{if(typeof e.content==`string`)return e;let t=!1,n=e.content.map(e=>{if(e.type!==`tool-call`&&e.type!==`tool-result`)return e;let n=e.providerOptions;if(!n)return e;let r,i=new Set;for(let t of vg){let a=n[t];if(!a)continue;let o=a[yg];if(typeof o!=`string`)continue;let{[yg]:s,...c}=a;i.add(t),r={...r??n,[t]:e.type===`tool-result`?{...c,itemId:o}:c}}if(!r)return e;if(e.type===`tool-result`)for(let e of vg){if(i.has(e))continue;let t=r[e];if(typeof t?.itemId!=`string`)continue;let{itemId:n,...a}=t;r={...r,[e]:a}}return t=!0,{...e,providerOptions:r}});return t?{...e,content:n}:e})}function lMe(e){return e.map(e=>{if(e.parts.length===0)return!1;let t=e.parts.filter(e=>e.type===`error`?!1:e.type!==`tool-invocation`||e.toolInvocation.state!==`call`&&e.toolInvocation.state!==`partial-call`);if(!t.length)return!1;let n={...e,parts:t};return`toolInvocations`in e&&e.toolInvocations&&(n.toolInvocations=e.toolInvocations.filter(e=>e.state===`result`)),n}).filter(e=>!!e)}function uMe(e,t=`response`){let n=-1;for(let t=e.length-1;t>=0;t--)if(e[t].role===`user`){n=t;break}let r=(e,n)=>e.parts.filter(r=>typeof r.type==`string`&&r.type.startsWith(`data-`)||r.type===`error`||r.type===`text`&&(!(`text`in r)||r.text===``||r.text?.trim()===``)&&(e.role===`user`||e.parts.some(e=>e.type!==`text`||`text`in e&&e.text!==``&&e.text?.trim()!==``))?!1:ch(r)?t===`response`?r.state!==`input-streaming`:sMe(r)?!1:r.state===`output-available`||r.state===`output-error`?!0:r.state===`input-available`?r.providerExecuted?n:t===`prompt-with-suspended`:!1:!0),i=-1;if(n!==e.length-1)for(let t=e.length-1;t>n;t--){let n=e[t];if(n.role===`assistant`&&n.parts.length!==0&&r(n,!0).length>0){i=t;break}}return e.map((e,t)=>{if(e.parts.length===0)return!1;let n=e.role===`assistant`&&t===i,a=r(e,n);if(!a.length)return!1;let o=oMe(a);return{...e,parts:o.map(e=>ch(e)&&e.state===`output-available`?{...e,output:Lke(e.output,{unwrapContent:!1}).output}:e)}}).filter(e=>!!e)}function dMe(e){for(let t of e)if(t.role===`assistant`)for(let[e,n]of t.parts.entries()){if(!ch(n))continue;let r=t.parts.at(e+1);r&&r.type!==`step-start`&&!ch(r)&&t.parts.splice(e+1,0,{type:`step-start`}),r&&ch(r)&&!n.providerExecuted&&r.providerExecuted&&(r.state===`output-available`||r.state===`output-error`)&&t.parts.splice(e+1,0,{type:`step-start`})}return e}function Zg(e){let t=lMe(e),n=new Map,r=0,i=LOe(t.map(e=>{if(e.role!==`user`)return e;let t=r++;if(!e.experimental_attachments?.length)return e;let i=e.experimental_attachments.filter(e=>gm(e.url,e.contentType).type===`providerFileId`);if(!i.length)return e;n.set(t,i);let a=e.experimental_attachments.filter(e=>!i.includes(e));return{...e,experimental_attachments:a.length?a:void 0}}));if(!n.size)return i;let a=0;return i.map(e=>{if(e.role!==`user`)return e;let t=n.get(a++);if(!t)return e;let r=t.map(e=>({type:`file`,data:e.url,mimeType:e.contentType||`application/octet-stream`})),i=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content;return{...e,content:[...i,...r]}})}function fMe(e){if(!e||typeof e!=`object`)return;let t=e.content;if(!Array.isArray(t)||!t.some(e=>{if(!e||typeof e!=`object`)return!1;let t=e;return(t.type===`image`||t.type===`audio`)&&typeof t.data==`string`}))return;let n=t.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;switch(t.type){case`text`:return{type:`text`,text:String(t.text??``)};case`image`:return typeof t.data==`string`?{type:`media`,data:t.data,mediaType:String(t.mimeType??`image/png`)}:{type:`text`,text:JSON.stringify(t)};case`audio`:return typeof t.data==`string`?{type:`media`,data:t.data,mediaType:String(t.mimeType??`audio/wav`)}:{type:`text`,text:JSON.stringify(t)};default:return{type:`text`,text:JSON.stringify(t)}}}).filter(Boolean);return n.length>0?{type:`content`,value:n}:void 0}function pMe(e){let t=new Map;for(let n of e)if(n.content?.format===2&&n.content.parts)for(let e of n.content.parts){if(e.type!==`tool-invocation`||e.toolInvocation?.state!==`result`)continue;let n=e.providerMetadata?.mastra;n&&typeof n==`object`&&`modelOutput`in n||t.set(e.toolInvocation.toolCallId,e.toolInvocation.result)}return t}function mMe(e,t){if(!e||typeof e!=`object`)return!1;let n=e;return n.type===`json`?n.value===t||Eke(n.value,t):!1}function hMe(e,t){let n=pMe(t);return n.size===0?e:e.map(e=>{if(e.role!==`tool`||!Array.isArray(e.content))return e;let t=!1,r=e.content.map(e=>{if(e.type!==`tool-result`||!n.has(e.toolCallId)||e.output?.type!==`json`)return e;let r=n.get(e.toolCallId),i;try{if(i=fMe(r),!i||!mMe(e.output,r))return e}catch{return e}return t=!0,{...e,output:i}});return t?{...e,content:r}:e})}function gMe(e){let t=new Map;if(e?.content?.format!==2||!e.content.parts)return t;for(let n of e.content.parts)n.type===`tool-invocation`&&n.toolInvocation?.state===`output-error`&&n.providerExecuted&&n.toolInvocation.result!==void 0&&t.set(n.toolInvocation.toolCallId,n.toolInvocation.result);return t}function _Me(e,t){let n=gMe(t);return n.size===0?e:e.map(e=>{if(e.role!==`assistant`||!Array.isArray(e.content))return e;let t=!1,r=e.content.map(e=>{if(e.type!==`tool-result`||e.output?.type!==`error-json`||!n.has(e.toolCallId))return e;let r=n.get(e.toolCallId);return typeof r==`string`?e:(t=!0,{...e,output:{type:`error-json`,value:r??null}})});return t?{...e,content:r}:e})}function vMe(e,t){let n=[];for(let e of t)if(e.role===`assistant`)for(let t of e.parts)t.type===`file`&&n.push(t.providerMetadata??void 0);if(n.length===0||n.every(e=>e==null))return e;let r=0;return e.map(e=>{if(e.role!==`assistant`||typeof e.content==`string`)return e;let t=!1,i=e.content.map(e=>{if(e.type!==`file`||r>=n.length)return e;let i=n[r++];return e.providerOptions||!i?e:(t=!0,{...e,providerOptions:i})});return t?{...e,content:i}:e})}var yMe=[`signature`,`redactedData`,`itemId`,`reasoningEncryptedContent`,`thoughtSignature`];function bMe(e){return Object.values(e??{}).some(e=>!!e&&typeof e==`object`&&yMe.some(t=>t in e))}function xMe(e){return e.role!==`assistant`||!Array.isArray(e.content)||e.content.length===0?!1:e.content.every(e=>e.type===`reasoning`&&!bMe(e.providerOptions))}function Qg(e,t,n=`response`){let r=dMe(uMe(e,n)),i=[],a=new Map(t.map(e=>[e.id,e]));for(let e of r){let t=_Me(ibe([e]),a.get(e.id));if(t.length===0)continue;let r=e.metadata&&typeof e.metadata==`object`&&`providerMetadata`in e.metadata?e.metadata.providerMetadata:void 0;if(r){let n=-1;for(let r=t.length-1;r>=0;r--)if(t[r]?.role===e.role){n=r;break}n!==-1&&(t[n]={...t[n],providerOptions:r})}for(let e of t)n!==`response`&&xMe(e)||i.push(e)}let o=Jke(hMe(vMe(cMe(i),r),t),t);switch(n){case`prompt`:return Xke(o);case`prompt-with-suspended`:return Zke(o);default:return o}}function SMe(e,t,n,r){return Qg(e.map(e=>Sg.fromCoreMessage(e,n,t)).map(e=>zg.toUIMessage(e)),r)}function CMe(e){if(typeof e==`string`)return{role:`system`,content:e};if(_g.isAIV6CoreMessage(e)){let t=Wg.fromModelMessage(e,`system`);return Sg.systemToV4Core(t)}if(_g.isAIV5CoreMessage(e)){let t=zg.fromModelMessage(e,`system`);return Sg.systemToV4Core(t)}return _g.isMastraDBMessage(e)?Sg.systemToV4Core(e):e}var wMe=class e{static extractStepContent(t,n,r,i){let a=t.flatMap(e=>e.parts),o=[];return a.forEach((e,t)=>{e.type===`step-start`&&o.push(t)}),n===-1?e.extractLastStep(a,o,r,i):n===1?e.extractFirstStep(a,o,r):e.extractMiddleStep(a,o,n,r)}static extractLastStep(t,n,r,i){let a=t.filter(e=>e.type?.startsWith(`tool-`)),o=n.length>0;if(!o&&a.length>0){let n=a[a.length-1];if(!n)return[];let o=t.indexOf(n),s=new Set(i??[]),c=s.size?a.findIndex(e=>s.has(e.toolCallId??``)):-1,l=a[(c===-1?a.length-1:c)-1],u=(l?t.indexOf(l):-1)+1,d=t.slice(u,o+1);return e.convertPartsToContent(d,`last-step`,r)}if(n.length+1===1&&!o)return e.convertPartsToContent(t,`last-step`,r);let s=n[n.length-1];if(s===void 0)return[];let c=t.slice(s+1);return c.length===0?[]:e.convertPartsToContent(c,`last-step`,r)}static extractFirstStep(t,n,r){let i=n[0]??t.length;if(i===0)return[];let a=t.slice(0,i);return e.convertPartsToContent(a,`step-1`,r)}static extractMiddleStep(t,n,r,i){let a=r-2;if(a<0||a>=n.length)return[];let o=(n[a]??0)+1,s=n[a+1]??t.length;if(o>=s)return[];let c=t.slice(o,s);return e.convertPartsToContent(c,`step-${r}`,i)}static convertPartsToContent(e,t,n){return ibe(uMe([{id:t,role:`assistant`,parts:e}])).flatMap(n)}static convertToStepContent(e,t,n){let r=e||n();return r?typeof r.content==`string`?[{type:`text`,text:r.content}]:r.content.map(e=>e.type===`tool-result`?{type:`tool-result`,input:bg(t,e.toolCallId),output:e.output,toolCallId:e.toolCallId,toolName:e.toolName}:e.type===`file`?{type:`file`,file:new jke({data:typeof e.data==`string`?mm(e.data).base64Content:e.data instanceof URL?e.data.toString():pm(e.data),mediaType:e.mediaType})}:e.type===`image`?{type:`file`,file:new jke({data:typeof e.image==`string`?mm(e.image).base64Content:e.image instanceof URL?e.image.toString():pm(e.image),mediaType:e.mediaType||`unknown`})}:{...e}):[]}},$g=class e{static isSealed(e){return(e.content?.metadata)?.mastra?.sealed===!0}static shouldMerge(t,n,r,i,a=!1){if(!t||e.isSealed(t)||t.id!==n.id&&(t.content?.metadata)?.mastra?.responseBoundary||n.content.metadata?.completionResult||t.content.metadata?.completionResult||n.content.metadata?.isTaskCompleteResult||t.content.metadata?.isTaskCompleteResult)return!1;let o=t.content?.parts??[];return o.length>0&&o.every(e=>e.type.startsWith(`data-`))&&t.id!==n.id?!1:t.role===`assistant`&&n.role===`assistant`&&t.threadId===n.threadId&&r!==`memory`&&(!a||!i)}static merge(t,n){n.content.metadata&&(t.content.metadata={...t.content.metadata??{},...n.content.metadata});let r=new Map,i=new Map;for(let[e,a]of n.content.parts.entries())if(a.type===`tool-invocation`){if(!a.toolInvocation)continue;let n=[...t.content.parts].reverse().find(e=>e.type===`tool-invocation`&&e.toolInvocation?.toolCallId===a.toolInvocation.toolCallId);if(n&&n.type===`tool-invocation`){let i=n.toolInvocation;if(a.toolInvocation.state===`result`){n.toolInvocation={...n.toolInvocation,step:a.toolInvocation.step,state:`result`,result:a.toolInvocation.result,args:{...n.toolInvocation.args,...a.toolInvocation.args}},tMe(n,i,a.updatedAt),a.providerMetadata&&(n.providerMetadata={...n.providerMetadata,...a.providerMetadata}),t.content.toolInvocations||(t.content.toolInvocations=[]);let e=t.content.toolInvocations.findIndex(e=>e.toolCallId===n.toolInvocation.toolCallId);e===-1?t.content.toolInvocations.push(n.toolInvocation):t.content.toolInvocations[e]=n.toolInvocation}else(a.toolInvocation.state===`approval-requested`||a.toolInvocation.state===`approval-responded`||a.toolInvocation.state===`output-denied`||a.toolInvocation.state===`output-error`)&&(n.toolInvocation={...n.toolInvocation,state:a.toolInvocation.state,approval:a.toolInvocation.approval,errorText:a.toolInvocation.errorText,...a.toolInvocation.state===`output-error`&&a.toolInvocation.result!==void 0?{result:a.toolInvocation.result}:{},rawInput:a.toolInvocation.rawInput,args:{...n.toolInvocation.args,...a.toolInvocation.args}},tMe(n,i,a.updatedAt),a.providerMetadata&&(n.providerMetadata={...n.providerMetadata,...a.providerMetadata}),`providerExecuted`in a&&a.providerExecuted!==void 0&&(n.providerExecuted=a.providerExecuted),`title`in a&&a.title!==void 0&&(n.title=a.title),`preliminary`in a&&a.preliminary!==void 0&&(n.preliminary=a.preliminary));let o=t.content.parts.findIndex(e=>e===n);r.set(e,o)}else i.set(e,a)}else i.set(e,a);e.addPartsToMessage({latestMessage:t,incomingMessage:n,anchorMap:r,partsToAdd:i}),!t.content.content&&n.content.content&&(t.content.content=n.content.content),t.content.content&&n.content.content&&t.content.content!==n.content.content&&(t.content.content=n.content.content)}static addPartsToMessage({latestMessage:t,incomingMessage:n,anchorMap:r,partsToAdd:i}){let a=-1,o=0,s=e.createMergeIndex(t,n),c;for(let l=0;l<n.content.parts.length;++l){let u=n.content.parts[l];if(!u)continue;let d=s.keyOf(u),f=i.get(l);if(d&&f){if(r.size>0){if(r.has(l))continue;let i=[...r.keys()].filter(e=>e<l).pop()??-1,f=[...r.keys()].find(e=>e>l)??-1,p=i===-1?0:r.get(i),m=i===-1?l:l-i;i!==a&&(o=0,a=i);let h=p+m+o,g=f===-1?t.content.parts.length:r.get(f);if(h<0||h>g)continue;if(!c||c.leftAnchor!==i){let e=t.content.parts.slice(h,g),n=new Map;for(let t of e){let e=s.keyOf(t);n.set(e,(n.get(e)??0)+1)}c={leftAnchor:i,parts:e,start:0,counts:n}}for(;c.parts.length-c.start>g-h;){let e=s.keyOf(c.parts[c.start++]);c.counts.set(e,c.counts.get(e)-1)}if(!c.counts.get(d)){let i=e.pushNewPart({latestMessage:t,newMessage:n,part:u,insertAt:h,index:s});if(i===0)continue;o+=i-1;for(let[e,t]of r.entries())t>=h&&r.set(e,t+i)}}else e.pushNewPart({latestMessage:t,newMessage:n,part:u,index:s})}}}static createMergeIndex(e,t){let n=new Map,r=e=>Jg.fromDBParts([e]),i=e=>e.type.startsWith(`data-`)&&`id`in e&&typeof e.id==`string`?e.id:void 0,a=(e,t)=>{let a=new Set,o=new Map;for(let e of t){if(!e.type.startsWith(`data-`))continue;let t=r(e),n=i(e);n===void 0?o.set(t,(o.get(t)??0)+1):a.add(`${t}|id:${JSON.stringify(n)}`)}for(let t of[...e].reverse()){if(n.has(t))continue;let e=r(t),s=i(t),c=o.get(e)??0,l=s===void 0?void 0:`${e}|id:${JSON.stringify(s)}`;l!==void 0&&!a.has(l)&&c>0?(o.set(e,c-1),n.set(t,e)):n.set(t,l??e)}};a(e.content.parts,t.content.parts),a(t.content.parts,e.content.parts);let o=e=>{let t=n.get(e);return t===void 0&&(t=r(e),n.set(e,t)),t},s=e=>{let t=new Map;for(let n of e){let e=o(n);t.set(e,(t.get(e)??0)+1)}return t},c=t.content.parts,l=new Map;c.forEach((e,t)=>{l.has(e)||l.set(e,t)});let u=c.findIndex(e=>e.type!==`step-start`);return{keyOf:o,latestCounts:s(e.content.parts),incomingCounts:s(c),incomingIndex:l,firstIncomingNonStepStart:u===-1?c.length:u}}static pushNewPart({latestMessage:e,newMessage:t,part:n,insertAt:r,index:i}){let a=i.keyOf(n),o=i.latestCounts.get(a)??0;if(o<(i.incomingCounts.get(a)??0)){let s=i.incomingIndex.get(n)??-1,c=s>0&&t.content.parts[s-1]?.type===`step-start`,l=s<=i.firstIncomingNonStepStart,u=e.role===`assistant`&&(n.type===`text`&&!c||n.type===`tool-invocation`&&l)&&e.content.parts.length>0&&e.content.parts.at(-1)?.type===`tool-invocation`,d;if(u){let t=e.content.parts.findLast(e=>e.type===`step-start`);d=t?.model?eMe({type:`step-start`,model:t.model}):{type:`step-start`};let n=i.keyOf(d);i.latestCounts.set(n,(i.latestCounts.get(n)??0)+1)}return i.latestCounts.set(a,o+1),typeof r==`number`?d?(e.content.parts.splice(r,0,d),e.content.parts.splice(r+1,0,n)):e.content.parts.splice(r,0,n):(d&&e.content.parts.push(d),e.content.parts.push(n)),d?2:1}return 0}};function TMe(e,t){let n,r=e.type;switch(r){case`image`:n=e.image;break;case`file`:n=e.data;break;default:throw Error(`Unsupported part type: ${r}`)}let{data:i,mediaType:a}=kke(n),o=a??e.mediaType,s=i;if(s instanceof URL&&t){let e=t[s.toString()];e&&(s=e.data,o??=e.mediaType)}switch(r){case`image`:return(s instanceof Uint8Array||typeof s==`string`)&&(o=Dpe({data:s,signatures:wpe})??o),{type:`file`,mediaType:o??`image/*`,filename:void 0,data:s,providerOptions:e.providerOptions};case`file`:if(o==null)throw Error(`Media type is missing for file part`);return{type:`file`,mediaType:o,filename:e.filename,data:s,providerOptions:e.providerOptions}}}function EMe(e){let t=[];for(let n of e){let e=gm(n.url,n.contentType);if(e.type===`providerFileId`){t.push({type:`file`,data:n.url,mimeType:n.contentType||`application/octet-stream`});continue}let r=n.url;e.type===`raw`&&(r=Ope(n.url,n.contentType||`application/octet-stream`));let i;try{i=new URL(r)}catch{throw Error(`Invalid URL: ${n.url}`)}switch(i.protocol){case`http:`:case`https:`:case`gs:`:case`s3:`:if(n.contentType?.startsWith(`image/`))t.push({type:`image`,image:i.toString(),mimeType:n.contentType});else{if(!n.contentType)throw Error(`If the attachment is not an image, it must specify a content type`);t.push({type:`file`,data:i.toString(),mimeType:n.contentType})}break;case`data:`:if(n.contentType?.startsWith(`image/`))t.push({type:`image`,image:r,mimeType:n.contentType});else if(n.contentType?.startsWith(`text/`))t.push({type:`file`,data:r,mimeType:n.contentType});else{if(!n.contentType)throw Error(`If the attachment is not an image or text, it must specify a content type`);t.push({type:`file`,data:r,mimeType:n.contentType})}break;default:throw Error(`Unsupported URL protocol: ${i.protocol}`)}}return t}var DMe=e=>{let t=new Map,n=/__split-\d+$/;return r=>{let i=e.at(-1);if(r.role===i?.role&&Array.isArray(i.content)&&Array.isArray(r.content)&&(r.role!==`assistant`||r.role===`assistant`&&r.content.at(-1)?.type!==`tool-call`))for(let e of r.content)i.content.push(e);else{let i=r.id;if(n.test(i)){e.push(r);return}let a=t.get(i)||0;a>0&&(r.id=`${i}__split-${a}`),t.set(i,a+1),e.push(r)}}};function e_(e){let t=[],n=DMe(t);for(let t=0;t<e.length;t++){let r=e[t],i=t===e.length-1;if(!r?.content)continue;let{content:a,experimental_attachments:o=[],parts:s}=r.content,{role:c}=r,l={id:r.id,createdAt:r.createdAt,resourceId:r.resourceId,threadId:r.threadId},u=[...o],d=[];for(let e of s)if(e.type===`file`){let{mediaType:t,data:n}=_m(e);u.push({url:n,contentType:t??`application/octet-stream`})}else d.push(e);switch(c){case`user`:if(d==null){let e=u?[{type:`text`,text:a||``},...EMe(u)]:{type:`text`,text:a||``};n({role:`user`,...l,type:`text`,content:e})}else{let e=r.content.parts.filter(e=>e.type===`text`).map(e=>({type:`text`,text:e.text})),t=u?[...e,...EMe(u)]:e;n({role:`user`,...l,type:`text`,content:Array.isArray(t)&&t.length===1&&t[0]?.type===`text`&&a!==void 0?a:t})}break;case`assistant`:{if(r.content.parts!=null){let e=0,t=!1,i=[];function a(){let r=[];for(let e of i)switch(e.type){case`file`:case`text`:r.push(e);break;case`reasoning`:for(let t of e.details)switch(t.type){case`text`:r.push({type:`reasoning`,text:t.text,signature:t.signature});break;case`redacted`:r.push({type:`redacted-reasoning`,data:t.data})}break;case`tool-invocation`:e.toolInvocation.toolName!==`updateWorkingMemory`&&r.push({type:`tool-call`,toolCallId:e.toolInvocation.toolCallId,toolName:e.toolInvocation.toolName,args:e.toolInvocation.args})}n({role:`assistant`,...l,type:r.some(e=>e.type===`tool-call`)?`tool-call`:`text`,content:typeof r!=`string`&&Array.isArray(r)&&r.length===1&&r[0]?.type===`text`?r[0].text:r});let a=i.filter(e=>`type`in e&&e.type===`tool-invocation`).map(e=>e.toolInvocation).filter(e=>e.toolName!==`updateWorkingMemory`).filter(e=>e.state===`result`&&`result`in e);a.length>0&&n({role:`tool`,...l,type:`tool-result`,content:a.map(e=>{let{toolCallId:t,toolName:n,result:r}=e;return{type:`tool-result`,toolCallId:t,toolName:n,result:r}})}),i=[],t=!1,e++}for(let n of r.content.parts)switch(n.type){case`text`:t&&a(),i.push(n);break;case`file`:case`reasoning`:i.push(n);break;case`tool-invocation`:(i.some(e=>e.type===`text`||e.type===`file`||e.type===`reasoning`)||(n.toolInvocation.step??0)!==e)&&a(),i.push(n),t=!0}a();let o=r.content.toolInvocations;if(o&&o.length>0){let e=new Set;for(let t of r.content.parts)t.type===`tool-invocation`&&t.toolInvocation.toolCallId&&e.add(t.toolInvocation.toolCallId);let t=o.filter(t=>!e.has(t.toolCallId)&&t.toolName!==`updateWorkingMemory`);if(t.length>0){let e=new Map;for(let n of t){let t=n.step??0;e.has(t)||e.set(t,[]),e.get(t).push(n)}let r=Array.from(e.keys()).sort((e,t)=>e-t);for(let t of r){let r=e.get(t);n({role:`assistant`,...l,type:`tool-call`,content:[...r.map(({toolCallId:e,toolName:t,args:n})=>({type:`tool-call`,toolCallId:e,toolName:t,args:n}))]});let i=r.filter(e=>e.state===`result`&&`result`in e);i.length>0&&n({role:`tool`,...l,type:`tool-result`,content:i.map(e=>{let{toolCallId:t,toolName:n,result:r}=e;return{type:`tool-result`,toolCallId:t,toolName:n,result:r}})})}}}break}let e=r.content.toolInvocations;if(e==null||e.length===0){n({role:`assistant`,...l,content:a||``,type:`text`});break}let t=e.reduce((e,t)=>Math.max(e,t.step??0),0);for(let r=0;r<=t;r++){let t=e.filter(e=>(e.step??0)===r&&e.toolName!==`updateWorkingMemory`);if(t.length===0)continue;n({role:`assistant`,...l,type:`tool-call`,content:[...i&&a&&r===0?[{type:`text`,text:a}]:[],...t.map(({toolCallId:e,toolName:t,args:n})=>({type:`tool-call`,toolCallId:e,toolName:t,args:n}))]});let o=t.filter(e=>e.state===`result`&&`result`in e);o.length>0&&n({role:`tool`,...l,type:`tool-result`,content:o.map(e=>{let{toolCallId:t,toolName:n,result:r}=e;return{type:`tool-result`,toolCallId:t,toolName:n,result:r}})})}a&&!i&&n({role:`assistant`,...l,type:`text`,content:a||``});break}}}return t}function OMe(e){if(e.protocol===`data:`){let t=e.pathname.indexOf(`,`);return`data:${t===-1?e.pathname:e.pathname.slice(0,t)},<${t===-1?0:e.pathname.length-t-1} chars>`}return`${e.origin}${e.pathname}`}var kMe=async({url:e,downloadRetries:t})=>{let n=e.toString(),r=OMe(e);try{let i=await Fke(n,{method:`GET`},e.protocol===`data:`?1:t,{shouldRetryResponse:e=>e.status>=500});if(!i.ok)throw new yn({id:`DOWNLOAD_ASSETS_FAILED`,text:`Failed to download asset: ${r}`,domain:gn.LLM,category:_n.USER,details:{url:n}});return{data:new Uint8Array(await i.arrayBuffer()),mediaType:i.headers.get(`content-type`)??void 0}}catch(e){throw new yn({id:`DOWNLOAD_ASSETS_FAILED`,text:`Failed to download asset: ${r}`,domain:gn.LLM,category:_n.USER,details:{url:n}},e)}};function AMe(e){let t=e.type===`image`?e.image:e.data;if(typeof t!=`string`)return t;try{return new URL(t)}catch{return t}}function jMe(e){let t=AMe(e);return t instanceof URL?t.toString():void 0}function MMe(e){return e instanceof yn&&e.id===`DOWNLOAD_ASSETS_FAILED`}async function NMe({messages:e,downloadConcurrency:t=10,downloadRetries:n=3,supportedUrls:r,cache:i,isUnavailable:a,onUnavailable:o}){let s=(await W(async()=>{let{default:e}=await import(`./p-map-D81h6UuU.js`);return{default:e}},[],import.meta.url)).default,c=(await s(e.filter(e=>e.role===`user`).map(e=>e.content).filter(e=>Array.isArray(e)).flat().filter(e=>e.type===`image`||e.type===`file`).map(e=>({mediaType:e.mediaType??(e.type===`image`?`image/*`:void 0),data:AMe(e)})).filter(e=>e.data instanceof URL).map(e=>({url:e.data,isUrlSupportedByModel:e.mediaType!=null&&Zfe({url:e.data.toString(),mediaType:e.mediaType,supportedUrls:r??{}})})),async e=>{let t=e.url.toString();if(e.isUrlSupportedByModel||a?.(t))return null;let r=i?.get(t);if(!r&&(r=kMe({url:e.url,downloadRetries:n}),i)){let e=r;i.set(t,e),e.catch(()=>{i.get(t)===e&&i.delete(t)})}try{return{url:t,...await r}}catch(e){if(!o||!MMe(e))throw e;return o(t,e),null}},{concurrency:t})).filter(e=>e?.data!=null).map(({url:e,data:t,mediaType:n})=>[e,{data:t,mediaType:n}]);return Object.fromEntries(c)}var t_=`unavailableAttachments`;function PMe(e){let t=e.content.metadata?.mastra;if(!t||typeof t!=`object`)return[];let n=t[t_];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function FMe(e,t){let n=e?.mastra??{},r=Array.isArray(n[t_])?n[t_]:[];return{...e,mastra:{...n,[t_]:[...new Set([...r,...t])]}}}function n_(e){if(e instanceof URL)return e.toString();if(!(typeof e!=`string`||e.startsWith(`data:`)))try{return new URL(e).toString()}catch{return}}function IMe(e){return`[Attachment unavailable: ${e}]`}function LMe(e){let t=new Set(PMe(e));if(e.role!==`user`||t.size===0)return e;let n=e=>{let n=n_(e);return n!==void 0&&t.has(n)},r=e=>({type:`text`,text:IMe(e)}),i=e.content.parts??[],a=e.content.experimental_attachments??[],o=new Set,s=i.map(e=>{if(e.type!==`file`)return e;let{mediaType:n,data:i}=_m(e),a=n_(i);return a===void 0||!t.has(a)?e:(o.add(a),r(e.filename||n||`file`))}),c=a.filter(e=>{let n=n_(e.url);return n!==void 0&&t.has(n)&&!o.has(n)}),l=a.filter(e=>n(e.url));if(o.size===0&&l.length===0)return e;let u=e.content.content,d=typeof u==`string`&&u&&!s.some(e=>e.type===`text`)?[{type:`text`,text:u}]:[];return{...e,content:{...e.content,parts:[...c.map(e=>r(e.name||e.contentType||`unknown`)),...d,...s],...l.length>0?{experimental_attachments:a.filter(e=>!n(e.url))}:{}}}}function RMe(e){let t=[];for(let n of e.content.parts??[]){if(n.type!==`file`)continue;let e=n_(_m(n).data);e&&t.push(e)}for(let n of e.content.experimental_attachments??[]){let e=n_(n.url);e&&t.push(e)}return t}function zMe(e){return{...e,createdAt:e.createdAt.toISOString()}}function BMe(e){return{...e,createdAt:new Date(e.createdAt)}}function VMe(e){return e.map(zMe)}function HMe(e){return e.map(BMe)}var UMe=class{memoryMessages=new Set;newUserMessages=new Set;newResponseMessages=new Set;userContextMessages=new Set;memoryMessagesPersisted=new Set;newUserMessagesPersisted=new Set;newResponseMessagesPersisted=new Set;userContextMessagesPersisted=new Set;addToSource(e,t){switch(t){case`memory`:this.memoryMessages.add(e),this.memoryMessagesPersisted.add(e);break;case`response`:this.memoryMessages.has(e)&&this.memoryMessages.delete(e),this.newResponseMessages.add(e),this.newResponseMessagesPersisted.add(e),this.newUserMessages.has(e)&&this.newUserMessages.delete(e);break;case`input`:case`user`:this.newUserMessages.add(e),this.newUserMessagesPersisted.add(e);break;case`context`:this.userContextMessages.add(e),this.userContextMessagesPersisted.add(e);break;default:throw Error(`Missing message source for message ${e}`)}}isMemoryMessage(e){return this.memoryMessages.has(e)}isUserMessage(e){return this.newUserMessages.has(e)}isResponseMessage(e){return this.newResponseMessages.has(e)}isContextMessage(e){return this.userContextMessages.has(e)}getMemoryMessages(){return this.memoryMessages}getUserMessages(){return this.newUserMessages}getResponseMessages(){return this.newResponseMessages}getContextMessages(){return this.userContextMessages}getMemoryMessagesPersisted(){return this.memoryMessagesPersisted}getUserMessagesPersisted(){return this.newUserMessagesPersisted}getResponseMessagesPersisted(){return this.newResponseMessagesPersisted}getContextMessagesPersisted(){return this.userContextMessagesPersisted}removeMessage(e){this.memoryMessages.delete(e),this.newUserMessages.delete(e),this.newResponseMessages.delete(e),this.userContextMessages.delete(e)}clearUserMessages(){this.newUserMessages.clear()}clearResponseMessages(){this.newResponseMessages.clear()}clearContextMessages(){this.userContextMessages.clear()}clearAll(){this.newUserMessages.clear(),this.newResponseMessages.clear(),this.userContextMessages.clear()}createSourceChecker(){let e={memory:new Set(Array.from(this.memoryMessages.values()).map(e=>e.id)),output:new Set(Array.from(this.newResponseMessages.values()).map(e=>e.id)),input:new Set(Array.from(this.newUserMessages.values()).map(e=>e.id)),context:new Set(Array.from(this.userContextMessages.values()).map(e=>e.id))};return{...e,getSource:t=>e.memory.has(t.id)?`memory`:e.input.has(t.id)?`input`:e.output.has(t.id)?`response`:e.context.has(t.id)?`context`:null}}isNewMessage(e){let t=typeof e==`string`?e:e.id;return typeof e!=`string`&&(this.newUserMessages.has(e)||this.newResponseMessages.has(e))?!0:Array.from(this.newUserMessages).some(e=>e.id===t)||Array.from(this.newResponseMessages).some(e=>e.id===t)}serializeSourceTracking(){let e=e=>Array.from(e).map(e=>e.id);return{memoryMessages:e(this.memoryMessages),newUserMessages:e(this.newUserMessages),newResponseMessages:e(this.newResponseMessages),userContextMessages:e(this.userContextMessages),memoryMessagesPersisted:e(this.memoryMessagesPersisted),newUserMessagesPersisted:e(this.newUserMessagesPersisted),newResponseMessagesPersisted:e(this.newResponseMessagesPersisted),userContextMessagesPersisted:e(this.userContextMessagesPersisted)}}deserializeSourceTracking(e,t){let n=e=>new Set(e.map(e=>t.find(t=>t.id===e)).filter(Boolean));this.memoryMessages=n(e.memoryMessages),this.newUserMessages=n(e.newUserMessages),this.newResponseMessages=n(e.newResponseMessages),this.userContextMessages=n(e.userContextMessages),this.memoryMessagesPersisted=n(e.memoryMessagesPersisted),this.newUserMessagesPersisted=n(e.newUserMessagesPersisted),this.newResponseMessagesPersisted=n(e.newResponseMessagesPersisted),this.userContextMessagesPersisted=n(e.userContextMessagesPersisted)}serializeAll(e){return{messages:VMe(e.messages),systemMessages:e.systemMessages,taggedSystemMessages:e.taggedSystemMessages,memoryInfo:e.memoryInfo,_agentNetworkAppend:e.agentNetworkAppend,...this.serializeSourceTracking()}}deserializeAll(e){let t=HMe(e.messages);return this.deserializeSourceTracking({memoryMessages:e.memoryMessages,newUserMessages:e.newUserMessages,newResponseMessages:e.newResponseMessages,userContextMessages:e.userContextMessages,memoryMessagesPersisted:e.memoryMessagesPersisted,newUserMessagesPersisted:e.newUserMessagesPersisted,newResponseMessagesPersisted:e.newResponseMessagesPersisted,userContextMessagesPersisted:e.userContextMessagesPersisted},t),{messages:t,systemMessages:e.systemMessages,taggedSystemMessages:e.taggedSystemMessages,memoryInfo:e.memoryInfo,agentNetworkAppend:e._agentNetworkAppend}}},r_={"partial-call":0,call:1,"approval-requested":2,"approval-responded":3,result:4,"output-error":4,"output-denied":4};function WMe(e){return r_[e]===r_.result}function GMe(e){return e===`approval-responded`||WMe(e)}function KMe(e,t){return!WMe(e)&&r_[t]>r_[e]}function qMe(e){return e.role===`system`&&e.parts.length>0&&e.parts.every(e=>e.type.startsWith(`data-`))}function JMe(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(!qMe(r)){t.push(r);continue}let i=t[t.length-1],a=e[n+1];i&&i.role===`assistant`?t[t.length-1]={...i,parts:[...i.parts,...r.parts]}:a&&a.role===`assistant`?e[n+1]={...a,parts:[...r.parts,...a.parts]}:t.push({...r,role:`assistant`})}return t}function YMe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function XMe(e,t){if(!e&&!t)return;let n={...e??{}};for(let[e,r]of Object.entries(t??{})){let t=n[e];n[e]=YMe(t)&&YMe(r)?{...t,...r}:r}return n}function ZMe(e,t){let n=new Map;for(let t of e.content.parts)t.type===`tool-invocation`&&n.set(t.toolInvocation.toolCallId,t);if(n.size===0)return t;let r=!1,i=t.content.parts.map(e=>{if(e.type!==`tool-invocation`)return e;let t=n.get(e.toolInvocation.toolCallId);if(!t||KMe(t.toolInvocation.state,e.toolInvocation.state))return e;let i=t.providerMetadata?.mastra?.backgroundTask,a=e.providerMetadata?.mastra?.backgroundTask;if(i?.status===`running`&&(a?.status===`completed`||a?.status===`failed`))return e;r=!0;let{toolCallId:o,toolName:s,args:c}=e.toolInvocation;return{type:`tool-invocation`,toolInvocation:{state:`call`,toolCallId:o,toolName:s,args:c}}});return r?{...t,content:{...t.content,parts:i}}:t}function QMe(e,t){let n=new Map;for(let t of e.content.parts)t.type===`tool-invocation`&&n.set(t.toolInvocation.toolCallId,t);let r=t.content.parts.flatMap(e=>{if(e.type!==`tool-invocation`)return[];let{state:t,toolCallId:r,result:i,errorText:a,approval:o}=e.toolInvocation,s=n.get(r);return!s||!GMe(t)||!KMe(s.toolInvocation.state,t)||s.providerExecuted&&t!==`approval-responded`?[]:[{type:`tool-invocation`,toolInvocation:{...s.toolInvocation,state:t,result:i,errorText:a,approval:o??s.toolInvocation.approval}}]});return{...t,content:{format:2,parts:r}}}function $Me(e,t,n,r){let i=e.indexOf(t);if(i!==-1)return i;let a=t.createdAt;if(a==null||r===void 0||r.messageId!==n)return-1;let o=e.flatMap((e,t)=>e.type===`step-start`&&e.createdAt!=null&&+e.createdAt==+a?[t]:[]);if(o.length!==1)return-1;let s=o[0],c=eNe(e,s),l=r.prefix;return c.length===l.length&&c.every((e,t)=>e[0]===l[t][0]&&e[1]===l[t][1])?s:-1}function eNe(e,t){let n=[];for(let r=0;r<t;r++){let t=e[r];t.type===`text`?n.push([t.type,t.text]):t.type===`tool-invocation`?n.push([t.type,t.toolInvocation?.toolCallId]):t.type===`reasoning`?n.push([t.type,t.reasoning]):n.push([t.type,void 0])}return n}var tNe=class e{messages=[];messageIndex;systemMessages=[];taggedSystemMessages={};memoryInfo=null;stateManager=new UMe;#e=new Map;#t=new Map;get memoryMessages(){return this.stateManager.getMemoryMessages()}get newUserMessages(){return this.stateManager.getUserMessages()}get newResponseMessages(){return this.stateManager.getResponseMessages()}get userContextMessages(){return this.stateManager.getContextMessages()}get memoryMessagesPersisted(){return this.stateManager.getMemoryMessagesPersisted()}get newUserMessagesPersisted(){return this.stateManager.getUserMessagesPersisted()}get newResponseMessagesPersisted(){return this.stateManager.getResponseMessagesPersisted()}get userContextMessagesPersisted(){return this.stateManager.getContextMessagesPersisted()}assetDownloads=new Map;unavailableAttachmentUpdates=new Map;generateMessageId;_agentNetworkAppend=!1;filterIncompleteToolCalls;logger;responseMessageSplits=new Map;toAIV5UIMessages(e,t){return JMe(e.map(e=>zg.toUIMessage(e,t)))}toAIV4UIMessages(e,t){return JMe(e.map(e=>Sg.toUIMessage(e,t)))}toAIV6UIMessages(e){return JMe(e.map(Wg.toUIMessage))}isRecording=!1;spanRecordings=new Map;recordedEvents=[];constructor({threadId:e,resourceId:t,generateMessageId:n,logger:r,filterIncompleteToolCalls:i,_agentNetworkAppend:a}={}){e&&(this.memoryInfo={threadId:e,resourceId:t}),this.generateMessageId=n,this.logger=r,this.filterIncompleteToolCalls=i??!0,this._agentNetworkAppend=a||!1}startRecording(e){e?this.spanRecordings.set(e,[]):(this.isRecording=!0,this.recordedEvents=[])}hasRecordedEvents(){return this.recordedEvents.length>0}getRecordedEvents(){return[...this.recordedEvents]}stopRecording(e){if(e){let t=this.spanRecordings.get(e)??[];return this.spanRecordings.delete(e),t}this.isRecording=!1;let t=this.getRecordedEvents();return this.recordedEvents=[],t}recordMutation(e){if(this.spanRecordings.size>0){let t;for(;t;){let n=this.spanRecordings.get(t);if(n){n.push(e);return}t=t.parent}}this.isRecording&&this.recordedEvents.push(e)}addSignal(e,t){let n=t?.source??`input`,r=e.metadata?.precedesMessageId,i=typeof r==`string`?this.getMessageById(r):void 0,a=i?new Date(i.createdAt.getTime()-1):this.generateCreatedAt(n,new Date),o=e.acceptedAt??e.createdAt,s={id:e.id,tagName:e.tagName,contents:e.contents,attributes:e.attributes,metadata:e.metadata,author:e.author,providerOptions:e.providerOptions,createdAt:a,acceptedAt:o},c=e.type===`state`?Spe({...s,type:e.type}):Spe({...s,type:e.type,transient:e.transient}),l=c.toDBMessage(this.memoryInfo??void 0);return c.type!==`state`&&c.transient&&this.removeMatchingTransientSignals(l),this.addOne(l,n),c}removeMatchingTransientSignals(e){let t=e.content.metadata?.signal,n=e=>JSON.stringify(e.map(e=>({...e,createdAt:void 0}))),r=n(e.content.parts);for(let i=this.messages.length-1;i>=0;i--){let a=this.messages[i];if(!epe(a))continue;let o=a.content.metadata?.signal,s=a.id===e.id,c=!!t&&!!o&&o.type===t.type&&o.tagName===t.tagName&&n(a.content.parts)===r;(s||c)&&(this.messages.splice(i,1),this.stateManager.removeMessage(a))}}add(e,t,n={}){if(t===`user`&&(t=`input`),!e)return this;let r=Array.isArray(e)?e:[e];this.recordMutation({type:`add`,source:t,count:r.length});for(let e of r){if(xpe(e)&&t===`input`){this.addSignal(e,{source:t});continue}let r=xpe(e)?e.toDBMessage(this.memoryInfo??void 0):typeof e==`string`?{role:`user`,content:e}:e;if(Array.isArray(r))for(let e of r)this.addOne(typeof e==`string`?{role:`user`,content:e}:e,t,n);else this.addOne(typeof r==`string`?{role:`user`,content:r}:r,t,n)}return this.moveLiveMessagesPastStoredTies(),this}serialize(){let e=this.stateManager.serializeAll({messages:this.messages,systemMessages:this.systemMessages,taggedSystemMessages:this.taggedSystemMessages,memoryInfo:this.memoryInfo,agentNetworkAppend:this._agentNetworkAppend}),t=this.#c(),n=this.#a();return{...e,...t?{lastStepBoundary:t}:{},...n.length>0?{prunedResponseMessageIds:n}:{},...this.#t.size>0?{embeddedMessages:Object.fromEntries(this.#t)}:{}}}getEmbeddedMessages(){return this.#t}serializeForSpan(){return{messages:this.all.aiV4.core().map(e=>({role:e.role,content:e.content})),systemMessages:[...this.systemMessages.map(e=>({role:e.role,content:e.content})),...Object.entries(this.taggedSystemMessages).flatMap(([e,t])=>t.map(t=>({role:t.role,content:t.content,tag:e})))]}}deserialize(e){let t=this.stateManager.deserializeAll(e);this.messages=t.messages,this.systemMessages=t.systemMessages,this.taggedSystemMessages=t.taggedSystemMessages,this.memoryInfo=t.memoryInfo,this._agentNetworkAppend=t.agentNetworkAppend,this.responseMessageSplits.clear();for(let e of this.messages)this.updateLastCreatedAt(e);this.#e=new Map((e.prunedResponseMessageIds??[]).map(e=>[e,void 0]));for(let[t,n]of Object.entries(e.embeddedMessages??{}))this.#t.set(t,n);if(this.#s=void 0,e.lastStepBoundary){let{messageId:t,partIndex:n}=e.lastStepBoundary,r=this.messages.find(e=>e.id===t)?.content.parts,i=r?.[n];r&&i?.type===`step-start`&&(this.#l(t,r,i),this.#s=i)}return this}clone(){return new e({generateMessageId:this.generateMessageId,logger:this.logger,filterIncompleteToolCalls:this.filterIncompleteToolCalls}).deserialize(this.serialize())}cloneForPersistence(){if(this.responseMessageSplits.size===0)return this;let e=this.clone();for(let[t,n]of this.responseMessageSplits)e.coalesceSplitResponseMessages(n,t);return e}get promptConversionMode(){return this.filterIncompleteToolCalls?`prompt`:`prompt-with-suspended`}get dropsIncompleteToolCalls(){return this.filterIncompleteToolCalls}getMessagesForModelPrompt(){return this.messages.flatMap(e=>e.role===`signal`?this.convertSignalForModelPrompt(e):[e])}convertSignalForModelPrompt(e){let t=Cpe(e).toLLMMessage(),n=e.createdAt;return[nMe({...t,id:e.id,metadata:{createdAt:n}},`input`,{memoryInfo:this.memoryInfo,newMessageId:()=>e.id,generateCreatedAt:(e,t)=>t instanceof Date?t:typeof t==`string`||typeof t==`number`?new Date(t):n,dbMessages:this.messages})]}makeMessageSourceChecker(){return this.stateManager.createSourceChecker()}getRememberedAndInputMessageIds(){return new Set([...this.memoryMessagesPersisted,...this.newUserMessagesPersisted].map(e=>e.id))}getLatestUserContent(){let e=this.all.core().filter(e=>e.role===`user`).at(-1)?.content;return e?Xje(e):null}get get(){return{all:this.all,remembered:this.remembered,input:this.input,response:this.response}}get getPersisted(){return{remembered:this.rememberedPersisted,input:this.inputPersisted,taggedSystemMessages:this.taggedSystemMessages,response:this.responsePersisted}}get clear(){return{all:{db:()=>{let e=[...this.messages];return this.messages=[],this.stateManager.clearAll(),e.length>0&&this.recordMutation({type:`clear`,count:e.length}),e}},input:{db:()=>{let e=Array.from(this.stateManager.getUserMessages());return this.messages=this.messages.filter(e=>!this.stateManager.isUserMessage(e)),this.stateManager.clearUserMessages(),e.length>0&&this.recordMutation({type:`clear`,source:`input`,count:e.length}),e}},response:{db:()=>{let e=Array.from(this.stateManager.getResponseMessages());return this.messages=this.messages.filter(e=>!this.stateManager.isResponseMessage(e)),this.stateManager.clearResponseMessages(),e.length>0&&this.recordMutation({type:`clear`,source:`response`,count:e.length}),e}}}}removeByIds(e,t){let n=new Set(e),r=[],i=this.newResponseMessagesPersisted;return this.messages=this.messages.filter(e=>!n.has(e.id)||(r.push(e),t?.pruned&&i.has(e)?this.#e.set(e.id,e):t?.pruned||this.#e.delete(e.id),this.stateManager.removeMessage(e),!1)),r.length>0&&this.recordMutation({type:`removeByIds`,ids:e,count:r.length}),r}splitResponseMessageAtPartOffset(e,t){let n=this.messages.findIndex(t=>t.id===e),r=this.messages[n],i=r?.content.parts;if(!r||!this.stateManager.isResponseMessage(r)||!i||t<=0||t>=i.length)return;let a=e=>{let t={...r.content,parts:e};if(typeof t.content==`string`&&(t.content=e.reduce((e,t)=>t.type===`text`?t.text:e,``)),Array.isArray(t.toolInvocations)){let n=new Set(e.flatMap(e=>e.type===`tool-invocation`&&e.toolInvocation?[e.toolInvocation.toolCallId]:[]));t.toolInvocations=t.toolInvocations.filter(e=>n.has(e.toolCallId))}return t},o=e,s=this.newMessageId(r.role),c={...r,id:s,content:a(i.slice(t))};r.content=a(i.slice(0,t)),this.messages.splice(n,1,r,c);let l=this.#e,u=this.serialize();for(let t of[`newResponseMessages`,`newResponseMessagesPersisted`])u[t]=u[t].flatMap(t=>t===e?[o,s]:[t]);this.deserialize(u);for(let[e,t]of this.#e)t===void 0&&this.#e.set(e,l.get(e));return this.responseMessageSplits.set(s,o),{earlierMessageId:o,currentMessageId:s}}coalesceSplitResponseMessages(e,t){this.responseMessageSplits.delete(t);let n=this.messages.findIndex(t=>t.id===e),r=this.messages.findIndex(e=>e.id===t),i=this.messages[n],a=this.messages[r];if(!i){a&&(a.id=e);return}if(!a)return;let o=[...i.content.parts??[],...a.content.parts??[]],s={...i.content,...a.content,parts:o};if((typeof i.content.content==`string`||typeof a.content.content==`string`)&&(s.content=o.reduce((e,t)=>t.type===`text`?t.text:e,``)),Array.isArray(i.content.toolInvocations)||Array.isArray(a.content.toolInvocations)){let e=[...i.content.toolInvocations??[],...a.content.toolInvocations??[]],t=new Set(o.flatMap(e=>e.type===`tool-invocation`&&e.toolInvocation?[e.toolInvocation.toolCallId]:[]));s.toolInvocations=e.filter((n,r)=>t.has(n.toolCallId)&&e.findIndex(e=>e.toolCallId===n.toolCallId)===r)}i.content=s,this.messages.splice(Math.max(n,r),1),this.messages.splice(Math.min(n,r),1,i),this.stateManager.removeMessage(a)}rollbackToStepBoundary(e,t){let n=this.messages.find(t=>t.id===e);if(!n)return!1;let r=n.content?.parts;if(!r)return this.removeByIds([e]),!0;let i=t?$Me(r,t,e,this.#o.get(t)):-1;return i===-1?(this.removeByIds([e]),!0):(this.#n(n,i),!0)}#n(e,t){let n=e.content.parts;if(n.splice(t),n.length===0)this.removeByIds([e.id]);else{if(Array.isArray(e.content.toolInvocations)){let t=new Set(n.flatMap(e=>e.type===`tool-invocation`&&e.toolInvocation?[e.toolInvocation.toolCallId]:[]));e.content.toolInvocations=e.content.toolInvocations.filter(e=>t.has(e.toolCallId))}if(typeof e.content.content==`string`){let t=``;for(let e of n)e.type===`text`&&(t=e.text);e.content.content=t}e.content.metadata&&delete e.content.metadata.structuredOutput,this.stateManager.isResponseMessage(e)||(this.stateManager.removeMessage(e),this.stateManager.addToSource(e,`response`))}}#r;#i;markStepCompleted(){this.#r=new Map(this.get.response.db().map(e=>[e.id,e.content.parts?.length??0])),this.#i=new Map(this.get.response.db().flatMap(e=>e.content.metadata?.structuredOutput===void 0?[]:[[e.id,e.content.metadata.structuredOutput]]))}cloneWithCompletedSteps(e=``){let t=this.clone(),n=()=>(t.add({role:`assistant`,content:[{type:`text`,text:e}]},`response`,{merge:!1}),t.get.response.db().at(-1).id),r=this.#r,i=t.get.response.db().flatMap(e=>(e.content.parts??[]).slice(r?.get(e.id)??0)),a=i.filter(e=>e.type===`tool-invocation`);if(a.length>0&&a.every(e=>WMe(e.toolInvocation.state))){let r=i.flatMap(e=>e.type===`text`?[e.text]:[]).join(``);return e.trim().length>0&&!r.includes(e.trim())?{turn:t,inFlightMessageId:n()}:{turn:t}}for(let e of t.get.response.db()){let n=r?.get(e.id);if(n===void 0)t.removeByIds([e.id]);else if((e.content.parts?.length??0)>n){e.content={...e.content,parts:[...e.content.parts],...e.content.metadata?{metadata:{...e.content.metadata}}:{}},t.#n(e,n);let r=this.#i?.get(e.id);r!==void 0&&(e.content.metadata={...e.content.metadata,structuredOutput:r})}}return e.trim().length>0?{turn:t,inFlightMessageId:n()}:{turn:t}}all={db:()=>this.messages,v1:()=>e_(this.all.db()),aiV5:{model:()=>{let e=this.getMessagesForModelPrompt();return Qg(this.toAIV5UIMessages(e,{transformToolPayloads:!1}),e)},ui:()=>this.toAIV5UIMessages(this.all.db()),prompt:()=>{let e=SMe([...this.systemMessages,...Object.values(this.taggedSystemMessages).flat()],`system`,this.createAdapterContext(),this.messages),t=this.getMessagesForModelPrompt(),n=Qg(this.toAIV5UIMessages(t,{transformToolPayloads:!1}),t,this.promptConversionMode);return[...e,...n]},llmPrompt:async(e={downloadConcurrency:10,downloadRetries:3})=>{let t=this.getMessagesForModelPrompt().map(LMe),n=Qg(this.toAIV5UIMessages(t,{transformToolPayloads:!1}),t,this.promptConversionMode),r=new Map;for(let e of this.messages)if(e.content?.format===2&&e.content.parts)for(let t of e.content.parts)t.type===`tool-invocation`&&t.toolInvocation?.state===`result`&&t.providerMetadata?.mastra&&typeof t.providerMetadata.mastra==`object`&&Object.hasOwn(t.providerMetadata.mastra,`modelOutput`)&&t.providerMetadata.mastra.modelOutput!=null&&r.set(t.toolInvocation.toolCallId,t.providerMetadata.mastra.modelOutput);if(r.size>0){for(let e of n)if(e.role===`tool`&&Array.isArray(e.content))for(let t=0;t<e.content.length;t++){let n=e.content[t];n.type===`tool-result`&&r.has(n.toolCallId)&&(e.content[t]={...n,output:r.get(n.toolCallId)})}}let i=SMe([...this.systemMessages,...Object.values(this.taggedSystemMessages).flat()],`system`,this.createAdapterContext(),this.messages),a=new Set,o=await NMe({messages:n,downloadConcurrency:e?.downloadConcurrency,downloadRetries:e?.downloadRetries,supportedUrls:e?.supportedUrls,cache:this.assetDownloads,isUnavailable:e=>e.startsWith(`data:`)&&!Wpe(e),onUnavailable:(t,n)=>{let r=t.startsWith(`data:`);if(!r&&!e?.skipUnavailableAttachments)throw n;a.add(t),r||this.recordUnavailableAttachment(t),this.logger?.warn(`Skipping an attachment that could not be downloaded: ${n.message}`)}}),s=[...i,...n];return n.some(e=>(e.role===`user`||e.role===`assistant`)&&typeof e.content!=`string`&&e.content.some(e=>e.type===`image`||e.type===`file`))&&(s=s.map(e=>{if(e.role===`user`)return typeof e.content==`string`?{role:`user`,content:[{type:`text`,text:e.content}],providerOptions:e.providerOptions}:{role:`user`,content:e.content.map(e=>{if(e.type===`image`||e.type===`file`){let t=jMe(e),n=e.type===`image`?e.image:e.data,r=typeof n==`string`&&!Wpe(n,e.mediaType);if(r){let t=n.startsWith(`data:`)?`${n.slice(0,n.indexOf(`,`)+1)}<${n.length} chars>`:`${e.mediaType??e.type} <${n.length} chars>`;this.logger?.warn(`Skipping an attachment that is not a URL or valid file content: ${t}`)}return r||t&&a.has(t)?{type:`text`,text:IMe(e.type===`file`&&e.filename||e.mediaType||e.type)}:TMe(e,o)}return e}).filter(e=>e.type!==`text`||e.text!==``),providerOptions:e.providerOptions};if(e.role===`assistant`&&typeof e.content!=`string`){let t=e.content.map(e=>e.type===`file`?TMe(e,o):e);return{...e,content:t}}return e})),s=qke(s,this.messages,e.targetProvider,this.logger),s.filter(e=>e!=null).map(Ype).filter(e=>e.role===`system`||typeof e.content==`string`||e.content.length>0)}},aiV6:{ui:()=>this.toAIV6UIMessages(this.all.db()),llmPrompt:async e=>Qpe(await this.all.aiV5.llmPrompt(e))},aiV7:{ui:()=>this.toAIV6UIMessages(this.all.db()),llmPrompt:async e=>eme(await this.all.aiV5.llmPrompt(e))},prompt:()=>this.all.aiV4.prompt(),ui:()=>this.toAIV4UIMessages(this.all.db()),core:()=>Zg(this.toAIV4UIMessages(this.all.db(),{transformToolPayloads:!1})),aiV4:{ui:()=>this.toAIV4UIMessages(this.all.db()),core:()=>Zg(this.toAIV4UIMessages(this.getMessagesForModelPrompt(),{transformToolPayloads:!1})),prompt:()=>{let e=this.all.aiV4.core();return[...this.systemMessages,...Object.values(this.taggedSystemMessages).flat(),...e]},llmPrompt:()=>{let e=this.all.aiV4.core();return[...this.systemMessages,...Object.values(this.taggedSystemMessages).flat(),...e].map(Jpe)}}};remembered={db:()=>this.messages.filter(e=>this.memoryMessages.has(e)),v1:()=>e_(this.remembered.db()),aiV5:{model:()=>Qg(this.toAIV5UIMessages(this.remembered.db(),{transformToolPayloads:!1}),this.messages),ui:()=>this.toAIV5UIMessages(this.remembered.db())},aiV6:{ui:()=>this.toAIV6UIMessages(this.remembered.db())},ui:()=>this.toAIV4UIMessages(this.remembered.db()),core:()=>Zg(this.toAIV4UIMessages(this.remembered.db(),{transformToolPayloads:!1})),aiV4:{ui:()=>this.toAIV4UIMessages(this.remembered.db()),core:()=>Zg(this.toAIV4UIMessages(this.remembered.db(),{transformToolPayloads:!1}))}};rememberedPersisted={db:()=>this.all.db().filter(e=>this.memoryMessagesPersisted.has(e)),v1:()=>e_(this.rememberedPersisted.db()),aiV5:{model:()=>Qg(this.toAIV5UIMessages(this.rememberedPersisted.db(),{transformToolPayloads:!1}),this.messages),ui:()=>this.toAIV5UIMessages(this.rememberedPersisted.db())},aiV6:{ui:()=>this.toAIV6UIMessages(this.rememberedPersisted.db())},ui:()=>this.toAIV4UIMessages(this.rememberedPersisted.db()),core:()=>Zg(this.toAIV4UIMessages(this.rememberedPersisted.db(),{transformToolPayloads:!1})),aiV4:{ui:()=>this.toAIV4UIMessages(this.rememberedPersisted.db()),core:()=>Zg(this.toAIV4UIMessages(this.rememberedPersisted.db(),{transformToolPayloads:!1}))}};input={db:()=>this.messages.filter(e=>this.newUserMessages.has(e)),v1:()=>e_(this.input.db()),aiV5:{model:()=>Qg(this.toAIV5UIMessages(this.input.db(),{transformToolPayloads:!1}),this.messages),ui:()=>this.toAIV5UIMessages(this.input.db())},aiV6:{ui:()=>this.toAIV6UIMessages(this.input.db())},ui:()=>this.toAIV4UIMessages(this.input.db()),core:()=>Zg(this.toAIV4UIMessages(this.input.db(),{transformToolPayloads:!1})),aiV4:{ui:()=>this.toAIV4UIMessages(this.input.db()),core:()=>Zg(this.toAIV4UIMessages(this.input.db(),{transformToolPayloads:!1}))}};inputPersisted={db:()=>this.messages.filter(e=>this.newUserMessagesPersisted.has(e)),v1:()=>e_(this.inputPersisted.db()),aiV5:{model:()=>Qg(this.toAIV5UIMessages(this.inputPersisted.db(),{transformToolPayloads:!1}),this.messages),ui:()=>this.toAIV5UIMessages(this.inputPersisted.db())},aiV6:{ui:()=>this.toAIV6UIMessages(this.inputPersisted.db())},ui:()=>this.toAIV4UIMessages(this.inputPersisted.db()),core:()=>Zg(this.toAIV4UIMessages(this.inputPersisted.db(),{transformToolPayloads:!1})),aiV4:{ui:()=>this.toAIV4UIMessages(this.inputPersisted.db()),core:()=>Zg(this.toAIV4UIMessages(this.inputPersisted.db(),{transformToolPayloads:!1}))}};response={db:()=>this.messages.filter(e=>this.newResponseMessages.has(e)),v1:()=>e_(this.response.db()),aiV5:{ui:()=>this.toAIV5UIMessages(this.response.db()),model:()=>Qg(this.toAIV5UIMessages(this.response.db(),{transformToolPayloads:!1}),this.messages).filter(e=>e.role===`tool`||e.role===`assistant`),modelContent:(e,t)=>typeof e==`number`?wMe.extractStepContent(this.response.aiV5.ui(),e,this.response.aiV5.stepContent,t):this.response.aiV5.model().map(this.response.aiV5.stepContent).flat(),stepContent:e=>wMe.convertToStepContent(e,this.messages,()=>this.response.aiV5.model().at(-1))},aiV6:{ui:()=>this.toAIV6UIMessages(this.response.db())},aiV4:{ui:()=>this.toAIV4UIMessages(this.response.db()),core:()=>Zg(this.toAIV4UIMessages(this.response.db(),{transformToolPayloads:!1}))}};#a(){if(this.#e.size===0)return[];let e=new Set(this.responsePersisted.db().map(e=>e.id));return Array.from(this.#e.keys()).filter(t=>!e.has(t))}async getRunResponseMessages(e){let t=this.responsePersisted.db(),n=this.#a();if(n.length===0)return t;let r=[],i=[];for(let e of n){let t=this.#e.get(e);t?r.push(t):i.push(e)}if(i.length>0&&e){let t=new Set(i),n=await e(i)??[];r.push(...n.filter(e=>t.has(e.id)))}return[...r,...t].sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime())}responsePersisted={db:()=>this.messages.filter(e=>this.newResponseMessagesPersisted.has(e)),aiV5:{model:()=>Qg(this.toAIV5UIMessages(this.responsePersisted.db(),{transformToolPayloads:!1}),this.messages),ui:()=>this.toAIV5UIMessages(this.responsePersisted.db())},aiV6:{ui:()=>this.toAIV6UIMessages(this.responsePersisted.db())},ui:()=>this.toAIV4UIMessages(this.responsePersisted.db()),aiV4:{ui:()=>this.toAIV4UIMessages(this.responsePersisted.db()),core:()=>Zg(this.toAIV4UIMessages(this.responsePersisted.db(),{transformToolPayloads:!1}))}};recordUnavailableAttachment(e){for(let t of this.messages){if(t.role!==`user`||PMe(t).includes(e)||!RMe(t).includes(e))continue;t.content.metadata=FMe(t.content.metadata,[e]);let n=this.unavailableAttachmentUpdates.get(t.id)??new Set;n.add(e),this.unavailableAttachmentUpdates.set(t.id,n)}}drainUnavailableAttachmentUpdates(){let e=[...this.unavailableAttachmentUpdates].map(([e,t])=>({messageId:e,urls:[...t]}));return this.unavailableAttachmentUpdates.clear(),e}drainUnsavedMessages(){return this.drainUnsavedMessagesForSave().messages}drainUnsavedMessagesForSave(){let e=[...this.newUserMessages],t=[...this.newResponseMessages],n=this.messages.filter(e=>this.newUserMessages.has(e)||this.newResponseMessages.has(e));return this.newUserMessages.clear(),this.newResponseMessages.clear(),{messages:n.map(e=>this.transformMessageForTranscript(e)),restore:()=>{for(let t of e)this.messages.includes(t)&&this.newUserMessages.add(t);for(let e of t)this.messages.includes(e)&&this.newResponseMessages.add(e)}}}transformMessagesForTranscript(e){return e.map(e=>this.transformMessageForTranscript(e))}transformToolStateDataForTranscript(e,t){if(!e||typeof e!=`object`)return e;let n=e,r=n.metadata??n.providerMetadata,i=lm(r,`transcript`,t),a=lm(r,`transcript`,`input-available`),o=t===`approval`?um(i)?i.transformed:um(a)?a.transformed:void 0:um(a)?a.transformed:um(i)?i.transformed:void 0,s=t===`suspend`&&um(i)?i.transformed:void 0;return{...n,...o===void 0?{}:{args:o},...s===void 0?{}:{suspendPayload:s}}}transformMessageForTranscript(e){if(e.content?.format!==2||!e.content.parts)return e;let t=!1,n=new Map,r=e.content.parts.map(e=>{if(e.type===`tool-invocation`&&e.toolInvocation){let r=lm(e.providerMetadata,`transcript`,`input-available`),i=e.toolInvocation.state===`output-error`&&e.toolInvocation.result!==void 0&&e.providerExecuted===!0,a=e.toolInvocation.state===`result`||i?lm(e.providerMetadata,`transcript`,`output-available`)??lm(e.providerMetadata,`transcript`,`error`):e.toolInvocation.state===`output-error`?lm(e.providerMetadata,`transcript`,`error`):void 0;if(!r&&!a)return e;t=!0;let o=um(r)?r.transformed:e.toolInvocation.args,s=e.toolInvocation.state===`result`?um(a)?a.transformed:e.toolInvocation.result:void 0,c=i?um(a)?a.transformed:e.toolInvocation.result:void 0,l=e.toolInvocation.state===`output-error`?i&&um(a)?typeof c==`string`?c:dm(c):um(a)?a.transformed:e.toolInvocation.errorText:void 0;return n.set(e.toolInvocation.toolCallId,{args:o,...e.toolInvocation.state===`result`?{result:s}:{},...e.toolInvocation.state===`output-error`?{errorText:l,...i?{result:c}:{}}:{}}),{...e,toolInvocation:{...e.toolInvocation,args:o,...e.toolInvocation.state===`result`?{result:s}:{},...e.toolInvocation.state===`output-error`?{errorText:l,...i?{result:c}:{}}:{}}}}return e.type===`data-tool-call-suspended`||e.type===`data-tool-call-approval`?(t=!0,{...e,data:this.transformToolStateDataForTranscript(e.data,e.type===`data-tool-call-suspended`?`suspend`:`approval`)}):e}),i=e.content.toolInvocations?.map(e=>{let r=n.get(e.toolCallId);if(!r)return e;let i=e.state;return t=!0,{...e,...r.args===void 0?{}:{args:r.args},...(e.state===`result`||i===`output-error`)&&`result`in r?{result:r.result}:{},...i===`output-error`&&r.errorText!==void 0?{errorText:r.errorText}:{}}}),a=e.content.metadata&&typeof e.content.metadata==`object`?{...e.content.metadata}:e.content.metadata;if(a&&typeof a==`object`)for(let[e,n]of[[`suspendedTools`,`suspend`],[`pendingToolApprovals`,`approval`]]){let r=a[e];r&&typeof r==`object`&&(t=!0,a[e]=Object.fromEntries(Object.entries(r).map(([e,t])=>[e,this.transformToolStateDataForTranscript(t,n)])))}return t?{...e,content:{...e.content,parts:r,...i?{toolInvocations:i}:{},...a?{metadata:a}:{}}}:e}getEarliestUnsavedMessageTimestamp(){let e=this.messages.filter(e=>this.newUserMessages.has(e)||this.newResponseMessages.has(e));if(e.length!==0)return Math.min(...e.map(e=>new Date(e.createdAt).getTime()))}isNewMessage(e){return this.stateManager.isNewMessage(e)}updateToolInvocation(e,t){if(!e.toolInvocation?.toolCallId)return!1;let n=e.toolInvocation.toolCallId;for(let r=this.messages.length-1;r>=0;r--){let i=this.messages[r];if(i.role===`assistant`&&i.content?.parts)for(let r=0;r<i.content.parts.length;r++){let a=i.content.parts[r];if(a?.type===`tool-invocation`&&a.toolInvocation?.toolCallId===n)return this.mergeToolResultIntoPart(i,r,e,t),!0}}let r=e.toolInvocation.toolName;for(let i=this.messages.length-1;i>=0;i--){let a=this.messages[i];if(a.role===`assistant`&&a.content?.parts)for(let i=0;i<a.content.parts.length;i++){let o=a.content.parts[i];if(o?.type!==`tool-invocation`)continue;let s=o;if(s.providerExecuted===!0&&s.toolInvocation?.state===`call`&&s.toolInvocation.toolName===r){let r=s.toolInvocation.toolCallId;return s.toolInvocation.toolCallId=n,this.mergeToolResultIntoPart(a,i,e,t,r),!0}}}return this.logger?.warn(`updateToolInvocation: no matching tool call found for toolCallId=${n}`),!1}updateMessageMetadataByToolCallId(e,t){if(!e)return!1;for(let n=this.messages.length-1;n>=0;n--){let r=this.messages[n];if(r.role!==`assistant`||!r.content?.parts||!r.content.parts.some(t=>t?.type===`tool-invocation`&&t.toolInvocation?.toolCallId===e))continue;let i=r.content.metadata??{},a=t??{},o=i.backgroundTasks,s=a.backgroundTasks,c=XMe(o,s);return r.content.metadata={...i,...a,...c?{backgroundTasks:c}:{}},this.lastCreatedAt=Math.max(this.lastCreatedAt||0,Date.now()),this.updateLastCreatedAt(r),this.stateManager.isResponseMessage(r)||(this.stateManager.removeMessage(r),this.stateManager.addToSource(r,`response`)),!0}return this.logger?.warn(`updateMessageMetadataByToolCallId: no matching tool call found for toolCallId=${e}`),!1}addOutputErrorsToProviderToolCalls(e,t,n){if(!e||!t?.length)return!1;let r=new Set(t),i=n??`Provider tool call did not complete: the model stream terminated with an error.`,a=this.messages.find(t=>t.id===e&&t.role===`assistant`);if(!a?.content?.parts)return!1;let o=!1,s=[];for(let e=0;e<a.content.parts.length;e++){let t=a.content.parts[e];if(t?.type!==`tool-invocation`)continue;let n=t,c=n.toolInvocation?.state;n.providerExecuted!==!0||!r.has(n.toolInvocation?.toolCallId)||c!==`call`&&c!==`partial-call`||(n.toolInvocation={...n.toolInvocation,state:`output-error`,errorText:i},s.push(n.toolInvocation.toolCallId),o=!0)}return o?(Array.isArray(a.content.toolInvocations)&&(a.content.toolInvocations=a.content.toolInvocations.filter(e=>!s.includes(e.toolCallId))),this.lastCreatedAt=Math.max(this.lastCreatedAt||0,Date.now()),this.updateLastCreatedAt(a),this.stateManager.isResponseMessage(a)||(this.stateManager.removeMessage(a),this.stateManager.addToSource(a,`response`)),!0):!1}mergeToolResultIntoPart(e,t,n,r,i){let a=e.content.parts[t],o=i??a.toolInvocation.toolCallId,s=a,c=n,l=s.providerMetadata!==void 0||c.providerMetadata!==void 0?(()=>{let e=s.providerMetadata??{},t=c.providerMetadata??{},n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=t&&typeof t==`object`&&!Array.isArray(t)&&r&&typeof r==`object`&&!Array.isArray(r)?{...t,...r}:r}return Hke(e,t,n)})():void 0,u={...n,toolInvocation:{...n.toolInvocation,args:a.toolInvocation.args},...s.providerExecuted!==void 0&&c.providerExecuted===void 0?{providerExecuted:s.providerExecuted}:{},...a.title!==void 0&&n.title===void 0?{title:a.title}:{},...l===void 0?{}:{providerMetadata:l}};a.updatedAt!==void 0&&u.updatedAt===void 0&&(u.updatedAt=a.updatedAt),tMe(u,a.toolInvocation,n.updatedAt),e.content.parts[t]=u;let d=e.content.metadata??{},f=r??{},p=d.backgroundTasks,m=f.backgroundTasks,h=XMe(p,m);if(e.content.metadata={...d,...f,...h?{backgroundTasks:h}:{}},Array.isArray(e.content.toolInvocations)&&(n.toolInvocation.state===`result`||n.toolInvocation.state===`output-error`&&(c.providerExecuted??s.providerExecuted)===!0)){let t=n.toolInvocation;e.content.toolInvocations=e.content.toolInvocations.map(e=>e.toolCallId===o?{...e,toolCallId:t.toolCallId,state:`result`,args:a.toolInvocation.args,result:t.result}:e)}this.lastCreatedAt=Math.max(this.lastCreatedAt||0,Date.now()),this.updateLastCreatedAt(e),this.stateManager.isResponseMessage(e)||(this.stateManager.removeMessage(e),this.stateManager.addToSource(e,`response`))}stepStart(){return this.openStepBoundary().appended}openStepBoundary(){let e=this.messages[this.messages.length-1];if(!e||e.role!==`assistant`||!e.content?.parts||$g.isSealed(e))return{appended:!1};let t=e.content.parts[e.content.parts.length-1],n=t?.type!==`step-start`,r=eMe(n?{type:`step-start`}:t);return n&&e.content.parts.push(r),this.#l(e.id,e.content.parts,r),this.#s=r,this.stateManager.isResponseMessage(e)||(this.stateManager.removeMessage(e),this.stateManager.addToSource(e,`response`)),{boundary:r,appended:n}}#o=new WeakMap;#s;partsSinceStepBoundary(e){let t=e.content.parts??[],n=this.#s;if(!n)return t;let r=$Me(t,n,e.id,this.#o.get(n));return r===-1?t:t.slice(r+1)}#c(){let e=this.#s;if(!e)return;let t=this.#o.get(e);for(let n of this.messages){let r=$Me(n.content.parts??[],e,n.id,t);if(r!==-1)return{messageId:n.id,partIndex:r}}}#l(e,t,n){let r=t.indexOf(n);r!==-1&&this.#o.set(n,{messageId:e,prefix:eNe(t,r)})}rotateResponseMessageId(e){return this.markResponseMessageBoundary(e)||this.markResponseMessageBoundary(),this.newMessageId(`assistant`)}markResponseMessageBoundary(e){let t=e?this.messages.find(t=>t.id===e):[...this.messages].reverse().find(e=>e.role===`assistant`);return!t||t.role!==`assistant`?!1:(t.content.metadata={...t.content.metadata??{},mastra:{...t.content.metadata?.mastra??{},responseBoundary:!0}},this.stateManager.isResponseMessage(t)||(this.stateManager.removeMessage(t),this.stateManager.addToSource(t,`response`)),!0)}enrichLastStepStart(e){let t=this.messages[this.messages.length-1];if(!t||t.role!==`assistant`||!t.content?.parts||$g.isSealed(t))return!1;for(let n=t.content.parts.length-1;n>=0;n--){let r=t.content.parts[n];if(r?.type===`step-start`)return!r.model&&(r.model=e,this.stateManager.isResponseMessage(t)||(this.stateManager.removeMessage(t),this.stateManager.addToSource(t,`response`)),!0)}return!1}getSystemMessages(e){return e?this.taggedSystemMessages[e]||[]:this.systemMessages}getAllSystemMessages(){return[...this.systemMessages,...Object.values(this.taggedSystemMessages).flat()]}clearSystemMessages(e){return e?delete this.taggedSystemMessages[e]:this.systemMessages=[],this}replaceAllSystemMessages(e){this.systemMessages=[];for(let t of e)t.role===`system`&&this.systemMessages.push(t);return this}addSystem(e,t){if(!e)return this;for(let n of Array.isArray(e)?e:[e])this.addOneSystem(n,t);return this}addOneSystem(e,t){let n=CMe(e);if(n.role!==`system`)throw Error(`Expected role "system" but saw ${n.role} for message ${JSON.stringify(n,null,2)}`);t&&!this.isDuplicateSystem(n,t)?(this.taggedSystemMessages[t]||=[],this.taggedSystemMessages[t].push(n),this.recordMutation({type:`addSystem`,tag:t,message:n})):!t&&!this.isDuplicateSystem(n)&&(this.systemMessages.push(n),this.recordMutation({type:`addSystem`,message:n}))}isDuplicateSystem(e,t){return t?this.taggedSystemMessages[t]?this.taggedSystemMessages[t].some(t=>Jg.fromAIV4CoreMessageContent(t.content)===Jg.fromAIV4CoreMessageContent(e.content)):!1:this.systemMessages.some(t=>Jg.fromAIV4CoreMessageContent(t.content)===Jg.fromAIV4CoreMessageContent(e.content))}getMessageIndex(){let e=this.messageIndex;if(e&&e.messages===this.messages&&e.length===this.messages.length)return e;let t=new Map;for(let e of this.messages){let n=t.get(e.id);n?n.push(e):t.set(e.id,[e])}return this.messageIndex={messages:this.messages,length:this.messages.length,byId:t,sorted:!1},this.messageIndex}getMessagesWithId(e){return this.getMessageIndex().byId.get(e)??[]}getMessageById(e){return this.getMessagesWithId(e)[0]}appendMessage(e){let t=this.getMessageIndex(),n=this.messages.at(-1);this.messages.push(e),t.length=this.messages.length,t.sorted&&=!n||n.createdAt.getTime()<=e.createdAt.getTime();let r=t.byId.get(e.id);r?r.push(e):t.byId.set(e.id,[e])}replaceMessageAt(e,t){let n=this.getMessageIndex(),r=this.messages[e];this.messages[e]=t,n.sorted=!1;let i=n.byId.get(r.id)?.filter(e=>e!==r)??[];i.length?n.byId.set(r.id,i):n.byId.delete(r.id);let a=n.byId.get(t.id);a?a.push(t):n.byId.set(t.id,[t])}sortMessages(){this.messages.sort((e,t)=>e.createdAt.getTime()-t.createdAt.getTime()),this.getMessageIndex().sorted=!0}shouldReplaceMessage(e){if(!this.messages.length||!(`id`in e)||!e?.id)return{exists:!1};let t=this.getMessageById(e.id);return t?{exists:!0,shouldReplace:!Zje(t,e),id:t.id}:{exists:!1}}addOne(e,t,n={}){if((!(`content`in e)||!e.content&&typeof e.content!=`string`)&&(!(`parts`in e)||!e.parts))throw new yn({id:`INVALID_MESSAGE_CONTENT`,domain:gn.AGENT,category:_n.USER,text:`Message with role "${e.role}" must have either a 'content' property (string or array) or a 'parts' property (array) that is not empty, null, or undefined. Received message: ${JSON.stringify(e,null,2)}`,details:{role:e.role,messageSource:t,hasContent:`content`in e,hasParts:`parts`in e}});if(e.role===`system`){if(t===`memory`)return null;if(_g.isAIV4CoreMessage(e)||_g.isAIV6CoreMessage(e)||_g.isAIV5CoreMessage(e)||_g.isMastraDBMessage(e))return this.addSystem(e);throw new yn({id:`INVALID_SYSTEM_MESSAGE_FORMAT`,domain:gn.AGENT,category:_n.USER,text:`Invalid system message format. System messages must be CoreMessage format with 'role' and 'content' properties. The content should be a string or valid content array.`,details:{messageSource:t,receivedMessage:JSON.stringify(e,null,2)}})}let r=nMe(e,t,this.createAdapterContext()),i=r.role===`signal`?r.content.metadata?.signal:void 0;if(t===`input`&&r.role===`signal`&&!i?.acceptedAt){let e=i?.createdAt??r.createdAt.toISOString();r.createdAt=this.generateCreatedAt(t,r.createdAt),r.content.metadata={...r.content.metadata,signal:{...i,createdAt:r.createdAt.toISOString(),acceptedAt:e}}}let{exists:a,shouldReplace:o,id:s}=this.shouldReplaceMessage(r),c=this.messages.at(-1),l=!c||!$g.isSealed(c),u=a&&s?this.getMessageById(s):void 0,d=u?this.stateManager.isUserMessage(u)?`input`:this.stateManager.isResponseMessage(u)?`response`:this.stateManager.isContextMessage(u)?`context`:void 0:void 0;if(t===`memory`&&u&&d&&!$g.isSealed(r)){let e=this.messages.indexOf(u);if(d===`input`)$g.merge(r,QMe(r,u));else if(r.role===`user`&&u.role===`user`)r.content={...r.content,...u.content,metadata:{...r.content.metadata??{},...u.content.metadata??{}}};else{for(let e of u.content.parts){if(e.type!==`text`)continue;let t=r.content.parts.find(t=>t.type===`text`&&t.text.trim()===e.text.trim());t?.type===`text`&&(t.text=e.text)}$g.merge(r,ZMe(r,u))}return this.stateManager.removeMessage(u),this.replaceMessageAt(e,r),this.pushMessageToSource(r,`memory`),this.pushMessageToSource(r,d),this.updateLastCreatedAt(r),this.sortMessages(),this}if(t===`memory`){for(let e of this.getMessagesWithId(r.id))if(Zje(e,r)||$je(e,r))return}let f=!!u&&$g.isSealed(u),p=!!u&&u!==c,m=c?this.memoryMessages.has(c):!1;if(n.merge!==!1&&l&&!f&&!p&&$g.shouldMerge(c,r,t,m,this._agentNetworkAppend)&&c)$g.merge(c,r),this.updateLastCreatedAt(c),this.pushMessageToSource(c,t);else{let e=-1;o&&(e=this.messages.findIndex(e=>e.id===s));let i=e!==-1&&this.messages[e];if(o&&i){let a=this.messages.findLastIndex(e=>$g.isSealed(e)),o=a!==-1&&e<=a;if($g.isSealed(i)){let e=i.content?.parts||[],t=0;for(let n=e.length-1;n>=0;n--)if(e[n]?.metadata?.mastra?.sealedAt){t=n+1;break}t===0&&(t=e.length);let n=r.content.parts,a;if(n.length<=t){if(Zje(i,r))return this;a=n}else a=n.slice(t);a.length>0&&(r.id=this.generateMessageId?.({idType:`message`,source:`memory`})??dn(),r.content.parts=a,r.createdAt<=i.createdAt&&(r.createdAt=new Date(i.createdAt.getTime()+1)),this.appendMessage(r))}else if(o)r.id=this.generateMessageId?.({idType:`message`,source:`memory`})??dn(),r.createdAt<=i.createdAt&&(r.createdAt=new Date(i.createdAt.getTime()+1)),this.appendMessage(r);else{let a=this.memoryMessages.has(i);if(n.merge!==!1&&$g.shouldMerge(i,r,t,a,this._agentNetworkAppend))return $g.merge(i,r),this.updateLastCreatedAt(i),this.pushMessageToSource(i,t),this.sortMessages(),this;this.stateManager.removeMessage(i),this.replaceMessageAt(e,r)}}else a||this.appendMessage(r);this.pushMessageToSource(r,t)}if(this.getMessageIndex().sorted){let e=this.messages.at(-1);return e&&this.updateLastCreatedAt(e),this}for(let e of this.messages)this.updateLastCreatedAt(e);return this.sortMessages(),this}pushMessageToSource(e,t){this.stateManager.addToSource(e,t)}lastCreatedAt;seenAsStored=new WeakSet;livePlacement=new WeakMap;liveArrivals=0;moveLiveMessagesPastStoredTies(){let e=this.memoryMessages;if(!e.size)return;for(let t of e)this.seenAsStored.add(t);let t=this.messages.filter(e=>!this.seenAsStored.has(e)&&!this.isAnchoredSignal(e));if(!t.length)return;let n=new Set;for(let t of e)n.add(t.createdAt.getTime());let r=t.map(e=>{let t=e.createdAt.getTime(),n=this.livePlacement.get(e);return n&&n.placed===t||(n={own:t,placed:t,arrival:n?.arrival??this.liveArrivals++},this.livePlacement.set(e,n)),{message:e,placement:n}});r.sort((e,t)=>e.placement.own-t.placement.own||e.placement.arrival-t.placement.arrival);let i=!1,a;for(let{message:e,placement:t}of r){let r=t.own;for(a?.moved&&r<=a.time&&(r=a.time+1);n.has(r);)r++;if(a={time:r,moved:r!==t.own},t.placed=r,r===e.createdAt.getTime())continue;let o=e.createdAt.toISOString();e.createdAt=new Date(r);let s=e.content.metadata?.signal;s?.createdAt===o&&(s.createdAt=e.createdAt.toISOString()),this.updateLastCreatedAt(e),this.newResponseMessagesPersisted.has(e)?this.newResponseMessages.add(e):this.newUserMessagesPersisted.has(e)&&this.newUserMessages.add(e),i=!0}i&&this.sortMessages()}isAnchoredSignal(e){let t=(e.content.metadata?.signal)?.metadata?.precedesMessageId;return typeof t==`string`&&this.getMessageById(t)!==void 0}updateLastCreatedAt(e){this.lastCreatedAt=Math.max(this.lastCreatedAt||0,e.createdAt.getTime())}generateCreatedAt(e,t){let n=t instanceof Date?t:typeof t==`string`||typeof t==`number`?new Date(t):void 0;if(n&&!this.lastCreatedAt)return this.lastCreatedAt=n.getTime(),n;if(n&&e===`memory`)return n;let r=new Date,i=n?.getTime()||r.getTime(),a=this.lastCreatedAt||0;if(i<=a){let e=new Date(a+1);return this.lastCreatedAt=e.getTime(),e}return this.lastCreatedAt=i,n??r}newMessageId(e){return this.generateMessageId?this.generateMessageId({idType:`message`,source:`agent`,threadId:this.memoryInfo?.threadId,resourceId:this.memoryInfo?.resourceId,role:e}):dn()}createAdapterContext(){return{memoryInfo:this.memoryInfo,newMessageId:()=>this.newMessageId(),generateCreatedAt:(e,t)=>this.generateCreatedAt(e,t),dbMessages:this.messages}}},nNe=e=>typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`image`:{let t=e.mimeType??`image/*`;return{type:`file`,mimeType:t,data:cp(e.image,t)}}case`file`:return{type:`file`,mimeType:e.mimeType,data:cp(e.data,e.mimeType),...e.filename===void 0?{}:{filename:e.filename}};default:throw Error(`Unhandled content part type: ${e.type}`)}}),rNe=e=>({id:`user-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,role:`user`,createdAt:new Date,content:{format:2,parts:e}}),iNe=e=>rNe(e.flatMap(nNe)),aNe=new Set([`task_write`,`task_update`,`task_complete`,`task_check`]),oNe=`tasks`,sNe=new Set([`current-task-list`,`task-list-update`]),cNe=new Set([`pending`,`in_progress`,`completed`]),lNe=e=>typeof e.type==`string`&&e.type.startsWith(`data-`),i_=e=>typeof e==`object`&&!!e&&!Array.isArray(e),uNe=e=>typeof e==`string`&&cNe.has(e),dNe=e=>Array.isArray(e)&&e.every(e=>i_(e)&&typeof e.id==`string`&&typeof e.content==`string`&&uNe(e.status)&&typeof e.activeForm==`string`),fNe=e=>i_(e)?e.id===oNe||typeof e.tagName==`string`&&sNe.has(e.tagName):!1,pNe=e=>{if(!fNe(e)||!i_(e))return;let t=e.metadata;if(!i_(t))return;let n=t.value;if(i_(n))return dNe(n.tasks)?n.tasks:void 0},mNe=e=>{if(i_(e)&&dNe(e.tasks))return e.tasks;if(typeof e==`string`)try{let t=JSON.parse(e);return i_(t)&&dNe(t.tasks)?t.tasks:void 0}catch{return}},hNe=e=>{if(lNe(e))return pNe(e.data)},gNe=e=>{if(e.type!==`tool-result`)return;let t=e.payload;if(i_(t)&&typeof t.toolName==`string`&&aNe.has(t.toolName))return mNe(t.result)},_Ne=e=>{if(!i_(e)||e.type!==`tool-invocation`||!i_(e.toolInvocation))return;let t=e.toolInvocation;if(typeof t.toolName==`string`&&aNe.has(t.toolName))return mNe(t.result)},vNe=e=>{if(i_(e)&&typeof e.type==`string`&&e.type.startsWith(`data-`))return pNe(e.data)},yNe=e=>{if(e.role!==`signal`)return;let t=e.content?.metadata;if(i_(t))return pNe(t.signal)},bNe=e=>{let t;for(let n of e){for(let e of n.content?.parts??[]){let n=_Ne(e);n!==void 0&&(t=n)}let e=yNe(n);e!==void 0&&(t=e);for(let e of n.content?.parts??[]){let n=vNe(e);n!==void 0&&(t=n)}}return t??[]},a_=e=>typeof e==`object`&&!!e,xNe=[`pendingToolApprovals`,`requireApprovalMetadata`,`suspendedTools`],SNe=e=>a_(e)&&Object.values(e).every(e=>a_(e)),CNe=e=>{if(!a_(e))return[];let t=[];for(let n of xNe){let r=e[n];SNe(r)&&t.push(r)}return t},wNe=e=>{for(let t of e)for(let e of CNe(t.content?.metadata))for(let t of Object.values(e))if(a_(t)&&typeof t.runId==`string`&&t.runId.length>0)return t.runId},TNe=e=>{let t=e.content.metadata?.[lp];return typeof t==`string`?t:void 0},ENe=e=>{let t=e.content.metadata?.signal,n=i_(t)&&i_(t.metadata)?t.metadata[lp]:void 0;return typeof n==`string`?n:void 0},DNe=({conversation:e,history:t,previousHistory:n})=>{let r=new Map(n.map(e=>[e.id,e])),i=e.filter(e=>r.get(e.id)!==e),a=new Map(i.map(e=>[e.id,e])),o=new Set(i.flatMap(e=>TNe(e)??[])),s=new Set(t.map(e=>e.id)),c=new Set(t.flatMap(e=>ENe(e)??[])),l=t.map(e=>{let t=a.get(e.id);if(t)return t;let n=ENe(e);return!n||!o.has(n)?e:{...e,content:{...e.content,metadata:{...e.content.metadata,[lp]:n}}}}),u=i.filter(e=>{let t=TNe(e);return!s.has(e.id)&&!(t&&c.has(t))});return[...l,...u]},ONe=e=>{let t=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content,n=e.providerOptions??e.experimental_providerMetadata;return n?t.map(e=>{let t={...n};for(let[n,r]of Object.entries(e.providerOptions??e.experimental_providerMetadata??{}))t[n]={...t[n],...r};return{...e,providerOptions:t}}):t},kNe=(e,t=[])=>({role:`user`,content:[...e||t.length===0?[{type:`text`,text:e}]:[],...t.flatMap(ONe)]}),ANe=(e,t)=>{let n=new Set;for(let r of e){let e=r.content?.metadata;if(!e)continue;let i=[e.pendingToolApprovals,e.requireApprovalMetadata,e.suspendedTools];for(let e of i)if(e&&typeof e==`object`)for(let r of Object.values(e)){if(t&&r?.runId!==t)continue;let e=r?.toolCallId;typeof e==`string`&&e.length>0&&n.add(e)}}return n},jNe=(e,t)=>e.some(e=>{if(e.type!==`tool-invocation`)return!1;let n=e.toolInvocation;return n.toolCallId===t?n.state===`result`||n.result!=null:!1}),MNe=(e,t)=>{if(!e||typeof e!=`object`)return;let n=Object.fromEntries(Object.entries(e).filter(([,e])=>e&&typeof e==`object`&&typeof e.toolCallId==`string`&&!jNe(t,e.toolCallId)));return Object.keys(n).length?n:void 0},NNe=e=>e.filter(e=>{let t=e.content?.metadata;return!(t?.completionResult?.suppressFeedback||t?.isTaskCompleteResult?.suppressFeedback)}).map(e=>{let t=e.content?.metadata,n=t&&(t.status===`pending`||`clientMessageId`in t)?(()=>{let{[lp]:n,...r}=t,{status:i,...a}=r;return{...e,content:{...e.content,metadata:t.status===`pending`?a:r}}})():e,r=n.content?.metadata;if(!r?.pendingToolApprovals&&!r?.requireApprovalMetadata&&!r?.suspendedTools)return n;let{pendingToolApprovals:i,requireApprovalMetadata:a,suspendedTools:o,...s}=r,c=n.content.parts,l=MNe(i,c),u={...MNe(a,c),...l},d=MNe(o,c);return{...n,content:{...n.content,metadata:{...s,...i?{mode:`stream`}:{},...l?{pendingToolApprovals:l}:{},...Object.keys(u).length?{requireApprovalMetadata:u}:{},...d?{suspendedTools:d}:{}}}}}),PNe=e=>typeof e==`object`&&!!e,FNe=e=>PNe(e)&&typeof e.name==`string`?e.name:void 0,o_=e=>FNe(e)===`AbortError`,INe=e=>{if(!PNe(e))return!1;let t=e.status;return t===404||t===405||t===501||t===400&&typeof e.message==`string`&&e.message.includes(`No active agent run found for signal target`)},LNe=e=>typeof e.type==`string`&&e.type.startsWith(`data-`),s_=(e,t)=>e.map(e=>{let n=zg.fromUIMessage(e);return{...n,content:{...n.content,metadata:{...n.content.metadata??{},...t}}}}),RNe=({agentId:e,resourceId:t,threadId:n,initialMessages:r,requestContext:i,clientTools:a,onSignalSent:o,onSignalEcho:s,onThreadSignalsUnsupported:c,enableThreadSignals:l=!1,streamPath:u,withInitialHistory:d})=>{let f=l===!1,p=(0,G.useRef)(void 0),m=(0,G.useRef)(void 0),h=(0,G.useRef)(void 0),g=(0,G.useRef)(void 0),_=(0,G.useRef)({requestContext:i}),v=(0,G.useRef)(null),y=(0,G.useRef)(null),b=(0,G.useRef)(null),x=(0,G.useRef)(void 0),S=(0,G.useRef)(null),C=(0,G.useRef)(!1),[w,T]=(0,G.useState)([]),[E,D]=(0,G.useState)([]),O=(0,G.useRef)(void 0),[k,A]=(0,G.useState)({}),[j,M]=(0,G.useState)({}),N=(0,G.useRef)(new Set),P=(0,G.useRef)(new Set),F=(0,G.useRef)(void 0),I=(0,G.useRef)(!1),L=(0,G.useRef)(void 0),[R,z]=(0,G.useState)(!1),B=Y(),[V,H]=(0,G.useState)(!1),[ee,te]=(0,G.useState)(void 0),[U,W]=(0,G.useState)(void 0),ne=`${e}:${t??``}:${n??``}`,re=d?d===!0?`history`:`history:${d.perPage??``}`:``,ie=d&&!f&&n&&U?.key===`${e}:${t||e}:${n}:${u??``}:${re}`?U.pagination:void 0,ae=d&&ee?.key===ne?ee.messages:r,oe=(0,G.useRef)(void 0);(0,G.useEffect)(()=>{let r=oe.current,i=r?.agentId===e&&r.resourceId===t&&r.threadId===n;if(i&&r.initialMessages===ae)return;let a=NNe(ae??[]);if(oe.current={agentId:e,resourceId:t,threadId:n,initialMessages:ae,formattedMessages:a},i){T(e=>DNe({conversation:e,history:a,previousHistory:r.formattedMessages})),D(O.current??bNe(a));let e=wNe(a);if(I.current||!F.current&&V&&e!==p.current)return}else O.current=void 0,P.current.clear(),F.current=void 0,I.current=!1,r&&H(!1),T(a),D(bNe(a));let o=ANe(a,F.current);for(let e of P.current)N.current.has(e)?o.add(e):o.delete(e);N.current=o,z(o.size>0),p.current=F.current??wNe(a)},[e,t,n,ae,V,R]),(0,G.useEffect)(()=>{_.current={..._.current,requestContext:i}},[i]);let se=e=>e instanceof URL?e.toString():Zue(e),ce=e=>{let t=e.reduce((e,t)=>{if(typeof t.content==`string`)return e.push({type:`text`,text:t.content}),e;for(let n of t.content)n.type===`text`?e.push({type:`text`,text:n.text}):n.type===`file`?e.push({type:`file`,data:se(n.data),mediaType:n.mimeType,...n.filename?{filename:n.filename}:{}}):n.type===`image`&&e.push({type:`file`,data:se(n.image),mediaType:n.mimeType??`image/png`});return e},[]);return t.length===1&&t[0]?.type===`text`?t[0].text:t},le=(0,G.useCallback)(()=>{C.current=!0,c?.()},[c]),ue=e=>e.flatMap(e=>typeof e.content==`string`?[e.content]:e.content.map(e=>e.type===`text`?e.text:e.type===`image`?`Image`:e.filename?`File: ${e.filename}`:`File`)).join(` `).replace(/\s+/g,` `).trim()||`Attachment`,de=(0,G.useCallback)(()=>{let e=b.current;e?.unsubscribe?e.unsubscribe():y.current?.abort(),b.current=null,y.current=null,x.current=void 0,S.current=null,W(void 0)},[]),fe=(0,G.useCallback)(async(e,t)=>{let n=e.type===`finish`||e.type===`abort`||e.type===`error`;if(n&&F.current&&e.runId!==F.current)return;let r=`runId`in e&&typeof e.runId==`string`?e.runId:void 0;T(t=>{let n={mode:`stream`,runId:r},i=hde({chunk:e,conversation:t,metadata:n});return(e.type===`start`||e.type===`step-start`)&&e.payload?.messageId&&r?i.map(t=>t.id===e.payload.messageId&&t.role===`assistant`?{...t,content:{...t.content,metadata:{...t.content.metadata,...n}}}:t):i});let i=gNe(e)??hNe(e);if(i!==void 0&&(O.current=i,D(i)),e.type===`data-user-message`&&LNe(e)&&(e.data?.type===`user-message`||e.data?.type===`user`)&&typeof e.data?.id==`string`&&s?.(e.data.id),e.type===`start`&&(H(!0),`runId`in e&&typeof e.runId==`string`&&(F.current!==e.runId&&P.current.clear(),I.current=!1,F.current=e.runId,p.current=e.runId)),e.type===`tool-call-approval`||e.type===`tool-call-suspended`){let t=e.payload?.toolCallId;typeof t==`string`&&(P.current.add(t),N.current.add(t),z(!0)),r&&((!F.current||I.current)&&(F.current=r,I.current=!1),F.current===r&&(p.current=r)),H(!1)}if(e.type===`tool-call-resumed`){let t=e.payload?.toolCallId;typeof t==`string`&&(P.current.add(t),N.current.delete(t),z(N.current.size>0))}if(n){e.runId===F.current&&(I.current=!0);for(let e of N.current)P.current.add(e);N.current.clear(),z(!1),H(!1)}(t??m.current)?.(e)},[s]),pe=(0,G.useCallback)(async({threadId:t,resourceId:n})=>{let r=`${e}:${n??``}:${t}:${u??``}:${re}`;if(x.current===r&&S.current){await S.current;return}de();let i=new AbortController;y.current=i,x.current=r;let a=()=>{y.current===i&&(b.current=null,y.current=null,x.current=void 0,S.current=null,W(void 0))},o=new op({...B.options,abortSignal:i.signal}).getAgent(e,void 0,{stream:u});S.current=o.subscribeToThread({resourceId:n,threadId:t,withRunStatus:!0,...d?{withInitialHistory:d}:{}}).then(o=>{let s=o;y.current===i?(b.current=s,s.processDataStream({onChunk:a=>{if(a.type===`thread-history`){if(y.current===i){let{hasMore:e,activeRunId:t}=a.payload;t&&t!==F.current&&(!F.current||I.current)&&(F.current=t,I.current=!1,p.current=t,H(N.current.size===0)),W(typeof e==`boolean`?{key:r,pagination:{hasMore:e}}:void 0)}let o=NNe(a.payload.messages),s=oe.current?.formattedMessages??[];T(e=>DNe({conversation:e,history:o,previousHistory:s})),te({key:`${e}:${n??``}:${t}`,messages:a.payload.messages})}else if(a.type===`thread-run-status`){if(a.runId!==F.current){L.current?.set(a.runId,a);return}if(H(!1),a.payload.status!==`suspended`){I.current=!0;for(let e of N.current)P.current.add(e);N.current.clear(),z(!1)}}else return fe(a)}}).catch(e=>{o_(e)||(console.error(`[useChat] Thread subscription failed`,e),H(!1))}).finally(()=>{b.current===s&&(b.current=null),a()})):s.unsubscribe()}).catch(e=>{if(a(),INe(e))le();else throw o_(e)||(console.error(`[useChat] Thread subscription failed`,e),H(!1)),e}),await S.current},[e,B,de,re,le,fe,u,d]);(0,G.useEffect)(()=>(C.current=!1,de),[e,t,n,de]),(0,G.useEffect)(()=>{!n||f?de():pe({threadId:n,resourceId:t||e}).catch(e=>{o_(e)||console.error(`[useChat] Thread subscription failed`,e)})},[e,de,pe,t,n,f]);let me=async({coreUserMessages:n,model:r,requestContext:o,threadId:s,modelSettings:c,signal:l,onFinish:d,tracingOptions:f,clientTools:m,clientToolsResolver:h})=>{let{frequencyPenalty:g,presencePenalty:v,maxRetries:y,maxTokens:b,temperature:x,topK:S,topP:C,instructions:w,system:E,providerOptions:D,maxSteps:O,requireToolApproval:k}=c||{},A=o??i,j=m??a;_.current={model:r,requestContext:A},H(!0);let M=new op({...B.options,abortSignal:l}).getAgent(e,void 0,{stream:u}),N=dn();p.current=N;let P=await M.generate(n,{model:r,runId:N,maxSteps:O,modelSettings:{frequencyPenalty:g,presencePenalty:v,maxRetries:y,maxOutputTokens:b,temperature:x,topK:S,topP:C},instructions:w,system:E,requestContext:A,...s?{memory:{thread:s,resource:t||e}}:{},providerOptions:D,tracingOptions:f,requireToolApproval:k,clientTools:j,clientToolsResolver:h});if(P.finishReason===`suspended`&&P.suspendPayload){let{toolCallId:e,toolName:t,args:n}=P.suspendPayload;if(P.response?.uiMessages){let r=s_(P.response.uiMessages,{mode:`generate`,requireApprovalMetadata:{[t]:{toolCallId:e,toolName:t,args:n}}});T(e=>[...e,...r])}H(!1)}else if(H(!1),P&&`uiMessages`in P.response&&P.response.uiMessages){let e=s_(P.response.uiMessages,{mode:`generate`});d?.(e),T(t=>[...t,...e])}},he=async({coreUserMessages:n,model:r,requestContext:c,threadId:l,onChunk:d,modelSettings:h,signal:g,tracingOptions:y,clientTools:b,clientToolsResolver:x,signalId:S,clientMessageId:w,metadata:E})=>{let{frequencyPenalty:D,presencePenalty:O,maxRetries:k,maxTokens:A,temperature:j,topK:M,topP:R,instructions:V,system:ee,providerOptions:te,maxSteps:U,requireToolApproval:W}=h||{},ne=c??i,re=b??a,ie={model:r,maxSteps:U,modelSettings:{frequencyPenalty:D,presencePenalty:O,maxRetries:k,maxOutputTokens:A,temperature:j,topK:M,topP:R},instructions:V,system:ee,providerOptions:te,requireToolApproval:W,tracingOptions:y};_.current={model:r,requestContext:ne},H(!0),v.current?.abort();let ae=new AbortController;v.current=ae,g&&(g.aborted?ae.abort():g.addEventListener(`abort`,()=>ae.abort(),{once:!0}));let oe=new op({...B.options,abortSignal:ae.signal}).getAgent(e,void 0,{stream:u}),se=e=>o_(e)&&ae.signal.aborted&&!g?.aborted,de=()=>{v.current&&v.current!==ae||H(!1)},me=()=>{de(),S&&T(e=>e.filter(e=>e.id!==S||e.content.metadata?.status!==`pending`))},he=async()=>{try{await ge()}catch(e){if(!se(e))throw e;me()}},ge=async()=>{let i=dn();p.current=i;let a=await oe.stream(n,{model:r,runId:i,maxSteps:U,untilIdle:!0,modelSettings:{frequencyPenalty:D,presencePenalty:O,maxRetries:k,maxOutputTokens:A,temperature:j,topK:M,topP:R},instructions:V,system:ee,requestContext:ne,...l?{memory:{thread:l,resource:t||e}}:{},providerOptions:te,requireToolApproval:W,tracingOptions:y,clientTools:re,clientToolsResolver:x});m.current=d,p.current=i,await a.processDataStream({onChunk:e=>fe(e,d)}),v.current===ae&&(v.current=null),de()};if(!l||C.current||f||(m.current=d,await pe({threadId:l,resourceId:t||e}),C.current)){await he();return}let _e=S??dn(),ve=ce(n),ye=ne,be={model:r,maxSteps:U,modelSettings:{frequencyPenalty:D,presencePenalty:O,maxRetries:k,maxOutputTokens:A,temperature:j,topK:M,topP:R},instructions:V,system:ee,requestContext:ye,providerOptions:te,requireToolApproval:W,tracingOptions:y,clientTools:re,clientToolsResolver:x},xe=F.current,Se=new Map;L.current=Se;try{let r=await oe.sendMessage({message:w||E?{contents:ve,metadata:{...E,...w?{[lp]:w}:{}}}:ve,resourceId:t||e,threadId:l,ifIdle:{streamOptions:{...ie,requestContext:ye,clientTools:re,clientToolsResolver:x}}});if(v.current===ae&&F.current===xe&&F.current!==r.runId){P.current.clear(),F.current=r.runId,I.current=!1,p.current=r.runId,H(!0);let e=Se.get(r.runId);if(e&&(H(!1),e.payload.status!==`suspended`)){I.current=!0;for(let e of N.current)P.current.add(e);N.current.clear(),z(!1)}}let i=r.signal&&typeof r.signal==`object`&&`id`in r.signal&&typeof r.signal.id==`string`?r.signal.id:_e;o?.(i,ue(n)),N.current.size>0&&H(!1)}catch(r){if(se(r)){me();return}if(INe(r))try{await oe.sendSignal({signal:{id:_e,type:`user-message`,contents:ve,...E?{metadata:E}:{}},resourceId:t||e,threadId:l,ifIdle:{streamOptions:be}}),o?.(_e,ue(n));return}catch(e){if(s?.(_e),se(e)){me();return}if(INe(e)){le(),T(e=>[...e,iNe(n)]),await he();return}throw e}throw r}finally{L.current===Se&&(L.current=void 0)}v.current===ae&&(v.current=null)},ge=async({coreUserMessages:n,model:r,requestContext:a,threadId:o,onNetworkChunk:s,modelSettings:c,signal:l,tracingOptions:d})=>{let{frequencyPenalty:f,presencePenalty:m,maxRetries:v,maxTokens:y,temperature:b,topK:x,topP:S,maxSteps:C}=c||{},w=a??i;_.current={model:r,requestContext:w},H(!0);let E=new op({...B.options,abortSignal:l}).getAgent(e,void 0,{stream:u}),D=dn();p.current=D;let O=await E.network(n,{model:r,maxSteps:C,modelSettings:{frequencyPenalty:f,presencePenalty:m,maxRetries:v,maxOutputTokens:y,temperature:b,topK:x,topP:S},runId:D,requestContext:w,...o?{memory:{thread:o,resource:t||e}}:{},tracingOptions:d});g.current=s,h.current=D,await O.processDataStream({onChunk:async e=>{T(t=>Tde({chunk:e,conversation:t,metadata:{mode:`network`,runId:D}})),s?.(e)}}),T(e=>vp(e)),H(!1)};return{setMessages:T,sendMessage:async({mode:e=`stream`,metadata:t,...n})=>{!V&&!R&&(p.current=void 0);let r=[kNe(n.message,n.coreUserMessages)],i=iNe(r),a=t?{...i,content:{...i.content,metadata:{...i.content.metadata,...t}}}:i,o=e===`stream`&&n.threadId&&!C.current&&!f?`client-set-${dn()}`:void 0,s=o,c=o;if(s){let e={...a.content.metadata,mode:`stream`,status:`pending`,[lp]:c},t={...a,id:o,content:{...a.content,metadata:e}};T(e=>[...e,t])}else T(e=>[...e,a]);try{e===`generate`?await me({...n,coreUserMessages:r}):e===`stream`?await he({...n,coreUserMessages:r,signalId:s,clientMessageId:c,metadata:t}):e===`network`&&await ge({...n,coreUserMessages:r})}catch(e){throw H(!1),s&&T(e=>e.filter(e=>e.id!==s||e.content.metadata?.status!==`pending`)),e}},isRunning:V,activeRunId:V||R?p.current:void 0,isAwaitingToolApproval:R,messages:w,initialHistoryPagination:ie,tasks:E,approveToolCall:async(r,i)=>{let a=m.current,o=p.current,s=_.current;if(!o)return console.info(`[approveToolCall] approveToolCall can only be called after a stream has started`);H(!0),A(e=>({...e,[r]:{status:`approved`}}));let c=B.getAgent(e,void 0,{stream:u});if(x.current&&n)try{await c.sendToolApproval({resourceId:t||e,threadId:n,toolCallId:r,approved:!0,...s.model===void 0?{}:{streamOptions:{model:s.model}},...i===void 0?{}:{resumeData:i},requestContext:s.requestContext}),F.current??=o,P.current.add(r),N.current.delete(r),z(N.current.size>0),H(!1)}catch(e){throw A(e=>{let t={...e};return delete t[r],t}),H(!1),e}else try{await(i===void 0?await c.approveToolCall({runId:o,toolCallId:r,...s}):await c.resumeStream(i,{runId:o,toolCallId:r,...s})).processDataStream({onChunk:async e=>{await fe(e,a)}}),H(!1)}catch(e){throw A(e=>{let t={...e};return delete t[r],t}),H(!1),e}},declineToolCall:async r=>{let i=m.current,a=p.current,o=_.current;if(!a)return console.info(`[declineToolCall] declineToolCall can only be called after a stream has started`);H(!0),A(e=>({...e,[r]:{status:`declined`}}));let s=B.getAgent(e,void 0,{stream:u});if(x.current&&n)try{await s.sendToolApproval({resourceId:t||e,threadId:n,toolCallId:r,approved:!1,...o.model===void 0?{}:{streamOptions:{model:o.model}},requestContext:o.requestContext}),F.current??=a,P.current.add(r),N.current.delete(r),z(N.current.size>0),H(!1)}catch(e){throw A(e=>{let t={...e};return delete t[r],t}),H(!1),e}else await(await s.declineToolCall({runId:a,toolCallId:r,...o})).processDataStream({onChunk:async e=>{await fe(e,i)}}),H(!1)},approveToolCallGenerate:async t=>{let n=p.current,r=_.current;if(!n)return console.info(`[approveToolCallGenerate] approveToolCallGenerate can only be called after a generate has started`);H(!0),A(e=>({...e,[t]:{status:`approved`}}));let i=await B.getAgent(e,void 0,{stream:u}).approveToolCallGenerate({runId:n,toolCallId:t,...r});if(i&&`uiMessages`in i.response&&i.response.uiMessages){let e=s_(i.response.uiMessages,{mode:`generate`});T(t=>[...t,...e])}H(!1)},declineToolCallGenerate:async t=>{let n=p.current,r=_.current;if(!n)return console.info(`[declineToolCallGenerate] declineToolCallGenerate can only be called after a generate has started`);H(!0),A(e=>({...e,[t]:{status:`declined`}}));let i=await B.getAgent(e,void 0,{stream:u}).declineToolCallGenerate({runId:n,toolCallId:t,...r});if(i&&`uiMessages`in i.response&&i.response.uiMessages){let e=s_(i.response.uiMessages,{mode:`generate`});T(t=>[...t,...e])}H(!1)},cancelRun:()=>{let r=p.current,i=B?.getAgent(e),a=b.current,o=v.current,s=new AbortController,c=setTimeout(()=>s.abort(Error(`Agent run cancellation was not acknowledged`)),1e4),l=(async()=>{if(i&&r)for(;;){s.signal.throwIfAborted();let a={signal:s.signal};if((n?await i.abortThread({threadId:n,resourceId:t||e,expectedRunId:r},a):await i.abortRun(r,a)).aborted)return;await new Promise(e=>setTimeout(e,100))}await a?.abort?.()})().catch(e=>{if(!PNe(e)||e.status!==404&&e.status!==501)throw e}).finally(()=>{clearTimeout(c),o?.abort(),v.current===o&&(v.current=null)});return l.catch(e=>console.error(`[useChat] Failed to abort agent run`,e)),de(),T(e=>vp(e)),I.current=!0,N.current.clear(),z(!1),H(!1),p.current=void 0,m.current=void 0,h.current=void 0,g.current=void 0,_.current={},l},toolCallApprovals:k,approveNetworkToolCall:async(t,n)=>{let r=g.current,i=n||h.current,a=_.current;if(!i)return console.info(`[approveNetworkToolCall] approveNetworkToolCall can only be called after a network stream has started`);p.current=i,H(!0),M(e=>({...e,[n?`${n}-${t}`:t]:{status:`approved`}})),await(await B.getAgent(e,void 0,{stream:u}).approveNetworkToolCall({runId:i,...a})).processDataStream({onChunk:async e=>{T(t=>Tde({chunk:e,conversation:t,metadata:{mode:`network`,runId:i}})),r?.(e)}}),T(e=>vp(e)),H(!1)},declineNetworkToolCall:async(t,n)=>{let r=g.current,i=n||h.current,a=_.current;if(!i)return console.info(`[declineNetworkToolCall] declineNetworkToolCall can only be called after a network stream has started`);p.current=i,H(!0),M(e=>({...e,[n?`${n}-${t}`:t]:{status:`declined`}})),await(await B.getAgent(e,void 0,{stream:u}).declineNetworkToolCall({runId:i,...a})).processDataStream({onChunk:async e=>{T(t=>Tde({chunk:e,conversation:t,metadata:{mode:`network`,runId:i}})),r?.(e)}}),T(e=>vp(e)),H(!1)},networkToolCallApprovals:j}};function c_(e){let[t,n]=(0,G.useState)(!1),[r,i]=(0,G.useState)(!1),[a,o]=(0,G.useState)(!1),[s,c]=(0,G.useState)(null),[l,u]=(0,G.useState)(void 0),d=(0,G.useRef)(e);d.current=e;let f=(0,G.useCallback)(()=>{n(!1),i(!1),o(!1),c(null),u(void 0)},[]),p=(0,G.useCallback)(async e=>{n(!0),i(!1),o(!1),c(null);try{let t=await d.current(e);return u(t),i(!0),t}catch(e){throw c(e),o(!0),e}finally{n(!1)}},[]);return{mutate:(0,G.useCallback)(e=>{p(e).catch(()=>{})},[p]),mutateAsync:p,isPending:t,isSuccess:r,isError:a,error:s,data:l,reset:f}}function zNe({debugMode:e,tracingOptions:t,onError:n}){let r=Y(),[i,a]=(0,G.useState)(),[o,s]=(0,G.useState)(!1),c=(0,G.useRef)(void 0),l=(0,G.useRef)(!0),u=(0,G.useCallback)(()=>{let e=c.current;c.current=void 0,e&&(e.controller.abort(),e.reader?.cancel().catch(()=>void 0),e.reader?.releaseLock(),e.reader=void 0)},[]);(0,G.useEffect)(()=>(l.current=!0,()=>{l.current=!1,u()}),[u]);async function d(e,t){if(!l.current)return;u();let r={controller:new AbortController};c.current=r;let{signal:i}=r.controller;s(!0);try{let t=await e(i);if(i.aborted){await t?.cancel();return}if(!t){n?.(Error(`No stream returned`),`No stream returned`);return}let o=t.getReader();for(r.reader=o;!i.aborted;){let{done:e,value:t}=await o.read();if(e||i.aborted)break;if(a(e=>bp(e,t)),t.type===`workflow-step-start`&&s(!0),t.type===`workflow-step-suspended`&&s(!1),t.type===`workflow-finish`&&t.payload.workflowStatus===`failed`)throw Error(t.payload.metadata?.errorMessage||`Workflow execution failed`)}}catch(e){if(!i.aborted){if(!r.reader)throw e;n?.(e instanceof Error?e:Error(t),t)}}finally{r.reader?.releaseLock(),r.reader=void 0,c.current===r&&(c.current=void 0,s(!1))}}let f=c_(({workflowId:n,runId:i,inputData:o,initialState:s,requestContext:c,perStep:l,resourceId:u})=>(a({status:`pending`,input:o,steps:{}}),d(async a=>{let d=await r.getWorkflow(n).createRun({runId:i,resourceId:u});if(!a.aborted)return d.stream({inputData:o,initialState:s,requestContext:c,closeOnSuspend:!0,tracingOptions:t,perStep:l??e,resourceId:u})},`Error streaming workflow`))),p=c_(async({workflowId:e,runId:t,storeRunResult:n})=>{l.current&&(a(n??void 0),n?.status===`suspended`?(u(),s(!1)):await d(async n=>{let i=await r.getWorkflow(e).createRun({runId:t});if(!n.aborted)return i.observeStream()},`Error observing workflow`))}),m=c_(({workflowId:n,runId:i,step:a,resumeData:o,requestContext:s,perStep:c})=>d(async l=>{let u=await r.getWorkflow(n).createRun({runId:i});if(!l.aborted)return u.resumeStream({step:a,resumeData:o,requestContext:s,tracingOptions:t,perStep:c??e})},`Error resuming workflow stream`)),h=c_(({workflowId:n,requestContext:i,runId:a,perStep:o,...s})=>d(async c=>{let l=await r.getWorkflow(n).createRun({runId:a});if(!c.aborted)return l.timeTravelStream({...s,perStep:o??e,requestContext:i,tracingOptions:t})},`Error time traveling workflow stream`));return{streamWorkflow:f,streamResult:i,isStreaming:o,observeWorkflowStream:p,closeStreamsAndReset:(0,G.useCallback)(()=>{u(),s(!1),a(void 0)},[u]),resumeWorkflowStream:m,timeTravelWorkflowStream:h}}function BNe(){let e=Y();return c_(async({workflowId:t,prevRunId:n,resourceId:r})=>{try{let{runId:i}=await e.getWorkflow(t).createRun({runId:n,resourceId:r});return{runId:i}}catch(e){throw console.error(`Error creating workflow run:`,e),e}})}function VNe(){let e=Y();return c_(async({workflowId:t,runId:n})=>{try{return(await e.getWorkflow(t).createRun({runId:n})).cancelRun()}catch(e){throw console.error(`Error canceling workflow run:`,e),e}})}var HNe={"audio/webm":`webm`,"video/webm":`webm`,"audio/ogg":`ogg`,"audio/mp4":`m4a`,"video/mp4":`mp4`,"audio/mpeg":`mp3`,"audio/wav":`wav`},UNe=`audio/webm`;function WNe(e){let[t=``]=e.split(`;`);return t.trim().toLowerCase()}function GNe(e){e.getTracks().forEach(e=>e.stop())}async function KNe(e){let t=await navigator.mediaDevices.getUserMedia({audio:!0}),n;try{n=new MediaRecorder(t)}catch(e){throw GNe(t),e}let r=[];return n.ondataavailable=e=>{e.data.size>0&&r.push(e.data)},n.onstop=()=>{let i=WNe(n.mimeType||r[0]?.type||``)||UNe,a=new File(r,`recording-${Date.now()}.${HNe[i]??`webm`}`,{type:i,lastModified:Date.now()});GNe(t),e(a)},n}async function qNe(e,t){let n=new window.AudioContext,r=e.getReader(),i=[];try{for(;;){let{done:e,value:t}=await r.read();if(e)break;i.push(t)}let e=i.reduce((e,t)=>e+t.length,0),a=new Uint8Array(e),o=0;for(let e of i)a.set(e,o),o+=e.length;let s=await n.decodeAudioData(a.buffer),c=n.createBufferSource();return c.buffer=s,c.onended=t??null,c.connect(n.destination),c.start(),()=>{c.onended=null,c.stop(),n.close()}}catch(e){throw await r.cancel().catch(()=>void 0),await n.close().catch(()=>void 0),e}finally{r.releaseLock()}}var JNe=`Speech Recognition not supported in this browser`,YNe=()=>`SpeechRecognition`in window||`webkitSpeechRecognition`in window,XNe=()=>()=>{},ZNe=()=>!0,QNe=({language:e=`en-US`,agentId:t,requestContext:n})=>{let r=Y(),[i,a]=(0,G.useState)();(0,G.useEffect)(()=>{if(!t)return;let e=!1,i=r.getAgent(t);return(async()=>{try{let r=await i.voice.getSpeakers(n);e||a({agentId:t,agent:r.length>0?i:void 0})}catch{e||a({agentId:t})}})(),()=>{e=!0}},[t,r,n]);let o=i&&i.agentId===t?i.agent:void 0,s=$Ne({language:e}),c=ePe({agent:o,language:e});return o?c:s},$Ne=({language:e=`en-US`})=>{let t=(0,G.useRef)(null),n=(0,G.useSyncExternalStore)(XNe,YNe,ZNe),[r,i]=(0,G.useState)({isListening:!1,transcript:``,error:null}),a=e=>{let n=t.current;if(!n)return;n.start();let r=``;n.onresult=t=>{let n=``;for(let e=t.resultIndex;e<t.results.length;e++){let r=t.results[e][0].transcript;t.results[e].isFinal&&(n+=r+` `)}n&&(r+=n,i(e=>({...e,transcript:r})),e?.(r))}},o=()=>{t.current&&t.current.stop()};return(0,G.useEffect)(()=>{if(!YNe())return;let n=new(window.SpeechRecognition||window.webkitSpeechRecognition);return t.current=n,n.continuous=!0,n.lang=e,n.onstart=()=>{i(e=>({...e,isListening:!0,error:null,transcript:``}))},n.onerror=e=>{i(t=>({...t,error:`Error: ${e.error}`}))},n.onend=()=>i(e=>({...e,isListening:!1})),()=>{try{n.stop()}catch{}n.onstart=null,n.onresult=null,n.onerror=null,n.onend=null,t.current=null}},[e]),{...r,error:n?r.error:JNe,start:a,stop:o}},ePe=({agent:e,language:t})=>{let[n,r]=(0,G.useState)({isListening:!1,transcript:``,error:null}),i=(0,G.useRef)(null),a=(0,G.useRef)(0),o=(0,G.useRef)(!1);(0,G.useEffect)(()=>()=>{a.current+=1,o.current=!1,i.current?.stop(),i.current=null},[e]);let s=(n,o)=>s=>{e&&n===a.current&&(i.current=null,r(e=>({...e,isListening:!1})),e.voice.listen(s,{language:t}).then(e=>{n===a.current&&(r(t=>({...t,transcript:e.text,error:null})),o?.(e.text))}).catch(e=>{if(n!==a.current)return;let t=e instanceof Error?e.message:`Failed to transcribe speech`;r(e=>({...e,error:t}))}))},c=t=>{if(!e||o.current||i.current)return;o.current=!0,a.current+=1;let n=a.current;KNe(s(n,t)).then(e=>{if(o.current=!1,n!==a.current)try{e.stop()}catch{}else i.current=e,r(e=>({...e,isListening:!0,error:null})),e.start()}).catch(e=>{if(o.current=!1,n!==a.current)return;let t=e instanceof Error?e.message:`Failed to start speech recording`;r(e=>({...e,isListening:!1,error:t}))})},l=()=>{i.current?(i.current.stop(),i.current=null):o.current&&(a.current+=1),o.current=!1,r(e=>({...e,isListening:!1}))};return{...n,start:c,stop:l}},tPe=({children:e,baseUrl:t,headers:n,apiPrefix:r,credentials:i,customFetch:a})=>(0,K.jsx)(Gue,{baseUrl:t,headers:n,apiPrefix:r,credentials:i,customFetch:a,children:e}),l_=(e,t)=>t?.(e)??null;(0,G.memo)(({step:e,Step:t,MapStep:n,AgentStep:r,ToolStep:i,ClassifierStep:a,ForEachStep:o,ParallelStep:s,Conditional:c,LoopStep:l,SleepStep:u,SleepUntilStep:d,NestedWorkflowStep:f,UnknownStep:p})=>{switch(e.kind){case`step`:return(0,K.jsx)(K.Fragment,{children:t?.(e)??l_(e,p)});case`map-step`:return(0,K.jsx)(K.Fragment,{children:n?.(e)??l_(e,p)});case`agent-step`:return(0,K.jsx)(K.Fragment,{children:r?.(e)??l_(e,p)});case`tool-step`:return(0,K.jsx)(K.Fragment,{children:i?.(e)??l_(e,p)});case`classifier-step`:return(0,K.jsx)(K.Fragment,{children:a?.(e)??l_(e,p)});case`foreach-step`:return(0,K.jsx)(K.Fragment,{children:o?.(e)??l_(e,p)});case`parallel-step`:return(0,K.jsx)(K.Fragment,{children:s?.(e)??l_(e,p)});case`conditional`:return(0,K.jsx)(K.Fragment,{children:c?.(e)??l_(e,p)});case`loop-step`:return(0,K.jsx)(K.Fragment,{children:l?.(e)??l_(e,p)});case`sleep-step`:return(0,K.jsx)(K.Fragment,{children:u?.(e)??l_(e,p)});case`sleep-until-step`:return(0,K.jsx)(K.Fragment,{children:d?.(e)??l_(e,p)});case`nested-workflow-step`:return(0,K.jsx)(K.Fragment,{children:f?.(e)??l_(e,p)});default:return(0,K.jsx)(K.Fragment,{children:l_(e,p)})}});var nPe=G.createContext(void 0),u_=e=>{let t=G.useContext(nPe);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},rPe=({client:e,children:t})=>(G.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,K.jsx)(nPe.Provider,{value:e,children:t})),iPe={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},d_=new class{#e=iPe;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function aPe(e){setTimeout(e,0)}var oPe=typeof window>`u`||`Deno`in globalThis;function f_(){}function sPe(e,t){return typeof e==`function`?e(t):e}function cPe(e){return typeof e==`number`&&e>=0&&e!==1/0}function lPe(e,t){return Math.max(e+(t||0)-Date.now(),0)}function p_(e,t){return typeof e==`function`?e(t):e}function uPe(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==fPe(o,t.options))return!1}else if(!h_(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function dPe(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(m_(t.options.mutationKey)!==m_(a))return!1}else if(!h_(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function fPe(e,t){return(t?.queryKeyHashFn||m_)(e)}function m_(e){return JSON.stringify(e,(e,t)=>gPe(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function h_(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){if(t.length>e.length)return!1;for(let n=0;n<t.length;n++)if(!h_(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!h_(e[r],t[r]))return!1;return!0}return!1}var pPe=Object.prototype.hasOwnProperty;function mPe(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=hPe(e)&&hPe(t);if(!r&&!(gPe(e)&&gPe(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:pPe.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=mPe(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function g_(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n of Object.keys(e))if(!pPe.call(t,n)||e[n]!==t[n])return!1;return!0}function hPe(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function gPe(e){if(!_Pe(e))return!1;let t=Object.getPrototypeOf(e),n=t?.constructor;if(n===void 0)return!0;if(typeof n!=`function`)return!1;let r=n.prototype;return!(!_Pe(r)||!r.hasOwnProperty(`isPrototypeOf`)||t!==Object.prototype)}function _Pe(e){return Object.prototype.toString.call(e)===`[object Object]`}function vPe(e){return new Promise(t=>{d_.setTimeout(t,e)})}function yPe(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:mPe(e,t)}function __(e){return e}function bPe(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(-n):r}function xPe(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,n):r}var v_=Symbol();function SPe(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===v_?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function CPe(e,t){return typeof e==`function`?e(...t):!!e}var wPe=Symbol();function TPe(e,t,n,r){let i=!1,a;return Object.defineProperties(e,{[wPe]:{value:r},signal:{enumerable:!0,get:()=>(a??=t(),i||(i=!0,a.aborted?n():a.addEventListener(`abort`,n,{once:!0})),a)}}),e}var EPe=()=>oPe,DPe=()=>EPe(),y_=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(){}},OPe=new class extends y_{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},kPe=aPe;function APe(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=kPe,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var b_=APe(),x_=new class extends y_{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let 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.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function jPe(e){return Math.min(1e3*2**e,3e4)}function MPe(e){return(e??`online`)!==`online`||x_.isOnline()}var NPe=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function PPe(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(f_);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new NPe(t);h(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},f=()=>OPe.isFocused()&&(e.networkMode===`always`||x_.isOnline())&&e.canRun(),p=()=>MPe(e.networkMode)&&e.canRun(),m=e=>{c()||(r?.(),i=`resolved`,a(e))},h=e=>{c()||(r?.(),i=`rejected`,o(e))},g=t=>new Promise(n=>{r=e=>{(c()||t())&&n(e)},e.onPause?.()}).then(()=>{r=void 0,c()||e.onContinue?.()}),_=()=>{if(c())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(m).catch(r=>{if(c())return;let i=e.retry??(DPe()?0:3),a=e.retryDelay??jPe,o=typeof a==`function`?a(n,r):a,s=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);t||!s?h(r):(n++,e.onFail?.(n,r),vPe(o).then(()=>c()||f()?void 0:g(f)).then(()=>{t?h(r):_()}))})};return{promise:s,status:()=>i,cancel:l,continue:()=>(r?.(),s),cancelRetry:u,continueRetry:d,canStart:p,start:()=>(p()?_():g(p).then(_),s)}}var FPe=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),cPe(this.gcTime)&&(this.#e=d_.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(DPe()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(d_.clearTimeout(this.#e),this.#e=void 0)}};function IPe(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=t,u=e=>{TPe(e,()=>t.signal,()=>n=!0,l[wPe])},d=SPe(t.options,t.fetchOptions),f=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return u(e),e})(),o=await d(a),{maxPages:s}=t.options,c=i?xPe:bPe;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?RPe:LPe,n={pages:a,pageParams:o};s=await f(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]===void 0?r.initialPageParam:o[0]:LPe(r,s);if(c>0&&e==null)break;s=await f(s,e),c++}while(c<t)}return s};t.fetchFn=t.options.persister?()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function LPe(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function RPe(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function zPe(e,t){return t?LPe(e,t)!=null:!1}function BPe(e,t){return!t||!e.getPreviousPageParam?!1:RPe(e,t)!=null}var VPe=class extends FPe{#e;#t;#n;#r;#i;#a;#o;#s;#c;constructor(e){super(),this.#c=!1,this.#s=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=WPe(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#s,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=WPe(this.options);e.data!==void 0&&(this.setState(UPe(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=yPe(this.state.data,e,this.options);return this.#l({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(f_).catch(f_):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>p_(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===v_||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.state.data!==void 0&&this.getObserversCount()>0&&this.observers.some(e=>p_(e.options.staleTime,this)===`static`)}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:!lPe(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){let t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#a&&(this.#c||this.state.fetchStatus===`paused`&&this.state.status===`pending`?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#l({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a&&this.#o)return this.#a.continueRetry(),this.#o}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperties(e,{[wPe]:{value:n.signal,enumerable:!0},signal:{enumerable:!0,get:()=>(this.#c=!0,n.signal)}})},i=()=>{let e=SPe(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#c=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?IPe(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#l({type:`fetch`,meta:a.fetchOptions?.meta});let o=this.#a=PPe({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof NPe&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#l({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#l({type:`pause`})},onContinue:()=>{this.#l({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}),s=(async()=>{try{let e=await o.promise;if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof NPe){if(e.silent){if(this.#a!==o&&this.#o)return this.#o;throw e}if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#l({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.#a===o&&(this.#a=void 0,this.#o=void 0),this.scheduleGc()}})();return this.#o=s,o.start(),s}#l(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...HPe(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...UPe(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),b_.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function HPe(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:MPe(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function UPe(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function WPe(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var S_=class extends y_{#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),KPe(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return qPe(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return qPe(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let 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 p_(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!g_(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&JPe(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||p_(this.options.enabled,this.#t)!==p_(t.enabled,this.#t)||p_(this.options.staleTime,this.#t)!==p_(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||p_(this.options.enabled,this.#t)!==p_(t.enabled,this.#t)||i!==this.#f)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return g_(this.getCurrentResult(),n)||(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),Reflect.get(e,n))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t),r=()=>{},i,a=new Promise(e=>{i=e,r=this.#e.getQueryCache().subscribe(i=>{i.type===`updated`&&i.query.queryHash===n.queryHash&&n.state.data!==void 0&&(r(),e(this.createResult(n,t)))})});return Promise.race([n.fetch(t).then(()=>{let e=this.createResult(n,t);return i?.(e),e}).finally(()=>{r()}),a])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#m(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(f_)),t}#h(e){return!DPe()&&p_(this.options.enabled,this.#t)!==!1&&cPe(e)}#g(){this.#b();let e=p_(this.options.staleTime,this.#t);if(this.#r.isStale||!this.#h(e))return;let t=lPe(this.#r.dataUpdatedAt,e)+1;this.#u=d_.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return p_(this.options.refetchInterval,this.#t)??!1}#v(e){this.#x(),this.#f=e,this.#f!==0&&this.#h(this.#f)&&(this.#d=d_.setInterval(()=>{(this.options.refetchIntervalInBackground||OPe.isFocused())&&this.#m()},this.#f))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#u!==void 0&&(d_.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(d_.clearInterval(this.#d),this.#d=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&KPe(e,t),o=i&&JPe(e,n,t,r);(a||o)&&(l={...l,...HPe(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#l?.state.data,this.#l):t.placeholderData,e!==void 0&&(m=`success`,d=yPe(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h){if(i&&d===a?.data&&t.select===this.#s)d=this.#c;else try{this.#s=t.select,d=t.select(d),d=yPe(i?.data,d,t),this.#c=d,this.#o=null}catch(e){this.#o=e}}else d===void 0&&(this.#o=null);this.#o&&(f=this.#o,d=this.#c,p=Date.now(),m=`error`,u=!1);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,y=_&&g,b=d!==void 0;return{status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:y,isLoading:y,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!b,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&b,isStale:YPe(e,t),refetch:this.refetch,isEnabled:p_(t.enabled,e)!==!1}}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);if(this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#l=this.#t),g_(t,e))return;this.#r=t;let n=(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#p.size||this.options.throwOnError&&this.#r.error!==e.error)return!0;for(let t of n??this.#p)if(this.#r[t]!==e[t])return!0;return!1})();b_.batch(()=>{n&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}};function GPe(e,t){return p_(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||p_(t.retryOnMount,e)!==!1)}function KPe(e,t){return GPe(e,t)||e.state.data!==void 0&&qPe(e,t,t.refetchOnMount)}function qPe(e,t,n){if(p_(t.enabled,e)!==!1&&p_(t.staleTime,e)!==`static`){let r=p_(n,e);return r===`always`||r!==!1&&YPe(e,t)}return!1}function JPe(e,t,n,r){return(e!==t||p_(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&YPe(e,n)}function YPe(e,t){return p_(t.enabled,e)!==!1&&e.isStaleByTime(p_(t.staleTime,e))}var XPe=class extends S_{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type=`infinite`,super.setOptions(e)}getOptimisticResult(e){return e._type=`infinite`,super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:`forward`}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:`backward`}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:a,isError:o,isRefetchError:s}=r,c=n.fetchMeta?.fetchMore?.direction,l=o&&c===`forward`,u=i&&c===`forward`,d=o&&c===`backward`,f=i&&c===`backward`;return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:zPe(t,n.data),hasPreviousPage:BPe(t,n.data),isFetchNextPageError:l,isFetchingNextPage:u,isFetchPreviousPageError:d,isFetchingPreviousPage:f,isRefetchError:s&&!l&&!d,isRefetching:a&&!u&&!f}}},ZPe=class extends FPe{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||QPe(),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.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??(this.state.status===`pending`?this.execute(this.state.variables):Promise.resolve())}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},r=this.#r=PPe({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),i=this.state.status===`pending`,a=!r.canStart();try{if(i)t();else{this.#i({type:`pending`,variables:e,isPaused:a}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:a})}this.state.isPaused&&r.canStart()&&t();let o=await r.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#i({type:`success`,data:o}),o}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#r===r&&(this.#r=void 0),this.#n.runNext(this)}}#i(e){let t=t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,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{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}};this.state=t(this.state),b_.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function QPe(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var $Pe=class extends y_{#e;#t;#n;constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}build(e,t,n){let r=new ZPe({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=C_(e);if(typeof t==`string`){let 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)){let t=C_(e);if(typeof t==`string`){let n=this.#t.get(t);if(n){if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=C_(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}return!0}runNext(e){let t=C_(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){b_.batch(()=>{let e=this.getAll();this.#e.clear(),this.#t.clear(),e.forEach(e=>{this.notify({type:`removed`,mutation:e})})})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>dPe(t,e))}findAll(e={}){return this.getAll().filter(t=>dPe(e,t))}notify(e){b_.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return b_.batch(()=>Promise.all(e.map(e=>e.continue().catch(f_))))}};function C_(e){return e.options.scope?.id}var eFe=class extends y_{#e;#t=void 0;#n;#r;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),g_(this.options,t)||this.#e.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&m_(t.mutationKey)!==m_(this.options.mutationKey)?this.reset():this.#n?.state.status===`pending`&&this.#n.setOptions(this.options)}onSubscribe(){this.listeners.size===1&&this.#n&&(this.#n.addObserver(this),this.#i())}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#i(),this.#a()}mutate(e,t){return this.#r=t,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(e)}#i(){let e=this.#n?.state??QPe();this.#t={...e,isPending:e.status===`pending`,isSuccess:e.status===`success`,isError:e.status===`error`,isIdle:e.status===`idle`,mutate:this.mutate,reset:this.reset}}#a(e){b_.batch(()=>{let t=this.#r;if(t&&this.hasListeners()){let n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type===`success`){try{t.onSuccess?.(e.data,n,r,i)}catch(e){Promise.reject(e)}try{t.onSettled?.(e.data,null,n,r,i)}catch(e){Promise.reject(e)}}else if(e?.type===`error`){try{t.onError?.(e.error,n,r,i)}catch(e){Promise.reject(e)}try{t.onSettled?.(void 0,e.error,n,r,i)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}};function tFe(e,t){let n=new Set(t);return e.filter(e=>!n.has(e))}var nFe=class extends y_{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l=[];constructor(e,t,n){super(),this.#e=e,this.#r=n,this.#n=[],this.#i=[],this.#t=[],this.setQueries(t)}onSubscribe(){this.listeners.size===1&&this.#i.forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,this.#i.forEach(e=>{e.destroy()})}setQueries(e,t){this.#n=e,this.#r=t,b_.batch(()=>{let e=this.#i,t=this.#p(this.#n);t.forEach(e=>e.observer.setOptions(e.defaultedQueryOptions));let n=t.map(e=>e.observer),r=n.map(e=>e.getCurrentResult()),i=e.length!==n.length,a=n.some((t,n)=>t!==e[n]),o=i||a,s=o?!0:r.some((e,t)=>{let n=this.#t[t];return!n||!g_(e,n)});(o||s)&&(o&&(this.#l=t,this.#i=n),this.#t=r,this.hasListeners()&&(o&&(tFe(e,n).forEach(e=>{e.destroy()}),tFe(n,e).forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})),this.#h()))})}getCurrentResult(){return this.#t}getQueries(){return this.#i.map(e=>e.getCurrentQuery())}getObservers(){return this.#i}getOptimisticResult(e,t){let n=this.#p(e),r=n.map(e=>e.observer.getOptimisticResult(e.defaultedQueryOptions)),i=n.map(e=>e.defaultedQueryOptions.queryHash);return[r,e=>this.#d(e??r,t,i),()=>this.#u(r,n)]}#u(e,t){let n=new Set;return t.map((r,i)=>{let a=e[i];return r.defaultedQueryOptions.notifyOnChangeProps?a:r.observer.trackResult(a,e=>{n.has(e)||(n.add(e),t.forEach(t=>{t.observer.trackProp(e)}))})})}#d(e,t,n){if(t){let r=this.#c,i=n!==void 0&&r!==void 0&&(r.length!==n.length||n.some((e,t)=>e!==r[t]));return(this.#t!==this.#s||i||t!==this.#o)&&(this.#o=t,this.#s=this.#t,n!==void 0&&(this.#c=n),this.#a=mPe(this.#a,t(e))),this.#a}return e}#f(){return!this.#r?.combine||this.#i.some((e,t)=>e.options.suspense&&this.#t[t]?.data===void 0)}#p(e){let t=new Map;this.#i.forEach(e=>{let n=e.options.queryHash;if(!n)return;let r=t.get(n);r?r.push(e):t.set(n,[e])});let n=[];return e.forEach(e=>{let r=this.#e.defaultQueryOptions(e),i=t.get(r.queryHash)?.shift()??new S_(this.#e,r);n.push({defaultedQueryOptions:r,observer:i})}),n}#m(e,t){let n=this.#i.indexOf(e);n!==-1&&(this.#t=this.#t.slice(),this.#t[n]=t,this.#h())}#h(){if(this.hasListeners()){let e=this.#f(),t=this.#a,n=e?t:this.#d(this.#u(this.#t,this.#l),this.#r?.combine);(e||t!==n)&&b_.batch(()=>{this.listeners.forEach(e=>{e(this.#t)})})}}},rFe=class extends y_{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){let r=t.queryKey,i=t.queryHash??fPe(r,t),a=this.get(i);return a||(a=new VPe({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){this.#e.get(e.queryHash)===e&&(e.destroy(),this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){b_.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>uPe(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>uPe(e,t)):t}notify(e){b_.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){b_.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){b_.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},iFe=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new rFe,this.#t=e.mutationCache||new $Pe,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=OPe.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=x_.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(p_(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=sPe(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return b_.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;b_.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return b_.batch(()=>{let r=n.findAll(e),i=new Set(r);return r.forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,predicate:e=>i.has(e)},t)})}cancelQueries(e,t={}){let n={revert:!0,...t},r=b_.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(f_).catch(f_)}invalidateQueries(e,t={}){return b_.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=b_.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n),r=e.state.fetchStatus===`paused`;return(!n.throwOnError||r)&&(t=t.catch(f_)),r?Promise.resolve():t}));return Promise.all(r).then(f_)}async query(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t),r=n.isStaleByTime(p_(t.staleTime,n))?await n.fetch(t):n.state.data,i=t.select;return i?i(r):r}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(p_(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(f_).catch(f_)}infiniteQuery(e){return e._type=`infinite`,this.query(e)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(f_).catch(f_)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return x_.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(m_(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{h_(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(m_(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{h_(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=fPe(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===v_&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},aFe=G.createContext(!1),oFe=()=>G.useContext(aFe);aFe.Provider;function sFe(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var cFe=G.createContext(sFe()),lFe=()=>G.useContext(cFe),uFe=(e,t,n)=>{let r=n?.state.status===`error`&&typeof e.throwOnError==`function`?CPe(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},dFe=e=>{G.useEffect(()=>{e.clearReset()},[e])},fFe=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||CPe(n,[e.error,r])),pFe=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},mFe=(e,t)=>e?.suspense&&t.isPending,hFe=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function w_({queries:e,...t},n){let r=u_(n),i=oFe(),a=lFe(),o=t.subscribed!==!1,s=G.useMemo(()=>e.map(e=>{let t=r.defaultQueryOptions(e);return t._optimisticResults=i?`isRestoring`:o?`optimistic`:void 0,t}),[e,r,i,o]);s.forEach(e=>{pFe(e);let t=r.getQueryCache().get(e.queryHash);uFe(e,a,t)}),dFe(a);let[c]=G.useState(()=>new nFe(r,s,t)),[l,u,d]=c.getOptimisticResult(s,t.combine);G.useEffect(()=>{c.setQueries(s,t)},[s,t,c]);let f=!i&&o;G.useSyncExternalStore(G.useCallback(e=>f?c.subscribe(b_.batchCalls(e)):f_,[c,f]),()=>c.getCurrentResult(),()=>c.getCurrentResult());let p=l.some((e,t)=>mFe(s[t],e))?l.flatMap((e,t)=>{let n=s[t];return n&&mFe(n,e)?hFe(n,new S_(r,n),a):[]}):[];if(p.length>0)throw Promise.all(p);let m=l.find((e,t)=>{let n=s[t];return n&&fFe({result:e,errorResetBoundary:a,throwOnError:n.throwOnError,query:r.getQueryCache().get(n.queryHash),suspense:n.suspense})});if(m)throw m.error;return u(d())}function gFe(e,t,n){let r=oFe(),i=lFe(),a=u_(n),o=a.defaultQueryOptions(e),s=a.getQueryCache().get(o.queryHash),c=e.subscribed!==!1;o._optimisticResults=r?`isRestoring`:c?`optimistic`:void 0,pFe(o),uFe(o,i,s),dFe(i);let[l]=G.useState(()=>new t(a,o)),u=l.getOptimisticResult(o);G.useEffect(()=>{l.setOptions(o)},[o,l]);let d=!r&&c;if(G.useSyncExternalStore(G.useCallback(e=>{let t=d?l.subscribe(b_.batchCalls(e)):f_;return l.updateResult(),t},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),mFe(o,u))throw hFe(o,l,i);if(fFe({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw u.error;return o.notifyOnChangeProps?u:l.trackResult(u)}function T_(e,t){return gFe(e,S_,t)}function E_(e){return e}function D_(e,t){let n=u_(t),[r]=G.useState(()=>new eFe(n,e));G.useEffect(()=>{r.setOptions(e)},[r,e]);let i=G.useSyncExternalStore(G.useCallback(e=>r.subscribe(b_.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=G.useCallback((...e)=>{r.mutate(e[0],e[1]).catch(f_)},[r]);if(i.error&&CPe(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}function O_(e,t){return gFe(e,XPe,t)}function k_(e){return`user`in e&&e.user!==void 0}async function _Fe(e,t,n){return fetch(t,n)}function vFe(e,t){return(e,t)=>fetch(e,t)}var yFe=new WeakMap,bFe=0;function xFe(e){let t=yFe.get(e);if(t!==void 0)return t;let n=bFe++;return yFe.set(e,n),n}async function SFe(e,{redirectUri:t}){let{baseUrl:n=``,apiPrefix:r,headers:i={}}=e.options,a=(r||`/api`).trim(),o=(a.startsWith(`/`)?a:`/${a}`).replace(/\/$/,``),s=new URLSearchParams;t&&s.set(`redirect_uri`,t);let c=`${n}${o}/auth/sso/login${s.toString()?`?${s}`:``}`,l=await fetch(c,{credentials:`include`,headers:{...i,"Content-Type":`application/json`}});if(!l.ok)throw Error(`Failed to initiate SSO login: ${l.status}`);return l.json()}async function CFe(e){let{baseUrl:t=``,headers:n={},apiPrefix:r}=e.options,i=(r||`/api`).trim(),a=(i.startsWith(`/`)?i:`/${i}`).replace(/\/$/,``),o=await fetch(`${t}${a}/auth/capabilities`,{credentials:`include`,headers:{...n,"Content-Type":`application/json`}});if(!o.ok)throw Error(`Failed to fetch auth capabilities: ${o.status}`);return o.json()}function A_({queryOptions:e}={}){let t=Y();return T_({queryKey:[`auth`,`capabilities`,xFe(t)],queryFn:()=>CFe(t),staleTime:6e4,retry:!1,placeholderData:__,...e})}var wFe=3,TFe=8e3,EFe=class extends Error{status;constructor(e){super(`Failed to fetch current user: ${e}`),this.status=e,this.name=`CurrentUserError`}};function DFe(e){return e instanceof EFe&&e.status===401}function j_({queryOptions:e}={}){let t=Y().options?.baseUrl||``;return T_({queryKey:[`auth`,`me`],queryFn:async()=>{let e=await _Fe(t,`${t}/api/auth/me`,{credentials:`include`,headers:{"Content-Type":`application/json`}});if(!e.ok)throw new EFe(e.status);return e.json()},staleTime:6e4,retry:(e,t)=>!(t instanceof EFe)||t.status!==503?!1:e<wFe,retryDelay:e=>Math.min(TFe,500*2**e),...e})}var OFe=({queryOptions:e}={})=>{let t=Y(),{data:n,isLoading:r,error:i}=A_(),a=!!(n&&k_(n)&&n.capabilities.rbac),{data:o,isLoading:s,error:c}=T_({queryKey:[`permission-patterns`,xFe(t)],queryFn:()=>t.getPermissionPatterns(),enabled:a,retry:!1,staleTime:1/0,placeholderData:__,...e});return{patterns:(0,G.useMemo)(()=>new Set(o?.patterns??[]),[o]),isLoading:r||a&&s,error:i||c}};async function kFe(e,{email:t,password:n}){let{baseUrl:r=``,apiPrefix:i,headers:a={}}=e.options||{},o=(i??`/api`).trim(),s=(o===``?``:o.startsWith(`/`)?o:`/${o}`).replace(/\/+$/,``),c=await fetch(`${r}${s}/auth/credentials/sign-in`,{method:`POST`,credentials:`include`,headers:{...a,"Content-Type":`application/json`},body:JSON.stringify({email:t,password:n})}),l=await c.json();if(!c.ok)throw Error(l.message||l.error||`Invalid email or password`);return l}function AFe({queryOptions:e}={}){let t=Y(),n=u_();return D_({mutationFn:({email:e,password:n})=>kFe(t,{email:e,password:n}),onSuccess:()=>{n.invalidateQueries({queryKey:[`auth`]})},...e})}async function jFe(e,{email:t,password:n,name:r}){let{baseUrl:i=``,apiPrefix:a,headers:o={}}=e.options||{},s=(a??`/api`).trim(),c=(s===``?``:s.startsWith(`/`)?s:`/${s}`).replace(/\/+$/,``),l=await fetch(`${i}${c}/auth/credentials/sign-up`,{method:`POST`,credentials:`include`,headers:{...o,"Content-Type":`application/json`},body:JSON.stringify({email:t,password:n,name:r})}),u=await l.json();if(!l.ok)throw Error(u.message||u.error||`Failed to create account`);return u}function MFe({queryOptions:e}={}){let t=Y(),n=u_();return D_({mutationFn:({email:e,password:n,name:r})=>jFe(t,{email:e,password:n,name:r}),onSuccess:()=>{n.invalidateQueries({queryKey:[`auth`]})},...e})}function NFe({queryOptions:e}={}){let t=Y();return D_({mutationFn:({redirectUri:e})=>SFe(t,{redirectUri:e}),...e})}async function PFe(e){let{baseUrl:t=``,apiPrefix:n,headers:r={}}=e.options,i=(n||`/api`).trim(),a=(i.startsWith(`/`)?i:`/${i}`).replace(/\/$/,``),o=await fetch(`${t}${a}/auth/logout`,{method:`POST`,credentials:`include`,headers:{...r,"Content-Type":`application/json`}});if(!o.ok)throw Error(`Failed to logout: ${o.status}`);return o.json()}function FFe({onLoggedOut:e,queryOptions:t}={}){let n=Y(),r=u_();return D_({mutationFn:async t=>{let r=await PFe(n);return await e?.(t).catch(()=>{}),r},onSuccess:()=>{r.invalidateQueries({queryKey:[`auth`]})},...t})}var M_=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,N_=/^[\\/]{2}/;function IFe(e,t){return t+e.replace(/\\/g,`/`)}var LFe=`popstate`;function RFe(e){return typeof e==`object`&&!!e&&`pathname`in e&&`search`in e&&`hash`in e&&`state`in e&&`key`in e}function zFe(e={}){function t(e,t){let n=t.state?.masked,{pathname:r,search:i,hash:a}=n||e.location;return I_(``,{pathname:r,search:i,hash:a},t.state&&t.state.usr||null,t.state&&t.state.key||`default`,n?{pathname:e.location.pathname,search:e.location.search,hash:e.location.hash}:void 0)}function n(e,t){return typeof t==`string`?t:L_(t)}return HFe(t,n,null,e)}function P_(e,t){if(e===!1||e==null)throw Error(t)}function F_(e,t){if(!e){typeof console<`u`&&console.warn(t);try{throw Error(t)}catch{}}}function BFe(){return Math.random().toString(36).substring(2,10)}function VFe(e,t){return{usr:e.state,key:e.key,idx:t,masked:e.mask?{pathname:e.pathname,search:e.search,hash:e.hash}:void 0}}function I_(e,t,n=null,r,i){return{pathname:typeof e==`string`?e:e.pathname,search:``,hash:``,...typeof t==`string`?R_(t):t,state:n,key:t&&t.key||r||BFe(),mask:i}}function L_({pathname:e=`/`,search:t=``,hash:n=``}){return t&&t!==`?`&&(e+=t.charAt(0)===`?`?t:`?`+t),n&&n!==`#`&&(e+=n.charAt(0)===`#`?n:`#`+n),e}function R_(e){let t={};if(e){let n=e.indexOf(`#`);n>=0&&(t.hash=e.substring(n),e=e.substring(0,n));let r=e.indexOf(`?`);r>=0&&(t.search=e.substring(r),e=e.substring(0,r)),e&&(t.pathname=e)}return t}function HFe(e,t,n,r={}){let{window:i=document.defaultView,v5Compat:a=!1}=r,o=i.history,s=`POP`,c=null,l=u();l??(l=0,o.replaceState({...o.state,idx:l},``));function u(){return(o.state||{idx:null}).idx}function d(){s=`POP`;let e=u(),t=e==null?null:e-l;l=e,c&&c({action:s,location:h.location,delta:t})}function f(e,t){s=`PUSH`;let r=RFe(e)?e:I_(h.location,e,t);n&&n(r,e),l=u()+1;let d=VFe(r,l),f=h.createHref(r.mask||r);try{o.pushState(d,``,f)}catch(e){if(e instanceof DOMException&&e.name===`DataCloneError`)throw e;i.location.assign(f)}a&&c&&c({action:s,location:h.location,delta:1})}function p(e,t){s=`REPLACE`;let r=RFe(e)?e:I_(h.location,e,t);n&&n(r,e),l=u();let i=VFe(r,l),d=h.createHref(r.mask||r);o.replaceState(i,``,d),a&&c&&c({action:s,location:h.location,delta:0})}function m(e){return UFe(i,e)}let h={get action(){return s},get location(){return e(i,o)},listen(e){if(c)throw Error(`A history only accepts one active listener`);return i.addEventListener(LFe,d),c=e,()=>{i.removeEventListener(LFe,d),c=null}},createHref(e){return t(i,e)},createURL:m,encodeLocation(e){let t=m(e);return{pathname:t.pathname,search:t.search,hash:t.hash}},push:f,replace:p,go(e){return o.go(e)}};return h}function UFe(e,t,n=!1){let r=`http://localhost`;e&&(r=e.location.origin===`null`?e.location.href:e.location.origin),P_(r,`No window.location.(origin|href) available to create URL`);let i=typeof t==`string`?t:L_(t);return i=i.replace(/ $/,`%20`),!n&&N_.test(i)&&(i=r+i),new URL(i,r)}var WFe=class{#e=new Map;constructor(e){if(e)for(let[t,n]of e)this.set(t,n)}get(e){if(this.#e.has(e))return this.#e.get(e);if(e.defaultValue!==void 0)return e.defaultValue;throw Error(`No value found for context`)}set(e,t){this.#e.set(e,t)}},GFe=class extends Error{},KFe=new Set([`lazy`,`caseSensitive`,`path`,`id`,`index`,`children`,`unstable_validateParams`]);function qFe(e){return KFe.has(e)}var JFe=new Set([`lazy`,`caseSensitive`,`path`,`id`,`index`,`middleware`,`children`,`unstable_validateParams`]);function YFe(e){return JFe.has(e)}function XFe(e){return e.index===!0}function ZFe(e){let t={};return e.Component&&Object.assign(t,{element:G.createElement(e.Component),Component:void 0}),e.HydrateFallback&&Object.assign(t,{hydrateFallbackElement:G.createElement(e.HydrateFallback),HydrateFallback:void 0}),e.ErrorBoundary&&Object.assign(t,{errorElement:G.createElement(e.ErrorBoundary),ErrorBoundary:void 0}),t}function z_(e,t=ZFe,n=[],r={},i=!1){return e.map((e,a)=>{let o=[...n,String(a)],s=typeof e.id==`string`?e.id:o.join(`-`);if(P_(e.index!==!0||!e.children,`Cannot specify children on an index route`),P_(i||!r[s],`Found a route id collision on id "${s}". Route id's must be globally unique within Data Router usages`),XFe(e)){let n={...e,id:s};return r[s]=QFe(n,t(n)),n}{let n={...e,id:s,children:void 0};return r[s]=QFe(n,t(n)),e.children&&(n.children=z_(e.children,t,o,r,i)),n}})}function QFe(e,t){return Object.assign(e,{...t,...typeof t.lazy==`object`&&t.lazy!=null?{lazy:{...e.lazy,...t.lazy}}:{}})}function $Fe(e,t,n=`/`){return eIe(e,t,n,!1)}function eIe(e,t,n,r,i){let a=V_((typeof t==`string`?R_(t):t).pathname||`/`,n);if(a==null)return null;let o=i??nIe(e),s=null,c=bIe(a);for(let e=0;s==null&&e<o.length;++e)s=_Ie(o[e],c,r);return s}function tIe(e,t){let{route:n,pathname:r,params:i}=e;return{id:n.id,pathname:r,params:i,loaderData:t[n.id],handle:n.handle}}function nIe(e){let t=rIe(e);return aIe(t),t}function rIe(e,t=[],n=[],r=``,i=!1){let a=(e,a,o=i,s)=>{let c={relativePath:s===void 0?e.path||``:s,caseSensitive:e.caseSensitive===!0,childrenIndex:a,route:e};if(c.relativePath.startsWith(`/`)){if(!c.relativePath.startsWith(r)&&o)return;P_(c.relativePath.startsWith(r),`Absolute route path "${c.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),c.relativePath=c.relativePath.slice(r.length)}let l=W_([r,c.relativePath]),u=n.concat(c);e.children&&e.children.length>0&&(P_(e.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${l}".`),rIe(e.children,t,u,l,o)),(e.path!=null||e.index)&&t.push({path:l,score:hIe(l,e.index),routesMeta:u.map((e,t)=>{let[n,r]=yIe(e.relativePath,e.caseSensitive,t===u.length-1);return{...e,matcher:n,compiledParams:r}})})};return e.forEach((e,t)=>{if(e.path===``||!e.path?.includes(`?`))a(e,t);else for(let n of iIe(e.path))a(e,t,!0,n)}),t}function iIe(e){let t=e.split(`/`);if(t.length===0)return[];let[n,...r]=t,i=n.endsWith(`?`),a=n.replace(/\?$/,``);if(r.length===0)return i?[a,``]:[a];let o=iIe(r.join(`/`)),s=[];return s.push(...o.map(e=>e===``?a:[a,e].join(`/`))),i&&s.push(...o),s.map(t=>e.startsWith(`/`)&&t===``?`/`:t)}function aIe(e){e.sort((e,t)=>e.score===t.score?gIe(e.routesMeta.map(e=>e.childrenIndex),t.routesMeta.map(e=>e.childrenIndex)):t.score-e.score)}var oIe=/^:[\w-]+$/,sIe=/^:[\w-]+/,cIe=3.5,lIe=3,uIe=2,dIe=1,fIe=10,pIe=-2,mIe=e=>e===`*`;function hIe(e,t){let n=e.split(`/`),r=n.length;return n.some(mIe)&&(r+=pIe),t&&(r+=uIe),n.filter(e=>!mIe(e)).reduce((e,t)=>e+(oIe.test(t)?lIe:sIe.test(t)?cIe:t===``?dIe:fIe),r)}function gIe(e,t){return e.length===t.length&&e.slice(0,-1).every((e,n)=>e===t[n])?e[e.length-1]-t[t.length-1]:0}function _Ie(e,t,n=!1){let{routesMeta:r}=e,i={},a=`/`,o=[];for(let e=0;e<r.length;++e){let s=r[e],c=e===r.length-1,l=a===`/`?t:t.slice(a.length)||`/`,u={path:s.relativePath,caseSensitive:s.caseSensitive,end:c},d=s.matcher&&s.compiledParams?vIe(u,l,s.matcher,s.compiledParams):B_(u,l),f=s.route;if(!d&&c&&n&&!r[r.length-1].route.index&&(d=B_({path:s.relativePath,caseSensitive:s.caseSensitive,end:!1},l)),!d)return null;Object.assign(i,d.params),o.push({params:i,pathname:W_([a,d.pathname]),pathnameBase:OIe(W_([a,d.pathnameBase])),route:f}),d.pathnameBase!==`/`&&(a=W_([a,d.pathnameBase]))}return o}function B_(e,t){typeof e==`string`&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=yIe(e.path,e.caseSensitive,e.end);return vIe(e,t,n,r)}function vIe(e,t,n,r){let i=t.match(n);if(!i)return null;let a=i[0],o=G_(a,1),s=i.slice(1);return{params:r.reduce((e,{paramName:t,isOptional:n},r)=>{if(t===`*`){let e=s[r]||``;o=G_(a.slice(0,a.length-e.length),1)}let i=s[r];return e[t]=n&&!i?void 0:(i||``).replace(/%2F/g,`/`),e},{}),pathname:a,pathnameBase:o,pattern:e}}function yIe(e,t=!1,n=!0){F_(e===`*`||!e.endsWith(`*`)||e.endsWith(`/*`),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,`/*`)}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,`/*`)}".`);let r=[],i=`^`+e.replace(/\/*\*?$/,``).replace(/^\/*/,`/`).replace(/[\\.*+^${}|()[\]]/g,`\\$&`).replace(/\/:([\w-]+)(\?)?/g,(e,t,n,i,a)=>{if(r.push({paramName:t,isOptional:n!=null}),n){let t=a.charAt(i+e.length);return t&&t!==`/`?`/([^\\/]*)`:`(?:/([^\\/]*))?`}return`/([^\\/]+)`}).replace(/\/((?:[^/?()[\]*^\\]|\\.)+)\?(?=\/|$|\()/g,`(?:/$1)?`);return e.endsWith(`*`)?(r.push({paramName:`*`}),i+=e===`*`||e===`/*`?`(.*)$`:`(?:\\/(.+)|\\/*)$`):n?i+=`\\/*$`:e!==``&&e!==`/`&&(i+=`(?:(?=\\/|$))`),[new RegExp(i,t?void 0:`i`),r]}function bIe(e){try{return e.split(`/`).map(e=>decodeURIComponent(e).replace(/\//g,`%2F`)).join(`/`)}catch(t){return F_(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${t}).`),e}}function V_(e,t){if(t===`/`)return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith(`/`)?t.length-1:t.length,r=e.charAt(n);return r&&r!==`/`?null:e.slice(n)||`/`}function xIe({basename:e,pathname:t}){return t===`/`?e:W_([e,t])}var SIe=e=>M_.test(e);function CIe(e,t=`/`){let{pathname:n,search:r=``,hash:i=``}=typeof e==`string`?R_(e):e,a;return n?(n=DIe(n),a=n.startsWith(`/`)||n.startsWith(`\\`)?wIe(n.substring(1),`/`):wIe(n,t)):a=t,{pathname:a,search:kIe(r),hash:AIe(i)}}function wIe(e,t){let n=G_(t).split(`/`);return e.split(`/`).forEach(e=>{e===`..`?n.length>1&&n.pop():e!==`.`&&n.push(e)}),n.length>1?n.join(`/`):`/`}function TIe(e,t,n,r){return`Cannot include a '${e}' character in a manually specified \`to.${t}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function EIe(e){return e.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function H_(e){let t=EIe(e);return t.map((e,n)=>n===t.length-1?e.pathname:e.pathnameBase)}function U_(e,t,n,r=!1){let i;typeof e==`string`?i=R_(e):(i={...e},P_(!i.pathname||!i.pathname.includes(`?`),TIe(`?`,`pathname`,`search`,i)),P_(!i.pathname||!i.pathname.includes(`#`),TIe(`#`,`pathname`,`hash`,i)),P_(!i.search||!i.search.includes(`#`),TIe(`#`,`search`,`hash`,i)));let a=e===``||i.pathname===``,o=a?`/`:i.pathname,s;if(o==null)s=n;else{let e=t.length-1;if(!r&&o.startsWith(`..`)){let t=o.split(`/`);for(;t[0]===`..`;)t.shift(),--e;i.pathname=t.join(`/`)}s=e>=0?t[e]:`/`}let c=CIe(i,s),l=o&&o!==`/`&&o.endsWith(`/`),u=(a||o===`.`)&&n.endsWith(`/`);return!c.pathname.endsWith(`/`)&&(l||u)&&(c.pathname+=`/`),c}var DIe=e=>e.replace(/[\\/]{2,}/g,`/`),W_=e=>DIe(e.join(`/`));function G_(e,t=0){let n=e.length;for(;n>t&&e.charCodeAt(n-1)===47;)n--;return n===e.length?e:e.slice(0,n)}var OIe=e=>G_(e).replace(/^\/*/,`/`),kIe=e=>!e||e===`?`?``:e.startsWith(`?`)?e:`?`+e,AIe=e=>!e||e===`#`?``:e.startsWith(`#`)?e:`#`+e,K_=(e,t=302)=>{let n=t;typeof n==`number`?n={status:n}:n.status===void 0&&(n.status=302);let r=new Headers(n.headers);return r.set(`Location`,e),new Response(null,{...n,headers:r})},jIe=[`EvalError`,`RangeError`,`ReferenceError`,`SyntaxError`,`TypeError`,`URIError`],q_=class{status;statusText;data;error;internal;constructor(e,t,n,r=!1){this.status=e,this.statusText=t||``,this.internal=r,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function J_(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.internal==`boolean`&&`data`in e}function Y_(e){return W_(e.map(e=>e.route.path).filter(Boolean))||`/`}function MIe(e,t){let n=new URL(typeof e==`string`||e instanceof URL?e:e.url),r=typeof t==`string`?R_(t):t;if(n.pathname=r.pathname||`/`,r.search){let e=new URLSearchParams(r.search),t=e.getAll(`index`);e.delete(`index`);for(let n of t.filter(Boolean))e.append(`index`,n);let i=e.toString();n.search=i?`?${i}`:``}else n.search=``;return n.hash=r.hash||``,n}var NIe=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function PIe(e,t){let n=e;if(typeof n!=`string`||!M_.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,i=!1;if(NIe)try{let e=new URL(window.location.href),r=N_.test(n)?new URL(IFe(n,e.protocol)):new URL(n),a=V_(r.pathname,t);r.origin===e.origin&&a!=null?n=a+r.search+r.hash:i=!0}catch{F_(!1,`<Link to="${n}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:r,isExternal:i,to:n}}var FIe=Symbol(`Uninstrumented`),X_=new WeakMap;function IIe(e,t){let n={lazy:[],"lazy.loader":[],"lazy.action":[],"lazy.middleware":[],middleware:[],loader:[],action:[]};e.forEach(e=>e({id:t.id,index:t.index,path:t.path,instrument(e){e.lazy!=null&&n.lazy.push(e.lazy),e[`lazy.loader`]!=null&&n[`lazy.loader`].push(e[`lazy.loader`]),e[`lazy.action`]!=null&&n[`lazy.action`].push(e[`lazy.action`]),e[`lazy.middleware`]!=null&&n[`lazy.middleware`].push(e[`lazy.middleware`]),e.middleware!=null&&n.middleware.push(e.middleware),e.loader!=null&&n.loader.push(e.loader),e.action!=null&&n.action.push(e.action)}}));let r={};if(typeof t.lazy==`function`&&n.lazy.length>0){let e=t.lazy;r.lazy=async(...t)=>$_(await ev(n.lazy,void 0,()=>e(...t),tv))}if(typeof t.lazy==`object`){let e=t.lazy;if(typeof e.middleware==`function`&&n[`lazy.middleware`].length>0){let t=e.middleware;r.lazy=Object.assign(r.lazy||{},{middleware:async(...e)=>$_(await ev(n[`lazy.middleware`],void 0,()=>t(...e),tv))})}if(typeof e.loader==`function`&&n[`lazy.loader`].length>0){let t=e.loader;r.lazy=Object.assign(r.lazy||{},{loader:async(...e)=>$_(await ev(n[`lazy.loader`],void 0,()=>t(...e),tv))})}if(typeof e.action==`function`&&n[`lazy.action`].length>0){let t=e.action;r.lazy=Object.assign(r.lazy||{},{action:async(...e)=>$_(await ev(n[`lazy.action`],void 0,()=>t(...e),tv))})}}if(typeof t.loader==`function`&&n.loader.length>0){let e=Z_(t.loader),i=async(...t)=>$_(await ev(n.loader,BIe(t[0]),()=>e(...t),tv));e.hydrate===!0&&(i.hydrate=!0),Q_(i,e),r.loader=i}if(typeof t.action==`function`&&n.action.length>0){let e=Z_(t.action),i=async(...t)=>$_(await ev(n.action,BIe(t[0]),()=>e(...t),tv));Q_(i,e),r.action=i}return t.middleware&&t.middleware.length>0&&n.middleware.length>0&&(r.middleware=t.middleware.map(e=>{let t=Z_(e),r=async(...e)=>$_(await ev(n.middleware,BIe(e[0]),()=>t(...e),tv));return Q_(r,t),r})),r}function LIe(e,t){let n={navigate:[],fetch:[]};if(t.forEach(e=>e({instrument(e){e.navigate!=null&&n.navigate.push(e.navigate),e.fetch!=null&&n.fetch.push(e.fetch)}})),n.navigate.length>0){let t=Z_(e.navigate),r=async(...r)=>{let[i,a]=r,o,s={to:typeof i==`number`||typeof i==`string`?i:i?L_(i):`.`,...VIe(e,a??{})};return $_(await ev(n.navigate,s,async()=>{if(typeof i==`number`)return await t(...r);let n=RIe(e,e=>{o=e});try{return await t(...r)}finally{n()}},e=>({...tv(e),meta:o})))};Q_(r,t),e.navigate=r}if(n.fetch.length>0){let t=Z_(e.fetch),r=async(...r)=>{let[i,a,o,s]=r,c;return $_(await ev(n.fetch,{href:o??`.`,fetcherKey:i,...VIe(e,s??{})},async()=>{let n=RIe(e,e=>{c=e});try{return await t(...r)}finally{n()}},e=>({...tv(e),meta:c})))};Q_(r,t),e.fetch=r}return e}function Z_(e){return e[FIe]??e}function Q_(e,t){e[FIe]=t}function RIe(e,t){return X_.set(e,t),()=>{X_.get(e)===t&&X_.delete(e)}}function zIe(e){let t=X_.get(e);return X_.delete(e),t}function $_(e){if(e.type===`error`)throw e.value;return e.value}async function ev(e,t,n,r,i={result:null,innerResult:null},a=e.length-1){let o=e[a];if(o){let s,c=async()=>(s?console.error(`You cannot call instrumented handlers more than once`):s=ev(e,t,n,r,i,a-1),await s,P_(i.innerResult,`Expected an inner result`),i.innerResult);try{await o(c,t)}catch(e){console.error(`An instrumentation function threw an error:`,e)}s||await c(),await s}else{try{i.result={type:`success`,value:await n()}}catch(e){i.result={type:`error`,value:e}}i.innerResult=r(i.result,t)}return i.result||(i.result={type:`error`,value:Error(`No result assigned in instrumentation chain.`)},i.innerResult=r(i.result,t)),i.result}function tv(e){return e.type===`error`&&e.value instanceof Error?{status:`error`,error:e.value}:{status:`success`,error:void 0}}function BIe(e){let{request:t,context:n,params:r}=e;return{...e,request:HIe(t),params:{...r},context:UIe(n)}}function VIe(e,t){return{currentUrl:L_(e.state.location),...`formMethod`in t?{formMethod:t.formMethod}:{},...`formEncType`in t?{formEncType:t.formEncType}:{},...`formData`in t?{formData:t.formData}:{},...`body`in t?{body:t.body}:{}}}function HIe(e){return{method:e.method,url:e.url,headers:{get:(...t)=>e.headers.get(...t)}}}function UIe(e){return{get:t=>e.get(t)}}var WIe=class{#e=[];#t=[];#n;#r=0;constructor(e){this.#n=e}update(e){this.#e=e,this.#t=nIe(e),this.#r=this.#t.reduce((e,t)=>e+t.routesMeta.length,0)}get matchCost(){return this.#r}match(e,t=!1){return eIe(this.#e,e,this.#n,t,this.#t)}},GIe=new URL(`http://localhost`);function KIe(e){if(e.createURL)return e.createURL(`/`);try{return new URL(e.createHref(`/`),GIe)}catch{return GIe}}function qIe(e,t){return e.origin===t.origin&&(e.origin!==`null`||e.protocol===t.protocol&&e.host===t.host)}function JIe(e,t){if(e.startsWith(`//`))return!0;let n=t.protocol.toLowerCase();return e.toLowerCase().startsWith(n)?t.host===``||e.slice(n.length).startsWith(`//`):!1}function nv(e,t,n,r){let i=null;try{i=e==null?null:new URL(e,n)}catch{}let a=new URL(t,n),o=i!=null&&!qIe(i,n),s=!qIe(a,n);if(r===`reject`){if(o||s)throw Error(`External navigation is not allowed`)}else if(s&&(i==null||!JIe(e,i)||!qIe(i,a)))throw Error(`External navigation is not allowed`)}var YIe=[`POST`,`PUT`,`PATCH`,`DELETE`],XIe=new Set(YIe),ZIe=[`GET`,...YIe],QIe=new Set(ZIe),$Ie=new Set([301,302,303,307,308]),eLe=new Set([307,308]),rv={state:`idle`,location:void 0,matches:void 0,historyAction:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},tLe={state:`idle`,data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},iv={state:`unblocked`,proceed:void 0,reset:void 0,location:void 0},nLe=`remix-router-transitions`,rLe=Symbol(`ResetLoaderData`);function iLe(e,t){return e.unstable_routePatternMatching?(P_(void 0,`You must call unstable_preloadRoutePattern() from "react-router/route-pattern" before enabling future.unstable_routePatternMatching.`),new(void 0)(t)):new WIe(t)}var aLe=class{#e;#t;#n;constructor(e,t){this.#e=e,this.#n=t,this.#n.update(e)}get stableRoutes(){return this.#e}get activeRoutes(){return this.#t??this.#e}get hasHMRRoutes(){return this.#t!=null}setRoutes(e){this.#e=e,this.#t||this.#n.update(e)}setHmrRoutes(e){this.#t=e,this.#n.update(e)}commitHmrRoutes(){this.#t&&(this.#e=this.#t,this.#t=void 0,this.#n.update(this.#e))}},av=new WeakMap;function oLe(e){let t=e.window?e.window:typeof window<`u`?window:void 0,n=t!==void 0&&t.document!==void 0&&t.document.createElement!==void 0;P_(e.routes.length>0,`You must provide a non-empty routes array to createRouter`);let r=e.hydrationRouteProperties||[],i=e.mapRouteProperties,a=i||(()=>({}));if(e.instrumentations){let t=e.instrumentations;a=e=>({...i?.(e),...IIe(t.map(e=>e.route).filter(Boolean),e)})}let o={...e.future},s=e.basename||`/`;s.startsWith(`/`)||(s=`/${s}`);let c=iLe(o,s),l={},u=new aLe(z_(e.routes,a,void 0,l),c),d=e.dataStrategy||xLe,f=null,p=new Set,m=null,h=null,g=null,_=e.hydrationData!=null,v=c.match(e.history.location),y=!1,b=null,x,S;if(v==null&&!e.patchRoutesOnNavigation){let t=fv(404,{pathname:e.history.location.pathname}),{matches:n,route:r}=dv(u.activeRoutes);x=!0,S=!x,v=n,b={[r.id]:t}}else if(v&&!e.hydrationData&&Ue(v,e.history.location.pathname).active&&(v=null),!v){x=!1,S=!x,v=[];let t=Ue(null,e.history.location.pathname);t.active&&t.matches&&(y=!0,v=t.matches)}else if(v.some(e=>e.route.lazy))x=!1,S=!x;else if(!v.some(e=>dLe(e.route)))x=!0,S=!x;else{let t=e.hydrationData?e.hydrationData.loaderData:null,n=e.hydrationData?e.hydrationData.errors:null,r=v;if(n){let e=v.findIndex(e=>n[e.route.id]!==void 0);r=r.slice(0,e+1)}S=!1,x=!0,r.forEach(e=>{let r=fLe(e.route,t,n);S||=r.renderFallback,x&&=!r.shouldLoad})}let C,w={historyAction:e.history.action,location:e.history.location,matches:v,initialized:x,renderFallback:S,navigation:rv,restoreScrollPosition:e.hydrationData==null&&null,preventScrollReset:!1,revalidation:`idle`,loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||b,fetchers:new Map,blockers:new Map},T=`POP`,E=0,D,O=null,k=!1,A,j=!1,M=new Map,N=null,P=!1,F=!1,I=new Set,L=new Map,R=0,z=-1,B=new Map,V=new Set,H=new Map,ee=new Map,te=new Set,U=new Map,W,ne=null;function re(){if(f=e.history.listen(({action:t,location:n,delta:r})=>{if(W){W(),W=void 0;return}F_(U.size===0||r!=null,"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");let i=Le({currentLocation:w.location,nextLocation:n,historyAction:t});if(i&&r!=null){let t=new Promise(e=>{W=e});e.history.go(r*-1),Ie(i,{state:`blocked`,location:n,proceed(){Ie(i,{state:`proceeding`,proceed:void 0,reset:void 0,location:n}),t.then(()=>e.history.go(r))},reset(){let e=new Map(w.blockers);e.set(i,iv),oe({blockers:e})}}),O?.resolve(),O=null}else return o.unstable_customRouteDiscovery&&(E+=r||0),de(t,n)}),n){iRe(t,M);let e=()=>aRe(t,M);t.addEventListener(`pagehide`,e),N=()=>t.removeEventListener(`pagehide`,e)}return w.initialized||de(`POP`,w.location,{initialHydration:!0}),C}function ie(){f&&f(),N&&N(),p.clear(),A&&A.abort(),w.fetchers.forEach((e,t)=>Oe(w.fetchers,t)),w.blockers.forEach((e,t)=>Fe(t))}function ae(e){return p.add(e),()=>p.delete(e)}function oe(e,t={}){let n=e.errors??null,r=n?av.get(n):void 0;r!==void 0&&(n=r),(e.errors!==void 0||e.initialized)&&(w.errors&&av.delete(w.errors),e.errors&&av.set(e.errors,n)),e.matches&&=e.matches.map(e=>{let t=l[e.route.id],n=e.route;return n.element!==t.element||n.errorElement!==t.errorElement||n.hydrateFallbackElement!==t.hydrateFallbackElement?{...e,route:t}:e}),w={...w,...e};let i=[],a=[];w.fetchers.forEach((e,t)=>{e.state===`idle`&&(te.has(t)?i.push(t):a.push(t))}),te.forEach(e=>{!w.fetchers.has(e)&&!L.has(e)&&i.push(e)}),[...p].forEach(e=>e(w,{deletedFetchers:i,newErrors:n,viewTransitionOpts:t.viewTransitionOpts,flushSync:t.flushSync===!0})),i.forEach(e=>Oe(w.fetchers,e)),a.forEach(e=>w.fetchers.delete(e))}function se(t,n,{flushSync:r}={}){let i=w.actionData!=null&&w.navigation.formMethod!=null&&gv(w.navigation.formMethod)&&w.navigation.state===`loading`&&t.state?._isRedirect!==!0,a;a=n.actionData?Object.keys(n.actionData).length>0?n.actionData:null:i?w.actionData:null;let o=n.loaderData?zLe(w.loaderData,n.loaderData,n.matches||[],n.errors):w.loaderData,s=w.blockers;s.size>0&&!P&&(s=new Map(s),s.forEach((e,t)=>s.set(t,iv)));let c=!P&&He(t,n.matches||w.matches),l=k===!0||w.navigation.formMethod!=null&&gv(w.navigation.formMethod)&&t.state?._isRedirect!==!0;u.commitHmrRoutes(),P||T===`POP`||(T===`PUSH`?e.history.push(t,t.state):T===`REPLACE`&&e.history.replace(t,t.state));let d;if(T===`POP`&&!P&&t!==w.location){let e=M.get(w.location.pathname);e&&e.has(t.pathname)?d={currentLocation:w.location,nextLocation:t}:M.has(t.pathname)&&(d={currentLocation:t,nextLocation:w.location})}else if(j){let e=M.get(w.location.pathname);e?e.add(t.pathname):(e=new Set([t.pathname]),M.set(w.location.pathname,e)),d={currentLocation:w.location,nextLocation:t}}oe({...n,actionData:a,loaderData:o,historyAction:T,location:t,initialized:!0,renderFallback:!1,navigation:rv,revalidation:`idle`,restoreScrollPosition:c,preventScrollReset:l,blockers:s},{viewTransitionOpts:d,flushSync:r===!0}),ce(),O?.resolve(),O=null,ne?.resolve(),ne=null}function ce(){E=0,T=`POP`,k=!1,j=!1,P=!1,F=B.size>0}async function le(t,n){if(D&&await D,O?.resolve(),O=null,typeof t==`number`){O||=oRe();let n=O.promise;return e.history.go(t),n}let r=zIe(C),{path:i,submission:a,error:o}=lLe(!1,cLe(w.location,w.matches,s,t,n?.fromRouteId,n?.relative),n),c;if(n?.mask){let t=typeof n.mask==`string`?R_(n.mask):{...w.location.mask,...n.mask};if(c={pathname:t.pathname??``,search:t.search??``,hash:t.hash??``},N_.test(c.pathname))throw Error(`External navigation is not allowed`);c.pathname.startsWith(`\\`)&&(c.pathname=c.pathname.replace(/^\\+/,`/`)),nv(typeof n.mask==`string`?n.mask:L_(n.mask),L_(c),e.history.createURL(`/`),`reject`)}let l=w.location,u=I_(l,i,n&&n.state,void 0,c);u={...u,...e.history.encodeLocation(u)},nv(t==null?e.history.createHref(w.location):typeof t==`string`?t:L_(t),e.history.createHref(u.mask||u),e.history.createURL(`/`),`reject`);let d=n&&n.replace!=null?n.replace:void 0,f=`PUSH`,p=w.location.pathname+w.location.search;d===!0?f=`REPLACE`:d===!1||a!=null&&gv(a.formMethod)&&(a.formAction===p||u.pathname+u.search===p)&&(f=`REPLACE`);let m=n&&`preventScrollReset`in n?n.preventScrollReset===!0:void 0,h=(n&&n.flushSync)===!0,g=Le({currentLocation:l,nextLocation:u,historyAction:f});g?Ie(g,{state:`blocked`,location:u,proceed(){Ie(g,{state:`proceeding`,proceed:void 0,reset:void 0,location:u}),le(t,n)},reset(){let e=new Map(w.blockers);e.set(g,iv),oe({blockers:e})}}):await de(f,u,{submission:a,pendingError:o,preventScrollReset:m,replace:n&&n.replace,enableViewTransition:n&&n.viewTransition,flushSync:h,callSiteDefaultShouldRevalidate:n&&n.defaultShouldRevalidate,instrumentationNavigateMetaReceiver:r})}function ue(){if(D)return D.then(ue);ne||=oRe(),Ce(),oe({revalidation:`loading`});let e=ne.promise;return w.navigation.state===`submitting`?e:w.navigation.state===`idle`?(de(w.historyAction,w.location,{startUninterruptedRevalidation:!0,dataStrategyInitiator:`revalidation`}),e):(de(T||w.historyAction,w.navigation.location,{overrideNavigation:w.navigation,dataStrategyInitiator:`revalidation`,enableViewTransition:j===!0}),e)}async function de(t,n,r){D&&await D,A&&A.abort(),A=null,T=t,P=(r&&r.startUninterruptedRevalidation)===!0,Ve(w.location,w.matches),k=(r&&r.preventScrollReset)===!0,j=(r&&r.enableViewTransition)===!0;let i=r?.initialHydration&&w.matches&&w.matches.length>0&&!y?w.matches:c.match(n),a=(r&&r.flushSync)===!0;if(i&&w.initialized&&!F&&HLe(w.location,n)&&!(r&&r.submission&&gv(r.submission.formMethod))){se(n,{matches:i},{flushSync:a});return}let o=Ue(i,n.pathname);if(o.active&&o.matches&&(i=o.matches),r?.instrumentationNavigateMetaReceiver){let t=$Le(e.history,n,i);r.instrumentationNavigateMetaReceiver(t)}if(!i){let{error:e,notFoundMatches:t,route:r}=Re(n.pathname);se(n,{matches:t,loaderData:{},errors:{[r.id]:e}},{flushSync:a});return}let s=r&&r.overrideNavigation?{...r.overrideNavigation,matches:i,historyAction:t}:void 0;A=new AbortController;let l=lv(e.history,n,A.signal,r&&r.submission),u=r?.initialHydration?`initialization`:r?.dataStrategyInitiator??`navigation`,d=e.getContext?await e.getContext():new WFe,f;if(r&&r.pendingError)f=[uv(i).route.id,{type:`error`,error:r.pendingError}];else if(r&&r.submission&&gv(r.submission.formMethod)){let c=await pe(l,u,n,r.submission,i,t,d,o.active,r&&r.initialHydration===!0,{replace:r.replace,flushSync:a});if(c.shortCircuited)return;if(c.pendingActionResult){let[e,t]=c.pendingActionResult;if(mv(t)&&J_(t.error)&&t.error.status===404){A=null,se(n,{matches:c.matches,loaderData:{},errors:{[e]:t.error}});return}}i=c.matches||i,f=c.pendingActionResult,s=tRe(n,i,t,r.submission),a=!1,o.active=!1,l=lv(e.history,l.url,l.signal)}let{shortCircuited:p,matches:m,loaderData:h,errors:g,workingFetchers:_}=await me(l,u,n,i,t,d,o.active,s,r&&r.submission,r&&r.fetcherSubmission,r&&r.replace,r&&r.initialHydration===!0,a,f,r&&r.callSiteDefaultShouldRevalidate);p||(A=null,se(n,{matches:m||i,...BLe(f),loaderData:h,errors:g,..._?{fetchers:_}:{}}))}function fe(){let t=oRe();D=t.promise;let n=E,r=O;O=null,A?.abort(),A=null,ce(),ne?.resolve(),ne=null;let i=new Map(w.blockers);i.forEach((e,t)=>{e.state===`proceeding`&&i.set(t,iv)});let a=new Map(w.fetchers),o=Me(a);a.forEach((e,t)=>{e.state===`loading`&&!L.has(t)&&(a.set(t,yv(e.data)),o=!0)}),I.clear(),oe({navigation:rv,revalidation:`idle`,blockers:i,...o?{fetchers:a}:{}});function s(){D=void 0,r?.resolve(),t.resolve()}return n?(W=s,e.history.go(-n)):s(),t.promise}async function pe(t,n,i,c,d,f,p,m,h,g={}){if(o.unstable_customRouteDiscovery||Ce(),oe({navigation:nRe(i,d,f,c)},{flushSync:g.flushSync===!0}),m){let e=await We(d,i.pathname,t.signal);if(o.unstable_customRouteDiscovery&&t.signal.aborted||e.type===`aborted`)return{shortCircuited:!0};if(e.type===`cancelled`)return await fe(),{shortCircuited:!0};if(e.type===`error`){if(e.partialMatches.length===0){let{matches:t,route:n}=dv(u.activeRoutes);return{matches:t,pendingActionResult:[n.id,{type:`error`,error:e.error}]}}let t=uv(e.partialMatches).route.id;return{matches:e.partialMatches,pendingActionResult:[t,{type:`error`,error:e.error}]}}if(e.matches)d=e.matches;else{let{notFoundMatches:e,error:t,route:n}=Re(i.pathname);return{matches:e,pendingActionResult:[n.id,{type:`error`,error:t}]}}}o.unstable_customRouteDiscovery&&Ce();let _,v=_v(d,i);if(!v.route.action&&!v.route.lazy)_={type:`error`,error:fv(405,{method:t.method,pathname:i.pathname,routeId:v.route.id})};else{let e=await xe(t,i,cv(a,l,t,i,d,v,h?[]:r,p),p,null,n,f);if(_=e[v.route.id],!_){for(let t of d)if(e[t.route.id]){_=e[t.route.id];break}}if(t.signal.aborted)return{shortCircuited:!0}}if(hv(_)){let r;return r=g&&g.replace!=null?g.replace:PLe(_.response.headers.get(`Location`),new URL(t.url),s,e.history)===w.location.pathname+w.location.search,await be(t,_,!0,n,{submission:c,replace:r}),{shortCircuited:!0}}if(mv(_)){let e=uv(d,v.route.id);return(g&&g.replace)!==!0&&(T=`PUSH`),{matches:d,pendingActionResult:[e.route.id,_,v.route.id]}}return{matches:d,pendingActionResult:[v.route.id,_]}}async function me(t,n,i,s,d,f,p,m,h,g,_,v,y,b,x){let S=m||tRe(i,s,d,h),C=h||g||eRe(S),T=!P&&!v;if(p){if(T){let e=he(b);oe({navigation:S,...e===void 0?{}:{actionData:e}},{flushSync:y})}let e=await We(s,i.pathname,t.signal);if(o.unstable_customRouteDiscovery&&t.signal.aborted||e.type===`aborted`)return{shortCircuited:!0};if(e.type===`cancelled`)return await fe(),{shortCircuited:!0};if(e.type===`error`){if(e.partialMatches.length===0){let{matches:t,route:n}=dv(u.activeRoutes);return{matches:t,loaderData:{},errors:{[n.id]:e.error}}}let t=uv(e.partialMatches).route.id;return{matches:e.partialMatches,loaderData:{},errors:{[t]:e.error}}}if(e.matches)s=e.matches,v&&!t.signal.aborted&&oe({matches:s});else{let{error:e,notFoundMatches:t,route:n}=Re(i.pathname);return{matches:t,loaderData:{},errors:{[n.id]:e}}}}let{dsMatches:E,revalidatingFetchers:D}=uLe(t,f,a,l,e.history,w,s,C,i,v?[]:r,v===!0,F,I,te,H,V,c,b,x);if(z=++R,!e.dataStrategy&&!E.some(e=>e.shouldLoad)&&!E.some(e=>e.route.middleware&&e.route.middleware.length>0)&&D.length===0){let e=new Map(w.fetchers),t=Me(e);return se(i,{matches:s,loaderData:{},errors:b&&mv(b[1])?{[b[0]]:b[1].error}:null,...BLe(b),...t?{fetchers:e}:{}},{flushSync:y}),{shortCircuited:!0}}if(T){let e={};if(!p){e.navigation=S;let t=he(b);t!==void 0&&(e.actionData=t)}D.length>0&&(e.fetchers=ge(D)),oe(e,{flushSync:y})}D.forEach(e=>{Ae(e.key),e.controller&&L.set(e.key,e.controller)});let O=()=>D.forEach(e=>{L.get(e.key)===e.controller&&Ae(e.key)});A&&A.signal.addEventListener(`abort`,O);let{loaderResults:k,fetcherResults:j}=await Se(E,D,t,i,f,n,d);if(t.signal.aborted)return{shortCircuited:!0};A&&A.signal.removeEventListener(`abort`,O),D.forEach(e=>{L.get(e.key)===e.controller&&L.delete(e.key)});let M=pv(k);if(M)return await be(t,M.result,!0,n,{replace:_}),{shortCircuited:!0};if(M=pv(j),M)return V.add(M.key),await be(t,M.result,!0,n,{replace:_}),{shortCircuited:!0};let N=new Map(w.fetchers),{loaderData:B,errors:ee}=RLe(w,s,k,b,D,j,N);if(v&&w.errors){let e=ee??null;ee={...w.errors,...ee},av.set(ee,e)}let U=Me(N),W=Ne(z,N),ne=U||W||D.length>0;return{matches:s,loaderData:B,errors:ee,...ne?{workingFetchers:N}:{}}}function he(e){if(e&&!mv(e[1]))return{[e[0]]:e[1].data};if(w.actionData)return Object.keys(w.actionData).length===0?null:w.actionData}function ge(e){let t=new Map(w.fetchers);return e.forEach(e=>{let n=t.get(e.key),r=vv(void 0,n?n.data:void 0);t.set(e.key,r)}),t}async function _e(t,n,r,i){D&&await D,Ae(t);let a=(i&&i.flushSync)===!0,o=zIe(C),l=cLe(w.location,w.matches,s,r,n,i?.relative),u=c.match(l),d=Ue(u,l);if(d.active&&d.matches&&(u=d.matches),o&&o($Le(e.history,l,u)),!u){Te(t,n,fv(404,{pathname:l}),{flushSync:a});return}let{path:f,submission:p,error:m}=lLe(!0,l,i);if(m){Te(t,n,m,{flushSync:a});return}let h=e.getContext?await e.getContext():new WFe,g=(i&&i.preventScrollReset)===!0;if(p&&gv(p.formMethod)){await ve(t,n,f,u,h,d.active,a,g,p,i&&i.defaultShouldRevalidate);return}let _={routeId:n,path:f,isDiscovering:d.active};H.set(t,_),await ye(t,_,u,h,a,g,p)}async function ve(t,n,i,s,u,d,f,p,m,h){o.unstable_customRouteDiscovery||Ce(),H.delete(t);let g=w.fetchers.get(t);we(t,rRe(m,g),{flushSync:f});let _=new AbortController;o.unstable_customRouteDiscovery&&L.set(t,_);let v=lv(e.history,i,_.signal,m);if(d){let e=await We(s,new URL(v.url).pathname,v.signal,t);if(o.unstable_customRouteDiscovery&&v.signal.aborted||e.type===`aborted`)return;if(e.type===`cancelled`){L.delete(t),H.delete(t),we(t,yv(g?.data),{flushSync:f});return}if(e.type===`error`){Te(t,n,e.error,{flushSync:f});return}if(e.matches)s=e.matches;else{Te(t,n,fv(404,{pathname:i}),{flushSync:f});return}}let y=_v(s,i);if(!y.route.action&&!y.route.lazy){Te(t,n,fv(405,{method:m.formMethod,pathname:i,routeId:n}),{flushSync:f});return}o.unstable_customRouteDiscovery&&Ce(),L.set(t,_);let b=R,x=cv(a,l,v,i,s,y,r,u),S=await xe(v,i,x,u,t,`fetcher`),C=S[y.route.id];if(!C){for(let e of x)if(S[e.route.id]){C=S[e.route.id];break}}if(v.signal.aborted){L.get(t)===_&&L.delete(t);return}if(te.has(t)){if(mv(C)){we(t,yv(void 0));return}hv(C)&&(F=!0,C={type:`data`,data:void 0})}else{if(hv(C)){if(z>b)F=!0,C={type:`data`,data:void 0};else return L.delete(t),V.add(t),we(t,vv(m)),be(v,C,!1,`fetcher`,{fetcherSubmission:m,preventScrollReset:p})}if(mv(C)){Te(t,n,C.error);return}}F=!0;let E=w.navigation.location||w.location,D=lv(e.history,E,_.signal),O=w.navigation.state===`idle`?w.matches:c.match(w.navigation.location);P_(O,`Didn't find any matches after fetcher action`);let k=++R;B.set(t,k);let{dsMatches:j,revalidatingFetchers:M}=uLe(D,u,a,l,e.history,w,O,m,E,r,!1,F,I,te,H,V,c,[y.route.id,C],h),N=vv(m,C.data),P=new Map(w.fetchers);P.set(t,N),M.filter(e=>e.key!==t).forEach(e=>{let t=e.key,n=P.get(t),r=vv(void 0,n?n.data:void 0);P.set(t,r),Ae(t),e.controller&&L.set(t,e.controller)}),oe({fetchers:P});let ee=()=>M.forEach(e=>{L.get(e.key)===e.controller&&Ae(e.key)});_.signal.addEventListener(`abort`,ee);let{loaderResults:U,fetcherResults:W}=await Se(j,M,D,E,u,`fetcher`);if(_.signal.aborted){B.get(t)===k&&B.delete(t);return}_.signal.removeEventListener(`abort`,ee),B.delete(t),L.delete(t),M.forEach(e=>{L.get(e.key)===e.controller&&L.delete(e.key)});let ne=w.fetchers.has(t),re=e=>{if(!ne)return e;let n=new Map(e.fetchers);return n.set(t,yv(C.data)),{...e,fetchers:n}},ie=pv(U);if(ie)return w=re(w),be(D,ie.result,!1,`fetcher`,{preventScrollReset:p});if(ie=pv(W),ie)return V.add(ie.key),w=re(w),be(D,ie.result,!1,`fetcher`,{preventScrollReset:p});let ae=new Map(w.fetchers);ne&&ae.set(t,yv(C.data));let{loaderData:ce,errors:le}=RLe(w,O,U,void 0,M,W,ae);Ne(k,ae),w.navigation.state===`loading`&&k>z?(P_(T,`Expected pending action`),A&&A.abort(),Me(ae),se(w.navigation.location,{matches:O,loaderData:ce,errors:le,fetchers:ae})):(oe({errors:le,loaderData:zLe(w.loaderData,ce,O,le),fetchers:ae}),F=B.size>0)}async function ye(t,n,i,s,c,u,d){let{routeId:f,path:p}=n,m=w.fetchers.get(t);we(t,vv(d,m?m.data:void 0),{flushSync:c});let h=new AbortController;o.unstable_customRouteDiscovery&&L.set(t,h);let g=lv(e.history,p,h.signal);if(n.isDiscovering){let e=await We(i,new URL(g.url).pathname,g.signal,t);if(o.unstable_customRouteDiscovery&&g.signal.aborted||e.type===`aborted`)return;if(e.type===`cancelled`){L.delete(t),H.delete(t),we(t,yv(m?.data),{flushSync:c});return}if(e.type===`error`){Te(t,f,e.error,{flushSync:c});return}if(e.matches)i=e.matches,n.isDiscovering=!1;else{Te(t,f,fv(404,{pathname:p}),{flushSync:c});return}}let _=_v(i,p);L.set(t,h);let v=R,y=await xe(g,p,cv(a,l,g,p,i,_,r,s),s,t,`fetcher`),b=y[_.route.id];if(!b){for(let e of i)if(y[e.route.id]){b=y[e.route.id];break}}if(L.get(t)===h&&L.delete(t),!g.signal.aborted){if(te.has(t))we(t,yv(void 0));else{if(hv(b)){if(z>v){we(t,yv(void 0));return}V.add(t),await be(g,b,!1,`fetcher`,{preventScrollReset:u});return}mv(b)?Te(t,f,b.error):we(t,yv(b.data))}}}async function be(r,i,a,o,{submission:c,fetcherSubmission:l,preventScrollReset:u,replace:d}={}){a||(O?.resolve(),O=null),i.response.headers.has(`X-Remix-Revalidate`)&&(F=!0);let f=i.response.headers.get(`Location`);P_(f,`Expected a Location header on the redirect Response`);let p=f,m=new URL(r.url);f=PLe(f,m,s,e.history),nv(p,f,m,`allow-explicit`);let h=I_(w.location,f,{_isRedirect:!0});if(n){let e=!1;if(i.response.headers.has(`X-Remix-Reload-Document`))e=!0;else if(SIe(f)){let n=UFe(t,f,!0);e=n.origin!==t.location.origin||V_(n.pathname,s)==null}if(e){d?t.location.replace(f):t.location.assign(f);return}}A=null;let g=d===!0||i.response.headers.has(`X-Remix-Replace`)?`REPLACE`:`PUSH`,{formMethod:_,formAction:v,formEncType:y}=w.navigation;!c&&!l&&_&&v&&y&&(c=eRe(w.navigation));let b=c||l;eLe.has(i.response.status)&&b&&gv(b.formMethod)?await de(g,h,{submission:{...b,formAction:f},preventScrollReset:u||k,enableViewTransition:a?j:void 0,dataStrategyInitiator:o}):await de(g,h,{overrideNavigation:tRe(h,[],g,c),fetcherSubmission:l,preventScrollReset:u||k,enableViewTransition:a?j:void 0,dataStrategyInitiator:o})}async function xe(e,t,n,r,i,a,o=null){let c,l={};try{c=await DLe(d,e,t,n,i,a,r,!1,o)}catch(e){return n.filter(e=>e.shouldLoad).forEach(t=>{l[t.route.id]={type:`error`,error:e}}),l}if(e.signal.aborted)return l;if(!gv(e.method))for(let e of n){if(c[e.route.id]?.type===`error`)break;c.hasOwnProperty(e.route.id)||w.loaderData.hasOwnProperty(e.route.id)||w.errors&&w.errors.hasOwnProperty(e.route.id)||!e.shouldCallHandler()||(c[e.route.id]={type:`error`,result:Error(`No result returned from dataStrategy for route ${e.route.id}`)})}for(let[t,r]of Object.entries(c))if(KLe(r)){let i=r.result;l[t]={type:`redirect`,response:jLe(i,e,t,n,s)}}else l[t]=await ALe(r);return l}async function Se(e,t,n,r,i,a,o=null){let s=xe(n,r,e,i,null,a,o),c=Promise.all(t.map(async e=>{if(e.matches&&e.match&&e.request&&e.controller){let t=(await xe(e.request,e.path,e.matches,i,e.key,a,o))[e.match.route.id];return{[e.key]:t}}return Promise.resolve({[e.key]:{type:`error`,error:fv(404,{pathname:e.path})}})}));return{loaderResults:await s,fetcherResults:(await c).reduce((e,t)=>Object.assign(e,t),{})}}function Ce(){F=!0,H.forEach((e,t)=>{o.unstable_customRouteDiscovery&&e.isDiscovering||(L.has(t)&&I.add(t),Ae(t))})}function we(e,t,n={}){let r=new Map(w.fetchers);r.set(e,t),oe({fetchers:r},{flushSync:(n&&n.flushSync)===!0})}function Te(e,t,n,r={}){let i=uv(w.matches,t),a=new Map(w.fetchers);Oe(a,e),oe({errors:{[i.route.id]:n},fetchers:a},{flushSync:(r&&r.flushSync)===!0})}function Ee(e){return ee.set(e,(ee.get(e)||0)+1),te.has(e)&&te.delete(e),w.fetchers.get(e)||tLe}function De(e,t){Ae(e,t?.reason),H.delete(e),I.delete(e),we(e,yv(null))}function Oe(e,t){let n=w.fetchers.get(t);L.has(t)&&!(n&&n.state===`loading`&&B.has(t))&&Ae(t),H.delete(t),B.delete(t),V.delete(t),te.delete(t),I.delete(t),e.delete(t)}function ke(e){let t=(ee.get(e)||0)-1;t<=0?(ee.delete(e),te.add(e)):ee.set(e,t),oe({fetchers:new Map(w.fetchers)})}function Ae(e,t){let n=L.get(e);n&&(n.abort(t),L.delete(e))}function je(e,t){for(let n of e){let e=t.get(n);P_(e,`Expected fetcher: ${n}`);let r=yv(e.data);t.set(n,r)}}function Me(e){let t=[],n=!1;for(let r of V){let i=e.get(r);P_(i,`Expected fetcher: ${r}`),i.state===`loading`&&(V.delete(r),t.push(r),n=!0)}return je(t,e),n}function Ne(e,t){let n=[];for(let[r,i]of B)if(i<e){let e=t.get(r);P_(e,`Expected fetcher: ${r}`),e.state===`loading`&&(Ae(r),B.delete(r),n.push(r))}return je(n,t),n.length>0}function Pe(e,t){let n=w.blockers.get(e)||iv;return U.get(e)!==t&&U.set(e,t),n}function Fe(e){w.blockers.delete(e),U.delete(e)}function Ie(e,t){let n=w.blockers.get(e)||iv;P_(n.state===`unblocked`&&t.state===`blocked`||n.state===`blocked`&&t.state===`blocked`||n.state===`blocked`&&t.state===`proceeding`||n.state===`blocked`&&t.state===`unblocked`||n.state===`proceeding`&&t.state===`unblocked`,`Invalid blocker state transition: ${n.state} -> ${t.state}`);let r=new Map(w.blockers);r.set(e,t),oe({blockers:r})}function Le({currentLocation:e,nextLocation:t,historyAction:n}){if(U.size===0)return;U.size>1&&F_(!1,`A router only supports one blocker at a time`);let r=Array.from(U.entries()),[i,a]=r[r.length-1],o=w.blockers.get(i);if(!(o&&o.state===`proceeding`)&&a({currentLocation:e,nextLocation:t,historyAction:n}))return i}function Re(e){let t=fv(404,{pathname:e}),n=u.activeRoutes,{matches:r,route:i}=dv(n);return{notFoundMatches:r,route:i,error:t}}function ze(e,t,n){if(m=e,g=t,h=n||null,!_&&w.navigation===rv){_=!0;let e=He(w.location,w.matches);e!=null&&oe({restoreScrollPosition:e})}return()=>{m=null,g=null,h=null}}function Be(e,t){return h&&h(e,t.map(e=>tIe(e,w.loaderData)))||e.key}function Ve(e,t){if(m&&g){let n=Be(e,t);m[n]=g()}}function He(e,t){if(m){let n=Be(e,t),r=m[n];if(typeof r==`number`)return r}return null}function Ue(t,n){if(e.patchRoutesOnNavigation){if(!t)return{active:!0,matches:c.match(n,!0)||[]};if(Object.keys(t[0].params).length>0)return{active:!0,matches:c.match(n,!0)}}return{active:!1,matches:null}}async function We(t,n,r,i){if(!e.patchRoutesOnNavigation)return{type:`success`,matches:t};let s=t;for(;;){let t=l;try{await e.patchRoutesOnNavigation({signal:r,path:n,matches:s,fetcherKey:i,patch:(e,n)=>{r.aborted||hLe(e,n,u,t,a,!1)}})}catch(e){if(o.unstable_customRouteDiscovery){if(r.aborted)return{type:`aborted`};if(e instanceof GFe)return{type:`cancelled`}}return{type:`error`,error:e,partialMatches:s}}if(r.aborted)return{type:`aborted`};let d=c.match(n),f=null;if(d&&(Object.keys(d[0].params).length===0||(f=c.match(n,!0),!(f&&s.length<f.length&&Ge(s,f.slice(0,s.length))))))return{type:`success`,matches:d};if(f||=c.match(n,!0),!f||Ge(s,f))return{type:`success`,matches:null};s=f}}function Ge(e,t){return e.length===t.length&&e.every((e,n)=>e.route.id===t[n].route.id)}function Ke(e){l={},u.setHmrRoutes(z_(e,a,void 0,l))}function qe(e,t,n=!1){hLe(e,t,u,l,a,n),u.hasHMRRoutes||oe({})}return C={get basename(){return s},get future(){return o},get state(){return w},get routes(){return u.stableRoutes},match(e){return c.match(e)},get manifest(){return l},get window(){return t},initialize:re,subscribe:ae,enableScrollRestoration:ze,navigate:le,fetch:_e,revalidate:ue,createHref:t=>e.history.createHref(t),createURL:t=>e.history.createURL(t),encodeLocation:t=>e.history.encodeLocation(t),getFetcher:Ee,resetFetcher:De,deleteFetcher:ke,dispose:ie,getBlocker:Pe,deleteBlocker:Fe,patchRoutes:qe,_internalFetchControllers:L,_internalSetRoutes:Ke,_internalSetStateDoNotUseOrYouWillBreakYourApp(e){oe(e)}},e.instrumentations&&(C=LIe(C,e.instrumentations.map(e=>e.router).filter(Boolean))),C}function sLe(e){return e!=null&&(`formData`in e&&e.formData!=null||`body`in e&&e.body!==void 0)}function cLe(e,t,n,r,i,a){let o,s;if(i){o=[];for(let e of t)if(o.push(e),e.route.id===i){s=e;break}}else o=t,s=t[t.length-1];let c=U_(r||`.`,H_(o),V_(e.pathname,n)||e.pathname,a===`path`);if(r??(c.search=e.search,c.hash=e.hash),(r==null||r===``||r===`.`)&&s){let e=QLe(c.search);if(s.route.index&&!e)c.search=c.search?c.search.replace(/^\?/,`?index&`):`?index`;else if(!s.route.index&&e){let e=new URLSearchParams(c.search),t=e.getAll(`index`);e.delete(`index`),t.filter(e=>e).forEach(t=>e.append(`index`,t));let n=e.toString();c.search=n?`?${n}`:``}}return n!==`/`&&(c.pathname=xIe({basename:n,pathname:c.pathname})),L_(c)}function lLe(e,t,n){if(!n||!sLe(n))return{path:t};if(n.formMethod&&!ZLe(n.formMethod))return{path:t,error:fv(405,{method:n.formMethod})};let r=()=>({path:t,error:fv(400,{type:`invalid-body`})}),i=(n.formMethod||`get`).toUpperCase(),a=VLe(t);if(n.body!==void 0){if(n.formEncType===`text/plain`){if(!gv(i))return r();let e=typeof n.body==`string`?n.body:n.body instanceof FormData||n.body instanceof URLSearchParams?Array.from(n.body.entries()).reduce((e,[t,n])=>`${e}${t}=${n}\n`,``):String(n.body);return{path:t,submission:{formMethod:i,formAction:a,formEncType:n.formEncType,formData:void 0,json:void 0,text:e}}}if(n.formEncType===`application/json`){if(!gv(i))return r();try{let e=typeof n.body==`string`?JSON.parse(n.body):n.body;return{path:t,submission:{formMethod:i,formAction:a,formEncType:n.formEncType,formData:void 0,json:e,text:void 0}}}catch{return r()}}}P_(typeof FormData==`function`,`FormData is not available in this environment`);let o,s;if(n.formData)o=FLe(n.formData),s=n.formData;else if(n.body instanceof FormData)o=FLe(n.body),s=n.body;else if(n.body instanceof URLSearchParams)o=n.body,s=ILe(o);else if(n.body==null)o=new URLSearchParams,s=new FormData;else try{o=new URLSearchParams(n.body),s=ILe(o)}catch{return r()}let c={formMethod:i,formAction:a,formEncType:n&&n.formEncType||`application/x-www-form-urlencoded`,formData:s,json:void 0,text:void 0};if(gv(c.formMethod))return{path:t,submission:c};let l=R_(t);return e&&l.search&&QLe(l.search)&&o.append(`index`,``),l.search=`?${o}`,{path:L_(l),submission:c}}function uLe(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v){let y=_?mv(_[1])?_[1].error:_[1].data:void 0,b=i.createURL(a.location),x=i.createURL(c),S;if(u&&a.errors){let e=Object.keys(a.errors)[0];S=o.findIndex(t=>t.route.id===e)}else if(_&&mv(_[1])){let e=_[0];S=o.findIndex(t=>t.route.id===e)-1}let C=_?_[1].statusCode:void 0,w=C&&C>=400,T={currentUrl:b,currentParams:a.matches[0]?.params||{},nextUrl:x,nextParams:o[0].params,...s,actionResult:y,actionStatus:C},E=Y_(o),D=o.map((i,o)=>{let{route:s}=i,f=null;if(S!=null&&o>S)f=!1;else if(s.lazy)f=!0;else if(!dLe(s))f=!1;else if(u){let{shouldLoad:e}=fLe(s,a.loaderData,a.errors);f=e}else pLe(a.loaderData,a.matches[o],i)&&(f=!0);if(f!==null)return ELe(n,r,e,c,E,i,l,t,f);let p=!1;typeof v==`boolean`?p=v:w?p=!1:d||b.pathname+b.search===x.pathname+x.search?p=!0:b.search===x.search?mLe(a.matches[o],i)&&(p=!0):p=!0;let m={...T,defaultShouldRevalidate:p};return ELe(n,r,e,c,E,i,l,t,ov(i,m),m,v)}),O=[];return m.forEach((e,s)=>{if(u||!o.some(t=>t.route.id===e.routeId)||p.has(s)||e.isDiscovering)return;let c=a.fetchers.get(s),m=c&&c.state!==`idle`&&c.data===void 0,_=g.match(e.path);if(!_){O.push({key:s,routeId:e.routeId,path:e.path,matches:null,match:null,request:null,controller:null});return}if(h.has(s))return;let y=_v(_,e.path),b=new AbortController,x=lv(i,e.path,b.signal),S=null;if(f.has(s))f.delete(s),S=cv(n,r,x,e.path,_,y,l,t);else if(m)d&&(S=cv(n,r,x,e.path,_,y,l,t));else{let i;i=typeof v==`boolean`?v:!w&&d;let a={...T,defaultShouldRevalidate:i};ov(y,a)&&(S=cv(n,r,x,e.path,_,y,l,t,a))}S&&O.push({key:s,routeId:e.routeId,path:e.path,matches:S,match:y,request:x,controller:b})}),{dsMatches:D,revalidatingFetchers:O}}function dLe(e){return e.loader!=null||e.middleware!=null&&e.middleware.length>0}function fLe(e,t,n){if(e.lazy)return{shouldLoad:!0,renderFallback:!0};if(!dLe(e))return{shouldLoad:!1,renderFallback:!1};let r=t!=null&&e.id in t,i=n!=null&&n[e.id]!==void 0;if(!r&&i)return{shouldLoad:!1,renderFallback:!1};if(typeof e.loader==`function`&&e.loader.hydrate===!0)return{shouldLoad:!0,renderFallback:!r};let a=!r&&!i;return{shouldLoad:a,renderFallback:a}}function pLe(e,t,n){let r=!t||n.route.id!==t.route.id,i=!e.hasOwnProperty(n.route.id);return r||i}function mLe(e,t){let n=e.route.path;return e.pathname!==t.pathname||n!=null&&n.endsWith(`*`)&&e.params[`*`]!==t.params[`*`]}function ov(e,t){if(e.route.shouldRevalidate){let n=e.route.shouldRevalidate(t);if(typeof n==`boolean`)return n}return t.defaultShouldRevalidate}function hLe(e,t,n,r,i,a){let o;if(e){let t=r[e];P_(t,`No route found to patch children into: routeId = ${e}`),t.children||=[],o=t.children}else o=n.activeRoutes;let s=[],c=[];if(t.forEach(e=>{let t=o.find(t=>gLe(e,t));t?c.push({existingRoute:t,newRoute:e}):s.push(e)}),s.length>0){let t=z_(s,i,[e||`_`,`patch`,String(o?.length||`0`)],r);o.push(...t)}if(a&&c.length>0)for(let e=0;e<c.length;e++){let{existingRoute:t,newRoute:n}=c[e],r=t,[a]=z_([n],i,[],{},!0);Object.assign(r,{element:a.element?a.element:r.element,errorElement:a.errorElement?a.errorElement:r.errorElement,hydrateFallbackElement:a.hydrateFallbackElement?a.hydrateFallbackElement:r.hydrateFallbackElement})}n.hasHMRRoutes||n.setRoutes([...n.activeRoutes])}function gLe(e,t){return`id`in e&&`id`in t&&e.id===t.id?!0:e.index!==t.index||e.path!==t.path||e.caseSensitive!==t.caseSensitive?!1:(!e.children||e.children.length===0)&&(!t.children||t.children.length===0)?!0:e.children?.every((e,n)=>t.children?.some(t=>gLe(e,t)))??!1}var _Le=new WeakMap,vLe=({key:e,route:t,manifest:n,mapRouteProperties:r})=>{let i=n[t.id];if(P_(i,`No route found in manifest`),!i.lazy||typeof i.lazy!=`object`)return;let a=i.lazy[e];if(!a)return;let o=_Le.get(i);o||(o={},_Le.set(i,o));let s=o[e];if(s)return s;let c=(async()=>{let t=qFe(e),n=i[e]!==void 0;if(t)F_(!t,`Route property `+e+` is not a supported lazy route property. This property will be ignored.`),o[e]=Promise.resolve();else if(n)F_(!1,`Route "${i.id}" has a static property "${e}" defined. The lazy property will be ignored.`);else{let t=await a();t!=null&&(Object.assign(i,{[e]:t}),Object.assign(i,r(i)))}typeof i.lazy==`object`&&(i.lazy[e]=void 0,Object.values(i.lazy).every(e=>e===void 0)&&(i.lazy=void 0))})();return o[e]=c,c.catch(()=>{o[e]===c&&delete o[e]}),c},sv=new WeakMap;function yLe(e,t,n,r,i){let a=n[e.id];if(P_(a,`No route found in manifest`),!e.lazy)return{lazyRoutePromise:void 0,lazyHandlerPromise:void 0};if(typeof e.lazy==`function`){let t=sv.get(a);if(t)return{lazyRoutePromise:t,lazyHandlerPromise:t};let n=(async()=>{P_(typeof e.lazy==`function`,`No lazy route function found`);let t=await e.lazy(),n={};for(let e in t){let r=t[e];if(r===void 0)continue;let i=YFe(e),o=a[e]!==void 0;i?F_(!i,`Route property `+e+` is not a supported property to be returned from a lazy route function. This property will be ignored.`):o?F_(!o,`Route "${a.id}" has a static property "${e}" defined but its lazy function is also returning a value for this property. The lazy route property "${e}" will be ignored.`):n[e]=r}Object.assign(a,n),Object.assign(a,{...r(a),lazy:void 0})})();return sv.set(a,n),n.catch(()=>{sv.get(a)===n&&sv.delete(a)}),{lazyRoutePromise:n,lazyHandlerPromise:n}}let o=Object.keys(e.lazy),s=[],c;for(let a of o){if(i&&i.includes(a))continue;let o=vLe({key:a,route:e,manifest:n,mapRouteProperties:r});o&&(s.push(o),a===t&&(c=o))}let l=s.length>0?Promise.all(s).then(()=>{}):void 0;return l?.catch(()=>{}),c?.catch(()=>{}),{lazyRoutePromise:l,lazyHandlerPromise:c}}async function bLe(e){let t=e.matches.filter(e=>e.shouldLoad),n={};return(await Promise.all(t.map(e=>e.resolve()))).forEach((e,r)=>{n[t[r].route.id]=e}),n}async function xLe(e){return e.matches.some(e=>e.route.middleware)?SLe(e,()=>bLe(e)):bLe(e)}function SLe(e,t){return CLe(e,t,e=>{if(XLe(e))throw e;return e},WLe,n);async function n(t,n,r){if(r)return Object.assign(r.value,{[n]:{type:`error`,result:t}});{let{matches:r}=e,i=Math.min(Math.max(r.findIndex(e=>e.route.id===n),0),Math.max(r.findIndex(e=>e.shouldCallHandler()),0)),a=r[i].route.id;for(let e of r.slice(0,i+1))try{await e._lazyPromises?.route}catch{a=e.route.id;break}return{[uv(r,a).route.id]:{type:`error`,result:t}}}}}async function CLe(e,t,n,r,i){let{matches:a,...o}=e;return await wLe(o,a.flatMap(e=>e.route.middleware?e.route.middleware.map(t=>[e.route.id,t]):[]),t,n,r,i)}async function wLe(e,t,n,r,i,a,o=0){let{request:s}=e;if(s.signal.aborted)throw s.signal.reason??Error(`Request aborted: ${s.method} ${s.url}`);let c=t[o];if(!c)return await n();let[l,u]=c,d,f=async()=>{if(d)throw Error("You may only call `next()` once per middleware");try{return d={value:await wLe(e,t,n,r,i,a,o+1)},d.value}catch(e){return d={value:await a(e,l,d)},d.value}};try{let t=await u(e,f),n=t==null?void 0:r(t);return i(n)?n:d?n??d.value:(d={value:await f()},d.value)}catch(e){return await a(e,l,d)}}function TLe(e,t,n,r,i){let a=vLe({key:`middleware`,route:r.route,manifest:t,mapRouteProperties:e}),o=yLe(r.route,gv(n.method)?`action`:`loader`,t,e,i);return{middleware:a,route:o.lazyRoutePromise,handler:o.lazyHandlerPromise}}function ELe(e,t,n,r,i,a,o,s,c,l=null,u){let d=!1,f=TLe(e,t,n,a,o);return{...a,_lazyPromises:f,shouldLoad:c,shouldRevalidateArgs:l,shouldCallHandler(e){return d=!0,l?typeof u==`boolean`?ov(a,{...l,defaultShouldRevalidate:u}):typeof e==`boolean`?ov(a,{...l,defaultShouldRevalidate:e}):ov(a,l):c},resolve(e){let{lazy:t,loader:o,middleware:l}=a.route,u=d||c||e&&!gv(n.method)&&(t||o),p=l&&l.length>0&&!o&&!t;return u&&(gv(n.method)||!p)?OLe({request:n,path:r,pattern:i,match:a,lazyHandlerPromise:f?.handler,lazyRoutePromise:f?.route,handlerOverride:e,scopedContext:s}):Promise.resolve({type:`data`,result:void 0})}}}function cv(e,t,n,r,i,a,o,s,c=null){return i.map(l=>l.route.id===a.route.id?ELe(e,t,n,r,Y_(i),l,o,s,!0,c):{...l,shouldLoad:!1,shouldRevalidateArgs:c,shouldCallHandler:()=>!1,_lazyPromises:TLe(e,t,n,l,o),resolve:()=>Promise.resolve({type:`data`,result:void 0})})}async function DLe(e,t,n,r,i,a,o,s,c=null){r.some(e=>e._lazyPromises?.middleware)&&await Promise.all(r.map(e=>e._lazyPromises?.middleware));let l={request:t,url:MIe(t,n),pattern:Y_(r),params:r[0].params,context:o,matches:r,unstable_initiator:a,unstable_navigationType:a===`navigation`?c:null},u=s?()=>{throw Error("You cannot call `runClientMiddleware()` from a static handler `dataStrategy`. Middleware is run outside of `dataStrategy` during SSR in order to bubble up the Response. You can enable middleware via the `respond` API in `query`/`queryRoute`")}:e=>{let t=l;return SLe(t,()=>e({...t,fetcherKey:i,runClientMiddleware:()=>{throw Error("Cannot call `runClientMiddleware()` from within an `runClientMiddleware` handler")}}))},d=await e({...l,fetcherKey:i,runClientMiddleware:u});try{await Promise.all(r.flatMap(e=>[e._lazyPromises?.handler,e._lazyPromises?.route]))}catch{}return d}async function OLe({request:e,path:t,pattern:n,match:r,lazyHandlerPromise:i,lazyRoutePromise:a,handlerOverride:o,scopedContext:s}){let c,l,u=gv(e.method),d=u?`action`:`loader`,f=i=>{let a,c=new Promise((e,t)=>a=t);l=()=>a(),e.signal.addEventListener(`abort`,l);let u=a=>typeof i==`function`?i({request:e,url:MIe(e,t),pattern:n,params:r.params,context:s},...a===void 0?[]:[a]):Promise.reject(Error(`You cannot call the handler for a route which defines a boolean "${d}" [routeId: ${r.route.id}]`)),f=(async()=>{try{return{type:`data`,result:await(o?o(e=>u(e)):u())}}catch(e){return{type:`error`,result:e}}})();return Promise.race([f,c])};try{let t=u?r.route.action:r.route.loader;if(i||a){if(t){let e,[n]=await Promise.all([f(t).catch(t=>{e=t}),i,a]);if(e!==void 0)throw e;c=n}else{await i;let t=u?r.route.action:r.route.loader;if(t)[c]=await Promise.all([f(t),a]);else if(d===`action`){let t=new URL(e.url),n=t.pathname+t.search;throw fv(405,{method:e.method,pathname:n,routeId:r.route.id})}else return await a,{type:`data`,result:void 0}}}else if(t)c=await f(t);else{let t=new URL(e.url);throw fv(404,{pathname:t.pathname+t.search})}}catch(e){return{type:`error`,result:e}}finally{l&&e.signal.removeEventListener(`abort`,l)}return c}async function kLe(e){let t=e.headers.get(`Content-Type`);return t&&/\bapplication\/json\b/.test(t)?e.body==null?null:e.json():e.text()}async function ALe(e){let{result:t,type:n}=e;if(JLe(t)){let e;try{e=await kLe(t)}catch(e){return{type:`error`,error:e}}return n===`error`?{type:`error`,error:new q_(t.status,t.statusText,e),statusCode:t.status,headers:t.headers}:{type:`data`,data:e,statusCode:t.status,headers:t.headers}}return n===`error`?qLe(t)?t.data instanceof Error?{type:`error`,error:t.data,statusCode:t.init?.status,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:`error`,error:ULe(t),statusCode:J_(t)?t.status:void 0,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:`error`,error:t,statusCode:J_(t)?t.status:void 0}:qLe(t)?{type:`data`,data:t.data,statusCode:t.init?.status,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:`data`,data:t}}function jLe(e,t,n,r,i){let a=e.headers.get(`Location`);if(P_(a,`Redirects returned/thrown from loaders/actions must have a Location header`),!SIe(a)){let o=r.slice(0,r.findIndex(e=>e.route.id===n)+1);a=cLe(new URL(t.url),o,i,a),e.headers.set(`Location`,a)}return e}var MLe=[`about:`,`blob:`,`chrome:`,`chrome-untrusted:`,`content:`,`data:`,`devtools:`,`file:`,`filesystem:`,`javascript:`];function NLe(e){try{return MLe.includes(new URL(e).protocol)}catch{return!1}}function PLe(e,t,n,r){if(SIe(e)){let r=e,i=N_.test(r)?new URL(IFe(r,t.protocol)):new URL(r);if(NLe(i.toString()))throw Error(`Invalid redirect location`);let a=V_(i.pathname,n)!=null;if(i.origin===t.origin&&a)return DIe(i.pathname)+i.search+i.hash}try{if(NLe(r.createURL(e).toString()))throw Error(`Invalid redirect location`)}catch{}return e}function lv(e,t,n,r){let i=e.createURL(VLe(t)).toString(),a={signal:n};if(r&&gv(r.formMethod)){let{formMethod:e,formEncType:t}=r;a.method=e.toUpperCase(),t===`application/json`?(a.headers=new Headers({"Content-Type":t}),a.body=JSON.stringify(r.json)):a.body=t===`text/plain`?r.text:t===`application/x-www-form-urlencoded`&&r.formData?FLe(r.formData):r.formData}return new Request(i,a)}function FLe(e){let t=new URLSearchParams;for(let[n,r]of e.entries())t.append(n,typeof r==`string`?r:r.name);return t}function ILe(e){let t=new FormData;for(let[n,r]of e.entries())t.append(n,r);return t}function LLe(e,t,n,r=!1,i=!1){let a={},o=null,s,c=!1,l={},u=n&&mv(n[1])?n[1].error:void 0;return e.forEach(n=>{if(!(n.route.id in t))return;let d=n.route.id,f=t[d];if(P_(!hv(f),`Cannot handle redirect results in processLoaderData`),mv(f)){let t=f.error;if(u!==void 0&&(t=u,u=void 0),o||={},i)o[d]=t;else{let n=uv(e,d);o[n.route.id]??(o[n.route.id]=t)}r||(a[d]=rLe),c||(c=!0,s=J_(f.error)?f.error.status:500),f.headers&&(l[d]=f.headers)}else a[d]=f.data,f.statusCode&&f.statusCode!==200&&!c&&(s=f.statusCode),f.headers&&(l[d]=f.headers)}),u!==void 0&&n&&(o={[n[0]]:u},n[2]&&(a[n[2]]=void 0)),{loaderData:a,errors:o,statusCode:s||200,loaderHeaders:l}}function RLe(e,t,n,r,i,a,o){let{loaderData:s,errors:c}=LLe(t,n,r);return i.filter(e=>!e.matches||e.matches.some(e=>e.shouldLoad)).forEach(t=>{let{key:n,routeId:r,controller:i}=t;if(i&&i.signal.aborted)return;let s=a[n];if(P_(s,`Did not find corresponding fetcher result`),mv(s)){let t=uv(e.matches,r);c&&c[t.route.id]||(c={...c,[t.route.id]:s.error}),o.delete(n)}else if(hv(s))P_(!1,`Unhandled fetcher revalidation redirect`);else{let e=yv(s.data);o.set(n,e)}}),{loaderData:s,errors:c}}function zLe(e,t,n,r){let i=Object.entries(t).filter(([,e])=>e!==rLe).reduce((e,[t,n])=>(e[t]=n,e),{}),a=0;for(let o of n){let n=o.route.id;if(!t.hasOwnProperty(n)&&e.hasOwnProperty(n)&&o.route.loader&&(i[n]=e[n],a++),r&&r.hasOwnProperty(n))break}return Object.keys(t).length===0&&a===Object.keys(e).length?e:i}function BLe(e){return e?mv(e[1])?{actionData:{}}:{actionData:{[e[0]]:e[1].data}}:{}}function uv(e,t){return(t?e.slice(0,e.findIndex(e=>e.route.id===t)+1):[...e]).reverse().find(e=>e.route.ErrorBoundary!=null||e.route.errorElement!=null)||e[0]}function dv(e){let t=e.length===1?e[0]:e.find(e=>e.index||!e.path||e.path===`/`)||{id:`__shim-error-route__`};return{matches:[{params:{},pathname:``,pathnameBase:``,route:t}],route:t}}function fv(e,{pathname:t,routeId:n,method:r,type:i,message:a}={}){let o=`Unknown Server Error`,s=`Unknown @remix-run/router error`;return e===400?(o=`Bad Request`,r&&t&&n?s=`You made a ${r} request to "${t}" but did not provide a \`loader\` for route "${n}", so there is no way to handle the request.`:i===`invalid-body`&&(s=`Unable to encode submission body`)):e===403?(o=`Forbidden`,s=`Route "${n}" does not match URL "${t}"`):e===404?(o=`Not Found`,s=`No route matches URL "${t}"`):e===405&&(o=`Method Not Allowed`,r&&t&&n?s=`You made a ${r.toUpperCase()} request to "${t}" but did not provide an \`action\` for route "${n}", so there is no way to handle the request.`:r&&(s=`Invalid request method "${r.toUpperCase()}"`)),new q_(e||500,o,Error(s),!0)}function pv(e){let t=Object.entries(e);for(let e=t.length-1;e>=0;e--){let[n,r]=t[e];if(hv(r))return{key:n,result:r}}}function VLe(e){return L_({...typeof e==`string`?R_(e):e,hash:``})}function HLe(e,t){return e.pathname!==t.pathname||e.search!==t.search?!1:e.hash===``?t.hash!==``:e.hash===t.hash||t.hash!==``}function ULe(e){return new q_(e.init?.status??500,e.init?.statusText??`Internal Server Error`,e.data)}function WLe(e){return typeof e==`object`&&!!e&&Object.entries(e).every(([e,t])=>typeof e==`string`&&GLe(t))}function GLe(e){return typeof e==`object`&&!!e&&`type`in e&&`result`in e&&(e.type===`data`||e.type===`error`)}function KLe(e){return JLe(e.result)&&$Ie.has(e.result.status)}function mv(e){return e.type===`error`}function hv(e){return(e&&e.type)===`redirect`}function qLe(e){return typeof e==`object`&&!!e&&`type`in e&&`data`in e&&`init`in e&&e.type===`DataWithResponseInit`}function JLe(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.headers==`object`&&e.body!==void 0}function YLe(e){return $Ie.has(e)}function XLe(e){return JLe(e)&&YLe(e.status)&&e.headers.has(`Location`)}function ZLe(e){return QIe.has(e.toUpperCase())}function gv(e){return XIe.has(e.toUpperCase())}function QLe(e){return new URLSearchParams(e).getAll(`index`).some(e=>e===``)}function _v(e,t){let n=typeof t==`string`?R_(t).search:t.search;if(e[e.length-1].route.index&&QLe(n||``))return e[e.length-1];let r=EIe(e);return r[r.length-1]}function $Le(e,t,n){return{url:MIe(e.createURL(t),t),pattern:n?Y_(n):``,params:n?.[0]?.params?{...n[0].params}:{}}}function eRe(e){let{formMethod:t,formAction:n,formEncType:r,text:i,formData:a,json:o}=e;if(t&&n&&r){if(i!=null)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:void 0,text:i};if(a!=null)return{formMethod:t,formAction:n,formEncType:r,formData:a,json:void 0,text:void 0};if(o!==void 0)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:o,text:void 0}}}function tRe(e,t,n,r){return r?{state:`loading`,location:e,matches:t,historyAction:n,formMethod:r.formMethod,formAction:r.formAction,formEncType:r.formEncType,formData:r.formData,json:r.json,text:r.text}:{state:`loading`,location:e,matches:t,historyAction:n,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0}}function nRe(e,t,n,r){return{state:`submitting`,location:e,matches:t,historyAction:n,formMethod:r.formMethod,formAction:r.formAction,formEncType:r.formEncType,formData:r.formData,json:r.json,text:r.text}}function vv(e,t){return e?{state:`loading`,formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t}:{state:`loading`,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:t}}function rRe(e,t){return{state:`submitting`,formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t?t.data:void 0}}function yv(e){return{state:`idle`,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:e}}function iRe(e,t){try{let n=e.sessionStorage.getItem(nLe);if(n){let e=JSON.parse(n);for(let[n,r]of Object.entries(e||{}))r&&Array.isArray(r)&&t.set(n,new Set(r||[]))}}catch{}}function aRe(e,t){if(t.size>0){let n={};for(let[e,r]of t)n[e]=[...r];try{e.sessionStorage.setItem(nLe,JSON.stringify(n))}catch(e){F_(!1,`Failed to save applied view transitions in sessionStorage (${e}).`)}}}function oRe(){let e,t,n=new Promise((r,i)=>{e=async e=>{r(e);try{await n}catch{}},t=async e=>{i(e);try{await n}catch{}}});return{promise:n,resolve:e,reject:t}}var bv=G.createContext(null);bv.displayName=`DataRouter`;var sRe=G.createContext(null);sRe.displayName=`DataRouterState`;var cRe=G.createContext(null);cRe.displayName=`DataRouterData`;var lRe=G.createContext(null);lRe.displayName=`DataRouterNavigation`;var uRe=G.createContext(!1);function dRe(){return G.useContext(uRe)}var fRe=G.createContext({isTransitioning:!1});fRe.displayName=`ViewTransition`;var pRe=G.createContext(null);pRe.displayName=`Fetchers`;var mRe=G.createContext(null);mRe.displayName=`Await`;var xv=G.createContext(null);xv.displayName=`Navigation`;var Sv=G.createContext(null);Sv.displayName=`Location`;var Cv=G.createContext({outlet:null,matches:[],isDataRoute:!1});Cv.displayName=`Route`;var wv=G.createContext(!1);wv.displayName=`IsDataRoute`;var Tv=G.createContext(void 0);Tv.displayName=`RouteId`;var hRe=G.createContext(null);hRe.displayName=`RouteError`;var gRe=`REACT_ROUTER_ERROR`,_Re=`REDIRECT`,vRe=`ROUTE_ERROR_RESPONSE`;function yRe(e){if(e.startsWith(`${gRe}:${_Re}:{`))try{let t=JSON.parse(e.slice(28));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`&&typeof t.location==`string`&&typeof t.reloadDocument==`boolean`&&typeof t.replace==`boolean`)return t}catch{}}function bRe(e){if(e.startsWith(`${gRe}:${vRe}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`)return new q_(t.status,t.statusText,t.data)}catch{}}function xRe(e,{relative:t}={}){P_(Ev(),`useHref() may be used only in the context of a <Router> component.`);let{basename:n,navigator:r}=G.useContext(xv),{hash:i,pathname:a,search:o}=Av(e,{relative:t}),s=a;return n!==`/`&&(s=a===`/`?n:W_([n,a])),r.createHref({pathname:s,search:o,hash:i})}function Ev(){return G.useContext(Sv)!=null}function Dv(){return P_(Ev(),`useLocation() may be used only in the context of a <Router> component.`),G.useContext(Sv).location}function SRe(e){P_(Ev(),`useMatch() may be used only in the context of a <Router> component.`);let{pathname:t}=Dv();return G.useMemo(()=>B_(e,bIe(t)),[t,e])}var CRe=`You should call navigate() in a React.useEffect(), not when your component is first rendered.`;function Ov(){return G.useContext(wv)?BRe():wRe()}function wRe(){P_(Ev(),`useNavigate() may be used only in the context of a <Router> component.`);let e=G.useContext(bv),{basename:t,navigator:n}=G.useContext(xv),{matches:r}=G.useContext(Cv),{pathname:i}=Dv(),a=JSON.stringify(H_(r)),o=G.useRef(!1);return G.useLayoutEffect(()=>{o.current=!0}),G.useCallback((r,s={})=>{if(F_(o.current,CRe),!o.current)return;if(typeof r==`number`){n.go(r);return}let c=U_(r,JSON.parse(a),i,s.relative===`path`);e==null&&t!==`/`&&(c.pathname=c.pathname===`/`?t:W_([t,c.pathname])),nv(typeof r==`string`?r:L_(r),n.createHref(c),KIe(n),`reject`),(s.replace?n.replace:n.push)(c,s.state,s)},[t,n,a,i,e])}var TRe=G.createContext(null);function ERe(e){let t=G.useContext(Cv).outlet;return G.useMemo(()=>t&&G.createElement(TRe.Provider,{value:e},t),[t,e])}function kv(){let{matches:e}=G.useContext(Cv);return e[e.length-1]?.params??{}}function Av(e,{relative:t}={}){let{matches:n}=G.useContext(Cv),{pathname:r}=Dv(),i=JSON.stringify(H_(n));return G.useMemo(()=>U_(e,JSON.parse(i),r,t===`path`),[e,i,r,t])}function DRe(e,t,n){P_(Ev(),`useRoutes() may be used only in the context of a <Router> component.`);let{navigator:r}=G.useContext(xv),{matches:i}=G.useContext(Cv),a=i[i.length-1],o=a?a.params:{};a&&a.pathname;let s=a?a.pathnameBase:`/`;a&&a.route;let c=Dv(),l;if(t){let e=typeof t==`string`?R_(t):t;P_(s===`/`||e.pathname?.startsWith(s),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${s}" but pathname "${e.pathname}" was given in the \`location\` prop.`),l=e}else l=c;let u=l.pathname||`/`,d=u;if(s!==`/`){let e=s.replace(/^\//,``).split(`/`);d=`/`+u.replace(/^\//,``).split(`/`).slice(e.length).join(`/`)}let f;f=n?n.state.matches.length?n.state.matches.map(e=>Object.assign(e,{route:n.manifest[e.route.id]||e.route})):n.router.match(n.state.location):$Fe(e,{pathname:d});let p=PRe(f&&f.map(e=>Object.assign({},e,{params:Object.assign({},o,e.params),pathname:W_([s,r.encodeLocation?r.encodeLocation(e.pathname.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathname]),pathnameBase:e.pathnameBase===`/`?s:W_([s,r.encodeLocation?r.encodeLocation(e.pathnameBase.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathnameBase])})),i,n);return t&&p?G.createElement(Sv.Provider,{value:{location:{pathname:`/`,search:``,hash:``,state:null,key:`default`,mask:void 0,...l},navigationType:`POP`}},p):p}function ORe(){let e=zRe(),t=J_(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null;return G.createElement(G.Fragment,null,G.createElement(`h2`,null,`Unexpected Application Error!`),G.createElement(`h3`,{style:{fontStyle:`italic`}},t),n?G.createElement(`pre`,{style:{padding:`0.5rem`,backgroundColor:`rgba(200,200,200, 0.5)`}},n):null,null)}var kRe=G.createElement(ORe,null),ARe=class extends G.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static contextType=uRe;static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!==`idle`&&e.revalidation===`idle`?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error===void 0?t.error:e.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error(`React Router caught the following error during render`,e)}render(){let e=this.state.error;if(this.context&&typeof e==`object`&&e&&`digest`in e&&typeof e.digest==`string`){let t=bRe(e.digest);t&&(e=t)}let t=e===void 0?this.props.children:G.createElement(Cv.Provider,{value:this.props.routeContext},G.createElement(wv.Provider,{value:this.props.routeContext.isDataRoute},G.createElement(Tv.Provider,{value:this.props.routeContext.matches[this.props.routeContext.matches.length-1]?.route.id},G.createElement(hRe.Provider,{value:e,children:this.props.component}))));return this.context?G.createElement(MRe,{error:e},t):t}},jRe=new WeakMap;function MRe({children:e,error:t}){let{basename:n,navigator:r}=G.useContext(xv);if(typeof t==`object`&&t&&`digest`in t&&typeof t.digest==`string`){let e=yRe(t.digest);if(e){let i=jRe.get(t);if(i)throw i;let a=PIe(e.location,n),o=a.absoluteURL||a.to;if(nv(e.location,o,KIe(r),`allow-explicit`),NLe(o))throw Error(`Invalid redirect location`);if(NIe&&!jRe.get(t)){if(a.isExternal||e.reloadDocument)window.location.href=o;else{let n=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(a.to,{replace:e.replace}));throw jRe.set(t,n),n}}return G.createElement(`meta`,{httpEquiv:`refresh`,content:`0;url=${o}`})}}return e}function NRe({routeContext:e,match:t,children:n}){let r=G.useContext(bv);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),G.createElement(Cv.Provider,{value:e},G.createElement(wv.Provider,{value:e.isDataRoute},G.createElement(Tv.Provider,{value:t.route.id},n)))}function PRe(e,t=[],n){let r=n?.state;if(e==null){if(!r)return null;if(r.errors)e=r.matches;else if(t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let i=e,a=r?.errors;if(a!=null){let e=i.findIndex(e=>e.route.id&&a?.[e.route.id]!==void 0);P_(e>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(a).join(`,`)}`),i=i.slice(0,Math.min(i.length,e+1))}let o=!1,s=-1;if(n&&r){o=r.renderFallback;for(let e=0;e<i.length;e++){let t=i[e];if((t.route.HydrateFallback||t.route.hydrateFallbackElement)&&(s=e),t.route.id){let{loaderData:e,errors:a}=r,c=t.route.loader&&!e.hasOwnProperty(t.route.id)&&(!a||a[t.route.id]===void 0);if(t.route.lazy||c){n.isStatic&&(o=!0),i=s>=0?i.slice(0,s+1):[i[0]];break}}}}let c=n?.onError,l=r&&c?(e,t)=>{c(e,{location:r.location,params:r.matches?.[0]?.params??{},pattern:Y_(r.matches),errorInfo:t})}:void 0;return i.reduceRight((e,n,c)=>{let u,d=!1,f=null,p=null;r&&(u=a&&n.route.id?a[n.route.id]:void 0,f=n.route.errorElement||kRe,o&&(s<0&&c===0?(HRe(`route-fallback`,!1,"No `HydrateFallback` element provided to render during initial hydration"),d=!0,p=null):s===c&&(d=!0,p=n.route.hydrateFallbackElement||null)));let m=t.concat(i.slice(0,c+1)),h=()=>{let t;return t=u?f:d?p:n.route.Component?G.createElement(n.route.Component,null):n.route.element?n.route.element:e,G.createElement(NRe,{match:n,routeContext:{outlet:e,matches:m,isDataRoute:r!=null},children:t})};return r&&(n.route.ErrorBoundary||n.route.errorElement||c===0)?G.createElement(ARe,{location:r.location,revalidation:r.revalidation,component:f,error:u,children:h(),routeContext:{outlet:null,matches:m,isDataRoute:!0},onError:l}):h()},null)}function FRe(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function jv(e){let t=G.useContext(bv);return P_(t,FRe(e)),t}function IRe(e){let t=G.useContext(sRe);return P_(t,FRe(e)),t}function LRe(e){let t=G.useContext(cRe);return P_(t,FRe(e)),t}function RRe(e){let t=G.useContext(Tv);return P_(t,`${e} can only be used on routes that contain a unique "id"`),t}function zRe(){let e=G.useContext(hRe),t=LRe(`useRouteError`),n=RRe(`useRouteError`);return e===void 0?t.errors?.[n]:e}function BRe(){let{router:e}=jv(`useNavigate`),t=RRe(`useNavigate`),n=G.useRef(!1);return G.useLayoutEffect(()=>{n.current=!0}),G.useCallback(async(r,i={})=>{F_(n.current,CRe),n.current&&(typeof r==`number`?await e.navigate(r):await e.navigate(r,{fromRouteId:t,...i}))},[e,t])}var VRe={};function HRe(e,t,n){!t&&!VRe[e]&&(VRe[e]=!0,F_(!1,n))}function URe(e,t){if(e===!1||e==null)throw Error(t)}function WRe(e,t,n){let r=typeof e==`string`?new URL(e,n??(typeof window>`u`?`server://singlefetch/`:window.location.origin)):new URL(e);return n&&r.origin!==n&&(r=new URL(r.pathname+r.search+r.hash,n)),r.pathname.endsWith(`/`)?r.pathname=`${r.pathname}_.${t}`:r.pathname=`${r.pathname}.${t}`,r}async function GRe(e,t){if(e.id in t)return t[e.id];try{let n=await import(e.module);return t[e.id]=n,n}catch(t){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(t),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function KRe(e){return e!=null&&typeof e.page==`string`}function qRe(e){return e==null?!1:e.href==null?e.rel===`preload`&&typeof e.imageSrcSet==`string`&&typeof e.imageSizes==`string`:typeof e.rel==`string`&&typeof e.href==`string`}async function JRe(e,t,n){return $Re((await Promise.all(e.map(async e=>{let r=t.routes[e.route.id];if(r){let e=await GRe(r,n);return e.links?e.links():[]}return[]}))).flat(1).filter(qRe).filter(e=>e.rel===`stylesheet`||e.rel===`preload`).map(e=>e.rel===`stylesheet`?{...e,rel:`prefetch`,as:`style`}:{...e,rel:`prefetch`}))}function YRe(e,t,n,r,i,a){let o=(e,t)=>!n[t]||e.route.id!==n[t].route.id,s=(e,t)=>n[t].pathname!==e.pathname||n[t].route.path?.endsWith(`*`)&&n[t].params[`*`]!==e.params[`*`];return a===`assets`?t.filter((e,t)=>o(e,t)||s(e,t)):a===`data`?t.filter((t,a)=>{let c=r.routes[t.route.id];if(!c||!c.hasLoader)return!1;if(o(t,a)||s(t,a))return!0;if(t.route.shouldRevalidate){let r=t.route.shouldRevalidate({currentUrl:new URL(i.pathname+i.search+i.hash,window.origin),currentParams:n[0]?.params||{},nextUrl:new URL(e,window.origin),nextParams:t.params,defaultShouldRevalidate:!0});if(typeof r==`boolean`)return r}return!0}):[]}function XRe(e,t,{includeHydrateFallback:n}={}){return ZRe(e.map(e=>{let r=t.routes[e.route.id];if(!r)return[];let i=[r.module];return r.clientActionModule&&(i=i.concat(r.clientActionModule)),r.clientLoaderModule&&(i=i.concat(r.clientLoaderModule)),n&&r.hydrateFallbackModule&&(i=i.concat(r.hydrateFallbackModule)),r.imports&&(i=i.concat(r.imports)),i}).flat(1))}function ZRe(e){return[...new Set(e)]}function QRe(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function $Re(e,t){let n=new Set,r=new Set(t);return e.reduce((e,i)=>{if(t&&!KRe(i)&&i.as===`script`&&i.href&&r.has(i.href))return e;let a=JSON.stringify(QRe(i));return n.has(a)||(n.add(a),e.push({key:a,link:i})),e},[])}var eze={};function tze(e,t){!e&&!eze[t]&&(eze[t]=!0,console.warn(t))}var Mv=G.createContext(void 0);Mv.displayName=`FrameworkContext`;function Nv(){let e=G.useContext(Mv);return URe(e,`You must render this element inside a <HydratedRouter> element`),e}function nze(e,t){let n=G.useContext(Mv),[r,i]=G.useState(!1),[a,o]=G.useState(!1),{onFocus:s,onBlur:c,onMouseEnter:l,onMouseLeave:u,onTouchStart:d}=t,f=G.useRef(null);G.useEffect(()=>{if(e===`render`&&o(!0),e===`viewport`){let e=new IntersectionObserver(e=>{e.forEach(e=>{o(e.isIntersecting)})},{threshold:.5});return f.current&&e.observe(f.current),()=>{e.disconnect()}}},[e]),G.useEffect(()=>{if(r){let e=setTimeout(()=>{o(!0)},100);return()=>{clearTimeout(e)}}},[r]);let p=()=>{i(!0)},m=()=>{i(!1),o(!1)};return n?e===`intent`?[a,f,{onFocus:Pv(s,p),onBlur:Pv(c,m),onMouseEnter:Pv(l,p),onMouseLeave:Pv(u,m),onTouchStart:Pv(d,p)}]:[a,f,{}]:[!1,f,{}]}function Pv(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function rze({page:e,...t}){let n=dRe(),{nonce:r}=Nv(),{router:i}=jv(`PrefetchPageLinks`),a=G.useMemo(()=>i.match(e),[i,i.routes,e]);return a?(t.nonce==null&&r&&(t={...t,nonce:r}),n?G.createElement(aze,{page:e,matches:a,...t}):G.createElement(oze,{page:e,matches:a,...t})):null}function ize(e){let{manifest:t,routeModules:n}=Nv(),[r,i]=G.useState([]);return G.useEffect(()=>{let r=!1;return JRe(e,t,n).then(e=>{r||i(e)}),()=>{r=!0}},[e,t,n]),r}function aze({page:e,matches:t,...n}){let r=Dv(),{unstable_apiServerOrigin:i}=Nv(),a=G.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=WRe(e,`rsc`,i),a=!1,o=[];for(let e of t)typeof e.route.shouldRevalidate==`function`?a=!0:o.push(e.route.id);return a&&o.length>0&&n.searchParams.set(`_routes`,o.join(`,`)),[i?n.toString():n.pathname+n.search]},[e,r,t,i]);return G.createElement(G.Fragment,null,a.map(e=>G.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})))}function oze({page:e,matches:t,...n}){let r=Dv(),{manifest:i,routeModules:a,unstable_apiServerOrigin:o}=Nv(),{matches:s}=IRe(`PrefetchPageLinks`),{loaderData:c}=LRe(`PrefetchPageLinks`),l=G.useMemo(()=>YRe(e,t,s,i,r,`data`),[e,t,s,i,r]),u=G.useMemo(()=>YRe(e,t,s,i,r,`assets`),[e,t,s,i,r]),d=G.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=new Set,s=!1;if(t.forEach(e=>{let t=i.routes[e.route.id];t&&t.hasLoader&&(!l.some(t=>t.route.id===e.route.id)&&e.route.id in c&&a[e.route.id]?.shouldRevalidate||t.hasClientLoader?s=!0:n.add(e.route.id))}),n.size===0)return[];let u=WRe(e,`data`,o);return s&&n.size>0&&u.searchParams.set(`_routes`,t.filter(e=>n.has(e.route.id)).map(e=>e.route.id).join(`,`)),[o?u.toString():u.pathname+u.search]},[c,r,i,l,t,e,a,o]),f=G.useMemo(()=>XRe(u,i),[u,i]),p=ize(u);return G.createElement(G.Fragment,null,d.map(e=>G.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})),f.map(e=>G.createElement(`link`,{key:e,rel:`modulepreload`,href:e,...n})),p.map(({key:e,link:t})=>G.createElement(`link`,{key:e,nonce:n.nonce,...t,crossOrigin:t.crossOrigin??n.crossOrigin})))}function sze(...e){return t=>{e.forEach(e=>{typeof e==`function`?e(t):e!=null&&(e.current=t)})}}var cze=[`HydrateFallback`,`hydrateFallbackElement`],lze=class{status=`pending`;promise;resolve;reject;constructor(){this.promise=new Promise((e,t)=>{this.resolve=t=>{this.status===`pending`&&(this.status=`resolved`,e(t))},this.reject=e=>{this.status===`pending`&&(this.status=`rejected`,t(e))}})}};function uze(e,t){e.ready.catch(e=>{if(!(t.visibilityState===`hidden`||typeof e==`object`&&e&&`name`in e&&e.name===`AbortError`))throw e})}function dze({router:e,flushSync:t,onError:n,useTransitions:r}){r=dRe()||r;let[i,a]=G.useState(e.state),[o,s]=(0,G.useOptimistic)(i),c=G.useRef(o),[l,u]=G.useState(),[d,f]=G.useState({isTransitioning:!1}),[p,m]=G.useState(),[h,g]=G.useState(),[_,v]=G.useState(),y=G.useRef(new Map),b=G.useRef(new WeakSet),x=G.useCallback((i,{deletedFetchers:o,newErrors:l,flushSync:d,viewTransitionOpts:_})=>{c.current=i,l&&i.errors&&av.has(i.errors)&&(b.current.has(i.errors)?l=null:b.current.add(i.errors)),l&&n&&Object.values(l).forEach(e=>n(e,{location:i.location,params:i.matches[0]?.params??{},pattern:Y_(i.matches)})),i.fetchers.forEach((e,t)=>{e.data!==void 0&&y.current.set(t,e.data)}),o.forEach(e=>y.current.delete(e)),tze(d===!1||t!=null,'You provided the `flushSync` option to a router update, but you are not using the `<RouterProvider>` from `react-router/dom` so `ReactDOM.flushSync()` is unavailable. Please update your app to `import { RouterProvider } from "react-router/dom"` and ensure you have `react-dom` installed as a dependency to use the `flushSync` option.');let x=e.window!=null&&e.window.document!=null&&typeof e.window.document.startViewTransition==`function`;if(tze(_==null||x,"You provided the `viewTransition` option to a router update, but you do not appear to be running in a DOM environment as `window.startViewTransition` is not available."),!_||!x)t&&d?t(()=>a(i)):r===!1?a(i):G.startTransition(()=>{r===!0&&s(e=>fze(e,i)),a(i)});else if(t&&d){t(()=>{h&&(p?.resolve(),h.skipTransition()),f({isTransitioning:!0,flushSync:!0,currentLocation:_.currentLocation,nextLocation:_.nextLocation})});let n=e.window.document.startViewTransition(()=>{t(()=>a(i))});uze(n,e.window.document),n.finished.finally(()=>{t(()=>{m(void 0),g(void 0),u(void 0),f({isTransitioning:!1})})}),t(()=>g(n))}else h?(p?.resolve(),h.skipTransition(),v({state:i,currentLocation:_.currentLocation,nextLocation:_.nextLocation})):(u(i),f({isTransitioning:!0,flushSync:!1,currentLocation:_.currentLocation,nextLocation:_.nextLocation}))},[e.window,t,h,p,r,s,n]);G.useLayoutEffect(()=>e.subscribe(x),[e,x]),G.useLayoutEffect(()=>{let t=e.state.errors,n=t?av.get(t):null;(c.current!==e.state||t&&n&&!b.current.has(t))&&x(e.state,{deletedFetchers:[],flushSync:!1,newErrors:n??null})},[e,x]),G.useEffect(()=>{d.isTransitioning&&!d.flushSync&&m(new lze)},[d]),G.useEffect(()=>{if(p&&l&&e.window){let t=l,n=p.promise,i=e.window.document.startViewTransition(async()=>{r===!1?a(t):G.startTransition(()=>{r===!0&&s(e=>fze(e,t)),a(t)}),await n});uze(i,e.window.document),i.finished.finally(()=>{m(void 0),g(void 0),u(void 0),f({isTransitioning:!1})}),g(i)}},[l,p,e.window,r,s]),G.useEffect(()=>{p&&l&&o.location.key===l.location.key&&p.resolve()},[p,h,o.location,l]),G.useEffect(()=>{!d.isTransitioning&&_&&(u(_.state),f({isTransitioning:!0,flushSync:!1,currentLocation:_.currentLocation,nextLocation:_.nextLocation}),v(void 0))},[d.isTransitioning,_]);let S=G.useMemo(()=>({createHref:e.createHref,createURL:e.createURL,encodeLocation:e.encodeLocation,go:t=>e.navigate(t),push:(t,n,r)=>e.navigate(t,{state:n,preventScrollReset:r?.preventScrollReset}),replace:(t,n,r)=>e.navigate(t,{replace:!0,state:n,preventScrollReset:r?.preventScrollReset})}),[e]),C=e.basename||`/`,w=G.useMemo(()=>({router:e,navigator:S,static:!1,basename:C,onError:n}),[e,S,C,n]),T=G.useMemo(()=>({historyAction:o.historyAction,location:o.location,matches:o.matches,initialized:o.initialized,renderFallback:o.renderFallback,restoreScrollPosition:o.restoreScrollPosition,preventScrollReset:o.preventScrollReset,blockers:o.blockers}),[o.historyAction,o.location,o.matches,o.initialized,o.renderFallback,o.restoreScrollPosition,o.preventScrollReset,o.blockers]),E=G.useMemo(()=>({navigation:o.navigation,revalidation:o.revalidation}),[o.navigation,o.revalidation]),D=G.useMemo(()=>({loaderData:o.loaderData,actionData:o.actionData,errors:o.errors}),[o.loaderData,o.actionData,o.errors]),O=G.useMemo(()=>({fetchers:o.fetchers,fetcherData:y.current}),[o.fetchers]);return G.createElement(G.Fragment,null,G.createElement(bv.Provider,{value:w},G.createElement(sRe.Provider,{value:T},G.createElement(lRe.Provider,{value:E},G.createElement(cRe.Provider,{value:D},G.createElement(pRe.Provider,{value:O},G.createElement(fRe.Provider,{value:d},G.createElement(hze,{basename:C,location:o.location,navigationType:o.historyAction,navigator:S,useTransitions:r},G.createElement(pze,{routes:e.routes,manifest:e.manifest,state:o,isStatic:!1,onError:n})))))))),null)}function fze(e,t){return{...e,navigation:t.navigation.state===`idle`?e.navigation:t.navigation,revalidation:t.revalidation===`idle`?e.revalidation:t.revalidation,actionData:t.navigation.state===`submitting`?e.actionData:t.actionData,fetchers:t.fetchers}}var pze=G.memo(mze);function mze({routes:e,manifest:t,state:n,isStatic:r,onError:i}){let a=G.useContext(bv);P_(a,`You must render this element inside a <DataRouterContext.Provider> element`);let o=G.useContext(Mv)?.routeDiscoveryRuntime;return G.useEffect(()=>{n.initialized&&o?.markReady()},[n.initialized,o]),DRe(e,void 0,{router:a.router,manifest:t,state:n,isStatic:r,onError:i})}function Fv({to:e,replace:t,state:n,relative:r}){P_(Ev(),`<Navigate> may be used only in the context of a <Router> component.`);let{static:i,navigator:a}=G.useContext(xv);F_(!i,`<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.`);let{matches:o}=G.useContext(Cv),{pathname:s}=Dv(),c=Ov(),l=U_(e,H_(o),s,r===`path`);nv(typeof e==`string`?e:L_(e),a.createHref(l),KIe(a),`reject`);let u=JSON.stringify(l);return G.useEffect(()=>{c(JSON.parse(u),{replace:t,state:n,relative:r})},[c,u,r,t,n]),null}function Iv(e){return ERe(e.context)}function hze({basename:e=`/`,children:t=null,location:n,navigationType:r=`POP`,navigator:i,static:a=!1,useTransitions:o}){P_(!Ev(),`You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`);let s=e.replace(/^\/*/,`/`),c=G.useMemo(()=>({basename:s,navigator:i,static:a,useTransitions:o,future:{}}),[s,i,a,o]);typeof n==`string`&&(n=R_(n));let{pathname:l=`/`,search:u=``,hash:d=``,state:f=null,key:p=`default`,mask:m}=n,h=G.useMemo(()=>{let e=V_(l,s);return e==null?null:{location:{pathname:e,search:u,hash:d,state:f,key:p,mask:m},navigationType:r}},[s,l,u,d,f,p,r,m]);return F_(h!=null,`<Router basename="${s}"> is not able to match the URL "${l}${u}${d}" because it does not start with the basename, so the <Router> won't render anything.`),h==null?null:G.createElement(xv.Provider,{value:c},G.createElement(Sv.Provider,{children:t,value:h}))}G.Component;var gze=`application/x-www-form-urlencoded`;function _ze(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}function vze(e){return _ze(e)&&e.tagName.toLowerCase()===`button`}function yze(e){return _ze(e)&&e.tagName.toLowerCase()===`form`}function bze(e){return _ze(e)&&e.tagName.toLowerCase()===`input`}function xze(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function Sze(e,t){return e.button===0&&(!t||t===`_self`)&&!xze(e)}function Cze(e=``){return new URLSearchParams(typeof e==`string`||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(e=>[n,e]):[[n,r]])},[]))}function wze(e,t){let n=Cze(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}var Tze=null;function Eze(){if(Tze===null)try{new FormData(document.createElement(`form`),0),Tze=!1}catch{Tze=!0}return Tze}var Dze=new Set([`application/x-www-form-urlencoded`,`multipart/form-data`,`text/plain`]);function Oze(e){return e!=null&&!Dze.has(e)?(F_(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${gze}"`),null):e}function kze(e,t){let n,r,i,a,o;if(yze(e)){let o=e.getAttribute(`action`);r=o?V_(o,t):null,n=e.getAttribute(`method`)||`get`,i=Oze(e.getAttribute(`enctype`))||gze,a=new FormData(e)}else if(vze(e)||bze(e)&&(e.type===`submit`||e.type===`image`)){let o=e.form;if(o==null)throw Error(`Cannot submit a <button> or <input type="submit"> without a <form>`);let s=e.getAttribute(`formaction`)||o.getAttribute(`action`);if(r=s?V_(s,t):null,n=e.getAttribute(`formmethod`)||o.getAttribute(`method`)||`get`,i=Oze(e.getAttribute(`formenctype`))||Oze(o.getAttribute(`enctype`))||gze,a=new FormData(o,e),!Eze()){let{name:t,type:n,value:r}=e;if(n===`image`){let e=t?`${t}.`:``;a.append(`${e}x`,`0`),a.append(`${e}y`,`0`)}else t&&a.append(t,r)}}else if(_ze(e))throw Error(`Cannot submit element that is not <form>, <button>, or <input type="submit|image">`);else n=`get`,r=null,i=gze,o=e;return a&&i===`text/plain`&&(o=a,a=void 0),{action:r,method:n.toLowerCase(),encType:i,formData:a,body:o}}var Aze=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;try{Aze&&(window.__reactRouterVersion=`8`)}catch{}function jze(e,t){return oLe({basename:t?.basename,getContext:t?.getContext,future:t?.future,history:zFe({window:t?.window}),hydrationData:t?.hydrationData||Mze(),routes:e,mapRouteProperties:ZFe,hydrationRouteProperties:cze,dataStrategy:t?.dataStrategy,patchRoutesOnNavigation:t?.patchRoutesOnNavigation,window:t?.window,instrumentations:t?.instrumentations}).initialize()}function Mze(){let e=window?.__staticRouterHydrationData;return e&&e.errors&&(e={...e,errors:Nze(e.errors)}),e}function Nze(e){if(!e)return null;let t=Object.entries(e),n={};for(let[e,r]of t)if(r&&r.__type===`RouteErrorResponse`)n[e]=new q_(r.status,r.statusText,r.data,r.internal===!0);else if(r&&r.__type===`Error`){if(typeof r.__subType==`string`&&jIe.includes(r.__subType)){let t=window[r.__subType];if(typeof t==`function`)try{let i=new t(r.message);i.stack=``,n[e]=i}catch{}}if(n[e]==null){let t=Error(r.message);t.stack=``,n[e]=t}}else n[e]=r;return n}var Lv=G.forwardRef(function({onClick:e,discover:t=`render`,prefetch:n=`none`,relative:r,reloadDocument:i,replace:a,mask:o,state:s,target:c,to:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m){let{basename:h,navigator:g,useTransitions:_}=G.useContext(xv),v=typeof l==`string`&&M_.test(l),y=PIe(l,h);l=y.to;let b=xRe(l,{relative:r}),x=Dv(),S=null;if(o){let e=U_(o,[],x.mask?x.mask.pathname:`/`,!0);h!==`/`&&(e.pathname=e.pathname===`/`?h:W_([h,e.pathname])),S=g.createHref(e)}let[C,w,T]=nze(n,p),E=Ize(l,{replace:a,mask:o,state:s,target:c,preventScrollReset:u,relative:r,viewTransition:d,defaultShouldRevalidate:f,useTransitions:_});function D(t){e&&e(t),t.defaultPrevented||E(t)}let O=!(y.isExternal||i),k=G.createElement(`a`,{...p,...T,href:(O?S:void 0)||y.absoluteURL||b,onClick:O?D:e,ref:sze(m,w),target:c,"data-discover":!v&&t===`render`?`true`:void 0});return C&&!v?G.createElement(G.Fragment,null,k,G.createElement(rze,{page:b})):k});Lv.displayName=`Link`;var Pze=G.forwardRef(function({"aria-current":e=`page`,caseSensitive:t=!1,className:n=``,end:r=!1,style:i,to:a,viewTransition:o,children:s,...c},l){let u=Av(a,{relative:c.relative}),d=Dv(),f=G.useContext(lRe),{navigator:p,basename:m}=G.useContext(xv),h=f!=null&&Vze(u)&&o===!0,g=p.encodeLocation?p.encodeLocation(u).pathname:u.pathname,_=d.pathname,v=f?.navigation.location?f.navigation.location.pathname:null;t||(_=_.toLowerCase(),v=v?v.toLowerCase():null,g=g.toLowerCase()),v&&m&&(v=V_(v,m)||v);let y=g!==`/`&&g.endsWith(`/`)?g.length-1:g.length,b=_===g||!r&&_.startsWith(g)&&_.charAt(y)===`/`,x=v!=null&&(v===g||!r&&v.startsWith(g)&&v.charAt(y)===`/`),S={isActive:b,isPending:x,isTransitioning:h},C=b?e:void 0,w;w=typeof n==`function`?n(S):[n,b?`active`:null,x?`pending`:null,h?`transitioning`:null].filter(Boolean).join(` `);let T=typeof i==`function`?i(S):i;return G.createElement(Lv,{...c,"aria-current":C,className:w,ref:l,style:T,to:a,viewTransition:o},typeof s==`function`?s(S):s)});Pze.displayName=`NavLink`;var Fze=G.forwardRef(({discover:e=`render`,fetcherKey:t,navigate:n,reloadDocument:r,replace:i,state:a,method:o=`get`,action:s,onSubmit:c,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m)=>{let{useTransitions:h}=G.useContext(xv),g=zze(),_=Bze(s,{relative:l}),v=o.toLowerCase()===`get`?`get`:`post`,y=typeof s==`string`&&M_.test(s);return G.createElement(`form`,{ref:m,method:v,action:_,onSubmit:r?c:e=>{if(c&&c(e),e.defaultPrevented)return;e.preventDefault();let r=e.nativeEvent.submitter,s=r?.getAttribute(`formmethod`)||o,p=()=>g(r||e.currentTarget,{fetcherKey:t,method:s,navigate:n,replace:i,state:a,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f});h&&n!==!1?G.startTransition(()=>p()):p()},...p,"data-discover":!y&&e===`render`?`true`:void 0})});Fze.displayName=`Form`;function Ize(e,{target:t,replace:n,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c,useTransitions:l}={}){let u=Ov(),d=Dv(),f=Av(e,{relative:o});return G.useCallback(p=>{if(Sze(p,t)){p.preventDefault();let t=n===void 0?L_(d)===L_(f):n,m=()=>u(e,{replace:t,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c});l?G.startTransition(()=>m()):m()}},[d,u,f,n,r,i,t,e,a,o,s,c,l])}function Rv(e){F_(typeof URLSearchParams<`u`,"You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let t=G.useRef(Cze(e)),n=G.useRef(!1),r=Dv(),i=G.useMemo(()=>wze(r.search,n.current?null:t.current),[r.search]),a=Ov();return[i,G.useCallback((e,t)=>{let r=Cze(typeof e==`function`?e(new URLSearchParams(i)):e);n.current=!0,a(`?`+r,t)},[a,i])]}var Lze=0,Rze=()=>`__${String(++Lze)}__`;function zze(){let{router:e}=jv(`useSubmit`),{basename:t}=G.useContext(xv),n=RRe(`useSubmit`),r=e.fetch,i=e.navigate;return G.useCallback(async(e,a={})=>{let{action:o,method:s,encType:c,formData:l,body:u}=kze(e,t);a.navigate===!1?await r(a.fetcherKey||Rze(),n,a.action||o,{defaultShouldRevalidate:a.defaultShouldRevalidate,preventScrollReset:a.preventScrollReset,relative:a.relative,formData:l,body:u,formMethod:a.method||s,formEncType:a.encType||c,flushSync:a.flushSync}):await i(a.action||o,{defaultShouldRevalidate:a.defaultShouldRevalidate,preventScrollReset:a.preventScrollReset,relative:a.relative,formData:l,body:u,formMethod:a.method||s,formEncType:a.encType||c,replace:a.replace,state:a.state,fromRouteId:n,flushSync:a.flushSync,viewTransition:a.viewTransition})},[r,i,t,n])}function Bze(e,{relative:t}={}){let{basename:n}=G.useContext(xv),r=G.useContext(Cv);P_(r,`useFormAction must be used inside a RouteContext`);let[i]=r.matches.slice(-1),a={...Av(e||`.`,{relative:t})},o=Dv();if(e==null){a.search=o.search;let e=new URLSearchParams(a.search),t=e.getAll(`index`);if(t.some(e=>e===``)){e.delete(`index`),t.filter(e=>e).forEach(t=>e.append(`index`,t));let n=e.toString();a.search=n?`?${n}`:``}}return(!e||e===`.`)&&i.route.index&&(a.search=a.search?a.search.replace(/^\?/,`?index&`):`?index`),n!==`/`&&(a.pathname=a.pathname===`/`?n:W_([n,a.pathname])),L_(a)}function Vze(e,{relative:t}={}){let n=G.useContext(fRe);P_(n!=null,"`useViewTransitionState` must be used within `react-router/dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=jv(`useViewTransitionState`),i=Av(e,{relative:t});if(!n.isTransitioning)return!1;let a=V_(n.currentLocation.pathname,r)||n.currentLocation.pathname,o=V_(n.nextLocation.pathname,r)||n.nextLocation.pathname;return B_(i.pathname,o)!=null||B_(i.pathname,a)!=null}var zv=`fixed`,Hze=`[--field:var(--field-on-surface)] [--field-disabled:var(--field-on-surface)] [--field-rim:var(--field-rim-on-surface)]`,Uze=`[--field:var(--card)] [--field-disabled:var(--fill-subtle)] [--field-rim:var(--surface-rim)]`,Bv=`bg-card hover:bg-card active:bg-card shadow-raised `+Hze,Vv=`bg-card shadow-overlay `+Hze,Wze=`bg-dialog shadow-overlay [--field:var(--field-on-surface)] [--field-disabled:var(--field-on-surface)] [--field-rim:var(--surface-rim)]`,Gze=`bg-background shadow-raised `+Uze,Kze=`bg-background `+Uze,qze=`state-layer`,Jze=`group-hover:bg-[linear-gradient(var(--fill-subtle),var(--fill-subtle))] group-focus-visible:bg-[linear-gradient(var(--fill-subtle),var(--fill-subtle))]`,Yze=[],Xze=void 0;function Zze(){return Xze}function Qze(e){Yze.push(e)}function Hv(e){let t=(t,n)=>{let r=s($ze).current,i;try{Xze=r;for(let e of Yze)e.before(r);i=e(t,n);for(let e of Yze)e.after(r);r.didInitialize=!0}finally{Xze=void 0}return i};return t.displayName=e.displayName||e.name,t}function Uv(e){return G.forwardRef(Hv(e))}function $ze(){return{didInitialize:!1}}var Wv=typeof document<`u`?G.useLayoutEffect:()=>{};function eBe(e,t){return function(n,...r){let i=new URL(e);return i.searchParams.set(`code`,n.toString()),r.forEach(e=>i.searchParams.append(`args[]`,e)),`${t} error #${n}; visit ${i} for the full message.`}}var Gv=eBe(`https://base-ui.com/production-error`,`Base UI`),tBe=G.createContext(void 0);function Kv(e){let t=G.useContext(tBe);if(t===void 0&&!e)throw Error(Gv(72));return t}function nBe(e){G.useEffect(e,V)}var qv=0,Jv=class e{static create(){return new e}currentId=qv;start(e,t){this.clear(),this.currentId=setTimeout(()=>{this.currentId=qv,t()},e)}isStarted(){return this.currentId!==qv}clear=()=>{this.currentId!==qv&&(clearTimeout(this.currentId),this.currentId=qv)};disposeEffect=()=>this.clear};function Yv(){let e=s(Jv.create).current;return nBe(e.disposeEffect),e}function rBe(){return typeof navigator>`u`?{userAgent:``,platform:``,maxTouchPoints:0}:{userAgent:navigator.userAgent,platform:navigator.platform??``,maxTouchPoints:navigator.maxTouchPoints??0}}var{userAgent:iBe,platform:aBe,maxTouchPoints:oBe}=rBe(),sBe=iBe.toLowerCase(),Xv=aBe.toLowerCase(),Zv=/^i(os$|p)/.test(Xv)||Xv===`macintel`&&oBe>1,cBe=`android`,Qv=Xv===cBe||sBe.includes(cBe),lBe=!Zv&&Xv.startsWith(`mac`);Xv.startsWith(`win`),!Qv&&/^(linux|chrome os)/.test(Xv);var uBe=lBe||Zv,$v=typeof CSS<`u`&&!!CSS.supports?.(`-webkit-backdrop-filter:none`),dBe=!$v&&sBe.includes(`firefox`);!$v&&sBe.includes(`chrom`);var fBe=uBe,pBe=/jsdom|happydom/.test(sBe);function ey(e){e.preventDefault(),e.stopPropagation()}function mBe(e){return`nativeEvent`in e}function ty(e){return e.pointerType===``&&e.isTrusted?!0:Qv&&e.pointerType?e.type===`click`&&e.buttons===1:e.detail===0&&!e.pointerType}function hBe(e){return pBe?!1:!Qv&&e.width===0&&e.height===0||e.type===`pointerdown`&&e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType===`mouse`&&(Qv||e.buttons===0)||e.width<1&&e.height<1&&e.pressure===0&&e.detail===0&&e.pointerType===`touch`}function ny(e,t){let n=[`mouse`,`pen`];return t||n.push(``,void 0),n.includes(e)}function gBe(e){let t=e.type;return t===`click`||t===`mousedown`||t===`keydown`||t===`keyup`}function _Be(){return typeof window<`u`}function ry(e){return vBe(e)?(e.nodeName||``).toLowerCase():`#document`}function iy(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function ay(e){return((vBe(e)?e.ownerDocument:e.document)||window.document)?.documentElement}function vBe(e){return _Be()?e instanceof Node||e instanceof iy(e).Node:!1}function oy(e){return _Be()?e instanceof Element||e instanceof iy(e).Element:!1}function sy(e){return _Be()?e instanceof HTMLElement||e instanceof iy(e).HTMLElement:!1}function cy(e){return!_Be()||typeof ShadowRoot>`u`?!1:e instanceof ShadowRoot||e instanceof iy(e).ShadowRoot}function ly(e){let{overflow:t,overflowX:n,overflowY:r,display:i}=fy(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!==`inline`&&i!==`contents`}function yBe(e){return/^(table|td|th)$/.test(ry(e))}function bBe(e){try{if(e.matches(`:popover-open`))return!0}catch{}try{return e.matches(`:modal`)}catch{return!1}}var xBe=/transform|translate|scale|rotate|perspective|filter/,SBe=/paint|layout|strict|content/,uy=e=>!!e&&e!==`none`,CBe;function wBe(e){let t=oy(e)?fy(e):e;return uy(t.transform)||uy(t.translate)||uy(t.scale)||uy(t.rotate)||uy(t.perspective)||!EBe()&&(uy(t.backdropFilter)||uy(t.filter))||xBe.test(t.willChange||``)||SBe.test(t.contain||``)}function TBe(e){let t=py(e);for(;sy(t)&&!dy(t);){if(wBe(t))return t;if(bBe(t))return null;t=py(t)}return null}function EBe(){return CBe??=typeof CSS<`u`&&CSS.supports&&CSS.supports(`-webkit-backdrop-filter`,`none`),CBe}function dy(e){return/^(html|body|#document)$/.test(ry(e))}function fy(e){return iy(e).getComputedStyle(e)}function DBe(e){return oy(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function py(e){if(ry(e)===`html`)return e;let t=e.assignedSlot||e.parentNode||cy(e)&&e.host||ay(e);return cy(t)?t.host:t}function OBe(e){let t=py(e);return dy(t)?(e.ownerDocument||e).body:sy(t)&&ly(t)?t:OBe(t)}function my(e,t,n){t===void 0&&(t=[]),n===void 0&&(n=!0);let r=OBe(e),i=r===e.ownerDocument?.body,a=iy(r);if(i){let e=kBe(a);return t.concat(a,a.visualViewport||[],ly(r)?r:[],e&&n?my(e):[])}return t.concat(r,my(r,[],n))}function kBe(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function hy(e){let t=e.activeElement;for(;t?.shadowRoot?.activeElement!=null;)t=t.shadowRoot.activeElement;return t}function gy(e,t){if(!e||!t)return!1;let n=t.getRootNode?.();if(e.contains(t))return!0;if(n&&cy(n)){let n=t;for(;n;){if(e===n)return!0;n=n.parentNode||n.host}}return!1}function _y(e,t){let n=e;for(;n;){if(oy(n)&&n.matches(t))return n;n=n.assignedSlot??n.parentNode??(cy(n)?n.host:null)}return null}function vy(e){return`composedPath`in e?e.composedPath()[0]??e.target:e.target}var ABe=`data-base-ui-focusable`,jBe=`input:not([type='hidden']):not([disabled]),[contenteditable]:not([contenteditable='false']),textarea:not([disabled])`,MBe=`ArrowLeft`,NBe=`ArrowRight`,PBe=`ArrowUp`,FBe=`ArrowDown`,IBe=`data-starting-style`,LBe=`data-ending-style`,RBe={[IBe]:``},zBe={[LBe]:``},yy={transitionStatus(e){return e===`starting`?RBe:e===`ending`?zBe:null}},BBe=`data-open`,VBe=`data-closed`,HBe=`data-anchor-hidden`,UBe=`data-popup-open`,WBe=`data-pressed`,GBe={[UBe]:``},KBe={[UBe]:``,[WBe]:``},qBe={[BBe]:``},JBe={[VBe]:``},YBe={[HBe]:``},by={open(e){return e?GBe:null}},xy={open(e){return e?KBe:null}},Sy={open(e){return e?qBe:JBe},anchorHidden(e){return e?YBe:null}},Cy={...Sy,...yy},XBe=`data-trigger-disabled`;function ZBe(e,t){if(!oy(e))return!1;let n=e;if(t.hasElement(n))return!n.hasAttribute(XBe);for(let[,e]of t.entries())if(gy(e,n))return!e.hasAttribute(XBe);return!1}function QBe(e,t){if(t==null)return!1;if(`composedPath`in e)return e.composedPath().includes(t);let n=e;return n.target!=null&&t.contains(n.target)}function $Be(e){return e.matches(`html,body`)}function wy(e){return sy(e)&&e.matches(`input:not([type='hidden']):not([disabled]),[contenteditable]:not([contenteditable='false']),textarea:not([disabled])`)}function eVe(e){return _y(e,`button,a[href],[role="button"],select,[tabindex]:not([tabindex="-1"]),${jBe}`)!=null}function tVe(e){return e?e.getAttribute(`role`)===`combobox`&&wy(e):!1}function nVe(e){if(!e||pBe)return!0;try{return e.matches(`:focus-visible`)}catch{return!0}}function rVe(e){return e?e.hasAttribute(`data-base-ui-focusable`)?e:e.querySelector(`[data-base-ui-focusable]`)||e:null}function iVe(e,t){return t!=null&&!ny(t)?0:typeof e==`function`?e():e}function Ty(e,t,n){let r=iVe(e,n);return typeof r==`number`?r:r?.[t]}function aVe(e){return typeof e==`function`?e():e}function oVe(e,t){return t||e===`click`||e===`mousedown`}function sVe(e){return e?.includes(`mouse`)&&e!==`mousedown`}function Ey(e,t,n,r){let i=!1,a=!1,o=r??te;return{reason:e,event:t??new Event(`base-ui`),cancel(){i=!0},allowPropagation(){a=!0},get isCanceled(){return i},get isPropagationAllowed(){return a},trigger:n,...o}}function Dy(e,t,n){let r=n??te;return{reason:e,event:t??new Event(`base-ui`),...r}}var Oy=`none`,ky=`trigger-press`,Ay=`trigger-hover`,cVe=`trigger-focus`,lVe=`outside-press`,jy=`item-press`,uVe=`close-press`,dVe=`clear-press`,fVe=`chip-remove-press`,pVe=`track-press`,My=`input-change`,Ny=`input-clear`,mVe=`input-press`,hVe=`focus-out`,gVe=`escape-key`,_Ve=`close-watcher`,vVe=`list-navigation`,yVe=`keyboard`,bVe=`pointer`,xVe=`drag`,SVe=`cancel-open`,CVe=`sibling-open`,wVe=`disabled`,TVe=`missing`,EVe=`initial`,Py=`imperative-action`,Fy=`swipe`,DVe=`window-resize`,OVe=G.createContext({hasProvider:!1,timeoutMs:0,delayRef:{current:0},initialDelayRef:{current:0},timeout:new Jv,currentIdRef:{current:null},currentContextRef:{current:null}});function kVe(e,t){e.current=t.current}function AVe(e){let{children:t,delay:n,timeoutMs:r=0}=e,i=G.useRef(n),a=G.useRef(n),o=G.useRef(null),s=G.useRef(null),c=Yv();return Wv(()=>{a.current=n,o.current?i.current={open:Ty(i.current,`open`),close:Ty(n,`close`)}:i.current=n},[n,o,i,a]),(0,K.jsx)(OVe.Provider,{value:G.useMemo(()=>({hasProvider:!0,delayRef:i,initialDelayRef:a,currentIdRef:o,timeoutMs:r,currentContextRef:s,timeout:c}),[r,c]),children:t})}function jVe(e,t={open:!1}){let{open:n}=t,r=e.useState(`floatingId`),{currentIdRef:i,delayRef:a,timeoutMs:o,initialDelayRef:s,currentContextRef:c,hasProvider:l,timeout:u}=G.useContext(OVe),[d,f]=G.useState(!1),p=G.useRef(n);return Wv(()=>{p.current=n},[n]),Wv(()=>{function t(){c.current?.setIsInstantPhase(!1),i.current=null,c.current=null,a.current=s.current,u.clear()}if(i.current&&!n&&i.current===r){if(f(!1),o){let n=r;return u.start(o,()=>{e.select(`open`)||i.current&&i.current!==n||t()}),()=>{(p.current||i.current!==n)&&u.clear()}}t()}},[n,r,i,a,o,s,c,u,e]),Wv(()=>{if(!n)return;let t=c.current,o=i.current;u.clear(),c.current={onOpenChange:e.setOpen,setIsInstantPhase:f},i.current=r,a.current={open:0,close:Ty(s.current,`close`)},o!==null&&o!==r?(f(!0),t?.setIsInstantPhase(!0),t?.onOpenChange(!1,Ey(Oy))):(f(!1),t?.setIsInstantPhase(!1))},[n,r,e,i,a,s,c,u]),Wv(()=>()=>{if(i.current===r){if(c.current=null,!p.current)return;i.current=null,kVe(a,s),u.clear()}},[c,i,a,r,s,u]),G.useMemo(()=>({activeIdRef:i,hasProvider:l,delayRef:a,isInstantPhase:d}),[i,l,a,d])}function Iy(e,t,n,r){return e.addEventListener(t,n,r),()=>{e.removeEventListener(t,n,r)}}function Ly(...e){return()=>{for(let t=0;t<e.length;t+=1){let n=e[t];n&&n()}}}function Ry(e){let t=s(MVe,e).current;return t.next=e,Wv(t.effect),t}function MVe(e){let t={current:e,next:e,effect:()=>{t.current=t.next}};return t}var NVe={...G},PVe=NVe.useInsertionEffect,FVe=PVe&&PVe!==NVe.useLayoutEffect?PVe:e=>e();function zy(e){let t=s(IVe).current;return t.next=e,FVe(t.effect),t.trampoline}function IVe(){let e={next:void 0,callback:LVe,trampoline:(...t)=>e.callback?.(...t),effect:()=>{e.callback=e.next}};return e}function LVe(){}var By=null;globalThis.requestAnimationFrame;var Vy=new class{callbacks=[];callbacksCount=0;nextId=1;startId=1;isScheduled=!1;tick=e=>{this.isScheduled=!1;let t=this.callbacks,n=this.callbacksCount;if(this.callbacks=[],this.callbacksCount=0,this.startId=this.nextId,n>0)for(let n=0;n<t.length;n+=1)t[n]?.(e)};request(e){let t=this.nextId;return this.nextId+=1,this.callbacks.push(e),this.callbacksCount+=1,this.isScheduled||=(requestAnimationFrame(this.tick),!0),t}cancel(e){let t=e-this.startId;t<0||t>=this.callbacks.length||this.callbacks[t]!==null&&(this.callbacks[t]=null,--this.callbacksCount)}},Hy=class e{static create(){return new e}static request(e){return Vy.request(e)}static cancel(e){return Vy.cancel(e)}currentId=By;request(e){this.cancel(),this.currentId=Vy.request(()=>{this.currentId=By,e()})}cancel=()=>{this.currentId!==By&&(Vy.cancel(this.currentId),this.currentId=By)};disposeEffect=()=>this.cancel};function Uy(){let e=s(Hy.create).current;return nBe(e.disposeEffect),e}function Wy(e){return e?.ownerDocument||document}var RVe={clipPath:`inset(50%)`,overflow:`hidden`,whiteSpace:`nowrap`,border:0,padding:0,width:1,height:1,margin:-1},Gy={...RVe,position:`fixed`,margin:0,top:0,left:0},Ky={...RVe,position:`absolute`},qy=G.forwardRef(function(e,t){let[n,r]=G.useState();Wv(()=>{fBe&&$v&&r(`button`)},[]);let i={tabIndex:0,role:n};return(0,K.jsx)(`span`,{...e,ref:t,style:Gy,"aria-hidden":!n||void 0,...i,"data-base-ui-focus-guard":``})}),Jy=Math.min,Yy=Math.max,Xy=Math.round,Zy=Math.floor,Qy=e=>({x:e,y:e}),zVe={left:`right`,right:`left`,bottom:`top`,top:`bottom`};function BVe(e,t,n){return Yy(e,Jy(t,n))}function $y(e,t){return typeof e==`function`?e(t):e}function eb(e){return e.split(`-`)[0]}function tb(e){return e.split(`-`)[1]}function VVe(e){return e===`x`?`y`:`x`}function HVe(e){return e===`y`?`height`:`width`}function nb(e){let t=e[0];return t===`t`||t===`b`?`y`:`x`}function UVe(e){return VVe(nb(e))}function WVe(e,t,n){n===void 0&&(n=!1);let r=tb(e),i=UVe(e),a=HVe(i),o=i===`x`?r===(n?`end`:`start`)?`right`:`left`:r===`start`?`bottom`:`top`;return t.reference[a]>t.floating[a]&&(o=rb(o)),[o,rb(o)]}function GVe(e){let t=rb(e);return[KVe(e),t,KVe(t)]}function KVe(e){return e.includes(`start`)?e.replace(`start`,`end`):e.replace(`end`,`start`)}var qVe=[`left`,`right`],JVe=[`right`,`left`],YVe=[`top`,`bottom`],XVe=[`bottom`,`top`];function ZVe(e,t,n){switch(e){case`top`:case`bottom`:return n?t?JVe:qVe:t?qVe:JVe;case`left`:case`right`:return t?YVe:XVe;default:return[]}}function QVe(e,t,n,r){let i=tb(e),a=ZVe(eb(e),n===`start`,r);return i&&(a=a.map(e=>e+`-`+i),t&&(a=a.concat(a.map(KVe)))),a}function rb(e){let t=eb(e);return zVe[t]+e.slice(t.length)}function $Ve(e){return{top:e.top??0,right:e.right??0,bottom:e.bottom??0,left:e.left??0}}function eHe(e){return typeof e==`number`?{top:e,right:e,bottom:e,left:e}:$Ve(e)}function ib(e){let{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function ab(e,t,n){return Math.floor(e/t)!==n}function ob(e,t){return t<0||t>=e.length}function sb(e,t){return cb(e.current,{disabledIndices:t})}function tHe(e,t){return cb(e.current,{decrement:!0,startingIndex:e.current.length,disabledIndices:t})}function nHe(e,t,n){let{decrement:r,loopFocus:i,allowEscape:a,disabledIndices:o,minIndex:s,maxIndex:c}=n,l=()=>cb(e,{startingIndex:t,decrement:r,disabledIndices:o}),u,d=!1;if(!i)u=r?Math.max(s,l()):Math.min(c,l());else if(r?t<=s:t>=c){let n=r?-1:e.length;a&&t!==n?u=-1:(u=r?c:s,d=!0)}else u=l();return{index:ob(e,u)?-1:u,wrapped:d}}function cb(e,{startingIndex:t=-1,decrement:n=!1,disabledIndices:r,amount:i=1}={}){let a=t;do a+=n?-i:i;while(a>=0&&a<=e.length-1&&lb(e,a,r));return a}function rHe(e,{event:t,orientation:n,loopFocus:r,onLoop:i,rtl:a,cols:o,disabledIndices:s,minIndex:c,maxIndex:l,prevIndex:u,stopEvent:d=!1}){let f=u,p;if(t.key===`ArrowUp`?p=`up`:t.key===`ArrowDown`&&(p=`down`),p){let n=[],a=[],m=!1,h=0;{let t=null,r=-1;e.forEach((e,i)=>{if(e==null)return;h+=1;let o=_y(e,`[role="row"]`);o&&(m=!0),(o!==t||r===-1)&&(t=o,r+=1,n[r]=[]),n[r].push(i),a[i]=r})}let g=!1,_=0;if(m)for(let e of n){let t=e.length;t>_&&(_=t),t!==o&&(g=!0)}let v=g&&h<e.length,y=_||o,b=o=>{if(!g||u===-1)return;let c=a[u];if(c==null)return;let l=n[c].indexOf(u),d=o===`up`?-1:1;for(let o=c+d,f=0;f<n.length;f+=1,o+=d){if(o<0||o>=n.length){if(!r||v)return;if(o=o<0?n.length-1:0,i){let e=Math.min(l,n[o].length-1),r=i(t,u,n[o][e]??n[o][0]);o=a[r]??o}}let c=n[o];for(let t=Math.min(l,c.length-1);t>=0;--t){let n=c[t];if(!lb(e,n,s))return n}}},x=t=>{if(!v||u===-1)return;let n=u%y,i=t===`up`?-y:y,a=l-l%y,o=Zy(l/y)+1;for(let t=u-n+i,c=0;c<o;c+=1,t+=i){if(t<0||t>l){if(!r)return;t=t<0?a:0}let i=Math.min(t+y-1,l);for(let r=Math.min(t+n,i);r>=t;--r)if(!lb(e,r,s))return r}};d&&ey(t);let S=b(p)??x(p);if(S!==void 0)f=S;else if(u===-1)f=p===`up`?l:c;else if(f=cb(e,{startingIndex:u,amount:y,decrement:p===`up`,disabledIndices:s}),r){if(p===`up`&&(u-y<c||f<0)){let e=u%y,n=l%y,r=l-(n-e);f=n===e?l:n>e?r:r-y,i&&(f=i(t,u,f))}p===`down`&&u+y>l&&(f=cb(e,{startingIndex:u%y-y,amount:y,disabledIndices:s}),i&&(f=i(t,u,f)))}ob(e,f)&&(f=u)}if(n===`both`){let n=Zy(u/o);t.key===(a?`ArrowLeft`:`ArrowRight`)&&(d&&ey(t),u%o===o-1?r&&(f=cb(e,{startingIndex:u-u%o-1,disabledIndices:s}),i&&(f=i(t,u,f))):(f=cb(e,{startingIndex:u,disabledIndices:s}),r&&ab(f,o,n)&&(f=cb(e,{startingIndex:u-u%o-1,disabledIndices:s}),i&&(f=i(t,u,f)))),ab(f,o,n)&&(f=u)),t.key===(a?`ArrowRight`:`ArrowLeft`)&&(d&&ey(t),u%o===0?r&&(f=cb(e,{startingIndex:u+(o-u%o),decrement:!0,disabledIndices:s}),i&&(f=i(t,u,f))):(f=cb(e,{startingIndex:u,decrement:!0,disabledIndices:s}),r&&ab(f,o,n)&&(f=cb(e,{startingIndex:u+(o-u%o),decrement:!0,disabledIndices:s}),i&&(f=i(t,u,f)))),ab(f,o,n)&&(f=u));let c=Zy(l/o)===n;ob(e,f)&&(r&&c?(f=t.key===(a?`ArrowRight`:`ArrowLeft`)?l:cb(e,{startingIndex:u-u%o-1,disabledIndices:s}),i&&(f=i(t,u,f))):f=u)}return f}function lb(e,t,n){if(typeof n==`function`?n(t):n?.includes(t)??!1)return!0;let r=e[t];return r?!ub(r)||r.matches(`:disabled`)?!0:!n&&(r.hasAttribute(`disabled`)||r.getAttribute(`aria-disabled`)===`true`):!1}function iHe(e){return e.visibility===`hidden`||e.visibility===`collapse`}function ub(e,t=e?fy(e):null){return!e||!e.isConnected||!t||iHe(t)?!1:typeof e.checkVisibility==`function`?e.checkVisibility():t.display!==`none`&&t.display!==`contents`}var aHe=`a[href],button,input,select,textarea,summary,details,iframe,object,embed,[tabindex],[contenteditable]:not([contenteditable="false"]),audio[controls],video[controls]`;function oHe(e){let t=e.assignedSlot;if(t)return t;if(e.parentElement)return e.parentElement;let n=e.getRootNode();return cy(n)?n.host:null}function sHe(e){for(let t of Array.from(e.children))if(ry(t)===`summary`)return t;return null}function cHe(e,t){let n=sHe(t);return!!n&&(e===n||gy(n,e))}function lHe(e){let t=e?ry(e):``;return e!=null&&e.matches(aHe)&&(t!==`summary`||e.parentElement!=null&&ry(e.parentElement)===`details`&&sHe(e.parentElement)===e)&&(t!==`details`||sHe(e)==null)&&(t!==`input`||e.type!==`hidden`)}function uHe(e){if(!lHe(e)||!e.isConnected||e.matches(`:disabled`))return!1;for(let t=e;t;t=oHe(t)){let n=t!==e,r=ry(t)===`slot`;if(t.hasAttribute(`inert`)||n&&ry(t)===`details`&&!t.open&&!cHe(e,t)||t.hasAttribute(`hidden`)||!r&&!dHe(t,n))return!1}return!0}function dHe(e,t){let n=fy(e);return t?n.display!==`none`:ub(e,n)}function fHe(e){let t=e.tabIndex;if(t<0){let t=ry(e);if(t===`details`||t===`audio`||t===`video`||sy(e)&&e.isContentEditable)return 0}return t}function pHe(e){if(ry(e)!==`input`)return null;let t=e;return t.type===`radio`&&t.name!==``?t:null}function mHe(e,t){let n=pHe(e);if(!n)return!0;let r=t.find(e=>{let t=pHe(e);return t?.name===n.name&&t.form===n.form&&t.checked});return r?r===n:t.find(e=>{let t=pHe(e);return t?.name===n.name&&t.form===n.form})===n}function hHe(e){if(sy(e)&&ry(e)===`slot`){let t=e.assignedElements({flatten:!0});if(t.length>0)return t}return sy(e)&&e.shadowRoot?Array.from(e.shadowRoot.children):Array.from(e.children)}function gHe(e,t){hHe(e).forEach(e=>{lHe(e)&&t.push(e),gHe(e,t)})}function _He(e,t,n){hHe(e).forEach(e=>{sy(e)&&e.matches(t)&&n.push(e),_He(e,t,n)})}function db(e){return uHe(e)&&fHe(e)>=0}function vHe(e){let t=[];return gHe(e,t),t.filter(uHe)}function fb(e){let t=vHe(e);return t.filter(e=>fHe(e)>=0&&mHe(e,t))}function yHe(e,t){let n=fb(e),r=n.length;if(r===0)return;let i=hy(Wy(e)),a=n.indexOf(i);return n[a===-1?t===1?0:r-1:a+t]}function bHe(e){return yHe(Wy(e).body,1)||e}function xHe(e){return yHe(Wy(e).body,-1)||e}function SHe(e,t,n){if(!e)return null;let r=[];gHe(Wy(e).body,r);let i=r.indexOf(e);if(i===-1)return null;let a=r.filter(uHe);for(let e=1;e<r.length;e+=1){let o=r[(i+t*e+r.length)%r.length];if(!gy(n,o)&&db(o)&&mHe(o,a))return o}return r[i]}function pb(e,t){let n=t||e.currentTarget,r=e.relatedTarget;return!r||!gy(n,r)}function CHe(e){fb(e).forEach(e=>{e.dataset.tabindex=e.getAttribute(`tabindex`)||``,e.setAttribute(`tabindex`,`-1`)})}function wHe(e){let t=[];_He(e,`[data-tabindex]`,t),t.forEach(e=>{let t=e.dataset.tabindex;delete e.dataset.tabindex,t?e.setAttribute(`tabindex`,t):e.removeAttribute(`tabindex`)})}function mb(e,t,n=!0){return e.filter(e=>e.parentId===t).flatMap(t=>[...!n||t.context?.open?[t]:[],...mb(e,t.id,n)])}function THe(e,t){let n=[],r=e.find(e=>e.id===t)?.parentId;for(;r;){let t=e.find(e=>e.id===r);r=t?.parentId,t&&(n=n.concat(t))}return n}function hb(e){return`data-base-ui-${e}`}var gb=0;function _b(e,t={}){let{preventScroll:n=!1,sync:r=!1,shouldFocus:i}=t;cancelAnimationFrame(gb);function a(){(!i||i())&&e?.focus({preventScroll:n})}if(r)return a(),C;let o=requestAnimationFrame(a);return gb=o,()=>{gb===o&&(cancelAnimationFrame(o),gb=0)}}var EHe=`data-base-ui-inert`,vb=new WeakMap,yb=new WeakSet,bb=new WeakMap,DHe=0;function OHe(e){return e?cy(e)?e.host:OHe(e.parentNode):null}var kHe=(e,t)=>t.map(t=>{if(e.contains(t))return t;let n=OHe(t);return e.contains(n)?n:null}).filter(e=>e!=null),AHe=e=>{let t=new Set;return e.forEach(e=>{let n=e;for(;n&&!t.has(n);)t.add(n),n=n.parentNode}),t},jHe=(e,t,n)=>{let r=[],i=e=>{e&&!n.has(e)&&Array.from(e.children).forEach(e=>{ry(e)!==`script`&&(t.has(e)?i(e):r.push(e))})};return i(e),r};function MHe(e,t,n,{mark:r=!0}){let i=kHe(t,e),a=r?jHe(t,AHe(i),new Set(i)):[],o=[],s=[];if(n){let e=kHe(t,Array.from(t.querySelectorAll(`[aria-live]`))),n=i.concat(e);jHe(t,AHe(n),new Set(n)).forEach(e=>{let t=e.getAttribute(`aria-hidden`),n=t!==null&&t!==`false`,r=(vb.get(e)||0)+1;vb.set(e,r),o.push(e),r===1&&n&&yb.add(e),n||e.setAttribute(`aria-hidden`,`true`)})}return r&&a.forEach(e=>{let t=(bb.get(e)||0)+1;bb.set(e,t),s.push(e),t===1&&e.setAttribute(EHe,``)}),DHe+=1,()=>{o.forEach(e=>{let t=(vb.get(e)||0)-1;vb.set(e,t),t||(yb.has(e)||e.removeAttribute(`aria-hidden`),yb.delete(e))}),r&&s.forEach(e=>{let t=(bb.get(e)||0)-1;bb.set(e,t),t||e.removeAttribute(EHe)}),--DHe,DHe||(vb=new WeakMap,yb=new WeakSet,bb=new WeakMap)}}function NHe(e,t={}){let{ariaHidden:n=!1,mark:r=!0}=t,i=Wy(e[0]).body;return MHe(e,i,n,{mark:r})}function PHe(){let[,e]=G.useState({});return G.useCallback(()=>{e({})},[])}var FHe=0;function IHe(e,t=`mui`){let n=G.useRef(void 0),r=PHe(),i=e??n.current;return G.useEffect(()=>{n.current??(FHe+=1,n.current=`${t}-${FHe}`,e??r())},[e,t,r]),i}var LHe=NVe.useId;function xb(e,t){if(LHe!==void 0){let n=LHe();return e??(t?`${t}-${n}`:n)}return IHe(e,t)}var RHe={style:{transition:`none`}},zHe=`data-base-ui-click-trigger`,BHe=`data-base-ui-swipe-ignore`,VHe=`[${BHe}]`,HHe={fallbackAxisSide:`none`},Sb={fallbackAxisSide:`end`},UHe={clipPath:`inset(50%)`,position:`fixed`,top:0,left:0},WHe=G.createContext(null),GHe=()=>G.useContext(WHe),KHe=hb(`portal`);function qHe(e={}){let{ref:t,container:n,componentProps:r=te,elementProps:i}=e,a=xb(),o=GHe()?.portalNode,[s,c]=G.useState(null),[l,u]=G.useState(null),d=zy(e=>{e!==null&&u(e)}),f=G.useRef(null);Wv(()=>{if(n===null){f.current&&(f.current=null,u(null),c(null));return}let e=(n&&(vBe(n)?n:n.current))??o??document.body;e==null?f.current&&(f.current=null,u(null),c(null)):f.current!==e&&(f.current=e,u(null),c(e))},[n,o]);let p=N(`div`,r,{ref:[t,d],props:[{id:a,[KHe]:``},i]}),m=s&&p?Pt.createPortal(p,s):null;return{node:l,nodeId:G.isValidElement(p)?p.props.id:void 0,subtree:m}}var Cb=G.forwardRef(function(e,t){let{render:n,className:r,style:i,children:a,container:o,portalOwnerRole:s,...c}=e,{node:l,nodeId:u,subtree:d}=qHe({container:o,ref:t,componentProps:e,elementProps:c}),f=G.useRef(null),p=G.useRef(null),m=G.useRef(null),h=G.useRef(null),[g,_]=G.useState(null),v=G.useRef(!1),y=g?.modal,b=g?.open,x=!!g&&!g.modal&&g.open&&!!l;G.useEffect(()=>{if(!l||y)return;function e(e){l&&e.relatedTarget&&pb(e)&&(e.type===`focusin`?v.current&&=(wHe(l),!1):(CHe(l),v.current=!0))}return Ly(Iy(l,`focusin`,e,!0),Iy(l,`focusout`,e,!0))},[l,y]),Wv(()=>{l&&b===!0&&v.current&&(wHe(l),v.current=!1)},[b,l]);let S=G.useMemo(()=>({beforeOutsideRef:f,afterOutsideRef:p,beforeInsideRef:m,afterInsideRef:h,portalNode:l,setFocusManagerState:_}),[l]);return(0,K.jsxs)(G.Fragment,{children:[d,(0,K.jsxs)(WHe.Provider,{value:S,children:[x&&l&&(0,K.jsx)(qy,{"data-type":`outside`,ref:f,onFocus:e=>{pb(e,l)?m.current?.focus():xHe(g?g.domReference:null)?.focus()}}),x&&l&&(0,K.jsx)(`span`,{role:s,"aria-owns":u,style:UHe}),l&&Pt.createPortal(a,l),x&&l&&(0,K.jsx)(qy,{"data-type":`outside`,ref:p,onFocus:e=>{pb(e,l)?h.current?.focus():(bHe(g?g.domReference:null)?.focus(),g?.closeOnFocusOut&&g?.onOpenChange(!1,Ey(`focus-out`,e.nativeEvent)))}})]})]})});function JHe(){let e=new Map;return{emit(t,n){e.get(t)?.forEach(e=>e(n))},on(t,n){e.has(t)||e.set(t,new Set),e.get(t).add(n)},off(t,n){e.get(t)?.delete(n)}}}var YHe=class{nodesRef={current:[]};events=JHe();addNode(e){this.nodesRef.current.push(e)}removeNode(e){let t=this.nodesRef.current.findIndex(t=>t===e);t!==-1&&this.nodesRef.current.splice(t,1)}},XHe=G.createContext(null),ZHe=G.createContext(null),wb=()=>G.useContext(XHe)?.id||null,Tb=e=>{let t=G.useContext(ZHe);return e??t};function Eb(e){let t=xb(),n=Tb(e),r=wb();return Wv(()=>{if(!t)return;let e={id:t,parentId:r};return n?.addNode(e),()=>{n?.removeNode(e)}},[n,t,r]),t}function QHe(e){let{children:t,id:n}=e,r=wb();return(0,K.jsx)(XHe.Provider,{value:G.useMemo(()=>({id:n,parentId:r}),[n,r]),children:t})}function $He(e){let{children:t,externalTree:n}=e,r=s(()=>n??new YHe).current;return(0,K.jsx)(ZHe.Provider,{value:r,children:t})}function Db(e){return e==null?e:`current`in e?e.current:e}function eUe(e,t){let n=iy(vy(e));return e instanceof n.KeyboardEvent?`keyboard`:e instanceof n.FocusEvent?t||`keyboard`:`pointerType`in e?e.pointerType||(ty(e)?`keyboard`:t||`mouse`):`touches`in e?`touch`:e instanceof n.MouseEvent?t||(e.detail===0?`keyboard`:`mouse`):``}var tUe=20,Ob=[];function nUe(){Ob=Ob.filter(e=>e.deref()?.isConnected)}function rUe(e){nUe(),e&&ry(e)!==`body`&&(Ob.push(new WeakRef(e)),Ob.length>tUe&&(Ob=Ob.slice(-20)))}function iUe(){return nUe(),Ob[Ob.length-1]?.deref()}function aUe(e){return e?db(e)?e:fb(e)[0]||e:null}function oUe(e){if(e.hasAttribute(`tabindex`)&&!e.hasAttribute(`data-tabindex`)||!e.getAttribute(`role`)?.includes(`dialog`))return;let t=vHe(e).filter(e=>{let t=e.getAttribute(`data-tabindex`)||``;return db(e)||e.hasAttribute(`data-tabindex`)&&!t.startsWith(`-`)}),n=e.getAttribute(`tabindex`);t.length===0?n!==`0`&&(e.setAttribute(`tabindex`,`0`),e.setAttribute(`data-tabindex`,`0`)):(n!==`-1`||e.hasAttribute(`data-tabindex`)&&e.getAttribute(`data-tabindex`)!==`-1`)&&(e.setAttribute(`tabindex`,`-1`),e.setAttribute(`data-tabindex`,`-1`))}function kb(e){let{context:t,children:n,disabled:r=!1,initialFocus:i=!0,returnFocus:a=!0,explicitReturnFocus:o,restoreFocus:s=!1,modal:c=!0,closeOnFocusOut:l=!0,openInteractionType:u=``,nextFocusableElement:d,previousFocusableElement:f,beforeContentFocusGuardRef:p,externalTree:m,getInsideElements:h}=e,g=t.useState(`open`),_=t.useState(`domReferenceElement`),y=t.useState(`floatingElement`),{events:b,dataRef:x}=t.context,S=zy(()=>x.current.floatingContext?.nodeId),C=i===!1,w=tVe(_)&&C,T=Ry(i),E=Ry(a),D=Ry(o),O=Ry(u),k=Ry(g),A=Tb(m),j=GHe(),M=G.useRef(!1),N=G.useRef(!1),P=G.useRef(!1),F=G.useRef(null),I=G.useRef(``),L=G.useRef(``),R=G.useRef(null),z=G.useRef(null),B=v(R,p,j?.beforeInsideRef),V=v(z,j?.afterInsideRef),H=Yv(),ee=Yv(),te=Uy(),U=j!=null,W=rVe(y),ne=zy((e=W)=>e?fb(e):[]),re=zy(()=>h?.().filter(e=>e!=null)??[]);G.useEffect(()=>{if(r||!c)return;function e(e){e.key===`Tab`&&gy(W,hy(Wy(W)))&&ne().length===0&&!w&&ey(e)}return Iy(Wy(W),`keydown`,e)},[r,W,c,w,ne]),G.useEffect(()=>{if(r||!g)return;let e=Wy(W);function t(){P.current=!1}function n(e){let t=vy(e),n=re(),r=gy(y,t)||gy(_,t)||gy(j?.portalNode,t)||n.some(e=>e===t||gy(e,t));P.current=!r,L.current=e.pointerType||`keyboard`,_y(t,`[data-base-ui-click-trigger]`)&&(N.current=!0,ee.start(0,()=>{N.current=!1}))}function i(){L.current=`keyboard`}return Ly(Iy(e,`pointerdown`,n,!0),Iy(e,`pointerup`,t,!0),Iy(e,`pointercancel`,t,!0),Iy(e,`keydown`,i,!0),t)},[r,y,_,W,g,j,ee,re]),G.useEffect(()=>{if(r||!l)return;let e=Wy(W);function n(){N.current=!0,ee.start(0,()=>{N.current=!1})}function i(e){let t=vy(e);db(t)&&(F.current=t)}function a(n){let r=n.relatedTarget,i=n.currentTarget,a=vy(n);c&&r==null&&a!=null&&gy(y,a)&&rUe(a),queueMicrotask(()=>{let o=S(),l=t.context.triggerElements,u=re(),p=r?.hasAttribute(hb(`focus-guard`))&&[R.current,z.current,j?.beforeInsideRef.current,j?.afterInsideRef.current,j?.beforeOutsideRef.current,j?.afterOutsideRef.current,Db(f),Db(d)].includes(r),m=!(gy(_,r)||gy(y,r)||gy(r,y)||gy(j?.portalNode,r)||u.some(e=>e===r||gy(e,r))||l.hasMatchingElement(e=>gy(e,r))||p||A&&(mb(A.nodesRef.current,o).find(e=>gy(e.context?.elements.floating,r)||gy(e.context?.elements.domReference,r))||THe(A.nodesRef.current,o).find(e=>[e.context?.elements.floating,rVe(e.context?.elements.floating)].includes(r)||e.context?.elements.domReference===r)));if(i===_&&W&&oUe(W),s&&i!==_&&!ub(a)&&hy(e)===e.body){if(sy(W)&&(W.focus(),s===`popup`)){te.request(()=>{W.focus()});return}let e=ne(),t=F.current,n=(t&&e.includes(t)?t:null)||e[e.length-1]||W;sy(n)&&n.focus()}x.current.insideReactTree?x.current.insideReactTree=!1:(w||!c)&&r&&m&&!N.current&&(w||r!==iUe())&&(M.current=!0,t.setOpen(!1,Ey(hVe,n)))})}function o(){P.current||(x.current.insideReactTree=!0,H.start(0,()=>{x.current.insideReactTree=!1}))}let u=sy(_)?_:null;if(y||u)return Ly(u&&Iy(u,`focusout`,a),u&&Iy(u,`pointerdown`,n),y&&Iy(y,`focusin`,i),y&&Iy(y,`focusout`,a),y&&j&&Iy(y,`focusout`,o,!0))},[r,_,y,W,c,A,j,t,l,s,ne,w,S,x,H,ee,te,d,f,re]),G.useEffect(()=>{if(r||!y||!g)return;let e=Array.from(j?.portalNode?.querySelectorAll(`[${hb(`portal`)}]`)||[]),t=(A?THe(A.nodesRef.current,S()):[]).find(e=>tVe(e.context?.elements.domReference||null))?.context?.elements.domReference,n=NHe([y,...e,R.current,z.current,j?.beforeOutsideRef.current,j?.afterOutsideRef.current,...re(),t,Db(f),Db(d),w?_:null].filter(e=>e!=null),{ariaHidden:c||w,mark:!1}),i=NHe([y,...e].filter(e=>e!=null));return()=>{i(),n()}},[g,r,_,y,c,j,w,A,S,d,f,re]),Wv(()=>{if(!g||r||!sy(W))return;I.current=``,L.current=``;let e=Wy(W),t=hy(e);queueMicrotask(()=>{let n=T.current,r=typeof n==`function`?n(O.current||``):n;if(r===void 0||r===!1||gy(W,t))return;let i=null,a=()=>(i??=ne(W),i[0]||W),o;o=r===!0||r===null?a():Db(r),o||=a();let s=gy(W,hy(e)),c=x.current.openEvent,l=c?.type===`mousedown`&&ty(c);_b(o,{sync:l,preventScroll:o===W,shouldFocus(){if(!k.current)return!1;if(s)return!0;let t=hy(e);return!(t!==o&&gy(W,t))}})})},[r,g,W,ne,T,O,k,x]);let ie=G.useRef(null);Wv(()=>{if(r||!W){ie.current=null;return}ie.current&&=(ie.current.cancelled=!0,null);let e=Wy(W),t=hy(e),n=O.current==null;rUe(t);function i(e){if(e.open||(I.current=eUe(e.nativeEvent,L.current)),(e.reason===`focus-out`&&e.triggerElement?.hasAttribute(hb(`focus-guard`))||e.reason===`trigger-hover`&&e.nativeEvent.type===`mouseleave`)&&(M.current=!0),e.reason===`outside-press`){if(e.nested)M.current=!1;else if(ty(e.nativeEvent)||hBe(e.nativeEvent))M.current=!1;else{let e=!1;Wy(W).createElement(`div`).focus({get preventScroll(){return e=!0,!1}}),e?M.current=!1:M.current=!0}}}b.on(`openchange`,i);function a(e){let r=E.current,i=typeof r==`function`?r(e):r;if(i===void 0||i===!1)return null;i===null&&(i=!0);let a=_?.isConnected?_:null,o=t?.isConnected&&ry(t)!==`body`?t:null,s=n?o||a:a||o;return s||=iUe()||null,typeof i==`boolean`?s:Db(i)||s||null}return()=>{b.off(`openchange`,i);let t=hy(e),n=re(),r=gy(y,t)||n.some(e=>e===t||gy(e,t))||A&&mb(A.nodesRef.current,S(),!1).some(e=>gy(e.context?.elements.floating,t)),o=E.current,s=I.current,c=a(s),l={cancelled:!1};ie.current=l,queueMicrotask(()=>{ie.current===l&&(ie.current=null);let n=aUe(c),i=D.current??typeof o!=`boolean`;if(!l.cancelled&&o&&!M.current&&sy(n)&&(i||n===t||t===e.body||r)){let e={preventScroll:!0};s===`keyboard`&&(e.focusVisible=!0),n.focus(e)}M.current=!1})}},[r,y,W,E,D,O,b,A,_,S,re]),Wv(()=>{if(!$v||g||!y)return;let e=hy(Wy(y));sy(e)&&wy(e)&&gy(y,e)&&e.blur()},[g,y]),Wv(()=>{if(!r&&j)return j.setFocusManagerState({modal:c,closeOnFocusOut:l,open:g,onOpenChange:t.setOpen,domReference:_}),()=>{j.setFocusManagerState(null)}},[r,j,c,g,t,l,_]),Wv(()=>{if(!r&&W)return oUe(W),()=>{queueMicrotask(nUe)}},[r,W]);let ae=!r&&(!c||!w)&&(U||c);return(0,K.jsxs)(G.Fragment,{children:[ae&&(0,K.jsx)(qy,{"data-type":`inside`,ref:B,onFocus:e=>{if(c){let e=ne();_b(e[e.length-1])}else j?.portalNode&&(M.current=!1,pb(e,j.portalNode)?bHe(_)?.focus():Db(f??j.beforeOutsideRef)?.focus())}}),n,ae&&(0,K.jsx)(qy,{"data-type":`inside`,ref:V,onFocus:e=>{c?_b(ne()[0]):j?.portalNode&&(l&&(M.current=!0),pb(e,j.portalNode)?xHe(_)?.focus():Db(d??j.afterOutsideRef)?.focus())}})]})}function Ab(e,t={}){let{enabled:n=!0,event:r=`click`,toggle:i=!0,ignoreMouse:a=!1,stickIfOpen:o=!0,touchOpenDelay:s=0,reason:c=ky}=t,l=e.context.dataRef,u=G.useRef(void 0),d=Uy(),f=Yv(),p=G.useMemo(()=>{function t(t,n,r,i){let a=Ey(c,n,r);t&&i===`touch`&&s>0?f.start(s,()=>{e.setOpen(!0,a)}):e.setOpen(t,a)}function n(t,n,r){let a=l.current.openEvent,s=e.select(`domReferenceElement`)!==n;return t&&s||!t||!i?!0:a&&(typeof o==`function`?o():o)?!r(a.type):!1}return{onPointerDown(e){u.current=ny(e.pointerType,!0)&&hBe(e.nativeEvent)?`virtual`:e.pointerType},onMouseDown(i){let o=u.current,s=i.nativeEvent,c=e.select(`open`);if(i.button!==0||r===`click`||ny(o,!0)&&a)return;let l=n(c,i.currentTarget,e=>e===`click`||e===`mousedown`),f=vy(s),p=wy(f);if(p||o===`virtual`){t(l,s,p?f:i.currentTarget,o);return}let m=i.currentTarget;d.request(()=>{t(l,s,m,o)})},onClick(i){if(r===`mousedown-only`)return;let o=u.current;r===`mousedown`&&o?u.current=void 0:ny(o,!0)&&a||t(n(e.select(`open`),i.currentTarget,e=>e===`click`||e===`mousedown`||e===`keydown`||e===`keyup`),i.nativeEvent,i.currentTarget,o)},onKeyDown(){u.current=void 0}}},[l,r,a,c,e,o,i,d,f,s]);return G.useMemo(()=>n?{reference:p}:te,[n,p])}function sUe(e,t){let n=null,r=null,i=!1;return{contextElement:e||void 0,getBoundingClientRect(){let a=e?.getBoundingClientRect()||{width:0,height:0,x:0,y:0},o=t.axis===`x`||t.axis===`both`,s=t.axis===`y`||t.axis===`both`,c=[`mouseenter`,`mousemove`].includes(t.dataRef.current.openEvent?.type||``)&&t.pointerType!==`touch`,l=t.axis===`y`?a.width:0,u=t.axis===`x`?a.height:0,d=a.x,f=a.y;return n==null&&t.x&&o&&(n=a.x-t.x),r==null&&t.y&&s&&(r=a.y-t.y),d-=n||0,f-=r||0,(!i||c)&&(d=o&&t.x!=null?t.x:d,f=s&&t.y!=null?t.y:f),i=!0,{width:l,height:u,x:d,y:f,top:f,right:d+l,bottom:f+u,left:d}}}}function cUe(e){return e!=null&&e.clientX!=null}function lUe(e,t={}){let{enabled:n=!0,axis:r=`both`}=t,i=e.useState(`open`),a=e.useState(`floatingElement`),o=e.useState(`domReferenceElement`),s=e.context.dataRef,c=G.useRef(!1),l=G.useRef(null),[u,d]=G.useState(),[f,p]=G.useState([]),m=zy(t=>{e.set(`positionReference`,t)}),h=zy((t,n,i)=>{c.current||(!s.current.openEvent||cUe(s.current.openEvent))&&e.set(`positionReference`,sUe(i??o,{x:t,y:n,axis:r,dataRef:s,pointerType:u}))}),g=zy(e=>{i?l.current||(h(e.clientX,e.clientY,e.currentTarget),p([])):h(e.clientX,e.clientY,e.currentTarget)}),_=ny(u)?a:i;G.useEffect(()=>{if(!n){m(o);return}if(!_)return;function e(){l.current?.(),l.current=null}let t=iy(a);function r(t){let n=vy(t);gy(a,n)?e():h(t.clientX,t.clientY)}return!s.current.openEvent||cUe(s.current.openEvent)?l.current=Iy(t,`mousemove`,r):m(o),e},[_,n,a,s,o,e,h,m,f]),G.useEffect(()=>()=>{e.set(`positionReference`,null)},[e]),G.useEffect(()=>{n&&!a&&(c.current=!1)},[n,a]),G.useEffect(()=>{!n&&i&&(c.current=!0)},[n,i]);let v=G.useMemo(()=>{function e(e){d(e.pointerType)}return{onPointerDown:e,onPointerEnter:e,onMouseMove:g,onMouseEnter:g}},[g]);return G.useMemo(()=>n?{reference:v,trigger:v}:{},[n,v])}function uUe(){return!1}function dUe(e){return{escapeKey:typeof e==`boolean`?e:e?.escapeKey??!1,outsidePress:typeof e==`boolean`?e:e?.outsidePress??!0}}function jb(e,t={}){let{enabled:n=!0,escapeKey:r=!0,outsidePress:i=!0,outsidePressEvent:a=`sloppy`,referencePress:o=uUe,bubbles:s,externalTree:c}=t,l=e.useState(`open`),u=e.useState(`floatingElement`),{dataRef:d,events:f}=e.context,p=Tb(c),m=zy(typeof i==`function`?i:()=>!1),h=typeof i==`function`?m:i,g=h!==!1,_=zy(()=>a),{escapeKey:v,outsidePress:y}=dUe(s),b=G.useRef(!1),x=G.useRef(!1),S=G.useRef(!1),C=G.useRef(!1),w=G.useRef(!1),T=G.useRef(``),E=G.useRef(null),D=Yv(),O=Yv(),k=Yv(),A=zy(()=>{O.clear(),d.current.insideReactTree=!1}),j=zy(e=>{let t=d.current.floatingContext?.nodeId;return(p?mb(p.nodesRef.current,t):[]).some(t=>t.context?.open&&!t.context.dataRef.current[e])}),M=zy(t=>QBe(t,e.select(`floatingElement`))||QBe(t,e.select(`domReferenceElement`))),N=zy(t=>{o()&&e.setOpen(!1,Ey(ky,t.nativeEvent))}),P=zy(t=>{if(!l||!n||!r||t.key!==`Escape`)return;let i=mBe(t)?t.nativeEvent:t;if(w.current||i.isComposing||!v&&j(`__escapeKeyBubbles`))return;let a=Ey(gVe,i);e.setOpen(!1,a),a.isCanceled||t.preventDefault(),!v&&!a.isPropagationAllowed&&t.stopPropagation()}),F=zy(()=>{d.current.insideReactTree=!0,O.start(0,A)}),I=zy(t=>{if(!l||!n||t.button!==0)return;let r=vy(t.nativeEvent);gy(e.select(`floatingElement`),r)&&(b.current||(b.current=!0,x.current=!1))}),L=zy(e=>{l&&n&&(e.defaultPrevented||e.nativeEvent.defaultPrevented)&&b.current&&(x.current=!0)});G.useEffect(()=>{function e(e){e.open||(C.current=!1)}return f.on(`openchange`,e),()=>{f.off(`openchange`,e)}},[f]),G.useEffect(()=>A,[A]),G.useEffect(()=>{if(!l||!n)return l||(C.current=!1,w.current=!1,T.current=``,E.current=null),A;d.current.__escapeKeyBubbles=v,d.current.__outsidePressBubbles=y;let t=new Jv,i=Wy(u);function a(){k.clear(),w.current=!0}function o(){w.current=!0,k.start($v?5:0,()=>{w.current=!1})}function s(){S.current=!0,t.start(0,()=>{S.current=!1})}function c(){b.current=!1,x.current=!1}function f(){let e=T.current,t=e===`pen`||!e?`mouse`:e,n=_(),r=typeof n==`function`?n():n;return typeof r==`string`?r:r[t]}function m(e){let t=f();return t===`intentional`&&e.type!==`click`||t===`sloppy`&&e.type===`click`}function O(e){let t=d.current.floatingContext?.nodeId,n=p&&mb(p.nodesRef.current,t).some(t=>QBe(e,t.context?.elements.floating));return M(e)||n}function N(n){if(m(n)){n.type!==`click`&&!M(n)&&(t.clear(),S.current=!1),A();return}if(d.current.insideReactTree){A();return}let r=vy(n),i=`[${hb(`inert`)}]`,a=oy(r)?r.getRootNode():null,o=Array.from((cy(a)?a:Wy(e.select(`floatingElement`))).querySelectorAll(i)),s=e.context.triggerElements;if(r&&(s.hasElement(r)||s.hasMatchingElement(e=>gy(e,r))))return;let c=oy(r)?r:null;for(;c&&!dy(c);){let e=py(c);if(dy(e)||!oy(e))break;c=e}if(!(o.length&&oy(r)&&!$Be(r)&&!gy(r,e.select(`floatingElement`))&&o.every(e=>!gy(c,e)))){if(sy(r)&&!(`touches`in n)){let e=dy(r),t=fy(r),i=/auto|scroll/,a=e||i.test(t.overflowX),o=e||i.test(t.overflowY),s=a&&r.clientWidth>0&&r.scrollWidth>r.clientWidth,c=o&&r.clientHeight>0&&r.scrollHeight>r.clientHeight,l=t.direction===`rtl`,u=c&&(l?n.offsetX<=r.offsetWidth-r.clientWidth:n.offsetX>r.clientWidth),d=s&&n.offsetY>r.clientHeight;if(u||d)return}if(!O(n)){if(f()===`intentional`){if(n.detail!==0&&!ty(n)&&!C.current)return;if(S.current){t.clear(),S.current=!1;return}}typeof h==`function`&&!h(n)||j(`__outsidePressBubbles`)||(e.setOpen(!1,Ey(lVe,n)),A())}}}function F(t){f()===`sloppy`&&t.pointerType!==`touch`&&e.select(`open`)&&n&&!M(t)&&N(t)}function I(t){if(f()!==`sloppy`||!e.select(`open`)||!n||M(t))return;let r=t.touches[0];r&&(E.current={startTime:Date.now(),startX:r.clientX,startY:r.clientY,dismissOnTouchEnd:!1,dismissOnMouseDown:!0},D.start(1e3,()=>{E.current&&(E.current.dismissOnTouchEnd=!1,E.current.dismissOnMouseDown=!1)}))}function L(e,t){let n=vy(e);if(!n)return;let r=Iy(n,e.type,()=>{t(e),r()})}function R(e){T.current=`touch`,L(e,I)}function z(e){D.clear(),e.type===`pointerdown`&&(e.button===0&&(C.current=!0),T.current=e.pointerType),(e.type!==`mousedown`||!E.current||E.current.dismissOnMouseDown)&&L(e,e=>{e.type===`pointerdown`?F(e):N(e)})}function B(e){if(e.type===`pointercancel`&&(C.current=!1),!b.current)return;let n=x.current;c(),f()===`intentional`&&(e.type===`pointercancel`?n&&s():O(e)||(n?s():(typeof h!=`function`||h(e))&&(t.clear(),S.current=!0,A())))}function V(e){if(f()!==`sloppy`||!E.current||M(e))return;let t=e.touches[0];if(!t)return;let n=Math.abs(t.clientX-E.current.startX),r=Math.abs(t.clientY-E.current.startY),i=Math.sqrt(n*n+r*r);i>5&&(E.current.dismissOnTouchEnd=!0),i>10&&(N(e),D.clear(),E.current=null)}function H(e){L(e,V)}function ee(e){f()===`sloppy`&&E.current&&!M(e)&&(E.current.dismissOnTouchEnd&&N(e),D.clear(),E.current=null)}function te(e){L(e,ee)}let U=Ly(r&&Ly(Iy(i,`keydown`,P),Iy(i,`compositionstart`,a),Iy(i,`compositionend`,o)),g&&Ly(Iy(i,`click`,z,!0),Iy(i,`pointerdown`,z,!0),Iy(i,`pointerup`,B,!0),Iy(i,`pointercancel`,B,!0),Iy(i,`mousedown`,z,!0),Iy(i,`mouseup`,B,!0),Iy(i,`touchstart`,R,{capture:!0,passive:!0}),Iy(i,`touchmove`,H,{capture:!0,passive:!0}),Iy(i,`touchend`,te,{capture:!0,passive:!0})));return()=>{U(),t.clear(),c(),S.current=!1}},[d,u,r,g,h,l,n,v,y,P,A,_,j,M,p,e,D,k]);let R=G.useMemo(()=>({onKeyDown:P,onPointerDown:N,onClick:N}),[P,N]),z=G.useMemo(()=>({onKeyDown:P,onPointerDown:L,onMouseDown:L,onClickCapture:F,onMouseDownCapture(e){F(),I(e)},onPointerDownCapture(e){F(),I(e)},onMouseUpCapture:F,onTouchEndCapture:F,onTouchMoveCapture:F}),[P,F,I,L]);return G.useMemo(()=>n?{reference:R,floating:z,trigger:R}:{},[n,R,z])}function Mb(e,t,n,r){return{left:e,top:t,right:n,bottom:r,x:e,y:t,width:n-e,height:r-t}}function fUe(e){return{left:e.left,top:e.top,right:e.right,bottom:e.bottom,width:e.width,height:e.height}}function pUe(e){let t=[],n,r=1/0,i=1/0,a=-1/0,o=-1/0;for(let s of Array.from(e).sort((e,t)=>e.top-t.top)){if(r=Math.min(r,s.left),i=Math.min(i,s.top),a=Math.max(a,s.right),o=Math.max(o,s.bottom),!n||s.top-n.top>n.height/2)t.push(fUe(s));else{let e=t[t.length-1];e.left=Math.min(e.left,s.left),e.right=Math.max(e.right,s.right),e.bottom=Math.max(e.bottom,s.bottom),e.width=e.right-e.left,e.height=e.bottom-e.top}n=s}return{lines:t,fallback:Mb(r,i,a,o)}}function mUe(e,t,n){return e.findIndex(e=>t>e.left-2&&t<e.right+2&&n>e.top-2&&n<e.bottom+2)}function hUe(e){return Mb(e.left,e.top,e.right,e.bottom)}function gUe(e,t,n){let{lines:r}=pUe(e.getClientRects());if(r.length<2)return;let i=mUe(r,t,n);return{x:t,y:n,lineIndex:i===-1?void 0:i,element:e}}function _Ue(e,t,n){let{lines:r,fallback:i}=pUe(e.getClientRects());if(r.length<2)return null;let a=n?.x,o=n?.y,s=t[0];if(n?.lineIndex!=null&&r[n.lineIndex])return hUe(r[n.lineIndex]);if(a!=null&&o!=null){let e=mUe(r,a,o);if(e!==-1)return hUe(r[e])}if(r.length===2&&r[0].left>r[1].right&&a!=null&&o!=null)return i;if(s===`t`||s===`b`){let e=r[0],t=r[r.length-1],n=s===`t`?e:t;return Mb(n.left,e.top,n.right,t.bottom)}let c=s===`l`,l=r[0].left,u=r[0].right,d=c?1/0:-1/0,f=r[0],p=r[0];for(let e of r){l=Math.min(l,e.left),u=Math.max(u,e.right);let t=c?e.left:e.right;c&&t<d||!c&&t>d?(d=t,f=e,p=e):t===d&&(p=e)}return Mb(l,f.top,u,p.bottom)}function vUe(e){return`contextElement`in e&&e.contextElement?e.contextElement:oy(e)?e:void 0}function yUe(e,t){function n(t){bUe(e,t.currentTarget,t.clientX,t.clientY)}function r(e){t||n(e)}return{onFocus(){e.current=void 0},onMouseEnter:r,onMouseMove:r}}function bUe(e,t,n,r){let i=gUe(t,n,r);return e.current=i,i}function xUe(e){return{name:`inline`,async fn(t){let n=t.elements.reference;if(typeof n?.getClientRects!=`function`)return{};let r=vUe(n),i=e.current,a=i?.element===n||i?.element===r?i:void 0,o=_Ue(n,t.placement,a);if(!o||typeof t.platform.getElementRects!=`function`)return{};let s=await t.platform.getElementRects({reference:{contextElement:r,getBoundingClientRect(){return o}},floating:t.elements.floating,strategy:t.strategy});return t.rects.reference.x===s.reference.x&&t.rects.reference.y===s.reference.y&&t.rects.reference.width===s.reference.width&&t.rects.reference.height===s.reference.height?{}:{reset:{rects:s}}}}}function SUe(e){let{popupStore:t,treatPopupAsFloatingElement:n=!1,floatingRootContext:r,floatingId:i,nested:a,onOpenChange:o}=e,s=t.useState(`open`),c=t.useState(`activeTriggerElement`),l=t.useState(n?`popupElement`:`positionerElement`),u=o;return t.useSyncedValue(`floatingId`,i),Wv(()=>{let e={open:s,floatingId:i,referenceElement:c,floatingElement:l};oy(c)&&(e.domReferenceElement=c),r.state.positionReference===r.state.referenceElement&&(e.positionReference=c),r.update(e)},[s,i,c,l,r]),r.context.onOpenChange=u,r.context.nested=a,r}function Nb(e,t=!1,n=!1,r=!1){let[i,a]=G.useState(e&&t?`idle`:void 0),[o,s]=G.useState(e&&!r);return e&&!o&&(s(!0),a(`starting`)),!e&&o&&i!==`ending`&&!n&&a(`ending`),!e&&!o&&i===`ending`&&a(void 0),Wv(()=>{if(!e&&o&&i!==`ending`&&n){let e=Hy.request(()=>{a(`ending`)});return()=>{Hy.cancel(e)}}},[e,o,i,n]),Wv(()=>{if(!e||t||i===void 0)return;let n=Hy.request(()=>{a(void 0)});return()=>{Hy.cancel(n)}},[t,e,i]),Wv(()=>{if(!e||!t)return;e&&o&&i!==`idle`&&a(`starting`);let n=Hy.request(()=>{a(`idle`)});return()=>{Hy.cancel(n)}},[t,e,o,i]),{mounted:o,setMounted:s,transitionStatus:i}}function CUe(e,t){return e.getAnimations(t).filter(e=>{let t=e.effect?.getTiming();return t?.duration!==1/0&&t?.iterations!==1/0})}var Pb=null;function wUe(e){if(!Pb){let e=[];Pb=e,queueMicrotask(()=>{Pb=null,Pt.flushSync(()=>{for(let t of e)t()})})}Pb.push(e)}function Fb(e,t=!1,n=!1){let r=Uy();return zy((i,a=null)=>{r.cancel();let o=Db(e);if(o==null)return;let s=o,c=()=>{n?wUe(()=>{a?.aborted||i()}):Pt.flushSync(i)};if(typeof s.getAnimations!=`function`||globalThis.BASE_UI_ANIMATIONS_DISABLED){i();return}function l(){Promise.all(CUe(s).map(e=>e.finished.then(C))).then(()=>{a?.aborted||c()},()=>{a?.aborted||(CUe(s).some(e=>e.pending||e.playState!==`finished`)?l():c())})}if(t){let e=IBe;if(!s.hasAttribute(e)){r.request(l);return}let t=new MutationObserver(()=>{s.hasAttribute(e)||(t.disconnect(),l())});t.observe(s,{attributes:!0,attributeFilter:[e]}),a?.addEventListener(`abort`,()=>t.disconnect(),{once:!0})}else r.request(l)})}function Ib(e){let{enabled:t=!0,open:n,ref:r,batch:i=!1,onComplete:a}=e,o=zy(a),s=Fb(r,n,i);G.useEffect(()=>{if(!t)return;let e=new AbortController;return s(o,e.signal),()=>{e.abort()}},[t,n,o,s])}function TUe(e){let{open:t,ref:n,preventUnmountOnClose:r,setPreventUnmountOnClose:i,onUnmount:a,animateInitialOpen:o}=e,s=zy(i),{mounted:c,setMounted:l,transitionStatus:u}=Nb(t,!1,!1,o),d=!t&&r;Wv(()=>{t&&s(!1)},[t,s]);let f=G.useRef(c),p=G.useRef(!1),m=PHe(),h=()=>{f.current=!1,l(!1),a()};Wv(()=>{f.current=c,p.current&&(p.current=!1,!t&&c&&h())});let g=zy(()=>{f.current&&(t?(p.current=!0,m()):h())});return Ib({enabled:c&&!t&&!d,open:t,ref:n,onComplete(){t||g()}}),{mounted:c,transitionStatus:u,preventUnmountingOnClose:d,forceUnmount:g}}var Lb={tabIndex:-1,[ABe]:``};function EUe(e){return t=>t!==`touch`||e.current}function Rb(e,t=!1){let n=xb(),r=wb()!=null,i=s(()=>e(n,r)).current;return SUe({popupStore:i,treatPopupAsFloatingElement:t,floatingRootContext:i.state.floatingRootContext,floatingId:n,nested:r,onOpenChange:i.setOpen}),i}function zb({handle:e,store:t}){return Wv(()=>e.attachStore(t),[e,t]),null}function DUe(e){let t=e.context.triggerElements.size;e.select(`open`)&&e.state.triggerCount!==t&&e.set(`triggerCount`,t)}function OUe(e,t){let n=G.useRef(null);return zy(r=>{let i=n.current;if(i!==null){if(i.element===r&&i.store===t&&i.id===e)return;n.current=null;let a=i.store;a.context.triggerElements.getById(i.id)===i.element&&(a.context.triggerElements.delete(i.id),DUe(a))}r!==null&&e!==void 0&&(n.current={store:t,id:e,element:r},t.context.triggerElements.add(e,r),DUe(t))})}function Bb(e,t,n,r=!1){let i=e.preventUnmountingOnClose;t?i=!1:r&&(i=!0);let a=n?.id??null,o=e.activeTriggerId,s=e.activeTriggerElement;return(a||t)&&(o=a,s=n??null),{open:t,preventUnmountingOnClose:i,activeTriggerId:o,activeTriggerElement:s,openedWithoutTrigger:t?n==null:e.openedWithoutTrigger}}function Vb(e){let t=!1;return e.preventUnmountOnClose=()=>{t=!0},()=>t}function kUe(e,t,n,r={}){let i=n.reason,a=i===Ay,o=t&&i===`trigger-focus`,s=!t&&(i===`trigger-press`||i===`escape-key`),c=Vb(n);if(e.context.onOpenChange?.(t,n),n.isCanceled)return;r.onBeforeDispatch?.(),e.state.floatingRootContext.dispatchOpenChange(t,n);let l=()=>{let i=Bb(e.state,t,n.trigger,c()),l={...r.extraState,...i};o?l.instantType=`focus`:s?l.instantType=`dismiss`:a&&(l.instantType=void 0),e.update(l)};a?Pt.flushSync(l):l()}function Hb(e,t,n,r){let i=n.useState(`isMountedByTrigger`,e),a=OUe(e,n),o=zy(t=>{let i=n.select(`open`),a=n.select(`activeTriggerId`);if(a===e){let e={activeTriggerElement:t,...i?r:null};n.update(e)}else if(a==null&&i&&!n.state.openedWithoutTrigger){let i={activeTriggerId:e??null,activeTriggerElement:t,...r};n.update(i)}}),s=zy(e=>{a(e),e&&o(e)});return Wv(()=>(s(t.current),()=>s(null)),[s,t,n,e]),Wv(()=>{if(i){let e={activeTriggerElement:t.current,...r};n.update(e)}},[i,n,t,...Object.values(r)]),{registerTrigger:s,isMountedByThisTrigger:i}}function Ub(e,t={}){let{closeOnActiveTriggerUnmount:n=!1}=t,r=G.useRef(null),i=e.useState(`open`);Wv(()=>{if(!i){r.current=null,e.state.triggerCount!==0&&e.set(`triggerCount`,0),e.state.openedWithoutTrigger&&e.set(`openedWithoutTrigger`,!1);return}let t=e.context.triggerElements.size,a={};e.state.triggerCount!==t&&(a.triggerCount=t);let o=e.select(`activeTriggerId`),s=null;if(o){let t=e.context.triggerElements.getById(o);if(t)r.current=o,t!==e.state.activeTriggerElement&&(a.activeTriggerElement=t);else{for(let[t,n]of e.context.triggerElements.entries())if(n===e.state.activeTriggerElement){a.activeTriggerId=t,a.activeTriggerElement=n,r.current=t;break}a.activeTriggerId===void 0&&(r.current===o?s=o:r.current=null)}}else r.current=null;if(!s&&!o&&!e.state.openedWithoutTrigger&&t===1){let t=e.context.triggerElements.entries().next();if(!t.done){let[e,n]=t.value;a.activeTriggerId=e,a.activeTriggerElement=n,r.current=e}}(a.triggerCount!==void 0||a.activeTriggerId!==void 0||a.activeTriggerElement!==void 0)&&e.update(a),s&&n&&queueMicrotask(()=>{if(e.select(`open`)&&e.select(`activeTriggerId`)===s&&!e.context.triggerElements.getById(s)){let t=Ey(Oy);e.setOpen(!1,t),t.isCanceled||e.update({activeTriggerId:null,activeTriggerElement:null})}})},[i,e,e.useState(`triggerCount`),e.useState(`activeTriggerId`),e.useState(`activeTriggerElement`),n])}function Wb(e,t,n,r){let{mounted:i,transitionStatus:a,forceUnmount:o}=TUe({open:e,ref:t.context.popupRef,preventUnmountOnClose:t.useState(`preventUnmountingOnClose`),setPreventUnmountOnClose:e=>t.set(`preventUnmountingOnClose`,e),animateInitialOpen:r,onUnmount(){t.update({activeTriggerId:null,activeTriggerElement:null,mounted:!1,preventUnmountingOnClose:!1}),n?.(),t.context.onOpenChangeComplete?.(!1)}});return s(()=>(t.set(`mounted`,i),null)),t.useSyncedValues({mounted:i,transitionStatus:a}),{forceUnmount:o,transitionStatus:a}}function Gb(e,t){e.useSyncedValues(t),Wv(()=>()=>{e.update({activeTriggerProps:te,inactiveTriggerProps:te,popupProps:te})},[e])}function AUe(e,t){Wv(()=>{!t&&e.state.openMethod!==null&&e.set(`openMethod`,null)},[t,e]),Wv(()=>()=>{e.state.openMethod!==null&&e.set(`openMethod`,null)},[e])}var Kb=class{idMap=new Map;add(e,t){this.idMap.set(e,t)}delete(e){this.idMap.delete(e)}hasElement(e){for(let t of this.idMap.values())if(t===e)return!0;return!1}hasMatchingElement(e){for(let t of this.idMap.values())if(e(t))return!0;return!1}getById(e){return this.idMap.get(e)}entries(){return this.idMap.entries()}elements(){return this.idMap.values()}get size(){return this.idMap.size}},jUe=i((e=>{var t=b();function n(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var r=typeof Object.is==`function`?Object.is:n,i=t.useState,a=t.useEffect,o=t.useLayoutEffect,s=t.useDebugValue;function c(e,t){var n=t(),r=i({inst:{value:n,getSnapshot:t}}),c=r[0].inst,u=r[1];return o(function(){c.value=n,c.getSnapshot=t,l(c)&&u({inst:c})},[e,n,t]),a(function(){return l(c)&&u({inst:c}),e(function(){l(c)&&u({inst:c})})},[e]),s(n),n}function l(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!r(e,n)}catch{return!0}}function u(e,t){return t()}var d=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?u:c;e.useSyncExternalStore=t.useSyncExternalStore===void 0?d:t.useSyncExternalStore})),MUe=i(((e,t)=>{t.exports=jUe()})),NUe=i((e=>{var t=b(),n=MUe();function r(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var i=typeof Object.is==`function`?Object.is:r,a=n.useSyncExternalStore,o=t.useRef,s=t.useEffect,c=t.useMemo,l=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,u){var d=o(null);if(d.current===null){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=c(function(){function e(e){if(!a){if(a=!0,o=e,e=r(e),u!==void 0&&f.hasValue){var t=f.value;if(u(t,e))return s=t}return s=e}if(t=s,i(o,e))return t;var n=r(e);return u!==void 0&&u(t,n)?(o=e,t):(o=e,s=n)}var a=!1,o,s,c=n===void 0?null:n;return[function(){return e(t())},c===null?void 0:function(){return e(c())}]},[t,n,r,u]);var p=a(e,d[0],d[1]);return s(function(){f.hasValue=!0,f.value=p},[p]),l(p),p}})),PUe=i(((e,t)=>{t.exports=NUe()})),qb=MUe(),FUe=e(PUe(),1),IUe=ee(19)?zUe:BUe;function LUe(e,t,n,r,i){return IUe(e,t,n,r,i)}function RUe(e,t,n,r,i){let a=G.useCallback(()=>t(e.getSnapshot(),n,r,i),[e,t,n,r,i]);return(0,qb.useSyncExternalStore)(e.subscribe,a,a)}Qze({before(e){e.syncIndex=0,e.didInitialize||(e.syncTick=1,e.syncHooks=[],e.didChangeStore=!0,e.getSnapshot=()=>{let t=!1;for(let n=0;n<e.syncHooks.length;n+=1){let r=e.syncHooks[n],i=r.selector(r.store.state,r.a1,r.a2,r.a3);Object.is(r.value,i)||(t=!0,r.value=i)}return t&&(e.syncTick+=1),e.syncTick})},after(e){e.syncHooks.length>0&&(e.didChangeStore&&(e.didChangeStore=!1,e.subscribe=t=>{let n=new Set;for(let t of e.syncHooks)n.add(t.store);let r=[];for(let e of n)r.push(e.subscribe(t));return()=>{for(let e of r)e()}}),(0,qb.useSyncExternalStore)(e.subscribe,e.getSnapshot,e.getSnapshot))}});function zUe(e,t,n,r,i){let a=Zze();if(!a)return RUe(e,t,n,r,i);let o=a.syncIndex;a.syncIndex+=1;let s;return a.didInitialize?(s=a.syncHooks[o],s.store===e&&s.selector===t&&Object.is(s.a1,n)&&Object.is(s.a2,r)&&Object.is(s.a3,i)||(s.store!==e&&(a.didChangeStore=!0),s.store=e,s.selector=t,s.a1=n,s.a2=r,s.a3=i,s.value=t(e.getSnapshot(),n,r,i))):(s={store:e,selector:t,a1:n,a2:r,a3:i,value:t(e.getSnapshot(),n,r,i)},a.syncHooks.push(s)),s.value}function BUe(e,t,n,r,i){return(0,FUe.useSyncExternalStoreWithSelector)(e.subscribe,e.getSnapshot,e.getSnapshot,e=>t(e,n,r,i))}var VUe=class{static create(e){return new this(e)}constructor(e){this.state=e,this.listeners=new Set,this.updateTick=0}subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});getSnapshot=()=>this.state;setState(e){if(this.state===e)return;this.state=e,this.updateTick+=1;let t=this.updateTick;for(let n of this.listeners){if(t!==this.updateTick)return;n(e)}}update(e){for(let t in e)if(!Object.is(this.state[t],e[t])){this.setState({...this.state,...e});return}}set(e,t){Object.is(this.state[e],t)||this.setState({...this.state,[e]:t})}notifyAll(){let e={...this.state};this.setState(e)}use(e,t,n,r){return LUe(this,e,t,n,r)}},Jb=class extends VUe{constructor(e,t={},n){super(e),this.context=t,this.selectors=n}useSyncedValue(e,t){G.useDebugValue(e);let n=this;Wv(()=>{n.state[e]!==t&&n.set(e,t)},[n,e,t])}useSyncedValueWithCleanup(e,t){let n=this;Wv(()=>(n.state[e]!==t&&n.set(e,t),()=>{n.set(e,void 0)}),[n,e,t])}useSyncedValues(e){let t=this;Wv(()=>{t.update(e)},[t,...Object.values(e)])}useControlledProp(e,t){G.useDebugValue(e);let n=this,r=t!==void 0;Wv(()=>{r&&!Object.is(n.state[e],t)&&n.setState({...n.state,[e]:t})},[n,e,t,r])}select(e,t,n,r){let i=this.selectors[e];return i(this.state,t,n,r)}useState(e,t,n,r){return G.useDebugValue(e),LUe(this,this.selectors[e],t,n,r)}useContextCallback(e,t){G.useDebugValue(e);let n=zy(t??C);this.context[e]=n}useStateSetter(e){let t=G.useRef(void 0);return t.current===void 0&&(t.current=t=>{this.set(e,t)}),t.current}observe(e,t){let n;n=typeof e==`function`?e:this.selectors[e];let r=n(this.state);return t(r,r,this),this.subscribe(e=>{let i=n(e);if(!Object.is(r,i)){let e=r;r=i,t(i,e,this)}})}},HUe={open:e=>e.open,transitionStatus:e=>e.transitionStatus,domReferenceElement:e=>e.domReferenceElement,referenceElement:e=>e.positionReference??e.referenceElement,floatingElement:e=>e.floatingElement,floatingId:e=>e.floatingId},UUe=class extends Jb{constructor(e){let{syncOnly:t,nested:n,onOpenChange:r,triggerElements:i,...a}=e;super({...a,positionReference:a.referenceElement,domReferenceElement:a.referenceElement},{onOpenChange:r,dataRef:{current:{}},events:JHe(),nested:n,triggerElements:i},HUe),this.syncOnly=t}syncOpenEvent=(e,t)=>{(!e||!this.state.open||t!=null&&gBe(t))&&(this.context.dataRef.current.openEvent=e?t:void 0)};dispatchOpenChange=(e,t)=>{this.syncOpenEvent(e,t.event);let n={open:e,reason:t.reason,nativeEvent:t.event,nested:this.context.nested,triggerElement:t.trigger};this.context.events.emit(`openchange`,n)};setOpen=(e,t)=>{this.syncOnly||this.dispatchOpenChange(e,t),this.context.onOpenChange?.(e,t)}};function Yb(e,t,n=!1){return{open:!1,openProp:void 0,mounted:!1,transitionStatus:void 0,floatingRootContext:new UUe({open:!1,transitionStatus:void 0,floatingElement:null,referenceElement:null,triggerElements:e,floatingId:t,syncOnly:!0,nested:n,onOpenChange:void 0}),floatingId:t,triggerCount:0,preventUnmountingOnClose:!1,payload:void 0,activeTriggerId:null,activeTriggerElement:null,openedWithoutTrigger:!1,triggerIdProp:void 0,popupElement:null,positionerElement:null,activeTriggerProps:te,inactiveTriggerProps:te,popupProps:te}}var Xb=e=>e.triggerIdProp??e.activeTriggerId,Zb=e=>e.openProp??e.open,WUe=e=>(e.popupElement?.id??e.floatingId)||void 0;function GUe(e,t){return t!==void 0&&Zb(e)&&Xb(e)===t}function KUe(e,t){return GUe(e,t)?!0:t!==void 0&&Zb(e)&&Xb(e)==null&&!e.openedWithoutTrigger&&e.triggerCount===1}var Qb={open:Zb,mounted:e=>e.mounted,transitionStatus:e=>Zb(e)&&!e.mounted?`starting`:e.transitionStatus,floatingRootContext:e=>e.floatingRootContext,triggerCount:e=>e.triggerCount,preventUnmountingOnClose:e=>e.preventUnmountingOnClose,payload:e=>e.payload,activeTriggerId:Xb,activeTriggerElement:e=>e.mounted?e.activeTriggerElement:null,popupId:WUe,isTriggerActive:(e,t)=>t!==void 0&&Xb(e)===t,isOpenedByTrigger:(e,t)=>GUe(e,t),isMountedByTrigger:(e,t)=>t!==void 0&&Xb(e)===t&&e.mounted,triggerProps:(e,t)=>t?e.activeTriggerProps:e.inactiveTriggerProps,triggerPopupId:(e,t)=>KUe(e,t)?WUe(e):void 0,popupProps:e=>e.popupProps,popupElement:e=>e.popupElement,positionerElement:e=>e.positionerElement};function $b(e){let t=G.useCallback(t=>e===void 0?C:e.subscribeStore(t),[e]),n=G.useCallback(()=>e===void 0?void 0:e.store,[e]);return(0,qb.useSyncExternalStore)(t,n,()=>e?.serverStore)}function qUe(e){let{open:t=!1,onOpenChange:n,elements:r={}}=e,i=xb(),a=wb()!=null,o=s(()=>new UUe({open:t,transitionStatus:void 0,onOpenChange:n,referenceElement:r.reference??null,floatingElement:r.floating??null,triggerElements:new Kb,floatingId:i,syncOnly:!1,nested:a})).current;return Wv(()=>{let e={open:t,floatingId:i};r.reference!==void 0&&(e.referenceElement=r.reference,e.domReferenceElement=oy(r.reference)?r.reference:null),r.floating!==void 0&&(e.floatingElement=r.floating),o.update(e)},[t,i,r.reference,r.floating,o]),o.context.onOpenChange=n,o.context.nested=a,o}var JUe=lBe&&$v;function YUe(e,t={}){let{enabled:n=!0,delay:r}=t,{events:i,dataRef:a}=e.context,o=G.useRef(!1),s=G.useRef(null),c=G.useRef(!0),l=Yv();G.useEffect(()=>{let t=e.select(`domReferenceElement`);if(!n)return;let r=iy(t);function i(){let t=e.select(`domReferenceElement`);!e.select(`open`)&&sy(t)&&t===hy(Wy(t))&&(o.current=!0,s.current=t)}function a(){c.current=!0}function l(){c.current=!1}return Ly(Iy(r,`blur`,i),JUe&&Iy(r,`keydown`,a,!0),JUe&&Iy(r,`pointerdown`,l,!0))},[e,n]),G.useEffect(()=>{if(!n)return;function t(t){if(t.reason===`trigger-press`||t.reason===`escape-key`){let t=e.select(`domReferenceElement`);oy(t)&&(s.current=t,o.current=!0)}}return i.on(`openchange`,t),()=>{i.off(`openchange`,t)}},[i,n,e]);let u=G.useMemo(()=>{function t(){o.current=!1,s.current=null}return{onMouseLeave(){t()},onFocus(n){let i=n.currentTarget;if(o.current){if(s.current===i)return;t()}let a=vy(n.nativeEvent);if(oy(a)){if(JUe&&!n.relatedTarget){if(!c.current&&!wy(a))return}else if(!nVe(a))return}let u=ZBe(n.relatedTarget,e.context.triggerElements),{nativeEvent:d,currentTarget:f}=n;e.select(`open`)&&u||!r?e.setOpen(!0,Ey(cVe,d,f)):l.start(r,()=>{o.current||e.setOpen(!0,Ey(cVe,d,f))})},onBlur(n){t();let r=n.relatedTarget,i=n.nativeEvent,o=oy(r)&&r.hasAttribute(hb(`focus-guard`))&&r.getAttribute(`data-type`)===`outside`;l.start(0,()=>{let t=e.select(`domReferenceElement`),n=hy(Wy(t));!r&&n===t||gy(a.current.floatingContext?.refs.floating.current,n)||gy(t,n)||o||ZBe(r??n,e.context.triggerElements)||e.setOpen(!1,Ey(cVe,i))})}}},[a,r,e,l]);return G.useMemo(()=>n?{reference:u,trigger:u}:{},[n,u])}var XUe=class e{pointerType=void 0;interactedInside=!1;handler=void 0;blockMouseMove=!0;performedPointerEventsMutation=!1;pointerEventsScopeElement=null;pointerEventsReferenceElement=null;pointerEventsFloatingElement=null;restTimeoutPending=!1;openChangeTimeout=new Jv;restTimeout=new Jv;handleCloseOptions=void 0;static create(){return new e}dispose=()=>{this.openChangeTimeout.clear(),this.restTimeout.clear()};disposeEffect=()=>this.dispose},ex=new WeakMap;function tx(e){if(!e.performedPointerEventsMutation)return;let t=e.pointerEventsScopeElement;t&&ex.get(t)===e&&(e.pointerEventsScopeElement?.style.removeProperty(`pointer-events`),e.pointerEventsReferenceElement?.style.removeProperty(`pointer-events`),e.pointerEventsFloatingElement?.style.removeProperty(`pointer-events`),ex.delete(t)),e.performedPointerEventsMutation=!1,e.pointerEventsScopeElement=null,e.pointerEventsReferenceElement=null,e.pointerEventsFloatingElement=null}function ZUe(e,t){let{scopeElement:n,referenceElement:r,floatingElement:i}=t,a=ex.get(n);a&&a!==e&&tx(a),tx(e),e.performedPointerEventsMutation=!0,e.pointerEventsScopeElement=n,e.pointerEventsReferenceElement=r,e.pointerEventsFloatingElement=i,ex.set(n,e),n.style.pointerEvents=`none`,r.style.pointerEvents=`auto`,i.style.pointerEvents=`auto`}function QUe(e){let t=e.context.dataRef.current,n=s(()=>t.hoverInteractionState??XUe.create()).current;return t.hoverInteractionState||=n,nBe(t.hoverInteractionState.disposeEffect),t.hoverInteractionState}function nx(e,t={}){let{enabled:n=!0,closeDelay:r=0,nodeId:i}=t,a=e.useState(`open`),o=e.useState(`floatingElement`),s=e.useState(`domReferenceElement`),{dataRef:c}=e.context,l=Tb(),u=wb(),d=QUe(e),f=Yv(),p=zy(()=>oVe(c.current.openEvent?.type,d.interactedInside)),m=zy(()=>sVe(c.current.openEvent?.type)),h=zy(()=>{tx(d)});Wv(()=>{a||(d.pointerType=void 0,d.restTimeoutPending=!1,d.interactedInside=!1,h())},[a,d,h]),G.useEffect(()=>h,[h]),Wv(()=>{if(n&&a&&d.handleCloseOptions?.blockPointerEvents&&m()&&oy(s)&&o){let e=s,t=o,n=Wy(o),r=l?.nodesRef.current.find(e=>e.id===u)?.context?.elements.floating;r&&(r.style.pointerEvents=``);let i=d.pointerEventsScopeElement===t?null:d.pointerEventsScopeElement,a=r===t?null:r,c=d.handleCloseOptions?.getScope?.()??i??a??_y(e,`[data-rootownerid]`)??n.body;return ZUe(d,{scopeElement:c,referenceElement:e,floatingElement:t}),()=>{h()}}},[n,a,s,o,d,m,l,u,h]),G.useEffect(()=>{if(!n)return;function t(){return!!(l&&u&&mb(l.nodesRef.current,u).length>0)}function a(t){let n=Ty(r,`close`,d.pointerType),i=()=>{e.setOpen(!1,Ey(Ay,t)),l?.events.emit(`floating.closed`,t)};n?d.openChangeTimeout.start(n,i):(d.openChangeTimeout.clear(),i())}function s(e){let t=vy(e);eVe(t)?d.interactedInside=_y(t,`[aria-haspopup]`)!=null:d.interactedInside=!1}function g(){d.openChangeTimeout.clear(),f.clear(),l?.events.off(`floating.closed`,v),h()}function _(n){if(t()&&l){l.events.on(`floating.closed`,v);return}if(ZBe(n.relatedTarget,e.context.triggerElements))return;let r=c.current.floatingContext?.nodeId??i,o=n.relatedTarget;l&&r&&oy(o)&&mb(l.nodesRef.current,r,!1).some(e=>gy(e.context?.elements.floating,o))||(d.handler?d.handler(n):(h(),m()&&!p()&&a(n)))}function v(n){l&&u&&!t()&&f.start(0,()=>{l.events.off(`floating.closed`,v),e.setOpen(!1,Ey(Ay,n)),l.events.emit(`floating.closed`,n)})}let y=o;return Ly(y&&Iy(y,`mouseenter`,g),y&&Iy(y,`mouseleave`,_),y&&Iy(y,`pointerdown`,s,!0),()=>{l?.events.off(`floating.closed`,v)})},[n,o,e,c,r,i,m,p,h,d,l,u,f])}var $Ue={current:null};function rx(e,t={}){let{enabled:n=!0,delay:r=0,handleClose:i=null,mouseOnly:a=!1,restMs:o=0,move:s=!0,triggerElementRef:c=$Ue,externalTree:l,isActiveTrigger:u=!0,getHandleCloseContext:d,isClosing:f,shouldOpen:p,guardStaleOpen:m=!1}=t,{dataRef:h,events:g}=e.context,_=Tb(l),v=QUe(e),y=G.useRef(!1),b=Ry(i),x=Ry(r),S=Ry(o),C=Ry(n),w=Ry(p),T=Ry(f),E=zy(()=>oVe(h.current.openEvent?.type,v.interactedInside)),D=zy(()=>w.current?.()!==!1),O=zy((t,n,r)=>{let i=e.context.triggerElements;if(i.hasElement(n))return!t||!gy(t,n);if(!oy(r))return!1;let a=r;return i.hasMatchingElement(e=>gy(e,a))&&(!t||!gy(t,a))}),k=zy(()=>{v.handler&&=(Wy(e.select(`domReferenceElement`)).removeEventListener(`mousemove`,v.handler),void 0)}),A=zy(()=>{tx(v)});return u&&(v.handleCloseOptions=i?.__options),G.useEffect(()=>k,[k]),G.useEffect(()=>{if(!n)return;function e(e){e.open?y.current=!1:(y.current=e.reason===Ay,k(),v.openChangeTimeout.clear(),v.restTimeout.clear(),v.blockMouseMove=!0,v.restTimeoutPending=!1)}return g.on(`openchange`,e),()=>{g.off(`openchange`,e)}},[n,g,v,k]),G.useEffect(()=>{if(!n)return;function t(t,n=!0){let r=Ty(x.current,`close`,v.pointerType);r?v.openChangeTimeout.start(r,()=>{e.setOpen(!1,Ey(Ay,t)),_?.events.emit(`floating.closed`,t)}):n&&(v.openChangeTimeout.clear(),e.setOpen(!1,Ey(Ay,t)),_?.events.emit(`floating.closed`,t))}let r=c.current??(u?e.select(`domReferenceElement`):null);if(!oy(r))return;function i(t){if(v.openChangeTimeout.clear(),v.blockMouseMove=!1,a&&!ny(v.pointerType))return;let n=aVe(S.current),r=Ty(x.current,`open`,v.pointerType),i=vy(t),o=t.currentTarget??null,s=e.select(`domReferenceElement`),c=o;if(oy(i)&&!e.context.triggerElements.hasElement(i)){for(let t of e.context.triggerElements.elements())if(gy(t,i)){c=t;break}}oy(o)&&oy(s)&&!e.context.triggerElements.hasElement(o)&&gy(o,s)&&(c=s);let l=c!=null&&O(s,c,i),u=e.select(`open`),d=T.current?.()??e.select(`transitionStatus`)===`ending`,f=!u&&d&&y.current,p=!l&&oy(c)&&oy(s)&&gy(s,c)&&f,m=n>0&&!r,h=l&&(u||f)||p,g=!u||l;h?D()&&e.setOpen(!0,Ey(Ay,t,c)):m||(r?v.openChangeTimeout.start(r,()=>{g&&D()&&e.setOpen(!0,Ey(Ay,t,c))}):g&&D()&&e.setOpen(!0,Ey(Ay,t,c)))}function o(n){if(E()){A();return}k();let r=Wy(e.select(`domReferenceElement`));v.restTimeout.clear(),v.restTimeoutPending=!1;let i=h.current.floatingContext??d?.();if(!ZBe(n.relatedTarget,e.context.triggerElements)){if(b.current&&i){e.select(`open`)||v.openChangeTimeout.clear();let a=c.current;v.handler=b.current({...i,tree:_,x:n.clientX,y:n.clientY,onClose(){A(),k(),C.current&&!E()&&a===e.select(`domReferenceElement`)&&t(n,!0)}}),r.addEventListener(`mousemove`,v.handler),v.handler(n)}else v.pointerType===`touch`&&gy(e.select(`floatingElement`),n.relatedTarget)||t(n)}}function l(e){gy(r,e.relatedTarget)||(v.openChangeTimeout.clear(),v.restTimeout.clear(),v.restTimeoutPending=!1)}let f=m?Iy(r,`mouseout`,l):void 0;return s?Ly(Iy(r,`mousemove`,i,{once:!0}),Iy(r,`mouseenter`,i),Iy(r,`mouseleave`,o),f):Ly(Iy(r,`mouseenter`,i),Iy(r,`mouseleave`,o),f)},[k,A,h,x,e,n,b,v,u,O,E,a,s,S,c,_,C,d,T,D,m]),G.useMemo(()=>{if(!n)return;function t(e){v.pointerType=e.pointerType}return{onPointerDown:t,onPointerEnter:t,onMouseMove(t){let{nativeEvent:n}=t,r=t.currentTarget,i=e.select(`domReferenceElement`),o=e.select(`open`),s=O(i,r,t.target);if(a&&!ny(v.pointerType))return;if(o&&s&&v.handleCloseOptions?.blockPointerEvents){let t=e.select(`floatingElement`);if(t){let e=v.handleCloseOptions?.getScope?.()??r.ownerDocument.body;ZUe(v,{scopeElement:e,referenceElement:r,floatingElement:t})}}let c=aVe(S.current);if(o&&!s||c===0||!s&&v.restTimeoutPending&&t.movementX**2+t.movementY**2<2)return;v.restTimeout.clear();function l(){if(v.restTimeoutPending=!1,E())return;let t=e.select(`open`);!v.blockMouseMove&&(!t||s)&&D()&&e.setOpen(!0,Ey(Ay,n,r))}v.pointerType===`touch`?Pt.flushSync(()=>{l()}):s&&o?l():(v.restTimeoutPending=!0,v.restTimeout.start(c,l))}}},[n,v,E,O,a,e,S,D])}function eWe(e){return $v&&e.movementX===0&&e.movementY===0}function ix(e,t,n){switch(e){case`vertical`:return t;case`horizontal`:return n;default:return t||n}}function ax(e,t){return ix(t,e===`ArrowUp`||e===`ArrowDown`,e===`ArrowLeft`||e===`ArrowRight`)}function tWe(e,t,n){return ix(t,e===`ArrowDown`,n?e===`ArrowLeft`:e===`ArrowRight`)||e===`Enter`||e===` `||e===``}function nWe(e,t,n){return ix(t,n?e===MBe:e===NBe,e===FBe)}function rWe(e,t,n,r){return t===`both`||t===`horizontal`&&r?e===`Escape`:ix(t,n?e===NBe:e===MBe,e===PBe)}function iWe(e,t){let{listRef:n,activeIndex:r,onNavigate:i=()=>{},enabled:a=!0,selectedIndex:o=null,allowEscape:s=!1,loopFocus:c=!1,nested:l=!1,rtl:u=!1,virtual:d=!1,focusItemOnOpen:f=`auto`,focusItemOnHover:p=!0,openOnArrowKeyDown:m=!0,disabledIndices:h=void 0,orientation:g=`vertical`,triggerOrientation:_=g,parentOrientation:v,id:y,resetOnPointerLeave:b=!0,externalTree:x,nestedReturnFocusRef:S,grid:C}=t,w=C!=null,T=e.useState(`open`),E=e.useState(`floatingElement`),D=e.useState(`domReferenceElement`),O=e.context.dataRef,k=rVe(E),A=tVe(D),j=Ry(k),M=wb(),N=Tb(x),P=G.useRef(f),F=G.useRef(o??-1),I=G.useRef(null),L=G.useRef(!0),R=zy(e=>{i(F.current===-1?null:F.current,e)}),z=G.useRef(!!E),B=G.useRef(T),V=G.useRef(!1),H=G.useRef(!1),ee=G.useRef(null),te=Ry(h),U=Ry(T),W=Ry(o),ne=Ry(b),re=Uy(),ie=Uy(),ae=zy(()=>{re.cancel();function e(e){d||(ee.current=_b(e,{sync:V.current,preventScroll:!0}))}let t=n.current[F.current],r=H.current;t&&e(t),(V.current?e=>e():e=>re.request(e))(()=>{let i=n.current[F.current]||t;i&&(t||e(i),de&&(r||!L.current)&&i.scrollIntoView?.({block:`nearest`,inline:`nearest`}))})});Wv(()=>{O.current.orientation=g},[O,g]),Wv(()=>{T||(I.current=null),T&&f===`auto`||(P.current=f)},[T,f]),Wv(()=>{a&&(T&&E?(F.current=o??-1,P.current&&o!=null&&(H.current=!0,R())):z.current&&(F.current=-1,R()))},[a,T,E,o,R]),Wv(()=>{if(a){if(!T)V.current=!1;else if(E){if(r==null){if(V.current=!1,W.current!=null)return;if(z.current&&(F.current=-1,ae()),(!B.current||!z.current)&&P.current&&(I.current!=null||P.current===!0&&I.current==null)){let e=0,t=()=>{n.current[0]==null?(e<2&&(e?e=>ie.request(e):queueMicrotask)(t),e+=1):(F.current=I.current==null||tWe(I.current,_,u)||l?sb(n):tHe(n),I.current=null,R())};t()}}else ob(n.current,r)||(F.current=r,ae(),H.current=!1)}}},[a,T,E,r,W,l,n,_,u,R,ae,ie]),Wv(()=>{if(!a||E||!N||d||!z.current)return;let e=N.nodesRef.current,t=e.find(e=>e.id===M)?.context?.elements.floating,n=hy(Wy(D??t??null)),r=e.some(e=>e.context&&gy(e.context.elements.floating,n));t&&!r&&L.current&&t.focus({preventScroll:!0})},[a,E,D,N,M,d]),Wv(()=>{B.current=T,z.current=!!E});let oe=r!=null,se=zy(e=>{if(!U.current)return;let t=n.current.indexOf(e.currentTarget);t!==-1&&(F.current!==t||r!==t)&&(F.current=t,R(e))}),ce=zy(()=>v??N?.nodesRef.current.find(e=>e.id===M)?.context?.dataRef?.current.orientation),le=zy(()=>sb(n,te.current)),ue=zy(t=>{if(L.current=!1,V.current=!0,t.which===229||!U.current&&t.currentTarget===j.current)return;if(l&&rWe(t.key,g,u,w)){ax(t.key,ce())||ey(t),e.setOpen(!1,Ey(vVe,t.nativeEvent));let n=S?.current??D;sy(n)&&n.focus();return}r!=null&&r!==F.current&&!ob(n.current,r)&&(F.current=r);let i=F.current,a=sb(n,h),o=tHe(n,h);if(A||(t.key===`Home`&&(ey(t),F.current=a,R(t)),t.key===`End`&&(ey(t),F.current=o,R(t))),C!=null){let e=C(t,F.current,n,g,c,u,h,a,o);if(e!=null&&e!==F.current&&(F.current=e,R(t)),g===`both`)return}if(ax(t.key,g)){ey(t);let e=hy(t.currentTarget.ownerDocument);if(T&&!d&&gy(t.currentTarget,e)&&!n.current.some(t=>t!=null&&gy(t,e))){F.current=tWe(t.key,g,u)?a:o,R(t),r===F.current&&ae();return}let{index:l,wrapped:f}=nHe(n.current,i,{decrement:!tWe(t.key,g,u),loopFocus:c,allowEscape:s,disabledIndices:h,minIndex:a,maxIndex:o});f&&(V.current=!1),F.current=l,R(t)}}),de=G.useMemo(()=>({onFocus(e){V.current=!0,se(e)},onClick({currentTarget:e}){d||e.focus({preventScroll:!0})},onMouseMove(e){eWe(e)||(V.current=!0,H.current=!1,p&&se(e))},onPointerLeave(e){if(!U.current||!L.current||e.pointerType===`touch`)return;V.current=!0;let t=e.relatedTarget;if(p&&!n.current.includes(t)&&ne.current&&(ee.current?.(),ee.current=null,F.current=-1,R(e),!d)){let e=j.current,t=hy(Wy(e));e&&gy(e,t)&&e.focus({preventScroll:!0})}}}),[se,U,j,p,n,R,ne,d]),fe=G.useMemo(()=>d&&T&&oe&&{"aria-activedescendant":`${y}-${r}`},[d,T,oe,y,r]),pe=G.useMemo(()=>({...A?{}:fe,onKeyDown(t){if(t.key===`Tab`&&t.shiftKey&&T&&!d){let n=vy(t.nativeEvent);if(n&&!gy(j.current,n))return;ey(t);let r=Ey(hVe,t.nativeEvent);e.setOpen(!1,r);let i=S?.current??D;!r.isCanceled&&sy(i)&&i.focus()}else ue(t)},onPointerMove(e){eWe(e)||(L.current=!0)}}),[fe,ue,j,A,e,T,d,D,S]),me=G.useMemo(()=>{function t(t){e.setOpen(!0,Ey(vVe,t.nativeEvent,t.currentTarget))}function n(e){f===`auto`&&ty(e.nativeEvent)&&(P.current=!d)}function r(e){P.current=f,f===`auto`&&hBe(e.nativeEvent)&&(P.current=!0)}return{onKeyDown(n){let r=e.select(`open`);L.current=!1;let i=n.key.startsWith(`Arrow`),a=nWe(n.key,ce(),u),o=ax(n.key,r?g:_),s=(l?a:o)||n.key===`Enter`||n.key.trim()===``;if(d&&r&&(!l||wy(n.currentTarget)))return ue(n);if(r||m||!i){if(s){let e=ax(n.key,ce());I.current=l&&e?null:n.key}l?a&&(ey(n),r?(F.current=le(),R(n),d&&j.current?.focus()):t(n)):o&&(W.current!=null&&(F.current=W.current),ey(n),!r&&m?t(n):ue(n),r&&R(n))}},onFocus(t){t.target===t.currentTarget&&e.select(`open`)&&!d&&(F.current=-1,R(t))},onPointerDown:r,onPointerEnter:r,onMouseDown:n,onClick:n}},[ue,f,le,l,R,e,m,g,_,ce,u,W,d,j]),he=G.useMemo(()=>({...fe,...me}),[fe,me]);return G.useMemo(()=>a?{reference:he,floating:pe,item:de,trigger:me}:{},[a,he,pe,me,de])}function aWe(e,t){let{listRef:n,elementsRef:r,activeIndex:i,onMatch:a,disabledIndices:o,onTyping:s,enabled:c=!0,resetMs:l=750,selectedIndex:u=null}=t,d=zy(s),f=e.useState(`open`),p=Yv(),m=G.useRef(``),h=G.useRef(u??i??-1),g=G.useRef(null),_=zy(e=>{function t(e){return r?.current[e]}function s(e){let n=t(e);return n&&!ub(n)||n?.matches(`:disabled`)?!1:o==null||!lb(V,e,o)}function c(e,t,n=0){if(e.length===0)return-1;let r=(n%e.length+e.length)%e.length,i=t.toLowerCase();for(let t=0;t<e.length;t+=1){let n=(r+t)%e.length;if(e[n]?.toLowerCase().startsWith(i)&&s(n))return n}return-1}let _=n.current;if(m.current.length>0&&e.key===` `&&(ey(e),d?.(!0)),m.current.length>0&&m.current[0]!==` `&&c(_,m.current)===-1&&e.key!==` `&&d?.(!1),_==null||e.key.length!==1||e.ctrlKey||e.metaKey||e.altKey)return;f&&e.key!==` `&&(ey(e),d?.(!0));let v=m.current===``;v&&(h.current=u??i??-1),_.every((e,t)=>e&&s(t)?e[0]?.toLowerCase()!==e[1]?.toLowerCase():!0)&&m.current===e.key&&(m.current=``,h.current=g.current),m.current+=e.key,p.start(l,()=>{m.current=``,h.current=g.current,d?.(!1)});let y=((v?u??i??-1:h.current)??0)+1,b=c(_,m.current,y);b===-1?e.key!==` `&&(m.current=``,d?.(!1)):(a?.(b,e),g.current=b)}),v=zy(t=>{let n=t.relatedTarget,r=e.select(`domReferenceElement`),i=e.select(`floatingElement`);gy(r,n)||gy(i,n)||(p.clear(),m.current=``,h.current=g.current,d?.(!1))});Wv(()=>{(f||u===null)&&(p.clear(),g.current=null,m.current!==``&&(m.current=``,d?.(!1)))},[f,u,p,d]);let y=G.useMemo(()=>({onKeyDown:_,onBlur:v}),[_,v]);return G.useMemo(()=>c?{reference:y,floating:y}:{},[c,y])}var oWe=.1,sWe=oWe*oWe,ox=.5;function sx(e,t,n,r,i,a){return r>=t!=a>=t&&e<=(i-n)*(t-r)/(a-r)+n}function cx(e,t,n,r,i,a,o,s,c,l){let u=!1;return sx(e,t,n,r,i,a)&&(u=!u),sx(e,t,i,a,o,s)&&(u=!u),sx(e,t,o,s,c,l)&&(u=!u),sx(e,t,c,l,n,r)&&(u=!u),u}function cWe(e,t,n){return e>=n.x&&e<=n.x+n.width&&t>=n.y&&t<=n.y+n.height}function lx(e,t,n,r,i,a){return e>=Math.min(n,i)&&e<=Math.max(n,i)&&t>=Math.min(r,a)&&t<=Math.max(r,a)}function ux(e={}){let{blockPointerEvents:t=!1}=e,n=new Jv,r=({x:e,y:t,placement:r,elements:i,onClose:a,nodeId:o,tree:s})=>{let c=r?.split(`-`)[0],l=!1,u=null,d=null,f=typeof performance<`u`?performance.now():0;function p(e,t){let n=performance.now(),r=n-f;if(u===null||d===null||r===0)return u=e,d=t,f=n,!1;let i=e-u,a=t-d,o=i*i+a*a,s=r*r*sWe;return u=e,d=t,f=n,o<s}function m(){n.clear(),a()}return function(r){n.clear();let a=i.domReference,u=i.floating;if(!a||!u||c==null||e==null||t==null)return;let{clientX:d,clientY:f}=r,h=vy(r),g=r.type===`mouseleave`,_=gy(u,h),v=gy(a,h);if(_&&(l=!0,!g))return;if(v&&(l=!1,!g)){l=!0;return}if(g&&oy(r.relatedTarget)&&gy(u,r.relatedTarget))return;function y(){return!!(s&&mb(s.nodesRef.current,o).length>0)}function b(){y()||m()}if(y())return;let x=a.getBoundingClientRect(),S=u.getBoundingClientRect(),C=e>S.right-S.width/2,w=t>S.bottom-S.height/2,T=S.width>x.width,E=S.height>x.height,D=(T?x:S).left,O=(T?x:S).right,k=(E?x:S).top,A=(E?x:S).bottom;if(c===`top`&&t>=x.bottom-1||c===`bottom`&&t<=x.top+1||c===`left`&&e>=x.right-1||c===`right`&&e<=x.left+1){b();return}let j=!1;switch(c){case`top`:j=lx(d,f,D,x.top+1,O,S.bottom-1);break;case`bottom`:j=lx(d,f,D,S.top+1,O,x.bottom-1);break;case`left`:j=lx(d,f,S.right-1,A,x.left+1,k);break;case`right`:j=lx(d,f,x.right-1,A,S.left+1,k)}if(j)return;if(l&&!cWe(d,f,x)||!g&&p(d,f)){b();return}let M=!1;switch(c){case`top`:{let n=T?ox/2:ox*4,r=T||C?e+n:e-n,i=T?e-n:C?e+n:e-n,a=t+ox+1,o=C||T?S.bottom-ox:S.top,s=C?T?S.bottom-ox:S.top:S.bottom-ox;M=cx(d,f,r,a,i,a,S.left,o,S.right,s);break}case`bottom`:{let n=T?ox/2:ox*4,r=T||C?e+n:e-n,i=T?e-n:C?e+n:e-n,a=t-ox,o=C||T?S.top+ox:S.bottom,s=C?T?S.top+ox:S.bottom:S.top+ox;M=cx(d,f,r,a,i,a,S.left,o,S.right,s);break}case`left`:{let n=E?ox/2:ox*4,r=E||w?t+n:t-n,i=E?t-n:w?t+n:t-n,a=e+ox+1,o=w||E?S.right-ox:S.left,s=w?E?S.right-ox:S.left:S.right-ox;M=cx(d,f,o,S.top,s,S.bottom,a,r,a,i);break}case`right`:{let n=E?ox/2:ox*4,r=E||w?t+n:t-n,i=E?t-n:w?t+n:t-n,a=e-ox,o=w||E?S.left+ox:S.right,s=w?E?S.left+ox:S.right:S.left+ox;M=cx(d,f,a,r,a,i,o,S.top,s,S.bottom);break}}M?l||n.start(40,b):b()}};return r.__options={...e,blockPointerEvents:t},r}function lWe(e,t,n){let{reference:r,floating:i}=e,a=nb(t),o=UVe(t),s=HVe(o),c=eb(t),l=a===`y`,u=r.x+r.width/2-i.width/2,d=r.y+r.height/2-i.height/2,f=r[s]/2-i[s]/2,p;switch(c){case`top`:p={x:u,y:r.y-i.height};break;case`bottom`:p={x:u,y:r.y+r.height};break;case`right`:p={x:r.x+r.width,y:d};break;case`left`:p={x:r.x-i.width,y:d};break;default:p={x:r.x,y:r.y}}let m=tb(t);return m&&(p[o]+=f*(m===`end`?1:-1)*(n&&l?-1:1)),p}async function uWe(e,t){t===void 0&&(t={});let{x:n,y:r,platform:i,rects:a,elements:o,strategy:s}=e,{boundary:c=`clippingAncestors`,rootBoundary:l=`viewport`,elementContext:u=`floating`,altBoundary:d=!1,padding:f=0}=$y(t,e),p=eHe(f),m=o[d?u===`floating`?`reference`:`floating`:u],h=ib(await i.getClippingRect({element:await(i.isElement==null?void 0:i.isElement(m))??!0?m:m.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(o.floating)),boundary:c,rootBoundary:l,strategy:s})),g=u===`floating`?{x:n,y:r,width:a.floating.width,height:a.floating.height}:a.reference,_=await(i.getOffsetParent==null?void 0:i.getOffsetParent(o.floating)),v=await(i.isElement==null?void 0:i.isElement(_))&&await(i.getScale==null?void 0:i.getScale(_))||{x:1,y:1},y=ib(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:o,rect:g,offsetParent:_,strategy:s}):g);return{top:(h.top-y.top+p.top)/v.y,bottom:(y.bottom-h.bottom+p.bottom)/v.y,left:(h.left-y.left+p.left)/v.x,right:(y.right-h.right+p.right)/v.x}}var dWe=50,fWe=async(e,t,n)=>{let{placement:r=`bottom`,strategy:i=`absolute`,middleware:a=[],platform:o}=n,s=o.detectOverflow?o:{...o,detectOverflow:uWe},c=await(o.isRTL==null?void 0:o.isRTL(t)),l=await o.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:d}=lWe(l,r,c),f=r,p=0,m={};for(let n=0;n<a.length;n++){let h=a[n];if(!h)continue;let{name:g,fn:_}=h,{x:v,y,data:b,reset:x}=await _({x:u,y:d,initialPlacement:r,placement:f,strategy:i,middlewareData:m,rects:l,platform:s,elements:{reference:e,floating:t}});u=v??u,d=y??d,m[g]={...m[g],...b},x&&p<dWe&&(p++,typeof x==`object`&&(x.placement&&(f=x.placement),x.rects&&(l=x.rects===!0?await o.getElementRects({reference:e,floating:t,strategy:i}):x.rects),{x:u,y:d}=lWe(l,f,c)),n=-1)}return{x:u,y:d,placement:f,strategy:i,middlewareData:m}},pWe=function(e){return e===void 0&&(e={}),{name:`flip`,options:e,async fn(t){var n;let{placement:r,middlewareData:i,rects:a,initialPlacement:o,platform:s,elements:c}=t,{mainAxis:l=!0,crossAxis:u=!0,fallbackPlacements:d,fallbackStrategy:f=`bestFit`,fallbackAxisSideDirection:p=`none`,flipAlignment:m=!0,...h}=$y(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};let g=eb(r),_=nb(o),v=eb(o)===o,y=await(s.isRTL==null?void 0:s.isRTL(c.floating)),b=d||(v||!m?[rb(o)]:GVe(o)),x=p!==`none`;!d&&x&&b.push(...QVe(o,m,p,y));let S=[o,...b],C=await s.detectOverflow(t,h),w=[],T=i.flip?.overflows||[];if(l&&w.push(C[g]),u){let e=WVe(r,a,y);w.push(C[e[0]],C[e[1]])}if(T=[...T,{placement:r,overflows:w}],!w.every(e=>e<=0)){let e=(i.flip?.index||0)+1,t=S[e];if(t&&(u!==`alignment`||_===nb(t)||T.every(e=>nb(e.placement)!==_||e.overflows[0]>0)))return{data:{index:e,overflows:T},reset:{placement:t}};let n=T.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0]?.placement;if(!n)switch(f){case`bestFit`:{let e=T.filter(e=>{if(x){let t=nb(e.placement);return t===_||t===`y`}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0]?.[0];e&&(n=e);break}case`initialPlacement`:n=o}if(r!==n)return{reset:{placement:n}}}return{}}}},mWe=new Set([`left`,`top`]);async function hWe(e,t){let{placement:n,platform:r,elements:i}=e,a=await(r.isRTL==null?void 0:r.isRTL(i.floating)),o=eb(n),s=tb(n),c=nb(n)===`y`,l=mWe.has(o)?-1:1,u=a&&c?-1:1,d=$y(t,e),{mainAxis:f,crossAxis:p,alignmentAxis:m}=typeof d==`number`?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return s&&typeof m==`number`&&(p=s===`end`?m*-1:m),c?{x:p*u,y:f*l}:{x:f*l,y:p*u}}var gWe=function(e){return e===void 0&&(e=0),{name:`offset`,options:e,async fn(t){var n;let{x:r,y:i,placement:a,middlewareData:o}=t,s=await hWe(t,e);return a===o.offset?.placement&&(n=o.arrow)!=null&&n.alignmentOffset?{}:{x:r+s.x,y:i+s.y,data:{...s,placement:a}}}}},_We=function(e){return e===void 0&&(e={}),{name:`shift`,options:e,async fn(t){let{x:n,y:r,placement:i,platform:a}=t,{mainAxis:o=!0,crossAxis:s=!1,limiter:c={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...l}=$y(e,t),u={x:n,y:r},d=await a.detectOverflow(t,l),f=nb(i),p=VVe(f),m=u[p],h=u[f],g=(e,t)=>BVe(t+d[e===`y`?`top`:`left`],t,t-d[e===`y`?`bottom`:`right`]);o&&(m=g(p,m)),s&&(h=g(f,h));let _=c.fn({...t,[p]:m,[f]:h});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[p]:o,[f]:s}}}}}},vWe=function(e){return e===void 0&&(e={}),{options:e,fn(t){let{x:n,y:r,placement:i,rects:a,middlewareData:o}=t,{offset:s=0,mainAxis:c=!0,crossAxis:l=!0}=$y(e,t),u={x:n,y:r},d=nb(i),f=VVe(d),p=u[f],m=u[d],h=$y(s,t),g=typeof h==`number`?{mainAxis:h,crossAxis:0}:{mainAxis:h.mainAxis??0,crossAxis:h.crossAxis??0};if(c){let e=f===`y`?`height`:`width`,t=a.reference[f]-a.floating[e]+g.mainAxis,n=a.reference[f]+a.reference[e]-g.mainAxis;p<t?p=t:p>n&&(p=n)}if(l){let e=f===`y`?`width`:`height`,t=mWe.has(eb(i)),n=a.reference[d]-a.floating[e]+(t&&o.offset?.[d]||0)+(t?0:g.crossAxis),r=a.reference[d]+a.reference[e]+(t?0:o.offset?.[d]||0)-(t?g.crossAxis:0);m<n?m=n:m>r&&(m=r)}return{[f]:p,[d]:m}}}},yWe=function(e){return e===void 0&&(e={}),{name:`size`,options:e,async fn(t){let{placement:n,rects:r,platform:i,elements:a}=t,{apply:o=()=>{},...s}=$y(e,t),c=await i.detectOverflow(t,s),l=eb(n),u=tb(n),d=nb(n)===`y`,{width:f,height:p}=r.floating,m,h;l===`top`||l===`bottom`?(m=l,h=u===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?`start`:`end`)?`left`:`right`):(h=l,m=u===`end`?`top`:`bottom`);let g=p-c.top-c.bottom,_=f-c.left-c.right,v=Jy(p-c[m],g),y=Jy(f-c[h],_),b=t.middlewareData.shift,x=!b,S=v,C=y;b!=null&&b.enabled.x&&(C=_),b!=null&&b.enabled.y&&(S=g),x&&!u&&(d?C=f-2*Yy(c.left,c.right):S=p-2*Yy(c.top,c.bottom)),await o({...t,availableWidth:C,availableHeight:S});let w=await i.getDimensions(a.floating);return f!==w.width||p!==w.height?{reset:{rects:!0}}:{}}}};function bWe(e){let t=fy(e),n=parseFloat(t.width)||0,r=parseFloat(t.height)||0,i=sy(e),a=i?e.offsetWidth:n,o=i?e.offsetHeight:r,s=Xy(n)!==a||Xy(r)!==o;return s&&(n=a,r=o),{width:n,height:r,$:s}}function xWe(e){return oy(e)?e:e.contextElement}function dx(e){let t=xWe(e);if(!sy(t))return Qy(1);let n=t.getBoundingClientRect(),{width:r,height:i,$:a}=bWe(t),o=(a?Xy(n.width):n.width)/r,s=(a?Xy(n.height):n.height)/i;return o&&Number.isFinite(o)||(o=1),s&&Number.isFinite(s)||(s=1),{x:o,y:s}}var SWe=Qy(0);function CWe(e){let t=iy(e);return!EBe()||!t.visualViewport?SWe:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function wWe(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===iy(e)}function fx(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);let i=e.getBoundingClientRect(),a=xWe(e),o=Qy(1);t&&(r?oy(r)&&(o=dx(r)):o=dx(e));let s=wWe(a,n,r)?CWe(a):Qy(0),c=(i.left+s.x)/o.x,l=(i.top+s.y)/o.y,u=i.width/o.x,d=i.height/o.y;if(a&&r){let e=iy(a),t=oy(r)?iy(r):r,n=e,i=kBe(n);for(;i&&t!==n;){let e=dx(i),t=i.getBoundingClientRect(),r=fy(i),a=t.left+(i.clientLeft+parseFloat(r.paddingLeft))*e.x,o=t.top+(i.clientTop+parseFloat(r.paddingTop))*e.y;c*=e.x,l*=e.y,u*=e.x,d*=e.y,c+=a,l+=o,n=iy(i),i=kBe(n)}}return ib({width:u,height:d,x:c,y:l})}function px(e,t){let n=DBe(e).scrollLeft;return t?t.left+n:fx(ay(e)).left+n}function TWe(e,t){let n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-px(e,n),y:n.top+t.scrollTop}}function EWe(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e,a=i===`fixed`,o=ay(r),s=t?bBe(t.floating):!1;if(r===o||s&&a)return n;let c={scrollLeft:0,scrollTop:0},l=Qy(1),u=Qy(0),d=sy(r);if((d||!a)&&((ry(r)!==`body`||ly(o))&&(c=DBe(r)),d)){let e=fx(r);l=dx(r),u.x=e.x+r.clientLeft,u.y=e.y+r.clientTop}let f=o&&!d&&!a?TWe(o,c):Qy(0);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+u.x+f.x,y:n.y*l.y-c.scrollTop*l.y+u.y+f.y}}function DWe(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function OWe(e){let t=DBe(e),n=e.ownerDocument.body,r=Yy(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=Yy(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight),a=-t.scrollLeft+px(e),o=-t.scrollTop;return fy(n).direction===`rtl`&&(a+=Yy(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:a,y:o}}var kWe=25;function AWe(e,t,n){n===void 0&&(n=`viewport`);let r=n===`layoutViewport`,i=iy(e),a=ay(e),o=i.visualViewport,s=a.clientWidth,c=a.clientHeight,l=0,u=0;if(o){let e=!EBe()||t===`fixed`;r?e||(l=-o.offsetLeft,u=-o.offsetTop):(s=o.width,c=o.height,e&&(l=o.offsetLeft,u=o.offsetTop))}if(px(a)<=0){let e=a.ownerDocument,t=e.body,n=getComputedStyle(t),r=e.compatMode===`CSS1Compat`&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(a.clientWidth-t.clientWidth-r),o=getComputedStyle(a).scrollbarGutter===`stable both-edges`?i/2:i;o<=kWe&&(s-=o)}return{width:s,height:c,x:l,y:u}}function jWe(e,t){let n=fx(e,!0,t===`fixed`),r=n.top+e.clientTop,i=n.left+e.clientLeft,a=dx(e);return{width:e.clientWidth*a.x,height:e.clientHeight*a.y,x:i*a.x,y:r*a.y}}function MWe(e,t,n){let r;if(t===`viewport`||t===`layoutViewport`)r=AWe(e,n,t);else if(t===`document`)r=OWe(ay(e));else if(oy(t))r=jWe(t,n);else{let n=CWe(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return ib(r)}function NWe(e,t){let n=t.get(e);if(n)return n;let r=my(e,[],!1).filter(e=>oy(e)&&ry(e)!==`body`),i=null,a=fy(e).position===`fixed`,o=a?py(e):e;for(;oy(o)&&!dy(o);){let e=fy(o),t=wBe(o),n=i?i.position:a?`fixed`:``;!t&&(n===`fixed`||n===`absolute`&&e.position===`static`)?r=r.filter(e=>e!==o):i=e,o=py(o)}return t.set(e,r),r}function PWe(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e,a=[...n===`clippingAncestors`?bBe(t)?[]:NWe(t,this._c):[].concat(n),r],o=MWe(t,a[0],i),s=o.top,c=o.right,l=o.bottom,u=o.left;for(let e=1;e<a.length;e++){let n=MWe(t,a[e],i);s=Yy(n.top,s),c=Jy(n.right,c),l=Jy(n.bottom,l),u=Yy(n.left,u)}return{width:c-u,height:l-s,x:u,y:s}}function FWe(e){let{width:t,height:n}=bWe(e);return{width:t,height:n}}function IWe(e,t,n){let r=sy(t),i=ay(t),a=n===`fixed`,o=fx(e,!0,a,t),s={scrollLeft:0,scrollTop:0},c=Qy(0);if((r||!a)&&((ry(t)!==`body`||ly(i))&&(s=DBe(t)),r)){let e=fx(t,!0,a,t);c.x=e.x+t.clientLeft,c.y=e.y+t.clientTop}!r&&i&&(c.x=px(i));let l=i&&!r&&!a?TWe(i,s):Qy(0);return{x:o.left+s.scrollLeft-c.x-l.x,y:o.top+s.scrollTop-c.y-l.y,width:o.width,height:o.height}}function LWe(e){return fy(e).position===`static`}function RWe(e,t){if(!sy(e)||fy(e).position===`fixed`)return null;if(t)return t(e);let n=e.offsetParent;return ay(e)===n&&(n=n.ownerDocument.body),n}function zWe(e,t){let n=iy(e);if(bBe(e))return n;if(!sy(e)){let t=py(e);for(;t&&!dy(t);){if(oy(t)&&!LWe(t))return t;t=py(t)}return n}let r=RWe(e,t);for(;r&&yBe(r)&&LWe(r);)r=RWe(r,t);return r&&dy(r)&&LWe(r)&&!wBe(r)?n:r||TBe(e)||n}var BWe=async function(e){let t=this.getOffsetParent||zWe,n=this.getDimensions,r=await n(e.floating);return{reference:IWe(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function VWe(e){return fy(e).direction===`rtl`}var HWe={convertOffsetParentRelativeRectToViewportRelativeRect:EWe,getDocumentElement:ay,getClippingRect:PWe,getOffsetParent:zWe,getElementRects:BWe,getClientRects:DWe,getDimensions:FWe,getScale:dx,isElement:oy,isRTL:VWe};function UWe(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function WWe(e,t,n){let r=null,i,a=ay(e);function o(){var e;clearTimeout(i),(e=r)==null||e.disconnect(),r=null}function s(n,c){n===void 0&&(n=!1),c===void 0&&(c=1),o();let l=e.getBoundingClientRect(),{left:u,top:d,width:f,height:p}=l;if(n||t(),!f||!p)return;let m=Zy(d),h=Zy(a.clientWidth-(u+f)),g=Zy(a.clientHeight-(d+p)),_=Zy(u),v={rootMargin:-m+`px `+-h+`px `+-g+`px `+-_+`px`,threshold:Yy(0,Jy(1,c))||1},y=!0;function b(t){let n=t[0].intersectionRatio;if(!UWe(l,e.getBoundingClientRect()))return s();if(n!==c){if(!y)return s();n?s(!1,n):i=setTimeout(()=>{s(!1,1e-7)},1e3)}y=!1}try{r=new IntersectionObserver(b,{...v,root:a.ownerDocument})}catch{r=new IntersectionObserver(b,v)}r.observe(e)}let c=iy(e),l=()=>s(n);return c.addEventListener(`resize`,l),s(!0),()=>{c.removeEventListener(`resize`,l),o()}}function GWe(e,t,n,r){r===void 0&&(r={});let{ancestorScroll:i=!0,ancestorResize:a=!0,elementResize:o=typeof ResizeObserver==`function`,layoutShift:s=typeof IntersectionObserver==`function`,animationFrame:c=!1}=r,l=xWe(e),u=i||a?[...l?my(l):[],...t?my(t):[]]:[];u.forEach(e=>{i&&e.addEventListener(`scroll`,n),a&&e.addEventListener(`resize`,n)});let d=l&&s?WWe(l,n,a):null,f=-1,p=null;o&&(p=new ResizeObserver(e=>{let[r]=e;r&&r.target===l&&p&&t&&(p.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var e;(e=p)==null||e.observe(t)})),n()}),l&&!c&&p.observe(l),t&&p.observe(t));let m,h=c?fx(e):null;c&&g();function g(){let t=fx(e);h&&!UWe(h,t)&&n(),h=t,m=requestAnimationFrame(g)}return n(),()=>{var e;u.forEach(e=>{i&&e.removeEventListener(`scroll`,n),a&&e.removeEventListener(`resize`,n)}),d?.(),(e=p)==null||e.disconnect(),p=null,c&&cancelAnimationFrame(m)}}var KWe=gWe,qWe=_We,JWe=pWe,YWe=yWe,XWe=vWe,ZWe=(e,t,n)=>{let r=new Map,i=n??{},a={...HWe,...i.platform,_c:r};return fWe(e,t,{...i,platform:a})},mx=typeof document<`u`?G.useLayoutEffect:function(){};function hx(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,r,i;if(e&&t&&typeof e==`object`){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!hx(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){let n=i[r];if(!(n===`_owner`&&e.$$typeof)&&!hx(e[n],t[n]))return!1}return!0}return e!==e&&t!==t}function QWe(e){return typeof window>`u`?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function $We(e,t){let n=QWe(e);return Math.round(t*n)/n}function eGe(e){let t=G.useRef(e);return mx(()=>{t.current=e}),t}function tGe(e){e===void 0&&(e={});let{placement:t=`bottom`,strategy:n=`absolute`,middleware:r=[],platform:i,elements:{reference:a,floating:o}={},transform:s=!0,whileElementsMounted:c,open:l}=e,[u,d]=G.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,p]=G.useState(r);hx(f,r)||p(r);let[m,h]=G.useState(null),[g,_]=G.useState(null),v=G.useCallback(e=>{e!==S.current&&(S.current=e,h(e))},[]),y=G.useCallback(e=>{e!==C.current&&(C.current=e,_(e))},[]),b=a||m,x=o||g,S=G.useRef(null),C=G.useRef(null),w=G.useRef(u),T=c!=null,E=eGe(c),D=eGe(i),O=eGe(l),k=G.useCallback(()=>{if(!S.current||!C.current)return;let e={placement:t,strategy:n,middleware:f};D.current&&(e.platform=D.current),ZWe(S.current,C.current,e).then(e=>{let t={...e,isPositioned:O.current!==!1};A.current&&!hx(w.current,t)&&(w.current=t,Pt.flushSync(()=>{d(t)}))})},[f,t,n,D,O]);mx(()=>{l===!1&&w.current.isPositioned&&(w.current.isPositioned=!1,d(e=>({...e,isPositioned:!1})))},[l]);let A=G.useRef(!1);mx(()=>(A.current=!0,()=>{A.current=!1}),[]),mx(()=>{if(b&&(S.current=b),x&&(C.current=x),b&&x){if(E.current)return E.current(b,x,k);k()}},[b,x,k,E,T]);let j=G.useMemo(()=>({reference:S,floating:C,setReference:v,setFloating:y}),[v,y]),M=G.useMemo(()=>({reference:b,floating:x}),[b,x]),N=G.useMemo(()=>{let e={position:n,left:0,top:0};if(!M.floating)return e;let t=$We(M.floating,u.x),r=$We(M.floating,u.y);return s?{...e,transform:`translate(`+t+`px, `+r+`px)`,...QWe(M.floating)>=1.5&&{willChange:`transform`}}:{position:n,left:t,top:r}},[n,s,M.floating,u.x,u.y]);return G.useMemo(()=>({...u,update:k,refs:j,elements:M,floatingStyles:N}),[u,k,j,M,N])}var nGe=(e,t)=>{let n=KWe(e);return{name:n.name,fn:n.fn,options:[e,t]}},rGe=(e,t)=>{let n=qWe(e);return{name:n.name,fn:n.fn,options:[e,t]}},iGe=(e,t)=>({fn:XWe(e).fn,options:[e,t]}),aGe=(e,t)=>{let n=JWe(e);return{name:n.name,fn:n.fn,options:[e,t]}},oGe=(e,t)=>{let n=YWe(e);return{name:n.name,fn:n.fn,options:[e,t]}},sGe={...Qb,disabled:e=>e.disabled,instantType:e=>e.instantType,isInstantPhase:e=>e.isInstantPhase,trackCursorAxis:e=>e.trackCursorAxis,disableHoverablePopup:e=>e.disableHoverablePopup,lastOpenChangeReason:e=>e.openChangeReason,closeOnClick:e=>e.closeOnClick,appliedTriggerProps:(e,t)=>t?e.activeTriggerProps:void 0,closeDelay:e=>e.closeDelay,adaptiveOrigin:e=>e.adaptiveOrigin},cGe=class extends Jb{constructor(e,t,n){let r=new Kb;super(lGe(e,r,t,n),uGe(r),sGe)}setOpen=(e,t)=>{kUe(this,e,t,{extraState:{openChangeReason:t.reason}})};cancelPendingOpen(e){this.state.floatingRootContext.dispatchOpenChange(!1,Ey(ky,e))}};function lGe(e,t,n,r=!1){return{...Yb(t,n,r),disabled:!1,instantType:void 0,isInstantPhase:!1,trackCursorAxis:`none`,disableHoverablePopup:!1,openChangeReason:null,closeOnClick:!0,closeDelay:0,adaptiveOrigin:void 0,...e}}function uGe(e){return{popupRef:G.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerElements:e}}var dGe=Hv(function(e){let{disabled:t=!1,defaultOpen:n=!1,open:r,disableHoverablePopup:i=!1,trackCursorAxis:a=`none`,actionsRef:o,onOpenChange:s,onOpenChangeComplete:c,handle:l,triggerId:u,defaultTriggerId:d=null,children:f}=e,p=Rb((e,t)=>new cGe({open:n,openProp:r,activeTriggerId:d,triggerIdProp:u},e,t));p.useControlledProp(`openProp`,r),p.useControlledProp(`triggerIdProp`,u),p.useContextCallback(`onOpenChange`,s),p.useContextCallback(`onOpenChangeComplete`,c);let m=p.useState(`open`),h=!t&&m,g=p.useState(`activeTriggerId`),_=p.useState(`mounted`),v=p.useState(`payload`);p.useSyncedValues({trackCursorAxis:a,disableHoverablePopup:i,disabled:t}),Ub(p,{closeOnActiveTriggerUnmount:!0});let{forceUnmount:y,transitionStatus:b}=Wb(h,p),x=p.useState(`isInstantPhase`),S=p.useState(`instantType`),C=p.useState(`lastOpenChangeReason`),w=G.useRef(null);Wv(()=>{m&&t&&p.setOpen(!1,Ey(wVe))},[m,t,p]),Wv(()=>{b===`ending`&&C===`none`||b!==`ending`&&x?(S!==`delay`&&(w.current=S),p.set(`instantType`,`delay`)):w.current!==null&&(p.set(`instantType`,w.current),w.current=null)},[b,x,C,S,p]),Wv(()=>{h&&(g??p.set(`payload`,void 0))},[p,g,h]),G.useImperativeHandle(o,()=>({unmount:y,close:()=>p.setOpen(!1,Ey(Py))}),[y,p]);let T=h||_||!t&&a!==`none`;return(0,K.jsxs)(tBe.Provider,{value:p,children:[l&&(0,K.jsx)(zb,{handle:l,store:p}),T&&(0,K.jsx)(fGe,{store:p,disabled:t,trackCursorAxis:a}),typeof f==`function`?f({payload:v}):f]})});function fGe({store:e,disabled:t,trackCursorAxis:n}){let r=e.useState(`floatingRootContext`),i=jb(r,{enabled:!t,referencePress:()=>e.select(`closeOnClick`)}),a=lUe(r,{enabled:!t&&n!==`none`,axis:n===`none`?void 0:n}),o=G.useMemo(()=>D(a.reference,i.reference),[a.reference,i.reference]);return Gb(e,{activeTriggerProps:o,inactiveTriggerProps:o,popupProps:i.floating??te}),null}function gx(e){return xb(e,`base-ui`)}var pGe=G.createContext(void 0);function mGe(){return G.useContext(pGe)}var hGe=`data-base-ui-tooltip-trigger`;function gGe(e){let t=vy(e);return oy(t)?t:null}var _Ge=Uv(function(e,t){let{render:n,className:r,style:i,handle:a,payload:o,disabled:s,delay:c,closeOnClick:l=!0,closeDelay:u,id:d,...f}=e,p=Kv(!0),m=$b(a)??p;if(!m)throw Error(Gv(82));let h=gx(d),g=m.useState(`isTriggerActive`,h),_=m.useState(`isOpenedByTrigger`,h),v=m.useState(`floatingRootContext`),y=G.useRef(null),b=u??0,{registerTrigger:x,isMountedByThisTrigger:S}=Hb(h,y,m,{payload:o,closeOnClick:l,closeDelay:b}),C=mGe(),{activeIdRef:w,delayRef:T,isInstantPhase:E,hasProvider:D}=jVe(v,{open:_}),O=QUe(v);m.useSyncedValue(`isInstantPhase`,E);let k=m.useState(`disabled`),A=s??k,j=Ry(A),M=m.useState(`trackCursorAxis`),P=m.useState(`disableHoverablePopup`),F=G.useRef(!1),I=Yv(),L=G.useRef(void 0);function R(){return D&&w.current!=null?0:c??C??600}function z(e){let t=y.current;if(!t||!e)return!1;let n=_y(e,`[${hGe}]`);return n!==null&&n!==t&&gy(t,n)}function B(e){let t=z(e);return F.current=t,t&&(O.openChangeTimeout.clear(),O.restTimeout.clear(),O.restTimeoutPending=!1,I.clear()),t}let V=rx(v,{enabled:!A,mouseOnly:!0,move:!1,handleClose:!P&&M!==`both`?ux():null,restMs:R,delay(){return u==null&&D?{close:Ty(T.current,`close`)}:{close:b}},triggerElementRef:y,isActiveTrigger:g,isClosing:()=>m.select(`transitionStatus`)===`ending`,shouldOpen(){return!F.current}}),H=YUe(v,{enabled:!A}).reference,ee=e=>{let t=F.current,n=gGe(e),r=B(n),i=y.current,a=i&&n&&gy(i,n);if(r&&m.select(`open`)&&m.select(`lastOpenChangeReason`)===`trigger-hover`)m.setOpen(!1,Ey(Ay,e));else if(t&&!r&&a&&!j.current&&!m.select(`open`)&&i&&ny(L.current)){let t=()=>{F.current||j.current||m.select(`open`)||m.setOpen(!0,Ey(Ay,e,i))},n=R();n===0?(I.clear(),t()):I.start(n,t)}},te=m.useState(`appliedTriggerProps`,S||M!==`none`);return N(`button`,e,{state:{open:_},ref:[t,x,y],props:[V,H,te,{onMouseOver(e){ee(e.nativeEvent)},onFocus(e){z(gGe(e.nativeEvent))&&e.preventBaseUIHandler()},onMouseLeave(){F.current=!1,I.clear(),L.current=void 0},onPointerEnter(e){L.current=e.pointerType},onPointerDown(e){L.current=e.pointerType,m.set(`closeOnClick`,l),l&&!m.select(`open`)&&m.cancelPendingOpen(e.nativeEvent)},onClick(e){l&&!m.select(`open`)&&m.cancelPendingOpen(e.nativeEvent)},id:h,[XBe]:A?``:void 0,[hGe]:A?void 0:``},f],stateAttributesMapping:by})}),vGe=G.createContext(void 0);function yGe(){let e=G.useContext(vGe);if(e===void 0)throw Error(Gv(70));return e}var bGe=G.forwardRef(function(e,t){let{children:n,container:r,className:i,render:a,style:o,...s}=e,{node:c,subtree:l}=qHe({container:r,ref:t,componentProps:e,elementProps:s});return!l&&!c?null:(0,K.jsxs)(G.Fragment,{children:[l,c&&Pt.createPortal(n,c)]})}),xGe=G.forwardRef(function(e,t){let{keepMounted:n=!1,...r}=e;return Kv().useState(`mounted`)||n?(0,K.jsx)(vGe.Provider,{value:n,children:(0,K.jsx)(bGe,{ref:t,...r})}):null}),SGe=G.createContext(void 0);function CGe(){let e=G.useContext(SGe);if(e===void 0)throw Error(Gv(71));return e}function wGe(e){let{nodeId:t,externalTree:n,rootContext:r}=e,i=r.useState(`referenceElement`),a=r.useState(`floatingElement`),o=r.useState(`domReferenceElement`),s=r.useState(`open`),c=r.useState(`floatingId`),[l,u]=G.useState(null),d=G.useRef(null),f=Tb(n),p=G.useMemo(()=>({reference:i,floating:a,domReference:o}),[i,a,o]),m=tGe({...e,elements:{...p,...l&&{reference:l}}}),h=G.useCallback(e=>{let t=oy(e)?{getBoundingClientRect:()=>e.getBoundingClientRect(),getClientRects:()=>e.getClientRects(),contextElement:e}:e;u(t),m.refs.setReference(t)},[m.refs]),g=G.useMemo(()=>({...m.refs,setPositionReference:h,domReference:d}),[m.refs,h]),_=G.useMemo(()=>({...m.elements,domReference:o}),[m.elements,o]),v=G.useMemo(()=>({...m,dataRef:r.context.dataRef,open:s,onOpenChange:r.setOpen,events:r.context.events,floatingId:c,refs:g,elements:_,nodeId:t,rootStore:r}),[m,g,_,t,r,s,c]);return Wv(()=>{o&&(d.current=o)},[o]),Wv(()=>{r.context.dataRef.current.floatingContext=v;let e=f?.nodesRef.current.find(e=>e.id===t);e&&(e.context=v)}),G.useMemo(()=>({...m,context:v,refs:g,elements:_,rootStore:r}),[m,g,_,v,r])}var TGe=G.createContext(void 0);function _x(){return G.useContext(TGe)?.direction??`ltr`}var EGe=e=>({name:`arrow`,options:e,async fn(t){let{x:n,y:r,placement:i,rects:a,platform:o,elements:s,middlewareData:c}=t,{element:l,padding:u=0}=$y(e,t)||{};if(l==null)return{};let d=eHe(u),f={x:n,y:r},p=UVe(i),m=HVe(p),h=await o.getDimensions(l),g=p===`y`,_=g?`top`:`left`,v=g?`bottom`:`right`,y=g?`clientHeight`:`clientWidth`,b=a.reference[m]+a.reference[p]-f[p]-a.floating[m],x=f[p]-a.reference[p],S=s.floating[y]||a.floating[m],C=b/2-x/2,w=S/2-h[m]/2-1,T=Math.min(d[_],w),E=Math.min(d[v],w),D=T,O=S-h[m]-E,k=S/2-h[m]/2+C,A=BVe(D,k,O),j=!c.arrow&&tb(i)!=null&&k!==A&&a.reference[m]/2-(k<D?T:E)-h[m]/2<0,M=j?k<D?k-D:k-O:0;return{[p]:f[p]+M,data:{[p]:A,centerOffset:k-A-M,...j&&{alignmentOffset:M}},reset:j}}}),DGe=(e,t)=>{let{name:n,fn:r}=EGe(e);return{name:n,fn:r,options:[e,t]}},OGe={name:`hide`,async fn(e){let{width:t,height:n,x:r,y:i}=e.rects.reference,a=t===0&&n===0&&r===0&&i===0,o=await e.platform.detectOverflow(e,{elementContext:`reference`});return{data:{referenceHidden:o.top-n>=0||o.right-t>=0||o.bottom-n>=0||o.left-t>=0||a}}}},kGe={sideX:`left`,sideY:`top`},AGe=`--available-width`,jGe=`--available-height`,MGe=`--anchor-width`,NGe=`--anchor-height`,PGe=`--transform-origin`,FGe=AGe,IGe=jGe;function LGe(e,t,n){let r=e===`inline-start`||e===`inline-end`;return{top:`top`,right:r?n?`inline-start`:`inline-end`:`right`,bottom:`bottom`,left:r?n?`inline-end`:`inline-start`:`left`}[t]}function RGe(e,t,n){let{rects:r,placement:i}=e;return{side:LGe(t,eb(i),n),align:tb(i)||`center`,anchor:{width:r.reference.width,height:r.reference.height},positioner:{width:r.floating.width,height:r.floating.height}}}function vx(e){return zGe(e,wGe)}function zGe(e,t){let{anchor:n,positionMethod:r=`absolute`,side:i=`bottom`,sideOffset:a=0,align:o=`center`,alignOffset:s=0,collisionBoundary:c,collisionPadding:l=5,sticky:u=!1,arrowPadding:d=5,disableAnchorTracking:f=!1,inline:p,keepMounted:m=!1,floatingRootContext:h,mounted:g,collisionAvoidance:_,shift:v,nodeId:y,adaptiveOrigin:b,lazyFlip:x=!1,externalTree:S}=e,C=_.side||`flip`,w=_.align||`flip`,T=_.fallbackAxisSide||`end`,E=v?.crossAxis??!1,D=v?.rootBoundary,O=typeof n==`function`?n:void 0,k=zy(O),A=O?k:n,j=Ry(n),M=Ry(g),N=_x()===`rtl`,[P,F]=G.useState(null);!g&&P!==null&&F(null);let I=x===`placement`,L=P?eb(P):null,R=P&&I?tb(P)||`center`:null,z=L||{top:`top`,right:`right`,bottom:`bottom`,left:`left`,"inline-end":N?`left`:`right`,"inline-start":N?`right`:`left`}[i],B=R||o,V=B===`center`?z:`${z}-${B}`,H=l;typeof H==`number`?H={top:H,right:H,bottom:H,left:H}:H&&={top:H.top||0,right:H.right||0,bottom:H.bottom||0,left:H.left||0};let ee=+(i===`bottom`),te=+(i===`top`),U=+(i===`right`),W=+(i===`left`),ne={boundary:c===`clipping-ancestors`?`clippingAncestors`:c,padding:H},re=G.useRef(null),ie=Ry(a),ae=Ry(s),oe=typeof a==`function`?0:a,se=typeof s==`function`?0:s,ce=[];p&&ce.push(p),ce.push(nGe(e=>{let t=RGe(e,i,N),n=typeof ie.current==`function`?ie.current(t):ie.current,r=typeof ae.current==`function`?ae.current(t):ae.current;return{mainAxis:n,crossAxis:r,alignmentAxis:r}},[oe,se,N,i]));let le=w===`none`&&C!==`shift`,ue=!le&&(u||E||C===`shift`),de=C===`none`?null:aGe({...ne,padding:{top:H.top+1+ee,right:H.right+1+W,bottom:H.bottom+1+te,left:H.left+1+U},mainAxis:!E&&C===`flip`,crossAxis:w===`flip`&&`alignment`,fallbackAxisSideDirection:T}),fe=le?null:rGe({...ne,rootBoundary:D,mainAxis:w!==`none`,crossAxis:ue,limiter:u||E?void 0:iGe(e=>{if(!re.current)return{};let{width:t,height:n}=re.current.getBoundingClientRect(),r=nb(eb(e.placement)),i=r===`y`?t:n,a=r===`y`?H.left+H.right:H.top+H.bottom;return{offset:i/2+a/2}})},[ne,u,E,D,H,w]);C===`shift`||w===`shift`||B===`center`?ce.push(fe,de):ce.push(de,fe),ce.push(oGe({...ne,apply({elements:{floating:e},availableWidth:t,availableHeight:n,rects:r}){if(!M.current)return;let i=e.style;i.setProperty(FGe,`${t}px`),i.setProperty(IGe,`${n}px`);let a=iy(e).devicePixelRatio||1,{x:o,y:s,width:c,height:l}=r.reference,u=(Math.round((o+c)*a)-Math.round(o*a))/a,d=(Math.round((s+l)*a)-Math.round(s*a))/a;i.setProperty(MGe,`${u}px`),i.setProperty(NGe,`${d}px`)}}),DGe(e=>({element:re.current||Wy(e.elements.floating).createElement(`div`),padding:re.current?d:0}),[d]),{name:`transformOrigin`,fn(e){let{elements:{floating:t},middlewareData:n,placement:r,platform:o,rects:s,y:c}=e,l=eb(r),u=tb(r),d=nb(l)===`y`,f=re.current,p=typeof a==`function`?a(RGe(e,i,N)):a,m;m=!f&&u&&Math.abs(d?n.shift?.x||0:n.shift?.y||0)<=1?u===`start`===(d&&o.isRTL?.(t)===!0)?`100%`:`0%`:`${(d?n.arrow?.x||0:n.arrow?.y||0)+(d?f?.clientWidth||0:f?.clientHeight||0)/2}px`;let h=l===`top`||l===`left`?`calc(100% + ${p}px)`:`${-p}px`;return ue&&d&&Math.abs(n.shift?.y||0)>p&&(h=`${s.reference.y+s.reference.height/2-c}px`),t.style.setProperty(PGe,d?`${m} ${h}`:`${h} ${m}`),{}}},OGe,b),Wv(()=>{!g&&h&&h.update({referenceElement:null,floatingElement:null,domReferenceElement:null,positionReference:null})},[g,h]);let pe=G.useMemo(()=>({ancestorScroll:!f,elementResize:!f&&typeof ResizeObserver<`u`,layoutShift:!f&&typeof IntersectionObserver<`u`}),[f]),{refs:me,elements:he,x:ge,y:_e,middlewareData:ve,update:ye,placement:be,context:xe,isPositioned:Se,floatingStyles:Ce}=t({rootContext:h,open:m?g:void 0,placement:V,middleware:ce,strategy:r,whileElementsMounted:m?void 0:(...e)=>GWe(...e,pe),nodeId:y,externalTree:S}),{sideX:we,sideY:Te}=ve.adaptiveOrigin||kGe,Ee=Se?r:`fixed`,De=G.useMemo(()=>{let e;return e=Se?b?{position:Ee,[we]:ge,[Te]:_e}:{...Ce,position:Ee}:{position:Ee,top:0,left:0},e[FGe]=`100vw`,e[IGe]=`100vh`,Se||(e.opacity=0),e},[b,Ee,we,ge,Te,_e,Ce,Se]),Oe=G.useRef(null);Wv(()=>{if(!g)return;let e=j.current,t=typeof e==`function`?e():e,n=(BGe(t)?t.current:t)||null;n!==Oe.current&&(me.setPositionReference(n),Oe.current=n)},[g,me,A,j]),G.useEffect(()=>{if(!g)return;let e=j.current;typeof e!=`function`&&BGe(e)&&e.current!==Oe.current&&(me.setPositionReference(e.current),Oe.current=e.current)},[g,me,A,j]),G.useEffect(()=>{if(m&&g&&he.reference&&he.floating)return GWe(he.reference,he.floating,ye,pe)},[m,g,he,ye,pe]);let ke=eb(be),Ae=LGe(i,ke,N),je=tb(be)||`center`,Me=!!ve.hide?.referenceHidden;Wv(()=>{x&&g&&Se&&(ke!==z||I&&je!==B)&&F(be)},[x,I,g,Se,be,ke,je,z,B]);let Ne=G.useMemo(()=>({position:`absolute`,top:ve.arrow?.y,left:ve.arrow?.x}),[ve.arrow]),Pe=ve.arrow?.centerOffset!==0;return G.useMemo(()=>({positionerStyles:De,arrowStyles:Ne,arrowRef:re,arrowUncentered:Pe,side:Ae,align:je,physicalSide:ke,anchorHidden:Me,refs:me,context:xe,isPositioned:Se,update:ye}),[De,Ne,re,Pe,Ae,je,ke,Me,me,xe,Se,ye])}function BGe(e){return e!=null&&`current`in e}function yx(e){return e===`starting`?RHe:te}function bx(e,t,{styles:n,transitionStatus:r,props:i,refs:a,hidden:o,inert:s=!1}){let c={...n};return s&&(c.pointerEvents=`none`),N(`div`,e,{state:t,ref:a,props:[{role:`presentation`,hidden:o,style:c},yx(r),i],stateAttributesMapping:Sy})}var VGe=G.forwardRef(function(e,t){let{render:n,className:r,anchor:i,positionMethod:a=`absolute`,side:o=`top`,align:s=`center`,sideOffset:c=0,alignOffset:l=0,collisionBoundary:u=`clipping-ancestors`,collisionPadding:d=5,arrowPadding:f=5,sticky:p=!1,disableAnchorTracking:m=!1,collisionAvoidance:h=Sb,style:g,..._}=e,v=Kv(),y=yGe(),b=v.useState(`open`),x=v.useState(`mounted`),S=v.useState(`trackCursorAxis`),C=v.useState(`disableHoverablePopup`),w=v.useState(`floatingRootContext`),T=v.useState(`instantType`),E=v.useState(`transitionStatus`),D=vx({anchor:i,positionMethod:a,floatingRootContext:w,mounted:x,side:o,sideOffset:c,align:s,alignOffset:l,collisionBoundary:u,collisionPadding:d,sticky:p,arrowPadding:f,disableAnchorTracking:m,keepMounted:y,collisionAvoidance:h,adaptiveOrigin:v.useState(`adaptiveOrigin`)}),O=bx(e,G.useMemo(()=>({open:b,side:D.side,align:D.align,anchorHidden:D.anchorHidden,instant:S===`none`?T:`tracking-cursor`}),[b,D.side,D.align,D.anchorHidden,S,T]),{styles:D.positionerStyles,transitionStatus:E,props:_,refs:[t,v.useStateSetter(`positionerElement`)],hidden:!x,inert:!b||S===`both`||C});return(0,K.jsx)(SGe.Provider,{value:D,children:O})}),HGe=G.forwardRef(function(e,t){let{render:n,className:r,style:i,...a}=e,o=Kv(),{side:s,align:c}=CGe(),l=o.useState(`open`),u=o.useState(`instantType`),d=o.useState(`transitionStatus`),f=o.useState(`popupProps`),p=o.useState(`floatingRootContext`),m=o.useState(`disabled`),h=o.useState(`closeDelay`);Ib({open:l,ref:o.context.popupRef,onComplete(){l&&o.context.onOpenChangeComplete?.(!0)}}),nx(p,{enabled:!m,closeDelay:h});let g=o.useStateSetter(`popupElement`);return N(`div`,e,{state:{open:l,side:s,align:c,instant:u,transitionStatus:d},ref:[t,o.context.popupRef,g],props:[Lb,f,yx(d),a],stateAttributesMapping:Cy})}),UGe=G.forwardRef(function(e,t){let{render:n,className:r,style:i,...a}=e,o=Kv(),{arrowRef:s,side:c,align:l,arrowUncentered:u,arrowStyles:d}=CGe(),f={open:o.useState(`open`),side:c,align:l,uncentered:u,instant:o.useState(`instantType`)};return N(`div`,e,{state:f,ref:[t,s],props:[{style:d,"aria-hidden":!0},a],stateAttributesMapping:Sy})}),WGe=function(e){let{delay:t,closeDelay:n,timeout:r=400}=e,i=G.useMemo(()=>({open:t,close:n}),[t,n]);return(0,K.jsx)(pGe.Provider,{value:t,children:(0,K.jsx)(AVe,{delay:i,timeoutMs:r,children:e.children})})};function xx(e){return ee(19)?e:e?`true`:void 0}function GGe(e){let[t,n]=G.useState({current:e,previous:null});return Object.is(e,t.current)||n({current:e,previous:t.current}),t.previous}function KGe(e){let t=fy(e),n=parseFloat(t.width)||0,r=parseFloat(t.height)||0,i=sy(e),a=i?e.offsetWidth:n,o=i?e.offsetHeight:r;return(Xy(n)!==a||Xy(r)!==o)&&(n=a,r=o),{width:n,height:r}}function Sx({delay:e,delayDuration:t,timeout:n,skipDelayDuration:r,...i}){let a=e??t,o=n??r;return(0,K.jsx)(WGe,{...a===void 0?{}:{delay:a},...o===void 0?{}:{timeout:o},...i})}var Cx=dGe,wx=G.forwardRef(({asChild:e,render:t,children:n,...r},i)=>e&&G.isValidElement(n)?(0,K.jsx)(_Ge,{ref:i,render:n,...r}):(0,K.jsx)(_Ge,{ref:i,render:t,...r,children:n}));wx.displayName=`TooltipTrigger`;var Tx=G.forwardRef(({className:e,side:t=`top`,sideOffset:n=8,align:r=`center`,alignOffset:i=0,arrowPadding:a=10,anchor:o,positionMethod:s=zv,collisionBoundary:l,collisionPadding:u,sticky:d,disableAnchorTracking:f,collisionAvoidance:p,keepMounted:m,children:h,...g},_)=>{let v={side:t,sideOffset:n,align:r,alignOffset:i,arrowPadding:a,anchor:o,positionMethod:s,collisionBoundary:l,collisionPadding:u,sticky:d,disableAnchorTracking:f,collisionAvoidance:p};return(0,K.jsx)(xGe,{keepMounted:m,children:(0,K.jsx)(VGe,{className:`isolate z-100`,...v,children:(0,K.jsxs)(HGe,{ref:_,role:`tooltip`,className:c(`relative z-100 flex origin-(--transform-origin) flex-col rounded-lg px-2.5 py-1.5 text-caption text-foreground transition-[transform,scale,opacity] duration-150`,Vv,`data-[starting-style]:scale-95 data-[starting-style]:opacity-0`,`data-[ending-style]:scale-95 data-[ending-style]:opacity-0`,`data-[instant]:transition-none motion-reduce:transition-none`,e),...g,children:[h,(0,K.jsx)(UGe,{className:c(`flex`,`data-[side=top]:bottom-[-7px] data-[side=top]:rotate-180`,`data-[side=bottom]:top-[-7px]`,`data-[side=left]:right-[-9px] data-[side=left]:rotate-90`,`data-[side=right]:left-[-9px] data-[side=right]:-rotate-90`),children:(0,K.jsx)(qGe,{})})]})})})});Tx.displayName=`TooltipContent`;function qGe(){return(0,K.jsxs)(`svg`,{width:`12`,height:`8`,viewBox:`0 0 12 8`,fill:`none`,overflow:`visible`,children:[(0,K.jsx)(`path`,{d:`M0 7L4 2Q6 0 8 2L12 7L12 8L0 8Z`,className:`fill-card`}),(0,K.jsx)(`path`,{d:`M0 7.5L4 2.5Q6 0.5 8 2.5L12 7.5`,className:`fill-none [stroke:var(--surface-rim)]`,strokeWidth:`1`,strokeLinejoin:`round`,strokeLinecap:`round`})]})}var Ex={xs:`[&>svg]:size-icon-xs`,sm:`[&>svg]:size-icon-sm`,md:`[&>svg]:size-icon-md`,lg:`[&>svg]:size-icon-lg`},Dx=({children:e,className:t,size:n=`md`,...r})=>(0,K.jsx)(`span`,{"data-slot":`icon`,className:c(`block`,Ex[n],t),...r,children:e}),Ox=c(`[--control-icon:var(--control-icon-rest)] [&_svg]:text-(color:--control-icon)`,`not-disabled:hover:[--control-icon:var(--control-icon-hover)] aria-disabled:[--control-icon:var(--control-icon-rest)]`,`data-[shape=icon]:[--control-icon-hover:var(--foreground)]`),JGe=`[--control-icon-hover:var(--foreground)]`,YGe=G.createContext(void 0),kx={sm:`h-control-sm`,md:`h-control-md`,lg:`h-control-lg`},Ax={sm:`h-control-sm text-label`,md:`h-control-md text-label`,lg:`h-control-lg text-label`},jx={sm:`[--control-px:.9em] [--control-gap:0.3125rem]`,md:`[--control-px:.9em] [--control-gap:0.375rem]`,lg:`[--control-px:1em] [--control-gap:0.375rem]`},XGe={default:`data-[popup-open]:[--surface-tint:var(--fill)] data-[popup-open]:text-foreground`,ghost:`data-[popup-open]:bg-fill-subtle data-[popup-open]:text-foreground`};function ZGe(e){return e==="default"||e===`ghost`?XGe[e]:void 0}var QGe=`disabled:cursor-not-allowed disabled:text-muted-foreground`,$Ge=`focus-visible:border-border-focus`,eKe=`focus-within:border-border-focus`,tKe=`outline-hidden focus-visible:outline-hidden ${$Ge}`,nKe=`focus-visible:outline-hidden focus-visible:[--surface-rim:var(--border-focus)]`,rKe=`focus-visible:outline-hidden focus-visible:[--surface-rim:var(--field-rim-focus)]`,iKe=`aria-invalid:[--field-rim:var(--destructive-indicator)] aria-invalid:[--field-rim-focus:var(--destructive-indicator)]`,aKe=`has-[[aria-invalid=true]]:[--field-rim:var(--destructive-indicator)] has-[[aria-invalid=true]]:[--field-rim-focus:var(--destructive-indicator)]`;function Mx(e){return e?{"aria-invalid":!0}:{}}var oKe=`aria-invalid:border-destructive-indicator aria-invalid:hover:border-destructive-indicator aria-invalid:focus-visible:border-destructive-indicator`;``+rKe;var sKe=`w-(--field-width,100%) max-w-(--field-max-width,none) shrink-(--field-shrink,1)`,cKe=`bg-field shadow-input text-foreground disabled:bg-field-disabled [&:hover:not(:focus-visible):not(:disabled):not([data-popup-open])]:[--surface-tint:var(--fill-subtle)] outline-hidden focus-visible:outline-hidden `+rKe,Nx=`bg-field shadow-input text-foreground has-[:disabled]:bg-field-disabled [&:hover:not(:has(:focus-visible)):not(:has(:disabled))]:[--surface-tint:var(--fill-subtle)] outline-hidden focus-within:outline-hidden has-[:focus-visible]:[--surface-rim:var(--field-rim-focus)]`,lKe=`bg-field shadow-input text-foreground [&:hover:not(:active):not(:disabled):not([data-popup-open])]:[--surface-tint:var(--fill-subtle)] [&:active:not(:disabled)]:[--surface-tint:var(--fill)] focus-visible:outline-hidden focus-visible:[--surface-rim:var(--border-focus)]`;function uKe(e){return e===`filled`?`default`:e}var dKe=`border-0 bg-transparent outline-hidden focus-visible:outline-hidden`,fKe=G.createContext(void 0);function Px(e=!1){let t=G.useContext(fKe);if(t===void 0&&!e)throw Error(Gv(16));return t}function pKe(e){let{focusableWhenDisabled:t,disabled:n,composite:r=!1,tabIndex:i=0,isNativeButton:a}=e,o=r&&t!==!1,s=r&&t===!1;return{props:G.useMemo(()=>{let e={onKeyDown(e){n&&t&&e.key!==`Tab`&&e.preventDefault()}};return r||(e.tabIndex=i,!a&&n&&(e.tabIndex=t?i:-1)),(a&&(t||o)||!a&&n)&&(e[`aria-disabled`]=n),a&&(!t||s)&&(e.disabled=n),e},[r,n,t,o,s,a,i])}}function Fx(e,t,{detail:n=0,pointerType:r=``}={}){e.dispatchEvent(new(iy(e)).PointerEvent(`click`,{bubbles:!0,cancelable:!0,composed:!0,detail:n,pointerType:r,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,altKey:t.altKey,metaKey:t.metaKey}))}function Ix(e={}){let{disabled:t=!1,focusableWhenDisabled:n,tabIndex:r=0,native:i=!0,composite:a}=e,o=G.useRef(null),s=Px(!0),c=a??s!==void 0,{props:l}=pKe({focusableWhenDisabled:n,disabled:t,composite:c,tabIndex:r,isNativeButton:i}),u=G.useCallback(()=>{let e=o.current;mKe(e)&&c&&t&&l.disabled===void 0&&e.disabled&&(e.disabled=!1)},[t,l.disabled,c]);return Wv(u,[u]),{getButtonProps:G.useCallback((e={})=>{let{onClick:n,onMouseDown:r,onKeyUp:a,onKeyDown:o,onPointerDown:s,...u}=e;return D({onClick(e){t?e.preventDefault():n?.(e)},onMouseDown(e){t||r?.(e)},onKeyDown(e){if(t||(O(e),o?.(e),e.baseUIHandlerPrevented))return;let n=e.target===e.currentTarget,r=e.currentTarget,a=mKe(r),s=!i&&hKe(r),l=n&&(i?a:!s),u=e.key===`Enter`,d=e.key===` `,f=r.getAttribute(`role`),p=f?.startsWith(`menuitem`)||f===`option`||f===`gridcell`;if(n&&c&&d){if(e.defaultPrevented&&p)return;e.preventDefault(),(!i||a)&&(e.preventBaseUIHandler(),Fx(r,e))}else!l||i||!d&&!u?n&&s&&d&&e.preventDefault():e.defaultPrevented||(e.preventDefault(),u&&(e.preventBaseUIHandler(),Fx(r,e)))},onKeyUp(e){t||(O(e),a?.(e),e.target===e.currentTarget&&i&&c&&mKe(e.currentTarget)&&e.key===` `?e.preventDefault():e.baseUIHandlerPrevented||e.target!==e.currentTarget||i||c||e.defaultPrevented||e.key!==` `||(e.preventBaseUIHandler(),Fx(e.currentTarget,e)))},onPointerDown(e){t?e.preventDefault():s?.(e)}},i?{type:`button`}:{role:`button`},l,u)},[t,l,c,i]),buttonRef:zy(e=>{o.current=e,u()})}}function mKe(e){return sy(e)&&e.tagName===`BUTTON`}function hKe(e){return sy(e)&&e.tagName===`A`&&!!e.href}var gKe=G.forwardRef(function(e,t){let{render:n,className:r,disabled:i=!1,focusableWhenDisabled:a=!1,nativeButton:o=!0,style:s,...c}=e,{getButtonProps:l,buttonRef:u}=Ix({disabled:i,focusableWhenDisabled:a,native:o});return N(`button`,e,{state:{disabled:i},ref:[t,u],props:[c,l]})}),_Ke=c(`rounded-full px-[calc(var(--control-px)-var(--control-border,0px))]`,`has-[>[data-slot=button-icon]]:pl-[calc(var(--control-px)-2px-var(--control-border,0px))]`,`has-[>svg]:pl-[calc(var(--control-px)-2px-var(--control-border,0px))]`,`has-[>[data-slot=button-icon-end]]:pr-[calc(var(--control-px)-2px-var(--control-border,0px))]`),vKe=c(`relative size-auto gap-1 rounded-xs px-0 text-label`,`before:absolute before:-inset-x-2`,`has-[>[data-slot=button-icon-end]]:pr-0 has-[>[data-slot=button-icon]]:pl-0 has-[>svg]:pl-0`),yKe=c(`relative inline-flex items-center gap-1`,Ex.sm,`[&>svg]:shrink-0`,`after:absolute after:inset-x-0 after:bottom-0 after:h-px after:origin-left after:scale-x-0 after:bg-current`,`after:transition-transform after:duration-fast after:ease-out-custom motion-reduce:after:transition-none`),Lx=Nt(c(`inline-flex cursor-pointer items-center justify-center whitespace-nowrap`,A,QGe,`aria-disabled:pointer-events-none aria-disabled:cursor-not-allowed aria-disabled:text-muted-foreground`,tKe),{variants:{variant:{default:c(`border-0`,lKe,Ox,`disabled:bg-fill-subtle aria-disabled:bg-fill-subtle`),primary:c(`border border-transparent bg-fill-inverse text-background [--control-border:1px] not-disabled:hover:bg-fill-inverse-hover not-disabled:active:bg-fill-inverse-active`,g,`focus-visible:border-transparent`,`disabled:bg-fill-inverse-disabled disabled:text-background/75 aria-disabled:bg-fill-inverse-disabled aria-disabled:text-background/75`),destructive:c(`border border-transparent bg-fill-destructive text-fill-destructive-foreground [--control-border:1px] not-disabled:hover:bg-fill-destructive-hover not-disabled:active:bg-fill-destructive-active`,g,`focus-visible:border-transparent`,`disabled:bg-fill-destructive-disabled disabled:text-fill-destructive-disabled-foreground aria-disabled:bg-fill-destructive-disabled aria-disabled:text-fill-destructive-disabled-foreground`),"destructive-ghost":c(`border border-transparent bg-transparent text-destructive-foreground [--control-border:1px] not-disabled:hover:bg-destructive-subtle not-disabled:hover:text-destructive-foreground not-disabled:active:bg-destructive-subtle-active`,`disabled:bg-transparent disabled:text-placeholder aria-disabled:bg-transparent aria-disabled:text-placeholder`),ghost:c(`border border-transparent bg-transparent text-muted-foreground [--control-border:1px] not-disabled:hover:bg-fill-subtle not-disabled:hover:text-foreground not-disabled:active:bg-fill`,Ox,`disabled:bg-transparent aria-disabled:bg-transparent`),subtle:c(`border-0 bg-fill-hover text-foreground not-disabled:hover:bg-fill-hover not-disabled:active:bg-fill`,p,`disabled:bg-transparent aria-disabled:bg-transparent`),link:c(`border-0 bg-transparent text-muted-foreground not-disabled:hover:text-foreground`,`not-disabled:hover:[&>[data-slot=button-label]]:after:scale-x-100 not-disabled:hover:[&>[data-slot=button-label]]:after:duration-normal`,g,`disabled:text-placeholder aria-disabled:text-placeholder`)},size:{sm:c(Ax.sm,Ex.sm,jx.sm,`gap-(--control-gap)`,_Ke),md:c(Ax.md,Ex.md,jx.md,`gap-(--control-gap)`,_Ke),lg:c(Ax.lg,Ex.lg,jx.lg,`gap-(--control-gap)`,_Ke),"icon-sm":c(kx.sm,`w-control-sm rounded-full`),"icon-md":c(kx.md,`w-control-md rounded-full`),"icon-lg":c(kx.lg,`w-control-lg rounded-full`)}},compoundVariants:[{variant:`link`,className:vKe},{variant:`link`,size:[`sm`,`md`,`icon-sm`,`icon-md`],className:`before:-inset-y-1`},{variant:`link`,size:[`lg`,`icon-lg`],className:`before:-inset-y-1.5`}],defaultVariants:{variant:`default`,size:`md`}});function bKe(e){if(e.type===`a`)return!0;let{href:t,to:n}=e.props;return t!==void 0||n!==void 0}function xKe(e){e.preventDefault(),e.stopPropagation()}var Rx={sm:`sm`,md:`md`,lg:`lg`,"icon-sm":`sm`,"icon-md":`md`,"icon-lg":`lg`};function SKe(e,t){return e===`link`?`sm`:Rx[t]}function CKe({size:e,children:t}){return(0,K.jsx)(zx,{slot:`button-icon`,size:Rx[e],children:t})}function wKe(){return(0,K.jsx)(_,{"aria-hidden":!0,"data-slot":`trigger-chevron`,className:`mx-[-0.125em] shrink-0`})}function TKe({size:e}){return(0,K.jsx)(zx,{slot:`button-icon-end`,size:Rx[e],children:(0,K.jsx)(wKe,{})})}function zx({slot:e,size:t,children:n}){if(n)return(0,K.jsx)(Dx,{"data-slot":e,size:t,children:n})}function EKe({variant:e,children:t}){return e===`link`?(0,K.jsx)(`span`,{"data-slot":`button-label`,className:yKe,children:t}):t}function DKe(e){return G.Children.toArray(e).flatMap(e=>G.isValidElement(e)&&e.type===G.Fragment?DKe(e.props.children):[e])}function OKe(e){let t=DKe(e);return t.length>0&&t.every(e=>G.isValidElement(e))}function Bx(e){return e?.startsWith(`icon-`)??!1}var X=G.forwardRef(({className:e,render:t,as:n,href:r,to:i,target:a,prefetch:o,size:s,variant:l=`default`,disabled:u,children:d,icon:f,iconEnd:p,tooltip:m,tooltipPosition:h,"aria-label":g,type:_,...v},y)=>{let b=l!==`link`&&Bx(s),x=s??`md`,S=l??`default`,C=SKe(S,x),w=g??((b||OKe(d))&&typeof m==`string`?m:void 0),T=b?(0,K.jsx)(Dx,{size:Rx[x],children:d}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(zx,{slot:`button-icon`,size:C,children:f}),(0,K.jsx)(EKe,{variant:S,children:d}),(0,K.jsx)(zx,{slot:`button-icon-end`,size:C,children:p})]}),E={disabled:u,type:_,"aria-label":w,"data-variant":l,"data-shape":b?`icon`:void 0,className:c(Lx({variant:l,size:x}),e),...v},D=t?void 0:n,O={...r===void 0?null:{href:r},...i===void 0?null:{to:i},...a===void 0?null:{target:a},...o===void 0?null:{prefetch:o}},k=S===`link`,A=r??i,j={...A===void 0?null:{href:A},...a===void 0?null:{target:a}},M=G.isValidElement(t)&&bKe(t)?t:k?G.createElement(`a`,j):void 0,N=M?.props,P=M?.type!==`a`&&N?.href!==void 0?``:void 0,F=N?.to===void 0?void 0:``,I=u?{...k?null:{href:P},...k?null:{to:F},"aria-disabled":!0,onClick:xKe,onAuxClick:xKe,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&xKe(e)}}:void 0,L=D?(0,K.jsx)(D,{ref:y,...O,...E,children:T}):M?G.cloneElement(M,{ref:y,...E,disabled:void 0,type:void 0,...I,className:c(E.className,M.props.className),children:T}):(0,K.jsx)(gKe,{ref:y,render:t,...E,children:T});return m?(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{asChild:!0,children:L}),(0,K.jsx)(Tx,{side:h,children:m})]}):L});X.displayName=`Button`;var kKe={default:`h-6 min-w-6 rounded-md px-1.5 text-caption`,sm:`h-5 min-w-5 rounded-md px-1 text-meta`,xs:`h-4 min-w-4 rounded px-1 text-meta leading-none`},Vx=({children:e,size:t=`default`,className:n})=>(0,K.jsx)(`kbd`,{className:c(`inline-flex items-center justify-center bg-card font-mono text-foreground shadow-raised`,kKe[t],u.transform,`active:scale-95 active:shadow-none`,n),children:(0,K.jsx)(`span`,{className:`[text-box:trim-both_cap_alphabetic]`,children:e})}),Hx=U(`IconPlusMedium`,()=>(0,K.jsx)(`path`,{d:`M12 5.5V12M12 12V18.5M12 12H5.5M12 12H18.5`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`})),Ux=(e,t={})=>{let{enabled:n=!0,target:r}=t,i=nn(),a=rn(),o=(0,G.useRef)({depth:a,bindings:e,shouldHandle:t.shouldHandle,insideFields:t.insideFields,repeat:t.repeat});o.current.bindings=e,o.current.shouldHandle=t.shouldHandle,o.current.insideFields=t.insideFields,o.current.repeat=t.repeat,o.current.depth=a;let s=!r&&i.status===`ready`?i.dispatcher:void 0;(0,G.useEffect)(()=>{if(!n)return;if(s)return s.register(o.current);let e=r?r.current??null:window;if(!e)return;let t=Zt(),i=t.register(o.current),a=e=>{e instanceof KeyboardEvent&&t.handleKeydown(e)};return e.addEventListener(`keydown`,a),()=>{e.removeEventListener(`keydown`,a),i(),t.reset()}},[n,r,s])},AKe=({count:e,containerRef:t,pageSize:n=10,initialIndex:r=0,onActivate:i,onNavigate:a,global:o=!1})=>{let[s,c]=(0,G.useState)(r),l=t=>Math.min(Math.max(t,0),Math.max(e-1,0)),u=e=>{let n=l(e);c(n),a?.(n);let r=t.current?.querySelector(`[data-row-index="${n}"]`);r&&(r.focus(),r.scrollIntoView?.({block:`nearest`}))},d=[[Rt(`mod+Home`),()=>u(0)],[Rt(`mod+End`),()=>u(e-1)],[Rt(`ArrowUp`),()=>u(s-1)],[Rt(`ArrowDown`),()=>u(s+1)],[Rt(`PageUp`),()=>u(s-n)],[Rt(`PageDown`),()=>u(s+n)],[Rt(`Home`),()=>u(0)],[Rt(`End`),()=>u(e-1)]],f=e=>{for(let[t,n]of d)if(Ut(e.nativeEvent,t)){e.preventDefault(),n();return}},p=()=>t.current?.contains(document.activeElement)??!1,m=e=>u(p()?s+e:s);return Ux({ArrowUp:()=>m(-1),ArrowDown:()=>m(1),PageUp:()=>u(s-n),PageDown:()=>u(s+n)},{enabled:o,shouldHandle:t=>!t.defaultPrevented&&e>0&&!Gt(t.target)}),(0,G.useEffect)(()=>{s>=e&&c(Math.max(e-1,0))},[s,e]),{activeIndex:s,setActiveIndex:c,activate:e=>i?.(e),getRowProps:e=>({tabIndex:e===s?0:-1,"data-row-index":e,onFocus:()=>c(e),onKeyDown:f}),getContainerProps:()=>({})}},Wx=(...e)=>t=>{let n=e.map(e=>{if(typeof e==`function`)return e(t);e&&(e.current=t)});return()=>{e.forEach((e,t)=>{let r=n[t];typeof r==`function`?r():typeof e==`function`?e(null):e&&(e.current=null)})}},Gx=G.forwardRef(({tooltip:e,shortcutEnabled:t=!0,disabled:n,children:r,...i},a)=>{let o=(0,G.useRef)(null);return Ux({c:()=>o.current?.click()},{enabled:t&&!n}),(0,K.jsx)(X,{ref:Wx(o,a),icon:(0,K.jsx)(Hx,{}),disabled:n,tooltip:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[e,(0,K.jsx)(Vx,{size:`xs`,children:`C`})]}),...i,children:r})});Gx.displayName=`CreateButton`;var Kx=U(`IconCircleBanSign`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M21 12C21 16.9706 16.9706 21 12 21C9.51472 21 7.26472 19.9926 5.63604 18.364C4.00736 16.7353 3 14.4853 3 12C3 7.02944 7.02944 3 12 3C14.4853 3 16.7353 4.00736 18.364 5.63604C19.9926 7.26472 21 9.51472 21 12Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`square`}),(0,K.jsx)(`path`,{d:`M18 6L6 18`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`square`})]})),qx=U(`IconCircleX`,()=>(0,K.jsx)(`path`,{d:`M15 9L9 15M15 15L9 9M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})),jKe={default:(0,K.jsx)(Kx,{}),error:(0,K.jsx)(qx,{})},MKe={default:`text-muted-foreground`,error:`text-destructive-foreground`};function Jx({tone:e=`default`,iconSlot:t=jKe[e],titleSlot:n,descriptionSlot:r,actionSlot:i,className:a,as:o=`h3`,variant:s=`inline`}){let l=(0,K.jsxs)(`div`,{"data-tone":e,className:c(`group/empty-state flex max-w-full flex-col items-center justify-center px-4 py-6 text-center`,`transition-opacity duration-normal ease-out-custom`,a),children:[t&&(0,K.jsx)(`div`,{className:c(`mb-3 max-w-full [&>svg]:size-icon-lg`,MKe[e]),children:t}),(0,K.jsx)(o,{className:`text-subheading text-foreground`,children:n}),r&&(0,K.jsx)(T,{variant:`caption`,tone:`muted`,className:`mt-1.5 max-w-md wrap-anywhere`,children:r}),i&&(0,K.jsx)(`div`,{className:`mt-4 max-w-full`,children:i})]});return s===`fill`?(0,K.jsx)(`div`,{"data-slot":`empty-state-fill`,className:`flex h-full items-center-safe justify-center-safe`,children:l}):l}var NKe={sm:`w-6`,md:`w-8`,lg:`w-10`},PKe={sm:2.2,md:2.5,lg:2.9},FKe={sm:4.3,md:4.4,lg:4.498};function IKe({className:e,size:t=`md`,"aria-label":n=`Loading`}){let r=`brand-loader-${(0,G.useId)().replace(/[^a-zA-Z0-9_-]/g,``)}`,i=FKe[t];return(0,K.jsx)(`div`,{role:`status`,"aria-label":n,className:c(`brand-loader inline-block text-foreground`,NKe[t],e),style:{"--brand-loader-stroke":PKe[t]},children:(0,K.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 34 21`,"aria-hidden":`true`,children:[(0,K.jsx)(`defs`,{children:(0,K.jsxs)(`filter`,{id:r,x:`-5%`,y:`-5%`,width:`110%`,height:`110%`,children:[(0,K.jsx)(`feGaussianBlur`,{in:`SourceGraphic`,stdDeviation:`0.9`}),(0,K.jsx)(`feColorMatrix`,{values:`1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 11 -4.3`})]})}),(0,K.jsxs)(`g`,{filter:`url(#${r})`,children:[(0,K.jsx)(`line`,{className:`brand-loader-ln23`,x1:`10.387`,y1:`4.498`,x2:`16.899`,y2:`16.192`}),(0,K.jsx)(`line`,{className:`brand-loader-ln34`,x1:`16.899`,y1:`16.192`,x2:`22.815`,y2:`4.56`}),(0,K.jsx)(`line`,{className:`brand-loader-ln45`,x1:`22.815`,y1:`4.56`,x2:`28.57`,y2:`16.192`}),(0,K.jsx)(`circle`,{className:`brand-loader-b1`,cx:`4.498`,cy:`16.192`,r:i}),(0,K.jsx)(`circle`,{className:`brand-loader-b2`,cx:`10.387`,cy:`4.498`,r:i}),(0,K.jsx)(`circle`,{className:`brand-loader-b3`,cx:`16.899`,cy:`16.192`,r:i}),(0,K.jsx)(`circle`,{className:`brand-loader-b4`,cx:`22.815`,cy:`4.56`,r:i}),(0,K.jsx)(`circle`,{className:`brand-loader-b5`,cx:`28.57`,cy:`16.192`,r:i})]})]})})}var Yx=U(`IconCircleInfo`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M11 11H12V16M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M12 7.25C11.5858 7.25 11.25 7.58579 11.25 8C11.25 8.41421 11.5858 8.75 12 8.75C12.4142 8.75 12.75 8.41421 12.75 8C12.75 7.58579 12.4142 7.25 12 7.25Z`,fill:`currentColor`,stroke:`currentColor`,strokeWidth:`0.5`})]})),Xx=U(`IconExclamationCircle`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`circle`,{cx:`12`,cy:`12`,r:`9`,stroke:`currentColor`,strokeWidth:`2`}),(0,K.jsx)(`path`,{d:`M12 8V12.5`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`}),(0,K.jsx)(`circle`,{cx:`12`,cy:`15.7996`,r:`1.2`,fill:`currentColor`})]})),Zx=U(`IconExclamationTriangle`,()=>(0,K.jsx)(`path`,{d:`M12 9.01917V12.0134M12 15H12.01M10.2765 3.99036L3.27481 15.998C2.49885 17.3288 3.45836 19 4.99836 19H19.0016C20.5416 19 21.5011 17.3288 20.7252 15.998L13.7235 3.99035C12.9536 2.66988 11.0464 2.66988 10.2765 3.99036ZM12.25 15C12.25 15.1381 12.1381 15.25 12 15.25C11.8619 15.25 11.75 15.1381 11.75 15C11.75 14.8619 11.8619 14.75 12 14.75C12.1381 14.75 12.25 14.8619 12.25 15Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`})),LKe=U(`IconLightBulbSimple`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M12 3C8.13401 3 5 6.13401 5 10C5 12.5463 6.35958 14.7751 8.39241 16C8.75337 16.2175 9 16.5949 9 17.0163V19C9 20.6569 10.3431 22 12 22C13.6569 22 15 20.6569 15 19V17.0163C15 16.5949 15.2466 16.2175 15.6076 16C17.6404 14.7751 19 12.5463 19 10C19 6.13401 15.866 3 12 3Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M15 18H9`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`square`,strokeLinejoin:`round`})]}));function RKe(e){if(!e||typeof document>`u`)return;let t=document.head||document.getElementsByTagName(`head`)[0],n=document.createElement(`style`);n.type=`text/css`,t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}var zKe=e=>{switch(e){case`success`:return HKe;case`info`:return WKe;case`warning`:return UKe;case`error`:return GKe;default:return null}},BKe=Array(12).fill(0),VKe=({visible:e,className:t})=>G.createElement(`div`,{className:[`sonner-loading-wrapper`,t].filter(Boolean).join(` `),"data-visible":e},G.createElement(`div`,{className:`sonner-spinner`},BKe.map((e,t)=>G.createElement(`div`,{className:`sonner-loading-bar`,key:`spinner-bar-${t}`})))),HKe=G.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},G.createElement(`path`,{fillRule:`evenodd`,d:`M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z`,clipRule:`evenodd`})),UKe=G.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 24 24`,fill:`currentColor`,height:`20`,width:`20`},G.createElement(`path`,{fillRule:`evenodd`,d:`M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z`,clipRule:`evenodd`})),WKe=G.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},G.createElement(`path`,{fillRule:`evenodd`,d:`M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z`,clipRule:`evenodd`})),GKe=G.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},G.createElement(`path`,{fillRule:`evenodd`,d:`M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z`,clipRule:`evenodd`})),KKe=G.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`},G.createElement(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),G.createElement(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})),qKe=()=>{let[e,t]=G.useState(document.hidden);return G.useEffect(()=>{let e=()=>{t(document.hidden)};return document.addEventListener(`visibilitychange`,e),()=>window.removeEventListener(`visibilitychange`,e)},[]),e},JKe=1,Qx=new class{constructor(){this.subscribe=e=>(this.subscribers.push(e),()=>{let t=this.subscribers.indexOf(e);this.subscribers.splice(t,1)}),this.publish=e=>{this.subscribers.forEach(t=>t(e))},this.addToast=e=>{this.publish(e),this.toasts=[...this.toasts,e]},this.create=e=>{let{message:t,...n}=e,r=typeof e?.id==`number`||e.id?.length>0?e.id:JKe++,i=this.toasts.find(e=>e.id===r),a=e.dismissible===void 0||e.dismissible;return this.dismissedToasts.has(r)&&this.dismissedToasts.delete(r),i?this.toasts=this.toasts.map(n=>n.id===r?(this.publish({...n,...e,id:r,title:t}),{...n,...e,id:r,dismissible:a,title:t}):n):this.addToast({title:t,...n,dismissible:a,id:r}),r},this.dismiss=e=>(e?(this.dismissedToasts.add(e),requestAnimationFrame(()=>this.subscribers.forEach(t=>t({id:e,dismiss:!0})))):this.toasts.forEach(e=>{this.subscribers.forEach(t=>t({id:e.id,dismiss:!0}))}),e),this.message=(e,t)=>this.create({...t,message:e}),this.error=(e,t)=>this.create({...t,message:e,type:`error`}),this.success=(e,t)=>this.create({...t,type:`success`,message:e}),this.info=(e,t)=>this.create({...t,type:`info`,message:e}),this.warning=(e,t)=>this.create({...t,type:`warning`,message:e}),this.loading=(e,t)=>this.create({...t,type:`loading`,message:e}),this.promise=(e,t)=>{if(!t)return;let n;t.loading!==void 0&&(n=this.create({...t,promise:e,type:`loading`,message:t.loading,description:typeof t.description==`function`?void 0:t.description}));let r=Promise.resolve(e instanceof Function?e():e),i=n!==void 0,a,o=r.then(async e=>{if(a=[`resolve`,e],G.isValidElement(e))i=!1,this.create({id:n,type:`default`,message:e});else if(XKe(e)&&!e.ok){i=!1;let r=typeof t.error==`function`?await t.error(`HTTP error! status: ${e.status}`):t.error,a=typeof t.description==`function`?await t.description(`HTTP error! status: ${e.status}`):t.description,o=typeof r==`object`&&!G.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}else if(e instanceof Error){i=!1;let r=typeof t.error==`function`?await t.error(e):t.error,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!G.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}else if(t.success!==void 0){i=!1;let r=typeof t.success==`function`?await t.success(e):t.success,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!G.isValidElement(r)?r:{message:r};this.create({id:n,type:`success`,description:a,...o})}}).catch(async e=>{if(a=[`reject`,e],t.error!==void 0){i=!1;let r=typeof t.error==`function`?await t.error(e):t.error,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!G.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}}).finally(()=>{i&&(this.dismiss(n),n=void 0),t.finally==null||t.finally.call(t)}),s=()=>new Promise((e,t)=>o.then(()=>a[0]===`reject`?t(a[1]):e(a[1])).catch(t));return typeof n!=`string`&&typeof n!=`number`?{unwrap:s}:Object.assign(n,{unwrap:s})},this.custom=(e,t)=>{let n=t?.id||JKe++;return this.create({jsx:e(n),id:n,...t}),n},this.getActiveToasts=()=>this.toasts.filter(e=>!this.dismissedToasts.has(e.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},YKe=(e,t)=>{let n=t?.id||JKe++;return Qx.addToast({title:e,...t,id:n}),n},XKe=e=>e&&typeof e==`object`&&`ok`in e&&typeof e.ok==`boolean`&&`status`in e&&typeof e.status==`number`,$x=Object.assign(YKe,{success:Qx.success,info:Qx.info,warning:Qx.warning,error:Qx.error,custom:Qx.custom,message:Qx.message,promise:Qx.promise,dismiss:Qx.dismiss,loading:Qx.loading},{getHistory:()=>Qx.toasts,getToasts:()=>Qx.getActiveToasts()});RKe(`[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}`);function eS(e){return e.label!==void 0}var ZKe=3,QKe=`24px`,$Ke=`16px`,eqe=4e3,tqe=356,nqe=14,rqe=45,iqe=200;function tS(...e){return e.filter(Boolean).join(` `)}function aqe(e){let[t,n]=e.split(`-`),r=[];return t&&r.push(t),n&&r.push(n),r}var oqe=e=>{let{invert:t,toast:n,unstyled:r,interacting:i,setHeights:a,visibleToasts:o,heights:s,index:c,toasts:l,expanded:u,removeToast:d,defaultRichColors:f,closeButton:p,style:m,cancelButtonStyle:h,actionButtonStyle:g,className:_=``,descriptionClassName:v=``,duration:y,position:b,gap:x,expandByDefault:S,classNames:C,icons:w,closeButtonAriaLabel:T=`Close toast`}=e,[E,D]=G.useState(null),[O,k]=G.useState(null),[A,j]=G.useState(!1),[M,N]=G.useState(!1),[P,F]=G.useState(!1),[I,L]=G.useState(!1),[R,z]=G.useState(!1),[B,V]=G.useState(0),[H,ee]=G.useState(0),te=G.useRef(n.duration||y||eqe),U=G.useRef(null),W=G.useRef(null),ne=c===0,re=c+1<=o,ie=n.type,ae=n.dismissible!==!1,oe=n.className||``,se=n.descriptionClassName||``,ce=G.useMemo(()=>s.findIndex(e=>e.toastId===n.id)||0,[s,n.id]),le=G.useMemo(()=>n.closeButton??p,[n.closeButton,p]),ue=G.useMemo(()=>n.duration||y||eqe,[n.duration,y]),de=G.useRef(0),fe=G.useRef(0),pe=G.useRef(0),me=G.useRef(null),[he,ge]=b.split(`-`),_e=G.useMemo(()=>s.reduce((e,t,n)=>n>=ce?e:e+t.height,0),[s,ce]),ve=qKe(),ye=n.invert||t,be=ie===`loading`;fe.current=G.useMemo(()=>ce*x+_e,[ce,_e]),G.useEffect(()=>{te.current=ue},[ue]),G.useEffect(()=>{j(!0)},[]),G.useEffect(()=>{let e=W.current;if(e){let t=e.getBoundingClientRect().height;return ee(t),a(e=>[{toastId:n.id,height:t,position:n.position},...e]),()=>a(e=>e.filter(e=>e.toastId!==n.id))}},[a,n.id]),G.useLayoutEffect(()=>{if(!A)return;let e=W.current,t=e.style.height;e.style.height=`auto`;let r=e.getBoundingClientRect().height;e.style.height=t,ee(r),a(e=>e.find(e=>e.toastId===n.id)?e.map(e=>e.toastId===n.id?{...e,height:r}:e):[{toastId:n.id,height:r,position:n.position},...e])},[A,n.title,n.description,a,n.id,n.jsx,n.action,n.cancel]);let xe=G.useCallback(()=>{N(!0),V(fe.current),a(e=>e.filter(e=>e.toastId!==n.id)),setTimeout(()=>{d(n)},iqe)},[n,d,a,fe]);G.useEffect(()=>{if(n.promise&&ie===`loading`||n.duration===1/0||n.type===`loading`)return;let e;return u||i||ve?(()=>{if(pe.current<de.current){let e=new Date().getTime()-de.current;te.current-=e}pe.current=new Date().getTime()})():te.current!==1/0&&(de.current=new Date().getTime(),e=setTimeout(()=>{n.onAutoClose==null||n.onAutoClose.call(n,n),xe()},te.current)),()=>clearTimeout(e)},[u,i,n,ie,ve,xe]),G.useEffect(()=>{n.delete&&(xe(),n.onDismiss==null||n.onDismiss.call(n,n))},[xe,n.delete]);function Se(){return w?.loading?G.createElement(`div`,{className:tS(C?.loader,n?.classNames?.loader,`sonner-loader`),"data-visible":ie===`loading`},w.loading):G.createElement(VKe,{className:tS(C?.loader,n?.classNames?.loader),visible:ie===`loading`})}let Ce=n.icon||w?.[ie]||zKe(ie);return G.createElement(`li`,{tabIndex:0,ref:W,className:tS(_,oe,C?.toast,n?.classNames?.toast,C?.default,C?.[ie],n?.classNames?.[ie]),"data-sonner-toast":``,"data-rich-colors":n.richColors??f,"data-styled":!(n.jsx||n.unstyled||r),"data-mounted":A,"data-promise":!!n.promise,"data-swiped":R,"data-removed":M,"data-visible":re,"data-y-position":he,"data-x-position":ge,"data-index":c,"data-front":ne,"data-swiping":P,"data-dismissible":ae,"data-type":ie,"data-invert":ye,"data-swipe-out":I,"data-swipe-direction":O,"data-expanded":!!(u||S&&A),"data-testid":n.testId,style:{"--index":c,"--toasts-before":c,"--z-index":l.length-c,"--offset":`${M?B:fe.current}px`,"--initial-height":S?`auto`:`${H}px`,...m,...n.style},onDragEnd:()=>{F(!1),D(null),me.current=null},onPointerDown:e=>{e.button!==2&&!be&&ae&&(U.current=new Date,V(fe.current),e.target.setPointerCapture(e.pointerId),e.target.tagName!==`BUTTON`&&(F(!0),me.current={x:e.clientX,y:e.clientY}))},onPointerUp:()=>{if(I||!ae)return;me.current=null;let e=Number(W.current?.style.getPropertyValue(`--swipe-amount-x`).replace(`px`,``)||0),t=Number(W.current?.style.getPropertyValue(`--swipe-amount-y`).replace(`px`,``)||0),r=new Date().getTime()-U.current?.getTime(),i=E===`x`?e:t,a=Math.abs(i)/r;if(Math.abs(i)>=rqe||a>.11)V(fe.current),n.onDismiss==null||n.onDismiss.call(n,n),k(E===`x`?e>0?`right`:`left`:t>0?`down`:`up`),xe(),L(!0);else{var o,s;(o=W.current)==null||o.style.setProperty(`--swipe-amount-x`,`0px`),(s=W.current)==null||s.style.setProperty(`--swipe-amount-y`,`0px`),z(!1),F(!1),D(null)}},onPointerMove:t=>{var n,r;if(!me.current||!ae||window.getSelection()?.toString().length>0)return;let i=t.clientY-me.current.y,a=t.clientX-me.current.x,o=e.swipeDirections??aqe(b);!E&&(Math.abs(a)>1||Math.abs(i)>1)&&D(Math.abs(a)>Math.abs(i)?`x`:`y`);let s={x:0,y:0},c=e=>1/(1.5+Math.abs(e)/20);if(E===`y`){if(o.includes(`top`)||o.includes(`bottom`)){if(o.includes(`top`)&&i<0||o.includes(`bottom`)&&i>0)s.y=i;else{let e=i*c(i);s.y=Math.abs(e)<Math.abs(i)?e:i}}}else if(E===`x`&&(o.includes(`left`)||o.includes(`right`))){if(o.includes(`left`)&&a<0||o.includes(`right`)&&a>0)s.x=a;else{let e=a*c(a);s.x=Math.abs(e)<Math.abs(a)?e:a}}(Math.abs(s.x)>0||Math.abs(s.y)>0)&&z(!0),(n=W.current)==null||n.style.setProperty(`--swipe-amount-x`,`${s.x}px`),(r=W.current)==null||r.style.setProperty(`--swipe-amount-y`,`${s.y}px`)}},le&&!n.jsx&&ie!==`loading`?G.createElement(`button`,{"aria-label":T,"data-disabled":be,"data-close-button":!0,onClick:be||!ae?()=>{}:()=>{xe(),n.onDismiss==null||n.onDismiss.call(n,n)},className:tS(C?.closeButton,n?.classNames?.closeButton)},w?.close??KKe):null,(ie||n.icon||n.promise)&&n.icon!==null&&(w?.[ie]!==null||n.icon)?G.createElement(`div`,{"data-icon":``,className:tS(C?.icon,n?.classNames?.icon)},n.promise||n.type===`loading`&&!n.icon?n.icon||Se():null,n.type===`loading`?null:Ce):null,G.createElement(`div`,{"data-content":``,className:tS(C?.content,n?.classNames?.content)},G.createElement(`div`,{"data-title":``,className:tS(C?.title,n?.classNames?.title)},n.jsx?n.jsx:typeof n.title==`function`?n.title():n.title),n.description?G.createElement(`div`,{"data-description":``,className:tS(v,se,C?.description,n?.classNames?.description)},typeof n.description==`function`?n.description():n.description):null),G.isValidElement(n.cancel)?n.cancel:n.cancel&&eS(n.cancel)?G.createElement(`button`,{"data-button":!0,"data-cancel":!0,style:n.cancelButtonStyle||h,onClick:e=>{eS(n.cancel)&&ae&&(n.cancel.onClick==null||n.cancel.onClick.call(n.cancel,e),xe())},className:tS(C?.cancelButton,n?.classNames?.cancelButton)},n.cancel.label):null,G.isValidElement(n.action)?n.action:n.action&&eS(n.action)?G.createElement(`button`,{"data-button":!0,"data-action":!0,style:n.actionButtonStyle||g,onClick:e=>{eS(n.action)&&(n.action.onClick==null||n.action.onClick.call(n.action,e),e.defaultPrevented||xe())},className:tS(C?.actionButton,n?.classNames?.actionButton)},n.action.label):null)};function sqe(){if(typeof window>`u`||typeof document>`u`)return`ltr`;let e=document.documentElement.getAttribute(`dir`);return e===`auto`||!e?window.getComputedStyle(document.documentElement).direction:e}function cqe(e,t){let n={};return[e,t].forEach((e,t)=>{let r=t===1,i=r?`--mobile-offset`:`--offset`,a=r?$Ke:QKe;function o(e){[`top`,`right`,`bottom`,`left`].forEach(t=>{n[`${i}-${t}`]=typeof e==`number`?`${e}px`:e})}typeof e==`number`||typeof e==`string`?o(e):typeof e==`object`?[`top`,`right`,`bottom`,`left`].forEach(t=>{e[t]===void 0?n[`${i}-${t}`]=a:n[`${i}-${t}`]=typeof e[t]==`number`?`${e[t]}px`:e[t]}):o(a)}),n}var lqe=G.forwardRef(function(e,t){let{id:n,invert:r,position:i=`bottom-right`,hotkey:a=[`altKey`,`KeyT`],expand:o,closeButton:s,className:c,offset:l,mobileOffset:u,theme:d=`light`,richColors:f,duration:p,style:m,visibleToasts:h=ZKe,toastOptions:g,dir:_=sqe(),gap:v=nqe,icons:y,containerAriaLabel:b=`Notifications`}=e,[x,S]=G.useState([]),C=G.useMemo(()=>n?x.filter(e=>e.toasterId===n):x.filter(e=>!e.toasterId),[x,n]),w=G.useMemo(()=>Array.from(new Set([i].concat(C.filter(e=>e.position).map(e=>e.position)))),[C,i]),[T,E]=G.useState([]),[D,O]=G.useState(!1),[k,A]=G.useState(!1),[j,M]=G.useState(d===`system`?typeof window<`u`&&window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`:d),N=G.useRef(null),P=a.join(`+`).replace(/Key/g,``).replace(/Digit/g,``),F=G.useRef(null),I=G.useRef(!1),L=G.useCallback(e=>{S(t=>(t.find(t=>t.id===e.id)?.delete||Qx.dismiss(e.id),t.filter(({id:t})=>t!==e.id)))},[]);return G.useEffect(()=>Qx.subscribe(e=>{e.dismiss?requestAnimationFrame(()=>{S(t=>t.map(t=>t.id===e.id?{...t,delete:!0}:t))}):setTimeout(()=>{Pt.flushSync(()=>{S(t=>{let n=t.findIndex(t=>t.id===e.id);return n===-1?[e,...t]:[...t.slice(0,n),{...t[n],...e},...t.slice(n+1)]})})})}),[x]),G.useEffect(()=>{if(d!==`system`){M(d);return}if(d===`system`&&(window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?M(`dark`):M(`light`)),typeof window>`u`)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`);try{e.addEventListener(`change`,({matches:e})=>{M(e?`dark`:`light`)})}catch{e.addListener(({matches:e})=>{try{M(e?`dark`:`light`)}catch(e){console.error(e)}})}},[d]),G.useEffect(()=>{x.length<=1&&O(!1)},[x]),G.useEffect(()=>{let e=e=>{if(a.every(t=>e[t]||e.code===t)){var t;O(!0),(t=N.current)==null||t.focus()}e.code===`Escape`&&(document.activeElement===N.current||N.current?.contains(document.activeElement))&&O(!1)};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[a]),G.useEffect(()=>{if(N.current)return()=>{F.current&&(F.current.focus({preventScroll:!0}),F.current=null,I.current=!1)}},[N.current]),G.createElement(`section`,{ref:t,"aria-label":`${b} ${P}`,tabIndex:-1,"aria-live":`polite`,"aria-relevant":`additions text`,"aria-atomic":`false`,suppressHydrationWarning:!0},w.map((t,n)=>{let[i,a]=t.split(`-`);return C.length?G.createElement(`ol`,{key:t,dir:_===`auto`?sqe():_,tabIndex:-1,ref:N,className:c,"data-sonner-toaster":!0,"data-sonner-theme":j,"data-y-position":i,"data-x-position":a,style:{"--front-toast-height":`${T[0]?.height||0}px`,"--width":`${tqe}px`,"--gap":`${v}px`,...m,...cqe(l,u)},onBlur:e=>{I.current&&!e.currentTarget.contains(e.relatedTarget)&&(I.current=!1,F.current&&=(F.current.focus({preventScroll:!0}),null))},onFocus:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||I.current||(I.current=!0,F.current=e.relatedTarget)},onMouseEnter:()=>O(!0),onMouseMove:()=>O(!0),onMouseLeave:()=>{k||O(!1)},onDragEnd:()=>O(!1),onPointerDown:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||A(!0)},onPointerUp:()=>A(!1)},C.filter(e=>!e.position&&n===0||e.position===t).map((n,i)=>G.createElement(oqe,{key:n.id,icons:y,index:i,toast:n,defaultRichColors:f,duration:g?.duration??p,className:g?.className,descriptionClassName:g?.descriptionClassName,invert:r,visibleToasts:h,closeButton:g?.closeButton??s,interacting:k,position:t,style:g?.style,unstyled:g?.unstyled,classNames:g?.classNames,cancelButtonStyle:g?.cancelButtonStyle,actionButtonStyle:g?.actionButtonStyle,closeButtonAriaLabel:g?.closeButtonAriaLabel,removeToast:L,toasts:C.filter(e=>e.position==n.position),heights:T.filter(e=>e.position==n.position),setHeights:E,expandByDefault:o,gap:v,expanded:D,swipeDirections:e.swipeDirections}))):null}))}),nS=(e,t)=>Array.isArray(e)?e.map(t):t(e);function uqe(e){return!e||typeof e!=`object`||!(`label`in e)?e:{...e,label:(0,K.jsx)(EKe,{variant:`link`,children:e.label})}}function rS(e){let t={...e};return e.action!==void 0&&(t.action=uqe(e.action)),e.cancel!==void 0&&(t.cancel=uqe(e.cancel)),t}var iS=(e,t={})=>{if(Array.isArray(e))return e.map(e=>$x(e,rS(t)));if((0,G.isValidElement)(e)||typeof e==`string`)return $x(e,rS(t));throw Error(`Invalid message type`)};iS.success=(e,t={})=>nS(e,e=>$x.success(e,rS(t))),iS.error=(e,t={})=>nS(e,e=>$x.error(e,rS(t))),iS.warning=(e,t={})=>nS(e,e=>$x.warning(e,rS(t))),iS.info=(e,t={})=>nS(e,e=>$x.info(e,rS(t))),iS.custom=(e,t={})=>$x(e,rS(t)),iS.dismiss=e=>$x.dismiss(e),iS.promise=({myPromise:e,loadingMessage:t,successMessage:n,errorMessage:r,onSuccess:i,onError:a,options:o={}})=>$x.promise(e,{loading:t??`Loading...`,success:e=>(i?.(e),n),error:e=>(a?.(e),r||(e instanceof Error?e.message:`Error...`)),...rS(o)});function dqe(e){let t=getComputedStyle(e),n=Array.from(e.children).reduce((e,t)=>{let n=getComputedStyle(t);return e+Number.parseFloat(n.height)+Number.parseFloat(n.marginTop)+Number.parseFloat(n.marginBottom)},0)+Number.parseFloat(t.rowGap)*Math.max(0,e.childElementCount-1)+Number.parseFloat(t.paddingTop)+Number.parseFloat(t.paddingBottom);return Math.round(n)>e.clientHeight}function fqe(e){let t=Array.from(e.querySelectorAll(`[data-content]`),e=>({content:e,overflows:dqe(e)}));return()=>{for(let{content:e,overflows:n}of t)n&&e.tabIndex!==0?e.tabIndex=0:!n&&e.hasAttribute(`tabindex`)&&e.removeAttribute(`tabindex`)}}var pqe=64;function mqe(e){let t=getComputedStyle(e);if(e.style.height&&e.style.height!==`auto`)return Number.parseFloat(t.height);let n=e.getBoundingClientRect(),r=t.transform===`none`?1:new DOMMatrixReadOnly(t.transform).d,i=Array.from(e.children).reduce((e,t)=>{let i=getComputedStyle(t);if(i.position===`absolute`||i.position===`fixed`||i.display===`none`)return e;let a=i.marginBottom===`auto`?0:Number.parseFloat(i.marginBottom),o=t.getBoundingClientRect(),s=r>0?(o.bottom-n.top)/r:r<0?(n.bottom-o.top)/-r:t instanceof HTMLElement?t.offsetTop+t.offsetHeight:0;return Math.max(e,s+a)},0),a=Number.parseFloat(t.minHeight),o=Number.parseFloat(t.maxHeight);return Math.max(Number.isFinite(a)?a:0,Math.min(Number.isFinite(o)?o:1/0,i+Number.parseFloat(t.paddingBottom)+Number.parseFloat(t.borderBottomWidth)))}function hqe(e,t,n,r){return e.dataset.promise===`true`&&e.dataset.front===`true`&&(e.dataset.type===`success`||e.dataset.type===`error`)&&(t.type===`loading`||n)&&r>.5}function gqe(e){let t=e.trim();return Number.parseFloat(t)*(t.endsWith(`ms`)?1:1e3)}function _qe(e,t,n){let r=getComputedStyle(e),i=gqe(r.getPropertyValue(`--duration-normal`)),a=r.getPropertyValue(`--toast-settle-ease`).trim(),o=[e.animate([{translate:`0 ${e.dataset.yPosition===`bottom`?t:0}px`,clipPath:`inset(0 0 ${t}px 0 round ${n})`},{translate:`0 0`,clipPath:`inset(0 round ${n})`}],{duration:i,easing:a})];for(let t of e.querySelectorAll(`[data-description], :scope > [data-content] ~ *`))o.push(t.animate([{opacity:0},{opacity:1}],{duration:i,easing:a}));return o}function vqe(e){let t=new Map;return{measure:n=>{let r=Array.from(n.querySelectorAll(`[data-sonner-toaster]`),e=>{let n=Number.parseFloat(getComputedStyle(e).getPropertyValue(`--gap`)),r=0;return{stack:e,notifications:Array.from(e.querySelectorAll(`:scope > [data-sonner-toast]`)).filter(e=>e.dataset.removed!==`true`&&e.getClientRects().length>0).map(e=>{let i=Math.round(mqe(e)*pqe)/pqe,a=r;r+=i+n;let o=t.get(e),s=getComputedStyle(e),c=s.translate===`none`?0:Number.parseFloat(s.translate.split(` `)[1]??`0`);return{notification:e,height:i,position:a,previous:o,reveal:o?i-o.height+c:0,radius:s.borderRadius}})}});return()=>{for(let{stack:n,notifications:i}of r){n.style.setProperty(`--mastra-front-height`,`${i[0]?.height??0}px`),n.setAttribute(`data-mastra-measured`,``);for(let{notification:n,height:r,position:a,previous:o,reveal:s,radius:c}of i){if(n.style.setProperty(`--mastra-toast-height`,`${r}px`),n.style.setProperty(`--mastra-toast-offset`,`${a}px`),n.setAttribute(`data-mastra-measured`,``),o?.height===r&&o.type===n.dataset.type)continue;let i=o?.animations.some(e=>e.playState===`running`)??!1;for(let e of o?.animations??[])e.cancel();let l=o&&!e.matches&&hqe(n,o,i,s)?_qe(n,s,c):[];t.set(n,{height:r,type:n.dataset.type,animations:l})}}for(let[e,r]of t)if(!(n.contains(e)&&e.dataset.removed!==`true`)){for(let e of r.animations)e.cancel();t.delete(e)}}},cancelAnimations:()=>{for(let e of t.values())for(let t of e.animations)t.cancel()}}}function yqe(e){if(!e||typeof ResizeObserver>`u`)return;let t=matchMedia(`(prefers-reduced-motion: reduce)`),n=vqe(t);t.addEventListener(`change`,n.cancelAnimations);let r=()=>{let t=fqe(e),r=n.measure(e);t(),r()},i=new ResizeObserver(r),a=()=>{i.disconnect();for(let t of e.querySelectorAll(`[data-sonner-toast] > *`))i.observe(t);r()},o=new MutationObserver(a);return o.observe(e,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:[`data-removed`]}),a(),()=>{o.disconnect(),i.disconnect(),t.removeEventListener(`change`,n.cancelAnimations),n.cancelAnimations()}}var bqe={success:(0,K.jsx)(LKe,{"aria-hidden":!0}),error:(0,K.jsx)(Xx,{"aria-hidden":!0}),warning:(0,K.jsx)(Zx,{"aria-hidden":!0}),info:(0,K.jsx)(Yx,{"aria-hidden":!0})},xqe=Lx({variant:`link`}),aS=({className:e,toastOptions:t,icons:n,variant:r=`default`,...i})=>(0,K.jsx)(lqe,{ref:yqe,...i,closeButton:!0,icons:{...bqe,loading:(0,K.jsx)(`span`,{"aria-hidden":!0,className:`flex`,children:(0,K.jsx)(IKe,{size:`sm`,className:c(`toast-promise-loader w-5`,{"toast-promise-success":n?.success===void 0,"toast-promise-error":n?.error===void 0})})}),...n},className:c(`mastra-toaster`,r===`neutral`&&`mastra-toaster-neutral`,e),toastOptions:{duration:5e3,...t,classNames:{actionButton:xqe,cancelButton:xqe,...t?.classNames}}});function oS({children:e,side:t=`top`,align:n,contentClassName:r,...i}){let a=G.useId();return(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{render:(0,K.jsx)(`button`,{type:`button`,...i,"aria-describedby":a,className:c(`flex shrink-0 cursor-help items-center rounded-full text-placeholder/80 hover:text-muted-foreground focus-visible:text-muted-foreground`,A,p)}),children:(0,K.jsx)(Dx,{size:`xs`,children:(0,K.jsx)(Yx,{})})}),(0,K.jsx)(Tx,{id:a,keepMounted:!0,side:t,align:n,className:c(`max-w-64`,r),children:e})]})}var sS=U(`IconArrowLeft`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M10 6L4 12L10 18`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M5 12H20`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),3),cS=U(`IconEyeOpen`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M15 12C15 13.6569 13.6569 15 12 15C10.3431 15 9 13.6569 9 12C9 10.3431 10.3431 9 12 9C13.6569 9 15 10.3431 15 12Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M21.4974 11.0946C16.66 2.96839 7.33998 2.96848 2.50257 11.0947C2.17069 11.6523 2.17069 12.3479 2.50257 12.9054C7.33998 21.0316 16.66 21.0315 21.4974 12.9053C21.8293 12.3477 21.8293 11.6521 21.4974 11.0946Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]})),lS=e=>{let t=Y();return T_({queryKey:[`builder-settings`],queryFn:()=>t.getBuilderSettings(),enabled:e?.enabled??!0})},Sqe={active:!1},uS=()=>{let{data:e}=lS();return e?.modelPolicy??Sqe},Cqe={visibleTools:null,visibleAgents:null,visibleWorkflows:null},wqe=()=>{let{data:e}=lS(),t=e?.picker;return(0,G.useMemo)(()=>t?{visibleTools:t.visibleTools===null?null:new Set(t.visibleTools),visibleAgents:t.visibleAgents===null?null:new Set(t.visibleAgents),visibleWorkflows:t.visibleWorkflows===null?null:new Set(t.visibleWorkflows)}:Cqe,[t])};async function Tqe(e,{roleId:t}){let{baseUrl:n=``,apiPrefix:r,headers:i={}}=e.options||{},a=(r??`/api`).trim(),o=(a===``?``:a.startsWith(`/`)?a:`/${a}`).replace(/\/+$/,``),s=await fetch(`${n}${o}/auth/roles/${encodeURIComponent(t)}/permissions`,{credentials:`include`,headers:{...i,"Content-Type":`application/json`}});if(!s.ok)throw Error(`Failed to fetch role permissions: ${s.status}`);return s.json()}var Eqe=(0,G.createContext)(null);function Dqe({children:e}){let t=Y(),[n,r]=(0,G.useState)(null),[i,a]=(0,G.useState)(null),{mutateAsync:o,reset:s,isPending:c}=D_({mutationFn:async({role:e})=>({role:e,permissions:(await Tqe(t,{roleId:e.id})).permissions}),onSuccess:({role:e,permissions:t})=>{r(e),a(t)}}),l=(0,G.useMemo)(()=>({impersonatedRole:n,impersonatedPermissions:i,isImpersonating:n!==null,startImpersonation:async e=>{await o({role:e})},stopImpersonation:()=>{r(null),a(null),s()},isSwitching:c}),[n,i,c,o,s]);return(0,K.jsx)(Eqe.Provider,{value:l,children:e})}function dS(){return(0,G.useContext)(Eqe)||{impersonatedRole:null,impersonatedPermissions:null,isImpersonating:!1,startImpersonation:async()=>{},stopImpersonation:()=>{},isSwitching:!1}}function Oqe(e,t){if(e===`*`)return!0;let n=e.split(`:`),r=t.split(`:`);if(n.length<2||r.length<2)return e===t;let[i,a,o]=n,[s,c,l]=r;return i===`*`?a===`*`?!0:a===c?o===void 0||o===l:!1:i===s&&(a===`*`||a===c)?o===void 0||o===l:!1}function kqe(e,t){return e.some(e=>Oqe(e,t))}function fS(){let{data:e,isLoading:t}=A_(),{isImpersonating:n,impersonatedPermissions:r,impersonatedRole:i}=dS(),a=e&&k_(e),o=a?e.access:null,s=a?e.capabilities.rbac:!1,c=n&&i?[i.id]:o?.roles??[],l=n&&r?r:o?.permissions??[],u=e=>!s&&!n||kqe(l,e);return{roles:c,permissions:l,isLoading:t,isAuthenticated:!!a,rbacEnabled:s,hasPermission:e=>u(e),hasAllPermissions:e=>!s&&!n||e.every(e=>kqe(l,e)),hasAnyPermission:e=>!s&&!n||e.some(e=>kqe(l,e)),hasRole:e=>!s&&!n||c.includes(e),canEdit:e=>u(`${e}:write`),canDelete:e=>u(`${e}:delete`),canExecute:e=>u(`${e}:execute`)}}function pS(){let{hasAnyPermission:e,hasPermission:t,rbacEnabled:n}=fS(),r=!n||e([`stored-agents:read`,`stored-agents:write`]),i=!n||e([`stored-agents:read`,`stored-agents:write`]),a=!n||t(`stored-agents:write`),o=!n||e([`stored-agents:read`,`stored-agents:write`]),s=!n||t(`stored-skills:read`),c=!n||e([`stored-agents:read`,`stored-skills:read`]),{data:l,isLoading:u,error:d}=lS({enabled:i}),f=l?.enabled===!0,p=l?.features?.agent!==void 0;return{isLoading:i&&u,error:i?d:null,denialReason:r?d?`error`:!f||!p?`not-configured`:null:`permission-denied`,isBuilderEnabled:f,hasAgentFeature:p,hasRequiredPermissions:r,canAccessAgentBuilder:r&&f&&p,canWrite:a,canExecute:o,canManageSkills:s,canUseFavorites:c,agentFeatures:l?.features?.agent}}var Aqe=[`/swagger-ui`,`/openapi.json`],mS=(0,G.forwardRef)(({children:e,href:t,...n},r)=>t&&Aqe.some(e=>t.startsWith(e))?(0,K.jsx)(`a`,{ref:r,href:t,...n,children:e}):(0,K.jsx)(Lv,{ref:r,to:t??``,...n,children:e})),jqe=({paths:e})=>{let t=Dv(),{data:n,isLoading:r}=A_();if(r)return(0,K.jsx)(`div`,{className:`flex h-screen w-full items-center justify-center`,children:(0,K.jsx)(It,{})});if(n?.enabled&&!k_(n)){let e=`${t.pathname}${t.search}${t.hash}`,n=`/login?redirect=${encodeURIComponent(e)}`;return(0,K.jsx)(Fv,{to:n,replace:!0})}return(0,K.jsx)(Mqe,{paths:e})},Mqe=({paths:e})=>{let t=Ov(),{isLoading:n,denialReason:r,hasAgentFeature:i}=pS();return n?(0,K.jsx)(`div`,{className:`flex h-screen w-full items-center justify-center`,children:(0,K.jsx)(It,{})}):r===`permission-denied`?(0,K.jsx)(Nqe,{}):r===`error`?(0,K.jsx)(`div`,{className:`flex h-screen items-center justify-center`,children:(0,K.jsx)(Jx,{titleSlot:`Error`,descriptionSlot:`Failed to load Agent Builder configuration.`})}):r===`not-configured`?(0,K.jsx)(`div`,{className:`flex h-screen items-center justify-center`,children:(0,K.jsx)(Jx,{titleSlot:`Agent Builder Not Configured`,descriptionSlot:`Agent Builder is not enabled. Contact your administrator to enable this feature.`})}):i?(0,K.jsx)(Sx,{children:(0,K.jsxs)(on,{Link:mS,navigate:t,paths:e,children:[(0,K.jsx)(Iv,{}),(0,K.jsx)(aS,{position:`bottom-right`})]})}):(0,K.jsx)(`div`,{className:`flex h-screen items-center justify-center`,children:(0,K.jsx)(Jx,{titleSlot:`No Features Enabled`,descriptionSlot:`No Agent Builder features are configured.`})})};function Nqe(){let{isImpersonating:e,impersonatedRole:t,stopImpersonation:n}=dS();return(0,K.jsx)(`div`,{className:`flex h-screen items-center justify-center`,children:(0,K.jsxs)(`div`,{className:`flex flex-col items-center gap-4`,children:[(0,K.jsx)(Jx,{titleSlot:`Access Denied`,descriptionSlot:`You don't have permission to access the Agent Builder.`}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(X,{render:(0,K.jsx)(mS,{href:`/agents`}),size:`sm`,icon:(0,K.jsx)(sS,{}),children:`Back to Studio`}),e&&(0,K.jsxs)(X,{variant:`default`,size:`sm`,onClick:n,icon:(0,K.jsx)(cS,{}),children:[`Exit `,t?.name,` preview`]})]})]})})}var hS=[{route:`/agents`,permission:`agents:read`,name:`Agents`},{route:`/workflows`,permission:`workflows:read`,name:`Workflows`},{route:`/metrics`,permission:`observability:read`,name:`Metrics`},{route:`/intelligence`,permission:`observability:read`,name:`Intelligence`},{route:`/traces`,permission:`observability:read`,name:`Traces`},{route:`/spans`,permission:`observability:read`,name:`Spans`},{route:`/threads`,permission:`observability:read`,name:`Threads`},{route:`/logs`,permission:`logs:read`,name:`Logs`},{route:`/scorers`,permission:`scores:read`,name:`Scorers`},{route:`/datasets`,permission:[`datasets:read`],name:`Datasets`},{route:`/knowledge`,permission:`knowledge:read`,name:`Knowledge`},{route:`/experiments`,permission:[`datasets:read`],name:`Experiments`},{route:`/experiments/review-queue`,permission:[`datasets:read`],name:`Review Queue`},{route:`/tools`,permission:`tools:read`,name:`Tools`},{route:`/mcps`,permission:`mcp:read`,name:`MCP Servers`},{route:`/processors`,permission:`processors:read`,name:`Processors`},{route:`/prompts`,permission:`stored-prompt-blocks:read`,name:`Prompts`},{route:`/workspaces`,permission:`workspaces:read`,name:`Workspaces`},{route:`/settings`,permission:`public`,name:`Settings`},{route:`/resources`,permission:`public`,name:`Resources`},{route:`/connections`,permission:`public`,name:`Connections`}];function Pqe(e){return[...new Set(e.flatMap(e=>Array.isArray(e.permission)?e.permission:[e.permission]).filter(e=>e!==`public`))]}var Fqe=Pqe(hS);function gS(e){let t=hS.find(t=>t.route===e);return t?t.permission:hS.find(t=>e.startsWith(t.route+`/`))?.permission}function _S(e,t,n){return!e||e===`public`?!0:Array.isArray(e)?n(e):t(e)}function Iqe(e,t){let n=new Set;for(let{route:r,permission:i}of hS){if(i===`public`)continue;let a=Array.isArray(i)?i.sort().join(`,`):i;if(!n.has(a)&&(n.add(a),_S(i,e,t)))return r}return`/resources`}function Lqe({children:e}){let{pathname:t}=Dv(),{hasPermission:n,hasAnyPermission:r,rbacEnabled:i,isAuthenticated:a,isLoading:o}=fS();if(o)return(0,K.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,K.jsx)(It,{})});if(!i||!a)return(0,K.jsx)(K.Fragment,{children:e});let s=gS(t);if(!s||s===`public`||_S(s,n,r))return(0,K.jsx)(K.Fragment,{children:e});let c=Iqe(n,r);return c===t?(0,K.jsx)(K.Fragment,{children:e}):(0,K.jsx)(Fv,{to:c,replace:!0})}var vS=U(`IconArrowRotateCounterClockwise`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M4.4834 14.6667C5.58163 17.7738 8.54493 20 12.0282 20C16.4465 20 20.0282 16.4183 20.0282 12C20.0282 7.58172 16.4465 4 12.0282 4C8.93224 4 6.99986 5.5 4.99986 8`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M5 4V8H9`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]})),Rqe=e=>{let t=e.trim().replace(/\/+/g,`/`).replace(/\/$/,``);return t?t.startsWith(`/`)?t:`/${t}`:``},zqe=(e,t)=>`${e.replace(/\/+$/,``)}${Rqe(t)}/auth/capabilities`,Bqe=async(e,t,n)=>{try{let r=await fetch(zqe(e,t),{headers:n});if(!r.ok)return{status:`inactive`};let i=await r.json();return{status:typeof i==`object`&&i&&typeof i.enabled==`boolean`?`active`:`inactive`}}catch{return{status:`inactive`}}},Vqe=(e=`http://localhost:4111`,t=`/api`,n)=>T_({queryKey:[`mastra-instance-status`,e,t,n],queryFn:()=>Bqe(e,t,n),retry:!1}),Hqe=(0,G.createContext)({baseUrl:``,headers:{},apiPrefix:void 0,isLoading:!1,setConfig:()=>{}}),yS=()=>(0,G.useContext)(Hqe),bS=`mastra-studio-config`,Uqe=`auth_header`,Wqe=`Authorization`,Gqe=()=>{if(typeof window>`u`)return{};let e=new URL(window.location.href).searchParams.get(Uqe);return e?{[Wqe]:e}:{}},Kqe=()=>{if(typeof window>`u`)return;let e=new URL(window.location.href);e.searchParams.has(Uqe)&&(e.searchParams.delete(Uqe),window.history.replaceState(window.history.state,``,`${e.pathname}${e.search}${e.hash}`))},qqe=e=>{let{[Wqe]:t,...n}=e.headers;return{...e,headers:n}},Jqe=({children:e,endpoint:t=`http://localhost:4111`,defaultApiPrefix:n=`/api`})=>{let[r]=(0,G.useState)(Gqe),i=Object.keys(r).length>0,{data:a,isLoading:o,error:s}=Vqe(t,n,r),[c,l]=(0,G.useState)({baseUrl:``,headers:r,apiPrefix:void 0,isLoading:!0});(0,G.useEffect)(()=>{Kqe()},[]),(0,G.useLayoutEffect)(()=>{if(s&&!o)return l({baseUrl:``,headers:r,apiPrefix:void 0,isLoading:!1});if(!a?.status)return;let e=localStorage.getItem(bS);if(e){let t=JSON.parse(e);if(typeof t==`object`&&t){let e={...t,headers:{...t.headers??{},...r},apiPrefix:t.apiPrefix??n};return i&&localStorage.setItem(bS,JSON.stringify(qqe(e))),l({...e,isLoading:!1})}}if(a.status===`active`){let e={baseUrl:t,headers:r,apiPrefix:n};return i&&localStorage.setItem(bS,JSON.stringify(qqe(e))),l({...e,isLoading:!1})}return l({baseUrl:``,headers:r,apiPrefix:void 0,isLoading:!1})},[a,t,n,o,s,r,i]);let u=e=>{l(t=>{let n={...t,...e},r=i?qqe(n):n;return localStorage.setItem(bS,JSON.stringify(r)),n})};return(0,K.jsx)(Hqe.Provider,{value:{...c,setConfig:u},children:e})};function Yqe({children:e,baseUrl:t}){let{patterns:n,isLoading:r,error:i}=OFe();if(r)return(0,K.jsx)(`div`,{className:`flex h-screen w-full items-center justify-center`,children:(0,K.jsx)(It,{})});if(i)return(0,K.jsx)(Xqe,{error:i,baseUrl:t});if(n.size>0){for(let e of Fqe)if(!n.has(e))throw Error(`Invalid permission pattern: "${e}". It is not in the server's PERMISSION_PATTERNS — check for a typo in route-permissions.ts.`)}return(0,K.jsx)(K.Fragment,{children:e})}var Xqe=({error:e,baseUrl:t})=>{let n=[`Studio could not reach the Mastra server at ${t}. Check that the instance URL and API prefix in Settings are correct, and that the server is running.`,`Error: ${e.message}`];return(0,K.jsx)(`div`,{className:`flex h-screen w-full items-center justify-center`,children:(0,K.jsx)(Jx,{tone:`error`,titleSlot:`Failed to load studio`,descriptionSlot:n.join(`
|
|
173
|
+
`):void 0,experimental_attachments:s.length>0?s:void 0,content:l||void 0,metadata:Object.keys(u).length>0?u:void 0}};return e.providerOptions&&(d.content.providerMetadata=e.providerOptions),d}};function Bg(e,t){for(let[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}function Vg(e,t,n){let r=lm(e,`display`,t);return um(r)?r.transformed:n}function Tje(e){return e.startsWith(`tool-`)?vm(e.slice(5)):vm(e)}function Eje(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}function Dje(e){return e===`approval-requested`||e===`approval-responded`||e===`output-denied`}function Oje(e){if(e)return{id:e.id,approved:`approved`in e?e.approved:void 0,reason:`reason`in e?e.reason:void 0}}function Hg(e){return e}function kje(e){return e.type===`dynamic-tool`?vm(e.toolName):Tje(e.type)}function Aje(e){let t=`callProviderMetadata`in e?e.callProviderMetadata:void 0,n=`resultProviderMetadata`in e?e.resultProviderMetadata:void 0;if(!n)return Hg(t);if(!t)return Hg(n);let r={...t};for(let[e,t]of Object.entries(n)){let n=r[e];r[e]=n?{...n,...t}:t}return Hg(Hke(t,n,r))}function jje(e){let t={toolCallId:e.toolCallId,toolName:kje(e),args:Eje(e.input),approval:`approval`in e?Oje(e.approval):void 0,providerMetadata:Aje(e),providerExecuted:e.providerExecuted,title:e.title,preliminary:`preliminary`in e?e.preliminary:void 0};switch(e.state){case`input-streaming`:return Ug({...t,state:`partial-call`});case`input-available`:return Ug({...t,state:`call`});case`output-available`:return Ug({...t,state:`result`,result:gg(e.output)});case`output-error`:return Ug({...t,state:`output-error`,errorText:e.errorText,rawInput:`rawInput`in e?e.rawInput:void 0});case`approval-requested`:case`approval-responded`:case`output-denied`:return Ug({...t,state:e.state})}}function Mje(e){return e.type===`dynamic-tool`&&!Dje(e.state)?{...e,type:`tool-${vm(e.toolName)}`}:e}function Nje(e){return Fg(e)||e.type.startsWith(`data-`)||[`text`,`reasoning`,`file`,`source-url`,`source-document`,`step-start`,`error`].includes(e.type)}function Pje(e){if(e.type!==`data-tool-call-suspended`||!(`data`in e))return;let t=e.data;if(t&&typeof t==`object`&&`toolCallId`in t)return typeof t.toolCallId==`string`?t.toolCallId:void 0}function Ug({toolCallId:e,toolName:t,args:n,state:r,approval:i,result:a,errorText:o,rawInput:s,providerMetadata:c,providerExecuted:l,title:u,preliminary:d}){return Bg({type:`tool-invocation`,toolInvocation:Bg({toolCallId:e,toolName:t,args:n,state:r},{approval:i,result:a,errorText:o,rawInput:s})},{providerMetadata:c,providerExecuted:l,title:u,preliminary:d})}function Fje(e,t){for(let n of e)if(n.type===`tool-invocation`&&n.toolInvocation.toolCallId===t)return n}function Ije(e,t){if(e)for(let n of[...e].reverse()){for(let e of[...n.content.parts||[]].reverse())if(e.type===`tool-invocation`&&e.toolInvocation.approval?.id===t&&e.toolInvocation.state===`approval-requested`)return e;let e=n.content.metadata?.pendingToolApprovals;if(e&&typeof e==`object`)for(let r of Object.values(e)){if(!r||typeof r!=`object`)continue;let e=`toolCallId`in r?r.toolCallId:void 0;if(typeof e!=`string`)continue;let i=`runId`in r?r.runId:void 0,a=typeof i==`string`?`${i}::${e}`:e;if(a!==t)continue;let o=Fje(n.content.parts||[],e);if(o)return Ug({toolCallId:o.toolInvocation.toolCallId,toolName:o.toolInvocation.toolName,args:o.toolInvocation.args,state:`approval-requested`,approval:{id:a},providerMetadata:o.providerMetadata,providerExecuted:o.providerExecuted,title:o.title,preliminary:o.preliminary})}}}function Lje(e,t){let n=t.pendingToolApprovals;if(n&&typeof n==`object`)for(let t of Object.values(n)){if(!t||typeof t!=`object`)continue;let n=`toolCallId`in t?t.toolCallId:void 0;if(typeof n!=`string`)continue;let r=`runId`in t?t.runId:void 0,i=typeof r==`string`?`${r}::${n}`:n,a=e.findIndex(e=>Fg(e)&&e.toolCallId===n&&e.state===`input-available`);if(a===-1)continue;let o=e[a];o&&Fg(o)&&o.state===`input-available`&&(e[a]={...o,state:`approval-requested`,approval:{id:i}})}}function Rje(e){let t=[];for(let n of e){if(n.type!==`tool-invocation`)continue;let e=n.toolInvocation;e.state===`result`?t.push({args:e.args,result:e.result,toolCallId:e.toolCallId,toolName:e.toolName,state:`result`}):(e.state===`call`||e.state===`partial-call`)&&t.push({args:e.args,toolCallId:e.toolCallId,toolName:e.toolName,state:e.state})}return t.length>0?t:void 0}var Wg=class e{static toUIMessage(t){let n=zg.toUIMessage(t),r=n.metadata||{},i=[];if(t.role===`signal`&&n.role!==`user`)return{id:t.id,role:`system`,metadata:Object.keys(r).length>0?r:void 0,parts:n.parts.map(t=>e.toUIPartFromV5(t))};let a=t.content.parts||[],o=a.some(e=>e.type===`tool-invocation`),s=a.some(e=>e.type===`reasoning`),c=a.some(e=>e.type===`file`),l=a.some(e=>e.type===`text`);for(let t of a){let n=e.toUIPart(t);n&&i.push(n)}if(!o||!s||!c||!l)for(let t of n.parts)ch(t)?o||i.push(e.toUIPartFromV5(t)):t.type===`reasoning`?s||i.push(e.toUIPartFromV5(t)):t.type===`file`?c||i.push(e.toUIPartFromV5(t)):t.type===`text`&&!l&&i.push(e.toUIPartFromV5(t));return e.rehydrateSuspendedToolParts(i,n.parts),Lje(i,r),{id:t.id,role:t.role===`signal`?n.role:t.role,metadata:Object.keys(r).length>0?r:void 0,parts:i}}static fromUIMessage(e){let t=e=>e.type!==`source-document`&&!Fg(e),n=e=>e.type===`text`&&e.text===``,r=e.parts.filter(Nje),i=r.some(e=>t(e)&&!n(e));e={...e,parts:i?r.filter(e=>!n(e)):r};let a=e.parts.filter(t),o=zg.fromUIMessage({...e,parts:a.map(e=>Mje(e))}),s=o.content.parts||[],c=[],l=0;for(let t of e.parts)if(t.type===`source-document`)c.push(Bg({type:`source-document`,sourceId:t.sourceId,mediaType:t.mediaType,title:t.title},{filename:t.filename,providerMetadata:Hg(t.providerMetadata)}));else if(Fg(t))c.push(jje(t));else{let e=s[l++];e&&c.push(e)}return{...o,content:{...o.content,parts:c,toolInvocations:Rje(c)||o.content.toolInvocations}}}static fromModelMessage(e,t,n={}){let r=Array.isArray(e.content)?e.content:[{type:`text`,text:e.content}],i=r.filter(e=>e.type!==`tool-approval-request`&&e.type!==`tool-approval-response`),a=zg.fromModelMessage({...e,content:i},t,n),o=[...a.content.parts];if(e.role===`assistant`){let e=new Map;for(let t of r){if(t.type===`tool-call`){e.set(t.toolCallId,{toolName:vm(t.toolName),args:Eje(t.input)});continue}if(t.type!==`tool-approval-request`)continue;let n=e.get(t.toolCallId),r=Fje(o,t.toolCallId);r?(r.toolInvocation.state=`approval-requested`,r.toolInvocation.approval={id:t.approvalId}):o.push(Ug({toolCallId:t.toolCallId,toolName:n?.toolName||`unknown`,args:n?.args||{},state:`approval-requested`,approval:{id:t.approvalId}}))}}else if(e.role===`tool`)for(let e of r){if(e.type!==`tool-approval-response`)continue;let t=Ije(n.dbMessages,e.approvalId);t&&o.push(Ug({toolCallId:t.toolInvocation.toolCallId,toolName:t.toolInvocation.toolName,args:t.toolInvocation.args,state:`approval-responded`,approval:{id:e.approvalId,approved:e.approved,reason:e.reason},providerMetadata:t.providerMetadata,providerExecuted:t.providerExecuted,title:t.title}))}return{...a,content:{...a.content,parts:o}}}static toUIPart(t){if(t.type===`tool-invocation`){let e=Bg({type:`tool-${vm(t.toolInvocation.toolName)}`,toolCallId:t.toolInvocation.toolCallId,providerExecuted:t.providerExecuted},{callProviderMetadata:Gke(t.providerMetadata),title:t.title});switch(t.toolInvocation.state){case`partial-call`:return{...e,state:`input-streaming`,input:Vg(t.providerMetadata,`input-available`,t.toolInvocation.args)};case`call`:return{...e,state:`input-available`,input:Vg(t.providerMetadata,`input-available`,t.toolInvocation.args)};case`approval-requested`:return{...e,state:`approval-requested`,input:Vg(t.providerMetadata,`input-available`,t.toolInvocation.args),approval:{id:t.toolInvocation.approval?.id||t.toolInvocation.toolCallId}};case`approval-responded`:return{...e,state:`approval-responded`,input:Vg(t.providerMetadata,`input-available`,t.toolInvocation.args),approval:{id:t.toolInvocation.approval?.id||t.toolInvocation.toolCallId,approved:t.toolInvocation.approval?.approved??!1,reason:t.toolInvocation.approval?.reason}};case`output-error`:return Bg({...e,state:`output-error`,input:Vg(t.providerMetadata,`input-available`,t.toolInvocation.args),errorText:Vg(t.providerMetadata,`error`,t.toolInvocation.errorText||``)},{rawInput:t.toolInvocation.rawInput,resultProviderMetadata:Uke(t.providerMetadata),approval:t.toolInvocation.approval?.approved===!0?{id:t.toolInvocation.approval.id,approved:!0,reason:t.toolInvocation.approval.reason}:void 0});case`output-denied`:return{...e,state:`output-denied`,input:Vg(t.providerMetadata,`input-available`,t.toolInvocation.args),approval:{id:t.toolInvocation.approval?.id||t.toolInvocation.toolCallId,approved:!1,reason:t.toolInvocation.approval?.reason}};case`result`:return Bg({...e,state:`output-available`,input:Vg(t.providerMetadata,`input-available`,t.toolInvocation.args),output:Vg(t.providerMetadata,`output-available`,Vg(t.providerMetadata,`error`,t.toolInvocation.result))},{preliminary:t.preliminary,resultProviderMetadata:Uke(t.providerMetadata),approval:t.toolInvocation.approval?.approved===!0?{id:t.toolInvocation.approval.id,approved:!0,reason:t.toolInvocation.approval.reason}:void 0});default:throw Error(`Unhandled toolInvocation.state: ${String(t.toolInvocation.state)}`)}}if(t.type===`source-document`)return Bg({type:`source-document`,sourceId:t.sourceId,mediaType:t.mediaType,title:t.title},{filename:t.filename,providerMetadata:t.providerMetadata});let n=zg.toUIMessage({id:`tmp`,role:`assistant`,createdAt:new Date,content:{format:2,parts:[t]}}).parts[0];return n?e.toUIPartFromV5(n):void 0}static rehydrateSuspendedToolParts(t,n){let r=new Set(t.map(Pje).filter(e=>e!==void 0));for(let i of n){let n=Pje(i);if(!n||r.has(n))continue;let a=t.findIndex(e=>Fg(e)&&e.toolCallId===n),o=e.toUIPartFromV5(i);a===-1?t.push(o):t.splice(a+1,0,o),r.add(n)}}static toUIPartFromV5(e){if(ch(e)){let t={type:e.type,toolCallId:e.toolCallId,providerExecuted:e.providerExecuted};switch(e.state){case`input-streaming`:return Bg({...t,state:`input-streaming`,input:e.input},{callProviderMetadata:`callProviderMetadata`in e?e.callProviderMetadata:void 0,title:`title`in e?e.title:void 0});case`input-available`:return Bg({...t,state:`input-available`,input:e.input},{callProviderMetadata:`callProviderMetadata`in e?e.callProviderMetadata:void 0,title:`title`in e?e.title:void 0});case`output-available`:return Bg({...t,state:`output-available`,input:e.input,output:e.output},{callProviderMetadata:`callProviderMetadata`in e?e.callProviderMetadata:void 0,preliminary:`preliminary`in e?e.preliminary:void 0,title:`title`in e?e.title:void 0});case`output-error`:return Bg({...t,state:`output-error`,input:e.input,errorText:e.errorText},{rawInput:`rawInput`in e?e.rawInput:void 0,callProviderMetadata:`callProviderMetadata`in e?e.callProviderMetadata:void 0,title:`title`in e?e.title:void 0})}}switch(e.type){case`text`:return Bg({type:`text`,text:e.text},{providerMetadata:e.providerMetadata});case`reasoning`:return Bg({type:`reasoning`,text:e.text,state:e.state},{providerMetadata:e.providerMetadata});case`file`:return Bg({type:`file`,url:e.url,mediaType:e.mediaType},{filename:`filename`in e?e.filename:void 0,providerMetadata:e.providerMetadata});case`source-url`:return Bg({type:`source-url`,sourceId:e.sourceId,url:e.url},{title:e.title,providerMetadata:e.providerMetadata});case`step-start`:return{type:`step-start`};default:return typeof e.type==`string`&&e.type.startsWith(`data-`)?{type:e.type,data:`data`in e?e.data:void 0}:e}}},zje=/^(itemId|signature|redactedData|encryptedContent|reasoningEncryptedContent|\w*Signature|\w*Digest)$/;function Bje(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Gg(e){let t=3735928559,n=1103547991;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);t=Math.imul(t^i,2654435761),n=Math.imul(n^i,1597334677)}return t=Math.imul(t^t>>>16,2246822507)^Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),(4294967296*(2097151&n)+(t>>>0)).toString(36)}function Vje(...e){let t=new Set;for(let n of e)if(Bje(n)){for(let e of Object.values(n))if(Bje(e))for(let[n,r]of Object.entries(e))typeof r==`string`&&r.length!==0&&zje.test(n)&&t.add(`${n}:${Gg(r)}`)}return[...t].sort()}function Kg(e,...t){for(let n of Vje(...t))e+=`|${n}`;return e}function Hje(e){return JSON.stringify(e,(e,t)=>{if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.create(null);for(let n of Object.keys(t).sort())e[n]=t[n];return e}return t})}function qg(e,...t){let n=new Set(t.flatMap(e=>Kke(e)));for(let t of n)e+=`|${t}`;return e}var Jg=class e{static fromAIV4Parts(t){let n=``;for(let r of t)n+=r.type,n+=e.fromAIV4Part(r);return n}static fromAIV4Part(e){let t=``;if(e.type===`text`&&(t+=e.text,t=qg(t,e.providerMetadata)),e.type===`tool-invocation`){if(!e.toolInvocation)return t;t+=e.toolInvocation.toolCallId,t+=e.toolInvocation.state}if(e.type===`reasoning`){t+=e.reasoning,t+=(e.details??[]).reduce((e,t)=>t.type===`text`?e+(t.text?.length??0)+(t.signature?.length||0):e,0);let n=e;n&&Object.hasOwn(n,`providerMetadata`)&&(t=qg(t,n.providerMetadata)),t=Kg(t,n?.providerMetadata);for(let n of e.details??[]){let e=n.type===`text`?n.signature:n.data;e&&(t+=`|${n.type}:${Gg(e)}`)}}if(e.type===`file`){let{mediaType:n,data:r}=_m(e);t+=r,t+=n}return t}static fromDBParts(t){let n=``;for(let r of t)if(n+=r.type,r.type.startsWith(`data-`)){let e=r.data;n+=Hje(e)}else n+=e.fromAIV4Part(r);return n}static fromAIV4CoreMessageContent(e){if(typeof e==`string`)return e;let t=``;for(let n of e){if(t+=n.type,n.type===`text`){t+=n.text.length;let e=n;t=qg(t,e.providerMetadata,e.providerOptions)}if(n.type===`reasoning`){t+=n.text.length;let e=n;t=qg(t,e.providerMetadata,e.providerOptions),t=Kg(t,e.providerMetadata,e.providerOptions),n.signature&&(t+=`|signature:${Gg(n.signature)}`)}n.type===`tool-call`&&(t+=n.toolCallId,t+=n.toolName),n.type===`tool-result`&&(t+=n.toolCallId,t+=n.toolName),n.type===`file`&&(t+=n.filename,t+=n.mimeType),n.type===`image`&&(t+=Ape(n.image),t+=n.mimeType),n.type===`redacted-reasoning`&&(t+=n.data.length,t+=`|${Gg(n.data)}`)}return t}static fromAIV5Parts(e){let t=``;for(let n of e)t+=n.type,n.type===`text`&&(t+=n.text,t=qg(t,n.providerMetadata)),(ch(n)||n.type===`dynamic-tool`)&&(t+=n.toolCallId,t+=n.state),n.type===`reasoning`&&(t+=n.text,t=qg(t,n.providerMetadata),t=Kg(t,n.providerMetadata)),n.type===`file`&&(t+=n.url.length,t+=n.mediaType,t+=n.filename||``);return t}static fromAIV5ModelMessageContent(e){if(typeof e==`string`)return e;let t=``;for(let n of e)t+=n.type,n.type===`text`&&(t+=n.text.length,t=qg(t,n.providerOptions)),n.type===`reasoning`&&(t+=n.text.length,t=qg(t,n.providerOptions),t=Kg(t,n.providerOptions)),n.type===`tool-call`&&(t+=n.toolCallId,t+=n.toolName),n.type===`tool-result`&&(t+=n.toolCallId,t+=n.toolName),n.type===`file`&&(t+=n.filename,t+=n.mediaType),n.type===`image`&&(t+=Ape(n.image),t+=n.mediaType);return t}},Uje=`<working_memory>`,Wje=`</working_memory>`,Gje=`updateWorkingMemory`;function Yg(e){let t=``,n=0;for(;n<e.length;){let r=e.indexOf(Uje,n);if(r===-1){t+=e.substring(n);break}t+=e.substring(n,r);let i=e.indexOf(Wje,r+16);if(i===-1){t+=e.substring(r);break}n=i+17}return t}var Kje=`skip_thought_signature_validator`;function qje(e){let t=e=>e?.type===`tool-invocation`&&e.toolInvocation?.toolName===`updateWorkingMemory`;if(!e.some(t))return e;let n=[];return e.forEach((t,r)=>{let i=e[r-1];(t?.type===`step-start`||i?.type===`tool-invocation`&&t?.type!==`tool-invocation`||n.length===0)&&n.push([]),n[n.length-1].push(t)}),n.flatMap(e=>{if(!e.some(t))return e;let n=e.filter(e=>!t(e)),r=n.findIndex(e=>e?.type===`tool-invocation`),i=n[r];if(i?.type===`tool-invocation`){let a=i.providerMetadata;for(let n of e)if(t(n))for(let[e,t]of Object.entries(n.providerMetadata??{}))t?.thoughtSignature!==void 0&&a?.[e]?.thoughtSignature===void 0&&(a={...a,[e]:{...a?.[e],thoughtSignature:Kje}});a!==i.providerMetadata&&(n[r]={...i,providerMetadata:a})}return n.every(e=>e?.type===`step-start`||e?.type===`reasoning`||e?.type===`text`&&!Yg(e.text??``).trim())?[]:n})}function Jje(e){if(!e?.some(e=>e.toolName===`updateWorkingMemory`))return e;let t=e.filter(e=>e.toolName!==Gje);return t.length>0?t:void 0}function Yje(e){return e.filter(e=>e.role!==`system`&&!epe(e)).map(e=>{let t={...e};if(e.content&&typeof e.content==`object`&&!Array.isArray(e.content)&&(t.content={...e.content}),typeof t.content?.content==`string`&&t.content.content.length>0){let e=Yg(t.content.content);t.content.content=e===t.content.content?t.content.content:e.trim()}return Array.isArray(t.content?.parts)&&(Array.isArray(t.content.toolInvocations)&&(t.content.toolInvocations=Jje(t.content.toolInvocations)),t.content.parts=qje(t.content.parts).map(e=>{if(e.type===`tool-invocation`&&e.toolInvocation.state===`partial-call`)return null;if(e.type===`text`){let t=typeof e.text==`string`?e.text:``,n=Yg(t);return{...e,text:n===t?t:n.trim()}}return e}).filter(e=>!!e),t.content.parts.length===0)?null:t}).filter(e=>!!e)}function Xje(e){return typeof e==`string`?e:e.reduce((e,t)=>(t.type===`text`&&(e+=t.text),e),``)}function Zje(e,t){let n=_g.isAIV4UIMessage(e)&&e,r=_g.isAIV4UIMessage(t)&&t;if(n&&!r)return!1;if(n&&r)return Jg.fromAIV4Parts(e.parts)===Jg.fromAIV4Parts(t.parts);let i=_g.isAIV4CoreMessage(e)&&e,a=_g.isAIV4CoreMessage(t)&&t;if(i&&!a)return!1;if(i&&a)return Jg.fromAIV4CoreMessageContent(i.content)===Jg.fromAIV4CoreMessageContent(a.content);let o=_g.isMastraMessageV1(e)&&e,s=_g.isMastraMessageV1(t)&&t;if(o&&!s)return!1;if(o&&s)return o.id===s.id&&Jg.fromAIV4CoreMessageContent(o.content)===Jg.fromAIV4CoreMessageContent(s.content);let c=_g.isMastraDBMessage(e)&&e,l=_g.isMastraDBMessage(t)&&t;if(c&&!l)return!1;if(c&&l)return c.id===l.id&&Jg.fromDBParts(c.content.parts)===Jg.fromDBParts(l.content.parts);let u=_g.isAIV5UIMessage(e)&&e,d=_g.isAIV5UIMessage(t)&&t;if(u&&!d)return!1;if(u&&d)return Jg.fromAIV5Parts(e.parts)===Jg.fromAIV5Parts(t.parts);let f=_g.isAIV5CoreMessage(e)&&e,p=_g.isAIV5CoreMessage(t)&&t;return f&&!p?!1:f&&p?Jg.fromAIV5ModelMessageContent(f.content)===Jg.fromAIV5ModelMessageContent(p.content):!0}function Qje(e){return qje(e).map(e=>e.type===`text`?{...e,text:Yg(typeof e.text==`string`?e.text:``).trim()}:e)}function $je(e,t){if(e.id!==t.id)return!1;let n=Jg.fromDBParts(Qje(t.content.parts)),[r]=Yje([e]);return[e,r].some(e=>e!==void 0&&Jg.fromDBParts(Qje(e.content.parts))===n)}function eMe(e){return e.createdAt??=Date.now(),e}function Xg(e,t){return t===`memory`||!Array.isArray(e.content.parts)||(e.content.parts=e.content.parts.map(e=>eMe(e))),e}function tMe(e,t,n){n===void 0?(e.updatedAt===void 0||JSON.stringify(t)!==JSON.stringify(e.toolInvocation))&&(e.updatedAt=Date.now()):e.updatedAt=n}function nMe(e,t,n){if(t!==`memory`&&`threadId`in e&&e.threadId&&n.memoryInfo&&e.threadId!==n.memoryInfo.threadId)throw Error(`Received input message with wrong threadId. Input ${e.threadId}, expected ${n.memoryInfo.threadId}`);if(t!==`memory`&&`resourceId`in e&&e.resourceId&&n.memoryInfo?.resourceId&&e.resourceId!==n.memoryInfo.resourceId)throw Error(`Received input message with wrong resourceId. Input ${e.resourceId}, expected ${n.memoryInfo.resourceId}`);if(_g.isMastraMessageV1(e))return Xg(rMe(e,t,n),t);if(_g.isMastraDBMessage(e))return Xg(iMe(e,n,t),t);if(_g.isAIV4CoreMessage(e))return Xg(Sg.fromCoreMessage(e,n,t),t);if(_g.isAIV4UIMessage(e))return Xg(Sg.fromUIMessage(e,n,t),t);let r=`id`in e&&typeof e.id==`string`?e.id:n.newMessageId();if(_g.isAIV6CoreMessage(e)){let i=Wg.fromModelMessage(e,t,n),a=`metadata`in e&&e.metadata&&typeof e.metadata==`object`&&`createdAt`in e.metadata?e.metadata.createdAt:void 0;return{...i,id:r,createdAt:n.generateCreatedAt(t,a),threadId:n.memoryInfo?.threadId,resourceId:n.memoryInfo?.resourceId}}if(_g.isAIV6UIMessage(e)){let i=Wg.fromUIMessage(e),a=`createdAt`in e?e.createdAt:void 0;return{...i,id:r,createdAt:n.generateCreatedAt(t,a),threadId:n.memoryInfo?.threadId,resourceId:n.memoryInfo?.resourceId}}if(_g.isAIV5CoreMessage(e)){let i=zg.fromModelMessage(e,t,n),a=`metadata`in e&&e.metadata&&typeof e.metadata==`object`&&`createdAt`in e.metadata?e.metadata.createdAt:void 0;return Xg({...i,id:r,createdAt:n.generateCreatedAt(t,a),threadId:n.memoryInfo?.threadId,resourceId:n.memoryInfo?.resourceId},t)}if(_g.isAIV5UIMessage(e)){let i=zg.fromUIMessage(e),a=`createdAt`in e?e.createdAt:void 0;return Xg({...i,id:r,createdAt:n.generateCreatedAt(t,a),threadId:n.memoryInfo?.threadId,resourceId:n.memoryInfo?.resourceId},t)}throw Error(`Found unhandled message ${JSON.stringify(e)}`)}function rMe(e,t,n){let r=Sg.fromCoreMessage({content:e.content,role:e.role},n,t);return{id:e.id,role:r.role,createdAt:n.generateCreatedAt(t,e.createdAt),threadId:e.threadId,resourceId:e.resourceId,content:r.content}}function iMe(e,t,n){return e.content.parts=Array.isArray(e.content.parts)?e.content.parts.filter(e=>typeof e==`object`&&!!e):[],e.id||=t.newMessageId(),e.createdAt===void 0||e.createdAt===null?e.createdAt=t.generateCreatedAt(n):e.createdAt instanceof Date||(e.createdAt=new Date(e.createdAt)),e.content.toolInvocations&&e.content.parts&&(e.content.toolInvocations=e.content.toolInvocations.map(t=>{if(!t.args||Object.keys(t.args).length===0){let n=e.content.parts.find(e=>e.type===`tool-invocation`&&e.toolInvocation&&e.toolInvocation.toolCallId===t.toolCallId&&e.toolInvocation.args&&Object.keys(e.toolInvocation.args).length>0);if(n&&n.type===`tool-invocation`)return{...t,args:n.toolInvocation.args}}return t})),!e.threadId&&t.memoryInfo?.threadId&&(e.threadId=t.memoryInfo.threadId),!e.resourceId&&t.memoryInfo?.resourceId&&(e.resourceId=t.memoryInfo.resourceId),e}function aMe(e){return e.type.startsWith(`source-`)}function oMe(e){let t=[];for(let n of e){if(n.type!==`text`){t.push(n);continue}let e=n,r=Bke(e.providerMetadata);if(!r){t.push(n);continue}let i=!1;for(let n=t.length-1;n>=0;n--){let a=t[n];if(a.type===`text`){let o=a;Bke(o.providerMetadata)===r&&(t[n]={...o,text:o.text+e.text},i=!0);break}if(!aMe(a))break}i||t.push(n)}return t}function sMe(e){if(ebe(e)!==`tool_search`||!e.providerExecuted)return!1;let t=`callProviderMetadata`in e?e.callProviderMetadata:void 0,n=zke(t);if(n&&(e.state!==`output-available`&&e.state!==`output-error`||Wke(t,n.provider)))return!1;let r=e.input;return!(r&&typeof r==`object`&&typeof r.call_id==`string`)}function cMe(e){return e.map(e=>{if(typeof e.content==`string`)return e;let t=!1,n=e.content.map(e=>{if(e.type!==`tool-call`&&e.type!==`tool-result`)return e;let n=e.providerOptions;if(!n)return e;let r,i=new Set;for(let t of vg){let a=n[t];if(!a)continue;let o=a[yg];if(typeof o!=`string`)continue;let{[yg]:s,...c}=a;i.add(t),r={...r??n,[t]:e.type===`tool-result`?{...c,itemId:o}:c}}if(!r)return e;if(e.type===`tool-result`)for(let e of vg){if(i.has(e))continue;let t=r[e];if(typeof t?.itemId!=`string`)continue;let{itemId:n,...a}=t;r={...r,[e]:a}}return t=!0,{...e,providerOptions:r}});return t?{...e,content:n}:e})}function lMe(e){return e.map(e=>{if(e.parts.length===0)return!1;let t=e.parts.filter(e=>e.type===`error`?!1:e.type!==`tool-invocation`||e.toolInvocation.state!==`call`&&e.toolInvocation.state!==`partial-call`);if(!t.length)return!1;let n={...e,parts:t};return`toolInvocations`in e&&e.toolInvocations&&(n.toolInvocations=e.toolInvocations.filter(e=>e.state===`result`)),n}).filter(e=>!!e)}function uMe(e,t=`response`){let n=-1;for(let t=e.length-1;t>=0;t--)if(e[t].role===`user`){n=t;break}let r=(e,n)=>e.parts.filter(r=>typeof r.type==`string`&&r.type.startsWith(`data-`)||r.type===`error`||r.type===`text`&&(!(`text`in r)||r.text===``||r.text?.trim()===``)&&(e.role===`user`||e.parts.some(e=>e.type!==`text`||`text`in e&&e.text!==``&&e.text?.trim()!==``))?!1:ch(r)?t===`response`?r.state!==`input-streaming`:sMe(r)?!1:r.state===`output-available`||r.state===`output-error`?!0:r.state===`input-available`?r.providerExecuted?n:t===`prompt-with-suspended`:!1:!0),i=-1;if(n!==e.length-1)for(let t=e.length-1;t>n;t--){let n=e[t];if(n.role===`assistant`&&n.parts.length!==0&&r(n,!0).length>0){i=t;break}}return e.map((e,t)=>{if(e.parts.length===0)return!1;let n=e.role===`assistant`&&t===i,a=r(e,n);if(!a.length)return!1;let o=oMe(a);return{...e,parts:o.map(e=>ch(e)&&e.state===`output-available`?{...e,output:Lke(e.output,{unwrapContent:!1}).output}:e)}}).filter(e=>!!e)}function dMe(e){for(let t of e)if(t.role===`assistant`)for(let[e,n]of t.parts.entries()){if(!ch(n))continue;let r=t.parts.at(e+1);r&&r.type!==`step-start`&&!ch(r)&&t.parts.splice(e+1,0,{type:`step-start`}),r&&ch(r)&&!n.providerExecuted&&r.providerExecuted&&(r.state===`output-available`||r.state===`output-error`)&&t.parts.splice(e+1,0,{type:`step-start`})}return e}function Zg(e){let t=lMe(e),n=new Map,r=0,i=LOe(t.map(e=>{if(e.role!==`user`)return e;let t=r++;if(!e.experimental_attachments?.length)return e;let i=e.experimental_attachments.filter(e=>gm(e.url,e.contentType).type===`providerFileId`);if(!i.length)return e;n.set(t,i);let a=e.experimental_attachments.filter(e=>!i.includes(e));return{...e,experimental_attachments:a.length?a:void 0}}));if(!n.size)return i;let a=0;return i.map(e=>{if(e.role!==`user`)return e;let t=n.get(a++);if(!t)return e;let r=t.map(e=>({type:`file`,data:e.url,mimeType:e.contentType||`application/octet-stream`})),i=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content;return{...e,content:[...i,...r]}})}function fMe(e){if(!e||typeof e!=`object`)return;let t=e.content;if(!Array.isArray(t)||!t.some(e=>{if(!e||typeof e!=`object`)return!1;let t=e;return(t.type===`image`||t.type===`audio`)&&typeof t.data==`string`}))return;let n=t.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;switch(t.type){case`text`:return{type:`text`,text:String(t.text??``)};case`image`:return typeof t.data==`string`?{type:`media`,data:t.data,mediaType:String(t.mimeType??`image/png`)}:{type:`text`,text:JSON.stringify(t)};case`audio`:return typeof t.data==`string`?{type:`media`,data:t.data,mediaType:String(t.mimeType??`audio/wav`)}:{type:`text`,text:JSON.stringify(t)};default:return{type:`text`,text:JSON.stringify(t)}}}).filter(Boolean);return n.length>0?{type:`content`,value:n}:void 0}function pMe(e){let t=new Map;for(let n of e)if(n.content?.format===2&&n.content.parts)for(let e of n.content.parts){if(e.type!==`tool-invocation`||e.toolInvocation?.state!==`result`)continue;let n=e.providerMetadata?.mastra;n&&typeof n==`object`&&`modelOutput`in n||t.set(e.toolInvocation.toolCallId,e.toolInvocation.result)}return t}function mMe(e,t){if(!e||typeof e!=`object`)return!1;let n=e;return n.type===`json`?n.value===t||Eke(n.value,t):!1}function hMe(e,t){let n=pMe(t);return n.size===0?e:e.map(e=>{if(e.role!==`tool`||!Array.isArray(e.content))return e;let t=!1,r=e.content.map(e=>{if(e.type!==`tool-result`||!n.has(e.toolCallId)||e.output?.type!==`json`)return e;let r=n.get(e.toolCallId),i;try{if(i=fMe(r),!i||!mMe(e.output,r))return e}catch{return e}return t=!0,{...e,output:i}});return t?{...e,content:r}:e})}function gMe(e){let t=new Map;if(e?.content?.format!==2||!e.content.parts)return t;for(let n of e.content.parts)n.type===`tool-invocation`&&n.toolInvocation?.state===`output-error`&&n.providerExecuted&&n.toolInvocation.result!==void 0&&t.set(n.toolInvocation.toolCallId,n.toolInvocation.result);return t}function _Me(e,t){let n=gMe(t);return n.size===0?e:e.map(e=>{if(e.role!==`assistant`||!Array.isArray(e.content))return e;let t=!1,r=e.content.map(e=>{if(e.type!==`tool-result`||e.output?.type!==`error-json`||!n.has(e.toolCallId))return e;let r=n.get(e.toolCallId);return typeof r==`string`?e:(t=!0,{...e,output:{type:`error-json`,value:r??null}})});return t?{...e,content:r}:e})}function vMe(e,t){let n=[];for(let e of t)if(e.role===`assistant`)for(let t of e.parts)t.type===`file`&&n.push(t.providerMetadata??void 0);if(n.length===0||n.every(e=>e==null))return e;let r=0;return e.map(e=>{if(e.role!==`assistant`||typeof e.content==`string`)return e;let t=!1,i=e.content.map(e=>{if(e.type!==`file`||r>=n.length)return e;let i=n[r++];return e.providerOptions||!i?e:(t=!0,{...e,providerOptions:i})});return t?{...e,content:i}:e})}var yMe=[`signature`,`redactedData`,`itemId`,`reasoningEncryptedContent`,`thoughtSignature`];function bMe(e){return Object.values(e??{}).some(e=>!!e&&typeof e==`object`&&yMe.some(t=>t in e))}function xMe(e){return e.role!==`assistant`||!Array.isArray(e.content)||e.content.length===0?!1:e.content.every(e=>e.type===`reasoning`&&!bMe(e.providerOptions))}function Qg(e,t,n=`response`){let r=dMe(uMe(e,n)),i=[],a=new Map(t.map(e=>[e.id,e]));for(let e of r){let t=_Me(ibe([e]),a.get(e.id));if(t.length===0)continue;let r=e.metadata&&typeof e.metadata==`object`&&`providerMetadata`in e.metadata?e.metadata.providerMetadata:void 0;if(r){let n=-1;for(let r=t.length-1;r>=0;r--)if(t[r]?.role===e.role){n=r;break}n!==-1&&(t[n]={...t[n],providerOptions:r})}for(let e of t)n!==`response`&&xMe(e)||i.push(e)}let o=Jke(hMe(vMe(cMe(i),r),t),t);switch(n){case`prompt`:return Xke(o);case`prompt-with-suspended`:return Zke(o);default:return o}}function SMe(e,t,n,r){return Qg(e.map(e=>Sg.fromCoreMessage(e,n,t)).map(e=>zg.toUIMessage(e)),r)}function CMe(e){if(typeof e==`string`)return{role:`system`,content:e};if(_g.isAIV6CoreMessage(e)){let t=Wg.fromModelMessage(e,`system`);return Sg.systemToV4Core(t)}if(_g.isAIV5CoreMessage(e)){let t=zg.fromModelMessage(e,`system`);return Sg.systemToV4Core(t)}return _g.isMastraDBMessage(e)?Sg.systemToV4Core(e):e}var wMe=class e{static extractStepContent(t,n,r,i){let a=t.flatMap(e=>e.parts),o=[];return a.forEach((e,t)=>{e.type===`step-start`&&o.push(t)}),n===-1?e.extractLastStep(a,o,r,i):n===1?e.extractFirstStep(a,o,r):e.extractMiddleStep(a,o,n,r)}static extractLastStep(t,n,r,i){let a=t.filter(e=>e.type?.startsWith(`tool-`)),o=n.length>0;if(!o&&a.length>0){let n=a[a.length-1];if(!n)return[];let o=t.indexOf(n),s=new Set(i??[]),c=s.size?a.findIndex(e=>s.has(e.toolCallId??``)):-1,l=a[(c===-1?a.length-1:c)-1],u=(l?t.indexOf(l):-1)+1,d=t.slice(u,o+1);return e.convertPartsToContent(d,`last-step`,r)}if(n.length+1===1&&!o)return e.convertPartsToContent(t,`last-step`,r);let s=n[n.length-1];if(s===void 0)return[];let c=t.slice(s+1);return c.length===0?[]:e.convertPartsToContent(c,`last-step`,r)}static extractFirstStep(t,n,r){let i=n[0]??t.length;if(i===0)return[];let a=t.slice(0,i);return e.convertPartsToContent(a,`step-1`,r)}static extractMiddleStep(t,n,r,i){let a=r-2;if(a<0||a>=n.length)return[];let o=(n[a]??0)+1,s=n[a+1]??t.length;if(o>=s)return[];let c=t.slice(o,s);return e.convertPartsToContent(c,`step-${r}`,i)}static convertPartsToContent(e,t,n){return ibe(uMe([{id:t,role:`assistant`,parts:e}])).flatMap(n)}static convertToStepContent(e,t,n){let r=e||n();return r?typeof r.content==`string`?[{type:`text`,text:r.content}]:r.content.map(e=>e.type===`tool-result`?{type:`tool-result`,input:bg(t,e.toolCallId),output:e.output,toolCallId:e.toolCallId,toolName:e.toolName}:e.type===`file`?{type:`file`,file:new jke({data:typeof e.data==`string`?mm(e.data).base64Content:e.data instanceof URL?e.data.toString():pm(e.data),mediaType:e.mediaType})}:e.type===`image`?{type:`file`,file:new jke({data:typeof e.image==`string`?mm(e.image).base64Content:e.image instanceof URL?e.image.toString():pm(e.image),mediaType:e.mediaType||`unknown`})}:{...e}):[]}},$g=class e{static isSealed(e){return(e.content?.metadata)?.mastra?.sealed===!0}static shouldMerge(t,n,r,i,a=!1){if(!t||e.isSealed(t)||t.id!==n.id&&(t.content?.metadata)?.mastra?.responseBoundary||n.content.metadata?.completionResult||t.content.metadata?.completionResult||n.content.metadata?.isTaskCompleteResult||t.content.metadata?.isTaskCompleteResult)return!1;let o=t.content?.parts??[];return o.length>0&&o.every(e=>e.type.startsWith(`data-`))&&t.id!==n.id?!1:t.role===`assistant`&&n.role===`assistant`&&t.threadId===n.threadId&&r!==`memory`&&(!a||!i)}static merge(t,n){n.content.metadata&&(t.content.metadata={...t.content.metadata??{},...n.content.metadata});let r=new Map,i=new Map;for(let[e,a]of n.content.parts.entries())if(a.type===`tool-invocation`){if(!a.toolInvocation)continue;let n=[...t.content.parts].reverse().find(e=>e.type===`tool-invocation`&&e.toolInvocation?.toolCallId===a.toolInvocation.toolCallId);if(n&&n.type===`tool-invocation`){let i=n.toolInvocation;if(a.toolInvocation.state===`result`){n.toolInvocation={...n.toolInvocation,step:a.toolInvocation.step,state:`result`,result:a.toolInvocation.result,args:{...n.toolInvocation.args,...a.toolInvocation.args}},tMe(n,i,a.updatedAt),a.providerMetadata&&(n.providerMetadata={...n.providerMetadata,...a.providerMetadata}),t.content.toolInvocations||(t.content.toolInvocations=[]);let e=t.content.toolInvocations.findIndex(e=>e.toolCallId===n.toolInvocation.toolCallId);e===-1?t.content.toolInvocations.push(n.toolInvocation):t.content.toolInvocations[e]=n.toolInvocation}else(a.toolInvocation.state===`approval-requested`||a.toolInvocation.state===`approval-responded`||a.toolInvocation.state===`output-denied`||a.toolInvocation.state===`output-error`)&&(n.toolInvocation={...n.toolInvocation,state:a.toolInvocation.state,approval:a.toolInvocation.approval,errorText:a.toolInvocation.errorText,...a.toolInvocation.state===`output-error`&&a.toolInvocation.result!==void 0?{result:a.toolInvocation.result}:{},rawInput:a.toolInvocation.rawInput,args:{...n.toolInvocation.args,...a.toolInvocation.args}},tMe(n,i,a.updatedAt),a.providerMetadata&&(n.providerMetadata={...n.providerMetadata,...a.providerMetadata}),`providerExecuted`in a&&a.providerExecuted!==void 0&&(n.providerExecuted=a.providerExecuted),`title`in a&&a.title!==void 0&&(n.title=a.title),`preliminary`in a&&a.preliminary!==void 0&&(n.preliminary=a.preliminary));let o=t.content.parts.findIndex(e=>e===n);r.set(e,o)}else i.set(e,a)}else i.set(e,a);e.addPartsToMessage({latestMessage:t,incomingMessage:n,anchorMap:r,partsToAdd:i}),!t.content.content&&n.content.content&&(t.content.content=n.content.content),t.content.content&&n.content.content&&t.content.content!==n.content.content&&(t.content.content=n.content.content)}static addPartsToMessage({latestMessage:t,incomingMessage:n,anchorMap:r,partsToAdd:i}){let a=-1,o=0,s=e.createMergeIndex(t,n),c;for(let l=0;l<n.content.parts.length;++l){let u=n.content.parts[l];if(!u)continue;let d=s.keyOf(u),f=i.get(l);if(d&&f){if(r.size>0){if(r.has(l))continue;let i=[...r.keys()].filter(e=>e<l).pop()??-1,f=[...r.keys()].find(e=>e>l)??-1,p=i===-1?0:r.get(i),m=i===-1?l:l-i;i!==a&&(o=0,a=i);let h=p+m+o,g=f===-1?t.content.parts.length:r.get(f);if(h<0||h>g)continue;if(!c||c.leftAnchor!==i){let e=t.content.parts.slice(h,g),n=new Map;for(let t of e){let e=s.keyOf(t);n.set(e,(n.get(e)??0)+1)}c={leftAnchor:i,parts:e,start:0,counts:n}}for(;c.parts.length-c.start>g-h;){let e=s.keyOf(c.parts[c.start++]);c.counts.set(e,c.counts.get(e)-1)}if(!c.counts.get(d)){let i=e.pushNewPart({latestMessage:t,newMessage:n,part:u,insertAt:h,index:s});if(i===0)continue;o+=i-1;for(let[e,t]of r.entries())t>=h&&r.set(e,t+i)}}else e.pushNewPart({latestMessage:t,newMessage:n,part:u,index:s})}}}static createMergeIndex(e,t){let n=new Map,r=e=>Jg.fromDBParts([e]),i=e=>e.type.startsWith(`data-`)&&`id`in e&&typeof e.id==`string`?e.id:void 0,a=(e,t)=>{let a=new Set,o=new Map;for(let e of t){if(!e.type.startsWith(`data-`))continue;let t=r(e),n=i(e);n===void 0?o.set(t,(o.get(t)??0)+1):a.add(`${t}|id:${JSON.stringify(n)}`)}for(let t of[...e].reverse()){if(n.has(t))continue;let e=r(t),s=i(t),c=o.get(e)??0,l=s===void 0?void 0:`${e}|id:${JSON.stringify(s)}`;l!==void 0&&!a.has(l)&&c>0?(o.set(e,c-1),n.set(t,e)):n.set(t,l??e)}};a(e.content.parts,t.content.parts),a(t.content.parts,e.content.parts);let o=e=>{let t=n.get(e);return t===void 0&&(t=r(e),n.set(e,t)),t},s=e=>{let t=new Map;for(let n of e){let e=o(n);t.set(e,(t.get(e)??0)+1)}return t},c=t.content.parts,l=new Map;c.forEach((e,t)=>{l.has(e)||l.set(e,t)});let u=c.findIndex(e=>e.type!==`step-start`);return{keyOf:o,latestCounts:s(e.content.parts),incomingCounts:s(c),incomingIndex:l,firstIncomingNonStepStart:u===-1?c.length:u}}static pushNewPart({latestMessage:e,newMessage:t,part:n,insertAt:r,index:i}){let a=i.keyOf(n),o=i.latestCounts.get(a)??0;if(o<(i.incomingCounts.get(a)??0)){let s=i.incomingIndex.get(n)??-1,c=s>0&&t.content.parts[s-1]?.type===`step-start`,l=s<=i.firstIncomingNonStepStart,u=e.role===`assistant`&&(n.type===`text`&&!c||n.type===`tool-invocation`&&l)&&e.content.parts.length>0&&e.content.parts.at(-1)?.type===`tool-invocation`,d;if(u){let t=e.content.parts.findLast(e=>e.type===`step-start`);d=t?.model?eMe({type:`step-start`,model:t.model}):{type:`step-start`};let n=i.keyOf(d);i.latestCounts.set(n,(i.latestCounts.get(n)??0)+1)}return i.latestCounts.set(a,o+1),typeof r==`number`?d?(e.content.parts.splice(r,0,d),e.content.parts.splice(r+1,0,n)):e.content.parts.splice(r,0,n):(d&&e.content.parts.push(d),e.content.parts.push(n)),d?2:1}return 0}};function TMe(e,t){let n,r=e.type;switch(r){case`image`:n=e.image;break;case`file`:n=e.data;break;default:throw Error(`Unsupported part type: ${r}`)}let{data:i,mediaType:a}=kke(n),o=a??e.mediaType,s=i;if(s instanceof URL&&t){let e=t[s.toString()];e&&(s=e.data,o??=e.mediaType)}switch(r){case`image`:return(s instanceof Uint8Array||typeof s==`string`)&&(o=Dpe({data:s,signatures:wpe})??o),{type:`file`,mediaType:o??`image/*`,filename:void 0,data:s,providerOptions:e.providerOptions};case`file`:if(o==null)throw Error(`Media type is missing for file part`);return{type:`file`,mediaType:o,filename:e.filename,data:s,providerOptions:e.providerOptions}}}function EMe(e){let t=[];for(let n of e){let e=gm(n.url,n.contentType);if(e.type===`providerFileId`){t.push({type:`file`,data:n.url,mimeType:n.contentType||`application/octet-stream`});continue}let r=n.url;e.type===`raw`&&(r=Ope(n.url,n.contentType||`application/octet-stream`));let i;try{i=new URL(r)}catch{throw Error(`Invalid URL: ${n.url}`)}switch(i.protocol){case`http:`:case`https:`:case`gs:`:case`s3:`:if(n.contentType?.startsWith(`image/`))t.push({type:`image`,image:i.toString(),mimeType:n.contentType});else{if(!n.contentType)throw Error(`If the attachment is not an image, it must specify a content type`);t.push({type:`file`,data:i.toString(),mimeType:n.contentType})}break;case`data:`:if(n.contentType?.startsWith(`image/`))t.push({type:`image`,image:r,mimeType:n.contentType});else if(n.contentType?.startsWith(`text/`))t.push({type:`file`,data:r,mimeType:n.contentType});else{if(!n.contentType)throw Error(`If the attachment is not an image or text, it must specify a content type`);t.push({type:`file`,data:r,mimeType:n.contentType})}break;default:throw Error(`Unsupported URL protocol: ${i.protocol}`)}}return t}var DMe=e=>{let t=new Map,n=/__split-\d+$/;return r=>{let i=e.at(-1);if(r.role===i?.role&&Array.isArray(i.content)&&Array.isArray(r.content)&&(r.role!==`assistant`||r.role===`assistant`&&r.content.at(-1)?.type!==`tool-call`))for(let e of r.content)i.content.push(e);else{let i=r.id;if(n.test(i)){e.push(r);return}let a=t.get(i)||0;a>0&&(r.id=`${i}__split-${a}`),t.set(i,a+1),e.push(r)}}};function e_(e){let t=[],n=DMe(t);for(let t=0;t<e.length;t++){let r=e[t],i=t===e.length-1;if(!r?.content)continue;let{content:a,experimental_attachments:o=[],parts:s}=r.content,{role:c}=r,l={id:r.id,createdAt:r.createdAt,resourceId:r.resourceId,threadId:r.threadId},u=[...o],d=[];for(let e of s)if(e.type===`file`){let{mediaType:t,data:n}=_m(e);u.push({url:n,contentType:t??`application/octet-stream`})}else d.push(e);switch(c){case`user`:if(d==null){let e=u?[{type:`text`,text:a||``},...EMe(u)]:{type:`text`,text:a||``};n({role:`user`,...l,type:`text`,content:e})}else{let e=r.content.parts.filter(e=>e.type===`text`).map(e=>({type:`text`,text:e.text})),t=u?[...e,...EMe(u)]:e;n({role:`user`,...l,type:`text`,content:Array.isArray(t)&&t.length===1&&t[0]?.type===`text`&&a!==void 0?a:t})}break;case`assistant`:{if(r.content.parts!=null){let e=0,t=!1,i=[];function a(){let r=[];for(let e of i)switch(e.type){case`file`:case`text`:r.push(e);break;case`reasoning`:for(let t of e.details)switch(t.type){case`text`:r.push({type:`reasoning`,text:t.text,signature:t.signature});break;case`redacted`:r.push({type:`redacted-reasoning`,data:t.data})}break;case`tool-invocation`:e.toolInvocation.toolName!==`updateWorkingMemory`&&r.push({type:`tool-call`,toolCallId:e.toolInvocation.toolCallId,toolName:e.toolInvocation.toolName,args:e.toolInvocation.args})}n({role:`assistant`,...l,type:r.some(e=>e.type===`tool-call`)?`tool-call`:`text`,content:typeof r!=`string`&&Array.isArray(r)&&r.length===1&&r[0]?.type===`text`?r[0].text:r});let a=i.filter(e=>`type`in e&&e.type===`tool-invocation`).map(e=>e.toolInvocation).filter(e=>e.toolName!==`updateWorkingMemory`).filter(e=>e.state===`result`&&`result`in e);a.length>0&&n({role:`tool`,...l,type:`tool-result`,content:a.map(e=>{let{toolCallId:t,toolName:n,result:r}=e;return{type:`tool-result`,toolCallId:t,toolName:n,result:r}})}),i=[],t=!1,e++}for(let n of r.content.parts)switch(n.type){case`text`:t&&a(),i.push(n);break;case`file`:case`reasoning`:i.push(n);break;case`tool-invocation`:(i.some(e=>e.type===`text`||e.type===`file`||e.type===`reasoning`)||(n.toolInvocation.step??0)!==e)&&a(),i.push(n),t=!0}a();let o=r.content.toolInvocations;if(o&&o.length>0){let e=new Set;for(let t of r.content.parts)t.type===`tool-invocation`&&t.toolInvocation.toolCallId&&e.add(t.toolInvocation.toolCallId);let t=o.filter(t=>!e.has(t.toolCallId)&&t.toolName!==`updateWorkingMemory`);if(t.length>0){let e=new Map;for(let n of t){let t=n.step??0;e.has(t)||e.set(t,[]),e.get(t).push(n)}let r=Array.from(e.keys()).sort((e,t)=>e-t);for(let t of r){let r=e.get(t);n({role:`assistant`,...l,type:`tool-call`,content:[...r.map(({toolCallId:e,toolName:t,args:n})=>({type:`tool-call`,toolCallId:e,toolName:t,args:n}))]});let i=r.filter(e=>e.state===`result`&&`result`in e);i.length>0&&n({role:`tool`,...l,type:`tool-result`,content:i.map(e=>{let{toolCallId:t,toolName:n,result:r}=e;return{type:`tool-result`,toolCallId:t,toolName:n,result:r}})})}}}break}let e=r.content.toolInvocations;if(e==null||e.length===0){n({role:`assistant`,...l,content:a||``,type:`text`});break}let t=e.reduce((e,t)=>Math.max(e,t.step??0),0);for(let r=0;r<=t;r++){let t=e.filter(e=>(e.step??0)===r&&e.toolName!==`updateWorkingMemory`);if(t.length===0)continue;n({role:`assistant`,...l,type:`tool-call`,content:[...i&&a&&r===0?[{type:`text`,text:a}]:[],...t.map(({toolCallId:e,toolName:t,args:n})=>({type:`tool-call`,toolCallId:e,toolName:t,args:n}))]});let o=t.filter(e=>e.state===`result`&&`result`in e);o.length>0&&n({role:`tool`,...l,type:`tool-result`,content:o.map(e=>{let{toolCallId:t,toolName:n,result:r}=e;return{type:`tool-result`,toolCallId:t,toolName:n,result:r}})})}a&&!i&&n({role:`assistant`,...l,type:`text`,content:a||``});break}}}return t}function OMe(e){if(e.protocol===`data:`){let t=e.pathname.indexOf(`,`);return`data:${t===-1?e.pathname:e.pathname.slice(0,t)},<${t===-1?0:e.pathname.length-t-1} chars>`}return`${e.origin}${e.pathname}`}var kMe=async({url:e,downloadRetries:t})=>{let n=e.toString(),r=OMe(e);try{let i=await Fke(n,{method:`GET`},e.protocol===`data:`?1:t,{shouldRetryResponse:e=>e.status>=500});if(!i.ok)throw new yn({id:`DOWNLOAD_ASSETS_FAILED`,text:`Failed to download asset: ${r}`,domain:gn.LLM,category:_n.USER,details:{url:n}});return{data:new Uint8Array(await i.arrayBuffer()),mediaType:i.headers.get(`content-type`)??void 0}}catch(e){throw new yn({id:`DOWNLOAD_ASSETS_FAILED`,text:`Failed to download asset: ${r}`,domain:gn.LLM,category:_n.USER,details:{url:n}},e)}};function AMe(e){let t=e.type===`image`?e.image:e.data;if(typeof t!=`string`)return t;try{return new URL(t)}catch{return t}}function jMe(e){let t=AMe(e);return t instanceof URL?t.toString():void 0}function MMe(e){return e instanceof yn&&e.id===`DOWNLOAD_ASSETS_FAILED`}async function NMe({messages:e,downloadConcurrency:t=10,downloadRetries:n=3,supportedUrls:r,cache:i,isUnavailable:a,onUnavailable:o}){let s=(await W(async()=>{let{default:e}=await import(`./p-map-D81h6UuU.js`);return{default:e}},[],import.meta.url)).default,c=(await s(e.filter(e=>e.role===`user`).map(e=>e.content).filter(e=>Array.isArray(e)).flat().filter(e=>e.type===`image`||e.type===`file`).map(e=>({mediaType:e.mediaType??(e.type===`image`?`image/*`:void 0),data:AMe(e)})).filter(e=>e.data instanceof URL).map(e=>({url:e.data,isUrlSupportedByModel:e.mediaType!=null&&Zfe({url:e.data.toString(),mediaType:e.mediaType,supportedUrls:r??{}})})),async e=>{let t=e.url.toString();if(e.isUrlSupportedByModel||a?.(t))return null;let r=i?.get(t);if(!r&&(r=kMe({url:e.url,downloadRetries:n}),i)){let e=r;i.set(t,e),e.catch(()=>{i.get(t)===e&&i.delete(t)})}try{return{url:t,...await r}}catch(e){if(!o||!MMe(e))throw e;return o(t,e),null}},{concurrency:t})).filter(e=>e?.data!=null).map(({url:e,data:t,mediaType:n})=>[e,{data:t,mediaType:n}]);return Object.fromEntries(c)}var t_=`unavailableAttachments`;function PMe(e){let t=e.content.metadata?.mastra;if(!t||typeof t!=`object`)return[];let n=t[t_];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function FMe(e,t){let n=e?.mastra??{},r=Array.isArray(n[t_])?n[t_]:[];return{...e,mastra:{...n,[t_]:[...new Set([...r,...t])]}}}function n_(e){if(e instanceof URL)return e.toString();if(!(typeof e!=`string`||e.startsWith(`data:`)))try{return new URL(e).toString()}catch{return}}function IMe(e){return`[Attachment unavailable: ${e}]`}function LMe(e){let t=new Set(PMe(e));if(e.role!==`user`||t.size===0)return e;let n=e=>{let n=n_(e);return n!==void 0&&t.has(n)},r=e=>({type:`text`,text:IMe(e)}),i=e.content.parts??[],a=e.content.experimental_attachments??[],o=new Set,s=i.map(e=>{if(e.type!==`file`)return e;let{mediaType:n,data:i}=_m(e),a=n_(i);return a===void 0||!t.has(a)?e:(o.add(a),r(e.filename||n||`file`))}),c=a.filter(e=>{let n=n_(e.url);return n!==void 0&&t.has(n)&&!o.has(n)}),l=a.filter(e=>n(e.url));if(o.size===0&&l.length===0)return e;let u=e.content.content,d=typeof u==`string`&&u&&!s.some(e=>e.type===`text`)?[{type:`text`,text:u}]:[];return{...e,content:{...e.content,parts:[...c.map(e=>r(e.name||e.contentType||`unknown`)),...d,...s],...l.length>0?{experimental_attachments:a.filter(e=>!n(e.url))}:{}}}}function RMe(e){let t=[];for(let n of e.content.parts??[]){if(n.type!==`file`)continue;let e=n_(_m(n).data);e&&t.push(e)}for(let n of e.content.experimental_attachments??[]){let e=n_(n.url);e&&t.push(e)}return t}function zMe(e){return{...e,createdAt:e.createdAt.toISOString()}}function BMe(e){return{...e,createdAt:new Date(e.createdAt)}}function VMe(e){return e.map(zMe)}function HMe(e){return e.map(BMe)}var UMe=class{memoryMessages=new Set;newUserMessages=new Set;newResponseMessages=new Set;userContextMessages=new Set;memoryMessagesPersisted=new Set;newUserMessagesPersisted=new Set;newResponseMessagesPersisted=new Set;userContextMessagesPersisted=new Set;addToSource(e,t){switch(t){case`memory`:this.memoryMessages.add(e),this.memoryMessagesPersisted.add(e);break;case`response`:this.memoryMessages.has(e)&&this.memoryMessages.delete(e),this.newResponseMessages.add(e),this.newResponseMessagesPersisted.add(e),this.newUserMessages.has(e)&&this.newUserMessages.delete(e);break;case`input`:case`user`:this.newUserMessages.add(e),this.newUserMessagesPersisted.add(e);break;case`context`:this.userContextMessages.add(e),this.userContextMessagesPersisted.add(e);break;default:throw Error(`Missing message source for message ${e}`)}}isMemoryMessage(e){return this.memoryMessages.has(e)}isUserMessage(e){return this.newUserMessages.has(e)}isResponseMessage(e){return this.newResponseMessages.has(e)}isContextMessage(e){return this.userContextMessages.has(e)}getMemoryMessages(){return this.memoryMessages}getUserMessages(){return this.newUserMessages}getResponseMessages(){return this.newResponseMessages}getContextMessages(){return this.userContextMessages}getMemoryMessagesPersisted(){return this.memoryMessagesPersisted}getUserMessagesPersisted(){return this.newUserMessagesPersisted}getResponseMessagesPersisted(){return this.newResponseMessagesPersisted}getContextMessagesPersisted(){return this.userContextMessagesPersisted}removeMessage(e){this.memoryMessages.delete(e),this.newUserMessages.delete(e),this.newResponseMessages.delete(e),this.userContextMessages.delete(e)}clearUserMessages(){this.newUserMessages.clear()}clearResponseMessages(){this.newResponseMessages.clear()}clearContextMessages(){this.userContextMessages.clear()}clearAll(){this.newUserMessages.clear(),this.newResponseMessages.clear(),this.userContextMessages.clear()}createSourceChecker(){let e={memory:new Set(Array.from(this.memoryMessages.values()).map(e=>e.id)),output:new Set(Array.from(this.newResponseMessages.values()).map(e=>e.id)),input:new Set(Array.from(this.newUserMessages.values()).map(e=>e.id)),context:new Set(Array.from(this.userContextMessages.values()).map(e=>e.id))};return{...e,getSource:t=>e.memory.has(t.id)?`memory`:e.input.has(t.id)?`input`:e.output.has(t.id)?`response`:e.context.has(t.id)?`context`:null}}isNewMessage(e){let t=typeof e==`string`?e:e.id;return typeof e!=`string`&&(this.newUserMessages.has(e)||this.newResponseMessages.has(e))?!0:Array.from(this.newUserMessages).some(e=>e.id===t)||Array.from(this.newResponseMessages).some(e=>e.id===t)}serializeSourceTracking(){let e=e=>Array.from(e).map(e=>e.id);return{memoryMessages:e(this.memoryMessages),newUserMessages:e(this.newUserMessages),newResponseMessages:e(this.newResponseMessages),userContextMessages:e(this.userContextMessages),memoryMessagesPersisted:e(this.memoryMessagesPersisted),newUserMessagesPersisted:e(this.newUserMessagesPersisted),newResponseMessagesPersisted:e(this.newResponseMessagesPersisted),userContextMessagesPersisted:e(this.userContextMessagesPersisted)}}deserializeSourceTracking(e,t){let n=e=>new Set(e.map(e=>t.find(t=>t.id===e)).filter(Boolean));this.memoryMessages=n(e.memoryMessages),this.newUserMessages=n(e.newUserMessages),this.newResponseMessages=n(e.newResponseMessages),this.userContextMessages=n(e.userContextMessages),this.memoryMessagesPersisted=n(e.memoryMessagesPersisted),this.newUserMessagesPersisted=n(e.newUserMessagesPersisted),this.newResponseMessagesPersisted=n(e.newResponseMessagesPersisted),this.userContextMessagesPersisted=n(e.userContextMessagesPersisted)}serializeAll(e){return{messages:VMe(e.messages),systemMessages:e.systemMessages,taggedSystemMessages:e.taggedSystemMessages,memoryInfo:e.memoryInfo,_agentNetworkAppend:e.agentNetworkAppend,...this.serializeSourceTracking()}}deserializeAll(e){let t=HMe(e.messages);return this.deserializeSourceTracking({memoryMessages:e.memoryMessages,newUserMessages:e.newUserMessages,newResponseMessages:e.newResponseMessages,userContextMessages:e.userContextMessages,memoryMessagesPersisted:e.memoryMessagesPersisted,newUserMessagesPersisted:e.newUserMessagesPersisted,newResponseMessagesPersisted:e.newResponseMessagesPersisted,userContextMessagesPersisted:e.userContextMessagesPersisted},t),{messages:t,systemMessages:e.systemMessages,taggedSystemMessages:e.taggedSystemMessages,memoryInfo:e.memoryInfo,agentNetworkAppend:e._agentNetworkAppend}}},r_={"partial-call":0,call:1,"approval-requested":2,"approval-responded":3,result:4,"output-error":4,"output-denied":4};function WMe(e){return r_[e]===r_.result}function GMe(e){return e===`approval-responded`||WMe(e)}function KMe(e,t){return!WMe(e)&&r_[t]>r_[e]}function qMe(e){return e.role===`system`&&e.parts.length>0&&e.parts.every(e=>e.type.startsWith(`data-`))}function JMe(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(!qMe(r)){t.push(r);continue}let i=t[t.length-1],a=e[n+1];i&&i.role===`assistant`?t[t.length-1]={...i,parts:[...i.parts,...r.parts]}:a&&a.role===`assistant`?e[n+1]={...a,parts:[...r.parts,...a.parts]}:t.push({...r,role:`assistant`})}return t}function YMe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function XMe(e,t){if(!e&&!t)return;let n={...e??{}};for(let[e,r]of Object.entries(t??{})){let t=n[e];n[e]=YMe(t)&&YMe(r)?{...t,...r}:r}return n}function ZMe(e,t){let n=new Map;for(let t of e.content.parts)t.type===`tool-invocation`&&n.set(t.toolInvocation.toolCallId,t);if(n.size===0)return t;let r=!1,i=t.content.parts.map(e=>{if(e.type!==`tool-invocation`)return e;let t=n.get(e.toolInvocation.toolCallId);if(!t||KMe(t.toolInvocation.state,e.toolInvocation.state))return e;let i=t.providerMetadata?.mastra?.backgroundTask,a=e.providerMetadata?.mastra?.backgroundTask;if(i?.status===`running`&&(a?.status===`completed`||a?.status===`failed`))return e;r=!0;let{toolCallId:o,toolName:s,args:c}=e.toolInvocation;return{type:`tool-invocation`,toolInvocation:{state:`call`,toolCallId:o,toolName:s,args:c}}});return r?{...t,content:{...t.content,parts:i}}:t}function QMe(e,t){let n=new Map;for(let t of e.content.parts)t.type===`tool-invocation`&&n.set(t.toolInvocation.toolCallId,t);let r=t.content.parts.flatMap(e=>{if(e.type!==`tool-invocation`)return[];let{state:t,toolCallId:r,result:i,errorText:a,approval:o}=e.toolInvocation,s=n.get(r);return!s||!GMe(t)||!KMe(s.toolInvocation.state,t)||s.providerExecuted&&t!==`approval-responded`?[]:[{type:`tool-invocation`,toolInvocation:{...s.toolInvocation,state:t,result:i,errorText:a,approval:o??s.toolInvocation.approval}}]});return{...t,content:{format:2,parts:r}}}function $Me(e,t,n,r){let i=e.indexOf(t);if(i!==-1)return i;let a=t.createdAt;if(a==null||r===void 0||r.messageId!==n)return-1;let o=e.flatMap((e,t)=>e.type===`step-start`&&e.createdAt!=null&&+e.createdAt==+a?[t]:[]);if(o.length!==1)return-1;let s=o[0],c=eNe(e,s),l=r.prefix;return c.length===l.length&&c.every((e,t)=>e[0]===l[t][0]&&e[1]===l[t][1])?s:-1}function eNe(e,t){let n=[];for(let r=0;r<t;r++){let t=e[r];t.type===`text`?n.push([t.type,t.text]):t.type===`tool-invocation`?n.push([t.type,t.toolInvocation?.toolCallId]):t.type===`reasoning`?n.push([t.type,t.reasoning]):n.push([t.type,void 0])}return n}var tNe=class e{messages=[];messageIndex;systemMessages=[];taggedSystemMessages={};memoryInfo=null;stateManager=new UMe;#e=new Map;#t=new Map;get memoryMessages(){return this.stateManager.getMemoryMessages()}get newUserMessages(){return this.stateManager.getUserMessages()}get newResponseMessages(){return this.stateManager.getResponseMessages()}get userContextMessages(){return this.stateManager.getContextMessages()}get memoryMessagesPersisted(){return this.stateManager.getMemoryMessagesPersisted()}get newUserMessagesPersisted(){return this.stateManager.getUserMessagesPersisted()}get newResponseMessagesPersisted(){return this.stateManager.getResponseMessagesPersisted()}get userContextMessagesPersisted(){return this.stateManager.getContextMessagesPersisted()}assetDownloads=new Map;unavailableAttachmentUpdates=new Map;generateMessageId;_agentNetworkAppend=!1;filterIncompleteToolCalls;logger;responseMessageSplits=new Map;toAIV5UIMessages(e,t){return JMe(e.map(e=>zg.toUIMessage(e,t)))}toAIV4UIMessages(e,t){return JMe(e.map(e=>Sg.toUIMessage(e,t)))}toAIV6UIMessages(e){return JMe(e.map(Wg.toUIMessage))}isRecording=!1;spanRecordings=new Map;recordedEvents=[];constructor({threadId:e,resourceId:t,generateMessageId:n,logger:r,filterIncompleteToolCalls:i,_agentNetworkAppend:a}={}){e&&(this.memoryInfo={threadId:e,resourceId:t}),this.generateMessageId=n,this.logger=r,this.filterIncompleteToolCalls=i??!0,this._agentNetworkAppend=a||!1}startRecording(e){e?this.spanRecordings.set(e,[]):(this.isRecording=!0,this.recordedEvents=[])}hasRecordedEvents(){return this.recordedEvents.length>0}getRecordedEvents(){return[...this.recordedEvents]}stopRecording(e){if(e){let t=this.spanRecordings.get(e)??[];return this.spanRecordings.delete(e),t}this.isRecording=!1;let t=this.getRecordedEvents();return this.recordedEvents=[],t}recordMutation(e){if(this.spanRecordings.size>0){let t;for(;t;){let n=this.spanRecordings.get(t);if(n){n.push(e);return}t=t.parent}}this.isRecording&&this.recordedEvents.push(e)}addSignal(e,t){let n=t?.source??`input`,r=e.metadata?.precedesMessageId,i=typeof r==`string`?this.getMessageById(r):void 0,a=i?new Date(i.createdAt.getTime()-1):this.generateCreatedAt(n,new Date),o=e.acceptedAt??e.createdAt,s={id:e.id,tagName:e.tagName,contents:e.contents,attributes:e.attributes,metadata:e.metadata,author:e.author,providerOptions:e.providerOptions,createdAt:a,acceptedAt:o},c=e.type===`state`?Spe({...s,type:e.type}):Spe({...s,type:e.type,transient:e.transient}),l=c.toDBMessage(this.memoryInfo??void 0);return c.type!==`state`&&c.transient&&this.removeMatchingTransientSignals(l),this.addOne(l,n),c}removeMatchingTransientSignals(e){let t=e.content.metadata?.signal,n=e=>JSON.stringify(e.map(e=>({...e,createdAt:void 0}))),r=n(e.content.parts);for(let i=this.messages.length-1;i>=0;i--){let a=this.messages[i];if(!epe(a))continue;let o=a.content.metadata?.signal,s=a.id===e.id,c=!!t&&!!o&&o.type===t.type&&o.tagName===t.tagName&&n(a.content.parts)===r;(s||c)&&(this.messages.splice(i,1),this.stateManager.removeMessage(a))}}add(e,t,n={}){if(t===`user`&&(t=`input`),!e)return this;let r=Array.isArray(e)?e:[e];this.recordMutation({type:`add`,source:t,count:r.length});for(let e of r){if(xpe(e)&&t===`input`){this.addSignal(e,{source:t});continue}let r=xpe(e)?e.toDBMessage(this.memoryInfo??void 0):typeof e==`string`?{role:`user`,content:e}:e;if(Array.isArray(r))for(let e of r)this.addOne(typeof e==`string`?{role:`user`,content:e}:e,t,n);else this.addOne(typeof r==`string`?{role:`user`,content:r}:r,t,n)}return this.moveLiveMessagesPastStoredTies(),this}serialize(){let e=this.stateManager.serializeAll({messages:this.messages,systemMessages:this.systemMessages,taggedSystemMessages:this.taggedSystemMessages,memoryInfo:this.memoryInfo,agentNetworkAppend:this._agentNetworkAppend}),t=this.#c(),n=this.#a();return{...e,...t?{lastStepBoundary:t}:{},...n.length>0?{prunedResponseMessageIds:n}:{},...this.#t.size>0?{embeddedMessages:Object.fromEntries(this.#t)}:{}}}getEmbeddedMessages(){return this.#t}serializeForSpan(){return{messages:this.all.aiV4.core().map(e=>({role:e.role,content:e.content})),systemMessages:[...this.systemMessages.map(e=>({role:e.role,content:e.content})),...Object.entries(this.taggedSystemMessages).flatMap(([e,t])=>t.map(t=>({role:t.role,content:t.content,tag:e})))]}}deserialize(e){let t=this.stateManager.deserializeAll(e);this.messages=t.messages,this.systemMessages=t.systemMessages,this.taggedSystemMessages=t.taggedSystemMessages,this.memoryInfo=t.memoryInfo,this._agentNetworkAppend=t.agentNetworkAppend,this.responseMessageSplits.clear();for(let e of this.messages)this.updateLastCreatedAt(e);this.#e=new Map((e.prunedResponseMessageIds??[]).map(e=>[e,void 0]));for(let[t,n]of Object.entries(e.embeddedMessages??{}))this.#t.set(t,n);if(this.#s=void 0,e.lastStepBoundary){let{messageId:t,partIndex:n}=e.lastStepBoundary,r=this.messages.find(e=>e.id===t)?.content.parts,i=r?.[n];r&&i?.type===`step-start`&&(this.#l(t,r,i),this.#s=i)}return this}clone(){return new e({generateMessageId:this.generateMessageId,logger:this.logger,filterIncompleteToolCalls:this.filterIncompleteToolCalls}).deserialize(this.serialize())}cloneForPersistence(){if(this.responseMessageSplits.size===0)return this;let e=this.clone();for(let[t,n]of this.responseMessageSplits)e.coalesceSplitResponseMessages(n,t);return e}get promptConversionMode(){return this.filterIncompleteToolCalls?`prompt`:`prompt-with-suspended`}get dropsIncompleteToolCalls(){return this.filterIncompleteToolCalls}getMessagesForModelPrompt(){return this.messages.flatMap(e=>e.role===`signal`?this.convertSignalForModelPrompt(e):[e])}convertSignalForModelPrompt(e){let t=Cpe(e).toLLMMessage(),n=e.createdAt;return[nMe({...t,id:e.id,metadata:{createdAt:n}},`input`,{memoryInfo:this.memoryInfo,newMessageId:()=>e.id,generateCreatedAt:(e,t)=>t instanceof Date?t:typeof t==`string`||typeof t==`number`?new Date(t):n,dbMessages:this.messages})]}makeMessageSourceChecker(){return this.stateManager.createSourceChecker()}getRememberedAndInputMessageIds(){return new Set([...this.memoryMessagesPersisted,...this.newUserMessagesPersisted].map(e=>e.id))}getLatestUserContent(){let e=this.all.core().filter(e=>e.role===`user`).at(-1)?.content;return e?Xje(e):null}get get(){return{all:this.all,remembered:this.remembered,input:this.input,response:this.response}}get getPersisted(){return{remembered:this.rememberedPersisted,input:this.inputPersisted,taggedSystemMessages:this.taggedSystemMessages,response:this.responsePersisted}}get clear(){return{all:{db:()=>{let e=[...this.messages];return this.messages=[],this.stateManager.clearAll(),e.length>0&&this.recordMutation({type:`clear`,count:e.length}),e}},input:{db:()=>{let e=Array.from(this.stateManager.getUserMessages());return this.messages=this.messages.filter(e=>!this.stateManager.isUserMessage(e)),this.stateManager.clearUserMessages(),e.length>0&&this.recordMutation({type:`clear`,source:`input`,count:e.length}),e}},response:{db:()=>{let e=Array.from(this.stateManager.getResponseMessages());return this.messages=this.messages.filter(e=>!this.stateManager.isResponseMessage(e)),this.stateManager.clearResponseMessages(),e.length>0&&this.recordMutation({type:`clear`,source:`response`,count:e.length}),e}}}}removeByIds(e,t){let n=new Set(e),r=[],i=this.newResponseMessagesPersisted;return this.messages=this.messages.filter(e=>!n.has(e.id)||(r.push(e),t?.pruned&&i.has(e)?this.#e.set(e.id,e):t?.pruned||this.#e.delete(e.id),this.stateManager.removeMessage(e),!1)),r.length>0&&this.recordMutation({type:`removeByIds`,ids:e,count:r.length}),r}splitResponseMessageAtPartOffset(e,t){let n=this.messages.findIndex(t=>t.id===e),r=this.messages[n],i=r?.content.parts;if(!r||!this.stateManager.isResponseMessage(r)||!i||t<=0||t>=i.length)return;let a=e=>{let t={...r.content,parts:e};if(typeof t.content==`string`&&(t.content=e.reduce((e,t)=>t.type===`text`?t.text:e,``)),Array.isArray(t.toolInvocations)){let n=new Set(e.flatMap(e=>e.type===`tool-invocation`&&e.toolInvocation?[e.toolInvocation.toolCallId]:[]));t.toolInvocations=t.toolInvocations.filter(e=>n.has(e.toolCallId))}return t},o=e,s=this.newMessageId(r.role),c={...r,id:s,content:a(i.slice(t))};r.content=a(i.slice(0,t)),this.messages.splice(n,1,r,c);let l=this.#e,u=this.serialize();for(let t of[`newResponseMessages`,`newResponseMessagesPersisted`])u[t]=u[t].flatMap(t=>t===e?[o,s]:[t]);this.deserialize(u);for(let[e,t]of this.#e)t===void 0&&this.#e.set(e,l.get(e));return this.responseMessageSplits.set(s,o),{earlierMessageId:o,currentMessageId:s}}coalesceSplitResponseMessages(e,t){this.responseMessageSplits.delete(t);let n=this.messages.findIndex(t=>t.id===e),r=this.messages.findIndex(e=>e.id===t),i=this.messages[n],a=this.messages[r];if(!i){a&&(a.id=e);return}if(!a)return;let o=[...i.content.parts??[],...a.content.parts??[]],s={...i.content,...a.content,parts:o};if((typeof i.content.content==`string`||typeof a.content.content==`string`)&&(s.content=o.reduce((e,t)=>t.type===`text`?t.text:e,``)),Array.isArray(i.content.toolInvocations)||Array.isArray(a.content.toolInvocations)){let e=[...i.content.toolInvocations??[],...a.content.toolInvocations??[]],t=new Set(o.flatMap(e=>e.type===`tool-invocation`&&e.toolInvocation?[e.toolInvocation.toolCallId]:[]));s.toolInvocations=e.filter((n,r)=>t.has(n.toolCallId)&&e.findIndex(e=>e.toolCallId===n.toolCallId)===r)}i.content=s,this.messages.splice(Math.max(n,r),1),this.messages.splice(Math.min(n,r),1,i),this.stateManager.removeMessage(a)}rollbackToStepBoundary(e,t){let n=this.messages.find(t=>t.id===e);if(!n)return!1;let r=n.content?.parts;if(!r)return this.removeByIds([e]),!0;let i=t?$Me(r,t,e,this.#o.get(t)):-1;return i===-1?(this.removeByIds([e]),!0):(this.#n(n,i),!0)}#n(e,t){let n=e.content.parts;if(n.splice(t),n.length===0)this.removeByIds([e.id]);else{if(Array.isArray(e.content.toolInvocations)){let t=new Set(n.flatMap(e=>e.type===`tool-invocation`&&e.toolInvocation?[e.toolInvocation.toolCallId]:[]));e.content.toolInvocations=e.content.toolInvocations.filter(e=>t.has(e.toolCallId))}if(typeof e.content.content==`string`){let t=``;for(let e of n)e.type===`text`&&(t=e.text);e.content.content=t}e.content.metadata&&delete e.content.metadata.structuredOutput,this.stateManager.isResponseMessage(e)||(this.stateManager.removeMessage(e),this.stateManager.addToSource(e,`response`))}}#r;#i;markStepCompleted(){this.#r=new Map(this.get.response.db().map(e=>[e.id,e.content.parts?.length??0])),this.#i=new Map(this.get.response.db().flatMap(e=>e.content.metadata?.structuredOutput===void 0?[]:[[e.id,e.content.metadata.structuredOutput]]))}cloneWithCompletedSteps(e=``){let t=this.clone(),n=()=>(t.add({role:`assistant`,content:[{type:`text`,text:e}]},`response`,{merge:!1}),t.get.response.db().at(-1).id),r=this.#r,i=t.get.response.db().flatMap(e=>(e.content.parts??[]).slice(r?.get(e.id)??0)),a=i.filter(e=>e.type===`tool-invocation`);if(a.length>0&&a.every(e=>WMe(e.toolInvocation.state))){let r=i.flatMap(e=>e.type===`text`?[e.text]:[]).join(``);return e.trim().length>0&&!r.includes(e.trim())?{turn:t,inFlightMessageId:n()}:{turn:t}}for(let e of t.get.response.db()){let n=r?.get(e.id);if(n===void 0)t.removeByIds([e.id]);else if((e.content.parts?.length??0)>n){e.content={...e.content,parts:[...e.content.parts],...e.content.metadata?{metadata:{...e.content.metadata}}:{}},t.#n(e,n);let r=this.#i?.get(e.id);r!==void 0&&(e.content.metadata={...e.content.metadata,structuredOutput:r})}}return e.trim().length>0?{turn:t,inFlightMessageId:n()}:{turn:t}}all={db:()=>this.messages,v1:()=>e_(this.all.db()),aiV5:{model:()=>{let e=this.getMessagesForModelPrompt();return Qg(this.toAIV5UIMessages(e,{transformToolPayloads:!1}),e)},ui:()=>this.toAIV5UIMessages(this.all.db()),prompt:()=>{let e=SMe([...this.systemMessages,...Object.values(this.taggedSystemMessages).flat()],`system`,this.createAdapterContext(),this.messages),t=this.getMessagesForModelPrompt(),n=Qg(this.toAIV5UIMessages(t,{transformToolPayloads:!1}),t,this.promptConversionMode);return[...e,...n]},llmPrompt:async(e={downloadConcurrency:10,downloadRetries:3})=>{let t=this.getMessagesForModelPrompt().map(LMe),n=Qg(this.toAIV5UIMessages(t,{transformToolPayloads:!1}),t,this.promptConversionMode),r=new Map;for(let e of this.messages)if(e.content?.format===2&&e.content.parts)for(let t of e.content.parts)t.type===`tool-invocation`&&t.toolInvocation?.state===`result`&&t.providerMetadata?.mastra&&typeof t.providerMetadata.mastra==`object`&&Object.hasOwn(t.providerMetadata.mastra,`modelOutput`)&&t.providerMetadata.mastra.modelOutput!=null&&r.set(t.toolInvocation.toolCallId,t.providerMetadata.mastra.modelOutput);if(r.size>0){for(let e of n)if(e.role===`tool`&&Array.isArray(e.content))for(let t=0;t<e.content.length;t++){let n=e.content[t];n.type===`tool-result`&&r.has(n.toolCallId)&&(e.content[t]={...n,output:r.get(n.toolCallId)})}}let i=SMe([...this.systemMessages,...Object.values(this.taggedSystemMessages).flat()],`system`,this.createAdapterContext(),this.messages),a=new Set,o=await NMe({messages:n,downloadConcurrency:e?.downloadConcurrency,downloadRetries:e?.downloadRetries,supportedUrls:e?.supportedUrls,cache:this.assetDownloads,isUnavailable:e=>e.startsWith(`data:`)&&!Wpe(e),onUnavailable:(t,n)=>{let r=t.startsWith(`data:`);if(!r&&!e?.skipUnavailableAttachments)throw n;a.add(t),r||this.recordUnavailableAttachment(t),this.logger?.warn(`Skipping an attachment that could not be downloaded: ${n.message}`)}}),s=[...i,...n];return n.some(e=>(e.role===`user`||e.role===`assistant`)&&typeof e.content!=`string`&&e.content.some(e=>e.type===`image`||e.type===`file`))&&(s=s.map(e=>{if(e.role===`user`)return typeof e.content==`string`?{role:`user`,content:[{type:`text`,text:e.content}],providerOptions:e.providerOptions}:{role:`user`,content:e.content.map(e=>{if(e.type===`image`||e.type===`file`){let t=jMe(e),n=e.type===`image`?e.image:e.data,r=typeof n==`string`&&!Wpe(n,e.mediaType);if(r){let t=n.startsWith(`data:`)?`${n.slice(0,n.indexOf(`,`)+1)}<${n.length} chars>`:`${e.mediaType??e.type} <${n.length} chars>`;this.logger?.warn(`Skipping an attachment that is not a URL or valid file content: ${t}`)}return r||t&&a.has(t)?{type:`text`,text:IMe(e.type===`file`&&e.filename||e.mediaType||e.type)}:TMe(e,o)}return e}).filter(e=>e.type!==`text`||e.text!==``),providerOptions:e.providerOptions};if(e.role===`assistant`&&typeof e.content!=`string`){let t=e.content.map(e=>e.type===`file`?TMe(e,o):e);return{...e,content:t}}return e})),s=qke(s,this.messages,e.targetProvider,this.logger),s.filter(e=>e!=null).map(Ype).filter(e=>e.role===`system`||typeof e.content==`string`||e.content.length>0)}},aiV6:{ui:()=>this.toAIV6UIMessages(this.all.db()),llmPrompt:async e=>Qpe(await this.all.aiV5.llmPrompt(e))},aiV7:{ui:()=>this.toAIV6UIMessages(this.all.db()),llmPrompt:async e=>eme(await this.all.aiV5.llmPrompt(e))},prompt:()=>this.all.aiV4.prompt(),ui:()=>this.toAIV4UIMessages(this.all.db()),core:()=>Zg(this.toAIV4UIMessages(this.all.db(),{transformToolPayloads:!1})),aiV4:{ui:()=>this.toAIV4UIMessages(this.all.db()),core:()=>Zg(this.toAIV4UIMessages(this.getMessagesForModelPrompt(),{transformToolPayloads:!1})),prompt:()=>{let e=this.all.aiV4.core();return[...this.systemMessages,...Object.values(this.taggedSystemMessages).flat(),...e]},llmPrompt:()=>{let e=this.all.aiV4.core();return[...this.systemMessages,...Object.values(this.taggedSystemMessages).flat(),...e].map(Jpe)}}};remembered={db:()=>this.messages.filter(e=>this.memoryMessages.has(e)),v1:()=>e_(this.remembered.db()),aiV5:{model:()=>Qg(this.toAIV5UIMessages(this.remembered.db(),{transformToolPayloads:!1}),this.messages),ui:()=>this.toAIV5UIMessages(this.remembered.db())},aiV6:{ui:()=>this.toAIV6UIMessages(this.remembered.db())},ui:()=>this.toAIV4UIMessages(this.remembered.db()),core:()=>Zg(this.toAIV4UIMessages(this.remembered.db(),{transformToolPayloads:!1})),aiV4:{ui:()=>this.toAIV4UIMessages(this.remembered.db()),core:()=>Zg(this.toAIV4UIMessages(this.remembered.db(),{transformToolPayloads:!1}))}};rememberedPersisted={db:()=>this.all.db().filter(e=>this.memoryMessagesPersisted.has(e)),v1:()=>e_(this.rememberedPersisted.db()),aiV5:{model:()=>Qg(this.toAIV5UIMessages(this.rememberedPersisted.db(),{transformToolPayloads:!1}),this.messages),ui:()=>this.toAIV5UIMessages(this.rememberedPersisted.db())},aiV6:{ui:()=>this.toAIV6UIMessages(this.rememberedPersisted.db())},ui:()=>this.toAIV4UIMessages(this.rememberedPersisted.db()),core:()=>Zg(this.toAIV4UIMessages(this.rememberedPersisted.db(),{transformToolPayloads:!1})),aiV4:{ui:()=>this.toAIV4UIMessages(this.rememberedPersisted.db()),core:()=>Zg(this.toAIV4UIMessages(this.rememberedPersisted.db(),{transformToolPayloads:!1}))}};input={db:()=>this.messages.filter(e=>this.newUserMessages.has(e)),v1:()=>e_(this.input.db()),aiV5:{model:()=>Qg(this.toAIV5UIMessages(this.input.db(),{transformToolPayloads:!1}),this.messages),ui:()=>this.toAIV5UIMessages(this.input.db())},aiV6:{ui:()=>this.toAIV6UIMessages(this.input.db())},ui:()=>this.toAIV4UIMessages(this.input.db()),core:()=>Zg(this.toAIV4UIMessages(this.input.db(),{transformToolPayloads:!1})),aiV4:{ui:()=>this.toAIV4UIMessages(this.input.db()),core:()=>Zg(this.toAIV4UIMessages(this.input.db(),{transformToolPayloads:!1}))}};inputPersisted={db:()=>this.messages.filter(e=>this.newUserMessagesPersisted.has(e)),v1:()=>e_(this.inputPersisted.db()),aiV5:{model:()=>Qg(this.toAIV5UIMessages(this.inputPersisted.db(),{transformToolPayloads:!1}),this.messages),ui:()=>this.toAIV5UIMessages(this.inputPersisted.db())},aiV6:{ui:()=>this.toAIV6UIMessages(this.inputPersisted.db())},ui:()=>this.toAIV4UIMessages(this.inputPersisted.db()),core:()=>Zg(this.toAIV4UIMessages(this.inputPersisted.db(),{transformToolPayloads:!1})),aiV4:{ui:()=>this.toAIV4UIMessages(this.inputPersisted.db()),core:()=>Zg(this.toAIV4UIMessages(this.inputPersisted.db(),{transformToolPayloads:!1}))}};response={db:()=>this.messages.filter(e=>this.newResponseMessages.has(e)),v1:()=>e_(this.response.db()),aiV5:{ui:()=>this.toAIV5UIMessages(this.response.db()),model:()=>Qg(this.toAIV5UIMessages(this.response.db(),{transformToolPayloads:!1}),this.messages).filter(e=>e.role===`tool`||e.role===`assistant`),modelContent:(e,t)=>typeof e==`number`?wMe.extractStepContent(this.response.aiV5.ui(),e,this.response.aiV5.stepContent,t):this.response.aiV5.model().map(this.response.aiV5.stepContent).flat(),stepContent:e=>wMe.convertToStepContent(e,this.messages,()=>this.response.aiV5.model().at(-1))},aiV6:{ui:()=>this.toAIV6UIMessages(this.response.db())},aiV4:{ui:()=>this.toAIV4UIMessages(this.response.db()),core:()=>Zg(this.toAIV4UIMessages(this.response.db(),{transformToolPayloads:!1}))}};#a(){if(this.#e.size===0)return[];let e=new Set(this.responsePersisted.db().map(e=>e.id));return Array.from(this.#e.keys()).filter(t=>!e.has(t))}async getRunResponseMessages(e){let t=this.responsePersisted.db(),n=this.#a();if(n.length===0)return t;let r=[],i=[];for(let e of n){let t=this.#e.get(e);t?r.push(t):i.push(e)}if(i.length>0&&e){let t=new Set(i),n=await e(i)??[];r.push(...n.filter(e=>t.has(e.id)))}return[...r,...t].sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime())}responsePersisted={db:()=>this.messages.filter(e=>this.newResponseMessagesPersisted.has(e)),aiV5:{model:()=>Qg(this.toAIV5UIMessages(this.responsePersisted.db(),{transformToolPayloads:!1}),this.messages),ui:()=>this.toAIV5UIMessages(this.responsePersisted.db())},aiV6:{ui:()=>this.toAIV6UIMessages(this.responsePersisted.db())},ui:()=>this.toAIV4UIMessages(this.responsePersisted.db()),aiV4:{ui:()=>this.toAIV4UIMessages(this.responsePersisted.db()),core:()=>Zg(this.toAIV4UIMessages(this.responsePersisted.db(),{transformToolPayloads:!1}))}};recordUnavailableAttachment(e){for(let t of this.messages){if(t.role!==`user`||PMe(t).includes(e)||!RMe(t).includes(e))continue;t.content.metadata=FMe(t.content.metadata,[e]);let n=this.unavailableAttachmentUpdates.get(t.id)??new Set;n.add(e),this.unavailableAttachmentUpdates.set(t.id,n)}}drainUnavailableAttachmentUpdates(){let e=[...this.unavailableAttachmentUpdates].map(([e,t])=>({messageId:e,urls:[...t]}));return this.unavailableAttachmentUpdates.clear(),e}drainUnsavedMessages(){return this.drainUnsavedMessagesForSave().messages}drainUnsavedMessagesForSave(){let e=[...this.newUserMessages],t=[...this.newResponseMessages],n=this.messages.filter(e=>this.newUserMessages.has(e)||this.newResponseMessages.has(e));return this.newUserMessages.clear(),this.newResponseMessages.clear(),{messages:n.map(e=>this.transformMessageForTranscript(e)),restore:()=>{for(let t of e)this.messages.includes(t)&&this.newUserMessages.add(t);for(let e of t)this.messages.includes(e)&&this.newResponseMessages.add(e)}}}transformMessagesForTranscript(e){return e.map(e=>this.transformMessageForTranscript(e))}transformToolStateDataForTranscript(e,t){if(!e||typeof e!=`object`)return e;let n=e,r=n.metadata??n.providerMetadata,i=lm(r,`transcript`,t),a=lm(r,`transcript`,`input-available`),o=t===`approval`?um(i)?i.transformed:um(a)?a.transformed:void 0:um(a)?a.transformed:um(i)?i.transformed:void 0,s=t===`suspend`&&um(i)?i.transformed:void 0;return{...n,...o===void 0?{}:{args:o},...s===void 0?{}:{suspendPayload:s}}}transformMessageForTranscript(e){if(e.content?.format!==2||!e.content.parts)return e;let t=!1,n=new Map,r=e.content.parts.map(e=>{if(e.type===`tool-invocation`&&e.toolInvocation){let r=lm(e.providerMetadata,`transcript`,`input-available`),i=e.toolInvocation.state===`output-error`&&e.toolInvocation.result!==void 0&&e.providerExecuted===!0,a=e.toolInvocation.state===`result`||i?lm(e.providerMetadata,`transcript`,`output-available`)??lm(e.providerMetadata,`transcript`,`error`):e.toolInvocation.state===`output-error`?lm(e.providerMetadata,`transcript`,`error`):void 0;if(!r&&!a)return e;t=!0;let o=um(r)?r.transformed:e.toolInvocation.args,s=e.toolInvocation.state===`result`?um(a)?a.transformed:e.toolInvocation.result:void 0,c=i?um(a)?a.transformed:e.toolInvocation.result:void 0,l=e.toolInvocation.state===`output-error`?i&&um(a)?typeof c==`string`?c:dm(c):um(a)?a.transformed:e.toolInvocation.errorText:void 0;return n.set(e.toolInvocation.toolCallId,{args:o,...e.toolInvocation.state===`result`?{result:s}:{},...e.toolInvocation.state===`output-error`?{errorText:l,...i?{result:c}:{}}:{}}),{...e,toolInvocation:{...e.toolInvocation,args:o,...e.toolInvocation.state===`result`?{result:s}:{},...e.toolInvocation.state===`output-error`?{errorText:l,...i?{result:c}:{}}:{}}}}return e.type===`data-tool-call-suspended`||e.type===`data-tool-call-approval`?(t=!0,{...e,data:this.transformToolStateDataForTranscript(e.data,e.type===`data-tool-call-suspended`?`suspend`:`approval`)}):e}),i=e.content.toolInvocations?.map(e=>{let r=n.get(e.toolCallId);if(!r)return e;let i=e.state;return t=!0,{...e,...r.args===void 0?{}:{args:r.args},...(e.state===`result`||i===`output-error`)&&`result`in r?{result:r.result}:{},...i===`output-error`&&r.errorText!==void 0?{errorText:r.errorText}:{}}}),a=e.content.metadata&&typeof e.content.metadata==`object`?{...e.content.metadata}:e.content.metadata;if(a&&typeof a==`object`)for(let[e,n]of[[`suspendedTools`,`suspend`],[`pendingToolApprovals`,`approval`]]){let r=a[e];r&&typeof r==`object`&&(t=!0,a[e]=Object.fromEntries(Object.entries(r).map(([e,t])=>[e,this.transformToolStateDataForTranscript(t,n)])))}return t?{...e,content:{...e.content,parts:r,...i?{toolInvocations:i}:{},...a?{metadata:a}:{}}}:e}getEarliestUnsavedMessageTimestamp(){let e=this.messages.filter(e=>this.newUserMessages.has(e)||this.newResponseMessages.has(e));if(e.length!==0)return Math.min(...e.map(e=>new Date(e.createdAt).getTime()))}isNewMessage(e){return this.stateManager.isNewMessage(e)}updateToolInvocation(e,t){if(!e.toolInvocation?.toolCallId)return!1;let n=e.toolInvocation.toolCallId;for(let r=this.messages.length-1;r>=0;r--){let i=this.messages[r];if(i.role===`assistant`&&i.content?.parts)for(let r=0;r<i.content.parts.length;r++){let a=i.content.parts[r];if(a?.type===`tool-invocation`&&a.toolInvocation?.toolCallId===n)return this.mergeToolResultIntoPart(i,r,e,t),!0}}let r=e.toolInvocation.toolName;for(let i=this.messages.length-1;i>=0;i--){let a=this.messages[i];if(a.role===`assistant`&&a.content?.parts)for(let i=0;i<a.content.parts.length;i++){let o=a.content.parts[i];if(o?.type!==`tool-invocation`)continue;let s=o;if(s.providerExecuted===!0&&s.toolInvocation?.state===`call`&&s.toolInvocation.toolName===r){let r=s.toolInvocation.toolCallId;return s.toolInvocation.toolCallId=n,this.mergeToolResultIntoPart(a,i,e,t,r),!0}}}return this.logger?.warn(`updateToolInvocation: no matching tool call found for toolCallId=${n}`),!1}updateMessageMetadataByToolCallId(e,t){if(!e)return!1;for(let n=this.messages.length-1;n>=0;n--){let r=this.messages[n];if(r.role!==`assistant`||!r.content?.parts||!r.content.parts.some(t=>t?.type===`tool-invocation`&&t.toolInvocation?.toolCallId===e))continue;let i=r.content.metadata??{},a=t??{},o=i.backgroundTasks,s=a.backgroundTasks,c=XMe(o,s);return r.content.metadata={...i,...a,...c?{backgroundTasks:c}:{}},this.lastCreatedAt=Math.max(this.lastCreatedAt||0,Date.now()),this.updateLastCreatedAt(r),this.stateManager.isResponseMessage(r)||(this.stateManager.removeMessage(r),this.stateManager.addToSource(r,`response`)),!0}return this.logger?.warn(`updateMessageMetadataByToolCallId: no matching tool call found for toolCallId=${e}`),!1}addOutputErrorsToProviderToolCalls(e,t,n){if(!e||!t?.length)return!1;let r=new Set(t),i=n??`Provider tool call did not complete: the model stream terminated with an error.`,a=this.messages.find(t=>t.id===e&&t.role===`assistant`);if(!a?.content?.parts)return!1;let o=!1,s=[];for(let e=0;e<a.content.parts.length;e++){let t=a.content.parts[e];if(t?.type!==`tool-invocation`)continue;let n=t,c=n.toolInvocation?.state;n.providerExecuted!==!0||!r.has(n.toolInvocation?.toolCallId)||c!==`call`&&c!==`partial-call`||(n.toolInvocation={...n.toolInvocation,state:`output-error`,errorText:i},s.push(n.toolInvocation.toolCallId),o=!0)}return o?(Array.isArray(a.content.toolInvocations)&&(a.content.toolInvocations=a.content.toolInvocations.filter(e=>!s.includes(e.toolCallId))),this.lastCreatedAt=Math.max(this.lastCreatedAt||0,Date.now()),this.updateLastCreatedAt(a),this.stateManager.isResponseMessage(a)||(this.stateManager.removeMessage(a),this.stateManager.addToSource(a,`response`)),!0):!1}mergeToolResultIntoPart(e,t,n,r,i){let a=e.content.parts[t],o=i??a.toolInvocation.toolCallId,s=a,c=n,l=s.providerMetadata!==void 0||c.providerMetadata!==void 0?(()=>{let e=s.providerMetadata??{},t=c.providerMetadata??{},n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=t&&typeof t==`object`&&!Array.isArray(t)&&r&&typeof r==`object`&&!Array.isArray(r)?{...t,...r}:r}return Hke(e,t,n)})():void 0,u={...n,toolInvocation:{...n.toolInvocation,args:a.toolInvocation.args},...s.providerExecuted!==void 0&&c.providerExecuted===void 0?{providerExecuted:s.providerExecuted}:{},...a.title!==void 0&&n.title===void 0?{title:a.title}:{},...l===void 0?{}:{providerMetadata:l}};a.updatedAt!==void 0&&u.updatedAt===void 0&&(u.updatedAt=a.updatedAt),tMe(u,a.toolInvocation,n.updatedAt),e.content.parts[t]=u;let d=e.content.metadata??{},f=r??{},p=d.backgroundTasks,m=f.backgroundTasks,h=XMe(p,m);if(e.content.metadata={...d,...f,...h?{backgroundTasks:h}:{}},Array.isArray(e.content.toolInvocations)&&(n.toolInvocation.state===`result`||n.toolInvocation.state===`output-error`&&(c.providerExecuted??s.providerExecuted)===!0)){let t=n.toolInvocation;e.content.toolInvocations=e.content.toolInvocations.map(e=>e.toolCallId===o?{...e,toolCallId:t.toolCallId,state:`result`,args:a.toolInvocation.args,result:t.result}:e)}this.lastCreatedAt=Math.max(this.lastCreatedAt||0,Date.now()),this.updateLastCreatedAt(e),this.stateManager.isResponseMessage(e)||(this.stateManager.removeMessage(e),this.stateManager.addToSource(e,`response`))}stepStart(){return this.openStepBoundary().appended}openStepBoundary(){let e=this.messages[this.messages.length-1];if(!e||e.role!==`assistant`||!e.content?.parts||$g.isSealed(e))return{appended:!1};let t=e.content.parts[e.content.parts.length-1],n=t?.type!==`step-start`,r=eMe(n?{type:`step-start`}:t);return n&&e.content.parts.push(r),this.#l(e.id,e.content.parts,r),this.#s=r,this.stateManager.isResponseMessage(e)||(this.stateManager.removeMessage(e),this.stateManager.addToSource(e,`response`)),{boundary:r,appended:n}}#o=new WeakMap;#s;partsSinceStepBoundary(e){let t=e.content.parts??[],n=this.#s;if(!n)return t;let r=$Me(t,n,e.id,this.#o.get(n));return r===-1?t:t.slice(r+1)}#c(){let e=this.#s;if(!e)return;let t=this.#o.get(e);for(let n of this.messages){let r=$Me(n.content.parts??[],e,n.id,t);if(r!==-1)return{messageId:n.id,partIndex:r}}}#l(e,t,n){let r=t.indexOf(n);r!==-1&&this.#o.set(n,{messageId:e,prefix:eNe(t,r)})}rotateResponseMessageId(e){return this.markResponseMessageBoundary(e)||this.markResponseMessageBoundary(),this.newMessageId(`assistant`)}markResponseMessageBoundary(e){let t=e?this.messages.find(t=>t.id===e):[...this.messages].reverse().find(e=>e.role===`assistant`);return!t||t.role!==`assistant`?!1:(t.content.metadata={...t.content.metadata??{},mastra:{...t.content.metadata?.mastra??{},responseBoundary:!0}},this.stateManager.isResponseMessage(t)||(this.stateManager.removeMessage(t),this.stateManager.addToSource(t,`response`)),!0)}enrichLastStepStart(e){let t=this.messages[this.messages.length-1];if(!t||t.role!==`assistant`||!t.content?.parts||$g.isSealed(t))return!1;for(let n=t.content.parts.length-1;n>=0;n--){let r=t.content.parts[n];if(r?.type===`step-start`)return!r.model&&(r.model=e,this.stateManager.isResponseMessage(t)||(this.stateManager.removeMessage(t),this.stateManager.addToSource(t,`response`)),!0)}return!1}getSystemMessages(e){return e?this.taggedSystemMessages[e]||[]:this.systemMessages}getAllSystemMessages(){return[...this.systemMessages,...Object.values(this.taggedSystemMessages).flat()]}clearSystemMessages(e){return e?delete this.taggedSystemMessages[e]:this.systemMessages=[],this}replaceAllSystemMessages(e){this.systemMessages=[];for(let t of e)t.role===`system`&&this.systemMessages.push(t);return this}addSystem(e,t){if(!e)return this;for(let n of Array.isArray(e)?e:[e])this.addOneSystem(n,t);return this}addOneSystem(e,t){let n=CMe(e);if(n.role!==`system`)throw Error(`Expected role "system" but saw ${n.role} for message ${JSON.stringify(n,null,2)}`);t&&!this.isDuplicateSystem(n,t)?(this.taggedSystemMessages[t]||=[],this.taggedSystemMessages[t].push(n),this.recordMutation({type:`addSystem`,tag:t,message:n})):!t&&!this.isDuplicateSystem(n)&&(this.systemMessages.push(n),this.recordMutation({type:`addSystem`,message:n}))}isDuplicateSystem(e,t){return t?this.taggedSystemMessages[t]?this.taggedSystemMessages[t].some(t=>Jg.fromAIV4CoreMessageContent(t.content)===Jg.fromAIV4CoreMessageContent(e.content)):!1:this.systemMessages.some(t=>Jg.fromAIV4CoreMessageContent(t.content)===Jg.fromAIV4CoreMessageContent(e.content))}getMessageIndex(){let e=this.messageIndex;if(e&&e.messages===this.messages&&e.length===this.messages.length)return e;let t=new Map;for(let e of this.messages){let n=t.get(e.id);n?n.push(e):t.set(e.id,[e])}return this.messageIndex={messages:this.messages,length:this.messages.length,byId:t,sorted:!1},this.messageIndex}getMessagesWithId(e){return this.getMessageIndex().byId.get(e)??[]}getMessageById(e){return this.getMessagesWithId(e)[0]}appendMessage(e){let t=this.getMessageIndex(),n=this.messages.at(-1);this.messages.push(e),t.length=this.messages.length,t.sorted&&=!n||n.createdAt.getTime()<=e.createdAt.getTime();let r=t.byId.get(e.id);r?r.push(e):t.byId.set(e.id,[e])}replaceMessageAt(e,t){let n=this.getMessageIndex(),r=this.messages[e];this.messages[e]=t,n.sorted=!1;let i=n.byId.get(r.id)?.filter(e=>e!==r)??[];i.length?n.byId.set(r.id,i):n.byId.delete(r.id);let a=n.byId.get(t.id);a?a.push(t):n.byId.set(t.id,[t])}sortMessages(){this.messages.sort((e,t)=>e.createdAt.getTime()-t.createdAt.getTime()),this.getMessageIndex().sorted=!0}shouldReplaceMessage(e){if(!this.messages.length||!(`id`in e)||!e?.id)return{exists:!1};let t=this.getMessageById(e.id);return t?{exists:!0,shouldReplace:!Zje(t,e),id:t.id}:{exists:!1}}addOne(e,t,n={}){if((!(`content`in e)||!e.content&&typeof e.content!=`string`)&&(!(`parts`in e)||!e.parts))throw new yn({id:`INVALID_MESSAGE_CONTENT`,domain:gn.AGENT,category:_n.USER,text:`Message with role "${e.role}" must have either a 'content' property (string or array) or a 'parts' property (array) that is not empty, null, or undefined. Received message: ${JSON.stringify(e,null,2)}`,details:{role:e.role,messageSource:t,hasContent:`content`in e,hasParts:`parts`in e}});if(e.role===`system`){if(t===`memory`)return null;if(_g.isAIV4CoreMessage(e)||_g.isAIV6CoreMessage(e)||_g.isAIV5CoreMessage(e)||_g.isMastraDBMessage(e))return this.addSystem(e);throw new yn({id:`INVALID_SYSTEM_MESSAGE_FORMAT`,domain:gn.AGENT,category:_n.USER,text:`Invalid system message format. System messages must be CoreMessage format with 'role' and 'content' properties. The content should be a string or valid content array.`,details:{messageSource:t,receivedMessage:JSON.stringify(e,null,2)}})}let r=nMe(e,t,this.createAdapterContext()),i=r.role===`signal`?r.content.metadata?.signal:void 0;if(t===`input`&&r.role===`signal`&&!i?.acceptedAt){let e=i?.createdAt??r.createdAt.toISOString();r.createdAt=this.generateCreatedAt(t,r.createdAt),r.content.metadata={...r.content.metadata,signal:{...i,createdAt:r.createdAt.toISOString(),acceptedAt:e}}}let{exists:a,shouldReplace:o,id:s}=this.shouldReplaceMessage(r),c=this.messages.at(-1),l=!c||!$g.isSealed(c),u=a&&s?this.getMessageById(s):void 0,d=u?this.stateManager.isUserMessage(u)?`input`:this.stateManager.isResponseMessage(u)?`response`:this.stateManager.isContextMessage(u)?`context`:void 0:void 0;if(t===`memory`&&u&&d&&!$g.isSealed(r)){let e=this.messages.indexOf(u);if(d===`input`)$g.merge(r,QMe(r,u));else if(r.role===`user`&&u.role===`user`)r.content={...r.content,...u.content,metadata:{...r.content.metadata??{},...u.content.metadata??{}}};else{for(let e of u.content.parts){if(e.type!==`text`)continue;let t=r.content.parts.find(t=>t.type===`text`&&t.text.trim()===e.text.trim());t?.type===`text`&&(t.text=e.text)}$g.merge(r,ZMe(r,u))}return this.stateManager.removeMessage(u),this.replaceMessageAt(e,r),this.pushMessageToSource(r,`memory`),this.pushMessageToSource(r,d),this.updateLastCreatedAt(r),this.sortMessages(),this}if(t===`memory`){for(let e of this.getMessagesWithId(r.id))if(Zje(e,r)||$je(e,r))return}let f=!!u&&$g.isSealed(u),p=!!u&&u!==c,m=c?this.memoryMessages.has(c):!1;if(n.merge!==!1&&l&&!f&&!p&&$g.shouldMerge(c,r,t,m,this._agentNetworkAppend)&&c)$g.merge(c,r),this.updateLastCreatedAt(c),this.pushMessageToSource(c,t);else{let e=-1;o&&(e=this.messages.findIndex(e=>e.id===s));let i=e!==-1&&this.messages[e];if(o&&i){let a=this.messages.findLastIndex(e=>$g.isSealed(e)),o=a!==-1&&e<=a;if($g.isSealed(i)){let e=i.content?.parts||[],t=0;for(let n=e.length-1;n>=0;n--)if(e[n]?.metadata?.mastra?.sealedAt){t=n+1;break}t===0&&(t=e.length);let n=r.content.parts,a;if(n.length<=t){if(Zje(i,r))return this;a=n}else a=n.slice(t);a.length>0&&(r.id=this.generateMessageId?.({idType:`message`,source:`memory`})??dn(),r.content.parts=a,r.createdAt<=i.createdAt&&(r.createdAt=new Date(i.createdAt.getTime()+1)),this.appendMessage(r))}else if(o)r.id=this.generateMessageId?.({idType:`message`,source:`memory`})??dn(),r.createdAt<=i.createdAt&&(r.createdAt=new Date(i.createdAt.getTime()+1)),this.appendMessage(r);else{let a=this.memoryMessages.has(i);if(n.merge!==!1&&$g.shouldMerge(i,r,t,a,this._agentNetworkAppend))return $g.merge(i,r),this.updateLastCreatedAt(i),this.pushMessageToSource(i,t),this.sortMessages(),this;this.stateManager.removeMessage(i),this.replaceMessageAt(e,r)}}else a||this.appendMessage(r);this.pushMessageToSource(r,t)}if(this.getMessageIndex().sorted){let e=this.messages.at(-1);return e&&this.updateLastCreatedAt(e),this}for(let e of this.messages)this.updateLastCreatedAt(e);return this.sortMessages(),this}pushMessageToSource(e,t){this.stateManager.addToSource(e,t)}lastCreatedAt;seenAsStored=new WeakSet;livePlacement=new WeakMap;liveArrivals=0;moveLiveMessagesPastStoredTies(){let e=this.memoryMessages;if(!e.size)return;for(let t of e)this.seenAsStored.add(t);let t=this.messages.filter(e=>!this.seenAsStored.has(e)&&!this.isAnchoredSignal(e));if(!t.length)return;let n=new Set;for(let t of e)n.add(t.createdAt.getTime());let r=t.map(e=>{let t=e.createdAt.getTime(),n=this.livePlacement.get(e);return n&&n.placed===t||(n={own:t,placed:t,arrival:n?.arrival??this.liveArrivals++},this.livePlacement.set(e,n)),{message:e,placement:n}});r.sort((e,t)=>e.placement.own-t.placement.own||e.placement.arrival-t.placement.arrival);let i=!1,a;for(let{message:e,placement:t}of r){let r=t.own;for(a?.moved&&r<=a.time&&(r=a.time+1);n.has(r);)r++;if(a={time:r,moved:r!==t.own},t.placed=r,r===e.createdAt.getTime())continue;let o=e.createdAt.toISOString();e.createdAt=new Date(r);let s=e.content.metadata?.signal;s?.createdAt===o&&(s.createdAt=e.createdAt.toISOString()),this.updateLastCreatedAt(e),this.newResponseMessagesPersisted.has(e)?this.newResponseMessages.add(e):this.newUserMessagesPersisted.has(e)&&this.newUserMessages.add(e),i=!0}i&&this.sortMessages()}isAnchoredSignal(e){let t=(e.content.metadata?.signal)?.metadata?.precedesMessageId;return typeof t==`string`&&this.getMessageById(t)!==void 0}updateLastCreatedAt(e){this.lastCreatedAt=Math.max(this.lastCreatedAt||0,e.createdAt.getTime())}generateCreatedAt(e,t){let n=t instanceof Date?t:typeof t==`string`||typeof t==`number`?new Date(t):void 0;if(n&&!this.lastCreatedAt)return this.lastCreatedAt=n.getTime(),n;if(n&&e===`memory`)return n;let r=new Date,i=n?.getTime()||r.getTime(),a=this.lastCreatedAt||0;if(i<=a){let e=new Date(a+1);return this.lastCreatedAt=e.getTime(),e}return this.lastCreatedAt=i,n??r}newMessageId(e){return this.generateMessageId?this.generateMessageId({idType:`message`,source:`agent`,threadId:this.memoryInfo?.threadId,resourceId:this.memoryInfo?.resourceId,role:e}):dn()}createAdapterContext(){return{memoryInfo:this.memoryInfo,newMessageId:()=>this.newMessageId(),generateCreatedAt:(e,t)=>this.generateCreatedAt(e,t),dbMessages:this.messages}}},nNe=e=>typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`image`:{let t=e.mimeType??`image/*`;return{type:`file`,mimeType:t,data:cp(e.image,t)}}case`file`:return{type:`file`,mimeType:e.mimeType,data:cp(e.data,e.mimeType),...e.filename===void 0?{}:{filename:e.filename}};default:throw Error(`Unhandled content part type: ${e.type}`)}}),rNe=e=>({id:`user-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,role:`user`,createdAt:new Date,content:{format:2,parts:e}}),iNe=e=>rNe(e.flatMap(nNe)),aNe=new Set([`task_write`,`task_update`,`task_complete`,`task_check`]),oNe=`tasks`,sNe=new Set([`current-task-list`,`task-list-update`]),cNe=new Set([`pending`,`in_progress`,`completed`]),lNe=e=>typeof e.type==`string`&&e.type.startsWith(`data-`),i_=e=>typeof e==`object`&&!!e&&!Array.isArray(e),uNe=e=>typeof e==`string`&&cNe.has(e),dNe=e=>Array.isArray(e)&&e.every(e=>i_(e)&&typeof e.id==`string`&&typeof e.content==`string`&&uNe(e.status)&&typeof e.activeForm==`string`),fNe=e=>i_(e)?e.id===oNe||typeof e.tagName==`string`&&sNe.has(e.tagName):!1,pNe=e=>{if(!fNe(e)||!i_(e))return;let t=e.metadata;if(!i_(t))return;let n=t.value;if(i_(n))return dNe(n.tasks)?n.tasks:void 0},mNe=e=>{if(i_(e)&&dNe(e.tasks))return e.tasks;if(typeof e==`string`)try{let t=JSON.parse(e);return i_(t)&&dNe(t.tasks)?t.tasks:void 0}catch{return}},hNe=e=>{if(lNe(e))return pNe(e.data)},gNe=e=>{if(e.type!==`tool-result`)return;let t=e.payload;if(i_(t)&&typeof t.toolName==`string`&&aNe.has(t.toolName))return mNe(t.result)},_Ne=e=>{if(!i_(e)||e.type!==`tool-invocation`||!i_(e.toolInvocation))return;let t=e.toolInvocation;if(typeof t.toolName==`string`&&aNe.has(t.toolName))return mNe(t.result)},vNe=e=>{if(i_(e)&&typeof e.type==`string`&&e.type.startsWith(`data-`))return pNe(e.data)},yNe=e=>{if(e.role!==`signal`)return;let t=e.content?.metadata;if(i_(t))return pNe(t.signal)},bNe=e=>{let t;for(let n of e){for(let e of n.content?.parts??[]){let n=_Ne(e);n!==void 0&&(t=n)}let e=yNe(n);e!==void 0&&(t=e);for(let e of n.content?.parts??[]){let n=vNe(e);n!==void 0&&(t=n)}}return t??[]},a_=e=>typeof e==`object`&&!!e,xNe=[`pendingToolApprovals`,`requireApprovalMetadata`,`suspendedTools`],SNe=e=>a_(e)&&Object.values(e).every(e=>a_(e)),CNe=e=>{if(!a_(e))return[];let t=[];for(let n of xNe){let r=e[n];SNe(r)&&t.push(r)}return t},wNe=e=>{for(let t of e)for(let e of CNe(t.content?.metadata))for(let t of Object.values(e))if(a_(t)&&typeof t.runId==`string`&&t.runId.length>0)return t.runId},TNe=e=>{let t=e.content.metadata?.[lp];return typeof t==`string`?t:void 0},ENe=e=>{let t=e.content.metadata?.signal,n=i_(t)&&i_(t.metadata)?t.metadata[lp]:void 0;return typeof n==`string`?n:void 0},DNe=({conversation:e,history:t,previousHistory:n})=>{let r=new Map(n.map(e=>[e.id,e])),i=e.filter(e=>r.get(e.id)!==e),a=new Map(i.map(e=>[e.id,e])),o=new Set(i.flatMap(e=>TNe(e)??[])),s=new Set(t.map(e=>e.id)),c=new Set(t.flatMap(e=>ENe(e)??[])),l=t.map(e=>{let t=a.get(e.id);if(t)return t;let n=ENe(e);return!n||!o.has(n)?e:{...e,content:{...e.content,metadata:{...e.content.metadata,[lp]:n}}}}),u=i.filter(e=>{let t=TNe(e);return!s.has(e.id)&&!(t&&c.has(t))});return[...l,...u]},ONe=e=>{let t=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content,n=e.providerOptions??e.experimental_providerMetadata;return n?t.map(e=>{let t={...n};for(let[n,r]of Object.entries(e.providerOptions??e.experimental_providerMetadata??{}))t[n]={...t[n],...r};return{...e,providerOptions:t}}):t},kNe=(e,t=[])=>({role:`user`,content:[...e||t.length===0?[{type:`text`,text:e}]:[],...t.flatMap(ONe)]}),ANe=(e,t)=>{let n=new Set;for(let r of e){let e=r.content?.metadata;if(!e)continue;let i=[e.pendingToolApprovals,e.requireApprovalMetadata,e.suspendedTools];for(let e of i)if(e&&typeof e==`object`)for(let r of Object.values(e)){if(t&&r?.runId!==t)continue;let e=r?.toolCallId;typeof e==`string`&&e.length>0&&n.add(e)}}return n},jNe=(e,t)=>e.some(e=>{if(e.type!==`tool-invocation`)return!1;let n=e.toolInvocation;return n.toolCallId===t?n.state===`result`||n.result!=null:!1}),MNe=(e,t)=>{if(!e||typeof e!=`object`)return;let n=Object.fromEntries(Object.entries(e).filter(([,e])=>e&&typeof e==`object`&&typeof e.toolCallId==`string`&&!jNe(t,e.toolCallId)));return Object.keys(n).length?n:void 0},NNe=e=>e.filter(e=>{let t=e.content?.metadata;return!(t?.completionResult?.suppressFeedback||t?.isTaskCompleteResult?.suppressFeedback)}).map(e=>{let t=e.content?.metadata,n=t&&(t.status===`pending`||`clientMessageId`in t)?(()=>{let{[lp]:n,...r}=t,{status:i,...a}=r;return{...e,content:{...e.content,metadata:t.status===`pending`?a:r}}})():e,r=n.content?.metadata;if(!r?.pendingToolApprovals&&!r?.requireApprovalMetadata&&!r?.suspendedTools)return n;let{pendingToolApprovals:i,requireApprovalMetadata:a,suspendedTools:o,...s}=r,c=n.content.parts,l=MNe(i,c),u={...MNe(a,c),...l},d=MNe(o,c);return{...n,content:{...n.content,metadata:{...s,...i?{mode:`stream`}:{},...l?{pendingToolApprovals:l}:{},...Object.keys(u).length?{requireApprovalMetadata:u}:{},...d?{suspendedTools:d}:{}}}}}),PNe=e=>typeof e==`object`&&!!e,FNe=e=>PNe(e)&&typeof e.name==`string`?e.name:void 0,o_=e=>FNe(e)===`AbortError`,INe=e=>{if(!PNe(e))return!1;let t=e.status;return t===404||t===405||t===501||t===400&&typeof e.message==`string`&&e.message.includes(`No active agent run found for signal target`)},LNe=e=>typeof e.type==`string`&&e.type.startsWith(`data-`),s_=(e,t)=>e.map(e=>{let n=zg.fromUIMessage(e);return{...n,content:{...n.content,metadata:{...n.content.metadata??{},...t}}}}),RNe=({agentId:e,resourceId:t,threadId:n,initialMessages:r,requestContext:i,clientTools:a,onSignalSent:o,onSignalEcho:s,onThreadSignalsUnsupported:c,enableThreadSignals:l=!1,streamPath:u,withInitialHistory:d})=>{let f=l===!1,p=(0,G.useRef)(void 0),m=(0,G.useRef)(void 0),h=(0,G.useRef)(void 0),g=(0,G.useRef)(void 0),_=(0,G.useRef)({requestContext:i}),v=(0,G.useRef)(null),y=(0,G.useRef)(null),b=(0,G.useRef)(null),x=(0,G.useRef)(void 0),S=(0,G.useRef)(null),C=(0,G.useRef)(!1),[w,T]=(0,G.useState)([]),[E,D]=(0,G.useState)([]),O=(0,G.useRef)(void 0),[k,A]=(0,G.useState)({}),[j,M]=(0,G.useState)({}),N=(0,G.useRef)(new Set),P=(0,G.useRef)(new Set),F=(0,G.useRef)(void 0),I=(0,G.useRef)(!1),L=(0,G.useRef)(void 0),[R,z]=(0,G.useState)(!1),B=Y(),[V,H]=(0,G.useState)(!1),[ee,te]=(0,G.useState)(void 0),[U,W]=(0,G.useState)(void 0),ne=`${e}:${t??``}:${n??``}`,re=d?d===!0?`history`:`history:${d.perPage??``}`:``,ie=d&&!f&&n&&U?.key===`${e}:${t||e}:${n}:${u??``}:${re}`?U.pagination:void 0,ae=d&&ee?.key===ne?ee.messages:r,oe=(0,G.useRef)(void 0);(0,G.useEffect)(()=>{let r=oe.current,i=r?.agentId===e&&r.resourceId===t&&r.threadId===n;if(i&&r.initialMessages===ae)return;let a=NNe(ae??[]);if(oe.current={agentId:e,resourceId:t,threadId:n,initialMessages:ae,formattedMessages:a},i){T(e=>DNe({conversation:e,history:a,previousHistory:r.formattedMessages})),D(O.current??bNe(a));let e=wNe(a);if(I.current||!F.current&&V&&e!==p.current)return}else O.current=void 0,P.current.clear(),F.current=void 0,I.current=!1,r&&H(!1),T(a),D(bNe(a));let o=ANe(a,F.current);for(let e of P.current)N.current.has(e)?o.add(e):o.delete(e);N.current=o,z(o.size>0),p.current=F.current??wNe(a)},[e,t,n,ae,V,R]),(0,G.useEffect)(()=>{_.current={..._.current,requestContext:i}},[i]);let se=e=>e instanceof URL?e.toString():Zue(e),ce=e=>{let t=e.reduce((e,t)=>{if(typeof t.content==`string`)return e.push({type:`text`,text:t.content}),e;for(let n of t.content)n.type===`text`?e.push({type:`text`,text:n.text}):n.type===`file`?e.push({type:`file`,data:se(n.data),mediaType:n.mimeType,...n.filename?{filename:n.filename}:{}}):n.type===`image`&&e.push({type:`file`,data:se(n.image),mediaType:n.mimeType??`image/png`});return e},[]);return t.length===1&&t[0]?.type===`text`?t[0].text:t},le=(0,G.useCallback)(()=>{C.current=!0,c?.()},[c]),ue=e=>e.flatMap(e=>typeof e.content==`string`?[e.content]:e.content.map(e=>e.type===`text`?e.text:e.type===`image`?`Image`:e.filename?`File: ${e.filename}`:`File`)).join(` `).replace(/\s+/g,` `).trim()||`Attachment`,de=(0,G.useCallback)(()=>{let e=b.current;e?.unsubscribe?e.unsubscribe():y.current?.abort(),b.current=null,y.current=null,x.current=void 0,S.current=null,W(void 0)},[]),fe=(0,G.useCallback)(async(e,t)=>{let n=e.type===`finish`||e.type===`abort`||e.type===`error`;if(n&&F.current&&e.runId!==F.current)return;let r=`runId`in e&&typeof e.runId==`string`?e.runId:void 0;T(t=>{let n={mode:`stream`,runId:r},i=hde({chunk:e,conversation:t,metadata:n});return(e.type===`start`||e.type===`step-start`)&&e.payload?.messageId&&r?i.map(t=>t.id===e.payload.messageId&&t.role===`assistant`?{...t,content:{...t.content,metadata:{...t.content.metadata,...n}}}:t):i});let i=gNe(e)??hNe(e);if(i!==void 0&&(O.current=i,D(i)),e.type===`data-user-message`&&LNe(e)&&(e.data?.type===`user-message`||e.data?.type===`user`)&&typeof e.data?.id==`string`&&s?.(e.data.id),e.type===`start`&&(H(!0),`runId`in e&&typeof e.runId==`string`&&(F.current!==e.runId&&P.current.clear(),I.current=!1,F.current=e.runId,p.current=e.runId)),e.type===`tool-call-approval`||e.type===`tool-call-suspended`){let t=e.payload?.toolCallId;typeof t==`string`&&(P.current.add(t),N.current.add(t),z(!0)),r&&((!F.current||I.current)&&(F.current=r,I.current=!1),F.current===r&&(p.current=r)),H(!1)}if(e.type===`tool-call-resumed`){let t=e.payload?.toolCallId;typeof t==`string`&&(P.current.add(t),N.current.delete(t),z(N.current.size>0))}if(n){e.runId===F.current&&(I.current=!0);for(let e of N.current)P.current.add(e);N.current.clear(),z(!1),H(!1)}(t??m.current)?.(e)},[s]),pe=(0,G.useCallback)(async({threadId:t,resourceId:n})=>{let r=`${e}:${n??``}:${t}:${u??``}:${re}`;if(x.current===r&&S.current){await S.current;return}de();let i=new AbortController;y.current=i,x.current=r;let a=()=>{y.current===i&&(b.current=null,y.current=null,x.current=void 0,S.current=null,W(void 0))},o=new op({...B.options,abortSignal:i.signal}).getAgent(e,void 0,{stream:u});S.current=o.subscribeToThread({resourceId:n,threadId:t,withRunStatus:!0,...d?{withInitialHistory:d}:{}}).then(o=>{let s=o;y.current===i?(b.current=s,s.processDataStream({onChunk:a=>{if(a.type===`thread-history`){if(y.current===i){let{hasMore:e,activeRunId:t}=a.payload;t&&t!==F.current&&(!F.current||I.current)&&(F.current=t,I.current=!1,p.current=t,H(N.current.size===0)),W(typeof e==`boolean`?{key:r,pagination:{hasMore:e}}:void 0)}let o=NNe(a.payload.messages),s=oe.current?.formattedMessages??[];T(e=>DNe({conversation:e,history:o,previousHistory:s})),te({key:`${e}:${n??``}:${t}`,messages:a.payload.messages})}else if(a.type===`thread-run-status`){if(a.runId!==F.current){L.current?.set(a.runId,a);return}if(H(!1),a.payload.status!==`suspended`){I.current=!0;for(let e of N.current)P.current.add(e);N.current.clear(),z(!1)}}else return fe(a)}}).catch(e=>{o_(e)||(console.error(`[useChat] Thread subscription failed`,e),H(!1))}).finally(()=>{b.current===s&&(b.current=null),a()})):s.unsubscribe()}).catch(e=>{if(a(),INe(e))le();else throw o_(e)||(console.error(`[useChat] Thread subscription failed`,e),H(!1)),e}),await S.current},[e,B,de,re,le,fe,u,d]);(0,G.useEffect)(()=>(C.current=!1,de),[e,t,n,de]),(0,G.useEffect)(()=>{!n||f?de():pe({threadId:n,resourceId:t||e}).catch(e=>{o_(e)||console.error(`[useChat] Thread subscription failed`,e)})},[e,de,pe,t,n,f]);let me=async({coreUserMessages:n,model:r,requestContext:o,threadId:s,modelSettings:c,signal:l,onFinish:d,tracingOptions:f,clientTools:m,clientToolsResolver:h})=>{let{frequencyPenalty:g,presencePenalty:v,maxRetries:y,maxTokens:b,temperature:x,topK:S,topP:C,instructions:w,system:E,providerOptions:D,maxSteps:O,requireToolApproval:k}=c||{},A=o??i,j=m??a;_.current={model:r,requestContext:A},H(!0);let M=new op({...B.options,abortSignal:l}).getAgent(e,void 0,{stream:u}),N=dn();p.current=N;let P=await M.generate(n,{model:r,runId:N,maxSteps:O,modelSettings:{frequencyPenalty:g,presencePenalty:v,maxRetries:y,maxOutputTokens:b,temperature:x,topK:S,topP:C},instructions:w,system:E,requestContext:A,...s?{memory:{thread:s,resource:t||e}}:{},providerOptions:D,tracingOptions:f,requireToolApproval:k,clientTools:j,clientToolsResolver:h});if(P.finishReason===`suspended`&&P.suspendPayload){let{toolCallId:e,toolName:t,args:n}=P.suspendPayload;if(P.response?.uiMessages){let r=s_(P.response.uiMessages,{mode:`generate`,requireApprovalMetadata:{[t]:{toolCallId:e,toolName:t,args:n}}});T(e=>[...e,...r])}H(!1)}else if(H(!1),P&&`uiMessages`in P.response&&P.response.uiMessages){let e=s_(P.response.uiMessages,{mode:`generate`});d?.(e),T(t=>[...t,...e])}},he=async({coreUserMessages:n,model:r,requestContext:c,threadId:l,onChunk:d,modelSettings:h,signal:g,tracingOptions:y,clientTools:b,clientToolsResolver:x,signalId:S,clientMessageId:w,metadata:E})=>{let{frequencyPenalty:D,presencePenalty:O,maxRetries:k,maxTokens:A,temperature:j,topK:M,topP:R,instructions:V,system:ee,providerOptions:te,maxSteps:U,requireToolApproval:W}=h||{},ne=c??i,re=b??a,ie={model:r,maxSteps:U,modelSettings:{frequencyPenalty:D,presencePenalty:O,maxRetries:k,maxOutputTokens:A,temperature:j,topK:M,topP:R},instructions:V,system:ee,providerOptions:te,requireToolApproval:W,tracingOptions:y};_.current={model:r,requestContext:ne},H(!0),v.current?.abort();let ae=new AbortController;v.current=ae,g&&(g.aborted?ae.abort():g.addEventListener(`abort`,()=>ae.abort(),{once:!0}));let oe=new op({...B.options,abortSignal:ae.signal}).getAgent(e,void 0,{stream:u}),se=e=>o_(e)&&ae.signal.aborted&&!g?.aborted,de=()=>{v.current&&v.current!==ae||H(!1)},me=()=>{de(),S&&T(e=>e.filter(e=>e.id!==S||e.content.metadata?.status!==`pending`))},he=async()=>{try{await ge()}catch(e){if(!se(e))throw e;me()}},ge=async()=>{let i=dn();p.current=i;let a=await oe.stream(n,{model:r,runId:i,maxSteps:U,untilIdle:!0,modelSettings:{frequencyPenalty:D,presencePenalty:O,maxRetries:k,maxOutputTokens:A,temperature:j,topK:M,topP:R},instructions:V,system:ee,requestContext:ne,...l?{memory:{thread:l,resource:t||e}}:{},providerOptions:te,requireToolApproval:W,tracingOptions:y,clientTools:re,clientToolsResolver:x});m.current=d,p.current=i,await a.processDataStream({onChunk:e=>fe(e,d)}),v.current===ae&&(v.current=null),de()};if(!l||C.current||f||(m.current=d,await pe({threadId:l,resourceId:t||e}),C.current)){await he();return}let _e=S??dn(),ve=ce(n),ye=ne,be={model:r,maxSteps:U,modelSettings:{frequencyPenalty:D,presencePenalty:O,maxRetries:k,maxOutputTokens:A,temperature:j,topK:M,topP:R},instructions:V,system:ee,requestContext:ye,providerOptions:te,requireToolApproval:W,tracingOptions:y,clientTools:re,clientToolsResolver:x},xe=F.current,Se=new Map;L.current=Se;try{let r=await oe.sendMessage({message:w||E?{contents:ve,metadata:{...E,...w?{[lp]:w}:{}}}:ve,resourceId:t||e,threadId:l,ifIdle:{streamOptions:{...ie,requestContext:ye,clientTools:re,clientToolsResolver:x}}});if(v.current===ae&&F.current===xe&&F.current!==r.runId){P.current.clear(),F.current=r.runId,I.current=!1,p.current=r.runId,H(!0);let e=Se.get(r.runId);if(e&&(H(!1),e.payload.status!==`suspended`)){I.current=!0;for(let e of N.current)P.current.add(e);N.current.clear(),z(!1)}}let i=r.signal&&typeof r.signal==`object`&&`id`in r.signal&&typeof r.signal.id==`string`?r.signal.id:_e;o?.(i,ue(n)),N.current.size>0&&H(!1)}catch(r){if(se(r)){me();return}if(INe(r))try{await oe.sendSignal({signal:{id:_e,type:`user-message`,contents:ve,...E?{metadata:E}:{}},resourceId:t||e,threadId:l,ifIdle:{streamOptions:be}}),o?.(_e,ue(n));return}catch(e){if(s?.(_e),se(e)){me();return}if(INe(e)){le(),T(e=>[...e,iNe(n)]),await he();return}throw e}throw r}finally{L.current===Se&&(L.current=void 0)}v.current===ae&&(v.current=null)},ge=async({coreUserMessages:n,model:r,requestContext:a,threadId:o,onNetworkChunk:s,modelSettings:c,signal:l,tracingOptions:d})=>{let{frequencyPenalty:f,presencePenalty:m,maxRetries:v,maxTokens:y,temperature:b,topK:x,topP:S,maxSteps:C}=c||{},w=a??i;_.current={model:r,requestContext:w},H(!0);let E=new op({...B.options,abortSignal:l}).getAgent(e,void 0,{stream:u}),D=dn();p.current=D;let O=await E.network(n,{model:r,maxSteps:C,modelSettings:{frequencyPenalty:f,presencePenalty:m,maxRetries:v,maxOutputTokens:y,temperature:b,topK:x,topP:S},runId:D,requestContext:w,...o?{memory:{thread:o,resource:t||e}}:{},tracingOptions:d});g.current=s,h.current=D,await O.processDataStream({onChunk:async e=>{T(t=>Tde({chunk:e,conversation:t,metadata:{mode:`network`,runId:D}})),s?.(e)}}),T(e=>vp(e)),H(!1)};return{setMessages:T,sendMessage:async({mode:e=`stream`,metadata:t,...n})=>{!V&&!R&&(p.current=void 0);let r=[kNe(n.message,n.coreUserMessages)],i=iNe(r),a=t?{...i,content:{...i.content,metadata:{...i.content.metadata,...t}}}:i,o=e===`stream`&&n.threadId&&!C.current&&!f?`client-set-${dn()}`:void 0,s=o,c=o;if(s){let e={...a.content.metadata,mode:`stream`,status:`pending`,[lp]:c},t={...a,id:o,content:{...a.content,metadata:e}};T(e=>[...e,t])}else T(e=>[...e,a]);try{e===`generate`?await me({...n,coreUserMessages:r}):e===`stream`?await he({...n,coreUserMessages:r,signalId:s,clientMessageId:c,metadata:t}):e===`network`&&await ge({...n,coreUserMessages:r})}catch(e){throw H(!1),s&&T(e=>e.filter(e=>e.id!==s||e.content.metadata?.status!==`pending`)),e}},isRunning:V,activeRunId:V||R?p.current:void 0,isAwaitingToolApproval:R,messages:w,initialHistoryPagination:ie,tasks:E,approveToolCall:async(r,i)=>{let a=m.current,o=p.current,s=_.current;if(!o)return console.info(`[approveToolCall] approveToolCall can only be called after a stream has started`);H(!0),A(e=>({...e,[r]:{status:`approved`}}));let c=B.getAgent(e,void 0,{stream:u});if(x.current&&n)try{await c.sendToolApproval({resourceId:t||e,threadId:n,toolCallId:r,approved:!0,...s.model===void 0?{}:{streamOptions:{model:s.model}},...i===void 0?{}:{resumeData:i},requestContext:s.requestContext}),F.current??=o,P.current.add(r),N.current.delete(r),z(N.current.size>0),H(!1)}catch(e){throw A(e=>{let t={...e};return delete t[r],t}),H(!1),e}else try{await(i===void 0?await c.approveToolCall({runId:o,toolCallId:r,...s}):await c.resumeStream(i,{runId:o,toolCallId:r,...s})).processDataStream({onChunk:async e=>{await fe(e,a)}}),H(!1)}catch(e){throw A(e=>{let t={...e};return delete t[r],t}),H(!1),e}},declineToolCall:async r=>{let i=m.current,a=p.current,o=_.current;if(!a)return console.info(`[declineToolCall] declineToolCall can only be called after a stream has started`);H(!0),A(e=>({...e,[r]:{status:`declined`}}));let s=B.getAgent(e,void 0,{stream:u});if(x.current&&n)try{await s.sendToolApproval({resourceId:t||e,threadId:n,toolCallId:r,approved:!1,...o.model===void 0?{}:{streamOptions:{model:o.model}},requestContext:o.requestContext}),F.current??=a,P.current.add(r),N.current.delete(r),z(N.current.size>0),H(!1)}catch(e){throw A(e=>{let t={...e};return delete t[r],t}),H(!1),e}else await(await s.declineToolCall({runId:a,toolCallId:r,...o})).processDataStream({onChunk:async e=>{await fe(e,i)}}),H(!1)},approveToolCallGenerate:async t=>{let n=p.current,r=_.current;if(!n)return console.info(`[approveToolCallGenerate] approveToolCallGenerate can only be called after a generate has started`);H(!0),A(e=>({...e,[t]:{status:`approved`}}));let i=await B.getAgent(e,void 0,{stream:u}).approveToolCallGenerate({runId:n,toolCallId:t,...r});if(i&&`uiMessages`in i.response&&i.response.uiMessages){let e=s_(i.response.uiMessages,{mode:`generate`});T(t=>[...t,...e])}H(!1)},declineToolCallGenerate:async t=>{let n=p.current,r=_.current;if(!n)return console.info(`[declineToolCallGenerate] declineToolCallGenerate can only be called after a generate has started`);H(!0),A(e=>({...e,[t]:{status:`declined`}}));let i=await B.getAgent(e,void 0,{stream:u}).declineToolCallGenerate({runId:n,toolCallId:t,...r});if(i&&`uiMessages`in i.response&&i.response.uiMessages){let e=s_(i.response.uiMessages,{mode:`generate`});T(t=>[...t,...e])}H(!1)},cancelRun:()=>{let r=p.current,i=B?.getAgent(e),a=b.current,o=v.current,s=new AbortController,c=setTimeout(()=>s.abort(Error(`Agent run cancellation was not acknowledged`)),1e4),l=(async()=>{if(i&&r)for(;;){s.signal.throwIfAborted();let a={signal:s.signal};if((n?await i.abortThread({threadId:n,resourceId:t||e,expectedRunId:r},a):await i.abortRun(r,a)).aborted)return;await new Promise(e=>setTimeout(e,100))}await a?.abort?.()})().catch(e=>{if(!PNe(e)||e.status!==404&&e.status!==501)throw e}).finally(()=>{clearTimeout(c),o?.abort(),v.current===o&&(v.current=null)});return l.catch(e=>console.error(`[useChat] Failed to abort agent run`,e)),de(),T(e=>vp(e)),I.current=!0,N.current.clear(),z(!1),H(!1),p.current=void 0,m.current=void 0,h.current=void 0,g.current=void 0,_.current={},l},toolCallApprovals:k,approveNetworkToolCall:async(t,n)=>{let r=g.current,i=n||h.current,a=_.current;if(!i)return console.info(`[approveNetworkToolCall] approveNetworkToolCall can only be called after a network stream has started`);p.current=i,H(!0),M(e=>({...e,[n?`${n}-${t}`:t]:{status:`approved`}})),await(await B.getAgent(e,void 0,{stream:u}).approveNetworkToolCall({runId:i,...a})).processDataStream({onChunk:async e=>{T(t=>Tde({chunk:e,conversation:t,metadata:{mode:`network`,runId:i}})),r?.(e)}}),T(e=>vp(e)),H(!1)},declineNetworkToolCall:async(t,n)=>{let r=g.current,i=n||h.current,a=_.current;if(!i)return console.info(`[declineNetworkToolCall] declineNetworkToolCall can only be called after a network stream has started`);p.current=i,H(!0),M(e=>({...e,[n?`${n}-${t}`:t]:{status:`declined`}})),await(await B.getAgent(e,void 0,{stream:u}).declineNetworkToolCall({runId:i,...a})).processDataStream({onChunk:async e=>{T(t=>Tde({chunk:e,conversation:t,metadata:{mode:`network`,runId:i}})),r?.(e)}}),T(e=>vp(e)),H(!1)},networkToolCallApprovals:j}};function c_(e){let[t,n]=(0,G.useState)(!1),[r,i]=(0,G.useState)(!1),[a,o]=(0,G.useState)(!1),[s,c]=(0,G.useState)(null),[l,u]=(0,G.useState)(void 0),d=(0,G.useRef)(e);d.current=e;let f=(0,G.useCallback)(()=>{n(!1),i(!1),o(!1),c(null),u(void 0)},[]),p=(0,G.useCallback)(async e=>{n(!0),i(!1),o(!1),c(null);try{let t=await d.current(e);return u(t),i(!0),t}catch(e){throw c(e),o(!0),e}finally{n(!1)}},[]);return{mutate:(0,G.useCallback)(e=>{p(e).catch(()=>{})},[p]),mutateAsync:p,isPending:t,isSuccess:r,isError:a,error:s,data:l,reset:f}}function zNe({debugMode:e,tracingOptions:t,onError:n}){let r=Y(),[i,a]=(0,G.useState)(),[o,s]=(0,G.useState)(!1),c=(0,G.useRef)(void 0),l=(0,G.useRef)(!0),u=(0,G.useCallback)(()=>{let e=c.current;c.current=void 0,e&&(e.controller.abort(),e.reader?.cancel().catch(()=>void 0),e.reader?.releaseLock(),e.reader=void 0)},[]);(0,G.useEffect)(()=>(l.current=!0,()=>{l.current=!1,u()}),[u]);async function d(e,t){if(!l.current)return;u();let r={controller:new AbortController};c.current=r;let{signal:i}=r.controller;s(!0);try{let t=await e(i);if(i.aborted){await t?.cancel();return}if(!t){n?.(Error(`No stream returned`),`No stream returned`);return}let o=t.getReader();for(r.reader=o;!i.aborted;){let{done:e,value:t}=await o.read();if(e||i.aborted)break;if(a(e=>bp(e,t)),t.type===`workflow-step-start`&&s(!0),t.type===`workflow-step-suspended`&&s(!1),t.type===`workflow-finish`&&t.payload.workflowStatus===`failed`)throw Error(t.payload.metadata?.errorMessage||`Workflow execution failed`)}}catch(e){if(!i.aborted){if(!r.reader)throw e;n?.(e instanceof Error?e:Error(t),t)}}finally{r.reader?.releaseLock(),r.reader=void 0,c.current===r&&(c.current=void 0,s(!1))}}let f=c_(({workflowId:n,runId:i,inputData:o,initialState:s,requestContext:c,perStep:l,resourceId:u})=>(a({status:`pending`,input:o,steps:{}}),d(async a=>{let d=await r.getWorkflow(n).createRun({runId:i,resourceId:u});if(!a.aborted)return d.stream({inputData:o,initialState:s,requestContext:c,closeOnSuspend:!0,tracingOptions:t,perStep:l??e,resourceId:u})},`Error streaming workflow`))),p=c_(async({workflowId:e,runId:t,storeRunResult:n})=>{l.current&&(a(n??void 0),n?.status===`suspended`?(u(),s(!1)):await d(async n=>{let i=await r.getWorkflow(e).createRun({runId:t});if(!n.aborted)return i.observeStream()},`Error observing workflow`))}),m=c_(({workflowId:n,runId:i,step:a,resumeData:o,requestContext:s,perStep:c})=>d(async l=>{let u=await r.getWorkflow(n).createRun({runId:i});if(!l.aborted)return u.resumeStream({step:a,resumeData:o,requestContext:s,tracingOptions:t,perStep:c??e})},`Error resuming workflow stream`)),h=c_(({workflowId:n,requestContext:i,runId:a,perStep:o,...s})=>d(async c=>{let l=await r.getWorkflow(n).createRun({runId:a});if(!c.aborted)return l.timeTravelStream({...s,perStep:o??e,requestContext:i,tracingOptions:t})},`Error time traveling workflow stream`));return{streamWorkflow:f,streamResult:i,isStreaming:o,observeWorkflowStream:p,closeStreamsAndReset:(0,G.useCallback)(()=>{u(),s(!1),a(void 0)},[u]),resumeWorkflowStream:m,timeTravelWorkflowStream:h}}function BNe(){let e=Y();return c_(async({workflowId:t,prevRunId:n,resourceId:r})=>{try{let{runId:i}=await e.getWorkflow(t).createRun({runId:n,resourceId:r});return{runId:i}}catch(e){throw console.error(`Error creating workflow run:`,e),e}})}function VNe(){let e=Y();return c_(async({workflowId:t,runId:n})=>{try{return(await e.getWorkflow(t).createRun({runId:n})).cancelRun()}catch(e){throw console.error(`Error canceling workflow run:`,e),e}})}var HNe={"audio/webm":`webm`,"video/webm":`webm`,"audio/ogg":`ogg`,"audio/mp4":`m4a`,"video/mp4":`mp4`,"audio/mpeg":`mp3`,"audio/wav":`wav`},UNe=`audio/webm`;function WNe(e){let[t=``]=e.split(`;`);return t.trim().toLowerCase()}function GNe(e){e.getTracks().forEach(e=>e.stop())}async function KNe(e){let t=await navigator.mediaDevices.getUserMedia({audio:!0}),n;try{n=new MediaRecorder(t)}catch(e){throw GNe(t),e}let r=[];return n.ondataavailable=e=>{e.data.size>0&&r.push(e.data)},n.onstop=()=>{let i=WNe(n.mimeType||r[0]?.type||``)||UNe,a=new File(r,`recording-${Date.now()}.${HNe[i]??`webm`}`,{type:i,lastModified:Date.now()});GNe(t),e(a)},n}async function qNe(e,t){let n=new window.AudioContext,r=e.getReader(),i=[];try{for(;;){let{done:e,value:t}=await r.read();if(e)break;i.push(t)}let e=i.reduce((e,t)=>e+t.length,0),a=new Uint8Array(e),o=0;for(let e of i)a.set(e,o),o+=e.length;let s=await n.decodeAudioData(a.buffer),c=n.createBufferSource();return c.buffer=s,c.onended=t??null,c.connect(n.destination),c.start(),()=>{c.onended=null,c.stop(),n.close()}}catch(e){throw await r.cancel().catch(()=>void 0),await n.close().catch(()=>void 0),e}finally{r.releaseLock()}}var JNe=`Speech Recognition not supported in this browser`,YNe=()=>`SpeechRecognition`in window||`webkitSpeechRecognition`in window,XNe=()=>()=>{},ZNe=()=>!0,QNe=({language:e=`en-US`,agentId:t,requestContext:n})=>{let r=Y(),[i,a]=(0,G.useState)();(0,G.useEffect)(()=>{if(!t)return;let e=!1,i=r.getAgent(t);return(async()=>{try{let r=await i.voice.getSpeakers(n);e||a({agentId:t,agent:r.length>0?i:void 0})}catch{e||a({agentId:t})}})(),()=>{e=!0}},[t,r,n]);let o=i&&i.agentId===t?i.agent:void 0,s=$Ne({language:e}),c=ePe({agent:o,language:e});return o?c:s},$Ne=({language:e=`en-US`})=>{let t=(0,G.useRef)(null),n=(0,G.useSyncExternalStore)(XNe,YNe,ZNe),[r,i]=(0,G.useState)({isListening:!1,transcript:``,error:null}),a=e=>{let n=t.current;if(!n)return;n.start();let r=``;n.onresult=t=>{let n=``;for(let e=t.resultIndex;e<t.results.length;e++){let r=t.results[e][0].transcript;t.results[e].isFinal&&(n+=r+` `)}n&&(r+=n,i(e=>({...e,transcript:r})),e?.(r))}},o=()=>{t.current&&t.current.stop()};return(0,G.useEffect)(()=>{if(!YNe())return;let n=new(window.SpeechRecognition||window.webkitSpeechRecognition);return t.current=n,n.continuous=!0,n.lang=e,n.onstart=()=>{i(e=>({...e,isListening:!0,error:null,transcript:``}))},n.onerror=e=>{i(t=>({...t,error:`Error: ${e.error}`}))},n.onend=()=>i(e=>({...e,isListening:!1})),()=>{try{n.stop()}catch{}n.onstart=null,n.onresult=null,n.onerror=null,n.onend=null,t.current=null}},[e]),{...r,error:n?r.error:JNe,start:a,stop:o}},ePe=({agent:e,language:t})=>{let[n,r]=(0,G.useState)({isListening:!1,transcript:``,error:null}),i=(0,G.useRef)(null),a=(0,G.useRef)(0),o=(0,G.useRef)(!1);(0,G.useEffect)(()=>()=>{a.current+=1,o.current=!1,i.current?.stop(),i.current=null},[e]);let s=(n,o)=>s=>{e&&n===a.current&&(i.current=null,r(e=>({...e,isListening:!1})),e.voice.listen(s,{language:t}).then(e=>{n===a.current&&(r(t=>({...t,transcript:e.text,error:null})),o?.(e.text))}).catch(e=>{if(n!==a.current)return;let t=e instanceof Error?e.message:`Failed to transcribe speech`;r(e=>({...e,error:t}))}))},c=t=>{if(!e||o.current||i.current)return;o.current=!0,a.current+=1;let n=a.current;KNe(s(n,t)).then(e=>{if(o.current=!1,n!==a.current)try{e.stop()}catch{}else i.current=e,r(e=>({...e,isListening:!0,error:null})),e.start()}).catch(e=>{if(o.current=!1,n!==a.current)return;let t=e instanceof Error?e.message:`Failed to start speech recording`;r(e=>({...e,isListening:!1,error:t}))})},l=()=>{i.current?(i.current.stop(),i.current=null):o.current&&(a.current+=1),o.current=!1,r(e=>({...e,isListening:!1}))};return{...n,start:c,stop:l}},tPe=({children:e,baseUrl:t,headers:n,apiPrefix:r,credentials:i,customFetch:a})=>(0,K.jsx)(Gue,{baseUrl:t,headers:n,apiPrefix:r,credentials:i,customFetch:a,children:e}),l_=(e,t)=>t?.(e)??null;(0,G.memo)(({step:e,Step:t,MapStep:n,AgentStep:r,ToolStep:i,ClassifierStep:a,ForEachStep:o,ParallelStep:s,Conditional:c,LoopStep:l,SleepStep:u,SleepUntilStep:d,NestedWorkflowStep:f,UnknownStep:p})=>{switch(e.kind){case`step`:return(0,K.jsx)(K.Fragment,{children:t?.(e)??l_(e,p)});case`map-step`:return(0,K.jsx)(K.Fragment,{children:n?.(e)??l_(e,p)});case`agent-step`:return(0,K.jsx)(K.Fragment,{children:r?.(e)??l_(e,p)});case`tool-step`:return(0,K.jsx)(K.Fragment,{children:i?.(e)??l_(e,p)});case`classifier-step`:return(0,K.jsx)(K.Fragment,{children:a?.(e)??l_(e,p)});case`foreach-step`:return(0,K.jsx)(K.Fragment,{children:o?.(e)??l_(e,p)});case`parallel-step`:return(0,K.jsx)(K.Fragment,{children:s?.(e)??l_(e,p)});case`conditional`:return(0,K.jsx)(K.Fragment,{children:c?.(e)??l_(e,p)});case`loop-step`:return(0,K.jsx)(K.Fragment,{children:l?.(e)??l_(e,p)});case`sleep-step`:return(0,K.jsx)(K.Fragment,{children:u?.(e)??l_(e,p)});case`sleep-until-step`:return(0,K.jsx)(K.Fragment,{children:d?.(e)??l_(e,p)});case`nested-workflow-step`:return(0,K.jsx)(K.Fragment,{children:f?.(e)??l_(e,p)});default:return(0,K.jsx)(K.Fragment,{children:l_(e,p)})}});var nPe=G.createContext(void 0),u_=e=>{let t=G.useContext(nPe);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},rPe=({client:e,children:t})=>(G.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,K.jsx)(nPe.Provider,{value:e,children:t})),iPe={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},d_=new class{#e=iPe;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function aPe(e){setTimeout(e,0)}var oPe=typeof window>`u`||`Deno`in globalThis;function f_(){}function sPe(e,t){return typeof e==`function`?e(t):e}function cPe(e){return typeof e==`number`&&e>=0&&e!==1/0}function lPe(e,t){return Math.max(e+(t||0)-Date.now(),0)}function p_(e,t){return typeof e==`function`?e(t):e}function uPe(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==fPe(o,t.options))return!1}else if(!h_(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function dPe(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(m_(t.options.mutationKey)!==m_(a))return!1}else if(!h_(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function fPe(e,t){return(t?.queryKeyHashFn||m_)(e)}function m_(e){return JSON.stringify(e,(e,t)=>gPe(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function h_(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){if(t.length>e.length)return!1;for(let n=0;n<t.length;n++)if(!h_(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!h_(e[r],t[r]))return!1;return!0}return!1}var pPe=Object.prototype.hasOwnProperty;function mPe(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=hPe(e)&&hPe(t);if(!r&&!(gPe(e)&&gPe(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:pPe.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=mPe(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function g_(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n of Object.keys(e))if(!pPe.call(t,n)||e[n]!==t[n])return!1;return!0}function hPe(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function gPe(e){if(!_Pe(e))return!1;let t=Object.getPrototypeOf(e),n=t?.constructor;if(n===void 0)return!0;if(typeof n!=`function`)return!1;let r=n.prototype;return!(!_Pe(r)||!r.hasOwnProperty(`isPrototypeOf`)||t!==Object.prototype)}function _Pe(e){return Object.prototype.toString.call(e)===`[object Object]`}function vPe(e){return new Promise(t=>{d_.setTimeout(t,e)})}function yPe(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:mPe(e,t)}function __(e){return e}function bPe(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(-n):r}function xPe(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,n):r}var v_=Symbol();function SPe(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===v_?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function CPe(e,t){return typeof e==`function`?e(...t):!!e}var wPe=Symbol();function TPe(e,t,n,r){let i=!1,a;return Object.defineProperties(e,{[wPe]:{value:r},signal:{enumerable:!0,get:()=>(a??=t(),i||(i=!0,a.aborted?n():a.addEventListener(`abort`,n,{once:!0})),a)}}),e}var EPe=()=>oPe,DPe=()=>EPe(),y_=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(){}},OPe=new class extends y_{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},kPe=aPe;function APe(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=kPe,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var b_=APe(),x_=new class extends y_{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let 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.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function jPe(e){return Math.min(1e3*2**e,3e4)}function MPe(e){return(e??`online`)!==`online`||x_.isOnline()}var NPe=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function PPe(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(f_);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new NPe(t);h(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},f=()=>OPe.isFocused()&&(e.networkMode===`always`||x_.isOnline())&&e.canRun(),p=()=>MPe(e.networkMode)&&e.canRun(),m=e=>{c()||(r?.(),i=`resolved`,a(e))},h=e=>{c()||(r?.(),i=`rejected`,o(e))},g=t=>new Promise(n=>{r=e=>{(c()||t())&&n(e)},e.onPause?.()}).then(()=>{r=void 0,c()||e.onContinue?.()}),_=()=>{if(c())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(m).catch(r=>{if(c())return;let i=e.retry??(DPe()?0:3),a=e.retryDelay??jPe,o=typeof a==`function`?a(n,r):a,s=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);t||!s?h(r):(n++,e.onFail?.(n,r),vPe(o).then(()=>c()||f()?void 0:g(f)).then(()=>{t?h(r):_()}))})};return{promise:s,status:()=>i,cancel:l,continue:()=>(r?.(),s),cancelRetry:u,continueRetry:d,canStart:p,start:()=>(p()?_():g(p).then(_),s)}}var FPe=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),cPe(this.gcTime)&&(this.#e=d_.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(DPe()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(d_.clearTimeout(this.#e),this.#e=void 0)}};function IPe(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=t,u=e=>{TPe(e,()=>t.signal,()=>n=!0,l[wPe])},d=SPe(t.options,t.fetchOptions),f=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return u(e),e})(),o=await d(a),{maxPages:s}=t.options,c=i?xPe:bPe;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?RPe:LPe,n={pages:a,pageParams:o};s=await f(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]===void 0?r.initialPageParam:o[0]:LPe(r,s);if(c>0&&e==null)break;s=await f(s,e),c++}while(c<t)}return s};t.fetchFn=t.options.persister?()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function LPe(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function RPe(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function zPe(e,t){return t?LPe(e,t)!=null:!1}function BPe(e,t){return!t||!e.getPreviousPageParam?!1:RPe(e,t)!=null}var VPe=class extends FPe{#e;#t;#n;#r;#i;#a;#o;#s;#c;constructor(e){super(),this.#c=!1,this.#s=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=WPe(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#s,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=WPe(this.options);e.data!==void 0&&(this.setState(UPe(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=yPe(this.state.data,e,this.options);return this.#l({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(f_).catch(f_):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>p_(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===v_||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.state.data!==void 0&&this.getObserversCount()>0&&this.observers.some(e=>p_(e.options.staleTime,this)===`static`)}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:!lPe(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){let t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#a&&(this.#c||this.state.fetchStatus===`paused`&&this.state.status===`pending`?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#l({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a&&this.#o)return this.#a.continueRetry(),this.#o}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperties(e,{[wPe]:{value:n.signal,enumerable:!0},signal:{enumerable:!0,get:()=>(this.#c=!0,n.signal)}})},i=()=>{let e=SPe(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#c=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?IPe(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#l({type:`fetch`,meta:a.fetchOptions?.meta});let o=this.#a=PPe({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof NPe&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#l({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#l({type:`pause`})},onContinue:()=>{this.#l({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}),s=(async()=>{try{let e=await o.promise;if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof NPe){if(e.silent){if(this.#a!==o&&this.#o)return this.#o;throw e}if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#l({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.#a===o&&(this.#a=void 0,this.#o=void 0),this.scheduleGc()}})();return this.#o=s,o.start(),s}#l(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...HPe(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...UPe(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),b_.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function HPe(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:MPe(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function UPe(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function WPe(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var S_=class extends y_{#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),KPe(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return qPe(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return qPe(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let 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 p_(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!g_(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&JPe(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||p_(this.options.enabled,this.#t)!==p_(t.enabled,this.#t)||p_(this.options.staleTime,this.#t)!==p_(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||p_(this.options.enabled,this.#t)!==p_(t.enabled,this.#t)||i!==this.#f)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return g_(this.getCurrentResult(),n)||(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),Reflect.get(e,n))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t),r=()=>{},i,a=new Promise(e=>{i=e,r=this.#e.getQueryCache().subscribe(i=>{i.type===`updated`&&i.query.queryHash===n.queryHash&&n.state.data!==void 0&&(r(),e(this.createResult(n,t)))})});return Promise.race([n.fetch(t).then(()=>{let e=this.createResult(n,t);return i?.(e),e}).finally(()=>{r()}),a])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#m(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(f_)),t}#h(e){return!DPe()&&p_(this.options.enabled,this.#t)!==!1&&cPe(e)}#g(){this.#b();let e=p_(this.options.staleTime,this.#t);if(this.#r.isStale||!this.#h(e))return;let t=lPe(this.#r.dataUpdatedAt,e)+1;this.#u=d_.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return p_(this.options.refetchInterval,this.#t)??!1}#v(e){this.#x(),this.#f=e,this.#f!==0&&this.#h(this.#f)&&(this.#d=d_.setInterval(()=>{(this.options.refetchIntervalInBackground||OPe.isFocused())&&this.#m()},this.#f))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#u!==void 0&&(d_.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(d_.clearInterval(this.#d),this.#d=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&KPe(e,t),o=i&&JPe(e,n,t,r);(a||o)&&(l={...l,...HPe(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#l?.state.data,this.#l):t.placeholderData,e!==void 0&&(m=`success`,d=yPe(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h){if(i&&d===a?.data&&t.select===this.#s)d=this.#c;else try{this.#s=t.select,d=t.select(d),d=yPe(i?.data,d,t),this.#c=d,this.#o=null}catch(e){this.#o=e}}else d===void 0&&(this.#o=null);this.#o&&(f=this.#o,d=this.#c,p=Date.now(),m=`error`,u=!1);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,y=_&&g,b=d!==void 0;return{status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:y,isLoading:y,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!b,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&b,isStale:YPe(e,t),refetch:this.refetch,isEnabled:p_(t.enabled,e)!==!1}}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);if(this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#l=this.#t),g_(t,e))return;this.#r=t;let n=(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#p.size||this.options.throwOnError&&this.#r.error!==e.error)return!0;for(let t of n??this.#p)if(this.#r[t]!==e[t])return!0;return!1})();b_.batch(()=>{n&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}};function GPe(e,t){return p_(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||p_(t.retryOnMount,e)!==!1)}function KPe(e,t){return GPe(e,t)||e.state.data!==void 0&&qPe(e,t,t.refetchOnMount)}function qPe(e,t,n){if(p_(t.enabled,e)!==!1&&p_(t.staleTime,e)!==`static`){let r=p_(n,e);return r===`always`||r!==!1&&YPe(e,t)}return!1}function JPe(e,t,n,r){return(e!==t||p_(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&YPe(e,n)}function YPe(e,t){return p_(t.enabled,e)!==!1&&e.isStaleByTime(p_(t.staleTime,e))}var XPe=class extends S_{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type=`infinite`,super.setOptions(e)}getOptimisticResult(e){return e._type=`infinite`,super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:`forward`}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:`backward`}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:a,isError:o,isRefetchError:s}=r,c=n.fetchMeta?.fetchMore?.direction,l=o&&c===`forward`,u=i&&c===`forward`,d=o&&c===`backward`,f=i&&c===`backward`;return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:zPe(t,n.data),hasPreviousPage:BPe(t,n.data),isFetchNextPageError:l,isFetchingNextPage:u,isFetchPreviousPageError:d,isFetchingPreviousPage:f,isRefetchError:s&&!l&&!d,isRefetching:a&&!u&&!f}}},ZPe=class extends FPe{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||QPe(),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.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??(this.state.status===`pending`?this.execute(this.state.variables):Promise.resolve())}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},r=this.#r=PPe({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),i=this.state.status===`pending`,a=!r.canStart();try{if(i)t();else{this.#i({type:`pending`,variables:e,isPaused:a}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:a})}this.state.isPaused&&r.canStart()&&t();let o=await r.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#i({type:`success`,data:o}),o}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#r===r&&(this.#r=void 0),this.#n.runNext(this)}}#i(e){let t=t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,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{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}};this.state=t(this.state),b_.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function QPe(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var $Pe=class extends y_{#e;#t;#n;constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}build(e,t,n){let r=new ZPe({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=C_(e);if(typeof t==`string`){let 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)){let t=C_(e);if(typeof t==`string`){let n=this.#t.get(t);if(n){if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=C_(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}return!0}runNext(e){let t=C_(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){b_.batch(()=>{let e=this.getAll();this.#e.clear(),this.#t.clear(),e.forEach(e=>{this.notify({type:`removed`,mutation:e})})})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>dPe(t,e))}findAll(e={}){return this.getAll().filter(t=>dPe(e,t))}notify(e){b_.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return b_.batch(()=>Promise.all(e.map(e=>e.continue().catch(f_))))}};function C_(e){return e.options.scope?.id}var eFe=class extends y_{#e;#t=void 0;#n;#r;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),g_(this.options,t)||this.#e.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&m_(t.mutationKey)!==m_(this.options.mutationKey)?this.reset():this.#n?.state.status===`pending`&&this.#n.setOptions(this.options)}onSubscribe(){this.listeners.size===1&&this.#n&&(this.#n.addObserver(this),this.#i())}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#i(),this.#a()}mutate(e,t){return this.#r=t,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(e)}#i(){let e=this.#n?.state??QPe();this.#t={...e,isPending:e.status===`pending`,isSuccess:e.status===`success`,isError:e.status===`error`,isIdle:e.status===`idle`,mutate:this.mutate,reset:this.reset}}#a(e){b_.batch(()=>{let t=this.#r;if(t&&this.hasListeners()){let n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type===`success`){try{t.onSuccess?.(e.data,n,r,i)}catch(e){Promise.reject(e)}try{t.onSettled?.(e.data,null,n,r,i)}catch(e){Promise.reject(e)}}else if(e?.type===`error`){try{t.onError?.(e.error,n,r,i)}catch(e){Promise.reject(e)}try{t.onSettled?.(void 0,e.error,n,r,i)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}};function tFe(e,t){let n=new Set(t);return e.filter(e=>!n.has(e))}var nFe=class extends y_{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l=[];constructor(e,t,n){super(),this.#e=e,this.#r=n,this.#n=[],this.#i=[],this.#t=[],this.setQueries(t)}onSubscribe(){this.listeners.size===1&&this.#i.forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,this.#i.forEach(e=>{e.destroy()})}setQueries(e,t){this.#n=e,this.#r=t,b_.batch(()=>{let e=this.#i,t=this.#p(this.#n);t.forEach(e=>e.observer.setOptions(e.defaultedQueryOptions));let n=t.map(e=>e.observer),r=n.map(e=>e.getCurrentResult()),i=e.length!==n.length,a=n.some((t,n)=>t!==e[n]),o=i||a,s=o?!0:r.some((e,t)=>{let n=this.#t[t];return!n||!g_(e,n)});(o||s)&&(o&&(this.#l=t,this.#i=n),this.#t=r,this.hasListeners()&&(o&&(tFe(e,n).forEach(e=>{e.destroy()}),tFe(n,e).forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})),this.#h()))})}getCurrentResult(){return this.#t}getQueries(){return this.#i.map(e=>e.getCurrentQuery())}getObservers(){return this.#i}getOptimisticResult(e,t){let n=this.#p(e),r=n.map(e=>e.observer.getOptimisticResult(e.defaultedQueryOptions)),i=n.map(e=>e.defaultedQueryOptions.queryHash);return[r,e=>this.#d(e??r,t,i),()=>this.#u(r,n)]}#u(e,t){let n=new Set;return t.map((r,i)=>{let a=e[i];return r.defaultedQueryOptions.notifyOnChangeProps?a:r.observer.trackResult(a,e=>{n.has(e)||(n.add(e),t.forEach(t=>{t.observer.trackProp(e)}))})})}#d(e,t,n){if(t){let r=this.#c,i=n!==void 0&&r!==void 0&&(r.length!==n.length||n.some((e,t)=>e!==r[t]));return(this.#t!==this.#s||i||t!==this.#o)&&(this.#o=t,this.#s=this.#t,n!==void 0&&(this.#c=n),this.#a=mPe(this.#a,t(e))),this.#a}return e}#f(){return!this.#r?.combine||this.#i.some((e,t)=>e.options.suspense&&this.#t[t]?.data===void 0)}#p(e){let t=new Map;this.#i.forEach(e=>{let n=e.options.queryHash;if(!n)return;let r=t.get(n);r?r.push(e):t.set(n,[e])});let n=[];return e.forEach(e=>{let r=this.#e.defaultQueryOptions(e),i=t.get(r.queryHash)?.shift()??new S_(this.#e,r);n.push({defaultedQueryOptions:r,observer:i})}),n}#m(e,t){let n=this.#i.indexOf(e);n!==-1&&(this.#t=this.#t.slice(),this.#t[n]=t,this.#h())}#h(){if(this.hasListeners()){let e=this.#f(),t=this.#a,n=e?t:this.#d(this.#u(this.#t,this.#l),this.#r?.combine);(e||t!==n)&&b_.batch(()=>{this.listeners.forEach(e=>{e(this.#t)})})}}},rFe=class extends y_{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){let r=t.queryKey,i=t.queryHash??fPe(r,t),a=this.get(i);return a||(a=new VPe({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){this.#e.get(e.queryHash)===e&&(e.destroy(),this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){b_.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>uPe(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>uPe(e,t)):t}notify(e){b_.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){b_.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){b_.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},iFe=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new rFe,this.#t=e.mutationCache||new $Pe,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=OPe.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=x_.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(p_(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=sPe(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return b_.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;b_.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return b_.batch(()=>{let r=n.findAll(e),i=new Set(r);return r.forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,predicate:e=>i.has(e)},t)})}cancelQueries(e,t={}){let n={revert:!0,...t},r=b_.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(f_).catch(f_)}invalidateQueries(e,t={}){return b_.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=b_.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n),r=e.state.fetchStatus===`paused`;return(!n.throwOnError||r)&&(t=t.catch(f_)),r?Promise.resolve():t}));return Promise.all(r).then(f_)}async query(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t),r=n.isStaleByTime(p_(t.staleTime,n))?await n.fetch(t):n.state.data,i=t.select;return i?i(r):r}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(p_(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(f_).catch(f_)}infiniteQuery(e){return e._type=`infinite`,this.query(e)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(f_).catch(f_)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return x_.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(m_(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{h_(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(m_(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{h_(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=fPe(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===v_&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},aFe=G.createContext(!1),oFe=()=>G.useContext(aFe);aFe.Provider;function sFe(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var cFe=G.createContext(sFe()),lFe=()=>G.useContext(cFe),uFe=(e,t,n)=>{let r=n?.state.status===`error`&&typeof e.throwOnError==`function`?CPe(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},dFe=e=>{G.useEffect(()=>{e.clearReset()},[e])},fFe=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||CPe(n,[e.error,r])),pFe=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},mFe=(e,t)=>e?.suspense&&t.isPending,hFe=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function w_({queries:e,...t},n){let r=u_(n),i=oFe(),a=lFe(),o=t.subscribed!==!1,s=G.useMemo(()=>e.map(e=>{let t=r.defaultQueryOptions(e);return t._optimisticResults=i?`isRestoring`:o?`optimistic`:void 0,t}),[e,r,i,o]);s.forEach(e=>{pFe(e);let t=r.getQueryCache().get(e.queryHash);uFe(e,a,t)}),dFe(a);let[c]=G.useState(()=>new nFe(r,s,t)),[l,u,d]=c.getOptimisticResult(s,t.combine);G.useEffect(()=>{c.setQueries(s,t)},[s,t,c]);let f=!i&&o;G.useSyncExternalStore(G.useCallback(e=>f?c.subscribe(b_.batchCalls(e)):f_,[c,f]),()=>c.getCurrentResult(),()=>c.getCurrentResult());let p=l.some((e,t)=>mFe(s[t],e))?l.flatMap((e,t)=>{let n=s[t];return n&&mFe(n,e)?hFe(n,new S_(r,n),a):[]}):[];if(p.length>0)throw Promise.all(p);let m=l.find((e,t)=>{let n=s[t];return n&&fFe({result:e,errorResetBoundary:a,throwOnError:n.throwOnError,query:r.getQueryCache().get(n.queryHash),suspense:n.suspense})});if(m)throw m.error;return u(d())}function gFe(e,t,n){let r=oFe(),i=lFe(),a=u_(n),o=a.defaultQueryOptions(e),s=a.getQueryCache().get(o.queryHash),c=e.subscribed!==!1;o._optimisticResults=r?`isRestoring`:c?`optimistic`:void 0,pFe(o),uFe(o,i,s),dFe(i);let[l]=G.useState(()=>new t(a,o)),u=l.getOptimisticResult(o);G.useEffect(()=>{l.setOptions(o)},[o,l]);let d=!r&&c;if(G.useSyncExternalStore(G.useCallback(e=>{let t=d?l.subscribe(b_.batchCalls(e)):f_;return l.updateResult(),t},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),mFe(o,u))throw hFe(o,l,i);if(fFe({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw u.error;return o.notifyOnChangeProps?u:l.trackResult(u)}function T_(e,t){return gFe(e,S_,t)}function E_(e){return e}function D_(e,t){let n=u_(t),[r]=G.useState(()=>new eFe(n,e));G.useEffect(()=>{r.setOptions(e)},[r,e]);let i=G.useSyncExternalStore(G.useCallback(e=>r.subscribe(b_.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=G.useCallback((...e)=>{r.mutate(e[0],e[1]).catch(f_)},[r]);if(i.error&&CPe(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}function O_(e,t){return gFe(e,XPe,t)}function k_(e){return`user`in e&&e.user!==void 0}async function _Fe(e,t,n){return fetch(t,n)}function vFe(e,t){return(e,t)=>fetch(e,t)}var yFe=new WeakMap,bFe=0;function xFe(e){let t=yFe.get(e);if(t!==void 0)return t;let n=bFe++;return yFe.set(e,n),n}async function SFe(e,{redirectUri:t}){let{baseUrl:n=``,apiPrefix:r,headers:i={}}=e.options,a=(r||`/api`).trim(),o=(a.startsWith(`/`)?a:`/${a}`).replace(/\/$/,``),s=new URLSearchParams;t&&s.set(`redirect_uri`,t);let c=`${n}${o}/auth/sso/login${s.toString()?`?${s}`:``}`,l=await fetch(c,{credentials:`include`,headers:{...i,"Content-Type":`application/json`}});if(!l.ok)throw Error(`Failed to initiate SSO login: ${l.status}`);return l.json()}async function CFe(e){let{baseUrl:t=``,headers:n={},apiPrefix:r}=e.options,i=(r||`/api`).trim(),a=(i.startsWith(`/`)?i:`/${i}`).replace(/\/$/,``),o=await fetch(`${t}${a}/auth/capabilities`,{credentials:`include`,headers:{...n,"Content-Type":`application/json`}});if(!o.ok)throw Error(`Failed to fetch auth capabilities: ${o.status}`);return o.json()}function A_({queryOptions:e}={}){let t=Y();return T_({queryKey:[`auth`,`capabilities`,xFe(t)],queryFn:()=>CFe(t),staleTime:6e4,retry:!1,placeholderData:__,...e})}var wFe=3,TFe=8e3,EFe=class extends Error{status;constructor(e){super(`Failed to fetch current user: ${e}`),this.status=e,this.name=`CurrentUserError`}};function DFe(e){return e instanceof EFe&&e.status===401}function j_({queryOptions:e}={}){let t=Y().options?.baseUrl||``;return T_({queryKey:[`auth`,`me`],queryFn:async()=>{let e=await _Fe(t,`${t}/api/auth/me`,{credentials:`include`,headers:{"Content-Type":`application/json`}});if(!e.ok)throw new EFe(e.status);return e.json()},staleTime:6e4,retry:(e,t)=>!(t instanceof EFe)||t.status!==503?!1:e<wFe,retryDelay:e=>Math.min(TFe,500*2**e),...e})}var OFe=({queryOptions:e}={})=>{let t=Y(),{data:n,isLoading:r,error:i}=A_(),a=!!(n&&k_(n)&&n.capabilities.rbac),{data:o,isLoading:s,error:c}=T_({queryKey:[`permission-patterns`,xFe(t)],queryFn:()=>t.getPermissionPatterns(),enabled:a,retry:!1,staleTime:1/0,placeholderData:__,...e});return{patterns:(0,G.useMemo)(()=>new Set(o?.patterns??[]),[o]),isLoading:r||a&&s,error:i||c}};async function kFe(e,{email:t,password:n}){let{baseUrl:r=``,apiPrefix:i,headers:a={}}=e.options||{},o=(i??`/api`).trim(),s=(o===``?``:o.startsWith(`/`)?o:`/${o}`).replace(/\/+$/,``),c=await fetch(`${r}${s}/auth/credentials/sign-in`,{method:`POST`,credentials:`include`,headers:{...a,"Content-Type":`application/json`},body:JSON.stringify({email:t,password:n})}),l=await c.json();if(!c.ok)throw Error(l.message||l.error||`Invalid email or password`);return l}function AFe({queryOptions:e}={}){let t=Y(),n=u_();return D_({mutationFn:({email:e,password:n})=>kFe(t,{email:e,password:n}),onSuccess:()=>{n.invalidateQueries({queryKey:[`auth`]})},...e})}async function jFe(e,{email:t,password:n,name:r}){let{baseUrl:i=``,apiPrefix:a,headers:o={}}=e.options||{},s=(a??`/api`).trim(),c=(s===``?``:s.startsWith(`/`)?s:`/${s}`).replace(/\/+$/,``),l=await fetch(`${i}${c}/auth/credentials/sign-up`,{method:`POST`,credentials:`include`,headers:{...o,"Content-Type":`application/json`},body:JSON.stringify({email:t,password:n,name:r})}),u=await l.json();if(!l.ok)throw Error(u.message||u.error||`Failed to create account`);return u}function MFe({queryOptions:e}={}){let t=Y(),n=u_();return D_({mutationFn:({email:e,password:n,name:r})=>jFe(t,{email:e,password:n,name:r}),onSuccess:()=>{n.invalidateQueries({queryKey:[`auth`]})},...e})}function NFe({queryOptions:e}={}){let t=Y();return D_({mutationFn:({redirectUri:e})=>SFe(t,{redirectUri:e}),...e})}async function PFe(e){let{baseUrl:t=``,apiPrefix:n,headers:r={}}=e.options,i=(n||`/api`).trim(),a=(i.startsWith(`/`)?i:`/${i}`).replace(/\/$/,``),o=await fetch(`${t}${a}/auth/logout`,{method:`POST`,credentials:`include`,headers:{...r,"Content-Type":`application/json`}});if(!o.ok)throw Error(`Failed to logout: ${o.status}`);return o.json()}function FFe({onLoggedOut:e,queryOptions:t}={}){let n=Y(),r=u_();return D_({mutationFn:async t=>{let r=await PFe(n);return await e?.(t).catch(()=>{}),r},onSuccess:()=>{r.invalidateQueries({queryKey:[`auth`]})},...t})}var M_=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,N_=/^[\\/]{2}/;function IFe(e,t){return t+e.replace(/\\/g,`/`)}var LFe=`popstate`;function RFe(e){return typeof e==`object`&&!!e&&`pathname`in e&&`search`in e&&`hash`in e&&`state`in e&&`key`in e}function zFe(e={}){function t(e,t){let n=t.state?.masked,{pathname:r,search:i,hash:a}=n||e.location;return I_(``,{pathname:r,search:i,hash:a},t.state&&t.state.usr||null,t.state&&t.state.key||`default`,n?{pathname:e.location.pathname,search:e.location.search,hash:e.location.hash}:void 0)}function n(e,t){return typeof t==`string`?t:L_(t)}return HFe(t,n,null,e)}function P_(e,t){if(e===!1||e==null)throw Error(t)}function F_(e,t){if(!e){typeof console<`u`&&console.warn(t);try{throw Error(t)}catch{}}}function BFe(){return Math.random().toString(36).substring(2,10)}function VFe(e,t){return{usr:e.state,key:e.key,idx:t,masked:e.mask?{pathname:e.pathname,search:e.search,hash:e.hash}:void 0}}function I_(e,t,n=null,r,i){return{pathname:typeof e==`string`?e:e.pathname,search:``,hash:``,...typeof t==`string`?R_(t):t,state:n,key:t&&t.key||r||BFe(),mask:i}}function L_({pathname:e=`/`,search:t=``,hash:n=``}){return t&&t!==`?`&&(e+=t.charAt(0)===`?`?t:`?`+t),n&&n!==`#`&&(e+=n.charAt(0)===`#`?n:`#`+n),e}function R_(e){let t={};if(e){let n=e.indexOf(`#`);n>=0&&(t.hash=e.substring(n),e=e.substring(0,n));let r=e.indexOf(`?`);r>=0&&(t.search=e.substring(r),e=e.substring(0,r)),e&&(t.pathname=e)}return t}function HFe(e,t,n,r={}){let{window:i=document.defaultView,v5Compat:a=!1}=r,o=i.history,s=`POP`,c=null,l=u();l??(l=0,o.replaceState({...o.state,idx:l},``));function u(){return(o.state||{idx:null}).idx}function d(){s=`POP`;let e=u(),t=e==null?null:e-l;l=e,c&&c({action:s,location:h.location,delta:t})}function f(e,t){s=`PUSH`;let r=RFe(e)?e:I_(h.location,e,t);n&&n(r,e),l=u()+1;let d=VFe(r,l),f=h.createHref(r.mask||r);try{o.pushState(d,``,f)}catch(e){if(e instanceof DOMException&&e.name===`DataCloneError`)throw e;i.location.assign(f)}a&&c&&c({action:s,location:h.location,delta:1})}function p(e,t){s=`REPLACE`;let r=RFe(e)?e:I_(h.location,e,t);n&&n(r,e),l=u();let i=VFe(r,l),d=h.createHref(r.mask||r);o.replaceState(i,``,d),a&&c&&c({action:s,location:h.location,delta:0})}function m(e){return UFe(i,e)}let h={get action(){return s},get location(){return e(i,o)},listen(e){if(c)throw Error(`A history only accepts one active listener`);return i.addEventListener(LFe,d),c=e,()=>{i.removeEventListener(LFe,d),c=null}},createHref(e){return t(i,e)},createURL:m,encodeLocation(e){let t=m(e);return{pathname:t.pathname,search:t.search,hash:t.hash}},push:f,replace:p,go(e){return o.go(e)}};return h}function UFe(e,t,n=!1){let r=`http://localhost`;e&&(r=e.location.origin===`null`?e.location.href:e.location.origin),P_(r,`No window.location.(origin|href) available to create URL`);let i=typeof t==`string`?t:L_(t);return i=i.replace(/ $/,`%20`),!n&&N_.test(i)&&(i=r+i),new URL(i,r)}var WFe=class{#e=new Map;constructor(e){if(e)for(let[t,n]of e)this.set(t,n)}get(e){if(this.#e.has(e))return this.#e.get(e);if(e.defaultValue!==void 0)return e.defaultValue;throw Error(`No value found for context`)}set(e,t){this.#e.set(e,t)}},GFe=class extends Error{},KFe=new Set([`lazy`,`caseSensitive`,`path`,`id`,`index`,`children`,`unstable_validateParams`]);function qFe(e){return KFe.has(e)}var JFe=new Set([`lazy`,`caseSensitive`,`path`,`id`,`index`,`middleware`,`children`,`unstable_validateParams`]);function YFe(e){return JFe.has(e)}function XFe(e){return e.index===!0}function ZFe(e){let t={};return e.Component&&Object.assign(t,{element:G.createElement(e.Component),Component:void 0}),e.HydrateFallback&&Object.assign(t,{hydrateFallbackElement:G.createElement(e.HydrateFallback),HydrateFallback:void 0}),e.ErrorBoundary&&Object.assign(t,{errorElement:G.createElement(e.ErrorBoundary),ErrorBoundary:void 0}),t}function z_(e,t=ZFe,n=[],r={},i=!1){return e.map((e,a)=>{let o=[...n,String(a)],s=typeof e.id==`string`?e.id:o.join(`-`);if(P_(e.index!==!0||!e.children,`Cannot specify children on an index route`),P_(i||!r[s],`Found a route id collision on id "${s}". Route id's must be globally unique within Data Router usages`),XFe(e)){let n={...e,id:s};return r[s]=QFe(n,t(n)),n}{let n={...e,id:s,children:void 0};return r[s]=QFe(n,t(n)),e.children&&(n.children=z_(e.children,t,o,r,i)),n}})}function QFe(e,t){return Object.assign(e,{...t,...typeof t.lazy==`object`&&t.lazy!=null?{lazy:{...e.lazy,...t.lazy}}:{}})}function $Fe(e,t,n=`/`){return eIe(e,t,n,!1)}function eIe(e,t,n,r,i){let a=V_((typeof t==`string`?R_(t):t).pathname||`/`,n);if(a==null)return null;let o=i??nIe(e),s=null,c=bIe(a);for(let e=0;s==null&&e<o.length;++e)s=_Ie(o[e],c,r);return s}function tIe(e,t){let{route:n,pathname:r,params:i}=e;return{id:n.id,pathname:r,params:i,loaderData:t[n.id],handle:n.handle}}function nIe(e){let t=rIe(e);return aIe(t),t}function rIe(e,t=[],n=[],r=``,i=!1){let a=(e,a,o=i,s)=>{let c={relativePath:s===void 0?e.path||``:s,caseSensitive:e.caseSensitive===!0,childrenIndex:a,route:e};if(c.relativePath.startsWith(`/`)){if(!c.relativePath.startsWith(r)&&o)return;P_(c.relativePath.startsWith(r),`Absolute route path "${c.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),c.relativePath=c.relativePath.slice(r.length)}let l=W_([r,c.relativePath]),u=n.concat(c);e.children&&e.children.length>0&&(P_(e.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${l}".`),rIe(e.children,t,u,l,o)),(e.path!=null||e.index)&&t.push({path:l,score:hIe(l,e.index),routesMeta:u.map((e,t)=>{let[n,r]=yIe(e.relativePath,e.caseSensitive,t===u.length-1);return{...e,matcher:n,compiledParams:r}})})};return e.forEach((e,t)=>{if(e.path===``||!e.path?.includes(`?`))a(e,t);else for(let n of iIe(e.path))a(e,t,!0,n)}),t}function iIe(e){let t=e.split(`/`);if(t.length===0)return[];let[n,...r]=t,i=n.endsWith(`?`),a=n.replace(/\?$/,``);if(r.length===0)return i?[a,``]:[a];let o=iIe(r.join(`/`)),s=[];return s.push(...o.map(e=>e===``?a:[a,e].join(`/`))),i&&s.push(...o),s.map(t=>e.startsWith(`/`)&&t===``?`/`:t)}function aIe(e){e.sort((e,t)=>e.score===t.score?gIe(e.routesMeta.map(e=>e.childrenIndex),t.routesMeta.map(e=>e.childrenIndex)):t.score-e.score)}var oIe=/^:[\w-]+$/,sIe=/^:[\w-]+/,cIe=3.5,lIe=3,uIe=2,dIe=1,fIe=10,pIe=-2,mIe=e=>e===`*`;function hIe(e,t){let n=e.split(`/`),r=n.length;return n.some(mIe)&&(r+=pIe),t&&(r+=uIe),n.filter(e=>!mIe(e)).reduce((e,t)=>e+(oIe.test(t)?lIe:sIe.test(t)?cIe:t===``?dIe:fIe),r)}function gIe(e,t){return e.length===t.length&&e.slice(0,-1).every((e,n)=>e===t[n])?e[e.length-1]-t[t.length-1]:0}function _Ie(e,t,n=!1){let{routesMeta:r}=e,i={},a=`/`,o=[];for(let e=0;e<r.length;++e){let s=r[e],c=e===r.length-1,l=a===`/`?t:t.slice(a.length)||`/`,u={path:s.relativePath,caseSensitive:s.caseSensitive,end:c},d=s.matcher&&s.compiledParams?vIe(u,l,s.matcher,s.compiledParams):B_(u,l),f=s.route;if(!d&&c&&n&&!r[r.length-1].route.index&&(d=B_({path:s.relativePath,caseSensitive:s.caseSensitive,end:!1},l)),!d)return null;Object.assign(i,d.params),o.push({params:i,pathname:W_([a,d.pathname]),pathnameBase:OIe(W_([a,d.pathnameBase])),route:f}),d.pathnameBase!==`/`&&(a=W_([a,d.pathnameBase]))}return o}function B_(e,t){typeof e==`string`&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=yIe(e.path,e.caseSensitive,e.end);return vIe(e,t,n,r)}function vIe(e,t,n,r){let i=t.match(n);if(!i)return null;let a=i[0],o=G_(a,1),s=i.slice(1);return{params:r.reduce((e,{paramName:t,isOptional:n},r)=>{if(t===`*`){let e=s[r]||``;o=G_(a.slice(0,a.length-e.length),1)}let i=s[r];return e[t]=n&&!i?void 0:(i||``).replace(/%2F/g,`/`),e},{}),pathname:a,pathnameBase:o,pattern:e}}function yIe(e,t=!1,n=!0){F_(e===`*`||!e.endsWith(`*`)||e.endsWith(`/*`),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,`/*`)}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,`/*`)}".`);let r=[],i=`^`+e.replace(/\/*\*?$/,``).replace(/^\/*/,`/`).replace(/[\\.*+^${}|()[\]]/g,`\\$&`).replace(/\/:([\w-]+)(\?)?/g,(e,t,n,i,a)=>{if(r.push({paramName:t,isOptional:n!=null}),n){let t=a.charAt(i+e.length);return t&&t!==`/`?`/([^\\/]*)`:`(?:/([^\\/]*))?`}return`/([^\\/]+)`}).replace(/\/((?:[^/?()[\]*^\\]|\\.)+)\?(?=\/|$|\()/g,`(?:/$1)?`);return e.endsWith(`*`)?(r.push({paramName:`*`}),i+=e===`*`||e===`/*`?`(.*)$`:`(?:\\/(.+)|\\/*)$`):n?i+=`\\/*$`:e!==``&&e!==`/`&&(i+=`(?:(?=\\/|$))`),[new RegExp(i,t?void 0:`i`),r]}function bIe(e){try{return e.split(`/`).map(e=>decodeURIComponent(e).replace(/\//g,`%2F`)).join(`/`)}catch(t){return F_(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${t}).`),e}}function V_(e,t){if(t===`/`)return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith(`/`)?t.length-1:t.length,r=e.charAt(n);return r&&r!==`/`?null:e.slice(n)||`/`}function xIe({basename:e,pathname:t}){return t===`/`?e:W_([e,t])}var SIe=e=>M_.test(e);function CIe(e,t=`/`){let{pathname:n,search:r=``,hash:i=``}=typeof e==`string`?R_(e):e,a;return n?(n=DIe(n),a=n.startsWith(`/`)||n.startsWith(`\\`)?wIe(n.substring(1),`/`):wIe(n,t)):a=t,{pathname:a,search:kIe(r),hash:AIe(i)}}function wIe(e,t){let n=G_(t).split(`/`);return e.split(`/`).forEach(e=>{e===`..`?n.length>1&&n.pop():e!==`.`&&n.push(e)}),n.length>1?n.join(`/`):`/`}function TIe(e,t,n,r){return`Cannot include a '${e}' character in a manually specified \`to.${t}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function EIe(e){return e.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function H_(e){let t=EIe(e);return t.map((e,n)=>n===t.length-1?e.pathname:e.pathnameBase)}function U_(e,t,n,r=!1){let i;typeof e==`string`?i=R_(e):(i={...e},P_(!i.pathname||!i.pathname.includes(`?`),TIe(`?`,`pathname`,`search`,i)),P_(!i.pathname||!i.pathname.includes(`#`),TIe(`#`,`pathname`,`hash`,i)),P_(!i.search||!i.search.includes(`#`),TIe(`#`,`search`,`hash`,i)));let a=e===``||i.pathname===``,o=a?`/`:i.pathname,s;if(o==null)s=n;else{let e=t.length-1;if(!r&&o.startsWith(`..`)){let t=o.split(`/`);for(;t[0]===`..`;)t.shift(),--e;i.pathname=t.join(`/`)}s=e>=0?t[e]:`/`}let c=CIe(i,s),l=o&&o!==`/`&&o.endsWith(`/`),u=(a||o===`.`)&&n.endsWith(`/`);return!c.pathname.endsWith(`/`)&&(l||u)&&(c.pathname+=`/`),c}var DIe=e=>e.replace(/[\\/]{2,}/g,`/`),W_=e=>DIe(e.join(`/`));function G_(e,t=0){let n=e.length;for(;n>t&&e.charCodeAt(n-1)===47;)n--;return n===e.length?e:e.slice(0,n)}var OIe=e=>G_(e).replace(/^\/*/,`/`),kIe=e=>!e||e===`?`?``:e.startsWith(`?`)?e:`?`+e,AIe=e=>!e||e===`#`?``:e.startsWith(`#`)?e:`#`+e,K_=(e,t=302)=>{let n=t;typeof n==`number`?n={status:n}:n.status===void 0&&(n.status=302);let r=new Headers(n.headers);return r.set(`Location`,e),new Response(null,{...n,headers:r})},jIe=[`EvalError`,`RangeError`,`ReferenceError`,`SyntaxError`,`TypeError`,`URIError`],q_=class{status;statusText;data;error;internal;constructor(e,t,n,r=!1){this.status=e,this.statusText=t||``,this.internal=r,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function J_(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.internal==`boolean`&&`data`in e}function Y_(e){return W_(e.map(e=>e.route.path).filter(Boolean))||`/`}function MIe(e,t){let n=new URL(typeof e==`string`||e instanceof URL?e:e.url),r=typeof t==`string`?R_(t):t;if(n.pathname=r.pathname||`/`,r.search){let e=new URLSearchParams(r.search),t=e.getAll(`index`);e.delete(`index`);for(let n of t.filter(Boolean))e.append(`index`,n);let i=e.toString();n.search=i?`?${i}`:``}else n.search=``;return n.hash=r.hash||``,n}var NIe=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function PIe(e,t){let n=e;if(typeof n!=`string`||!M_.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,i=!1;if(NIe)try{let e=new URL(window.location.href),r=N_.test(n)?new URL(IFe(n,e.protocol)):new URL(n),a=V_(r.pathname,t);r.origin===e.origin&&a!=null?n=a+r.search+r.hash:i=!0}catch{F_(!1,`<Link to="${n}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:r,isExternal:i,to:n}}var FIe=Symbol(`Uninstrumented`),X_=new WeakMap;function IIe(e,t){let n={lazy:[],"lazy.loader":[],"lazy.action":[],"lazy.middleware":[],middleware:[],loader:[],action:[]};e.forEach(e=>e({id:t.id,index:t.index,path:t.path,instrument(e){e.lazy!=null&&n.lazy.push(e.lazy),e[`lazy.loader`]!=null&&n[`lazy.loader`].push(e[`lazy.loader`]),e[`lazy.action`]!=null&&n[`lazy.action`].push(e[`lazy.action`]),e[`lazy.middleware`]!=null&&n[`lazy.middleware`].push(e[`lazy.middleware`]),e.middleware!=null&&n.middleware.push(e.middleware),e.loader!=null&&n.loader.push(e.loader),e.action!=null&&n.action.push(e.action)}}));let r={};if(typeof t.lazy==`function`&&n.lazy.length>0){let e=t.lazy;r.lazy=async(...t)=>$_(await ev(n.lazy,void 0,()=>e(...t),tv))}if(typeof t.lazy==`object`){let e=t.lazy;if(typeof e.middleware==`function`&&n[`lazy.middleware`].length>0){let t=e.middleware;r.lazy=Object.assign(r.lazy||{},{middleware:async(...e)=>$_(await ev(n[`lazy.middleware`],void 0,()=>t(...e),tv))})}if(typeof e.loader==`function`&&n[`lazy.loader`].length>0){let t=e.loader;r.lazy=Object.assign(r.lazy||{},{loader:async(...e)=>$_(await ev(n[`lazy.loader`],void 0,()=>t(...e),tv))})}if(typeof e.action==`function`&&n[`lazy.action`].length>0){let t=e.action;r.lazy=Object.assign(r.lazy||{},{action:async(...e)=>$_(await ev(n[`lazy.action`],void 0,()=>t(...e),tv))})}}if(typeof t.loader==`function`&&n.loader.length>0){let e=Z_(t.loader),i=async(...t)=>$_(await ev(n.loader,BIe(t[0]),()=>e(...t),tv));e.hydrate===!0&&(i.hydrate=!0),Q_(i,e),r.loader=i}if(typeof t.action==`function`&&n.action.length>0){let e=Z_(t.action),i=async(...t)=>$_(await ev(n.action,BIe(t[0]),()=>e(...t),tv));Q_(i,e),r.action=i}return t.middleware&&t.middleware.length>0&&n.middleware.length>0&&(r.middleware=t.middleware.map(e=>{let t=Z_(e),r=async(...e)=>$_(await ev(n.middleware,BIe(e[0]),()=>t(...e),tv));return Q_(r,t),r})),r}function LIe(e,t){let n={navigate:[],fetch:[]};if(t.forEach(e=>e({instrument(e){e.navigate!=null&&n.navigate.push(e.navigate),e.fetch!=null&&n.fetch.push(e.fetch)}})),n.navigate.length>0){let t=Z_(e.navigate),r=async(...r)=>{let[i,a]=r,o,s={to:typeof i==`number`||typeof i==`string`?i:i?L_(i):`.`,...VIe(e,a??{})};return $_(await ev(n.navigate,s,async()=>{if(typeof i==`number`)return await t(...r);let n=RIe(e,e=>{o=e});try{return await t(...r)}finally{n()}},e=>({...tv(e),meta:o})))};Q_(r,t),e.navigate=r}if(n.fetch.length>0){let t=Z_(e.fetch),r=async(...r)=>{let[i,a,o,s]=r,c;return $_(await ev(n.fetch,{href:o??`.`,fetcherKey:i,...VIe(e,s??{})},async()=>{let n=RIe(e,e=>{c=e});try{return await t(...r)}finally{n()}},e=>({...tv(e),meta:c})))};Q_(r,t),e.fetch=r}return e}function Z_(e){return e[FIe]??e}function Q_(e,t){e[FIe]=t}function RIe(e,t){return X_.set(e,t),()=>{X_.get(e)===t&&X_.delete(e)}}function zIe(e){let t=X_.get(e);return X_.delete(e),t}function $_(e){if(e.type===`error`)throw e.value;return e.value}async function ev(e,t,n,r,i={result:null,innerResult:null},a=e.length-1){let o=e[a];if(o){let s,c=async()=>(s?console.error(`You cannot call instrumented handlers more than once`):s=ev(e,t,n,r,i,a-1),await s,P_(i.innerResult,`Expected an inner result`),i.innerResult);try{await o(c,t)}catch(e){console.error(`An instrumentation function threw an error:`,e)}s||await c(),await s}else{try{i.result={type:`success`,value:await n()}}catch(e){i.result={type:`error`,value:e}}i.innerResult=r(i.result,t)}return i.result||(i.result={type:`error`,value:Error(`No result assigned in instrumentation chain.`)},i.innerResult=r(i.result,t)),i.result}function tv(e){return e.type===`error`&&e.value instanceof Error?{status:`error`,error:e.value}:{status:`success`,error:void 0}}function BIe(e){let{request:t,context:n,params:r}=e;return{...e,request:HIe(t),params:{...r},context:UIe(n)}}function VIe(e,t){return{currentUrl:L_(e.state.location),...`formMethod`in t?{formMethod:t.formMethod}:{},...`formEncType`in t?{formEncType:t.formEncType}:{},...`formData`in t?{formData:t.formData}:{},...`body`in t?{body:t.body}:{}}}function HIe(e){return{method:e.method,url:e.url,headers:{get:(...t)=>e.headers.get(...t)}}}function UIe(e){return{get:t=>e.get(t)}}var WIe=class{#e=[];#t=[];#n;#r=0;constructor(e){this.#n=e}update(e){this.#e=e,this.#t=nIe(e),this.#r=this.#t.reduce((e,t)=>e+t.routesMeta.length,0)}get matchCost(){return this.#r}match(e,t=!1){return eIe(this.#e,e,this.#n,t,this.#t)}},GIe=new URL(`http://localhost`);function KIe(e){if(e.createURL)return e.createURL(`/`);try{return new URL(e.createHref(`/`),GIe)}catch{return GIe}}function qIe(e,t){return e.origin===t.origin&&(e.origin!==`null`||e.protocol===t.protocol&&e.host===t.host)}function JIe(e,t){if(e.startsWith(`//`))return!0;let n=t.protocol.toLowerCase();return e.toLowerCase().startsWith(n)?t.host===``||e.slice(n.length).startsWith(`//`):!1}function nv(e,t,n,r){let i=null;try{i=e==null?null:new URL(e,n)}catch{}let a=new URL(t,n),o=i!=null&&!qIe(i,n),s=!qIe(a,n);if(r===`reject`){if(o||s)throw Error(`External navigation is not allowed`)}else if(s&&(i==null||!JIe(e,i)||!qIe(i,a)))throw Error(`External navigation is not allowed`)}var YIe=[`POST`,`PUT`,`PATCH`,`DELETE`],XIe=new Set(YIe),ZIe=[`GET`,...YIe],QIe=new Set(ZIe),$Ie=new Set([301,302,303,307,308]),eLe=new Set([307,308]),rv={state:`idle`,location:void 0,matches:void 0,historyAction:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},tLe={state:`idle`,data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},iv={state:`unblocked`,proceed:void 0,reset:void 0,location:void 0},nLe=`remix-router-transitions`,rLe=Symbol(`ResetLoaderData`);function iLe(e,t){return e.unstable_routePatternMatching?(P_(void 0,`You must call unstable_preloadRoutePattern() from "react-router/route-pattern" before enabling future.unstable_routePatternMatching.`),new(void 0)(t)):new WIe(t)}var aLe=class{#e;#t;#n;constructor(e,t){this.#e=e,this.#n=t,this.#n.update(e)}get stableRoutes(){return this.#e}get activeRoutes(){return this.#t??this.#e}get hasHMRRoutes(){return this.#t!=null}setRoutes(e){this.#e=e,this.#t||this.#n.update(e)}setHmrRoutes(e){this.#t=e,this.#n.update(e)}commitHmrRoutes(){this.#t&&(this.#e=this.#t,this.#t=void 0,this.#n.update(this.#e))}},av=new WeakMap;function oLe(e){let t=e.window?e.window:typeof window<`u`?window:void 0,n=t!==void 0&&t.document!==void 0&&t.document.createElement!==void 0;P_(e.routes.length>0,`You must provide a non-empty routes array to createRouter`);let r=e.hydrationRouteProperties||[],i=e.mapRouteProperties,a=i||(()=>({}));if(e.instrumentations){let t=e.instrumentations;a=e=>({...i?.(e),...IIe(t.map(e=>e.route).filter(Boolean),e)})}let o={...e.future},s=e.basename||`/`;s.startsWith(`/`)||(s=`/${s}`);let c=iLe(o,s),l={},u=new aLe(z_(e.routes,a,void 0,l),c),d=e.dataStrategy||xLe,f=null,p=new Set,m=null,h=null,g=null,_=e.hydrationData!=null,v=c.match(e.history.location),y=!1,b=null,x,S;if(v==null&&!e.patchRoutesOnNavigation){let t=fv(404,{pathname:e.history.location.pathname}),{matches:n,route:r}=dv(u.activeRoutes);x=!0,S=!x,v=n,b={[r.id]:t}}else if(v&&!e.hydrationData&&Ue(v,e.history.location.pathname).active&&(v=null),!v){x=!1,S=!x,v=[];let t=Ue(null,e.history.location.pathname);t.active&&t.matches&&(y=!0,v=t.matches)}else if(v.some(e=>e.route.lazy))x=!1,S=!x;else if(!v.some(e=>dLe(e.route)))x=!0,S=!x;else{let t=e.hydrationData?e.hydrationData.loaderData:null,n=e.hydrationData?e.hydrationData.errors:null,r=v;if(n){let e=v.findIndex(e=>n[e.route.id]!==void 0);r=r.slice(0,e+1)}S=!1,x=!0,r.forEach(e=>{let r=fLe(e.route,t,n);S||=r.renderFallback,x&&=!r.shouldLoad})}let C,w={historyAction:e.history.action,location:e.history.location,matches:v,initialized:x,renderFallback:S,navigation:rv,restoreScrollPosition:e.hydrationData==null&&null,preventScrollReset:!1,revalidation:`idle`,loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||b,fetchers:new Map,blockers:new Map},T=`POP`,E=0,D,O=null,k=!1,A,j=!1,M=new Map,N=null,P=!1,F=!1,I=new Set,L=new Map,R=0,z=-1,B=new Map,V=new Set,H=new Map,ee=new Map,te=new Set,U=new Map,W,ne=null;function re(){if(f=e.history.listen(({action:t,location:n,delta:r})=>{if(W){W(),W=void 0;return}F_(U.size===0||r!=null,"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");let i=Le({currentLocation:w.location,nextLocation:n,historyAction:t});if(i&&r!=null){let t=new Promise(e=>{W=e});e.history.go(r*-1),Ie(i,{state:`blocked`,location:n,proceed(){Ie(i,{state:`proceeding`,proceed:void 0,reset:void 0,location:n}),t.then(()=>e.history.go(r))},reset(){let e=new Map(w.blockers);e.set(i,iv),oe({blockers:e})}}),O?.resolve(),O=null}else return o.unstable_customRouteDiscovery&&(E+=r||0),de(t,n)}),n){iRe(t,M);let e=()=>aRe(t,M);t.addEventListener(`pagehide`,e),N=()=>t.removeEventListener(`pagehide`,e)}return w.initialized||de(`POP`,w.location,{initialHydration:!0}),C}function ie(){f&&f(),N&&N(),p.clear(),A&&A.abort(),w.fetchers.forEach((e,t)=>Oe(w.fetchers,t)),w.blockers.forEach((e,t)=>Fe(t))}function ae(e){return p.add(e),()=>p.delete(e)}function oe(e,t={}){let n=e.errors??null,r=n?av.get(n):void 0;r!==void 0&&(n=r),(e.errors!==void 0||e.initialized)&&(w.errors&&av.delete(w.errors),e.errors&&av.set(e.errors,n)),e.matches&&=e.matches.map(e=>{let t=l[e.route.id],n=e.route;return n.element!==t.element||n.errorElement!==t.errorElement||n.hydrateFallbackElement!==t.hydrateFallbackElement?{...e,route:t}:e}),w={...w,...e};let i=[],a=[];w.fetchers.forEach((e,t)=>{e.state===`idle`&&(te.has(t)?i.push(t):a.push(t))}),te.forEach(e=>{!w.fetchers.has(e)&&!L.has(e)&&i.push(e)}),[...p].forEach(e=>e(w,{deletedFetchers:i,newErrors:n,viewTransitionOpts:t.viewTransitionOpts,flushSync:t.flushSync===!0})),i.forEach(e=>Oe(w.fetchers,e)),a.forEach(e=>w.fetchers.delete(e))}function se(t,n,{flushSync:r}={}){let i=w.actionData!=null&&w.navigation.formMethod!=null&&gv(w.navigation.formMethod)&&w.navigation.state===`loading`&&t.state?._isRedirect!==!0,a;a=n.actionData?Object.keys(n.actionData).length>0?n.actionData:null:i?w.actionData:null;let o=n.loaderData?zLe(w.loaderData,n.loaderData,n.matches||[],n.errors):w.loaderData,s=w.blockers;s.size>0&&!P&&(s=new Map(s),s.forEach((e,t)=>s.set(t,iv)));let c=!P&&He(t,n.matches||w.matches),l=k===!0||w.navigation.formMethod!=null&&gv(w.navigation.formMethod)&&t.state?._isRedirect!==!0;u.commitHmrRoutes(),P||T===`POP`||(T===`PUSH`?e.history.push(t,t.state):T===`REPLACE`&&e.history.replace(t,t.state));let d;if(T===`POP`&&!P&&t!==w.location){let e=M.get(w.location.pathname);e&&e.has(t.pathname)?d={currentLocation:w.location,nextLocation:t}:M.has(t.pathname)&&(d={currentLocation:t,nextLocation:w.location})}else if(j){let e=M.get(w.location.pathname);e?e.add(t.pathname):(e=new Set([t.pathname]),M.set(w.location.pathname,e)),d={currentLocation:w.location,nextLocation:t}}oe({...n,actionData:a,loaderData:o,historyAction:T,location:t,initialized:!0,renderFallback:!1,navigation:rv,revalidation:`idle`,restoreScrollPosition:c,preventScrollReset:l,blockers:s},{viewTransitionOpts:d,flushSync:r===!0}),ce(),O?.resolve(),O=null,ne?.resolve(),ne=null}function ce(){E=0,T=`POP`,k=!1,j=!1,P=!1,F=B.size>0}async function le(t,n){if(D&&await D,O?.resolve(),O=null,typeof t==`number`){O||=oRe();let n=O.promise;return e.history.go(t),n}let r=zIe(C),{path:i,submission:a,error:o}=lLe(!1,cLe(w.location,w.matches,s,t,n?.fromRouteId,n?.relative),n),c;if(n?.mask){let t=typeof n.mask==`string`?R_(n.mask):{...w.location.mask,...n.mask};if(c={pathname:t.pathname??``,search:t.search??``,hash:t.hash??``},N_.test(c.pathname))throw Error(`External navigation is not allowed`);c.pathname.startsWith(`\\`)&&(c.pathname=c.pathname.replace(/^\\+/,`/`)),nv(typeof n.mask==`string`?n.mask:L_(n.mask),L_(c),e.history.createURL(`/`),`reject`)}let l=w.location,u=I_(l,i,n&&n.state,void 0,c);u={...u,...e.history.encodeLocation(u)},nv(t==null?e.history.createHref(w.location):typeof t==`string`?t:L_(t),e.history.createHref(u.mask||u),e.history.createURL(`/`),`reject`);let d=n&&n.replace!=null?n.replace:void 0,f=`PUSH`,p=w.location.pathname+w.location.search;d===!0?f=`REPLACE`:d===!1||a!=null&&gv(a.formMethod)&&(a.formAction===p||u.pathname+u.search===p)&&(f=`REPLACE`);let m=n&&`preventScrollReset`in n?n.preventScrollReset===!0:void 0,h=(n&&n.flushSync)===!0,g=Le({currentLocation:l,nextLocation:u,historyAction:f});g?Ie(g,{state:`blocked`,location:u,proceed(){Ie(g,{state:`proceeding`,proceed:void 0,reset:void 0,location:u}),le(t,n)},reset(){let e=new Map(w.blockers);e.set(g,iv),oe({blockers:e})}}):await de(f,u,{submission:a,pendingError:o,preventScrollReset:m,replace:n&&n.replace,enableViewTransition:n&&n.viewTransition,flushSync:h,callSiteDefaultShouldRevalidate:n&&n.defaultShouldRevalidate,instrumentationNavigateMetaReceiver:r})}function ue(){if(D)return D.then(ue);ne||=oRe(),Ce(),oe({revalidation:`loading`});let e=ne.promise;return w.navigation.state===`submitting`?e:w.navigation.state===`idle`?(de(w.historyAction,w.location,{startUninterruptedRevalidation:!0,dataStrategyInitiator:`revalidation`}),e):(de(T||w.historyAction,w.navigation.location,{overrideNavigation:w.navigation,dataStrategyInitiator:`revalidation`,enableViewTransition:j===!0}),e)}async function de(t,n,r){D&&await D,A&&A.abort(),A=null,T=t,P=(r&&r.startUninterruptedRevalidation)===!0,Ve(w.location,w.matches),k=(r&&r.preventScrollReset)===!0,j=(r&&r.enableViewTransition)===!0;let i=r?.initialHydration&&w.matches&&w.matches.length>0&&!y?w.matches:c.match(n),a=(r&&r.flushSync)===!0;if(i&&w.initialized&&!F&&HLe(w.location,n)&&!(r&&r.submission&&gv(r.submission.formMethod))){se(n,{matches:i},{flushSync:a});return}let o=Ue(i,n.pathname);if(o.active&&o.matches&&(i=o.matches),r?.instrumentationNavigateMetaReceiver){let t=$Le(e.history,n,i);r.instrumentationNavigateMetaReceiver(t)}if(!i){let{error:e,notFoundMatches:t,route:r}=Re(n.pathname);se(n,{matches:t,loaderData:{},errors:{[r.id]:e}},{flushSync:a});return}let s=r&&r.overrideNavigation?{...r.overrideNavigation,matches:i,historyAction:t}:void 0;A=new AbortController;let l=lv(e.history,n,A.signal,r&&r.submission),u=r?.initialHydration?`initialization`:r?.dataStrategyInitiator??`navigation`,d=e.getContext?await e.getContext():new WFe,f;if(r&&r.pendingError)f=[uv(i).route.id,{type:`error`,error:r.pendingError}];else if(r&&r.submission&&gv(r.submission.formMethod)){let c=await pe(l,u,n,r.submission,i,t,d,o.active,r&&r.initialHydration===!0,{replace:r.replace,flushSync:a});if(c.shortCircuited)return;if(c.pendingActionResult){let[e,t]=c.pendingActionResult;if(mv(t)&&J_(t.error)&&t.error.status===404){A=null,se(n,{matches:c.matches,loaderData:{},errors:{[e]:t.error}});return}}i=c.matches||i,f=c.pendingActionResult,s=tRe(n,i,t,r.submission),a=!1,o.active=!1,l=lv(e.history,l.url,l.signal)}let{shortCircuited:p,matches:m,loaderData:h,errors:g,workingFetchers:_}=await me(l,u,n,i,t,d,o.active,s,r&&r.submission,r&&r.fetcherSubmission,r&&r.replace,r&&r.initialHydration===!0,a,f,r&&r.callSiteDefaultShouldRevalidate);p||(A=null,se(n,{matches:m||i,...BLe(f),loaderData:h,errors:g,..._?{fetchers:_}:{}}))}function fe(){let t=oRe();D=t.promise;let n=E,r=O;O=null,A?.abort(),A=null,ce(),ne?.resolve(),ne=null;let i=new Map(w.blockers);i.forEach((e,t)=>{e.state===`proceeding`&&i.set(t,iv)});let a=new Map(w.fetchers),o=Me(a);a.forEach((e,t)=>{e.state===`loading`&&!L.has(t)&&(a.set(t,yv(e.data)),o=!0)}),I.clear(),oe({navigation:rv,revalidation:`idle`,blockers:i,...o?{fetchers:a}:{}});function s(){D=void 0,r?.resolve(),t.resolve()}return n?(W=s,e.history.go(-n)):s(),t.promise}async function pe(t,n,i,c,d,f,p,m,h,g={}){if(o.unstable_customRouteDiscovery||Ce(),oe({navigation:nRe(i,d,f,c)},{flushSync:g.flushSync===!0}),m){let e=await We(d,i.pathname,t.signal);if(o.unstable_customRouteDiscovery&&t.signal.aborted||e.type===`aborted`)return{shortCircuited:!0};if(e.type===`cancelled`)return await fe(),{shortCircuited:!0};if(e.type===`error`){if(e.partialMatches.length===0){let{matches:t,route:n}=dv(u.activeRoutes);return{matches:t,pendingActionResult:[n.id,{type:`error`,error:e.error}]}}let t=uv(e.partialMatches).route.id;return{matches:e.partialMatches,pendingActionResult:[t,{type:`error`,error:e.error}]}}if(e.matches)d=e.matches;else{let{notFoundMatches:e,error:t,route:n}=Re(i.pathname);return{matches:e,pendingActionResult:[n.id,{type:`error`,error:t}]}}}o.unstable_customRouteDiscovery&&Ce();let _,v=_v(d,i);if(!v.route.action&&!v.route.lazy)_={type:`error`,error:fv(405,{method:t.method,pathname:i.pathname,routeId:v.route.id})};else{let e=await xe(t,i,cv(a,l,t,i,d,v,h?[]:r,p),p,null,n,f);if(_=e[v.route.id],!_){for(let t of d)if(e[t.route.id]){_=e[t.route.id];break}}if(t.signal.aborted)return{shortCircuited:!0}}if(hv(_)){let r;return r=g&&g.replace!=null?g.replace:PLe(_.response.headers.get(`Location`),new URL(t.url),s,e.history)===w.location.pathname+w.location.search,await be(t,_,!0,n,{submission:c,replace:r}),{shortCircuited:!0}}if(mv(_)){let e=uv(d,v.route.id);return(g&&g.replace)!==!0&&(T=`PUSH`),{matches:d,pendingActionResult:[e.route.id,_,v.route.id]}}return{matches:d,pendingActionResult:[v.route.id,_]}}async function me(t,n,i,s,d,f,p,m,h,g,_,v,y,b,x){let S=m||tRe(i,s,d,h),C=h||g||eRe(S),T=!P&&!v;if(p){if(T){let e=he(b);oe({navigation:S,...e===void 0?{}:{actionData:e}},{flushSync:y})}let e=await We(s,i.pathname,t.signal);if(o.unstable_customRouteDiscovery&&t.signal.aborted||e.type===`aborted`)return{shortCircuited:!0};if(e.type===`cancelled`)return await fe(),{shortCircuited:!0};if(e.type===`error`){if(e.partialMatches.length===0){let{matches:t,route:n}=dv(u.activeRoutes);return{matches:t,loaderData:{},errors:{[n.id]:e.error}}}let t=uv(e.partialMatches).route.id;return{matches:e.partialMatches,loaderData:{},errors:{[t]:e.error}}}if(e.matches)s=e.matches,v&&!t.signal.aborted&&oe({matches:s});else{let{error:e,notFoundMatches:t,route:n}=Re(i.pathname);return{matches:t,loaderData:{},errors:{[n.id]:e}}}}let{dsMatches:E,revalidatingFetchers:D}=uLe(t,f,a,l,e.history,w,s,C,i,v?[]:r,v===!0,F,I,te,H,V,c,b,x);if(z=++R,!e.dataStrategy&&!E.some(e=>e.shouldLoad)&&!E.some(e=>e.route.middleware&&e.route.middleware.length>0)&&D.length===0){let e=new Map(w.fetchers),t=Me(e);return se(i,{matches:s,loaderData:{},errors:b&&mv(b[1])?{[b[0]]:b[1].error}:null,...BLe(b),...t?{fetchers:e}:{}},{flushSync:y}),{shortCircuited:!0}}if(T){let e={};if(!p){e.navigation=S;let t=he(b);t!==void 0&&(e.actionData=t)}D.length>0&&(e.fetchers=ge(D)),oe(e,{flushSync:y})}D.forEach(e=>{Ae(e.key),e.controller&&L.set(e.key,e.controller)});let O=()=>D.forEach(e=>{L.get(e.key)===e.controller&&Ae(e.key)});A&&A.signal.addEventListener(`abort`,O);let{loaderResults:k,fetcherResults:j}=await Se(E,D,t,i,f,n,d);if(t.signal.aborted)return{shortCircuited:!0};A&&A.signal.removeEventListener(`abort`,O),D.forEach(e=>{L.get(e.key)===e.controller&&L.delete(e.key)});let M=pv(k);if(M)return await be(t,M.result,!0,n,{replace:_}),{shortCircuited:!0};if(M=pv(j),M)return V.add(M.key),await be(t,M.result,!0,n,{replace:_}),{shortCircuited:!0};let N=new Map(w.fetchers),{loaderData:B,errors:ee}=RLe(w,s,k,b,D,j,N);if(v&&w.errors){let e=ee??null;ee={...w.errors,...ee},av.set(ee,e)}let U=Me(N),W=Ne(z,N),ne=U||W||D.length>0;return{matches:s,loaderData:B,errors:ee,...ne?{workingFetchers:N}:{}}}function he(e){if(e&&!mv(e[1]))return{[e[0]]:e[1].data};if(w.actionData)return Object.keys(w.actionData).length===0?null:w.actionData}function ge(e){let t=new Map(w.fetchers);return e.forEach(e=>{let n=t.get(e.key),r=vv(void 0,n?n.data:void 0);t.set(e.key,r)}),t}async function _e(t,n,r,i){D&&await D,Ae(t);let a=(i&&i.flushSync)===!0,o=zIe(C),l=cLe(w.location,w.matches,s,r,n,i?.relative),u=c.match(l),d=Ue(u,l);if(d.active&&d.matches&&(u=d.matches),o&&o($Le(e.history,l,u)),!u){Te(t,n,fv(404,{pathname:l}),{flushSync:a});return}let{path:f,submission:p,error:m}=lLe(!0,l,i);if(m){Te(t,n,m,{flushSync:a});return}let h=e.getContext?await e.getContext():new WFe,g=(i&&i.preventScrollReset)===!0;if(p&&gv(p.formMethod)){await ve(t,n,f,u,h,d.active,a,g,p,i&&i.defaultShouldRevalidate);return}let _={routeId:n,path:f,isDiscovering:d.active};H.set(t,_),await ye(t,_,u,h,a,g,p)}async function ve(t,n,i,s,u,d,f,p,m,h){o.unstable_customRouteDiscovery||Ce(),H.delete(t);let g=w.fetchers.get(t);we(t,rRe(m,g),{flushSync:f});let _=new AbortController;o.unstable_customRouteDiscovery&&L.set(t,_);let v=lv(e.history,i,_.signal,m);if(d){let e=await We(s,new URL(v.url).pathname,v.signal,t);if(o.unstable_customRouteDiscovery&&v.signal.aborted||e.type===`aborted`)return;if(e.type===`cancelled`){L.delete(t),H.delete(t),we(t,yv(g?.data),{flushSync:f});return}if(e.type===`error`){Te(t,n,e.error,{flushSync:f});return}if(e.matches)s=e.matches;else{Te(t,n,fv(404,{pathname:i}),{flushSync:f});return}}let y=_v(s,i);if(!y.route.action&&!y.route.lazy){Te(t,n,fv(405,{method:m.formMethod,pathname:i,routeId:n}),{flushSync:f});return}o.unstable_customRouteDiscovery&&Ce(),L.set(t,_);let b=R,x=cv(a,l,v,i,s,y,r,u),S=await xe(v,i,x,u,t,`fetcher`),C=S[y.route.id];if(!C){for(let e of x)if(S[e.route.id]){C=S[e.route.id];break}}if(v.signal.aborted){L.get(t)===_&&L.delete(t);return}if(te.has(t)){if(mv(C)){we(t,yv(void 0));return}hv(C)&&(F=!0,C={type:`data`,data:void 0})}else{if(hv(C)){if(z>b)F=!0,C={type:`data`,data:void 0};else return L.delete(t),V.add(t),we(t,vv(m)),be(v,C,!1,`fetcher`,{fetcherSubmission:m,preventScrollReset:p})}if(mv(C)){Te(t,n,C.error);return}}F=!0;let E=w.navigation.location||w.location,D=lv(e.history,E,_.signal),O=w.navigation.state===`idle`?w.matches:c.match(w.navigation.location);P_(O,`Didn't find any matches after fetcher action`);let k=++R;B.set(t,k);let{dsMatches:j,revalidatingFetchers:M}=uLe(D,u,a,l,e.history,w,O,m,E,r,!1,F,I,te,H,V,c,[y.route.id,C],h),N=vv(m,C.data),P=new Map(w.fetchers);P.set(t,N),M.filter(e=>e.key!==t).forEach(e=>{let t=e.key,n=P.get(t),r=vv(void 0,n?n.data:void 0);P.set(t,r),Ae(t),e.controller&&L.set(t,e.controller)}),oe({fetchers:P});let ee=()=>M.forEach(e=>{L.get(e.key)===e.controller&&Ae(e.key)});_.signal.addEventListener(`abort`,ee);let{loaderResults:U,fetcherResults:W}=await Se(j,M,D,E,u,`fetcher`);if(_.signal.aborted){B.get(t)===k&&B.delete(t);return}_.signal.removeEventListener(`abort`,ee),B.delete(t),L.delete(t),M.forEach(e=>{L.get(e.key)===e.controller&&L.delete(e.key)});let ne=w.fetchers.has(t),re=e=>{if(!ne)return e;let n=new Map(e.fetchers);return n.set(t,yv(C.data)),{...e,fetchers:n}},ie=pv(U);if(ie)return w=re(w),be(D,ie.result,!1,`fetcher`,{preventScrollReset:p});if(ie=pv(W),ie)return V.add(ie.key),w=re(w),be(D,ie.result,!1,`fetcher`,{preventScrollReset:p});let ae=new Map(w.fetchers);ne&&ae.set(t,yv(C.data));let{loaderData:ce,errors:le}=RLe(w,O,U,void 0,M,W,ae);Ne(k,ae),w.navigation.state===`loading`&&k>z?(P_(T,`Expected pending action`),A&&A.abort(),Me(ae),se(w.navigation.location,{matches:O,loaderData:ce,errors:le,fetchers:ae})):(oe({errors:le,loaderData:zLe(w.loaderData,ce,O,le),fetchers:ae}),F=B.size>0)}async function ye(t,n,i,s,c,u,d){let{routeId:f,path:p}=n,m=w.fetchers.get(t);we(t,vv(d,m?m.data:void 0),{flushSync:c});let h=new AbortController;o.unstable_customRouteDiscovery&&L.set(t,h);let g=lv(e.history,p,h.signal);if(n.isDiscovering){let e=await We(i,new URL(g.url).pathname,g.signal,t);if(o.unstable_customRouteDiscovery&&g.signal.aborted||e.type===`aborted`)return;if(e.type===`cancelled`){L.delete(t),H.delete(t),we(t,yv(m?.data),{flushSync:c});return}if(e.type===`error`){Te(t,f,e.error,{flushSync:c});return}if(e.matches)i=e.matches,n.isDiscovering=!1;else{Te(t,f,fv(404,{pathname:p}),{flushSync:c});return}}let _=_v(i,p);L.set(t,h);let v=R,y=await xe(g,p,cv(a,l,g,p,i,_,r,s),s,t,`fetcher`),b=y[_.route.id];if(!b){for(let e of i)if(y[e.route.id]){b=y[e.route.id];break}}if(L.get(t)===h&&L.delete(t),!g.signal.aborted){if(te.has(t))we(t,yv(void 0));else{if(hv(b)){if(z>v){we(t,yv(void 0));return}V.add(t),await be(g,b,!1,`fetcher`,{preventScrollReset:u});return}mv(b)?Te(t,f,b.error):we(t,yv(b.data))}}}async function be(r,i,a,o,{submission:c,fetcherSubmission:l,preventScrollReset:u,replace:d}={}){a||(O?.resolve(),O=null),i.response.headers.has(`X-Remix-Revalidate`)&&(F=!0);let f=i.response.headers.get(`Location`);P_(f,`Expected a Location header on the redirect Response`);let p=f,m=new URL(r.url);f=PLe(f,m,s,e.history),nv(p,f,m,`allow-explicit`);let h=I_(w.location,f,{_isRedirect:!0});if(n){let e=!1;if(i.response.headers.has(`X-Remix-Reload-Document`))e=!0;else if(SIe(f)){let n=UFe(t,f,!0);e=n.origin!==t.location.origin||V_(n.pathname,s)==null}if(e){d?t.location.replace(f):t.location.assign(f);return}}A=null;let g=d===!0||i.response.headers.has(`X-Remix-Replace`)?`REPLACE`:`PUSH`,{formMethod:_,formAction:v,formEncType:y}=w.navigation;!c&&!l&&_&&v&&y&&(c=eRe(w.navigation));let b=c||l;eLe.has(i.response.status)&&b&&gv(b.formMethod)?await de(g,h,{submission:{...b,formAction:f},preventScrollReset:u||k,enableViewTransition:a?j:void 0,dataStrategyInitiator:o}):await de(g,h,{overrideNavigation:tRe(h,[],g,c),fetcherSubmission:l,preventScrollReset:u||k,enableViewTransition:a?j:void 0,dataStrategyInitiator:o})}async function xe(e,t,n,r,i,a,o=null){let c,l={};try{c=await DLe(d,e,t,n,i,a,r,!1,o)}catch(e){return n.filter(e=>e.shouldLoad).forEach(t=>{l[t.route.id]={type:`error`,error:e}}),l}if(e.signal.aborted)return l;if(!gv(e.method))for(let e of n){if(c[e.route.id]?.type===`error`)break;c.hasOwnProperty(e.route.id)||w.loaderData.hasOwnProperty(e.route.id)||w.errors&&w.errors.hasOwnProperty(e.route.id)||!e.shouldCallHandler()||(c[e.route.id]={type:`error`,result:Error(`No result returned from dataStrategy for route ${e.route.id}`)})}for(let[t,r]of Object.entries(c))if(KLe(r)){let i=r.result;l[t]={type:`redirect`,response:jLe(i,e,t,n,s)}}else l[t]=await ALe(r);return l}async function Se(e,t,n,r,i,a,o=null){let s=xe(n,r,e,i,null,a,o),c=Promise.all(t.map(async e=>{if(e.matches&&e.match&&e.request&&e.controller){let t=(await xe(e.request,e.path,e.matches,i,e.key,a,o))[e.match.route.id];return{[e.key]:t}}return Promise.resolve({[e.key]:{type:`error`,error:fv(404,{pathname:e.path})}})}));return{loaderResults:await s,fetcherResults:(await c).reduce((e,t)=>Object.assign(e,t),{})}}function Ce(){F=!0,H.forEach((e,t)=>{o.unstable_customRouteDiscovery&&e.isDiscovering||(L.has(t)&&I.add(t),Ae(t))})}function we(e,t,n={}){let r=new Map(w.fetchers);r.set(e,t),oe({fetchers:r},{flushSync:(n&&n.flushSync)===!0})}function Te(e,t,n,r={}){let i=uv(w.matches,t),a=new Map(w.fetchers);Oe(a,e),oe({errors:{[i.route.id]:n},fetchers:a},{flushSync:(r&&r.flushSync)===!0})}function Ee(e){return ee.set(e,(ee.get(e)||0)+1),te.has(e)&&te.delete(e),w.fetchers.get(e)||tLe}function De(e,t){Ae(e,t?.reason),H.delete(e),I.delete(e),we(e,yv(null))}function Oe(e,t){let n=w.fetchers.get(t);L.has(t)&&!(n&&n.state===`loading`&&B.has(t))&&Ae(t),H.delete(t),B.delete(t),V.delete(t),te.delete(t),I.delete(t),e.delete(t)}function ke(e){let t=(ee.get(e)||0)-1;t<=0?(ee.delete(e),te.add(e)):ee.set(e,t),oe({fetchers:new Map(w.fetchers)})}function Ae(e,t){let n=L.get(e);n&&(n.abort(t),L.delete(e))}function je(e,t){for(let n of e){let e=t.get(n);P_(e,`Expected fetcher: ${n}`);let r=yv(e.data);t.set(n,r)}}function Me(e){let t=[],n=!1;for(let r of V){let i=e.get(r);P_(i,`Expected fetcher: ${r}`),i.state===`loading`&&(V.delete(r),t.push(r),n=!0)}return je(t,e),n}function Ne(e,t){let n=[];for(let[r,i]of B)if(i<e){let e=t.get(r);P_(e,`Expected fetcher: ${r}`),e.state===`loading`&&(Ae(r),B.delete(r),n.push(r))}return je(n,t),n.length>0}function Pe(e,t){let n=w.blockers.get(e)||iv;return U.get(e)!==t&&U.set(e,t),n}function Fe(e){w.blockers.delete(e),U.delete(e)}function Ie(e,t){let n=w.blockers.get(e)||iv;P_(n.state===`unblocked`&&t.state===`blocked`||n.state===`blocked`&&t.state===`blocked`||n.state===`blocked`&&t.state===`proceeding`||n.state===`blocked`&&t.state===`unblocked`||n.state===`proceeding`&&t.state===`unblocked`,`Invalid blocker state transition: ${n.state} -> ${t.state}`);let r=new Map(w.blockers);r.set(e,t),oe({blockers:r})}function Le({currentLocation:e,nextLocation:t,historyAction:n}){if(U.size===0)return;U.size>1&&F_(!1,`A router only supports one blocker at a time`);let r=Array.from(U.entries()),[i,a]=r[r.length-1],o=w.blockers.get(i);if(!(o&&o.state===`proceeding`)&&a({currentLocation:e,nextLocation:t,historyAction:n}))return i}function Re(e){let t=fv(404,{pathname:e}),n=u.activeRoutes,{matches:r,route:i}=dv(n);return{notFoundMatches:r,route:i,error:t}}function ze(e,t,n){if(m=e,g=t,h=n||null,!_&&w.navigation===rv){_=!0;let e=He(w.location,w.matches);e!=null&&oe({restoreScrollPosition:e})}return()=>{m=null,g=null,h=null}}function Be(e,t){return h&&h(e,t.map(e=>tIe(e,w.loaderData)))||e.key}function Ve(e,t){if(m&&g){let n=Be(e,t);m[n]=g()}}function He(e,t){if(m){let n=Be(e,t),r=m[n];if(typeof r==`number`)return r}return null}function Ue(t,n){if(e.patchRoutesOnNavigation){if(!t)return{active:!0,matches:c.match(n,!0)||[]};if(Object.keys(t[0].params).length>0)return{active:!0,matches:c.match(n,!0)}}return{active:!1,matches:null}}async function We(t,n,r,i){if(!e.patchRoutesOnNavigation)return{type:`success`,matches:t};let s=t;for(;;){let t=l;try{await e.patchRoutesOnNavigation({signal:r,path:n,matches:s,fetcherKey:i,patch:(e,n)=>{r.aborted||hLe(e,n,u,t,a,!1)}})}catch(e){if(o.unstable_customRouteDiscovery){if(r.aborted)return{type:`aborted`};if(e instanceof GFe)return{type:`cancelled`}}return{type:`error`,error:e,partialMatches:s}}if(r.aborted)return{type:`aborted`};let d=c.match(n),f=null;if(d&&(Object.keys(d[0].params).length===0||(f=c.match(n,!0),!(f&&s.length<f.length&&Ge(s,f.slice(0,s.length))))))return{type:`success`,matches:d};if(f||=c.match(n,!0),!f||Ge(s,f))return{type:`success`,matches:null};s=f}}function Ge(e,t){return e.length===t.length&&e.every((e,n)=>e.route.id===t[n].route.id)}function Ke(e){l={},u.setHmrRoutes(z_(e,a,void 0,l))}function qe(e,t,n=!1){hLe(e,t,u,l,a,n),u.hasHMRRoutes||oe({})}return C={get basename(){return s},get future(){return o},get state(){return w},get routes(){return u.stableRoutes},match(e){return c.match(e)},get manifest(){return l},get window(){return t},initialize:re,subscribe:ae,enableScrollRestoration:ze,navigate:le,fetch:_e,revalidate:ue,createHref:t=>e.history.createHref(t),createURL:t=>e.history.createURL(t),encodeLocation:t=>e.history.encodeLocation(t),getFetcher:Ee,resetFetcher:De,deleteFetcher:ke,dispose:ie,getBlocker:Pe,deleteBlocker:Fe,patchRoutes:qe,_internalFetchControllers:L,_internalSetRoutes:Ke,_internalSetStateDoNotUseOrYouWillBreakYourApp(e){oe(e)}},e.instrumentations&&(C=LIe(C,e.instrumentations.map(e=>e.router).filter(Boolean))),C}function sLe(e){return e!=null&&(`formData`in e&&e.formData!=null||`body`in e&&e.body!==void 0)}function cLe(e,t,n,r,i,a){let o,s;if(i){o=[];for(let e of t)if(o.push(e),e.route.id===i){s=e;break}}else o=t,s=t[t.length-1];let c=U_(r||`.`,H_(o),V_(e.pathname,n)||e.pathname,a===`path`);if(r??(c.search=e.search,c.hash=e.hash),(r==null||r===``||r===`.`)&&s){let e=QLe(c.search);if(s.route.index&&!e)c.search=c.search?c.search.replace(/^\?/,`?index&`):`?index`;else if(!s.route.index&&e){let e=new URLSearchParams(c.search),t=e.getAll(`index`);e.delete(`index`),t.filter(e=>e).forEach(t=>e.append(`index`,t));let n=e.toString();c.search=n?`?${n}`:``}}return n!==`/`&&(c.pathname=xIe({basename:n,pathname:c.pathname})),L_(c)}function lLe(e,t,n){if(!n||!sLe(n))return{path:t};if(n.formMethod&&!ZLe(n.formMethod))return{path:t,error:fv(405,{method:n.formMethod})};let r=()=>({path:t,error:fv(400,{type:`invalid-body`})}),i=(n.formMethod||`get`).toUpperCase(),a=VLe(t);if(n.body!==void 0){if(n.formEncType===`text/plain`){if(!gv(i))return r();let e=typeof n.body==`string`?n.body:n.body instanceof FormData||n.body instanceof URLSearchParams?Array.from(n.body.entries()).reduce((e,[t,n])=>`${e}${t}=${n}\n`,``):String(n.body);return{path:t,submission:{formMethod:i,formAction:a,formEncType:n.formEncType,formData:void 0,json:void 0,text:e}}}if(n.formEncType===`application/json`){if(!gv(i))return r();try{let e=typeof n.body==`string`?JSON.parse(n.body):n.body;return{path:t,submission:{formMethod:i,formAction:a,formEncType:n.formEncType,formData:void 0,json:e,text:void 0}}}catch{return r()}}}P_(typeof FormData==`function`,`FormData is not available in this environment`);let o,s;if(n.formData)o=FLe(n.formData),s=n.formData;else if(n.body instanceof FormData)o=FLe(n.body),s=n.body;else if(n.body instanceof URLSearchParams)o=n.body,s=ILe(o);else if(n.body==null)o=new URLSearchParams,s=new FormData;else try{o=new URLSearchParams(n.body),s=ILe(o)}catch{return r()}let c={formMethod:i,formAction:a,formEncType:n&&n.formEncType||`application/x-www-form-urlencoded`,formData:s,json:void 0,text:void 0};if(gv(c.formMethod))return{path:t,submission:c};let l=R_(t);return e&&l.search&&QLe(l.search)&&o.append(`index`,``),l.search=`?${o}`,{path:L_(l),submission:c}}function uLe(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v){let y=_?mv(_[1])?_[1].error:_[1].data:void 0,b=i.createURL(a.location),x=i.createURL(c),S;if(u&&a.errors){let e=Object.keys(a.errors)[0];S=o.findIndex(t=>t.route.id===e)}else if(_&&mv(_[1])){let e=_[0];S=o.findIndex(t=>t.route.id===e)-1}let C=_?_[1].statusCode:void 0,w=C&&C>=400,T={currentUrl:b,currentParams:a.matches[0]?.params||{},nextUrl:x,nextParams:o[0].params,...s,actionResult:y,actionStatus:C},E=Y_(o),D=o.map((i,o)=>{let{route:s}=i,f=null;if(S!=null&&o>S)f=!1;else if(s.lazy)f=!0;else if(!dLe(s))f=!1;else if(u){let{shouldLoad:e}=fLe(s,a.loaderData,a.errors);f=e}else pLe(a.loaderData,a.matches[o],i)&&(f=!0);if(f!==null)return ELe(n,r,e,c,E,i,l,t,f);let p=!1;typeof v==`boolean`?p=v:w?p=!1:d||b.pathname+b.search===x.pathname+x.search?p=!0:b.search===x.search?mLe(a.matches[o],i)&&(p=!0):p=!0;let m={...T,defaultShouldRevalidate:p};return ELe(n,r,e,c,E,i,l,t,ov(i,m),m,v)}),O=[];return m.forEach((e,s)=>{if(u||!o.some(t=>t.route.id===e.routeId)||p.has(s)||e.isDiscovering)return;let c=a.fetchers.get(s),m=c&&c.state!==`idle`&&c.data===void 0,_=g.match(e.path);if(!_){O.push({key:s,routeId:e.routeId,path:e.path,matches:null,match:null,request:null,controller:null});return}if(h.has(s))return;let y=_v(_,e.path),b=new AbortController,x=lv(i,e.path,b.signal),S=null;if(f.has(s))f.delete(s),S=cv(n,r,x,e.path,_,y,l,t);else if(m)d&&(S=cv(n,r,x,e.path,_,y,l,t));else{let i;i=typeof v==`boolean`?v:!w&&d;let a={...T,defaultShouldRevalidate:i};ov(y,a)&&(S=cv(n,r,x,e.path,_,y,l,t,a))}S&&O.push({key:s,routeId:e.routeId,path:e.path,matches:S,match:y,request:x,controller:b})}),{dsMatches:D,revalidatingFetchers:O}}function dLe(e){return e.loader!=null||e.middleware!=null&&e.middleware.length>0}function fLe(e,t,n){if(e.lazy)return{shouldLoad:!0,renderFallback:!0};if(!dLe(e))return{shouldLoad:!1,renderFallback:!1};let r=t!=null&&e.id in t,i=n!=null&&n[e.id]!==void 0;if(!r&&i)return{shouldLoad:!1,renderFallback:!1};if(typeof e.loader==`function`&&e.loader.hydrate===!0)return{shouldLoad:!0,renderFallback:!r};let a=!r&&!i;return{shouldLoad:a,renderFallback:a}}function pLe(e,t,n){let r=!t||n.route.id!==t.route.id,i=!e.hasOwnProperty(n.route.id);return r||i}function mLe(e,t){let n=e.route.path;return e.pathname!==t.pathname||n!=null&&n.endsWith(`*`)&&e.params[`*`]!==t.params[`*`]}function ov(e,t){if(e.route.shouldRevalidate){let n=e.route.shouldRevalidate(t);if(typeof n==`boolean`)return n}return t.defaultShouldRevalidate}function hLe(e,t,n,r,i,a){let o;if(e){let t=r[e];P_(t,`No route found to patch children into: routeId = ${e}`),t.children||=[],o=t.children}else o=n.activeRoutes;let s=[],c=[];if(t.forEach(e=>{let t=o.find(t=>gLe(e,t));t?c.push({existingRoute:t,newRoute:e}):s.push(e)}),s.length>0){let t=z_(s,i,[e||`_`,`patch`,String(o?.length||`0`)],r);o.push(...t)}if(a&&c.length>0)for(let e=0;e<c.length;e++){let{existingRoute:t,newRoute:n}=c[e],r=t,[a]=z_([n],i,[],{},!0);Object.assign(r,{element:a.element?a.element:r.element,errorElement:a.errorElement?a.errorElement:r.errorElement,hydrateFallbackElement:a.hydrateFallbackElement?a.hydrateFallbackElement:r.hydrateFallbackElement})}n.hasHMRRoutes||n.setRoutes([...n.activeRoutes])}function gLe(e,t){return`id`in e&&`id`in t&&e.id===t.id?!0:e.index!==t.index||e.path!==t.path||e.caseSensitive!==t.caseSensitive?!1:(!e.children||e.children.length===0)&&(!t.children||t.children.length===0)?!0:e.children?.every((e,n)=>t.children?.some(t=>gLe(e,t)))??!1}var _Le=new WeakMap,vLe=({key:e,route:t,manifest:n,mapRouteProperties:r})=>{let i=n[t.id];if(P_(i,`No route found in manifest`),!i.lazy||typeof i.lazy!=`object`)return;let a=i.lazy[e];if(!a)return;let o=_Le.get(i);o||(o={},_Le.set(i,o));let s=o[e];if(s)return s;let c=(async()=>{let t=qFe(e),n=i[e]!==void 0;if(t)F_(!t,`Route property `+e+` is not a supported lazy route property. This property will be ignored.`),o[e]=Promise.resolve();else if(n)F_(!1,`Route "${i.id}" has a static property "${e}" defined. The lazy property will be ignored.`);else{let t=await a();t!=null&&(Object.assign(i,{[e]:t}),Object.assign(i,r(i)))}typeof i.lazy==`object`&&(i.lazy[e]=void 0,Object.values(i.lazy).every(e=>e===void 0)&&(i.lazy=void 0))})();return o[e]=c,c.catch(()=>{o[e]===c&&delete o[e]}),c},sv=new WeakMap;function yLe(e,t,n,r,i){let a=n[e.id];if(P_(a,`No route found in manifest`),!e.lazy)return{lazyRoutePromise:void 0,lazyHandlerPromise:void 0};if(typeof e.lazy==`function`){let t=sv.get(a);if(t)return{lazyRoutePromise:t,lazyHandlerPromise:t};let n=(async()=>{P_(typeof e.lazy==`function`,`No lazy route function found`);let t=await e.lazy(),n={};for(let e in t){let r=t[e];if(r===void 0)continue;let i=YFe(e),o=a[e]!==void 0;i?F_(!i,`Route property `+e+` is not a supported property to be returned from a lazy route function. This property will be ignored.`):o?F_(!o,`Route "${a.id}" has a static property "${e}" defined but its lazy function is also returning a value for this property. The lazy route property "${e}" will be ignored.`):n[e]=r}Object.assign(a,n),Object.assign(a,{...r(a),lazy:void 0})})();return sv.set(a,n),n.catch(()=>{sv.get(a)===n&&sv.delete(a)}),{lazyRoutePromise:n,lazyHandlerPromise:n}}let o=Object.keys(e.lazy),s=[],c;for(let a of o){if(i&&i.includes(a))continue;let o=vLe({key:a,route:e,manifest:n,mapRouteProperties:r});o&&(s.push(o),a===t&&(c=o))}let l=s.length>0?Promise.all(s).then(()=>{}):void 0;return l?.catch(()=>{}),c?.catch(()=>{}),{lazyRoutePromise:l,lazyHandlerPromise:c}}async function bLe(e){let t=e.matches.filter(e=>e.shouldLoad),n={};return(await Promise.all(t.map(e=>e.resolve()))).forEach((e,r)=>{n[t[r].route.id]=e}),n}async function xLe(e){return e.matches.some(e=>e.route.middleware)?SLe(e,()=>bLe(e)):bLe(e)}function SLe(e,t){return CLe(e,t,e=>{if(XLe(e))throw e;return e},WLe,n);async function n(t,n,r){if(r)return Object.assign(r.value,{[n]:{type:`error`,result:t}});{let{matches:r}=e,i=Math.min(Math.max(r.findIndex(e=>e.route.id===n),0),Math.max(r.findIndex(e=>e.shouldCallHandler()),0)),a=r[i].route.id;for(let e of r.slice(0,i+1))try{await e._lazyPromises?.route}catch{a=e.route.id;break}return{[uv(r,a).route.id]:{type:`error`,result:t}}}}}async function CLe(e,t,n,r,i){let{matches:a,...o}=e;return await wLe(o,a.flatMap(e=>e.route.middleware?e.route.middleware.map(t=>[e.route.id,t]):[]),t,n,r,i)}async function wLe(e,t,n,r,i,a,o=0){let{request:s}=e;if(s.signal.aborted)throw s.signal.reason??Error(`Request aborted: ${s.method} ${s.url}`);let c=t[o];if(!c)return await n();let[l,u]=c,d,f=async()=>{if(d)throw Error("You may only call `next()` once per middleware");try{return d={value:await wLe(e,t,n,r,i,a,o+1)},d.value}catch(e){return d={value:await a(e,l,d)},d.value}};try{let t=await u(e,f),n=t==null?void 0:r(t);return i(n)?n:d?n??d.value:(d={value:await f()},d.value)}catch(e){return await a(e,l,d)}}function TLe(e,t,n,r,i){let a=vLe({key:`middleware`,route:r.route,manifest:t,mapRouteProperties:e}),o=yLe(r.route,gv(n.method)?`action`:`loader`,t,e,i);return{middleware:a,route:o.lazyRoutePromise,handler:o.lazyHandlerPromise}}function ELe(e,t,n,r,i,a,o,s,c,l=null,u){let d=!1,f=TLe(e,t,n,a,o);return{...a,_lazyPromises:f,shouldLoad:c,shouldRevalidateArgs:l,shouldCallHandler(e){return d=!0,l?typeof u==`boolean`?ov(a,{...l,defaultShouldRevalidate:u}):typeof e==`boolean`?ov(a,{...l,defaultShouldRevalidate:e}):ov(a,l):c},resolve(e){let{lazy:t,loader:o,middleware:l}=a.route,u=d||c||e&&!gv(n.method)&&(t||o),p=l&&l.length>0&&!o&&!t;return u&&(gv(n.method)||!p)?OLe({request:n,path:r,pattern:i,match:a,lazyHandlerPromise:f?.handler,lazyRoutePromise:f?.route,handlerOverride:e,scopedContext:s}):Promise.resolve({type:`data`,result:void 0})}}}function cv(e,t,n,r,i,a,o,s,c=null){return i.map(l=>l.route.id===a.route.id?ELe(e,t,n,r,Y_(i),l,o,s,!0,c):{...l,shouldLoad:!1,shouldRevalidateArgs:c,shouldCallHandler:()=>!1,_lazyPromises:TLe(e,t,n,l,o),resolve:()=>Promise.resolve({type:`data`,result:void 0})})}async function DLe(e,t,n,r,i,a,o,s,c=null){r.some(e=>e._lazyPromises?.middleware)&&await Promise.all(r.map(e=>e._lazyPromises?.middleware));let l={request:t,url:MIe(t,n),pattern:Y_(r),params:r[0].params,context:o,matches:r,unstable_initiator:a,unstable_navigationType:a===`navigation`?c:null},u=s?()=>{throw Error("You cannot call `runClientMiddleware()` from a static handler `dataStrategy`. Middleware is run outside of `dataStrategy` during SSR in order to bubble up the Response. You can enable middleware via the `respond` API in `query`/`queryRoute`")}:e=>{let t=l;return SLe(t,()=>e({...t,fetcherKey:i,runClientMiddleware:()=>{throw Error("Cannot call `runClientMiddleware()` from within an `runClientMiddleware` handler")}}))},d=await e({...l,fetcherKey:i,runClientMiddleware:u});try{await Promise.all(r.flatMap(e=>[e._lazyPromises?.handler,e._lazyPromises?.route]))}catch{}return d}async function OLe({request:e,path:t,pattern:n,match:r,lazyHandlerPromise:i,lazyRoutePromise:a,handlerOverride:o,scopedContext:s}){let c,l,u=gv(e.method),d=u?`action`:`loader`,f=i=>{let a,c=new Promise((e,t)=>a=t);l=()=>a(),e.signal.addEventListener(`abort`,l);let u=a=>typeof i==`function`?i({request:e,url:MIe(e,t),pattern:n,params:r.params,context:s},...a===void 0?[]:[a]):Promise.reject(Error(`You cannot call the handler for a route which defines a boolean "${d}" [routeId: ${r.route.id}]`)),f=(async()=>{try{return{type:`data`,result:await(o?o(e=>u(e)):u())}}catch(e){return{type:`error`,result:e}}})();return Promise.race([f,c])};try{let t=u?r.route.action:r.route.loader;if(i||a){if(t){let e,[n]=await Promise.all([f(t).catch(t=>{e=t}),i,a]);if(e!==void 0)throw e;c=n}else{await i;let t=u?r.route.action:r.route.loader;if(t)[c]=await Promise.all([f(t),a]);else if(d===`action`){let t=new URL(e.url),n=t.pathname+t.search;throw fv(405,{method:e.method,pathname:n,routeId:r.route.id})}else return await a,{type:`data`,result:void 0}}}else if(t)c=await f(t);else{let t=new URL(e.url);throw fv(404,{pathname:t.pathname+t.search})}}catch(e){return{type:`error`,result:e}}finally{l&&e.signal.removeEventListener(`abort`,l)}return c}async function kLe(e){let t=e.headers.get(`Content-Type`);return t&&/\bapplication\/json\b/.test(t)?e.body==null?null:e.json():e.text()}async function ALe(e){let{result:t,type:n}=e;if(JLe(t)){let e;try{e=await kLe(t)}catch(e){return{type:`error`,error:e}}return n===`error`?{type:`error`,error:new q_(t.status,t.statusText,e),statusCode:t.status,headers:t.headers}:{type:`data`,data:e,statusCode:t.status,headers:t.headers}}return n===`error`?qLe(t)?t.data instanceof Error?{type:`error`,error:t.data,statusCode:t.init?.status,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:`error`,error:ULe(t),statusCode:J_(t)?t.status:void 0,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:`error`,error:t,statusCode:J_(t)?t.status:void 0}:qLe(t)?{type:`data`,data:t.data,statusCode:t.init?.status,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:`data`,data:t}}function jLe(e,t,n,r,i){let a=e.headers.get(`Location`);if(P_(a,`Redirects returned/thrown from loaders/actions must have a Location header`),!SIe(a)){let o=r.slice(0,r.findIndex(e=>e.route.id===n)+1);a=cLe(new URL(t.url),o,i,a),e.headers.set(`Location`,a)}return e}var MLe=[`about:`,`blob:`,`chrome:`,`chrome-untrusted:`,`content:`,`data:`,`devtools:`,`file:`,`filesystem:`,`javascript:`];function NLe(e){try{return MLe.includes(new URL(e).protocol)}catch{return!1}}function PLe(e,t,n,r){if(SIe(e)){let r=e,i=N_.test(r)?new URL(IFe(r,t.protocol)):new URL(r);if(NLe(i.toString()))throw Error(`Invalid redirect location`);let a=V_(i.pathname,n)!=null;if(i.origin===t.origin&&a)return DIe(i.pathname)+i.search+i.hash}try{if(NLe(r.createURL(e).toString()))throw Error(`Invalid redirect location`)}catch{}return e}function lv(e,t,n,r){let i=e.createURL(VLe(t)).toString(),a={signal:n};if(r&&gv(r.formMethod)){let{formMethod:e,formEncType:t}=r;a.method=e.toUpperCase(),t===`application/json`?(a.headers=new Headers({"Content-Type":t}),a.body=JSON.stringify(r.json)):a.body=t===`text/plain`?r.text:t===`application/x-www-form-urlencoded`&&r.formData?FLe(r.formData):r.formData}return new Request(i,a)}function FLe(e){let t=new URLSearchParams;for(let[n,r]of e.entries())t.append(n,typeof r==`string`?r:r.name);return t}function ILe(e){let t=new FormData;for(let[n,r]of e.entries())t.append(n,r);return t}function LLe(e,t,n,r=!1,i=!1){let a={},o=null,s,c=!1,l={},u=n&&mv(n[1])?n[1].error:void 0;return e.forEach(n=>{if(!(n.route.id in t))return;let d=n.route.id,f=t[d];if(P_(!hv(f),`Cannot handle redirect results in processLoaderData`),mv(f)){let t=f.error;if(u!==void 0&&(t=u,u=void 0),o||={},i)o[d]=t;else{let n=uv(e,d);o[n.route.id]??(o[n.route.id]=t)}r||(a[d]=rLe),c||(c=!0,s=J_(f.error)?f.error.status:500),f.headers&&(l[d]=f.headers)}else a[d]=f.data,f.statusCode&&f.statusCode!==200&&!c&&(s=f.statusCode),f.headers&&(l[d]=f.headers)}),u!==void 0&&n&&(o={[n[0]]:u},n[2]&&(a[n[2]]=void 0)),{loaderData:a,errors:o,statusCode:s||200,loaderHeaders:l}}function RLe(e,t,n,r,i,a,o){let{loaderData:s,errors:c}=LLe(t,n,r);return i.filter(e=>!e.matches||e.matches.some(e=>e.shouldLoad)).forEach(t=>{let{key:n,routeId:r,controller:i}=t;if(i&&i.signal.aborted)return;let s=a[n];if(P_(s,`Did not find corresponding fetcher result`),mv(s)){let t=uv(e.matches,r);c&&c[t.route.id]||(c={...c,[t.route.id]:s.error}),o.delete(n)}else if(hv(s))P_(!1,`Unhandled fetcher revalidation redirect`);else{let e=yv(s.data);o.set(n,e)}}),{loaderData:s,errors:c}}function zLe(e,t,n,r){let i=Object.entries(t).filter(([,e])=>e!==rLe).reduce((e,[t,n])=>(e[t]=n,e),{}),a=0;for(let o of n){let n=o.route.id;if(!t.hasOwnProperty(n)&&e.hasOwnProperty(n)&&o.route.loader&&(i[n]=e[n],a++),r&&r.hasOwnProperty(n))break}return Object.keys(t).length===0&&a===Object.keys(e).length?e:i}function BLe(e){return e?mv(e[1])?{actionData:{}}:{actionData:{[e[0]]:e[1].data}}:{}}function uv(e,t){return(t?e.slice(0,e.findIndex(e=>e.route.id===t)+1):[...e]).reverse().find(e=>e.route.ErrorBoundary!=null||e.route.errorElement!=null)||e[0]}function dv(e){let t=e.length===1?e[0]:e.find(e=>e.index||!e.path||e.path===`/`)||{id:`__shim-error-route__`};return{matches:[{params:{},pathname:``,pathnameBase:``,route:t}],route:t}}function fv(e,{pathname:t,routeId:n,method:r,type:i,message:a}={}){let o=`Unknown Server Error`,s=`Unknown @remix-run/router error`;return e===400?(o=`Bad Request`,r&&t&&n?s=`You made a ${r} request to "${t}" but did not provide a \`loader\` for route "${n}", so there is no way to handle the request.`:i===`invalid-body`&&(s=`Unable to encode submission body`)):e===403?(o=`Forbidden`,s=`Route "${n}" does not match URL "${t}"`):e===404?(o=`Not Found`,s=`No route matches URL "${t}"`):e===405&&(o=`Method Not Allowed`,r&&t&&n?s=`You made a ${r.toUpperCase()} request to "${t}" but did not provide an \`action\` for route "${n}", so there is no way to handle the request.`:r&&(s=`Invalid request method "${r.toUpperCase()}"`)),new q_(e||500,o,Error(s),!0)}function pv(e){let t=Object.entries(e);for(let e=t.length-1;e>=0;e--){let[n,r]=t[e];if(hv(r))return{key:n,result:r}}}function VLe(e){return L_({...typeof e==`string`?R_(e):e,hash:``})}function HLe(e,t){return e.pathname!==t.pathname||e.search!==t.search?!1:e.hash===``?t.hash!==``:e.hash===t.hash||t.hash!==``}function ULe(e){return new q_(e.init?.status??500,e.init?.statusText??`Internal Server Error`,e.data)}function WLe(e){return typeof e==`object`&&!!e&&Object.entries(e).every(([e,t])=>typeof e==`string`&&GLe(t))}function GLe(e){return typeof e==`object`&&!!e&&`type`in e&&`result`in e&&(e.type===`data`||e.type===`error`)}function KLe(e){return JLe(e.result)&&$Ie.has(e.result.status)}function mv(e){return e.type===`error`}function hv(e){return(e&&e.type)===`redirect`}function qLe(e){return typeof e==`object`&&!!e&&`type`in e&&`data`in e&&`init`in e&&e.type===`DataWithResponseInit`}function JLe(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.headers==`object`&&e.body!==void 0}function YLe(e){return $Ie.has(e)}function XLe(e){return JLe(e)&&YLe(e.status)&&e.headers.has(`Location`)}function ZLe(e){return QIe.has(e.toUpperCase())}function gv(e){return XIe.has(e.toUpperCase())}function QLe(e){return new URLSearchParams(e).getAll(`index`).some(e=>e===``)}function _v(e,t){let n=typeof t==`string`?R_(t).search:t.search;if(e[e.length-1].route.index&&QLe(n||``))return e[e.length-1];let r=EIe(e);return r[r.length-1]}function $Le(e,t,n){return{url:MIe(e.createURL(t),t),pattern:n?Y_(n):``,params:n?.[0]?.params?{...n[0].params}:{}}}function eRe(e){let{formMethod:t,formAction:n,formEncType:r,text:i,formData:a,json:o}=e;if(t&&n&&r){if(i!=null)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:void 0,text:i};if(a!=null)return{formMethod:t,formAction:n,formEncType:r,formData:a,json:void 0,text:void 0};if(o!==void 0)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:o,text:void 0}}}function tRe(e,t,n,r){return r?{state:`loading`,location:e,matches:t,historyAction:n,formMethod:r.formMethod,formAction:r.formAction,formEncType:r.formEncType,formData:r.formData,json:r.json,text:r.text}:{state:`loading`,location:e,matches:t,historyAction:n,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0}}function nRe(e,t,n,r){return{state:`submitting`,location:e,matches:t,historyAction:n,formMethod:r.formMethod,formAction:r.formAction,formEncType:r.formEncType,formData:r.formData,json:r.json,text:r.text}}function vv(e,t){return e?{state:`loading`,formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t}:{state:`loading`,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:t}}function rRe(e,t){return{state:`submitting`,formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t?t.data:void 0}}function yv(e){return{state:`idle`,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:e}}function iRe(e,t){try{let n=e.sessionStorage.getItem(nLe);if(n){let e=JSON.parse(n);for(let[n,r]of Object.entries(e||{}))r&&Array.isArray(r)&&t.set(n,new Set(r||[]))}}catch{}}function aRe(e,t){if(t.size>0){let n={};for(let[e,r]of t)n[e]=[...r];try{e.sessionStorage.setItem(nLe,JSON.stringify(n))}catch(e){F_(!1,`Failed to save applied view transitions in sessionStorage (${e}).`)}}}function oRe(){let e,t,n=new Promise((r,i)=>{e=async e=>{r(e);try{await n}catch{}},t=async e=>{i(e);try{await n}catch{}}});return{promise:n,resolve:e,reject:t}}var bv=G.createContext(null);bv.displayName=`DataRouter`;var sRe=G.createContext(null);sRe.displayName=`DataRouterState`;var cRe=G.createContext(null);cRe.displayName=`DataRouterData`;var lRe=G.createContext(null);lRe.displayName=`DataRouterNavigation`;var uRe=G.createContext(!1);function dRe(){return G.useContext(uRe)}var fRe=G.createContext({isTransitioning:!1});fRe.displayName=`ViewTransition`;var pRe=G.createContext(null);pRe.displayName=`Fetchers`;var mRe=G.createContext(null);mRe.displayName=`Await`;var xv=G.createContext(null);xv.displayName=`Navigation`;var Sv=G.createContext(null);Sv.displayName=`Location`;var Cv=G.createContext({outlet:null,matches:[],isDataRoute:!1});Cv.displayName=`Route`;var wv=G.createContext(!1);wv.displayName=`IsDataRoute`;var Tv=G.createContext(void 0);Tv.displayName=`RouteId`;var hRe=G.createContext(null);hRe.displayName=`RouteError`;var gRe=`REACT_ROUTER_ERROR`,_Re=`REDIRECT`,vRe=`ROUTE_ERROR_RESPONSE`;function yRe(e){if(e.startsWith(`${gRe}:${_Re}:{`))try{let t=JSON.parse(e.slice(28));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`&&typeof t.location==`string`&&typeof t.reloadDocument==`boolean`&&typeof t.replace==`boolean`)return t}catch{}}function bRe(e){if(e.startsWith(`${gRe}:${vRe}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`)return new q_(t.status,t.statusText,t.data)}catch{}}function xRe(e,{relative:t}={}){P_(Ev(),`useHref() may be used only in the context of a <Router> component.`);let{basename:n,navigator:r}=G.useContext(xv),{hash:i,pathname:a,search:o}=Av(e,{relative:t}),s=a;return n!==`/`&&(s=a===`/`?n:W_([n,a])),r.createHref({pathname:s,search:o,hash:i})}function Ev(){return G.useContext(Sv)!=null}function Dv(){return P_(Ev(),`useLocation() may be used only in the context of a <Router> component.`),G.useContext(Sv).location}function SRe(e){P_(Ev(),`useMatch() may be used only in the context of a <Router> component.`);let{pathname:t}=Dv();return G.useMemo(()=>B_(e,bIe(t)),[t,e])}var CRe=`You should call navigate() in a React.useEffect(), not when your component is first rendered.`;function Ov(){return G.useContext(wv)?BRe():wRe()}function wRe(){P_(Ev(),`useNavigate() may be used only in the context of a <Router> component.`);let e=G.useContext(bv),{basename:t,navigator:n}=G.useContext(xv),{matches:r}=G.useContext(Cv),{pathname:i}=Dv(),a=JSON.stringify(H_(r)),o=G.useRef(!1);return G.useLayoutEffect(()=>{o.current=!0}),G.useCallback((r,s={})=>{if(F_(o.current,CRe),!o.current)return;if(typeof r==`number`){n.go(r);return}let c=U_(r,JSON.parse(a),i,s.relative===`path`);e==null&&t!==`/`&&(c.pathname=c.pathname===`/`?t:W_([t,c.pathname])),nv(typeof r==`string`?r:L_(r),n.createHref(c),KIe(n),`reject`),(s.replace?n.replace:n.push)(c,s.state,s)},[t,n,a,i,e])}var TRe=G.createContext(null);function ERe(e){let t=G.useContext(Cv).outlet;return G.useMemo(()=>t&&G.createElement(TRe.Provider,{value:e},t),[t,e])}function kv(){let{matches:e}=G.useContext(Cv);return e[e.length-1]?.params??{}}function Av(e,{relative:t}={}){let{matches:n}=G.useContext(Cv),{pathname:r}=Dv(),i=JSON.stringify(H_(n));return G.useMemo(()=>U_(e,JSON.parse(i),r,t===`path`),[e,i,r,t])}function DRe(e,t,n){P_(Ev(),`useRoutes() may be used only in the context of a <Router> component.`);let{navigator:r}=G.useContext(xv),{matches:i}=G.useContext(Cv),a=i[i.length-1],o=a?a.params:{};a&&a.pathname;let s=a?a.pathnameBase:`/`;a&&a.route;let c=Dv(),l;if(t){let e=typeof t==`string`?R_(t):t;P_(s===`/`||e.pathname?.startsWith(s),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${s}" but pathname "${e.pathname}" was given in the \`location\` prop.`),l=e}else l=c;let u=l.pathname||`/`,d=u;if(s!==`/`){let e=s.replace(/^\//,``).split(`/`);d=`/`+u.replace(/^\//,``).split(`/`).slice(e.length).join(`/`)}let f;f=n?n.state.matches.length?n.state.matches.map(e=>Object.assign(e,{route:n.manifest[e.route.id]||e.route})):n.router.match(n.state.location):$Fe(e,{pathname:d});let p=PRe(f&&f.map(e=>Object.assign({},e,{params:Object.assign({},o,e.params),pathname:W_([s,r.encodeLocation?r.encodeLocation(e.pathname.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathname]),pathnameBase:e.pathnameBase===`/`?s:W_([s,r.encodeLocation?r.encodeLocation(e.pathnameBase.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathnameBase])})),i,n);return t&&p?G.createElement(Sv.Provider,{value:{location:{pathname:`/`,search:``,hash:``,state:null,key:`default`,mask:void 0,...l},navigationType:`POP`}},p):p}function ORe(){let e=zRe(),t=J_(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null;return G.createElement(G.Fragment,null,G.createElement(`h2`,null,`Unexpected Application Error!`),G.createElement(`h3`,{style:{fontStyle:`italic`}},t),n?G.createElement(`pre`,{style:{padding:`0.5rem`,backgroundColor:`rgba(200,200,200, 0.5)`}},n):null,null)}var kRe=G.createElement(ORe,null),ARe=class extends G.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static contextType=uRe;static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!==`idle`&&e.revalidation===`idle`?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error===void 0?t.error:e.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error(`React Router caught the following error during render`,e)}render(){let e=this.state.error;if(this.context&&typeof e==`object`&&e&&`digest`in e&&typeof e.digest==`string`){let t=bRe(e.digest);t&&(e=t)}let t=e===void 0?this.props.children:G.createElement(Cv.Provider,{value:this.props.routeContext},G.createElement(wv.Provider,{value:this.props.routeContext.isDataRoute},G.createElement(Tv.Provider,{value:this.props.routeContext.matches[this.props.routeContext.matches.length-1]?.route.id},G.createElement(hRe.Provider,{value:e,children:this.props.component}))));return this.context?G.createElement(MRe,{error:e},t):t}},jRe=new WeakMap;function MRe({children:e,error:t}){let{basename:n,navigator:r}=G.useContext(xv);if(typeof t==`object`&&t&&`digest`in t&&typeof t.digest==`string`){let e=yRe(t.digest);if(e){let i=jRe.get(t);if(i)throw i;let a=PIe(e.location,n),o=a.absoluteURL||a.to;if(nv(e.location,o,KIe(r),`allow-explicit`),NLe(o))throw Error(`Invalid redirect location`);if(NIe&&!jRe.get(t)){if(a.isExternal||e.reloadDocument)window.location.href=o;else{let n=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(a.to,{replace:e.replace}));throw jRe.set(t,n),n}}return G.createElement(`meta`,{httpEquiv:`refresh`,content:`0;url=${o}`})}}return e}function NRe({routeContext:e,match:t,children:n}){let r=G.useContext(bv);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),G.createElement(Cv.Provider,{value:e},G.createElement(wv.Provider,{value:e.isDataRoute},G.createElement(Tv.Provider,{value:t.route.id},n)))}function PRe(e,t=[],n){let r=n?.state;if(e==null){if(!r)return null;if(r.errors)e=r.matches;else if(t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let i=e,a=r?.errors;if(a!=null){let e=i.findIndex(e=>e.route.id&&a?.[e.route.id]!==void 0);P_(e>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(a).join(`,`)}`),i=i.slice(0,Math.min(i.length,e+1))}let o=!1,s=-1;if(n&&r){o=r.renderFallback;for(let e=0;e<i.length;e++){let t=i[e];if((t.route.HydrateFallback||t.route.hydrateFallbackElement)&&(s=e),t.route.id){let{loaderData:e,errors:a}=r,c=t.route.loader&&!e.hasOwnProperty(t.route.id)&&(!a||a[t.route.id]===void 0);if(t.route.lazy||c){n.isStatic&&(o=!0),i=s>=0?i.slice(0,s+1):[i[0]];break}}}}let c=n?.onError,l=r&&c?(e,t)=>{c(e,{location:r.location,params:r.matches?.[0]?.params??{},pattern:Y_(r.matches),errorInfo:t})}:void 0;return i.reduceRight((e,n,c)=>{let u,d=!1,f=null,p=null;r&&(u=a&&n.route.id?a[n.route.id]:void 0,f=n.route.errorElement||kRe,o&&(s<0&&c===0?(HRe(`route-fallback`,!1,"No `HydrateFallback` element provided to render during initial hydration"),d=!0,p=null):s===c&&(d=!0,p=n.route.hydrateFallbackElement||null)));let m=t.concat(i.slice(0,c+1)),h=()=>{let t;return t=u?f:d?p:n.route.Component?G.createElement(n.route.Component,null):n.route.element?n.route.element:e,G.createElement(NRe,{match:n,routeContext:{outlet:e,matches:m,isDataRoute:r!=null},children:t})};return r&&(n.route.ErrorBoundary||n.route.errorElement||c===0)?G.createElement(ARe,{location:r.location,revalidation:r.revalidation,component:f,error:u,children:h(),routeContext:{outlet:null,matches:m,isDataRoute:!0},onError:l}):h()},null)}function FRe(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function jv(e){let t=G.useContext(bv);return P_(t,FRe(e)),t}function IRe(e){let t=G.useContext(sRe);return P_(t,FRe(e)),t}function LRe(e){let t=G.useContext(cRe);return P_(t,FRe(e)),t}function RRe(e){let t=G.useContext(Tv);return P_(t,`${e} can only be used on routes that contain a unique "id"`),t}function zRe(){let e=G.useContext(hRe),t=LRe(`useRouteError`),n=RRe(`useRouteError`);return e===void 0?t.errors?.[n]:e}function BRe(){let{router:e}=jv(`useNavigate`),t=RRe(`useNavigate`),n=G.useRef(!1);return G.useLayoutEffect(()=>{n.current=!0}),G.useCallback(async(r,i={})=>{F_(n.current,CRe),n.current&&(typeof r==`number`?await e.navigate(r):await e.navigate(r,{fromRouteId:t,...i}))},[e,t])}var VRe={};function HRe(e,t,n){!t&&!VRe[e]&&(VRe[e]=!0,F_(!1,n))}function URe(e,t){if(e===!1||e==null)throw Error(t)}function WRe(e,t,n){let r=typeof e==`string`?new URL(e,n??(typeof window>`u`?`server://singlefetch/`:window.location.origin)):new URL(e);return n&&r.origin!==n&&(r=new URL(r.pathname+r.search+r.hash,n)),r.pathname.endsWith(`/`)?r.pathname=`${r.pathname}_.${t}`:r.pathname=`${r.pathname}.${t}`,r}async function GRe(e,t){if(e.id in t)return t[e.id];try{let n=await import(e.module);return t[e.id]=n,n}catch(t){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(t),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function KRe(e){return e!=null&&typeof e.page==`string`}function qRe(e){return e==null?!1:e.href==null?e.rel===`preload`&&typeof e.imageSrcSet==`string`&&typeof e.imageSizes==`string`:typeof e.rel==`string`&&typeof e.href==`string`}async function JRe(e,t,n){return $Re((await Promise.all(e.map(async e=>{let r=t.routes[e.route.id];if(r){let e=await GRe(r,n);return e.links?e.links():[]}return[]}))).flat(1).filter(qRe).filter(e=>e.rel===`stylesheet`||e.rel===`preload`).map(e=>e.rel===`stylesheet`?{...e,rel:`prefetch`,as:`style`}:{...e,rel:`prefetch`}))}function YRe(e,t,n,r,i,a){let o=(e,t)=>!n[t]||e.route.id!==n[t].route.id,s=(e,t)=>n[t].pathname!==e.pathname||n[t].route.path?.endsWith(`*`)&&n[t].params[`*`]!==e.params[`*`];return a===`assets`?t.filter((e,t)=>o(e,t)||s(e,t)):a===`data`?t.filter((t,a)=>{let c=r.routes[t.route.id];if(!c||!c.hasLoader)return!1;if(o(t,a)||s(t,a))return!0;if(t.route.shouldRevalidate){let r=t.route.shouldRevalidate({currentUrl:new URL(i.pathname+i.search+i.hash,window.origin),currentParams:n[0]?.params||{},nextUrl:new URL(e,window.origin),nextParams:t.params,defaultShouldRevalidate:!0});if(typeof r==`boolean`)return r}return!0}):[]}function XRe(e,t,{includeHydrateFallback:n}={}){return ZRe(e.map(e=>{let r=t.routes[e.route.id];if(!r)return[];let i=[r.module];return r.clientActionModule&&(i=i.concat(r.clientActionModule)),r.clientLoaderModule&&(i=i.concat(r.clientLoaderModule)),n&&r.hydrateFallbackModule&&(i=i.concat(r.hydrateFallbackModule)),r.imports&&(i=i.concat(r.imports)),i}).flat(1))}function ZRe(e){return[...new Set(e)]}function QRe(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function $Re(e,t){let n=new Set,r=new Set(t);return e.reduce((e,i)=>{if(t&&!KRe(i)&&i.as===`script`&&i.href&&r.has(i.href))return e;let a=JSON.stringify(QRe(i));return n.has(a)||(n.add(a),e.push({key:a,link:i})),e},[])}var eze={};function tze(e,t){!e&&!eze[t]&&(eze[t]=!0,console.warn(t))}var Mv=G.createContext(void 0);Mv.displayName=`FrameworkContext`;function Nv(){let e=G.useContext(Mv);return URe(e,`You must render this element inside a <HydratedRouter> element`),e}function nze(e,t){let n=G.useContext(Mv),[r,i]=G.useState(!1),[a,o]=G.useState(!1),{onFocus:s,onBlur:c,onMouseEnter:l,onMouseLeave:u,onTouchStart:d}=t,f=G.useRef(null);G.useEffect(()=>{if(e===`render`&&o(!0),e===`viewport`){let e=new IntersectionObserver(e=>{e.forEach(e=>{o(e.isIntersecting)})},{threshold:.5});return f.current&&e.observe(f.current),()=>{e.disconnect()}}},[e]),G.useEffect(()=>{if(r){let e=setTimeout(()=>{o(!0)},100);return()=>{clearTimeout(e)}}},[r]);let p=()=>{i(!0)},m=()=>{i(!1),o(!1)};return n?e===`intent`?[a,f,{onFocus:Pv(s,p),onBlur:Pv(c,m),onMouseEnter:Pv(l,p),onMouseLeave:Pv(u,m),onTouchStart:Pv(d,p)}]:[a,f,{}]:[!1,f,{}]}function Pv(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function rze({page:e,...t}){let n=dRe(),{nonce:r}=Nv(),{router:i}=jv(`PrefetchPageLinks`),a=G.useMemo(()=>i.match(e),[i,i.routes,e]);return a?(t.nonce==null&&r&&(t={...t,nonce:r}),n?G.createElement(aze,{page:e,matches:a,...t}):G.createElement(oze,{page:e,matches:a,...t})):null}function ize(e){let{manifest:t,routeModules:n}=Nv(),[r,i]=G.useState([]);return G.useEffect(()=>{let r=!1;return JRe(e,t,n).then(e=>{r||i(e)}),()=>{r=!0}},[e,t,n]),r}function aze({page:e,matches:t,...n}){let r=Dv(),{unstable_apiServerOrigin:i}=Nv(),a=G.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=WRe(e,`rsc`,i),a=!1,o=[];for(let e of t)typeof e.route.shouldRevalidate==`function`?a=!0:o.push(e.route.id);return a&&o.length>0&&n.searchParams.set(`_routes`,o.join(`,`)),[i?n.toString():n.pathname+n.search]},[e,r,t,i]);return G.createElement(G.Fragment,null,a.map(e=>G.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})))}function oze({page:e,matches:t,...n}){let r=Dv(),{manifest:i,routeModules:a,unstable_apiServerOrigin:o}=Nv(),{matches:s}=IRe(`PrefetchPageLinks`),{loaderData:c}=LRe(`PrefetchPageLinks`),l=G.useMemo(()=>YRe(e,t,s,i,r,`data`),[e,t,s,i,r]),u=G.useMemo(()=>YRe(e,t,s,i,r,`assets`),[e,t,s,i,r]),d=G.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=new Set,s=!1;if(t.forEach(e=>{let t=i.routes[e.route.id];t&&t.hasLoader&&(!l.some(t=>t.route.id===e.route.id)&&e.route.id in c&&a[e.route.id]?.shouldRevalidate||t.hasClientLoader?s=!0:n.add(e.route.id))}),n.size===0)return[];let u=WRe(e,`data`,o);return s&&n.size>0&&u.searchParams.set(`_routes`,t.filter(e=>n.has(e.route.id)).map(e=>e.route.id).join(`,`)),[o?u.toString():u.pathname+u.search]},[c,r,i,l,t,e,a,o]),f=G.useMemo(()=>XRe(u,i),[u,i]),p=ize(u);return G.createElement(G.Fragment,null,d.map(e=>G.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})),f.map(e=>G.createElement(`link`,{key:e,rel:`modulepreload`,href:e,...n})),p.map(({key:e,link:t})=>G.createElement(`link`,{key:e,nonce:n.nonce,...t,crossOrigin:t.crossOrigin??n.crossOrigin})))}function sze(...e){return t=>{e.forEach(e=>{typeof e==`function`?e(t):e!=null&&(e.current=t)})}}var cze=[`HydrateFallback`,`hydrateFallbackElement`],lze=class{status=`pending`;promise;resolve;reject;constructor(){this.promise=new Promise((e,t)=>{this.resolve=t=>{this.status===`pending`&&(this.status=`resolved`,e(t))},this.reject=e=>{this.status===`pending`&&(this.status=`rejected`,t(e))}})}};function uze(e,t){e.ready.catch(e=>{if(!(t.visibilityState===`hidden`||typeof e==`object`&&e&&`name`in e&&e.name===`AbortError`))throw e})}function dze({router:e,flushSync:t,onError:n,useTransitions:r}){r=dRe()||r;let[i,a]=G.useState(e.state),[o,s]=(0,G.useOptimistic)(i),c=G.useRef(o),[l,u]=G.useState(),[d,f]=G.useState({isTransitioning:!1}),[p,m]=G.useState(),[h,g]=G.useState(),[_,v]=G.useState(),y=G.useRef(new Map),b=G.useRef(new WeakSet),x=G.useCallback((i,{deletedFetchers:o,newErrors:l,flushSync:d,viewTransitionOpts:_})=>{c.current=i,l&&i.errors&&av.has(i.errors)&&(b.current.has(i.errors)?l=null:b.current.add(i.errors)),l&&n&&Object.values(l).forEach(e=>n(e,{location:i.location,params:i.matches[0]?.params??{},pattern:Y_(i.matches)})),i.fetchers.forEach((e,t)=>{e.data!==void 0&&y.current.set(t,e.data)}),o.forEach(e=>y.current.delete(e)),tze(d===!1||t!=null,'You provided the `flushSync` option to a router update, but you are not using the `<RouterProvider>` from `react-router/dom` so `ReactDOM.flushSync()` is unavailable. Please update your app to `import { RouterProvider } from "react-router/dom"` and ensure you have `react-dom` installed as a dependency to use the `flushSync` option.');let x=e.window!=null&&e.window.document!=null&&typeof e.window.document.startViewTransition==`function`;if(tze(_==null||x,"You provided the `viewTransition` option to a router update, but you do not appear to be running in a DOM environment as `window.startViewTransition` is not available."),!_||!x)t&&d?t(()=>a(i)):r===!1?a(i):G.startTransition(()=>{r===!0&&s(e=>fze(e,i)),a(i)});else if(t&&d){t(()=>{h&&(p?.resolve(),h.skipTransition()),f({isTransitioning:!0,flushSync:!0,currentLocation:_.currentLocation,nextLocation:_.nextLocation})});let n=e.window.document.startViewTransition(()=>{t(()=>a(i))});uze(n,e.window.document),n.finished.finally(()=>{t(()=>{m(void 0),g(void 0),u(void 0),f({isTransitioning:!1})})}),t(()=>g(n))}else h?(p?.resolve(),h.skipTransition(),v({state:i,currentLocation:_.currentLocation,nextLocation:_.nextLocation})):(u(i),f({isTransitioning:!0,flushSync:!1,currentLocation:_.currentLocation,nextLocation:_.nextLocation}))},[e.window,t,h,p,r,s,n]);G.useLayoutEffect(()=>e.subscribe(x),[e,x]),G.useLayoutEffect(()=>{let t=e.state.errors,n=t?av.get(t):null;(c.current!==e.state||t&&n&&!b.current.has(t))&&x(e.state,{deletedFetchers:[],flushSync:!1,newErrors:n??null})},[e,x]),G.useEffect(()=>{d.isTransitioning&&!d.flushSync&&m(new lze)},[d]),G.useEffect(()=>{if(p&&l&&e.window){let t=l,n=p.promise,i=e.window.document.startViewTransition(async()=>{r===!1?a(t):G.startTransition(()=>{r===!0&&s(e=>fze(e,t)),a(t)}),await n});uze(i,e.window.document),i.finished.finally(()=>{m(void 0),g(void 0),u(void 0),f({isTransitioning:!1})}),g(i)}},[l,p,e.window,r,s]),G.useEffect(()=>{p&&l&&o.location.key===l.location.key&&p.resolve()},[p,h,o.location,l]),G.useEffect(()=>{!d.isTransitioning&&_&&(u(_.state),f({isTransitioning:!0,flushSync:!1,currentLocation:_.currentLocation,nextLocation:_.nextLocation}),v(void 0))},[d.isTransitioning,_]);let S=G.useMemo(()=>({createHref:e.createHref,createURL:e.createURL,encodeLocation:e.encodeLocation,go:t=>e.navigate(t),push:(t,n,r)=>e.navigate(t,{state:n,preventScrollReset:r?.preventScrollReset}),replace:(t,n,r)=>e.navigate(t,{replace:!0,state:n,preventScrollReset:r?.preventScrollReset})}),[e]),C=e.basename||`/`,w=G.useMemo(()=>({router:e,navigator:S,static:!1,basename:C,onError:n}),[e,S,C,n]),T=G.useMemo(()=>({historyAction:o.historyAction,location:o.location,matches:o.matches,initialized:o.initialized,renderFallback:o.renderFallback,restoreScrollPosition:o.restoreScrollPosition,preventScrollReset:o.preventScrollReset,blockers:o.blockers}),[o.historyAction,o.location,o.matches,o.initialized,o.renderFallback,o.restoreScrollPosition,o.preventScrollReset,o.blockers]),E=G.useMemo(()=>({navigation:o.navigation,revalidation:o.revalidation}),[o.navigation,o.revalidation]),D=G.useMemo(()=>({loaderData:o.loaderData,actionData:o.actionData,errors:o.errors}),[o.loaderData,o.actionData,o.errors]),O=G.useMemo(()=>({fetchers:o.fetchers,fetcherData:y.current}),[o.fetchers]);return G.createElement(G.Fragment,null,G.createElement(bv.Provider,{value:w},G.createElement(sRe.Provider,{value:T},G.createElement(lRe.Provider,{value:E},G.createElement(cRe.Provider,{value:D},G.createElement(pRe.Provider,{value:O},G.createElement(fRe.Provider,{value:d},G.createElement(hze,{basename:C,location:o.location,navigationType:o.historyAction,navigator:S,useTransitions:r},G.createElement(pze,{routes:e.routes,manifest:e.manifest,state:o,isStatic:!1,onError:n})))))))),null)}function fze(e,t){return{...e,navigation:t.navigation.state===`idle`?e.navigation:t.navigation,revalidation:t.revalidation===`idle`?e.revalidation:t.revalidation,actionData:t.navigation.state===`submitting`?e.actionData:t.actionData,fetchers:t.fetchers}}var pze=G.memo(mze);function mze({routes:e,manifest:t,state:n,isStatic:r,onError:i}){let a=G.useContext(bv);P_(a,`You must render this element inside a <DataRouterContext.Provider> element`);let o=G.useContext(Mv)?.routeDiscoveryRuntime;return G.useEffect(()=>{n.initialized&&o?.markReady()},[n.initialized,o]),DRe(e,void 0,{router:a.router,manifest:t,state:n,isStatic:r,onError:i})}function Fv({to:e,replace:t,state:n,relative:r}){P_(Ev(),`<Navigate> may be used only in the context of a <Router> component.`);let{static:i,navigator:a}=G.useContext(xv);F_(!i,`<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.`);let{matches:o}=G.useContext(Cv),{pathname:s}=Dv(),c=Ov(),l=U_(e,H_(o),s,r===`path`);nv(typeof e==`string`?e:L_(e),a.createHref(l),KIe(a),`reject`);let u=JSON.stringify(l);return G.useEffect(()=>{c(JSON.parse(u),{replace:t,state:n,relative:r})},[c,u,r,t,n]),null}function Iv(e){return ERe(e.context)}function hze({basename:e=`/`,children:t=null,location:n,navigationType:r=`POP`,navigator:i,static:a=!1,useTransitions:o}){P_(!Ev(),`You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`);let s=e.replace(/^\/*/,`/`),c=G.useMemo(()=>({basename:s,navigator:i,static:a,useTransitions:o,future:{}}),[s,i,a,o]);typeof n==`string`&&(n=R_(n));let{pathname:l=`/`,search:u=``,hash:d=``,state:f=null,key:p=`default`,mask:m}=n,h=G.useMemo(()=>{let e=V_(l,s);return e==null?null:{location:{pathname:e,search:u,hash:d,state:f,key:p,mask:m},navigationType:r}},[s,l,u,d,f,p,r,m]);return F_(h!=null,`<Router basename="${s}"> is not able to match the URL "${l}${u}${d}" because it does not start with the basename, so the <Router> won't render anything.`),h==null?null:G.createElement(xv.Provider,{value:c},G.createElement(Sv.Provider,{children:t,value:h}))}G.Component;var gze=`application/x-www-form-urlencoded`;function _ze(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}function vze(e){return _ze(e)&&e.tagName.toLowerCase()===`button`}function yze(e){return _ze(e)&&e.tagName.toLowerCase()===`form`}function bze(e){return _ze(e)&&e.tagName.toLowerCase()===`input`}function xze(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function Sze(e,t){return e.button===0&&(!t||t===`_self`)&&!xze(e)}function Cze(e=``){return new URLSearchParams(typeof e==`string`||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(e=>[n,e]):[[n,r]])},[]))}function wze(e,t){let n=Cze(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}var Tze=null;function Eze(){if(Tze===null)try{new FormData(document.createElement(`form`),0),Tze=!1}catch{Tze=!0}return Tze}var Dze=new Set([`application/x-www-form-urlencoded`,`multipart/form-data`,`text/plain`]);function Oze(e){return e!=null&&!Dze.has(e)?(F_(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${gze}"`),null):e}function kze(e,t){let n,r,i,a,o;if(yze(e)){let o=e.getAttribute(`action`);r=o?V_(o,t):null,n=e.getAttribute(`method`)||`get`,i=Oze(e.getAttribute(`enctype`))||gze,a=new FormData(e)}else if(vze(e)||bze(e)&&(e.type===`submit`||e.type===`image`)){let o=e.form;if(o==null)throw Error(`Cannot submit a <button> or <input type="submit"> without a <form>`);let s=e.getAttribute(`formaction`)||o.getAttribute(`action`);if(r=s?V_(s,t):null,n=e.getAttribute(`formmethod`)||o.getAttribute(`method`)||`get`,i=Oze(e.getAttribute(`formenctype`))||Oze(o.getAttribute(`enctype`))||gze,a=new FormData(o,e),!Eze()){let{name:t,type:n,value:r}=e;if(n===`image`){let e=t?`${t}.`:``;a.append(`${e}x`,`0`),a.append(`${e}y`,`0`)}else t&&a.append(t,r)}}else if(_ze(e))throw Error(`Cannot submit element that is not <form>, <button>, or <input type="submit|image">`);else n=`get`,r=null,i=gze,o=e;return a&&i===`text/plain`&&(o=a,a=void 0),{action:r,method:n.toLowerCase(),encType:i,formData:a,body:o}}var Aze=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;try{Aze&&(window.__reactRouterVersion=`8`)}catch{}function jze(e,t){return oLe({basename:t?.basename,getContext:t?.getContext,future:t?.future,history:zFe({window:t?.window}),hydrationData:t?.hydrationData||Mze(),routes:e,mapRouteProperties:ZFe,hydrationRouteProperties:cze,dataStrategy:t?.dataStrategy,patchRoutesOnNavigation:t?.patchRoutesOnNavigation,window:t?.window,instrumentations:t?.instrumentations}).initialize()}function Mze(){let e=window?.__staticRouterHydrationData;return e&&e.errors&&(e={...e,errors:Nze(e.errors)}),e}function Nze(e){if(!e)return null;let t=Object.entries(e),n={};for(let[e,r]of t)if(r&&r.__type===`RouteErrorResponse`)n[e]=new q_(r.status,r.statusText,r.data,r.internal===!0);else if(r&&r.__type===`Error`){if(typeof r.__subType==`string`&&jIe.includes(r.__subType)){let t=window[r.__subType];if(typeof t==`function`)try{let i=new t(r.message);i.stack=``,n[e]=i}catch{}}if(n[e]==null){let t=Error(r.message);t.stack=``,n[e]=t}}else n[e]=r;return n}var Lv=G.forwardRef(function({onClick:e,discover:t=`render`,prefetch:n=`none`,relative:r,reloadDocument:i,replace:a,mask:o,state:s,target:c,to:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m){let{basename:h,navigator:g,useTransitions:_}=G.useContext(xv),v=typeof l==`string`&&M_.test(l),y=PIe(l,h);l=y.to;let b=xRe(l,{relative:r}),x=Dv(),S=null;if(o){let e=U_(o,[],x.mask?x.mask.pathname:`/`,!0);h!==`/`&&(e.pathname=e.pathname===`/`?h:W_([h,e.pathname])),S=g.createHref(e)}let[C,w,T]=nze(n,p),E=Ize(l,{replace:a,mask:o,state:s,target:c,preventScrollReset:u,relative:r,viewTransition:d,defaultShouldRevalidate:f,useTransitions:_});function D(t){e&&e(t),t.defaultPrevented||E(t)}let O=!(y.isExternal||i),k=G.createElement(`a`,{...p,...T,href:(O?S:void 0)||y.absoluteURL||b,onClick:O?D:e,ref:sze(m,w),target:c,"data-discover":!v&&t===`render`?`true`:void 0});return C&&!v?G.createElement(G.Fragment,null,k,G.createElement(rze,{page:b})):k});Lv.displayName=`Link`;var Pze=G.forwardRef(function({"aria-current":e=`page`,caseSensitive:t=!1,className:n=``,end:r=!1,style:i,to:a,viewTransition:o,children:s,...c},l){let u=Av(a,{relative:c.relative}),d=Dv(),f=G.useContext(lRe),{navigator:p,basename:m}=G.useContext(xv),h=f!=null&&Vze(u)&&o===!0,g=p.encodeLocation?p.encodeLocation(u).pathname:u.pathname,_=d.pathname,v=f?.navigation.location?f.navigation.location.pathname:null;t||(_=_.toLowerCase(),v=v?v.toLowerCase():null,g=g.toLowerCase()),v&&m&&(v=V_(v,m)||v);let y=g!==`/`&&g.endsWith(`/`)?g.length-1:g.length,b=_===g||!r&&_.startsWith(g)&&_.charAt(y)===`/`,x=v!=null&&(v===g||!r&&v.startsWith(g)&&v.charAt(y)===`/`),S={isActive:b,isPending:x,isTransitioning:h},C=b?e:void 0,w;w=typeof n==`function`?n(S):[n,b?`active`:null,x?`pending`:null,h?`transitioning`:null].filter(Boolean).join(` `);let T=typeof i==`function`?i(S):i;return G.createElement(Lv,{...c,"aria-current":C,className:w,ref:l,style:T,to:a,viewTransition:o},typeof s==`function`?s(S):s)});Pze.displayName=`NavLink`;var Fze=G.forwardRef(({discover:e=`render`,fetcherKey:t,navigate:n,reloadDocument:r,replace:i,state:a,method:o=`get`,action:s,onSubmit:c,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m)=>{let{useTransitions:h}=G.useContext(xv),g=zze(),_=Bze(s,{relative:l}),v=o.toLowerCase()===`get`?`get`:`post`,y=typeof s==`string`&&M_.test(s);return G.createElement(`form`,{ref:m,method:v,action:_,onSubmit:r?c:e=>{if(c&&c(e),e.defaultPrevented)return;e.preventDefault();let r=e.nativeEvent.submitter,s=r?.getAttribute(`formmethod`)||o,p=()=>g(r||e.currentTarget,{fetcherKey:t,method:s,navigate:n,replace:i,state:a,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f});h&&n!==!1?G.startTransition(()=>p()):p()},...p,"data-discover":!y&&e===`render`?`true`:void 0})});Fze.displayName=`Form`;function Ize(e,{target:t,replace:n,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c,useTransitions:l}={}){let u=Ov(),d=Dv(),f=Av(e,{relative:o});return G.useCallback(p=>{if(Sze(p,t)){p.preventDefault();let t=n===void 0?L_(d)===L_(f):n,m=()=>u(e,{replace:t,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c});l?G.startTransition(()=>m()):m()}},[d,u,f,n,r,i,t,e,a,o,s,c,l])}function Rv(e){F_(typeof URLSearchParams<`u`,"You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let t=G.useRef(Cze(e)),n=G.useRef(!1),r=Dv(),i=G.useMemo(()=>wze(r.search,n.current?null:t.current),[r.search]),a=Ov();return[i,G.useCallback((e,t)=>{let r=Cze(typeof e==`function`?e(new URLSearchParams(i)):e);n.current=!0,a(`?`+r,t)},[a,i])]}var Lze=0,Rze=()=>`__${String(++Lze)}__`;function zze(){let{router:e}=jv(`useSubmit`),{basename:t}=G.useContext(xv),n=RRe(`useSubmit`),r=e.fetch,i=e.navigate;return G.useCallback(async(e,a={})=>{let{action:o,method:s,encType:c,formData:l,body:u}=kze(e,t);a.navigate===!1?await r(a.fetcherKey||Rze(),n,a.action||o,{defaultShouldRevalidate:a.defaultShouldRevalidate,preventScrollReset:a.preventScrollReset,relative:a.relative,formData:l,body:u,formMethod:a.method||s,formEncType:a.encType||c,flushSync:a.flushSync}):await i(a.action||o,{defaultShouldRevalidate:a.defaultShouldRevalidate,preventScrollReset:a.preventScrollReset,relative:a.relative,formData:l,body:u,formMethod:a.method||s,formEncType:a.encType||c,replace:a.replace,state:a.state,fromRouteId:n,flushSync:a.flushSync,viewTransition:a.viewTransition})},[r,i,t,n])}function Bze(e,{relative:t}={}){let{basename:n}=G.useContext(xv),r=G.useContext(Cv);P_(r,`useFormAction must be used inside a RouteContext`);let[i]=r.matches.slice(-1),a={...Av(e||`.`,{relative:t})},o=Dv();if(e==null){a.search=o.search;let e=new URLSearchParams(a.search),t=e.getAll(`index`);if(t.some(e=>e===``)){e.delete(`index`),t.filter(e=>e).forEach(t=>e.append(`index`,t));let n=e.toString();a.search=n?`?${n}`:``}}return(!e||e===`.`)&&i.route.index&&(a.search=a.search?a.search.replace(/^\?/,`?index&`):`?index`),n!==`/`&&(a.pathname=a.pathname===`/`?n:W_([n,a.pathname])),L_(a)}function Vze(e,{relative:t}={}){let n=G.useContext(fRe);P_(n!=null,"`useViewTransitionState` must be used within `react-router/dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=jv(`useViewTransitionState`),i=Av(e,{relative:t});if(!n.isTransitioning)return!1;let a=V_(n.currentLocation.pathname,r)||n.currentLocation.pathname,o=V_(n.nextLocation.pathname,r)||n.nextLocation.pathname;return B_(i.pathname,o)!=null||B_(i.pathname,a)!=null}var zv=`fixed`,Hze=`[--field:var(--field-on-surface)] [--field-disabled:var(--field-on-surface)] [--field-rim:var(--field-rim-on-surface)]`,Uze=`[--field:var(--card)] [--field-disabled:var(--fill-subtle)] [--field-rim:var(--surface-rim)]`,Bv=`bg-card hover:bg-card active:bg-card shadow-raised `+Hze,Vv=`bg-card shadow-overlay `+Hze,Wze=`bg-dialog shadow-overlay [--field:var(--field-on-surface)] [--field-disabled:var(--field-on-surface)] [--field-rim:var(--surface-rim)]`,Gze=`bg-background shadow-raised `+Uze,Kze=`bg-background `+Uze,qze=`state-layer`,Jze=`group-hover:bg-[linear-gradient(var(--fill-subtle),var(--fill-subtle))] group-focus-visible:bg-[linear-gradient(var(--fill-subtle),var(--fill-subtle))]`,Yze=[],Xze=void 0;function Zze(){return Xze}function Qze(e){Yze.push(e)}function Hv(e){let t=(t,n)=>{let r=s($ze).current,i;try{Xze=r;for(let e of Yze)e.before(r);i=e(t,n);for(let e of Yze)e.after(r);r.didInitialize=!0}finally{Xze=void 0}return i};return t.displayName=e.displayName||e.name,t}function Uv(e){return G.forwardRef(Hv(e))}function $ze(){return{didInitialize:!1}}var Wv=typeof document<`u`?G.useLayoutEffect:()=>{};function eBe(e,t){return function(n,...r){let i=new URL(e);return i.searchParams.set(`code`,n.toString()),r.forEach(e=>i.searchParams.append(`args[]`,e)),`${t} error #${n}; visit ${i} for the full message.`}}var Gv=eBe(`https://base-ui.com/production-error`,`Base UI`),tBe=G.createContext(void 0);function Kv(e){let t=G.useContext(tBe);if(t===void 0&&!e)throw Error(Gv(72));return t}function nBe(e){G.useEffect(e,V)}var qv=0,Jv=class e{static create(){return new e}currentId=qv;start(e,t){this.clear(),this.currentId=setTimeout(()=>{this.currentId=qv,t()},e)}isStarted(){return this.currentId!==qv}clear=()=>{this.currentId!==qv&&(clearTimeout(this.currentId),this.currentId=qv)};disposeEffect=()=>this.clear};function Yv(){let e=s(Jv.create).current;return nBe(e.disposeEffect),e}function rBe(){return typeof navigator>`u`?{userAgent:``,platform:``,maxTouchPoints:0}:{userAgent:navigator.userAgent,platform:navigator.platform??``,maxTouchPoints:navigator.maxTouchPoints??0}}var{userAgent:iBe,platform:aBe,maxTouchPoints:oBe}=rBe(),sBe=iBe.toLowerCase(),Xv=aBe.toLowerCase(),Zv=/^i(os$|p)/.test(Xv)||Xv===`macintel`&&oBe>1,cBe=`android`,Qv=Xv===cBe||sBe.includes(cBe),lBe=!Zv&&Xv.startsWith(`mac`);Xv.startsWith(`win`),!Qv&&/^(linux|chrome os)/.test(Xv);var uBe=lBe||Zv,$v=typeof CSS<`u`&&!!CSS.supports?.(`-webkit-backdrop-filter:none`),dBe=!$v&&sBe.includes(`firefox`);!$v&&sBe.includes(`chrom`);var fBe=uBe,pBe=/jsdom|happydom/.test(sBe);function ey(e){e.preventDefault(),e.stopPropagation()}function mBe(e){return`nativeEvent`in e}function ty(e){return e.pointerType===``&&e.isTrusted?!0:Qv&&e.pointerType?e.type===`click`&&e.buttons===1:e.detail===0&&!e.pointerType}function hBe(e){return pBe?!1:!Qv&&e.width===0&&e.height===0||e.type===`pointerdown`&&e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType===`mouse`&&(Qv||e.buttons===0)||e.width<1&&e.height<1&&e.pressure===0&&e.detail===0&&e.pointerType===`touch`}function ny(e,t){let n=[`mouse`,`pen`];return t||n.push(``,void 0),n.includes(e)}function gBe(e){let t=e.type;return t===`click`||t===`mousedown`||t===`keydown`||t===`keyup`}function _Be(){return typeof window<`u`}function ry(e){return vBe(e)?(e.nodeName||``).toLowerCase():`#document`}function iy(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function ay(e){return((vBe(e)?e.ownerDocument:e.document)||window.document)?.documentElement}function vBe(e){return _Be()?e instanceof Node||e instanceof iy(e).Node:!1}function oy(e){return _Be()?e instanceof Element||e instanceof iy(e).Element:!1}function sy(e){return _Be()?e instanceof HTMLElement||e instanceof iy(e).HTMLElement:!1}function cy(e){return!_Be()||typeof ShadowRoot>`u`?!1:e instanceof ShadowRoot||e instanceof iy(e).ShadowRoot}function ly(e){let{overflow:t,overflowX:n,overflowY:r,display:i}=fy(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!==`inline`&&i!==`contents`}function yBe(e){return/^(table|td|th)$/.test(ry(e))}function bBe(e){try{if(e.matches(`:popover-open`))return!0}catch{}try{return e.matches(`:modal`)}catch{return!1}}var xBe=/transform|translate|scale|rotate|perspective|filter/,SBe=/paint|layout|strict|content/,uy=e=>!!e&&e!==`none`,CBe;function wBe(e){let t=oy(e)?fy(e):e;return uy(t.transform)||uy(t.translate)||uy(t.scale)||uy(t.rotate)||uy(t.perspective)||!EBe()&&(uy(t.backdropFilter)||uy(t.filter))||xBe.test(t.willChange||``)||SBe.test(t.contain||``)}function TBe(e){let t=py(e);for(;sy(t)&&!dy(t);){if(wBe(t))return t;if(bBe(t))return null;t=py(t)}return null}function EBe(){return CBe??=typeof CSS<`u`&&CSS.supports&&CSS.supports(`-webkit-backdrop-filter`,`none`),CBe}function dy(e){return/^(html|body|#document)$/.test(ry(e))}function fy(e){return iy(e).getComputedStyle(e)}function DBe(e){return oy(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function py(e){if(ry(e)===`html`)return e;let t=e.assignedSlot||e.parentNode||cy(e)&&e.host||ay(e);return cy(t)?t.host:t}function OBe(e){let t=py(e);return dy(t)?(e.ownerDocument||e).body:sy(t)&&ly(t)?t:OBe(t)}function my(e,t,n){t===void 0&&(t=[]),n===void 0&&(n=!0);let r=OBe(e),i=r===e.ownerDocument?.body,a=iy(r);if(i){let e=kBe(a);return t.concat(a,a.visualViewport||[],ly(r)?r:[],e&&n?my(e):[])}return t.concat(r,my(r,[],n))}function kBe(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function hy(e){let t=e.activeElement;for(;t?.shadowRoot?.activeElement!=null;)t=t.shadowRoot.activeElement;return t}function gy(e,t){if(!e||!t)return!1;let n=t.getRootNode?.();if(e.contains(t))return!0;if(n&&cy(n)){let n=t;for(;n;){if(e===n)return!0;n=n.parentNode||n.host}}return!1}function _y(e,t){let n=e;for(;n;){if(oy(n)&&n.matches(t))return n;n=n.assignedSlot??n.parentNode??(cy(n)?n.host:null)}return null}function vy(e){return`composedPath`in e?e.composedPath()[0]??e.target:e.target}var ABe=`data-base-ui-focusable`,jBe=`input:not([type='hidden']):not([disabled]),[contenteditable]:not([contenteditable='false']),textarea:not([disabled])`,MBe=`ArrowLeft`,NBe=`ArrowRight`,PBe=`ArrowUp`,FBe=`ArrowDown`,IBe=`data-starting-style`,LBe=`data-ending-style`,RBe={[IBe]:``},zBe={[LBe]:``},yy={transitionStatus(e){return e===`starting`?RBe:e===`ending`?zBe:null}},BBe=`data-open`,VBe=`data-closed`,HBe=`data-anchor-hidden`,UBe=`data-popup-open`,WBe=`data-pressed`,GBe={[UBe]:``},KBe={[UBe]:``,[WBe]:``},qBe={[BBe]:``},JBe={[VBe]:``},YBe={[HBe]:``},by={open(e){return e?GBe:null}},xy={open(e){return e?KBe:null}},Sy={open(e){return e?qBe:JBe},anchorHidden(e){return e?YBe:null}},Cy={...Sy,...yy},XBe=`data-trigger-disabled`;function ZBe(e,t){if(!oy(e))return!1;let n=e;if(t.hasElement(n))return!n.hasAttribute(XBe);for(let[,e]of t.entries())if(gy(e,n))return!e.hasAttribute(XBe);return!1}function QBe(e,t){if(t==null)return!1;if(`composedPath`in e)return e.composedPath().includes(t);let n=e;return n.target!=null&&t.contains(n.target)}function $Be(e){return e.matches(`html,body`)}function wy(e){return sy(e)&&e.matches(`input:not([type='hidden']):not([disabled]),[contenteditable]:not([contenteditable='false']),textarea:not([disabled])`)}function eVe(e){return _y(e,`button,a[href],[role="button"],select,[tabindex]:not([tabindex="-1"]),${jBe}`)!=null}function tVe(e){return e?e.getAttribute(`role`)===`combobox`&&wy(e):!1}function nVe(e){if(!e||pBe)return!0;try{return e.matches(`:focus-visible`)}catch{return!0}}function rVe(e){return e?e.hasAttribute(`data-base-ui-focusable`)?e:e.querySelector(`[data-base-ui-focusable]`)||e:null}function iVe(e,t){return t!=null&&!ny(t)?0:typeof e==`function`?e():e}function Ty(e,t,n){let r=iVe(e,n);return typeof r==`number`?r:r?.[t]}function aVe(e){return typeof e==`function`?e():e}function oVe(e,t){return t||e===`click`||e===`mousedown`}function sVe(e){return e?.includes(`mouse`)&&e!==`mousedown`}function Ey(e,t,n,r){let i=!1,a=!1,o=r??te;return{reason:e,event:t??new Event(`base-ui`),cancel(){i=!0},allowPropagation(){a=!0},get isCanceled(){return i},get isPropagationAllowed(){return a},trigger:n,...o}}function Dy(e,t,n){let r=n??te;return{reason:e,event:t??new Event(`base-ui`),...r}}var Oy=`none`,ky=`trigger-press`,Ay=`trigger-hover`,cVe=`trigger-focus`,lVe=`outside-press`,jy=`item-press`,uVe=`close-press`,dVe=`clear-press`,fVe=`chip-remove-press`,pVe=`track-press`,My=`input-change`,Ny=`input-clear`,mVe=`input-press`,hVe=`focus-out`,gVe=`escape-key`,_Ve=`close-watcher`,vVe=`list-navigation`,yVe=`keyboard`,bVe=`pointer`,xVe=`drag`,SVe=`cancel-open`,CVe=`sibling-open`,wVe=`disabled`,TVe=`missing`,EVe=`initial`,Py=`imperative-action`,Fy=`swipe`,DVe=`window-resize`,OVe=G.createContext({hasProvider:!1,timeoutMs:0,delayRef:{current:0},initialDelayRef:{current:0},timeout:new Jv,currentIdRef:{current:null},currentContextRef:{current:null}});function kVe(e,t){e.current=t.current}function AVe(e){let{children:t,delay:n,timeoutMs:r=0}=e,i=G.useRef(n),a=G.useRef(n),o=G.useRef(null),s=G.useRef(null),c=Yv();return Wv(()=>{a.current=n,o.current?i.current={open:Ty(i.current,`open`),close:Ty(n,`close`)}:i.current=n},[n,o,i,a]),(0,K.jsx)(OVe.Provider,{value:G.useMemo(()=>({hasProvider:!0,delayRef:i,initialDelayRef:a,currentIdRef:o,timeoutMs:r,currentContextRef:s,timeout:c}),[r,c]),children:t})}function jVe(e,t={open:!1}){let{open:n}=t,r=e.useState(`floatingId`),{currentIdRef:i,delayRef:a,timeoutMs:o,initialDelayRef:s,currentContextRef:c,hasProvider:l,timeout:u}=G.useContext(OVe),[d,f]=G.useState(!1),p=G.useRef(n);return Wv(()=>{p.current=n},[n]),Wv(()=>{function t(){c.current?.setIsInstantPhase(!1),i.current=null,c.current=null,a.current=s.current,u.clear()}if(i.current&&!n&&i.current===r){if(f(!1),o){let n=r;return u.start(o,()=>{e.select(`open`)||i.current&&i.current!==n||t()}),()=>{(p.current||i.current!==n)&&u.clear()}}t()}},[n,r,i,a,o,s,c,u,e]),Wv(()=>{if(!n)return;let t=c.current,o=i.current;u.clear(),c.current={onOpenChange:e.setOpen,setIsInstantPhase:f},i.current=r,a.current={open:0,close:Ty(s.current,`close`)},o!==null&&o!==r?(f(!0),t?.setIsInstantPhase(!0),t?.onOpenChange(!1,Ey(Oy))):(f(!1),t?.setIsInstantPhase(!1))},[n,r,e,i,a,s,c,u]),Wv(()=>()=>{if(i.current===r){if(c.current=null,!p.current)return;i.current=null,kVe(a,s),u.clear()}},[c,i,a,r,s,u]),G.useMemo(()=>({activeIdRef:i,hasProvider:l,delayRef:a,isInstantPhase:d}),[i,l,a,d])}function Iy(e,t,n,r){return e.addEventListener(t,n,r),()=>{e.removeEventListener(t,n,r)}}function Ly(...e){return()=>{for(let t=0;t<e.length;t+=1){let n=e[t];n&&n()}}}function Ry(e){let t=s(MVe,e).current;return t.next=e,Wv(t.effect),t}function MVe(e){let t={current:e,next:e,effect:()=>{t.current=t.next}};return t}var NVe={...G},PVe=NVe.useInsertionEffect,FVe=PVe&&PVe!==NVe.useLayoutEffect?PVe:e=>e();function zy(e){let t=s(IVe).current;return t.next=e,FVe(t.effect),t.trampoline}function IVe(){let e={next:void 0,callback:LVe,trampoline:(...t)=>e.callback?.(...t),effect:()=>{e.callback=e.next}};return e}function LVe(){}var By=null;globalThis.requestAnimationFrame;var Vy=new class{callbacks=[];callbacksCount=0;nextId=1;startId=1;isScheduled=!1;tick=e=>{this.isScheduled=!1;let t=this.callbacks,n=this.callbacksCount;if(this.callbacks=[],this.callbacksCount=0,this.startId=this.nextId,n>0)for(let n=0;n<t.length;n+=1)t[n]?.(e)};request(e){let t=this.nextId;return this.nextId+=1,this.callbacks.push(e),this.callbacksCount+=1,this.isScheduled||=(requestAnimationFrame(this.tick),!0),t}cancel(e){let t=e-this.startId;t<0||t>=this.callbacks.length||this.callbacks[t]!==null&&(this.callbacks[t]=null,--this.callbacksCount)}},Hy=class e{static create(){return new e}static request(e){return Vy.request(e)}static cancel(e){return Vy.cancel(e)}currentId=By;request(e){this.cancel(),this.currentId=Vy.request(()=>{this.currentId=By,e()})}cancel=()=>{this.currentId!==By&&(Vy.cancel(this.currentId),this.currentId=By)};disposeEffect=()=>this.cancel};function Uy(){let e=s(Hy.create).current;return nBe(e.disposeEffect),e}function Wy(e){return e?.ownerDocument||document}var RVe={clipPath:`inset(50%)`,overflow:`hidden`,whiteSpace:`nowrap`,border:0,padding:0,width:1,height:1,margin:-1},Gy={...RVe,position:`fixed`,margin:0,top:0,left:0},Ky={...RVe,position:`absolute`},qy=G.forwardRef(function(e,t){let[n,r]=G.useState();Wv(()=>{fBe&&$v&&r(`button`)},[]);let i={tabIndex:0,role:n};return(0,K.jsx)(`span`,{...e,ref:t,style:Gy,"aria-hidden":!n||void 0,...i,"data-base-ui-focus-guard":``})}),Jy=Math.min,Yy=Math.max,Xy=Math.round,Zy=Math.floor,Qy=e=>({x:e,y:e}),zVe={left:`right`,right:`left`,bottom:`top`,top:`bottom`};function BVe(e,t,n){return Yy(e,Jy(t,n))}function $y(e,t){return typeof e==`function`?e(t):e}function eb(e){return e.split(`-`)[0]}function tb(e){return e.split(`-`)[1]}function VVe(e){return e===`x`?`y`:`x`}function HVe(e){return e===`y`?`height`:`width`}function nb(e){let t=e[0];return t===`t`||t===`b`?`y`:`x`}function UVe(e){return VVe(nb(e))}function WVe(e,t,n){n===void 0&&(n=!1);let r=tb(e),i=UVe(e),a=HVe(i),o=i===`x`?r===(n?`end`:`start`)?`right`:`left`:r===`start`?`bottom`:`top`;return t.reference[a]>t.floating[a]&&(o=rb(o)),[o,rb(o)]}function GVe(e){let t=rb(e);return[KVe(e),t,KVe(t)]}function KVe(e){return e.includes(`start`)?e.replace(`start`,`end`):e.replace(`end`,`start`)}var qVe=[`left`,`right`],JVe=[`right`,`left`],YVe=[`top`,`bottom`],XVe=[`bottom`,`top`];function ZVe(e,t,n){switch(e){case`top`:case`bottom`:return n?t?JVe:qVe:t?qVe:JVe;case`left`:case`right`:return t?YVe:XVe;default:return[]}}function QVe(e,t,n,r){let i=tb(e),a=ZVe(eb(e),n===`start`,r);return i&&(a=a.map(e=>e+`-`+i),t&&(a=a.concat(a.map(KVe)))),a}function rb(e){let t=eb(e);return zVe[t]+e.slice(t.length)}function $Ve(e){return{top:e.top??0,right:e.right??0,bottom:e.bottom??0,left:e.left??0}}function eHe(e){return typeof e==`number`?{top:e,right:e,bottom:e,left:e}:$Ve(e)}function ib(e){let{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function ab(e,t,n){return Math.floor(e/t)!==n}function ob(e,t){return t<0||t>=e.length}function sb(e,t){return cb(e.current,{disabledIndices:t})}function tHe(e,t){return cb(e.current,{decrement:!0,startingIndex:e.current.length,disabledIndices:t})}function nHe(e,t,n){let{decrement:r,loopFocus:i,allowEscape:a,disabledIndices:o,minIndex:s,maxIndex:c}=n,l=()=>cb(e,{startingIndex:t,decrement:r,disabledIndices:o}),u,d=!1;if(!i)u=r?Math.max(s,l()):Math.min(c,l());else if(r?t<=s:t>=c){let n=r?-1:e.length;a&&t!==n?u=-1:(u=r?c:s,d=!0)}else u=l();return{index:ob(e,u)?-1:u,wrapped:d}}function cb(e,{startingIndex:t=-1,decrement:n=!1,disabledIndices:r,amount:i=1}={}){let a=t;do a+=n?-i:i;while(a>=0&&a<=e.length-1&&lb(e,a,r));return a}function rHe(e,{event:t,orientation:n,loopFocus:r,onLoop:i,rtl:a,cols:o,disabledIndices:s,minIndex:c,maxIndex:l,prevIndex:u,stopEvent:d=!1}){let f=u,p;if(t.key===`ArrowUp`?p=`up`:t.key===`ArrowDown`&&(p=`down`),p){let n=[],a=[],m=!1,h=0;{let t=null,r=-1;e.forEach((e,i)=>{if(e==null)return;h+=1;let o=_y(e,`[role="row"]`);o&&(m=!0),(o!==t||r===-1)&&(t=o,r+=1,n[r]=[]),n[r].push(i),a[i]=r})}let g=!1,_=0;if(m)for(let e of n){let t=e.length;t>_&&(_=t),t!==o&&(g=!0)}let v=g&&h<e.length,y=_||o,b=o=>{if(!g||u===-1)return;let c=a[u];if(c==null)return;let l=n[c].indexOf(u),d=o===`up`?-1:1;for(let o=c+d,f=0;f<n.length;f+=1,o+=d){if(o<0||o>=n.length){if(!r||v)return;if(o=o<0?n.length-1:0,i){let e=Math.min(l,n[o].length-1),r=i(t,u,n[o][e]??n[o][0]);o=a[r]??o}}let c=n[o];for(let t=Math.min(l,c.length-1);t>=0;--t){let n=c[t];if(!lb(e,n,s))return n}}},x=t=>{if(!v||u===-1)return;let n=u%y,i=t===`up`?-y:y,a=l-l%y,o=Zy(l/y)+1;for(let t=u-n+i,c=0;c<o;c+=1,t+=i){if(t<0||t>l){if(!r)return;t=t<0?a:0}let i=Math.min(t+y-1,l);for(let r=Math.min(t+n,i);r>=t;--r)if(!lb(e,r,s))return r}};d&&ey(t);let S=b(p)??x(p);if(S!==void 0)f=S;else if(u===-1)f=p===`up`?l:c;else if(f=cb(e,{startingIndex:u,amount:y,decrement:p===`up`,disabledIndices:s}),r){if(p===`up`&&(u-y<c||f<0)){let e=u%y,n=l%y,r=l-(n-e);f=n===e?l:n>e?r:r-y,i&&(f=i(t,u,f))}p===`down`&&u+y>l&&(f=cb(e,{startingIndex:u%y-y,amount:y,disabledIndices:s}),i&&(f=i(t,u,f)))}ob(e,f)&&(f=u)}if(n===`both`){let n=Zy(u/o);t.key===(a?`ArrowLeft`:`ArrowRight`)&&(d&&ey(t),u%o===o-1?r&&(f=cb(e,{startingIndex:u-u%o-1,disabledIndices:s}),i&&(f=i(t,u,f))):(f=cb(e,{startingIndex:u,disabledIndices:s}),r&&ab(f,o,n)&&(f=cb(e,{startingIndex:u-u%o-1,disabledIndices:s}),i&&(f=i(t,u,f)))),ab(f,o,n)&&(f=u)),t.key===(a?`ArrowRight`:`ArrowLeft`)&&(d&&ey(t),u%o===0?r&&(f=cb(e,{startingIndex:u+(o-u%o),decrement:!0,disabledIndices:s}),i&&(f=i(t,u,f))):(f=cb(e,{startingIndex:u,decrement:!0,disabledIndices:s}),r&&ab(f,o,n)&&(f=cb(e,{startingIndex:u+(o-u%o),decrement:!0,disabledIndices:s}),i&&(f=i(t,u,f)))),ab(f,o,n)&&(f=u));let c=Zy(l/o)===n;ob(e,f)&&(r&&c?(f=t.key===(a?`ArrowRight`:`ArrowLeft`)?l:cb(e,{startingIndex:u-u%o-1,disabledIndices:s}),i&&(f=i(t,u,f))):f=u)}return f}function lb(e,t,n){if(typeof n==`function`?n(t):n?.includes(t)??!1)return!0;let r=e[t];return r?!ub(r)||r.matches(`:disabled`)?!0:!n&&(r.hasAttribute(`disabled`)||r.getAttribute(`aria-disabled`)===`true`):!1}function iHe(e){return e.visibility===`hidden`||e.visibility===`collapse`}function ub(e,t=e?fy(e):null){return!e||!e.isConnected||!t||iHe(t)?!1:typeof e.checkVisibility==`function`?e.checkVisibility():t.display!==`none`&&t.display!==`contents`}var aHe=`a[href],button,input,select,textarea,summary,details,iframe,object,embed,[tabindex],[contenteditable]:not([contenteditable="false"]),audio[controls],video[controls]`;function oHe(e){let t=e.assignedSlot;if(t)return t;if(e.parentElement)return e.parentElement;let n=e.getRootNode();return cy(n)?n.host:null}function sHe(e){for(let t of Array.from(e.children))if(ry(t)===`summary`)return t;return null}function cHe(e,t){let n=sHe(t);return!!n&&(e===n||gy(n,e))}function lHe(e){let t=e?ry(e):``;return e!=null&&e.matches(aHe)&&(t!==`summary`||e.parentElement!=null&&ry(e.parentElement)===`details`&&sHe(e.parentElement)===e)&&(t!==`details`||sHe(e)==null)&&(t!==`input`||e.type!==`hidden`)}function uHe(e){if(!lHe(e)||!e.isConnected||e.matches(`:disabled`))return!1;for(let t=e;t;t=oHe(t)){let n=t!==e,r=ry(t)===`slot`;if(t.hasAttribute(`inert`)||n&&ry(t)===`details`&&!t.open&&!cHe(e,t)||t.hasAttribute(`hidden`)||!r&&!dHe(t,n))return!1}return!0}function dHe(e,t){let n=fy(e);return t?n.display!==`none`:ub(e,n)}function fHe(e){let t=e.tabIndex;if(t<0){let t=ry(e);if(t===`details`||t===`audio`||t===`video`||sy(e)&&e.isContentEditable)return 0}return t}function pHe(e){if(ry(e)!==`input`)return null;let t=e;return t.type===`radio`&&t.name!==``?t:null}function mHe(e,t){let n=pHe(e);if(!n)return!0;let r=t.find(e=>{let t=pHe(e);return t?.name===n.name&&t.form===n.form&&t.checked});return r?r===n:t.find(e=>{let t=pHe(e);return t?.name===n.name&&t.form===n.form})===n}function hHe(e){if(sy(e)&&ry(e)===`slot`){let t=e.assignedElements({flatten:!0});if(t.length>0)return t}return sy(e)&&e.shadowRoot?Array.from(e.shadowRoot.children):Array.from(e.children)}function gHe(e,t){hHe(e).forEach(e=>{lHe(e)&&t.push(e),gHe(e,t)})}function _He(e,t,n){hHe(e).forEach(e=>{sy(e)&&e.matches(t)&&n.push(e),_He(e,t,n)})}function db(e){return uHe(e)&&fHe(e)>=0}function vHe(e){let t=[];return gHe(e,t),t.filter(uHe)}function fb(e){let t=vHe(e);return t.filter(e=>fHe(e)>=0&&mHe(e,t))}function yHe(e,t){let n=fb(e),r=n.length;if(r===0)return;let i=hy(Wy(e)),a=n.indexOf(i);return n[a===-1?t===1?0:r-1:a+t]}function bHe(e){return yHe(Wy(e).body,1)||e}function xHe(e){return yHe(Wy(e).body,-1)||e}function SHe(e,t,n){if(!e)return null;let r=[];gHe(Wy(e).body,r);let i=r.indexOf(e);if(i===-1)return null;let a=r.filter(uHe);for(let e=1;e<r.length;e+=1){let o=r[(i+t*e+r.length)%r.length];if(!gy(n,o)&&db(o)&&mHe(o,a))return o}return r[i]}function pb(e,t){let n=t||e.currentTarget,r=e.relatedTarget;return!r||!gy(n,r)}function CHe(e){fb(e).forEach(e=>{e.dataset.tabindex=e.getAttribute(`tabindex`)||``,e.setAttribute(`tabindex`,`-1`)})}function wHe(e){let t=[];_He(e,`[data-tabindex]`,t),t.forEach(e=>{let t=e.dataset.tabindex;delete e.dataset.tabindex,t?e.setAttribute(`tabindex`,t):e.removeAttribute(`tabindex`)})}function mb(e,t,n=!0){return e.filter(e=>e.parentId===t).flatMap(t=>[...!n||t.context?.open?[t]:[],...mb(e,t.id,n)])}function THe(e,t){let n=[],r=e.find(e=>e.id===t)?.parentId;for(;r;){let t=e.find(e=>e.id===r);r=t?.parentId,t&&(n=n.concat(t))}return n}function hb(e){return`data-base-ui-${e}`}var gb=0;function _b(e,t={}){let{preventScroll:n=!1,sync:r=!1,shouldFocus:i}=t;cancelAnimationFrame(gb);function a(){(!i||i())&&e?.focus({preventScroll:n})}if(r)return a(),C;let o=requestAnimationFrame(a);return gb=o,()=>{gb===o&&(cancelAnimationFrame(o),gb=0)}}var EHe=`data-base-ui-inert`,vb=new WeakMap,yb=new WeakSet,bb=new WeakMap,DHe=0;function OHe(e){return e?cy(e)?e.host:OHe(e.parentNode):null}var kHe=(e,t)=>t.map(t=>{if(e.contains(t))return t;let n=OHe(t);return e.contains(n)?n:null}).filter(e=>e!=null),AHe=e=>{let t=new Set;return e.forEach(e=>{let n=e;for(;n&&!t.has(n);)t.add(n),n=n.parentNode}),t},jHe=(e,t,n)=>{let r=[],i=e=>{e&&!n.has(e)&&Array.from(e.children).forEach(e=>{ry(e)!==`script`&&(t.has(e)?i(e):r.push(e))})};return i(e),r};function MHe(e,t,n,{mark:r=!0}){let i=kHe(t,e),a=r?jHe(t,AHe(i),new Set(i)):[],o=[],s=[];if(n){let e=kHe(t,Array.from(t.querySelectorAll(`[aria-live]`))),n=i.concat(e);jHe(t,AHe(n),new Set(n)).forEach(e=>{let t=e.getAttribute(`aria-hidden`),n=t!==null&&t!==`false`,r=(vb.get(e)||0)+1;vb.set(e,r),o.push(e),r===1&&n&&yb.add(e),n||e.setAttribute(`aria-hidden`,`true`)})}return r&&a.forEach(e=>{let t=(bb.get(e)||0)+1;bb.set(e,t),s.push(e),t===1&&e.setAttribute(EHe,``)}),DHe+=1,()=>{o.forEach(e=>{let t=(vb.get(e)||0)-1;vb.set(e,t),t||(yb.has(e)||e.removeAttribute(`aria-hidden`),yb.delete(e))}),r&&s.forEach(e=>{let t=(bb.get(e)||0)-1;bb.set(e,t),t||e.removeAttribute(EHe)}),--DHe,DHe||(vb=new WeakMap,yb=new WeakSet,bb=new WeakMap)}}function NHe(e,t={}){let{ariaHidden:n=!1,mark:r=!0}=t,i=Wy(e[0]).body;return MHe(e,i,n,{mark:r})}function PHe(){let[,e]=G.useState({});return G.useCallback(()=>{e({})},[])}var FHe=0;function IHe(e,t=`mui`){let n=G.useRef(void 0),r=PHe(),i=e??n.current;return G.useEffect(()=>{n.current??(FHe+=1,n.current=`${t}-${FHe}`,e??r())},[e,t,r]),i}var LHe=NVe.useId;function xb(e,t){if(LHe!==void 0){let n=LHe();return e??(t?`${t}-${n}`:n)}return IHe(e,t)}var RHe={style:{transition:`none`}},zHe=`data-base-ui-click-trigger`,BHe=`data-base-ui-swipe-ignore`,VHe=`[${BHe}]`,HHe={fallbackAxisSide:`none`},Sb={fallbackAxisSide:`end`},UHe={clipPath:`inset(50%)`,position:`fixed`,top:0,left:0},WHe=G.createContext(null),GHe=()=>G.useContext(WHe),KHe=hb(`portal`);function qHe(e={}){let{ref:t,container:n,componentProps:r=te,elementProps:i}=e,a=xb(),o=GHe()?.portalNode,[s,c]=G.useState(null),[l,u]=G.useState(null),d=zy(e=>{e!==null&&u(e)}),f=G.useRef(null);Wv(()=>{if(n===null){f.current&&(f.current=null,u(null),c(null));return}let e=(n&&(vBe(n)?n:n.current))??o??document.body;e==null?f.current&&(f.current=null,u(null),c(null)):f.current!==e&&(f.current=e,u(null),c(e))},[n,o]);let p=N(`div`,r,{ref:[t,d],props:[{id:a,[KHe]:``},i]}),m=s&&p?Pt.createPortal(p,s):null;return{node:l,nodeId:G.isValidElement(p)?p.props.id:void 0,subtree:m}}var Cb=G.forwardRef(function(e,t){let{render:n,className:r,style:i,children:a,container:o,portalOwnerRole:s,...c}=e,{node:l,nodeId:u,subtree:d}=qHe({container:o,ref:t,componentProps:e,elementProps:c}),f=G.useRef(null),p=G.useRef(null),m=G.useRef(null),h=G.useRef(null),[g,_]=G.useState(null),v=G.useRef(!1),y=g?.modal,b=g?.open,x=!!g&&!g.modal&&g.open&&!!l;G.useEffect(()=>{if(!l||y)return;function e(e){l&&e.relatedTarget&&pb(e)&&(e.type===`focusin`?v.current&&=(wHe(l),!1):(CHe(l),v.current=!0))}return Ly(Iy(l,`focusin`,e,!0),Iy(l,`focusout`,e,!0))},[l,y]),Wv(()=>{l&&b===!0&&v.current&&(wHe(l),v.current=!1)},[b,l]);let S=G.useMemo(()=>({beforeOutsideRef:f,afterOutsideRef:p,beforeInsideRef:m,afterInsideRef:h,portalNode:l,setFocusManagerState:_}),[l]);return(0,K.jsxs)(G.Fragment,{children:[d,(0,K.jsxs)(WHe.Provider,{value:S,children:[x&&l&&(0,K.jsx)(qy,{"data-type":`outside`,ref:f,onFocus:e=>{pb(e,l)?m.current?.focus():xHe(g?g.domReference:null)?.focus()}}),x&&l&&(0,K.jsx)(`span`,{role:s,"aria-owns":u,style:UHe}),l&&Pt.createPortal(a,l),x&&l&&(0,K.jsx)(qy,{"data-type":`outside`,ref:p,onFocus:e=>{pb(e,l)?h.current?.focus():(bHe(g?g.domReference:null)?.focus(),g?.closeOnFocusOut&&g?.onOpenChange(!1,Ey(`focus-out`,e.nativeEvent)))}})]})]})});function JHe(){let e=new Map;return{emit(t,n){e.get(t)?.forEach(e=>e(n))},on(t,n){e.has(t)||e.set(t,new Set),e.get(t).add(n)},off(t,n){e.get(t)?.delete(n)}}}var YHe=class{nodesRef={current:[]};events=JHe();addNode(e){this.nodesRef.current.push(e)}removeNode(e){let t=this.nodesRef.current.findIndex(t=>t===e);t!==-1&&this.nodesRef.current.splice(t,1)}},XHe=G.createContext(null),ZHe=G.createContext(null),wb=()=>G.useContext(XHe)?.id||null,Tb=e=>{let t=G.useContext(ZHe);return e??t};function Eb(e){let t=xb(),n=Tb(e),r=wb();return Wv(()=>{if(!t)return;let e={id:t,parentId:r};return n?.addNode(e),()=>{n?.removeNode(e)}},[n,t,r]),t}function QHe(e){let{children:t,id:n}=e,r=wb();return(0,K.jsx)(XHe.Provider,{value:G.useMemo(()=>({id:n,parentId:r}),[n,r]),children:t})}function $He(e){let{children:t,externalTree:n}=e,r=s(()=>n??new YHe).current;return(0,K.jsx)(ZHe.Provider,{value:r,children:t})}function Db(e){return e==null?e:`current`in e?e.current:e}function eUe(e,t){let n=iy(vy(e));return e instanceof n.KeyboardEvent?`keyboard`:e instanceof n.FocusEvent?t||`keyboard`:`pointerType`in e?e.pointerType||(ty(e)?`keyboard`:t||`mouse`):`touches`in e?`touch`:e instanceof n.MouseEvent?t||(e.detail===0?`keyboard`:`mouse`):``}var tUe=20,Ob=[];function nUe(){Ob=Ob.filter(e=>e.deref()?.isConnected)}function rUe(e){nUe(),e&&ry(e)!==`body`&&(Ob.push(new WeakRef(e)),Ob.length>tUe&&(Ob=Ob.slice(-20)))}function iUe(){return nUe(),Ob[Ob.length-1]?.deref()}function aUe(e){return e?db(e)?e:fb(e)[0]||e:null}function oUe(e){if(e.hasAttribute(`tabindex`)&&!e.hasAttribute(`data-tabindex`)||!e.getAttribute(`role`)?.includes(`dialog`))return;let t=vHe(e).filter(e=>{let t=e.getAttribute(`data-tabindex`)||``;return db(e)||e.hasAttribute(`data-tabindex`)&&!t.startsWith(`-`)}),n=e.getAttribute(`tabindex`);t.length===0?n!==`0`&&(e.setAttribute(`tabindex`,`0`),e.setAttribute(`data-tabindex`,`0`)):(n!==`-1`||e.hasAttribute(`data-tabindex`)&&e.getAttribute(`data-tabindex`)!==`-1`)&&(e.setAttribute(`tabindex`,`-1`),e.setAttribute(`data-tabindex`,`-1`))}function kb(e){let{context:t,children:n,disabled:r=!1,initialFocus:i=!0,returnFocus:a=!0,explicitReturnFocus:o,restoreFocus:s=!1,modal:c=!0,closeOnFocusOut:l=!0,openInteractionType:u=``,nextFocusableElement:d,previousFocusableElement:f,beforeContentFocusGuardRef:p,externalTree:m,getInsideElements:h}=e,g=t.useState(`open`),_=t.useState(`domReferenceElement`),y=t.useState(`floatingElement`),{events:b,dataRef:x}=t.context,S=zy(()=>x.current.floatingContext?.nodeId),C=i===!1,w=tVe(_)&&C,T=Ry(i),E=Ry(a),D=Ry(o),O=Ry(u),k=Ry(g),A=Tb(m),j=GHe(),M=G.useRef(!1),N=G.useRef(!1),P=G.useRef(!1),F=G.useRef(null),I=G.useRef(``),L=G.useRef(``),R=G.useRef(null),z=G.useRef(null),B=v(R,p,j?.beforeInsideRef),V=v(z,j?.afterInsideRef),H=Yv(),ee=Yv(),te=Uy(),U=j!=null,W=rVe(y),ne=zy((e=W)=>e?fb(e):[]),re=zy(()=>h?.().filter(e=>e!=null)??[]);G.useEffect(()=>{if(r||!c)return;function e(e){e.key===`Tab`&&gy(W,hy(Wy(W)))&&ne().length===0&&!w&&ey(e)}return Iy(Wy(W),`keydown`,e)},[r,W,c,w,ne]),G.useEffect(()=>{if(r||!g)return;let e=Wy(W);function t(){P.current=!1}function n(e){let t=vy(e),n=re(),r=gy(y,t)||gy(_,t)||gy(j?.portalNode,t)||n.some(e=>e===t||gy(e,t));P.current=!r,L.current=e.pointerType||`keyboard`,_y(t,`[data-base-ui-click-trigger]`)&&(N.current=!0,ee.start(0,()=>{N.current=!1}))}function i(){L.current=`keyboard`}return Ly(Iy(e,`pointerdown`,n,!0),Iy(e,`pointerup`,t,!0),Iy(e,`pointercancel`,t,!0),Iy(e,`keydown`,i,!0),t)},[r,y,_,W,g,j,ee,re]),G.useEffect(()=>{if(r||!l)return;let e=Wy(W);function n(){N.current=!0,ee.start(0,()=>{N.current=!1})}function i(e){let t=vy(e);db(t)&&(F.current=t)}function a(n){let r=n.relatedTarget,i=n.currentTarget,a=vy(n);c&&r==null&&a!=null&&gy(y,a)&&rUe(a),queueMicrotask(()=>{let o=S(),l=t.context.triggerElements,u=re(),p=r?.hasAttribute(hb(`focus-guard`))&&[R.current,z.current,j?.beforeInsideRef.current,j?.afterInsideRef.current,j?.beforeOutsideRef.current,j?.afterOutsideRef.current,Db(f),Db(d)].includes(r),m=!(gy(_,r)||gy(y,r)||gy(r,y)||gy(j?.portalNode,r)||u.some(e=>e===r||gy(e,r))||l.hasMatchingElement(e=>gy(e,r))||p||A&&(mb(A.nodesRef.current,o).find(e=>gy(e.context?.elements.floating,r)||gy(e.context?.elements.domReference,r))||THe(A.nodesRef.current,o).find(e=>[e.context?.elements.floating,rVe(e.context?.elements.floating)].includes(r)||e.context?.elements.domReference===r)));if(i===_&&W&&oUe(W),s&&i!==_&&!ub(a)&&hy(e)===e.body){if(sy(W)&&(W.focus(),s===`popup`)){te.request(()=>{W.focus()});return}let e=ne(),t=F.current,n=(t&&e.includes(t)?t:null)||e[e.length-1]||W;sy(n)&&n.focus()}x.current.insideReactTree?x.current.insideReactTree=!1:(w||!c)&&r&&m&&!N.current&&(w||r!==iUe())&&(M.current=!0,t.setOpen(!1,Ey(hVe,n)))})}function o(){P.current||(x.current.insideReactTree=!0,H.start(0,()=>{x.current.insideReactTree=!1}))}let u=sy(_)?_:null;if(y||u)return Ly(u&&Iy(u,`focusout`,a),u&&Iy(u,`pointerdown`,n),y&&Iy(y,`focusin`,i),y&&Iy(y,`focusout`,a),y&&j&&Iy(y,`focusout`,o,!0))},[r,_,y,W,c,A,j,t,l,s,ne,w,S,x,H,ee,te,d,f,re]),G.useEffect(()=>{if(r||!y||!g)return;let e=Array.from(j?.portalNode?.querySelectorAll(`[${hb(`portal`)}]`)||[]),t=(A?THe(A.nodesRef.current,S()):[]).find(e=>tVe(e.context?.elements.domReference||null))?.context?.elements.domReference,n=NHe([y,...e,R.current,z.current,j?.beforeOutsideRef.current,j?.afterOutsideRef.current,...re(),t,Db(f),Db(d),w?_:null].filter(e=>e!=null),{ariaHidden:c||w,mark:!1}),i=NHe([y,...e].filter(e=>e!=null));return()=>{i(),n()}},[g,r,_,y,c,j,w,A,S,d,f,re]),Wv(()=>{if(!g||r||!sy(W))return;I.current=``,L.current=``;let e=Wy(W),t=hy(e);queueMicrotask(()=>{let n=T.current,r=typeof n==`function`?n(O.current||``):n;if(r===void 0||r===!1||gy(W,t))return;let i=null,a=()=>(i??=ne(W),i[0]||W),o;o=r===!0||r===null?a():Db(r),o||=a();let s=gy(W,hy(e)),c=x.current.openEvent,l=c?.type===`mousedown`&&ty(c);_b(o,{sync:l,preventScroll:o===W,shouldFocus(){if(!k.current)return!1;if(s)return!0;let t=hy(e);return!(t!==o&&gy(W,t))}})})},[r,g,W,ne,T,O,k,x]);let ie=G.useRef(null);Wv(()=>{if(r||!W){ie.current=null;return}ie.current&&=(ie.current.cancelled=!0,null);let e=Wy(W),t=hy(e),n=O.current==null;rUe(t);function i(e){if(e.open||(I.current=eUe(e.nativeEvent,L.current)),(e.reason===`focus-out`&&e.triggerElement?.hasAttribute(hb(`focus-guard`))||e.reason===`trigger-hover`&&e.nativeEvent.type===`mouseleave`)&&(M.current=!0),e.reason===`outside-press`){if(e.nested)M.current=!1;else if(ty(e.nativeEvent)||hBe(e.nativeEvent))M.current=!1;else{let e=!1;Wy(W).createElement(`div`).focus({get preventScroll(){return e=!0,!1}}),e?M.current=!1:M.current=!0}}}b.on(`openchange`,i);function a(e){let r=E.current,i=typeof r==`function`?r(e):r;if(i===void 0||i===!1)return null;i===null&&(i=!0);let a=_?.isConnected?_:null,o=t?.isConnected&&ry(t)!==`body`?t:null,s=n?o||a:a||o;return s||=iUe()||null,typeof i==`boolean`?s:Db(i)||s||null}return()=>{b.off(`openchange`,i);let t=hy(e),n=re(),r=gy(y,t)||n.some(e=>e===t||gy(e,t))||A&&mb(A.nodesRef.current,S(),!1).some(e=>gy(e.context?.elements.floating,t)),o=E.current,s=I.current,c=a(s),l={cancelled:!1};ie.current=l,queueMicrotask(()=>{ie.current===l&&(ie.current=null);let n=aUe(c),i=D.current??typeof o!=`boolean`;if(!l.cancelled&&o&&!M.current&&sy(n)&&(i||n===t||t===e.body||r)){let e={preventScroll:!0};s===`keyboard`&&(e.focusVisible=!0),n.focus(e)}M.current=!1})}},[r,y,W,E,D,O,b,A,_,S,re]),Wv(()=>{if(!$v||g||!y)return;let e=hy(Wy(y));sy(e)&&wy(e)&&gy(y,e)&&e.blur()},[g,y]),Wv(()=>{if(!r&&j)return j.setFocusManagerState({modal:c,closeOnFocusOut:l,open:g,onOpenChange:t.setOpen,domReference:_}),()=>{j.setFocusManagerState(null)}},[r,j,c,g,t,l,_]),Wv(()=>{if(!r&&W)return oUe(W),()=>{queueMicrotask(nUe)}},[r,W]);let ae=!r&&(!c||!w)&&(U||c);return(0,K.jsxs)(G.Fragment,{children:[ae&&(0,K.jsx)(qy,{"data-type":`inside`,ref:B,onFocus:e=>{if(c){let e=ne();_b(e[e.length-1])}else j?.portalNode&&(M.current=!1,pb(e,j.portalNode)?bHe(_)?.focus():Db(f??j.beforeOutsideRef)?.focus())}}),n,ae&&(0,K.jsx)(qy,{"data-type":`inside`,ref:V,onFocus:e=>{c?_b(ne()[0]):j?.portalNode&&(l&&(M.current=!0),pb(e,j.portalNode)?xHe(_)?.focus():Db(d??j.afterOutsideRef)?.focus())}})]})}function Ab(e,t={}){let{enabled:n=!0,event:r=`click`,toggle:i=!0,ignoreMouse:a=!1,stickIfOpen:o=!0,touchOpenDelay:s=0,reason:c=ky}=t,l=e.context.dataRef,u=G.useRef(void 0),d=Uy(),f=Yv(),p=G.useMemo(()=>{function t(t,n,r,i){let a=Ey(c,n,r);t&&i===`touch`&&s>0?f.start(s,()=>{e.setOpen(!0,a)}):e.setOpen(t,a)}function n(t,n,r){let a=l.current.openEvent,s=e.select(`domReferenceElement`)!==n;return t&&s||!t||!i?!0:a&&(typeof o==`function`?o():o)?!r(a.type):!1}return{onPointerDown(e){u.current=ny(e.pointerType,!0)&&hBe(e.nativeEvent)?`virtual`:e.pointerType},onMouseDown(i){let o=u.current,s=i.nativeEvent,c=e.select(`open`);if(i.button!==0||r===`click`||ny(o,!0)&&a)return;let l=n(c,i.currentTarget,e=>e===`click`||e===`mousedown`),f=vy(s),p=wy(f);if(p||o===`virtual`){t(l,s,p?f:i.currentTarget,o);return}let m=i.currentTarget;d.request(()=>{t(l,s,m,o)})},onClick(i){if(r===`mousedown-only`)return;let o=u.current;r===`mousedown`&&o?u.current=void 0:ny(o,!0)&&a||t(n(e.select(`open`),i.currentTarget,e=>e===`click`||e===`mousedown`||e===`keydown`||e===`keyup`),i.nativeEvent,i.currentTarget,o)},onKeyDown(){u.current=void 0}}},[l,r,a,c,e,o,i,d,f,s]);return G.useMemo(()=>n?{reference:p}:te,[n,p])}function sUe(e,t){let n=null,r=null,i=!1;return{contextElement:e||void 0,getBoundingClientRect(){let a=e?.getBoundingClientRect()||{width:0,height:0,x:0,y:0},o=t.axis===`x`||t.axis===`both`,s=t.axis===`y`||t.axis===`both`,c=[`mouseenter`,`mousemove`].includes(t.dataRef.current.openEvent?.type||``)&&t.pointerType!==`touch`,l=t.axis===`y`?a.width:0,u=t.axis===`x`?a.height:0,d=a.x,f=a.y;return n==null&&t.x&&o&&(n=a.x-t.x),r==null&&t.y&&s&&(r=a.y-t.y),d-=n||0,f-=r||0,(!i||c)&&(d=o&&t.x!=null?t.x:d,f=s&&t.y!=null?t.y:f),i=!0,{width:l,height:u,x:d,y:f,top:f,right:d+l,bottom:f+u,left:d}}}}function cUe(e){return e!=null&&e.clientX!=null}function lUe(e,t={}){let{enabled:n=!0,axis:r=`both`}=t,i=e.useState(`open`),a=e.useState(`floatingElement`),o=e.useState(`domReferenceElement`),s=e.context.dataRef,c=G.useRef(!1),l=G.useRef(null),[u,d]=G.useState(),[f,p]=G.useState([]),m=zy(t=>{e.set(`positionReference`,t)}),h=zy((t,n,i)=>{c.current||(!s.current.openEvent||cUe(s.current.openEvent))&&e.set(`positionReference`,sUe(i??o,{x:t,y:n,axis:r,dataRef:s,pointerType:u}))}),g=zy(e=>{i?l.current||(h(e.clientX,e.clientY,e.currentTarget),p([])):h(e.clientX,e.clientY,e.currentTarget)}),_=ny(u)?a:i;G.useEffect(()=>{if(!n){m(o);return}if(!_)return;function e(){l.current?.(),l.current=null}let t=iy(a);function r(t){let n=vy(t);gy(a,n)?e():h(t.clientX,t.clientY)}return!s.current.openEvent||cUe(s.current.openEvent)?l.current=Iy(t,`mousemove`,r):m(o),e},[_,n,a,s,o,e,h,m,f]),G.useEffect(()=>()=>{e.set(`positionReference`,null)},[e]),G.useEffect(()=>{n&&!a&&(c.current=!1)},[n,a]),G.useEffect(()=>{!n&&i&&(c.current=!0)},[n,i]);let v=G.useMemo(()=>{function e(e){d(e.pointerType)}return{onPointerDown:e,onPointerEnter:e,onMouseMove:g,onMouseEnter:g}},[g]);return G.useMemo(()=>n?{reference:v,trigger:v}:{},[n,v])}function uUe(){return!1}function dUe(e){return{escapeKey:typeof e==`boolean`?e:e?.escapeKey??!1,outsidePress:typeof e==`boolean`?e:e?.outsidePress??!0}}function jb(e,t={}){let{enabled:n=!0,escapeKey:r=!0,outsidePress:i=!0,outsidePressEvent:a=`sloppy`,referencePress:o=uUe,bubbles:s,externalTree:c}=t,l=e.useState(`open`),u=e.useState(`floatingElement`),{dataRef:d,events:f}=e.context,p=Tb(c),m=zy(typeof i==`function`?i:()=>!1),h=typeof i==`function`?m:i,g=h!==!1,_=zy(()=>a),{escapeKey:v,outsidePress:y}=dUe(s),b=G.useRef(!1),x=G.useRef(!1),S=G.useRef(!1),C=G.useRef(!1),w=G.useRef(!1),T=G.useRef(``),E=G.useRef(null),D=Yv(),O=Yv(),k=Yv(),A=zy(()=>{O.clear(),d.current.insideReactTree=!1}),j=zy(e=>{let t=d.current.floatingContext?.nodeId;return(p?mb(p.nodesRef.current,t):[]).some(t=>t.context?.open&&!t.context.dataRef.current[e])}),M=zy(t=>QBe(t,e.select(`floatingElement`))||QBe(t,e.select(`domReferenceElement`))),N=zy(t=>{o()&&e.setOpen(!1,Ey(ky,t.nativeEvent))}),P=zy(t=>{if(!l||!n||!r||t.key!==`Escape`)return;let i=mBe(t)?t.nativeEvent:t;if(w.current||i.isComposing||!v&&j(`__escapeKeyBubbles`))return;let a=Ey(gVe,i);e.setOpen(!1,a),a.isCanceled||t.preventDefault(),!v&&!a.isPropagationAllowed&&t.stopPropagation()}),F=zy(()=>{d.current.insideReactTree=!0,O.start(0,A)}),I=zy(t=>{if(!l||!n||t.button!==0)return;let r=vy(t.nativeEvent);gy(e.select(`floatingElement`),r)&&(b.current||(b.current=!0,x.current=!1))}),L=zy(e=>{l&&n&&(e.defaultPrevented||e.nativeEvent.defaultPrevented)&&b.current&&(x.current=!0)});G.useEffect(()=>{function e(e){e.open||(C.current=!1)}return f.on(`openchange`,e),()=>{f.off(`openchange`,e)}},[f]),G.useEffect(()=>A,[A]),G.useEffect(()=>{if(!l||!n)return l||(C.current=!1,w.current=!1,T.current=``,E.current=null),A;d.current.__escapeKeyBubbles=v,d.current.__outsidePressBubbles=y;let t=new Jv,i=Wy(u);function a(){k.clear(),w.current=!0}function o(){w.current=!0,k.start($v?5:0,()=>{w.current=!1})}function s(){S.current=!0,t.start(0,()=>{S.current=!1})}function c(){b.current=!1,x.current=!1}function f(){let e=T.current,t=e===`pen`||!e?`mouse`:e,n=_(),r=typeof n==`function`?n():n;return typeof r==`string`?r:r[t]}function m(e){let t=f();return t===`intentional`&&e.type!==`click`||t===`sloppy`&&e.type===`click`}function O(e){let t=d.current.floatingContext?.nodeId,n=p&&mb(p.nodesRef.current,t).some(t=>QBe(e,t.context?.elements.floating));return M(e)||n}function N(n){if(m(n)){n.type!==`click`&&!M(n)&&(t.clear(),S.current=!1),A();return}if(d.current.insideReactTree){A();return}let r=vy(n),i=`[${hb(`inert`)}]`,a=oy(r)?r.getRootNode():null,o=Array.from((cy(a)?a:Wy(e.select(`floatingElement`))).querySelectorAll(i)),s=e.context.triggerElements;if(r&&(s.hasElement(r)||s.hasMatchingElement(e=>gy(e,r))))return;let c=oy(r)?r:null;for(;c&&!dy(c);){let e=py(c);if(dy(e)||!oy(e))break;c=e}if(!(o.length&&oy(r)&&!$Be(r)&&!gy(r,e.select(`floatingElement`))&&o.every(e=>!gy(c,e)))){if(sy(r)&&!(`touches`in n)){let e=dy(r),t=fy(r),i=/auto|scroll/,a=e||i.test(t.overflowX),o=e||i.test(t.overflowY),s=a&&r.clientWidth>0&&r.scrollWidth>r.clientWidth,c=o&&r.clientHeight>0&&r.scrollHeight>r.clientHeight,l=t.direction===`rtl`,u=c&&(l?n.offsetX<=r.offsetWidth-r.clientWidth:n.offsetX>r.clientWidth),d=s&&n.offsetY>r.clientHeight;if(u||d)return}if(!O(n)){if(f()===`intentional`){if(n.detail!==0&&!ty(n)&&!C.current)return;if(S.current){t.clear(),S.current=!1;return}}typeof h==`function`&&!h(n)||j(`__outsidePressBubbles`)||(e.setOpen(!1,Ey(lVe,n)),A())}}}function F(t){f()===`sloppy`&&t.pointerType!==`touch`&&e.select(`open`)&&n&&!M(t)&&N(t)}function I(t){if(f()!==`sloppy`||!e.select(`open`)||!n||M(t))return;let r=t.touches[0];r&&(E.current={startTime:Date.now(),startX:r.clientX,startY:r.clientY,dismissOnTouchEnd:!1,dismissOnMouseDown:!0},D.start(1e3,()=>{E.current&&(E.current.dismissOnTouchEnd=!1,E.current.dismissOnMouseDown=!1)}))}function L(e,t){let n=vy(e);if(!n)return;let r=Iy(n,e.type,()=>{t(e),r()})}function R(e){T.current=`touch`,L(e,I)}function z(e){D.clear(),e.type===`pointerdown`&&(e.button===0&&(C.current=!0),T.current=e.pointerType),(e.type!==`mousedown`||!E.current||E.current.dismissOnMouseDown)&&L(e,e=>{e.type===`pointerdown`?F(e):N(e)})}function B(e){if(e.type===`pointercancel`&&(C.current=!1),!b.current)return;let n=x.current;c(),f()===`intentional`&&(e.type===`pointercancel`?n&&s():O(e)||(n?s():(typeof h!=`function`||h(e))&&(t.clear(),S.current=!0,A())))}function V(e){if(f()!==`sloppy`||!E.current||M(e))return;let t=e.touches[0];if(!t)return;let n=Math.abs(t.clientX-E.current.startX),r=Math.abs(t.clientY-E.current.startY),i=Math.sqrt(n*n+r*r);i>5&&(E.current.dismissOnTouchEnd=!0),i>10&&(N(e),D.clear(),E.current=null)}function H(e){L(e,V)}function ee(e){f()===`sloppy`&&E.current&&!M(e)&&(E.current.dismissOnTouchEnd&&N(e),D.clear(),E.current=null)}function te(e){L(e,ee)}let U=Ly(r&&Ly(Iy(i,`keydown`,P),Iy(i,`compositionstart`,a),Iy(i,`compositionend`,o)),g&&Ly(Iy(i,`click`,z,!0),Iy(i,`pointerdown`,z,!0),Iy(i,`pointerup`,B,!0),Iy(i,`pointercancel`,B,!0),Iy(i,`mousedown`,z,!0),Iy(i,`mouseup`,B,!0),Iy(i,`touchstart`,R,{capture:!0,passive:!0}),Iy(i,`touchmove`,H,{capture:!0,passive:!0}),Iy(i,`touchend`,te,{capture:!0,passive:!0})));return()=>{U(),t.clear(),c(),S.current=!1}},[d,u,r,g,h,l,n,v,y,P,A,_,j,M,p,e,D,k]);let R=G.useMemo(()=>({onKeyDown:P,onPointerDown:N,onClick:N}),[P,N]),z=G.useMemo(()=>({onKeyDown:P,onPointerDown:L,onMouseDown:L,onClickCapture:F,onMouseDownCapture(e){F(),I(e)},onPointerDownCapture(e){F(),I(e)},onMouseUpCapture:F,onTouchEndCapture:F,onTouchMoveCapture:F}),[P,F,I,L]);return G.useMemo(()=>n?{reference:R,floating:z,trigger:R}:{},[n,R,z])}function Mb(e,t,n,r){return{left:e,top:t,right:n,bottom:r,x:e,y:t,width:n-e,height:r-t}}function fUe(e){return{left:e.left,top:e.top,right:e.right,bottom:e.bottom,width:e.width,height:e.height}}function pUe(e){let t=[],n,r=1/0,i=1/0,a=-1/0,o=-1/0;for(let s of Array.from(e).sort((e,t)=>e.top-t.top)){if(r=Math.min(r,s.left),i=Math.min(i,s.top),a=Math.max(a,s.right),o=Math.max(o,s.bottom),!n||s.top-n.top>n.height/2)t.push(fUe(s));else{let e=t[t.length-1];e.left=Math.min(e.left,s.left),e.right=Math.max(e.right,s.right),e.bottom=Math.max(e.bottom,s.bottom),e.width=e.right-e.left,e.height=e.bottom-e.top}n=s}return{lines:t,fallback:Mb(r,i,a,o)}}function mUe(e,t,n){return e.findIndex(e=>t>e.left-2&&t<e.right+2&&n>e.top-2&&n<e.bottom+2)}function hUe(e){return Mb(e.left,e.top,e.right,e.bottom)}function gUe(e,t,n){let{lines:r}=pUe(e.getClientRects());if(r.length<2)return;let i=mUe(r,t,n);return{x:t,y:n,lineIndex:i===-1?void 0:i,element:e}}function _Ue(e,t,n){let{lines:r,fallback:i}=pUe(e.getClientRects());if(r.length<2)return null;let a=n?.x,o=n?.y,s=t[0];if(n?.lineIndex!=null&&r[n.lineIndex])return hUe(r[n.lineIndex]);if(a!=null&&o!=null){let e=mUe(r,a,o);if(e!==-1)return hUe(r[e])}if(r.length===2&&r[0].left>r[1].right&&a!=null&&o!=null)return i;if(s===`t`||s===`b`){let e=r[0],t=r[r.length-1],n=s===`t`?e:t;return Mb(n.left,e.top,n.right,t.bottom)}let c=s===`l`,l=r[0].left,u=r[0].right,d=c?1/0:-1/0,f=r[0],p=r[0];for(let e of r){l=Math.min(l,e.left),u=Math.max(u,e.right);let t=c?e.left:e.right;c&&t<d||!c&&t>d?(d=t,f=e,p=e):t===d&&(p=e)}return Mb(l,f.top,u,p.bottom)}function vUe(e){return`contextElement`in e&&e.contextElement?e.contextElement:oy(e)?e:void 0}function yUe(e,t){function n(t){bUe(e,t.currentTarget,t.clientX,t.clientY)}function r(e){t||n(e)}return{onFocus(){e.current=void 0},onMouseEnter:r,onMouseMove:r}}function bUe(e,t,n,r){let i=gUe(t,n,r);return e.current=i,i}function xUe(e){return{name:`inline`,async fn(t){let n=t.elements.reference;if(typeof n?.getClientRects!=`function`)return{};let r=vUe(n),i=e.current,a=i?.element===n||i?.element===r?i:void 0,o=_Ue(n,t.placement,a);if(!o||typeof t.platform.getElementRects!=`function`)return{};let s=await t.platform.getElementRects({reference:{contextElement:r,getBoundingClientRect(){return o}},floating:t.elements.floating,strategy:t.strategy});return t.rects.reference.x===s.reference.x&&t.rects.reference.y===s.reference.y&&t.rects.reference.width===s.reference.width&&t.rects.reference.height===s.reference.height?{}:{reset:{rects:s}}}}}function SUe(e){let{popupStore:t,treatPopupAsFloatingElement:n=!1,floatingRootContext:r,floatingId:i,nested:a,onOpenChange:o}=e,s=t.useState(`open`),c=t.useState(`activeTriggerElement`),l=t.useState(n?`popupElement`:`positionerElement`),u=o;return t.useSyncedValue(`floatingId`,i),Wv(()=>{let e={open:s,floatingId:i,referenceElement:c,floatingElement:l};oy(c)&&(e.domReferenceElement=c),r.state.positionReference===r.state.referenceElement&&(e.positionReference=c),r.update(e)},[s,i,c,l,r]),r.context.onOpenChange=u,r.context.nested=a,r}function Nb(e,t=!1,n=!1,r=!1){let[i,a]=G.useState(e&&t?`idle`:void 0),[o,s]=G.useState(e&&!r);return e&&!o&&(s(!0),a(`starting`)),!e&&o&&i!==`ending`&&!n&&a(`ending`),!e&&!o&&i===`ending`&&a(void 0),Wv(()=>{if(!e&&o&&i!==`ending`&&n){let e=Hy.request(()=>{a(`ending`)});return()=>{Hy.cancel(e)}}},[e,o,i,n]),Wv(()=>{if(!e||t||i===void 0)return;let n=Hy.request(()=>{a(void 0)});return()=>{Hy.cancel(n)}},[t,e,i]),Wv(()=>{if(!e||!t)return;e&&o&&i!==`idle`&&a(`starting`);let n=Hy.request(()=>{a(`idle`)});return()=>{Hy.cancel(n)}},[t,e,o,i]),{mounted:o,setMounted:s,transitionStatus:i}}function CUe(e,t){return e.getAnimations(t).filter(e=>{let t=e.effect?.getTiming();return t?.duration!==1/0&&t?.iterations!==1/0})}var Pb=null;function wUe(e){if(!Pb){let e=[];Pb=e,queueMicrotask(()=>{Pb=null,Pt.flushSync(()=>{for(let t of e)t()})})}Pb.push(e)}function Fb(e,t=!1,n=!1){let r=Uy();return zy((i,a=null)=>{r.cancel();let o=Db(e);if(o==null)return;let s=o,c=()=>{n?wUe(()=>{a?.aborted||i()}):Pt.flushSync(i)};if(typeof s.getAnimations!=`function`||globalThis.BASE_UI_ANIMATIONS_DISABLED){i();return}function l(){Promise.all(CUe(s).map(e=>e.finished.then(C))).then(()=>{a?.aborted||c()},()=>{a?.aborted||(CUe(s).some(e=>e.pending||e.playState!==`finished`)?l():c())})}if(t){let e=IBe;if(!s.hasAttribute(e)){r.request(l);return}let t=new MutationObserver(()=>{s.hasAttribute(e)||(t.disconnect(),l())});t.observe(s,{attributes:!0,attributeFilter:[e]}),a?.addEventListener(`abort`,()=>t.disconnect(),{once:!0})}else r.request(l)})}function Ib(e){let{enabled:t=!0,open:n,ref:r,batch:i=!1,onComplete:a}=e,o=zy(a),s=Fb(r,n,i);G.useEffect(()=>{if(!t)return;let e=new AbortController;return s(o,e.signal),()=>{e.abort()}},[t,n,o,s])}function TUe(e){let{open:t,ref:n,preventUnmountOnClose:r,setPreventUnmountOnClose:i,onUnmount:a,animateInitialOpen:o}=e,s=zy(i),{mounted:c,setMounted:l,transitionStatus:u}=Nb(t,!1,!1,o),d=!t&&r;Wv(()=>{t&&s(!1)},[t,s]);let f=G.useRef(c),p=G.useRef(!1),m=PHe(),h=()=>{f.current=!1,l(!1),a()};Wv(()=>{f.current=c,p.current&&(p.current=!1,!t&&c&&h())});let g=zy(()=>{f.current&&(t?(p.current=!0,m()):h())});return Ib({enabled:c&&!t&&!d,open:t,ref:n,onComplete(){t||g()}}),{mounted:c,transitionStatus:u,preventUnmountingOnClose:d,forceUnmount:g}}var Lb={tabIndex:-1,[ABe]:``};function EUe(e){return t=>t!==`touch`||e.current}function Rb(e,t=!1){let n=xb(),r=wb()!=null,i=s(()=>e(n,r)).current;return SUe({popupStore:i,treatPopupAsFloatingElement:t,floatingRootContext:i.state.floatingRootContext,floatingId:n,nested:r,onOpenChange:i.setOpen}),i}function zb({handle:e,store:t}){return Wv(()=>e.attachStore(t),[e,t]),null}function DUe(e){let t=e.context.triggerElements.size;e.select(`open`)&&e.state.triggerCount!==t&&e.set(`triggerCount`,t)}function OUe(e,t){let n=G.useRef(null);return zy(r=>{let i=n.current;if(i!==null){if(i.element===r&&i.store===t&&i.id===e)return;n.current=null;let a=i.store;a.context.triggerElements.getById(i.id)===i.element&&(a.context.triggerElements.delete(i.id),DUe(a))}r!==null&&e!==void 0&&(n.current={store:t,id:e,element:r},t.context.triggerElements.add(e,r),DUe(t))})}function Bb(e,t,n,r=!1){let i=e.preventUnmountingOnClose;t?i=!1:r&&(i=!0);let a=n?.id??null,o=e.activeTriggerId,s=e.activeTriggerElement;return(a||t)&&(o=a,s=n??null),{open:t,preventUnmountingOnClose:i,activeTriggerId:o,activeTriggerElement:s,openedWithoutTrigger:t?n==null:e.openedWithoutTrigger}}function Vb(e){let t=!1;return e.preventUnmountOnClose=()=>{t=!0},()=>t}function kUe(e,t,n,r={}){let i=n.reason,a=i===Ay,o=t&&i===`trigger-focus`,s=!t&&(i===`trigger-press`||i===`escape-key`),c=Vb(n);if(e.context.onOpenChange?.(t,n),n.isCanceled)return;r.onBeforeDispatch?.(),e.state.floatingRootContext.dispatchOpenChange(t,n);let l=()=>{let i=Bb(e.state,t,n.trigger,c()),l={...r.extraState,...i};o?l.instantType=`focus`:s?l.instantType=`dismiss`:a&&(l.instantType=void 0),e.update(l)};a?Pt.flushSync(l):l()}function Hb(e,t,n,r){let i=n.useState(`isMountedByTrigger`,e),a=OUe(e,n),o=zy(t=>{let i=n.select(`open`),a=n.select(`activeTriggerId`);if(a===e){let e={activeTriggerElement:t,...i?r:null};n.update(e)}else if(a==null&&i&&!n.state.openedWithoutTrigger){let i={activeTriggerId:e??null,activeTriggerElement:t,...r};n.update(i)}}),s=zy(e=>{a(e),e&&o(e)});return Wv(()=>(s(t.current),()=>s(null)),[s,t,n,e]),Wv(()=>{if(i){let e={activeTriggerElement:t.current,...r};n.update(e)}},[i,n,t,...Object.values(r)]),{registerTrigger:s,isMountedByThisTrigger:i}}function Ub(e,t={}){let{closeOnActiveTriggerUnmount:n=!1}=t,r=G.useRef(null),i=e.useState(`open`);Wv(()=>{if(!i){r.current=null,e.state.triggerCount!==0&&e.set(`triggerCount`,0),e.state.openedWithoutTrigger&&e.set(`openedWithoutTrigger`,!1);return}let t=e.context.triggerElements.size,a={};e.state.triggerCount!==t&&(a.triggerCount=t);let o=e.select(`activeTriggerId`),s=null;if(o){let t=e.context.triggerElements.getById(o);if(t)r.current=o,t!==e.state.activeTriggerElement&&(a.activeTriggerElement=t);else{for(let[t,n]of e.context.triggerElements.entries())if(n===e.state.activeTriggerElement){a.activeTriggerId=t,a.activeTriggerElement=n,r.current=t;break}a.activeTriggerId===void 0&&(r.current===o?s=o:r.current=null)}}else r.current=null;if(!s&&!o&&!e.state.openedWithoutTrigger&&t===1){let t=e.context.triggerElements.entries().next();if(!t.done){let[e,n]=t.value;a.activeTriggerId=e,a.activeTriggerElement=n,r.current=e}}(a.triggerCount!==void 0||a.activeTriggerId!==void 0||a.activeTriggerElement!==void 0)&&e.update(a),s&&n&&queueMicrotask(()=>{if(e.select(`open`)&&e.select(`activeTriggerId`)===s&&!e.context.triggerElements.getById(s)){let t=Ey(Oy);e.setOpen(!1,t),t.isCanceled||e.update({activeTriggerId:null,activeTriggerElement:null})}})},[i,e,e.useState(`triggerCount`),e.useState(`activeTriggerId`),e.useState(`activeTriggerElement`),n])}function Wb(e,t,n,r){let{mounted:i,transitionStatus:a,forceUnmount:o}=TUe({open:e,ref:t.context.popupRef,preventUnmountOnClose:t.useState(`preventUnmountingOnClose`),setPreventUnmountOnClose:e=>t.set(`preventUnmountingOnClose`,e),animateInitialOpen:r,onUnmount(){t.update({activeTriggerId:null,activeTriggerElement:null,mounted:!1,preventUnmountingOnClose:!1}),n?.(),t.context.onOpenChangeComplete?.(!1)}});return s(()=>(t.set(`mounted`,i),null)),t.useSyncedValues({mounted:i,transitionStatus:a}),{forceUnmount:o,transitionStatus:a}}function Gb(e,t){e.useSyncedValues(t),Wv(()=>()=>{e.update({activeTriggerProps:te,inactiveTriggerProps:te,popupProps:te})},[e])}function AUe(e,t){Wv(()=>{!t&&e.state.openMethod!==null&&e.set(`openMethod`,null)},[t,e]),Wv(()=>()=>{e.state.openMethod!==null&&e.set(`openMethod`,null)},[e])}var Kb=class{idMap=new Map;add(e,t){this.idMap.set(e,t)}delete(e){this.idMap.delete(e)}hasElement(e){for(let t of this.idMap.values())if(t===e)return!0;return!1}hasMatchingElement(e){for(let t of this.idMap.values())if(e(t))return!0;return!1}getById(e){return this.idMap.get(e)}entries(){return this.idMap.entries()}elements(){return this.idMap.values()}get size(){return this.idMap.size}},jUe=i((e=>{var t=b();function n(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var r=typeof Object.is==`function`?Object.is:n,i=t.useState,a=t.useEffect,o=t.useLayoutEffect,s=t.useDebugValue;function c(e,t){var n=t(),r=i({inst:{value:n,getSnapshot:t}}),c=r[0].inst,u=r[1];return o(function(){c.value=n,c.getSnapshot=t,l(c)&&u({inst:c})},[e,n,t]),a(function(){return l(c)&&u({inst:c}),e(function(){l(c)&&u({inst:c})})},[e]),s(n),n}function l(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!r(e,n)}catch{return!0}}function u(e,t){return t()}var d=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?u:c;e.useSyncExternalStore=t.useSyncExternalStore===void 0?d:t.useSyncExternalStore})),MUe=i(((e,t)=>{t.exports=jUe()})),NUe=i((e=>{var t=b(),n=MUe();function r(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var i=typeof Object.is==`function`?Object.is:r,a=n.useSyncExternalStore,o=t.useRef,s=t.useEffect,c=t.useMemo,l=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,u){var d=o(null);if(d.current===null){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=c(function(){function e(e){if(!a){if(a=!0,o=e,e=r(e),u!==void 0&&f.hasValue){var t=f.value;if(u(t,e))return s=t}return s=e}if(t=s,i(o,e))return t;var n=r(e);return u!==void 0&&u(t,n)?(o=e,t):(o=e,s=n)}var a=!1,o,s,c=n===void 0?null:n;return[function(){return e(t())},c===null?void 0:function(){return e(c())}]},[t,n,r,u]);var p=a(e,d[0],d[1]);return s(function(){f.hasValue=!0,f.value=p},[p]),l(p),p}})),PUe=i(((e,t)=>{t.exports=NUe()})),qb=MUe(),FUe=e(PUe(),1),IUe=ee(19)?zUe:BUe;function LUe(e,t,n,r,i){return IUe(e,t,n,r,i)}function RUe(e,t,n,r,i){let a=G.useCallback(()=>t(e.getSnapshot(),n,r,i),[e,t,n,r,i]);return(0,qb.useSyncExternalStore)(e.subscribe,a,a)}Qze({before(e){e.syncIndex=0,e.didInitialize||(e.syncTick=1,e.syncHooks=[],e.didChangeStore=!0,e.getSnapshot=()=>{let t=!1;for(let n=0;n<e.syncHooks.length;n+=1){let r=e.syncHooks[n],i=r.selector(r.store.state,r.a1,r.a2,r.a3);Object.is(r.value,i)||(t=!0,r.value=i)}return t&&(e.syncTick+=1),e.syncTick})},after(e){e.syncHooks.length>0&&(e.didChangeStore&&(e.didChangeStore=!1,e.subscribe=t=>{let n=new Set;for(let t of e.syncHooks)n.add(t.store);let r=[];for(let e of n)r.push(e.subscribe(t));return()=>{for(let e of r)e()}}),(0,qb.useSyncExternalStore)(e.subscribe,e.getSnapshot,e.getSnapshot))}});function zUe(e,t,n,r,i){let a=Zze();if(!a)return RUe(e,t,n,r,i);let o=a.syncIndex;a.syncIndex+=1;let s;return a.didInitialize?(s=a.syncHooks[o],s.store===e&&s.selector===t&&Object.is(s.a1,n)&&Object.is(s.a2,r)&&Object.is(s.a3,i)||(s.store!==e&&(a.didChangeStore=!0),s.store=e,s.selector=t,s.a1=n,s.a2=r,s.a3=i,s.value=t(e.getSnapshot(),n,r,i))):(s={store:e,selector:t,a1:n,a2:r,a3:i,value:t(e.getSnapshot(),n,r,i)},a.syncHooks.push(s)),s.value}function BUe(e,t,n,r,i){return(0,FUe.useSyncExternalStoreWithSelector)(e.subscribe,e.getSnapshot,e.getSnapshot,e=>t(e,n,r,i))}var VUe=class{static create(e){return new this(e)}constructor(e){this.state=e,this.listeners=new Set,this.updateTick=0}subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});getSnapshot=()=>this.state;setState(e){if(this.state===e)return;this.state=e,this.updateTick+=1;let t=this.updateTick;for(let n of this.listeners){if(t!==this.updateTick)return;n(e)}}update(e){for(let t in e)if(!Object.is(this.state[t],e[t])){this.setState({...this.state,...e});return}}set(e,t){Object.is(this.state[e],t)||this.setState({...this.state,[e]:t})}notifyAll(){let e={...this.state};this.setState(e)}use(e,t,n,r){return LUe(this,e,t,n,r)}},Jb=class extends VUe{constructor(e,t={},n){super(e),this.context=t,this.selectors=n}useSyncedValue(e,t){G.useDebugValue(e);let n=this;Wv(()=>{n.state[e]!==t&&n.set(e,t)},[n,e,t])}useSyncedValueWithCleanup(e,t){let n=this;Wv(()=>(n.state[e]!==t&&n.set(e,t),()=>{n.set(e,void 0)}),[n,e,t])}useSyncedValues(e){let t=this;Wv(()=>{t.update(e)},[t,...Object.values(e)])}useControlledProp(e,t){G.useDebugValue(e);let n=this,r=t!==void 0;Wv(()=>{r&&!Object.is(n.state[e],t)&&n.setState({...n.state,[e]:t})},[n,e,t,r])}select(e,t,n,r){let i=this.selectors[e];return i(this.state,t,n,r)}useState(e,t,n,r){return G.useDebugValue(e),LUe(this,this.selectors[e],t,n,r)}useContextCallback(e,t){G.useDebugValue(e);let n=zy(t??C);this.context[e]=n}useStateSetter(e){let t=G.useRef(void 0);return t.current===void 0&&(t.current=t=>{this.set(e,t)}),t.current}observe(e,t){let n;n=typeof e==`function`?e:this.selectors[e];let r=n(this.state);return t(r,r,this),this.subscribe(e=>{let i=n(e);if(!Object.is(r,i)){let e=r;r=i,t(i,e,this)}})}},HUe={open:e=>e.open,transitionStatus:e=>e.transitionStatus,domReferenceElement:e=>e.domReferenceElement,referenceElement:e=>e.positionReference??e.referenceElement,floatingElement:e=>e.floatingElement,floatingId:e=>e.floatingId},UUe=class extends Jb{constructor(e){let{syncOnly:t,nested:n,onOpenChange:r,triggerElements:i,...a}=e;super({...a,positionReference:a.referenceElement,domReferenceElement:a.referenceElement},{onOpenChange:r,dataRef:{current:{}},events:JHe(),nested:n,triggerElements:i},HUe),this.syncOnly=t}syncOpenEvent=(e,t)=>{(!e||!this.state.open||t!=null&&gBe(t))&&(this.context.dataRef.current.openEvent=e?t:void 0)};dispatchOpenChange=(e,t)=>{this.syncOpenEvent(e,t.event);let n={open:e,reason:t.reason,nativeEvent:t.event,nested:this.context.nested,triggerElement:t.trigger};this.context.events.emit(`openchange`,n)};setOpen=(e,t)=>{this.syncOnly||this.dispatchOpenChange(e,t),this.context.onOpenChange?.(e,t)}};function Yb(e,t,n=!1){return{open:!1,openProp:void 0,mounted:!1,transitionStatus:void 0,floatingRootContext:new UUe({open:!1,transitionStatus:void 0,floatingElement:null,referenceElement:null,triggerElements:e,floatingId:t,syncOnly:!0,nested:n,onOpenChange:void 0}),floatingId:t,triggerCount:0,preventUnmountingOnClose:!1,payload:void 0,activeTriggerId:null,activeTriggerElement:null,openedWithoutTrigger:!1,triggerIdProp:void 0,popupElement:null,positionerElement:null,activeTriggerProps:te,inactiveTriggerProps:te,popupProps:te}}var Xb=e=>e.triggerIdProp??e.activeTriggerId,Zb=e=>e.openProp??e.open,WUe=e=>(e.popupElement?.id??e.floatingId)||void 0;function GUe(e,t){return t!==void 0&&Zb(e)&&Xb(e)===t}function KUe(e,t){return GUe(e,t)?!0:t!==void 0&&Zb(e)&&Xb(e)==null&&!e.openedWithoutTrigger&&e.triggerCount===1}var Qb={open:Zb,mounted:e=>e.mounted,transitionStatus:e=>Zb(e)&&!e.mounted?`starting`:e.transitionStatus,floatingRootContext:e=>e.floatingRootContext,triggerCount:e=>e.triggerCount,preventUnmountingOnClose:e=>e.preventUnmountingOnClose,payload:e=>e.payload,activeTriggerId:Xb,activeTriggerElement:e=>e.mounted?e.activeTriggerElement:null,popupId:WUe,isTriggerActive:(e,t)=>t!==void 0&&Xb(e)===t,isOpenedByTrigger:(e,t)=>GUe(e,t),isMountedByTrigger:(e,t)=>t!==void 0&&Xb(e)===t&&e.mounted,triggerProps:(e,t)=>t?e.activeTriggerProps:e.inactiveTriggerProps,triggerPopupId:(e,t)=>KUe(e,t)?WUe(e):void 0,popupProps:e=>e.popupProps,popupElement:e=>e.popupElement,positionerElement:e=>e.positionerElement};function $b(e){let t=G.useCallback(t=>e===void 0?C:e.subscribeStore(t),[e]),n=G.useCallback(()=>e===void 0?void 0:e.store,[e]);return(0,qb.useSyncExternalStore)(t,n,()=>e?.serverStore)}function qUe(e){let{open:t=!1,onOpenChange:n,elements:r={}}=e,i=xb(),a=wb()!=null,o=s(()=>new UUe({open:t,transitionStatus:void 0,onOpenChange:n,referenceElement:r.reference??null,floatingElement:r.floating??null,triggerElements:new Kb,floatingId:i,syncOnly:!1,nested:a})).current;return Wv(()=>{let e={open:t,floatingId:i};r.reference!==void 0&&(e.referenceElement=r.reference,e.domReferenceElement=oy(r.reference)?r.reference:null),r.floating!==void 0&&(e.floatingElement=r.floating),o.update(e)},[t,i,r.reference,r.floating,o]),o.context.onOpenChange=n,o.context.nested=a,o}var JUe=lBe&&$v;function YUe(e,t={}){let{enabled:n=!0,delay:r}=t,{events:i,dataRef:a}=e.context,o=G.useRef(!1),s=G.useRef(null),c=G.useRef(!0),l=Yv();G.useEffect(()=>{let t=e.select(`domReferenceElement`);if(!n)return;let r=iy(t);function i(){let t=e.select(`domReferenceElement`);!e.select(`open`)&&sy(t)&&t===hy(Wy(t))&&(o.current=!0,s.current=t)}function a(){c.current=!0}function l(){c.current=!1}return Ly(Iy(r,`blur`,i),JUe&&Iy(r,`keydown`,a,!0),JUe&&Iy(r,`pointerdown`,l,!0))},[e,n]),G.useEffect(()=>{if(!n)return;function t(t){if(t.reason===`trigger-press`||t.reason===`escape-key`){let t=e.select(`domReferenceElement`);oy(t)&&(s.current=t,o.current=!0)}}return i.on(`openchange`,t),()=>{i.off(`openchange`,t)}},[i,n,e]);let u=G.useMemo(()=>{function t(){o.current=!1,s.current=null}return{onMouseLeave(){t()},onFocus(n){let i=n.currentTarget;if(o.current){if(s.current===i)return;t()}let a=vy(n.nativeEvent);if(oy(a)){if(JUe&&!n.relatedTarget){if(!c.current&&!wy(a))return}else if(!nVe(a))return}let u=ZBe(n.relatedTarget,e.context.triggerElements),{nativeEvent:d,currentTarget:f}=n;e.select(`open`)&&u||!r?e.setOpen(!0,Ey(cVe,d,f)):l.start(r,()=>{o.current||e.setOpen(!0,Ey(cVe,d,f))})},onBlur(n){t();let r=n.relatedTarget,i=n.nativeEvent,o=oy(r)&&r.hasAttribute(hb(`focus-guard`))&&r.getAttribute(`data-type`)===`outside`;l.start(0,()=>{let t=e.select(`domReferenceElement`),n=hy(Wy(t));!r&&n===t||gy(a.current.floatingContext?.refs.floating.current,n)||gy(t,n)||o||ZBe(r??n,e.context.triggerElements)||e.setOpen(!1,Ey(cVe,i))})}}},[a,r,e,l]);return G.useMemo(()=>n?{reference:u,trigger:u}:{},[n,u])}var XUe=class e{pointerType=void 0;interactedInside=!1;handler=void 0;blockMouseMove=!0;performedPointerEventsMutation=!1;pointerEventsScopeElement=null;pointerEventsReferenceElement=null;pointerEventsFloatingElement=null;restTimeoutPending=!1;openChangeTimeout=new Jv;restTimeout=new Jv;handleCloseOptions=void 0;static create(){return new e}dispose=()=>{this.openChangeTimeout.clear(),this.restTimeout.clear()};disposeEffect=()=>this.dispose},ex=new WeakMap;function tx(e){if(!e.performedPointerEventsMutation)return;let t=e.pointerEventsScopeElement;t&&ex.get(t)===e&&(e.pointerEventsScopeElement?.style.removeProperty(`pointer-events`),e.pointerEventsReferenceElement?.style.removeProperty(`pointer-events`),e.pointerEventsFloatingElement?.style.removeProperty(`pointer-events`),ex.delete(t)),e.performedPointerEventsMutation=!1,e.pointerEventsScopeElement=null,e.pointerEventsReferenceElement=null,e.pointerEventsFloatingElement=null}function ZUe(e,t){let{scopeElement:n,referenceElement:r,floatingElement:i}=t,a=ex.get(n);a&&a!==e&&tx(a),tx(e),e.performedPointerEventsMutation=!0,e.pointerEventsScopeElement=n,e.pointerEventsReferenceElement=r,e.pointerEventsFloatingElement=i,ex.set(n,e),n.style.pointerEvents=`none`,r.style.pointerEvents=`auto`,i.style.pointerEvents=`auto`}function QUe(e){let t=e.context.dataRef.current,n=s(()=>t.hoverInteractionState??XUe.create()).current;return t.hoverInteractionState||=n,nBe(t.hoverInteractionState.disposeEffect),t.hoverInteractionState}function nx(e,t={}){let{enabled:n=!0,closeDelay:r=0,nodeId:i}=t,a=e.useState(`open`),o=e.useState(`floatingElement`),s=e.useState(`domReferenceElement`),{dataRef:c}=e.context,l=Tb(),u=wb(),d=QUe(e),f=Yv(),p=zy(()=>oVe(c.current.openEvent?.type,d.interactedInside)),m=zy(()=>sVe(c.current.openEvent?.type)),h=zy(()=>{tx(d)});Wv(()=>{a||(d.pointerType=void 0,d.restTimeoutPending=!1,d.interactedInside=!1,h())},[a,d,h]),G.useEffect(()=>h,[h]),Wv(()=>{if(n&&a&&d.handleCloseOptions?.blockPointerEvents&&m()&&oy(s)&&o){let e=s,t=o,n=Wy(o),r=l?.nodesRef.current.find(e=>e.id===u)?.context?.elements.floating;r&&(r.style.pointerEvents=``);let i=d.pointerEventsScopeElement===t?null:d.pointerEventsScopeElement,a=r===t?null:r,c=d.handleCloseOptions?.getScope?.()??i??a??_y(e,`[data-rootownerid]`)??n.body;return ZUe(d,{scopeElement:c,referenceElement:e,floatingElement:t}),()=>{h()}}},[n,a,s,o,d,m,l,u,h]),G.useEffect(()=>{if(!n)return;function t(){return!!(l&&u&&mb(l.nodesRef.current,u).length>0)}function a(t){let n=Ty(r,`close`,d.pointerType),i=()=>{e.setOpen(!1,Ey(Ay,t)),l?.events.emit(`floating.closed`,t)};n?d.openChangeTimeout.start(n,i):(d.openChangeTimeout.clear(),i())}function s(e){let t=vy(e);eVe(t)?d.interactedInside=_y(t,`[aria-haspopup]`)!=null:d.interactedInside=!1}function g(){d.openChangeTimeout.clear(),f.clear(),l?.events.off(`floating.closed`,v),h()}function _(n){if(t()&&l){l.events.on(`floating.closed`,v);return}if(ZBe(n.relatedTarget,e.context.triggerElements))return;let r=c.current.floatingContext?.nodeId??i,o=n.relatedTarget;l&&r&&oy(o)&&mb(l.nodesRef.current,r,!1).some(e=>gy(e.context?.elements.floating,o))||(d.handler?d.handler(n):(h(),m()&&!p()&&a(n)))}function v(n){l&&u&&!t()&&f.start(0,()=>{l.events.off(`floating.closed`,v),e.setOpen(!1,Ey(Ay,n)),l.events.emit(`floating.closed`,n)})}let y=o;return Ly(y&&Iy(y,`mouseenter`,g),y&&Iy(y,`mouseleave`,_),y&&Iy(y,`pointerdown`,s,!0),()=>{l?.events.off(`floating.closed`,v)})},[n,o,e,c,r,i,m,p,h,d,l,u,f])}var $Ue={current:null};function rx(e,t={}){let{enabled:n=!0,delay:r=0,handleClose:i=null,mouseOnly:a=!1,restMs:o=0,move:s=!0,triggerElementRef:c=$Ue,externalTree:l,isActiveTrigger:u=!0,getHandleCloseContext:d,isClosing:f,shouldOpen:p,guardStaleOpen:m=!1}=t,{dataRef:h,events:g}=e.context,_=Tb(l),v=QUe(e),y=G.useRef(!1),b=Ry(i),x=Ry(r),S=Ry(o),C=Ry(n),w=Ry(p),T=Ry(f),E=zy(()=>oVe(h.current.openEvent?.type,v.interactedInside)),D=zy(()=>w.current?.()!==!1),O=zy((t,n,r)=>{let i=e.context.triggerElements;if(i.hasElement(n))return!t||!gy(t,n);if(!oy(r))return!1;let a=r;return i.hasMatchingElement(e=>gy(e,a))&&(!t||!gy(t,a))}),k=zy(()=>{v.handler&&=(Wy(e.select(`domReferenceElement`)).removeEventListener(`mousemove`,v.handler),void 0)}),A=zy(()=>{tx(v)});return u&&(v.handleCloseOptions=i?.__options),G.useEffect(()=>k,[k]),G.useEffect(()=>{if(!n)return;function e(e){e.open?y.current=!1:(y.current=e.reason===Ay,k(),v.openChangeTimeout.clear(),v.restTimeout.clear(),v.blockMouseMove=!0,v.restTimeoutPending=!1)}return g.on(`openchange`,e),()=>{g.off(`openchange`,e)}},[n,g,v,k]),G.useEffect(()=>{if(!n)return;function t(t,n=!0){let r=Ty(x.current,`close`,v.pointerType);r?v.openChangeTimeout.start(r,()=>{e.setOpen(!1,Ey(Ay,t)),_?.events.emit(`floating.closed`,t)}):n&&(v.openChangeTimeout.clear(),e.setOpen(!1,Ey(Ay,t)),_?.events.emit(`floating.closed`,t))}let r=c.current??(u?e.select(`domReferenceElement`):null);if(!oy(r))return;function i(t){if(v.openChangeTimeout.clear(),v.blockMouseMove=!1,a&&!ny(v.pointerType))return;let n=aVe(S.current),r=Ty(x.current,`open`,v.pointerType),i=vy(t),o=t.currentTarget??null,s=e.select(`domReferenceElement`),c=o;if(oy(i)&&!e.context.triggerElements.hasElement(i)){for(let t of e.context.triggerElements.elements())if(gy(t,i)){c=t;break}}oy(o)&&oy(s)&&!e.context.triggerElements.hasElement(o)&&gy(o,s)&&(c=s);let l=c!=null&&O(s,c,i),u=e.select(`open`),d=T.current?.()??e.select(`transitionStatus`)===`ending`,f=!u&&d&&y.current,p=!l&&oy(c)&&oy(s)&&gy(s,c)&&f,m=n>0&&!r,h=l&&(u||f)||p,g=!u||l;h?D()&&e.setOpen(!0,Ey(Ay,t,c)):m||(r?v.openChangeTimeout.start(r,()=>{g&&D()&&e.setOpen(!0,Ey(Ay,t,c))}):g&&D()&&e.setOpen(!0,Ey(Ay,t,c)))}function o(n){if(E()){A();return}k();let r=Wy(e.select(`domReferenceElement`));v.restTimeout.clear(),v.restTimeoutPending=!1;let i=h.current.floatingContext??d?.();if(!ZBe(n.relatedTarget,e.context.triggerElements)){if(b.current&&i){e.select(`open`)||v.openChangeTimeout.clear();let a=c.current;v.handler=b.current({...i,tree:_,x:n.clientX,y:n.clientY,onClose(){A(),k(),C.current&&!E()&&a===e.select(`domReferenceElement`)&&t(n,!0)}}),r.addEventListener(`mousemove`,v.handler),v.handler(n)}else v.pointerType===`touch`&&gy(e.select(`floatingElement`),n.relatedTarget)||t(n)}}function l(e){gy(r,e.relatedTarget)||(v.openChangeTimeout.clear(),v.restTimeout.clear(),v.restTimeoutPending=!1)}let f=m?Iy(r,`mouseout`,l):void 0;return s?Ly(Iy(r,`mousemove`,i,{once:!0}),Iy(r,`mouseenter`,i),Iy(r,`mouseleave`,o),f):Ly(Iy(r,`mouseenter`,i),Iy(r,`mouseleave`,o),f)},[k,A,h,x,e,n,b,v,u,O,E,a,s,S,c,_,C,d,T,D,m]),G.useMemo(()=>{if(!n)return;function t(e){v.pointerType=e.pointerType}return{onPointerDown:t,onPointerEnter:t,onMouseMove(t){let{nativeEvent:n}=t,r=t.currentTarget,i=e.select(`domReferenceElement`),o=e.select(`open`),s=O(i,r,t.target);if(a&&!ny(v.pointerType))return;if(o&&s&&v.handleCloseOptions?.blockPointerEvents){let t=e.select(`floatingElement`);if(t){let e=v.handleCloseOptions?.getScope?.()??r.ownerDocument.body;ZUe(v,{scopeElement:e,referenceElement:r,floatingElement:t})}}let c=aVe(S.current);if(o&&!s||c===0||!s&&v.restTimeoutPending&&t.movementX**2+t.movementY**2<2)return;v.restTimeout.clear();function l(){if(v.restTimeoutPending=!1,E())return;let t=e.select(`open`);!v.blockMouseMove&&(!t||s)&&D()&&e.setOpen(!0,Ey(Ay,n,r))}v.pointerType===`touch`?Pt.flushSync(()=>{l()}):s&&o?l():(v.restTimeoutPending=!0,v.restTimeout.start(c,l))}}},[n,v,E,O,a,e,S,D])}function eWe(e){return $v&&e.movementX===0&&e.movementY===0}function ix(e,t,n){switch(e){case`vertical`:return t;case`horizontal`:return n;default:return t||n}}function ax(e,t){return ix(t,e===`ArrowUp`||e===`ArrowDown`,e===`ArrowLeft`||e===`ArrowRight`)}function tWe(e,t,n){return ix(t,e===`ArrowDown`,n?e===`ArrowLeft`:e===`ArrowRight`)||e===`Enter`||e===` `||e===``}function nWe(e,t,n){return ix(t,n?e===MBe:e===NBe,e===FBe)}function rWe(e,t,n,r){return t===`both`||t===`horizontal`&&r?e===`Escape`:ix(t,n?e===NBe:e===MBe,e===PBe)}function iWe(e,t){let{listRef:n,activeIndex:r,onNavigate:i=()=>{},enabled:a=!0,selectedIndex:o=null,allowEscape:s=!1,loopFocus:c=!1,nested:l=!1,rtl:u=!1,virtual:d=!1,focusItemOnOpen:f=`auto`,focusItemOnHover:p=!0,openOnArrowKeyDown:m=!0,disabledIndices:h=void 0,orientation:g=`vertical`,triggerOrientation:_=g,parentOrientation:v,id:y,resetOnPointerLeave:b=!0,externalTree:x,nestedReturnFocusRef:S,grid:C}=t,w=C!=null,T=e.useState(`open`),E=e.useState(`floatingElement`),D=e.useState(`domReferenceElement`),O=e.context.dataRef,k=rVe(E),A=tVe(D),j=Ry(k),M=wb(),N=Tb(x),P=G.useRef(f),F=G.useRef(o??-1),I=G.useRef(null),L=G.useRef(!0),R=zy(e=>{i(F.current===-1?null:F.current,e)}),z=G.useRef(!!E),B=G.useRef(T),V=G.useRef(!1),H=G.useRef(!1),ee=G.useRef(null),te=Ry(h),U=Ry(T),W=Ry(o),ne=Ry(b),re=Uy(),ie=Uy(),ae=zy(()=>{re.cancel();function e(e){d||(ee.current=_b(e,{sync:V.current,preventScroll:!0}))}let t=n.current[F.current],r=H.current;t&&e(t),(V.current?e=>e():e=>re.request(e))(()=>{let i=n.current[F.current]||t;i&&(t||e(i),de&&(r||!L.current)&&i.scrollIntoView?.({block:`nearest`,inline:`nearest`}))})});Wv(()=>{O.current.orientation=g},[O,g]),Wv(()=>{T||(I.current=null),T&&f===`auto`||(P.current=f)},[T,f]),Wv(()=>{a&&(T&&E?(F.current=o??-1,P.current&&o!=null&&(H.current=!0,R())):z.current&&(F.current=-1,R()))},[a,T,E,o,R]),Wv(()=>{if(a){if(!T)V.current=!1;else if(E){if(r==null){if(V.current=!1,W.current!=null)return;if(z.current&&(F.current=-1,ae()),(!B.current||!z.current)&&P.current&&(I.current!=null||P.current===!0&&I.current==null)){let e=0,t=()=>{n.current[0]==null?(e<2&&(e?e=>ie.request(e):queueMicrotask)(t),e+=1):(F.current=I.current==null||tWe(I.current,_,u)||l?sb(n):tHe(n),I.current=null,R())};t()}}else ob(n.current,r)||(F.current=r,ae(),H.current=!1)}}},[a,T,E,r,W,l,n,_,u,R,ae,ie]),Wv(()=>{if(!a||E||!N||d||!z.current)return;let e=N.nodesRef.current,t=e.find(e=>e.id===M)?.context?.elements.floating,n=hy(Wy(D??t??null)),r=e.some(e=>e.context&&gy(e.context.elements.floating,n));t&&!r&&L.current&&t.focus({preventScroll:!0})},[a,E,D,N,M,d]),Wv(()=>{B.current=T,z.current=!!E});let oe=r!=null,se=zy(e=>{if(!U.current)return;let t=n.current.indexOf(e.currentTarget);t!==-1&&(F.current!==t||r!==t)&&(F.current=t,R(e))}),ce=zy(()=>v??N?.nodesRef.current.find(e=>e.id===M)?.context?.dataRef?.current.orientation),le=zy(()=>sb(n,te.current)),ue=zy(t=>{if(L.current=!1,V.current=!0,t.which===229||!U.current&&t.currentTarget===j.current)return;if(l&&rWe(t.key,g,u,w)){ax(t.key,ce())||ey(t),e.setOpen(!1,Ey(vVe,t.nativeEvent));let n=S?.current??D;sy(n)&&n.focus();return}r!=null&&r!==F.current&&!ob(n.current,r)&&(F.current=r);let i=F.current,a=sb(n,h),o=tHe(n,h);if(A||(t.key===`Home`&&(ey(t),F.current=a,R(t)),t.key===`End`&&(ey(t),F.current=o,R(t))),C!=null){let e=C(t,F.current,n,g,c,u,h,a,o);if(e!=null&&e!==F.current&&(F.current=e,R(t)),g===`both`)return}if(ax(t.key,g)){ey(t);let e=hy(t.currentTarget.ownerDocument);if(T&&!d&&gy(t.currentTarget,e)&&!n.current.some(t=>t!=null&&gy(t,e))){F.current=tWe(t.key,g,u)?a:o,R(t),r===F.current&&ae();return}let{index:l,wrapped:f}=nHe(n.current,i,{decrement:!tWe(t.key,g,u),loopFocus:c,allowEscape:s,disabledIndices:h,minIndex:a,maxIndex:o});f&&(V.current=!1),F.current=l,R(t)}}),de=G.useMemo(()=>({onFocus(e){V.current=!0,se(e)},onClick({currentTarget:e}){d||e.focus({preventScroll:!0})},onMouseMove(e){eWe(e)||(V.current=!0,H.current=!1,p&&se(e))},onPointerLeave(e){if(!U.current||!L.current||e.pointerType===`touch`)return;V.current=!0;let t=e.relatedTarget;if(p&&!n.current.includes(t)&&ne.current&&(ee.current?.(),ee.current=null,F.current=-1,R(e),!d)){let e=j.current,t=hy(Wy(e));e&&gy(e,t)&&e.focus({preventScroll:!0})}}}),[se,U,j,p,n,R,ne,d]),fe=G.useMemo(()=>d&&T&&oe&&{"aria-activedescendant":`${y}-${r}`},[d,T,oe,y,r]),pe=G.useMemo(()=>({...A?{}:fe,onKeyDown(t){if(t.key===`Tab`&&t.shiftKey&&T&&!d){let n=vy(t.nativeEvent);if(n&&!gy(j.current,n))return;ey(t);let r=Ey(hVe,t.nativeEvent);e.setOpen(!1,r);let i=S?.current??D;!r.isCanceled&&sy(i)&&i.focus()}else ue(t)},onPointerMove(e){eWe(e)||(L.current=!0)}}),[fe,ue,j,A,e,T,d,D,S]),me=G.useMemo(()=>{function t(t){e.setOpen(!0,Ey(vVe,t.nativeEvent,t.currentTarget))}function n(e){f===`auto`&&ty(e.nativeEvent)&&(P.current=!d)}function r(e){P.current=f,f===`auto`&&hBe(e.nativeEvent)&&(P.current=!0)}return{onKeyDown(n){let r=e.select(`open`);L.current=!1;let i=n.key.startsWith(`Arrow`),a=nWe(n.key,ce(),u),o=ax(n.key,r?g:_),s=(l?a:o)||n.key===`Enter`||n.key.trim()===``;if(d&&r&&(!l||wy(n.currentTarget)))return ue(n);if(r||m||!i){if(s){let e=ax(n.key,ce());I.current=l&&e?null:n.key}l?a&&(ey(n),r?(F.current=le(),R(n),d&&j.current?.focus()):t(n)):o&&(W.current!=null&&(F.current=W.current),ey(n),!r&&m?t(n):ue(n),r&&R(n))}},onFocus(t){t.target===t.currentTarget&&e.select(`open`)&&!d&&(F.current=-1,R(t))},onPointerDown:r,onPointerEnter:r,onMouseDown:n,onClick:n}},[ue,f,le,l,R,e,m,g,_,ce,u,W,d,j]),he=G.useMemo(()=>({...fe,...me}),[fe,me]);return G.useMemo(()=>a?{reference:he,floating:pe,item:de,trigger:me}:{},[a,he,pe,me,de])}function aWe(e,t){let{listRef:n,elementsRef:r,activeIndex:i,onMatch:a,disabledIndices:o,onTyping:s,enabled:c=!0,resetMs:l=750,selectedIndex:u=null}=t,d=zy(s),f=e.useState(`open`),p=Yv(),m=G.useRef(``),h=G.useRef(u??i??-1),g=G.useRef(null),_=zy(e=>{function t(e){return r?.current[e]}function s(e){let n=t(e);return n&&!ub(n)||n?.matches(`:disabled`)?!1:o==null||!lb(V,e,o)}function c(e,t,n=0){if(e.length===0)return-1;let r=(n%e.length+e.length)%e.length,i=t.toLowerCase();for(let t=0;t<e.length;t+=1){let n=(r+t)%e.length;if(e[n]?.toLowerCase().startsWith(i)&&s(n))return n}return-1}let _=n.current;if(m.current.length>0&&e.key===` `&&(ey(e),d?.(!0)),m.current.length>0&&m.current[0]!==` `&&c(_,m.current)===-1&&e.key!==` `&&d?.(!1),_==null||e.key.length!==1||e.ctrlKey||e.metaKey||e.altKey)return;f&&e.key!==` `&&(ey(e),d?.(!0));let v=m.current===``;v&&(h.current=u??i??-1),_.every((e,t)=>e&&s(t)?e[0]?.toLowerCase()!==e[1]?.toLowerCase():!0)&&m.current===e.key&&(m.current=``,h.current=g.current),m.current+=e.key,p.start(l,()=>{m.current=``,h.current=g.current,d?.(!1)});let y=((v?u??i??-1:h.current)??0)+1,b=c(_,m.current,y);b===-1?e.key!==` `&&(m.current=``,d?.(!1)):(a?.(b,e),g.current=b)}),v=zy(t=>{let n=t.relatedTarget,r=e.select(`domReferenceElement`),i=e.select(`floatingElement`);gy(r,n)||gy(i,n)||(p.clear(),m.current=``,h.current=g.current,d?.(!1))});Wv(()=>{(f||u===null)&&(p.clear(),g.current=null,m.current!==``&&(m.current=``,d?.(!1)))},[f,u,p,d]);let y=G.useMemo(()=>({onKeyDown:_,onBlur:v}),[_,v]);return G.useMemo(()=>c?{reference:y,floating:y}:{},[c,y])}var oWe=.1,sWe=oWe*oWe,ox=.5;function sx(e,t,n,r,i,a){return r>=t!=a>=t&&e<=(i-n)*(t-r)/(a-r)+n}function cx(e,t,n,r,i,a,o,s,c,l){let u=!1;return sx(e,t,n,r,i,a)&&(u=!u),sx(e,t,i,a,o,s)&&(u=!u),sx(e,t,o,s,c,l)&&(u=!u),sx(e,t,c,l,n,r)&&(u=!u),u}function cWe(e,t,n){return e>=n.x&&e<=n.x+n.width&&t>=n.y&&t<=n.y+n.height}function lx(e,t,n,r,i,a){return e>=Math.min(n,i)&&e<=Math.max(n,i)&&t>=Math.min(r,a)&&t<=Math.max(r,a)}function ux(e={}){let{blockPointerEvents:t=!1}=e,n=new Jv,r=({x:e,y:t,placement:r,elements:i,onClose:a,nodeId:o,tree:s})=>{let c=r?.split(`-`)[0],l=!1,u=null,d=null,f=typeof performance<`u`?performance.now():0;function p(e,t){let n=performance.now(),r=n-f;if(u===null||d===null||r===0)return u=e,d=t,f=n,!1;let i=e-u,a=t-d,o=i*i+a*a,s=r*r*sWe;return u=e,d=t,f=n,o<s}function m(){n.clear(),a()}return function(r){n.clear();let a=i.domReference,u=i.floating;if(!a||!u||c==null||e==null||t==null)return;let{clientX:d,clientY:f}=r,h=vy(r),g=r.type===`mouseleave`,_=gy(u,h),v=gy(a,h);if(_&&(l=!0,!g))return;if(v&&(l=!1,!g)){l=!0;return}if(g&&oy(r.relatedTarget)&&gy(u,r.relatedTarget))return;function y(){return!!(s&&mb(s.nodesRef.current,o).length>0)}function b(){y()||m()}if(y())return;let x=a.getBoundingClientRect(),S=u.getBoundingClientRect(),C=e>S.right-S.width/2,w=t>S.bottom-S.height/2,T=S.width>x.width,E=S.height>x.height,D=(T?x:S).left,O=(T?x:S).right,k=(E?x:S).top,A=(E?x:S).bottom;if(c===`top`&&t>=x.bottom-1||c===`bottom`&&t<=x.top+1||c===`left`&&e>=x.right-1||c===`right`&&e<=x.left+1){b();return}let j=!1;switch(c){case`top`:j=lx(d,f,D,x.top+1,O,S.bottom-1);break;case`bottom`:j=lx(d,f,D,S.top+1,O,x.bottom-1);break;case`left`:j=lx(d,f,S.right-1,A,x.left+1,k);break;case`right`:j=lx(d,f,x.right-1,A,S.left+1,k)}if(j)return;if(l&&!cWe(d,f,x)||!g&&p(d,f)){b();return}let M=!1;switch(c){case`top`:{let n=T?ox/2:ox*4,r=T||C?e+n:e-n,i=T?e-n:C?e+n:e-n,a=t+ox+1,o=C||T?S.bottom-ox:S.top,s=C?T?S.bottom-ox:S.top:S.bottom-ox;M=cx(d,f,r,a,i,a,S.left,o,S.right,s);break}case`bottom`:{let n=T?ox/2:ox*4,r=T||C?e+n:e-n,i=T?e-n:C?e+n:e-n,a=t-ox,o=C||T?S.top+ox:S.bottom,s=C?T?S.top+ox:S.bottom:S.top+ox;M=cx(d,f,r,a,i,a,S.left,o,S.right,s);break}case`left`:{let n=E?ox/2:ox*4,r=E||w?t+n:t-n,i=E?t-n:w?t+n:t-n,a=e+ox+1,o=w||E?S.right-ox:S.left,s=w?E?S.right-ox:S.left:S.right-ox;M=cx(d,f,o,S.top,s,S.bottom,a,r,a,i);break}case`right`:{let n=E?ox/2:ox*4,r=E||w?t+n:t-n,i=E?t-n:w?t+n:t-n,a=e-ox,o=w||E?S.left+ox:S.right,s=w?E?S.left+ox:S.right:S.left+ox;M=cx(d,f,a,r,a,i,o,S.top,s,S.bottom);break}}M?l||n.start(40,b):b()}};return r.__options={...e,blockPointerEvents:t},r}function lWe(e,t,n){let{reference:r,floating:i}=e,a=nb(t),o=UVe(t),s=HVe(o),c=eb(t),l=a===`y`,u=r.x+r.width/2-i.width/2,d=r.y+r.height/2-i.height/2,f=r[s]/2-i[s]/2,p;switch(c){case`top`:p={x:u,y:r.y-i.height};break;case`bottom`:p={x:u,y:r.y+r.height};break;case`right`:p={x:r.x+r.width,y:d};break;case`left`:p={x:r.x-i.width,y:d};break;default:p={x:r.x,y:r.y}}let m=tb(t);return m&&(p[o]+=f*(m===`end`?1:-1)*(n&&l?-1:1)),p}async function uWe(e,t){t===void 0&&(t={});let{x:n,y:r,platform:i,rects:a,elements:o,strategy:s}=e,{boundary:c=`clippingAncestors`,rootBoundary:l=`viewport`,elementContext:u=`floating`,altBoundary:d=!1,padding:f=0}=$y(t,e),p=eHe(f),m=o[d?u===`floating`?`reference`:`floating`:u],h=ib(await i.getClippingRect({element:await(i.isElement==null?void 0:i.isElement(m))??!0?m:m.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(o.floating)),boundary:c,rootBoundary:l,strategy:s})),g=u===`floating`?{x:n,y:r,width:a.floating.width,height:a.floating.height}:a.reference,_=await(i.getOffsetParent==null?void 0:i.getOffsetParent(o.floating)),v=await(i.isElement==null?void 0:i.isElement(_))&&await(i.getScale==null?void 0:i.getScale(_))||{x:1,y:1},y=ib(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:o,rect:g,offsetParent:_,strategy:s}):g);return{top:(h.top-y.top+p.top)/v.y,bottom:(y.bottom-h.bottom+p.bottom)/v.y,left:(h.left-y.left+p.left)/v.x,right:(y.right-h.right+p.right)/v.x}}var dWe=50,fWe=async(e,t,n)=>{let{placement:r=`bottom`,strategy:i=`absolute`,middleware:a=[],platform:o}=n,s=o.detectOverflow?o:{...o,detectOverflow:uWe},c=await(o.isRTL==null?void 0:o.isRTL(t)),l=await o.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:d}=lWe(l,r,c),f=r,p=0,m={};for(let n=0;n<a.length;n++){let h=a[n];if(!h)continue;let{name:g,fn:_}=h,{x:v,y,data:b,reset:x}=await _({x:u,y:d,initialPlacement:r,placement:f,strategy:i,middlewareData:m,rects:l,platform:s,elements:{reference:e,floating:t}});u=v??u,d=y??d,m[g]={...m[g],...b},x&&p<dWe&&(p++,typeof x==`object`&&(x.placement&&(f=x.placement),x.rects&&(l=x.rects===!0?await o.getElementRects({reference:e,floating:t,strategy:i}):x.rects),{x:u,y:d}=lWe(l,f,c)),n=-1)}return{x:u,y:d,placement:f,strategy:i,middlewareData:m}},pWe=function(e){return e===void 0&&(e={}),{name:`flip`,options:e,async fn(t){var n;let{placement:r,middlewareData:i,rects:a,initialPlacement:o,platform:s,elements:c}=t,{mainAxis:l=!0,crossAxis:u=!0,fallbackPlacements:d,fallbackStrategy:f=`bestFit`,fallbackAxisSideDirection:p=`none`,flipAlignment:m=!0,...h}=$y(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};let g=eb(r),_=nb(o),v=eb(o)===o,y=await(s.isRTL==null?void 0:s.isRTL(c.floating)),b=d||(v||!m?[rb(o)]:GVe(o)),x=p!==`none`;!d&&x&&b.push(...QVe(o,m,p,y));let S=[o,...b],C=await s.detectOverflow(t,h),w=[],T=i.flip?.overflows||[];if(l&&w.push(C[g]),u){let e=WVe(r,a,y);w.push(C[e[0]],C[e[1]])}if(T=[...T,{placement:r,overflows:w}],!w.every(e=>e<=0)){let e=(i.flip?.index||0)+1,t=S[e];if(t&&(u!==`alignment`||_===nb(t)||T.every(e=>nb(e.placement)!==_||e.overflows[0]>0)))return{data:{index:e,overflows:T},reset:{placement:t}};let n=T.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0]?.placement;if(!n)switch(f){case`bestFit`:{let e=T.filter(e=>{if(x){let t=nb(e.placement);return t===_||t===`y`}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0]?.[0];e&&(n=e);break}case`initialPlacement`:n=o}if(r!==n)return{reset:{placement:n}}}return{}}}},mWe=new Set([`left`,`top`]);async function hWe(e,t){let{placement:n,platform:r,elements:i}=e,a=await(r.isRTL==null?void 0:r.isRTL(i.floating)),o=eb(n),s=tb(n),c=nb(n)===`y`,l=mWe.has(o)?-1:1,u=a&&c?-1:1,d=$y(t,e),{mainAxis:f,crossAxis:p,alignmentAxis:m}=typeof d==`number`?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return s&&typeof m==`number`&&(p=s===`end`?m*-1:m),c?{x:p*u,y:f*l}:{x:f*l,y:p*u}}var gWe=function(e){return e===void 0&&(e=0),{name:`offset`,options:e,async fn(t){var n;let{x:r,y:i,placement:a,middlewareData:o}=t,s=await hWe(t,e);return a===o.offset?.placement&&(n=o.arrow)!=null&&n.alignmentOffset?{}:{x:r+s.x,y:i+s.y,data:{...s,placement:a}}}}},_We=function(e){return e===void 0&&(e={}),{name:`shift`,options:e,async fn(t){let{x:n,y:r,placement:i,platform:a}=t,{mainAxis:o=!0,crossAxis:s=!1,limiter:c={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...l}=$y(e,t),u={x:n,y:r},d=await a.detectOverflow(t,l),f=nb(i),p=VVe(f),m=u[p],h=u[f],g=(e,t)=>BVe(t+d[e===`y`?`top`:`left`],t,t-d[e===`y`?`bottom`:`right`]);o&&(m=g(p,m)),s&&(h=g(f,h));let _=c.fn({...t,[p]:m,[f]:h});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[p]:o,[f]:s}}}}}},vWe=function(e){return e===void 0&&(e={}),{options:e,fn(t){let{x:n,y:r,placement:i,rects:a,middlewareData:o}=t,{offset:s=0,mainAxis:c=!0,crossAxis:l=!0}=$y(e,t),u={x:n,y:r},d=nb(i),f=VVe(d),p=u[f],m=u[d],h=$y(s,t),g=typeof h==`number`?{mainAxis:h,crossAxis:0}:{mainAxis:h.mainAxis??0,crossAxis:h.crossAxis??0};if(c){let e=f===`y`?`height`:`width`,t=a.reference[f]-a.floating[e]+g.mainAxis,n=a.reference[f]+a.reference[e]-g.mainAxis;p<t?p=t:p>n&&(p=n)}if(l){let e=f===`y`?`width`:`height`,t=mWe.has(eb(i)),n=a.reference[d]-a.floating[e]+(t&&o.offset?.[d]||0)+(t?0:g.crossAxis),r=a.reference[d]+a.reference[e]+(t?0:o.offset?.[d]||0)-(t?g.crossAxis:0);m<n?m=n:m>r&&(m=r)}return{[f]:p,[d]:m}}}},yWe=function(e){return e===void 0&&(e={}),{name:`size`,options:e,async fn(t){let{placement:n,rects:r,platform:i,elements:a}=t,{apply:o=()=>{},...s}=$y(e,t),c=await i.detectOverflow(t,s),l=eb(n),u=tb(n),d=nb(n)===`y`,{width:f,height:p}=r.floating,m,h;l===`top`||l===`bottom`?(m=l,h=u===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?`start`:`end`)?`left`:`right`):(h=l,m=u===`end`?`top`:`bottom`);let g=p-c.top-c.bottom,_=f-c.left-c.right,v=Jy(p-c[m],g),y=Jy(f-c[h],_),b=t.middlewareData.shift,x=!b,S=v,C=y;b!=null&&b.enabled.x&&(C=_),b!=null&&b.enabled.y&&(S=g),x&&!u&&(d?C=f-2*Yy(c.left,c.right):S=p-2*Yy(c.top,c.bottom)),await o({...t,availableWidth:C,availableHeight:S});let w=await i.getDimensions(a.floating);return f!==w.width||p!==w.height?{reset:{rects:!0}}:{}}}};function bWe(e){let t=fy(e),n=parseFloat(t.width)||0,r=parseFloat(t.height)||0,i=sy(e),a=i?e.offsetWidth:n,o=i?e.offsetHeight:r,s=Xy(n)!==a||Xy(r)!==o;return s&&(n=a,r=o),{width:n,height:r,$:s}}function xWe(e){return oy(e)?e:e.contextElement}function dx(e){let t=xWe(e);if(!sy(t))return Qy(1);let n=t.getBoundingClientRect(),{width:r,height:i,$:a}=bWe(t),o=(a?Xy(n.width):n.width)/r,s=(a?Xy(n.height):n.height)/i;return o&&Number.isFinite(o)||(o=1),s&&Number.isFinite(s)||(s=1),{x:o,y:s}}var SWe=Qy(0);function CWe(e){let t=iy(e);return!EBe()||!t.visualViewport?SWe:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function wWe(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===iy(e)}function fx(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);let i=e.getBoundingClientRect(),a=xWe(e),o=Qy(1);t&&(r?oy(r)&&(o=dx(r)):o=dx(e));let s=wWe(a,n,r)?CWe(a):Qy(0),c=(i.left+s.x)/o.x,l=(i.top+s.y)/o.y,u=i.width/o.x,d=i.height/o.y;if(a&&r){let e=iy(a),t=oy(r)?iy(r):r,n=e,i=kBe(n);for(;i&&t!==n;){let e=dx(i),t=i.getBoundingClientRect(),r=fy(i),a=t.left+(i.clientLeft+parseFloat(r.paddingLeft))*e.x,o=t.top+(i.clientTop+parseFloat(r.paddingTop))*e.y;c*=e.x,l*=e.y,u*=e.x,d*=e.y,c+=a,l+=o,n=iy(i),i=kBe(n)}}return ib({width:u,height:d,x:c,y:l})}function px(e,t){let n=DBe(e).scrollLeft;return t?t.left+n:fx(ay(e)).left+n}function TWe(e,t){let n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-px(e,n),y:n.top+t.scrollTop}}function EWe(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e,a=i===`fixed`,o=ay(r),s=t?bBe(t.floating):!1;if(r===o||s&&a)return n;let c={scrollLeft:0,scrollTop:0},l=Qy(1),u=Qy(0),d=sy(r);if((d||!a)&&((ry(r)!==`body`||ly(o))&&(c=DBe(r)),d)){let e=fx(r);l=dx(r),u.x=e.x+r.clientLeft,u.y=e.y+r.clientTop}let f=o&&!d&&!a?TWe(o,c):Qy(0);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+u.x+f.x,y:n.y*l.y-c.scrollTop*l.y+u.y+f.y}}function DWe(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function OWe(e){let t=DBe(e),n=e.ownerDocument.body,r=Yy(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=Yy(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight),a=-t.scrollLeft+px(e),o=-t.scrollTop;return fy(n).direction===`rtl`&&(a+=Yy(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:a,y:o}}var kWe=25;function AWe(e,t,n){n===void 0&&(n=`viewport`);let r=n===`layoutViewport`,i=iy(e),a=ay(e),o=i.visualViewport,s=a.clientWidth,c=a.clientHeight,l=0,u=0;if(o){let e=!EBe()||t===`fixed`;r?e||(l=-o.offsetLeft,u=-o.offsetTop):(s=o.width,c=o.height,e&&(l=o.offsetLeft,u=o.offsetTop))}if(px(a)<=0){let e=a.ownerDocument,t=e.body,n=getComputedStyle(t),r=e.compatMode===`CSS1Compat`&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(a.clientWidth-t.clientWidth-r),o=getComputedStyle(a).scrollbarGutter===`stable both-edges`?i/2:i;o<=kWe&&(s-=o)}return{width:s,height:c,x:l,y:u}}function jWe(e,t){let n=fx(e,!0,t===`fixed`),r=n.top+e.clientTop,i=n.left+e.clientLeft,a=dx(e);return{width:e.clientWidth*a.x,height:e.clientHeight*a.y,x:i*a.x,y:r*a.y}}function MWe(e,t,n){let r;if(t===`viewport`||t===`layoutViewport`)r=AWe(e,n,t);else if(t===`document`)r=OWe(ay(e));else if(oy(t))r=jWe(t,n);else{let n=CWe(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return ib(r)}function NWe(e,t){let n=t.get(e);if(n)return n;let r=my(e,[],!1).filter(e=>oy(e)&&ry(e)!==`body`),i=null,a=fy(e).position===`fixed`,o=a?py(e):e;for(;oy(o)&&!dy(o);){let e=fy(o),t=wBe(o),n=i?i.position:a?`fixed`:``;!t&&(n===`fixed`||n===`absolute`&&e.position===`static`)?r=r.filter(e=>e!==o):i=e,o=py(o)}return t.set(e,r),r}function PWe(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e,a=[...n===`clippingAncestors`?bBe(t)?[]:NWe(t,this._c):[].concat(n),r],o=MWe(t,a[0],i),s=o.top,c=o.right,l=o.bottom,u=o.left;for(let e=1;e<a.length;e++){let n=MWe(t,a[e],i);s=Yy(n.top,s),c=Jy(n.right,c),l=Jy(n.bottom,l),u=Yy(n.left,u)}return{width:c-u,height:l-s,x:u,y:s}}function FWe(e){let{width:t,height:n}=bWe(e);return{width:t,height:n}}function IWe(e,t,n){let r=sy(t),i=ay(t),a=n===`fixed`,o=fx(e,!0,a,t),s={scrollLeft:0,scrollTop:0},c=Qy(0);if((r||!a)&&((ry(t)!==`body`||ly(i))&&(s=DBe(t)),r)){let e=fx(t,!0,a,t);c.x=e.x+t.clientLeft,c.y=e.y+t.clientTop}!r&&i&&(c.x=px(i));let l=i&&!r&&!a?TWe(i,s):Qy(0);return{x:o.left+s.scrollLeft-c.x-l.x,y:o.top+s.scrollTop-c.y-l.y,width:o.width,height:o.height}}function LWe(e){return fy(e).position===`static`}function RWe(e,t){if(!sy(e)||fy(e).position===`fixed`)return null;if(t)return t(e);let n=e.offsetParent;return ay(e)===n&&(n=n.ownerDocument.body),n}function zWe(e,t){let n=iy(e);if(bBe(e))return n;if(!sy(e)){let t=py(e);for(;t&&!dy(t);){if(oy(t)&&!LWe(t))return t;t=py(t)}return n}let r=RWe(e,t);for(;r&&yBe(r)&&LWe(r);)r=RWe(r,t);return r&&dy(r)&&LWe(r)&&!wBe(r)?n:r||TBe(e)||n}var BWe=async function(e){let t=this.getOffsetParent||zWe,n=this.getDimensions,r=await n(e.floating);return{reference:IWe(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function VWe(e){return fy(e).direction===`rtl`}var HWe={convertOffsetParentRelativeRectToViewportRelativeRect:EWe,getDocumentElement:ay,getClippingRect:PWe,getOffsetParent:zWe,getElementRects:BWe,getClientRects:DWe,getDimensions:FWe,getScale:dx,isElement:oy,isRTL:VWe};function UWe(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function WWe(e,t,n){let r=null,i,a=ay(e);function o(){var e;clearTimeout(i),(e=r)==null||e.disconnect(),r=null}function s(n,c){n===void 0&&(n=!1),c===void 0&&(c=1),o();let l=e.getBoundingClientRect(),{left:u,top:d,width:f,height:p}=l;if(n||t(),!f||!p)return;let m=Zy(d),h=Zy(a.clientWidth-(u+f)),g=Zy(a.clientHeight-(d+p)),_=Zy(u),v={rootMargin:-m+`px `+-h+`px `+-g+`px `+-_+`px`,threshold:Yy(0,Jy(1,c))||1},y=!0;function b(t){let n=t[0].intersectionRatio;if(!UWe(l,e.getBoundingClientRect()))return s();if(n!==c){if(!y)return s();n?s(!1,n):i=setTimeout(()=>{s(!1,1e-7)},1e3)}y=!1}try{r=new IntersectionObserver(b,{...v,root:a.ownerDocument})}catch{r=new IntersectionObserver(b,v)}r.observe(e)}let c=iy(e),l=()=>s(n);return c.addEventListener(`resize`,l),s(!0),()=>{c.removeEventListener(`resize`,l),o()}}function GWe(e,t,n,r){r===void 0&&(r={});let{ancestorScroll:i=!0,ancestorResize:a=!0,elementResize:o=typeof ResizeObserver==`function`,layoutShift:s=typeof IntersectionObserver==`function`,animationFrame:c=!1}=r,l=xWe(e),u=i||a?[...l?my(l):[],...t?my(t):[]]:[];u.forEach(e=>{i&&e.addEventListener(`scroll`,n),a&&e.addEventListener(`resize`,n)});let d=l&&s?WWe(l,n,a):null,f=-1,p=null;o&&(p=new ResizeObserver(e=>{let[r]=e;r&&r.target===l&&p&&t&&(p.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var e;(e=p)==null||e.observe(t)})),n()}),l&&!c&&p.observe(l),t&&p.observe(t));let m,h=c?fx(e):null;c&&g();function g(){let t=fx(e);h&&!UWe(h,t)&&n(),h=t,m=requestAnimationFrame(g)}return n(),()=>{var e;u.forEach(e=>{i&&e.removeEventListener(`scroll`,n),a&&e.removeEventListener(`resize`,n)}),d?.(),(e=p)==null||e.disconnect(),p=null,c&&cancelAnimationFrame(m)}}var KWe=gWe,qWe=_We,JWe=pWe,YWe=yWe,XWe=vWe,ZWe=(e,t,n)=>{let r=new Map,i=n??{},a={...HWe,...i.platform,_c:r};return fWe(e,t,{...i,platform:a})},mx=typeof document<`u`?G.useLayoutEffect:function(){};function hx(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,r,i;if(e&&t&&typeof e==`object`){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!hx(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){let n=i[r];if(!(n===`_owner`&&e.$$typeof)&&!hx(e[n],t[n]))return!1}return!0}return e!==e&&t!==t}function QWe(e){return typeof window>`u`?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function $We(e,t){let n=QWe(e);return Math.round(t*n)/n}function eGe(e){let t=G.useRef(e);return mx(()=>{t.current=e}),t}function tGe(e){e===void 0&&(e={});let{placement:t=`bottom`,strategy:n=`absolute`,middleware:r=[],platform:i,elements:{reference:a,floating:o}={},transform:s=!0,whileElementsMounted:c,open:l}=e,[u,d]=G.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,p]=G.useState(r);hx(f,r)||p(r);let[m,h]=G.useState(null),[g,_]=G.useState(null),v=G.useCallback(e=>{e!==S.current&&(S.current=e,h(e))},[]),y=G.useCallback(e=>{e!==C.current&&(C.current=e,_(e))},[]),b=a||m,x=o||g,S=G.useRef(null),C=G.useRef(null),w=G.useRef(u),T=c!=null,E=eGe(c),D=eGe(i),O=eGe(l),k=G.useCallback(()=>{if(!S.current||!C.current)return;let e={placement:t,strategy:n,middleware:f};D.current&&(e.platform=D.current),ZWe(S.current,C.current,e).then(e=>{let t={...e,isPositioned:O.current!==!1};A.current&&!hx(w.current,t)&&(w.current=t,Pt.flushSync(()=>{d(t)}))})},[f,t,n,D,O]);mx(()=>{l===!1&&w.current.isPositioned&&(w.current.isPositioned=!1,d(e=>({...e,isPositioned:!1})))},[l]);let A=G.useRef(!1);mx(()=>(A.current=!0,()=>{A.current=!1}),[]),mx(()=>{if(b&&(S.current=b),x&&(C.current=x),b&&x){if(E.current)return E.current(b,x,k);k()}},[b,x,k,E,T]);let j=G.useMemo(()=>({reference:S,floating:C,setReference:v,setFloating:y}),[v,y]),M=G.useMemo(()=>({reference:b,floating:x}),[b,x]),N=G.useMemo(()=>{let e={position:n,left:0,top:0};if(!M.floating)return e;let t=$We(M.floating,u.x),r=$We(M.floating,u.y);return s?{...e,transform:`translate(`+t+`px, `+r+`px)`,...QWe(M.floating)>=1.5&&{willChange:`transform`}}:{position:n,left:t,top:r}},[n,s,M.floating,u.x,u.y]);return G.useMemo(()=>({...u,update:k,refs:j,elements:M,floatingStyles:N}),[u,k,j,M,N])}var nGe=(e,t)=>{let n=KWe(e);return{name:n.name,fn:n.fn,options:[e,t]}},rGe=(e,t)=>{let n=qWe(e);return{name:n.name,fn:n.fn,options:[e,t]}},iGe=(e,t)=>({fn:XWe(e).fn,options:[e,t]}),aGe=(e,t)=>{let n=JWe(e);return{name:n.name,fn:n.fn,options:[e,t]}},oGe=(e,t)=>{let n=YWe(e);return{name:n.name,fn:n.fn,options:[e,t]}},sGe={...Qb,disabled:e=>e.disabled,instantType:e=>e.instantType,isInstantPhase:e=>e.isInstantPhase,trackCursorAxis:e=>e.trackCursorAxis,disableHoverablePopup:e=>e.disableHoverablePopup,lastOpenChangeReason:e=>e.openChangeReason,closeOnClick:e=>e.closeOnClick,appliedTriggerProps:(e,t)=>t?e.activeTriggerProps:void 0,closeDelay:e=>e.closeDelay,adaptiveOrigin:e=>e.adaptiveOrigin},cGe=class extends Jb{constructor(e,t,n){let r=new Kb;super(lGe(e,r,t,n),uGe(r),sGe)}setOpen=(e,t)=>{kUe(this,e,t,{extraState:{openChangeReason:t.reason}})};cancelPendingOpen(e){this.state.floatingRootContext.dispatchOpenChange(!1,Ey(ky,e))}};function lGe(e,t,n,r=!1){return{...Yb(t,n,r),disabled:!1,instantType:void 0,isInstantPhase:!1,trackCursorAxis:`none`,disableHoverablePopup:!1,openChangeReason:null,closeOnClick:!0,closeDelay:0,adaptiveOrigin:void 0,...e}}function uGe(e){return{popupRef:G.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerElements:e}}var dGe=Hv(function(e){let{disabled:t=!1,defaultOpen:n=!1,open:r,disableHoverablePopup:i=!1,trackCursorAxis:a=`none`,actionsRef:o,onOpenChange:s,onOpenChangeComplete:c,handle:l,triggerId:u,defaultTriggerId:d=null,children:f}=e,p=Rb((e,t)=>new cGe({open:n,openProp:r,activeTriggerId:d,triggerIdProp:u},e,t));p.useControlledProp(`openProp`,r),p.useControlledProp(`triggerIdProp`,u),p.useContextCallback(`onOpenChange`,s),p.useContextCallback(`onOpenChangeComplete`,c);let m=p.useState(`open`),h=!t&&m,g=p.useState(`activeTriggerId`),_=p.useState(`mounted`),v=p.useState(`payload`);p.useSyncedValues({trackCursorAxis:a,disableHoverablePopup:i,disabled:t}),Ub(p,{closeOnActiveTriggerUnmount:!0});let{forceUnmount:y,transitionStatus:b}=Wb(h,p),x=p.useState(`isInstantPhase`),S=p.useState(`instantType`),C=p.useState(`lastOpenChangeReason`),w=G.useRef(null);Wv(()=>{m&&t&&p.setOpen(!1,Ey(wVe))},[m,t,p]),Wv(()=>{b===`ending`&&C===`none`||b!==`ending`&&x?(S!==`delay`&&(w.current=S),p.set(`instantType`,`delay`)):w.current!==null&&(p.set(`instantType`,w.current),w.current=null)},[b,x,C,S,p]),Wv(()=>{h&&(g??p.set(`payload`,void 0))},[p,g,h]),G.useImperativeHandle(o,()=>({unmount:y,close:()=>p.setOpen(!1,Ey(Py))}),[y,p]);let T=h||_||!t&&a!==`none`;return(0,K.jsxs)(tBe.Provider,{value:p,children:[l&&(0,K.jsx)(zb,{handle:l,store:p}),T&&(0,K.jsx)(fGe,{store:p,disabled:t,trackCursorAxis:a}),typeof f==`function`?f({payload:v}):f]})});function fGe({store:e,disabled:t,trackCursorAxis:n}){let r=e.useState(`floatingRootContext`),i=jb(r,{enabled:!t,referencePress:()=>e.select(`closeOnClick`)}),a=lUe(r,{enabled:!t&&n!==`none`,axis:n===`none`?void 0:n}),o=G.useMemo(()=>D(a.reference,i.reference),[a.reference,i.reference]);return Gb(e,{activeTriggerProps:o,inactiveTriggerProps:o,popupProps:i.floating??te}),null}function gx(e){return xb(e,`base-ui`)}var pGe=G.createContext(void 0);function mGe(){return G.useContext(pGe)}var hGe=`data-base-ui-tooltip-trigger`;function gGe(e){let t=vy(e);return oy(t)?t:null}var _Ge=Uv(function(e,t){let{render:n,className:r,style:i,handle:a,payload:o,disabled:s,delay:c,closeOnClick:l=!0,closeDelay:u,id:d,...f}=e,p=Kv(!0),m=$b(a)??p;if(!m)throw Error(Gv(82));let h=gx(d),g=m.useState(`isTriggerActive`,h),_=m.useState(`isOpenedByTrigger`,h),v=m.useState(`floatingRootContext`),y=G.useRef(null),b=u??0,{registerTrigger:x,isMountedByThisTrigger:S}=Hb(h,y,m,{payload:o,closeOnClick:l,closeDelay:b}),C=mGe(),{activeIdRef:w,delayRef:T,isInstantPhase:E,hasProvider:D}=jVe(v,{open:_}),O=QUe(v);m.useSyncedValue(`isInstantPhase`,E);let k=m.useState(`disabled`),A=s??k,j=Ry(A),M=m.useState(`trackCursorAxis`),P=m.useState(`disableHoverablePopup`),F=G.useRef(!1),I=Yv(),L=G.useRef(void 0);function R(){return D&&w.current!=null?0:c??C??600}function z(e){let t=y.current;if(!t||!e)return!1;let n=_y(e,`[${hGe}]`);return n!==null&&n!==t&&gy(t,n)}function B(e){let t=z(e);return F.current=t,t&&(O.openChangeTimeout.clear(),O.restTimeout.clear(),O.restTimeoutPending=!1,I.clear()),t}let V=rx(v,{enabled:!A,mouseOnly:!0,move:!1,handleClose:!P&&M!==`both`?ux():null,restMs:R,delay(){return u==null&&D?{close:Ty(T.current,`close`)}:{close:b}},triggerElementRef:y,isActiveTrigger:g,isClosing:()=>m.select(`transitionStatus`)===`ending`,shouldOpen(){return!F.current}}),H=YUe(v,{enabled:!A}).reference,ee=e=>{let t=F.current,n=gGe(e),r=B(n),i=y.current,a=i&&n&&gy(i,n);if(r&&m.select(`open`)&&m.select(`lastOpenChangeReason`)===`trigger-hover`)m.setOpen(!1,Ey(Ay,e));else if(t&&!r&&a&&!j.current&&!m.select(`open`)&&i&&ny(L.current)){let t=()=>{F.current||j.current||m.select(`open`)||m.setOpen(!0,Ey(Ay,e,i))},n=R();n===0?(I.clear(),t()):I.start(n,t)}},te=m.useState(`appliedTriggerProps`,S||M!==`none`);return N(`button`,e,{state:{open:_},ref:[t,x,y],props:[V,H,te,{onMouseOver(e){ee(e.nativeEvent)},onFocus(e){z(gGe(e.nativeEvent))&&e.preventBaseUIHandler()},onMouseLeave(){F.current=!1,I.clear(),L.current=void 0},onPointerEnter(e){L.current=e.pointerType},onPointerDown(e){L.current=e.pointerType,m.set(`closeOnClick`,l),l&&!m.select(`open`)&&m.cancelPendingOpen(e.nativeEvent)},onClick(e){l&&!m.select(`open`)&&m.cancelPendingOpen(e.nativeEvent)},id:h,[XBe]:A?``:void 0,[hGe]:A?void 0:``},f],stateAttributesMapping:by})}),vGe=G.createContext(void 0);function yGe(){let e=G.useContext(vGe);if(e===void 0)throw Error(Gv(70));return e}var bGe=G.forwardRef(function(e,t){let{children:n,container:r,className:i,render:a,style:o,...s}=e,{node:c,subtree:l}=qHe({container:r,ref:t,componentProps:e,elementProps:s});return!l&&!c?null:(0,K.jsxs)(G.Fragment,{children:[l,c&&Pt.createPortal(n,c)]})}),xGe=G.forwardRef(function(e,t){let{keepMounted:n=!1,...r}=e;return Kv().useState(`mounted`)||n?(0,K.jsx)(vGe.Provider,{value:n,children:(0,K.jsx)(bGe,{ref:t,...r})}):null}),SGe=G.createContext(void 0);function CGe(){let e=G.useContext(SGe);if(e===void 0)throw Error(Gv(71));return e}function wGe(e){let{nodeId:t,externalTree:n,rootContext:r}=e,i=r.useState(`referenceElement`),a=r.useState(`floatingElement`),o=r.useState(`domReferenceElement`),s=r.useState(`open`),c=r.useState(`floatingId`),[l,u]=G.useState(null),d=G.useRef(null),f=Tb(n),p=G.useMemo(()=>({reference:i,floating:a,domReference:o}),[i,a,o]),m=tGe({...e,elements:{...p,...l&&{reference:l}}}),h=G.useCallback(e=>{let t=oy(e)?{getBoundingClientRect:()=>e.getBoundingClientRect(),getClientRects:()=>e.getClientRects(),contextElement:e}:e;u(t),m.refs.setReference(t)},[m.refs]),g=G.useMemo(()=>({...m.refs,setPositionReference:h,domReference:d}),[m.refs,h]),_=G.useMemo(()=>({...m.elements,domReference:o}),[m.elements,o]),v=G.useMemo(()=>({...m,dataRef:r.context.dataRef,open:s,onOpenChange:r.setOpen,events:r.context.events,floatingId:c,refs:g,elements:_,nodeId:t,rootStore:r}),[m,g,_,t,r,s,c]);return Wv(()=>{o&&(d.current=o)},[o]),Wv(()=>{r.context.dataRef.current.floatingContext=v;let e=f?.nodesRef.current.find(e=>e.id===t);e&&(e.context=v)}),G.useMemo(()=>({...m,context:v,refs:g,elements:_,rootStore:r}),[m,g,_,v,r])}var TGe=G.createContext(void 0);function _x(){return G.useContext(TGe)?.direction??`ltr`}var EGe=e=>({name:`arrow`,options:e,async fn(t){let{x:n,y:r,placement:i,rects:a,platform:o,elements:s,middlewareData:c}=t,{element:l,padding:u=0}=$y(e,t)||{};if(l==null)return{};let d=eHe(u),f={x:n,y:r},p=UVe(i),m=HVe(p),h=await o.getDimensions(l),g=p===`y`,_=g?`top`:`left`,v=g?`bottom`:`right`,y=g?`clientHeight`:`clientWidth`,b=a.reference[m]+a.reference[p]-f[p]-a.floating[m],x=f[p]-a.reference[p],S=s.floating[y]||a.floating[m],C=b/2-x/2,w=S/2-h[m]/2-1,T=Math.min(d[_],w),E=Math.min(d[v],w),D=T,O=S-h[m]-E,k=S/2-h[m]/2+C,A=BVe(D,k,O),j=!c.arrow&&tb(i)!=null&&k!==A&&a.reference[m]/2-(k<D?T:E)-h[m]/2<0,M=j?k<D?k-D:k-O:0;return{[p]:f[p]+M,data:{[p]:A,centerOffset:k-A-M,...j&&{alignmentOffset:M}},reset:j}}}),DGe=(e,t)=>{let{name:n,fn:r}=EGe(e);return{name:n,fn:r,options:[e,t]}},OGe={name:`hide`,async fn(e){let{width:t,height:n,x:r,y:i}=e.rects.reference,a=t===0&&n===0&&r===0&&i===0,o=await e.platform.detectOverflow(e,{elementContext:`reference`});return{data:{referenceHidden:o.top-n>=0||o.right-t>=0||o.bottom-n>=0||o.left-t>=0||a}}}},kGe={sideX:`left`,sideY:`top`},AGe=`--available-width`,jGe=`--available-height`,MGe=`--anchor-width`,NGe=`--anchor-height`,PGe=`--transform-origin`,FGe=AGe,IGe=jGe;function LGe(e,t,n){let r=e===`inline-start`||e===`inline-end`;return{top:`top`,right:r?n?`inline-start`:`inline-end`:`right`,bottom:`bottom`,left:r?n?`inline-end`:`inline-start`:`left`}[t]}function RGe(e,t,n){let{rects:r,placement:i}=e;return{side:LGe(t,eb(i),n),align:tb(i)||`center`,anchor:{width:r.reference.width,height:r.reference.height},positioner:{width:r.floating.width,height:r.floating.height}}}function vx(e){return zGe(e,wGe)}function zGe(e,t){let{anchor:n,positionMethod:r=`absolute`,side:i=`bottom`,sideOffset:a=0,align:o=`center`,alignOffset:s=0,collisionBoundary:c,collisionPadding:l=5,sticky:u=!1,arrowPadding:d=5,disableAnchorTracking:f=!1,inline:p,keepMounted:m=!1,floatingRootContext:h,mounted:g,collisionAvoidance:_,shift:v,nodeId:y,adaptiveOrigin:b,lazyFlip:x=!1,externalTree:S}=e,C=_.side||`flip`,w=_.align||`flip`,T=_.fallbackAxisSide||`end`,E=v?.crossAxis??!1,D=v?.rootBoundary,O=typeof n==`function`?n:void 0,k=zy(O),A=O?k:n,j=Ry(n),M=Ry(g),N=_x()===`rtl`,[P,F]=G.useState(null);!g&&P!==null&&F(null);let I=x===`placement`,L=P?eb(P):null,R=P&&I?tb(P)||`center`:null,z=L||{top:`top`,right:`right`,bottom:`bottom`,left:`left`,"inline-end":N?`left`:`right`,"inline-start":N?`right`:`left`}[i],B=R||o,V=B===`center`?z:`${z}-${B}`,H=l;typeof H==`number`?H={top:H,right:H,bottom:H,left:H}:H&&={top:H.top||0,right:H.right||0,bottom:H.bottom||0,left:H.left||0};let ee=+(i===`bottom`),te=+(i===`top`),U=+(i===`right`),W=+(i===`left`),ne={boundary:c===`clipping-ancestors`?`clippingAncestors`:c,padding:H},re=G.useRef(null),ie=Ry(a),ae=Ry(s),oe=typeof a==`function`?0:a,se=typeof s==`function`?0:s,ce=[];p&&ce.push(p),ce.push(nGe(e=>{let t=RGe(e,i,N),n=typeof ie.current==`function`?ie.current(t):ie.current,r=typeof ae.current==`function`?ae.current(t):ae.current;return{mainAxis:n,crossAxis:r,alignmentAxis:r}},[oe,se,N,i]));let le=w===`none`&&C!==`shift`,ue=!le&&(u||E||C===`shift`),de=C===`none`?null:aGe({...ne,padding:{top:H.top+1+ee,right:H.right+1+W,bottom:H.bottom+1+te,left:H.left+1+U},mainAxis:!E&&C===`flip`,crossAxis:w===`flip`&&`alignment`,fallbackAxisSideDirection:T}),fe=le?null:rGe({...ne,rootBoundary:D,mainAxis:w!==`none`,crossAxis:ue,limiter:u||E?void 0:iGe(e=>{if(!re.current)return{};let{width:t,height:n}=re.current.getBoundingClientRect(),r=nb(eb(e.placement)),i=r===`y`?t:n,a=r===`y`?H.left+H.right:H.top+H.bottom;return{offset:i/2+a/2}})},[ne,u,E,D,H,w]);C===`shift`||w===`shift`||B===`center`?ce.push(fe,de):ce.push(de,fe),ce.push(oGe({...ne,apply({elements:{floating:e},availableWidth:t,availableHeight:n,rects:r}){if(!M.current)return;let i=e.style;i.setProperty(FGe,`${t}px`),i.setProperty(IGe,`${n}px`);let a=iy(e).devicePixelRatio||1,{x:o,y:s,width:c,height:l}=r.reference,u=(Math.round((o+c)*a)-Math.round(o*a))/a,d=(Math.round((s+l)*a)-Math.round(s*a))/a;i.setProperty(MGe,`${u}px`),i.setProperty(NGe,`${d}px`)}}),DGe(e=>({element:re.current||Wy(e.elements.floating).createElement(`div`),padding:re.current?d:0}),[d]),{name:`transformOrigin`,fn(e){let{elements:{floating:t},middlewareData:n,placement:r,platform:o,rects:s,y:c}=e,l=eb(r),u=tb(r),d=nb(l)===`y`,f=re.current,p=typeof a==`function`?a(RGe(e,i,N)):a,m;m=!f&&u&&Math.abs(d?n.shift?.x||0:n.shift?.y||0)<=1?u===`start`===(d&&o.isRTL?.(t)===!0)?`100%`:`0%`:`${(d?n.arrow?.x||0:n.arrow?.y||0)+(d?f?.clientWidth||0:f?.clientHeight||0)/2}px`;let h=l===`top`||l===`left`?`calc(100% + ${p}px)`:`${-p}px`;return ue&&d&&Math.abs(n.shift?.y||0)>p&&(h=`${s.reference.y+s.reference.height/2-c}px`),t.style.setProperty(PGe,d?`${m} ${h}`:`${h} ${m}`),{}}},OGe,b),Wv(()=>{!g&&h&&h.update({referenceElement:null,floatingElement:null,domReferenceElement:null,positionReference:null})},[g,h]);let pe=G.useMemo(()=>({ancestorScroll:!f,elementResize:!f&&typeof ResizeObserver<`u`,layoutShift:!f&&typeof IntersectionObserver<`u`}),[f]),{refs:me,elements:he,x:ge,y:_e,middlewareData:ve,update:ye,placement:be,context:xe,isPositioned:Se,floatingStyles:Ce}=t({rootContext:h,open:m?g:void 0,placement:V,middleware:ce,strategy:r,whileElementsMounted:m?void 0:(...e)=>GWe(...e,pe),nodeId:y,externalTree:S}),{sideX:we,sideY:Te}=ve.adaptiveOrigin||kGe,Ee=Se?r:`fixed`,De=G.useMemo(()=>{let e;return e=Se?b?{position:Ee,[we]:ge,[Te]:_e}:{...Ce,position:Ee}:{position:Ee,top:0,left:0},e[FGe]=`100vw`,e[IGe]=`100vh`,Se||(e.opacity=0),e},[b,Ee,we,ge,Te,_e,Ce,Se]),Oe=G.useRef(null);Wv(()=>{if(!g)return;let e=j.current,t=typeof e==`function`?e():e,n=(BGe(t)?t.current:t)||null;n!==Oe.current&&(me.setPositionReference(n),Oe.current=n)},[g,me,A,j]),G.useEffect(()=>{if(!g)return;let e=j.current;typeof e!=`function`&&BGe(e)&&e.current!==Oe.current&&(me.setPositionReference(e.current),Oe.current=e.current)},[g,me,A,j]),G.useEffect(()=>{if(m&&g&&he.reference&&he.floating)return GWe(he.reference,he.floating,ye,pe)},[m,g,he,ye,pe]);let ke=eb(be),Ae=LGe(i,ke,N),je=tb(be)||`center`,Me=!!ve.hide?.referenceHidden;Wv(()=>{x&&g&&Se&&(ke!==z||I&&je!==B)&&F(be)},[x,I,g,Se,be,ke,je,z,B]);let Ne=G.useMemo(()=>({position:`absolute`,top:ve.arrow?.y,left:ve.arrow?.x}),[ve.arrow]),Pe=ve.arrow?.centerOffset!==0;return G.useMemo(()=>({positionerStyles:De,arrowStyles:Ne,arrowRef:re,arrowUncentered:Pe,side:Ae,align:je,physicalSide:ke,anchorHidden:Me,refs:me,context:xe,isPositioned:Se,update:ye}),[De,Ne,re,Pe,Ae,je,ke,Me,me,xe,Se,ye])}function BGe(e){return e!=null&&`current`in e}function yx(e){return e===`starting`?RHe:te}function bx(e,t,{styles:n,transitionStatus:r,props:i,refs:a,hidden:o,inert:s=!1}){let c={...n};return s&&(c.pointerEvents=`none`),N(`div`,e,{state:t,ref:a,props:[{role:`presentation`,hidden:o,style:c},yx(r),i],stateAttributesMapping:Sy})}var VGe=G.forwardRef(function(e,t){let{render:n,className:r,anchor:i,positionMethod:a=`absolute`,side:o=`top`,align:s=`center`,sideOffset:c=0,alignOffset:l=0,collisionBoundary:u=`clipping-ancestors`,collisionPadding:d=5,arrowPadding:f=5,sticky:p=!1,disableAnchorTracking:m=!1,collisionAvoidance:h=Sb,style:g,..._}=e,v=Kv(),y=yGe(),b=v.useState(`open`),x=v.useState(`mounted`),S=v.useState(`trackCursorAxis`),C=v.useState(`disableHoverablePopup`),w=v.useState(`floatingRootContext`),T=v.useState(`instantType`),E=v.useState(`transitionStatus`),D=vx({anchor:i,positionMethod:a,floatingRootContext:w,mounted:x,side:o,sideOffset:c,align:s,alignOffset:l,collisionBoundary:u,collisionPadding:d,sticky:p,arrowPadding:f,disableAnchorTracking:m,keepMounted:y,collisionAvoidance:h,adaptiveOrigin:v.useState(`adaptiveOrigin`)}),O=bx(e,G.useMemo(()=>({open:b,side:D.side,align:D.align,anchorHidden:D.anchorHidden,instant:S===`none`?T:`tracking-cursor`}),[b,D.side,D.align,D.anchorHidden,S,T]),{styles:D.positionerStyles,transitionStatus:E,props:_,refs:[t,v.useStateSetter(`positionerElement`)],hidden:!x,inert:!b||S===`both`||C});return(0,K.jsx)(SGe.Provider,{value:D,children:O})}),HGe=G.forwardRef(function(e,t){let{render:n,className:r,style:i,...a}=e,o=Kv(),{side:s,align:c}=CGe(),l=o.useState(`open`),u=o.useState(`instantType`),d=o.useState(`transitionStatus`),f=o.useState(`popupProps`),p=o.useState(`floatingRootContext`),m=o.useState(`disabled`),h=o.useState(`closeDelay`);Ib({open:l,ref:o.context.popupRef,onComplete(){l&&o.context.onOpenChangeComplete?.(!0)}}),nx(p,{enabled:!m,closeDelay:h});let g=o.useStateSetter(`popupElement`);return N(`div`,e,{state:{open:l,side:s,align:c,instant:u,transitionStatus:d},ref:[t,o.context.popupRef,g],props:[Lb,f,yx(d),a],stateAttributesMapping:Cy})}),UGe=G.forwardRef(function(e,t){let{render:n,className:r,style:i,...a}=e,o=Kv(),{arrowRef:s,side:c,align:l,arrowUncentered:u,arrowStyles:d}=CGe(),f={open:o.useState(`open`),side:c,align:l,uncentered:u,instant:o.useState(`instantType`)};return N(`div`,e,{state:f,ref:[t,s],props:[{style:d,"aria-hidden":!0},a],stateAttributesMapping:Sy})}),WGe=function(e){let{delay:t,closeDelay:n,timeout:r=400}=e,i=G.useMemo(()=>({open:t,close:n}),[t,n]);return(0,K.jsx)(pGe.Provider,{value:t,children:(0,K.jsx)(AVe,{delay:i,timeoutMs:r,children:e.children})})};function xx(e){return ee(19)?e:e?`true`:void 0}function GGe(e){let[t,n]=G.useState({current:e,previous:null});return Object.is(e,t.current)||n({current:e,previous:t.current}),t.previous}function KGe(e){let t=fy(e),n=parseFloat(t.width)||0,r=parseFloat(t.height)||0,i=sy(e),a=i?e.offsetWidth:n,o=i?e.offsetHeight:r;return(Xy(n)!==a||Xy(r)!==o)&&(n=a,r=o),{width:n,height:r}}function Sx({delay:e,delayDuration:t,timeout:n,skipDelayDuration:r,...i}){let a=e??t,o=n??r;return(0,K.jsx)(WGe,{...a===void 0?{}:{delay:a},...o===void 0?{}:{timeout:o},...i})}var Cx=dGe,wx=G.forwardRef(({asChild:e,render:t,children:n,...r},i)=>e&&G.isValidElement(n)?(0,K.jsx)(_Ge,{ref:i,render:n,...r}):(0,K.jsx)(_Ge,{ref:i,render:t,...r,children:n}));wx.displayName=`TooltipTrigger`;var Tx=G.forwardRef(({className:e,side:t=`top`,sideOffset:n=8,align:r=`center`,alignOffset:i=0,arrowPadding:a=10,anchor:o,positionMethod:s=zv,collisionBoundary:l,collisionPadding:u,sticky:d,disableAnchorTracking:f,collisionAvoidance:p,keepMounted:m,children:h,...g},_)=>{let v={side:t,sideOffset:n,align:r,alignOffset:i,arrowPadding:a,anchor:o,positionMethod:s,collisionBoundary:l,collisionPadding:u,sticky:d,disableAnchorTracking:f,collisionAvoidance:p};return(0,K.jsx)(xGe,{keepMounted:m,children:(0,K.jsx)(VGe,{className:`isolate z-100`,...v,children:(0,K.jsxs)(HGe,{ref:_,role:`tooltip`,className:c(`relative z-100 flex origin-(--transform-origin) flex-col rounded-lg px-2.5 py-1.5 text-caption text-foreground transition-[transform,scale,opacity] duration-150`,Vv,`data-[starting-style]:scale-95 data-[starting-style]:opacity-0`,`data-[ending-style]:scale-95 data-[ending-style]:opacity-0`,`data-[instant]:transition-none motion-reduce:transition-none`,e),...g,children:[h,(0,K.jsx)(UGe,{className:c(`flex`,`data-[side=top]:bottom-[-7px] data-[side=top]:rotate-180`,`data-[side=bottom]:top-[-7px]`,`data-[side=left]:right-[-9px] data-[side=left]:rotate-90`,`data-[side=right]:left-[-9px] data-[side=right]:-rotate-90`),children:(0,K.jsx)(qGe,{})})]})})})});Tx.displayName=`TooltipContent`;function qGe(){return(0,K.jsxs)(`svg`,{width:`12`,height:`8`,viewBox:`0 0 12 8`,fill:`none`,overflow:`visible`,children:[(0,K.jsx)(`path`,{d:`M0 7L4 2Q6 0 8 2L12 7L12 8L0 8Z`,className:`fill-card`}),(0,K.jsx)(`path`,{d:`M0 7.5L4 2.5Q6 0.5 8 2.5L12 7.5`,className:`fill-none [stroke:var(--surface-rim)]`,strokeWidth:`1`,strokeLinejoin:`round`,strokeLinecap:`round`})]})}var Ex={xs:`[&>svg]:size-icon-xs`,sm:`[&>svg]:size-icon-sm`,md:`[&>svg]:size-icon-md`,lg:`[&>svg]:size-icon-lg`},Dx=({children:e,className:t,size:n=`md`,...r})=>(0,K.jsx)(`span`,{"data-slot":`icon`,className:c(`block`,Ex[n],t),...r,children:e}),Ox=c(`[--control-icon:var(--control-icon-rest)] [&_svg]:text-(color:--control-icon)`,`not-disabled:hover:[--control-icon:var(--control-icon-hover)] aria-disabled:[--control-icon:var(--control-icon-rest)]`,`data-[shape=icon]:[--control-icon-hover:var(--foreground)]`),JGe=`[--control-icon-hover:var(--foreground)]`,YGe=G.createContext(void 0),kx={sm:`h-control-sm`,md:`h-control-md`,lg:`h-control-lg`},Ax={sm:`h-control-sm text-label`,md:`h-control-md text-label`,lg:`h-control-lg text-label`},jx={sm:`[--control-px:.9em] [--control-gap:0.3125rem]`,md:`[--control-px:.9em] [--control-gap:0.375rem]`,lg:`[--control-px:1em] [--control-gap:0.375rem]`},XGe={default:`data-[popup-open]:[--surface-tint:var(--fill)] data-[popup-open]:text-foreground`,ghost:`data-[popup-open]:bg-fill-subtle data-[popup-open]:text-foreground`};function ZGe(e){return e==="default"||e===`ghost`?XGe[e]:void 0}var QGe=`disabled:cursor-not-allowed disabled:text-muted-foreground`,$Ge=`focus-visible:border-border-focus`,eKe=`focus-within:border-border-focus`,tKe=`outline-hidden focus-visible:outline-hidden ${$Ge}`,nKe=`focus-visible:outline-hidden focus-visible:[--surface-rim:var(--border-focus)]`,rKe=`focus-visible:outline-hidden focus-visible:[--surface-rim:var(--field-rim-focus)]`,iKe=`aria-invalid:[--field-rim:var(--destructive-indicator)] aria-invalid:[--field-rim-focus:var(--destructive-indicator)]`,aKe=`has-[[aria-invalid=true]]:[--field-rim:var(--destructive-indicator)] has-[[aria-invalid=true]]:[--field-rim-focus:var(--destructive-indicator)]`;function Mx(e){return e?{"aria-invalid":!0}:{}}var oKe=`aria-invalid:border-destructive-indicator aria-invalid:hover:border-destructive-indicator aria-invalid:focus-visible:border-destructive-indicator`;``+rKe;var sKe=`w-(--field-width,100%) max-w-(--field-max-width,none) shrink-(--field-shrink,1)`,cKe=`bg-field shadow-input text-foreground disabled:bg-field-disabled [&:hover:not(:focus-visible):not(:disabled):not([data-popup-open])]:[--surface-tint:var(--fill-subtle)] outline-hidden focus-visible:outline-hidden `+rKe,Nx=`bg-field shadow-input text-foreground has-[:disabled]:bg-field-disabled [&:hover:not(:has(:focus-visible)):not(:has(:disabled))]:[--surface-tint:var(--fill-subtle)] outline-hidden focus-within:outline-hidden has-[:focus-visible]:[--surface-rim:var(--field-rim-focus)]`,lKe=`bg-field shadow-input text-foreground [&:hover:not(:active):not(:disabled):not([data-popup-open])]:[--surface-tint:var(--fill-subtle)] [&:active:not(:disabled)]:[--surface-tint:var(--fill)] focus-visible:outline-hidden focus-visible:[--surface-rim:var(--border-focus)]`;function uKe(e){return e===`filled`?`default`:e}var dKe=`border-0 bg-transparent outline-hidden focus-visible:outline-hidden`,fKe=G.createContext(void 0);function Px(e=!1){let t=G.useContext(fKe);if(t===void 0&&!e)throw Error(Gv(16));return t}function pKe(e){let{focusableWhenDisabled:t,disabled:n,composite:r=!1,tabIndex:i=0,isNativeButton:a}=e,o=r&&t!==!1,s=r&&t===!1;return{props:G.useMemo(()=>{let e={onKeyDown(e){n&&t&&e.key!==`Tab`&&e.preventDefault()}};return r||(e.tabIndex=i,!a&&n&&(e.tabIndex=t?i:-1)),(a&&(t||o)||!a&&n)&&(e[`aria-disabled`]=n),a&&(!t||s)&&(e.disabled=n),e},[r,n,t,o,s,a,i])}}function Fx(e,t,{detail:n=0,pointerType:r=``}={}){e.dispatchEvent(new(iy(e)).PointerEvent(`click`,{bubbles:!0,cancelable:!0,composed:!0,detail:n,pointerType:r,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,altKey:t.altKey,metaKey:t.metaKey}))}function Ix(e={}){let{disabled:t=!1,focusableWhenDisabled:n,tabIndex:r=0,native:i=!0,composite:a}=e,o=G.useRef(null),s=Px(!0),c=a??s!==void 0,{props:l}=pKe({focusableWhenDisabled:n,disabled:t,composite:c,tabIndex:r,isNativeButton:i}),u=G.useCallback(()=>{let e=o.current;mKe(e)&&c&&t&&l.disabled===void 0&&e.disabled&&(e.disabled=!1)},[t,l.disabled,c]);return Wv(u,[u]),{getButtonProps:G.useCallback((e={})=>{let{onClick:n,onMouseDown:r,onKeyUp:a,onKeyDown:o,onPointerDown:s,...u}=e;return D({onClick(e){t?e.preventDefault():n?.(e)},onMouseDown(e){t||r?.(e)},onKeyDown(e){if(t||(O(e),o?.(e),e.baseUIHandlerPrevented))return;let n=e.target===e.currentTarget,r=e.currentTarget,a=mKe(r),s=!i&&hKe(r),l=n&&(i?a:!s),u=e.key===`Enter`,d=e.key===` `,f=r.getAttribute(`role`),p=f?.startsWith(`menuitem`)||f===`option`||f===`gridcell`;if(n&&c&&d){if(e.defaultPrevented&&p)return;e.preventDefault(),(!i||a)&&(e.preventBaseUIHandler(),Fx(r,e))}else!l||i||!d&&!u?n&&s&&d&&e.preventDefault():e.defaultPrevented||(e.preventDefault(),u&&(e.preventBaseUIHandler(),Fx(r,e)))},onKeyUp(e){t||(O(e),a?.(e),e.target===e.currentTarget&&i&&c&&mKe(e.currentTarget)&&e.key===` `?e.preventDefault():e.baseUIHandlerPrevented||e.target!==e.currentTarget||i||c||e.defaultPrevented||e.key!==` `||(e.preventBaseUIHandler(),Fx(e.currentTarget,e)))},onPointerDown(e){t?e.preventDefault():s?.(e)}},i?{type:`button`}:{role:`button`},l,u)},[t,l,c,i]),buttonRef:zy(e=>{o.current=e,u()})}}function mKe(e){return sy(e)&&e.tagName===`BUTTON`}function hKe(e){return sy(e)&&e.tagName===`A`&&!!e.href}var gKe=G.forwardRef(function(e,t){let{render:n,className:r,disabled:i=!1,focusableWhenDisabled:a=!1,nativeButton:o=!0,style:s,...c}=e,{getButtonProps:l,buttonRef:u}=Ix({disabled:i,focusableWhenDisabled:a,native:o});return N(`button`,e,{state:{disabled:i},ref:[t,u],props:[c,l]})}),_Ke=c(`rounded-full px-[calc(var(--control-px)-var(--control-border,0px))]`,`has-[>[data-slot=button-icon]]:pl-[calc(var(--control-px)-2px-var(--control-border,0px))]`,`has-[>svg]:pl-[calc(var(--control-px)-2px-var(--control-border,0px))]`,`has-[>[data-slot=button-icon-end]]:pr-[calc(var(--control-px)-2px-var(--control-border,0px))]`),vKe=c(`relative size-auto gap-1 rounded-xs px-0 text-label`,`before:absolute before:-inset-x-2`,`has-[>[data-slot=button-icon-end]]:pr-0 has-[>[data-slot=button-icon]]:pl-0 has-[>svg]:pl-0`),yKe=c(`relative inline-flex items-center gap-1`,Ex.sm,`[&>svg]:shrink-0`,`after:absolute after:inset-x-0 after:bottom-0 after:h-px after:origin-left after:scale-x-0 after:bg-current`,`after:transition-transform after:duration-fast after:ease-out-custom motion-reduce:after:transition-none`),Lx=Nt(c(`inline-flex cursor-pointer items-center justify-center whitespace-nowrap`,A,QGe,`aria-disabled:pointer-events-none aria-disabled:cursor-not-allowed aria-disabled:text-muted-foreground`,tKe),{variants:{variant:{default:c(`border-0`,lKe,Ox,`disabled:bg-fill-subtle aria-disabled:bg-fill-subtle`),primary:c(`border border-transparent bg-fill-inverse text-background [--control-border:1px] not-disabled:hover:bg-fill-inverse-hover not-disabled:active:bg-fill-inverse-active`,g,`focus-visible:border-transparent`,`disabled:bg-fill-inverse-disabled disabled:text-background/75 aria-disabled:bg-fill-inverse-disabled aria-disabled:text-background/75`),destructive:c(`border border-transparent bg-fill-destructive text-fill-destructive-foreground [--control-border:1px] not-disabled:hover:bg-fill-destructive-hover not-disabled:active:bg-fill-destructive-active`,g,`focus-visible:border-transparent`,`disabled:bg-fill-destructive-disabled disabled:text-fill-destructive-disabled-foreground aria-disabled:bg-fill-destructive-disabled aria-disabled:text-fill-destructive-disabled-foreground`),"destructive-ghost":c(`border border-transparent bg-transparent text-destructive-foreground [--control-border:1px] not-disabled:hover:bg-destructive-subtle not-disabled:hover:text-destructive-foreground not-disabled:active:bg-destructive-subtle-active`,`disabled:bg-transparent disabled:text-placeholder aria-disabled:bg-transparent aria-disabled:text-placeholder`),ghost:c(`border border-transparent bg-transparent text-muted-foreground [--control-border:1px] not-disabled:hover:bg-fill-subtle not-disabled:hover:text-foreground not-disabled:active:bg-fill`,Ox,`disabled:bg-transparent aria-disabled:bg-transparent`),subtle:c(`border-0 bg-fill-hover text-foreground not-disabled:hover:bg-fill-hover not-disabled:active:bg-fill`,p,`disabled:bg-transparent aria-disabled:bg-transparent`),link:c(`border-0 bg-transparent text-muted-foreground not-disabled:hover:text-foreground`,`not-disabled:hover:[&>[data-slot=button-label]]:after:scale-x-100 not-disabled:hover:[&>[data-slot=button-label]]:after:duration-normal`,g,`disabled:text-placeholder aria-disabled:text-placeholder`)},size:{sm:c(Ax.sm,Ex.sm,jx.sm,`gap-(--control-gap)`,_Ke),md:c(Ax.md,Ex.md,jx.md,`gap-(--control-gap)`,_Ke),lg:c(Ax.lg,Ex.lg,jx.lg,`gap-(--control-gap)`,_Ke),"icon-sm":c(kx.sm,`w-control-sm rounded-full`),"icon-md":c(kx.md,`w-control-md rounded-full`),"icon-lg":c(kx.lg,`w-control-lg rounded-full`)}},compoundVariants:[{variant:`link`,className:vKe},{variant:`link`,size:[`sm`,`md`,`icon-sm`,`icon-md`],className:`before:-inset-y-1`},{variant:`link`,size:[`lg`,`icon-lg`],className:`before:-inset-y-1.5`}],defaultVariants:{variant:`default`,size:`md`}});function bKe(e){if(e.type===`a`)return!0;let{href:t,to:n}=e.props;return t!==void 0||n!==void 0}function xKe(e){e.preventDefault(),e.stopPropagation()}var Rx={sm:`sm`,md:`md`,lg:`lg`,"icon-sm":`sm`,"icon-md":`md`,"icon-lg":`lg`};function SKe(e,t){return e===`link`?`sm`:Rx[t]}function CKe({size:e,children:t}){return(0,K.jsx)(zx,{slot:`button-icon`,size:Rx[e],children:t})}function wKe(){return(0,K.jsx)(_,{"aria-hidden":!0,"data-slot":`trigger-chevron`,className:`mx-[-0.125em] shrink-0`})}function TKe({size:e}){return(0,K.jsx)(zx,{slot:`button-icon-end`,size:Rx[e],children:(0,K.jsx)(wKe,{})})}function zx({slot:e,size:t,children:n}){if(n)return(0,K.jsx)(Dx,{"data-slot":e,size:t,children:n})}function EKe({variant:e,children:t}){return e===`link`?(0,K.jsx)(`span`,{"data-slot":`button-label`,className:yKe,children:t}):t}function DKe(e){return G.Children.toArray(e).flatMap(e=>G.isValidElement(e)&&e.type===G.Fragment?DKe(e.props.children):[e])}function OKe(e){let t=DKe(e);return t.length>0&&t.every(e=>G.isValidElement(e))}function Bx(e){return e?.startsWith(`icon-`)??!1}var X=G.forwardRef(({className:e,render:t,as:n,href:r,to:i,target:a,prefetch:o,size:s,variant:l=`default`,disabled:u,children:d,icon:f,iconEnd:p,tooltip:m,tooltipPosition:h,"aria-label":g,type:_,...v},y)=>{let b=l!==`link`&&Bx(s),x=s??`md`,S=l??`default`,C=SKe(S,x),w=g??((b||OKe(d))&&typeof m==`string`?m:void 0),T=b?(0,K.jsx)(Dx,{size:Rx[x],children:d}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(zx,{slot:`button-icon`,size:C,children:f}),(0,K.jsx)(EKe,{variant:S,children:d}),(0,K.jsx)(zx,{slot:`button-icon-end`,size:C,children:p})]}),E={disabled:u,type:_,"aria-label":w,"data-variant":l,"data-shape":b?`icon`:void 0,className:c(Lx({variant:l,size:x}),e),...v},D=t?void 0:n,O={...r===void 0?null:{href:r},...i===void 0?null:{to:i},...a===void 0?null:{target:a},...o===void 0?null:{prefetch:o}},k=S===`link`,A=r??i,j={...A===void 0?null:{href:A},...a===void 0?null:{target:a}},M=G.isValidElement(t)&&bKe(t)?t:k?G.createElement(`a`,j):void 0,N=M?.props,P=M?.type!==`a`&&N?.href!==void 0?``:void 0,F=N?.to===void 0?void 0:``,I=u?{...k?null:{href:P},...k?null:{to:F},"aria-disabled":!0,onClick:xKe,onAuxClick:xKe,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&xKe(e)}}:void 0,L=D?(0,K.jsx)(D,{ref:y,...O,...E,children:T}):M?G.cloneElement(M,{ref:y,...E,disabled:void 0,type:void 0,...I,className:c(E.className,M.props.className),children:T}):(0,K.jsx)(gKe,{ref:y,render:t,...E,children:T});return m?(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{asChild:!0,children:L}),(0,K.jsx)(Tx,{side:h,children:m})]}):L});X.displayName=`Button`;var kKe={default:`h-6 min-w-6 rounded-md px-1.5 text-caption`,sm:`h-5 min-w-5 rounded-md px-1 text-meta`,xs:`h-4 min-w-4 rounded px-1 text-meta leading-none`},Vx=({children:e,size:t=`default`,className:n})=>(0,K.jsx)(`kbd`,{className:c(`inline-flex items-center justify-center bg-card font-mono text-foreground shadow-raised`,kKe[t],u.transform,`active:scale-95 active:shadow-none`,n),children:(0,K.jsx)(`span`,{className:`[text-box:trim-both_cap_alphabetic]`,children:e})}),Hx=U(`IconPlusMedium`,()=>(0,K.jsx)(`path`,{d:`M12 5.5V12M12 12V18.5M12 12H5.5M12 12H18.5`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`})),Ux=(e,t={})=>{let{enabled:n=!0,target:r}=t,i=nn(),a=rn(),o=(0,G.useRef)({depth:a,bindings:e,shouldHandle:t.shouldHandle,insideFields:t.insideFields,repeat:t.repeat});o.current.bindings=e,o.current.shouldHandle=t.shouldHandle,o.current.insideFields=t.insideFields,o.current.repeat=t.repeat,o.current.depth=a;let s=!r&&i.status===`ready`?i.dispatcher:void 0;(0,G.useEffect)(()=>{if(!n)return;if(s)return s.register(o.current);let e=r?r.current??null:window;if(!e)return;let t=Zt(),i=t.register(o.current),a=e=>{e instanceof KeyboardEvent&&t.handleKeydown(e)};return e.addEventListener(`keydown`,a),()=>{e.removeEventListener(`keydown`,a),i(),t.reset()}},[n,r,s])},AKe=({count:e,containerRef:t,pageSize:n=10,initialIndex:r=0,onActivate:i,onNavigate:a,global:o=!1})=>{let[s,c]=(0,G.useState)(r),l=t=>Math.min(Math.max(t,0),Math.max(e-1,0)),u=e=>{let n=l(e);c(n),a?.(n);let r=t.current?.querySelector(`[data-row-index="${n}"]`);r&&(r.focus(),r.scrollIntoView?.({block:`nearest`}))},d=[[Rt(`mod+Home`),()=>u(0)],[Rt(`mod+End`),()=>u(e-1)],[Rt(`ArrowUp`),()=>u(s-1)],[Rt(`ArrowDown`),()=>u(s+1)],[Rt(`PageUp`),()=>u(s-n)],[Rt(`PageDown`),()=>u(s+n)],[Rt(`Home`),()=>u(0)],[Rt(`End`),()=>u(e-1)]],f=e=>{for(let[t,n]of d)if(Ut(e.nativeEvent,t)){e.preventDefault(),n();return}},p=()=>t.current?.contains(document.activeElement)??!1,m=e=>u(p()?s+e:s);return Ux({ArrowUp:()=>m(-1),ArrowDown:()=>m(1),PageUp:()=>u(s-n),PageDown:()=>u(s+n)},{enabled:o,shouldHandle:t=>!t.defaultPrevented&&e>0&&!Gt(t.target)}),(0,G.useEffect)(()=>{s>=e&&c(Math.max(e-1,0))},[s,e]),{activeIndex:s,setActiveIndex:c,activate:e=>i?.(e),getRowProps:e=>({tabIndex:e===s?0:-1,"data-row-index":e,onFocus:()=>c(e),onKeyDown:f}),getContainerProps:()=>({})}},Wx=(...e)=>t=>{let n=e.map(e=>{if(typeof e==`function`)return e(t);e&&(e.current=t)});return()=>{e.forEach((e,t)=>{let r=n[t];typeof r==`function`?r():typeof e==`function`?e(null):e&&(e.current=null)})}},Gx=G.forwardRef(({tooltip:e,shortcutEnabled:t=!0,disabled:n,children:r,...i},a)=>{let o=(0,G.useRef)(null);return Ux({c:()=>o.current?.click()},{enabled:t&&!n}),(0,K.jsx)(X,{ref:Wx(o,a),icon:(0,K.jsx)(Hx,{}),disabled:n,tooltip:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[e,(0,K.jsx)(Vx,{size:`xs`,children:`C`})]}),...i,children:r})});Gx.displayName=`CreateButton`;var Kx=U(`IconCircleBanSign`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M21 12C21 16.9706 16.9706 21 12 21C9.51472 21 7.26472 19.9926 5.63604 18.364C4.00736 16.7353 3 14.4853 3 12C3 7.02944 7.02944 3 12 3C14.4853 3 16.7353 4.00736 18.364 5.63604C19.9926 7.26472 21 9.51472 21 12Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`square`}),(0,K.jsx)(`path`,{d:`M18 6L6 18`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`square`})]})),qx=U(`IconCircleX`,()=>(0,K.jsx)(`path`,{d:`M15 9L9 15M15 15L9 9M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})),jKe={default:(0,K.jsx)(Kx,{}),error:(0,K.jsx)(qx,{})},MKe={default:`text-muted-foreground`,error:`text-destructive-foreground`};function Jx({tone:e=`default`,iconSlot:t=jKe[e],titleSlot:n,descriptionSlot:r,actionSlot:i,statusSlot:a,className:o,as:s=`h3`,variant:l=`inline`,layout:u=`stacked`}){let d=u===`split`,f=(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(s,{className:c(`text-foreground`,d?`text-heading`:`text-subheading`),children:n}),r&&(0,K.jsx)(T,{variant:d?`body`:`caption`,tone:`muted`,className:`mt-1.5 max-w-md wrap-anywhere`,children:r}),i&&(0,K.jsx)(`div`,{className:c(`max-w-full`,d?`mt-6`:`mt-4`),children:i}),a&&(0,K.jsx)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`mt-2 flex max-w-full items-center gap-2`,children:a})]}),p=(0,K.jsx)(`div`,{"data-slot":`empty-state`,"data-tone":e,"data-layout":u,className:c(`group/empty-state flex max-w-full px-4 py-6`,d?`@container w-full justify-center`:`flex-col items-center justify-center text-center`,`transition-opacity duration-normal ease-out-custom`,o),children:d?(0,K.jsxs)(`div`,{className:`flex flex-col items-center gap-6 text-center @2xl:flex-row @2xl:gap-12 @2xl:text-left`,children:[t&&(0,K.jsx)(`div`,{"data-slot":`empty-state-art-slot`,className:c(`flex h-60 w-52 max-w-full shrink-0 items-center justify-center [&_svg]:max-h-full [&_svg]:max-w-full`,MKe[e]),children:t}),(0,K.jsx)(`div`,{className:`flex w-80 max-w-full flex-col items-center @2xl:items-start`,children:f})]}):(0,K.jsxs)(K.Fragment,{children:[t&&(0,K.jsx)(`div`,{className:c(`mb-3 max-w-full [&>svg]:size-icon-lg`,MKe[e]),children:t}),f]})});return l===`fill`?(0,K.jsx)(`div`,{"data-slot":`empty-state-fill`,className:`flex h-full items-center-safe justify-center-safe`,children:p}):p}var NKe={sm:`w-6`,md:`w-8`,lg:`w-10`},PKe={sm:2.2,md:2.5,lg:2.9},FKe={sm:4.3,md:4.4,lg:4.498};function IKe({className:e,size:t=`md`,"aria-label":n=`Loading`}){let r=`brand-loader-${(0,G.useId)().replace(/[^a-zA-Z0-9_-]/g,``)}`,i=FKe[t];return(0,K.jsx)(`div`,{role:`status`,"aria-label":n,className:c(`brand-loader inline-block text-foreground`,NKe[t],e),style:{"--brand-loader-stroke":PKe[t]},children:(0,K.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 34 21`,"aria-hidden":`true`,children:[(0,K.jsx)(`defs`,{children:(0,K.jsxs)(`filter`,{id:r,x:`-5%`,y:`-5%`,width:`110%`,height:`110%`,children:[(0,K.jsx)(`feGaussianBlur`,{in:`SourceGraphic`,stdDeviation:`0.9`}),(0,K.jsx)(`feColorMatrix`,{values:`1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 11 -4.3`})]})}),(0,K.jsxs)(`g`,{filter:`url(#${r})`,children:[(0,K.jsx)(`line`,{className:`brand-loader-ln23`,x1:`10.387`,y1:`4.498`,x2:`16.899`,y2:`16.192`}),(0,K.jsx)(`line`,{className:`brand-loader-ln34`,x1:`16.899`,y1:`16.192`,x2:`22.815`,y2:`4.56`}),(0,K.jsx)(`line`,{className:`brand-loader-ln45`,x1:`22.815`,y1:`4.56`,x2:`28.57`,y2:`16.192`}),(0,K.jsx)(`circle`,{className:`brand-loader-b1`,cx:`4.498`,cy:`16.192`,r:i}),(0,K.jsx)(`circle`,{className:`brand-loader-b2`,cx:`10.387`,cy:`4.498`,r:i}),(0,K.jsx)(`circle`,{className:`brand-loader-b3`,cx:`16.899`,cy:`16.192`,r:i}),(0,K.jsx)(`circle`,{className:`brand-loader-b4`,cx:`22.815`,cy:`4.56`,r:i}),(0,K.jsx)(`circle`,{className:`brand-loader-b5`,cx:`28.57`,cy:`16.192`,r:i})]})]})})}var Yx=U(`IconCircleInfo`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M11 11H12V16M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M12 7.25C11.5858 7.25 11.25 7.58579 11.25 8C11.25 8.41421 11.5858 8.75 12 8.75C12.4142 8.75 12.75 8.41421 12.75 8C12.75 7.58579 12.4142 7.25 12 7.25Z`,fill:`currentColor`,stroke:`currentColor`,strokeWidth:`0.5`})]})),Xx=U(`IconExclamationCircle`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`circle`,{cx:`12`,cy:`12`,r:`9`,stroke:`currentColor`,strokeWidth:`2`}),(0,K.jsx)(`path`,{d:`M12 8V12.5`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`}),(0,K.jsx)(`circle`,{cx:`12`,cy:`15.7996`,r:`1.2`,fill:`currentColor`})]})),Zx=U(`IconExclamationTriangle`,()=>(0,K.jsx)(`path`,{d:`M12 9.01917V12.0134M12 15H12.01M10.2765 3.99036L3.27481 15.998C2.49885 17.3288 3.45836 19 4.99836 19H19.0016C20.5416 19 21.5011 17.3288 20.7252 15.998L13.7235 3.99035C12.9536 2.66988 11.0464 2.66988 10.2765 3.99036ZM12.25 15C12.25 15.1381 12.1381 15.25 12 15.25C11.8619 15.25 11.75 15.1381 11.75 15C11.75 14.8619 11.8619 14.75 12 14.75C12.1381 14.75 12.25 14.8619 12.25 15Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`})),LKe=U(`IconLightBulbSimple`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M12 3C8.13401 3 5 6.13401 5 10C5 12.5463 6.35958 14.7751 8.39241 16C8.75337 16.2175 9 16.5949 9 17.0163V19C9 20.6569 10.3431 22 12 22C13.6569 22 15 20.6569 15 19V17.0163C15 16.5949 15.2466 16.2175 15.6076 16C17.6404 14.7751 19 12.5463 19 10C19 6.13401 15.866 3 12 3Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M15 18H9`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`square`,strokeLinejoin:`round`})]}));function RKe(e){if(!e||typeof document>`u`)return;let t=document.head||document.getElementsByTagName(`head`)[0],n=document.createElement(`style`);n.type=`text/css`,t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}var zKe=e=>{switch(e){case`success`:return HKe;case`info`:return WKe;case`warning`:return UKe;case`error`:return GKe;default:return null}},BKe=Array(12).fill(0),VKe=({visible:e,className:t})=>G.createElement(`div`,{className:[`sonner-loading-wrapper`,t].filter(Boolean).join(` `),"data-visible":e},G.createElement(`div`,{className:`sonner-spinner`},BKe.map((e,t)=>G.createElement(`div`,{className:`sonner-loading-bar`,key:`spinner-bar-${t}`})))),HKe=G.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},G.createElement(`path`,{fillRule:`evenodd`,d:`M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z`,clipRule:`evenodd`})),UKe=G.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 24 24`,fill:`currentColor`,height:`20`,width:`20`},G.createElement(`path`,{fillRule:`evenodd`,d:`M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z`,clipRule:`evenodd`})),WKe=G.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},G.createElement(`path`,{fillRule:`evenodd`,d:`M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z`,clipRule:`evenodd`})),GKe=G.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},G.createElement(`path`,{fillRule:`evenodd`,d:`M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z`,clipRule:`evenodd`})),KKe=G.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`},G.createElement(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),G.createElement(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})),qKe=()=>{let[e,t]=G.useState(document.hidden);return G.useEffect(()=>{let e=()=>{t(document.hidden)};return document.addEventListener(`visibilitychange`,e),()=>window.removeEventListener(`visibilitychange`,e)},[]),e},JKe=1,Qx=new class{constructor(){this.subscribe=e=>(this.subscribers.push(e),()=>{let t=this.subscribers.indexOf(e);this.subscribers.splice(t,1)}),this.publish=e=>{this.subscribers.forEach(t=>t(e))},this.addToast=e=>{this.publish(e),this.toasts=[...this.toasts,e]},this.create=e=>{let{message:t,...n}=e,r=typeof e?.id==`number`||e.id?.length>0?e.id:JKe++,i=this.toasts.find(e=>e.id===r),a=e.dismissible===void 0||e.dismissible;return this.dismissedToasts.has(r)&&this.dismissedToasts.delete(r),i?this.toasts=this.toasts.map(n=>n.id===r?(this.publish({...n,...e,id:r,title:t}),{...n,...e,id:r,dismissible:a,title:t}):n):this.addToast({title:t,...n,dismissible:a,id:r}),r},this.dismiss=e=>(e?(this.dismissedToasts.add(e),requestAnimationFrame(()=>this.subscribers.forEach(t=>t({id:e,dismiss:!0})))):this.toasts.forEach(e=>{this.subscribers.forEach(t=>t({id:e.id,dismiss:!0}))}),e),this.message=(e,t)=>this.create({...t,message:e}),this.error=(e,t)=>this.create({...t,message:e,type:`error`}),this.success=(e,t)=>this.create({...t,type:`success`,message:e}),this.info=(e,t)=>this.create({...t,type:`info`,message:e}),this.warning=(e,t)=>this.create({...t,type:`warning`,message:e}),this.loading=(e,t)=>this.create({...t,type:`loading`,message:e}),this.promise=(e,t)=>{if(!t)return;let n;t.loading!==void 0&&(n=this.create({...t,promise:e,type:`loading`,message:t.loading,description:typeof t.description==`function`?void 0:t.description}));let r=Promise.resolve(e instanceof Function?e():e),i=n!==void 0,a,o=r.then(async e=>{if(a=[`resolve`,e],G.isValidElement(e))i=!1,this.create({id:n,type:`default`,message:e});else if(XKe(e)&&!e.ok){i=!1;let r=typeof t.error==`function`?await t.error(`HTTP error! status: ${e.status}`):t.error,a=typeof t.description==`function`?await t.description(`HTTP error! status: ${e.status}`):t.description,o=typeof r==`object`&&!G.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}else if(e instanceof Error){i=!1;let r=typeof t.error==`function`?await t.error(e):t.error,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!G.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}else if(t.success!==void 0){i=!1;let r=typeof t.success==`function`?await t.success(e):t.success,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!G.isValidElement(r)?r:{message:r};this.create({id:n,type:`success`,description:a,...o})}}).catch(async e=>{if(a=[`reject`,e],t.error!==void 0){i=!1;let r=typeof t.error==`function`?await t.error(e):t.error,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!G.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}}).finally(()=>{i&&(this.dismiss(n),n=void 0),t.finally==null||t.finally.call(t)}),s=()=>new Promise((e,t)=>o.then(()=>a[0]===`reject`?t(a[1]):e(a[1])).catch(t));return typeof n!=`string`&&typeof n!=`number`?{unwrap:s}:Object.assign(n,{unwrap:s})},this.custom=(e,t)=>{let n=t?.id||JKe++;return this.create({jsx:e(n),id:n,...t}),n},this.getActiveToasts=()=>this.toasts.filter(e=>!this.dismissedToasts.has(e.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},YKe=(e,t)=>{let n=t?.id||JKe++;return Qx.addToast({title:e,...t,id:n}),n},XKe=e=>e&&typeof e==`object`&&`ok`in e&&typeof e.ok==`boolean`&&`status`in e&&typeof e.status==`number`,$x=Object.assign(YKe,{success:Qx.success,info:Qx.info,warning:Qx.warning,error:Qx.error,custom:Qx.custom,message:Qx.message,promise:Qx.promise,dismiss:Qx.dismiss,loading:Qx.loading},{getHistory:()=>Qx.toasts,getToasts:()=>Qx.getActiveToasts()});RKe(`[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}`);function eS(e){return e.label!==void 0}var ZKe=3,QKe=`24px`,$Ke=`16px`,eqe=4e3,tqe=356,nqe=14,rqe=45,iqe=200;function tS(...e){return e.filter(Boolean).join(` `)}function aqe(e){let[t,n]=e.split(`-`),r=[];return t&&r.push(t),n&&r.push(n),r}var oqe=e=>{let{invert:t,toast:n,unstyled:r,interacting:i,setHeights:a,visibleToasts:o,heights:s,index:c,toasts:l,expanded:u,removeToast:d,defaultRichColors:f,closeButton:p,style:m,cancelButtonStyle:h,actionButtonStyle:g,className:_=``,descriptionClassName:v=``,duration:y,position:b,gap:x,expandByDefault:S,classNames:C,icons:w,closeButtonAriaLabel:T=`Close toast`}=e,[E,D]=G.useState(null),[O,k]=G.useState(null),[A,j]=G.useState(!1),[M,N]=G.useState(!1),[P,F]=G.useState(!1),[I,L]=G.useState(!1),[R,z]=G.useState(!1),[B,V]=G.useState(0),[H,ee]=G.useState(0),te=G.useRef(n.duration||y||eqe),U=G.useRef(null),W=G.useRef(null),ne=c===0,re=c+1<=o,ie=n.type,ae=n.dismissible!==!1,oe=n.className||``,se=n.descriptionClassName||``,ce=G.useMemo(()=>s.findIndex(e=>e.toastId===n.id)||0,[s,n.id]),le=G.useMemo(()=>n.closeButton??p,[n.closeButton,p]),ue=G.useMemo(()=>n.duration||y||eqe,[n.duration,y]),de=G.useRef(0),fe=G.useRef(0),pe=G.useRef(0),me=G.useRef(null),[he,ge]=b.split(`-`),_e=G.useMemo(()=>s.reduce((e,t,n)=>n>=ce?e:e+t.height,0),[s,ce]),ve=qKe(),ye=n.invert||t,be=ie===`loading`;fe.current=G.useMemo(()=>ce*x+_e,[ce,_e]),G.useEffect(()=>{te.current=ue},[ue]),G.useEffect(()=>{j(!0)},[]),G.useEffect(()=>{let e=W.current;if(e){let t=e.getBoundingClientRect().height;return ee(t),a(e=>[{toastId:n.id,height:t,position:n.position},...e]),()=>a(e=>e.filter(e=>e.toastId!==n.id))}},[a,n.id]),G.useLayoutEffect(()=>{if(!A)return;let e=W.current,t=e.style.height;e.style.height=`auto`;let r=e.getBoundingClientRect().height;e.style.height=t,ee(r),a(e=>e.find(e=>e.toastId===n.id)?e.map(e=>e.toastId===n.id?{...e,height:r}:e):[{toastId:n.id,height:r,position:n.position},...e])},[A,n.title,n.description,a,n.id,n.jsx,n.action,n.cancel]);let xe=G.useCallback(()=>{N(!0),V(fe.current),a(e=>e.filter(e=>e.toastId!==n.id)),setTimeout(()=>{d(n)},iqe)},[n,d,a,fe]);G.useEffect(()=>{if(n.promise&&ie===`loading`||n.duration===1/0||n.type===`loading`)return;let e;return u||i||ve?(()=>{if(pe.current<de.current){let e=new Date().getTime()-de.current;te.current-=e}pe.current=new Date().getTime()})():te.current!==1/0&&(de.current=new Date().getTime(),e=setTimeout(()=>{n.onAutoClose==null||n.onAutoClose.call(n,n),xe()},te.current)),()=>clearTimeout(e)},[u,i,n,ie,ve,xe]),G.useEffect(()=>{n.delete&&(xe(),n.onDismiss==null||n.onDismiss.call(n,n))},[xe,n.delete]);function Se(){return w?.loading?G.createElement(`div`,{className:tS(C?.loader,n?.classNames?.loader,`sonner-loader`),"data-visible":ie===`loading`},w.loading):G.createElement(VKe,{className:tS(C?.loader,n?.classNames?.loader),visible:ie===`loading`})}let Ce=n.icon||w?.[ie]||zKe(ie);return G.createElement(`li`,{tabIndex:0,ref:W,className:tS(_,oe,C?.toast,n?.classNames?.toast,C?.default,C?.[ie],n?.classNames?.[ie]),"data-sonner-toast":``,"data-rich-colors":n.richColors??f,"data-styled":!(n.jsx||n.unstyled||r),"data-mounted":A,"data-promise":!!n.promise,"data-swiped":R,"data-removed":M,"data-visible":re,"data-y-position":he,"data-x-position":ge,"data-index":c,"data-front":ne,"data-swiping":P,"data-dismissible":ae,"data-type":ie,"data-invert":ye,"data-swipe-out":I,"data-swipe-direction":O,"data-expanded":!!(u||S&&A),"data-testid":n.testId,style:{"--index":c,"--toasts-before":c,"--z-index":l.length-c,"--offset":`${M?B:fe.current}px`,"--initial-height":S?`auto`:`${H}px`,...m,...n.style},onDragEnd:()=>{F(!1),D(null),me.current=null},onPointerDown:e=>{e.button!==2&&!be&&ae&&(U.current=new Date,V(fe.current),e.target.setPointerCapture(e.pointerId),e.target.tagName!==`BUTTON`&&(F(!0),me.current={x:e.clientX,y:e.clientY}))},onPointerUp:()=>{if(I||!ae)return;me.current=null;let e=Number(W.current?.style.getPropertyValue(`--swipe-amount-x`).replace(`px`,``)||0),t=Number(W.current?.style.getPropertyValue(`--swipe-amount-y`).replace(`px`,``)||0),r=new Date().getTime()-U.current?.getTime(),i=E===`x`?e:t,a=Math.abs(i)/r;if(Math.abs(i)>=rqe||a>.11)V(fe.current),n.onDismiss==null||n.onDismiss.call(n,n),k(E===`x`?e>0?`right`:`left`:t>0?`down`:`up`),xe(),L(!0);else{var o,s;(o=W.current)==null||o.style.setProperty(`--swipe-amount-x`,`0px`),(s=W.current)==null||s.style.setProperty(`--swipe-amount-y`,`0px`),z(!1),F(!1),D(null)}},onPointerMove:t=>{var n,r;if(!me.current||!ae||window.getSelection()?.toString().length>0)return;let i=t.clientY-me.current.y,a=t.clientX-me.current.x,o=e.swipeDirections??aqe(b);!E&&(Math.abs(a)>1||Math.abs(i)>1)&&D(Math.abs(a)>Math.abs(i)?`x`:`y`);let s={x:0,y:0},c=e=>1/(1.5+Math.abs(e)/20);if(E===`y`){if(o.includes(`top`)||o.includes(`bottom`)){if(o.includes(`top`)&&i<0||o.includes(`bottom`)&&i>0)s.y=i;else{let e=i*c(i);s.y=Math.abs(e)<Math.abs(i)?e:i}}}else if(E===`x`&&(o.includes(`left`)||o.includes(`right`))){if(o.includes(`left`)&&a<0||o.includes(`right`)&&a>0)s.x=a;else{let e=a*c(a);s.x=Math.abs(e)<Math.abs(a)?e:a}}(Math.abs(s.x)>0||Math.abs(s.y)>0)&&z(!0),(n=W.current)==null||n.style.setProperty(`--swipe-amount-x`,`${s.x}px`),(r=W.current)==null||r.style.setProperty(`--swipe-amount-y`,`${s.y}px`)}},le&&!n.jsx&&ie!==`loading`?G.createElement(`button`,{"aria-label":T,"data-disabled":be,"data-close-button":!0,onClick:be||!ae?()=>{}:()=>{xe(),n.onDismiss==null||n.onDismiss.call(n,n)},className:tS(C?.closeButton,n?.classNames?.closeButton)},w?.close??KKe):null,(ie||n.icon||n.promise)&&n.icon!==null&&(w?.[ie]!==null||n.icon)?G.createElement(`div`,{"data-icon":``,className:tS(C?.icon,n?.classNames?.icon)},n.promise||n.type===`loading`&&!n.icon?n.icon||Se():null,n.type===`loading`?null:Ce):null,G.createElement(`div`,{"data-content":``,className:tS(C?.content,n?.classNames?.content)},G.createElement(`div`,{"data-title":``,className:tS(C?.title,n?.classNames?.title)},n.jsx?n.jsx:typeof n.title==`function`?n.title():n.title),n.description?G.createElement(`div`,{"data-description":``,className:tS(v,se,C?.description,n?.classNames?.description)},typeof n.description==`function`?n.description():n.description):null),G.isValidElement(n.cancel)?n.cancel:n.cancel&&eS(n.cancel)?G.createElement(`button`,{"data-button":!0,"data-cancel":!0,style:n.cancelButtonStyle||h,onClick:e=>{eS(n.cancel)&&ae&&(n.cancel.onClick==null||n.cancel.onClick.call(n.cancel,e),xe())},className:tS(C?.cancelButton,n?.classNames?.cancelButton)},n.cancel.label):null,G.isValidElement(n.action)?n.action:n.action&&eS(n.action)?G.createElement(`button`,{"data-button":!0,"data-action":!0,style:n.actionButtonStyle||g,onClick:e=>{eS(n.action)&&(n.action.onClick==null||n.action.onClick.call(n.action,e),e.defaultPrevented||xe())},className:tS(C?.actionButton,n?.classNames?.actionButton)},n.action.label):null)};function sqe(){if(typeof window>`u`||typeof document>`u`)return`ltr`;let e=document.documentElement.getAttribute(`dir`);return e===`auto`||!e?window.getComputedStyle(document.documentElement).direction:e}function cqe(e,t){let n={};return[e,t].forEach((e,t)=>{let r=t===1,i=r?`--mobile-offset`:`--offset`,a=r?$Ke:QKe;function o(e){[`top`,`right`,`bottom`,`left`].forEach(t=>{n[`${i}-${t}`]=typeof e==`number`?`${e}px`:e})}typeof e==`number`||typeof e==`string`?o(e):typeof e==`object`?[`top`,`right`,`bottom`,`left`].forEach(t=>{e[t]===void 0?n[`${i}-${t}`]=a:n[`${i}-${t}`]=typeof e[t]==`number`?`${e[t]}px`:e[t]}):o(a)}),n}var lqe=G.forwardRef(function(e,t){let{id:n,invert:r,position:i=`bottom-right`,hotkey:a=[`altKey`,`KeyT`],expand:o,closeButton:s,className:c,offset:l,mobileOffset:u,theme:d=`light`,richColors:f,duration:p,style:m,visibleToasts:h=ZKe,toastOptions:g,dir:_=sqe(),gap:v=nqe,icons:y,containerAriaLabel:b=`Notifications`}=e,[x,S]=G.useState([]),C=G.useMemo(()=>n?x.filter(e=>e.toasterId===n):x.filter(e=>!e.toasterId),[x,n]),w=G.useMemo(()=>Array.from(new Set([i].concat(C.filter(e=>e.position).map(e=>e.position)))),[C,i]),[T,E]=G.useState([]),[D,O]=G.useState(!1),[k,A]=G.useState(!1),[j,M]=G.useState(d===`system`?typeof window<`u`&&window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`:d),N=G.useRef(null),P=a.join(`+`).replace(/Key/g,``).replace(/Digit/g,``),F=G.useRef(null),I=G.useRef(!1),L=G.useCallback(e=>{S(t=>(t.find(t=>t.id===e.id)?.delete||Qx.dismiss(e.id),t.filter(({id:t})=>t!==e.id)))},[]);return G.useEffect(()=>Qx.subscribe(e=>{e.dismiss?requestAnimationFrame(()=>{S(t=>t.map(t=>t.id===e.id?{...t,delete:!0}:t))}):setTimeout(()=>{Pt.flushSync(()=>{S(t=>{let n=t.findIndex(t=>t.id===e.id);return n===-1?[e,...t]:[...t.slice(0,n),{...t[n],...e},...t.slice(n+1)]})})})}),[x]),G.useEffect(()=>{if(d!==`system`){M(d);return}if(d===`system`&&(window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?M(`dark`):M(`light`)),typeof window>`u`)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`);try{e.addEventListener(`change`,({matches:e})=>{M(e?`dark`:`light`)})}catch{e.addListener(({matches:e})=>{try{M(e?`dark`:`light`)}catch(e){console.error(e)}})}},[d]),G.useEffect(()=>{x.length<=1&&O(!1)},[x]),G.useEffect(()=>{let e=e=>{if(a.every(t=>e[t]||e.code===t)){var t;O(!0),(t=N.current)==null||t.focus()}e.code===`Escape`&&(document.activeElement===N.current||N.current?.contains(document.activeElement))&&O(!1)};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[a]),G.useEffect(()=>{if(N.current)return()=>{F.current&&(F.current.focus({preventScroll:!0}),F.current=null,I.current=!1)}},[N.current]),G.createElement(`section`,{ref:t,"aria-label":`${b} ${P}`,tabIndex:-1,"aria-live":`polite`,"aria-relevant":`additions text`,"aria-atomic":`false`,suppressHydrationWarning:!0},w.map((t,n)=>{let[i,a]=t.split(`-`);return C.length?G.createElement(`ol`,{key:t,dir:_===`auto`?sqe():_,tabIndex:-1,ref:N,className:c,"data-sonner-toaster":!0,"data-sonner-theme":j,"data-y-position":i,"data-x-position":a,style:{"--front-toast-height":`${T[0]?.height||0}px`,"--width":`${tqe}px`,"--gap":`${v}px`,...m,...cqe(l,u)},onBlur:e=>{I.current&&!e.currentTarget.contains(e.relatedTarget)&&(I.current=!1,F.current&&=(F.current.focus({preventScroll:!0}),null))},onFocus:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||I.current||(I.current=!0,F.current=e.relatedTarget)},onMouseEnter:()=>O(!0),onMouseMove:()=>O(!0),onMouseLeave:()=>{k||O(!1)},onDragEnd:()=>O(!1),onPointerDown:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||A(!0)},onPointerUp:()=>A(!1)},C.filter(e=>!e.position&&n===0||e.position===t).map((n,i)=>G.createElement(oqe,{key:n.id,icons:y,index:i,toast:n,defaultRichColors:f,duration:g?.duration??p,className:g?.className,descriptionClassName:g?.descriptionClassName,invert:r,visibleToasts:h,closeButton:g?.closeButton??s,interacting:k,position:t,style:g?.style,unstyled:g?.unstyled,classNames:g?.classNames,cancelButtonStyle:g?.cancelButtonStyle,actionButtonStyle:g?.actionButtonStyle,closeButtonAriaLabel:g?.closeButtonAriaLabel,removeToast:L,toasts:C.filter(e=>e.position==n.position),heights:T.filter(e=>e.position==n.position),setHeights:E,expandByDefault:o,gap:v,expanded:D,swipeDirections:e.swipeDirections}))):null}))}),nS=(e,t)=>Array.isArray(e)?e.map(t):t(e);function uqe(e){return!e||typeof e!=`object`||!(`label`in e)?e:{...e,label:(0,K.jsx)(EKe,{variant:`link`,children:e.label})}}function rS(e){let t={...e};return e.action!==void 0&&(t.action=uqe(e.action)),e.cancel!==void 0&&(t.cancel=uqe(e.cancel)),t}var iS=(e,t={})=>{if(Array.isArray(e))return e.map(e=>$x(e,rS(t)));if((0,G.isValidElement)(e)||typeof e==`string`)return $x(e,rS(t));throw Error(`Invalid message type`)};iS.success=(e,t={})=>nS(e,e=>$x.success(e,rS(t))),iS.error=(e,t={})=>nS(e,e=>$x.error(e,rS(t))),iS.warning=(e,t={})=>nS(e,e=>$x.warning(e,rS(t))),iS.info=(e,t={})=>nS(e,e=>$x.info(e,rS(t))),iS.custom=(e,t={})=>$x(e,rS(t)),iS.dismiss=e=>$x.dismiss(e),iS.promise=({myPromise:e,loadingMessage:t,successMessage:n,errorMessage:r,onSuccess:i,onError:a,options:o={}})=>$x.promise(e,{loading:t??`Loading...`,success:e=>(i?.(e),n),error:e=>(a?.(e),r||(e instanceof Error?e.message:`Error...`)),...rS(o)});function dqe(e){let t=getComputedStyle(e),n=Array.from(e.children).reduce((e,t)=>{let n=getComputedStyle(t);return e+Number.parseFloat(n.height)+Number.parseFloat(n.marginTop)+Number.parseFloat(n.marginBottom)},0)+Number.parseFloat(t.rowGap)*Math.max(0,e.childElementCount-1)+Number.parseFloat(t.paddingTop)+Number.parseFloat(t.paddingBottom);return Math.round(n)>e.clientHeight}function fqe(e){let t=Array.from(e.querySelectorAll(`[data-content]`),e=>({content:e,overflows:dqe(e)}));return()=>{for(let{content:e,overflows:n}of t)n&&e.tabIndex!==0?e.tabIndex=0:!n&&e.hasAttribute(`tabindex`)&&e.removeAttribute(`tabindex`)}}var pqe=64;function mqe(e){let t=getComputedStyle(e);if(e.style.height&&e.style.height!==`auto`)return Number.parseFloat(t.height);let n=e.getBoundingClientRect(),r=t.transform===`none`?1:new DOMMatrixReadOnly(t.transform).d,i=Array.from(e.children).reduce((e,t)=>{let i=getComputedStyle(t);if(i.position===`absolute`||i.position===`fixed`||i.display===`none`)return e;let a=i.marginBottom===`auto`?0:Number.parseFloat(i.marginBottom),o=t.getBoundingClientRect(),s=r>0?(o.bottom-n.top)/r:r<0?(n.bottom-o.top)/-r:t instanceof HTMLElement?t.offsetTop+t.offsetHeight:0;return Math.max(e,s+a)},0),a=Number.parseFloat(t.minHeight),o=Number.parseFloat(t.maxHeight);return Math.max(Number.isFinite(a)?a:0,Math.min(Number.isFinite(o)?o:1/0,i+Number.parseFloat(t.paddingBottom)+Number.parseFloat(t.borderBottomWidth)))}function hqe(e,t,n,r){return e.dataset.promise===`true`&&e.dataset.front===`true`&&(e.dataset.type===`success`||e.dataset.type===`error`)&&(t.type===`loading`||n)&&r>.5}function gqe(e){let t=e.trim();return Number.parseFloat(t)*(t.endsWith(`ms`)?1:1e3)}function _qe(e,t,n){let r=getComputedStyle(e),i=gqe(r.getPropertyValue(`--duration-normal`)),a=r.getPropertyValue(`--toast-settle-ease`).trim(),o=[e.animate([{translate:`0 ${e.dataset.yPosition===`bottom`?t:0}px`,clipPath:`inset(0 0 ${t}px 0 round ${n})`},{translate:`0 0`,clipPath:`inset(0 round ${n})`}],{duration:i,easing:a})];for(let t of e.querySelectorAll(`[data-description], :scope > [data-content] ~ *`))o.push(t.animate([{opacity:0},{opacity:1}],{duration:i,easing:a}));return o}function vqe(e){let t=new Map;return{measure:n=>{let r=Array.from(n.querySelectorAll(`[data-sonner-toaster]`),e=>{let n=Number.parseFloat(getComputedStyle(e).getPropertyValue(`--gap`)),r=0;return{stack:e,notifications:Array.from(e.querySelectorAll(`:scope > [data-sonner-toast]`)).filter(e=>e.dataset.removed!==`true`&&e.getClientRects().length>0).map(e=>{let i=Math.round(mqe(e)*pqe)/pqe,a=r;r+=i+n;let o=t.get(e),s=getComputedStyle(e),c=s.translate===`none`?0:Number.parseFloat(s.translate.split(` `)[1]??`0`);return{notification:e,height:i,position:a,previous:o,reveal:o?i-o.height+c:0,radius:s.borderRadius}})}});return()=>{for(let{stack:n,notifications:i}of r){n.style.setProperty(`--mastra-front-height`,`${i[0]?.height??0}px`),n.setAttribute(`data-mastra-measured`,``);for(let{notification:n,height:r,position:a,previous:o,reveal:s,radius:c}of i){if(n.style.setProperty(`--mastra-toast-height`,`${r}px`),n.style.setProperty(`--mastra-toast-offset`,`${a}px`),n.setAttribute(`data-mastra-measured`,``),o?.height===r&&o.type===n.dataset.type)continue;let i=o?.animations.some(e=>e.playState===`running`)??!1;for(let e of o?.animations??[])e.cancel();let l=o&&!e.matches&&hqe(n,o,i,s)?_qe(n,s,c):[];t.set(n,{height:r,type:n.dataset.type,animations:l})}}for(let[e,r]of t)if(!(n.contains(e)&&e.dataset.removed!==`true`)){for(let e of r.animations)e.cancel();t.delete(e)}}},cancelAnimations:()=>{for(let e of t.values())for(let t of e.animations)t.cancel()}}}function yqe(e){if(!e||typeof ResizeObserver>`u`)return;let t=matchMedia(`(prefers-reduced-motion: reduce)`),n=vqe(t);t.addEventListener(`change`,n.cancelAnimations);let r=()=>{let t=fqe(e),r=n.measure(e);t(),r()},i=new ResizeObserver(r),a=()=>{i.disconnect();for(let t of e.querySelectorAll(`[data-sonner-toast] > *`))i.observe(t);r()},o=new MutationObserver(a);return o.observe(e,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:[`data-removed`]}),a(),()=>{o.disconnect(),i.disconnect(),t.removeEventListener(`change`,n.cancelAnimations),n.cancelAnimations()}}var bqe={success:(0,K.jsx)(LKe,{"aria-hidden":!0}),error:(0,K.jsx)(Xx,{"aria-hidden":!0}),warning:(0,K.jsx)(Zx,{"aria-hidden":!0}),info:(0,K.jsx)(Yx,{"aria-hidden":!0})},xqe=Lx({variant:`link`}),aS=({className:e,toastOptions:t,icons:n,variant:r=`default`,...i})=>(0,K.jsx)(lqe,{ref:yqe,...i,closeButton:!0,icons:{...bqe,loading:(0,K.jsx)(`span`,{"aria-hidden":!0,className:`flex`,children:(0,K.jsx)(IKe,{size:`sm`,className:c(`toast-promise-loader w-5`,{"toast-promise-success":n?.success===void 0,"toast-promise-error":n?.error===void 0})})}),...n},className:c(`mastra-toaster`,r===`neutral`&&`mastra-toaster-neutral`,e),toastOptions:{duration:5e3,...t,classNames:{actionButton:xqe,cancelButton:xqe,...t?.classNames}}});function oS({children:e,side:t=`top`,align:n,contentClassName:r,...i}){let a=G.useId();return(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{render:(0,K.jsx)(`button`,{type:`button`,...i,"aria-describedby":a,className:c(`flex shrink-0 cursor-help items-center rounded-full text-placeholder/80 hover:text-muted-foreground focus-visible:text-muted-foreground`,A,p)}),children:(0,K.jsx)(Dx,{size:`xs`,children:(0,K.jsx)(Yx,{})})}),(0,K.jsx)(Tx,{id:a,keepMounted:!0,side:t,align:n,className:c(`max-w-64`,r),children:e})]})}var sS=U(`IconArrowLeft`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M10 6L4 12L10 18`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M5 12H20`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),3),cS=U(`IconEyeOpen`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M15 12C15 13.6569 13.6569 15 12 15C10.3431 15 9 13.6569 9 12C9 10.3431 10.3431 9 12 9C13.6569 9 15 10.3431 15 12Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M21.4974 11.0946C16.66 2.96839 7.33998 2.96848 2.50257 11.0947C2.17069 11.6523 2.17069 12.3479 2.50257 12.9054C7.33998 21.0316 16.66 21.0315 21.4974 12.9053C21.8293 12.3477 21.8293 11.6521 21.4974 11.0946Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]})),lS=e=>{let t=Y();return T_({queryKey:[`builder-settings`],queryFn:()=>t.getBuilderSettings(),enabled:e?.enabled??!0})},Sqe={active:!1},uS=()=>{let{data:e}=lS();return e?.modelPolicy??Sqe},Cqe={visibleTools:null,visibleAgents:null,visibleWorkflows:null},wqe=()=>{let{data:e}=lS(),t=e?.picker;return(0,G.useMemo)(()=>t?{visibleTools:t.visibleTools===null?null:new Set(t.visibleTools),visibleAgents:t.visibleAgents===null?null:new Set(t.visibleAgents),visibleWorkflows:t.visibleWorkflows===null?null:new Set(t.visibleWorkflows)}:Cqe,[t])};async function Tqe(e,{roleId:t}){let{baseUrl:n=``,apiPrefix:r,headers:i={}}=e.options||{},a=(r??`/api`).trim(),o=(a===``?``:a.startsWith(`/`)?a:`/${a}`).replace(/\/+$/,``),s=await fetch(`${n}${o}/auth/roles/${encodeURIComponent(t)}/permissions`,{credentials:`include`,headers:{...i,"Content-Type":`application/json`}});if(!s.ok)throw Error(`Failed to fetch role permissions: ${s.status}`);return s.json()}var Eqe=(0,G.createContext)(null);function Dqe({children:e}){let t=Y(),[n,r]=(0,G.useState)(null),[i,a]=(0,G.useState)(null),{mutateAsync:o,reset:s,isPending:c}=D_({mutationFn:async({role:e})=>({role:e,permissions:(await Tqe(t,{roleId:e.id})).permissions}),onSuccess:({role:e,permissions:t})=>{r(e),a(t)}}),l=(0,G.useMemo)(()=>({impersonatedRole:n,impersonatedPermissions:i,isImpersonating:n!==null,startImpersonation:async e=>{await o({role:e})},stopImpersonation:()=>{r(null),a(null),s()},isSwitching:c}),[n,i,c,o,s]);return(0,K.jsx)(Eqe.Provider,{value:l,children:e})}function dS(){return(0,G.useContext)(Eqe)||{impersonatedRole:null,impersonatedPermissions:null,isImpersonating:!1,startImpersonation:async()=>{},stopImpersonation:()=>{},isSwitching:!1}}function Oqe(e,t){if(e===`*`)return!0;let n=e.split(`:`),r=t.split(`:`);if(n.length<2||r.length<2)return e===t;let[i,a,o]=n,[s,c,l]=r;return i===`*`?a===`*`?!0:a===c?o===void 0||o===l:!1:i===s&&(a===`*`||a===c)?o===void 0||o===l:!1}function kqe(e,t){return e.some(e=>Oqe(e,t))}function fS(){let{data:e,isLoading:t}=A_(),{isImpersonating:n,impersonatedPermissions:r,impersonatedRole:i}=dS(),a=e&&k_(e),o=a?e.access:null,s=a?e.capabilities.rbac:!1,c=n&&i?[i.id]:o?.roles??[],l=n&&r?r:o?.permissions??[],u=e=>!s&&!n||kqe(l,e);return{roles:c,permissions:l,isLoading:t,isAuthenticated:!!a,rbacEnabled:s,hasPermission:e=>u(e),hasAllPermissions:e=>!s&&!n||e.every(e=>kqe(l,e)),hasAnyPermission:e=>!s&&!n||e.some(e=>kqe(l,e)),hasRole:e=>!s&&!n||c.includes(e),canEdit:e=>u(`${e}:write`),canDelete:e=>u(`${e}:delete`),canExecute:e=>u(`${e}:execute`)}}function pS(){let{hasAnyPermission:e,hasPermission:t,rbacEnabled:n}=fS(),r=!n||e([`stored-agents:read`,`stored-agents:write`]),i=!n||e([`stored-agents:read`,`stored-agents:write`]),a=!n||t(`stored-agents:write`),o=!n||e([`stored-agents:read`,`stored-agents:write`]),s=!n||t(`stored-skills:read`),c=!n||e([`stored-agents:read`,`stored-skills:read`]),{data:l,isLoading:u,error:d}=lS({enabled:i}),f=l?.enabled===!0,p=l?.features?.agent!==void 0;return{isLoading:i&&u,error:i?d:null,denialReason:r?d?`error`:!f||!p?`not-configured`:null:`permission-denied`,isBuilderEnabled:f,hasAgentFeature:p,hasRequiredPermissions:r,canAccessAgentBuilder:r&&f&&p,canWrite:a,canExecute:o,canManageSkills:s,canUseFavorites:c,agentFeatures:l?.features?.agent}}var Aqe=[`/swagger-ui`,`/openapi.json`],mS=(0,G.forwardRef)(({children:e,href:t,...n},r)=>t&&Aqe.some(e=>t.startsWith(e))?(0,K.jsx)(`a`,{ref:r,href:t,...n,children:e}):(0,K.jsx)(Lv,{ref:r,to:t??``,...n,children:e})),jqe=({paths:e})=>{let t=Dv(),{data:n,isLoading:r}=A_();if(r)return(0,K.jsx)(`div`,{className:`flex h-screen w-full items-center justify-center`,children:(0,K.jsx)(It,{})});if(n?.enabled&&!k_(n)){let e=`${t.pathname}${t.search}${t.hash}`,n=`/login?redirect=${encodeURIComponent(e)}`;return(0,K.jsx)(Fv,{to:n,replace:!0})}return(0,K.jsx)(Mqe,{paths:e})},Mqe=({paths:e})=>{let t=Ov(),{isLoading:n,denialReason:r,hasAgentFeature:i}=pS();return n?(0,K.jsx)(`div`,{className:`flex h-screen w-full items-center justify-center`,children:(0,K.jsx)(It,{})}):r===`permission-denied`?(0,K.jsx)(Nqe,{}):r===`error`?(0,K.jsx)(`div`,{className:`flex h-screen items-center justify-center`,children:(0,K.jsx)(Jx,{titleSlot:`Error`,descriptionSlot:`Failed to load Agent Builder configuration.`})}):r===`not-configured`?(0,K.jsx)(`div`,{className:`flex h-screen items-center justify-center`,children:(0,K.jsx)(Jx,{titleSlot:`Agent Builder Not Configured`,descriptionSlot:`Agent Builder is not enabled. Contact your administrator to enable this feature.`})}):i?(0,K.jsx)(Sx,{children:(0,K.jsxs)(on,{Link:mS,navigate:t,paths:e,children:[(0,K.jsx)(Iv,{}),(0,K.jsx)(aS,{position:`bottom-right`})]})}):(0,K.jsx)(`div`,{className:`flex h-screen items-center justify-center`,children:(0,K.jsx)(Jx,{titleSlot:`No Features Enabled`,descriptionSlot:`No Agent Builder features are configured.`})})};function Nqe(){let{isImpersonating:e,impersonatedRole:t,stopImpersonation:n}=dS();return(0,K.jsx)(`div`,{className:`flex h-screen items-center justify-center`,children:(0,K.jsxs)(`div`,{className:`flex flex-col items-center gap-4`,children:[(0,K.jsx)(Jx,{titleSlot:`Access Denied`,descriptionSlot:`You don't have permission to access the Agent Builder.`}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(X,{render:(0,K.jsx)(mS,{href:`/agents`}),size:`sm`,icon:(0,K.jsx)(sS,{}),children:`Back to Studio`}),e&&(0,K.jsxs)(X,{variant:`default`,size:`sm`,onClick:n,icon:(0,K.jsx)(cS,{}),children:[`Exit `,t?.name,` preview`]})]})]})})}var hS=[{route:`/agents`,permission:`agents:read`,name:`Agents`},{route:`/workflows`,permission:`workflows:read`,name:`Workflows`},{route:`/metrics`,permission:`observability:read`,name:`Metrics`},{route:`/intelligence`,permission:`observability:read`,name:`Intelligence`},{route:`/traces`,permission:`observability:read`,name:`Traces`},{route:`/spans`,permission:`observability:read`,name:`Spans`},{route:`/threads`,permission:`observability:read`,name:`Threads`},{route:`/logs`,permission:`logs:read`,name:`Logs`},{route:`/scorers`,permission:`scores:read`,name:`Scorers`},{route:`/datasets`,permission:[`datasets:read`],name:`Datasets`},{route:`/knowledge`,permission:`knowledge:read`,name:`Knowledge`},{route:`/experiments`,permission:[`datasets:read`],name:`Experiments`},{route:`/experiments/review-queue`,permission:[`datasets:read`],name:`Review Queue`},{route:`/tools`,permission:`tools:read`,name:`Tools`},{route:`/mcps`,permission:`mcp:read`,name:`MCP Servers`},{route:`/processors`,permission:`processors:read`,name:`Processors`},{route:`/prompts`,permission:`stored-prompt-blocks:read`,name:`Prompts`},{route:`/workspaces`,permission:`workspaces:read`,name:`Workspaces`},{route:`/settings`,permission:`public`,name:`Settings`},{route:`/resources`,permission:`public`,name:`Resources`},{route:`/connections`,permission:`public`,name:`Connections`}];function Pqe(e){return[...new Set(e.flatMap(e=>Array.isArray(e.permission)?e.permission:[e.permission]).filter(e=>e!==`public`))]}var Fqe=Pqe(hS);function gS(e){let t=hS.find(t=>t.route===e);return t?t.permission:hS.find(t=>e.startsWith(t.route+`/`))?.permission}function _S(e,t,n){return!e||e===`public`?!0:Array.isArray(e)?n(e):t(e)}function Iqe(e,t){let n=new Set;for(let{route:r,permission:i}of hS){if(i===`public`)continue;let a=Array.isArray(i)?i.sort().join(`,`):i;if(!n.has(a)&&(n.add(a),_S(i,e,t)))return r}return`/resources`}function Lqe({children:e}){let{pathname:t}=Dv(),{hasPermission:n,hasAnyPermission:r,rbacEnabled:i,isAuthenticated:a,isLoading:o}=fS();if(o)return(0,K.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,K.jsx)(It,{})});if(!i||!a)return(0,K.jsx)(K.Fragment,{children:e});let s=gS(t);if(!s||s===`public`||_S(s,n,r))return(0,K.jsx)(K.Fragment,{children:e});let c=Iqe(n,r);return c===t?(0,K.jsx)(K.Fragment,{children:e}):(0,K.jsx)(Fv,{to:c,replace:!0})}var vS=U(`IconArrowRotateCounterClockwise`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M4.4834 14.6667C5.58163 17.7738 8.54493 20 12.0282 20C16.4465 20 20.0282 16.4183 20.0282 12C20.0282 7.58172 16.4465 4 12.0282 4C8.93224 4 6.99986 5.5 4.99986 8`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M5 4V8H9`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]})),Rqe=e=>{let t=e.trim().replace(/\/+/g,`/`).replace(/\/$/,``);return t?t.startsWith(`/`)?t:`/${t}`:``},zqe=(e,t)=>`${e.replace(/\/+$/,``)}${Rqe(t)}/auth/capabilities`,Bqe=async(e,t,n)=>{try{let r=await fetch(zqe(e,t),{headers:n});if(!r.ok)return{status:`inactive`};let i=await r.json();return{status:typeof i==`object`&&i&&typeof i.enabled==`boolean`?`active`:`inactive`}}catch{return{status:`inactive`}}},Vqe=(e=`http://localhost:4111`,t=`/api`,n)=>T_({queryKey:[`mastra-instance-status`,e,t,n],queryFn:()=>Bqe(e,t,n),retry:!1}),Hqe=(0,G.createContext)({baseUrl:``,headers:{},apiPrefix:void 0,isLoading:!1,setConfig:()=>{}}),yS=()=>(0,G.useContext)(Hqe),bS=`mastra-studio-config`,Uqe=`auth_header`,Wqe=`Authorization`,Gqe=()=>{if(typeof window>`u`)return{};let e=new URL(window.location.href).searchParams.get(Uqe);return e?{[Wqe]:e}:{}},Kqe=()=>{if(typeof window>`u`)return;let e=new URL(window.location.href);e.searchParams.has(Uqe)&&(e.searchParams.delete(Uqe),window.history.replaceState(window.history.state,``,`${e.pathname}${e.search}${e.hash}`))},qqe=e=>{let{[Wqe]:t,...n}=e.headers;return{...e,headers:n}},Jqe=({children:e,endpoint:t=`http://localhost:4111`,defaultApiPrefix:n=`/api`})=>{let[r]=(0,G.useState)(Gqe),i=Object.keys(r).length>0,{data:a,isLoading:o,error:s}=Vqe(t,n,r),[c,l]=(0,G.useState)({baseUrl:``,headers:r,apiPrefix:void 0,isLoading:!0});(0,G.useEffect)(()=>{Kqe()},[]),(0,G.useLayoutEffect)(()=>{if(s&&!o)return l({baseUrl:``,headers:r,apiPrefix:void 0,isLoading:!1});if(!a?.status)return;let e=localStorage.getItem(bS);if(e){let t=JSON.parse(e);if(typeof t==`object`&&t){let e={...t,headers:{...t.headers??{},...r},apiPrefix:t.apiPrefix??n};return i&&localStorage.setItem(bS,JSON.stringify(qqe(e))),l({...e,isLoading:!1})}}if(a.status===`active`){let e={baseUrl:t,headers:r,apiPrefix:n};return i&&localStorage.setItem(bS,JSON.stringify(qqe(e))),l({...e,isLoading:!1})}return l({baseUrl:``,headers:r,apiPrefix:void 0,isLoading:!1})},[a,t,n,o,s,r,i]);let u=e=>{l(t=>{let n={...t,...e},r=i?qqe(n):n;return localStorage.setItem(bS,JSON.stringify(r)),n})};return(0,K.jsx)(Hqe.Provider,{value:{...c,setConfig:u},children:e})};function Yqe({children:e,baseUrl:t}){let{patterns:n,isLoading:r,error:i}=OFe();if(r)return(0,K.jsx)(`div`,{className:`flex h-screen w-full items-center justify-center`,children:(0,K.jsx)(It,{})});if(i)return(0,K.jsx)(Xqe,{error:i,baseUrl:t});if(n.size>0){for(let e of Fqe)if(!n.has(e))throw Error(`Invalid permission pattern: "${e}". It is not in the server's PERMISSION_PATTERNS — check for a typo in route-permissions.ts.`)}return(0,K.jsx)(K.Fragment,{children:e})}var Xqe=({error:e,baseUrl:t})=>{let n=[`Studio could not reach the Mastra server at ${t}. Check that the instance URL and API prefix in Settings are correct, and that the server is running.`,`Error: ${e.message}`];return(0,K.jsx)(`div`,{className:`flex h-screen w-full items-center justify-center`,children:(0,K.jsx)(Jx,{tone:`error`,titleSlot:`Failed to load studio`,descriptionSlot:n.join(`
|
|
174
174
|
|
|
175
175
|
`),actionSlot:(0,K.jsx)(X,{icon:(0,K.jsx)(vS,{}),onClick:()=>{localStorage.removeItem(bS),window.location.reload()},children:`Reset Studio configuration`})})})},xS=U(`IconArrowRotateClockwise`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M19.5165 14.6667C18.4182 17.7738 15.4549 20 11.9717 20C7.5534 20 3.97168 16.4183 3.97168 12C3.97168 7.58172 7.5534 4 11.9717 4C15.0676 4 17 5.5 19 8`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M19 4V8H15`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]})),Zqe=U(`IconBug`,()=>(0,K.jsx)(`path`,{d:`M6 13V15C6 18.3137 8.68629 21 12 21C15.3137 21 18 18.3137 18 15V13M6 13H3M6 13V10C6 9.63543 6.09754 9.29365 6.26796 8.99932M18 13H21M18 13V10C18 9.61052 17.8887 9.24705 17.6961 8.93966M6 17L3.25 18M18 17L20.75 18M12 13V20M8 7.5V7C8 4.79086 9.79086 3 12 3C14.2091 3 16 4.79086 16 7V7.5M6.27 9L6.26796 8.99932M6.26796 8.99932L3.25 8M6.26796 8.99932C6.61386 8.4019 7.26 8 8 8H16C16.7151 8 17.3425 8.37529 17.6961 8.93966M17.6961 8.93966L20.75 8`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})),SS=`text-muted-foreground hover:text-foreground`,CS=`text-muted-foreground group-hover:text-foreground`,Qqe={error:null,errorInfo:null};function $qe(e,t){if(e===t)return!1;if(!e||!t||e.length!==t.length)return!0;for(let n=0;n<e.length;n++)if(!Object.is(e[n],t[n]))return!0;return!1}var eJe=class extends G.Component{state=Qqe;static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){if(this.setState({errorInfo:t}),this.props.onError)try{this.props.onError(e,t)}catch(e){typeof console<`u`&&console.error(`[ErrorBoundary] onError handler threw:`,e)}typeof console<`u`&&console.error(`[ErrorBoundary] Uncaught error:`,e,t)}componentDidUpdate(e){this.state.error&&$qe(e.resetKeys,this.props.resetKeys)&&this.reset()}reset=()=>{this.setState(Qqe)};render(){let{error:e,errorInfo:t}=this.state,{children:n,fallback:r,title:i,description:a,variant:o,className:s}=this.props;return e?typeof r==`function`?r({error:e,errorInfo:t,reset:this.reset}):r===void 0?(0,K.jsx)(tJe,{error:e,errorInfo:t,reset:this.reset,title:i,description:a,variant:o??`section`,className:s}):r:n}};function tJe({error:e,errorInfo:t,reset:n,title:r,description:i,variant:a,className:o}){let s=t?.componentStack??e.stack??``,l=a===`inline`;return(0,K.jsx)(`div`,{role:`alert`,className:c(`@container flex w-full items-center justify-center`,l?`px-4 py-6`:`h-full min-h-60 flex-1 px-6 py-10`,o),children:(0,K.jsxs)(`div`,{className:c(`flex flex-col items-center text-center`,l?`max-w-md gap-3`:`max-w-2xl gap-4 @md:gap-5 @lg:gap-6`),children:[(0,K.jsx)(`div`,{className:c(`flex items-center justify-center rounded-full bg-destructive-subtle text-destructive-subtle-foreground`,l?`size-10 [&>svg]:size-icon-lg`:`size-14 @md:size-16 @lg:size-20 [&>svg]:size-7 @md:[&>svg]:size-8 @lg:[&>svg]:size-10`),children:(0,K.jsx)(Zx,{})}),(0,K.jsx)(`h3`,{className:c(`text-foreground`,l?`text-subheading`:`text-subheading @md:text-heading @lg:text-title`),children:r??`Something went wrong`}),(0,K.jsx)(`p`,{className:c(`text-muted-foreground`,l?`text-caption`:`text-body`),children:i??`An unexpected error occurred while rendering this part of the page.`}),(0,K.jsx)(`p`,{className:c(`rounded-md bg-card px-3 py-2 font-mono break-words text-muted-foreground`,l?`text-meta`:`text-caption`),children:e.message}),(0,K.jsxs)(`div`,{className:c(`flex flex-wrap items-center justify-center gap-2`,l?`mt-1`:`mt-2`),children:[(0,K.jsx)(X,{icon:(0,K.jsx)(vS,{}),variant:`primary`,size:l?`sm`:`lg`,onClick:n,children:`Try again`}),(0,K.jsx)(X,{icon:(0,K.jsx)(xS,{}),variant:`default`,size:l?`sm`:`lg`,onClick:()=>window.location.reload(),children:`Reload page`}),(0,K.jsx)(X,{icon:(0,K.jsx)(Zqe,{}),render:(0,K.jsx)(`a`,{href:`https://github.com/mastra-ai/mastra/issues`,target:`_blank`,rel:`noopener noreferrer`}),variant:`default`,size:l?`sm`:`lg`,children:`Report issue`})]}),s?(0,K.jsxs)(`details`,{className:c(`w-full text-left`,l?`mt-1`:`mt-2`),children:[(0,K.jsx)(`summary`,{className:c(`cursor-pointer text-caption`,SS),children:`Show error details`}),(0,K.jsx)(`pre`,{className:`mt-2 max-h-64 overflow-auto rounded-md bg-card p-3 text-meta break-words whitespace-pre-wrap text-muted-foreground`,children:s})]}):null]})})}var wS=({children:e,border:t=!0,className:n})=>(0,K.jsx)(`header`,{className:c(`z-50 flex h-header-default w-full items-center gap-2 bg-transparent px-2`,{"border-b border-surface-rim":t},n),children:e}),nJe=({children:e})=>(0,K.jsx)(T,{as:`h1`,variant:`body`,tone:`ink`,className:`flex items-center gap-2`,children:e}),TS=U(`IconChevronLeftMedium`,()=>(0,K.jsx)(`path`,{d:`M14.5 18L8.5 12L14.5 6`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})),rJe=8,iJe=(e,{enabled:t=!0,startFollowing:n=!0,onFollowingChange:r})=>{let i=(0,G.useRef)(t&&n),a=(0,G.useRef)(null),o=(0,G.useRef)(!1),s=(0,G.useRef)(null);G.useEffect(()=>{if(!t||!e?.current)return;let n=e.current,c=e=>{i.current!==e&&(i.current=e,r?.(e))},l=()=>{i.current&&(a.current!==null&&cancelAnimationFrame(a.current),a.current=requestAnimationFrame(()=>{i.current&&(n.scrollTop=n.scrollHeight),a.current=null}))},u=new MutationObserver(l);u.observe(n,{childList:!0,subtree:!0,characterData:!0});let d=new ResizeObserver(l);d.observe(n);let f=()=>{a.current!==null&&(cancelAnimationFrame(a.current),a.current=null)},p=()=>{c(!1),f()},m=()=>{o.current=!0,s.current!==null&&window.clearTimeout(s.current),s.current=window.setTimeout(()=>{o.current=!1,s.current=null},250)},h=e=>{m(),e.deltaY<0&&p()},g=e=>{m(),[`ArrowUp`,`PageUp`,`Home`].includes(e.key)&&p()},_=e=>{let t=e.target;t.scrollTop+t.clientHeight>=t.scrollHeight-rJe?c(!0):o.current&&(c(!1),f())};return n.addEventListener(`wheel`,h,{passive:!0}),n.addEventListener(`touchmove`,m,{passive:!0}),n.addEventListener(`pointerdown`,m),n.addEventListener(`keydown`,g),n.addEventListener(`scroll`,_),l(),()=>{n.removeEventListener(`wheel`,h),n.removeEventListener(`touchmove`,m),n.removeEventListener(`pointerdown`,m),n.removeEventListener(`keydown`,g),n.removeEventListener(`scroll`,_),u.disconnect(),d.disconnect(),f(),s.current!==null&&(window.clearTimeout(s.current),s.current=null)}},[t,e,r])},aJe=G.createContext(void 0);function ES(){let e=G.useContext(aJe);if(e===void 0)throw Error(Gv(53));return e}function DS(e,t,n){if(!e)return 0;let r=getComputedStyle(e),i=`${t}${n===`x`?`Inline`:`Block`}`,a=parseFloat(r[`${i}Start`]);return n===`x`&&t===`margin`?a*2:a+parseFloat(r[`${i}End`])}var OS=`base-ui-disable-scrollbar`,kS={className:OS,getElement(e){return(0,K.jsx)(`style`,{nonce:e,href:OS,precedence:`base-ui:low`,children:`.${OS}{scrollbar-width:none}.${OS}::-webkit-scrollbar{display:none}`})}},oJe=`data-has-overflow-x`,sJe=`data-has-overflow-y`,cJe=`data-overflow-x-start`,lJe=`data-overflow-x-end`,uJe=`data-overflow-y-start`,dJe=`data-overflow-y-end`,AS=e=>t=>t?{[e]:``}:null,jS={hasOverflowX:AS(oJe),hasOverflowY:AS(sJe),overflowXStart:AS(cJe),overflowXEnd:AS(lJe),overflowYStart:AS(uJe),overflowYEnd:AS(dJe),cornerHidden:()=>null},fJe=G.createContext(void 0),pJe={disableStyleElements:!1};function mJe(){return G.useContext(fJe)??pJe}var hJe=`--scroll-area-corner-height`,gJe=`--scroll-area-corner-width`,_Je=`data-orientation`,vJe={x:0,y:0},yJe={width:0,height:0},bJe={xStart:!1,xEnd:!1,yStart:!1,yEnd:!1},xJe={x:!0,y:!0,corner:!0},SJe=G.forwardRef(function(e,t){let{render:n,className:r,overflowEdgeThreshold:i,style:a,...o}=e,{xStart:s,xEnd:c,yStart:l,yEnd:u}=CJe(i),d=gx(),f=Yv(),p=Yv(),{nonce:m,disableStyleElements:h}=mJe(),[g,_]=G.useState(!1),[v,y]=G.useState(!1),[b,x]=G.useState(!1),[S,C]=G.useState(!1),[w,T]=G.useState(!1),[E,D]=G.useState(yJe),[O,k]=G.useState(yJe),[A,j]=G.useState(bJe),[M,P]=G.useState(xJe),F=G.useRef(null),I=G.useRef(null),L=G.useRef(null),R=G.useRef(null),z=G.useRef(null),B=G.useRef(null),V=G.useRef(null),H=G.useRef(null),ee=G.useRef(0),te=G.useRef(0),U=G.useRef(0),W=G.useRef(0),ne=G.useRef(`vertical`),re=G.useRef(vJe),ie=G.useRef(null);function ae(e){let t=e?x:y,n=e?f:p;t(!0),n.start(500,()=>{t(!1)})}let oe=zy(e=>{let t=e.x-re.current.x,n=e.y-re.current.y;re.current=e,n!==0&&ae(!0),t!==0&&ae(!1)}),se=zy(()=>{let e=I.current;e&&ie.current===null&&(ie.current=e.style.scrollSnapType,e.style.scrollSnapType=`none`)}),ce=zy(e=>{if(e.button!==0||H.current!==null&&(ne.current===`vertical`?z.current:B.current)?.hasPointerCapture(H.current))return;H.current=e.pointerId,ee.current=e.clientY,te.current=e.clientX,ne.current=e.currentTarget.getAttribute(_Je);let t=I.current;t&&(U.current=t.scrollTop,W.current=t.scrollLeft,se()),(ne.current===`vertical`?z.current:B.current)?.setPointerCapture(e.pointerId)}),le=zy(e=>{if(e.pointerId!==H.current)return;H.current=null,(ne.current===`vertical`?x:y)(!1),ie.current!==null&&(I.current&&(I.current.style.scrollSnapType=ie.current),ie.current=null);let t=ne.current===`vertical`?z.current:B.current;t?.hasPointerCapture(e.pointerId)&&t.releasePointerCapture(e.pointerId)}),ue=zy(e=>{if(e.pointerId!==H.current)return;if(e.buttons%2==0){le(e);return}let t=I.current;if(!t)return;let n=ne.current===`vertical`,r=n?z.current:B.current,i=n?L.current:R.current;if(!r||!i)return;let a=n?`y`:`x`,o=DS(i,`padding`,a),s=DS(r,`margin`,a),c=n?r.offsetHeight:r.offsetWidth,l=(n?i.offsetHeight:i.offsetWidth)-c-o-s,u=n?e.clientY-ee.current:e.clientX-te.current,d=l<=0?0:u/l,f=n?t.scrollHeight:t.scrollWidth,p=n?t.clientHeight:t.clientWidth,m=(n?U.current:W.current)+d*(f-p);n?t.scrollTop=m:t.scrollLeft=m,e.preventDefault(),ae(n)});function de(e){C(e.pointerType===`touch`)}function fe(e){if(de(e),e.pointerType!==`touch`){let t=gy(F.current,e.target);_(t)}}let pe=G.useMemo(()=>({scrolling:v||b,hasOverflowX:!M.x,hasOverflowY:!M.y,overflowXStart:A.xStart,overflowXEnd:A.xEnd,overflowYStart:A.yStart,overflowYEnd:A.yEnd,cornerHidden:M.corner}),[v,b,M.x,M.y,M.corner,A]),me={role:`presentation`,onPointerEnter:fe,onPointerMove:fe,onPointerDown:de,onPointerLeave(){_(!1)},style:{position:`relative`,[hJe]:`${E.height}px`,[gJe]:`${E.width}px`}},he=N(`div`,e,{state:pe,ref:[t,F],props:[me,o],stateAttributesMapping:jS}),ge=G.useMemo(()=>({handlePointerDown:ce,handlePointerMove:ue,handlePointerUp:le,handleScroll:oe,disableViewportSnap:se,cornerSize:E,setCornerSize:D,thumbSize:O,setThumbSize:k,hasMeasuredScrollbar:w,setHasMeasuredScrollbar:T,touchModality:S,cornerRef:V,scrollingX:v,scrollingY:b,hovering:g,setHovering:_,viewportRef:I,scrollbarYRef:L,scrollbarXRef:R,thumbYRef:z,thumbXRef:B,rootId:d,hiddenState:M,setHiddenState:P,overflowEdges:A,setOverflowEdges:j,viewportState:pe,overflowEdgeThreshold:{xStart:s,xEnd:c,yStart:l,yEnd:u}}),[ce,ue,le,oe,se,E,O,w,S,v,b,g,d,M,A,pe,s,c,l,u]);return(0,K.jsxs)(aJe.Provider,{value:ge,children:[!h&&kS.getElement(m),he]})});function CJe(e){let t=typeof e==`number`?{xStart:e,xEnd:e,yStart:e,yEnd:e}:e;return{xStart:Math.max(0,t?.xStart||0),xEnd:Math.max(0,t?.xEnd||0),yStart:Math.max(0,t?.yStart||0),yEnd:Math.max(0,t?.yEnd||0)}}function MS(e,t=-(2**53-1),n=2**53-1){return Math.max(t,Math.min(e,n))}var wJe=G.createContext(void 0);function TJe(){let e=G.useContext(wJe);if(e===void 0)throw Error(Gv(55));return e}function EJe(e,t){return Math.max(0,e-t)}function DJe(e,t){if(t<=0)return 0;let n=MS(e,0,t),r=n,i=t-n,a=r<=1,o=i<=1;return a&&o?r<=i?0:t:a?0:o?t:n}var OJe=`--scroll-area-overflow-x-start`,kJe=`--scroll-area-overflow-x-end`,AJe=`--scroll-area-overflow-y-start`,jJe=`--scroll-area-overflow-y-end`,MJe=`--scroll-area-thumb-height`,NJe=`--scroll-area-thumb-width`,PJe=[OJe,kJe,AJe,jJe],FJe=!1;function IJe(){FJe||$v||(typeof CSS<`u`&&`registerProperty`in CSS&&PJe.forEach(e=>{try{CSS.registerProperty({name:e,syntax:`<length>`,inherits:!1,initialValue:`0px`})}catch{}}),FJe=!0)}var LJe=G.forwardRef(function(e,t){let{render:n,className:r,style:i,...a}=e,{viewportRef:o,scrollbarYRef:s,scrollbarXRef:c,thumbYRef:l,thumbXRef:u,cornerRef:d,cornerSize:f,setCornerSize:p,setThumbSize:m,rootId:h,setHiddenState:g,hiddenState:_,setHasMeasuredScrollbar:v,handleScroll:y,touchModality:b,setHovering:x,setOverflowEdges:S,overflowEdgeThreshold:w,viewportState:T}=ES(),E=_x(),D=G.useRef(!0),O=G.useRef([NaN,NaN,NaN,NaN]),k=Yv(),A=Yv(),j=zy(()=>{let e=o.current,t=s.current,n=c.current,r=l.current,i=u.current,a=d.current;if(!e)return;let h=e.scrollHeight,_=e.scrollWidth,y=e.clientHeight,b=e.clientWidth,x=e.scrollTop,C=e.scrollLeft,T=O.current,D=Number.isNaN(T[0]);if(T[0]=y,T[1]=h,T[2]=b,T[3]=_,D&&v(!0),h===0||_===0)return;let k=RJe(e),A=k.y,j=k.x,M=b/_,N=y/h,P=Math.max(0,_-b),F=Math.max(0,h-y),I=0,L=0;j||(I=DJe(E===`rtl`?-C:C,P),L=P-I);let R=A?0:DJe(x,F),z=A?0:F-R,B=j?0:b,V=A?0:y,H=0,ee=0;!j&&!A&&(H=t?.offsetWidth||0,ee=n?.offsetHeight||0);let te=f.width===0&&f.height===0,U=te?H:0,W=te?ee:0,ne=DS(n,`padding`,`x`),re=DS(t,`padding`,`y`),ie=DS(i,`margin`,`x`),ae=DS(r,`margin`,`y`),oe=B-ne-ie,se=V-re-ae,ce=n?Math.min(n.offsetWidth-U,oe):oe,le=t?Math.min(t.offsetHeight-W,se):se,ue=Math.max(16,ce*M),de=Math.max(16,le*N);if(m(e=>NS(e,{width:ue,height:de})),t&&r){let e=zJe(r,MJe,x,F,h,de,t.offsetHeight-de-re-ae);r.style.transform=`translate3d(0,${e}px,0)`}if(n&&i){let e=n.offsetWidth-ue-ne-ie,t=zJe(i,NJe,E===`rtl`?-C:C,P,_,ue,e);i.style.transform=`translate3d(${E===`rtl`?-t:t}px,0,0)`}let fe=[I,L,R,z];PJe.forEach((t,n)=>{e.style.setProperty(t,`${fe[n]}px`)}),a&&p(e=>NS(e,{width:H,height:ee})),g(e=>NS(e,k));let pe={xStart:!j&&I>w.xStart,xEnd:!j&&L>w.xEnd,yStart:!A&&R>w.yStart,yEnd:!A&&z>w.yEnd};S(e=>NS(e,pe))});Wv(()=>{IJe()},[]),Wv(()=>{queueMicrotask(j)},[j,_,E,w.xStart,w.xEnd,w.yStart,w.yEnd]),Wv(()=>{o.current?.matches(`:hover`)&&x(!0)},[o,x]),Wv(()=>{let e=o.current;if(typeof ResizeObserver>`u`||!e)return;let t=!1,n=new ResizeObserver(()=>{if(!t){t=!0;let n=O.current;if(n[0]===e.clientHeight&&n[1]===e.scrollHeight&&n[2]===e.clientWidth&&n[3]===e.scrollWidth)return}j()});return n.observe(e),A.start(0,()=>{let t=CUe(e,{subtree:!0});t.length!==0&&Promise.allSettled(t.map(e=>e.finished.then(C))).then(j).catch(()=>{})}),()=>{n.disconnect(),A.clear()}},[j,o,A]);function M(){D.current=!1}let P={...h&&{"data-id":`${h}-viewport`},tabIndex:_.x&&_.y?-1:0,className:kS.className,style:{overflow:`scroll`},onScroll(){o.current&&(j(),(b||!D.current)&&y({x:o.current.scrollLeft,y:o.current.scrollTop}),k.start(100,()=>{D.current=!0}))},onWheel:M,onPointerMove:M,onPointerEnter:M,onKeyDown:M},F=N(`div`,e,{ref:[t,o],state:T,props:[P,a],stateAttributesMapping:jS}),I=G.useMemo(()=>({computeThumbPosition:j}),[j]);return(0,K.jsx)(wJe.Provider,{value:I,children:F})});function RJe(e){let t=e.clientHeight>=e.scrollHeight,n=e.clientWidth>=e.scrollWidth;return{y:t,x:n,corner:t||n}}function NS(e,t){for(let n in t)if(e[n]!==t[n])return t;return e}function zJe(e,t,n,r,i,a,o){let s=MS(n,0,r),c=n-s,l=Math.max(16,a*i/(i+Math.abs(c)));return e.style.setProperty(t,c?`${l}px`:``),(r?s/r*o:0)+(c>0?a-l:0)}var BJe=G.createContext(void 0);function VJe(){let e=G.useContext(BJe);if(e===void 0)throw Error(Gv(54));return e}var HJe=G.forwardRef(function(e,t){let{render:n,className:r,orientation:i=`vertical`,keepMounted:a=!1,style:o,...s}=e,{hovering:c,scrollingX:l,scrollingY:u,hiddenState:d,scrollbarYRef:f,scrollbarXRef:p,viewportRef:m,thumbYRef:h,thumbXRef:g,handlePointerDown:_,handlePointerUp:v,handleScroll:y,disableViewportSnap:b,rootId:x,thumbSize:S,hasMeasuredScrollbar:C,viewportState:w}=ES(),T=i===`vertical`,E={...w,hovering:c,scrolling:T?u:l,orientation:i},D=_x(),O=!C&&!a,k=T?d.y:d.x,A=a||!k;G.useEffect(()=>{if(!A)return;let e=m.current,t=T?f.current:p.current;if(!t)return;function n(t){if(!e||t.ctrlKey)return;let n=!T,r=n?`scrollLeft`:`scrollTop`,i=n?t.deltaX:t.deltaY;if(i===0)return;let a=n?e.scrollWidth-e.clientWidth:e.scrollHeight-e.clientHeight,o=n&&D===`rtl`?-a:0,s=n&&D===`rtl`?0:a,c=e[r];c<=o&&i<0||c>=s&&i>0||(t.preventDefault(),e[r]=Math.min(s,Math.max(o,c+i)),y({x:e.scrollLeft,y:e.scrollTop}))}return Iy(t,`wheel`,n,{passive:!1})},[D,y,T,p,f,A,m]);let j={...x&&{"data-id":`${x}-scrollbar`},"aria-hidden":!0,onPointerDown(e){if(e.button!==0)return;let t=vy(e.nativeEvent),n=T?h.current:g.current;if(n&&gy(n,t))return;let r=m.current;if(!r)return;let i=T?f.current:p.current;if(!n||!i)return;let a=T?`y`:`x`,o=DS(n,`margin`,a),s=DS(i,`padding`,a),c=T?n.offsetHeight:n.offsetWidth,l=i.getBoundingClientRect(),u=T?e.clientY-l.top-c/2-s+o/2:e.clientX-l.left-c/2-s+o/2,d=T?r.scrollHeight:r.scrollWidth,v=T?r.clientHeight:r.clientWidth,x=(T?i.offsetHeight:i.offsetWidth)-c-s-o;if(x<=0)return;let S=u/x,C=d-v;b(),T?r.scrollTop=S*C:r.scrollLeft=D===`rtl`?-(1-S)*C:S*C,y({x:r.scrollLeft,y:r.scrollTop}),_(e)},onMouseDown(e){e.preventDefault()},onPointerUp:v,onPointerCancel:v,style:{position:`absolute`,touchAction:`none`,WebkitUserSelect:`none`,userSelect:`none`,visibility:O?`hidden`:void 0,...T?{top:0,bottom:`var(${hJe})`,insetInlineEnd:0,[MJe]:`${S.height}px`}:{insetInlineStart:0,insetInlineEnd:`var(${gJe})`,bottom:0,[NJe]:`${S.width}px`}}},M=N(`div`,e,{ref:[t,T?f:p],state:E,props:[j,s],stateAttributesMapping:jS});return A?(0,K.jsx)(BJe.Provider,{value:i,children:M}):null}),UJe=G.forwardRef(function(e,t){let{render:n,className:r,style:i,...a}=e,{computeThumbPosition:o}=TJe(),{hasMeasuredScrollbar:s,viewportState:c}=ES(),l=G.useRef(null),u=G.useRef(s);return Wv(()=>{if(typeof ResizeObserver>`u`)return;let e=!1,t=new ResizeObserver(()=>{!e&&(e=!0,!u.current)||o()});return l.current&&t.observe(l.current),()=>{t.disconnect()}},[o]),N(`div`,e,{ref:[t,l],state:c,stateAttributesMapping:jS,props:[{role:`presentation`,style:{minWidth:`fit-content`}},a]})}),WJe=G.forwardRef(function(e,t){let{render:n,className:r,style:i,...a}=e,{thumbYRef:o,thumbXRef:s,handlePointerDown:c,handlePointerMove:l,handlePointerUp:u,scrollingX:d,scrollingY:f,hasMeasuredScrollbar:p}=ES(),m=VJe(),h=m===`vertical`;return N(`div`,e,{ref:[t,h?o:s],state:{scrolling:h?f:d,orientation:m},props:[{onPointerDown:c,onPointerMove:l,onPointerUp:u,onPointerCancel:u,style:{visibility:p?void 0:`hidden`,...h?{height:`var(--scroll-area-thumb-height)`}:{width:`var(--scroll-area-thumb-width)`}}},a]})}),GJe=G.forwardRef(function(e,t){let{render:n,className:r,style:i,...a}=e,{cornerRef:o,cornerSize:s,hiddenState:c}=ES(),l=N(`div`,e,{ref:[t,o],props:[{"aria-hidden":!0,style:{position:`absolute`,bottom:0,insetInlineEnd:0,width:s.width,height:s.height}},a]});return c.corner?null:l}),KJe=100,qJe=20,JJe=1,YJe=16,XJe=`2rem`,PS=`0px`,ZJe=`mask-t-from-[calc(100%-min(var(--scroll-area-fade-top),var(--scroll-area-overflow-y-start,0px)))] mask-b-from-[calc(100%-min(var(--scroll-area-fade-bottom),var(--scroll-area-overflow-y-end,0px)))] mask-l-from-[calc(100%-min(var(--scroll-area-fade-left),var(--scroll-area-overflow-x-start,0px)))] mask-r-from-[calc(100%-min(var(--scroll-area-fade-right),var(--scroll-area-overflow-x-end,0px)))]`,FS=e=>e===!0?XJe:e;function QJe(e,t){if(e===!1)return{top:!1,bottom:!1,left:!1,right:!1};let n=(t===`vertical`||t===`both`)&&XJe,r=(t===`horizontal`||t===`both`)&&XJe,i={top:n,bottom:n,left:r,right:r};return e===!0||e===void 0||(e.y!==void 0&&(i.top=FS(e.y),i.bottom=FS(e.y)),e.x!==void 0&&(i.left=FS(e.x),i.right=FS(e.x)),e.top!==void 0&&(i.top=FS(e.top)),e.bottom!==void 0&&(i.bottom=FS(e.bottom)),e.left!==void 0&&(i.left=FS(e.left)),e.right!==void 0&&(i.right=FS(e.right))),i}var $Je=e=>({"--scroll-area-fade-top":e.top||PS,"--scroll-area-fade-bottom":e.bottom||PS,"--scroll-area-fade-left":e.left||PS,"--scroll-area-fade-right":e.right||PS});function eYe(e,t,n){let r=e??t;return Number.isFinite(r)?Math.max(n,r):Math.max(n,t)}var tYe=({direction:e,label:t,onStartScrolling:n,onStopScrolling:r,onKeyboardScroll:i})=>{let a=e===`left`?TS:f;return(0,K.jsx)(`button`,{type:`button`,"aria-label":t,className:c(`absolute inset-y-1 z-10 hidden w-8 cursor-pointer items-center justify-center rounded-md border-0 bg-transparent hover:bg-fill-subtle active:bg-fill`,SS,A,p,e===`left`?`left-1 group-data-[overflow-x-start]/scroll-area:flex`:`right-1 group-data-[overflow-x-end]/scroll-area:flex`),onPointerDown:t=>n(e,t),onPointerUp:r,onPointerLeave:r,onPointerCancel:r,onBlur:r,onClick:t=>{t.detail===0&&i(e)},children:(0,K.jsx)(a,{"aria-hidden":`true`,className:`size-4`})})},nYe=({areaRef:e,scrollButtons:t})=>{let n=G.useRef(null),r=typeof t==`object`?t:void 0,i=eYe(r?.scrollSpeed,KJe,JJe),a=eYe(r?.scrollIntervalTime,qJe,YJe),o=r?.leftLabel??`Scroll left`,s=r?.rightLabel??`Scroll right`,c=G.useCallback(()=>{n.current&&=(clearInterval(n.current),null)},[]),l=G.useCallback((t,n=1)=>{let r=e.current;r&&r.scrollBy({left:t===`right`?i*n:-i*n,behavior:`smooth`})},[e,i]),u=G.useCallback((e,t)=>{t?.preventDefault(),t?.stopPropagation(),t?.currentTarget.setPointerCapture?.(t.pointerId),c(),l(e,2),n.current=setInterval(()=>{l(e)},a)},[a,l,c]);return G.useEffect(()=>()=>{c()},[c]),(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(tYe,{direction:`left`,label:o,onStartScrolling:u,onStopScrolling:c,onKeyboardScroll:e=>l(e,2)}),(0,K.jsx)(tYe,{direction:`right`,label:s,onStartScrolling:u,onStopScrolling:c,onKeyboardScroll:e=>l(e,2)})]})},rYe=G.createContext(null);function iYe(){let e=G.use(rYe);if(!e)throw Error(`ScrollAreaViewport must be a direct child of ScrollArea`);return e}function IS({className:e,contentClassName:t,children:n,ref:r,render:i}){let a=iYe(),{areaRef:o}=a,s=G.useMemo(()=>Wx(o,r),[o,r]);return(0,K.jsx)(LJe,{ref:s,className:c(a.className,e),style:a.style,render:i,children:(0,K.jsx)(UJe,{className:t,style:a.contentStyle,children:(0,K.jsx)(rYe,{value:null,children:n})})})}function LS({className:e,children:t,maxHeight:n,autoScroll:r=!1,autoScrollStartFollowing:i,onAutoScrollFollowingChange:a,orientation:o=`vertical`,scrollButtons:s,mask:l,revealScrollbarOnHover:u=!0,alwaysShowScrollbar:d=!1,...f}){let p=G.useRef(null);iJe(p,{enabled:r,startFollowing:i,onFollowingChange:a});let m=QJe(l,o),h=Object.values(m).some(Boolean),g=$Je(m);n&&(g.maxHeight=n),o===`vertical`?(g.overflowX=`hidden`,g.overflowY=`scroll`):o===`horizontal`&&(g.overflowX=`scroll`,g.overflowY=`hidden`);let _=o===`vertical`?{minWidth:`0px`}:o===`horizontal`?{minHeight:`0px`}:void 0,v={areaRef:p,className:c(`size-full`,h&&ZJe),style:g,contentStyle:_},y=G.Children.toArray(t).filter(e=>G.isValidElement(e)&&e.type===IS).length;if(y>1)throw Error(`ScrollArea takes at most one ScrollAreaViewport`);let b=y===1;return(0,K.jsxs)(SJe,{className:c(`group/scroll-area relative overflow-hidden`,e),...f,children:[(0,K.jsx)(rYe,{value:v,children:b?t:(0,K.jsx)(IS,{children:t})}),s&&o!==`vertical`&&(0,K.jsx)(nYe,{areaRef:p,scrollButtons:s}),(o===`vertical`||o===`both`)&&(0,K.jsx)(aYe,{orientation:`vertical`,revealOnHover:u,alwaysVisible:d}),(o===`horizontal`||o===`both`)&&(0,K.jsx)(aYe,{orientation:`horizontal`,revealOnHover:u,alwaysVisible:d}),o===`both`&&(0,K.jsx)(GJe,{})]})}function aYe({className:e,orientation:t=`vertical`,revealOnHover:n=!0,alwaysVisible:r=!1,...i}){return(0,K.jsx)(HJe,{"data-slot":`scroll-area-scrollbar`,orientation:t,className:c(`flex touch-none transition-opacity duration-normal ease-out-custom select-none`,r?`opacity-100`:`opacity-0 data-[scrolling]:opacity-100 data-[scrolling]:duration-0`,n&&!r&&`data-[hovering]:opacity-100`,t===`vertical`&&`my-(--scroll-area-scrollbar-inset,0px) w-1.5 p-px`,t===`horizontal`&&`mx-(--scroll-area-scrollbar-inset,0px) h-1.5 flex-col p-px`,e),...i,children:(0,K.jsx)(WJe,{className:`relative flex-1 rounded-full bg-muted-foreground/30 hover:bg-muted-foreground/60`})})}function RS({children:e,breadcrumbs:t,headerActions:n,actionRow:r,header:i,variant:a=`container`,mask:o=!1}){let s=i?(0,K.jsx)(`div`,{"data-slot":`page-layout-header`,className:c(a===`fit`&&`p-4`),children:i}):null;return(0,K.jsxs)(`div`,{"data-slot":`page-layout`,className:`flex h-full min-h-0 flex-col`,children:[(t||n)&&(0,K.jsxs)(wS,{className:`min-h-header-default shrink-0 gap-2 overflow-hidden px-2`,children:[t,n&&(0,K.jsx)(`div`,{className:`ml-auto flex shrink-0 items-center gap-2 overflow-hidden`,children:n})]}),r&&(0,K.jsx)(`div`,{"data-slot":`page-layout-action-row`,className:`flex shrink-0 flex-col gap-2 px-4 pt-4`,children:r}),(0,K.jsx)(`main`,{className:`flex min-h-0 flex-1 flex-col`,children:(0,K.jsx)(LS,{mask:o,className:`min-h-0 flex-1`,children:(0,K.jsx)(IS,{className:c(a===`container`&&`p-4`),contentClassName:c(a===`container`&&`h-full min-h-min`,a===`narrow`&&`grid min-h-full grid-cols-1`,a===`fit`&&(i?`grid h-full grid-cols-1 grid-rows-[auto_minmax(0,1fr)]`:`grid h-full grid-cols-1 grid-rows-1`)),children:a===`narrow`?(0,K.jsxs)(`div`,{"data-slot":`page-layout-container`,className:c(`mx-auto grid min-h-full w-full max-w-5xl grid-cols-1 p-4`,i?`grid-rows-[auto_1fr]`:`grid-rows-[1fr]`),children:[s,e]}):(0,K.jsxs)(K.Fragment,{children:[s,e]})})})})]})}var oYe=2e3;function sYe(){let[e]=(0,G.useState)(()=>typeof performance>`u`?`0ms`:`${-Math.round(performance.now()%oYe)}ms`);return e}function zS({className:e,style:t,...n}){let r=sYe();return(0,K.jsx)(`div`,{className:c(`relative overflow-hidden rounded-md bg-muted`,`before:absolute before:inset-0`,`before:-translate-x-full`,`before:animate-[shimmer_2s_infinite] before:[animation-delay:var(--shimmer-delay)]`,`before:bg-linear-to-r before:from-transparent before:via-fill-subtle before:to-transparent`,e),style:{"--shimmer-delay":r,...t},...n})}function BS({line:e=`text-body-sm`,className:t}){return(0,K.jsxs)(`span`,{className:c(`flex items-center`,e),children:[(0,K.jsx)(`span`,{"aria-hidden":!0,children:``}),(0,K.jsx)(zS,{className:c(`h-3.5`,t)})]})}var cYe=Ad(q(),hd()),VS={},lYe=new Map,uYe=new Map,dYe=e=>{try{return window.localStorage.getItem(e)}catch{return null}},fYe=e=>{if(!e)return VS;try{let t=cYe.safeParse(JSON.parse(e));return t.success?t.data:VS}catch{return VS}},pYe=e=>{let t=dYe(e),n=uYe.get(e);if(n&&n.raw===t)return n.value;let r=fYe(t);return uYe.set(e,{raw:t,value:r}),r},mYe=e=>{lYe.get(e)?.forEach(e=>e())},hYe=(e,t)=>{let n=lYe.get(e);n||(n=new Set,lYe.set(e,n)),n.add(t);let r=n=>{(n.key===e||n.key===null)&&t()};return window.addEventListener(`storage`,r),()=>{n.delete(t),window.removeEventListener(`storage`,r)}},gYe=(e,t)=>{try{window.localStorage.setItem(e,JSON.stringify(t))}catch{uYe.set(e,{raw:dYe(e),value:t})}mYe(e)};function _Ye(e){return[(0,G.useSyncExternalStore)((0,G.useCallback)(t=>hYe(e,t),[e]),()=>pYe(e),()=>VS),(0,G.useCallback)(t=>gYe(e,t),[e])]}var vYe=(e,t)=>`mastra-request-context:${e}:${t}`;function HS(e,t){return _Ye(vYe(e,t))}var yYe=(0,G.createContext)({selectedStepId:null,hoverStepId:null,setSelectedStepId:()=>void 0,setHoverStepId:()=>void 0});function US(){return(0,G.useContext)(yYe)}var WS=(0,G.createContext)({}),bYe=[`success`,`failed`,`canceled`,`bailed`,`tripwire`];function xYe(e){return`context`in e}function SYe(e){if(xYe(e)){let{input:t,...n}=e.context;return{input:t,steps:n}}return{input:e.payload,steps:e.steps??{}}}function CYe(e){return e.find(e=>e?.status===`suspended`)??e[0]}function wYe(e){return e.status===`failed`&&`tripwire`in e&&e.tripwire!==void 0?{...e,error:void 0}:e}function TYe(e){if(!Array.isArray(e))return e?wYe(e):void 0;let t=CYe(e);if(t)return{...wYe(t),payload:e.map(e=>e?.payload),output:e.map(e=>e?.output)}}function EYe(e){return Object.fromEntries(Object.entries(e).flatMap(([e,t])=>{let n=TYe(t);return n?[[e,n]]:[]}))}function DYe(e,t){let n=t.suspendPayload?.__workflow_meta?.path,r=Array.isArray(n)?n.filter(e=>typeof e==`string`):[];return r[0]===e?r:[e,...r]}function OYe(e){return Object.entries(e).filter(([,e])=>e.status===`suspended`).map(([e,t])=>DYe(e,t))}function kYe(e,t){switch(e.status){case`success`:return{result:e.result};case`failed`:return{error:e.error};case`suspended`:{let e=OYe(t),n=e[0]?.[0];return{suspended:e,suspendPayload:n?t[n]?.suspendPayload:void 0}}case`tripwire`:return`tripwire`in e&&e.tripwire?{tripwire:e.tripwire}:{};default:return{}}}function AYe(e){let{input:t,steps:n}=SYe(e),r=EYe(n);return{input:t,steps:r,status:e.status,...kYe(e,r)}}function jYe(e,t){let n=Object.entries(e).map(([e,n])=>[e,{...t[e],...n}]);return{...t,...Object.fromEntries(n)}}var MYe=[`success`,`failed`,`canceled`];function NYe(e,t){return LYe(e.status)?Object.entries(e.steps).some(([e,n])=>{if(n?.status!==`suspended`)return!1;let r=t.steps[e];if(!r)return!1;let i=MYe.includes(r.status);if(!i&&typeof r.resumedAt!=`number`)return!1;let a=i?r.endedAt:r.resumedAt;return typeof a!=`number`||typeof n.suspendedAt!=`number`||a>n.suspendedAt}):!1}function PYe(e,t){return e?t?NYe(e,t)?{...t,input:t.input??e.input}:{...e,input:e.input??t.input,steps:jYe(e.steps,t.steps)}:e:t}function FYe(e){return xYe(e)?e.value:e.initialState}function IYe(e,t){let n=FYe(e);return n&&Object.keys(n).length>0?{initialState:n,inputData:t}:t}function GS(e){return bYe.includes(e??``)}function LYe(e){return e===`paused`||e===`suspended`}function RYe(e){if(e===void 0)return;let t=new Date(e).getTime();return Number.isFinite(t)?t:void 0}function zYe(e){if(e&&typeof e==`object`&&`resourceId`in e)return typeof e.resourceId==`string`&&e.resourceId.length>0?e.resourceId:void 0}var BYe=U(`IconArrowRightLeft`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M7.49985 21L4.20696 17.7071C3.81643 17.3166 3.81643 16.6834 4.20696 16.2929L7.49985 13`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M16.5 11L19.7929 7.70711C20.1834 7.31658 20.1834 6.68342 19.7929 6.29289L16.5 3`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M5 17H20`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M4 7H19`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]})),VYe=U(`IconArrowsRepeat`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M4 13V7C4 5.89543 4.89543 5 6 5H15`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M13 2L16 5L13 8`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M20 11V17C20 18.1046 19.1046 19 18 19H9`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M11 22L8 19L11 16`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]})),KS=U(`IconBranch`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`circle`,{cx:`6.5`,cy:`6`,r:`2`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`circle`,{cx:`6.5`,cy:`18`,r:`2`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`circle`,{cx:`17.5`,cy:`6`,r:`2`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M6.5 8V16`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M17.5 8V10C17.5 11.1046 16.6046 12 15.5 12H8.5C7.39543 12 6.5 12.8954 6.5 14V16`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]})),qS=U(`IconCalendarClock4`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M20 8.5V7C20 5.89543 19.1046 5 18 5H6C4.89543 5 4 5.89543 4 7V18C4 19.1046 4.89543 20 6 20H8.5M8 5V3M16 5V3`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`circle`,{cx:`17`,cy:`17`,r:`5`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M17 15.0002V16.9999L18.5 18.5002`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]})),JS=U(`IconCodeBrackets`,()=>(0,K.jsx)(`path`,{d:`M10 20L14 4M18 8.00004L20.5858 10.5858C21.3668 11.3669 21.3668 12.6332 20.5858 13.4143L18 16M6 16L3.41421 13.4143C2.63316 12.6332 2.63317 11.3669 3.41421 10.5858L6 8.00004`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})),HYe=U(`IconFork`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M6.0002 3L5.07723 14.0756C5.02837 14.6619 5.24011 15.2399 5.65611 15.6559L8.41441 18.4142C8.78948 18.7893 9.0002 19.298 9.0002 19.8284V21`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M14 3V13`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M18 3L18.923 14.0756C18.9718 14.6619 18.7601 15.2399 18.3441 15.6559L15.5858 18.4142C15.2107 18.7893 15 19.298 15 19.8284V21`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M10 13V3`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]})),YS=U(`IconMaintenance`,()=>(0,K.jsx)(`path`,{d:`M14.5 16C18.0899 16 21 13.0899 21 9.5C21 8.75038 20.8731 8.03041 20.6396 7.36037L18 10C16.8954 11.1046 15.1046 11.1046 14 10C12.8954 8.89543 12.8954 7.10457 14 6L16.6396 3.36037C15.9696 3.12689 15.2496 3 14.5 3C10.9101 3 8 5.91015 8 9.5C8 10.3864 8.17743 11.2314 8.4987 12.0013L3.66421 16.8358C2.88316 17.6168 2.88316 18.8832 3.66421 19.6642L4.33579 20.3358C5.11684 21.1168 6.38316 21.1168 7.16421 20.3358L11.9987 15.5013C12.7686 15.8226 13.6136 16 14.5 16Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinejoin:`round`})),UYe=U(`IconRobot`,()=>(0,K.jsx)(`path`,{d:`M9 10C9 10.2761 8.77614 10.5 8.5 10.5C8.22386 10.5 8 10.2761 8 10M9 10C9 9.72386 8.77614 9.5 8.5 9.5C8.22386 9.5 8 9.72386 8 10M9 10H8M16 10C16 10.2761 15.7761 10.5 15.5 10.5C15.2239 10.5 15 10.2761 15 10M16 10C16 9.72386 15.7761 9.5 15.5 9.5C15.2239 9.5 15 9.72386 15 10M16 10H15M12 5V3M3.5 9C2.94772 9 2.5 9.44772 2.5 10C2.5 10.5523 2.94772 11 3.5 11M20.5 9C21.0523 9 21.5 9.44772 21.5 10C21.5 10.5523 21.0523 11 20.5 11M10 14.5H14M3.5 16V7C3.5 5.89543 4.39543 5 5.5 5H18.5C19.6046 5 20.5 5.89543 20.5 7V16C20.5 17.6569 19.1569 19 17.5 19H6.5C4.84315 19 3.5 17.6569 3.5 16Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})),XS=U(`IconStopwatch`,()=>(0,K.jsx)(`path`,{d:`M12 13L9 10M10 2H14M20 13C20 17.4183 16.4183 21 12 21C7.58172 21 4 17.4183 4 13C4 8.58172 7.58172 5 12 5C16.4183 5 20 8.58172 20 13Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})),ZS=e=>(0,K.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`-1.5 -1.5 27 27`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,...e,children:(0,K.jsx)(`path`,{d:`M5.8648 13.2539C6.3268 13.2539 6.7014 13.6288 6.7016 14.0906C6.7016 14.5526 6.3269 14.9273 5.8648 14.9273C4.1715 14.9277 2.799 16.3004 2.7984 17.9937C2.7984 19.6875 4.1712 21.0621 5.8648 21.0625C7.5589 21.0625 8.9336 19.6878 8.9336 17.9937C8.9341 17.5322 9.3086 17.157 9.7703 17.157C10.2316 17.1576 10.6065 17.5325 10.607 17.9937C10.607 20.6118 8.4829 22.7359 5.8648 22.7359C3.2471 22.7356 1.125 20.6115 1.125 17.9937C1.1255 15.3764 3.2475 13.2543 5.8648 13.2539ZM18.1352 13.2539C20.7525 13.2543 22.8745 15.3764 22.875 17.9937C22.875 20.6116 20.7529 22.7356 18.1352 22.7359C15.5173 22.7357 13.393 20.6116 13.393 17.9937C13.3935 17.5327 13.7686 17.1577 14.2297 17.157C14.6914 17.157 15.0659 17.5322 15.0664 17.9937C15.0664 19.6876 16.4413 21.0623 18.1352 21.0625C19.8289 21.0621 21.2016 19.6876 21.2016 17.9937C21.201 16.3004 19.8285 14.9277 18.1352 14.9273C17.6733 14.9271 17.2984 14.5525 17.2984 14.0906C17.2986 13.6289 17.6734 13.2541 18.1352 13.2539ZM12 1.2641C14.1558 1.2641 15.9028 3.0115 15.9031 5.1672C15.9031 6.7199 14.9968 8.0596 13.6842 8.6881C13.2114 8.9145 12.8367 9.3529 12.8367 9.8772V11.0507C12.8367 11.3465 12.9542 11.6302 13.1634 11.8394L17.4011 16.0771C17.5908 16.2667 17.8669 16.3226 18.1352 16.3226C19.0587 16.3228 19.8081 17.0703 19.8086 17.9937C19.8086 18.9177 19.059 19.667 18.1352 19.6672C17.2111 19.6672 16.4617 18.9178 16.4617 17.9937C16.4619 17.7256 16.4058 17.4493 16.2162 17.2597L12.7866 13.8301C12.3509 13.3945 11.6445 13.3945 11.209 13.8303L7.7817 17.2594C7.5919 17.4492 7.5381 17.7254 7.5383 17.9937C7.5383 18.9178 6.7889 19.6672 5.8648 19.6672C4.9412 19.6668 4.1914 18.9175 4.1914 17.9937C4.1919 17.0704 4.9415 16.323 5.8648 16.3226C6.1329 16.3226 6.4092 16.2645 6.5987 16.0751L10.8364 11.8394C11.0457 11.6302 11.1633 11.3464 11.1633 11.0505V9.8771C11.1633 9.3528 10.7887 8.9144 10.3159 8.688C9.0033 8.0595 8.0969 6.7198 8.0969 5.1672C8.0972 3.0116 9.8443 1.2642 12 1.2641Z`,fill:`currentColor`})}),QS={studio:`bg-product-studio-subtle text-product-studio-foreground`,server:`bg-product-server-subtle text-product-server-foreground`,observability:`bg-product-observability-subtle text-product-observability-foreground`,factory:`bg-product-factory-subtle text-product-factory-foreground`,workers:`bg-product-workers-subtle text-product-workers-foreground`,"persistent-server":`bg-product-persistent-server-subtle text-product-persistent-server-foreground`},$S={studio:`bg-product-studio text-product-studio-foreground`,server:`bg-product-server text-product-server-foreground`,observability:`bg-product-observability text-product-observability-foreground`,factory:`bg-product-factory text-product-factory-foreground`,workers:`bg-product-workers text-product-workers-foreground`,"persistent-server":`bg-product-persistent-server text-product-persistent-server-foreground`},WYe={strong:`bg-badge-green-strong text-badge-green-foreground`,subtle:`bg-badge-green-subtle text-badge-green-foreground`,indicator:`bg-badge-green-indicator`},GYe={strong:`bg-badge-red-strong text-badge-red-foreground`,subtle:`bg-badge-red-subtle text-badge-red-foreground`,indicator:`bg-badge-red-indicator`},KYe={strong:`bg-badge-amber-strong text-badge-amber-foreground`,subtle:`bg-badge-amber-subtle text-badge-amber-foreground`,indicator:`bg-badge-amber-indicator`},qYe={strong:`bg-badge-blue-strong text-badge-blue-foreground`,subtle:`bg-badge-blue-subtle text-badge-blue-foreground`,indicator:`bg-badge-blue-indicator`},JYe={studio:{strong:$S.studio,subtle:QS.studio,indicator:`bg-product-studio-foreground`},server:{strong:$S.server,subtle:QS.server,indicator:`bg-product-server-foreground`},observability:{strong:$S.observability,subtle:QS.observability,indicator:`bg-product-observability-foreground`},factory:{strong:$S.factory,subtle:QS.factory,indicator:`bg-product-factory-foreground`},workers:{strong:$S.workers,subtle:QS.workers,indicator:`bg-product-workers-foreground`},"persistent-server":{strong:$S[`persistent-server`],subtle:QS[`persistent-server`],indicator:`bg-product-persistent-server-foreground`},neutral:{strong:`bg-fill text-badge-neutral-foreground`,subtle:`bg-fill-subtle text-badge-neutral-foreground`,indicator:`bg-muted-foreground`},success:{...WYe,indicator:`bg-success-indicator`},destructive:{strong:`bg-badge-red-strong text-badge-red-foreground`,subtle:`bg-badge-red-subtle text-badge-red-foreground`,indicator:`bg-destructive-indicator`},info:{...qYe,indicator:`bg-info-indicator`},warning:{strong:`bg-badge-amber-strong text-warning-foreground`,subtle:`bg-badge-amber-subtle text-warning-foreground`,indicator:`bg-warning-indicator`},green:WYe,red:GYe,amber:KYe,blue:qYe,purple:{strong:`bg-badge-purple-strong text-badge-purple-foreground`,subtle:`bg-badge-purple-subtle text-badge-purple-foreground`,indicator:`bg-badge-purple-indicator`},orange:{strong:`bg-badge-orange-strong text-badge-orange-foreground`,subtle:`bg-badge-orange-subtle text-badge-orange-foreground`,indicator:`bg-badge-orange-indicator`},cyan:{strong:`bg-badge-cyan-strong text-badge-cyan-foreground`,subtle:`bg-badge-cyan-subtle text-badge-cyan-foreground`,indicator:`bg-badge-cyan-indicator`},pink:{strong:`bg-badge-pink-strong text-badge-pink-foreground`,subtle:`bg-badge-pink-subtle text-badge-pink-foreground`,indicator:`bg-badge-pink-indicator`}},YYe={xs:{badge:`h-[18px] gap-0.5 text-meta`,withoutLeadingVisual:`px-1.5`,withLeadingVisual:`pl-1 pr-1.5`,indicator:`size-1`},sm:{badge:`h-5 gap-1 text-meta`,withoutLeadingVisual:`px-1.5`,withLeadingVisual:`px-1.5`,indicator:`size-1`},md:{badge:`h-5 gap-1 text-column tracking-normal`,withoutLeadingVisual:`px-2`,withLeadingVisual:`pl-1.5 pr-2`,indicator:`size-1.5`}},eC=({icon:e,indicator:t,variant:n=`neutral`,emphasis:r=`strong`,size:i=`md`,className:a,children:o,...s})=>{let l=!!e,d=l||t!==void 0,f=YYe[i],p=d?f.withLeadingVisual:f.withoutLeadingVisual;return(0,K.jsxs)(`span`,{className:c(`inline-flex w-fit max-w-full shrink-0 items-center rounded-[7px]`,`shadow-inset`,JYe[n][r],f.badge,p,u.colors,a),...s,children:[t===void 0?null:(0,K.jsx)(`span`,{"aria-hidden":`true`,className:c(`shrink-0 rounded-full`,JYe[n].indicator,f.indicator,t===`pulse`&&`motion-safe:animate-pulse motion-reduce:animate-none`)}),l?(0,K.jsx)(Dx,{size:`xs`,children:e}):null,o]})},XYe=U(`IconArrowCornerDownRight`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M4 5V13C4 14.1046 4.89543 15 6 15H19`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M16 11L20 15L16 19`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]})),ZYe=U(`IconArrowsRepeatRightLeft`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M17.25 3L19.7197 5.46967C20.0126 5.76256 20.0126 6.23744 19.7197 6.53033L17.25 9`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M6.74989 21L4.28022 18.5303C3.98732 18.2374 3.98732 17.7626 4.28022 17.4697L6.74989 15`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M5 18H18C19.1046 18 20 17.1046 20 16V13`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M4 11V8C4 6.89543 4.89543 6 6 6H19`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]})),tC=U(`IconClock`,()=>(0,K.jsx)(`path`,{d:`M12 8V12L14.5 14.5M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})),nC=U(`IconLayersTwo`,()=>(0,K.jsx)(`path`,{d:`M7.90035 12.0002L3.59283 14.1014C2.84406 14.4666 2.84406 15.5337 3.59283 15.8989L11.5619 19.7863C11.8386 19.9213 12.1621 19.9213 12.4388 19.7863L20.4079 15.8989C21.1566 15.5337 21.1566 14.4666 20.4079 14.1014L16.1004 12.0002M7.90035 12.0002L3.59283 9.89893C2.84406 9.53367 2.84406 8.46664 3.59283 8.10139L11.5619 4.21402C11.8386 4.07905 12.1621 4.07905 12.4388 4.21402L20.4079 8.10139C21.1566 8.46664 21.1566 9.53367 20.4079 9.89893L16.1004 12.0002M7.90035 12.0002L11.5619 13.7863C11.8386 13.9213 12.1621 13.9213 12.4388 13.7863L16.1004 12.0002`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`square`,strokeLinejoin:`round`})),rC=U(`IconListBullets`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M10 6L20 6`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`}),(0,K.jsx)(`circle`,{cx:`4.5`,cy:`6`,r:`1.5`,fill:`currentColor`}),(0,K.jsx)(`path`,{d:`M10 12L20 12`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`}),(0,K.jsx)(`circle`,{cx:`4.5`,cy:`12`,r:`1.5`,fill:`currentColor`}),(0,K.jsx)(`path`,{d:`M10 18L20 18`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`}),(0,K.jsx)(`circle`,{cx:`4.5`,cy:`18`,r:`1.5`,fill:`currentColor`})]})),QYe=U(`IconPlayCircle`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M10 14.804V9.19617C10 8.79446 10.4498 8.55675 10.7817 8.78305L14.8941 11.587C15.1852 11.7855 15.1852 12.2147 14.8941 12.4132L10.7817 15.2171C10.4498 15.4434 10 15.2057 10 14.804Z`,fill:`currentColor`}),(0,K.jsx)(`circle`,{cx:`12`,cy:`12`,r:`9`,stroke:`currentColor`,strokeWidth:`2`})]})),$Ye=(e,t)=>Number(e.toPrecision(t));new Intl.NumberFormat(`en-US`,{style:`percent`,maximumFractionDigits:1});function iC(e,{signed:t=!1}={}){if(e!=null&&Number.isFinite(e)){if(t)return e===0?eXe(0):`${e>0?`+`:`-`}${eXe(Math.abs(e))}`;if(!(e<0))return eXe(e)}}function eXe(e){if(e<1e3)return`${$Ye(e,3)}ms`;let t=e/1e3;if(t<60)return`${$Ye(t,3)}s`;let[n,r,i]=[Math.floor(t/60),Math.floor(t/3600),Math.floor(t/86400)];return n<60?tXe(`${n}m`,Math.floor(t%60),`s`):r<24?tXe(`${r}h`,n%60,`m`):tXe(`${i}d`,r%24,`h`)}function tXe(e,t,n){return t>0?`${e} ${t}${n}`:e}function aC(e){if(!(e==null||!Number.isFinite(e)||e<0))return e<1e3?`${Math.round(e)} ms`:`${(e/1e3).toFixed(3)} s`}function nXe(e){return`${(e/1e3).toFixed(1)}s`}var rXe={js:`javascript`,javascript:`javascript`,mjs:`javascript`,cjs:`javascript`,node:`javascript`,ts:`typescript`,typescript:`typescript`,mts:`typescript`,cts:`typescript`,tsx:`tsx`,jsx:`jsx`,json:`json`,json5:`json`,md:`markdown`,markdown:`markdown`,py:`python`,python:`python`,sh:`bash`,bash:`bash`,shell:`bash`,zsh:`bash`,yml:`yaml`,yaml:`yaml`,diff:`diff`,patch:`diff`,css:`css`,scss:`css`,html:`html`,htm:`html`,xml:`xml`,svg:`xml`,sql:`sql`};async function oC(e){let[{StreamLanguage:t},n]=await Promise.all([W(()=>import(`./dist-LCE-PfnS.js`),__vite__mapDeps([0,1]),import.meta.url),e]);return t.define(n).parser}async function sC(e){let{javascript:t}=await W(async()=>{let{javascript:e}=await import(`./dist-dt9FWzHg.js`);return{javascript:e}},__vite__mapDeps([2,3,4,1]),import.meta.url);return t(e).language.parser}var iXe={javascript:()=>sC({}),jsx:()=>sC({jsx:!0}),typescript:()=>sC({typescript:!0}),tsx:()=>sC({jsx:!0,typescript:!0}),json:()=>W(()=>import(`./dist-DqeYHy1i.js`).then(e=>e.jsonLanguage.parser),__vite__mapDeps([5,6,4,1]),import.meta.url),markdown:()=>W(()=>import(`./dist-lH5IP94b.js`).then(e=>e.markdownLanguage.parser),__vite__mapDeps([7,8,1,3,4]),import.meta.url),bash:()=>oC(W(()=>import(`./shell-DwuoZtxw.js`).then(e=>e.shell),[],import.meta.url)),python:()=>oC(W(()=>import(`./python-DIWH3FmR.js`).then(e=>e.python),[],import.meta.url)),yaml:()=>oC(W(()=>import(`./yaml-BEzOWJ7L.js`).then(e=>e.yaml),[],import.meta.url)),diff:()=>oC(W(()=>import(`./diff-ChtP43wD.js`).then(e=>e.diff),[],import.meta.url)),css:()=>oC(W(()=>import(`./css-CIHhKeSF.js`).then(e=>e.css),[],import.meta.url)),html:()=>oC(W(()=>import(`./xml-aKzObEic.js`).then(e=>e.html),[],import.meta.url)),xml:()=>oC(W(()=>import(`./xml-aKzObEic.js`).then(e=>e.xml),[],import.meta.url)),sql:()=>oC(W(()=>import(`./sql-DrH7SW3s.js`).then(e=>e.standardSQL),[],import.meta.url))},aXe=new Map;function oXe(e){let t=aXe.get(e);return t||(t=iXe[e](),t.catch(()=>aXe.delete(e)),aXe.set(e,t)),t}var sXe=ne([{tag:[Re.comment,Re.bracket],class:`syntax-comment`},{tag:[Re.string,Re.meta,Re.regexp,Re.name,Re.quote,Re.standard(Re.tagName)],class:`syntax-string`},{tag:[Re.atom,Re.bool,Re.special(Re.variableName)],class:`syntax-literal`},{tag:[Re.keyword,Re.operator,Re.tagName,Re.deleted],class:`syntax-keyword`},{tag:[Re.function(Re.propertyName),Re.propertyName,Re.variableName,Re.number],class:`syntax-name`},{tag:[Re.definition(Re.variableName),Re.function(Re.variableName),Re.className,Re.attributeName,Re.url],class:`syntax-definition`},{tag:Re.link,class:`syntax-link`},{tag:Re.heading,class:`syntax-heading`},{tag:Re.emphasis,class:`syntax-emphasis`},{tag:Re.strong,class:`syntax-strong`},{tag:Re.strikethrough,class:`syntax-strike`},{tag:Re.invalid,class:`syntax-invalid`}]);function cXe(e,t){if(!t||!e.startsWith(t.code))return;let n=t.code.length;return Je.applyChanges(Je.addTree(t.tree),[{fromA:n,toA:n,fromB:n,toB:e.length}])}async function lXe(e,t,n){let r=rXe[t?.toLowerCase()];if(!r)return null;let i=(await oXe(r)).parse(e,cXe(e,n)),a=[],o=[a],s=(e,t)=>{e.split(`
|
|
176
176
|
`).forEach((e,n)=>{n>0&&o.push(a=[]),e&&a.push(t?{content:e,className:t}:{content:e})})},c=0;return Ne(i,sXe,(t,n,r)=>{t>c&&s(e.slice(c,t)),s(e.slice(t,n),r),c=n}),c<e.length&&s(e.slice(c)),{code:e,tokens:o,tree:i}}function uXe(e){let t=e?.split(`.`).pop()?.toLowerCase();return t?rXe[t]:void 0}function cC(e,t,n,r){var i=this,a=(0,G.useRef)(null),o=(0,G.useRef)(0),s=(0,G.useRef)(0),c=(0,G.useRef)(null),l=(0,G.useRef)([]),u=(0,G.useRef)(),d=(0,G.useRef)(),f=(0,G.useRef)(e),p=(0,G.useRef)(!0),m=(0,G.useRef)(),h=(0,G.useRef)();f.current=e;var g=typeof window<`u`,_=!t&&t!==0&&g;if(typeof e!=`function`)throw TypeError(`Expected a function`);t=+t||0;var v=!!(n||={}).leading,y=!(`trailing`in n)||!!n.trailing,b=!!n.flushOnExit&&y,x=`maxWait`in n,S=`debounceOnServer`in n&&!!n.debounceOnServer,C=x?Math.max(+n.maxWait||0,t):null,w=(0,G.useMemo)(function(){var e=function(e){var t=l.current,n=u.current;return l.current=u.current=null,o.current=e,s.current=s.current||e,d.current=f.current.apply(n,t)},n=function(e,t){_&&cancelAnimationFrame(c.current),c.current=_?requestAnimationFrame(e):setTimeout(e,t)},w=function(e){if(!p.current)return!1;var n=e-a.current;return!a.current||n>=t||n<0||x&&e-o.current>=C},T=function(t){return c.current=null,y&&l.current?e(t):(l.current=u.current=null,d.current)},E=function e(){var r=Date.now();if(v&&s.current===o.current&&D(),w(r))return T(r);if(p.current){var i=t-(r-a.current);n(e,x?Math.min(i,C-(r-o.current)):i)}},D=function(){r&&r({})},O=function(){if(g||S){var r,s=Date.now(),f=w(s);if(l.current=[].slice.call(arguments),u.current=i,a.current=s,b&&!m.current&&(m.current=function(){globalThis.document?.visibilityState===`hidden`&&h.current.flush()},(r=globalThis.document)==null||r.addEventListener==null||r.addEventListener(`visibilitychange`,m.current)),f){if(!c.current&&p.current)return o.current=a.current,n(E,t),v?e(a.current):d.current;if(x)return n(E,t),e(a.current)}return c.current||n(E,t),d.current}};return O.cancel=function(){var e=c.current;e&&(_?cancelAnimationFrame(c.current):clearTimeout(c.current)),o.current=0,l.current=a.current=u.current=c.current=null,e&&r&&r({})},O.isPending=function(){return!!c.current},O.flush=function(){return c.current?T(Date.now()):d.current},O},[v,x,t,C,y,b,_,g,S,r]);return h.current=w,(0,G.useEffect)(function(){return p.current=!0,function(){var e;b&&h.current.flush(),m.current&&=((e=globalThis.document)==null||e.removeEventListener==null||e.removeEventListener(`visibilitychange`,m.current),null),p.current=!1}},[b]),w}function dXe(e,t){return e===t}function lC(e,t,n){var r=n&&n.equalityFn||dXe,i=(0,G.useRef)(e),a=(0,G.useState)({})[1],o=cC((0,G.useCallback)(function(e){i.current=e,a({})},[a]),t,n,a),s=(0,G.useRef)(e);return r(s.current,e)||(o(e),s.current=e),[i.current,o]}var fXe=75;function pXe(e,t){let[n,r]=(0,G.useState)(null),i=(0,G.useRef)(null),[a,o]=lC(e,fXe,{leading:!0,maxWait:fXe});return(0,G.useEffect)(()=>()=>o.cancel(),[o]),(0,G.useEffect)(()=>{if(!t)return;let e=!1,n=i.current?.lang===t?i.current:void 0;return lXe(a,t,n).then(n=>{!e&&n?.tokens.length&&(i.current={...n,lang:t},r(i.current))}).catch(()=>{}),()=>{e=!0}},[a,t]),t?n:null}function mXe(e,t,n){return!e||e.lang!==n?null:t.startsWith(e.code)?e:null}var uC=G.memo(function({code:e,lang:t,lineClassName:n,...r}){let i=mXe(pXe(e,t),e,t);if(!i){if(!n)return(0,K.jsx)(`pre`,{...r,children:e});let t=e.split(`
|
|
@@ -721,6 +721,6 @@ window.parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/sandbox-proxy-
|
|
|
721
721
|
]`,Afi=[{name:`input`,description:`What the agent receives. A string or any JSON value.`,required:!0},{name:`groundTruth`,description:`Expected answer used by scorers.`,required:!1},{name:`metadata`,description:`Any object, useful for filtering and grouping.`,required:!1}];function jfi(){let{isCopied:e,handleCopy:t}=hC({text:kfi,showToast:!1});return(0,K.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,K.jsx)(T,{variant:`column`,tone:`ink`,className:`flex h-8 items-center`,children:`Each item looks like this`}),(0,K.jsx)(`dl`,{className:`divide-y divide-border rounded-lg border border-border`,children:Afi.map(e=>(0,K.jsxs)(`div`,{className:`grid grid-cols-[7rem_1fr] gap-3 px-3 py-2.5`,children:[(0,K.jsx)(`dt`,{className:H({tone:`ink`,variant:`meta`}),children:(0,K.jsx)(uX,{children:e.name})}),(0,K.jsxs)(`dd`,{className:`flex flex-col items-start gap-1.5 text-muted-foreground`,children:[(0,K.jsx)(T,{as:`span`,variant:`meta`,children:e.description}),e.required?(0,K.jsx)(eC,{variant:`success`,size:`xs`,children:`required`}):(0,K.jsx)(eC,{variant:`neutral`,emphasis:`subtle`,size:`xs`,children:`optional`})]})]},e.name))}),(0,K.jsxs)(`div`,{className:`overflow-hidden rounded-lg border border-border`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between border-b border-border bg-card py-1.5 pr-1.5 pl-3`,children:[(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,font:`mono`,children:`example.json`}),(0,K.jsx)(X,{icon:e?(0,K.jsx)(pC,{}):(0,K.jsx)(mC,{}),variant:`ghost`,size:`sm`,onClick:t,children:e?`Copied`:`Copy`})]}),(0,K.jsx)(bw,{variant:`embedded`,language:`json`,editable:!1,lineNumbers:!1,showCopyButton:!1,value:kfi,className:`p-3`})]}),(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:Ofi,target:`_blank`,rel:`noopener noreferrer`}),className:`self-start`,icon:(0,K.jsx)(tP,{}),children:`Datasets documentation`})]})}var Mfi=10,Nfi=`[
|
|
722
722
|
{ "input": "…", "groundTruth": "…" }
|
|
723
723
|
]`,Pfi=`flex min-h-0 flex-1 flex-col py-0`;function Ffi({tab:e,onTabChange:t,file:n,onFileSelect:r,onReplace:i,pastedText:a,onPastedTextChange:o,validation:s,isImporting:c}){return(0,K.jsxs)(gk,{value:e,defaultTab:`upload`,onValueChange:t,className:`flex h-full flex-col gap-3`,children:[(0,K.jsxs)(hk,{variant:`pill`,children:[(0,K.jsx)(_k,{value:`upload`,children:`Upload file`}),(0,K.jsx)(_k,{value:`paste`,children:`Paste JSON`})]}),(0,K.jsx)(vk,{value:`upload`,className:Pfi,children:n?(0,K.jsx)(zfi,{file:n,validation:s,onReplace:i,isImporting:c}):(0,K.jsx)(Ifi,{onFileSelect:r,disabled:c})}),(0,K.jsx)(vk,{value:`paste`,className:Pfi,children:(0,K.jsx)(bw,{"aria-label":`JSON items`,language:`json`,lineNumbers:!1,showCopyButton:!1,placeholder:Nfi,value:a,onChange:o,editable:!c,className:`min-h-50 flex-1`})})]})}function Ifi({onFileSelect:e,disabled:t}){let[n,r]=(0,G.useState)(!1),i=(0,G.useCallback)(t=>{let n=t.target.files?.[0];n&&e(n),t.target.value=``},[e]),a=(0,G.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),r(!0)},[]),o=(0,G.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),r(!1)},[]),s=(0,G.useCallback)(n=>{if(n.preventDefault(),n.stopPropagation(),r(!1),t)return;let i=n.dataTransfer.files?.[0];i&&e(i)},[t,e]);return(0,K.jsxs)(`div`,{"data-testid":`json-dropzone`,onDragOver:a,onDragLeave:o,onDrop:s,className:c(`relative flex flex-1 flex-col items-center justify-center gap-3 rounded-lg border border-dashed border-border bg-card px-4 py-6 text-center`,`hover:border-success-edge hover:bg-success-subtle`,n&&`border-success-edge bg-success-subtle`,t&&`cursor-wait opacity-60`),children:[(0,K.jsx)(`input`,{type:`file`,accept:`.json,application/json`,"aria-label":`Choose a JSON file`,onChange:i,disabled:t,className:`absolute inset-0 cursor-pointer opacity-0`}),(0,K.jsx)(`div`,{className:`flex size-9 items-center justify-center rounded-md border border-border bg-background text-muted-foreground`,children:(0,K.jsx)(pfi,{className:`size-icon-md`})}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,K.jsx)(T,{tone:`ink`,children:`Drop a JSON file here`}),(0,K.jsxs)(T,{variant:`caption`,tone:`muted`,children:[`or `,(0,K.jsx)(`span`,{className:`underline`,children:`choose a file`}),` from your computer`]})]}),(0,K.jsxs)(T,{variant:`meta`,tone:`muted`,children:[`.json files containing an array of items, up to `,Wli]})]})}function Lfi(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`}function Rfi(e){return typeof e==`string`?e:JSON.stringify(e)??``}function zfi({file:e,validation:t,onReplace:n,isImporting:r}){let i=`rows`in t?t.rows:[],a=`total`in t?t.total:0,o=i.slice(0,Mfi);return(0,K.jsxs)(`div`,{"data-testid":`json-file-card`,className:`rounded-lg border border-border`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2`,children:[(0,K.jsx)(xk,{className:`size-icon-md shrink-0 text-muted-foreground`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`ink`,font:`mono`,className:`min-w-0 flex-1 truncate`,children:e.name}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`shrink-0`,children:Lfi(e.size)}),(0,K.jsx)(X,{icon:(0,K.jsx)(xS,{}),variant:`ghost`,size:`sm`,onClick:n,disabled:r,children:`Replace`})]}),o.map(e=>(0,K.jsxs)(`div`,{className:`grid grid-cols-[2rem_1fr_auto] items-center gap-2 border-t border-border px-3 py-1.5`,children:[(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:e.index}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`ink`,font:`mono`,className:`truncate`,children:Rfi(e.input)}),e.hasInput?e.hasGroundTruth?null:(0,K.jsx)(eC,{variant:`warning`,size:`xs`,children:`no groundTruth`}):(0,K.jsx)(eC,{variant:`destructive`,size:`xs`,children:`no input`})]},e.index)),a>Mfi&&(0,K.jsxs)(T,{as:`p`,variant:`meta`,tone:`muted`,className:`border-t border-border px-3 py-1.5`,children:[`+ `,a-Mfi,` more`]})]})}var Bfi=e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsText(e)});function Vfi({datasetId:e,datasetName:t,open:n,onOpenChange:r,onSuccess:i}){let[a,o]=(0,G.useState)(`upload`),[s,c]=(0,G.useState)(null),[l,u]=(0,G.useState)(``),[d,f]=(0,G.useState)(null),[p,m]=(0,G.useState)(``),[h,g]=(0,G.useState)(!1),_=(0,G.useRef)(0),v=(0,G.useRef)(void 0),y=(0,G.useRef)(!1),{batchInsertItems:b}=ON(),x=a===`upload`?l:p,S=(0,G.useMemo)(()=>a===`upload`&&d?{status:`error`,kind:`parse`,message:d}:qli(x),[a,d,x]),C=(0,G.useCallback)(async e=>{let t=++_.current;if(!e.name.toLowerCase().endsWith(`.json`))f(`Only .json files are supported`);else if(e.size>4194304)f(`File is larger than ${Wli}`);else try{let n=await Bfi(e);if(t!==_.current)return;c({name:e.name,size:e.size}),u(n),f(null)}catch{if(t!==_.current)return;f(`Could not read the file`)}},[]),w=(0,G.useCallback)(()=>{_.current++,c(null),u(``),f(null)},[]),T=(0,G.useCallback)(()=>{_.current++,o(`upload`),c(null),u(``),f(null),m(``)},[]),E=(0,G.useCallback)(()=>{clearTimeout(v.current),y.current&&(v.current=setTimeout(T,150))},[T]);(0,G.useEffect)(()=>(y.current=!0,()=>{y.current=!1,clearTimeout(v.current)}),[]);let D=(0,G.useCallback)(()=>{r(!1),E()},[r,E]),O=(0,G.useCallback)(async()=>{if(S.status===`ready`){g(!0);try{await b.mutateAsync({datasetId:e,items:S.items}),iS.success(`Imported ${S.total} item${S.total===1?``:`s`}`),i?.(),r(!1),E()}catch(e){iS.error(e instanceof Error?e.message:`Failed to import items`)}finally{g(!1)}}},[S,b,e,i,r,E]);return(0,K.jsx)(nT,{open:n,onOpenChange:D,pending:h,children:(0,K.jsxs)(rT,{size:`xl`,children:[(0,K.jsxs)(iT,{children:[(0,K.jsx)(sT,{children:`Import into dataset`}),(0,K.jsxs)(cT,{children:[`Add items to `,t?(0,K.jsx)(`span`,{className:`text-foreground`,children:t}):`this dataset`,` from a JSON file or paste them directly.`]})]}),(0,K.jsx)(oT,{flush:!0,children:(0,K.jsxs)(`div`,{className:`grid divide-y divide-border md:grid-cols-[1.15fr_1fr] md:divide-x md:divide-y-0`,children:[(0,K.jsx)(`div`,{className:`flex min-h-[360px] flex-col p-4`,children:(0,K.jsx)(Ffi,{tab:a,onTabChange:o,file:s,onFileSelect:C,onReplace:w,pastedText:p,onPastedTextChange:m,validation:S,isImporting:h})}),(0,K.jsx)(`div`,{className:`p-4`,children:(0,K.jsx)(jfi,{})})]})}),(0,K.jsxs)(aT,{children:[(0,K.jsx)(Hfi,{validation:S}),(0,K.jsx)(lT,{children:`Cancel`}),(0,K.jsxs)(tT,{onConfirm:O,disabled:S.status!==`ready`,children:[h&&(0,K.jsx)(It,{}),S.status===`ready`?`Import ${S.total} item${S.total===1?``:`s`}`:`Import`]})]})]})})}function Hfi({validation:e}){let t=c(`size-1.5 shrink-0 rounded-full`,e.status===`idle`&&`bg-muted-foreground`,e.status===`ready`&&`bg-success-indicator`,e.status===`error`&&`bg-destructive-indicator`),n;switch(e.status){case`idle`:n=`No items yet`;break;case`ready`:n=(0,K.jsxs)(AC,{singleLine:!0,children:[(0,K.jsxs)(AC.Item,{className:`shrink-0`,children:[(0,K.jsx)(T,{as:`b`,variant:`label`,tone:`ink`,children:e.total}),` `,`item`,e.total===1?``:`s`,` ready`]}),e.missingGroundTruthCount>0&&(0,K.jsxs)(AC.Item,{children:[e.missingGroundTruthCount,` without groundTruth`]})]});break;case`error`:switch(e.kind){case`parse`:n=`Not valid JSON: ${e.message}`;break;case`not-array`:n=`Top level must be an array of items`;break;case`empty`:n=`The array has no items`;break;case`too-large`:n=`JSON is larger than ${Wli}`;break;case`missing-input`:n=(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`b`,variant:`label`,tone:`ink`,children:e.missingInputCount}),` `,`of `,e.total,` item`,e.total===1?``:`s`,` `,e.missingInputCount===1?`has`:`have`,` no`,` `,(0,K.jsx)(uX,{children:`input`})]})}}return(0,K.jsxs)(`div`,{role:`status`,className:`mr-auto flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(`span`,{className:t}),(0,K.jsx)(T,{tone:`muted`,as:`span`,variant:`caption`,className:`truncate`,children:n})]})}function Ufi(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;let t=e.tagName;return t===`INPUT`||t===`TEXTAREA`||t===`SELECT`||!!e.closest(`[role="dialog"]:not([data-item-panel])`)}function Wfi({active:e,onPrevious:t,onNext:n,onClose:r}){(0,G.useEffect)(()=>{if(!e)return;let i=e=>{e.defaultPrevented||Ufi(e.target)||(e.key===`PageUp`?(e.preventDefault(),t?.()):e.key===`PageDown`?(e.preventDefault(),n?.()):e.key===`Escape`&&(e.preventDefault(),r()))};return window.addEventListener(`keydown`,i),()=>window.removeEventListener(`keydown`,i)},[e,t,n,r])}var Gfi=(0,G.createContext)(null);function Kfi({datasetId:e,items:t,isLoadingItems:n,children:r}){let i=Ov(),a=SRe(`/datasets/:datasetId/items/:itemId`)?.params.itemId,o=(0,G.useCallback)(t=>{i(`/datasets/${e}/items/${encodeURIComponent(t)}`)},[i,e]),s=(0,G.useCallback)(()=>{i(`/datasets/${e}`)},[i,e]),c=(0,G.useMemo)(()=>a?t.findIndex(e=>e.id===a):-1,[t,a]),l=(0,G.useMemo)(()=>{if(c<=0)return;let e=t[c-1].id;return()=>o(e)},[c,t,o]),u=(0,G.useMemo)(()=>{if(c<0||c>=t.length-1)return;let e=t[c+1].id;return()=>o(e)},[c,t,o]);Wfi({active:!!a,onPrevious:l,onNext:u,onClose:s});let d=(0,G.useMemo)(()=>({datasetId:e,items:t,isLoadingItems:n,currentItemId:a,openItem:o,close:s,goToPreviousItem:l,goToNextItem:u}),[e,t,n,a,o,s,l,u]);return(0,K.jsx)(Gfi.Provider,{value:d,children:r})}function qfi(){let e=(0,G.useContext)(Gfi);if(!e)throw Error(`useDatasetItemPanel must be used within a DatasetItemPanelProvider`);return e}var Jfi=[`createdAt`];function Yfi({datasetId:e,onAddItemClick:t,onNavigateToDataset:n,toolbarActionsSlot:r}){let[i,a]=Rv(),{activeVersion:o}=MN(i,a),{sort:s,onSortChange:c}=u7({searchParams:i,setSearchParams:a,allowedKeys:Jfi}),l=(0,G.useMemo)(()=>s?{field:s.key,direction:s.direction===`asc`?`ASC`:`DESC`}:void 0,[s]),[u,d]=(0,G.useState)(!1),[f,p]=(0,G.useState)(!1),[m,h]=(0,G.useState)(!1),[g,_]=(0,G.useState)([]),[v,y]=(0,G.useState)(!1),[b,x]=(0,G.useState)([]),[S,C]=(0,G.useState)(!1),[w,T]=(0,G.useState)([]),[E,D]=(0,G.useState)(0),[O,k]=(0,G.useState)(``),[A]=lC(O,300),{data:j}=AN({datasetId:e,queryOptions:{enabled:!!e}}),{data:M=[],isLoading:N,setEndOfListElement:P,isFetchingNextPage:F,hasNextPage:I}=DN({datasetId:e,search:A||void 0,version:o,orderBy:l,queryOptions:{enabled:!!e}}),{deleteItems:L}=ON(),{currentItemId:R,openItem:z,close:B}=qfi();return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`grid h-full overflow-auto`,children:(0,K.jsx)(Dfi,{items:M,toolbarActionsSlot:r,isLoading:N,onItemClick:e=>{R===e?B():z(e)},featuredItemId:R,onAddClick:t??(()=>{}),onImportClick:()=>d(!0),onImportJsonClick:()=>p(!0),onBulkDeleteClick:e=>{T(e),C(!0)},onCreateDatasetClick:e=>{_(e),h(!0)},onAddToDatasetClick:e=>{x(e),y(!0)},datasetName:j?.name,clearSelectionTrigger:E,setEndOfListElement:P,isFetchingNextPage:F,hasNextPage:I,searchQuery:O,activeSearchQuery:A,onSearchChange:k,sort:s,onSortChange:c,currentDatasetVersion:j?.version})}),(0,K.jsx)(vfi,{datasetId:e,open:u,onOpenChange:d}),(0,K.jsx)(Vfi,{datasetId:e,datasetName:j?.name,open:f,onOpenChange:p}),(0,K.jsx)(nui,{open:m,onOpenChange:e=>{h(e),e||(_([]),D(e=>e+1))},items:g,onSuccess:e=>{h(!1),_([]),D(e=>e+1),n?.(e)}}),(0,K.jsx)(rui,{open:v,onOpenChange:e=>{y(e),e||(x([]),D(e=>e+1))},items:b,currentDatasetId:e}),(0,K.jsx)(QM,{open:S,onOpenChange:C,children:(0,K.jsxs)(QM.Content,{children:[(0,K.jsxs)(QM.Header,{children:[(0,K.jsx)(QM.Title,{children:`Delete Items`}),(0,K.jsxs)(QM.Description,{children:[`Are you sure you want to delete `,w.length,` item`,w.length===1?``:`s`,`? This action cannot be undone.`]})]}),(0,K.jsxs)(QM.Footer,{children:[(0,K.jsx)(QM.Cancel,{children:`Cancel`}),(0,K.jsx)(QM.Action,{onClick:async()=>{await L.mutateAsync({datasetId:e,itemIds:w}),iS.success(`Deleted ${w.length} items`),C(!1),T([]),D(e=>e+1)},children:L.isPending?`Deleting...`:`Delete`})]})]})})]})}var Xfi=`__create_tag__`;function Zfi({datasetId:e}){let{data:t}=AN({datasetId:e,queryOptions:{enabled:!!e}}),{data:n}=kN(),{updateDataset:r}=ON(),[i,a]=(0,G.useState)(``),o=(0,G.useMemo)(()=>Array.isArray(t?.tags)?t.tags:[],[t?.tags]),s=(0,G.useMemo)(()=>rli(n?.datasets??[]),[n?.datasets]),c=(0,G.useMemo)(()=>{let e=s.map(e=>({label:e,value:e,end:o.includes(e)?(0,K.jsx)(pC,{"data-testid":`tag-applied`,className:`size-icon-sm`}):void 0})),t=i.trim();return t.length>0&&!s.includes(t)&&!o.includes(t)?[{label:`Create "${t}"`,value:Xfi},...e]:e},[s,o,i]),l=t=>{r.mutate({datasetId:e,tags:t},{onError:()=>iS.error(`Failed to update tags`)})},u=e=>{let t=e===Xfi?i.trim():e;t&&!o.includes(t)&&l([...o,t])},d=e=>{l(o.filter(t=>t!==e))};return(0,K.jsxs)(`div`,{"data-testid":`dataset-tags-editor`,className:`flex flex-wrap items-center gap-2`,children:[o.map(e=>(0,K.jsxs)(ali,{value:e,size:`md`,className:`gap-1 pr-1`,children:[e,(0,K.jsx)(`button`,{type:`button`,"aria-label":`Remove tag ${e}`,disabled:r.isPending,onClick:()=>d(e),className:`cursor-pointer rounded-sm hover:opacity-70 disabled:opacity-50`,children:(0,K.jsx)(xw,{className:`size-icon-xs`})})]},e)),(0,K.jsx)(_N,{options:c,value:void 0,onValueChange:u,onInputValueChange:a,placeholder:`Add tag`,searchPlaceholder:`Search or create tag`,emptyText:`Type to create a tag`,variant:`ghost`,size:`sm`,className:`w-auto min-w-0`,disabled:r.isPending})]})}var F7=e=>JSON.stringify(e??null,null,2),Qfi=e=>e==null||e===``||typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0,$fi=[{key:`input`,title:`Input`,icon:(0,K.jsx)(H4,{}),value:e=>F7(e.input),payload:e=>e.input},{key:`groundTruth`,title:`Ground Truth`,icon:(0,K.jsx)(U4,{}),value:e=>Qfi(e.groundTruth)?void 0:F7(e.groundTruth),payload:e=>Qfi(e.groundTruth)?null:e.groundTruth},{key:`expectedTrajectory`,title:`Expected Trajectory`,icon:(0,K.jsx)(Emn,{}),value:e=>e.expectedTrajectory==null?void 0:F7(e.expectedTrajectory)},{key:`toolMocks`,title:`Tool Mocks`,icon:(0,K.jsx)(YS,{}),value:e=>e.toolMocks?.length?F7(e.toolMocks):void 0},{key:`requestContext`,title:`Request Context`,icon:(0,K.jsx)(JS,{}),value:e=>e.requestContext==null?void 0:F7(e.requestContext)},{key:`metadata`,title:`Metadata`,icon:(0,K.jsx)(wX,{}),value:e=>F7(e.metadata)}],epi=e=>e.toFixed(2);function tpi({delta:e,format:t=epi,higherIsBetter:n=!0,baseline:r}){let i=e===0?`text-muted-foreground`:(n?e>0:e<0)?`text-success-indicator`:`text-destructive-foreground`,a=e>0?`+`:e<0?`-`:``,o=`${a}${t(Math.abs(e))}`,s=r!==void 0&&r!==0&&Number.isFinite(r),l=(0,K.jsxs)(K.Fragment,{children:[a,s?`${(Math.abs(e)/Math.abs(r)*100).toFixed(1)}%`:t(Math.abs(e)),(0,K.jsx)(`span`,{"aria-hidden":!0,className:`inline-flex size-icon-sm shrink-0 [&>svg]:size-icon-sm`,children:e>0?(0,K.jsx)(R4,{}):e<0?(0,K.jsx)(PIr,{}):null})]}),u=c(`inline-flex items-center gap-1 tabular-nums`,i);return s?(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{render:(0,K.jsx)(`span`,{tabIndex:0,className:u}),children:l}),(0,K.jsx)(Tx,{children:o})]}):(0,K.jsx)(`span`,{className:u,children:l})}function npi({scorerId:e}){let{Link:t,paths:n}=sn();return(0,K.jsx)(t,{href:n.scorerLink(e),"aria-label":`Open ${e}`,className:`min-w-0 truncate hover:text-foreground hover:underline`,children:e})}function rpi({metrics:e}){if(e.length===0)return null;let t=e.some(e=>e.delta!=null);return(0,K.jsx)(`dl`,{className:c(`grid auto-rows-[minmax(1.5rem,auto)] items-center gap-x-4 gap-y-1`,t?`grid-cols-[minmax(0,1fr)_auto_auto]`:`grid-cols-[minmax(0,1fr)_auto]`),children:e.map(({id:e,icon:n,label:r,value:i,delta:a,formatDelta:o,rawValue:s,higherIsBetter:l,emphasis:u})=>(0,K.jsxs)(G.Fragment,{children:[(0,K.jsxs)(`dt`,{className:`flex min-w-0 items-center gap-1.5 text-body-sm text-muted-foreground [&>svg]:size-icon-sm [&>svg]:shrink-0`,children:[n,r]}),(0,K.jsx)(`dd`,{className:c(`flex min-w-0 justify-end text-right text-foreground tabular-nums`,u?`text-heading font-semibold`:`text-body-sm`),children:i}),t&&(0,K.jsx)(`dd`,{className:`flex justify-end text-body-sm`,children:a!=null&&(0,K.jsx)(tpi,{delta:a,format:o,higherIsBetter:l,baseline:s==null?void 0:s-a})})]},e))})}function I7({value:e}){return(0,K.jsx)(`div`,{className:`min-w-0 p-3 text-foreground`,children:typeof e==`string`?(0,K.jsx)(xY,{children:e}):(0,K.jsx)(bw,{value:JSON.stringify(e??null,null,2),language:`json`,editable:!1,lineNumbers:!1,showCopyButton:!1,variant:`embedded`,"aria-label":`JSON payload`})})}var ipi=`grid content-start gap-5`;function L7({title:e,actions:t,tone:n=`default`,collapsible:r=!0,framed:i=!1,expanded:a,onExpandedChange:o,children:s}){let l=i$({collapsedHeight:160}),u=a===void 0||!o?l:{...l,isExpanded:a,setExpanded:o,toggleExpanded:()=>o(!a)},d=r?(0,K.jsx)(r$,{state:u,expandLabel:`Expand`,children:s}):s;return(0,K.jsxs)(`section`,{className:`grid min-w-0 gap-2`,children:[(0,K.jsxs)(`div`,{className:`flex h-7 items-center justify-between gap-2`,children:[(0,K.jsx)(jQ.SectionHeading,{className:c(n===`negative`&&`text-destructive-foreground`),children:e}),(0,K.jsx)(`div`,{className:`ml-auto flex items-center gap-1`,children:t})]}),(0,K.jsxs)(`div`,{role:`region`,"aria-label":e,className:`min-w-0`,children:[i?n===`negative`?(0,K.jsx)(`div`,{className:`min-w-0 overflow-hidden rounded-lg border border-destructive-edge bg-destructive-subtle`,children:d}):(0,K.jsx)(nP,{className:`min-w-0 overflow-hidden`,children:d}):d,r&&u.isExpanded&&u.isClipped&&(0,K.jsx)(`div`,{className:`flex justify-center pt-1`,children:(0,K.jsx)(X,{size:`sm`,variant:`ghost`,icon:(0,K.jsx)(hZ,{}),onClick:()=>u.setExpanded(!1),children:`Collapse`})})]})]})}function api({item:e,diff:t}){return(0,K.jsxs)(`div`,{className:ipi,children:[(0,K.jsx)(rpi,{metrics:opi(e)}),$fi.map(n=>{if(n.payload&&!t){let t=n.payload(e);return t==null?null:(0,K.jsx)(L7,{title:n.title,framed:!0,actions:(0,K.jsx)(gC,{content:typeof t==`string`?t:JSON.stringify(t,null,2)}),children:(0,K.jsx)(I7,{value:t})},n.key)}let r=n.value(e),i=t?n.value(t.against):void 0;return r===void 0&&i===void 0?null:r===void 0?(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,K.jsx)(jQ.SectionHeading,{icon:n.icon,children:n.title}),(0,K.jsx)(T,{as:`p`,variant:`body`,tone:`muted`,children:`Not set in this version`})]},n.key):(0,K.jsx)(jQ.CodeSection,{title:n.title,icon:n.icon,codeStr:r,diff:t?{against:i??``,side:t.side}:void 0},n.key)})]})}function opi(e){let t=e.updatedAt&&new Date(e.updatedAt).getTime()!==new Date(e.createdAt).getTime(),n=[{id:`item-id`,icon:(0,K.jsx)(W6,{}),label:`Item Id`,value:(0,K.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,K.jsx)(`span`,{className:`font-mono`,title:e.id,children:aH(e.id)}),(0,K.jsx)(gC,{content:e.id,tooltip:`Copy item ID to clipboard`,variant:`link`})]}),delta:null},{id:`created`,icon:(0,K.jsx)($j,{}),label:`Created`,value:bC(e.createdAt,`date-time`),delta:null}];return t&&n.push({id:`updated`,icon:(0,K.jsx)(qS,{}),label:`Updated`,value:bC(e.updatedAt,`date-time`),delta:null}),n}function spi({field:e,errors:t}){return t.length===0?null:(0,K.jsx)(lk,{children:(0,K.jsx)(`span`,{className:`space-y-1`,children:t.map(t=>(0,K.jsxs)(`span`,{className:`block`,children:[(0,K.jsxs)(`code`,{className:`rounded bg-destructive-subtle px-1`,children:[e,t.path===`/`?``:t.path]}),`: `,t.message]},`${t.path}:${t.message}`))})})}function cpi({inputValue:e,setInputValue:t,groundTruthValue:n,setGroundTruthValue:r,metadataValue:i,setMetadataValue:a,trajectoryValue:o,setTrajectoryValue:s,toolMocksValue:c,setToolMocksValue:l,requestContextValue:u,setRequestContextValue:d,validationErrors:f,onSave:p,onCancel:m,isSaving:h}){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`mb-4`,children:(0,K.jsxs)(T,{as:`h3`,variant:`heading`,className:`flex items-center gap-2`,children:[(0,K.jsx)(iH,{className:`size-icon-lg`}),` Edit Item`]})}),(0,K.jsxs)(`div`,{className:`space-y-6`,children:[(0,K.jsxs)(ak,{invalid:f?.field===`input`,children:[(0,K.jsx)(sk,{required:!0,children:`Input (JSON)`}),(0,K.jsx)(bw,{value:e,onChange:t,showCopyButton:!1,className:`min-h-[120px]`}),f?.field===`input`&&(0,K.jsx)(spi,{field:`input`,errors:f.errors})]}),(0,K.jsxs)(ak,{invalid:f?.field===`groundTruth`,children:[(0,K.jsx)(sk,{children:`Ground Truth (JSON, optional)`}),(0,K.jsx)(bw,{value:n,onChange:r,showCopyButton:!1,className:`min-h-[100px]`}),f?.field===`groundTruth`&&(0,K.jsx)(spi,{field:`groundTruth`,errors:f.errors})]}),(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{children:`Expected Trajectory (JSON, optional)`}),(0,K.jsx)(bw,{value:o,onChange:s,showCopyButton:!1,className:`min-h-[80px]`})]}),(0,K.jsxs)(ak,{invalid:f?.field===`toolMocks`,children:[(0,K.jsx)(sk,{children:`Tool Mocks (JSON array, optional)`}),(0,K.jsxs)(ck,{children:[`Ordered static mocks served in place of executing the tool. Each entry is`,` `,(0,K.jsx)(`code`,{children:`{ "toolName", "args", "output" }`}),`. Calling a mocked tool with non-matching args fails the item; unmocked tools run live.`]}),(0,K.jsx)(bw,{value:c,onChange:l,showCopyButton:!1,className:`min-h-[100px]`}),f?.field===`toolMocks`&&(0,K.jsx)(spi,{field:`toolMocks`,errors:f.errors})]}),(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{children:`Request Context (JSON, optional)`}),(0,K.jsx)(bw,{value:u,onChange:d,showCopyButton:!1,className:`min-h-[80px]`})]}),(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{children:`Metadata (JSON, optional)`}),(0,K.jsx)(bw,{value:i,onChange:a,showCopyButton:!1,className:`min-h-[80px]`})]}),(0,K.jsxs)(`div`,{className:`flex gap-2 pt-4`,children:[(0,K.jsx)(X,{icon:(0,K.jsx)(pC,{}),variant:`primary`,onClick:p,disabled:h,children:h?`Saving...`:`Save changes`}),(0,K.jsx)(X,{icon:(0,K.jsx)(xw,{}),onClick:m,disabled:h,children:`Cancel`})]})]})]})}function lpi(){return(0,K.jsxs)(OC,{className:`inline-flex h-control-md w-fit cursor-pointer items-center gap-1.5 rounded-sm text-label text-muted-foreground focus-visible:outline-offset-2`,children:[(0,K.jsx)(y,{direction:`right`,className:`-mr-0.5 -ml-[4.3px] size-icon-md in-aria-expanded:translate-x-[2px]`}),`Advanced`]})}function upi({provider:e,modelId:t,canReset:n,onProviderChange:r,onModelIdChange:i,onReset:a,container:o}){let s=uS(),{isLoading:c}=Aq(),[l,u]=(0,G.useState)(!1);return s.active&&s.pickerVisible===!1?(0,K.jsxs)(uk,{className:`gap-2`,children:[(0,K.jsx)(dk,{children:`Model`}),(0,K.jsx)(`div`,{children:(0,K.jsx)(eC,{icon:(0,K.jsx)(CH,{}),children:`Locked by admin`})})]}):(0,K.jsxs)(uk,{className:`gap-2`,children:[(0,K.jsx)(dk,{children:`Model`}),c?(0,K.jsx)(zS,{className:`h-control-md w-60 rounded-full`}):(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsxs)($V,{className:`min-w-0`,children:[(0,K.jsx)(Mq,{value:e,onValueChange:e=>{r(e),u(!0)},container:o,"aria-label":`Model provider`,className:`w-auto min-w-0 shrink-0 gap-1 px-3`}),(0,K.jsx)(Nq,{llmId:e,value:t,onValueChange:i,open:l,onOpenChange:u,container:o,disabled:!e,"aria-label":`Model`,className:`w-auto min-w-0 gap-1 px-3`})]}),n&&(0,K.jsx)(X,{variant:`ghost`,size:`icon-md`,tooltip:`Use the agent's model`,onClick:a,children:(0,K.jsx)(vS,{})})]})]})}var dpi=(e,t)=>`${e}:${t}`,fpi=(e,t)=>e?.value===t?.value;function ppi({datasets:e,datasetId:t,version:n,onDatasetChange:r,container:i}){let{total:a}=DN({datasetId:t,search:void 0,version:n,queryOptions:{enabled:!!t}}),o=e.find(e=>e.value===t)??null;return(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{required:!0,info:`The items to run. Each item's input goes to the target. Runs on the latest version unless you pick one under Advanced.`,children:`Dataset`}),(0,K.jsxs)(fN,{items:e,value:o,onValueChange:e=>e&&r(e.value),isItemEqualToValue:fpi,autoHighlight:!0,children:[(0,K.jsx)(GOt,{placeholder:`Select a dataset`,children:a!==void 0&&(0,K.jsxs)(AC,{children:[(0,K.jsxs)(AC.Item,{children:[a,` `,a===1?`item`:`items`]}),(0,K.jsx)(AC.Item,{children:n===void 0?`latest`:`v${n}`})]})}),(0,K.jsxs)(pN,{container:i,children:[(0,K.jsx)(gN,{children:`No datasets found`}),(0,K.jsx)(mN,{children:e=>(0,K.jsx)(hN,{value:e,children:e.label},e.value)})]})]})]})}function mpi(e,t){return t!==void 0||(e??1)>1}function hpi({datasetId:e,version:t,onVersionChange:n,container:r}){let{data:i}=AN({datasetId:e,queryOptions:{enabled:!!e}});return mpi(i?.version,t)?(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{children:`Dataset version`}),(0,K.jsx)(VAt,{datasetId:e,value:t??null,onValueChange:e=>n(e??void 0),container:r})]}):null}function gpi({description:e,onDescriptionChange:t,disabled:n}){return(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{children:`Description`}),(0,K.jsx)(qk,{value:e,onChange:e=>t(e.target.value),placeholder:`Optional`,rows:2,disabled:n})]})}function _pi({name:e,defaultName:t,onNameChange:n,disabled:r}){return(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{children:`Experiment name`}),(0,K.jsx)(Jj,{value:e,placeholder:t,onChange:e=>n(e.target.value),disabled:r})]})}function vpi(e){try{return zO(e)}catch(e){console.error(`Failed to parse requestContextSchema:`,e);return}}function ypi({requestContextSchema:e,onChange:t}){let[n]=(0,G.useState)(()=>vpi(e));return n?(0,K.jsxs)(uk,{children:[(0,K.jsx)(dk,{children:`Request context`}),(0,K.jsx)(XM,{schema:n,onValuesChange:t,className:`[&_button[type=submit]]:hidden`})]}):(0,K.jsx)(`div`,{role:`alert`,children:(0,K.jsx)(Sk,{variant:`destructive`,children:`Failed to parse request context schema`})})}function bpi({schema:e,raw:t,onRawChange:n,onValuesChange:r}){return e?(0,K.jsx)(ypi,{requestContextSchema:e,onChange:r}):(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{children:`Request context (JSON)`}),(0,K.jsx)(bw,{value:t,onChange:n,showCopyButton:!1,"aria-label":`Request context JSON`,className:`min-h-[120px]`})]})}function xpi({onRun:e,canRun:t,isRunning:n}){return(0,K.jsx)(tT,{onConfirm:e,disabled:!t,children:(0,K.jsx)(Spi,{isRunning:n})})}function Spi({isRunning:e}){return e?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(It,{className:`h-4 w-4`}),`Starting…`]}):`Run experiment`}function Cpi({scorer:e}){let t=(0,K.jsx)(hN,{value:e,children:e.label});return e.description?(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{render:t}),(0,K.jsx)(Tx,{side:`right`,className:`max-w-64`,children:e.description})]}):t}function wpi(){let{data:e}=VN();return Object.entries(e??{}).filter(([,e])=>e.isRegistered).map(([e,t])=>({value:e,label:t.scorer?.config?.name||e,description:t.scorer?.config?.description||void 0}))}function Tpi(e,t){return e.map(e=>t.find(t=>t.value===e)??{value:e,label:e})}function Epi({scorerIds:e,usesDefaultScorers:t,onScorerIdsChange:n,container:r}){let i=wpi();return(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{info:`Grade each output automatically. Outputs are saved either way, so you can always review them yourself.`,children:`Scorers`}),(0,K.jsxs)(fN,{multiple:!0,items:i,value:Tpi(e,i),onValueChange:e=>n(e.map(e=>e.value)),isItemEqualToValue:fpi,autoHighlight:!0,children:[(0,K.jsx)(QOt,{children:(0,K.jsx)(VOt,{children:e=>(0,K.jsxs)(K.Fragment,{children:[e.map(e=>(0,K.jsx)($Ot,{children:e.label},e.value)),(0,K.jsx)(ekt,{placeholder:e.length===0?`No scoring, read the outputs yourself`:void 0})]})})}),(0,K.jsxs)(pN,{container:r,children:[(0,K.jsx)(gN,{children:`No scorers registered`}),(0,K.jsx)(mN,{children:e=>(0,K.jsx)(Cpi,{scorer:e},e.value)})]})]}),t&&(0,K.jsx)(ck,{children:`The dataset's default scorers.`})]})}var Dpi=[{type:`agent`,label:`Agents`},{type:`workflow`,label:`Workflows`},{type:`scorer`,label:`Scorers`}];function Opi(e){return Dpi.map(t=>({value:t.label,items:e.filter(e=>e.type===t.type)})).filter(e=>e.items.length>0)}function kpi({options:e,isLoading:t,target:n,onTargetValueChange:r,container:i,className:a}){return(0,K.jsxs)(ak,{className:a,children:[(0,K.jsx)(sk,{required:!0,info:`What runs on each item: an agent, a workflow, or a scorer you want to test.`,children:`Target`}),(0,K.jsxs)(fN,{items:Opi(e),value:n??null,onValueChange:e=>r(e?.value??``),isItemEqualToValue:fpi,disabled:t,autoHighlight:!0,children:[(0,K.jsx)(GOt,{placeholder:`Pick an agent, workflow or scorer`}),(0,K.jsxs)(pN,{container:i,children:[(0,K.jsx)(gN,{children:`Nothing to run`}),(0,K.jsx)(mN,{children:(e,t)=>(0,K.jsxs)(JOt,{items:e.items,children:[t>0?(0,K.jsx)(ZOt,{}):null,(0,K.jsx)(YOt,{children:e.value}),(0,K.jsx)(XOt,{children:e=>(0,K.jsx)(hN,{value:e,children:e.label},e.value)})]},e.value)})]})]})]})}var Api=(e,t)=>e.provider===t?.provider&&e.modelId===t?.modelId;function jpi(e){let[t,n]=(0,G.useState)(null),r=t??e??{provider:``,modelId:``},i=t?.provider&&t.modelId&&!Api(t,e)?t:void 0;return{provider:r.provider,modelId:r.modelId,setProvider:e=>{e!==r.provider&&n({provider:e,modelId:``})},setModelId:e=>n({provider:r.provider,modelId:e}),reset:()=>n(null),canReset:t!==null&&!Api(t,e),agentModel:i}}function Mpi(e,t){return e||(t[0]?.value??``)}function Npi({initialDatasetId:e,initialDatasetVersion:t}){let{data:n}=kN(),r=(n?.datasets??[]).map(e=>({value:e.id,label:e.name})),[i,a]=(0,G.useState)(e??``),[o,s]=(0,G.useState)(t);return{datasets:r,datasetId:Mpi(i,r),version:o,setVersion:s,selectDataset:e=>{a(e),s(void 0)}}}function Ppi({initialName:e,targetLabel:t}){let[n,r]=(0,G.useState)(e??``),[i]=(0,G.useState)(usi),a=dsi(t??`experiment`,i);return{name:n,setName:r,defaultName:a,runName:n.trim()||a}}var Fpi=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Ipi(e){if(Fpi(e)&&Object.keys(e).length!==0)return e}function Lpi(e){try{return{ok:!0,value:JSON.parse(e)}}catch{return{ok:!1}}}function Rpi(e){if(!e.trim())return{ok:!0};let t=Lpi(e);return t.ok?Fpi(t.value)?{ok:!0,requestContext:t.value}:{ok:!1,message:`Request context must be a JSON object`}:{ok:!1,message:`Request context must be valid JSON`}}function zpi(e){let t=Object.entries(e).filter(([,e])=>e!==void 0&&e!==``);return t.length===0?{ok:!0}:{ok:!0,requestContext:Object.fromEntries(t)}}function Bpi(e){let{data:t}=AN({datasetId:e,queryOptions:{enabled:!!e}}),[n,r]=(0,G.useState)(``),[i,a]=(0,G.useState)({}),o=Ipi(t?.requestContextSchema);return{schema:o,raw:n,setRaw:r,setValues:a,resetValues:()=>a({}),resolve:()=>o?zpi(i):Rpi(n)}}function Vpi({datasetId:e,initialScorerIds:t}){let{data:n}=AN({datasetId:e,queryOptions:{enabled:!!e}}),[r,i]=(0,G.useState)(t),a=n?.scorerIds??[];return{scorerIds:r??a,usesDefaultScorers:r===void 0&&a.length>0,setScorerIds:i,resetScorers:()=>i(void 0)}}var Hpi=(e,t,n,r)=>({value:dpi(e,t),label:n,type:e,id:t,defaultModel:r});function Upi(e,t){if(e&&t)return{provider:MK(e),modelId:t}}function Wpi(){let{data:e,isLoading:t}=wN(),{data:n,isLoading:r}=eN({}),{data:i,isLoading:a}=VN();return{options:[...Object.entries(e??{}).map(([e,t])=>Hpi(`agent`,e,t.name||e,Upi(t.provider,t.modelId))),...Object.entries(n??{}).map(([e,t])=>Hpi(`workflow`,e,t.name||e)),...Object.entries(i??{}).map(([e,t])=>Hpi(`scorer`,e,t.scorer?.config?.name||e))],isLoading:t||r||a}}function Gpi({initialTargetType:e,initialTargetId:t}){return!e||!t?``:dpi(e,t)}function Kpi(e,t,{initialTargetType:n,initialTargetId:r}){let i=e.find(e=>e.value===t);if(i)return i;if(n&&r&&t)return{value:t,label:r,type:n,id:r}}function qpi(e){let{options:t,isLoading:n}=Wpi(),[r,i]=(0,G.useState)(()=>Gpi(e));return{options:t,isLoading:n,target:Kpi(t,r,e),setTargetValue:i}}var Jpi=e=>(e.metaKey||e.ctrlKey)&&e.key===`Enter`,Ypi=e=>e.trim()||void 0,Xpi=e=>e.length>0?e:void 0;function Zpi({open:e,onOpenChange:t,onOpenChangeComplete:n,onSuccess:r,initialDatasetId:i,initialDatasetVersion:a,initialScorerIds:o,initialTargetType:s,initialTargetId:c,initialName:l,initialDescription:u}){let d=(0,G.useRef)(null),f=qpi({initialTargetType:s,initialTargetId:c}),p=Npi({initialDatasetId:i,initialDatasetVersion:a}),m=Vpi({datasetId:p.datasetId,initialScorerIds:o}),h=Bpi(p.datasetId),{target:g}=f,_=jpi(g?.defaultModel),v=g?.type===`agent`,y=v?_.agentModel:void 0,b=Ppi({initialName:l,targetLabel:y&&g?`${g.label} ${y.modelId}`:g?.label}),[x,S]=(0,G.useState)(u??``),[C,w]=(0,G.useState)(!1),{triggerExperiment:T}=ON(),{datasetId:E}=p,D=T.isPending,O=h.schema?E:void 0,k=!!(E&&g)&&!f.isLoading&&!D,A=e=>{f.setTargetValue(e),_.reset()},j=e=>{p.selectDataset(e),m.resetScorers(),h.resetValues()},M=async()=>{if(!k||!g)return;let e=h.resolve();if(!e.ok)$x.error(e.message);else try{let n=await T.mutateAsync({datasetId:E,name:b.runName,description:Ypi(x),targetType:g.type,targetId:g.id,agentModel:y,scorerIds:Xpi(m.scorerIds),version:p.version,requestContext:e.requestContext});$x.success(`Experiment started`),t(!1),r?.(n.experimentId)}catch(e){$x.error(e instanceof Error?e.message:`Failed to start experiment`)}};return(0,K.jsx)(nT,{open:e,onOpenChange:t,onOpenChangeComplete:n,pending:D,children:(0,K.jsxs)(rT,{ref:d,size:`lg`,onKeyDown:e=>{Jpi(e)&&k&&(e.preventDefault(),M())},children:[(0,K.jsxs)(iT,{children:[(0,K.jsx)(sT,{children:`New experiment`}),(0,K.jsx)(cT,{children:`Run every item in a dataset through an agent, workflow or scorer.`})]}),(0,K.jsx)(oT,{children:(0,K.jsxs)(DC,{open:C,onOpenChange:w,className:`py-3`,children:[(0,K.jsxs)(`div`,{className:`space-y-6`,children:[(0,K.jsx)(_pi,{name:b.name,defaultName:b.defaultName,onNameChange:b.setName,disabled:D}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-6 sm:flex-row sm:items-start sm:gap-4`,children:[(0,K.jsx)(kpi,{options:f.options,isLoading:f.isLoading,target:g,onTargetValueChange:A,container:d,className:`min-w-0 flex-1`}),v&&(0,K.jsx)(upi,{provider:_.provider,modelId:_.modelId,canReset:_.canReset,onProviderChange:_.setProvider,onModelIdChange:_.setModelId,onReset:_.reset,container:d})]}),(0,K.jsx)(ppi,{datasets:p.datasets,datasetId:E,version:p.version,onDatasetChange:j,container:d}),(0,K.jsx)(Epi,{scorerIds:m.scorerIds,usesDefaultScorers:m.usesDefaultScorers,onScorerIdsChange:m.setScorerIds,container:d})]}),(0,K.jsx)(`div`,{className:`mt-6`,children:(0,K.jsx)(lpi,{})}),(0,K.jsxs)(kC,{className:`space-y-6 pt-4`,children:[E&&(0,K.jsx)(hpi,{datasetId:E,version:p.version,onVersionChange:p.setVersion,container:d}),(0,K.jsx)(gpi,{description:x,onDescriptionChange:S,disabled:D}),(0,K.jsx)(bpi,{schema:h.schema,raw:h.raw,onRawChange:h.setRaw,onValuesChange:h.setValues},O)]})]})}),(0,K.jsxs)(aT,{children:[(0,K.jsx)(lT,{children:`Cancel`}),(0,K.jsx)(xpi,{onRun:M,canRun:k,isRunning:D})]})]})})}function Qpi({open:e,onOpenChange:t,onSuccess:n,...r}){let[i,a]=(0,G.useState)(0);return(0,K.jsx)(Zpi,{open:e,onOpenChange:t,onOpenChangeComplete:e=>{e||a(e=>e+1)},onSuccess:n,...r},`${i}:${JSON.stringify(r)}`)}var $pi=`mastra_model_total_input_tokens`,emi=`mastra_model_total_output_tokens`,tmi=()=>({estimatedCost:0,costUnits:new Set,hasUnknownCostUnit:!1});function nmi(e){let t=e.dimensions.name;if(t===`mastra_model_total_input_tokens`)return`inputTokens`;if(t===`mastra_model_total_output_tokens`)return`outputTokens`}function rmi(e,t,n){e[t]=(e[t]??0)+n.value,n.estimatedCost!=null&&(e.estimatedCost+=n.estimatedCost,n.costUnit?e.costUnits.add(n.costUnit.toLowerCase()):e.hasUnknownCostUnit=!0)}function imi(e){let t=!e.hasUnknownCostUnit&&e.costUnits.size===1;return{inputTokens:e.inputTokens,outputTokens:e.outputTokens,estimatedCost:t?e.estimatedCost:void 0,costUnit:t?[...e.costUnits][0]:void 0}}var ami=2e3;function omi(e){let t=tmi(),n=new Map;for(let r of e.groups){let e=nmi(r);if(!e)continue;rmi(t,e,r);let i=r.dimensions.traceId;i&&rmi(K6(n,i,tmi),e,r)}let r={};for(let[e,t]of n)r[e]=imi(t);return{summary:imi(t),traces:r}}var smi=5,cmi=e=>!e||Object.keys(e.traces).length===0&&e.summary.inputTokens===void 0&&e.summary.outputTokens===void 0,lmi=({experiments:e,supportsMetrics:t})=>{let n=Y(),r=pAt(e.map(e=>e.id));return w_({queries:e.map(({id:e,status:r})=>{let i=r!==`running`&&r!==`pending`;return{queryKey:[`experiment-item-usage`,e,i],queryFn:async()=>omi(await n.getMetricBreakdown({name:[$pi,emi],aggregation:`sum`,groupBy:[`traceId`,`name`],filters:{experimentId:e}})),enabled:t&&i,refetchInterval:e=>cmi(e.state.data)&&e.state.dataUpdateCount<smi?ami:!1}}),combine:r})},umi=({experimentId:e,experimentStatus:t,supportsMetrics:n,queryOptions:r})=>{let i=Y(),a=!!e&&n,o=T_({queryKey:[`experiment-metrics`,e],refetchInterval:t===`running`||t===`pending`?2e3:!1,queryFn:async()=>{if(!e)throw Error(`experimentId is required`);let t={experimentId:e},[n,r,a]=await Promise.all([i.getMetricAggregate({name:[`mastra_model_total_input_tokens`,`mastra_model_total_output_tokens`],aggregation:`sum`,filters:t}),i.getMetricAggregate({name:[`mastra_agent_duration_ms`],aggregation:`avg`,filters:t}),i.getMetricAggregate({name:[`mastra_agent_duration_ms`],aggregation:`count`,filters:t})]);return{totalTokens:n.value??null,estimatedCost:n.estimatedCost??null,costUnit:n.costUnit??null,avgAgentDurationMs:r.value??null,agentRuns:a.value??null}},...r});return{data:o.data,isLoading:o.isLoading,isEnabled:a}},dmi=({traceId:e,queryOptions:t})=>{let n=Y();return T_({queryKey:[`experiment-trace-light`,e],queryFn:async()=>{if(!e)throw Error(`Trace ID is required`);return n.getTraceLight(e)},...t})};function fmi({datasetId:e,target:t,queryOptions:n}){let r=Y(),i={perPage:100};return t?.targetType&&(i.targetType=t.targetType),t?.targetId&&(i.targetId=t.targetId),T_({queryKey:e?[`dataset-experiments`,e,i]:[`experiments`,i],queryFn:()=>e?r.listDatasetExperiments(e,i):r.listExperiments(i),...n})}var pmi=`mastra_agent_duration_ms`,mmi=500,hmi=5e3;function gmi(e){let t=[];for(let n=0;n<e.length;n+=mmi)t.push(e.slice(n,n+mmi));return t}function _mi(e){return e.flatMap(e=>e.status===`fulfilled`?[e.value]:[])}function vmi(e,t,n){let r=new Set(e),i=new Map;for(let e of t.flatMap(e=>e.groups)){let t=e.dimensions.experimentId,n=nmi(e);t&&r.has(t)&&n&&rmi(K6(i,t,tmi),n,e)}let a=new Map;for(let[e,t]of i)a.set(e,imi(t));for(let e of n.flatMap(e=>e.groups)){let t=e.dimensions.experimentId;t&&r.has(t)&&(K6(a,t,()=>({})).avgDurationMs=e.value)}return a}var ymi=({experiments:e,supportsMetrics:t})=>{let n=Y(),r=[...new Set(e.map(e=>e.id))].toSorted(),i=e.some(({status:e})=>e===`running`||e===`pending`);return T_({queryKey:[`experiments-list-metrics`,r],enabled:t&&r.length>0,queryFn:async()=>{let e=gmi(r),[t,i]=await Promise.all([Promise.allSettled(e.map(e=>n.getMetricBreakdown({name:[$pi,emi],aggregation:`sum`,groupBy:[`experimentId`,`name`],filters:{experimentIds:e},limit:e.length*2}))),Promise.allSettled(e.map(e=>n.getMetricBreakdown({name:[pmi],aggregation:`avg`,groupBy:[`experimentId`],filters:{experimentIds:e},limit:e.length})))]);return vmi(r,_mi(t),_mi(i))},placeholderData:__,refetchInterval:i?hmi:!1})};function bmi({datasetId:e,target:t,orderBy:n,queryOptions:r}){let i=Y(),{inView:a,setRef:o}=$M(),s=t?.targetType||void 0,c=t?.targetId||void 0,l=O_({queryKey:e?[`dataset-experiments`,e,`infinite`,{targetType:s,targetId:c,orderBy:n}]:[`experiments`,`infinite`,{targetType:s,targetId:c,orderBy:n}],queryFn:({pageParam:t})=>{let r={page:t,perPage:100};return s&&(r.targetType=s),c&&(r.targetId=c),n&&(r.orderBy=n),e?i.listDatasetExperiments(e,r):i.listExperiments(r)},initialPageParam:0,getNextPageParam:(e,t,n)=>{if(e?.experiments?.length&&e.pagination?.hasMore)return n+1},select:e=>e.pages.flatMap(e=>e?.experiments??[]),...r});return(0,G.useEffect)(()=>{a&&l.hasNextPage&&!l.isFetchingNextPage&&l.fetchNextPage()},[a,l]),{...l,setEndOfListElement:o}}var xmi=(0,G.createContext)(null);function Smi({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:i,hasNextPage:a,children:o}){let s=Ov(),c=SRe(`/experiments/:experimentId/items/:itemId`)?.params.itemId,l=(0,G.useCallback)(t=>{s(`/experiments/${e}/items/${encodeURIComponent(t)}`)},[s,e]),u=(0,G.useCallback)(()=>{s(`/experiments/${e}`)},[s,e]),d=(0,G.useMemo)(()=>c?r.findIndex(e=>e.itemId===c):-1,[r,c]),f=(0,G.useMemo)(()=>{if(d<=0)return;let e=r[d-1].itemId;return()=>l(e)},[d,r,l]),p=(0,G.useMemo)(()=>{if(d<0||d>=r.length-1)return;let e=r[d+1].itemId;return()=>l(e)},[d,r,l]);Wfi({active:!!c,onPrevious:f,onNext:p,onClose:u});let m=(0,G.useMemo)(()=>({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:i,hasNextPage:a,currentItemId:c,openItem:l,close:u,goToPreviousItem:f,goToNextItem:p}),[e,t,n,r,i,a,c,l,u,f,p]);return(0,K.jsx)(xmi.Provider,{value:m,children:o})}function Cmi(){let e=(0,G.useContext)(xmi);if(!e)throw Error(`useExperimentItemPanel must be used within an ExperimentItemPanelProvider`);return e}function wmi(e,t){if(!e||typeof e!=`object`||!(t in e))return;let n=e[t];return typeof n==`string`&&n?n:void 0}function Tmi(e){if(e.targetType===`agent`)return wmi(e.output,`text`)}function Emi(e){if(e.targetType)return Tmi(e);let{output:t}=e;if(t!=null&&t!==``)return typeof t==`string`?t:JSON.stringify(t)}function Dmi(e){let t=[];return e.some(e=>Emi(e))&&t.push({name:`output`,label:`Output`,size:`20rem`}),e.some(e=>R7(e))&&t.push({name:`error`,label:`Error`,size:`20rem`}),t}function R7(e){let t=wmi(e.error,`message`);if(t)return t;if(e.targetType===`agent`&&e.output&&typeof e.output==`object`)return wmi(e.output.error,`message`)}function Omi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function kmi(e){return Array.isArray(e)?e.flatMap(e=>Omi(e)&&Omi(e.payload)?[e.payload]:[]):[]}function Ami(e){if(e.targetType!==`agent`||!Omi(e.output))return[];let t=new Map(kmi(e.output.toolResults).map(e=>[e.toolCallId,e]));return kmi(e.output.toolCalls).flatMap(e=>{if(typeof e.toolName!=`string`)return[];let n=t.get(e.toolCallId);return[{toolName:e.toolName,args:e.args,...n&&{result:n.result,isError:n.isError===!0}}]})}function jmi(e){if(Tmi(e)||R7(e))return;let t=Ami(e).length;if(t!==0)return`No final text response after ${t} tool ${t===1?`call`:`calls`}`}var z7=e=>e==null?`-`:e.toFixed(2),Mmi=e=>iC(e)??`-`,Nmi=(e,t)=>e!=null&&t!=null?e-t:null,Pmi=new Set(Intl.supportedValuesOf(`currency`)),Fmi={minimumFractionDigits:3,maximumFractionDigits:3},B7=(e,t)=>{if(e===void 0)return`-`;let n=(t??`usd`).toUpperCase();return Pmi.has(n)?new Intl.NumberFormat(`en-US`,{style:`currency`,currency:n,...Fmi}).format(e):`${new Intl.NumberFormat(`en-US`,Fmi).format(e)} ${t}`},Imi=e=>t=>B7(t,e),Lmi=new Intl.NumberFormat(`en-US`),V7=e=>e===void 0?`-`:Lmi.format(e),H7=e=>{if(e?.inputTokens!==void 0||e?.outputTokens!==void 0)return(e.inputTokens??0)+(e.outputTokens??0)};function Rmi({scorerId:e,reason:t,nested:n=!1}){let r=`text-muted-foreground hover:text-foreground [&>svg]:size-icon-sm`;return(0,K.jsxs)(yX,{children:[(0,K.jsx)(bX,{delay:0,closeDelay:100,render:n?(0,K.jsx)(`span`,{"aria-hidden":!0,"data-testid":`score-reason-${e}`,className:`flex ${r}`}):(0,K.jsx)(`button`,{type:`button`,"aria-label":`Show ${e} reason`,className:`cursor-pointer ${r}`}),children:(0,K.jsx)(Yx,{})}),(0,K.jsx)(xX,{side:`left`,align:`start`,className:`max-h-80 max-w-100 overflow-y-auto`,onClick:e=>e.stopPropagation(),children:(0,K.jsx)(xY,{children:t})})]})}var zmi=new Set([`itemId`,`id`,`status`,`input`,`output`,`error`,`tags`,`scores`,`cost`,`tokens`,`duration`]);function Bmi({results:e,isLoading:t,featuredResultId:n,onResultClick:r,columns:i,scoresByItemId:a,scorerIds:o,setEndOfListElement:s,isFetchingNextPage:c,hasNextPage:l,emptyMessage:u=`No results yet`,selectedIds:d,onToggleSelect:f,onToggleSelectAll:p}){let{Link:m,paths:h}=sn(),g=!!(d&&f),_=i.filter(e=>zmi.has(e.name)||o?.includes(e.name)),v=[g?`2rem`:``,..._.map(e=>e.size)].filter(Boolean).join(` `),y=e=>_.some(t=>t.name===e),b=y(`itemId`)||y(`id`),x=y(`status`),S=y(`input`),C=y(`output`),w=y(`error`),T=y(`tags`),E=y(`scores`),D=y(`cost`),O=y(`tokens`),k=y(`duration`),A=d?e.filter(e=>d.has(e.id)).length:0,j=e.length>0&&A===e.length,{containerRef:M,getRowProps:N}=PZ({count:e.length}),P=e=>o?.includes(e.name)?(0,K.jsx)(Z.TopCell,{children:(0,K.jsxs)(m,{href:h.scorerLink(e.name),className:`flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-icon-sm [&>svg]:shrink-0`,children:[(0,K.jsx)(JN,{}),(0,K.jsx)(`span`,{className:`min-w-0 truncate`,children:e.label})]})},e.name):(0,K.jsx)(Z.TopCell,{children:e.label},e.name);return t?(0,K.jsx)(DH,{columns:v}):(0,K.jsxs)(Z,{columns:v,className:`min-w-0`,scrollRef:M,children:[(0,K.jsxs)(Z.Top,{hasLeadingCell:g,children:[g&&(p?(0,K.jsx)(Z.TopSelectCell,{checked:j?!0:A>0&&`indeterminate`,onToggle:p,"aria-label":`Select all`}):(0,K.jsx)(Z.TopCell,{children:`\xA0`})),g?(0,K.jsx)(Z.TopCells,{colStart:2,children:_.map(P)}):_.map(P)]}),e.length===0?(0,K.jsx)(Z.NoMatch,{message:u}):(0,K.jsxs)(K.Fragment,{children:[e.map((e,t)=>{let i=!!e.error,s=e.id===n,c=(0,K.jsxs)(K.Fragment,{children:[b&&(0,K.jsx)(Z.Cell,{className:`text-muted-foreground`,children:e.itemId?.slice(0,8)??``}),x&&(0,K.jsx)(Z.Cell,{className:`flex items-center`,"data-testid":`result-status-${e.id}`,children:e.status?(0,K.jsx)(x7r,{status:e.status}):(0,K.jsx)(`span`,{className:`text-placeholder`,children:`—`})}),S&&(0,K.jsx)(Z.TextCell,{font:`mono`,children:Wmi(Umi(e.input),200)}),C&&(0,K.jsx)(Z.Cell,{className:`truncate font-mono`,"data-testid":`result-output-${e.id}`,children:Emi(e)??``}),w&&(0,K.jsx)(Z.Cell,{className:`truncate text-destructive-foreground`,"data-testid":`result-error-${e.id}`,children:R7(e)??``}),T&&(0,K.jsx)(Z.Cell,{className:`flex items-center gap-1 overflow-hidden`,"data-testid":`result-tags-${e.id}`,children:e.tags?.map(e=>(0,K.jsx)(ali,{value:e,className:`shrink-0`},e))}),E&&(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(Vmi,{scores:e.scores})}),D&&(0,K.jsx)(Z.Cell,{className:`text-muted-foreground tabular-nums`,"data-testid":`result-cost-${e.id}`,children:B7(e.usage?.estimatedCost,e.usage?.costUnit)}),O&&(0,K.jsx)(Z.Cell,{className:`text-muted-foreground tabular-nums`,"data-testid":`result-tokens-${e.id}`,children:V7(H7(e.usage))}),k&&(0,K.jsx)(Z.Cell,{className:`text-muted-foreground tabular-nums`,"data-testid":`result-duration-${e.id}`,children:iC(Hmi(e))??`-`}),o?.map(t=>{let n=(a?.[e.itemId])?.find(e=>e.scorerId===t),r=n?.reason?.trim();return(0,K.jsxs)(Z.Cell,{className:`flex items-center gap-1.5 text-muted-foreground tabular-nums`,children:[n==null?`-`:n.score.toFixed(3),r&&(0,K.jsx)(Rmi,{scorerId:t,reason:r,nested:!0})]},t)})]});return g?(0,K.jsxs)(Z.RowWrapper,{children:[(0,K.jsx)(Z.SelectCell,{checked:d.has(e.id),onToggle:()=>f(e.id),"aria-label":`Select result ${e.itemId}`}),(0,K.jsx)(Z.RowButton,{colStart:2,featured:s,variant:i?`error`:`default`,"data-selected":s||void 0,onClick:()=>r(e.id),...N(t),children:c})]},e.id):(0,K.jsx)(Z.RowButton,{featured:s,variant:i?`error`:`default`,"data-selected":s||void 0,onClick:()=>r(e.id),...N(t),children:c},e.id)}),(0,K.jsx)(Z.NextPageLoading,{isLoading:c,hasMore:l,setEndOfListElement:s})]})]})}function Vmi({scores:e}){let t=Array.isArray(e)?e.map(e=>e.score).filter(e=>e!=null):Object.values(e??{});return t.length===0?(0,K.jsx)(T,{variant:`meta`,tone:`faint`,children:`—`}):(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(Dx,{size:`xs`,className:`text-muted-foreground`,children:(0,K.jsx)(G4,{})}),(0,K.jsx)(T,{variant:`meta`,tone:`muted`,font:`mono`,children:t[0].toFixed(2)}),t.length>1&&(0,K.jsxs)(eC,{children:[`+`,t.length-1]})]})}function Hmi({startedAt:e,completedAt:t}){if(e&&t)return new Date(t).getTime()-new Date(e).getTime()}function Umi(e){return e==null?`-`:typeof e==`string`?e:JSON.stringify(e,null,2)}function Wmi(e,t){return e.length<=t?e:e.slice(0,t-1)+`...`}function Gmi({experimentId:e,experimentStatus:t,results:n,isLoading:r,setEndOfListElement:i,isFetchingNextPage:a,hasNextPage:o,selectedIds:s,onToggleSelect:c,onToggleSelectAll:l,supportsMetrics:u=!1}){let{currentItemId:d,openItem:f,close:p}=Cmi(),m=(0,G.useMemo)(()=>d?n.find(e=>e.itemId===d)?.id??null:null,[n,d]),{data:h}=jN({experimentId:e,experimentStatus:t,queryOptions:{enabled:!!e}}),{data:g}=lmi({experiments:(0,G.useMemo)(()=>[{id:e,status:t}],[e,t]),supportsMetrics:u}),_=g[e]?.traces,v=(0,G.useMemo)(()=>_?n.map(e=>({...e,usage:e.traceId?_[e.traceId]:void 0})):n,[n,_]),y=(0,G.useMemo)(()=>{if(!h)return[];let e=new Set;for(let t of Object.values(h))for(let n of t)e.add(n.scorerId);return[...e].sort()},[h]),b=(0,G.useCallback)(e=>{let t=n.find(t=>t.id===e);t&&(t.itemId===d?p():f(t.itemId))},[n,d,p,f]),x=(0,G.useMemo)(()=>[{name:`itemId`,label:`Item ID`,size:`7rem`},{name:`input`,label:`Input`,size:`20rem`},...Dmi(n),...u?[{name:`cost`,label:`Cost`,size:`auto`},{name:`tokens`,label:`Tokens`,size:`auto`}]:[],{name:`duration`,label:`Duration`,size:`auto`},...y.map(e=>({name:e,label:e,size:`auto`}))],[n,y,u]);return(0,K.jsx)(`div`,{className:`h-full min-h-0 min-w-0 overflow-y-auto`,children:(0,K.jsx)(Bmi,{results:v,isLoading:r,featuredResultId:m,onResultClick:b,columns:x,scoresByItemId:h,scorerIds:y,setEndOfListElement:i,isFetchingNextPage:a,hasNextPage:o,selectedIds:s,onToggleSelect:c,onToggleSelectAll:l})})}function Kmi({children:e,className:t}){return(0,K.jsx)(`div`,{className:c(`grid content-start gap-4 overflow-y-auto`,t),children:e})}function qmi({children:e,className:t}){return(0,K.jsx)(`div`,{className:`flex w-full overflow-y-auto`,children:(0,K.jsx)(`div`,{className:c(`grid w-full content-start gap-4 overflow-y-auto`,t),children:e})})}function Jmi({children:e,className:t}){return(0,K.jsx)(`div`,{className:c(`flex w-full flex-wrap items-center justify-between gap-3 gap-x-4`,t),children:e})}var Ymi=Object.assign(qmi,{Content:Kmi,Toolbar:Jmi});function Xmi({children:e,className:t}){return(0,K.jsx)(`div`,{className:c(`grid size-full grid-cols-1 overflow-y-auto`,t),children:e})}function Zmi({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){let{data:i}=IAt({datasetId:e,queryOptions:{enabled:!!e}}),a=(i??[]).map(e=>{let t=`v${e.version}`,n=bC(e.createdAt,`date-time`),r=e.isCurrent?`(current)`:void 0;return{value:String(e.version),label:[t,n,r].filter(e=>e!==void 0).join(` `),content:(0,K.jsxs)(AC,{children:[(0,K.jsx)(AC.Item,{children:t}),n&&(0,K.jsx)(AC.Item,{children:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:n})}),r&&(0,K.jsx)(AC.Item,{children:r})]})}});return(0,K.jsxs)(Ymi.Toolbar,{className:`grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4`,children:[(0,K.jsx)(`div`,{}),(0,K.jsxs)(Bk,{items:a,value:t??``,onValueChange:e=>r?.(e,n??``),children:[(0,K.jsx)(Hk,{"aria-label":`Version A`,size:`md`,children:(0,K.jsx)(Vk,{placeholder:`Select version`})}),(0,K.jsx)(Uk,{children:a.map(e=>(0,K.jsx)(Wk,{value:e.value,label:e.label,children:e.content},e.value))})]}),(0,K.jsxs)(Bk,{items:a,value:n??``,onValueChange:e=>r?.(t??``,e),children:[(0,K.jsx)(Hk,{"aria-label":`Version B`,size:`md`,children:(0,K.jsx)(Vk,{placeholder:`Select an option`})}),(0,K.jsx)(Uk,{children:a.map(e=>(0,K.jsx)(Wk,{value:e.value,label:e.label,children:e.content},e.value))})]}),(0,K.jsx)(`div`,{})]})}var Qmi={added:{badgeVariant:`info`,borderColor:`border-info-edge`,icon:(0,K.jsx)(Hx,{}),tooltip:`Added in this version`},changed:{badgeVariant:`warning`,borderColor:`border-warning-edge`,icon:(0,K.jsx)(iH,{}),tooltip:`Changed in this version`},same:{badgeVariant:`success`,borderColor:`border-success-edge`,icon:(0,K.jsx)(ILr,{}),tooltip:`Same in both versions`}};function $mi({red:e=!1,tooltip:t}){return(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{render:(0,K.jsx)(`span`,{}),role:`img`,tabIndex:0,"aria-label":t,className:c(`rounded`,p),children:(0,K.jsx)(Kx,{className:c(`size-icon-lg text-muted-foreground/40`,{"text-destructive-foreground":e})})}),(0,K.jsx)(Tx,{children:t})]})}function ehi({href:e,tooltip:t,className:n,children:r}){let{Link:i}=sn(),a=(0,K.jsx)(i,{href:e,className:c(`flex w-full items-center justify-center gap-4 rounded-lg px-3 py-2 text-left hover:bg-fill-subtle`,u.colors,p,n),children:r});return t===void 0?a:(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{render:a}),(0,K.jsx)(Tx,{children:t})]})}function thi({variant:e,version:t}){if(!e)return(0,K.jsxs)(T,{as:`span`,tone:`muted`,children:[`v. `,t]});let{badgeVariant:n,icon:r,tooltip:i}=Qmi[e];return(0,K.jsxs)(`div`,{className:`grid grid-cols-[1fr_auto]`,children:[t!==void 0&&(0,K.jsxs)(T,{as:`span`,tone:`muted`,className:`flex min-w-16 justify-end pr-3`,children:[`v. `,t]}),(0,K.jsx)(`span`,{className:`inline-flex`,role:`img`,"aria-label":i,children:(0,K.jsx)(eC,{variant:n,size:`xs`,icon:r})})]})}function nhi(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?`same`:e&&t&&e.datasetVersion!==t.datasetVersion?`changed`:e?`added`:`removed`}function rhi({otherVersionExists:e,status:t,isNewer:n}){if(!e&&n)return`added`;if(t===`changed`&&n)return`changed`}function ihi({datasetId:e,versionA:t,versionB:n,allItems:r,itemsAMap:i,itemsBMap:a}){let o=t>n;return(0,K.jsx)(`div`,{className:`overflow-y-auto`,children:(0,K.jsx)(`ul`,{className:`grid content-start`,children:r.map(({id:t})=>{let n=i.get(t),r=a.get(t),s=nhi(n,r),l=rhi({otherVersionExists:r!==void 0,status:s,isNewer:o}),d=rhi({otherVersionExists:n!==void 0,status:s,isNewer:!o});return(0,K.jsxs)(`li`,{className:c(`text-foreground`,`grid grid-cols-[1fr_1fr_1fr_10rem] gap-3 overflow-hidden rounded-lg border border-transparent border-t-border px-3 py-[3px] pb-[2px] first:border-t-transparent`,u.colors),children:[(0,K.jsx)(T,{as:`p`,variant:`body`,tone:`faint`,className:`truncate py-[0.6rem]`,children:t}),s===`same`?(0,K.jsx)(ehi,{href:`/datasets/${e}/items/${t}`,className:`col-span-2 gap-2`,tooltip:Qmi.same.tooltip,children:(0,K.jsx)(thi,{variant:`same`,version:r?.datasetVersion})}):(0,K.jsxs)(K.Fragment,{children:[n?.datasetVersion?(0,K.jsx)(ehi,{href:`/datasets/${e}/items/${t}`,className:`gap-2`,tooltip:l?Qmi[l].tooltip:void 0,children:(0,K.jsx)(thi,{variant:l,version:n.datasetVersion})}):(0,K.jsx)(`div`,{className:`flex items-center justify-center`,children:(0,K.jsx)($mi,{red:o,tooltip:o?`Deleted in this version`:`Not present in this version`})}),r?.datasetVersion?(0,K.jsx)(ehi,{href:`/datasets/${e}/items/${t}`,className:`gap-2`,tooltip:d?Qmi[d].tooltip:void 0,children:(0,K.jsx)(thi,{variant:d,version:r.datasetVersion})}):(0,K.jsx)(`div`,{className:`flex items-center justify-center`,children:(0,K.jsx)($mi,{red:!o,tooltip:o?`Not present in this version`:`Deleted in this version`})})]}),s===`changed`?(0,K.jsx)(ehi,{href:`/datasets/${e}/items/${t}/versions?version=${n?.datasetVersion}&compare=${r?.datasetVersion}`,children:`Compare`}):(0,K.jsx)(`div`,{children:(0,K.jsx)($mi,{tooltip:`Comparing is available only for changed items`})})]},t)})})})}var ahi=U(`IconHistory`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M3 5V9H7`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M3.51172 15C4.74723 18.4956 8.08094 21 11.9996 21C16.9702 21 20.9996 16.9706 20.9996 12C20.9996 7.02944 16.9702 3 11.9996 3C8.27045 3 5.07102 5.26806 3.70551 8.5`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M12 8V12L15 15`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}));function ohi(e){if(!(e instanceof Error))return null;let t=e.message.match(/- ({.*})$/);if(!t)return null;try{let e=JSON.parse(t[1]);if(e.field&&Array.isArray(e.errors))return{field:e.field,errors:e.errors}}catch{}return null}function shi({item:e,itemId:t,fallback:n,onClose:r,variant:i=`drawer`,...a}){let o=e?.id??t,s=`Dataset item ${o??``}`,c=e?(0,K.jsx)(chi,{item:e,onClose:r,...a},e.id):t?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(jQ.Header,{children:[(0,K.jsx)(jQ.Heading,{children:`Dataset item`}),(0,K.jsx)(jQ.HeaderActions,{children:(0,K.jsx)(jQ.CloseButton,{icon:`x`,onClick:r,tooltip:`Close detail panel`})})]}),n]}):null;return i===`inline`?c?(0,K.jsx)(jQ,{variant:`inline`,title:s,children:c}):null:(0,K.jsx)(jQ,{open:!!o,onClose:r,title:s,children:c})}function chi({datasetId:e,item:t,items:n,onItemChange:r,onClose:i}){let{navigate:a}=sn(),{updateItem:o,deleteItem:s}=ON(),[c,l]=(0,G.useState)(!1),[u,d]=(0,G.useState)(``),[f,p]=(0,G.useState)(``),[m,h]=(0,G.useState)(``),[g,_]=(0,G.useState)(``),[v,y]=(0,G.useState)(``),[b,x]=(0,G.useState)(``),[S,C]=(0,G.useState)(null),[w,T]=(0,G.useState)(!1);(0,G.useEffect)(()=>{t&&(d(JSON.stringify(t.input,null,2)),p(t.groundTruth?JSON.stringify(t.groundTruth,null,2):``),h(t.metadata?JSON.stringify(t.metadata,null,2):``),_(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):``),y(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):``),x(t.requestContext?JSON.stringify(t.requestContext,null,2):``),l(!1),T(!1),C(null))},[t?.id]);let E=n.findIndex(e=>e.id===t.id),D=E>0?()=>r(n[E-1].id):void 0,O=E>=0&&E<n.length-1?()=>r(n[E+1].id):void 0;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(jQ.Header,{children:[(0,K.jsx)(jQ.Heading,{children:`Dataset item`}),(0,K.jsxs)(jQ.HeaderActions,{children:[!c&&(0,K.jsxs)(rE,{children:[(0,K.jsx)(rE.Trigger,{asChild:!0,children:(0,K.jsx)(X,{size:`icon-sm`,variant:`ghost`,tooltip:`Open actions menu`,"aria-label":`Open actions menu`,children:(0,K.jsx)(iE,{})})}),(0,K.jsxs)(rE.Content,{align:`end`,className:`w-48`,children:[(0,K.jsxs)(rE.Item,{onSelect:()=>a(`/datasets/${e}/items/${t.id}/versions?version=${t.datasetVersion}`),children:[(0,K.jsx)(ahi,{}),`Item versions`]}),(0,K.jsxs)(rE.Item,{onSelect:()=>l(!0),children:[(0,K.jsx)(iH,{}),`Edit`]}),(0,K.jsxs)(rE.Item,{onSelect:()=>T(!0),variant:`destructive`,children:[(0,K.jsx)(Kj,{}),`Delete item`]})]})]}),(0,K.jsx)(jQ.NextPrevNav,{onPrevious:D,onNext:O,previousLabel:`Go to previous item`,nextLabel:`Go to next item`}),(0,K.jsx)(jQ.CloseButton,{icon:`x`,onClick:i,tooltip:`Close detail panel`})]})]}),(0,K.jsx)(jQ.Content,{children:c?(0,K.jsx)(cpi,{inputValue:u,setInputValue:e=>{d(e),S?.field===`input`&&C(null)},groundTruthValue:f,setGroundTruthValue:e=>{p(e),S?.field===`groundTruth`&&C(null)},metadataValue:m,setMetadataValue:h,trajectoryValue:g,setTrajectoryValue:_,toolMocksValue:v,setToolMocksValue:y,requestContextValue:b,setRequestContextValue:x,validationErrors:S,onSave:async()=>{let n;try{n=JSON.parse(u)}catch{iS.error(`Input must be valid JSON`);return}let r;if(f.trim())try{r=JSON.parse(f)}catch{iS.error(`Ground Truth must be valid JSON`);return}let i;if(m.trim())try{i=JSON.parse(m)}catch{iS.error(`Metadata must be valid JSON`);return}let a=null;if(g.trim())try{a=JSON.parse(g)}catch{iS.error(`Expected Trajectory must be valid JSON`);return}let s;if(v.trim())try{let e=JSON.parse(v);if(!Array.isArray(e)){iS.error(`Tool Mocks must be a JSON array`);return}s=e}catch{iS.error(`Tool Mocks must be valid JSON`);return}else s=[];let c;if(b.trim())try{c=JSON.parse(b)}catch{iS.error(`Request Context must be valid JSON`);return}try{await o.mutateAsync({datasetId:e,itemId:t.id,input:n,groundTruth:r,metadata:i,expectedTrajectory:a,toolMocks:s,requestContext:c}),iS.success(`Item updated successfully`),l(!1),C(null)}catch(e){let t=ohi(e);t?C(t):iS.error(`Failed to update item: ${e instanceof Error?e.message:`Unknown error`}`)}},onCancel:()=>{d(JSON.stringify(t.input,null,2)),p(t.groundTruth?JSON.stringify(t.groundTruth,null,2):``),h(t.metadata?JSON.stringify(t.metadata,null,2):``),_(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):``),y(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):``),x(t.requestContext?JSON.stringify(t.requestContext,null,2):``),l(!1),C(null)},isSaving:o.isPending}):(0,K.jsx)(api,{item:t})}),(0,K.jsx)(QM,{open:w,onOpenChange:T,children:(0,K.jsxs)(QM.Content,{children:[(0,K.jsxs)(QM.Header,{children:[(0,K.jsx)(QM.Title,{children:`Delete Item`}),(0,K.jsx)(QM.Description,{children:`Are you sure you want to delete this item? This action cannot be undone.`})]}),(0,K.jsxs)(QM.Footer,{children:[(0,K.jsx)(QM.Cancel,{children:`Cancel`}),(0,K.jsx)(QM.Action,{onClick:async()=>{try{await s.mutateAsync({datasetId:e,itemId:t.id}),iS.success(`Item deleted successfully`),T(!1),i()}catch(e){iS.error(`Failed to delete item: ${e instanceof Error?e.message:`Unknown error`}`)}},children:s.isPending?`Deleting...`:`Yes, delete`})]})]})})]})}function lhi(){let{datasetId:e,items:t,isLoadingItems:n,currentItemId:r,openItem:i,close:a}=qfi(),o=Zw();J1r(r,a);let s=(0,G.useMemo)(()=>r?t.find(e=>e.id===r):void 0,[t,r]),{data:c,isLoading:l}=mAt({datasetId:s?``:e,itemId:!s&&r?r:``,queryOptions:{enabled:!(s||!e)&&!!(!s&&r&&r)}}),u=(0,K.jsx)(shi,{datasetId:e,item:s??c??void 0,itemId:r,fallback:n||l?(0,K.jsx)(jQ.LoadingData,{}):(0,K.jsxs)(jQ.NoData,{children:[`No loaded item "`,r,`".`]}),items:t,onItemChange:i,onClose:a,variant:o?`drawer`:`inline`});return o?u:r?(0,K.jsx)(Y8,{owner:`dataset-item`,children:u}):null}function uhi({crumbs:e,children:t}){return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:e}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Dataset`}),(0,K.jsx)(`div`,{}),(0,K.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:t})]})}function dhi(){let{datasetId:e}=kv(),t=Ov(),[n,r]=Rv(),{activeVersion:i}=MN(n,r),a=[eP(`/datasets`),iMt],o=[...a,aMt],[s,c]=(0,G.useState)(!1),[l,u]=(0,G.useState)(!1),[d,f]=(0,G.useState)(!1),[p,m]=(0,G.useState)(!1),[h,g]=(0,G.useState)(!1),{data:_,error:v,isLoading:y}=AN({datasetId:e,queryOptions:{enabled:!!e}}),{data:b=[],isLoading:x}=DN({datasetId:e,search:void 0,version:i,queryOptions:{enabled:!!e}});if(y)return null;if(v&&FN(v))return(0,K.jsx)(uhi,{crumbs:a,children:(0,K.jsx)(TH,{})});if(v&&IN(v))return(0,K.jsx)(uhi,{crumbs:a,children:(0,K.jsx)(wH,{resource:`datasets`})});if(v&&LN(v)||!y&&!v&&!_)return(0,K.jsx)(uhi,{crumbs:a,children:(0,K.jsx)(Jx,{titleSlot:`Dataset not found`,descriptionSlot:`No dataset with id "${e}".`,actionSlot:(0,K.jsx)(X,{render:(0,K.jsx)(Lv,{to:`/datasets`}),icon:(0,K.jsx)(sS,{}),children:`Back to datasets`})})});if(v)return(0,K.jsx)(uhi,{crumbs:a,children:(0,K.jsx)(Jx,{tone:`error`,titleSlot:`Failed to load dataset`,descriptionSlot:v instanceof Error?v.message:`An unexpected error occurred. Please try again.`})});let S=e=>{t(`/experiments/${e}`)},C=()=>{t(`/datasets`)},w=b.length>0,T=(_?.version??0)>0,E=w||T,D=w||(_?.tags?.length??0)>0,O=(0,K.jsxs)(K.Fragment,{children:[w&&(0,K.jsx)(X,{variant:`ghost`,size:`sm`,onClick:()=>c(!0),icon:(0,K.jsx)(Hx,{}),children:`New experiment`}),E&&(0,K.jsx)(X,{variant:`ghost`,size:`sm`,render:(0,K.jsx)(Lv,{to:`/experiments?dataset=${e}`}),icon:(0,K.jsx)(Ijt,{}),children:`Experiments`}),(0,K.jsx)(X,{variant:`ghost`,size:`sm`,onClick:()=>g(!0),icon:(0,K.jsx)(JS,{}),children:`Schema`}),(0,K.jsxs)(rE,{children:[(0,K.jsx)(rE.Trigger,{asChild:!0,children:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,"aria-label":`Dataset actions menu`,children:(0,K.jsx)(iE,{})})}),(0,K.jsxs)(rE.Content,{align:`end`,className:`w-48`,children:[(0,K.jsxs)(rE.Item,{onSelect:()=>void t(`/datasets/${e}/edit`),children:[(0,K.jsx)(iH,{}),` Edit dataset`]}),(0,K.jsxs)(rE.Item,{onSelect:()=>m(!0),children:[(0,K.jsx)(mC,{}),` Duplicate dataset`]}),(0,K.jsxs)(rE.Item,{onSelect:()=>f(!0),variant:`destructive`,children:[(0,K.jsx)(Kj,{}),` Delete dataset`]})]})]})]});return(0,K.jsxs)(Kfi,{datasetId:e,items:b,isLoadingItems:x,children:[(0,K.jsxs)(`div`,{className:`h-full`,children:[(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:o}),headerActions:O,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(`div`,{children:(0,K.jsx)(Yfi,{datasetId:e,onAddItemClick:()=>u(!0),toolbarActionsSlot:D?(0,K.jsx)(Zfi,{datasetId:e}):void 0})})]}),(0,K.jsx)(lhi,{})]}),(0,K.jsx)(Qpi,{initialDatasetId:e,initialDatasetVersion:i??void 0,open:s,onOpenChange:c,onSuccess:S},`${e}:${i??`latest`}`),(0,K.jsx)(Vor,{datasetId:e,open:l,onOpenChange:u}),_&&(0,K.jsx)(iui,{open:p,onOpenChange:m,sourceDatasetId:_.id,sourceDatasetName:_.name,sourceDatasetDescription:_.description,sourceDatasetTargetType:_.targetType}),_&&(0,K.jsx)(afi,{open:h,onOpenChange:g,dataset:_}),_&&(0,K.jsx)(Cui,{open:d,onOpenChange:f,datasetId:_.id,datasetName:_.name,onSuccess:C})]})}function fhi({children:e,className:t}){return(0,K.jsx)(`div`,{className:c(`grid content-start`,t),children:e})}function phi({children:e,isLoading:t}){return(0,K.jsx)(T,{variant:`caption`,tone:`muted`,className:c(`mt-1 ml-1 flex max-w-140 flex-wrap gap-x-4 gap-y-1 first-of-type:mt-3`,{"w-[40rem] max-w-[80%] animate-pulse rounded-md bg-fill":t}),children:t?(0,K.jsx)(K.Fragment,{children:`\xA0`}):(0,K.jsx)(K.Fragment,{children:e})})}function mhi({children:e,title:t,description:n,icon:r,className:i,withMargins:a=!0}){let o=t===`loading`,s=n===`loading`;return e?(0,K.jsx)(`header`,{className:c(`grid w-full grid-cols-[1fr_auto] gap-8`,{"mt-6 mb-4":a},i),children:e}):(0,K.jsxs)(`header`,{className:c(`grid gap-1 py-3`,i),children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,tone:`ink`,className:c(`flex items-center gap-2`,`[&>svg]:size-6 [&>svg]:text-muted-foreground`,{"w-60 max-w-[50%] animate-pulse rounded-md bg-muted":o}),children:o?(0,K.jsx)(K.Fragment,{children:`\xA0`}):(0,K.jsxs)(K.Fragment,{children:[r&&r,` `,t]})}),n&&(0,K.jsx)(T,{variant:`caption`,tone:`muted`,className:c(`m-0`,{"w-[40rem] max-w-[80%] animate-pulse rounded-md bg-muted":s}),children:s?(0,K.jsx)(K.Fragment,{children:`\xA0`}):n})]})}function hhi({children:e,isLoading:t}){return(0,K.jsx)(T,{as:`h1`,variant:`heading`,tone:`ink`,className:c(`flex items-center gap-2`,`[&>svg]:size-[1.25em] [&>svg]:opacity-50`,t&&`w-60 max-w-[50%] animate-pulse rounded-md bg-fill`),children:t?(0,K.jsx)(K.Fragment,{children:`\xA0`}):e})}var U7=Object.assign(mhi,{Title:hhi,Description:phi,Column:fhi}),ghi=[eP(`/datasets`),iMt,{id:`dataset-edit`,label:`Edit dataset`}];function _hi({children:e}){return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:ghi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Edit dataset`}),(0,K.jsx)(`div`,{}),(0,K.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:e})]})}function vhi(){let{datasetId:e}=kv(),t=Ov(),{data:n,error:r,isLoading:i}=AN({datasetId:e,queryOptions:{enabled:!!e}}),a=()=>void t(`/datasets/${e}`);return i?null:r&&FN(r)?(0,K.jsx)(_hi,{children:(0,K.jsx)(TH,{})}):r&&IN(r)?(0,K.jsx)(_hi,{children:(0,K.jsx)(wH,{resource:`datasets`})}):r||!n?(0,K.jsx)(_hi,{children:(0,K.jsx)(Jx,{tone:`error`,titleSlot:`Failed to load dataset`,descriptionSlot:r instanceof Error?r.message:`An unexpected error occurred. Please try again.`})}):(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:ghi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Edit dataset`}),(0,K.jsx)(`div`,{}),(0,K.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:(0,K.jsxs)(`div`,{className:`w-full max-w-2xl overflow-y-auto px-4 py-5`,children:[(0,K.jsx)(U7,{className:`mb-6 p-0`,children:(0,K.jsxs)(U7.Column,{children:[(0,K.jsxs)(U7.Title,{children:[(0,K.jsx)(uT,{}),` Edit dataset`]}),(0,K.jsx)(U7.Description,{children:n.name})]})}),(0,K.jsx)(nP,{className:`p-4`,children:(0,K.jsx)(Sui,{dataset:{id:n.id,name:n.name,description:n.description||``,inputSchema:n.inputSchema,groundTruthSchema:n.groundTruthSchema,requestContextSchema:n.requestContextSchema,scorerIds:n.scorerIds},onSuccess:a,onCancel:a})})]})})]})}var yhi=U(`IconChanges`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M20 18V6C20 4.89543 19.1046 4 18 4H6C4.89543 4 4 4.89543 4 6V18C4 19.1046 4.89543 20 6 20H18C19.1046 20 20 19.1046 20 18Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M9.5 10H14.5M12 7.5V12.5`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M9.5 16L14.5 16`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}));function bhi(e,t){return{id:e.id,datasetId:t,datasetVersion:e.datasetVersion,input:e.input,groundTruth:e.groundTruth,expectedTrajectory:e.expectedTrajectory,toolMocks:e.toolMocks,scorerIds:e.scorerIds,requestContext:e.requestContext,metadata:e.metadata,createdAt:e.createdAt,updatedAt:e.updatedAt}}function xhi(e,t){return e.map(e=>{let n=typeof e.updatedAt==`string`?new Date(e.updatedAt):e.updatedAt;return{value:String(e.datasetVersion),label:(0,K.jsxs)(`span`,{className:`flex w-full items-center gap-2`,children:[(0,K.jsxs)(AC,{children:[(0,K.jsx)(AC.Item,{children:(0,K.jsxs)(`b`,{children:[`v. `,e.datasetVersion]})}),(0,K.jsx)(AC.Item,{children:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:bC(n,`date-time`)})})]}),e.isLatest?(0,K.jsx)(eC,{variant:`blue`,size:`xs`,className:`ml-auto`,children:`Latest`}):null]}),disabled:t?.has(e.datasetVersion)??!1}})}function Shi(e){let t=Number(e);return e!=null&&Number.isFinite(t)&&t>0?t:null}function Chi(){let{datasetId:e,itemId:t}=kv(),[n,r]=Rv(),i=[eP(`/datasets`),iMt,{id:`dataset-item`,label:Qjt(t),to:e&&t?`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}`:void 0},{id:`dataset-item-versions`,label:`Item Version History`}],a=Shi(n.get(`version`)),o=Shi(n.get(`compare`)),s=n.get(`view`)===`diff`,{data:c,error:l}=AN({datasetId:e??``,queryOptions:{enabled:!!e}}),{data:u,isLoading:d}=NAt({datasetId:e??``,itemId:t??``,queryOptions:{enabled:!!e&&!!t}}),f=(a==null?void 0:u?.find(e=>e.datasetVersion===a))??u?.[0],p=f?.datasetVersion??null,m=o!=null&&o!==p?o:null,{data:h,isLoading:g}=PAt({datasetId:e??``,itemId:t??``,datasetVersion:m??0,latestVersion:c?.version,queryOptions:{enabled:!!e&&!!t&&(m??0)>0}}),_=(e,t)=>r(n=>{let r=new URLSearchParams(n);return t==null?r.delete(e):r.set(e,String(t)),r},{replace:!0});if(l&&FN(l))return(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:i}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Item Version History`}),(0,K.jsx)(TH,{variant:`fill`})]});if(l&&IN(l))return(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:i}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Item Version History`}),(0,K.jsx)(wH,{variant:`fill`,resource:`datasets`})]});if(!e||!t)return(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:i}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Item Version History`}),(0,K.jsx)(`div`,{className:`grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto`,children:(0,K.jsx)(`div`,{className:`py-5 text-center text-muted-foreground`,children:(0,K.jsx)(`p`,{children:`Item not found.`})})})]});let v=!!(f&&h),y=s&&v,b=f?bhi(f,e):null,x=h?bhi(h,e):null,S=(f?.datasetVersion??0)<(h?.datasetVersion??0);return(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:i}),headerActions:v&&(0,K.jsx)(X,{variant:`ghost`,size:`sm`,onClick:()=>_(`view`,s?null:`diff`),children:s?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Q0r,{}),` Default view`]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(yhi,{}),` Diff view`]})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Item Version History`}),(0,K.jsxs)(`div`,{className:`grid min-h-0 grid-cols-1 gap-4 md:grid-cols-2`,children:[(0,K.jsxs)(nP,{className:`grid min-h-0 grid-rows-[auto_1fr] overflow-hidden`,children:[(0,K.jsx)(rP,{children:(0,K.jsx)(whi,{label:`Version`,value:p==null?``:String(p),options:xhi(u??[],m==null?void 0:new Set([m])),onValueChange:e=>_(`version`,Number(e))})}),(0,K.jsx)(oP,{className:`grid content-start gap-5 overflow-y-auto`,children:d?(0,K.jsx)(T,{as:`p`,variant:`body`,tone:`muted`,children:`Loading...`}):b?(0,K.jsx)(api,{item:b,diff:y&&x?{against:x,side:S?`a`:`b`}:void 0}):(0,K.jsx)(T,{as:`p`,variant:`body`,tone:`muted`,children:`Item data not available`})})]}),(0,K.jsxs)(nP,{className:`grid min-h-0 grid-rows-[auto_1fr] overflow-hidden`,children:[(0,K.jsx)(rP,{children:(0,K.jsx)(whi,{label:`Compare version`,value:m==null?``:String(m),placeholder:`Select a version to compare`,options:xhi(u??[],p==null?void 0:new Set([p])),onValueChange:e=>_(`compare`,Number(e))})}),(0,K.jsx)(oP,{className:`grid content-start gap-5 overflow-y-auto`,children:m==null?(0,K.jsx)(Jx,{className:`h-full`,titleSlot:`No version selected`,descriptionSlot:`Pick a version above to compare it with the one on the left.`}):g?(0,K.jsx)(T,{as:`p`,variant:`body`,tone:`muted`,children:`Loading...`}):x?(0,K.jsx)(api,{item:x,diff:y&&b?{against:b,side:S?`b`:`a`}:void 0}):(0,K.jsxs)(T,{as:`p`,variant:`body`,tone:`muted`,children:[`Version `,m,` not found`]})})]})]})]})}function whi({label:e,value:t,options:n,placeholder:r=`Select version`,onValueChange:i}){return(0,K.jsxs)(`div`,{className:`grid grid-cols-[auto_1fr] items-center gap-4`,children:[(0,K.jsx)(ahi,{className:`size-icon-md opacity-50`}),(0,K.jsxs)(Bk,{value:t,onValueChange:i,children:[(0,K.jsx)(Hk,{"aria-label":e,className:`w-full`,children:(0,K.jsx)(Vk,{placeholder:r,className:`flex-1`})}),(0,K.jsx)(Uk,{children:n.map(e=>(0,K.jsx)(Wk,{value:e.value,disabled:e.disabled,children:e.label},e.value))})]})]})}var Thi=U(`IconLaw`,()=>(0,K.jsx)(`path`,{d:`M12 3V20M12 20H7M12 20H17M3 6H7.52786C7.83835 6 8.14458 5.92771 8.42229 5.78885L9.57771 5.21115C9.85542 5.07229 10.1616 5 10.4721 5H13.5279C13.8384 5 14.1446 5.07229 14.4223 5.21115L15.5777 5.78885C15.8554 5.92771 16.1616 6 16.4721 6H21M5.5 6L3.02044 13.4387C2.71808 14.3458 3.08919 15.3834 4.00531 15.657C5.01171 15.9577 5.98829 15.9577 6.99469 15.657C7.91081 15.3834 8.28192 14.3457 7.97956 13.4387L5.5 6ZM18.5 6L16.0204 13.4387C15.7181 14.3458 16.0892 15.3834 17.0053 15.657C18.0117 15.9577 18.9883 15.9577 19.9947 15.657C20.9108 15.3834 21.2819 14.3457 20.9796 13.4387L18.5 6Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})),Ehi=[eP(`/datasets`),iMt,{id:`dataset-versions`,label:`Versions`}];function Dhi(){let{datasetId:e}=kv(),[t]=Rv(),n=t.get(`ids`)?.split(`,`).map(Number).filter(e=>!isNaN(e)&&e>0)??[],r=Ov(),{data:i,error:a}=AN({datasetId:e??``,queryOptions:{enabled:!!e}}),o=DN({datasetId:e??``,search:void 0,version:n[0]??null,queryOptions:{enabled:!!e}}),s=DN({datasetId:e??``,search:void 0,version:n[1]??null,queryOptions:{enabled:!!e}}),c=(0,G.useMemo)(()=>o.data??[],[o.data]),l=(0,G.useMemo)(()=>s.data??[],[s.data]),u=(0,G.useMemo)(()=>{let e=new Map;for(let t of[...c,...l])e.has(t.id)||e.set(t.id,{id:t.id,createdAt:new Date(t.createdAt)});return[...e.values()].sort((e,t)=>t.createdAt.getTime()-e.createdAt.getTime())},[c,l]),d=(0,G.useMemo)(()=>new Map(c.map(e=>[e.id,e])),[c]),f=(0,G.useMemo)(()=>new Map(l.map(e=>[e.id,e])),[l]);return a&&FN(a)?(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:Ehi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Versions`}),(0,K.jsx)(TH,{variant:`fill`})]}):a&&IN(a)?(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:Ehi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Versions`}),(0,K.jsx)(wH,{variant:`fill`,resource:`datasets`})]}):!e||n.length<2?(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:Ehi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Versions`}),(0,K.jsx)(`div`,{className:`grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto`,children:(0,K.jsx)(`div`,{className:`py-5 text-center text-muted-foreground`,children:(0,K.jsx)(`p`,{children:`Select at least two versions to compare.`})})})]}):(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:Ehi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Versions`}),(0,K.jsx)(`div`,{className:`h-full overflow-hidden px-[3vw] pb-4`,children:(0,K.jsxs)(`div`,{className:`mx-auto grid h-full max-w-[140rem] grid-rows-[auto_1fr] gap-4`,children:[(0,K.jsxs)(U7,{children:[(0,K.jsxs)(U7.Column,{children:[(0,K.jsxs)(U7.Title,{children:[(0,K.jsx)(Thi,{}),` Compare Dataset Versions`]}),(0,K.jsx)(U7.Description,{children:(0,K.jsxs)(MZ,{children:[(0,K.jsx)(ahi,{}),` Comparing `,n.length,` versions of`,` `,i?.name||e?.slice(0,8)]})})]}),(0,K.jsx)(U7.Column,{children:(0,K.jsx)(X,{render:(0,K.jsx)(Lv,{to:`/datasets/${e}`}),icon:(0,K.jsx)(sS,{}),children:`Back to dataset`})})]}),(0,K.jsx)(Xmi,{children:(0,K.jsxs)(Ymi,{children:[(0,K.jsx)(Zmi,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:(t,n)=>{r(`/datasets/${e}/versions?ids=${t},${n}`,{replace:!0})}}),(0,K.jsx)(ihi,{datasetId:e,versionA:n[0],versionB:n[1],allItems:u,itemsAMap:d,itemsBMap:f})]})})]})})]})}var Ohi=100,khi=async(e,t,{page:n,experiments:r})=>{let i=await Promise.all(r.map(async r=>{try{let{results:i,pagination:a}=await e.listDatasetExperimentResults(r.datasetId,r.experimentId,{page:n,perPage:Ohi,status:t});return{experiment:r,results:i,hasMore:a.hasMore&&i.length>0}}catch{return{experiment:r,results:[],hasMore:!1}}})),a=i.filter(e=>e.hasMore).map(e=>e.experiment);return{items:i.flatMap(({experiment:e,results:n})=>n.filter(e=>e.status===t).map(t=>({id:t.id,input:t.input,output:t.output,error:t.error,itemId:t.itemId,experimentId:t.experimentId,datasetId:e.datasetId,traceId:t.traceId??void 0,scores:t.scores?Object.fromEntries(t.scores.map(e=>[e.scorerId,e.score??0])):{},tags:t.tags??[],targetType:t.targetType,createdAt:t.createdAt,startedAt:t.startedAt,completedAt:t.completedAt,status:t.status,groundTruth:t.groundTruth,toolMockReport:t.toolMockReport}))),next:a.length>0?{page:n+1,experiments:a}:void 0}},Ahi=(e,{experimentId:t,targetType:n,targetId:r,experiments:i,isLoadingExperiments:a=!1,queryOptions:o})=>{let s=Y(),{inView:c,setRef:l}=$M(),u=i!==void 0,{data:d,isLoading:f}=fmi({datasetId:void 0,target:{targetType:n,targetId:r},queryOptions:{enabled:!u}}),p=u?i:d?.experiments,m=u?a:f,h=t?p?.filter(e=>e.id===t):p,g=O_({queryKey:[`review-items`,e,`infinite`,t??`all`,u?`supplied`:`discovered`,u?void 0:n||`all`,u?void 0:r||`all`,h?.map(e=>[e.datasetId,e.id])],queryFn:async({pageParam:t})=>{let n=await khi(s,e,t);for(;n.items.length===0&&n.next;)n=await khi(s,e,n.next);return n},initialPageParam:{page:0,experiments:(h??[]).flatMap(e=>e.datasetId?[{experimentId:e.id,datasetId:e.datasetId}]:[])},getNextPageParam:e=>e.next,select:e=>e.pages.flatMap(e=>e.items),enabled:!!p,refetchOnWindowFocus:!1,...o});return(0,G.useEffect)(()=>{c&&g.hasNextPage&&!g.isFetching&&g.fetchNextPage({cancelRefetch:!1})},[c,g]),{...g,isLoading:g.isLoading||m,setEndOfListElement:l}},jhi=(e={})=>Ahi(`needs-review`,e),Mhi=(e={})=>Ahi(`complete`,e);function Nhi({queryOptions:e}={}){let t=Y();return T_({queryKey:[`experiment-review-summary`],queryFn:()=>t.getExperimentReviewSummary(),...e})}var Phi={baseline:`purple`,contender:`blue`},W7=e=>e===0?`Baseline`:`Contender ${e}`;function Fhi({open:e,onOpenChange:t,experimentId:n,experimentName:r,onSuccess:i}){let{deleteExperiment:a}=ON();return(0,K.jsx)(QM,{open:e,onOpenChange:t,children:(0,K.jsxs)(QM.Content,{children:[(0,K.jsxs)(QM.Header,{children:[(0,K.jsx)(QM.Title,{children:`Delete Experiment`}),(0,K.jsxs)(QM.Description,{children:[`Are you sure you want to delete "`,r||n,`"? This will permanently delete the experiment, all its results, and the traces it produced, including their spans and any scores, feedback, metrics and logs attached to those traces. This action cannot be undone.`]})]}),(0,K.jsxs)(QM.Footer,{children:[(0,K.jsx)(QM.Cancel,{children:`Cancel`}),(0,K.jsx)(X,{icon:(0,K.jsx)(Kj,{}),variant:`primary`,onClick:async()=>{try{await a.mutateAsync(n),iS.success(`Experiment deleted successfully`),t(!1),i?.()}catch(e){iS.error(`Failed to delete experiment: ${e instanceof Error?e.message:`Unknown error`}`)}},disabled:a.isPending,children:a.isPending?`Deleting...`:`Delete`})]})]})})}var Ihi=`minmax(9rem,1fr)`,Lhi=`minmax(8rem,16rem)`,Rhi=`auto auto auto auto auto auto auto auto`,zhi=`auto auto auto`,G7={experiment:`Experiment`,description:`Description`,dataset:`Dataset`,target:`Target`,status:`Status`,items:`Items`,succeeded:`Processed`,failed:`Errored`,duration:`Duration`,avgDuration:`Avg duration`,tokens:`Tokens`,cost:`Cost`,review:`Review`,date:`Date`},Bhi={completed:`neutral`,running:`warning`,failed:`destructive`,pending:`neutral`},K7={completed:`Run completed`,running:`Run in progress`,failed:`Run failed`,pending:`Run queued`};function Vhi(e){let t=aH(e.id)??e.id;return e.name||`Experiment #${t}`}var Hhi=60;function Uhi({experiment:e}){return(0,K.jsx)(`span`,{className:`block min-w-0 truncate text-left text-muted-foreground`,children:Vhi(e)})}function Whi({experiment:e}){let t=e.description;if(!t)return(0,K.jsx)(`span`,{className:`text-placeholder`,children:`—`});let n=(0,K.jsx)(`span`,{className:`block min-w-0 truncate text-left text-muted-foreground`,children:t});return t.length<=Hhi?n:(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{asChild:!0,children:n}),(0,K.jsx)(Tx,{children:t})]})}function Ghi(){let{data:e}=wN(),{data:t}=eN(),{data:n}=VN(),{data:r}=PN();return{agents:e,workflows:t,scorers:n,processors:r}}var Khi={agent:HN,workflow:ZS,scorer:JN,processor:qN},qhi={agent:`Agent`,workflow:`Workflow`,scorer:`Scorer`,processor:`Processor`},Jhi=`External (caller-run)`;function Yhi(e,{agents:t,workflows:n,scorers:r,processors:i}){let{targetType:a,targetId:o}=e;if(!o)return Jhi;switch(a){case`agent`:return t?.[o]?.name??o;case`workflow`:return n?.[o]?.name??o;case`scorer`:return r?.[o]?.scorer?.config?.name??o;case`processor`:return i?.[o]?.name??o;default:return o}}function Xhi({experiment:e,datasetName:t,review:n,selectionRole:r,showUsage:i=!1,metrics:a}){let o=e.status??`pending`,s=e.succeededCount??0,c=e.failedCount??0,l=e.totalItems??0;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Z.Cell,{children:r?(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(eC,{variant:r.variant,className:`shrink-0`,children:r.label}),(0,K.jsx)(Uhi,{experiment:e})]}):(0,K.jsx)(Uhi,{experiment:e})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(Whi,{experiment:e})}),t!==void 0&&(0,K.jsx)(Z.TextCell,{children:t}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(egi,{experiment:e})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(eC,{variant:Bhi[o]??`neutral`,indicator:`dot`,children:K7[o]??o})}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:l}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:s}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:(0,K.jsx)(`span`,{className:c>0?`text-destructive-foreground`:``,children:c})}),(0,K.jsx)($hi,{value:Zhi(e),format:iC}),i&&(0,K.jsx)(Qhi,{metrics:a}),(0,K.jsx)(Z.Cell,{className:`text-center`,children:(0,K.jsx)(tgi,{review:n})}),(0,K.jsx)(Z.TextCell,{children:bC(e.createdAt,`date`)??`—`})]})}function Zhi(e){if(e.startedAt&&e.completedAt)return new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime()}function Qhi({metrics:e}){let t=e?.avgDurationMs===void 0?void 0:Math.round(e.avgDurationMs);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)($hi,{value:t,format:iC}),(0,K.jsx)($hi,{value:H7(e),format:N5}),(0,K.jsx)($hi,{value:e?.estimatedCost,format:t=>B7(t,e?.costUnit)})]})}function $hi({value:e,format:t}){let n=e===void 0?void 0:t(e);return(0,K.jsx)(Z.TextCell,{className:`text-center tabular-nums`,children:n??(0,K.jsx)(`span`,{className:`text-placeholder`,children:`—`})})}function egi({experiment:e}){let t=Yhi(e,Ghi()),n=e.targetId?e.targetType:null,r=n?Khi[n]:null;return(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5 [&_svg]:size-icon-sm [&_svg]:shrink-0`,children:[r&&(0,K.jsx)(`span`,{className:`flex text-muted-foreground`,role:`img`,"aria-label":qhi[n],children:(0,K.jsx)(r,{})}),(0,K.jsx)(`span`,{className:n?`truncate`:`truncate text-placeholder`,children:t})]})}function tgi({review:e}){if(!e)return(0,K.jsx)(`span`,{className:`text-placeholder`,children:`—`});let t=e.needsReview+e.complete;return t===0?(0,K.jsx)(`span`,{className:`text-placeholder`,children:`—`}):e.needsReview>0?(0,K.jsxs)(eC,{size:`xs`,variant:`warning`,children:[e.needsReview,` pending`]}):(0,K.jsxs)(eC,{size:`xs`,variant:`success`,children:[e.complete,`/`,t,` reviewed`]})}var ngi=`${Ihi} ${Lhi} 1fr ${Rhi}`,rgi=`${ngi} auto`,igi=`${ngi} ${zhi} auto`,agi=[{label:G7.avgDuration,className:`text-center`},{label:G7.tokens,className:`text-center`},{label:G7.cost,className:`text-center`}],ogi=e=>[{label:G7.experiment},{label:G7.description},{label:G7.dataset},{label:G7.target},{label:G7.status,sortKey:`status`},{label:G7.items,className:`text-center`},{label:G7.succeeded,className:`text-center`},{label:G7.failed,className:`text-center`},{label:G7.duration,className:`text-center`},...e?agi:[],{label:G7.review,className:`text-center`},{label:G7.date,sortKey:`createdAt`}],sgi=e=>e.stopPropagation();function cgi({experiment:e,rowProps:t,onSelect:n,featured:r,onDelete:i,leadingCell:a,children:o}){let s=a?2:void 0,{paths:c,Link:l}=sn(),u=(0,G.useRef)(null);return(0,K.jsxs)(Z.RowWrapper,{...t,onSelectRow:n??(()=>u.current?.click()),children:[a,n?(0,K.jsx)(Z.RowButton,{colStart:s,colEnd:-2,featured:r,tabIndex:-1,onClick:e=>{e.stopPropagation(),n()},children:o}):(0,K.jsx)(Z.RowLink,{ref:u,colStart:s,colEnd:-2,featured:r,to:c.experimentLink(e.id),LinkComponent:l,tabIndex:-1,onClick:sgi,children:o}),(0,K.jsx)(Z.ActionsCell,{className:`pl-2`,children:(0,K.jsx)(X,{type:`button`,variant:`ghost`,size:`icon-sm`,tooltip:`Delete experiment`,"aria-label":`Delete experiment ${e.name??e.id}`,onClick:e=>{e.stopPropagation(),i()},children:(0,K.jsx)(Kj,{})})})]})}function lgi({experiments:e,datasets:t,reviewByExperiment:n,metricsByExperiment:r,isLoading:i,search:a=``,statusFilter:o=`all`,datasetFilter:s=`all`,selection:c,onSelectExperiment:l,selectedExperimentId:u,keyboardGlobal:d=!0,isFetchingNextPage:f,hasNextPage:p,setEndOfListElement:m,sort:h,onSortChange:g}){let _=(0,G.useMemo)(()=>{let e=new Map;return t?.forEach(t=>e.set(t.id,t.name)),e},[t]),v=(0,G.useMemo)(()=>h?e:[...e].sort((e,t)=>{let n=e.createdAt?new Date(e.createdAt).getTime():0;return(t.createdAt?new Date(t.createdAt).getTime():0)-n}),[e,h]),y=(0,G.useMemo)(()=>{let e=a.toLowerCase();return v.filter(t=>{let n=t.datasetId?_.get(t.datasetId)??``:``,r=!e||t.id.toLowerCase().includes(e)||(t.name??``).toLowerCase().includes(e)||n.toLowerCase().includes(e)||(t.targetId??``).toLowerCase().includes(e),i=o===`all`||t.status===o,a=s===`all`||t.datasetId===s;return r&&i&&a})},[v,a,_,o,s]),{containerRef:b,getRowProps:x}=PZ({count:y.length,global:d}),[S,C]=(0,G.useState)(null),w=r!==void 0,T=w?igi:rgi;if(i)return(0,K.jsx)(DH,{columns:T});let E=(c?.selectedExperimentIds.length??0)===0||y.length===0?!1:y.every(e=>c?.selectedExperimentIds.includes(e.id))?!0:`indeterminate`,D=c?`auto ${T}`:T,O=ogi(w).map(e=>e.sortKey&&g?(0,K.jsx)(Z.SortableTopCell,{className:e.className,sortKey:e.sortKey,sort:h?.key===e.sortKey?h.direction:void 0,onSortChange:g,children:e.label},e.label):(0,K.jsx)(Z.TopCell,{className:e.className,children:e.label},e.label));return(0,K.jsxs)(Z,{columns:D,scrollRef:b,children:[(0,K.jsx)(Z.Top,{hasLeadingCell:c!==void 0,children:c?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Z.TopSelectCell,{checked:E,onToggle:()=>c.onToggleAll(y.map(e=>e.id)),"aria-label":`Select all experiments`}),(0,K.jsxs)(Z.TopCells,{colStart:2,children:[O,(0,K.jsx)(Z.TopCell,{"aria-hidden":!0,children:null})]})]}):(0,K.jsxs)(K.Fragment,{children:[O,(0,K.jsx)(Z.TopCell,{"aria-hidden":!0,children:null})]})}),y.length===0&&!p?(0,K.jsx)(Z.NoMatch,{message:`No experiments match your filters`}):null,y.map((e,t)=>{let i=e.datasetId?_.get(e.datasetId)??aH(e.datasetId)??e.datasetId:`—`,a=c?.selectedExperimentIds.indexOf(e.id)??-1,o=a!==-1,s=!o&&c?.comparableDatasetId!==void 0&&e.datasetId!==c.comparableDatasetId,d=(0,K.jsx)(Xhi,{experiment:e,datasetName:i,review:n?.get(e.id),showUsage:w,metrics:r?.get(e.id),selectionRole:o?{label:W7(a),variant:a===0?Phi.baseline:Phi.contender}:void 0});return(0,K.jsx)(cgi,{experiment:e,rowProps:x(t),onSelect:l?()=>l(e):void 0,featured:o||u===e.id,onDelete:()=>C(e),leadingCell:c&&(0,K.jsx)(Z.SelectCell,{checked:o,disabled:s,onToggle:()=>c.onToggleSelection(e.id),"aria-label":`Select experiment ${e.id}`}),children:d},e.id)}),(0,K.jsx)(Z.NextPageLoading,{isLoading:f,hasMore:p,setEndOfListElement:m}),S&&(0,K.jsx)(Fhi,{open:!0,onOpenChange:e=>{e||C(null)},experimentId:S.id,experimentName:S.name??void 0})]})}var ugi=[{value:`all`,label:`All statuses`},{value:`completed`,label:`Completed`},{value:`running`,label:`Running`},{value:`failed`,label:`Failed`},{value:`pending`,label:`Pending`}];function dgi(e){return[{value:`all`,label:`All datasets`},...(e??[]).map(e=>({value:e.id,label:e.name}))]}var fgi=({onRunExperiment:e})=>(0,K.jsx)(Jx,{titleSlot:`No Experiments yet`,descriptionSlot:(0,K.jsxs)(K.Fragment,{children:[`Run an experiment from a dataset to evaluate `,(0,K.jsx)(`br`,{}),`your agents and workflows.`]}),actionSlot:(0,K.jsxs)(`div`,{className:`flex flex-col items-center gap-2`,children:[e&&(0,K.jsx)(X,{variant:`primary`,onClick:e,icon:(0,K.jsx)(Hx,{}),children:`New experiment`}),(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/docs/evals/experiments`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(tP,{}),children:`Experiments documentation`})]}),variant:`fill`}),pgi=e=>`${e} experiment${e===1?``:`s`}`;function mgi({experimentIds:e,onDeleted:t}){let[n,r]=(0,G.useState)(!1),[i,a]=(0,G.useState)(!1),{deleteExperiment:o}=ON(),s=e.length;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(X,{size:`sm`,variant:`destructive-ghost`,disabled:s===0,icon:(0,K.jsx)(Kj,{}),onClick:()=>r(!0),children:`Delete`}),(0,K.jsx)(QM,{open:n,onOpenChange:r,children:(0,K.jsxs)(QM.Content,{children:[(0,K.jsxs)(QM.Header,{children:[(0,K.jsxs)(QM.Title,{children:[`Delete `,pgi(s)]}),(0,K.jsxs)(QM.Description,{children:[s===1?`Its`:`Their`,` results and traces will be deleted too. This can't be undone.`]})]}),(0,K.jsxs)(QM.Footer,{children:[(0,K.jsx)(QM.Cancel,{children:`Cancel`}),(0,K.jsx)(X,{icon:(0,K.jsx)(Kj,{}),variant:`destructive`,onClick:async()=>{a(!0);let n=await Promise.allSettled(e.map(e=>o.mutateAsync(e)));a(!1);let i=n.filter(e=>e.status===`rejected`).length;i>0?iS.error(`Failed to delete ${i} of ${pgi(s)}`):(iS.success(`Deleted ${pgi(s)}`),r(!1),t())},disabled:i,children:i?`Deleting…`:s===1?`Delete experiment`:`Delete experiments`})]})]})})]})}function hgi({selectedIds:e,onClearSelection:t,onCompare:n,compareDisabledReason:r}){let i=e.length,a=i===0;return(0,K.jsxs)(`div`,{className:`flex items-center gap-1 whitespace-nowrap`,children:[(0,K.jsxs)(X,{variant:`ghost`,size:`sm`,disabled:a,iconEnd:a?void 0:(0,K.jsx)(xw,{}),onClick:t,tooltip:a?void 0:`Clear selection`,className:`mr-2 tabular-nums`,children:[i,` selected`]}),(0,K.jsx)(mgi,{experimentIds:e,onDeleted:t}),r?(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{render:(0,K.jsx)(`span`,{className:`cursor-not-allowed`,tabIndex:0}),children:(0,K.jsx)(X,{size:`sm`,disabled:!0,tabIndex:-1,icon:(0,K.jsx)(yhi,{}),children:`Compare`})}),(0,K.jsx)(Tx,{children:r})]}):(0,K.jsx)(X,{size:`sm`,onClick:n,icon:(0,K.jsx)(yhi,{}),children:`Compare`})]})}function ggi({dataset:e}){return(0,K.jsx)(T,{as:`p`,variant:`body-sm`,tone:`muted`,role:`note`,"aria-label":`Comparable experiments`,className:`min-w-0 truncate`,children:e?(0,K.jsxs)(K.Fragment,{children:[`Comparable experiments share dataset`,` `,(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`ink`,title:e.id,children:e.name})]}):`Select an experiment to pick the dataset to compare`})}var _gi=`search`,vgi=`status`,ygi=`dataset`,q7=`all`,bgi=[{id:`contains`,label:`contains`},{id:`is`,label:`is`}],xgi=ugi.filter(e=>e.value!==q7),Sgi=({search:e,statusFilter:t,datasetFilter:n,targetType:r,targetId:i})=>{let a=[];return e&&a.push(T7(_gi,e,`contains`)),a.push(...xli({targetType:r,targetId:i})),t!==q7&&a.push(T7(vgi,t)),n!==q7&&a.push(T7(ygi,n)),a},Cgi=e=>({...Sli(e),search:E7(e,_gi),statusFilter:E7(e,vgi)||q7,datasetFilter:E7(e,ygi)||q7});function wgi({search:e,statusFilter:t,datasetFilter:n,targetType:r,targetId:i,datasetOptions:a,onChange:o}){let s=Cli(r),c=(0,G.useMemo)(()=>[{id:_gi,label:`Search`,icon:oN,search:!0,operators:[`contains`]},...s,{id:vgi,label:`Status`,icon:EX,color:sP(`orange`),operators:[`is`],strict:!0,suggestions:xgi},{id:ygi,label:`Dataset`,icon:uT,color:sP(`blue`),operators:[`is`],strict:!0,suggestions:a.filter(e=>e.value!==q7)}],[s,a]),l=(0,G.useMemo)(()=>Sgi({search:e,statusFilter:t,datasetFilter:n,targetType:r,targetId:i}),[e,t,n,r,i]);return(0,K.jsxs)(m5,{fields:c,operators:bgi,value:l,onValueChange:e=>o(Cgi(e)),createItemId:e=>e,"aria-label":`Experiments filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(m5.Chips,{}),(0,K.jsx)(m5.Input,{placeholder:`Filter experiments`})]})}function Tgi({search:e,statusFilter:t,datasetFilter:n,datasetOptions:r,targetType:i,targetId:a,onFiltersChange:o,selection:s,comparableDataset:c}){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(TK,{children:(0,K.jsx)(TK.Start,{children:(0,K.jsx)(wgi,{search:e,statusFilter:t,datasetFilter:n,datasetOptions:r,targetType:i,targetId:a,onChange:o})})}),(0,K.jsxs)(TK,{children:[(0,K.jsx)(TK.Start,{className:`self-end`,children:(0,K.jsx)(ggi,{dataset:c})}),(0,K.jsx)(TK.End,{children:(0,K.jsx)(hgi,{...s})})]})]})}var Egi={present:!1,targetType:null,output:null,metadata:null,comment:null,error:null,startedAt:null,completedAt:null,scores:[]},Dgi=e=>e?e instanceof Date?e.toISOString():e:null,Ogi=e=>{let t=new Map;for(let n of e??[])t.set(n.itemId,n);return t},kgi=(e,t,n,r)=>{if(!e)return Egi;let i=new Map;for(let e of n??[])i.set(e.scorerId,e.reason??null);return{present:!0,targetType:t?.targetType??null,output:e.output,metadata:t?.metadata??null,comment:t?.comment??null,error:t?.error??null,startedAt:Dgi(t?.startedAt),completedAt:Dgi(t?.completedAt),scores:Object.entries(e.scores).map(([e,t])=>({scorerId:e,value:t,reason:i.get(e)??null})).sort((e,t)=>e.scorerId.localeCompare(t.scorerId)),traceId:t?.traceId??void 0,usage:t?.traceId?r?.[t.traceId]:void 0}},Agi=(e,t)=>{let n={};for(let r of new Set([...e.scores,...t.scores].map(e=>e.scorerId))){let i=e.scores.find(e=>e.scorerId===r)?.value??null,a=t.scores.find(e=>e.scorerId===r)?.value??null;n[r]=i!=null&&a!=null?a-i:null}return n};function J7(e){return!e.startedAt||!e.completedAt?null:new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime()}function jgi(e){let t=e.scores.map(e=>e.value).filter(e=>e!=null);return t.length>0?t.reduce((e,t)=>e+t,0)/t.length:null}var Mgi=(e,t)=>{let n=jgi(e),r=jgi(t);return n!=null&&r!=null?r-n:void 0},Ngi=(e,t)=>{let n=J7(e),r=J7(t);return n!=null&&r!=null?r-n:null},Pgi=(e,t)=>{let n=e.usage?.estimatedCost,r=t.usage?.estimatedCost;if(n!==void 0&&r!==void 0)return e.usage?.costUnit===t.usage?.costUnit?r-n:void 0},Fgi=(e,t)=>{let n=H7(e.usage),r=H7(t.usage);return n!==void 0&&r!==void 0?r-n:void 0},Igi=({comparison:e,experimentIds:t,resultsById:n,scoresById:r,usageById:i})=>{if(!e)return[];let a=new Map(t.map(e=>[e,Ogi(n?.[e])]));return e.items.map(e=>{let n=t.map(t=>kgi(e.results[t],a.get(t)?.get(e.itemId),r?.[t]?.[e.itemId],i?.[t]?.traces)),[o]=n;return{itemId:e.itemId,input:e.input,groundTruth:e.groundTruth,sides:n.map((e,n)=>({...e,experimentId:t[n],role:n===0?`baseline`:`contender`,deltas:n===0?null:Agi(o,e),durationDeltaMs:n===0?null:Ngi(o,e),costDelta:n===0?void 0:Pgi(o,e),tokenDelta:n===0?void 0:Fgi(o,e),averageScoreDelta:n===0?void 0:Mgi(o,e)}))}})};function Lgi({datasetId:e,itemId:t,onClose:n}){let{data:r,isLoading:i}=mAt({datasetId:e,itemId:t??``,queryOptions:{enabled:!!e&&!!t}});return(0,K.jsx)(shi,{datasetId:e,item:r,itemId:t,fallback:i?(0,K.jsx)(jQ.LoadingData,{}):(0,K.jsxs)(jQ.NoData,{children:[`Dataset item "`,t,`" not found.`]}),items:r?[r]:[],onItemChange:()=>{},onClose:n})}function Rgi({label:e,value:t,expanded:n,onExpandedChange:r}){return t==null?null:(0,K.jsx)(L7,{title:e,framed:!0,expanded:n,onExpandedChange:r,children:(0,K.jsx)(I7,{value:t})})}var zgi=U(`IconCoins`,()=>(0,K.jsx)(`path`,{d:`M9 16C5.68629 16 3 13.3137 3 10C3 6.68629 5.68629 4 9 4C11.4597 4 13.5737 5.48012 14.5 7.59829M21 14C21 17.3137 18.3137 20 15 20C12.3841 20 10.1591 18.3259 9.33811 15.9906C9.11911 15.3677 9 14.6978 9 14C9 10.7998 11.5055 8.1847 14.6619 8.00937C14.7738 8.00315 14.8865 8 15 8C18.3137 8 21 10.6863 21 14Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`square`}));function Bgi({usage:e,showUsage:t,durationMs:n,costDelta:r,tokenDelta:i,durationDeltaMs:a,averageScore:o,scores:s}){let c=e?.costUnit,l=t?[{id:`cost`,icon:(0,K.jsx)(zgi,{}),label:`Cost`,value:B7(e?.estimatedCost,c),rawValue:e?.estimatedCost,delta:r??null,formatDelta:Imi(c),higherIsBetter:!1}]:[],u=t?[{id:`tokens`,icon:(0,K.jsx)(Z4,{}),label:`Tokens`,value:V7(H7(e)),rawValue:H7(e),delta:i??null,formatDelta:V7,higherIsBetter:!1}]:[],d=n==null?[]:[{id:`duration`,icon:(0,K.jsx)(tC,{}),label:`Duration`,value:iC(n)??`-`,rawValue:n,delta:a??null,formatDelta:Mmi,higherIsBetter:!1}],f=o?[{id:`avg-score`,icon:(0,K.jsx)(G4,{}),label:`Avg score`,value:z7(o.value),rawValue:o.value,delta:o.delta??null}]:[];return[...l,...d,...f,...u,...s.map(e=>({id:`scorer:${e.scorerId}`,icon:(0,K.jsx)(JN,{}),label:e.label??(0,K.jsx)(npi,{scorerId:e.scorerId}),value:e.reason?.trim()?(0,K.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[z7(e.value),(0,K.jsx)(Rmi,{scorerId:e.scorerId,reason:e.reason})]}):z7(e.value),rawValue:e.value,delta:e.delta??null}))]}function Vgi({key:e,defaultValue:t,parse:n,toJSON:r=e=>e}){let i=new Set,a=null,o=t,s=!1,c=e=>{if(e===null)return t;try{return n(JSON.parse(e))}catch{return t}};return{read:()=>{if(s)return o;let t;try{t=localStorage.getItem(e)}catch{return s=!0,o}return t===a||(a=t,o=c(t)),o},write:t=>{a=JSON.stringify(r(t)),o=t;try{localStorage.setItem(e,a),s=!1}catch{s=!0}i.forEach(e=>e())},subscribe:t=>{let n=n=>{(n.key===e||n.key===null)&&(s=!1,t())};return i.add(t),window.addEventListener(`storage`,n),()=>{i.delete(t),window.removeEventListener(`storage`,n)}},defaultValue:t}}function Hgi(e){return(0,G.useSyncExternalStore)(e.subscribe,e.read,()=>e.defaultValue)}var Ugi={cost:`cost`,"total-cost":`cost`,duration:`duration`,"avg-duration":`duration`,"avg-score":`average`,tokens:`tokens`,"total-tokens":`tokens`,errors:`errors`};function Wgi(e){return e.startsWith(`scorer:`)?e:Ugi[e]}var Ggi=[],Kgi=Vgi({key:`mastra:experiments-compare:hidden-metrics`,defaultValue:Ggi,parse:e=>bd(q()).parse(e)});function qgi(){let e=Hgi(Kgi);return{isHidden:t=>e.includes(t),isMetricVisible:t=>{let n=Wgi(t);return n===void 0||!e.includes(n)},toggle:t=>Kgi.write(e.includes(t)?e.filter(e=>e!==t):[...e,t]),reset:()=>Kgi.write(Ggi)}}function Jgi(e){return e==null?`-`:typeof e==`string`?e:JSON.stringify(e,null,2)}function Ygi(e,t){return Bgi({usage:e.usage,showUsage:t,durationMs:J7(e),costDelta:e.costDelta,tokenDelta:e.tokenDelta,durationDeltaMs:e.durationDeltaMs,averageScore:e.scores.length>0?{value:jgi(e),delta:e.averageScoreDelta}:void 0,scores:e.scores.map(t=>({scorerId:t.scorerId,value:t.value,reason:t.reason,delta:e.deltas?.[t.scorerId]??null}))})}function Xgi({column:e,isLoading:t,showUsage:n=!1,outputExpanded:r,onOutputExpandedChange:i,onShowTrace:a}){let{isMetricVisible:o}=qgi();if(t)return(0,K.jsx)(`div`,{className:`flex h-32 items-center justify-center`,children:(0,K.jsx)(It,{})});if(!e.present)return(0,K.jsx)(T,{tone:`muted`,className:`py-5 text-center`,children:`Not present in this experiment`});let s=Jgi(e.output),c=Tmi(e),l=R7(e),u=Ami(e),d=jmi(e),f=Ygi(e,n).filter(e=>o(e.id)),{traceId:p}=e,m=p&&a?(0,K.jsx)(X,{size:`icon-sm`,variant:`ghost`,tooltip:`View trace`,"aria-label":`View trace`,onClick:()=>a(p),children:(0,K.jsx)(QN,{})}):void 0,h=f.length>0,g=e=>(0,K.jsxs)(K.Fragment,{children:[!h&&m,(0,K.jsx)(gC,{content:e,variant:`ghost`})]});return(0,K.jsxs)(`div`,{className:ipi,children:[h&&(0,K.jsx)(L7,{title:`Metrics`,collapsible:!1,actions:m,children:(0,K.jsx)(rpi,{metrics:f})}),l?(0,K.jsx)(L7,{title:`Error`,tone:`negative`,framed:!0,actions:g(l),children:(0,K.jsx)(T,{tone:`muted`,className:`p-3 break-words`,children:l})}):(0,K.jsx)(L7,{title:`Output`,framed:!0,actions:g(s),expanded:r,onExpandedChange:i,children:d?(0,K.jsx)(T,{tone:`muted`,className:`p-3 break-words`,children:d}):(0,K.jsx)(I7,{value:c??e.output})}),u.length>0&&(0,K.jsx)(L7,{title:`Tool calls (${u.length})`,children:(0,K.jsx)(lei,{toolCalls:u})}),e.comment&&(0,K.jsx)(L7,{title:`Comment`,framed:!0,children:(0,K.jsx)(I7,{value:e.comment})}),e.metadata&&Object.keys(e.metadata).length>0&&(0,K.jsx)(L7,{title:`Metadata`,framed:!0,actions:(0,K.jsx)(gC,{content:Jgi(e.metadata),variant:`ghost`}),children:(0,K.jsx)(I7,{value:e.metadata})})]})}var Zgi=U(`IconTarget`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M17 12C17 14.7614 14.7614 17 12 17C9.23858 17 7 14.7614 7 12C7 9.23858 9.23858 7 12 7C14.7614 7 17 9.23858 17 12Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M13 12C13 12.5523 12.5523 13 12 13C11.4477 13 11 12.5523 11 12C11 11.4477 11.4477 11 12 11C12.5523 11 13 11.4477 13 12Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinejoin:`round`})]}));function Qgi({experiment:e,open:t,onOpenChange:n}){let[r,i]=(0,G.useState)(e.name??``),[a,o]=(0,G.useState)(e.description??``),{updateExperiment:s}=ON(),c=!!r.trim();return(0,K.jsx)(nT,{open:t,onOpenChange:n,pending:s.isPending,children:(0,K.jsxs)(rT,{children:[(0,K.jsx)(iT,{children:(0,K.jsx)(sT,{children:`Rename Experiment`})}),(0,K.jsxs)(ZV,{onSubmit:async t=>{if(t.preventDefault(),c&&!s.isPending&&e.datasetId)try{await s.mutateAsync({datasetId:e.datasetId,experimentId:e.id,name:r.trim(),description:a.trim()}),iS.success(`Experiment renamed`),n(!1)}catch(e){iS.error(`Failed to rename experiment: ${e instanceof Error?e.message:`Unknown error`}`)}},children:[(0,K.jsxs)(oT,{children:[(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{required:!0,children:`Name`}),(0,K.jsx)(Jj,{required:!0,value:r,onChange:e=>i(e.target.value),placeholder:`Enter experiment name`,autoFocus:!0})]}),(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{children:`Description`}),(0,K.jsx)(Jj,{value:a,onChange:e=>o(e.target.value),placeholder:`Enter experiment description (optional)`})]})]}),(0,K.jsxs)(aT,{children:[(0,K.jsx)(lT,{children:`Cancel`}),(0,K.jsx)(tT,{type:`submit`,disabled:!c,children:s.isPending?`Saving...`:`Save`})]})]})]})})}function $gi({datasetId:e,version:t,differsFromBaseline:n}){let{Link:r,paths:i}=sn();return(0,K.jsxs)(`span`,{className:c(`flex min-w-0 items-center gap-2`,n&&`text-warning-foreground`),children:[n&&(0,K.jsx)(`span`,{className:`min-w-0 truncate`,children:`differs from baseline`}),(0,K.jsxs)(r,{href:`${i.datasetLink(e)}?version=${t}`,"aria-label":`Open dataset v${t}`,className:`shrink-0 hover:underline`,children:[`v`,t]})]})}function e_i({role:e,label:t,experiment:n,onSetBaseline:r}){let{Link:i}=sn(),[a,o]=(0,G.useState)(!1),s=n?aH(n.id)??n.id:null,l=!!n?.datasetId;return(0,K.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[n&&(0,K.jsxs)(rE,{children:[(0,K.jsx)(rE.Trigger,{render:(0,K.jsxs)(X,{size:`sm`,className:`max-w-full min-w-0`,children:[(0,K.jsx)(`span`,{className:`min-w-0 truncate`,children:n.name||s}),(0,K.jsx)(_,{"aria-hidden":!0})]})}),(0,K.jsxs)(rE.Content,{align:`start`,className:`min-w-48`,children:[(0,K.jsxs)(rE.Item,{render:(0,K.jsx)(i,{href:`/experiments/${n.id}`}),children:[(0,K.jsx)(tZ,{}),` View experiment`]}),l&&(0,K.jsxs)(rE.Item,{onSelect:()=>o(!0),children:[(0,K.jsx)(iH,{}),` Rename experiment`]})]})]}),n&&a&&(0,K.jsx)(Qgi,{experiment:n,open:!0,onOpenChange:o}),(0,K.jsx)(`div`,{className:`ml-auto shrink-0`,children:r?(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{render:(0,K.jsx)(`button`,{type:`button`,"aria-label":`Set as baseline`,onClick:r,className:c(`cursor-pointer rounded-[7px] hover:brightness-110`,p)}),children:(0,K.jsx)(eC,{variant:Phi[e],size:`md`,icon:(0,K.jsx)(AK,{}),children:t})}),(0,K.jsx)(Tx,{children:`Set as baseline`})]}):(0,K.jsx)(eC,{variant:Phi[e],size:`md`,icon:e===`baseline`?(0,K.jsx)(AK,{className:`fill-current`}):(0,K.jsx)(AK,{}),children:t})})]})}function t_i({role:e,experiment:t,summary:n,metrics:r,baselineMetrics:i,versionMismatch:a,showUsage:o=!1}){let{Link:s,paths:c}=sn(),{isMetricVisible:l}=qgi(),u=t?.createdAt?new Date(t.createdAt):null,d=e===`contender`,f=(e,t)=>d?Nmi(e,t):null,p=t?[...t.targetId?[{id:`target`,icon:t.targetType===`agent`?(0,K.jsx)(HN,{}):(0,K.jsx)(Zgi,{}),label:t.targetType===`agent`?`Agent`:`Target`,value:t.targetType===`agent`?(0,K.jsx)(s,{href:c.agentLink(t.targetId),className:`min-w-0 truncate hover:underline`,children:t.targetId}):(0,K.jsx)(`span`,{className:`min-w-0 truncate`,children:t.targetId}),delta:null}]:[],...t.datasetId&&t.datasetVersion!=null?[{id:`dataset-version`,icon:(0,K.jsx)(ahi,{}),label:`Dataset version`,value:(0,K.jsx)($gi,{datasetId:t.datasetId,version:t.datasetVersion,differsFromBaseline:a}),delta:null}]:[],...u?[{id:`created-at`,icon:(0,K.jsx)($j,{}),label:`Created`,value:bC(u,`date`),delta:null}]:[]]:[],m=o?r:void 0,h=[...m?[{id:`total-cost`,icon:(0,K.jsx)(zgi,{}),label:`Total cost`,value:B7(m.cost,m.costUnit),rawValue:m.cost,delta:m.costUnit===i?.costUnit?f(m.cost,i?.cost):null,formatDelta:Imi(m.costUnit),higherIsBetter:!1,emphasis:!0}]:[],...r?[{id:`avg-duration`,icon:(0,K.jsx)(tC,{}),label:`Avg duration`,value:iC(r.averageDurationMs)??`-`,rawValue:r.averageDurationMs,delta:f(r.averageDurationMs,i?.averageDurationMs),formatDelta:Mmi,higherIsBetter:!1,emphasis:!0}]:[],...r&&n&&n.length>0?[{id:`avg-score`,icon:(0,K.jsx)(G4,{}),label:`Avg score`,value:z7(r.averageScore),rawValue:r.averageScore,delta:f(r.averageScore,i?.averageScore),emphasis:!0}]:[],...m?[{id:`total-tokens`,icon:(0,K.jsx)(Z4,{}),label:`Total tokens`,value:V7(m.tokens),rawValue:m.tokens,delta:f(m.tokens,i?.tokens),formatDelta:V7,higherIsBetter:!1}]:[],...p,...r?[{id:`errors`,icon:(0,K.jsx)(Xx,{}),label:`Errors`,value:String(r.errorCount),delta:f(r.errorCount,i?.errorCount),formatDelta:String,higherIsBetter:!1}]:[],...(n??[]).map(({scorerId:e,average:t,delta:n})=>({id:`scorer:${e}`,icon:(0,K.jsx)(JN,{}),label:(0,K.jsx)(npi,{scorerId:e}),value:z7(t),rawValue:t,delta:d?n:null}))].filter(e=>l(e.id));return h.length===0?null:(0,K.jsx)(L7,{title:`Summary`,collapsible:!1,children:(0,K.jsx)(rpi,{metrics:h})})}function n_i(e){return(0,K.jsx)(qri,{...e,headerActionsSlot:e.traceId?(0,K.jsx)(ysi,{traceId:e.traceId,spans:e.spans},e.traceId):void 0})}function r_i({traceId:e,onClose:t,withQueryTrace:n,withFeedback:r}){let{navigate:i}=sn(),[a,o]=(0,G.useState)(),{data:s,isLoading:c}=dmi({traceId:e,queryOptions:{enabled:!!e}}),l=s?.spans,u=l?.find(e=>!e.parentSpanId),{data:d}=s8({traceId:e,queryOptions:{enabled:r&&!!e}}),{data:f}=o8({traceId:e,spanId:a,queryOptions:{enabled:r&&!!e&&!!a}}),{data:p}=BN({traceId:e,spanId:u?.spanId,page:0,queryOptions:{enabled:!!e&&!!u?.spanId}});return(0,K.jsx)(n_i,{size:`wide`,traceId:e,spans:l,isLoadingSpans:c,selectedSpanId:a??null,onClose:()=>{o(void 0),t()},onSpanSelect:o,showUnavailableFeaturesMsg:!1,traceHref:e?`/traces?traceId=${encodeURIComponent(e)}`:void 0,anchorSpanId:u?.spanId,withQueryTrace:n,withFeedback:r,onOpenScore:(e,t)=>i(CK(e,t)),feedbackTabBadge:r?d?.pagination?.total??void 0:void 0,feedbackTabSlot:r?({traceId:e})=>(0,K.jsx)(B5,{traceId:e}):void 0,scoresTabBadge:p?.pagination?.total??void 0,scoresTabSlot:({traceId:e,rootSpanId:t})=>t?(0,K.jsx)(nLr,{traceId:e,spanId:t,onScoreSelect:t=>i(CK(e,t))}):null,spanFeedbackTabBadge:r?f?.pagination?.total??void 0:void 0,spanFeedbackTabSlot:r?({traceId:e,spanId:t})=>e&&t?(0,K.jsx)($7r,{traceId:e,spanId:t},`${e}:${t}`):null:void 0})}var Y7=`min-w-0 px-4 py-3`,i_i=`grid grid-cols-[minmax(22rem,26rem)_repeat(var(--compare-cols),minmax(32rem,1fr))] divide-x divide-border border-border`,a_i=e=>!(e.target instanceof Element)||!e.currentTarget.contains(e.target)||e.target.closest(`a, button, input, select, textarea, [role="button"], [role="link"], [data-slot="collapsible-box-fade"]`)!==null,o_i=()=>!!window.getSelection()?.toString(),s_i=e=>e!=null,c_i=e=>e.length>0?e.reduce((e,t)=>e+t,0)/e.length:null,l_i=(e,t,n)=>c_i(e.map(e=>e.sides[t]?.scores.find(e=>e.scorerId===n)?.value??null).filter(s_i)),u_i=(e,t)=>{let n=e.map(e=>e.sides[t]).filter(e=>e?.present);return{errorCount:n.filter(e=>e.error).length,averageScore:c_i(n.flatMap(e=>e.scores.map(e=>e.value)).filter(s_i)),averageDurationMs:c_i(n.map(J7).filter(s_i))}};function d_i({datasetId:e,baselineId:t,contenderIds:n,onSetBaseline:r}){let i=(0,G.useMemo)(()=>[t,...n],[t,n]),[a,o]=(0,G.useState)(),[s,l]=(0,G.useState)(),u=a5(),d=e=>{l(void 0),o(e)},f=e=>{o(void 0),l(e)},{data:p,isLoading:m,error:h}=bAt({datasetId:e,experimentIds:i,baselineId:t,queryOptions:{enabled:!!e&&!!t&&n.length>0}}),{data:g,isLoading:_}=kAt({datasetId:e,experimentIds:i}),v=(0,G.useMemo)(()=>i.map(e=>({id:e,status:g[e]?.status})),[i,g]),{data:y,isLoading:b}=jAt({datasetId:e,experiments:v}),{data:x}=MAt({experiments:v}),{supportsMetrics:S,isLoading:C}=S7(),{data:w,isLoading:E}=lmi({experiments:v,supportsMetrics:S}),D=(0,G.useMemo)(()=>Igi({comparison:p,experimentIds:i,resultsById:y,scoresById:x,usageById:w}),[p,i,y,x,w]),O=(0,G.useMemo)(()=>{let e=[...new Set(D.flatMap(e=>e.sides.flatMap(e=>e.scores.map(e=>e.scorerId))))].sort();return i.map((t,n)=>e.map(e=>{let t=l_i(D,n,e),r=l_i(D,0,e);return{scorerId:e,average:t,delta:n>0&&t!=null&&r!=null?t-r:null}}))},[D,i]),k=(0,G.useMemo)(()=>i.map((e,t)=>{let n=w[e]?.summary;return{...u_i(D,t),cost:n?.estimatedCost,costUnit:n?.costUnit,tokens:H7(n)}}),[D,i,w]);if(m||_||C||E)return(0,K.jsx)(`div`,{className:`pointer-events-none fixed inset-0 flex items-center justify-center`,children:(0,K.jsx)(It,{})});if(h)return(0,K.jsx)(Sk,{variant:`warning`,title:`Error loading comparison`,children:(0,K.jsx)(Sk.Message,{children:h instanceof Error?h.message:`Unknown error`})});if(!p||p.items.length===0)return(0,K.jsx)(T,{as:`p`,variant:`body`,tone:`muted`,className:`py-5 text-center`,children:`No comparison data`});let A=g[t];return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{role:`table`,"aria-label":`Experiments comparison`,className:`grid min-w-[calc(22rem_+_var(--compare-cols)_*_32rem)]`,style:{"--compare-cols":i.length},children:[(0,K.jsxs)(`div`,{role:`row`,className:c(i_i,`sticky top-0 z-20 bg-background`),children:[(0,K.jsx)(`div`,{role:`columnheader`,"aria-label":`Items`,className:Y7}),i.map((e,t)=>(0,K.jsx)(`div`,{role:`columnheader`,"aria-label":W7(t),className:c(Y7,`border-b`),children:(0,K.jsx)(e_i,{role:t===0?`baseline`:`contender`,label:W7(t),experiment:g[e]??void 0,onSetBaseline:t>0&&r?()=>r(e):void 0})},e))]}),(0,K.jsxs)(`div`,{role:`row`,"aria-label":`Summary`,className:c(i_i,`border-b`),children:[(0,K.jsx)(`div`,{role:`cell`,"aria-label":`Items`,className:Y7}),i.map((e,t)=>{let n=g[e]??void 0;return(0,K.jsx)(`div`,{role:`cell`,"aria-label":W7(t),className:Y7,children:(0,K.jsx)(t_i,{role:t===0?`baseline`:`contender`,experiment:n,summary:O[t],metrics:b?void 0:k[t],baselineMetrics:b?void 0:k[0],versionMismatch:t>0&&n&&A?n?.datasetVersion!==A?.datasetVersion:void 0,showUsage:S})},e)})]}),D.map(e=>(0,K.jsx)(f_i,{row:e,isLoading:b,showUsage:S,onOpen:()=>d(e.itemId),onShowTrace:f},e.itemId))]}),(0,K.jsx)(Lgi,{datasetId:e,itemId:a,onClose:()=>o(void 0)}),(0,K.jsx)(r_i,{traceId:s,onClose:()=>l(void 0),withQueryTrace:u.enabled,withFeedback:u.enabled})]})}function f_i({row:e,isLoading:t,showUsage:n,onOpen:r,onShowTrace:i}){let[a,o]=(0,G.useState)({input:!1,groundTruth:!1,output:!1}),s=e=>({expanded:a[e],onExpandedChange:t=>o(n=>({...n,[e]:t}))}),l=s(`output`);return(0,K.jsxs)(`div`,{role:`row`,"aria-label":e.itemId,tabIndex:0,onClick:e=>{a_i(e)||o_i()||r()},onKeyDown:e=>{e.target!==e.currentTarget||e.key!==`Enter`&&e.key!==` `||(e.preventDefault(),r())},className:c(i_i,`cursor-pointer border-b transition-colors duration-normal ease-out-custom hover:bg-fill-subtle`,m),children:[(0,K.jsxs)(`div`,{role:`cell`,className:c(Y7,ipi),children:[(0,K.jsx)(Rgi,{label:`Input`,value:e.input,...s(`input`)}),(0,K.jsx)(Rgi,{label:`Ground truth`,value:e.groundTruth,...s(`groundTruth`)})]}),e.sides.map((e,r)=>(0,K.jsx)(`div`,{role:`cell`,"aria-label":W7(r),className:Y7,children:(0,K.jsx)(Xgi,{column:e,isLoading:t,showUsage:n,outputExpanded:l.expanded,onOutputExpandedChange:l.onExpandedChange,onShowTrace:i})},e.experimentId))]})}function p_i(e){let t=new Map;if(!e?.counts)return t;for(let n of e.counts)t.set(n.experimentId,{needsReview:n.needsReview,complete:n.complete,total:n.total});return t}var X7=[eP(`/experiments`)],m_i=[`createdAt`,`status`],h_i=new Map;function g_i(){let[e,t]=(0,G.useState)(``),[n,r]=(0,G.useState)(`all`),[i,a]=(0,G.useState)(!1),[o,s]=(0,G.useState)([]),c=Ov(),[l,u]=Rv(),{sort:d,onSortChange:f}=u7({searchParams:l,setSearchParams:u,allowedKeys:m_i}),p=(0,G.useMemo)(()=>d?{field:d.key,direction:d.direction===`asc`?`ASC`:`DESC`}:void 0,[d]),m=l.get(`dataset`)??`all`,{targetType:h,targetId:g}=Nli(),_=e=>{t(e.search),r(e.statusFilter),u(t=>{let n=new URLSearchParams(t),r=(e,t)=>{t?n.set(e,t):n.delete(e)};return r(`dataset`,e.datasetFilter===`all`?``:e.datasetFilter),r(O7,e.targetType),r(k7,e.targetType===h?e.targetId:``),n},{replace:!0})},{data:v,isLoading:y,error:b}=kN(),{data:x,isLoading:S,error:C,isFetchingNextPage:w,hasNextPage:T,setEndOfListElement:E}=bmi({datasetId:m===`all`?void 0:m,target:{targetType:h,targetId:g},orderBy:p}),{data:D}=Nhi(),{supportsMetrics:O}=S7(),k=(0,G.useMemo)(()=>v?.datasets??[],[v?.datasets]),A=(0,G.useMemo)(()=>x??[],[x]),j=(0,G.useMemo)(()=>dgi(k),[k]),{data:M}=yAt({datasetIds:(0,G.useMemo)(()=>A.flatMap(e=>e.datasetId?[e.datasetId]:[]),[A])}),N=(0,G.useMemo)(()=>{let e=new Map(k.map(e=>[e.id,e]));return M?.forEach(t=>e.set(t.id,t)),[...e.values()]},[k,M]),{data:P}=ymi({experiments:A,supportsMetrics:O}),F=O?P??h_i:void 0,I=(0,G.useMemo)(()=>p_i(D),[D]),L=y||S,R=C||b,z=e=>{let t=new Set(A.map(e=>e.id));s(n=>{let r=n.filter(e=>t.has(e));return r.includes(e)?r.filter(t=>t!==e):r.length>=10?[...r.slice(0,9),e]:[...r,e]})},B=e=>{let t=new Map(A.map(e=>[e.id,e.datasetId])),n=t.get(e[0]);s(r=>r.length>0?[]:e.filter(e=>t.get(e)===n).slice(0,10))},{selectedIds:V,selectedDatasetIds:H}=(0,G.useMemo)(()=>{let e=new Map(A.map(e=>[e.id,e.datasetId])),t=o.filter(t=>e.has(t));return{selectedIds:t,selectedDatasetIds:new Set(t.map(t=>e.get(t)))}},[A,o]),ee=A.find(e=>e.id===V[0])?.datasetId??void 0,te=ee?{id:ee,name:N.find(e=>e.id===ee)?.name??ee}:void 0,U=V.length<2?`Select at least two experiments to compare`:H.size===1?void 0:`Only experiments from the same dataset can be compared`,W=()=>{if(V.length<2||U)return;let[e,...t]=V,[n]=H;if(!n)return;let r=new URLSearchParams({dataset:n,baseline:e});for(let e of t)r.append(`contender`,e);c(`/experiments/compare?${r.toString()}`)};if(R&&FN(R))return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:X7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(TH,{variant:`fill`})]});if(C&&IN(C))return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:X7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(wH,{variant:`fill`,resource:`experiments`})]});if(b&&IN(b))return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:X7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(wH,{variant:`fill`,resource:`datasets`})]});if(R)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:X7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load experiments`,descriptionSlot:R.message})]});let ne=(0,K.jsx)(Qpi,{open:i,onOpenChange:a,onSuccess:e=>void c(`/experiments/${e}`)});return A.length===0&&!L&&m===`all`&&!h?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:X7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(fgi,{onRunExperiment:()=>a(!0)}),ne]}):(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:X7}),headerActions:(0,K.jsx)(X,{variant:`primary`,size:`sm`,icon:(0,K.jsx)(Hx,{}),onClick:()=>a(!0),children:`New experiment`}),actionRow:(0,K.jsx)(Tgi,{search:e,statusFilter:n,datasetFilter:m,datasetOptions:j,targetType:h,targetId:g,onFiltersChange:_,selection:{selectedIds:V,onClearSelection:()=>s([]),onCompare:W,compareDisabledReason:U},comparableDataset:te}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(lgi,{experiments:A,datasets:N,reviewByExperiment:I,metricsByExperiment:F,isLoading:L,search:e,statusFilter:n,datasetFilter:m,isFetchingNextPage:w,hasNextPage:T,setEndOfListElement:E,sort:d,onSortChange:f,selection:{selectedExperimentIds:V,onToggleSelection:z,onToggleAll:B,comparableDatasetId:ee}}),ne]})}var __i={baseline:`bg-badge-purple-indicator`,contender:`bg-badge-blue-indicator`};function v_i({experimentId:e,name:t,role:n,className:r,trailing:i}){let{Link:a,paths:o}=sn(),s=t||e.slice(0,8);return(0,K.jsxs)(X,{render:(0,K.jsx)(a,{href:o.experimentLink(e)}),variant:`ghost`,size:`sm`,className:c(`max-w-48 min-w-0`,r),"aria-label":`Open experiment ${s}`,children:[n&&(0,K.jsx)(`span`,{"aria-hidden":`true`,className:c(`size-1.5 shrink-0 rounded-full`,__i[n])}),(0,K.jsx)(`span`,{className:`min-w-0 truncate`,children:s}),i&&(0,K.jsx)(`span`,{className:`ml-auto flex shrink-0`,children:i})]})}function y_i(){let[e]=Rv(),t=e.get(`dataset`)??void 0,n=e.get(`baseline`)??void 0;return{datasetId:t,baselineId:n,contenderIds:(0,G.useMemo)(()=>[...new Set(e.getAll(`contender`))].filter(e=>e&&e!==n).slice(0,9),[e,n])}}function b_i(){let{datasetId:e,baselineId:t,contenderIds:n}=y_i();return{datasetId:e,experimentIds:e&&t&&n.length>0&&t?[t,...n]:[]}}function x_i(){let{experimentIds:e}=b_i();return e.length>0?`Comparing ${e.length} experiments`:`Comparing`}function S_i(){let{datasetId:e,experimentIds:t}=b_i(),{data:n}=kAt({datasetId:e??``,experimentIds:t});return t.length===0?null:(0,K.jsxs)(yX,{children:[(0,K.jsx)(bX,{delay:0,closeDelay:100,render:(0,K.jsx)(X,{type:`button`,variant:`ghost`,size:`icon-sm`,"aria-label":`Show compared experiments`,children:(0,K.jsx)(_,{})})}),(0,K.jsx)(xX,{side:`bottom`,align:`end`,sideOffset:4,showArrow:!1,className:`w-72 p-1.5`,children:(0,K.jsx)(`ul`,{"aria-label":`Compared experiments`,className:`grid gap-0.5`,children:t.map((e,t)=>(0,K.jsx)(`li`,{className:`grid`,children:(0,K.jsx)(v_i,{className:`w-full max-w-none justify-start`,experimentId:e,name:n[e]?.name,role:t===0?`baseline`:`contender`,trailing:t===0&&(0,K.jsx)(eC,{variant:`purple`,size:`sm`,icon:(0,K.jsx)(AK,{className:`fill-current`}),children:`Baseline`})})},e))})})]})}function C_i({experimentIds:e}){return e.map((t,n)=>(0,K.jsxs)(`span`,{className:`flex items-center gap-2`,children:[n>0&&n===e.length-1&&`and`,(0,K.jsxs)(`span`,{className:`flex items-center`,children:[(0,K.jsx)(v_i,{experimentId:t}),n<e.length-2&&`,`]})]},t))}function w_i({datasetId:e,baselineId:t,contenderIds:n}){let[,r]=Rv(),i=(0,G.useMemo)(()=>[t,...n],[t,n]),{data:a,isLoading:o,error:s}=kAt({datasetId:e,experimentIds:i});return s&&FN(s)?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Compare`}),(0,K.jsx)(TH,{variant:`fill`})]}):s&&IN(s)?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Compare`}),(0,K.jsx)(wH,{variant:`fill`,resource:`experiments`})]}):s&&!LN(s)?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Compare`}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load experiments`,descriptionSlot:s.message})]}):!o&&(s||i.some(e=>!a[e]))?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Compare`}),(0,K.jsx)(`div`,{className:`grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto`,children:(0,K.jsxs)(`div`,{className:`py-5 text-center text-muted-foreground`,children:[(0,K.jsxs)(T,{as:`p`,children:[`Experiments must belong to the same dataset (`,e,`) to be compared.`]}),(0,K.jsxs)(T,{className:`mt-2 flex items-center justify-center gap-2`,children:[`One of`,(0,K.jsx)(C_i,{experimentIds:i}),`was not found in it.`]})]})})]}):(0,K.jsx)(`div`,{className:`h-full overflow-auto`,children:(0,K.jsxs)(`div`,{className:`grid w-full content-start`,children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Experiments comparison`}),(0,K.jsx)(d_i,{datasetId:e,baselineId:t,contenderIds:n,onSetBaseline:t=>{let n=new URLSearchParams({dataset:e,baseline:t});for(let e of i)e!==t&&n.append(`contender`,e);r(n)}})]})})}function T_i(){let{datasetId:e,baselineId:t,contenderIds:n}=y_i();return!e||!t||n.length===0?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Compare`}),(0,K.jsx)(`div`,{className:`grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto`,children:(0,K.jsxs)(`div`,{className:`py-5 text-center text-muted-foreground`,children:[(0,K.jsx)(T,{as:`p`,children:`Select two to ten experiments to compare.`}),(0,K.jsxs)(T,{className:`mt-2`,children:[`Use the URL format: /experiments/compare?dataset=`,`{datasetId}`,`&baseline=`,`{experimentId}`,`&contender=`,`{experimentId}`,`&contender=`,`{experimentId}`]})]})})]}):(0,K.jsx)(w_i,{datasetId:e,baselineId:t,contenderIds:n})}function E_i(){let{datasetId:e}=y_i(),{Link:t,paths:n}=sn(),{data:r,isLoading:i}=AN({datasetId:e??``,queryOptions:{enabled:!!e}});if(!e||i)return null;let a=r?.name||e;return(0,K.jsx)(t,{href:n.datasetLink(e),"aria-label":`Open dataset ${a}`,className:c(`flex max-w-64 min-w-0 rounded-[7px] hover:brightness-110`,p),children:(0,K.jsx)(eC,{size:`md`,icon:(0,K.jsx)(uT,{}),className:`max-w-full min-w-0`,children:(0,K.jsx)(`span`,{className:`min-w-0 truncate`,children:a})})})}var D_i=[{key:`cost`,label:`Cost`,usage:!0},{key:`duration`,label:`Duration`},{key:`average`,label:`Avg score`},{key:`tokens`,label:`Tokens`,usage:!0},{key:`errors`,label:`Errors`}];function O_i({datasetId:e,baselineId:t,contenderIds:n}){let{data:r}=bAt({datasetId:e,experimentIds:(0,G.useMemo)(()=>[t,...n],[t,n]),baselineId:t}),{supportsMetrics:i}=S7(),{isHidden:a,toggle:o,reset:s}=qgi(),c=(0,G.useMemo)(()=>[...new Set((r?.items??[]).flatMap(e=>Object.values(e.results).flatMap(e=>e?Object.keys(e.scores):[])))].sort(),[r]),l=D_i.filter(e=>i||!e.usage);return(0,K.jsxs)(rE,{children:[(0,K.jsx)(rE.Trigger,{render:(0,K.jsx)(X,{variant:`ghost`,size:`md`,icon:(0,K.jsx)(Q0r,{"aria-hidden":!0}),children:`Metrics`})}),(0,K.jsxs)(rE.Content,{align:`end`,className:`min-w-56`,children:[(0,K.jsx)(rE.Label,{children:`Run metrics`}),l.map(e=>(0,K.jsx)(rE.CheckboxItem,{checked:!a(e.key),onCheckedChange:()=>o(e.key),children:e.label},e.key)),c.length>0&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(rE.Separator,{}),(0,K.jsx)(rE.Label,{children:`Scorers`}),c.map(e=>{let t=`scorer:${e}`;return(0,K.jsx)(rE.CheckboxItem,{checked:!a(t),onCheckedChange:()=>o(t),children:e},t)})]}),(0,K.jsx)(rE.Separator,{}),(0,K.jsx)(rE.Item,{onSelect:s,children:`Show all metrics`})]})]})}function k_i(){let{datasetId:e,baselineId:t,contenderIds:n}=y_i();return(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[e&&t&&n.length>0&&(0,K.jsx)(O_i,{datasetId:e,baselineId:t,contenderIds:n}),(0,K.jsx)(E_i,{})]})}var A_i=[eP(`/experiments`),{id:`experiments-compare`,Component:x_i,Switcher:S_i}];function j_i(){return(0,K.jsx)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:A_i}),headerActions:(0,K.jsx)(k_i,{}),children:(0,K.jsx)(T_i,{})})}function M_i(e){let{data:t}=jN({experimentId:e.id,experimentStatus:e.status,queryOptions:{enabled:!!e.id}});return(0,G.useMemo)(()=>{if(e.scorerIds?.length)return e.scorerIds;if(!t)return[];let n=new Set;for(let e of Object.values(t))for(let t of e)n.add(t.scorerId);return[...n].sort()},[e.scorerIds,t])}var N_i=[`agent`,`workflow`,`scorer`];function P_i({experiment:e}){let[t,n]=(0,G.useState)(!1),r=Ov(),{paths:i}=sn(),a=M_i(e),o=N_i.find(t=>t===e.targetType),s=e.status===`running`||e.status===`pending`;return!e.datasetId||!o||!e.targetId?null:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(X,{variant:`primary`,size:`sm`,onClick:()=>n(!0),disabled:s,tooltip:s?`Available once this run finishes`:`Run this experiment again with the same configuration`,icon:(0,K.jsx)(DT,{}),children:`Rerun`}),t&&(0,K.jsx)(Qpi,{open:!0,onOpenChange:n,initialDatasetId:e.datasetId,initialDatasetVersion:e.datasetVersion??void 0,initialTargetType:o,initialTargetId:e.targetId,initialScorerIds:a,initialName:e.name??void 0,initialDescription:e.description??void 0,onSuccess:e=>void r(i.experimentLink(e))},a.join(`,`))]})}function F_i({experiment:e,onDeleteClick:t}){let[n,r]=(0,G.useState)(!1),i=!!e.datasetId;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(P_i,{experiment:e}),(i||!!t)&&(0,K.jsxs)(rE,{children:[(0,K.jsx)(rE.Trigger,{asChild:!0,children:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,"aria-label":`Experiment actions menu`,children:(0,K.jsx)(iE,{})})}),(0,K.jsxs)(rE.Content,{align:`end`,className:`w-48`,children:[i&&(0,K.jsxs)(rE.Item,{onSelect:()=>r(!0),children:[(0,K.jsx)(iH,{}),` Rename experiment`]}),t&&(0,K.jsxs)(rE.Item,{onSelect:t,variant:`destructive`,children:[(0,K.jsx)(Kj,{}),` Delete experiment`]})]})]}),n&&(0,K.jsx)(Qgi,{experiment:e,open:!0,onOpenChange:r})]})}var I_i=U(`IconCircleRecord`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{fillRule:`evenodd`,clipRule:`evenodd`,d:`M9.91422 10.5858C10.6953 11.3668 10.6953 12.6332 9.91422 13.4142C9.13317 14.1953 7.86684 14.1953 7.08579 13.4142C6.30474 12.6332 6.30474 11.3668 7.08579 10.5858C7.86684 9.80474 9.13317 9.80474 9.91422 10.5858Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{fillRule:`evenodd`,clipRule:`evenodd`,d:`M16.9142 10.5858C17.6953 11.3668 17.6953 12.6332 16.9142 13.4142C16.1332 14.1953 14.8668 14.1953 14.0858 13.4142C13.3047 12.6332 13.3047 11.3668 14.0858 10.5858C14.8668 9.80474 16.1332 9.80474 16.9142 10.5858Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M8.5 14H15.5`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`}),(0,K.jsx)(`path`,{d:`M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z`,stroke:`currentColor`,strokeWidth:`2`})]}));function L_i(e){let{data:t,isLoading:n}=i8({traceId:e,queryOptions:{enabled:!!e}}),r=t?.spans.find(e=>!e.parentSpanId)?.entityType===`agent`,{supportsMetrics:i,isLoading:a}=S7(),o=r&&i,s=fXr({traceIds:e?[e]:[],enabled:o,autoRefetch:!1}),c=o&&(s.isLoading||s.isPlaceholderData);return{usage:e?s.data?.get(e):void 0,isLoading:!!e&&(n||a||c)}}var R_i=`__create_tag__`;function z_i({selectedResults:e,vocabulary:t,onAddTag:n,disabled:r,variant:i}){let[a,o]=(0,G.useState)(``),s=(0,G.useMemo)(()=>[...t].sort(),[t]),c=(0,G.useMemo)(()=>{if(e.length===0)return new Set;let[t,...n]=e;return new Set((t.tags??[]).filter(e=>n.every(t=>(t.tags??[]).includes(e))))},[e]),l=(0,G.useMemo)(()=>{let e=s.map(e=>({label:e,value:e,end:c.has(e)?(0,K.jsx)(pC,{"data-testid":`tag-applied`,className:`size-icon-sm`}):void 0})),t=a.trim();return t.length>0&&!s.includes(t)?[{label:`Create "${t}"`,value:R_i},...e]:e},[s,c,a]);return(0,K.jsx)(_N,{"data-testid":`experiment-results-tag-picker`,options:l,value:void 0,onValueChange:e=>{let t=e===R_i?a.trim():e;t&&!c.has(t)&&n(t)},onInputValueChange:o,placeholder:`Add tag`,searchPlaceholder:`Search or create tag`,emptyText:`Type to create a tag`,variant:i,size:`sm`,className:`w-auto min-w-0`,disabled:r})}function B_i(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function V_i({report:e}){let{served:t,unconsumed:n,liveCalls:r,failure:i}=e,a=[...t.map(e=>({outcome:`served`,toolName:e.toolName,args:e.args})),...r.map(e=>({outcome:`live`,toolName:e.toolName,args:e.args})),...n.map(e=>({outcome:`unconsumed`,toolName:e.toolName,args:e.args}))];return(0,K.jsxs)(`div`,{className:`grid gap-2`,"data-testid":`tool-mock-report`,children:[(0,K.jsx)(jQ.SectionHeading,{icon:(0,K.jsx)(YS,{}),children:`Tool Mocks`}),i&&(0,K.jsx)(Sk,{variant:`destructive`,title:`Mock mismatch`,children:(0,K.jsxs)(Sk.Message,{children:[(0,K.jsx)(`span`,{className:`block`,children:`Tool "${i.toolName}" was called with arguments that did not match an available mock (${i.code}).`}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`mt-1 block`,children:[`Called with: `,(0,K.jsx)(uX,{children:B_i(i.args)})]}),n.length>0&&(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`mt-1 block`,children:[`Unconsumed mocks: `,(0,K.jsx)(uX,{children:n.map(e=>B_i(e.args)).join(`, `)})]})]})}),(0,K.jsx)(`div`,{className:`divide-y divide-border rounded border border-border`,children:a.map((e,t)=>(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-2 px-3 py-1.5`,children:[(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`min-w-0 truncate`,children:[(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`muted`,font:`mono`,children:e.toolName}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,font:`mono`,className:`ml-2`,children:B_i(e.args)})]}),(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`shrink-0 rounded px-2 py-0.5 ${H_i(e.outcome)}`,children:e.outcome})]},`${e.outcome}-${e.toolName}-${t}`))})]})}function H_i(e){switch(e){case`served`:return`bg-success-subtle text-success-subtle-foreground`;case`live`:return`bg-badge-orange-subtle text-badge-orange-foreground`;case`unconsumed`:return`bg-muted-foreground/10 text-muted-foreground`}}function U_i({result:e,itemId:t,fallback:n,title:r,onClose:i,variant:a=`drawer`,...o}){let s=r??(t?`Experiment item ${t}`:`Experiment result ${e?.id??``}`),c=e?(0,K.jsx)(W_i,{result:e,onClose:i,...o}):t?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(jQ.Header,{children:[(0,K.jsxs)(jQ.Heading,{children:[`Experiment item`,(0,K.jsx)(jQ.CopyId,{id:t})]}),(0,K.jsx)(jQ.HeaderActions,{children:(0,K.jsx)(jQ.CloseButton,{icon:`x`,onClick:i})})]}),n]}):null;return a===`inline`?c?(0,K.jsx)(jQ,{variant:`inline`,title:s,children:c}):null:(0,K.jsx)(jQ,{open:!!(e??t),onClose:i,title:s,depth:1,children:c})}function W_i({result:e,scores:t,onPrevious:n,onNext:r,onClose:i,onShowTrace:a,onScoreClick:o,featuredScoreId:s,onFlagForReview:c,onTagsChange:l,tagVocabulary:u=[],isUpdatingTags:d=!1,experimentLink:f,onComplete:p,feedbackTabSlot:m}){let h=q_i(e.input),g=q_i(e.output),_=Tmi(e),v=Ami(e),y=jmi(e),b=c&&e.status!==`needs-review`&&e.status!==`complete`,x=Array.isArray(e.tags)?e.tags:[],S=(0,G.useMemo)(()=>[e],[e]),C=!!l||x.length>0,{Link:w}=sn(),E=m&&e.traceId?e.traceId:void 0,{data:D}=s8({traceId:E,queryOptions:{enabled:!!E}}),{usage:O,isLoading:k}=L_i(e.traceId),A=k&&(e.targetType==null||e.targetType===`agent`),j=Bgi({usage:O,showUsage:!!O||A,durationMs:J7(e),scores:[]}).map(e=>A&&(e.id===`cost`||e.id===`tokens`)?{...e,value:(0,K.jsx)(zS,{"aria-hidden":!0,className:`h-4 w-14`})}:e),M=typeof e.error==`string`&&e.error?e.error:R7(e),N=[...j,{id:`item-id`,icon:(0,K.jsx)(W6,{}),label:`Item Id`,value:(0,K.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,K.jsx)(`span`,{className:`font-mono`,title:e.itemId,children:aH(e.itemId)}),(0,K.jsx)(gC,{content:e.itemId,tooltip:`Copy item ID to clipboard`,variant:`link`})]}),delta:null},...e.createdAt?[{id:`created`,icon:(0,K.jsx)($j,{}),label:`Created`,value:bC(e.createdAt,`date-time`),delta:null}]:[],...e.status?[{id:`status`,icon:(0,K.jsx)(I_i,{}),label:`Status`,value:(0,K.jsx)(x7r,{status:e.status}),delta:null}]:[],...C?[{id:`tags`,icon:(0,K.jsx)(wX,{}),label:`Tags`,value:(0,K.jsx)(K_i,{tags:x,selectedResults:S,onTagsChange:l,tagVocabulary:u,isUpdatingTags:d}),delta:null}]:[],...Bgi({showUsage:!1,durationMs:null,scores:(t??[]).map(e=>({scorerId:e.scorerId,value:e.score,reason:e.reason,label:o?(0,K.jsx)(G_i,{scorerId:e.scorerId,featured:s===e.id,onClick:()=>o(e.id)}):void 0}))})],P=(0,K.jsx)(jQ.Content,{children:(0,K.jsxs)(`div`,{className:ipi,children:[(0,K.jsx)(rpi,{metrics:N}),(0,K.jsx)(L7,{title:`Input`,framed:!0,actions:(0,K.jsx)(gC,{content:h}),children:(0,K.jsx)(I7,{value:e.input})}),e.groundTruth!=null&&(0,K.jsx)(L7,{title:`Ground Truth`,framed:!0,actions:(0,K.jsx)(gC,{content:q_i(e.groundTruth)}),children:(0,K.jsx)(I7,{value:e.groundTruth})}),M?(0,K.jsx)(L7,{title:`Error`,tone:`negative`,framed:!0,actions:(0,K.jsx)(gC,{content:M}),children:(0,K.jsx)(T,{tone:`muted`,className:`p-3 break-words`,children:M})}):(0,K.jsx)(L7,{title:`Output`,framed:!0,actions:(0,K.jsx)(gC,{content:g}),children:y?(0,K.jsx)(T,{tone:`muted`,className:`p-3 break-words`,children:y}):(0,K.jsx)(I7,{value:_??e.output})}),v.length>0&&(0,K.jsx)(L7,{title:`Tool calls (${v.length})`,children:(0,K.jsx)(lei,{toolCalls:v})}),e.toolMockReport&&(0,K.jsx)(V_i,{report:e.toolMockReport})]})});return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(jQ.Header,{children:[b&&(0,K.jsx)(X,{size:`sm`,variant:`primary`,onClick:()=>c(e.id),icon:(0,K.jsx)(UN,{}),children:`Request review`}),p&&e.status===`needs-review`&&(0,K.jsx)(X,{size:`sm`,variant:`primary`,onClick:p,icon:(0,K.jsx)(EX,{}),children:`Mark as reviewed`}),(0,K.jsxs)(jQ.HeaderActions,{children:[f&&(0,K.jsx)(X,{size:`icon-sm`,variant:`ghost`,render:(0,K.jsx)(w,{href:f}),tooltip:`See experiment`,"aria-label":`See experiment`,children:(0,K.jsx)(GN,{})}),e.traceId&&a&&(0,K.jsx)(X,{size:`icon-sm`,variant:`ghost`,onClick:a,tooltip:`See trace`,"aria-label":`See trace`,children:(0,K.jsx)(QN,{})}),(0,K.jsx)(jQ.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:`Go to previous result`,nextLabel:`Go to next result`}),(0,K.jsx)(jQ.CloseButton,{icon:`x`,onClick:i})]})]}),E?(0,K.jsxs)(gk,{defaultTab:`details`,className:`grid h-full min-h-0 grid-rows-[auto_1fr]`,children:[(0,K.jsx)(jQ.Header,{children:(0,K.jsxs)(hk,{variant:`pill-ghost`,size:`sm`,children:[(0,K.jsx)(_k,{value:`details`,children:`Details`}),(0,K.jsxs)(_k,{value:`feedback`,children:[`Feedback`,D?.pagination?.total!=null&&(0,K.jsxs)(K.Fragment,{children:[` (`,D.pagination.total,`)`]})]})]})}),(0,K.jsx)(vk,{value:`details`,flush:!0,children:P}),(0,K.jsx)(vk,{value:`feedback`,flush:!0,children:(0,K.jsx)(jQ.Content,{children:m({traceId:E})})})]}):P]})}function G_i({scorerId:e,featured:t,onClick:n}){return(0,K.jsx)(`button`,{type:`button`,"aria-pressed":t,onClick:n,className:c(`min-w-0 cursor-pointer truncate hover:text-foreground hover:underline`,t&&`text-foreground`),children:e})}function K_i({tags:e,selectedResults:t,onTagsChange:n,tagVocabulary:r,isUpdatingTags:i}){return(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center justify-end gap-1.5`,children:[e.map(t=>(0,K.jsxs)(ali,{value:t,className:n?`gap-1 pr-1`:void 0,children:[t,n&&(0,K.jsx)(`button`,{type:`button`,"aria-label":`Remove tag ${t}`,disabled:i,onClick:()=>n(e.filter(e=>e!==t)),className:`cursor-pointer rounded-sm hover:opacity-70 disabled:opacity-50`,children:(0,K.jsx)(xw,{className:`size-icon-xs`})})]},t)),n&&(0,K.jsx)(z_i,{selectedResults:t,vocabulary:r,onAddTag:t=>n([...e,t]),disabled:i,variant:`ghost`})]})}function q_i(e){return e==null?`-`:typeof e==`string`?e:JSON.stringify(e,null,2)}function J_i(e){let t=e.scorer;return t?.hasJudge===!1||t?.hasJudge!==!0&&!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function Y_i({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:i}){return(0,K.jsx)(jQ,{open:!!e,onClose:r,title:e?`Score ${e.scorerId}`:`Score`,depth:2,children:e&&(0,K.jsx)(X_i,{score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:i})})}function X_i({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:i}){let a=J_i(e),o=a?`Not applicable (code-based scorer)`:`Step not configured`;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(jQ.Header,{children:[(0,K.jsx)(jQ.CloseButton,{onClick:r,tooltip:`Close score panel`}),(0,K.jsxs)(jQ.Heading,{children:[`Score`,(0,K.jsx)(jQ.CopyId,{id:e.scorerId})]}),(0,K.jsxs)(jQ.HeaderActions,{children:[i&&e.traceId&&(0,K.jsx)(X,{size:`icon-sm`,variant:`ghost`,onClick:i,tooltip:`See trace`,"aria-label":`See trace`,children:(0,K.jsx)(QN,{})}),(n||t)&&(0,K.jsx)(jQ.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:`Go to previous score`,nextLabel:`Go to next score`})]})]}),(0,K.jsx)(jQ.Content,{children:(0,K.jsxs)(`div`,{className:`grid gap-3`,children:[(0,K.jsx)(jQ.CodeSection,{title:`Score: ${e.score}`,icon:(0,K.jsx)(G4,{}),codeStr:e.reason||o,simplified:!0}),!a&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(jQ.CodeSection,{title:`Preprocess Prompt`,icon:(0,K.jsx)(K4,{}),codeStr:e.preprocessPrompt||o,simplified:!0}),(0,K.jsx)(jQ.CodeSection,{title:`Analyze Prompt`,icon:(0,K.jsx)(K4,{}),codeStr:e.analyzePrompt||o,simplified:!0}),(0,K.jsx)(jQ.CodeSection,{title:`Generate Score Prompt`,icon:(0,K.jsx)(K4,{}),codeStr:e.generateScorePrompt||o,simplified:!0}),(0,K.jsx)(jQ.CodeSection,{title:`Generate Reason Prompt`,icon:(0,K.jsx)(K4,{}),codeStr:e.generateReasonPrompt||o,simplified:!0})]})]})})]})}function Z_i(e,t){let[n,r]=(0,G.useState)(null),[i,a]=(0,G.useState)(void 0),[o,s]=(0,G.useState)(null),[c,l]=(0,G.useState)(t);return t!==c&&(l(t),r(null),a(void 0),s(null)),{featuredTraceId:n,setFeaturedTraceId:r,featuredSpanId:i,setFeaturedSpanId:a,featuredScoreId:o,setFeaturedScoreId:s,featuredScore:e?.find(e=>e.id===o)??null}}function Q_i({result:e,scores:t,state:n,withQueryTrace:r,withFeedback:i,...a}){let o=Z_i(t,e?.id),{navigate:s}=sn(),{featuredTraceId:c,setFeaturedTraceId:l,featuredSpanId:u,setFeaturedSpanId:d,featuredScoreId:f,setFeaturedScoreId:p,featuredScore:m}=n??o,h=e=>{p(t=>e===t?null:e),l(null),d(void 0)},g=e=>{e&&(l(e),d(void 0),p(null))},_=()=>{if(!f||!t)return;let e=t.findIndex(e=>e.id===f);if(e>=0&&e<t.length-1)return()=>p(t[e+1].id)},v=()=>{if(!f||!t)return;let e=t.findIndex(e=>e.id===f);if(e>0)return()=>p(t[e-1].id)},{data:y,isLoading:b}=dmi({traceId:c,queryOptions:{enabled:!!c}}),x=y?.spans,S=x?.find(e=>!e.parentSpanId),{data:C}=s8({traceId:c??void 0,queryOptions:{enabled:i&&!!c}}),{data:w}=o8({traceId:c??void 0,spanId:u,queryOptions:{enabled:i&&!!c&&!!u}}),{data:T}=BN({traceId:c??void 0,spanId:S?.spanId,page:0,queryOptions:{enabled:!!c&&!!S?.spanId}});return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(U_i,{...a,result:e,scores:t,onScoreClick:h,featuredScoreId:f,onShowTrace:e?.traceId?()=>g(e.traceId):void 0,feedbackTabSlot:i?({traceId:e})=>(0,K.jsx)(B5,{traceId:e},e):void 0}),(0,K.jsx)(Y_i,{score:m??void 0,onNext:_(),onPrevious:v(),onClose:()=>p(null),onShowTrace:m?()=>g(m.traceId):void 0}),(0,K.jsx)(n_i,{size:`wide`,depth:2,traceId:c??void 0,spans:x,isLoadingSpans:b,selectedSpanId:u??null,onClose:()=>{l(null),d(void 0)},onSpanSelect:d,showUnavailableFeaturesMsg:!1,traceHref:c?`/traces?traceId=${encodeURIComponent(c)}`:void 0,anchorSpanId:S?.spanId,withQueryTrace:r,withFeedback:i,onOpenScore:(e,t)=>s(CK(e,t)),feedbackTabBadge:i?C?.pagination?.total??void 0:void 0,feedbackTabSlot:i?({traceId:e})=>(0,K.jsx)(B5,{traceId:e}):void 0,scoresTabBadge:T?.pagination?.total??void 0,scoresTabSlot:({traceId:e,rootSpanId:n})=>n?(0,K.jsx)(nLr,{traceId:e,spanId:n,onScoreSelect:e=>{t?.some(t=>t.id===e)&&(l(null),d(void 0),p(e))}}):null,spanFeedbackTabBadge:i?w?.pagination?.total??void 0:void 0,spanFeedbackTabSlot:i?({traceId:e,spanId:t})=>e&&t?(0,K.jsx)($7r,{traceId:e,spanId:t},`${e}:${t}`):null:void 0})]})}function $_i({withQueryTrace:e,withFeedback:t,variant:n}){let{currentItemId:r,experimentId:i,datasetId:a,experimentStatus:o,results:s,isLoadingResults:c,hasNextPage:l,close:u,goToPreviousItem:d,goToNextItem:f}=Cmi(),p=(0,G.useMemo)(()=>r?s.find(e=>e.itemId===r):void 0,[s,r]),{data:m}=jN({experimentId:i,experimentStatus:o,queryOptions:{enabled:!!i}}),{updateExperimentResult:h}=ON(),g=(0,G.useCallback)(async e=>{try{await h.mutateAsync({datasetId:a,experimentId:i,resultId:e,status:`needs-review`}),iS(`Result flagged for review`)}catch{iS.error(`Failed to flag result for review`)}},[a,i,h]),_=(0,G.useCallback)(async e=>{try{await h.mutateAsync({datasetId:a,experimentId:i,resultId:e,status:`complete`}),iS(`Result marked as reviewed`)}catch{iS.error(`Failed to complete result`)}},[a,i,h]),v=p?m?.[p.itemId]:void 0,y=Z_i(v,p?.id);return(0,K.jsx)(Q_i,{variant:n,result:p,itemId:r,fallback:c||l?(0,K.jsx)(jQ.LoadingData,{}):(0,K.jsxs)(jQ.NoData,{children:[`No loaded result for item "`,r,`".`]}),scores:v,state:y,withQueryTrace:e,withFeedback:t,onPrevious:d,onNext:f,onClose:u,onComplete:p?()=>_(p.id):void 0,onFlagForReview:p?()=>void g(p.id):void 0})}function evi(e){let{currentItemId:t,close:n}=Cmi(),r=Zw();return J1r(t,n),r?(0,K.jsx)($_i,{...e}):t?(0,K.jsx)(Y8,{owner:`experiment-item`,children:(0,K.jsx)($_i,{...e,variant:`inline`})}):null}function tvi({children:e,className:t}){return(0,K.jsx)(`div`,{className:`@container`,children:(0,K.jsx)(`div`,{className:c(`grid gap-4 *:min-w-0! @xl:@max-4xl:grid-cols-2 @3xl:@max-4xl:has-[>:nth-child(3)]:grid-cols-3 @3xl:@max-4xl:has-[>:nth-child(4):last-child]:grid-cols-2 @4xl:grid-cols-[repeat(auto-fit,minmax(12rem,1fr))] @4xl:@max-6xl:has-[>:nth-child(5)]:grid-cols-3`,t),children:e})})}var nvi=[{label:`Agent`,entityType:`agent`},{label:`Workflow`,entityType:`workflow_run`},{label:`Scorer`,entityType:`scorer`},{label:`Ingest`,entityType:`rag_ingestion`},{label:`Classifier`,entityType:`classifier`}],Z7=`rootEntityType`,Q7={tags:`filterTags`,entityName:`filterEntityName`,runId:`filterRunId`,threadId:`filterThreadId`,sessionId:`filterSessionId`,requestId:`filterRequestId`,resourceId:`filterResourceId`,userId:`filterUserId`,organizationId:`filterOrganizationId`,serviceName:`filterServiceName`,environment:`filterEnvironment`,experimentId:`filterExperimentId`,provider:`filterProvider`,model:`filterModel`},rvi=Object.keys(Q7),ivi=`mastra:metrics:saved-filters`;function avi(e){let t=yvi(e);try{localStorage.setItem(ivi,t.toString())}catch{}}function ovi(){try{let e=localStorage.getItem(ivi);if(!e)return null;let t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function svi(e){if(e.has(`rootEntityType`))return!0;for(let t of rvi)if(e.has(Q7[t]))return!0;return!1}var cvi=`hasAll`,lvi=[{id:`is`,label:`is`},{id:cvi,label:`has all of`,arity:`many`}],uvi={rootEntityType:`Primitive type`,entityName:`Primitive name`,tags:`Tags`,serviceName:`Service Name`,environment:`Environment`,threadId:`Thread ID`,resourceId:`Resource ID`,userId:`User ID`,organizationId:`Organization ID`,runId:`Run ID`,sessionId:`Session ID`,requestId:`Request ID`,experimentId:`Experiment ID`,provider:`Provider`,model:`Model`},dvi={provider:U6,model:mP},fvi=[`threadId`,`resourceId`,`userId`,`organizationId`,`runId`,`sessionId`,`requestId`,`experimentId`],pvi=e=>({id:e,label:uvi[e],icon:dvi[e]??A8(e),color:j8(e)}),mvi=(e,t)=>e.label.localeCompare(t.label);function hvi({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r}){let i=(e,t)=>({...pvi(e),operators:[`is`],strict:!0,suggestions:t}),a=e=>({...pvi(e),operators:[`is`]}),o=e=>e.map(e=>({value:e})),s=[i(`rootEntityType`,nvi.map(e=>({value:e.entityType,label:e.label}))),i(`entityName`,o(t)),{...i(`tags`,o(e)),operators:[cvi]},i(`serviceName`,o(n)),i(`environment`,o(r))],c=fvi.map(a),l=[`provider`,`model`].map(e=>({...a(e),hidden:!0}));return[...s.toSorted(mvi),...c.toSorted(mvi),...l]}function gvi(e){return e.map(e=>{if(e.fieldId===`tags`){let t=[e.value].flat().filter(e=>e!==``);return{id:e.fieldId,fieldId:e.fieldId,operatorId:cvi,value:t}}let t=Array.isArray(e.value)?e.value[0]??``:e.value;return{id:e.fieldId,fieldId:e.fieldId,operatorId:`is`,value:Svi(t)?``:t}})}function _vi(e){return e.map(e=>({fieldId:e.fieldId,value:Array.isArray(e.value)?e.value.map(String):String(e.value)}))}function vvi(e){let t=[],n=new Map([[Z7,`rootEntityType`]]);for(let e of rvi)n.set(Q7[e],e);let r=new Set;for(let[i]of e.entries()){let a=n.get(i);if(!a||r.has(a))continue;if(r.add(a),a===`tags`){let n=e.getAll(i);if(n.length===0)continue;t.push({fieldId:a,value:n.filter(Boolean)});continue}if(a===`rootEntityType`||a===`entityName`||a===`serviceName`||a===`environment`||a===`provider`||a===`model`){let n=e.getAll(i);if(n.length>1){t.push({fieldId:a,value:n});continue}}let o=e.get(i);o!==null&&t.push({fieldId:a,value:o})}return t}function yvi(e){let t=new URLSearchParams,n=e.getAll(Z7);for(let e of n)t.append(Z7,e);for(let n of rvi){let r=Q7[n],i=e.getAll(r);for(let e of i)t.append(r,e)}return t}function bvi(e,t){e.delete(Z7);for(let t of rvi)e.delete(Q7[t]);for(let n of t){let t=n.fieldId===`rootEntityType`?Z7:Q7[n.fieldId];if(t){if(Array.isArray(n.value)){let r=n.value.filter(e=>typeof e==`string`&&e!==``);if(r.length===0){n.fieldId===`tags`&&e.append(t,``);continue}for(let n of r)e.append(t,n)}else typeof n.value==`string`&&e.set(t,n.value.trim())}}}var xvi=`Any`;function Svi(e){let t=e.trim();return t===``||t===xvi}var Cvi=new Set(nvi.map(e=>e.entityType));function wvi(e){let t=e.trim();return Cvi.has(t)?t:void 0}function Tvi(e){let t={};for(let n of e){let e=n.fieldId;if(Array.isArray(n.value)){let r=n.value.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(e=>!Svi(e));if(r.length===0)continue;if(e===`tags`)t.tags=r;else if(e===`rootEntityType`){let e=r[0],n=e===void 0?void 0:wvi(e);n&&(t.rootEntityType=n)}else t[e]=r[0]}else if(typeof n.value==`string`){if(Svi(n.value))continue;let r=n.value.trim();if(e===`rootEntityType`){let e=wvi(r);e&&(t.rootEntityType=e)}else t[e]=r}}return t}var Evi={first:0,normal:1,last:2},Dvi=class extends Error{constructor(){super(`Skipped: nothing is waiting for this request any more`),this.name=`SkippedRequestError`}};function Ovi(e){let t=0,n=[],r=()=>{t<e&&n.shift()?.start()};return{run(i,{priority:a=Evi.normal,isWanted:o}={}){return new Promise((s,c)=>{let l=e=>{e&&o&&!o()?(c(new Dvi),r()):(t++,i().then(s,c).finally(()=>{t--,r()}))};if(t<e&&n.length===0){l(!1);return}let u={priority:a,start:()=>l(!0)},d=n.findIndex(e=>e.priority>a);d===-1?n.push(u):n.splice(d,0,u)})}}}var kvi=(0,G.createContext)(void 0);function Avi(){let e=(0,G.use)(kvi);if(!e)throw Error(`useAggregateLimiter must be used inside MetricsProvider or AggregateLimiterProvider`);return e}function jvi(e,t){let n=Avi(),r=u_();return({queryKey:i})=>n.run(e,{priority:t,isWanted:()=>(r.getQueryCache().find({queryKey:i,exact:!0})?.getObserversCount()??0)>0})}function Mvi({children:e}){let t=(0,G.use)(kvi),[n]=(0,G.useState)(()=>t?void 0:Ovi(3));return(0,K.jsx)(kvi,{value:t??n,children:e})}var Nvi=864e5,Pvi={"24h":Nvi,"3d":2592e5,"7d":6048e5,"14d":12096e5,"30d":2592e6};function Fvi(e,t,n){if(e!==`custom`){let t=Pvi[e]??Nvi;return{start:new Date(n-t),end:new Date(n)}}return{start:t?.from??new Date(n-Nvi),end:t?.to??new Date(n)}}function Ivi({datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}){let i=(0,G.useRef)(null),a=e===`custom`?`custom:${t?.from?.getTime()??``}:${t?.to?.getTime()??``}`:`preset:${e}`;i.current&&i.current.key===a||(i.current={key:a,anchor:Date.now()});let o=i.current.anchor,s=(0,G.useMemo)(()=>Fvi(e,t,o),[e,t,o]);return{datePreset:e,customRange:t,timestamp:s,filters:(0,G.useMemo)(()=>({timestamp:s,...n}),[s,r]),dimensionalFilter:n,filterKey:(0,G.useMemo)(()=>`${a}|${r}`,[a,r])}}function Lvi(e){let t=Y(),{filters:n,filterKey:r,queryOptions:i}=e;return T_({queryKey:[`metrics`,`agent-runs-kpi`,r],queryFn:()=>t.getMetricAggregate({name:[`mastra_agent_duration_ms`],aggregation:`count`,filters:n,comparePeriod:`previous_period`}),...i})}new Intl.NumberFormat(`en-US`,{notation:`compact`,maximumSignificantDigits:3}),new Intl.NumberFormat(`en-US`),new Set(Intl.supportedValuesOf(`currency`));function Rvi(e){let t=Y(),{filters:n,filterKey:r,queryOptions:i}=e;return T_({queryKey:[`metrics`,`token-usage-by-agent`,r],queryFn:async()=>{let e={groupBy:[`entityName`],aggregation:`sum`,orderDirection:`DESC`,filters:n},[r,i]=await Promise.all([t.getMetricBreakdown({...e,name:[`mastra_model_total_input_tokens`]}),t.getMetricBreakdown({...e,name:[`mastra_model_total_output_tokens`]})]),a=new Map,o=e=>K6(a,e,()=>({input:0,output:0,cost:null,costUnit:null})),s=(e,t)=>{t.estimatedCost!=null&&(e.cost=(e.cost??0)+t.estimatedCost,t.costUnit&&(e.costUnit=t.costUnit))};for(let e of r.groups){let t=o(e.dimensions.entityName??`unknown`);t.input=e.value,s(t,e)}for(let e of i.groups){let t=o(e.dimensions.entityName??`unknown`);t.output=e.value,s(t,e)}return Array.from(a.entries()).map(([e,t])=>({name:e,input:t.input,output:t.output,total:t.input+t.output,cost:t.cost,costUnit:t.costUnit})).sort((e,t)=>t.total-e.total)},...i})}async function zvi(e,t,n){let r=await e.getMetricBreakdown({name:[t],groupBy:[`entityName`,`status`],aggregation:`count`,orderDirection:`DESC`,filters:n}),i=new Map;for(let e of r.groups){let t=e.dimensions.entityName??`unknown`,n=e.dimensions.status??`ok`,r=K6(i,t,()=>({completed:0,errors:0}));n===`error`?r.errors+=e.value:r.completed+=e.value}return Array.from(i.entries()).map(([e,t])=>({name:e,...t})).sort((e,t)=>t.completed+t.errors-(e.completed+e.errors))}function Bvi(e){let t=Y(),{filters:n,filterKey:r,queryOptions:i}=e;return T_({queryKey:[`metrics`,`trace-volume`,r],queryFn:async()=>{let[e,r,i]=await Promise.all([zvi(t,`mastra_agent_duration_ms`,n),zvi(t,`mastra_workflow_duration_ms`,n),zvi(t,`mastra_tool_duration_ms`,n)]);return{agentData:e,workflowData:r,toolData:i}},...i})}var Vvi=[{label:`Last 24 hours`,value:`24h`},{label:`Last 3 days`,value:`3d`},{label:`Last 7 days`,value:`7d`},{label:`Last 14 days`,value:`14d`},{label:`Last 30 days`,value:`30d`}],Hvi=new Set(Vvi.map(e=>e.value));function Uvi(e){return typeof e==`string`&&(Hvi.has(e)||e===`custom`)}var Wvi=(0,G.createContext)({datePreset:`24h`,setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:`Last 24 hours`,comparisonLabel:`vs previous 24h`,filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:`{}`,queryFilters:void 0,scope:{}});function $7(){return(0,G.useContext)(Wvi)}function Gvi(e,t){return e===`custom`?t?.from?t.to?`${yC(t.from)} – ${yC(t.to)}`:yC(t.from)??``:`Custom range`:Vvi.find(t=>t.value===e)?.label??e}var Kvi=36e5;function qvi(e,t){if(e!==`custom`)return`vs previous ${e}`;let n=t?.to?.getTime()??Date.now(),r=t?.from?.getTime()??n-24*Kvi,i=Math.round((n-r)/Kvi);return`vs previous ${i>24&&i%24==0?`${i/24}d`:`${i}h`}`}function Jvi({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:i,customRange:a,onCustomRangeChange:o,scope:s}){let c=(0,G.useMemo)(()=>JSON.stringify(n),[n]),l=(0,G.useMemo)(()=>n,[c]),u=(0,G.useMemo)(()=>Tvi(l),[l]),d=(0,G.useMemo)(()=>JSON.stringify(u),[u]),f=Ivi({datePreset:t,customRange:a,dimensionalFilter:u,dimensionalFilterKey:d}),p=(0,G.useMemo)(()=>s??{},[s]),m=Gvi(t,a),h=qvi(t,a),g=(0,G.useMemo)(()=>({datePreset:t,setDatePreset:r,customRange:a,setCustomRange:o??(()=>{}),dateRangeLabel:m,comparisonLabel:h,filterTokens:l,setFilterTokens:i,dimensionalFilter:u,dimensionalFilterKey:d,queryFilters:f,scope:p}),[t,r,a,o,m,h,l,i,u,d,f,p]);return(0,K.jsx)(Wvi.Provider,{value:g,children:(0,K.jsx)(Mvi,{children:e})})}var Yvi=[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`];function Xvi(e){switch(e){case`3d`:return`last-3d`;case`7d`:return`last-7d`;case`14d`:return`last-14d`;case`30d`:return`last-30d`;case`custom`:return`custom`;default:return`last-24h`}}function Zvi(e){switch(e){case`last-3d`:return`3d`;case`last-7d`:return`7d`;case`last-14d`:return`14d`;case`last-30d`:return`30d`;case`custom`:return`custom`;default:return`24h`}}var Qvi=864e5;function $vi(){let{data:e}=i5(),t=e?.capabilities.traceRetentionDays;if(t===void 0)return;let n=new Date(Date.now()-t*Qvi);return new Date(n.getFullYear(),n.getMonth(),n.getDate())}function eyi(){let{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=$7(),i=$vi();return(0,K.jsx)(f3r,{preset:Xvi(e),onPresetChange:e=>t(Zvi(e)),dateFrom:n?.from,dateTo:n?.to,onDateRangeChange:(e,t)=>r({from:e,to:t}),presets:Yvi,minDate:i})}var tyi=G.forwardRef(({label:e,children:t,...n},r)=>(0,K.jsx)(X,{ref:r,variant:`ghost`,size:`icon-sm`,tooltip:e,"aria-label":e,...n,children:t}));tyi.displayName=`MetricsCardAction`;function nyi({children:e,className:t}){return(0,K.jsx)(`div`,{className:c(`-my-1 flex shrink-0 items-center gap-1 self-start`,t),children:e})}function ryi({children:e,className:t}){return(0,K.jsx)(`div`,{className:c(`overflow-x-auto overflow-y-hidden [&_tbody>tr:last-child]:border-b-0`,t),children:e})}function iyi({className:e,...t}){return(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,className:c(`-my-1 shrink-0 cursor-grab active:cursor-grabbing`,e),...t,children:(0,K.jsx)(yP,{})})}function ayi({message:e=`Failed to load data`,className:t}){return(0,K.jsx)(`div`,{className:c(`flex flex-col items-center justify-center gap-3`,t),children:(0,K.jsx)(T,{variant:`caption`,className:`text-destructive-foreground`,children:e})})}function oyi({label:e,value:t,change:n,isLoading:r=!1,className:i}){return(0,K.jsxs)(`div`,{className:c(`grid gap-1.5`,i),children:[(0,K.jsx)(`h3`,{className:`text-body-sm text-muted-foreground`,children:e}),(0,K.jsxs)(`span`,{className:`flex items-baseline gap-2`,children:[(0,K.jsx)(`span`,{className:c(`text-title text-foreground tabular-nums [text-box:trim-both_cap_alphabetic]`,r&&`relative min-w-24`),children:r?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`span`,{className:`invisible`,children:`0`}),(0,K.jsx)(zS,{className:`absolute inset-0`})]}):t}),!r&&n&&(0,K.jsxs)(`span`,{className:`text-body-sm text-muted-foreground tabular-nums [text-box:trim-both_cap_alphabetic]`,children:[n,` vs previous`]})]})]})}function syi({className:e}){return(0,K.jsx)(`div`,{className:c(`flex items-center justify-center`,e),children:(0,K.jsx)(It,{size:`md`,variant:`pulse`,className:`text-placeholder`})})}function cyi({message:e=`No data yet`,className:t}){return(0,K.jsx)(`div`,{className:c(`flex h-full items-center justify-center`,t),children:(0,K.jsx)(T,{tone:`faint`,children:e})})}function lyi({children:e,className:t}){return(0,K.jsx)(nP,{className:c(`group/metrics-card grid min-h-72 min-w-80 flex-1 grid-rows-[auto_1fr] gap-4 px-4 py-3 2xl:min-w-120 md:min-w-88 lg:min-w-sm xl:min-w-104`,t),children:e})}function uyi({children:e,className:t,as:n=`h3`}){return(0,K.jsx)(n,{className:c(`text-subheading text-foreground`,t),children:e})}function dyi({title:e,value:t,onValueChange:n,options:r,className:i}){return(0,K.jsx)(`div`,{className:`flex min-w-0`,children:(0,K.jsxs)(rE,{modal:!1,children:[(0,K.jsxs)(rE.Trigger,{render:(0,K.jsx)(`button`,{type:`button`,className:c(`-mx-1.5 -my-0.5 flex items-center gap-1 self-start rounded-md px-1.5 py-0.5 text-left text-subheading text-foreground hover:bg-fill-subtle`,i)}),children:[e,(0,K.jsx)(_,{className:`size-icon-sm text-muted-foreground`})]}),(0,K.jsx)(rE.Content,{align:`start`,children:(0,K.jsx)(rE.RadioOptions,{options:r,value:t,onValueChange:n,closeOnSelect:!0})})]})})}function fyi({children:e,className:t}){return(0,K.jsx)(`div`,{className:c(`flex min-h-6 min-w-0 flex-wrap items-center justify-between gap-x-4 gap-y-2 [&>*:first-child]:min-w-0 [&>*:last-child:not(:first-child)]:ml-auto`,t),children:e})}function pyi({children:e,className:t}){return(0,K.jsx)(`div`,{className:c(`flex items-start gap-4 [&>:first-child]:min-w-0 [&>:first-child]:flex-1`,t),children:e})}function myi({value:e,isLoading:t=!1,className:n}){return(0,K.jsx)(`span`,{className:c(`order-last shrink-0 text-subheading text-foreground tabular-nums`,n),children:(0,K.jsx)(hyi,{value:e,isLoading:t})})}function hyi({value:e,isLoading:t}){return t?(0,K.jsx)(BS,{line:`text-body`,className:`h-4 w-14`}):typeof e==`string`?e:(0,K.jsx)(`span`,{className:`inline-flex items-center gap-3`,children:e.map(e=>(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,K.jsx)(`span`,{"aria-hidden":!0,className:`size-2 shrink-0 rounded-[2px]`,style:{backgroundColor:e.color}}),(0,K.jsxs)(`span`,{className:`sr-only`,children:[e.label,` `]}),e.value]},e.label))})}var e9=Object.assign(lyi,{Root:lyi,Kpi:z4,TopBar:pyi,Toolbar:fyi,Actions:nyi,Action:tyi,DragHandle:iyi,Title:uyi,TitleMenu:dyi,Total:myi,Headline:oyi,Loading:syi,Error:ayi,Content:ryi,NoData:cyi}),gyi=`pointer-events-none absolute opacity-0 pointer-coarse:pointer-events-auto pointer-coarse:static pointer-coarse:opacity-100 group-hover/metrics-card:pointer-events-auto group-hover/metrics-card:static group-hover/metrics-card:opacity-100 motion-safe:group-hover/metrics-card:transition-opacity group-focus-within/metrics-card:pointer-events-auto group-focus-within/metrics-card:static group-focus-within/metrics-card:opacity-100 motion-safe:group-focus-within/metrics-card:transition-opacity group-has-data-popup-open/metrics-card:pointer-events-auto group-has-data-popup-open/metrics-card:static group-has-data-popup-open/metrics-card:opacity-100`;function _yi({onClick:e}){return(0,K.jsx)(e9.Action,{label:`View in traces`,className:gyi,onClick:e,children:(0,K.jsx)(QN,{})})}function vyi({onClick:e}){return(0,K.jsx)(e9.Action,{label:`View errors in logs`,className:gyi,onClick:e,children:(0,K.jsx)(Ljt,{})})}function t9({isEmpty:e=!1,emptyMessage:t=`No data in this range`,children:n}){return(0,K.jsxs)(`div`,{className:`relative flex min-h-0 flex-1 flex-col`,"data-chart-empty":e||void 0,children:[(0,K.jsx)(`div`,{className:c(`flex min-h-0 flex-1 flex-col`,e&&`invisible [&_.recharts-xAxis-tick-labels]:visible`),children:(0,K.jsx)(G3r.Provider,{value:e,children:n})}),e&&(0,K.jsx)(byi,{message:t})]})}function yyi({className:e}){return(0,K.jsx)(`div`,{"aria-hidden":!0,className:c(`h-px bg-[linear-gradient(to_right,var(--border)_3px,transparent_3px)] bg-size-[6px_1px] opacity-50`,e)})}function byi({message:e}){return(0,K.jsxs)(`div`,{className:`absolute inset-0 flex flex-col justify-between`,style:{paddingTop:x5.top,paddingBottom:22},children:[(0,K.jsx)(yyi,{}),(0,K.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,K.jsx)(yyi,{className:`flex-1`}),(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`muted`,className:`max-w-[70%] text-center font-[450] text-balance`,children:e}),(0,K.jsx)(yyi,{className:`flex-1`})]}),(0,K.jsx)(yyi,{})]})}function n9({variant:e=`default`,title:t,href:n,LinkComponent:r,titleMenu:i,dragHandle:a,onTitleChange:o,total:s,change:l,isLoading:u=!1,actions:d,toolbar:f,isUpdating:p=!1,bodyHeight:m=`fixed`,className:h,children:g}){let _=c(`transition-opacity duration-200`,p&&`opacity-50`),v=e===`compact`,y=e===`hero`,b=!y&&m===`fixed`;return(0,K.jsxs)(e9,{className:c(`min-h-0! min-w-0! grid-cols-1`,`[&:has([data-slot=chart-skeleton])_[data-slot=chart-legend]]:invisible`,`[&:has([data-chart-empty])_[data-slot=chart-legend]]:invisible`,v&&`h-84`,h),children:[(0,K.jsxs)(e9.TopBar,{children:[y?(0,K.jsx)(e9.Headline,{label:t,value:typeof s==`string`?s:`—`,change:l,isLoading:u,className:_}):(0,K.jsx)(Syi,{title:t,href:n,LinkComponent:r,titleMenu:i,dragHandle:a,onTitleChange:o}),d&&(0,K.jsx)(e9.Actions,{className:c(y&&`my-0 self-center`),children:d}),!y&&s!==void 0&&(0,K.jsx)(e9.Total,{value:s,isLoading:u,className:_})]}),(0,K.jsxs)(e9.Content,{className:c(`flex flex-col gap-4 overflow-visible`,v&&`min-h-0`),children:[f||b&&f!==void 0&&(0,K.jsx)(`div`,{"aria-hidden":!0,className:`min-h-6`}),(0,K.jsx)(`div`,{className:c(`relative flex min-h-0 min-w-0 flex-col`,xyi(e,m),_),children:g})]})]})}function xyi(e,t){if(e===`compact`)return`flex-1`;if(e!==`hero`)return t===`fit`?`min-h-60`:`min-h-60 flex-1`}function Syi({dragHandle:e,...t}){return e?(0,K.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1.5`,children:[(0,K.jsx)(e9.DragHandle,{...e}),(0,K.jsx)(Cyi,{...t})]}):(0,K.jsx)(Cyi,{...t})}function Cyi({title:e,href:t,LinkComponent:n,titleMenu:r,onTitleChange:i}){return r?(0,K.jsx)(e9.TitleMenu,{title:e,...r}):t?(0,K.jsx)(`h3`,{className:`flex`,children:(0,K.jsx)(Tyi,{href:t,LinkComponent:n,children:e})}):i?(0,K.jsx)(wyi,{title:e,onTitleChange:i}):(0,K.jsx)(e9.Title,{children:e})}function wyi({title:e,onTitleChange:t}){return(0,K.jsx)(`h3`,{className:`flex min-w-0`,children:(0,K.jsx)(`input`,{"aria-label":`Widget title`,defaultValue:e,...Gk,onBlur:n=>{let r=n.currentTarget.value.trim();n.currentTarget.value=r,r!==e&&t(r)},onKeyDown:t=>{t.key===`Escape`&&(t.currentTarget.value=e),(t.key===`Enter`||t.key===`Escape`)&&(t.preventDefault(),t.currentTarget.blur())},className:c(`-mx-1.5 -my-0.5 field-sizing-content min-w-12 truncate rounded-md bg-transparent px-1.5 py-0.5`,`text-body zoom-safe-text font-medium text-foreground`,`outline-1 -outline-offset-1 outline-transparent outline-dashed hover:outline-border-strong focus:outline-border-focus`)},e)})}function Tyi({href:e,LinkComponent:t,children:n}){return(0,K.jsxs)(t??`a`,{href:e,className:c(`-mx-1.5 -my-0.5 inline-flex items-center gap-1.5 rounded-md px-1.5 py-0.5 text-subheading text-foreground hover:bg-fill-subtle`,`focus-visible:outline-1 focus-visible:-outline-offset-1 focus-visible:outline-border-focus focus-visible:outline-solid`),children:[n,(0,K.jsx)(dZ,{"aria-hidden":!0,className:`size-icon-sm text-muted-foreground`})]})}function r9({error:e,onRetry:t}){return FN(e)?(0,K.jsx)(TH,{}):IN(e)?(0,K.jsx)(wH,{resource:`traces`}):(0,K.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3`,children:[(0,K.jsx)(e9.Error,{message:`Couldn't load this data. Try again in a moment.`}),t&&(0,K.jsx)(X,{size:`sm`,icon:(0,K.jsx)(vS,{}),onClick:t,children:`Retry`})]})}function Eyi({label:e,icon:t,isError:n=!1,...r}){return(0,K.jsxs)(z4,{busy:!n&&(r.isLoading||r.isUpdating),children:[(0,K.jsx)(z4.Label,{icon:t&&(0,K.jsx)(t,{}),children:e}),n?(0,K.jsx)(Dyi,{}):(0,K.jsx)(Oyi,{...r})]})}function Dyi(){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(z4.ValueRow,{className:`mt-1`,children:(0,K.jsx)(z4.Value,{children:`—`})}),(0,K.jsx)(z4.Footer,{detail:(0,K.jsx)(`span`,{className:`text-destructive-foreground`,children:`Couldn't load`})})]})}function Oyi({value:e,change:t,lowerIsBetter:n,detail:r,previous:i,comparison:a,isLoading:o=!1,isUpdating:s=!1}){let l=c(`transition-opacity duration-200`,s&&`opacity-50`);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(z4.ValueRow,{className:c(`mt-1`,l),isLoading:o,children:[(0,K.jsx)(z4.Value,{children:e}),t!==void 0&&(0,K.jsx)(z4.Change,{changePct:t,comparison:a,lowerIsBetter:n,prevValue:i})]}),(0,K.jsx)(z4.Footer,{detail:r,prevValue:t===void 0?void 0:i,isLoading:o,className:l})]})}var kyi={2:`@3xl:grid-cols-2`,3:`@3xl:grid-cols-2 @7xl:grid-cols-3`},Ayi={1:``,2:`@3xl:col-span-2`,full:`col-span-full`};function i9({children:e,columns:t=3,className:n}){return(0,K.jsx)(`div`,{className:c(`@container`,n),children:(0,K.jsx)(`div`,{className:c(`grid gap-4`,kyi[t]),children:e})})}function jyi({children:e,span:t=1,className:n}){return(0,K.jsx)(`div`,{className:c(`min-w-0 *:size-full *:min-w-0!`,Ayi[t],n),children:e})}i9.Item=jyi;var Myi=864e5;function a9(e,t){let n=t.getTime()-e.getTime();return n<=9e7?{interval:`1h`,stepHours:1}:n<=2628e5?{interval:`1h`,stepHours:3}:n<=6084e5?{interval:`1h`,stepHours:6}:n<=12132e5?{interval:`1h`,stepHours:12}:{interval:`1d`,stepHours:24}}var o9=e=>e===`1h`?1:24;function Nyi(e,t){if(t>=24)return Math.floor(e/Myi)*Myi;let n=new Date(e),r=Math.floor(n.getHours()/t)*t;return new Date(n.getFullYear(),n.getMonth(),n.getDate(),r).getTime()}function Pyi(e,t){if(t>=24)return Nyi(e,t)+Myi;let n=new Date(e);return Nyi(new Date(n.getFullYear(),n.getMonth(),n.getDate(),n.getHours()+t).getTime(),t)}function Fyi(e,t,n){let r=_8r(e,t),i=[];for(let a=Nyi(e.getTime(),n);a<=t.getTime();a=Pyi(a,n))i.push(b8r(a,n,r));return i}function Iyi(e,t){let n=new Map(e.map((e,t)=>[e.ts,t]));return e=>n.get(Nyi(new Date(e.timestamp).getTime(),t))}function s9(e,t){return{from:new Date(e),to:new Date(Pyi(e,t))}}function c9(){let{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r,queryFilters:i}=$7(),a=Ivi({datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r});return i??a}var Lyi={input:`mastra_model_total_input_tokens`,output:`mastra_model_total_output_tokens`,cacheRead:`mastra_model_input_cache_read_tokens`},Ryi=`mastra_agent_duration_ms`;function zyi(){let e=Y(),{filters:t,filterKey:n,timestamp:r}=c9(),{interval:i,stepHours:a}=a9(r.start,r.end);return T_({queryKey:[`metrics`,`activity`,n,i],placeholderData:__,queryFn:async()=>{let n=n=>e.getMetricTimeSeries({name:[n],interval:i,aggregation:`sum`,filters:t}),[o,s,c,l]=await Promise.all([n(Lyi.input),n(Lyi.output),n(Lyi.cacheRead),e.getMetricTimeSeries({name:[Ryi],interval:i,aggregation:`count`,groupBy:[`status`],filters:t})]),u=Fyi(r.start,r.end,a).map(e=>({...e,input:0,cacheRead:0,output:0,cost:0,completed:0,failed:0,failureRate:0})),d=Iyi(u,a),f=e=>{let t=d(e);return t===void 0?void 0:u[t]},p=(e,t)=>{for(let n of e){let e=f(n);e&&(e[t]+=n.value,t!==`cacheRead`&&(e.cost+=n.estimatedCost??0))}};for(let e of o.series)p(e.points,`input`);for(let e of s.series)p(e.points,`output`);for(let e of c.series)p(e.points,`cacheRead`);for(let e of l.series){let t=/error|fail/i.test(e.name)?`failed`:`completed`;for(let n of e.points){let e=f(n);e&&(e[t]+=n.value)}}for(let e of u){e.input=Math.max(e.input-e.cacheRead,0);let t=e.completed+e.failed;e.failureRate=t>0?e.failed/t:0}return u}})}var Byi=[{dataKey:`input`,label:`Input`,color:g5.green},{dataKey:`cacheRead`,label:`Cache read`,color:g5.violet},{dataKey:`output`,label:`Output`,color:g5.sky}],Vyi=[{dataKey:`cost`,label:`Cost`,color:g5.green}],Hyi={tokens:`Token usage`,cost:`Model cost`},Uyi=[{value:`tokens`,label:Hyi.tokens},{value:`cost`,label:Hyi.cost}];function Wyi({onViewTraces:e,onTimeRangeClick:t}){let[n,r]=(0,G.useState)(`tokens`),{data:i=[],isLoading:a,isError:o,isPlaceholderData:s}=zyi(),{timestamp:c}=c9(),{stepHours:l}=a9(c.start,c.end),u=i.reduce((e,t)=>e+t.input+t.cacheRead+t.output,0),d=i.reduce((e,t)=>e+t.cost,0),f=n===`tokens`,p=f?Byi:Vyi,m={title:Hyi[n],titleMenu:{value:n,onValueChange:r,options:Uyi},actions:e&&(0,K.jsx)(_yi,{onClick:e}),toolbar:(0,K.jsx)(e9.Toolbar,{children:(0,K.jsx)(T5,{series:p})})};return o?(0,K.jsx)(n9,{...m,children:(0,K.jsx)(r9,{})}):(0,K.jsx)(n9,{...m,total:f?v5(u):b5(d),isLoading:a,isUpdating:s,children:(0,K.jsx)(t9,{isEmpty:!a&&u===0&&d===0,children:(0,K.jsx)(c8r,{data:i,series:p,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:f?v5:b5,axisFormatter:f?H3r:U3r,onBucketClick:t&&(e=>t(s9(Number(e.ts),l))),isLoading:a,...h5})})})}var Gyi=[{dataKey:`failureRate`,label:`Failed runs`,color:g5.error}],Kyi=e=>`${Math.round(e*100)}%`;function qyi({onViewErrors:e,onTimeRangeClick:t,titleMenu:n}){let{data:r=[],isLoading:i,isError:a,isPlaceholderData:o}=zyi(),{timestamp:s}=c9(),{stepHours:c}=a9(s.start,s.end),l=r.reduce((e,t)=>e+t.completed+t.failed,0),u=r.reduce((e,t)=>e+t.failed,0),d=u===0?[0,1]:void 0,f={title:`Failure rate`,titleMenu:n,actions:e&&(0,K.jsx)(vyi,{onClick:e}),toolbar:(0,K.jsx)(e9.Toolbar,{children:(0,K.jsx)(T5,{series:Gyi})})};return a?(0,K.jsx)(n9,{...f,children:(0,K.jsx)(r9,{})}):(0,K.jsx)(n9,{...f,total:y5(l>0?u/l:0),isLoading:i,isUpdating:o,children:(0,K.jsx)(t9,{isEmpty:!i&&l===0,children:(0,K.jsx)(B6r,{lineStyle:`thin`,data:r,series:Gyi,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:y5,axisFormatter:Kyi,yDomain:d,onBucketClick:t&&(e=>t(s9(Number(e.ts),c))),isLoading:i,...h5})})})}var Jyi=[{dataKey:`completed`,label:`Completed`,color:g5.green},{dataKey:`failed`,label:`Failed`,color:g5.error}],Yyi=[{value:`runs`,label:`Agent runs`},{value:`failure`,label:`Failure rate`}];function Xyi({onTimeRangeClick:e,onFailureTimeRangeClick:t,onViewErrors:n}){let[r,i]=(0,G.useState)(`runs`),a={value:r,onValueChange:i,options:Yyi};return r===`failure`?(0,K.jsx)(qyi,{titleMenu:a,onViewErrors:n,onTimeRangeClick:t}):(0,K.jsx)(Zyi,{titleMenu:a,onTimeRangeClick:e})}function Zyi({onTimeRangeClick:e,titleMenu:t}){let{data:n=[],isLoading:r,isError:i,isPlaceholderData:a}=zyi(),{timestamp:o}=c9(),{stepHours:s}=a9(o.start,o.end),c=n.reduce((e,t)=>e+t.completed+t.failed,0),l={title:`Agent runs`,titleMenu:t,toolbar:(0,K.jsx)(e9.Toolbar,{children:(0,K.jsx)(T5,{series:Jyi})})};return i?(0,K.jsx)(n9,{...l,children:(0,K.jsx)(r9,{})}):(0,K.jsx)(n9,{...l,total:v5(c),isLoading:r,isUpdating:a,children:(0,K.jsx)(t9,{isEmpty:!r&&c===0,children:(0,K.jsx)(c8r,{data:n,series:Jyi,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:v5,onBucketClick:e&&(t=>e(s9(Number(t.ts),s))),isLoading:r,...h5})})})}var Qyi={.5:`p50`,.95:`p95`,.99:`p99`},$yi={agents:`mastra_agent_duration_ms`,workflows:`mastra_workflow_duration_ms`,tools:`mastra_tool_duration_ms`};function ebi(e){let t=Y(),{filters:n,filterKey:r,timestamp:i}=c9(),{interval:a}=a9(i.start,i.end),o=o9(a);return T_({queryKey:[`metrics`,`latency-percentiles`,e,r,a],placeholderData:__,queryFn:async()=>{let r=await t.getMetricPercentiles({name:$yi[e],percentiles:[.5,.95,.99],interval:a,filters:n}),s=Fyi(i.start,i.end,o),c=Iyi(s,o);for(let e of r.series){let t=Qyi[e.percentile];if(t)for(let n of e.points){let e=s[c(n)??-1];e&&(e[t]=Math.round(n.value))}}return s}})}var tbi={agents:Dp.AGENT,workflows:Dp.WORKFLOW_RUN,tools:Dp.TOOL},nbi=[{dataKey:`p50`,label:`P50`,color:g5.sky},{dataKey:`p95`,label:`P95`,color:g5.green,emphasis:!0},{dataKey:`p99`,label:`P99`,color:g5.violet}],rbi={agents:`Agent latency`,workflows:`Workflow latency`,tools:`Tool latency`},ibi=[{value:`agents`,label:rbi.agents},{value:`workflows`,label:rbi.workflows},{value:`tools`,label:rbi.tools}];function abi({onViewTraces:e,onTimeRangeClick:t}){let[n,r]=(0,G.useState)(`agents`),{data:i=[],isLoading:a,isError:o,isPlaceholderData:s}=ebi(n),{timestamp:c}=c9(),l=o9(a9(c.start,c.end).interval),u=Math.max(0,...i.map(e=>e.p95??0)),d={title:rbi[n],titleMenu:{value:n,onValueChange:r,options:ibi},actions:e&&(0,K.jsx)(_yi,{onClick:()=>e(tbi[n])}),toolbar:(0,K.jsx)(e9.Toolbar,{children:(0,K.jsx)(T5,{series:nbi})})};return o?(0,K.jsx)(n9,{...d,children:(0,K.jsx)(r9,{})}):(0,K.jsx)(n9,{...d,total:V3r(u),isLoading:a,isUpdating:s,children:(0,K.jsx)(t9,{isEmpty:!a&&u===0,children:(0,K.jsx)(B6r,{lineStyle:`thin`,data:i,series:nbi,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:V3r,axisFormatter:W3r,onBucketClick:t&&(e=>t(s9(Number(e.ts),l))),isLoading:a,...h5})})})}var obi=`-mx-2 flex w-[calc(100%+1rem)] items-center gap-3 rounded-md px-2 py-1 text-left`,l9=`shrink-0 text-right text-body-sm tabular-nums`;function sbi({row:e,columns:t,valueWidth:n,share:r,highlighted:i,dimmed:a,onHover:o,LinkComponent:s}){let l=c(obi,i&&`bg-fill-subtle`,(e.href||e.onClick)&&`hover:bg-fill-subtle`);return(0,K.jsx)(`li`,{children:(0,K.jsxs)(cbi,{row:e,LinkComponent:s,className:l,style:{opacity:a?.5:1},onMouseEnter:o,children:[(0,K.jsx)(`span`,{className:`size-2 shrink-0 rounded-[2px]`,style:{backgroundColor:e.paint.color,opacity:e.paint.alpha}}),(0,K.jsx)(lbi,{row:e}),t.map((t,n)=>(0,K.jsx)(`span`,{className:c(l9,`text-muted-foreground`,t.width??`w-16`),children:e.cells?.[n]},t.label)),(0,K.jsx)(`span`,{className:c(l9,`w-12 text-muted-foreground`),children:r}),(0,K.jsx)(`span`,{className:c(l9,`text-foreground`,n),children:e.value})]})})}function cbi({row:e,LinkComponent:t,...n}){return e.href?(0,K.jsx)(t??`a`,{href:e.href,...n}):e.onClick?(0,K.jsx)(`button`,{type:`button`,onClick:e.onClick,...n}):(0,K.jsx)(`div`,{...n})}function lbi({row:e}){return typeof e.label==`string`?(0,K.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,title:e.title??e.label,children:(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`ink`,children:e.label})}):(0,K.jsx)(`span`,{className:`flex min-w-0 flex-1`,title:e.title,children:e.label})}var ubi=`var(--chart-share-1)`,dbi=[1,2,3,4,5].map(e=>`var(--chart-share-${e})`),fbi=[3,4,2,5,1].map(e=>`var(--chart-share-${e})`),pbi=[1,.7,.48,.32,.2,.14],mbi={color:`var(--chart-share-rest)`,alpha:1},hbi=50,gbi=`__rest`;function _bi(e,t,n){if(n===`hues`){let n=dbi.includes(e)?[e,...dbi.filter(t=>t!==e)]:[e,...fbi];return Array.from({length:t},(t,r)=>({color:n[r%n.length]??e,alpha:[1,.55,.3][Math.floor(r/n.length)]??.2}))}return Array.from({length:t},(t,n)=>({color:e,alpha:pbi[n]??.1}))}var vbi=e=>e.reduce((e,t)=>e+Math.max(t.share,0),0);function ybi(e){return e.map(e=>Number.isFinite(e.share)&&e.share>0?e:{...e,share:0}).toSorted((e,t)=>t.share-e.share)}function bbi(e,{limit:t,other:n,color:r,palette:i}){if(e.length<=t+1){let t=xbi(e,r,i);return{shown:t,bar:t,rest:[]}}let a=e.slice(t),o=n?.(a),s={key:gbi,label:`Other (${a.length})`,share:vbi(a),value:o?.value,cells:o?.cells,paint:mbi,segment:gbi},c=xbi(e.slice(0,t),r,i);return{shown:[...c,s],bar:c,rest:a}}function xbi(e,t,n){let r=_bi(t,e.length,n);return e.map((e,t)=>({...e,paint:Sbi(e)??r[t]??mbi,segment:e.key}))}var Sbi=e=>e.color?{color:e.color,alpha:1}:void 0;function Cbi(e,{count:t,color:n,palette:r}){let i=Math.min(t,e.length,hbi),a=xbi(e.slice(0,i),n,r),o=e.slice(i,t).map(e=>({...e,paint:mbi,segment:gbi}));return{shown:[...a,...o],bar:a,rest:e.slice(i)}}function wbi(e,t){let n=e.map(e=>({key:e.key,share:e.share,paint:e.paint})),r=t.length?[{key:gbi,share:vbi(t),paint:mbi}]:[],i=[...n,...r].filter(e=>e.share>0),a=i.reduce((e,t)=>e+t.share,0);return i.map(e=>({key:e.key,paint:e.paint,grow:e.share/a*100}))}function Tbi(e,t){if(t!==void 0)return e.find(e=>e.key===t)?.segment??t}var Ebi=(e,t)=>t!==void 0&&t!==e;function Dbi(e,t){return t===void 0||t===e.key?!1:t!==`__rest`||e.segment!==`__rest`}var Obi=(e,t)=>{let n=e/(t||1);return n>0?n<.001?`<0.1%`:`${(n*100).toFixed(+(n<.1))}%`:`0%`};function kbi({shown:e,total:t,limit:n,pageSize:r,onMore:i,onLess:a}){if(t<=n)return null;let o=t-e,s=`flex items-center gap-1.5 rounded-md px-2 py-1 text-label text-muted-foreground transition-colors duration-150 hover:bg-fill-subtle hover:text-foreground`,c=new Intl.NumberFormat(`en`,{notation:`compact`,maximumFractionDigits:1});return(0,K.jsxs)(`li`,{className:`-mx-2 flex items-center gap-1`,children:[o>0&&(0,K.jsxs)(`button`,{type:`button`,onClick:i,className:s,children:[(0,K.jsx)(_,{className:`size-icon-sm shrink-0`}),`Show `,Math.min(o,r),` more`]}),e>n&&(0,K.jsxs)(`button`,{type:`button`,onClick:a,className:s,children:[(0,K.jsx)(d,{className:`size-icon-sm shrink-0`}),`Show top `,n]}),o>0&&(0,K.jsxs)(`span`,{className:`ml-auto pr-2 text-body-sm text-placeholder tabular-nums`,children:[c.format(e),` of `,c.format(t)]})]})}var Abi=[`w-32`,`w-24`,`w-36`,`w-20`,`w-28`];function jbi({className:e}){return(0,K.jsxs)(K.Fragment,{children:[``,(0,K.jsx)(zS,{className:c(`absolute top-1/2 h-3.5 -translate-y-1/2`,e)})]})}function Mbi({rows:e,columns:t,valueWidth:n,header:r}){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`flex h-2`,children:(0,K.jsx)(zS,{className:`size-full rounded-full`})}),r,(0,K.jsx)(`ul`,{className:`grid min-w-0 grid-cols-1 gap-0.5`,"aria-busy":!0,children:Array.from({length:e},(e,r)=>(0,K.jsxs)(`li`,{className:obi,children:[(0,K.jsx)(zS,{className:`size-2 shrink-0 rounded-[2px]`}),(0,K.jsx)(`span`,{className:`min-w-0 flex-1`,children:(0,K.jsx)(T,{as:`span`,variant:`body-sm`,className:`relative`,children:(0,K.jsx)(jbi,{className:c(`left-0`,Abi[r%Abi.length])})})}),t.map(e=>(0,K.jsx)(`span`,{className:c(l9,`relative`,e.width??`w-16`),children:(0,K.jsx)(jbi,{className:`right-0 w-10`})},e.label)),(0,K.jsx)(`span`,{className:c(l9,`relative w-12`),children:(0,K.jsx)(jbi,{className:`right-0 w-9`})}),(0,K.jsx)(`span`,{className:c(l9,`relative`,n),children:(0,K.jsx)(jbi,{className:`right-0 w-12`})})]},r))})]})}function Nbi({className:e,...t}){return(0,K.jsx)(`div`,{className:c(`grid grid-cols-1`,e),children:(0,K.jsx)(Pbi,{...t})})}function Pbi({rows:e,columns:t=[],valueLabel:n,valueWidth:r=`w-14`,palette:i=`shades`,color:a=ubi,limit:o=5,overflow:s=`other`,pageSize:c=50,other:l,emptyState:u=`No data in this range.`,isLoading:d=!1,LinkComponent:f}){let[p,m]=(0,G.useState)(),[h,g]=(0,G.useState)(0),_=o+h*c,v=(0,K.jsx)(Fbi,{columns:t,valueLabel:n,valueWidth:r});if(d)return(0,K.jsx)(Mbi,{rows:s===`other`?o+1:o,columns:t,valueWidth:r,header:v});let y=ybi(e);if(y.length===0)return(0,K.jsx)(T,{variant:`body-sm`,tone:`muted`,className:`py-6 text-center`,children:u});let b=vbi(y),x=s===`more`,{shown:S,bar:C,rest:w}=x?Cbi(y,{count:_,color:a,palette:i}):bbi(y,{limit:o,other:l,color:a,palette:i}),E=wbi(C,w),D=Tbi(S,p),O=()=>m(void 0);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`flex h-2 gap-0.5`,onMouseLeave:O,children:E.map(e=>(0,K.jsx)(`span`,{"data-testid":`share-bar-segment`,onMouseEnter:()=>m(e.key),className:`h-full min-w-[3px] first:rounded-l-full last:rounded-r-full`,style:{flex:`${e.grow} 1 0`,backgroundColor:e.paint.color,opacity:e.paint.alpha*(Ebi(e.key,D)?.3:1)}},e.key))}),v,(0,K.jsxs)(`ul`,{className:`grid min-w-0 grid-cols-1 gap-0.5`,onMouseLeave:O,children:[S.map(e=>(0,K.jsx)(sbi,{row:e,columns:t,valueWidth:r,share:Obi(e.share,b),highlighted:p===e.key,dimmed:Dbi(e,p),onHover:()=>m(e.key),LinkComponent:f},e.key)),x&&(0,K.jsx)(kbi,{shown:Math.min(_,y.length),total:y.length,limit:o,pageSize:c,onMore:()=>g(e=>e+1),onLess:()=>g(0)})]})]})}function Fbi({columns:e,valueLabel:t,valueWidth:n}){let r=[...e.map(e=>({label:e.label,width:e.width??`w-16`})),{label:`Share`,width:`w-12`},{label:t,width:n}];return(0,K.jsx)(`div`,{"aria-hidden":!0,className:`flex items-center justify-end gap-3 pt-3 pb-0.5 text-column text-placeholder`,children:r.map(e=>(0,K.jsx)(`span`,{className:c(`shrink-0 text-right whitespace-nowrap`,e.width),children:e.label},e.label))})}var Ibi={agents:Dp.AGENT,workflows:Dp.WORKFLOW_RUN,tools:Dp.TOOL},Lbi=[{label:`Error rate`}],Rbi={agents:`Agent runs`,workflows:`Workflow runs`,tools:`Tool calls`},zbi=[{value:`agents`,label:Rbi.agents},{value:`workflows`,label:Rbi.workflows},{value:`tools`,label:Rbi.tools}],Bbi=(e,t)=>y5(t>0?e/t:0);function Vbi({onViewTraces:e,onViewErrors:t,onEntityClick:n}){let[r,i]=(0,G.useState)(`agents`),a=Ibi[r],o=Bvi({...c9(),queryOptions:{placeholderData:__}}),s={agents:o.data?.agentData??[],workflows:o.data?.workflowData??[],tools:o.data?.toolData??[]}[r],c=s.map(e=>({key:e.name,label:e.name,share:e.completed+e.errors,value:v5(e.completed+e.errors),cells:[Bbi(e.errors,e.completed+e.errors)],onClick:n&&(()=>n(a,e.name))})),l=new Map(s.map(e=>[e.name,e.errors])),u=s.reduce((e,t)=>e+t.completed+t.errors,0),d={title:Rbi[r],titleMenu:{value:r,onValueChange:i,options:zbi},actions:(e||t)&&(0,K.jsxs)(K.Fragment,{children:[e&&(0,K.jsx)(_yi,{onClick:()=>e(a)}),t&&(0,K.jsx)(vyi,{onClick:()=>t(a)})]})};return o.isError?(0,K.jsx)(n9,{...d,children:(0,K.jsx)(r9,{})}):(0,K.jsx)(n9,{...d,total:v5(u),isLoading:o.isLoading,isUpdating:o.isPlaceholderData,children:(0,K.jsx)(t9,{children:(0,K.jsx)(Nbi,{rows:c,columns:Lbi,valueLabel:`Runs`,color:g5.sky,other:e=>{let t=e.reduce((e,t)=>e+(l.get(t.key)??0),0),n=e.reduce((e,t)=>e+t.share,0);return{value:v5(n),cells:[Bbi(t,n)]}},emptyState:`No runs in this range.`,isLoading:o.isLoading},r)})})}var Hbi=[`mastra_model_total_input_tokens`,`mastra_model_total_output_tokens`],Ubi=100;function Wbi(e){let t=Y(),{filters:n,filterKey:r}=c9();return T_({queryKey:[`metrics`,`token-spend`,e,r],placeholderData:__,queryFn:async()=>{let{groups:r}=await t.getMetricBreakdown({name:Hbi,groupBy:[e],aggregation:`sum`,orderDirection:`DESC`,limit:Ubi,filters:n});return r.map(t=>({key:String(t.dimensions[e]??`unknown`),tokens:t.value,cost:t.estimatedCost??0}))}})}var Gbi={agents:`Usage by agent`,models:`Usage by model`,threads:`Usage by thread`},Kbi=[{value:`agents`,label:Gbi.agents},{value:`models`,label:Gbi.models},{value:`threads`,label:Gbi.threads}],qbi={placeholderData:__},Jbi=[{label:`Tokens`}];function Ybi(e){let[t,n]=(0,G.useState)(`agents`);return t===`models`?(0,K.jsx)(Zbi,{...e,onViewChange:n}):t===`threads`?(0,K.jsx)(Qbi,{...e,onViewChange:n}):(0,K.jsx)(Xbi,{...e,onViewChange:n})}function Xbi(e){let{onAgentClick:t}=e,{data:n=[],isLoading:r,isPlaceholderData:i,isError:a}=Rvi({...c9(),queryOptions:qbi}),o=n.map(e=>({key:e.name,cost:e.cost??0,tokens:e.total,onClick:t&&(()=>t(e.name))}));return(0,K.jsx)($bi,{view:`agents`,...e,rows:o,isLoading:r,isUpdating:i,isError:a})}function Zbi(e){let{onModelClick:t}=e,{data:n=[],isLoading:r,isPlaceholderData:i,isError:a}=Wbi(`model`),o=n.map(e=>({...e,onClick:t&&(()=>t(e.key))}));return(0,K.jsx)($bi,{view:`models`,...e,rows:o,isLoading:r,isUpdating:i,isError:a})}function Qbi(e){let{onThreadClick:t}=e,{data:n=[],isLoading:r,isPlaceholderData:i,isError:a}=Wbi(`threadId`),o=n.map(e=>({...e,onClick:t&&(()=>t(e.key))}));return(0,K.jsx)($bi,{view:`threads`,...e,rows:o,isLoading:r,isUpdating:i,isError:a})}function $bi({view:e,onViewChange:t,onViewTraces:n,rows:r,isLoading:i,isUpdating:a,isError:o}){let s=new Map(r.map(e=>[e.key,e.tokens])),c=r.map(e=>({key:e.key,label:e.key,share:e.cost,value:b5(e.cost),cells:[v5(e.tokens)],onClick:e.onClick})),l={title:Gbi[e],titleMenu:{value:e,onValueChange:t,options:Kbi},actions:n&&(0,K.jsx)(_yi,{onClick:n})};return o?(0,K.jsx)(n9,{...l,children:(0,K.jsx)(r9,{})}):(0,K.jsx)(n9,{...l,total:b5(r.reduce((e,t)=>e+t.cost,0)),isLoading:i,isUpdating:a,children:(0,K.jsx)(t9,{children:(0,K.jsx)(Nbi,{rows:c,columns:Jbi,valueLabel:`Cost`,color:g5.green,other:e=>({value:b5(e.reduce((e,t)=>e+t.share,0)),cells:[v5(e.reduce((e,t)=>e+(s.get(t.key)??0),0))]}),emptyState:`No model usage in this range.`,isLoading:i})})})}var exi=100;function txi(){let e=Y(),{filters:t,filterKey:n,timestamp:r}=c9(),{interval:i}=a9(r.start,r.end),a=o9(i);return T_({queryKey:[`metrics`,`scores`,n,i],placeholderData:__,queryFn:async()=>{let n=await e.listScores({filters:t,pagination:{page:0,perPage:exi}}),o=new Map(n.scores.map(e=>[e.scorerId,e.scorerName??e.scorerId])),s=[...o.keys()].toSorted(),c=await Promise.all(s.map(n=>Promise.all([e.getScoreAggregate({scorerId:n,aggregation:`avg`,filters:t}),e.getScoreTimeSeries({scorerId:n,aggregation:`avg`,interval:i,filters:t})]))),l=Fyi(r.start,r.end,a),u=Iyi(l,a),d=[];return c.forEach(([e,t],n)=>{let r=s[n];if(r){d.push({scorerId:r,name:o.get(r)??r,average:e.value??0});for(let e of t.series)for(let t of e.points){let e=l[u(t)??-1];e&&(e[r]=t.value)}}}),{scorers:d,buckets:l}}})}var nxi=[g5.green,g5.sky,g5.violet,g5.teal,g5.indigo],rxi=e=>e.toFixed(2),ixi=e=>String(+e.toFixed(2));function axi(e){return e.map(({scorerId:e,name:t},n)=>({dataKey:e,label:t,color:nxi[n%nxi.length]??g5.neutral}))}function oxi(){let{data:e,isLoading:t,isError:n,isPlaceholderData:r}=txi(),i=e?.scorers??[],a={title:`Scores`};return n?(0,K.jsx)(n9,{...a,children:(0,K.jsx)(r9,{})}):(0,K.jsx)(n9,{...a,isUpdating:r,children:(0,K.jsx)(t9,{isEmpty:!t&&i.length===0,children:(0,K.jsx)(B6r,{lineStyle:`thin`,data:e?.buckets??[],series:axi(i),height:`fill`,yDomain:[0,1],valueFormatter:rxi,axisFormatter:ixi,isLoading:t,...z3r})})})}var sxi=[`entityName`,`environment`,`threadId`,`resourceId`,`userId`,`organizationId`,`runId`,`sessionId`],cxi=[`provider`,`model`],lxi=[`serviceName`,`requestId`,`experimentId`],uxi=(e,t)=>({op:`eq`,left:{path:e},right:{literal:t}});function dxi(e){let t=lxi.filter(t=>e[t]!==void 0);if(t.length)return{supported:!1,unsupportedFields:t};let n=[];e.rootEntityType&&n.push(uxi(`entityType`,e.rootEntityType));for(let t of sxi){let r=e[t];r!==void 0&&n.push(uxi(t,r))}for(let t of e.tags??[])n.push({op:`includes`,path:`tags`,value:t});for(let t of cxi){let r=e[t];r!==void 0&&n.push({spans:{some:uxi(t,r)}})}return n.length===0?{supported:!0,where:void 0}:{supported:!0,where:n.length===1?n[0]:{op:`and`,args:n}}}var fxi=({start:e,end:t})=>({from:e.toISOString(),to:t.toISOString()}),pxi=({start:e,end:t})=>a9(e,t).interval;function mxi(e,t){let n=o9(pxi(t)),r=Fyi(t.start,t.end,n).map(e=>({...e,rows:[]})),i=Iyi(r,n);for(let t of e)t.bucket&&r[i({timestamp:t.bucket,value:0})??-1]?.rows.push(t);return r}function hxi({requiresRootSpanFields:e=!1}={}){let{data:t,isLoading:n}=i5(),{timestamp:r,dimensionalFilter:i}=c9();if(n)return{status:`loading`};let a=t?.capabilities;if(a?.traceAggregate!==!0||e&&a.traceQueryRootSpanFields!==!0)return{status:`unavailable`};let o=dxi(i);return o.supported?{status:`ready`,scope:{timeRange:fxi(r),...o.where?{where:o.where}:{},interval:pxi(r),window:r}}:{status:`unsupported-filter`,unsupportedFields:o.unsupportedFields}}function u9(e,{priority:t,enabled:n}={}){let r=Y();return zYr({request:e,enabled:n,queryOptions:{queryFn:jvi(()=>r.aggregateTraces(e),t),placeholderData:__,staleTime:1/0}})}var gxi=[{measure:`countDistinct.resourceId`,dataKey:`resources`,label:`Resources`,color:g5.sky},{measure:`countDistinct.threadId`,dataKey:`threads`,label:`Threads`,color:g5.green},{measure:`countDistinct.userId`,dataKey:`users`,label:`Users`,color:g5.violet},{measure:`countDistinct.sessionId`,dataKey:`sessions`,label:`Sessions`,color:g5.teal}],_xi=gxi.map(e=>e.measure),vxi=`Resources and threads`;function yxi(e,t){return e?.measures[t.measure]??0}function bxi({scope:e,onTimeRangeClick:t}){let n=u9({timeRange:e.timeRange,where:e.where,interval:e.interval,measures:_xi,limit:10}),r=u9({timeRange:e.timeRange,where:e.where,measures:_xi}),i=r.data?.rows[0],a=gxi.filter(e=>yxi(i,e)>0),o=a.map((e,t)=>({dataKey:e.dataKey,label:e.label,color:e.color,emphasis:t===0})),s=mxi(n.data?.rows??[],e.window).map(({rows:e,...t})=>({...t,...Object.fromEntries(a.map(t=>[t.dataKey,yxi(e[0],t)]))})),c=o9(e.interval===`1d`?`1d`:`1h`),l=n.error??r.error,u=n.isLoading||r.isLoading,d={title:vxi,total:l?void 0:a.length?a.map(e=>({label:e.label,value:v5(yxi(i,e)),color:e.color})):v5(0),isLoading:r.isLoading,toolbar:o.length>0&&(0,K.jsx)(e9.Toolbar,{children:(0,K.jsx)(T5,{series:o})})};return l?(0,K.jsx)(n9,{...d,children:(0,K.jsx)(r9,{error:l,onRetry:()=>{n.error&&n.refetch(),r.error&&r.refetch()}})}):(0,K.jsx)(n9,{...d,isUpdating:n.isPlaceholderData||r.isPlaceholderData,children:(0,K.jsx)(t9,{isEmpty:!u&&a.length===0,children:(0,K.jsx)(B6r,{lineStyle:`thin`,data:s,series:o,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:v5,axisFormatter:H3r,onBucketClick:t&&(e=>t({window:s9(Number(e.ts),c)})),isLoading:u,...h5})})})}var xxi={serviceName:`service`,requestId:`request ID`,experimentId:`experiment`};function Sxi({requiresRootSpanFields:e,children:t,...n}){let r=hxi({requiresRootSpanFields:e});return r.status===`unavailable`?null:r.status===`ready`?t(r.scope):(0,K.jsx)(n9,{...n,toolbar:null,children:r.status===`loading`?(0,K.jsx)(e9.Loading,{}):(0,K.jsx)(e9.NoData,{message:`Not available with a ${r.unsupportedFields.map(e=>xxi[e]??e).join(` or `)} filter.`})})}function Cxi(e){return(0,K.jsx)(Sxi,{title:vxi,children:t=>(0,K.jsx)(bxi,{scope:t,...e})})}function wxi(){return $7().scope}var Txi=[`entityName`,`environment`,`serviceName`,`threadId`,`resourceId`,`userId`,`organizationId`,`runId`,`sessionId`,`requestId`,`experimentId`],Exi=[`tags`,`provider`,`model`],Dxi=(e,t)=>({op:`eq`,left:{path:e},right:{literal:t}});function Oxi(e){let t=Exi.filter(t=>e[t]!==void 0);if(t.length)return{supported:!1,unsupportedFields:t};let n=[];e.rootEntityType&&n.push(Dxi(`entityType`,e.rootEntityType));for(let t of Txi){let r=e[t];r!==void 0&&n.push(Dxi(t,r))}return n.length===0?{supported:!0,where:void 0}:{supported:!0,where:n.length===1?n[0]:{op:`and`,args:n}}}function kxi(){let{data:e,isLoading:t}=i5(),{timestamp:n,dimensionalFilter:r}=c9();if(t)return{status:`loading`};if(e?.capabilities.spanAggregate!==!0)return{status:`unavailable`};let i=Oxi(r);return i.supported?{status:`ready`,scope:{timeRange:fxi(n),...i.where?{where:i.where}:{},interval:pxi(n),window:n}}:{status:`unsupported-filter`,unsupportedFields:i.unsupportedFields}}function Axi(e,{priority:t,enabled:n}={}){let r=Y();return RYr({request:e,enabled:n,queryOptions:{queryFn:jvi(()=>r.aggregateSpans(e),t),placeholderData:__,staleTime:1/0}})}var jxi=`Breakdown`,Mxi={projects:`Breakdown by project`,agents:`Breakdown by agent`,workflows:`Breakdown by workflow`,tools:`Breakdown by tool`,models:`Breakdown by model`,threads:`Breakdown by thread`,environments:`Breakdown by environment`};function Nxi({tab:e,tabs:t,onTabChange:n,isUpdating:r,children:i}){return(0,K.jsx)(n9,{title:Mxi[e],titleMenu:t.length>1?{value:e,onValueChange:n,options:t.map(e=>({value:e,label:Mxi[e]}))}:void 0,isUpdating:r,bodyHeight:`fit`,children:i})}var Pxi={agents:[`agent_run`],workflows:[`workflow_run`],tools:[`tool_call`,`mcp_tool_call`]},Fxi=e=>e in Pxi;function Ixi(e){let t=Pxi[e];return t.length===1?{op:`eq`,left:{path:`spanType`},right:{literal:t[0]??``}}:{op:`in`,value:{path:`spanType`},set:[...t]}}var Lxi=e=>e!==`workflows`&&e!==`tools`,Rxi=e=>e!==`models`,zxi=e=>e===`tools`||e===`models`;function d9(e,t){if(e===`projects`)return[`projectId`];let n=(...e)=>t?[`projectId`,...e]:e;return e===`environments`?n(`environment`):e===`threads`?n(`threadId`):e===`models`?n(`provider`,`model`):n(`entityName`)}var f9={trace:1e3,span:500};function Bxi({timeRange:e,where:t}){return{timeRange:e,...t?{where:t}:{},groupBy:[`projectId`],measures:[`count`,`errorRate`,`duration.p95`,`countDistinct.resourceId`,`countDistinct.threadId`],limit:f9.trace}}function Vxi({timeRange:e,where:t},n){return{timeRange:e,...t?{where:t}:{},groupBy:d9(`environments`,n),measures:[`count`,`errorRate`,`duration.p95`],limit:f9.trace}}function Hxi(e){let t={op:`exists`,path:`threadId`};return e?{op:`and`,args:[t,e]}:t}function Uxi({timeRange:e,where:t},n){return{timeRange:e,where:Hxi(t),groupBy:n?[`projectId`,`threadId`]:[`resourceId`,`threadId`],measures:[`count`,`errorRate`,`duration.p95`],limit:f9.trace}}function Wxi(e,t,n){return e===`projects`?Bxi(t):e===`environments`?Vxi(t,n):Uxi(t,n)}function Gxi({timeRange:e,where:t}){return{timeRange:e,where:Hxi(t),groupBy:[`resourceId`,`threadId`],measures:[`count`],limit:f9.trace}}function Kxi(e){let t=new Map;for(let n of e){let e=Yxi(n,`resourceId`);e&&t.set(Yxi(n,`threadId`),e)}return t}var qxi=e=>e===`agents`||e===`workflows`?`countDistinct.traceId`:`count`;function Jxi(e,{timeRange:t,where:n},r){let i=Ixi(e);return{timeRange:t,where:n?{op:`and`,args:[i,n]}:i,groupBy:d9(e,r),measures:[`count`,...qxi(e)===`count`?[]:[`countDistinct.traceId`],`errorCount`,`errorRate`,`duration.p95`],limit:f9.span}}var p9=(e,t)=>{let n=e.measures[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0},Yxi=(e,t)=>{let n=e.dimensions?.[t];return n==null?``:String(n)},Xxi=(e,t)=>t.map(t=>e.dimensions[t]==null?``:String(e.dimensions[t])).join(`|`);function Zxi({tab:e,groupBy:t,aggregateRows:n=[],usageGroups:r,spanGroups:i=[],resources:a}){let o=new Map,s=t.indexOf(`projectId`),c=t.indexOf(`provider`),l=e=>{let t=o.get(e);if(!t){let n=e.split(`|`);t={key:e,...s>=0?{projectId:n[s]??``}:{},...c>=0?{provider:n[c]??``}:{},name:n[n.length-1]??``,count:0,...r?{tokens:0}:{}},o.set(e,t)}return t},u=qxi(e);for(let e of n){let n=l(t.map(t=>Yxi(e,t)).join(`|`));n.count=p9(e,u)??0,n.errorRate=p9(e,`errorRate`),n.p95=p9(e,`duration.p95`),n.resources=p9(e,`countDistinct.resourceId`),n.threads=p9(e,`countDistinct.threadId`)}for(let e of i)l(Xxi(e,t)).count=e.value;for(let e of r??[]){let n=l(Xxi(e,t));n.tokens=e.value,n.cost=e.estimatedCost??void 0,n.costUnit=n.cost===void 0?void 0:e.costUnit??void 0}if(a)for(let e of o.values()){let t=a.get(e.name);t&&(e.resource=t)}return[...o.values()]}function Qxi({tab:e,groupBy:t,aggregateRows:n=[],usageGroups:r=[],spanGroups:i=[]}){let a=new Map,o=e=>{let t=a.get(e);return t||a.set(e,t={}),t},s=qxi(e);for(let e of n){let n=o(t.map(t=>Yxi(e,t)).join(`|`));n.count=p9(e,s)??0,n.errorRate=p9(e,`errorRate`),n.p95=p9(e,`duration.p95`)}for(let e of i)o(Xxi(e,t)).count=e.value;for(let e of r){let n=o(Xxi(e,t));n.tokens=e.value,n.cost=e.estimatedCost??void 0}return a}function $xi(e,t,n,r){let i=new Set(e.map(e=>e.key)),a=n.indexOf(`projectId`),o=n.indexOf(`provider`),s=[];for(let[e,n]of t){if(i.has(e)||!((n.count??0)>0||(n.tokens??0)>0))continue;let t=e.split(`|`);s.push({key:e,...a>=0?{projectId:t[a]??``}:{},...o>=0?{provider:t[o]??``}:{},name:t[t.length-1]??``,count:0,...r?{tokens:0}:{},...r&&n.cost!==void 0?{cost:0}:{}})}return[...e,...s]}function eSi(e,t,n){let r=e[n];if(r===void 0)return{isNew:!1};let i=t?.[n];if(i===void 0)return{isNew:n===`count`||n===`tokens`||n===`cost`?r>0:!1};let a=r-i;return{delta:a,change:tSi(n,a,i),isNew:!1}}function tSi(e,t,n){return e===`errorRate`?t:n>0?t/n:void 0}function nSi(e,t){if(e.delta!==void 0&&e.delta!==0)return e.delta>0==(t===`count`)?`good`:`bad`}var rSi=[`mastra_model_total_input_tokens`,`mastra_model_total_output_tokens`];function m9({groupBy:e,filters:t,window:n,measure:r=`tokens`,enabled:i=!0}){let a=Y(),{filters:o,filterKey:s}=c9();return T_({queryKey:[`metrics`,`cost-breakdown`,r,e,t,s,n.start.toISOString(),n.end.toISOString()],staleTime:1/0,enabled:i,queryFn:()=>a.getMetricBreakdown({name:r===`tokens`?rSi:[`mastra_model_total_input_tokens`],groupBy:e,aggregation:r===`tokens`?`sum`:`count`,orderDirection:`DESC`,limit:1e3,filters:{...o,...t,timestamp:n}})})}function iSi({start:e,end:t}){return{start:new Date(2*e.getTime()-t.getTime()),end:new Date(e.getTime())}}var aSi=[`count`,`errorRate`,`p95`,`tokens`,`cost`],oSi=e=>aSi.includes(e),sSi=e=>zxi(e)?`Spans`:`Traces`,cSi=`A trace is one end-to-end request, with every step it took.`,lSi=`A span is one step inside a trace, such as a tool call or a model call. One trace can have many.`,uSi=e=>zxi(e)?lSi:cSi,dSi={errorRate:`Errors`,p95:`P95 latency`,tokens:`Tokens`,cost:`Cost`},fSi=e=>e.toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`}),pSi=({start:e,end:t})=>`${fSi(e)} – ${fSi(t)}`;function mSi(e,t){return{summary:`Change in ${t.toLowerCase()} from the previous range of the same length. Sort by another column to compare that instead.`,current:`Selected: ${pSi(e)}`,previous:`Previous: ${pSi(iSi(e))}`}}var hSi=(e,t)=>t&&e!==`projects`,gSi=(e,t)=>t===`count`?sSi(e):dSi[t];function _Si({tab:e,built:t,previous:n,truncated:r,groupBy:i,usage:a}){return e===`threads`?t.filter(e=>e.name!==``):!n||r?t:$xi(t,n,i,a)}function vSi(e,t,n){return e===`projects`?n?.(t.key)??t.key:t.name?t.name:e===`environments`?`No environment`:e===`models`?`Unknown model`:`Unnamed`}var ySi=(e,t)=>e===`projects`?t.key:t.projectId;function bSi(e,t){let n=ySi(e,t),r=n?{projectId:n}:{};return Fxi(e)?{...r,span:{spanTypes:Pxi[e],entityName:t.name}}:e===`environments`?t.name?{...r,environment:t.name}:r:e===`threads`?{...r,threadId:t.name}:e===`models`&&t.name?{...r,model:t.name}:r}function xSi(e,t){return t&&t.toUpperCase()!==`USD`?`${v5(e)} ${t}`:b5(e)}function SSi(e,t){if(e.isNew)return`New`;if(e.change===void 0)return`—`;if(e.change===0)return t===`errorRate`?`0 pt`:`0%`;let n=e.change>0?`+`:`−`,r=Math.abs(e.change);return t===`errorRate`?r<5e-4?`${n}<0.1 pt`:`${n}${(r*100).toFixed(1)} pt`:`${n}${y5(r)}`}function CSi(e){let t=iSi(e.window);return{...e,window:t,timeRange:fxi(t)}}var wSi={good:`text-badge-green-foreground`,bad:`text-badge-red-foreground`};function TSi({trend:e,children:t}){return t===void 0?(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`—`}):(0,K.jsx)(`span`,{className:e?wSi[e]:`text-muted-foreground`,children:t})}function ESi({change:e,metric:t}){return e?(0,K.jsx)(TSi,{trend:nSi(e,t),children:SSi(e,t)}):(0,K.jsx)(TSi,{trend:void 0})}function DSi({window:e,label:t}){let{summary:n,current:r,previous:i}=mSi(e,t);return(0,K.jsxs)(`span`,{className:`grid gap-1`,children:[(0,K.jsx)(`span`,{children:n}),(0,K.jsx)(`span`,{className:`tabular-nums`,children:r}),(0,K.jsx)(`span`,{className:`tabular-nums`,children:i})]})}function OSi(){return(0,K.jsx)(`span`,{title:`No price for this model`,children:`Not priced`})}function kSi({row:e}){return e.cost===void 0?e.tokens?(0,K.jsx)(OSi,{}):`—`:xSi(e.cost,e.costUnit)}function h9({muted:e=!1,children:t}){return(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:e?`muted`:void 0,className:`tabular-nums`,children:t})}function ASi({mark:e,title:t,model:n}){return(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[e,(0,K.jsx)(`span`,{className:`truncate`,title:t,children:n?(0,K.jsx)(xni,{parts:QOn(n.name,n.provider)}):t})]})}var jSi=e=>(0,K.jsxs)(`svg`,{width:`19.125`,height:`18`,viewBox:`-1.0625 -1 19.125 18`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,...e,children:[(0,K.jsx)(`path`,{d:`M4.31445 3.16083C3.78402 3.16083 3.27531 3.37154 2.90024 3.74661C2.52517 4.12169 2.31445 4.63039 2.31445 5.16083V5.66083C2.31445 6.19126 2.52517 6.69997 2.90024 7.07504C3.27531 7.45011 3.78402 7.66083 4.31445 7.66083C4.84489 7.66083 5.35359 7.45011 5.72867 7.07504C6.10374 6.69997 6.31445 6.19126 6.31445 5.66083V5.16083C6.31445 4.63039 6.10374 4.12169 5.72867 3.74661C5.35359 3.37154 4.84489 3.16083 4.31445 3.16083Z`,fill:`currentColor`}),(0,K.jsx)(`path`,{d:`M6.76666 9.50235C6.57678 9.28532 6.30244 9.16083 6.01407 9.16083H4.50201C4.10791 9.16078 3.71766 9.23838 3.35356 9.38921C3.11733 9.48706 2.8951 9.6145 2.69205 9.76806C2.48056 9.928 2.38001 10.1888 2.38001 10.454V13.0642C2.38001 13.6165 2.82773 14.0642 3.38001 14.0642H8.55436C9.4135 14.0642 9.87269 13.0523 9.30695 12.4057L6.76666 9.50235Z`,fill:`currentColor`}),(0,K.jsx)(`path`,{fillRule:`evenodd`,clipRule:`evenodd`,d:`M12.0686 2.26107C12.0686 2.17635 11.9999 2.10767 11.9152 2.10767H10.9948C10.91 2.10767 10.8414 2.17635 10.8414 2.26107V3.85184C10.8414 3.95606 10.7397 4.02994 10.6406 3.99773L9.12775 3.50619C9.04718 3.48001 8.96063 3.52411 8.93445 3.60468L8.65003 4.48004C8.62385 4.56062 8.66795 4.64716 8.74852 4.67334L10.2611 5.1648C10.3602 5.19701 10.399 5.31655 10.3378 5.40086L9.40289 6.68765C9.35309 6.75619 9.36829 6.85212 9.43683 6.90192L10.1815 7.44292C10.25 7.49272 10.3459 7.47752 10.3957 7.40898L11.3309 6.12181C11.3922 6.03749 11.5179 6.03749 11.5791 6.12181L12.5143 7.40904C12.5641 7.47758 12.6601 7.49278 12.7286 7.44298L13.4732 6.90198C13.5418 6.85218 13.557 6.75625 13.5072 6.68771L12.5723 5.40091C12.511 5.3166 12.5499 5.19705 12.649 5.16485L14.1615 4.67338C14.2421 4.6472 14.2862 4.56066 14.26 4.48009L13.9756 3.60473C13.9494 3.52415 13.8629 3.48006 13.7823 3.50624L12.2694 3.99782C12.1703 4.03003 12.0686 3.95615 12.0686 3.85193V2.26107Z`,fill:`currentColor`})]}),MSi={agent:HN,workflow:ZS,tool:XN},NSi={agents:`agent`,workflows:`workflow`,tools:`tool`};function PSi({entity:e}){let t=MSi[e];return(0,K.jsx)(ekn,{icon:(0,K.jsx)(t,{className:`size-3`})})}function FSi({provider:e}){return e?(0,K.jsx)(tkn,{provider:e}):(0,K.jsx)(ekn,{icon:(0,K.jsx)(jSi,{className:`size-icon-xs`})})}function ISi({tab:e,row:t}){let n=NSi[e];return n?(0,K.jsx)(PSi,{entity:n}):e===`models`?(0,K.jsx)(FSi,{provider:t.provider}):null}function LSi({tab:e,row:t}){let{projectLabel:n}=wxi();return(0,K.jsx)(ASi,{mark:(0,K.jsx)(ISi,{tab:e,row:t}),title:vSi(e,t,n),model:e===`models`&&t.name!==``?{name:t.name,provider:t.provider}:void 0})}function RSi({text:e}){return(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`muted`,className:`truncate`,title:e,children:e})}var zSi={asc:cH,desc:sH},BSi=`focus-visible:outline-1 focus-visible:outline-solid focus-visible:outline-border-focus focus-visible:-outline-offset-1`,VSi=`cursor-help underline decoration-dotted decoration-placeholder/45 underline-offset-4 transition-[text-decoration-color] duration-150 group-hover/header:decoration-placeholder group-focus-visible/header:decoration-placeholder`;function HSi({header:e,explained:t,sorted:n,className:r,...i}){let a=n&&zSi[n];return(0,K.jsxs)(`button`,{type:`button`,...i,className:c(`group/header flex items-center gap-1 rounded whitespace-nowrap hover:text-muted-foreground`,BSi,r),children:[(0,K.jsx)(`span`,{className:c(t&&VSi),children:e}),a&&(0,K.jsx)(a,{"aria-hidden":!0,className:`size-3`})]})}function USi({header:e,explained:t,className:n,...r}){return(0,K.jsx)(`span`,{tabIndex:t?0:void 0,...r,className:c(`group/header rounded whitespace-nowrap`,BSi,n),children:(0,K.jsx)(`span`,{className:c(t&&VSi),children:e})})}function WSi({header:e,description:t,sorted:n,onSort:r}){let i=(0,G.useId)(),a=!!t,o=a?i:void 0,s=r?(0,K.jsx)(HSi,{header:e,explained:a,sorted:n,onClick:r,"aria-describedby":o}):(0,K.jsx)(USi,{header:e,explained:a,"aria-describedby":o});return a?(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{render:s}),(0,K.jsx)(Tx,{id:i,keepMounted:!0,side:`top`,className:`max-w-72`,children:t})]}):s}var GSi=`isolate before:absolute before:inset-x-0 before:-top-px before:bottom-0 before:-z-10 before:rounded hover:before:bg-fill-subtle after:absolute after:inset-x-0 after:bottom-0 after:h-px after:bg-border last:after:hidden after:[mask-image:linear-gradient(to_right,transparent,black_6px,black_calc(100%-6px),transparent)] hover:after:[mask-image:linear-gradient(to_right,transparent,black_24px,black_calc(100%-24px),transparent)] [&:has(+:hover)]:after:[mask-image:linear-gradient(to_right,transparent,black_24px,black_calc(100%-24px),transparent)]`,KSi=`pt-1.75 pb-2 text-body-sm`,qSi=c(`relative col-span-full grid grid-cols-subgrid items-center px-3`,KSi,GSi),JSi=[`w-32`,`w-24`,`w-36`,`w-20`,`w-28`],YSi=`a, button, input, select, textarea, label, [role="button"], [role="link"], [contenteditable]`;function XSi(e){if(!(e.target instanceof Element))return!1;let t=e.target.closest(YSi);return!!(t&&e.currentTarget.contains(t))}function ZSi(e,t,n){return e.align===`end`?`right-0 w-10`:t>0?`left-0 w-16`:c(`left-0`,JSi[n%JSi.length])}function QSi({columns:e,rows:t,getRowKey:n,empty:r,pageSize:i,isLoading:a,...o}){return a?Array.from({length:i??5},(t,n)=>(0,K.jsx)(eCi,{columns:e,rowIndex:n},n)):t.length===0?i?r===void 0?(0,K.jsx)($Si,{count:i}):(0,K.jsxs)(`div`,{role:`row`,className:`col-span-full grid *:col-start-1 *:row-start-1`,children:[(0,K.jsx)($Si,{count:i}),(0,K.jsx)(`p`,{role:`cell`,className:`flex items-center justify-center px-3 py-4 text-center text-body-sm text-muted-foreground`,children:r})]}):r===void 0?null:(0,K.jsx)(`div`,{role:`row`,className:`col-span-full`,children:(0,K.jsx)(`p`,{role:`cell`,className:`py-8 text-center text-body-sm text-muted-foreground`,children:r})}):t.map(t=>(0,K.jsx)(tCi,{row:t,columns:e,...o},n(t)))}function $Si({count:e}){return e<=0?null:(0,K.jsx)(`div`,{"aria-hidden":!0,"data-slot":`metrics-table-filler`,className:`col-span-full`,children:Array.from({length:e},(e,t)=>(0,K.jsx)(`div`,{className:KSi,children:``},t))})}function eCi({columns:e,rowIndex:t}){return(0,K.jsx)(`div`,{role:`row`,"aria-busy":!0,className:qSi,children:e.map((e,n)=>(0,K.jsxs)(`div`,{role:`cell`,className:c(`relative flex min-w-0`,e.align===`end`&&`justify-end`),children:[``,(0,K.jsx)(zS,{className:c(`absolute top-1/2 h-3.5 -translate-y-1/2`,ZSi(e,n,t))})]},e.id))})}function tCi({row:e,columns:t,onRowClick:n,onRowHover:r,isRowDimmed:i,isRowActive:a,rowTitle:o}){let s=a?.(e)??!1,l=i?.(e)??!1;return(0,K.jsx)(`div`,{role:`row`,"aria-current":s||void 0,tabIndex:n?0:void 0,title:o?.(e),onClick:n?t=>{XSi(t)||n?.(e)}:void 0,onKeyDown:n?t=>{t.target===t.currentTarget&&(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),n?.(e))}:void 0,onMouseEnter:r?()=>r(e):void 0,onMouseLeave:r?()=>r(void 0):void 0,className:c(qSi,`rounded text-foreground transition-opacity duration-150`,n&&c(`cursor-pointer`,`focus-visible:outline-1 focus-visible:outline-solid focus-visible:outline-border-focus focus-visible:-outline-offset-1`),s&&`before:bg-fill-subtle`,l&&`opacity-40`),children:t.map(t=>(0,K.jsx)(`div`,{role:`cell`,className:c(`flex min-w-0 items-center`,t.align===`end`&&`justify-end text-right`),children:t.cell(e)},t.id))})}var nCi=`after:absolute after:inset-x-0 after:bottom-0 after:h-px after:bg-border after:[mask-image:linear-gradient(to_right,transparent,black_6px,black_calc(100%-6px),transparent)] [&:has(+:hover)]:after:[mask-image:linear-gradient(to_right,transparent,black_24px,black_calc(100%-24px),transparent)]`,rCi={asc:`ascending`,desc:`descending`};function iCi(e,t){let n=t.firstDirection??`desc`;if(e?.column!==t.id)return{column:t.id,direction:n};if(e.direction===n)return{column:t.id,direction:n===`desc`?`asc`:`desc`}}function aCi(e,t){return typeof e==`number`&&typeof t==`number`?e-t:String(e).localeCompare(String(t))}function oCi(e,t,n){let r=t.find(e=>e.id===n?.column)?.sortValue;if(!n||!r)return e;let i=n.direction===`desc`?-1:1;return e.toSorted((e,t)=>{let n=r(e),a=r(t);return n===void 0&&a===void 0?0:n===void 0?1:a===void 0?-1:i*aCi(n,a)})}var sCi=e=>e.width??(e.align===`end`?`minmax(max-content,1fr)`:`max-content`);function cCi({columns:e,rows:t,getRowKey:n,sort:r,defaultSort:i,onSortChange:a,onRowClick:o,onRowHover:s,isRowDimmed:l,isRowActive:u,rowTitle:d,empty:f,pageSize:p,isLoading:m=!1,"aria-label":h,className:g}){let[_,v]=(0,G.useState)(i),[y,b]=(0,G.useState)(0),x=r??_,S=oCi(t,e,x),C=p?Math.ceil(S.length/p):1,w=Math.min(y,Math.max(0,C-1)),T=p?S.slice(w*p,(w+1)*p):S,E={gridTemplateColumns:e.map(sCi).join(` `)},D=!m&&C>1,O=e=>{let t=iCi(x,e)??i;v(t),b(0),a?.(t)};return(0,K.jsxs)(`div`,{className:c(`grid min-w-0 gap-3`,g),children:[(0,K.jsxs)(LS,{orientation:`horizontal`,children:[(0,K.jsxs)(`div`,{role:`table`,"aria-label":h,className:`grid min-w-min gap-x-4`,style:E,children:[(0,K.jsx)(`div`,{role:`row`,className:c(`relative col-span-full grid grid-cols-subgrid items-end px-3 pb-1.5 text-label text-placeholder`,nCi),children:e.map(e=>{let t=x?.column===e.id?x.direction:void 0;return(0,K.jsx)(`div`,{role:`columnheader`,"aria-sort":t&&rCi[t],className:c(`flex min-w-0 items-center gap-1`,e.align===`end`&&`justify-end text-right`),children:(0,K.jsx)(WSi,{header:e.header,description:e.description,sorted:t,onSort:e.sortValue?()=>O(e):void 0})},e.id)})}),(0,K.jsx)(QSi,{columns:e,rows:T,getRowKey:n,onRowClick:o,onRowHover:s,isRowDimmed:l,isRowActive:u,rowTitle:d,empty:f,pageSize:p,isLoading:m})]}),p!==void 0&&!m&&T.length>0&&(0,K.jsx)($Si,{count:p-T.length})]}),D&&(0,K.jsx)(yci,{page:w,pageCount:C,onPageChange:b})]})}var lCi=10,uCi={column:`count`,direction:`desc`},dCi={projects:`Project`,agents:`Agent`,workflows:`Workflow`,tools:`Tool`,models:`Model`,threads:`Thread`,environments:`Environment`},fCi={projects:`No traces in this range.`,agents:`No agent runs in this range.`,workflows:`No workflow runs in this range.`,tools:`No tool calls in this range.`,models:`No model usage in this range.`,threads:`No traces with a thread in this range.`,environments:`No traces in this range.`};function pCi({tab:e,groupBy:t,window:n,aggregate:r,totals:i,spans:a,resources:o,previousAggregate:s,previousUsage:c,previousSpans:l,limit:u,...d}){let f=wxi(),[p,m]=(0,G.useState)(uCi),[h,g]=(0,G.useState)(`count`),_=(e=uCi)=>{m(e),oSi(e.column)&&g(e.column)},v=[r,i,a].filter(e=>e!==void 0);if(v.some(e=>e.isError))return(0,K.jsx)(Nxi,{...d,tab:e,children:(0,K.jsx)(r9,{onRetry:()=>v.forEach(e=>e.isError&&void e.refetch())})});let y=v.some(e=>e.isLoading),b=Rxi(e),x=i!==void 0,S=hSi(e,d.byProject),C=r?.data?.truncated===!0,w=y?[]:Zxi({tab:e,groupBy:t,aggregateRows:r?.data?.rows,usageGroups:i?.data?.groups,spanGroups:a?.data?.groups,resources:o?.data?Kxi(o.data.rows):void 0}),E=[s,c,l].every(e=>!e||!e.isLoading&&!e.isError)&&!y?Qxi({tab:e,groupBy:t,aggregateRows:s?.data?.rows,usageGroups:c?.data?.groups,spanGroups:l?.data?.groups}):void 0,D=_Si({tab:e,built:w,previous:E,truncated:C,groupBy:t,usage:x}),O=sSi(e),k=e=>E?eSi(e,E.get(e.key),h):void 0,A=e=>e.projectId?f.projectLabel?.(e.projectId)??e.projectId:`—`,j={id:`name`,header:dCi[e],width:`minmax(12rem,3fr)`,cell:t=>(0,K.jsx)(LSi,{tab:e,row:t})},M={id:`project`,header:`Project`,width:`minmax(8rem,2fr)`,cell:e=>(0,K.jsx)(RSi,{text:A(e)})},N={id:`resource`,header:`Resource`,width:`minmax(6rem,1fr)`,cell:e=>(0,K.jsx)(RSi,{text:e.resource??`—`})},P=[{id:`errorRate`,header:`Errors`,align:`end`,sortValue:e=>e.errorRate,cell:e=>(0,K.jsx)(h9,{muted:!0,children:e.errorRate===void 0?`—`:y5(e.errorRate)})},{id:`p95`,header:`P95 latency`,align:`end`,sortValue:e=>e.p95,cell:e=>(0,K.jsx)(h9,{muted:!0,children:e.p95===void 0?`—`:V3r(e.p95)})}],F=[{id:`tokens`,header:`Tokens`,align:`end`,sortValue:e=>e.tokens,cell:e=>(0,K.jsx)(h9,{muted:!0,children:e.tokens===void 0?`—`:v5(e.tokens)})},{id:`cost`,header:`Cost`,align:`end`,sortValue:e=>e.cost,cell:e=>(0,K.jsx)(h9,{muted:!0,children:(0,K.jsx)(kSi,{row:e})})}],I={id:`count`,header:O,align:`end`,description:uSi(e),sortValue:e=>e.count,cell:e=>(0,K.jsx)(h9,{children:v5(e.count)})},L={id:`change`,header:`% Change`,align:`end`,description:(0,K.jsx)(DSi,{window:n,label:gSi(e,h)}),sortValue:e=>k(e)?.change,cell:e=>(0,K.jsx)(h9,{children:(0,K.jsx)(ESi,{change:k(e),metric:h})})},R=[j,...S?[M]:[],...e===`threads`?[N]:[],...b?P:[],...x?F:[],I,L];return(0,K.jsx)(Nxi,{...d,tab:e,isUpdating:r?.isPlaceholderData,children:(0,K.jsxs)(t9,{children:[(0,K.jsx)(cCi,{"aria-label":`${dCi[e]} breakdown`,columns:R,rows:D,getRowKey:e=>e.key,sort:p,defaultSort:uCi,onSortChange:_,onRowClick:d.onRowClick&&(t=>d.onRowClick?.(bSi(e,t))),pageSize:lCi,isLoading:y,empty:fCi[e]},e),!y&&C&&(0,K.jsxs)(T,{variant:`caption`,tone:`muted`,className:`pt-2`,children:[`Showing the `,v5(u),` busiest; sorting covers only these.`]})]})})}var mCi={entityType:`agent`};function hCi({tab:e,scope:t,...n}){let r=d9(e,n.byProject),i=Lxi(e),a=CSi(t),o=Axi(Jxi(e,t,n.byProject)),s=Axi(Jxi(e,a,n.byProject),{priority:Evi.last}),c=m9({groupBy:r,filters:mCi,window:t.window,enabled:i}),l=m9({groupBy:r,filters:mCi,window:a.window,enabled:i});return(0,K.jsx)(pCi,{...n,tab:e,groupBy:r,window:t.window,aggregate:o,totals:i?c:void 0,previousAggregate:s,previousUsage:i?l:void 0,limit:f9.span})}function gCi(e){let t=d9(`models`,e.byProject),{timestamp:n}=c9(),r=iSi(n),i=m9({groupBy:t,window:n}),a=m9({groupBy:t,window:n,measure:`modelSpans`}),o=m9({groupBy:t,window:r}),s=m9({groupBy:t,window:r,measure:`modelSpans`});return(0,K.jsx)(pCi,{...e,tab:`models`,groupBy:t,window:n,totals:i,spans:a,previousUsage:o,previousSpans:s,limit:f9.trace})}function _Ci({tab:e,scope:t,...n}){let r=d9(e,n.byProject),i=CSi(t),a=u9(Wxi(e,t,n.byProject)),o=u9(Wxi(e,i,n.byProject),{priority:Evi.last}),s=u9(Gxi(t),{enabled:e===`threads`&&n.byProject}),c=m9({groupBy:r,window:t.window}),l=n.byProject?s:a,u=m9({groupBy:r,window:i.window});return(0,K.jsx)(pCi,{...n,tab:e,groupBy:r,window:t.window,aggregate:a,totals:c,resources:e===`threads`?l:void 0,previousAggregate:o,previousUsage:u,limit:f9.trace})}var vCi={serviceName:`service`,requestId:`request ID`,experimentId:`experiment`,tags:`tags`,provider:`provider`,model:`model`};function yCi({tab:e,traceGate:t,spanGate:n,...r}){if(e===`models`)return(0,K.jsx)(gCi,{...r},e);let i=Fxi(e)?n:t;return i.status===`unsupported-filter`?(0,K.jsx)(Nxi,{...r,tab:e,children:(0,K.jsx)(e9.NoData,{message:`Not available with a ${i.unsupportedFields.map(e=>vCi[e]??e).join(` or `)} filter.`})}):Fxi(e)?n.status===`ready`&&(0,K.jsx)(hCi,{...r,tab:e,scope:n.scope},e):t.status===`ready`&&(0,K.jsx)(_Ci,{...r,tab:e,scope:t.scope},e)}function bCi({chosen:e,traceScope:t,spanGate:n,...r}){let i=u9(Bxi(t)).data?.rows.filter(e=>(e.measures.count??0)>0).length,a=e??xCi(i);return(0,K.jsx)(yCi,{...r,tab:a,traceGate:{status:`ready`,scope:t},spanGate:n})}function xCi(e){return e===void 0||e>=2?`projects`:`agents`}var SCi=[`projects`,`agents`,`workflows`,`tools`,`models`,`threads`,`environments`],CCi=SCi.filter(e=>e!==`projects`);function wCi({onRowClick:e}){let t=wxi().projectLabel!==void 0,n=hxi(),r=kxi(),[i,a]=(0,G.useState)();if(n.status===`unavailable`||r.status===`unavailable`)return null;if(n.status===`loading`||r.status===`loading`)return(0,K.jsx)(n9,{title:jxi,bodyHeight:`fit`,children:(0,K.jsx)(e9.Loading,{})});let o={tabs:t?SCi:CCi,onTabChange:a,onRowClick:e,byProject:t};return t&&n.status===`ready`?(0,K.jsx)(bCi,{...o,chosen:i,traceScope:n.scope,spanGate:r}):(0,K.jsx)(yCi,{...o,tab:i??`agents`,traceGate:n,spanGate:r})}function TCi({experiment:e,metrics:t}){let{data:n}=jN({experimentId:e.id,experimentStatus:e.status,queryOptions:{enabled:!!e.id}}),{data:r,isLoading:i}=lmi({experiments:(0,G.useMemo)(()=>[{id:e.id,status:e.status}],[e.id,e.status]),supportsMetrics:t?.isEnabled??!1}),a=e.status===`running`||e.status===`pending`||i,o=(0,G.useMemo)(()=>{if(!n)return;let e=Object.values(n).flat();return e.length===0?null:e.reduce((e,t)=>e+t.score,0)/e.length},[n]),s=e.startedAt??e.createdAt,c=!e.startedAt||!e.completedAt?`—`:iC(new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime())??`—`,l=r[e.id]?.summary,u=H7(l),d=l?.inputTokens===void 0&&l?.outputTokens===void 0?`input + output`:(0,K.jsxs)(AC,{singleLine:!0,children:[(0,K.jsxs)(AC.Item,{children:[V7(l.inputTokens??0),` in`]}),(0,K.jsxs)(AC.Item,{children:[V7(l.outputTokens??0),` out`]})]}),f=t?.isEnabled?t.data?.avgAgentDurationMs:void 0,p=f==null?void 0:iC(Math.round(f)),m=p?`${p} avg per item`:s?`started ${bC(new Date(s),`date-time`)}`:`not started`;return(0,K.jsxs)(tvi,{children:[t?.isEnabled&&(0,K.jsx)(Eyi,{label:`Total cost`,icon:zgi,value:l?.estimatedCost===void 0?`—`:B7(l.estimatedCost,l.costUnit),detail:`estimated`,isLoading:a}),(0,K.jsx)(Eyi,{label:`Run duration`,icon:XS,value:c,detail:m}),t?.isEnabled&&(0,K.jsx)(Eyi,{label:`Total tokens`,icon:Z4,value:u===void 0?`—`:V7(u),detail:d,isLoading:a}),(0,K.jsx)(Eyi,{label:`Avg score`,icon:G4,value:o==null?`—`:o.toFixed(3),detail:o==null?`no scores`:`across all scorers`,isLoading:o===void 0})]})}function ECi({selection:e}){let{selectedIds:t,selectedResults:n,tagVocabulary:r,isFlagging:i,isTagging:a}=e,o=i||a,s=t.size===0;return(0,K.jsxs)(`div`,{className:`flex min-h-8 items-center gap-2 whitespace-nowrap`,children:[(0,K.jsxs)(X,{variant:`ghost`,size:`sm`,disabled:s,iconEnd:s?void 0:(0,K.jsx)(xw,{}),onClick:e.clearSelection,tooltip:s?void 0:`Clear selection`,className:`tabular-nums`,children:[t.size,` selected`]}),!s&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(X,{size:`sm`,disabled:o,onClick:e.flagSelectedForReview,icon:(0,K.jsx)(UN,{}),children:`Request review`}),(0,K.jsx)(z_i,{selectedResults:n,vocabulary:r,onAddTag:e.addTagToSelected,disabled:o})]})]})}var DCi=e=>Math.floor(Math.random()*e);function OCi({messages:e,intervalMs:t=3e3}){let n=e.length,[r,i]=(0,G.useState)(()=>DCi(n));return(0,G.useEffect)(()=>{if(n<2)return;let e=setInterval(()=>i(e=>(e+1+DCi(n-1))%n),t);return()=>clearInterval(e)},[n,t]),n===0?null:(0,K.jsx)(K.Fragment,{children:e[r%n]})}function kCi(e=1e3){let[t,n]=(0,G.useState)(()=>Date.now());return(0,G.useEffect)(()=>{let t=setInterval(()=>n(Date.now()),e);return()=>clearInterval(t)},[e]),t}var ACi=[`Calling your target…`,`Working through the dataset items…`,`Feeding inputs to your agent…`,`Waiting on model responses…`,`Consulting the scorers…`,`Comparing outputs to ground truth…`,`Grading the answers…`,`Checking tool calls…`,`Following the agent’s trajectory…`,`Counting tokens…`,`Estimating the cost…`,`Timing each run…`,`Looking for hallucinations…`,`Weighing relevance…`,`Judging faithfulness…`,`Asking the LLM judge…`,`Recording traces…`,`Collecting scores…`,`Spotting regressions…`,`Tallying the results…`],jCi=`Waiting to start…`;function MCi({experiment:e}){let{status:t,totalItems:n,succeededCount:r,failedCount:i,startedAt:a}=e,o=kCi(),s=r+i,c=n===1?`item`:`items`,l=t===`pending`,u=a?Math.floor((o-new Date(a).getTime())/1e3)*1e3:void 0,d=!l&&u!==void 0?iC(u):void 0;return(0,K.jsx)(Jx,{variant:`fill`,as:`h2`,iconSlot:(0,K.jsx)(It,{}),titleSlot:l?`Experiment queued`:`Experiment in progress`,descriptionSlot:(0,K.jsxs)(`span`,{className:`flex flex-col items-center gap-1`,children:[(0,K.jsx)(`span`,{children:l?jCi:(0,K.jsx)(OCi,{messages:ACi})}),(0,K.jsxs)(AC,{className:`justify-center tabular-nums`,children:[(0,K.jsxs)(AC.Item,{children:[s,` / `,n,` `,c,` finished`]}),d&&(0,K.jsxs)(AC.Item,{children:[d,` elapsed`]})]})]})})}var NCi={pending:{icon:(0,K.jsx)(tC,{className:`size-icon-md text-warning-foreground`}),label:K7.pending},running:{icon:(0,K.jsx)(It,{size:`sm`}),label:K7.running},completed:{icon:(0,K.jsx)(EX,{className:`size-icon-md text-muted-foreground`}),label:K7.completed},failed:{icon:(0,K.jsx)(qx,{className:`size-icon-md text-destructive-foreground`}),label:K7.failed}};function PCi({status:e,className:t}){let n=NCi[e]??NCi.pending;return(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{render:(0,K.jsx)(`span`,{tabIndex:0,className:c(`flex shrink-0 items-center`,t),children:n.icon})}),(0,K.jsx)(Tx,{children:n.label})]})}var FCi=()=>{let{experimentId:e}=kv(),{data:t}=RAt({experimentId:e??``,queryOptions:{enabled:!!e,retryOnMount:!1}});return{experimentId:e,experiment:t}},ICi=()=>{let{experimentId:e,experiment:t}=FCi(),n=t?.datasetId??``,{data:r}=OAt({datasetId:n,experimentId:e??``,queryOptions:{enabled:!!(n&&e),retryOnMount:!1}});return r??t};function LCi(){let{experimentId:e,experiment:t}=FCi();if(!e)return null;let n=e.length>8?`${e.slice(0,8)}...`:e;return t?.name||n}function RCi(){let e=ICi();return e?.status?(0,K.jsx)(PCi,{status:e.status}):null}function zCi(){let e=ICi();if(!e||e.status===`running`||e.status===`pending`)return null;let{totalItems:t,failedCount:n}=e,r=`${t} ${t===1?`item`:`items`}`;return(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`tabular-nums`,children:(0,K.jsxs)(AC,{children:[(0,K.jsx)(AC.Item,{children:r}),n>0&&(0,K.jsxs)(AC.Item,{children:[n,` errored`]})]})})}function BCi({datasetId:e,experimentId:t}){let[n,r]=(0,G.useState)(!1),{updateExperimentResult:i}=ON();return{addTag:(0,G.useCallback)(async(a,o)=>{let s=o.filter(e=>!(e.tags??[]).includes(a));if(n||s.length===0)return;r(!0);let c=0;try{c=(await Promise.allSettled(s.map(n=>i.mutateAsync({datasetId:e,experimentId:t,resultId:n.id,tags:[...n.tags??[],a]})))).filter(e=>e.status===`fulfilled`).length}finally{r(!1)}c>0?iS(`Tag "${a}" added to ${c} result${c>1?`s`:``}`):iS.error(`Failed to add tag`)},[e,t,n,i]),isPending:n}}function VCi(e,t){let{data:n}=AN({datasetId:e,queryOptions:{enabled:!!e}});return(0,G.useMemo)(()=>[...new Set([...n?.tags??[],...t.flatMap(e=>e.tags??[])])].sort(),[n?.tags,t])}function HCi({datasetId:e,experimentId:t,results:n}){let[r,i]=(0,G.useState)(new Set),[a,o]=(0,G.useState)(!1),{updateExperimentResult:s}=ON(),{addTag:c,isPending:l}=BCi({datasetId:e,experimentId:t}),u=VCi(e,n),d=(0,G.useMemo)(()=>n.filter(e=>r.has(e.id)),[n,r]),f=(0,G.useCallback)(e=>{i(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),p=(0,G.useCallback)(()=>i(new Set),[]);return{selectedIds:r,selectedResults:d,toggleSelect:f,toggleSelectAll:(0,G.useCallback)(()=>{i(e=>n.length>0&&n.every(t=>e.has(t.id))?new Set:new Set(n.map(e=>e.id)))},[n]),clearSelection:p,flagSelectedForReview:(0,G.useCallback)(async()=>{if(a||r.size===0)return;o(!0);let n=new Set;try{for(let i of r)try{await s.mutateAsync({datasetId:e,experimentId:t,resultId:i,status:`needs-review`}),n.add(i)}catch{}}finally{o(!1)}n.size>0&&(i(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),iS(`${n.size} result${n.size>1?`s`:``} flagged for review`))},[e,t,a,r,s]),isFlagging:a,addTagToSelected:(0,G.useCallback)(e=>c(e,d),[c,d]),isTagging:l,tagVocabulary:u}}var UCi=[];function WCi({crumbs:e,children:t}){return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:e}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiment`}),(0,K.jsx)(`div`,{}),(0,K.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:t})]})}function GCi(){let{experimentId:e}=kv(),t=[eP(`/experiments`),{id:`experiment`,Component:LCi,icon:RCi,Action:zCi}],n=Ov(),[r,i]=(0,G.useState)(!1),a=a5(),{data:o,isLoading:s,error:c}=RAt({experimentId:e??``,queryOptions:{enabled:!!e}}),l=o?.datasetId??``,{data:u,isLoading:d,error:f}=OAt({datasetId:l,experimentId:e??``,queryOptions:{enabled:!!l&&!!e}}),p=u?.status===`completed`||u?.status===`failed`,{data:m,isLoading:h,setEndOfListElement:g,isFetchingNextPage:_,hasNextPage:v}=AAt({datasetId:l,experimentId:e??``,experimentStatus:u?.status,queryOptions:{enabled:!!l&&!!e&&p}}),{supportsMetrics:y}=S7(),b=umi({experimentId:e,experimentStatus:u?.status,supportsMetrics:y,queryOptions:{enabled:!!e&&y&&p}}),x=HCi({datasetId:l,experimentId:e??``,results:m??UCi}),S=c??f;if(!e||s||d)return null;if(S&&FN(S))return(0,K.jsx)(WCi,{crumbs:t,children:(0,K.jsx)(TH,{})});if(S&&IN(S))return(0,K.jsx)(WCi,{crumbs:t,children:(0,K.jsx)(wH,{resource:`datasets`})});let C=(0,K.jsx)(WCi,{crumbs:t,children:(0,K.jsx)(Jx,{titleSlot:`Experiment not found`,descriptionSlot:`No experiment with id "${e}".`,actionSlot:(0,K.jsx)(X,{render:(0,K.jsx)(Lv,{to:`/experiments`}),icon:(0,K.jsx)(sS,{}),children:`Back to experiments`})})});return S&&LN(S)?C:S?(0,K.jsx)(WCi,{crumbs:t,children:(0,K.jsx)(Jx,{tone:`error`,titleSlot:`Failed to load experiment`,descriptionSlot:S instanceof Error?S.message:`An unexpected error occurred. Please try again.`})}):!l||!u?C:(0,K.jsx)(Smi,{experimentId:e,datasetId:l,experimentStatus:u.status,results:m??[],isLoadingResults:h,hasNextPage:v,children:(0,K.jsxs)(`div`,{className:`h-full`,children:[(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:t}),headerActions:(0,K.jsx)(F_i,{experiment:u,onDeleteClick:()=>i(!0)}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),p?(0,K.jsxs)(`div`,{className:`grid content-start gap-4`,children:[(0,K.jsx)(TCi,{experiment:u,metrics:b}),(0,K.jsxs)(`div`,{className:`grid content-start gap-1`,children:[(0,K.jsx)(ECi,{selection:x}),(0,K.jsx)(Gmi,{experimentId:e,experimentStatus:u.status,results:m??[],isLoading:h,setEndOfListElement:g,isFetchingNextPage:_,hasNextPage:v,selectedIds:x.selectedIds,onToggleSelect:x.toggleSelect,onToggleSelectAll:x.toggleSelectAll,supportsMetrics:y})]})]}):(0,K.jsx)(MCi,{experiment:u})]}),(0,K.jsx)(evi,{withQueryTrace:a.enabled,withFeedback:a.enabled}),(0,K.jsx)(Fhi,{open:r,onOpenChange:i,experimentId:e,experimentName:u.name??void 0,onSuccess:()=>n(`/experiments`)})]})})}function KCi({tag:e,onRename:t,onRemove:n}){let[r,i]=(0,G.useState)(!1),[a,o]=(0,G.useState)(e),s=(0,G.useRef)(null);(0,G.useEffect)(()=>{r&&(s.current?.focus(),s.current?.select())},[r]);let l=()=>{let n=a.trim();n&&n!==e&&t(n),i(!1)};return r?(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 rounded-md border border-border bg-card px-1`,children:[(0,K.jsx)(Jj,{variant:`unstyled`,ref:s,value:a,onChange:e=>o(e.target.value),onKeyDown:t=>{t.key===`Enter`&&(t.preventDefault(),l()),t.key===`Escape`&&(o(e),i(!1))},onBlur:l,className:`h-auto w-20 bg-transparent px-0 py-0.5 text-caption text-muted-foreground outline-hidden`}),(0,K.jsx)(`button`,{type:`button`,onMouseDown:e=>{e.preventDefault(),l()},className:c(SS,`p-0.5`),children:(0,K.jsx)(pC,{className:`size-icon-xs`})})]}):(0,K.jsxs)(`span`,{className:`group inline-flex items-center gap-0.5 rounded-md border border-border bg-card px-1.5 py-0.5 text-muted-foreground`,children:[(0,K.jsx)(T,{as:`span`,variant:`caption`,children:e}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>{o(e),i(!0)},className:c(SS,`p-0.5 opacity-0 transition-opacity group-hover:opacity-100`),title:`Edit tag`,children:(0,K.jsx)(iH,{className:`size-icon-xs`})}),(0,K.jsx)(`button`,{type:`button`,onClick:n,className:`p-0.5 text-placeholder opacity-0 transition-opacity group-hover:opacity-100 hover:text-destructive-foreground`,title:`Remove tag`,children:(0,K.jsx)(xw,{className:`size-icon-xs`})})]})}function qCi({selectedCount:e,vocabulary:t,onApplyTag:n,onRemoveTag:r,onNewTag:i,size:a=`sm`}){let[o,s]=(0,G.useState)(!1),[c,l]=(0,G.useState)(``),u=t.filter(e=>e.toLowerCase().includes(c.toLowerCase())),d=c.trim()&&!t.includes(c.trim());return(0,K.jsxs)(Xj,{open:o,onOpenChange:s,children:[(0,K.jsx)(Zj,{asChild:!0,children:(0,K.jsxs)(X,{size:a,icon:(0,K.jsx)(wX,{}),children:[`Tag `,e,` items`]})}),(0,K.jsxs)(Qj,{className:`w-56 p-2`,align:`end`,children:[(0,K.jsx)(Jj,{value:c,onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Enter`&&c.trim()&&(e.preventDefault(),d?i(c.trim()):n(c.trim()),l(``))},placeholder:`Search or create tag`,className:`mb-1 h-7 text-caption`,autoFocus:!0}),(0,K.jsxs)(`div`,{className:`max-h-40 space-y-0.5 overflow-y-auto`,children:[u.map(e=>(0,K.jsxs)(`div`,{className:`flex items-center justify-between rounded px-2 py-1 hover:bg-fill-subtle`,children:[(0,K.jsx)(`button`,{type:`button`,onClick:()=>n(e),className:`flex-1 text-left text-muted-foreground`,children:(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`block`,children:e})}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>r(e),className:`ml-2 text-placeholder hover:text-destructive-foreground`,children:(0,K.jsx)(xw,{className:`size-icon-xs`})})]},e)),d&&(0,K.jsx)(`button`,{type:`button`,onClick:()=>{i(c.trim()),l(``)},className:`w-full rounded px-2 py-1 text-left text-info-indicator hover:bg-fill-subtle`,children:(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[`Create & apply "`,c.trim(),`"`]})})]})]})]})}var JCi=[{name:`itemId`,label:`Item ID`,size:`auto`},{name:`input`,label:`Input`,size:`20rem`},{name:`tags`,label:`Tags`,size:`auto`},{name:`scores`,label:`Scores`,size:`6rem`}],YCi=`__untagged__`,XCi=`all`,ZCi=[{value:`review`,label:`Review queue`},{value:`completed`,label:`Completed`}];function QCi({datasetId:e,experimentId:t,experiments:n,isLoadingExperiments:r,targetType:i,targetId:a,featuredItemId:o,toolbarStart:s,renderFilters:l,toolbarEnd:u,onCreateScorer:d,breadcrumbs:f,withQueryTrace:p,withFeedback:m}){let h=Y(),{paths:g}=sn(),{data:_}=AN({datasetId:e??``,queryOptions:{enabled:!!e}}),v=jhi({experimentId:t,targetType:i,targetId:a,experiments:n,isLoadingExperiments:r}),y=Mhi({experimentId:t,targetType:i,targetId:a,experiments:n,isLoadingExperiments:r}),{data:b,isLoading:x}=v,{data:S,isLoading:C}=y,{updateExperimentResult:w}=ON(),[E,D]=(0,G.useState)(o??null);(0,G.useEffect)(()=>{o!==void 0&&D(o)},[o]);let[O,k]=(0,G.useState)(null),[A,j]=(0,G.useState)(new Set),[M,N]=(0,G.useState)(!1),[P,F]=(0,G.useState)(!1),[I,L]=(0,G.useState)(!1),[R,z]=(0,G.useState)(``),[B,V]=(0,G.useState)(``),[H,ee]=(0,G.useState)(``),[te,U]=(0,G.useState)([]),[W,ne]=(0,G.useState)(!1),re=(0,G.useMemo)(()=>b??[],[b]),ie=(0,G.useMemo)(()=>{let e=new Set;if(_?.tags)for(let t of _.tags)e.add(t);for(let t of re)for(let n of t.tags)e.add(n);return[...e].sort()},[_,re]),ae=(0,G.useMemo)(()=>O?O===YCi?re.filter(e=>e.tags.length===0):re.filter(e=>e.tags.includes(O)):re,[re,O]),oe=(0,G.useMemo)(()=>{let e=new Map,t=0;for(let n of re){n.tags.length===0&&t++;for(let t of n.tags)e.set(t,(e.get(t)??0)+1)}let n=[...e.entries()].sort((e,t)=>t[1]-e[1]).map(([e])=>({value:e,label:e}));return[{value:XCi,label:`All tags`},...t>0?[{value:YCi,label:`Untagged`}]:[],...n]},[re]),se=!!O||M,ce=(0,G.useCallback)(()=>{k(null),N(!1),D(null)},[]),le=(0,G.useCallback)((e,t)=>{let n=re.find(t=>t.id===e);n?.experimentId&&n?.datasetId&&w.mutate({datasetId:n.datasetId,experimentId:n.experimentId,resultId:n.id,tags:t})},[re,w]),ue=(0,G.useCallback)(e=>{let t=re.find(t=>t.id===e);j(t=>{let n=new Set(t);return n.delete(e),n}),E===e&&D(null),t?.experimentId&&t?.datasetId&&w.mutate({datasetId:t.datasetId,experimentId:t.experimentId,resultId:t.id,status:null})},[re,w,E]),de=(0,G.useCallback)(e=>{let t=re.find(t=>t.id===e);j(t=>{let n=new Set(t);return n.delete(e),n}),E===e&&D(null),t?.experimentId&&t?.datasetId&&w.mutate({datasetId:t.datasetId,experimentId:t.experimentId,resultId:t.id,status:`complete`})},[re,w,E]),fe=(0,G.useMemo)(()=>{let e=M?S??[]:ae;return!M||!O?e:O===YCi?e.filter(e=>e.tags.length===0):e.filter(e=>e.tags.includes(O))},[M,S,ae,O]),pe=M?C:!1,me=(0,G.useMemo)(()=>new Set(fe.map(e=>e.id)),[fe]),he=(0,G.useMemo)(()=>[...A].filter(e=>me.has(e)).length,[A,me]),ge=fe.length>0&&he===fe.length,_e=(0,G.useCallback)(e=>{j(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),ve=(0,G.useCallback)(()=>{j(ge?new Set:new Set(fe.map(e=>e.id)))},[ge,fe]),ye=(0,G.useCallback)(e=>{for(let t of A){let n=re.find(e=>e.id===t);n&&!n.tags.includes(e)&&le(t,[...n.tags,e])}},[re,A,le]),be=(0,G.useCallback)(e=>{for(let t of A){let n=re.find(e=>e.id===t);n&&n.tags.includes(e)&&le(t,n.tags.filter(t=>t!==e))}},[re,A,le]),xe=(0,G.useCallback)(()=>{for(let e of A)de(e);j(new Set)},[A,de]),Se=(0,G.useCallback)(()=>{for(let e of A)ue(e);j(new Set)},[A,ue]),Ce=(0,G.useCallback)(()=>{z(``),L(!0)},[]),we=(0,G.useCallback)(async()=>{if(B&&H){F(!0),L(!1);try{let e=re.filter(e=>A.has(e.id));if(e.length===0){F(!1);return}let t=await h.clusterFailures({modelId:`${B}/${H}`,items:e.map(e=>({id:e.id,input:e.input,output:e.output??void 0,error:typeof e.error==`string`?e.error:e.error?String(e.error):void 0,scores:e.scores,existingTags:e.tags.length>0?e.tags:void 0})),availableTags:ie.length>0?ie:void 0,prompt:R||void 0});t.proposedTags&&t.proposedTags.length>0&&(U(t.proposedTags.map(e=>({...e,accepted:!0}))),ne(!0))}catch(e){console.error(`Analysis failed:`,e)}finally{F(!1)}}},[B,H,re,A,h,ie,R]),Te=(0,G.useCallback)(()=>{for(let e of te){if(!e.accepted)continue;let t=re.find(t=>t.id===e.itemId);if(t){let n=[...new Set([...t.tags,...e.tags])];le(t.id,n)}}ne(!1)},[te,re,le]),Ee=(0,G.useCallback)(e=>{D(t=>t===e?null:e)},[]),De=(0,G.useMemo)(()=>E?fe.find(e=>e.id===E)??null:null,[E,fe]),{data:Oe}=jN({experimentId:De?.experimentId??``,queryOptions:{enabled:!!De?.experimentId}}),ke=M?y:v,Ae=fe.length===0||!(!E||De);(0,G.useEffect)(()=>{Ae&&ke.hasNextPage&&!ke.isFetching&&ke.fetchNextPage({cancelRefetch:!1})},[Ae,ke]);let je=E?fe.findIndex(e=>e.id===E):-1,Me=je>0?()=>D(fe[je-1].id):void 0,Ne=je>=0&&je<fe.length-1?()=>D(fe[je+1].id):void 0,Pe=!M&&A.size>0,Fe=!!d&&!M&&ae.length>0,Ie=M?`completed`:`review`,Le=e=>{N(e===`completed`),D(null)},Re=(0,K.jsxs)(TK,{children:[(0,K.jsx)(TK.Start,{children:l?(0,K.jsxs)(K.Fragment,{children:[s,l({status:Ie,onStatusChange:Le,tag:O,onTagChange:k,tagOptions:oe.filter(e=>e.value!==XCi)})]}):(0,K.jsxs)(K.Fragment,{children:[s,(0,K.jsxs)(Bk,{value:Ie,onValueChange:e=>Le(e===`completed`?`completed`:`review`),children:[(0,K.jsx)(Hk,{"aria-label":`Status`,size:`md`,className:`whitespace-nowrap`,children:(0,K.jsx)(Vk,{placeholder:`Select an option`})}),(0,K.jsx)(Uk,{children:ZCi.map(e=>(0,K.jsx)(Wk,{value:e.value,children:e.label},e.value))})]}),oe.length>1&&(0,K.jsxs)(Bk,{value:O??XCi,onValueChange:e=>k(e===XCi?null:e),children:[(0,K.jsx)(Hk,{"aria-label":`Tags`,size:`md`,className:`whitespace-nowrap`,children:(0,K.jsx)(Vk,{placeholder:`Select an option`})}),(0,K.jsx)(Uk,{children:oe.map(e=>(0,K.jsx)(Wk,{value:e.value,children:e.label},e.value))})]}),se&&(0,K.jsx)(X,{onClick:ce,size:`sm`,variant:`default`,icon:(0,K.jsx)(xw,{}),children:`Reset`})]})}),(Pe||u||Fe)&&(0,K.jsxs)(TK.End,{children:[u,Fe&&(0,K.jsxs)(X,{size:`md`,onClick:()=>d?.(ae.map(e=>({input:e.input,output:e.output}))),children:[(0,K.jsx)(Dx,{size:`xs`,children:(0,K.jsx)(G4,{})}),`Create scorer`]}),Pe&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(qCi,{size:`md`,selectedCount:A.size,vocabulary:ie,onApplyTag:ye,onRemoveTag:be,onNewTag:e=>ye(e)}),(0,K.jsx)(X,{variant:`primary`,onClick:xe,icon:(0,K.jsx)(EX,{}),children:`Mark as reviewed`}),(0,K.jsxs)(rE,{children:[(0,K.jsx)(rE.Trigger,{asChild:!0,children:(0,K.jsx)(X,{size:`icon-md`,disabled:P,"aria-label":`More actions`,children:P?(0,K.jsx)(It,{className:`h-4 w-4`}):(0,K.jsx)(M4,{})})}),(0,K.jsxs)(rE.Content,{align:`end`,children:[(0,K.jsxs)(rE.Item,{onSelect:Ce,children:[(0,K.jsx)(Dx,{size:`xs`,children:(0,K.jsx)(DZ,{})}),`Analyze`]}),(0,K.jsx)(rE.Separator,{}),(0,K.jsxs)(rE.Item,{onSelect:Se,children:[(0,K.jsx)(Dx,{size:`xs`,children:(0,K.jsx)(Kj,{})}),`Remove from queue`]})]})]})]})]})]});if(x)return(0,K.jsxs)(RS,{breadcrumbs:f,actionRow:Re,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(It,{fill:!0})]});let ze=(0,K.jsx)(Q_i,{withQueryTrace:p,withFeedback:m,result:De??void 0,title:`Review item ${De?.id??``}`,scores:De?Oe?.[De.itemId]:void 0,experimentLink:De?.experimentId?g.experimentItemLink(De.experimentId,De.itemId):void 0,onComplete:M||!De?void 0:()=>de(De.id),onPrevious:Me,onNext:Ne,onClose:()=>D(null)});return(0,K.jsxs)(RS,{breadcrumbs:f,actionRow:Re,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(nT,{open:I,onOpenChange:L,children:(0,K.jsxs)(rT,{children:[(0,K.jsxs)(iT,{children:[(0,K.jsx)(sT,{children:`Analyze Items`}),(0,K.jsx)(cT,{children:`Use an LLM to automatically suggest tags for the selected items.`})]}),(0,K.jsxs)(oT,{children:[(0,K.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[(0,K.jsxs)(ak,{className:`gap-1`,children:[(0,K.jsx)(sk,{children:`Provider`}),(0,K.jsx)(Mq,{value:B,onValueChange:V})]}),(0,K.jsxs)(ak,{className:`gap-1`,children:[(0,K.jsx)(sk,{children:`Model`}),(0,K.jsx)(Nq,{llmId:B,value:H,onValueChange:ee})]})]}),(0,K.jsxs)(T,{variant:`meta`,tone:`muted`,children:[A.size,` item`,A.size===1?``:`s`,` will be analyzed`]}),(0,K.jsxs)(ak,{className:`gap-1`,children:[(0,K.jsx)(sk,{children:`Instructions (optional)`}),(0,K.jsx)(qk,{className:`text-caption`,value:R,onChange:e=>z(e.target.value),placeholder:`E.g., Focus on safety issues and factual errors`,rows:3})]})]}),(0,K.jsxs)(aT,{children:[(0,K.jsx)(lT,{children:`Cancel`}),(0,K.jsx)(tT,{onConfirm:we,disabled:!B||!H||P,children:`Analyze`})]})]})}),(0,K.jsx)(nT,{open:W,onOpenChange:ne,children:(0,K.jsxs)(rT,{size:`lg`,children:[(0,K.jsxs)(iT,{children:[(0,K.jsx)(sT,{children:`Review Proposed Tags`}),(0,K.jsxs)(cT,{children:[te.filter(e=>e.accepted).length,` of `,te.length,` proposals selected`]})]}),(0,K.jsx)(oT,{children:te.map((e,t)=>{let n=re.find(t=>t.id===e.itemId);return(0,K.jsx)(`div`,{className:c(`rounded-lg border p-3`,!e.accepted&&`opacity-50`),children:(0,K.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,K.jsx)(qj,{checked:e.accepted,onCheckedChange:e=>U(n=>n.map((n,r)=>r===t?{...n,accepted:!!e}:n))}),(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsx)(T,{variant:`meta`,tone:`muted`,className:`block truncate`,children:n?typeof n.input==`string`?n.input.slice(0,100):JSON.stringify(n.input).slice(0,100):e.itemId}),(0,K.jsx)(`div`,{className:`mt-1.5 flex flex-wrap gap-1`,children:e.tags.map((e,n)=>(0,K.jsx)(KCi,{tag:e,onRename:e=>U(r=>r.map((r,i)=>i===t?{...r,tags:r.tags.map((t,r)=>r===n?e:t)}:r)),onRemove:()=>U(e=>e.map((e,r)=>r===t?{...e,tags:e.tags.filter((e,t)=>t!==n)}:e))},`${e}-${n}`))}),e.reason&&(0,K.jsx)(T,{variant:`meta`,tone:`muted`,className:`mt-1 block italic`,children:e.reason})]})]})},e.itemId)})}),(0,K.jsxs)(aT,{children:[(0,K.jsx)(lT,{children:`Cancel`}),(0,K.jsxs)(tT,{onConfirm:Te,disabled:te.filter(e=>e.accepted).length===0,children:[`Accept `,te.filter(e=>e.accepted).length,` proposals`]})]})]})}),(0,K.jsxs)(`div`,{className:`grid h-full min-h-0 w-full grid-cols-1 gap-4 overflow-hidden`,children:[(0,K.jsx)(`div`,{className:`min-h-0 w-full overflow-hidden`,children:pe||fe.length===0&&ke.hasNextPage?(0,K.jsx)(It,{fill:!0}):fe.length===0?(0,K.jsx)(Jx,{titleSlot:M?`No completed reviews yet`:`No items to review`,descriptionSlot:M?`Items marked as complete will appear here for auditing.`:`When experiment results are flagged for review, they will appear here.`,variant:`fill`}):(0,K.jsx)(Bmi,{results:fe,isLoading:!1,featuredResultId:E,onResultClick:Ee,columns:JCi,selectedIds:M?void 0:A,onToggleSelect:M?void 0:_e,onToggleSelectAll:M?void 0:ve,setEndOfListElement:ke.setEndOfListElement,hasNextPage:ke.hasNextPage,isFetchingNextPage:ke.isFetchingNextPage})}),ze]})]})}var $Ci=`experiment`,ewi=`status`,twi=[{value:`review`,label:`Review queue`},{value:`completed`,label:`Completed`}],nwi=[{id:`is`,label:`is`}],rwi=({targetType:e,targetId:t,experimentId:n,status:r,tag:i})=>{let a=xli({targetType:e,targetId:t});return n&&a.push(T7($Ci,n)),r!==`review`&&a.push(T7(ewi,r)),i&&a.push(T7(`tag`,i)),a},iwi=e=>({...Sli(e),experimentId:E7(e,$Ci),status:E7(e,`status`)===`completed`?`completed`:`review`,tag:E7(e,`tag`)||null});function awi({targetType:e,targetId:t,experimentId:n,status:r,tag:i,experiments:a,tagOptions:o,onChange:s}){let c=Cli(e),l=(0,G.useMemo)(()=>[...c,{id:$Ci,label:`Experiment`,icon:GN,color:sP(`pink`),strict:!0,suggestions:a.map(e=>({value:e.id,label:Vhi(e)}))},{id:ewi,label:`Status`,icon:EX,color:sP(`orange`),strict:!0,suggestions:twi},{id:`tag`,label:`Tag`,icon:wX,color:sP(`pink`),strict:!0,hidden:o.length===0,suggestions:o}],[c,a,o]),u=(0,G.useMemo)(()=>rwi({targetType:e,targetId:t,experimentId:n,status:r,tag:i}),[e,t,n,r,i]);return(0,K.jsxs)(m5,{fields:l,operators:nwi,value:u,onValueChange:e=>s(iwi(e)),createItemId:e=>e,"aria-label":`Review queue filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(m5.Chips,{}),(0,K.jsx)(m5.Input,{placeholder:`Filter review queue`})]})}var owi=[eP(`/experiments`),eP(`/experiments/review-queue`)],swi=`experiment`,cwi=`review`;function lwi(){let[e,t]=Rv(),n=e.get(O7),r=_li(n)?n:``,i=r?e.get(`targetId`)??``:``,a=e.get(swi),o=e.get(cwi),{Link:s,paths:c}=sn(),l=a5(),{data:u,error:d}=fmi({datasetId:void 0,target:{targetType:r,targetId:i}}),f=u?.experiments.find(e=>e.id===a),p=(e,n)=>{e.status!==n.status&&n.onStatusChange(e.status),e.tag!==n.tag&&n.onTagChange(e.tag),t(t=>{let n=new URLSearchParams(t),a=e.targetType!==r,o=a||e.targetId!==i?``:e.experimentId,s=a?``:e.targetId;return e.targetType?n.set(O7,e.targetType):n.delete(O7),s?n.set(k7,s):n.delete(k7),o?n.set(swi,o):n.delete(swi),n.delete(cwi),n},{replace:!0})};return d&&FN(d)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:owi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(TH,{variant:`fill`})]}):d&&IN(d)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:owi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(wH,{variant:`fill`,resource:`experiments`})]}):d?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:owi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load experiments`,descriptionSlot:d.message})]}):(0,K.jsx)(QCi,{withQueryTrace:l.enabled,withFeedback:l.enabled,breadcrumbs:(0,K.jsx)(vN,{crumbs:owi}),datasetId:f?.datasetId??void 0,experimentId:a??void 0,targetType:r,targetId:i,featuredItemId:o,renderFilters:e=>(0,K.jsx)(awi,{targetType:r,targetId:i,experimentId:a??``,status:e.status,tag:e.tag,experiments:u?.experiments??[],tagOptions:e.tagOptions,onChange:t=>p(t,e)}),toolbarEnd:a?(0,K.jsx)(X,{render:(0,K.jsx)(s,{href:c.experimentLink(a)}),icon:(0,K.jsx)(R4,{}),children:`See experiment`}):void 0})}function uwi({connection:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){let i=t?e.authorId:void 0;return(0,K.jsxs)(`li`,{className:`flex items-center justify-between gap-4 border-b py-2`,children:[(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-2`,children:[(0,K.jsx)(T,{as:`p`,variant:`caption`,font:`mono`,className:`wrap-anywhere`,children:e.connectionId}),(0,K.jsxs)(AC,{children:[(0,K.jsx)(AC.Item,{children:(0,K.jsx)(T,{as:`span`,variant:`caption`,children:e.label??`(no label)`})}),(0,K.jsx)(AC.Item,{children:(0,K.jsx)(eC,{size:`xs`,emphasis:`subtle`,children:e.status})})]}),(e.scope||i)&&(0,K.jsxs)(`dl`,{className:`flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1`,children:[e.scope&&(0,K.jsxs)(`div`,{className:`flex min-w-0 items-baseline gap-1`,children:[(0,K.jsx)(`dt`,{children:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`faint`,children:`Scope`})}),(0,K.jsx)(`dd`,{className:`min-w-0`,children:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:e.scope})})]}),i&&(0,K.jsxs)(`div`,{className:`flex min-w-0 items-baseline gap-1`,children:[(0,K.jsx)(`dt`,{children:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`faint`,children:`Author`})}),(0,K.jsx)(`dd`,{className:`min-w-0 wrap-anywhere`,children:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:i})})]})]})]}),(0,K.jsx)(`button`,{type:`button`,className:`shrink-0 text-destructive-foreground underline disabled:opacity-50`,onClick:r,disabled:n,children:`Disconnect`})]})}function dwi({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return(0,K.jsx)(`ul`,{className:`space-y-1`,children:e.map(e=>(0,K.jsx)(uwi,{connection:e,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(e.connectionId)},e.connectionId))})}function fwi({groups:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return(0,K.jsx)(`div`,{className:`space-y-4`,children:e.map(([e,i])=>(0,K.jsxs)(`div`,{children:[(0,K.jsx)(T,{as:`h3`,variant:`subheading`,tone:`ink`,"data-testid":`integration-author-group-${e}`,children:e===`shared`?`Shared`:`Owned by ${e}`}),(0,K.jsx)(dwi,{connections:i,isAdmin:t,disconnectPending:n,onDisconnect:r})]},e))})}function pwi({providerId:e,toolkit:t,connections:n,groupedByAuthor:r,isAdmin:i,isLoading:a,error:o,disconnectPending:s,disconnectError:c,onDisconnect:l}){return(0,K.jsxs)(`div`,{className:`space-y-2 rounded border p-4`,children:[(0,K.jsx)(T,{as:`h2`,variant:`heading`,children:`Existing connections`}),!e||!t?(0,K.jsx)(`p`,{className:`text-muted-foreground`,children:`Pick a provider and toolkit to list connections.`}):a?(0,K.jsx)(`p`,{className:`text-muted-foreground`,children:`Loading…`}):o?(0,K.jsx)(`p`,{className:`text-destructive-foreground`,children:String(o)}):n.length===0?(0,K.jsx)(`p`,{className:`text-muted-foreground`,children:`No connections.`}):r?(0,K.jsx)(fwi,{groups:r,isAdmin:i,disconnectPending:s,onDisconnect:l}):(0,K.jsx)(dwi,{connections:n,isAdmin:i,disconnectPending:s,onDisconnect:l}),c?(0,K.jsx)(`p`,{className:`text-destructive-foreground`,children:String(c)}):null]})}function mwi({providers:e,toolkits:t,providerId:n,toolkit:r,label:i,providersLoading:a,providersError:o,toolkitsLoading:s,toolkitsError:c,authorizePending:l,authorizeError:u,authorizedConnection:d,onProviderChange:f,onToolkitChange:p,onLabelChange:m,onConnect:h}){return(0,K.jsxs)(`div`,{className:`space-y-4 rounded border p-4`,children:[(0,K.jsxs)(ak,{invalid:!!o,disabled:a,children:[(0,K.jsx)(sk,{children:`Provider`}),(0,K.jsxs)(Bk,{value:n,onValueChange:f,children:[(0,K.jsx)(Hk,{children:(0,K.jsx)(Vk,{placeholder:a?`Loading providers…`:`Select provider`})}),(0,K.jsx)(Uk,{children:e.map(e=>(0,K.jsx)(Wk,{value:e.id,children:`${e.displayName??e.name} (${e.id})`},e.id))})]}),(0,K.jsx)(lk,{children:o?String(o):void 0})]}),(0,K.jsxs)(ak,{invalid:!!c,disabled:!n||s,children:[(0,K.jsx)(sk,{children:`Toolkit`}),(0,K.jsxs)(Bk,{value:r,onValueChange:p,children:[(0,K.jsx)(Hk,{children:(0,K.jsx)(Vk,{placeholder:s?`Loading toolkits…`:`Select toolkit`})}),(0,K.jsx)(Uk,{children:t.map(e=>(0,K.jsx)(Wk,{value:e.slug,children:`${e.name} (${e.slug})`},e.slug))})]}),(0,K.jsx)(lk,{children:c?String(c):void 0})]}),(0,K.jsxs)(ak,{disabled:!n||!r,children:[(0,K.jsx)(sk,{children:`Label (optional)`}),(0,K.jsx)(Jj,{placeholder:`My personal Gmail`,value:i,onChange:e=>m(e.target.value)})]}),(0,K.jsx)(X,{type:`button`,variant:`primary`,onClick:h,disabled:!n||!r||l,children:l?`Authorizing…`:`Connect`}),u?(0,K.jsx)(`div`,{role:`alert`,children:(0,K.jsx)(Sk,{variant:`destructive`,children:String(u)})}):null,d?(0,K.jsxs)(Sk,{variant:`success`,children:[`Authorized: `,d.connectionId,` (status: `,d.status,`)`]}):null]})}var hwi=e=>e.authorId?.trim()||`shared`,gwi=(e,t)=>{if(!t||new Set(e.map(hwi)).size<=1)return null;let n=new Map;for(let t of e){let e=hwi(t);n.set(e,[...n.get(e)??[],t])}let r=Array.from(n.entries());return r.sort(([e],[t])=>e===`shared`?1:t===`shared`?-1:e.localeCompare(t)),r},_wi=[`*`,`tool-providers:*`,`tool-providers:admin`];function vwi(){let{data:e}=j_();return e?.permissions?.some(e=>_wi.includes(e))??!1}var ywi=[{id:`integrations`,label:`Integrations`}];function bwi(){let[e,t]=(0,G.useState)(``),[n,r]=(0,G.useState)(``),[i,a]=(0,G.useState)(``),o=Bq(),s=Hq({providerId:e||null,queryOptions:{enabled:!!e}}),c=_Pn({providerId:e||null,toolkit:n||null}),l=hPn(),u=gPn(),d=vwi(),f=o.data?.providers??[],p=s.data?.data??[],m=(0,G.useMemo)(()=>c.data?.items??[],[c.data?.items]),h=(0,G.useMemo)(()=>gwi(m,d),[m,d]);return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:ywi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Integrations`}),(0,K.jsxs)(`div`,{className:`max-w-3xl space-y-6`,children:[(0,K.jsx)(T,{as:`p`,variant:`body`,tone:`muted`,children:`Minimal page to verify the ToolProvider backend. Pick a provider and toolkit, then connect.`}),(0,K.jsx)(mwi,{providers:f,toolkits:p,providerId:e,toolkit:n,label:i,providersLoading:o.isLoading,providersError:o.error,toolkitsLoading:s.isLoading,toolkitsError:s.error,authorizePending:l.isPending,authorizeError:l.error,authorizedConnection:l.data,onProviderChange:e=>{t(e),r(``)},onToolkitChange:r,onLabelChange:a,onConnect:()=>{e&&n&&l.mutate({providerId:e,toolkit:n,label:i.trim()||null},{onSuccess:()=>{a(``),c.refetch()}})}}),(0,K.jsx)(pwi,{providerId:e,toolkit:n,connections:m,groupedByAuthor:h,isAdmin:d,isLoading:c.isLoading,error:c.error,disconnectPending:u.isPending,disconnectError:u.error,onDisconnect:t=>{u.mutate({providerId:e,connectionId:t})}})]})]})}function g9(e,t){return e.position===t.position?e.id===t.id?0:e.id<t.id?-1:1:e.position<t.position?-1:1}function xwi(e){return!e.deletedAt&&!e.mergedInto}function Swi(e){let t=new Map;for(let n of e)xwi(n)&&!t.has(n.id)&&t.set(n.id,{page:n,children:[]});let n=[],r=new Map;for(let e of t.values()){let i=e.page.parentId?t.get(e.page.parentId):void 0;i&&i!==e?(i.children.push(e),r.set(e,i)):n.push(e)}let i=new Set,a=e=>{if(!i.has(e)){i.add(e);for(let t of e.children)a(t)}};n.forEach(a);let o=[...t.values()].filter(e=>!i.has(e));o.sort((e,t)=>g9(e.page,t.page));for(let e of o){if(i.has(e))continue;let t=[],o=e;for(;o&&!t.includes(o);)t.push(o),o=r.get(o);let s=(o?t.slice(t.indexOf(o)):[e]).reduce((e,t)=>g9(t.page,e.page)<0?t:e),c=r.get(s);c&&c.children.splice(c.children.indexOf(s),1),n.push(s),a(s)}let s=e=>{e.sort((e,t)=>g9(e.page,t.page));for(let t of e)s(t.children)};return s(n),n}function Cwi(e,t){let n=[],r=(e,i)=>{for(let a of e){let e=t.has(a.page.id);n.push({page:a.page,depth:i,hasChildren:a.children.length>0,expanded:e}),e&&r(a.children,i+1)}};return r(e,0),n}function wwi(e,t){let n=new Map(e.map(e=>[e.id,e])),r=[],i=new Set([t]),a=n.get(t)?.parentId??null;for(;a&&n.has(a)&&!i.has(a);)i.add(a),r.unshift(a),a=n.get(a)?.parentId??null;return r}function _9(e){return e.childCountCapped?`${e.childCount??0}+`:String(e.childCount??0)}function Twi(e,t){let n=new Set;return t&&!(e.get(t.id)?.length??0)&&!(t.childCount??0)&&t.parentId&&t.parentId!==t.id&&(e.get(t.parentId)??[]).filter(e=>e.id!==t.id&&!v9(e)).slice(0,8).forEach(e=>n.add(e.id)),n}var Ewi=`more:`,Dwi=`rest:`,Owi=`group:`;function v9(e){return e.id.startsWith(Ewi)}function y9(e){return e.id.startsWith(Dwi)}function b9(e){return e.id.startsWith(Owi)}function kwi(e){return e.filter(e=>!e.deletedAt&&!e.mergedInto)}function Awi(e,t,n=Iwi){let r=kwi(e),i=new Map(r.map(e=>[e.id,e])),a=new Map,o=[];for(let e of r){let t=e.parentId&&e.parentId!==e.id?i.get(e.parentId):void 0;t?a.set(t.id,[...a.get(t.id)??[],e]):o.push(e)}for(let e of a.values())e.sort(g9);o.sort(g9);let s=t&&i.has(t)?t:o[0]?.id??null,c=s?i.get(s):void 0,l=new Map,u=new Map,d=new Map,f=[],p=(e,t,n,r)=>{if(l.has(e))return;l.set(e,n),d.set(e,t);let i=n===1?e:r;i&&u.set(e,i),f.push(e)};if(s)p(s,null,0,void 0);else for(let e of o)p(e.id,null,1,void 0);for(;f.length;){let e=f.shift(),t=l.get(e),n=i.get(e),r=n?.parentId&&i.has(n.parentId)?n.parentId:null;r&&p(r,e,t+1,u.get(e));for(let n of a.get(e)??[])p(n.id,e,t+1,u.get(e));if(e===s&&c&&o.includes(c))for(let n of o)n.id!==s&&p(n.id,e,t+1,n.id)}let m=new Map;for(let e=t?i.get(t)?.parentId:void 0;e&&!m.has(e);){let t=i.get(e);if(!t)break;m.set(t.id,t.isScope?`scope`:`ancestor`),e=t.parentId&&t.parentId!==t.id?t.parentId:void 0}for(let e of r)e.isScope&&!b9(e)&&!v9(e)&&l.has(e.id)&&m.set(e.id,`scope`);let h=Twi(a,c),g=new Map,_=new Set,v=0;for(let e of r){let t=l.get(e.id),r=t!==void 0&&(t<=1||h.has(e.id))&&!v9(e),i=t!==void 0&&m.has(e.id)&&!v9(e),a=t===void 0&&n.has(e.id)&&!v9(e);a&&_.add(e.id),g.set(e.id,r||a||i&&v++<10?`full`:`dot`)}return{depth:l,form:g,branch:u,via:d,level:m,linked:_,center:s}}var jwi=230,Mwi=300,Nwi=150,Pwi=70,Fwi=28,x9=16,Iwi=new Set;function Lwi(e,t,n,r,i){let a=Math.max(...e.map(e=>i(e)))/2,o=r.flatMap(e=>{let t=n.get(e);return t?[Math.atan2(t.y,t.x)]:[]}),s=new Map,c=[...e],l=a*2.5+x9,u=l+a;for(let e=0;c.length&&e<12;e++){let e=Math.asin(Math.min(1,(a+x9/2)/l)),t=2*Math.asin(Math.min(1,(a*2+x9)/(2*l))),n=o.length?[...o].sort((e,t)=>e-t):[-Math.PI],r=[];n.forEach((i,a)=>{let o=n[(a+1)%n.length],s=i+e,c=(a+1<n.length?o:o+2*Math.PI)-e;for(let e=s;e<=c+1e-9;e+=t)r.push(e)}),c.splice(0,Math.max(1,r.length)).forEach((e,t)=>{let n=r[t]??r[0]??0;s.set(e.id,{x:Math.cos(n)*l,y:Math.sin(n)*l})}),u=l+a,l+=a*2+x9}return{points:s,reach:u}}function Rwi(e,t,n,r=Iwi){let i=kwi(e),a=new Map(i.map(e=>[e.id,e])),o=new Map;for(let e of t.depth.keys()){if(!a.has(e)||e===t.center)continue;let n=t.via.get(e)??null;o.set(n,[...o.get(n)??[],e])}let s=new Map,c=e=>{let n=t.form.get(e)===`full`?4:1,r=(o.get(e)??[]).reduce((e,t)=>e+c(t),0),i=Math.max(n,r);return s.set(e,i),i},l=t.center?o.get(t.center)??[]:o.get(null)??[];l.forEach(c);let u=new Map;for(let[e,r]of t.depth){let i=a.get(e);i&&e!==t.center&&t.form.get(e)===`full`&&u.set(r,(u.get(r)??0)+n(i)+30)}let d=u.get(1)??0,f=Math.max(1,Math.ceil(d/(2*Math.PI*Mwi))),p=[...t.depth].filter(([e,n])=>n===1&&e!==t.center&&t.form.get(e)===`full`&&a.has(e)).length,m=p?d/p:0,h=[0,Math.max(jwi,d/f/(2*Math.PI))],g=e=>{for(;h.length<=e;){let e=h.length,t=h[e-1],n=u.has(e-1)&&e>1?Nwi:Pwi,r=e===2?(f-1)*m:0;h.push(Math.max(t+n+r,(u.get(e)??0)/(2*Math.PI)))}return h[e]},_=0,v=new Map,y=(e,n,r,i)=>{let a=e.reduce((e,t)=>e+(s.get(t)??1),0)||1,c=e.filter(e=>t.form.get(e)!==`full`).length,l=i*g(n),u=Math.max(1,Math.floor(l/Fwi)),d=r,p=0;for(let r of e){let e=(s.get(r)??1)/a*i,l=d+e/2,h=t.form.get(r)===`full`,b=h||c<=u?0:p%Math.ceil(c/u);h||p++;let x=g(n)+(h&&n===1?_++%f*m:b*Fwi);v.set(r,{x:Math.cos(l)*x,y:Math.sin(l)*x}),y(o.get(r)??[],n+1,d,e),d+=e}},b=l.length?(s.get(l[0])??1)/l.reduce((e,t)=>e+(s.get(t)??1),0)*2*Math.PI:0,x=()=>{v.clear(),_=0,t.center&&v.set(t.center,{x:0,y:0}),y(l,1,-Math.PI/2-b/2,2*Math.PI)};x();let S=i.filter(e=>!v.has(e.id)).sort((e,t)=>e.id<t.id?-1:1),C=S.filter(e=>r.has(e.id)&&t.form.get(e.id)===`full`),w=S.filter(e=>r.has(e.id)&&t.form.get(e.id)!==`full`),T=0,E=t.center?a.get(t.center)?.parentId:void 0,D=l.some(e=>e!==E);if(C.length&&t.center&&D){let e=Math.max(...C.map(e=>n(e)))/2,t=0;for(let[e,r]of v){let i=a.get(e);i&&(t=Math.max(t,Math.hypot(r.x,r.y)+n(i)/2))}let r=Math.max(t+x9+e,C.length*(e*2+x9)/(2*Math.PI));C.forEach((e,t)=>{let n=Math.PI/2+t/C.length*2*Math.PI;v.set(e.id,{x:Math.cos(n)*r,y:Math.sin(n)*r})}),T=r+e}else if(C.length&&t.center){let e=Lwi(C,t.center,v,l,n),r=Math.max(0,...l.filter(e=>t.form.get(e)===`full`).map(e=>n(a.get(e))));h.length=2,h[1]=Math.max(h[1],e.reach+x9+r/2),x();let i=Lwi(C,t.center,v,l,n);for(let[e,t]of i.points)v.set(e,t)}let O=w,k=Math.min(175,Math.max(120,O.length*Fwi/(2*Math.PI)));O.forEach((e,t)=>{let n=Math.PI/2+t/O.length*2*Math.PI;v.set(e.id,{x:Math.cos(n)*k,y:Math.sin(n)*k})});let A=S.filter(e=>!r.has(e.id));if(A.length){let e=Math.max(g(h.length),T)+Pwi;A.forEach((t,n)=>{let r=-Math.PI/2+n/A.length*2*Math.PI;v.set(t.id,{x:Math.cos(r)*e,y:Math.sin(r)*e})})}return v}var zwi=[`var(--chart-blue)`,`var(--chart-green)`,`var(--chart-amber)`,`var(--chart-pink)`,`var(--chart-cyan)`,`var(--chart-orange)`,`var(--chart-purple)`,`var(--chart-red)`];function Bwi(e,t){let n=[];for(let r of e){let e=t.branch.get(r.id);e&&!n.includes(e)&&n.push(e)}return new Map(n.map((e,t)=>[e,zwi[t%zwi.length]]))}var Vwi=.7,Hwi=.7;function Uwi(e){return e<=16?1:Math.max(Hwi,Math.sqrt(16/e))}var Wwi={author:``};function Gwi(e,t,n){return{id:e,scopeId:t.scopeId,parentId:t.id,isScope:!1,position:``,name:``,version:0,createdBy:Wwi,updatedBy:Wwi,createdAt:``,updatedAt:``,...n}}function Kwi(e){if(!e.isScope||!e.address)return null;let t=e.address.indexOf(`:`);return t>0?e.address.slice(0,t):null}function qwi(e){let t=e.cap??48,n=kwi(e.pages),r=new Map(n.map(e=>[e.id,e])),i=new Map,a=[];for(let e of n){let t=e.parentId&&e.parentId!==e.id?e.parentId:null;t?i.set(t,[...i.get(t)??[],e]):a.push(e)}for(let e of i.values())e.sort(g9);a.sort(g9);let o=e.focusId?r.get(e.focusId):void 0,s=new Map,c=new Map,l=new Map,u=[],d=(e,t)=>{l.has(e.id)||(l.set(e.id,t),s.set(e.id,e),u.push(e.id))},f=o??a[0],p=Twi(i,f);if(f&&d(f,0),f&&!o)for(let e of a.slice(1,9))d(e,1);for(let e=o?.parentId?r.get(o.parentId):void 0,t=1;e;t++)l.has(e.id)||d(e,t),e=e.parentId&&e.parentId!==e.id?r.get(e.parentId):void 0;for(;u.length;){let n=u.shift(),a=s.get(n),o=l.get(n);if(o>=3||o===2&&!p.has(n))continue;let m=a.parentId?r.get(a.parentId):void 0;m&&d(m,o+1);let h=i.get(n)??[];if(!e.loadedParents.has(n)){let e=a.childCount??0,t=Math.min(e,8);for(let r=0;r<t;r++){let t=Gwi(`${Ewi}${n}:${r}`,a,{name:`${a.childCountCapped?`${e}+`:e} ${e===1?`page`:`pages`} under ${a.name}`});s.set(t.id,t),l.set(t.id,o+1)}if(!h.length)continue}let g=new Map;for(let e of h){let t=Kwi(e);t&&g.set(t,[...g.get(t)??[],e])}let _=new Set;if(n!==f?.id)for(let[t,r]of g){let i=`${Owi}${n}:${t}`;if(r.length<3||e.openGroups.has(i))continue;for(let e of r)_.add(e.id);let c=Gwi(i,a,{isScope:!0,address:`${t}:*`,displayLabel:`${t} scopes`,name:`${r.length} ${t} scopes`,childCount:r.length});s.set(c.id,c),l.set(c.id,o+1)}let v=h.filter(e=>!_.has(e.id)),y=0;for(let r of v)if(l.has(r.id))y++;else{if(y>=t+(e.revealed?.get(n)??0))break;d(r,o+1),y++}if(e.loadedParents.has(n)){let e=Math.max(a.childCount??h.length,h.length),t=Math.max(0,e-y-_.size);if(c.set(n,{hidden:t,drawn:y}),t>0&&n===f?.id){let r=Gwi(`${Dwi}${n}`,a,{name:`+${a.childCountCapped?`${e}+`:t} more`,childCount:t});s.set(r.id,r),l.set(r.id,o+1)}}}let m=o?[o.id,...o.parentId&&o.parentId!==o.id?[o.parentId]:[]]:a.map(e=>e.id),h=[...l].filter(([e,t])=>(t<=1||p.has(e))&&!m.includes(e)).map(([e])=>s.get(e)).filter(e=>(e.childCount??0)>0&&!b9(e)&&!v9(e)&&!y9(e));return m.push(...h.slice(0,24).map(e=>e.id)),{pages:[...s.values()],hiddenChildren:c,wanted:m,hub:f?.id??null}}var Jwi={linear:{label:`Linear`,icon:e=>(0,K.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 100 100`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,...e,children:(0,K.jsx)(`path`,{d:`M1.22541 61.5228c-.2225-.9485.90748-1.5459 1.59638-.857L39.3342 97.1782c.6889.6889.0915 1.8189-.857 1.5964C20.0515 94.4522 5.54779 79.9485 1.22541 61.5228ZM.00189135 46.8891c-.01764375.2833.08887215.5599.28957165.7606L52.3503 99.7085c.2007.2007.4773.3075.7606.2896 2.3692-.1476 4.6938-.46 6.9624-.9259.7645-.157 1.0301-1.0963.4782-1.6481L2.57595 39.4485c-.55186-.5519-1.49117-.2863-1.648174.4782-.465915 2.2686-.77832 4.5932-.92588465 6.9624ZM4.21093 29.7054c-.16649.3738-.08169.8106.20765 1.1l64.77602 64.776c.2894.2894.7262.3742 1.1.2077 1.7861-.7956 3.5171-1.6927 5.1855-2.684.5521-.328.6373-1.0867.1832-1.5407L8.43566 24.3367c-.45409-.4541-1.21271-.3689-1.54074.1832-.99132 1.6684-1.88843 3.3994-2.68399 5.1855ZM12.6587 18.074c-.3701-.3701-.393-.9637-.0443-1.3541C21.7795 6.45931 35.1114 0 49.9519 0 77.5927 0 100 22.4073 100 50.0481c0 14.8405-6.4593 28.1724-16.7199 37.3375-.3903.3487-.984.3258-1.3542-.0443L12.6587 18.074Z`})})},notion:{label:`Notion`,icon:e=>(0,K.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,...e,children:(0,K.jsx)(`path`,{d:`M4.459 4.208c.746.606 1.026.56 2.428.466l13.215-.793c.28 0 .047-.28-.046-.326L17.86 1.968c-.42-.326-.981-.7-2.055-.607L3.01 2.295c-.466.046-.56.28-.374.466zm.793 3.08v13.904c0 .747.373 1.027 1.214.98l14.523-.84c.841-.046.935-.56.935-1.167V6.354c0-.606-.233-.933-.748-.887l-15.177.887c-.56.047-.747.327-.747.933zm14.337.745c.093.42 0 .84-.42.888l-.7.14v10.264c-.608.327-1.168.514-1.635.514-.748 0-.935-.234-1.495-.933l-4.577-7.186v6.952L12.21 19s0 .84-1.168.84l-3.222.186c-.093-.186 0-.653.327-.746l.84-.233V9.854L7.822 9.76c-.094-.42.14-1.026.793-1.073l3.456-.233 4.764 7.279v-6.44l-1.215-.139c-.093-.514.28-.887.747-.933zM1.936 1.035l13.31-.98c1.634-.14 2.055-.047 3.082.7l4.249 2.986c.7.513.934.653.934 1.213v16.378c0 1.026-.373 1.634-1.68 1.726l-15.458.934c-.98.047-1.448-.093-1.962-.747l-3.129-4.06c-.56-.747-.793-1.306-.793-1.96V2.667c0-.839.374-1.54 1.447-1.632z`})})},confluence:{label:`Confluence`,icon:e=>(0,K.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,...e,children:(0,K.jsx)(`path`,{d:`M.87 18.257c-.248.382-.53.875-.763 1.245a.764.764 0 0 0 .255 1.04l4.965 3.054a.764.764 0 0 0 1.058-.26c.199-.332.454-.763.733-1.221 1.967-3.247 3.945-2.853 7.508-1.146l4.957 2.337a.764.764 0 0 0 1.028-.382l2.364-5.346a.764.764 0 0 0-.382-1 599.851 599.851 0 0 1-4.965-2.361C10.911 10.97 5.224 11.185.87 18.257zM23.131 5.743c.249-.405.531-.875.764-1.25a.764.764 0 0 0-.256-1.034L18.675.404a.764.764 0 0 0-1.058.26c-.195.335-.451.763-.734 1.225-1.966 3.246-3.945 2.85-7.508 1.146L4.437.694a.764.764 0 0 0-1.027.382L1.046 6.422a.764.764 0 0 0 .382 1c1.039.49 3.105 1.467 4.965 2.361 6.698 3.246 12.392 3.029 16.738-4.04z`})})},zendesk:{label:`Zendesk`,icon:e=>(0,K.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,...e,children:(0,K.jsx)(`path`,{d:`M12.914 2.904V16.29L24 2.905H12.914zM0 2.906C0 5.966 2.483 8.45 5.543 8.45s5.542-2.484 5.543-5.544H0zm11.086 4.807L0 21.096h11.086V7.713zm7.37 7.84c-3.063 0-5.542 2.48-5.542 5.543H24c0-3.06-2.48-5.543-5.543-5.543z`})})},fireflies:{label:`Fireflies`},github:{label:`GitHub`,icon:kZ},slack:{label:`Slack`,icon:e=>(0,K.jsxs)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,...e,children:[(0,K.jsx)(`path`,{d:`M5.042 15.165a2.528 2.528 0 0 1-2.52 2.523A2.528 2.528 0 0 1 0 15.165a2.527 2.527 0 0 1 2.522-2.52h2.52v2.52zm1.271 0a2.527 2.527 0 0 1 2.521-2.52 2.527 2.527 0 0 1 2.521 2.52v6.313A2.528 2.528 0 0 1 8.834 24a2.528 2.528 0 0 1-2.521-2.522v-6.313z`,fill:`#E01E5A`}),(0,K.jsx)(`path`,{d:`M8.834 5.042a2.528 2.528 0 0 1-2.521-2.52A2.528 2.528 0 0 1 8.834 0a2.528 2.528 0 0 1 2.521 2.522v2.52H8.834zm0 1.271a2.527 2.527 0 0 1 2.521 2.521 2.527 2.527 0 0 1-2.521 2.521H2.522A2.528 2.528 0 0 1 0 8.834a2.528 2.528 0 0 1 2.522-2.521h6.312z`,fill:`#36C5F0`}),(0,K.jsx)(`path`,{d:`M18.956 8.834a2.528 2.528 0 0 1 2.522-2.521A2.528 2.528 0 0 1 24 8.834a2.528 2.528 0 0 1-2.522 2.521h-2.522V8.834zm-1.27 0a2.528 2.528 0 0 1-2.523 2.521 2.527 2.527 0 0 1-2.52-2.521V2.522A2.527 2.527 0 0 1 15.165 0a2.528 2.528 0 0 1 2.523 2.522v6.312z`,fill:`#2EB67D`}),(0,K.jsx)(`path`,{d:`M15.165 18.956a2.528 2.528 0 0 1 2.523 2.522A2.528 2.528 0 0 1 15.165 24a2.527 2.527 0 0 1-2.52-2.522v-2.522h2.52zm0-1.27a2.527 2.527 0 0 1-2.52-2.523 2.527 2.527 0 0 1 2.52-2.52h6.313A2.528 2.528 0 0 1 24 15.165a2.528 2.528 0 0 1-2.522 2.523h-6.313z`,fill:`#ECB22E`})]})},google:{label:`Google`,icon:gOn}};function Ywi(e){return!e.isScope&&e.parentId===e.scopeId?e.key:void 0}function Xwi(e){let t=e.isScope&&e.address?e.address.slice(0,e.address.indexOf(`:`)):Ywi(e);return t&&Object.hasOwn(Jwi,t)?Jwi[t]:void 0}var Zwi=new Map([[`org`,`Organization`],[`project`,`Project`],[`user`,`User`],[`agent`,`Agent`],[`team`,`Team`]]);function S9(e){let t=Ywi(e);if(t&&e.name===t)return Xwi(e)?.label??e.name;if(!e.address||e.name!==e.address)return e.name;let n=e.address.slice(0,e.address.indexOf(`:`));return Xwi(e)?.label??Zwi.get(n)??e.name}function Qwi(e,t){let n=[],r=new Set;for(let i=e.parentId?t.get(e.parentId):void 0;i&&!r.has(i.id);)r.add(i.id),n.unshift(i.isScope&&i.address?i.address:i.name),i=i.parentId?t.get(i.parentId):void 0;return n.join(` › `)}function $wi(e,t){if(e.isScope)return e.address;let n=[],r=new Set;for(let i=e;i&&!r.has(i.id);i=i.parentId?t.get(i.parentId):void 0){if(r.add(i.id),i.isScope)return i.address?`${i.address}#${n.reverse().join(`/`)}`:void 0;if(!i.key)return;n.push(i.key)}}function eTi(e){return e.normalize(`NFKC`).trim().replace(/\s+/g,` `).toLowerCase()}function tTi(e,t=new Map){let n=new Map,r=new Map,i=new Map,a=new Map;for(let t of e){if(t.deletedAt||t.mergedInto)continue;n.set(t.id,t),t.isScope&&t.address&&r.set(t.address,t),!t.isScope&&t.key&&t.parentId&&i.set(`${t.parentId}\u0000${t.key}`,t);let e=eTi(t.name);a.set(e,a.has(e)?null:t)}let o=e=>{let t=e.indexOf(`#`);if(t<=0)return;let n=r.get(e.slice(0,t));if(!n)return;let a=n;for(let r of e.slice(t+1).split(`/`))if(a=i.get(`${a.id}\u0000${r}`),!a||a.scopeId!==n.id)return;return a===n?void 0:a};return{resolve(e){let i=e.trim();if(!i)return;let s=t.get(i);return n.get(i)??(s&&!s.deletedAt&&!s.mergedInto?s:void 0)??o(i)??r.get(i)??a.get(eTi(i))??void 0}}}function nTi(e,t,n,r){let i=e.resolve(r);if(i)return n.includes(i.id)?i:void 0;let a=r.trim(),o=a.indexOf(`#`);if(o<=0)return;let s=a.slice(0,o),c=[...t.values()].find(e=>e.isScope&&e.address===s);if(!c)return;let l=a.slice(o+1).split(`/`),u=n.flatMap(e=>{let n=t.get(e);return n&&rTi(n,c,l,t)?[n]:[]});return u.length===1?u[0]:void 0}function rTi(e,t,n,r){if(e.isScope||e.deletedAt||e.mergedInto||e.scopeId!==t.id)return!1;let i=e;for(let e=n.length-1;e>=0;e--){if(i.key!==n[e])return!1;if(i.parentId===t.id)return e===0;let a=i.parentId?r.get(i.parentId):void 0;if(!a)return e>0;i=a}return!1}var iTi=/\[\[([^\]]+)\]\]/g,aTi=/^(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:^\1[ \t]*$|(?![\s\S]))/gm,oTi=/(`+)[\s\S]*?\1/g;function sTi(e){return[...e.replace(aTi,``).replace(oTi,``).matchAll(iTi)].map(e=>e[1]??``)}function cTi(e){let t=tTi(e),n=[];for(let r of e){if(!r.body||r.deletedAt||r.mergedInto)continue;let e=new Map;for(let n of sTi(r.body)){let i=t.resolve(n);i&&i.id!==r.id&&e.set(i.id,(e.get(i.id)??0)+1)}for(let[t,i]of e)n.push({source:r.id,target:t,kind:`link`,count:i})}return n}var lTi=(0,G.createContext)(new Map),uTi=12,dTi=320;function fTi({point:e,pane:t}){let n=`clamp(0.5rem, ${e.x}px - 10rem, calc(100% - 20.5rem))`;if(t.height>0&&e.y>t.height/2)return{left:n,bottom:t.height-e.y+uTi,maxHeight:Math.min(dTi,e.y-uTi-8)};let r=t.height>0?t.height-e.y-uTi-8:dTi;return{left:n,top:e.y+uTi,maxHeight:Math.min(dTi,r)}}function pTi(e,t){let n=(0,G.useRef)(e);return t(n.current,e)||(n.current=e),n.current}var mTi=/^(#{1,3})[ \t]+(.+?)[ \t#]*$/gm,hTi=/^(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:^\1[ \t]*$|(?![\s\S]))/gm;function gTi(e){return[...e.replace(hTi,``).matchAll(mTi)].map(([,e,t])=>({depth:e?.length??1,text:(t??``).replace(/\[\[([^\]]+)\]\]/g,`$1`).replace(/[*_`]/g,``)}))}var _Ti=/\[\[([^\]]+)\]\]/g;function vTi(e){let t=[],n=0;for(let r of e.matchAll(_Ti))r.index>n&&t.push({type:`text`,value:e.slice(n,r.index)}),t.push({type:`wikilink`,value:r[1]??``}),n=r.index+r[0].length;return n<e.length&&t.push({type:`text`,value:e.slice(n)}),t}function yTi({page:e,className:t}){let n=Xwi(e)?.icon;return n?(0,K.jsx)(n,{"aria-hidden":!0,className:c(`shrink-0 text-foreground`,t)}):null}function C9({label:e,children:t}){return(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{render:t}),(0,K.jsx)(Tx,{children:e})]})}var bTi={"scope-created":`Scope created`,"page-created":`Page created`,"page-updated":`Page edited`,"page-moved":`Page moved`,"page-merged":`Page merged`,"page-deleted":`Page deleted`,"note-added":`Note added`,"note-restamped":`Note restamped`,"note-removed":`Note removed`,"note-restored":`Note restored`,"pin-added":`Pinned`,"pin-removed":`Unpinned`};function xTi(e){return e.startsWith(`importer:`)?`Importer`:e}function STi({author:e}){let t=e.includes(`:`)?e.slice(e.indexOf(`:`)+1):e,n=0;for(let t of e)n=n*31+t.charCodeAt(0)|0;let r=[`--chart-blue`,`--chart-purple`,`--chart-green`,`--chart-orange`,`--chart-pink`],i=r[Math.abs(n)%r.length];return(0,K.jsx)(`span`,{"aria-hidden":!0,className:`flex size-6 shrink-0 items-center justify-center rounded-full border border-border`,style:{background:`color-mix(in oklab, var(${i}) 28%, var(--card))`},children:(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`ink`,children:(t.trim()[0]??`?`).toUpperCase()})})}function CTi(e,t){if(e.isScope)return e.address??null;let n=t.find(t=>t.id===e.scopeId);if(!n?.address)return null;let r=[...t.slice(t.indexOf(n)+1).filter(e=>!e.isScope),e].map(e=>e.key);return r.some(e=>!e)?null:`${n.address}#${r.join(`/`)}`}var wTi=(0,G.createContext)(null);function TTi({node:e,...t}){let n=(0,G.useContext)(wTi),r=e?.properties[TX];if(typeof r!=`string`||!n)return(0,K.jsx)(`span`,{...t});let i=n.index.resolve(r);return i?(0,K.jsx)(C9,{label:r,children:(0,K.jsx)(`button`,{type:`button`,"data-testid":`knowledge-body-link`,className:`rounded bg-badge-blue-subtle px-1 text-left font-medium wrap-anywhere text-badge-blue-foreground hover:underline`,onClick:()=>n.onPageClick(i),children:i.name})}):(0,K.jsx)(C9,{label:`No loaded page has this address`,children:(0,K.jsx)(`span`,{"data-testid":`knowledge-body-link-unresolved`,className:`rounded border border-dashed border-border px-1 wrap-anywhere text-muted-foreground`,children:r})})}var ETi=[J1n];function DTi(e,t){let n=new Map;for(let r of e.body?sTi(e.body):[]){let i=t.resolve(r);i&&i.id!==e.id&&n.set(i.id,{page:i,count:(n.get(i.id)?.count??0)+1})}return[...n.values()]}function OTi({label:e,value:t}){return(0,K.jsxs)(`div`,{className:`flex flex-col gap-0.5 px-3 py-2`,children:[(0,K.jsx)(`dt`,{children:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:e})}),(0,K.jsx)(`dd`,{children:(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`ink`,children:t})})]})}var kTi={span:TTi};function w9({label:e,count:t,children:n}){return(0,K.jsxs)(`section`,{"aria-label":e,className:`flex flex-col gap-2`,children:[(0,K.jsxs)(T,{as:`h3`,variant:`label`,tone:`ink`,className:`flex items-center gap-1.5`,children:[e,t?(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`muted`,className:`tabular-nums`,children:t}):null]}),n]})}function ATi({page:e,onPageClick:t}){return(0,K.jsx)(`button`,{type:`button`,className:`text-left font-medium text-info-indicator hover:underline`,onClick:()=>t(e),children:e.name})}var jTi=new WeakMap;function MTi(e,t){let n=jTi.get(e);n||jTi.set(e,n=new WeakMap);let r=n.get(t);return r||n.set(t,r=tTi(e.values(),t)),r}function NTi({note:e,pagesById:t,onPageClick:n,highlighted:r,itemRef:i,showPage:a,compact:o}){let s=MTi(t,(0,G.useContext)(lTi)),c=n=>nTi(s,t,e.mentions,n),l=e=>{let n=t.get(e);return n?.address??n?.name??e},u=a?t.get(e.pageId):void 0;return(0,K.jsxs)(`li`,{ref:i,"data-highlighted":r||void 0,className:`flex gap-3 rounded-lg border border-border bg-card ${o?`p-2`:`p-3`}`,style:r?{borderColor:`var(--chart-blue)`,boxShadow:`0 0 0 1px var(--chart-blue)`}:void 0,children:[o?null:(0,K.jsx)(STi,{author:e.provenance.author}),(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-1.5`,children:[(0,K.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-0.5`,children:[(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`ink`,children:xTi(e.provenance.author)}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:(0,K.jsx)(Dk,{value:e.updatedAt})}),u?(0,K.jsxs)(T,{as:`span`,variant:`caption`,tone:`muted`,children:[`on `,(0,K.jsx)(ATi,{page:u,onPageClick:n})]}):null]}),(0,K.jsx)(`p`,{className:`text-body wrap-anywhere text-foreground`,children:vTi(e.text).map((e,t)=>{if(e.type===`text`)return(0,K.jsx)(`span`,{children:e.value},t);let r=c(e.value);return r?(0,K.jsx)(C9,{label:e.value,children:(0,K.jsx)(`button`,{type:`button`,"data-testid":`knowledge-note-link`,className:`rounded bg-badge-blue-subtle px-1 text-left font-medium wrap-anywhere text-badge-blue-foreground hover:underline`,onClick:()=>n(r),children:r.name})},t):(0,K.jsx)(`span`,{className:`font-medium wrap-anywhere`,children:e.value},t)})}),e.stampScopeIds.length>0?(0,K.jsx)(`div`,{className:`flex min-w-0 flex-wrap gap-1`,"aria-label":`Stamped to`,children:e.stampScopeIds.map(e=>(0,K.jsx)(eC,{variant:`neutral`,size:`xs`,title:l(e),children:(0,K.jsx)(`span`,{className:`truncate`,children:l(e)})},e))}):null]})]})}function PTi({page:e,notes:t,pin:n,pagesById:r,onPageClick:i,highlightMentionOf:a,ancestors:o=[],mentionedBy:s=[],notesMore:c,childPages:l,activity:u,links:d,onOpenPage:f,compact:p=!1}){let m=(0,G.useRef)(null);(0,G.useEffect)(()=>{m.current?.scrollIntoView?.({block:`nearest`})},[a,t]);let h=!1,g=e.isScope?e:o.find(t=>t.id===e.scopeId)??r.get(e.scopeId),_=CTi(e,o),v=e.isScope?e.displayLabel??`Scope`:`Page`,y=(0,G.useMemo)(()=>new Map([...r,...[...o,e].map(e=>[e.id,e])]),[r,o,e]),b=(0,G.useContext)(lTi),x=(0,G.useMemo)(()=>tTi([...r.values(),...o,e],b),[r,o,e,b]),S=(0,G.useMemo)(()=>({index:x,onPageClick:i}),[x,i]),C=(0,G.useRef)(null),w=(0,G.useMemo)(()=>e.body?gTi(e.body):[],[e.body]),E=(0,G.useMemo)(()=>DTi(e,x),[e,x]),D=d?.out??E,O=d?.in??[],k=d?d.in.length:s.length,A=(0,K.jsx)(wTi.Provider,{value:S,children:(0,K.jsx)(xY,{remarkPlugins:ETi,components:kTi,children:e.body??``})}),j=(0,K.jsxs)(T,{variant:`body`,tone:`muted`,children:[`This `,e.isScope?`scope`:`page`,` has no body yet.`]}),M=e=>(0,K.jsx)(`ul`,{className:`flex flex-col gap-2`,children:e.map(e=>{let t=!!a&&e.mentions.includes(a),n=t&&!h;return n&&(h=!0),(0,K.jsx)(NTi,{note:e,pagesById:y,onPageClick:i,highlighted:t,compact:p,itemRef:n?e=>{m.current=e}:void 0},e.id)})}),N=a?t.filter(e=>e.mentions.includes(a)):[],P=t.reduce((e,t)=>!e||t.updatedAt>e.updatedAt?t:e,void 0),F=N.length>0?N:P?[P]:[],I=D.length>0||O.length>0||s.length>0?(0,K.jsx)(w9,{label:`Connections`,count:D.length+Math.max(O.length,s.length),children:(0,K.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[D.length>0?(0,K.jsxs)(`section`,{"aria-label":`Links to`,className:`flex flex-col gap-1.5`,children:[(0,K.jsx)(T,{as:`h4`,variant:`caption`,tone:`muted`,children:`Links to`}),(0,K.jsx)(`ul`,{className:`flex flex-col gap-1`,children:D.map(({page:e,count:t})=>(0,K.jsxs)(`li`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(oH,{"aria-hidden":!0,className:`size-icon-xs shrink-0 text-muted-foreground`}),(0,K.jsx)(`button`,{type:`button`,className:`min-w-0 truncate text-left text-body-sm text-foreground hover:underline`,onClick:()=>i(e),children:S9(e)}),t>1?(0,K.jsxs)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`tabular-nums`,children:[`×`,t]}):null]},e.id))})]}):null,O.length>0?(0,K.jsxs)(`section`,{"aria-label":`Linked from`,className:`flex flex-col gap-1.5`,children:[(0,K.jsx)(T,{as:`h4`,variant:`caption`,tone:`muted`,children:`Linked from`}),(0,K.jsx)(`ul`,{className:`flex flex-col gap-1`,children:O.map(({page:e,count:t})=>(0,K.jsxs)(`li`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(sS,{"aria-hidden":!0,className:`size-icon-xs shrink-0 text-muted-foreground`}),(0,K.jsx)(`button`,{type:`button`,className:`min-w-0 truncate text-left text-body-sm text-foreground hover:underline`,onClick:()=>i(e),children:S9(e)}),t>1?(0,K.jsxs)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`tabular-nums`,children:[`×`,t]}):null]},e.id))})]}):null,s.length>0?(0,K.jsxs)(`section`,{"aria-label":`Mentioned in`,className:`flex flex-col gap-1.5`,children:[(0,K.jsx)(T,{as:`h4`,variant:`caption`,tone:`muted`,children:`Mentioned in`}),(0,K.jsx)(`ul`,{className:`flex flex-col gap-2`,children:s.map(e=>(0,K.jsx)(NTi,{note:e,pagesById:y,onPageClick:i,showPage:!0,compact:!0},e.id))})]}):null]})}):null;return(0,K.jsxs)(`article`,{"aria-label":e.name,className:`@container flex min-h-0 flex-1 flex-col overflow-y-auto overscroll-contain`,children:[(0,K.jsxs)(`header`,{className:p?`flex flex-col gap-3 border-b border-surface-rim px-4 pt-3 pb-4`:`flex flex-col gap-3 border-b border-border bg-fill-subtle px-6 pt-5 pb-4`,children:[(0,K.jsxs)(hDt,{label:`Breadcrumb`,className:`ml-[-.9em] min-w-0`,listClassName:`overflow-hidden`,children:[o.map(e=>(0,K.jsx)(iN,{as:`button`,onClick:()=>i(e),children:S9(e)},e.id)),(0,K.jsx)(iN,{as:`span`,isCurrent:!0,children:S9(e)})]}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[p?null:(0,K.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(yTi,{page:e,className:`size-icon-lg`}),(0,K.jsx)(C9,{label:(e.isScope?e.address:_)??e.name,children:(0,K.jsx)(T,{as:`h2`,variant:`title`,className:`min-w-0 break-words`,"data-testid":`knowledge-page-title`,children:S9(e)})}),(0,K.jsxs)(eC,{variant:`neutral`,size:`sm`,className:`shrink-0 tabular-nums`,children:[`v`,e.version]})]}),e.description?(0,K.jsx)(T,{variant:`body`,tone:`muted`,className:`wrap-anywhere ${p?`line-clamp-3`:`line-clamp-6`}`,children:e.description}):null,(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,K.jsx)(eC,{variant:e.isScope?`info`:`neutral`,size:`sm`,children:v}),n?(0,K.jsx)(eC,{variant:`warning`,size:`sm`,icon:(0,K.jsx)(DX,{"aria-hidden":!0}),children:n.audience.length>0?`Pinned for ${n.audience.join(`, `)}`:`Pinned`}):null,p?(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,"data-testid":`knowledge-page-version`,children:(0,K.jsxs)(AC,{children:[e.isScope||!g?null:(0,K.jsxs)(AC.Item,{children:[`In `,S9(g)]}),(0,K.jsxs)(AC.Item,{children:[`v`,e.version]}),(0,K.jsxs)(AC.Item,{children:[`Updated`,` `,(0,K.jsx)(Dk,{value:e.updatedAt,label:`Updated by ${xTi(e.updatedBy.author)}`})]})]})}):null]})]})]}),p?(0,K.jsxs)(`div`,{className:`flex flex-col gap-6 p-4`,children:[(0,K.jsxs)(`dl`,{"aria-label":`Links and notes`,className:`grid grid-cols-3 divide-x divide-border rounded-lg border border-border`,children:[(0,K.jsx)(OTi,{label:`Links in`,value:k}),(0,K.jsx)(OTi,{label:`Links out`,value:D.length}),(0,K.jsx)(OTi,{label:`Notes`,value:c?`${t.length}+`:t.length})]}),(0,K.jsx)(w9,{label:`Preview`,children:e.body?(0,K.jsx)(LS,{maxHeight:`12rem`,children:(0,K.jsx)(`div`,{"data-testid":`knowledge-page-body`,children:A})}):j}),I,F.length>0?(0,K.jsxs)(w9,{label:a?`Notes that mention it`:`Latest note`,children:[M(F),f&&t.length>F.length?(0,K.jsxs)(X,{variant:`ghost`,size:`sm`,className:`self-start`,onClick:f,children:[`All `,c?``:`${t.length} `,`notes`]}):null]}):null]}):(0,K.jsxs)(`div`,{className:`flex flex-col gap-8 p-6 @3xl:flex-row`,children:[(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-8 @3xl:flex-1`,children:[e.body?(0,K.jsx)(`div`,{ref:C,"data-testid":`knowledge-page-body`,className:`max-w-3xl`,children:A}):j,t.length>0||c?(0,K.jsxs)(w9,{label:`Notes`,count:c?void 0:t.length,children:[M(t),c]}):null]}),(0,K.jsxs)(`aside`,{className:`flex min-w-0 flex-col divide-y divide-border border-t border-border *:py-6 *:last:pb-0 @3xl:w-72 @3xl:shrink-0 @3xl:border-t-0 @3xl:border-l @3xl:pl-8 @3xl:*:first:pt-0`,children:[w.length>1?(0,K.jsx)(w9,{label:`On this page`,children:(0,K.jsx)(`ol`,{className:`flex flex-col gap-1.5 border-l border-border`,children:w.map((e,t)=>(0,K.jsx)(`li`,{className:e.depth>2?`pl-6`:`pl-3`,children:(0,K.jsx)(`button`,{type:`button`,className:`text-left text-body-sm text-muted-foreground hover:text-foreground`,onClick:()=>{(C.current?.querySelectorAll(`h1, h2, h3`))?.[t]?.scrollIntoView({block:`start`,behavior:`smooth`})},children:(0,K.jsx)(`span`,{className:`line-clamp-2 wrap-anywhere`,children:e.text})})},t))})}):null,(0,K.jsx)(w9,{label:`Details`,children:(0,K.jsxs)(V4,{children:[e.isScope?null:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(V4.Key,{children:`Scope`}),(0,K.jsx)(V4.Value,{children:g?S9(g):e.scopeId})]}),(0,K.jsx)(V4.Key,{children:`Updated`}),(0,K.jsx)(V4.Value,{children:(0,K.jsx)(Dk,{value:e.updatedAt})}),(0,K.jsx)(V4.Key,{children:`By`}),(0,K.jsx)(V4.Value,{children:xTi(e.updatedBy.author)}),(0,K.jsx)(V4.Key,{children:`Created`}),(0,K.jsx)(V4.Value,{children:(0,K.jsx)(Dk,{value:e.createdAt})}),(0,K.jsx)(V4.Key,{children:`Version`}),(0,K.jsxs)(V4.Value,{children:[`v`,e.version]})]})}),I,l,u&&u.length>0?(0,K.jsx)(w9,{label:`Activity`,children:(0,K.jsx)(`ol`,{className:`relative flex flex-col gap-3 border-l border-border pl-4`,children:u.map(e=>(0,K.jsxs)(`li`,{className:`relative flex flex-col`,children:[(0,K.jsx)(`span`,{"aria-hidden":!0,className:`absolute top-1.5 -left-5 size-2 rounded-full border border-border bg-card`}),(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`ink`,children:bTi[e.action]??e.action}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`min-w-0`,children:(0,K.jsxs)(AC,{singleLine:!0,children:[(0,K.jsx)(AC.Item,{className:`min-w-0`,children:(0,K.jsx)(C9,{label:e.provenance.author,children:(0,K.jsx)(`span`,{className:`truncate`,children:xTi(e.provenance.author)})})}),(0,K.jsx)(AC.Item,{className:`shrink-0`,children:(0,K.jsx)(Dk,{value:e.createdAt})})]})})]},e.id))})}):null]})]})]},e.id)}function FTi(e,t){return e.split(/(\s+|(?<=:))/).map(e=>e.length>t&&!/^\s+$/.test(e)?`${e.slice(0,t-1)}\u2026`:e).join(``)}function T9(){return typeof window<`u`&&!!window.matchMedia?.(`(prefers-reduced-motion: no-preference)`).matches}function ITi(e,t){let n=e.map(e=>e.id).join(`\0`),[r,i]=(0,G.useState)(n),[a,o]=(0,G.useState)([]),s=(0,G.useRef)(e);if((0,G.useEffect)(()=>{s.current=e}),r!==n&&(i(n),t)){let t=new Set(e.map(e=>e.id)),n=s.current.filter(e=>!t.has(e.id));o(e=>[...e.filter(e=>!t.has(e.node.id)),...n.filter(t=>!e.some(e=>e.node.id===t.id)).map(e=>({node:e,fading:!1}))])}let c=a.some(e=>!e.fading),l=(0,G.useRef)(void 0);return(0,G.useEffect)(()=>{if(!c)return;let e=requestAnimationFrame(()=>{o(e=>e.map(e=>({...e,fading:!0}))),clearTimeout(l.current),l.current=setTimeout(()=>o(e=>e.filter(e=>!e.fading)),750)});return()=>cancelAnimationFrame(e)},[c,a.length]),(0,G.useEffect)(()=>()=>clearTimeout(l.current),[]),!t||a.length===0?e:[...e,...a.map(({node:e,fading:t})=>({...e,selectable:!1,focusable:!1,style:{...e.style,opacity:+!t,pointerEvents:`none`}}))]}var LTi=.15,RTi={left:0,right:0};function zTi(e,t){return e-t.left-t.right>0?t:RTi}function BTi({bounds:e,width:t,height:n,ring:r,anchor:i,insets:a=RTi}){let o=zTi(t,a),s=r?LTi:Vwi,c=t-o.left-o.right,l=VD(e,c,n,s,2,.1);if(i&&l.zoom<=s){let e=i.position.x+(i.width??0)/2,t=i.position.y+(i.height??0)/2;return{zoom:l.zoom,x:o.left+c/2-e*l.zoom,y:n/2-t*l.zoom}}return{...l,x:l.x+o.left}}var VTi=.05,HTi=3e3;function UTi({bounds:e,nodes:t,width:n,height:r,legend:i,insets:a=RTi}){let o=zTi(n,a),s=(t,i)=>{let a=VD(e,n-t-o.right,r-i,LTi,1,VTi);return{zoom:a.zoom,x:a.x+t,y:a.y+i}},c=s(o.left,0);if(!i||!t.some(e=>{let t=e.x*c.zoom+c.x,n=e.y*c.zoom+c.y;return t<i.right&&n<i.bottom}))return c;let l=s(i.right,0),u=s(o.left,i.bottom);return l.zoom>=u.zoom?l:u}var E9=e=>e?700:0;function WTi(e,t,n){if(t+48>n)return n/2-(e+t/2);if(e<24)return 24-e;let r=e+t-(n-24);return r>0?-r:0}function GTi(e){let t=+this._x.call(null,e),n=+this._y.call(null,e);return KTi(this.cover(t,n),t,n,e)}function KTi(e,t,n,r){if(isNaN(t)||isNaN(n))return e;var i,a=e._root,o={data:r},s=e._x0,c=e._y0,l=e._x1,u=e._y1,d,f,p,m,h,g,_,v;if(!a)return e._root=o,e;for(;a.length;)if((h=t>=(d=(s+l)/2))?s=d:l=d,(g=n>=(f=(c+u)/2))?c=f:u=f,i=a,!(a=a[_=g<<1|h]))return i[_]=o,e;if(p=+e._x.call(null,a.data),m=+e._y.call(null,a.data),t===p&&n===m)return o.next=a,i?i[_]=o:e._root=o,e;do i=i?i[_]=[,,,,]:e._root=[,,,,],(h=t>=(d=(s+l)/2))?s=d:l=d,(g=n>=(f=(c+u)/2))?c=f:u=f;while((_=g<<1|h)==(v=(m>=f)<<1|p>=d));return i[v]=a,i[_]=o,e}function qTi(e){Array.isArray(e)||(e=Array.from(e));let t=e.length,n=new Float64Array(t),r=new Float64Array(t),i=1/0,a=i,o=-i,s=o;for(let c=0,l,u,d;c<t;++c)isNaN(u=+this._x.call(null,l=e[c]))||isNaN(d=+this._y.call(null,l))?n[c]=NaN:(n[c]=u,r[c]=d,u<i&&(i=u),u>o&&(o=u),d<a&&(a=d),d>s&&(s=d));if(i>o||a>s)return this;this.cover(i,a).cover(o,s);for(let i=0;i<t;++i)KTi(this,n[i],r[i],e[i]);return this}function JTi(e,t){if(isNaN(e=+e)||isNaN(t=+t))return this;var n=this._x0,r=this._y0,i=this._x1,a=this._y1;if(isNaN(n))i=(n=Math.floor(e))+1,a=(r=Math.floor(t))+1;else{for(var o=i-n||1,s=this._root,c,l;n>e||e>=i||r>t||t>=a;)switch(l=(t<r)<<1|e<n,c=[,,,,],c[l]=s,s=c,o*=2,l){case 0:i=n+o,a=r+o;break;case 1:n=i-o,a=r+o;break;case 2:i=n+o,r=a-o;break;case 3:n=i-o,r=a-o}this._root&&this._root.length&&(this._root=s)}return this._x0=n,this._y0=r,this._x1=i,this._y1=a,this}function YTi(){var e=[];return this.visit(function(t){if(!t.length)do e.push(t.data);while(t=t.next)}),e}function XTi(e){return arguments.length?this.cover(+e[0][0],+e[0][1]).cover(+e[1][0],+e[1][1]):isNaN(this._x0)?void 0:[[this._x0,this._y0],[this._x1,this._y1]]}function D9(e,t,n,r,i){this.node=e,this.x0=t,this.y0=n,this.x1=r,this.y1=i}function ZTi(e,t,n){var r,i=this._x0,a=this._y0,o,s,c,l,u=this._x1,d=this._y1,f=[],p=this._root,m,h;for(p&&f.push(new D9(p,i,a,u,d)),n==null?n=1/0:(i=e-n,a=t-n,u=e+n,d=t+n,n*=n);m=f.pop();)if(!(!(p=m.node)||(o=m.x0)>u||(s=m.y0)>d||(c=m.x1)<i||(l=m.y1)<a)){if(p.length){var g=(o+c)/2,_=(s+l)/2;f.push(new D9(p[3],g,_,c,l),new D9(p[2],o,_,g,l),new D9(p[1],g,s,c,_),new D9(p[0],o,s,g,_)),(h=(t>=_)<<1|e>=g)&&(m=f[f.length-1],f[f.length-1]=f[f.length-1-h],f[f.length-1-h]=m)}else{var v=e-+this._x.call(null,p.data),y=t-+this._y.call(null,p.data),b=v*v+y*y;if(b<n){var x=Math.sqrt(n=b);i=e-x,a=t-x,u=e+x,d=t+x,r=p.data}}}return r}function QTi(e){if(isNaN(u=+this._x.call(null,e))||isNaN(d=+this._y.call(null,e)))return this;var t,n=this._root,r,i,a,o=this._x0,s=this._y0,c=this._x1,l=this._y1,u,d,f,p,m,h,g,_;if(!n)return this;if(n.length)for(;;){if((m=u>=(f=(o+c)/2))?o=f:c=f,(h=d>=(p=(s+l)/2))?s=p:l=p,t=n,!(n=n[g=h<<1|m]))return this;if(!n.length)break;(t[g+1&3]||t[g+2&3]||t[g+3&3])&&(r=t,_=g)}for(;n.data!==e;)if(i=n,!(n=n.next))return this;return(a=n.next)&&delete n.next,i?(a?i.next=a:delete i.next,this):t?(a?t[g]=a:delete t[g],(n=t[0]||t[1]||t[2]||t[3])&&n===(t[3]||t[2]||t[1]||t[0])&&!n.length&&(r?r[_]=n:this._root=n),this):(this._root=a,this)}function $Ti(e){for(var t=0,n=e.length;t<n;++t)this.remove(e[t]);return this}function eEi(){return this._root}function tEi(){var e=0;return this.visit(function(t){if(!t.length)do++e;while(t=t.next)}),e}function nEi(e){var t=[],n,r=this._root,i,a,o,s,c;for(r&&t.push(new D9(r,this._x0,this._y0,this._x1,this._y1));n=t.pop();)if(!e(r=n.node,a=n.x0,o=n.y0,s=n.x1,c=n.y1)&&r.length){var l=(a+s)/2,u=(o+c)/2;(i=r[3])&&t.push(new D9(i,l,u,s,c)),(i=r[2])&&t.push(new D9(i,a,u,l,c)),(i=r[1])&&t.push(new D9(i,l,o,s,u)),(i=r[0])&&t.push(new D9(i,a,o,l,u))}return this}function rEi(e){var t=[],n=[],r;for(this._root&&t.push(new D9(this._root,this._x0,this._y0,this._x1,this._y1));r=t.pop();){var i=r.node;if(i.length){var a,o=r.x0,s=r.y0,c=r.x1,l=r.y1,u=(o+c)/2,d=(s+l)/2;(a=i[0])&&t.push(new D9(a,o,s,u,d)),(a=i[1])&&t.push(new D9(a,u,s,c,d)),(a=i[2])&&t.push(new D9(a,o,d,u,l)),(a=i[3])&&t.push(new D9(a,u,d,c,l))}n.push(r)}for(;r=n.pop();)e(r.node,r.x0,r.y0,r.x1,r.y1);return this}function iEi(e){return e[0]}function aEi(e){return arguments.length?(this._x=e,this):this._x}function oEi(e){return e[1]}function sEi(e){return arguments.length?(this._y=e,this):this._y}function cEi(e,t,n){var r=new lEi(t??iEi,n??oEi,NaN,NaN,NaN,NaN);return e==null?r:r.addAll(e)}function lEi(e,t,n,r,i,a){this._x=e,this._y=t,this._x0=n,this._y0=r,this._x1=i,this._y1=a,this._root=void 0}function uEi(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}var O9=cEi.prototype=lEi.prototype;O9.copy=function(){var e=new lEi(this._x,this._y,this._x0,this._y0,this._x1,this._y1),t=this._root,n,r;if(!t)return e;if(!t.length)return e._root=uEi(t),e;for(n=[{source:t,target:e._root=[,,,,]}];t=n.pop();)for(var i=0;i<4;++i)(r=t.source[i])&&(r.length?n.push({source:r,target:t.target[i]=[,,,,]}):t.target[i]=uEi(r));return e},O9.add=GTi,O9.addAll=qTi,O9.cover=JTi,O9.data=YTi,O9.extent=XTi,O9.find=ZTi,O9.remove=QTi,O9.removeAll=$Ti,O9.root=eEi,O9.size=tEi,O9.visit=nEi,O9.visitAfter=rEi,O9.x=aEi,O9.y=sEi;function dEi(e,t){var n,r=1;e??=0,t??=0;function i(){var i,a=n.length,o,s=0,c=0;for(i=0;i<a;++i)o=n[i],s+=o.x,c+=o.y;for(s=(s/a-e)*r,c=(c/a-t)*r,i=0;i<a;++i)o=n[i],o.x-=s,o.y-=c}return i.initialize=function(e){n=e},i.x=function(t){return arguments.length?(e=+t,i):e},i.y=function(e){return arguments.length?(t=+e,i):t},i.strength=function(e){return arguments.length?(r=+e,i):r},i}function k9(e){return function(){return e}}function A9(e){return(e()-.5)*1e-6}function fEi(e){return e.x+e.vx}function pEi(e){return e.y+e.vy}function mEi(e){var t,n,r,i=1,a=1;typeof e!=`function`&&(e=k9(e==null?1:+e));function o(){for(var e,o=t.length,c,l,u,d,f,p,m=0;m<a;++m)for(c=cEi(t,fEi,pEi).visitAfter(s),e=0;e<o;++e)l=t[e],f=n[l.index],p=f*f,u=l.x+l.vx,d=l.y+l.vy,c.visit(h);function h(e,t,n,a,o){var s=e.data,c=e.r,m=f+c;if(s){if(s.index>l.index){var h=u-s.x-s.vx,g=d-s.y-s.vy,_=h*h+g*g;_<m*m&&(h===0&&(h=A9(r),_+=h*h),g===0&&(g=A9(r),_+=g*g),_=(m-(_=Math.sqrt(_)))/_*i,l.vx+=(h*=_)*(m=(c*=c)/(p+c)),l.vy+=(g*=_)*m,s.vx-=h*(m=1-m),s.vy-=g*m)}}else return t>u+m||a<u-m||n>d+m||o<d-m}}function s(e){if(e.data)return e.r=n[e.data.index];for(var t=e.r=0;t<4;++t)e[t]&&e[t].r>e.r&&(e.r=e[t].r)}function c(){if(t){var r,i=t.length,a;for(n=Array(i),r=0;r<i;++r)a=t[r],n[a.index]=+e(a,r,t)}}return o.initialize=function(e,n){t=e,r=n,c()},o.iterations=function(e){return arguments.length?(a=+e,o):a},o.strength=function(e){return arguments.length?(i=+e,o):i},o.radius=function(t){return arguments.length?(e=typeof t==`function`?t:k9(+t),c(),o):e},o}function hEi(e){return e.index}function gEi(e,t){var n=e.get(t);if(!n)throw Error(`node not found: `+t);return n}function _Ei(e){var t=hEi,n=d,r,i=k9(30),a,o,s,c,l,u=1;e??=[];function d(e){return 1/Math.min(s[e.source.index],s[e.target.index])}function f(t){for(var n=0,i=e.length;n<u;++n)for(var o=0,s,d,f,p,m,h,g;o<i;++o)s=e[o],d=s.source,f=s.target,p=f.x+f.vx-d.x-d.vx||A9(l),m=f.y+f.vy-d.y-d.vy||A9(l),h=Math.sqrt(p*p+m*m),h=(h-a[o])/h*t*r[o],p*=h,m*=h,f.vx-=p*(g=c[o]),f.vy-=m*g,d.vx+=p*(g=1-g),d.vy+=m*g}function p(){if(o){var n,i=o.length,l=e.length,u=new Map(o.map((e,n)=>[t(e,n,o),e])),d;for(n=0,s=Array(i);n<l;++n)d=e[n],d.index=n,typeof d.source!=`object`&&(d.source=gEi(u,d.source)),typeof d.target!=`object`&&(d.target=gEi(u,d.target)),s[d.source.index]=(s[d.source.index]||0)+1,s[d.target.index]=(s[d.target.index]||0)+1;for(n=0,c=Array(l);n<l;++n)d=e[n],c[n]=s[d.source.index]/(s[d.source.index]+s[d.target.index]);r=Array(l),m(),a=Array(l),h()}}function m(){if(o)for(var t=0,i=e.length;t<i;++t)r[t]=+n(e[t],t,e)}function h(){if(o)for(var t=0,n=e.length;t<n;++t)a[t]=+i(e[t],t,e)}return f.initialize=function(e,t){o=e,l=t,p()},f.links=function(t){return arguments.length?(e=t,p(),f):e},f.id=function(e){return arguments.length?(t=e,f):t},f.iterations=function(e){return arguments.length?(u=+e,f):u},f.strength=function(e){return arguments.length?(n=typeof e==`function`?e:k9(+e),m(),f):n},f.distance=function(e){return arguments.length?(i=typeof e==`function`?e:k9(+e),h(),f):i},f}var vEi=1664525,yEi=1013904223,bEi=4294967296;function xEi(){let e=1;return()=>(e=(vEi*e+yEi)%bEi)/bEi}function SEi(e){return e.x}function CEi(e){return e.y}var wEi=10,TEi=Math.PI*(3-Math.sqrt(5));function EEi(e){var t,n=1,r=.001,i=1-r**(1/300),a=0,o=.6,s=new Map,c=qtt(d),l=lE(`tick`,`end`),u=xEi();e??=[];function d(){f(),l.call(`tick`,t),n<r&&(c.stop(),l.call(`end`,t))}function f(r){var c,l=e.length,u;r===void 0&&(r=1);for(var d=0;d<r;++d)for(n+=(a-n)*i,s.forEach(function(e){e(n)}),c=0;c<l;++c)u=e[c],u.fx==null?u.x+=u.vx*=o:(u.x=u.fx,u.vx=0),u.fy==null?u.y+=u.vy*=o:(u.y=u.fy,u.vy=0);return t}function p(){for(var t=0,n=e.length,r;t<n;++t){if(r=e[t],r.index=t,r.fx!=null&&(r.x=r.fx),r.fy!=null&&(r.y=r.fy),isNaN(r.x)||isNaN(r.y)){var i=wEi*Math.sqrt(.5+t),a=t*TEi;r.x=i*Math.cos(a),r.y=i*Math.sin(a)}(isNaN(r.vx)||isNaN(r.vy))&&(r.vx=r.vy=0)}}function m(t){return t.initialize&&t.initialize(e,u),t}return p(),t={tick:f,restart:function(){return c.restart(d),t},stop:function(){return c.stop(),t},nodes:function(n){return arguments.length?(e=n,p(),s.forEach(m),t):e},alpha:function(e){return arguments.length?(n=+e,t):n},alphaMin:function(e){return arguments.length?(r=+e,t):r},alphaDecay:function(e){return arguments.length?(i=+e,t):+i},alphaTarget:function(e){return arguments.length?(a=+e,t):a},velocityDecay:function(e){return arguments.length?(o=1-e,t):1-o},randomSource:function(e){return arguments.length?(u=e,s.forEach(m),t):u},force:function(e,n){return arguments.length>1?(n==null?s.delete(e):s.set(e,m(n)),t):s.get(e)},find:function(t,n,r){var i=0,a=e.length,o,s,c,l,u;for(r==null?r=1/0:r*=r,i=0;i<a;++i)l=e[i],o=t-l.x,s=n-l.y,c=o*o+s*s,c<r&&(u=l,r=c);return u},on:function(e,n){return arguments.length>1?(l.on(e,n),t):l.on(e)}}}function DEi(){var e,t,n,r,i=k9(-30),a,o=1,s=1/0,c=.81;function l(n){var i,a=e.length,o=cEi(e,SEi,CEi).visitAfter(d);for(r=n,i=0;i<a;++i)t=e[i],o.visit(f)}function u(){if(e){var t,n=e.length,r;for(a=Array(n),t=0;t<n;++t)r=e[t],a[r.index]=+i(r,t,e)}}function d(e){var t=0,n,r,i=0,o,s,c;if(e.length){for(o=s=c=0;c<4;++c)(n=e[c])&&(r=Math.abs(n.value))&&(t+=n.value,i+=r,o+=r*n.x,s+=r*n.y);e.x=o/i,e.y=s/i}else{n=e,n.x=n.data.x,n.y=n.data.y;do t+=a[n.data.index];while(n=n.next)}e.value=t}function f(e,i,l,u){if(!e.value)return!0;var d=e.x-t.x,f=e.y-t.y,p=u-i,m=d*d+f*f;if(p*p/c<m)return m<s&&(d===0&&(d=A9(n),m+=d*d),f===0&&(f=A9(n),m+=f*f),m<o&&(m=Math.sqrt(o*m)),t.vx+=d*e.value*r/m,t.vy+=f*e.value*r/m),!0;if(!(e.length||m>=s)){(e.data!==t||e.next)&&(d===0&&(d=A9(n),m+=d*d),f===0&&(f=A9(n),m+=f*f),m<o&&(m=Math.sqrt(o*m)));do e.data!==t&&(p=a[e.data.index]*r/m,t.vx+=d*p,t.vy+=f*p);while(e=e.next)}}return l.initialize=function(t,r){e=t,n=r,u()},l.strength=function(e){return arguments.length?(i=typeof e==`function`?e:k9(+e),u(),l):i},l.distanceMin=function(e){return arguments.length?(o=e*e,l):Math.sqrt(o)},l.distanceMax=function(e){return arguments.length?(s=e*e,l):Math.sqrt(s)},l.theta=function(e){return arguments.length?(c=e*e,l):Math.sqrt(c)},l}function OEi(e){var t=k9(.1),n,r,i;typeof e!=`function`&&(e=k9(e==null?0:+e));function a(e){for(var t=0,a=n.length,o;t<a;++t)o=n[t],o.vx+=(i[t]-o.x)*r[t]*e}function o(){if(n){var a,o=n.length;for(r=Array(o),i=Array(o),a=0;a<o;++a)r[a]=isNaN(i[a]=+e(n[a],a,n))?0:+t(n[a],a,n)}}return a.initialize=function(e){n=e,o()},a.strength=function(e){return arguments.length?(t=typeof e==`function`?e:k9(+e),o(),a):t},a.x=function(t){return arguments.length?(e=typeof t==`function`?t:k9(+t),o(),a):e},a}function kEi(e){var t=k9(.1),n,r,i;typeof e!=`function`&&(e=k9(e==null?0:+e));function a(e){for(var t=0,a=n.length,o;t<a;++t)o=n[t],o.vy+=(i[t]-o.y)*r[t]*e}function o(){if(n){var a,o=n.length;for(r=Array(o),i=Array(o),a=0;a<o;++a)r[a]=isNaN(i[a]=+e(n[a],a,n))?0:+t(n[a],a,n)}}return a.initialize=function(e){n=e,o()},a.strength=function(e){return arguments.length?(t=typeof e==`function`?e:k9(+e),o(),a):t},a.y=function(t){return arguments.length?(e=typeof t==`function`?t:k9(+t),o(),a):e},a}var AEi=28,jEi=300;function MEi(e,t,n={}){let r=n.ticks??jEi,i=[...e].sort((e,t)=>e.id.localeCompare(t.id)).map((e,t)=>{let n=18*Math.sqrt(.5+t),r=t*2.399963229728653,i=e.initial??{x:n*Math.cos(r),y:n*Math.sin(r)};return{id:e.id,size:e.size,padding:e.padding??AEi,x:e.fixed?.x??i.x,y:e.fixed?.y??i.y,fx:e.fixed?.x??null,fy:e.fixed?.y??null}}),a=new Set(i.map(e=>e.id)),o=new Set(t.filter(e=>e.hug).map(e=>`${e.source}\u0000${e.target}`)),s=t.filter(e=>a.has(e.source)&&a.has(e.target)).map(e=>({source:e.source,target:e.target}));EEi(i).force(`link`,_Ei(s).id(e=>e.id).distance(e=>{let t=e.source,n=e.target;return(o.has(`${t.id}\u0000${n.id}`)?8:40)+(t.size+n.size)/2})).force(`charge`,DEi().strength(e=>e.size<=24?-60:-700)).force(`collide`,mEi().radius(e=>e.size/2+e.padding).strength(1).iterations(3)).force(`center`,dEi(0,0)).force(`x`,OEi(0).strength(.06)).force(`y`,kEi(0).strength(.08)).stop().tick(r),NEi(i);let c=new Map;for(let e of i)c.set(e.id,{x:e.x??0,y:e.y??0});return c}function NEi(e){let t=[...e].sort((e,t)=>t.size-e.size);for(let e=0;e<600;e++){let e=!1;for(let n=0;n<t.length;n++)for(let r=n+1;r<t.length;r++){let i=t[n],a=t[r];if(!i||!a)continue;let o=i.size/2+a.size/2+Math.min(i.padding,a.padding),s=(a.x??0)-(i.x??0),c=(a.y??0)-(i.y??0),l=Math.hypot(s,c);if(l>=o)continue;l===0&&(s=1,c=0,l=1);let u=o-l+.5,d=s/l,f=c/l,p=i.fx!=null,m=a.fx!=null;if(p&&m)continue;let h=p?0:m?1:.5,g=1-h;i.x=(i.x??0)-d*u*h,i.y=(i.y??0)-f*u*h,a.x=(a.x??0)+d*u*g,a.y=(a.y??0)+f*u*g,e=!0}if(!e)break}}function PEi(e,t=[]){let n=new Set(e.filter(e=>!e.deletedAt&&!e.mergedInto).map(e=>e.id)),r=[];for(let t of e)n.has(t.id)&&t.parentId&&t.parentId!==t.id&&n.has(t.parentId)&&r.push({source:t.parentId,target:t.id,kind:`parent`});let i=new Map;for(let e of t){if(e.kind!==`mention`&&e.kind!==`link`||e.source===e.target||!n.has(e.source)||!n.has(e.target))continue;let t=`${e.kind}\u0000${e.source}\u0000${e.target}`,r=i.get(t),a=e.count??1;r?r.count=(r.count??1)+a:i.set(t,{source:e.source,target:e.target,kind:e.kind,count:a})}return[...r,...i.values()]}function FEi(e){return`unplaced:${e}`}function IEi(e,t=[]){let n=new Set(e.filter(e=>!e.deletedAt&&!e.mergedInto).map(e=>e.id)),r=new Map,i=new Map;for(let e of t){if(!n.has(e.target))continue;let t=e.principalId&&n.has(e.principalId)?e.principalId:null;if(!t){if(e.principalId)continue;t=FEi(e.principal),r.has(t)||r.set(t,LEi(t,e))}t!==e.target&&i.set(`${t}\u0000${e.target}`,{source:t,target:e.target,kind:`grant`,role:e.role})}return{placeholders:[...r.values()],edges:[...i.values()]}}function LEi(e,t){let n={author:``};return{id:e,scopeId:e,parentId:null,isScope:!0,address:t.principal,displayLabel:t.principalLabel,position:``,name:t.principal,version:0,createdBy:n,updatedBy:n,createdAt:``,updatedAt:``}}function REi(e,t){let n=new Set([e]);for(let r of t)r.source===e&&n.add(r.target),r.target===e&&n.add(r.source);return n}function zEi(e,t,n){return{nodes:e.filter(e=>!e.deletedAt&&!e.mergedInto).map(e=>({id:e.id,type:`page`,position:{x:0,y:0},data:{page:e,size:e.isScope?124:108,selected:e.id===n}})),edges:t.map(e=>({id:`${e.kind}:${e.source}->${e.target}`,source:e.source,target:e.target,data:{kind:e.kind,count:e.count??1,...e.role?{role:e.role}:{}}}))}}var BEi=[`top`,`bottom`,`right`,`left`];function VEi(e,{dot:t,tip:n,gap:r}){let i=(t.left+t.right)/2,a=(t.top+t.bottom)/2;return e===`top`?{left:i-n.width/2,right:i+n.width/2,bottom:t.top-r,top:t.top-r-n.height}:e===`bottom`?{left:i-n.width/2,right:i+n.width/2,top:t.bottom+r,bottom:t.bottom+r+n.height}:e===`left`?{right:t.left-r,left:t.left-r-n.width,top:a-n.height/2,bottom:a+n.height/2}:{left:t.right+r,right:t.right+r+n.width,top:a-n.height/2,bottom:a+n.height/2}}function HEi(e,t){let n=Math.min(e.right,t.right)-Math.max(e.left,t.left),r=Math.min(e.bottom,t.bottom)-Math.max(e.top,t.top);return n>0&&r>0?n*r:0}function UEi(e,t,n){let r=Math.max(4,Math.ceil(Math.hypot(n.x-t.x,n.y-t.y)/6));for(let i=0;i<=r;i++){let a=t.x+(n.x-t.x)*i/r,o=t.y+(n.y-t.y)*i/r;if(a>=e.left&&a<=e.right&&o>=e.top&&o<=e.bottom)return!0}return!1}function WEi(e){let t=e=>(e.right-e.left)*(e.bottom-e.top),n=`top`,r=1/0;for(let i of BEi){let a=VEi(i,e),o=(t(a)-HEi(a,e.bounds))*100;for(let t of e.obstacles)o+=HEi(a,t)*4;for(let t of e.lines)UEi(a,t.from,t.to)&&(o+=2e3);o<r&&(n=i,r=o)}return n}var GEi=U(`IconArrowWallUp`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M16.25 10.9998L12.7071 7.45696C12.3166 7.06643 11.6834 7.06643 11.2929 7.45695L7.75 10.9998`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M12 21V7.75`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M19 3H5`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]})),KEi={left:0,right:0},qEi={"--knowledge-color":`var(--chart-blue)`,background:`color-mix(in oklab, var(--chart-blue) 16%, var(--card))`},JEi={"--knowledge-color":`var(--border-strong)`},YEi=`var(--muted-foreground)`,XEi={"--knowledge-color":YEi,background:YEi},ZEi={stroke:`var(--foreground)`,strokeOpacity:.45,strokeDasharray:`4 4`,strokeWidth:1.25},QEi=`var(--chart-cyan)`,$Ei={stroke:QEi,strokeWidth:2.25},eDi={type:TD.ArrowClosed,color:QEi,width:14,height:14},tDi=`var(--chart-blue)`,nDi=`var(--muted-foreground)`,rDi={type:TD.Arrow,color:nDi,width:12,height:12,strokeWidth:1.5},iDi=`var(--chart-purple)`,aDi={stroke:iDi,strokeWidth:1.75,strokeDasharray:`8 3 2 3`},oDi={type:TD.ArrowClosed,color:iDi,width:13,height:13},j9=`var(--chart-green)`,sDi={stroke:j9,strokeWidth:1.25},cDi={type:TD.ArrowClosed,color:j9,width:12,height:12},lDi={out:{stroke:j9},in:{stroke:`var(--chart-orange)`,strokeDasharray:`6 3`}},uDi={out:cDi,in:{type:TD.ArrowClosed,color:`var(--chart-orange)`,width:12,height:12}},dDi={stroke:`var(--foreground)`,strokeOpacity:.2,strokeWidth:1},fDi={background:`var(--card)`,borderColor:`var(--chart-purple)`,borderStyle:`dashed`};function pDi(e){let t=e/2*(1-Math.SQRT1_2);return{badge:20,style:{width:20,height:20,top:t,right:t,transform:`translate(50%, -50%)`}}}var mDi=150,hDi=4e3,gDi=3;function _Di(e){let{left:t,top:n,right:r,bottom:i}=e.getBoundingClientRect();return{left:t,top:n,right:r,bottom:i}}function vDi(e){let t=[];for(let n of e.querySelectorAll(`.react-flow__edge-path`)){if(typeof n.getTotalLength!=`function`||typeof n.getScreenCTM!=`function`)continue;let e=n.getScreenCTM();if(!e)continue;let r=n.getTotalLength(),i=n.getPointAtLength(0),a=n.getPointAtLength(r);t.push({from:{x:e.a*i.x+e.c*i.y+e.e,y:e.b*i.x+e.d*i.y+e.f},to:{x:e.a*a.x+e.c*a.y+e.e,y:e.b*a.x+e.d*a.y+e.f}})}return t}var yDi={top:{tip:`bottom-full left-1/2 mb-2`,transform:`translateX(-50%)`,origin:`bottom center`,tail:`top-full left-1/2 -translate-x-1/2 -translate-y-1/2 border-r border-b`},bottom:{tip:`top-full left-1/2 mt-2`,transform:`translateX(-50%)`,origin:`top center`,tail:`bottom-full left-1/2 -translate-x-1/2 translate-y-1/2 border-l border-t`},right:{tip:`left-full top-1/2 ml-2`,transform:`translateY(-50%)`,origin:`center left`,tail:`right-full top-1/2 translate-x-1/2 -translate-y-1/2 border-l border-b`},left:{tip:`right-full top-1/2 mr-2`,transform:`translateY(-50%)`,origin:`center right`,tail:`left-full top-1/2 -translate-x-1/2 -translate-y-1/2 border-r border-t`}};function bDi({level:e}){return(0,K.jsx)(e===`scope`?nC:GEi,{"aria-hidden":!0,"data-testid":`knowledge-level-icon-${e}`,className:`mr-1 inline-block size-3 align-text-bottom`})}function xDi({data:e}){let{page:t,size:n,color:r,path:i,ref:a,links:o,notShown:s}=e,[c,l]=(0,G.useState)(!1),u=(0,G.useRef)(null),d=(0,G.useRef)(null),[f,p]=(0,G.useState)(`top`),m=rO(e=>e.transform[2]),h=Math.min(Math.max(1/m,1),gDi),g=v9(t),_=b9(t),v=g?`Hover or click to load them`:_?`Click to show them`:null,y=!v&&t.childCount?`${_9(t)} ${t.childCount===1?`child`:`children`}`:null,b=t.isScope?t.displayLabel??`Scope`:`Page`,x=o&&(o.in>0||o.out>0)?_X(o,s):null,S=[t.name,v??i,y,x].filter(Boolean).join(`, `);(0,G.useLayoutEffect)(()=>{let e=u.current,t=d.current,n=e?.closest(`.knowledge-graph`);if(!c||!e||!t||!n)return;let r=_Di(e),i=_Di(t),a=t.offsetWidth*h,o=t.offsetHeight*h;if(!a||!o)return;let s=[...n.querySelectorAll(`[data-testid="knowledge-page-node"], [data-testid="knowledge-page-dot"]`),...(n.parentElement??n).querySelectorAll(`[aria-label="Legend"], [data-testid="knowledge-graph-back"], [data-knowledge-graph-zoom]`)].map(_Di).filter(e=>e.right>e.left&&(e.left!==i.left||e.top!==i.top)&&(e.left!==r.left||e.top!==r.top));p(WEi({dot:r,tip:{width:a,height:o},gap:8,bounds:_Di(n),obstacles:s,lines:vDi(n)}))},[c,h]);let C=yDi[f];return(0,K.jsxs)(`div`,{ref:u,"data-testid":`knowledge-page-dot`,"data-page-id":t.id,"data-page-type":g?`stand-in`:_?`group`:t.isScope?`scope`:`page`,"aria-label":S,className:`relative cursor-pointer transition-opacity`,style:{width:n,height:n,opacity:g?.5:void 0},onPointerEnter:()=>l(!0),onPointerLeave:()=>l(!1),children:[(0,K.jsx)(`span`,{"aria-hidden":!0,"data-testid":`knowledge-dot-hit-area`,className:`absolute rounded-full`,style:{inset:-8}}),(0,K.jsx)(`div`,{className:`size-full rounded-full border`,style:{background:g?`transparent`:r??`var(--muted-foreground)`,borderColor:r??`var(--muted-foreground)`,borderStyle:g?`dashed`:`solid`},children:e.showCount&&!g&&!_&&o&&o.in+o.out>0?(0,K.jsx)(T,{as:`span`,variant:`meta`,"data-testid":`knowledge-dot-count`,className:`flex size-full items-center justify-center`,style:{color:`var(--background)`},children:o.in+o.out}):null}),c?(0,K.jsxs)(`div`,{role:`tooltip`,ref:d,"data-side":f,className:`pointer-events-none absolute ${C.tip} flex w-max max-w-72 flex-col rounded-md border border-border bg-card px-2 py-1 shadow-overlay`,style:{transform:`${C.transform} scale(${h})`,transformOrigin:C.origin},children:[(0,K.jsx)(`span`,{"data-testid":`knowledge-tooltip-tail`,"aria-hidden":!0,className:`absolute size-2 rotate-45 border-border bg-card ${C.tail}`}),v?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`ink`,children:t.name}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:(0,K.jsxs)(AC,{children:[_&&(0,K.jsx)(AC.Item,{children:i}),(0,K.jsx)(AC.Item,{children:v})]})})]}):(0,K.jsx)(v1n,{name:t.name,kind:b,pageRef:a,path:i,childCount:t.childCount?_9(t):void 0,links:o,notShown:s})]}):null,(0,K.jsx)(fO,{type:`target`,position:ED.Top,className:`!invisible`}),(0,K.jsx)(fO,{type:`source`,position:ED.Bottom,className:`!invisible`})]})}var SDi=96,CDi=.74;function wDi({data:e}){if(e.form===`dot`)return(0,K.jsx)(xDi,{data:e});let{page:t,size:n,selected:r,pinned:i,badge:a}=e,o=b9(t),s=t.isScope?t.displayLabel??`Scope`:`Page`,c=EDi(t),l=y9(t),u=n<SDi,d=Math.max(4,Math.floor(n*CDi/(u?6.5:7.5))),f=TDi(e,s);return(0,K.jsxs)(`div`,{"data-testid":`knowledge-page-node`,"data-page-id":t.id,"data-page-type":c?`placeholder`:l?`rest`:o?`group`:t.isScope?`scope`:`page`,className:`relative transition-opacity ${c?`cursor-default`:`cursor-pointer`}`,style:{width:n,height:n},"aria-label":f,children:[(0,K.jsx)(C9,{label:f,children:(0,K.jsxs)(`div`,{className:`knowledge-circle flex size-full flex-col items-center justify-center gap-0.5 overflow-hidden rounded-full border-2 text-center shadow-raised ${l?`hover:border-foreground`:``}`,"data-selected":r||void 0,"data-far":e.far||void 0,style:{...c||l?fDi:e.far?XEi:t.isScope?qEi:JEi,paddingInline:.26/2*n},children:[e.far?null:(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:t.isScope?void 0:`muted`,className:`pointer-events-none inline-flex max-w-full items-center justify-center gap-1 whitespace-nowrap uppercase`,style:t.isScope?{color:`var(--chart-blue)`}:void 0,"data-testid":t.isScope?`knowledge-scope-caption`:`knowledge-page-caption`,children:[e.level?(0,K.jsx)(bDi,{level:e.level}):null,(0,K.jsx)(`span`,{className:`truncate`,children:l?`More`:e.isParent?`Parent`:s})]}),(0,K.jsx)(T,{as:`span`,variant:u?`meta`:`label`,tone:`ink`,className:`pointer-events-none max-w-full overflow-hidden [overflow-wrap:normal] ${u?`line-clamp-2`:`line-clamp-3`}`,style:e.far?{color:`var(--background)`}:void 0,"data-testid":`knowledge-circle-name`,children:(0,K.jsx)(DDi,{text:FTi(S9(t),d)})})]})}),i?(0,K.jsx)(ODi,{size:n}):null,e.hiddenLinks&&(e.hiddenLinks.in>0||e.hiddenLinks.out>0)?(0,K.jsx)(C9,{label:_X(e.hiddenLinks),children:(0,K.jsxs)(`span`,{"data-testid":`knowledge-hidden-links`,"aria-label":_X(e.hiddenLinks),className:`absolute bottom-full left-1/2 -mb-1 flex -translate-x-1/2 gap-1 rounded-full border border-border bg-card px-1.5 shadow-raised`,children:[e.hiddenLinks.in>0?(0,K.jsxs)(T,{as:`span`,variant:`meta`,style:{color:`var(--chart-orange)`},children:[`→`,e.hiddenLinks.in]}):null,e.hiddenLinks.out>0?(0,K.jsxs)(T,{as:`span`,variant:`meta`,style:{color:j9},children:[e.hiddenLinks.out,`→`]}):null]})}):null,a?(0,K.jsx)(C9,{label:`${a} children, not all drawn`,children:(0,K.jsx)(`span`,{"data-testid":`knowledge-child-count-badge`,"aria-label":`${a} children, not all drawn`,className:`absolute top-full left-1/2 -mt-1 -translate-x-1/2 rounded-full border border-border bg-card px-1.5 shadow-raised`,children:(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`ink`,children:a})})}):null,(0,K.jsx)(fO,{type:`target`,position:ED.Top,className:`!invisible`}),(0,K.jsx)(fO,{type:`source`,position:ED.Bottom,className:`!invisible`})]})}function TDi(e,t){let{page:n,links:r,notShown:i}=e;if(EDi(n))return`${t}: ${n.address}. Nothing written to it yet.`;if(y9(n))return`Show ${Math.min(12,n.childCount??12)} more of ${n.childCount??`the rest`}`;if(b9(n))return`${n.name}: click to show them`;if(n.isScope&&n.address){let e=S9(n);return e===n.address?`${t}: ${e}`:`${t}: ${e} (${n.address})`}return r&&r.in+r.out>0?`${n.name}: ${_X(r,i)}`:n.name}function EDi(e){return e.id.startsWith(`unplaced:`)}function DDi({text:e}){let t=e.split(`:`);return(0,K.jsx)(K.Fragment,{children:t.map((e,n)=>(0,K.jsxs)(G.Fragment,{children:[e,n<t.length-1?(0,K.jsxs)(K.Fragment,{children:[`:`,(0,K.jsx)(`wbr`,{})]}):null]},n))})}function ODi({size:e}){let{badge:t,style:n}=pDi(e);return(0,K.jsx)(`span`,{"data-testid":`knowledge-pin-badge`,className:`absolute flex items-center justify-center rounded-full bg-badge-amber-strong text-badge-amber-foreground shadow-raised`,style:n,"aria-label":`Pinned`,children:(0,K.jsx)(DX,{size:Math.round(t*.6),"aria-hidden":!0})})}function kDi(e,t,n=3){let r=t.x-e.x,i=t.y-e.y,a=Math.hypot(r,i)||1,o=r/a,s=i/a;return{x1:e.x+o*(e.r+n),y1:e.y+s*(e.r+n),x2:t.x-o*(t.r+n),y2:t.y-s*(t.r+n)}}function ADi({id:e,data:t,style:n,markerEnd:r}){if(!t)return null;let{x1:i,y1:a,x2:o,y2:s}=kDi(t.from,t.to),c=t.kind===`mention`,l=`M ${i} ${a} L ${o} ${s}`;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(mO,{id:e,path:l,style:n,markerEnd:r,interactionWidth:c?20:0}),t.kind===`grant`&&t.role?(0,K.jsx)(`path`,{d:l,fill:`none`,stroke:`transparent`,strokeWidth:14,"data-testid":`knowledge-grant-edge`,"data-role":t.role,"aria-label":`Grants ${t.role}`,children:(0,K.jsx)(`title`,{children:`Grants ${t.role}`})}):null]})}var jDi={rim:(0,G.memo)(ADi)},MDi={page:(0,G.memo)(wDi)};function NDi(e){if(e.length===0)return null;let t=1/0,n=1/0,r=-1/0,i=-1/0;for(let a of e)t=Math.min(t,a.position.x),n=Math.min(n,a.position.y),r=Math.max(r,a.position.x+(a.width??0)),i=Math.max(i,a.position.y+(a.height??0));return{x:t,y:n,width:r-t,height:i-n}}var PDi=`knowledge-circle inline-block size-3 shrink-0 rounded-full border-2`;function FDi({drawn:e,counts:t,dots:n,linkEnds:r,focused:i,levels:a,branches:o,collapsible:s}){let[c,l]=(0,G.useState)(!s),[u,d]=(0,G.useState)(!1),f=c||u;return(0,K.jsxs)(`div`,{className:`absolute top-3 left-3 z-10 flex translate-x-(--knowledge-pane-left) flex-col items-start gap-1.5 transition-transform duration-slow ease-out-custom motion-reduce:transition-none`,onPointerEnter:s?()=>d(!0):void 0,onPointerLeave:s?()=>d(!1):void 0,children:[s?(0,K.jsx)(X,{size:`sm`,icon:(0,K.jsx)(Yx,{}),"aria-expanded":f,className:`shadow-overlay`,onFocus:()=>d(!0),onBlur:()=>d(!1),onClick:()=>{l(e=>!e),d(!1)},children:`Legend`}):null,(0,K.jsxs)(`ul`,{"aria-label":`Legend`,hidden:s&&!f,className:`pointer-events-none flex flex-col gap-1 rounded-lg px-2.5 py-2 ${s?`bg-card shadow-overlay`:`rounded-md border border-border bg-card/90 shadow-raised`}`,children:[(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`span`,{className:PDi,style:{...qEi},"aria-hidden":!0}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Scope`})]}),a.includes(`scope`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-level-scope`,children:[(0,K.jsx)(nC,{"aria-hidden":!0,className:`size-icon-xs shrink-0 text-muted-foreground`}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Scope, above its pages`})]}):null,a.includes(`ancestor`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-level-ancestor`,children:[(0,K.jsx)(GEi,{"aria-hidden":!0,className:`size-icon-xs shrink-0 text-muted-foreground`}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Page above the focus`})]}):null,(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`span`,{className:PDi,style:{...JEi},"aria-hidden":!0}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Page`})]}),i?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-focused`,children:[(0,K.jsx)(`span`,{className:PDi,style:{...JEi,borderWidth:3},"aria-hidden":!0}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Focused page`})]}):null,n||r?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-dot`,children:[(0,K.jsx)(`span`,{className:`inline-block size-2 shrink-0 rounded-full bg-muted-foreground`,"aria-hidden":!0}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Page in another branch`})]}):null,o.slice(0,VDi).map(e=>(0,K.jsxs)(`li`,{className:`flex items-center gap-2 pl-0.5`,"data-testid":`knowledge-legend-branch`,children:[(0,K.jsx)(`span`,{className:`inline-block size-2 shrink-0 rounded-full`,style:{background:e.color},"aria-hidden":!0}),(0,K.jsx)(C9,{label:e.name,children:(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`pointer-events-auto max-w-40 truncate`,children:o.length>1?`Under ${e.name}`:e.scope?`Under parent scope`:`Under parent page`})})]},e.id)),o.length>VDi?(0,K.jsx)(`li`,{className:`pl-0.5`,children:(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,children:[`+`,o.length-VDi,` more branches`]})}):null,e.has(`out`)||e.has(`in`)?(0,K.jsxs)(K.Fragment,{children:[e.has(`out`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-out`,children:[(0,K.jsxs)(`svg`,{width:`16`,height:`8`,"aria-hidden":!0,className:`shrink-0`,children:[(0,K.jsx)(`line`,{x1:`0`,y1:`4`,x2:`12`,y2:`4`,stroke:j9,strokeWidth:`1.5`}),(0,K.jsx)(`polygon`,{points:`11,1 16,4 11,7`,fill:j9})]}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Links out of the selected page`})]}):null,e.has(`in`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-in`,children:[(0,K.jsxs)(`svg`,{width:`16`,height:`8`,"aria-hidden":!0,className:`shrink-0`,children:[(0,K.jsx)(`line`,{x1:`0`,y1:`4`,x2:`12`,y2:`4`,stroke:`var(--chart-orange)`,strokeWidth:`1.5`,strokeDasharray:`3 2`}),(0,K.jsx)(`polygon`,{points:`11,1 16,4 11,7`,fill:`var(--chart-orange)`})]}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Links into it`})]}):null]}):null,e.has(`mention`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-mention`,children:[(0,K.jsx)(`svg`,{width:`12`,height:`4`,"aria-hidden":!0,className:`shrink-0`,children:(0,K.jsx)(`line`,{x1:`0`,y1:`2`,x2:`12`,y2:`2`,stroke:tDi,strokeWidth:`2`})}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Mentioned in notes`})]}):null,e.has(`link`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,children:[(0,K.jsxs)(`svg`,{width:`16`,height:`8`,"aria-hidden":!0,className:`shrink-0`,"data-testid":`knowledge-legend-link`,children:[(0,K.jsx)(`line`,{x1:`0`,y1:`4`,x2:`12`,y2:`4`,...sDi}),(0,K.jsx)(`polygon`,{points:`11,1 16,4 11,7`,fill:j9})]}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Linked in page body`})]}):null,e.has(`dot-parent`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-dot-parent`,children:[(0,K.jsx)(`svg`,{width:`16`,height:`4`,"aria-hidden":!0,className:`shrink-0`,children:(0,K.jsx)(`line`,{x1:`0`,y1:`2`,x2:`16`,y2:`2`,...dDi,strokeOpacity:.5})}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Child page (dot)`})]}):null,e.has(`up`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-up`,children:[(0,K.jsxs)(`svg`,{width:`16`,height:`8`,"aria-hidden":!0,className:`shrink-0`,children:[(0,K.jsx)(`line`,{x1:`0`,y1:`4`,x2:`12`,y2:`4`,...$Ei}),(0,K.jsx)(`polygon`,{points:`9,1 15,4 9,7`,fill:QEi})]}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Parent of the focused page`})]}):null,e.has(`parent`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,children:[(0,K.jsxs)(`svg`,{width:`16`,height:`8`,"aria-hidden":!0,className:`shrink-0`,"data-testid":`knowledge-legend-parent-arrow`,children:[(0,K.jsx)(`line`,{x1:`0`,y1:`4`,x2:`14`,y2:`4`,...ZEi,strokeDasharray:`3 2`}),(0,K.jsx)(`polyline`,{points:`10,1 14,4 10,7`,fill:`none`,stroke:nDi,strokeWidth:`1.25`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Parent → child`})]}):null,t?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-link-counts`,children:[(0,K.jsx)(T,{as:`span`,variant:`meta`,style:{color:`var(--chart-orange)`},children:`→4`}),(0,K.jsx)(T,{as:`span`,variant:`meta`,style:{color:j9},children:`14→`}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Links in, links out (not drawn)`})]}):null,e.has(`grant`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,children:[(0,K.jsxs)(`svg`,{width:`16`,height:`8`,"aria-hidden":!0,className:`shrink-0`,"data-testid":`knowledge-legend-grant`,children:[(0,K.jsx)(`line`,{x1:`0`,y1:`4`,x2:`12`,y2:`4`,...aDi,strokeDasharray:`4 2 1 2`,strokeWidth:`1.5`}),(0,K.jsx)(`polygon`,{points:`11,1 16,4 11,7`,fill:iDi})]}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Grants access (hover for role)`})]}):null,(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`span`,{className:`flex size-3 shrink-0 items-center justify-center rounded-full bg-badge-amber-strong text-badge-amber-foreground [&>svg]:size-2`,"aria-hidden":!0,children:(0,K.jsx)(DX,{})}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Pinned`})]})]})]})}var IDi=4,LDi=`knowledge-neighbour`;function RDi(e){let t=(0,G.useRef)(new Map);return(0,G.useMemo)(()=>{let n=new Map,r=e.map(e=>{let r=JSON.stringify(e),i=t.current.get(e.id),a=i&&i.sig===r?i:{sig:r,edge:e};return n.set(e.id,a),a.edge});return t.current=n,r},[e])}var zDi=1.2,BDi=.8,VDi=4,HDi=40;function UDi(e){let{settled:t=!0}=e,n=(0,G.useRef)(e),[r,i]=(0,G.useState)(!1),a=!t&&!r;a||(n.current=e);let o=a?{...e,pages:n.current.pages,edges:n.current.edges,pinnedIds:n.current.pinnedIds,grants:n.current.grants,selectedPageId:n.current.selectedPageId,centerId:n.current.centerId,hiddenLinks:n.current.hiddenLinks,knownLinks:n.current.knownLinks,nearIds:n.current.nearIds}:e,[s,c]=(0,G.useState)(!1);return(0,G.useEffect)(()=>{if(t){c(!1),i(!1);return}let e=setTimeout(()=>c(!0),mDi),n=setTimeout(()=>i(!0),hDi);return()=>{clearTimeout(e),clearTimeout(n)}},[t,e.selectedPageId]),(0,K.jsxs)(hO,{children:[(0,K.jsx)(WDi,{...o}),s&&a?(0,K.jsx)(`p`,{role:`status`,"data-testid":`knowledge-graph-loading`,className:`pointer-events-none absolute bottom-3 left-1/2 z-10 -translate-x-1/2 rounded border border-border bg-card px-3 py-1 text-body-sm text-muted-foreground shadow-overlay`,children:`Loading pages…`}):null]})}function WDi({pages:e,edges:t,pinnedIds:n=[],grants:r,selectedPageId:i,centerId:a,hiddenLinks:o,knownLinks:s,nearIds:c,exactLinkCounts:l,fetchedLinks:u,onHover:d,showCounts:f,onPreview:p,onSelect:m,onOpen:h,onClearSelection:g,onMentionSelect:_,insets:v=KEi,collapsibleLegend:y}){let{graphPages:b,allEdges:x}=(0,G.useMemo)(()=>{let n=IEi(e,r);return{graphPages:n.placeholders.length?[...e,...n.placeholders]:e,allEdges:[...PEi(e,t),...n.edges]}},[e,t,r]),S=s??t,C=(0,G.useMemo)(()=>{let e=new Map,t=new Set;for(let n of S){if(n.kind!==`mention`&&n.kind!==`link`||n.source===n.target||t.has(`${n.source}\u0000${n.target}`))continue;t.add(`${n.source}\u0000${n.target}`);let r=e.get(n.source)??{in:0,out:0};r.out++,e.set(n.source,r);let i=e.get(n.target)??{in:0,out:0};i.in++,e.set(n.target,i)}for(let[t,n]of l??[])e.set(t,n);return e},[S,l]),w=(0,G.useMemo)(()=>{let e=new Map,t=(t,n)=>{let r=e.get(t);r?r.push(n):e.set(t,[n])};for(let e of[...S,...u??[]])(e.kind===`mention`||e.kind===`link`)&&(t(e.source,e),e.target!==e.source&&t(e.target,e));return e},[S,u]),E=(0,G.useMemo)(()=>{let e=Awi(b,i??a??null,c),t=Bwi(b,e),n=zEi(b,x);for(let t of n.nodes)if(e.form.get(t.id)===`dot`){let e=C.get(t.id),n=f&&!v9(t.data.page)&&!!e&&e.in+e.out>0;t.data.size=n?28:20}else t.id===e.center?t.data.size=Math.round(t.data.size*zDi):t.data.size=Math.round(108*(e.linked.has(t.id)?BDi:1));let r=n.nodes.filter(t=>e.depth.get(t.id)===1&&e.form.get(t.id)===`full`),o=Uwi(r.length);if(o<1)for(let e of r)e.data.size=Math.round(e.data.size*o);let s=new Map(n.nodes.map(e=>[e.id,e.data.size])),l=Rwi(b,e,e=>s.get(e.id)??20,c),u=MEi(n.nodes.map(t=>({id:t.id,size:t.data.size,padding:e.form.get(t.id)===`dot`?4:24,initial:l.get(t.id)})),[],{ticks:0});return{nodes:n.nodes,edges:n.edges,positions:u,shape:e,colors:t}},[b,x,i,a,C,f,c]),D=(0,G.useMemo)(()=>new Map(b.map(e=>[e.id,e])),[b]),O=(0,G.useMemo)(()=>{let e=E.shape.center?D.get(E.shape.center)?.parentId:void 0;return e&&E.positions.has(e)?e:null},[E,D]),k=(0,G.useMemo)(()=>{let e=new Set;for(let[t,n]of E.shape.level)E.shape.form.get(t)===`full`&&e.add(n);return[...e]},[E]),A=(0,G.useMemo)(()=>{let e=new Map;for(let t of E.nodes){if(E.shape.form.get(t.id)!==`dot`||v9(t.data.page))continue;let n=E.shape.branch.get(t.id),r=n?E.colors.get(n):void 0,i=n?D.get(n):void 0;n&&r&&i&&!e.has(n)&&e.set(n,{id:n,name:i.displayLabel??S9(i),color:r,scope:!!i.isScope})}return[...e.values()]},[E,D]),j=(0,G.useMemo)(()=>new Set(n),[n]),M=(0,G.useMemo)(()=>{let e=new Map;for(let t of b)t.parentId&&!v9(t)&&!y9(t)&&e.set(t.parentId,(e.get(t.parentId)??0)+1);return new Set(b.filter(t=>!b9(t)&&!y9(t)&&(t.childCountCapped||(t.childCount??0)>(e.get(t.id)??0))).map(e=>e.id))},[b]),[N,P]=(0,G.useState)(null);(0,G.useEffect)(()=>d?.(N),[N,d]);let F=(0,G.useMemo)(()=>{if(!N)return[];let e=new Set(E.nodes.map(e=>e.id)),t=new Set(E.edges.map(e=>e.id)),n=[];for(let r of w.get(N)??[]){let i=`${r.kind}:${r.source}->${r.target}`;if(!t.has(i)&&e.has(r.source)&&e.has(r.target)&&(t.add(i),n.push({id:i,source:r.source,target:r.target,data:{kind:r.kind,count:r.count??1}}),n.length>=HDi))break}return n},[N,w,E]),I=(0,G.useMemo)(()=>{let e=N?C.get(N):void 0;if(!N||!e)return 0;let t=new Set;for(let e of[...E.edges,...F]){let n=e.data?.kind;n!==`mention`&&n!==`link`||e.source!==N&&e.target!==N||t.add(`${e.source}\u0000${e.target}`)}return Math.max(0,e.in+e.out-t.size)},[N,C,E,F]),L=N&&E.positions.has(N)?N:i??null,R=(0,G.useMemo)(()=>L&&E.positions.has(L)?REi(L,[...x,...F.map(e=>({kind:e.data?.kind??`link`,source:e.source,target:e.target}))]):null,[L,E,x,F]),z=(0,G.useMemo)(()=>E.nodes.map(e=>{let t=E.positions.get(e.id)??{x:0,y:0};return{...e,width:e.data.size,height:e.data.size,handles:[{type:`target`,position:ED.Top,x:e.data.size/2,y:0,width:1,height:1},{type:`source`,position:ED.Bottom,x:e.data.size/2,y:e.data.size,width:1,height:1}],position:{x:t.x-e.data.size/2,y:t.y-e.data.size/2},data:{...e.data,selected:e.id===i,pinned:j.has(e.id),form:E.shape.form.get(e.id)??`full`,color:E.colors.get(E.shape.branch.get(e.id)??``),badge:M.has(e.id)?_9(e.data.page):void 0,path:Qwi(e.data.page,D),hiddenLinks:E.shape.form.get(e.id)===`full`?o?.get(e.id):void 0,ref:$wi(e.data.page,D),links:C.get(e.id),showCount:f,level:E.shape.form.get(e.id)===`full`?E.shape.level.get(e.id):void 0,isParent:e.id===O,far:E.shape.linked.has(e.id)||void 0}}}),[E,i,j,M,D,o,C,f,O]),{flowEdges:B,drawnEdgeStyles:V}=(0,G.useMemo)(()=>{let e=new Set,t=new Map(E.nodes.map(e=>[e.id,e.data.size])),n=e=>({...E.positions.get(e)??{x:0,y:0},r:(t.get(e)??0)/2});return{flowEdges:[...E.edges,...F].map(t=>{let r=t.data?.kind===`mention`,i=t.data?.kind===`grant`,a=t.data?.kind===`link`,o=E.shape.form.get(t.target)===`dot`,s=(r||a)&&L?t.source===L?`out`:t.target===L?`in`:void 0:void 0,c=!r&&!i&&!a&&t.source===O&&t.target===E.shape.center;return e.add(s??(c?`up`:r?`mention`:i?`grant`:a?`link`:o?`dot-parent`:`parent`)),{...t,type:`rim`,data:{kind:t.data?.kind??`parent`,count:t.data?.count??1,...t.data?.role?{role:t.data.role}:{},from:n(t.source),to:n(t.target)},...s===`in`?{zIndex:1}:{},...r&&_?{className:`cursor-pointer`}:{},style:s?{...lDi[s],strokeWidth:r?2:1.5}:r?{stroke:tDi,strokeWidth:Math.min(1.5+(t.data?.count??1)*.5,4)}:c?$Ei:i?aDi:a?sDi:o?dDi:ZEi,markerEnd:s?uDi[s]:c?eDi:r?{type:TD.ArrowClosed,color:tDi,width:14,height:14}:i?oDi:a?cDi:o?void 0:rDi}}),drawnEdgeStyles:e}},[E,F,_,L,O]),H=RDi(B),ee=(0,G.useMemo)(()=>z.map(e=>{let t=R?.has(e.id),n=e.id===N&&I>0;return!t&&!n?e:{...e,...t?{className:LDi}:{},...n?{data:{...e.data,notShown:I}}:{}}}),[z,R,N,I]),te=(0,G.useMemo)(()=>R?H.map(e=>R.has(e.source)&&R.has(e.target)?{...e,className:[e.className,LDi].filter(Boolean).join(` `)}:e):H,[H,R]),U=(0,G.useMemo)(()=>new Map(e.map(e=>[e.id,e])),[e]),W=uO(),ne=(0,G.useRef)(null),re=z.length>0,ie=ITi(ee,T9()),ae=E.shape.linked,oe={"--knowledge-pane-left":`${v.left}px`},se=(0,G.useRef)({nodes:z,selectedPageId:i,centerId:a,reactFlow:W,linkedIds:ae,insets:v});se.current={nodes:z,selectedPageId:i,centerId:a,reactFlow:W,linkedIds:ae,insets:v};let ce=(0,G.useRef)(!1),le=()=>{let e=ne.current,t=e?.clientWidth??0,n=e?.clientHeight??0;if(t===0||n===0)return ce.current=!0,null;ce.current=!1;let{nodes:r,reactFlow:i}=se.current,a=NDi(r);return a?{container:e,width:t,height:n,current:r,flow:i,bounds:a}:null},ue=(0,G.useCallback)(e=>{let t=le();if(!t)return;let{selectedPageId:n,centerId:r,linkedIds:i,insets:a}=se.current,o=t.current.find(e=>e.id===(n??r)),s=!!n&&t.current.some(e=>i.has(e.id)),c=BTi({bounds:t.bounds,width:t.width,height:t.height,ring:s,anchor:o,insets:a});t.flow.setViewport(c,e?{duration:e}:void 0)},[]),de=(0,G.useCallback)(()=>{let e=le();if(!e)return;let t=e.container?.getBoundingClientRect(),n=e.container?.querySelector(`[aria-label="Legend"]`)?.getBoundingClientRect(),r=UTi({bounds:e.bounds,nodes:e.current.map(e=>({x:e.position.x,y:e.position.y,width:e.width??0,height:e.height??0})),width:e.width,height:e.height,legend:t&&n?{right:n.right-t.left+8,bottom:n.bottom-t.top+8}:void 0,insets:se.current.insets});e.flow.setViewport(r)},[]),fe=(0,G.useCallback)(e=>{let t=ne.current,n=t?.clientWidth??0,r=t?.clientHeight??0,{nodes:i,selectedPageId:a,centerId:o,reactFlow:s,insets:c}=se.current,l=i.find(e=>e.id===(a??o));if(!l||n===0||r===0)return;let u=zTi(n,c),d=s.getViewport(),f=WTi(l.position.x*d.zoom+d.x-u.left,(l.width??0)*d.zoom,n-u.left-u.right),p=WTi(l.position.y*d.zoom+d.y,(l.height??0)*d.zoom,r);(f!==0||p!==0)&&s.setViewport({zoom:d.zoom,x:d.x+f,y:d.y+p},e?{duration:e}:void 0)},[]);(0,G.useEffect)(()=>{let e=ne.current;if(!e||typeof ResizeObserver>`u`)return;let t={width:e.clientWidth,height:e.clientHeight},n,r=!1,i=new ResizeObserver(([e])=>{if(!e)return;let{width:i,height:a}=e.contentRect,o=i!==t.width||a!==t.height;(t.width===0||t.height===0)&&(r=!0),t={width:i,height:a},(o||ce.current)&&i!==0&&a!==0&&(n!==void 0&&cancelAnimationFrame(n),n=requestAnimationFrame(()=>{n=void 0,r||ce.current?(r=!1,de()):fe()}))});return i.observe(e),()=>{i.disconnect(),n!==void 0&&cancelAnimationFrame(n)}},[re,de,fe]);let pe=(0,G.useRef)(null),me=!!i&&U.has(i),he=(0,G.useRef)(!1);(0,G.useEffect)(()=>{he.current&&fe(E9(T9()))},[v.left,v.right,fe]);let ge=(0,G.useRef)(0),_e=(0,G.useRef)(null),ve=(0,G.useRef)(``),ye=(0,G.useCallback)(()=>{ge.current=0},[]);(0,G.useEffect)(()=>{if(!he.current||((i??null)!==_e.current&&(ge.current=0),Date.now()>=ge.current))return;let e=z.map(e=>`${e.id}@${e.position.x},${e.position.y}`).join(`|`);e!==ve.current&&(ve.current=e,de())},[z,i,de]),(0,G.useEffect)(()=>{if(!he.current||!me||!i)return;let e=pe.current===i;pe.current=null,e||fe(E9(T9()))},[i,me,fe]);let be=e=>{if(v9(e)||b9(e)||y9(e))return m(e);if(e.id===i&&h)return h(e);pe.current=e.id,m(e)},xe=(0,G.useRef)(null),Se=e=>{if(e.key!==`Enter`&&e.key!==` `)return;let t=e.target.closest(`.react-flow__node`)?.dataset.id,n=t?U.get(t):void 0;n&&(e.preventDefault(),be(n))},Ce=(0,G.useRef)({activate:be,onPreview:p,onMentionSelect:_,onClearSelection:g,laidOut:E,pagesById:U});Ce.current={activate:be,onPreview:p,onMentionSelect:_,onClearSelection:g,laidOut:E,pagesById:U};let we=(0,G.useCallback)((e,t)=>{P(t.id),Ce.current.laidOut.shape.form.get(t.id)===`dot`&&Ce.current.onPreview?.(t.data.page)},[]),Te=(0,G.useCallback)(()=>P(null),[]),Ee=(0,G.useCallback)((e,t)=>{EDi(t.data.page)||Ce.current.activate(t.data.page)},[]),De=(0,G.useCallback)((e,t)=>{let{onMentionSelect:n,pagesById:r}=Ce.current;if(t.data?.kind!==`mention`||!n)return;let i=r.get(t.source),a=r.get(t.target);if(!i||!a)return;let o=ne.current?.getBoundingClientRect();n({source:i,target:a,point:{x:e.clientX-(o?.left??0),y:e.clientY-(o?.top??0)},pane:{width:o?.width??0,height:o?.height??0}})},[]),Oe=(0,G.useCallback)(e=>{let t=xe.current;xe.current=null,t&&Math.hypot(e.clientX-t.x,e.clientY-t.y)>IDi||Ce.current.onClearSelection?.()},[]);return re?(0,K.jsxs)(`div`,{ref:ne,style:oe,className:`knowledge-graph relative size-full`,"data-emphasis":R?`on`:void 0,"data-testid":`knowledge-page-graph`,onKeyDown:Se,onWheelCapture:ye,onPointerDownCapture:e=>{ye(),xe.current={x:e.clientX,y:e.clientY}},children:[(0,K.jsx)(FDi,{collapsible:y,branches:A,levels:k,focused:!!i&&E.positions.has(i),dots:[...E.shape.form.values()].includes(`dot`),linkEnds:E.shape.linked.size>0,drawn:V,counts:[...o??[]].some(([e,t])=>E.shape.form.get(e)===`full`&&(t.in>0||t.out>0))}),(0,K.jsx)(Bct,{nodes:ie,edges:te,nodeTypes:MDi,edgeTypes:jDi,onInit:()=>{he.current=!0,ge.current=Date.now()+HTi,_e.current=se.current.selectedPageId??null,ve.current=se.current.nodes.map(e=>`${e.id}@${e.position.x},${e.position.y}`).join(`|`),de()},minZoom:.1,proOptions:{hideAttribution:!0},nodesConnectable:!1,nodesDraggable:!1,onPaneClick:Oe,onNodeMouseEnter:we,onNodeMouseLeave:Te,onNodeClick:Ee,onEdgeClick:De,children:(0,K.jsx)($ct,{variant:gO.Dots,gap:26,size:1.4,color:`var(--border-strong)`})}),(0,K.jsx)(`div`,{className:`absolute bottom-3 left-3 z-10 translate-x-(--knowledge-tree-drawer-inset,0px) transition-transform duration-slow ease-out-custom motion-reduce:transition-none`,children:(0,K.jsxs)($V,{size:`sm`,"aria-label":`Zoom`,"data-knowledge-graph-zoom":!0,className:`rounded-full shadow-overlay`,children:[(0,K.jsx)(X,{size:`icon-sm`,tooltip:`Zoom out`,"aria-label":`Zoom out`,onClick:()=>void W.zoomOut({duration:E9(T9())}),children:(0,K.jsx)(A6e,{})}),(0,K.jsx)(X,{size:`icon-sm`,tooltip:`Zoom in`,"aria-label":`Zoom in`,onClick:()=>void W.zoomIn({duration:E9(T9())}),children:(0,K.jsx)(Hx,{})}),(0,K.jsx)(X,{size:`icon-sm`,tooltip:`Fit view`,"aria-label":`Fit view`,onClick:()=>ue(E9(T9())),children:(0,K.jsx)(k6e,{})})]})})]}):(0,K.jsx)(`div`,{className:`flex h-full items-center justify-center p-6`,children:(0,K.jsx)(T,{variant:`body`,tone:`muted`,children:`No pages yet.`})})}function GDi(e){let t;for(let n=e;n;n=n.parentElement){let{overflowY:e}=getComputedStyle(n);if(e===`auto`||e===`scroll`||e===`overlay`){if(n.scrollHeight>n.clientHeight)return n.getBoundingClientRect();t??=n}}return(t??e)?.getBoundingClientRect()}var KDi=1/3,qDi=.1,JDi=.7;function YDi({pages:e,pinnedIds:t,selectedPageId:n,onSelect:r,initiallyExpanded:i,mayHaveChildren:a,onExpandedChange:o,loadMore:s,"aria-label":l=`Knowledge pages`}){let u=(0,G.useMemo)(()=>Swi(e),[e]),d=(0,G.useMemo)(()=>new Set(t),[t]),[f,p]=(0,G.useState)(()=>new Set(i??u.map(e=>e.page.id))),[m,h]=(0,G.useState)(null),g=(0,G.useRef)(new Map),_=(0,G.useRef)(null);(0,G.useEffect)(()=>{if(!n){_.current=null;return}let t=wwi(e,n),r=[n,...t].join(`/`);_.current!==r&&(_.current=r,p(e=>t.every(t=>e.has(t))?e:new Set([...e,...t])))},[e,n]),(0,G.useEffect)(()=>{o?.(f)},[f,o]);let v=(0,G.useMemo)(()=>Cwi(u,f).map(e=>!e.hasChildren&&a?.(e.page)?{...e,hasChildren:!0}:e),[u,f,a]),b=(0,G.useRef)(null),x=(0,G.useRef)(null),S=(0,G.useRef)(!1);(0,G.useEffect)(()=>{if(!n){x.current=null;return}let e=g.current.get(n);if(!e)return;let t=x.current!==n;if(t)x.current=n,S.current=!1;else if(S.current)return;let r=GDi(b.current),i=e.getBoundingClientRect();if((t||r)&&!(!t&&r&&r.height===0&&i.top>=r.top&&i.bottom<=r.bottom)){if(r&&r.height>0){if(i.top>=r.top+r.height*qDi&&i.bottom<=r.top+r.height*JDi)return;e.style.scrollMarginTop=`${r.height*KDi}px`}e.scrollIntoView?.({block:`start`,behavior:t&&T9()?`smooth`:`auto`}),e.style.scrollMarginTop=``}},[v,n]);let C=m&&v.some(e=>e.page.id===m)?m:v.find(e=>e.page.id===n)?.page.id??v[0]?.page.id,w=(e,t)=>p(n=>{if(n.has(e)===t)return n;let r=new Set(n);return t?r.add(e):r.delete(e),r}),T=e=>{e&&(h(e),g.current.get(e)?.focus())},E=(e,t)=>{let n=v[t];if(n){switch(e.key){case`ArrowDown`:T(v[t+1]?.page.id);break;case`ArrowUp`:T(v[t-1]?.page.id);break;case`ArrowRight`:n.hasChildren&&!n.expanded?w(n.page.id,!0):n.expanded&&T(v[t+1]?.page.id);break;case`ArrowLeft`:n.expanded?w(n.page.id,!1):T(v.slice(0,t).findLast(e=>e.depth<n.depth)?.page.id);break;case`Enter`:case` `:r(n.page);break;default:return}e.preventDefault()}};if(v.length===0)return(0,K.jsx)(`p`,{className:`px-3 py-2 text-body text-muted-foreground`,children:`No pages yet.`});let D=[];return(0,K.jsx)(`div`,{ref:b,role:`tree`,"aria-label":l,className:`min-h-0 overflow-y-auto py-1`,onWheel:()=>S.current=!0,onTouchMove:()=>S.current=!0,onPointerDown:()=>S.current=!0,onKeyDown:()=>S.current=!0,children:v.map((e,t)=>{let i=e.page.id===n;D[e.depth]=e.page.id;let a=v[t+1]?.depth??-1,o=[];for(let t=e.depth-1;t>=a;t--){let e=t<0?``:D[t];e!==void 0&&o.push({parentId:e,depth:t+1})}return e.expanded&&v[t+1]?.depth!==e.depth+1&&o.unshift({parentId:e.page.id,depth:e.depth+1}),(0,K.jsxs)(G.Fragment,{children:[(0,K.jsxs)(`div`,{ref:t=>{t?g.current.set(e.page.id,t):g.current.delete(e.page.id)},role:`treeitem`,"aria-level":e.depth+1,"aria-selected":i,"aria-expanded":e.hasChildren?e.expanded:void 0,tabIndex:e.page.id===C?0:-1,onFocus:()=>h(e.page.id),onKeyDown:e=>E(e,t),onClick:()=>{r(e.page),e.hasChildren&&w(e.page.id,!0)},className:c(`flex h-8 cursor-pointer items-center gap-2 rounded-md pr-2 text-body-sm text-foreground outline-none focus-visible:bg-fill-subtle`,i?`bg-fill-hover`:`hover:bg-fill-subtle`),style:{paddingLeft:`${e.depth*12+4}px`},children:[e.hasChildren?(0,K.jsx)(`button`,{type:`button`,tabIndex:-1,"aria-label":e.expanded?`Collapse ${e.page.name}`:`Expand ${e.page.name}`,className:`flex size-3 shrink-0 items-center justify-center text-muted-foreground hover:text-foreground`,onClick:t=>{t.stopPropagation(),w(e.page.id,!e.expanded)},children:(0,K.jsx)(y,{direction:`right`,open:e.expanded,className:`size-3`})}):(0,K.jsx)(`span`,{className:`size-3 shrink-0`,"aria-hidden":!0}),(0,K.jsx)(`span`,{className:`flex shrink-0 items-center text-muted-foreground [&>svg]:size-icon-sm`,"aria-hidden":!0,children:Xwi(e.page)?.icon?(0,K.jsx)(yTi,{page:e.page}):e.hasChildren?(0,K.jsx)($N,{}):(0,K.jsx)(xk,{})}),(0,K.jsx)(`span`,{className:c(`min-w-0 flex-1 truncate`,e.page.isScope&&`font-medium`),children:S9(e.page)}),e.page.childCount?(0,K.jsx)(`span`,{"data-testid":`knowledge-tree-count`,"aria-label":`${_9(e.page)} below`,className:`shrink-0 text-caption text-placeholder tabular-nums`,children:_9(e.page)}):null,d.has(e.page.id)?(0,K.jsx)(DX,{className:`size-icon-xs shrink-0 text-badge-amber-indicator`,"aria-label":`Pinned`}):null,e.page.isScope&&e.page.address&&e.page.address!==e.page.name?(0,K.jsx)(`span`,{"data-testid":`knowledge-tree-address`,className:`max-w-1/2 min-w-0 truncate text-caption text-muted-foreground`,children:e.page.address}):null]}),o.map(({parentId:e,depth:t})=>{let n=s?.get(e);return n?(0,K.jsx)(`button`,{type:`button`,className:`flex h-8 w-full items-center text-left text-caption text-muted-foreground hover:text-foreground`,style:{paddingLeft:`${t*12+42}px`},onClick:n,children:`Load more`},`more-${e}`):null})]},e.page.id)})})}var XDi=U(`IconSidebarLeftArrow`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M4 6C4 4.89543 4.89543 4 6 4H18C19.1046 4 20 4.89543 20 6V18C20 19.1046 19.1046 20 18 20H6C4.89543 20 4 19.1046 4 18V6Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M9 4V20`,stroke:`currentColor`,strokeWidth:`2`}),(0,K.jsx)(`path`,{d:`M15.5 10L13.5 12L15.5 14`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]})),ZDi=U(`IconSidebarWideLeftArrow`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M15 10L13 12L15 14`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M3 7C3 5.89543 3.89543 5 5 5H19C20.1046 5 21 5.89543 21 7V17C21 18.1046 20.1046 19 19 19H5C3.89543 19 3 18.1046 3 17V7Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M8 5V12V19`,stroke:`currentColor`,strokeWidth:`2`})]})),QDi=/^[0-9A-Z]{26}$/,$Di=6e4,eOi=e=>Date.now()-Date.parse(e.createdAt)<$Di,tOi=2,nOi=40;function rOi(e){return`${e.kind}\u0000${e.source}\u0000${e.target}`}function iOi(e,t,n,r){let i=new Map;for(let t of e)t.source!==t.target&&!i.has(rOi(t))&&i.set(rOi(t),t);let a=new Map;for(let e of i.values())a.set(`${e.source}\u0000${e.target}`,e);let o=new Set,s={in:0,out:0};if(r)for(let[e,n]of i)t.has(n.source)&&t.has(n.target)&&o.add(e);else if(n){let e=new Set,r=new Set,a=0,c=0;for(let[l,u]of i){if(!t.has(u.source)||!t.has(u.target))continue;let i=u.source===n?`out`:u.target===n?`in`:null;if(!i)continue;let d=`${u.source}\u0000${u.target}`;!e.has(d)&&!r.has(d)&&((i===`out`?c:a)>=20?(r.add(d),s[i]++):(e.add(d),i===`out`?c++:a++)),e.has(d)&&o.add(l)}}let c=new Set([...o].map(e=>{let t=i.get(e);return`${t.source}\u0000${t.target}`})),l=new Map,u=(e,n)=>{if(!t.has(e))return;let r=l.get(e)??{in:0,out:0};r[n]++,l.set(e,r)};for(let[e,t]of a)c.has(e)||(u(t.source,`out`),u(t.target,`in`));return{edges:[...i.values()].filter(e=>o.has(rOi(e))),hidden:l,more:s}}function aOi(e,t){return t?`page`:e===`tree`?`tree`:`graph`}var oOi=296,sOi=44;function cOi(e,t){return e?t?oOi:sOi:0}var lOi=392,uOi=()=>[],dOi=[],fOi=()=>[],pOi=()=>({isPending:!1,isError:!1,error:null}),mOi=150;function hOi(e,t){let n=new Map,r=new Set;for(let e of t){if(e.kind===`parent`||r.has(`${e.source}\u0000${e.target}`))continue;r.add(`${e.source}\u0000${e.target}`);let t=n.get(e.source)??{in:0,out:0};t.out++,n.set(e.source,t);let i=n.get(e.target)??{in:0,out:0};i.in++,n.set(e.target,i)}let i=new Map;for(let[t,r]of e){let e=n.get(t)??{in:0,out:0};i.set(t,{in:Math.max(0,r.in-e.in),out:Math.max(0,r.out-e.out)})}return i}var gOi=()=>({isPending:!1,isError:!1,error:null});function _Oi(e){return!!e&&typeof e==`object`&&`status`in e&&e.status===404}function vOi(e,t){if(t.length===0)return e;let n=new Map(e);for(let e of t)n.set(e.id,e);return n}function yOi(e,t){if(!t)return e;let n=new Map(e.map(e=>[e.id,e])),r=new Map([[t,!0]]),i=e=>{let t=r.get(e.id);if(t!==void 0)return t;let a=e.parentId?n.get(e.parentId):void 0;r.set(e.id,!1);let o=!!a&&a.id!==e.id&&i(a);return r.set(e.id,o),o};return e.filter(i)}var bOi=[`w-32`,`w-24`,`w-40`,`w-28`,`w-36`,`w-20`];function xOi({label:e,rows:t}){return(0,K.jsx)(`div`,{role:`status`,"aria-label":e,className:`flex flex-col`,children:bOi.slice(0,t).map((e,t)=>(0,K.jsxs)(`div`,{className:`flex h-8 items-center gap-2 px-1`,style:{paddingLeft:`${t%3*12+4}px`},children:[(0,K.jsx)(zS,{className:`size-3.5 shrink-0`}),(0,K.jsx)(BS,{className:e})]},e))})}function SOi(){return(0,K.jsx)(`div`,{role:`status`,"aria-label":`Loading notes`,className:`flex flex-col gap-2`,children:[0,1].map(e=>(0,K.jsxs)(`div`,{className:`flex flex-col gap-2 rounded-lg border border-border p-3`,children:[(0,K.jsx)(BS,{className:`w-24`}),(0,K.jsx)(BS,{className:`w-full`}),(0,K.jsx)(BS,{className:`w-2/3`})]},e))})}function COi({compact:e}){return(0,K.jsxs)(`div`,{role:`status`,"aria-label":`Loading page`,className:`flex flex-col`,children:[(0,K.jsxs)(`div`,{className:`flex flex-col gap-2 border-b border-border ${e?`px-4 pt-3 pb-4`:`bg-fill-subtle px-6 pt-5 pb-4`}`,children:[(0,K.jsx)(BS,{line:`text-caption`,className:`w-28`}),e?null:(0,K.jsx)(BS,{line:`text-title`,className:`h-5 w-56`}),(0,K.jsx)(BS,{className:`w-72 max-w-full`}),(0,K.jsx)(BS,{line:`text-caption`,className:`w-40`})]}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-3 ${e?`p-4`:`p-6`}`,children:[(0,K.jsx)(BS,{className:`w-full max-w-3xl`}),(0,K.jsx)(BS,{className:`w-5/6 max-w-2xl`}),(0,K.jsx)(BS,{className:`w-2/3 max-w-xl`})]})]})}function wOi({onClick:e,label:t=`Load more`}){return(0,K.jsx)(`button`,{type:`button`,className:`self-start text-caption text-muted-foreground hover:text-foreground`,onClick:e,children:t})}function TOi({source:e,pageId:t,cursor:n,pagesById:r,onPageClick:i}){let a=e.usePage(t,n),[o,s]=(0,G.useState)(!1),c=(0,G.useMemo)(()=>vOi(r,a.data?.related??[]),[a.data,r]);if(a.isPending)return(0,K.jsx)(SOi,{});if(!a.data)return null;let l=a.data.notesNextCursor;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`ul`,{className:`flex flex-col gap-3`,children:a.data.notes.map(e=>(0,K.jsx)(NTi,{note:e,pagesById:c,onPageClick:i},e.id))}),l?o?(0,K.jsx)(TOi,{source:e,pageId:t,cursor:l,pagesById:r,onPageClick:i}):(0,K.jsx)(wOi,{label:`Load more notes`,onClick:()=>s(!0)}):null]})}function EOi({useTreeLevels:e,parentId:t,onOpen:n}){let[r,i]=(0,G.useState)([]),a=e((0,G.useMemo)(()=>[{parentId:t},...r.map(e=>({parentId:t,cursor:e}))],[t,r])),o=a.flatMap(e=>e.data?.pages??[]),s=a[a.length-1];if(a[0]?.isPending)return(0,K.jsx)(w9,{label:`Pages`,children:(0,K.jsx)(xOi,{label:`Loading pages`,rows:3})});let c=s?.data?.nextCursor;return o.length===0&&!c?null:(0,K.jsxs)(w9,{label:`Pages`,children:[(0,K.jsx)(`div`,{className:`rounded-xl p-1 ${Bv}`,children:(0,K.jsx)(N6,{className:`rounded-lg bg-background p-1`,onSelect:n,children:(0,K.jsx)(DOi,{pages:o,useTreeLevels:e,onOpen:n})})}),c?(0,K.jsx)(wOi,{onClick:()=>i(e=>[...e,c])}):null]})}function DOi({pages:e,useTreeLevels:t,onOpen:n}){return e.map(e=>e.childCount===0?(0,K.jsxs)(N6.File,{id:e.id,children:[(0,K.jsx)(N6.Icon,{className:`text-muted-foreground`,children:(0,K.jsx)(xk,{})}),(0,K.jsx)(OOi,{page:e})]},e.id):(0,K.jsx)(kOi,{page:e,useTreeLevels:t,onOpen:n},e.id))}function OOi({page:e}){return e.description?(0,K.jsx)(C9,{label:e.description,children:(0,K.jsx)(N6.Label,{children:e.name})}):(0,K.jsx)(N6.Label,{children:e.name})}function kOi({page:e,useTreeLevels:t,onOpen:n}){let[r,i]=(0,G.useState)(!1);return(0,K.jsxs)(N6.Folder,{id:e.id,open:r,onOpenChange:i,children:[(0,K.jsxs)(N6.FolderTrigger,{actions:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`Open ${e.name}`,"aria-label":`Open ${e.name}`,onClick:()=>n(e.id),children:(0,K.jsx)(oH,{})}),children:[(0,K.jsx)(N6.Icon,{className:`text-muted-foreground`,children:(0,K.jsx)($N,{})}),(0,K.jsx)(OOi,{page:e}),e.childCount?(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`ml-auto pl-2 tabular-nums`,children:e.childCount}):null]}),(0,K.jsx)(N6.FolderContent,{children:r?(0,K.jsx)(AOi,{parentId:e.id,useTreeLevels:t,onOpen:n}):null})]})}function AOi({parentId:e,useTreeLevels:t,onOpen:n}){let[r,i]=(0,G.useState)([]),a=t([{parentId:e},...r.map(t=>({parentId:e,cursor:t}))]),o=a.flatMap(e=>e.data?.pages??[]),s=a[a.length-1]?.data?.nextCursor;return a[0]?.isPending?(0,K.jsx)(`li`,{role:`none`,className:`pl-6`,children:(0,K.jsx)(xOi,{label:`Loading pages`,rows:2})}):a[0]?.isError?(0,K.jsx)(jOi,{children:`Couldn’t load the pages under this one.`}):o.length===0&&!s?(0,K.jsx)(jOi,{children:`No pages under this one.`}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(DOi,{pages:o,useTreeLevels:t,onOpen:n}),s?(0,K.jsx)(`li`,{role:`none`,className:`pl-9`,children:(0,K.jsx)(wOi,{onClick:()=>i(e=>[...e,s])})}):null]})}function jOi({children:e}){return(0,K.jsx)(`li`,{role:`none`,className:`flex h-8 items-center pl-9 text-caption text-muted-foreground`,children:e})}function MOi({source:e,mention:t,pagesById:n,onOpen:r,onClose:i}){let a=e.usePage(t.source.id),o=(a.data?.notes??[]).filter(e=>e.mentions.includes(t.target.id));return(0,G.useEffect)(()=>{let e=e=>{e.key===`Escape`&&i()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[i]),(0,K.jsxs)(`div`,{role:`dialog`,"aria-label":`${t.source.name} mentions ${t.target.name}`,"data-testid":`knowledge-mention-popup`,className:`absolute z-20 flex w-80 max-w-[calc(100%-1rem)] flex-col gap-2 overflow-hidden rounded-lg border border-border bg-card p-3 shadow-overlay`,style:fTi(t),children:[(0,K.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,K.jsxs)(T,{as:`h3`,variant:`card-title`,className:`min-w-0 flex-1`,children:[(0,K.jsx)(`button`,{type:`button`,className:`hover:underline`,onClick:()=>r(t.source.id),children:t.source.name}),(0,K.jsxs)(T,{as:`span`,variant:`card-title`,tone:`muted`,children:[` `,`mentions`,` `]}),(0,K.jsx)(`button`,{type:`button`,className:`hover:underline`,onClick:()=>r(t.target.id),children:t.target.name})]}),(0,K.jsx)(`button`,{type:`button`,"aria-label":`Close`,className:`rounded p-0.5 text-muted-foreground hover:bg-fill hover:text-foreground`,onClick:i,children:(0,K.jsx)(xw,{className:`size-icon-sm`,"aria-hidden":!0})})]}),(0,K.jsx)(`div`,{className:`min-h-0 overflow-y-auto`,children:a.isPending?(0,K.jsx)(SOi,{}):o.length===0?(0,K.jsxs)(T,{variant:`caption`,tone:`muted`,children:[`The notes that make this mention aren't in the first page of notes. Open `,t.source.name,` to read them all.`]}):(0,K.jsx)(`ul`,{className:`flex flex-col gap-2`,children:o.map(e=>(0,K.jsx)(NTi,{note:e,pagesById:vOi(n,a.data?[...a.data.related,...a.data.ancestors,a.data.page]:[]),onPageClick:e=>r(e.id),compact:!0},e.id))})})]})}function NOi({source:e,pageId:t,pagesById:n,onSelect:r,highlightMentionOf:i,compact:a,onOpenPage:o}){let s=e.usePage(t),c=(e.useActivity??gOi)(t),l=(e.usePageLinks??pOi)(t).data,u=(0,G.useMemo)(()=>l?LOi(t,l):void 0,[t,l]),[d,f]=(0,G.useState)(null),p=(0,G.useMemo)(()=>s.data?vOi(n,[...s.data.ancestors,...s.data.related]):n,[s.data,n]);if(s.isPending)return(0,K.jsx)(COi,{compact:a});if(s.isError||!s.data){let e=_Oi(s.error);return(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:e?`Page not found`:`Failed to load the page`,descriptionSlot:e?`It may have been deleted or merged.`:s.error?.message??``})}let m=e=>r(e.id),h=s.data.notesNextCursor;return(0,K.jsx)(PTi,{compact:a,onOpenPage:o,page:s.data.page,notes:s.data.notes,pin:s.data.pin??void 0,pagesById:p,onPageClick:m,highlightMentionOf:i,ancestors:s.data.ancestors,mentionedBy:s.data.mentionedBy,links:u,activity:c.data?.events,childPages:e.useTreeLevels?(0,K.jsx)(EOi,{useTreeLevels:e.useTreeLevels,parentId:t,onOpen:r},t):void 0,notesMore:h?d?.pageId===t?(0,K.jsx)(TOi,{source:e,pageId:t,cursor:h,pagesById:p,onPageClick:m}):(0,K.jsx)(wOi,{label:`Load more notes`,onClick:()=>f({pageId:t})}):void 0})}var POi=30;function FOi(e,t){let n=t.trim()?e.toLowerCase().indexOf(t.trim().toLowerCase()):-1;if(n<=POi)return e;let r=e.lastIndexOf(` `,n-POi)+1;return`…${e.slice(r)}`}function IOi({text:e,query:t}){let n=t.trim().toLowerCase(),r=n?e.toLowerCase().indexOf(n):-1;return r<0?(0,K.jsx)(K.Fragment,{children:e}):(0,K.jsxs)(K.Fragment,{children:[e.slice(0,r),(0,K.jsx)(`mark`,{className:`rounded-sm bg-badge-blue-subtle text-foreground`,children:e.slice(r,r+n.length)}),e.slice(r+n.length)]})}function LOi(e,{edges:t,pages:n}){let r=new Map(n.map(e=>[e.id,e])),i=(n,i)=>{let a=new Map;for(let r of t)r[n]===e&&r[i]!==e&&a.set(r[i],(a.get(r[i])??0)+r.count);return[...a].flatMap(([e,t])=>{let n=r.get(e);return n?[{page:n,count:t}]:[]})};return{out:i(`fromPageId`,`toPageId`),in:i(`toPageId`,`fromPageId`)}}function ROi({source:e,onSelect:t}){let[n,r]=(0,G.useState)(``),i=e.useSearch(n),a=n.trim().length>=tOi?i.data?.results??[]:[],o=new Set,s=a.map(e=>e.page).filter(e=>!o.has(e.id)&&(o.add(e.id),!0)).slice(0,10);return(0,K.jsxs)(`div`,{className:`relative w-64 min-w-0`,children:[(0,K.jsx)(MH,{label:`Search knowledge`,placeholder:`Search pages and notes`,size:`sm`,value:n,onValueChange:r}),s.length>0?(0,K.jsx)(`div`,{className:`absolute z-20 mt-1 w-full overflow-hidden rounded-xl ${Vv}`,children:(0,K.jsx)(LS,{maxHeight:`18rem`,children:(0,K.jsx)(`ul`,{role:`listbox`,"aria-label":`Search results`,className:`p-1`,children:s.map(e=>(0,K.jsx)(`li`,{role:`option`,"aria-selected":!1,children:(0,K.jsx)(`button`,{type:`button`,className:c(kT,`whitespace-normal`),onClick:()=>{t(e.id),r(``)},children:(0,K.jsxs)(`span`,{className:`flex min-w-0 flex-col gap-0.5`,children:[(0,K.jsx)(`span`,{className:`line-clamp-2 wrap-anywhere`,children:(0,K.jsx)(IOi,{text:e.name,query:n})}),e.description?(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`line-clamp-1 wrap-anywhere`,children:(0,K.jsx)(IOi,{text:FOi(e.description,n),query:n})}):null]})})},e.id))})})}):null]})}function zOi(e,t){let n=(e,t)=>e.size===t.size&&[...e].every(e=>t.has(e));return e.pages.length===t.pages.length&&e.pages.every((e,n)=>e===t.pages[n])&&n(e.loaded,t.loaded)&&n(e.failed,t.failed)&&e.nextCursor.size===t.nextCursor.size&&[...e.nextCursor].every(([e,n])=>t.nextCursor.get(e)===n)}function BOi(e,t,n,r){let[i,a]=(0,G.useState)(()=>new Set),[o,s]=(0,G.useState)(()=>new Map),c=(0,G.useMemo)(()=>{let e=[{parentId:null}];for(let t of i){e.push({parentId:t});for(let n of o.get(t)??[])e.push({parentId:t,cursor:n})}for(let t of r)i.has(t)||e.push({parentId:t});return e},[i,o,r]),l=(e.useTreeLevels??uOi)(c),{pages:u,loaded:d,failed:f,nextCursor:p}=pTi((0,G.useMemo)(()=>{let e=new Set,t=new Map,r=new Set,i=new Map;l.forEach((n,a)=>{let o=c[a];if(!o)return;let s=o.parentId??``;if(n.isError&&e.add(s),n.data){r.add(s);for(let e of n.data.pages)t.set(e.id,e);n.data.nextCursor?i.set(s,n.data.nextCursor):i.delete(s)}});for(let e of[...n?.ancestors??[],...n?[n.page]:[]])t.has(e.id)||t.set(e.id,e);return{pages:[...t.values()],loaded:r,failed:e,nextCursor:i}},[l,c,n]),zOi),m=(0,G.useMemo)(()=>t.truncated?null:new Set(t.pages.map(e=>e.parentId).filter(e=>e!==null)),[t]);return{pages:u,loaded:d,failed:f,mayHaveChildren:(0,G.useCallback)(e=>!d.has(e.id)&&(e.childCountCapped||(e.childCount===void 0?!eOi(e)&&(!m||m.has(e.id)):e.childCount>0)),[d,m]),loadMore:(0,G.useMemo)(()=>{let e=new Map;for(let[t,n]of p)e.set(t,()=>s(e=>new Map(e).set(t,[...e.get(t)??[],n])));return e},[p]),onExpandedChange:(0,G.useCallback)(e=>a(new Set(e)),[]),rootsPending:l[0]?.isPending??!1}}function VOi({graph:e,source:t,selectedPageId:n,onSelect:r,view:i,onViewChange:a,toolbarEnd:o,flush:s=!1}){let c=Zw(1024),l=!c&&i===`tree`?`graph`:i,u=t.usePage(n),d=!!t.useTreeLevels,[f,p]=(0,G.useState)([]),[m,h]=(0,G.useState)([]),[g,_]=(0,G.useState)(()=>new Set),[v,y]=(0,G.useState)(()=>new Map),[b,x]=(0,G.useState)(!1),[S,C]=(0,G.useState)(!0),w=BOi(t,e,u.data,f),E=(0,G.useMemo)(()=>d?qwi({pages:[...new Map([...e.pages,...w.pages].map(e=>[e.id,e])).values()],loadedParents:w.loaded,rootKey:``,focusId:n,openGroups:g,revealed:v}):{pages:e.pages,hiddenChildren:new Map,wanted:[],hub:null},[d,w.pages,w.loaded,n,g,v,e.pages]),D=!d||E.wanted.every(e=>w.loaded.has(e)||w.failed.has(e));(0,G.useEffect)(()=>{if(!d||l===`page`)return;let e=[...new Set([...E.wanted,...m])];p(t=>t.length===e.length&&t.every((t,n)=>t===e[n])?t:e)},[d,l,E.wanted,m]);let O=(t.usePageLinks??pOi)(l===`graph`?n:null).data,k=(0,G.useMemo)(()=>{let e=u.data;if(!e||e.page.id!==n)return null;let t=new Map([...w.pages,...e.ancestors,...e.related].map(e=>[e.id,e])),r=tTi(t.values()),i=e.page.id,a=e.notes.flatMap(e=>e.mentions).filter(e=>e&&e!==i),o=sTi(e.page.body??``).map(e=>e.trim()).filter(e=>e&&e!==i),s=[...a,...o],c=new Set(a),l=new Set(o.filter(e=>!e.includes(`:`)&&!QDi.test(e)&&!c.has(e))),d=(O?.edges??[]).filter(e=>e.toPageId===i),f=[...new Set([...(e.mentionedBy??[]).map(e=>e.pageId),...d.filter(e=>e.kind===`note`).map(e=>e.fromPageId)])].filter(e=>e!==i),p=[...new Set(d.filter(e=>e.kind===`body`).map(e=>e.fromPageId))].filter(e=>e!==i),m=[...new Set([...f,...p])],h=e=>t.get(e)??r.resolve(e),g=e=>[...new Set(e.filter(e=>!h(e)&&!l.has(e)))],_=e=>new Set(e.flatMap(e=>h(e)?.id??[])).size,v=e=>Math.max(0,nOi-_(e)),y=g(s),b=g(m);return{detail:e,known:t,mentions:a,refs:o,into:m,noteInto:f,bodyInto:p,lookup:h,fetchKeys:[...y.slice(0,v(s)),...b.slice(0,v(m))],unfetched:{out:Math.max(0,y.length-v(s)),in:Math.max(0,b.length-v(m))}}},[u.data,n,w.pages,O]),A=k?.fetchKeys??dOi,j=(t.useLinkedPages??fOi)(A),M=A.map((e,t)=>`${e}=${j[t]?.data?.page?.id??``}`).join(`|`),N=(0,G.useMemo)(()=>{let e=new Map;return A.forEach((t,n)=>{let r=j[n]?.data?.page;r&&e.set(t,r)}),e},[M]),P=(0,G.useMemo)(()=>{if(!k)return{edges:[],pages:[],unfetched:{in:0,out:0}};let{detail:e,lookup:t,mentions:n,refs:r,noteInto:i,bodyInto:a}=k,o=e=>t(e)??N.get(e),s=e.page.id,c=[],l=new Map,u=(e,t,n)=>{let r=o(e);!r||r.id===s?(!r&&t===`mention`&&n===`out`&&c.push({source:s,target:e,kind:t}),!r&&n===`in`&&c.push({source:e,target:s,kind:t})):(l.set(r.id,r),c.push(n===`out`?{source:s,target:r.id,kind:t}:{source:r.id,target:s,kind:t}))};for(let e of n)u(e,`mention`,`out`);for(let e of r)u(e,`link`,`out`);for(let e of i)u(e,`mention`,`in`);for(let e of a)u(e,`link`,`in`);return{edges:c.filter(e=>e.source!==e.target),pages:[...l.values()],unfetched:k.unfetched}},[k,N]),F=(0,G.useMemo)(()=>new Set(P.pages.map(e=>e.id)),[P.pages]),I=(0,G.useMemo)(()=>{let e=new Set(E.pages.map(e=>e.id)),t=P.pages.filter(t=>!e.has(t.id));return{...E,pages:t.length?[...E.pages,...t]:E.pages}},[E,P.pages]),L=(0,G.useMemo)(()=>new Map(I.pages.map(e=>[e.id,e])),[I.pages]),R=e=>h(t=>t.includes(e)?t:[...t,e].slice(-8)),[z,B]=(0,G.useState)(null),V=(0,G.useMemo)(()=>{let t=new Set;return[...e.edges.filter(e=>e.kind===`mention`),...cTi(I.pages),...P.edges].filter(e=>{let n=`${e.kind}:${e.source}>${e.target}`;return!t.has(n)&&(t.add(n),!0)})},[e.edges,I.pages,P.edges]),H=(0,G.useMemo)(()=>iOi(V,L,n,b),[V,L,n,b]),ee=H.edges,te=(0,G.useMemo)(()=>I.pages.filter(e=>!v9(e)&&!y9(e)&&!b9(e)).map(e=>e.id).sort(),[I.pages]),U=(t.useLinkCounts??pOi)(l===`graph`?te:[]),W=(0,G.useMemo)(()=>U.data?new Map(Object.entries(U.data)):void 0,[U.data]),ne=(0,G.useMemo)(()=>W?hOi(W,ee):H.hidden,[W,ee,H.hidden]),[re,ie]=(0,G.useState)(null),ae=(0,G.useRef)(void 0),oe=(0,G.useCallback)(e=>{clearTimeout(ae.current),e?ae.current=setTimeout(()=>ie(e),mOi):ie(null)},[]);(0,G.useEffect)(()=>()=>clearTimeout(ae.current),[]);let se=(t.usePageLinks??pOi)(re),ce=(0,G.useMemo)(()=>re&&se.data?se.data.edges.map(e=>({source:e.fromPageId,target:e.toPageId,kind:e.kind===`body`?`link`:`mention`,count:e.count})):[],[re,se.data]),[le,ue]=(0,G.useState)(null),[de,fe]=(0,G.useState)(null),pe=(0,G.useCallback)(()=>ue(null),[]),me=!c||l===`graph`,he=!c,[ge,_e]=(0,G.useState)(!0),[ve,ye]=(0,G.useState)(),be=(0,G.useRef)(null),xe=(0,G.useRef)(null),Se=(0,G.useRef)(null),Ce=(0,G.useRef)(!1),we=de&&de.source===n?de.target:void 0,Te=l===`page`&&!!n,[Ee,De]=(0,G.useState)([]),Oe=(0,G.useRef)(n),ke=(0,G.useRef)(null);(0,G.useEffect)(()=>{let e=Oe.current;Oe.current=n;let t=ke.current;ke.current=null,t&&t===n||e&&n&&e!==n&&De(t=>[...t.filter(e=>e!==n),e].slice(-50))},[n]);let Ae=Ee.length?Ee[Ee.length-1]:void 0,je=()=>{Ae&&(ke.current=Ae,De(e=>e.slice(0,-1)),r(Ae))},Me=e=>{r(e),a(`page`)},Ne=e=>{r(e),i!==`graph`&&a(`graph`)},Pe=e=>{e.isScope&&B(e.id),l===`graph`&&(d||L.has(e.id))&&e.id!==n?Ne(e.id):Me(e.id)},Fe=e=>{z&&!yOi([...w.pages,...I.pages],z).some(t=>t.id===e)&&B(null)},Ie=e=>{Fe(e),Me(e)},Le=e=>{l===`graph`&&(d||L.has(e))&&e!==n?(Fe(e),Ne(e)):Ie(e)},Re=z?w.pages.find(e=>e.id===z)??L.get(z):void 0,ze=yOi(t.useTreeLevels?w.pages:e.pages,Re?z:null),Be=(0,G.useMemo)(()=>yOi(I.pages,Re?z:null),[I.pages,Re,z]),Ve=l===`graph`?L.get(n??I.hub??``):void 0;Ve&&I.hiddenChildren.get(Ve.id);let He=[{value:`tree`,label:`Tree`,icon:(0,K.jsx)(ZN,{}),narrowOnly:!0},{value:`graph`,label:`Graph`,icon:(0,K.jsx)(n7e,{}),narrowOnly:!1},{value:`page`,label:`Page`,icon:(0,K.jsx)(xk,{}),narrowOnly:!1}],Ue=aOi(l,Te),We=he&&Te,Ge=he&&!Te&&n&&!_Oi(u.error)&&n?n:void 0;Ge&&Ge!==ve&&ye(Ge);let Ke=Ge??ve,qe={left:cOi(he,ge),right:Ge?lOi:0},Je={"--knowledge-tree-inset":`${qe.left}px`,"--knowledge-tree-drawer-inset":`${he&&ge?oOi:0}px`,"--knowledge-drawer-inset":`${qe.right}px`},Ye=()=>be.current?.querySelector(`[role="tab"][aria-selected="true"]`)?.focus(),Xe=e=>{e&&Ce.current&&(Ce.current=!1,Ye())},Ze=e=>{(0,Pt.flushSync)(()=>_e(e)),(e?Se:xe).current?.focus()},Qe=he&&!ge,$e=he?(0,K.jsxs)(jQ.Header,{children:[(0,K.jsx)(jQ.Heading,{children:`Pages`}),(0,K.jsx)(jQ.HeaderActions,{children:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`Hide pages`,"aria-label":`Hide pages`,ref:Se,onClick:()=>Ze(!1),children:(0,K.jsx)(ZDi,{})})})]}):null,et=(0,K.jsxs)(K.Fragment,{children:[Re?(0,K.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-surface-rim bg-fill-subtle px-3 py-2`,"data-testid":`knowledge-scope-focus`,children:[(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,K.jsx)(T,{as:`span`,variant:`eyebrow`,tone:`muted`,className:`uppercase`,children:Re.displayLabel??`Scope`}),(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5`,children:[(0,K.jsx)(yTi,{page:Re,className:`size-3.5`}),(0,K.jsx)(C9,{label:Re.address??Re.name,children:(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`ink`,className:`truncate`,children:S9(Re)})})]})]}),(0,K.jsx)(X,{variant:`ghost`,size:`sm`,onClick:()=>B(null),children:`All scopes`})]}):null,(0,K.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:t.useTreeLevels&&w.rootsPending?(0,K.jsx)(`div`,{className:`p-2`,children:(0,K.jsx)(xOi,{label:`Loading pages`,rows:6})}):(0,K.jsx)(YDi,{pages:ze,pinnedIds:e.pinnedIds,selectedPageId:n,onSelect:Pe,initiallyExpanded:Re?[Re.id]:void 0,...t.useTreeLevels?{mayHaveChildren:w.mayHaveChildren,onExpandedChange:w.onExpandedChange,loadMore:w.loadMore}:{}},Re?Re.id:`all`)})]}),tt=Ke?L.get(Ke)??w.pages.find(e=>e.id===Ke):void 0;return(0,K.jsx)(lTi.Provider,{value:N,children:(0,K.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col ${s?``:`gap-2`}`,children:[(0,K.jsxs)(TK,{className:s?`shrink-0 border-b border-surface-rim px-3 py-2`:void 0,children:[(0,K.jsxs)(TK.Start,{children:[(0,K.jsx)(gk,{ref:be,value:Ue,defaultTab:Ue,onValueChange:e=>a(e),"aria-label":`View`,children:(0,K.jsx)(hk,{variant:`pill-ghost`,size:`sm`,children:He.map(e=>(0,K.jsxs)(_k,{value:e.value,disabled:e.value===`page`&&!n,className:e.narrowOnly?`lg:hidden`:void 0,children:[(0,K.jsx)(Dx,{size:`xs`,children:e.icon}),(0,K.jsx)(T,{variant:`caption`,className:`text-inherit`,children:e.label})]},e.value))})}),(0,K.jsx)(ROi,{source:t,onSelect:Le})]}),o?(0,K.jsx)(TK.End,{children:o}):null]}),!d&&e.truncated&&!Te?(0,K.jsxs)(T,{variant:`caption`,tone:`muted`,className:s?`px-3 pt-2`:void 0,children:[`The graph shows the first `,e.pages.length,` pages. Open the tree or search to reach the rest.`]}):null,n&&!Te&&_Oi(u.error)?(0,K.jsx)(T,{role:`alert`,variant:`caption`,className:`text-destructive-foreground ${s?`px-3 pt-2`:``}`,children:`Page not found. The linked page may have been deleted or merged.`}):null,(0,K.jsxs)(`div`,{style:Je,className:`relative flex min-h-0 flex-1 flex-col gap-3 lg:flex-row`,children:[he?(0,K.jsx)(`div`,{inert:Qe,"aria-hidden":Qe||void 0,"data-state":Qe?`closed`:`open`,className:`absolute inset-y-2 left-2 z-10 flex w-72 transition duration-slow ease-out-custom motion-reduce:transition-none ${Qe?`pointer-events-none -translate-x-4 opacity-0`:`translate-x-0 opacity-100`}`,children:(0,K.jsxs)(jQ,{variant:`inline`,title:`Pages`,className:`shadow-overlay`,children:[$e,et]})}):(0,K.jsx)(`aside`,{"aria-label":`Pages`,className:`min-h-0 w-full flex-1 flex-col overflow-hidden rounded-lg border border-border bg-card lg:w-72 lg:flex-none lg:shrink-0 ${l===`tree`?`flex`:`hidden`}`,children:et}),he?(0,K.jsx)(X,{tooltip:`Show pages`,"aria-label":`Show pages`,size:`icon-sm`,inert:!Qe,"aria-hidden":!Qe||void 0,className:`absolute top-3 left-3 z-10 shadow-overlay transition-opacity duration-slow ease-out-custom motion-reduce:transition-none ${Qe?`opacity-100`:`pointer-events-none opacity-0`}`,ref:xe,onClick:()=>Ze(!0),children:(0,K.jsx)(XDi,{})}):null,Te&&!he?(0,K.jsx)(`section`,{ref:Xe,"aria-label":`Selected page`,className:`flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-lg border border-border bg-card`,children:(0,K.jsx)(NOi,{source:t,pageId:n,pagesById:L,onSelect:Ie,highlightMentionOf:we})}):(0,K.jsxs)(`div`,{className:`relative min-h-0 min-w-0 flex-1 overflow-hidden bg-sidebar lg:block lg:h-full ${s?``:`rounded-xl border border-border`} ${l===`graph`||We?`block`:`hidden`}`,"data-testid":`knowledge-graph-container`,children:[me&&!We?(0,K.jsx)(`div`,{className:`absolute top-3 right-3 z-10 -translate-x-(--knowledge-drawer-inset) transition-transform duration-slow ease-out-custom motion-reduce:transition-none`,children:(0,K.jsxs)($V,{orientation:`vertical`,size:`sm`,"aria-label":`Graph options`,className:`rounded-xl shadow-overlay`,children:[(0,K.jsx)(X,{"data-testid":`knowledge-graph-back`,"aria-label":`Back`,tooltip:Ae?`Back to the previous page`:`Nothing to go back to yet`,tooltipPosition:`left`,size:`icon-sm`,disabled:!Ae,onClick:je,children:(0,K.jsx)(sS,{})}),(0,K.jsx)(X,{"aria-label":`All links`,"aria-pressed":b,"data-testid":`knowledge-graph-all-links`,tooltip:b?`Show only the selected page’s links`:`Show every link between pages`,tooltipPosition:`left`,size:`icon-sm`,className:b?`[--control-icon:var(--foreground)]`:void 0,onClick:()=>x(e=>!e),children:(0,K.jsx)(tZ,{})}),(0,K.jsx)(X,{"aria-label":`Link counts`,"aria-pressed":S,"data-testid":`knowledge-graph-dot-counts`,tooltip:S?`Hide link counts`:`Show link counts on each dot`,tooltipPosition:`left`,size:`icon-sm`,className:S?`[--control-icon:var(--foreground)]`:void 0,onClick:()=>C(e=>!e),children:(0,K.jsx)(Z4,{})})]})}):null,me&&!We?(0,K.jsx)(UDi,{pages:Be,edges:ee,pinnedIds:e.pinnedIds,grants:e.grants,selectedPageId:n,centerId:I.hub,hiddenLinks:ne,knownLinks:V,fetchedLinks:ce,exactLinkCounts:W,onHover:oe,nearIds:F,settled:D,insets:qe,collapsibleLegend:he,showCounts:S,onPreview:e=>{v9(e)&&e.parentId&&R(e.parentId)},onSelect:e=>{if(v9(e))return e.parentId?R(e.parentId):void 0;if(y9(e)){let t=e.parentId;return t?(y(e=>new Map(e).set(t,(e.get(t)??0)+12)),w.loadMore.get(t)?.()):void 0}if(b9(e))return _(t=>new Set(t).add(e.id));Ne(e.id)},onOpen:e=>Me(e.id),onClearSelection:()=>{ue(null),n&&r(null)},onMentionSelect:ue}):null,he?(0,K.jsx)(`div`,{inert:!Ge,"aria-hidden":!Ge||void 0,"data-state":Ge?`open`:`closed`,onTransitionEnd:e=>{!Ge&&e.target===e.currentTarget&&ye(void 0)},className:`absolute inset-y-2 right-2 z-10 flex w-96 transition duration-slow ease-out-custom motion-reduce:transition-none ${Ge?`translate-x-0 opacity-100`:`pointer-events-none translate-x-4 opacity-0`}`,children:Ke?(0,K.jsxs)(jQ,{variant:`inline`,title:`Page details`,className:`shadow-overlay`,children:[(0,K.jsxs)(jQ.Header,{children:[(0,K.jsx)(jQ.Heading,{className:`min-w-0 flex-1 shrink`,children:(0,K.jsx)(`span`,{className:`truncate`,children:tt?.name??`Page`})}),(0,K.jsxs)(jQ.HeaderActions,{children:[(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`Open page`,"aria-label":`Open page`,onClick:()=>{Ce.current=!0,Me(Ke)},children:(0,K.jsx)(tP,{})}),(0,K.jsx)(jQ.CloseButton,{icon:`x`,label:`Close page details`,tooltip:`Close`,onClick:()=>{Ye(),r(null)}})]})]}),(0,K.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden`,children:(0,K.jsx)(NOi,{source:t,pageId:Ke,pagesById:L,onSelect:Le,highlightMentionOf:we,compact:!0,onOpenPage:()=>{Ce.current=!0,Me(Ke)}})})]}):null}):null,We?(0,K.jsx)(`section`,{ref:Xe,"aria-label":`Selected page`,className:`absolute inset-y-2 right-2 left-[calc(var(--knowledge-tree-inset)+0.5rem)] z-20 flex transition-[left] duration-slow ease-out-custom motion-reduce:transition-none`,children:(0,K.jsxs)(jQ,{variant:`inline`,title:`Page`,className:`shadow-overlay`,children:[(0,K.jsxs)(jQ.Header,{children:[(0,K.jsx)(jQ.Heading,{children:`Page`}),(0,K.jsx)(jQ.HeaderActions,{children:(0,K.jsx)(jQ.CloseButton,{icon:`x`,label:`Close page`,tooltip:`Close`,onClick:()=>{Ye(),a(`graph`)}})})]}),(0,K.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden`,children:(0,K.jsx)(NOi,{source:t,pageId:n,pagesById:L,onSelect:Ie,highlightMentionOf:we})})]})}):null,le&&me?(0,K.jsx)(MOi,{source:t,mention:le,pagesById:L,onClose:pe,onOpen:e=>{fe(e===le.source.id?{source:le.source.id,target:le.target.id}:null),ue(null),Ie(e)}}):null]})]})]})})}var HOi=2,UOi=5e3,WOi=6e4,GOi=5e3,KOi=150,M9=e=>e?WOi:UOi,qOi=e=>e instanceof qf&&(e.status>=400&&e.status<500||e.status===501);function JOi(e,t){return new Promise(n=>{let r=setTimeout(n,e);t.addEventListener(`abort`,()=>(clearTimeout(r),n()),{once:!0})})}function YOi(e){return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)}var XOi=()=>document.visibilityState!==`hidden`;function ZOi(e){let t=Y(),n=u_(),[r,i]=(0,G.useState)(!1),a=(0,G.useSyncExternalStore)(YOi,XOi,()=>!0),o=(0,G.useRef)(!1);return(0,G.useEffect)(()=>{if(!e||!a)return;let r=new AbortController,s,c=()=>{clearTimeout(s),s=setTimeout(()=>void n.invalidateQueries({queryKey:[`knowledge`,e]}),KOi)};return(async()=>{for(;!r.signal.aborted;){try{let n=(await t.getKnowledge(e).events({signal:r.signal})).getReader();for(o.current&&c(),o.current=!0,i(!0);!(await n.read()).done;)c()}catch(e){if(qOi(e)){i(!1);return}}if(r.signal.aborted)return;i(!1),await JOi(GOi,r.signal)}})(),()=>{r.abort(),clearTimeout(s),i(!1)}},[t,n,e,a]),r}function QOi(){let e=Y();return T_({queryKey:[`knowledge`,`instances`],queryFn:async()=>(await e.listKnowledge()).instances})}function $Oi(e,t){let n=Y();return T_({queryKey:[`knowledge`,e,`graph`],queryFn:e?async()=>n.getKnowledge(e).graph():v_,refetchInterval:M9(t)})}function eki(e,t,n,r){let i=Y();return T_({queryKey:[`knowledge`,e,`page`,n,r??null],queryFn:e&&n?async()=>i.getKnowledge(e).page(n,{noteCursor:r}):v_,refetchInterval:!r&&M9(t)})}function tki(e,t){let n=Y();return w_({queries:t.map(t=>({queryKey:[`knowledge`,e,`page`,t,null],queryFn:e?async()=>n.getKnowledge(e).page(t):v_,retry:(e,t)=>!(t&&`status`in t&&t.status===404)&&e<2,staleTime:3e4}))})}function nki(e,t,n){let r=Y();return w_({queries:n.map(n=>({queryKey:[`knowledge`,e,`tree`,n.parentId,n.cursor??null],queryFn:e?async()=>r.getKnowledge(e).tree({parentId:n.parentId??void 0,cursor:n.cursor}):v_,refetchInterval:!n.cursor&&M9(t)}))})}var rki=200,iki=(e,t)=>!qOi(t)&&e<2;function aki(e,t,n){let r=Y();return T_({queryKey:[`knowledge`,e,`link-counts`,n],queryFn:e&&n.length?async()=>{let t=r.getKnowledge(e),i=[];for(let e=0;e<n.length;e+=rki)i.push(n.slice(e,e+rki));let a=await Promise.all(i.map(e=>t.linkCounts(e)));return Object.assign({},...a.map(e=>e.counts))}:v_,placeholderData:__,retry:iki,refetchInterval:M9(t)})}function oki(e,t){let n=Y();return T_({queryKey:[`knowledge`,e,`page-links`,t],queryFn:e&&t?async()=>n.getKnowledge(e).pageLinks(t):v_,staleTime:3e4,retry:iki})}function ski(e,t,n){let r=Y();return T_({queryKey:[`knowledge`,e,`activity`,n],queryFn:e?async()=>r.getKnowledge(e).activity({pageId:n}):v_,refetchInterval:M9(t)})}function cki(e,t){let n=Y(),r=t.trim();return T_({queryKey:[`knowledge`,e,`search`,r],queryFn:e&&r.length>=HOi?async()=>n.getKnowledge(e).search(r):v_,placeholderData:__})}var lki=[eP(`/knowledge`)];function N9({children:e}){return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:lki}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Knowledge`}),e]})}function uki({knowledgeKey:e,live:t,graph:n}){let[r,i]=Rv(),a=r.get(`page`),o=r.get(`view`),s=o===`graph`||o===`page`||o===`tree`?o:a?`page`:`tree`,c=(0,G.useMemo)(()=>({usePage:(n,r)=>eki(e,t,n,r),useSearch:t=>cki(e,t),useTreeLevels:n=>nki(e,t,n),useLinkCounts:n=>aki(e,t,n),usePageLinks:t=>oki(e,t),useLinkedPages:t=>tki(e,t),useActivity:n=>ski(e,t,n)}),[e,t]),l=eki(e,t,a).data?.page.id;(0,G.useEffect)(()=>{l&&a&&l!==a&&i(e=>{let t=new URLSearchParams(e);return t.set(`page`,l),t},{replace:!0})},[l,a,i]);let u=(0,G.useRef)(null);(0,G.useEffect)(()=>{u.current=null},[r]);let d=(e,t)=>{let n=new URLSearchParams(u.current??r);t===null?n.delete(e):n.set(e,t),u.current=n,i(n)};return(0,K.jsx)(VOi,{graph:n,source:c,selectedPageId:a,onSelect:e=>d(`page`,e),view:s,onViewChange:e=>d(`view`,e)})}function dki(){let[e,t]=Rv(),n=QOi(),r=e.get(`instance`)??n.data?.[0]?.key,i=ZOi(r),a=$Oi(r,i),o=n.error??a.error;return o&&FN(o)?(0,K.jsx)(N9,{children:(0,K.jsx)(TH,{variant:`fill`})}):o&&IN(o)?(0,K.jsx)(N9,{children:(0,K.jsx)(wH,{variant:`fill`,resource:`knowledge`})}):n.error&&!n.data&&LN(n.error)?(0,K.jsx)(N9,{children:(0,K.jsx)(Jx,{variant:`fill`,titleSlot:`Knowledge browsing is not enabled`,descriptionSlot:`This server does not register the Knowledge routes. Add KNOWLEDGE_ROUTES from @mastra/server/server-adapter to server.apiRoutes, then reload.`})}):n.error&&!n.data?(0,K.jsx)(N9,{children:(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load Knowledge`,descriptionSlot:n.error.message})}):n.data&&n.data.length===0?(0,K.jsx)(N9,{children:(0,K.jsx)(Jx,{variant:`fill`,titleSlot:`No Knowledge instances`,descriptionSlot:`Register one on your Mastra instance with the knowledge option to browse it here.`})}):(0,K.jsx)(N9,{children:(0,K.jsxs)(`div`,{className:`flex h-full min-h-0 flex-1 flex-col gap-3`,children:[n.data&&n.data.length>1?(0,K.jsx)(`select`,{"aria-label":`Knowledge instance`,className:`text-ui-md h-8 w-fit rounded border border-border bg-card px-2`,value:r,onChange:e=>t(new URLSearchParams({instance:e.target.value})),children:n.data.map(e=>(0,K.jsx)(`option`,{value:e.key,children:e.key},e.key))}):null,!r||a.isPending?(0,K.jsx)(`p`,{className:`text-ui-md p-4 text-muted-foreground`,children:`Loading knowledge…`}):a.data?a.data.pages.length===0?(0,K.jsx)(Jx,{variant:`fill`,titleSlot:`No pages yet`,descriptionSlot:`Agents add pages and notes to Knowledge as they run. They will appear here.`}):(0,K.jsx)(uki,{knowledgeKey:r,live:i,graph:a.data}):(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load Knowledge`,descriptionSlot:a.error?.message})]})})}function fki({title:e,description:t,errorBanner:n,children:r}){return(0,K.jsxs)(`div`,{"data-testid":`login-page`,className:`w-full max-w-sm space-y-6 p-6`,children:[(0,K.jsxs)(`div`,{className:`flex flex-col items-center space-y-2`,children:[(0,K.jsx)(UZ,{className:`h-10 w-10`}),(0,K.jsx)(T,{as:`h1`,variant:`heading`,tone:`ink`,children:e})]}),t,n,r]})}function pki({redirectUri:e,onSuccess:t,initialMode:n=`signin`,errorMessage:r}){let{data:i,isLoading:a}=A_(),{mutate:o,isPending:s,error:c}=AFe(),{mutate:l,isPending:u,error:d}=MFe(),{mutate:f,isPending:p}=NFe(),[m,h]=(0,G.useState)(n),[g,_]=(0,G.useState)(``),[v,y]=(0,G.useState)(``),[b,x]=(0,G.useState)(``);if(a)return(0,K.jsx)(`div`,{className:`text-muted-foreground`,children:`Loading...`});if(!i?.enabled||!i?.login)return(0,K.jsx)(`div`,{className:`text-muted-foreground`,children:`Authentication is not configured`});let{login:S}=i,C=S.type===`sso`||S.type===`both`,w=S.type===`credentials`||S.type===`both`,E=S.sso,D=S.signUpEnabled!==!1,O=m===`signin`||!D,k=O?s:u,A=O?c:d,j=()=>{t?t():e?window.location.href=e:window.location.href=WZ(`/`)},M=e=>{e.preventDefault(),O?o({email:v,password:b},{onSuccess:j}):l({email:v,password:b,name:g||void 0},{onSuccess:j})},N=()=>{f({redirectUri:e},{onSuccess:e=>{window.location.href=e.url}})},P=()=>{h(O?`signup`:`signin`)},F=S.description?(0,K.jsxs)(`div`,{className:`flex items-start gap-2.5 rounded-md border border-border bg-sidebar p-3`,children:[(0,K.jsx)(CH,{className:`mt-0.5 size-icon-md shrink-0 text-muted-foreground`}),(0,K.jsx)(T,{tone:`muted`,children:S.description})]}):null;return(0,K.jsxs)(fki,{title:O?`Sign in to Mastra Studio`:`Create your account`,description:F,errorBanner:r?(0,K.jsx)(`div`,{role:`alert`,children:(0,K.jsx)(Sk,{variant:`destructive`,children:r})}):null,children:[w&&(0,K.jsxs)(ZV,{onSubmit:M,children:[!O&&(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{children:`Name`}),(0,K.jsx)(Jj,{name:`name`,type:`text`,autoComplete:`name`,value:g,onChange:e=>_(e.target.value),placeholder:`Your name`,variant:`default`,size:`lg`})]}),(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{required:!0,children:`Email`}),(0,K.jsx)(Jj,{name:`email`,type:`email`,autoComplete:`email`,value:v,onChange:e=>y(e.target.value),placeholder:`you@example.com`,required:!0,variant:`default`,size:`lg`}),(0,K.jsx)(lk,{})]}),(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{required:!0,children:`Password`}),(0,K.jsx)(Jj,{name:`password`,type:`password`,autoComplete:O?`current-password`:`new-password`,value:b,onChange:e=>x(e.target.value),placeholder:O?`Enter your password`:`Create a password`,required:!0,variant:`default`,size:`lg`}),(0,K.jsx)(lk,{})]}),A?(0,K.jsx)(`div`,{role:`alert`,children:(0,K.jsx)(Sk,{variant:`destructive`,children:A.message})}):null,(0,K.jsx)(X,{icon:(0,K.jsx)(Cmn,{}),type:`submit`,disabled:k,className:`w-full`,size:`lg`,children:k?O?`Signing in...`:`Creating account...`:O?`Sign in`:`Create account`}),D&&(0,K.jsxs)(`div`,{className:`text-center`,children:[(0,K.jsx)(T,{as:`span`,variant:`body`,tone:`muted`,children:O?`Don't have an account? `:`Already have an account? `}),(0,K.jsx)(`button`,{type:`button`,onClick:P,className:`text-foreground hover:underline`,children:(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:O?`Sign up`:`Sign in`})})]})]}),C&&w&&(0,K.jsxs)(`div`,{className:`relative`,children:[(0,K.jsx)(`div`,{className:`absolute inset-0 flex items-center`,children:(0,K.jsx)(`div`,{className:`w-full border-t border-border`})}),(0,K.jsx)(`div`,{className:`relative flex justify-center`,children:(0,K.jsx)(T,{as:`span`,variant:`body`,tone:`muted`,className:`bg-sidebar px-2`,children:`or continue with`})})]}),C&&E&&(0,K.jsxs)(X,{onClick:N,disabled:p,className:`w-full`,size:`lg`,children:[E.icon&&(0,K.jsx)(`span`,{className:`mr-2`,children:E.icon}),p?`Redirecting...`:E.text||`Sign in`]})]})}function mki(){let[e]=Rv(),t=Ov(),n=e.get(`redirect`)||`/`,r=e.get(`mode`)===`signup`?`signup`:`signin`,i=e.get(`error_description`)||e.get(`error`)||null;return(0,K.jsx)(pki,{redirectUri:n,onSuccess:()=>{n.startsWith(`http`)?window.location.href=n:t(n,{replace:!0})},initialMode:r,errorMessage:i})}function hki({disabled:e,onClear:t,onRemoveAll:n,onSave:r,onRemoveSaved:i}){let a=!!(n||r||i);return!t&&!a?null:(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[t&&(0,K.jsx)(X,{disabled:e,size:`md`,onClick:t,icon:(0,K.jsx)(xw,{}),children:`Clear`}),a&&(0,K.jsxs)(rE,{children:[(0,K.jsx)(rE.Trigger,{asChild:!0,children:(0,K.jsx)(X,{disabled:e,size:`icon-md`,"aria-label":`More filter actions`,children:(0,K.jsx)(iE,{})})}),(0,K.jsxs)(rE.Content,{align:`end`,children:[n&&(0,K.jsxs)(rE.Item,{onSelect:()=>n(),children:[(0,K.jsx)(xw,{}),`Remove all filters`]}),n&&(r||i)&&(0,K.jsx)(rE.Separator,{}),r&&(0,K.jsxs)(rE.Item,{onSelect:()=>r(),children:[(0,K.jsx)(W4,{}),`Save filters for next time`]}),i&&(0,K.jsxs)(rE.Item,{onSelect:()=>i(),children:[(0,K.jsx)(Kj,{}),`Remove saved filters`]})]})]})]})}var gki=c(kT,`min-w-0`);function _ki({role:e,checked:t,label:n,onClick:r}){return(0,K.jsxs)(`button`,{type:`button`,role:e,"aria-checked":t,"data-selected":t||void 0,"data-pick-multi-item":``,title:n,className:gki,onClick:r,children:[(0,K.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:n}),t&&(0,K.jsx)(`span`,{className:jT,children:(0,K.jsx)(pC,{})})]})}function vki({field:e,tokens:t,onChange:n}){let[r,i]=(0,G.useState)(``),a=`max-h-[80dvh] overflow-auto p-1`,o=(0,G.useMemo)(()=>{let t=r.trim().toLowerCase();return t?e.options.filter(e=>e.label.toLowerCase().includes(t)):e.options},[e.options,r]),s=(0,G.useMemo)(()=>t.find(t=>t.fieldId===e.id),[t,e.id]),l=typeof s?.value==`string`?s.value:e.multi?void 0:e.defaultValue,u=(0,G.useMemo)(()=>{let e=s?.value;return Array.isArray(e)?e:typeof e==`string`?[e]:[]},[s]);return(0,K.jsxs)(K.Fragment,{children:[e.searchable!==!1&&(0,K.jsxs)(`div`,{className:FT.container,children:[(0,K.jsx)(oN,{className:FT.icon}),(0,K.jsx)(`input`,{type:`text`,value:r,onChange:e=>i(e.target.value),placeholder:`Search ${e.label.toLowerCase()}`,className:FT.input,...Gk,onKeyDown:e=>{if(e.key!==`ArrowDown`)return;let t=e.currentTarget.closest(`[data-pick-multi-panel]`)?.querySelector(`[data-pick-multi-item]:not([disabled])`);t&&(e.preventDefault(),e.stopPropagation(),t.focus())}})]}),e.isLoading?(0,K.jsxs)(`div`,{className:c(I6e,`m-1`),children:[(0,K.jsx)(It,{size:`sm`,className:`size-3 text-muted-foreground`}),`Loading options…`]}):o.length===0?(0,K.jsx)(`div`,{className:c(I6e,`m-1`),children:e.emptyText??`No option found.`}):e.multi?(0,K.jsx)(`div`,{className:a,children:(0,K.jsx)(K.Fragment,{children:o.map(t=>{let r=u.includes(t.value);return(0,K.jsx)(_ki,{role:`checkbox`,checked:r,label:t.label,onClick:()=>n(e.id,r?u.filter(e=>e!==t.value):[...u,t.value])},t.value)})})}):(0,K.jsx)(`div`,{role:`radiogroup`,className:a,children:(0,K.jsxs)(K.Fragment,{children:[o.map(t=>(0,K.jsx)(_ki,{role:`radio`,checked:l===t.value,label:t.label,onClick:()=>n(e.id,t.value)},t.value)),!e.omitAnyOption&&(0,K.jsx)(_ki,{role:`radio`,checked:l===`Any`,label:`Any`,onClick:()=>n(e.id,`Any`)})]})})]})}function yki(e){return Array.isArray(e)?e.length===0?`Any`:e.join(`, `):e}var bki=`This filter is set by the current context and cannot be removed here.`;function xki(e,t){return e.kind===`pick-multi`&&e.options?Array.isArray(t)?t.length===0?`Any`:t.map(t=>e.options.find(e=>e.value===t)?.label??t).join(`, `):e.options.find(e=>e.value===t)?.label??t:yki(t)}function Ski({field:e,value:t,tooltipContent:n}){let r=xki(e,t),i=`${e.label} filter is locked by context`;return(0,K.jsx)(Sx,{delayDuration:150,children:(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{asChild:!0,children:(0,K.jsxs)($V,{"data-locked-field-id":e.id,"data-property-filter-pill":`locked`,tabIndex:0,"aria-label":i,children:[(0,K.jsx)(eH,{children:e.label}),(0,K.jsx)(eH,{children:`is`}),(0,K.jsx)(eH,{children:r}),(0,K.jsx)(eH,{children:(0,K.jsx)(CH,{})})]})}),(0,K.jsx)(Tx,{children:n})]})})}function Cki({field:e,value:t,onChange:n,onRemove:r,disabled:i,autoFocus:a}){let[o,s]=(0,G.useState)(t),c=(0,G.useRef)(null);return(0,G.useEffect)(()=>{o.trim()!==t&&s(t)},[t]),(0,G.useEffect)(()=>{a&&c.current?.focus()},[a]),(0,K.jsxs)($V,{children:[(0,K.jsx)(eH,{children:e.label}),(0,K.jsx)(eH,{children:`is`}),(0,K.jsx)(Jj,{ref:c,disabled:i,value:o,placeholder:e.placeholder??`Enter ${e.label}`,onChange:e=>{let r=e.target.value;s(r),r.trim()!==t&&n(r)},onKeyDown:e=>{if(e.key===`Enter`){e.preventDefault();let r=o.trim();r!==t&&n(r)}else e.key===`Escape`&&(e.preventDefault(),s(t),e.currentTarget.blur())}}),(0,K.jsx)(X,{size:`icon-md`,type:`button`,disabled:i,"aria-label":`Remove ${e.label} filter`,onMouseDown:e=>e.preventDefault(),onClick:r,children:(0,K.jsx)(xw,{})})]})}function wki({field:e,token:t,tokens:n,onChange:r,onRemove:i,disabled:a}){let[o,s]=(0,G.useState)(!1);return(0,K.jsxs)($V,{children:[(0,K.jsx)(eH,{children:e.label}),(0,K.jsx)(eH,{children:`is`}),(0,K.jsxs)(Xj,{open:o,onOpenChange:s,children:[(0,K.jsx)(Zj,{asChild:!0,children:(0,K.jsx)(X,{type:`button`,disabled:a,children:yki(t.value)})}),(0,K.jsx)(Qj,{align:`start`,sideOffset:4,className:`w-64 p-0`,"data-pick-multi-panel":!0,children:(0,K.jsx)(vki,{field:e,tokens:n,onChange:r})})]}),(0,K.jsx)(X,{size:`icon-md`,type:`button`,disabled:a,"aria-label":`Remove ${e.label} filter`,onClick:i,children:(0,K.jsx)(xw,{})})]})}function Tki({fields:e,tokens:t,onTokensChange:n,disabled:r,autoFocusFieldId:i,lockedFieldIds:a,lockedTooltipContent:o=bki}){if(t.length===0)return null;let s=new Set(a??[]),c=(e,r)=>{let i=[...t];i[e]=r,n(i)},l=e=>{n(t.filter((t,n)=>n!==e))};return(0,K.jsx)(`div`,{className:`flex flex-wrap items-center gap-2`,children:t.map((n,a)=>{let u=e.find(e=>e.id===n.fieldId);return u?s.has(n.fieldId)?(0,K.jsx)(Ski,{field:u,value:n.value,tooltipContent:o},`${n.fieldId}-${a}`):u.kind===`text`&&!Array.isArray(n.value)?(0,K.jsx)(Cki,{field:u,value:n.value,disabled:r,autoFocus:i===n.fieldId,onChange:e=>c(a,{fieldId:n.fieldId,value:e}),onRemove:()=>l(a)},`${n.fieldId}-${a}`):u.kind===`pick-multi`?(0,K.jsx)(wki,{field:u,token:n,tokens:t,disabled:r,onChange:(e,t)=>c(a,{fieldId:e,value:t}),onRemove:()=>l(a)},`${n.fieldId}-${a}`):(0,K.jsxs)($V,{children:[(0,K.jsx)(eH,{children:u.label}),(0,K.jsx)(eH,{children:`is`}),(0,K.jsx)(eH,{children:yki(n.value)}),(0,K.jsx)(X,{size:`icon-md`,type:`button`,disabled:r,"aria-label":`Remove ${u.label} filter`,onClick:()=>l(a),children:(0,K.jsx)(xw,{})})]},`${n.fieldId}-${a}`):null})})}var Eki=U(`IconFilter1`,()=>(0,K.jsx)(`path`,{d:`M18 4H6C4.89543 4 4 4.89543 4 6V7.17157C4 7.70201 4.21071 8.21071 4.58579 8.58579L9.41421 13.4142C9.78929 13.7893 10 14.298 10 14.8284V20.057C10 20.7552 10.6974 21.2385 11.3511 20.9933L13.3511 20.2433C13.7414 20.097 14 19.7238 14 19.307V14.8284C14 14.298 14.2107 13.7893 14.5858 13.4142L19.4142 8.58579C19.7893 8.21071 20 7.70201 20 7.17157V6C20 4.89543 19.1046 4 18 4Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinejoin:`round`})),Dki=(0,G.forwardRef)((e,t)=>(0,K.jsx)(`button`,{type:`button`,role:`menuitem`,"data-filter-item":``,ref:t,...e}));Dki.displayName=`FilterMenuButton`;function Oki({fields:e,tokens:t,onTokensChange:n,label:r=`Add filter`,disabled:i,size:a,onStartTextFilter:o,hiddenFieldIds:s}){let l=(0,G.useMemo)(()=>{if(!s||s.length===0)return e;let t=new Set(s);return e.filter(e=>!t.has(e.id))},[e,s]),[u,d]=(0,G.useState)(!1),[f,p]=(0,G.useState)(),[m,h]=(0,G.useState)([]),[g,_]=(0,G.useState)(),[v,y]=(0,G.useState)(),b=(0,G.useRef)(!1),x=(0,G.useCallback)(e=>{y(t=>t===e?void 0:e)},[]),S=(0,G.useCallback)(()=>y(void 0),[]);(0,G.useEffect)(()=>{u||y(void 0)},[u]);let C=(0,G.useMemo)(()=>l.find(e=>e.id===f),[l,f]),w=(0,G.useMemo)(()=>{let n=new Set;for(let r of t){let t=e.find(e=>e.id===r.fieldId);t&&t.kind!==`pick-multi`&&n.add(r.fieldId)}return n},[t,e]),E=(0,G.useCallback)(()=>{p(void 0),h([]),_(void 0)},[]);(0,G.useEffect)(()=>{u||E()},[u,E]);let D=(0,G.useCallback)((e,r)=>{let i=t.findIndex(t=>t.fieldId===e);if(Array.isArray(r)&&r.length===0){if(i===-1)return;n(t.filter((e,t)=>t!==i));return}if(i===-1){n([...t,{fieldId:e,value:r}]);return}let a=[...t];a[i]={fieldId:e,value:r},n(a)},[n,t]),O=(0,G.useCallback)(()=>{C?w.has(C.id)?_(`Remove the existing ${C.label} filter before adding another.`):m.length===0?_(`Choose at least one ${C.label.toLowerCase()} value.`):(n([...t,{fieldId:C.id,value:m}]),d(!1)):_(`Choose a property first.`)},[m,n,C,w,t]);return(0,K.jsxs)(Xj,{open:u,onOpenChange:d,children:[(0,K.jsx)(Zj,{asChild:!0,children:(0,K.jsx)(X,{size:a,disabled:i,icon:(0,K.jsx)(NZ,{}),children:r})}),(0,K.jsx)(Qj,{align:`start`,sideOffset:4,className:c(`w-64`,C?`p-3`:`p-1`),initialFocus:!1,finalFocus:()=>!b.current||(b.current=!1,!1),children:(0,K.jsxs)(`div`,{className:c(`grid`,C&&`gap-3`),children:[C&&(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`button`,{type:`button`,"aria-label":`Back to properties`,className:c(`text-muted-foreground hover:text-foreground`,`transition-[color] duration-fast ease-out-custom motion-reduce:transition-none`),onClick:E,children:(0,K.jsx)(sS,{className:`size-icon-md`})}),(0,K.jsx)(Eki,{className:`size-icon-md shrink-0 text-muted-foreground`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:`${C.label} is`})]}),!C&&(0,K.jsx)(`div`,{role:`menu`,className:`max-h-[80dvh] overflow-auto`,onKeyDown:e=>{if(e.key!==`ArrowDown`&&e.key!==`ArrowUp`&&e.key!==`Home`&&e.key!==`End`)return;let t=Array.from(e.currentTarget.querySelectorAll(`[data-filter-item]:not([disabled])`));if(t.length===0)return;e.preventDefault();let n=document.activeElement,r=t.findIndex(e=>e===n),i;i=e.key===`Home`?0:e.key===`End`?t.length-1:e.key===`ArrowDown`?r<0?0:(r+1)%t.length:r<=0?t.length-1:r-1,t[i]?.focus()},children:(0,K.jsx)(K.Fragment,{children:l.length>0?l.map(e=>{let r=w.has(e.id);return e.kind===`pick-multi`?(0,K.jsx)(kki,{field:e,tokens:t,onChange:D,open:v===e.id,onToggle:x,onClose:S},e.id):(0,K.jsxs)(Dki,{className:c(kT,`group`),disabled:r,onClick:()=>{_(void 0),e.kind===`text`?(n([...t,{fieldId:e.id,value:``}]),o?.(e.id),b.current=!0,d(!1)):p(e.id)},children:[(0,K.jsx)(`span`,{className:`truncate`,children:e.label}),r?(0,K.jsx)(`span`,{className:`ml-auto text-muted-foreground`,children:`In use`}):(0,K.jsx)(`span`,{className:c(AT,`text-muted-foreground opacity-0 group-hover:opacity-100 group-focus:opacity-100`),children:(0,K.jsx)(Hx,{})})]},e.id)}):(0,K.jsx)(`div`,{className:`flex h-control-md items-center gap-2 px-2 py-0.5 text-menu text-muted-foreground box-content`,children:`No matching property.`})})}),C&&(0,K.jsxs)(ak,{invalid:!!g,children:[(0,K.jsx)(_N,{multiple:!0,options:C.options??[],value:m,onValueChange:e=>{h(e),_(void 0)},placeholder:C.placeholder??`Choose ${C.label}`,searchPlaceholder:`Search ${C.label.toLowerCase()}`,emptyText:C.emptyText??`No option found.`,size:`md`,"aria-label":C.label}),(0,K.jsx)(lk,{children:g})]}),C&&(0,K.jsxs)(`div`,{className:`flex items-center justify-end gap-2`,children:[(0,K.jsx)(X,{icon:(0,K.jsx)(xw,{}),variant:`ghost`,size:`md`,onClick:()=>d(!1),children:`Cancel`}),(0,K.jsx)(X,{icon:(0,K.jsx)(NZ,{}),size:`md`,onClick:O,children:`Add filter`})]})]})})]})}function kki({field:e,tokens:t,onChange:n,open:r,onToggle:i,onClose:a}){let o=(0,G.useRef)(null);return(0,K.jsxs)(Xj,{open:r,onOpenChange:t=>{t?i(e.id):a()},children:[(0,K.jsx)(Zj,{asChild:!0,children:(0,K.jsxs)(Dki,{className:kT,onKeyDown:t=>{(t.key===`ArrowRight`||t.key===`ArrowLeft`)&&(r||i(e.id),t.preventDefault(),requestAnimationFrame(()=>{(o.current?.querySelector(`input, button, [tabindex]:not([tabindex="-1"])`))?.focus()}))},children:[r&&(0,K.jsx)(f,{className:`text-muted-foreground`}),(0,K.jsx)(`span`,{className:`truncate`,children:e.label}),!r&&(0,K.jsx)(`span`,{className:c(AT,`text-muted-foreground`),children:(0,K.jsx)(f,{})})]})}),(0,K.jsx)(Qj,{ref:o,side:`right`,align:`start`,sideOffset:4,className:`w-64 p-0`,initialFocus:!1,onKeyDown:e=>{if(e.key!==`ArrowDown`&&e.key!==`ArrowUp`&&e.key!==`Home`&&e.key!==`End`)return;let t=Array.from(e.currentTarget.querySelectorAll(`[data-pick-multi-item]:not([disabled])`));if(t.length===0)return;e.preventDefault(),e.stopPropagation();let n=document.activeElement,r=t.findIndex(e=>e===n),i;i=e.key===`Home`?0:e.key===`End`?t.length-1:e.key===`ArrowDown`?r<0?0:(r+1)%t.length:r<=0?t.length-1:r-1,t[i]?.focus()},"data-pick-multi-panel":!0,children:(0,K.jsx)(vki,{field:e,tokens:t,onChange:n})})]})}function Aki({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:i,onNext:a,depth:o,actions:s}){let c=e?xC(e.timestamp)??``:``;return(0,K.jsx)(jQ,{open:!!e,onClose:t,title:e?`Log ${c}`:`Log`,depth:o,children:e&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(jQ.Header,{children:[(0,K.jsx)(jQ.CloseButton,{onClick:t}),(0,K.jsx)(jQ.Heading,{children:`Log`}),(0,K.jsx)(jQ.Metadata,{children:(0,K.jsx)(jQ.Meta,{tooltip:c,children:c})}),(0,K.jsxs)(jQ.HeaderActions,{children:[s,(0,K.jsx)(jQ.NextPrevNav,{onPrevious:i,onNext:a,previousLabel:`Go to previous log`,nextLabel:`Go to next log`})]})]}),(0,K.jsx)(jQ.Content,{children:(0,K.jsxs)(`div`,{className:`grid gap-6 p-2`,children:[(0,K.jsxs)(V4,{children:[e.entityType&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(V4.Key,{children:`Entity Type`}),(0,K.jsx)(V4.Value,{children:e.entityType})]}),e.entityName&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(V4.Key,{children:`Entity Name`}),(0,K.jsx)(V4.Value,{children:e.entityName})]}),e.serviceName&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(V4.Key,{children:`Service`}),(0,K.jsx)(V4.Value,{children:e.serviceName})]}),e.environment&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(V4.Key,{children:`Environment`}),(0,K.jsx)(V4.Value,{children:e.environment})]}),e.source&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(V4.Key,{children:`Source`}),(0,K.jsx)(V4.Value,{children:e.source})]}),e.metadata&&Object.entries(e.metadata).map(([e,t])=>(0,K.jsxs)(G.Fragment,{children:[(0,K.jsx)(V4.Key,{children:e}),(0,K.jsx)(V4.Value,{children:String(t)})]},e))]}),(0,K.jsx)(jQ.CodeSection,{title:`Message`,codeStr:e.message,simplified:!0}),(e.traceId||e.spanId)&&(0,K.jsxs)(`div`,{className:`grid gap-2`,children:[e.traceId&&(0,K.jsxs)($V,{className:`w-full min-w-0`,children:[(0,K.jsxs)(X,{className:`min-w-0 flex-1 justify-between overflow-hidden`,icon:(0,K.jsx)(oH,{}),onClick:()=>e.traceId&&n?.(e.traceId),children:[(0,K.jsx)(`span`,{children:`Trace`}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,tone:`faint`,className:`ml-auto min-w-0 truncate`,children:[`# `,e.traceId]})]}),(0,K.jsx)(gC,{content:e.traceId,tooltip:`Copy trace ID to clipboard`})]}),e.spanId&&(0,K.jsxs)($V,{className:`w-full min-w-0`,children:[(0,K.jsxs)(X,{className:`min-w-0 flex-1 justify-between overflow-hidden`,disabled:!e.traceId||!r,onClick:()=>e.traceId&&e.spanId&&r?.(e.traceId,e.spanId),icon:(0,K.jsx)(oH,{}),children:[(0,K.jsx)(`span`,{children:`Span`}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,tone:`faint`,className:`ml-auto min-w-0 truncate`,children:[`# `,e.spanId]})]}),(0,K.jsx)(gC,{content:e.spanId,tooltip:`Copy span ID to clipboard`})]})]}),e.data&&Object.keys(e.data).length>0&&(0,K.jsx)(jQ.CodeSection,{title:`Data`,codeStr:JSON.stringify(e.data,null,2)})]})})]})})}function jki({error:e,resource:t,errorTitle:n}){if(FN(e))return(0,K.jsx)(TH,{});if(IN(e))return(0,K.jsx)(wH,{resource:t});if(zN(e))return(0,K.jsx)(Jx,{titleSlot:`Observability storage is not available`,descriptionSlot:`The observability storage domain is disabled or not configured. Enable it in your storage configuration to view logs in Studio.`});if(RN(e,`logs`))return(0,K.jsx)(Jx,{titleSlot:`Logs are not available with your current storage`,descriptionSlot:`The configured observability storage provider does not support listing logs. Switch to a storage provider with logs support to view runtime logs in Studio.`});let r=e instanceof Error?e.message:void 0;return(0,K.jsx)(Jx,{tone:`error`,titleSlot:n,descriptionSlot:r??`Unknown error`})}var Mki={debug:`neutral`,info:`info`,warn:`warning`,error:`destructive`,fatal:`destructive`};function Nki({level:e}){return(0,K.jsx)(uH,{children:(0,K.jsx)(eC,{variant:Mki[e],children:e})})}function Pki({entityType:e,className:t}){let n=c(`size-3.5 shrink-0 text-placeholder`,t);switch(e.toLowerCase()){case`agent`:return(0,K.jsx)(HN,{className:n,"aria-hidden":!0});case`workflow`:case`workflow_run`:return(0,K.jsx)(ZS,{className:n,"aria-hidden":!0});case`tool`:return(0,K.jsx)(XN,{className:n,"aria-hidden":!0});default:return null}}function Fki({entityType:e,entityName:t}){return(0,K.jsxs)(uH,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(Pki,{entityType:e??``}),t?(0,K.jsx)(T,{as:`span`,variant:`body-sm`,className:`min-w-0 truncate`,children:t}):`-`]})}function Iki({message:e}){return(0,K.jsx)(uH,{className:`min-w-0 truncate font-mono text-body-sm text-muted-foreground`,children:e})}function Lki({data:e}){if(!e||Object.keys(e).length===0)return(0,K.jsx)(uH,{children:null});let t=Object.entries(e).map(([e,t])=>{if(typeof t==`string`)return`${e}: ${t}`;try{return`${e}: ${JSON.stringify(t)}`}catch{return`${e}: <unserializable>`}}).join(`, `);return(0,K.jsx)(pH,{font:`mono`,children:t})}var P9=Object.assign(_H,{Top:SH,TopCell:yH,SortableTopCell:xH,TopCellWithTooltip:bH,TopCellSmart:dmn,RowWrapper:omn,RowButton:vH,RowLink:imn,Spacer:_mn,NoMatch:hH,DateCell:Epn,TimeCell:Opn,LevelCell:Nki,EntityCell:Fki,MessageCell:Iki,DataCell:Lki,NextPageLoading:mH}),Rki=`6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)`,zki=36,Bki=8;function Vki({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:i,logIdMap:a,featuredLogId:o,onLogClick:s,timestampSort:c,onSortChange:l}){let u=(0,G.useRef)(null),d=s7r({count:e.length,getScrollElement:()=>u.current,estimateSize:()=>zki,overscan:Bki}),{getRowProps:f}=PZ({count:e.length,containerRef:u,onNavigate:e=>d.scrollToIndex(e),global:!0}),p=(0,G.useRef)(t);if((0,G.useEffect)(()=>{p.current&&!t&&u.current?.dispatchEvent(new Event(`scroll`)),p.current=t},[t]),t)return(0,K.jsx)(DH,{columns:Rki,fit:`container`});let m=d.getVirtualItems(),h=d.getTotalSize(),g=m[0]?.start??0,_=m.length>0?Math.max(0,h-(m[m.length-1]?.end??0)):0;return(0,K.jsxs)(P9,{columns:Rki,scrollRef:u,className:`min-w-0`,fit:`container`,children:[(0,K.jsxs)(P9.Top,{children:[l?(0,K.jsx)(P9.SortableTopCell,{sortKey:`timestamp`,sort:c,onSortChange:l,children:`Date`}):(0,K.jsx)(P9.TopCell,{children:`Date`}),(0,K.jsx)(P9.TopCell,{children:`Time`}),(0,K.jsx)(P9.TopCell,{children:`Level`}),(0,K.jsx)(P9.TopCell,{children:`Entity`}),(0,K.jsx)(P9.TopCell,{children:`Message`}),(0,K.jsx)(P9.TopCell,{children:`Data`})]}),e.length===0?(0,K.jsx)(P9.NoMatch,{message:`No logs match your search`}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(P9.Spacer,{height:g}),m.map(t=>{let n=e[t.index];if(!n)return null;let r=a.get(n);if(!r)return null;let i=r===o;return(0,K.jsxs)(P9.RowButton,{ref:d.measureElement,"data-index":t.index,...f(t.index),onClick:()=>s(n),featured:i,variant:n.level===`error`||n.level===`fatal`?`error`:`default`,children:[(0,K.jsx)(P9.DateCell,{timestamp:n.timestamp}),(0,K.jsx)(P9.TimeCell,{timestamp:n.timestamp}),(0,K.jsx)(P9.LevelCell,{level:n.level}),(0,K.jsx)(P9.EntityCell,{entityType:n.entityType,entityName:n.entityName}),(0,K.jsx)(P9.MessageCell,{message:n.message}),(0,K.jsx)(P9.DataCell,{data:n.data})]},r)}),(0,K.jsx)(P9.Spacer,{height:_})]}),(0,K.jsx)(P9.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:i})]})}function Hki({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:i,filterFields:a,filterTokens:o,onFilterTokensChange:s,autoFocusFilterFieldId:l}){let u=o.length>0,d=o.some(e=>Uki(e,a));return u?(0,K.jsxs)(`div`,{className:c(`grid grid-cols-[1fr_auto] items-start gap-3`),children:[(0,K.jsx)(Tki,{fields:a,tokens:o,onTokensChange:s,disabled:i,autoFocusFieldId:l}),u&&(0,K.jsx)(hki,{disabled:i,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]}):null}function Uki(e,t){let n=t.find(t=>t.id===e.fieldId);return n?n.kind===`text`?typeof e.value==`string`&&e.value.trim()!==``:n.kind===`pick-multi`?n.multi?Array.isArray(e.value)&&e.value.length>0:typeof e.value==`string`&&e.value!==``&&e.value!==`Any`:n.kind===`multi-select`&&Array.isArray(e.value)&&e.value.length>0:!1}var Wki={"last-24h":`the last 24 hours`,"last-3d":`the last 3 days`,"last-7d":`the last 7 days`,"last-14d":`the last 14 days`,"last-30d":`the last 30 days`},Gki=`Pick a wider range or lower the logging level. Verbose entries (debug, info) may be filtered out.`;function Kki({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!==`all`&&e!==`custom`?{title:`No logs for ${Wki[e]}`,description:Gki}:t&&n?{title:`No logs between ${bC(t,`date-time`)} and ${bC(n,`date-time`)}`,description:Gki}:t?{title:`No logs since ${bC(t,`date-time`)}`,description:Gki}:{title:`No logs yet`,description:`Logs will appear here once agents, workflows, or tools are executed.`}}var qki=({datePreset:e,dateFrom:t,dateTo:n}={})=>{let{title:r,description:i}=Kki({datePreset:e,dateFrom:t,dateTo:n});return(0,K.jsx)(Jx,{titleSlot:r,descriptionSlot:i,actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/en/docs/observability/logging`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(tP,{}),children:`Logging documentation`}),variant:`fill`})},Jki=`Filters setting for Logs saved`,Yki=`Filters setting for Logs cleared up`;function Xki(e,t,n){let{storageKey:r,messages:i,skipHydration:a}=n??{},[o,s]=(0,G.useState)(()=>Yii(r)!==null),c=(0,G.useCallback)(()=>{qii(e,r),s(!0);let t=i?.saved??Jki;t!==!1&&iS.success(t)},[e,r,i?.saved]),l=(0,G.useCallback)(()=>{Jii(r),s(!1);let e=i?.cleared??Yki;e!==!1&&iS.success(e)},[r,i?.cleared]),u=(0,G.useRef)(!1);return(0,G.useEffect)(()=>{if(a||u.current||(u.current=!0,Xii(e)))return;let n=Yii(r);n&&t(e=>{let t=new URLSearchParams(e);for(let[e,r]of n)t.append(e,r);return t},{replace:!0})},[]),{hasSavedFilters:o,handleSave:c,handleRemoveSaved:l}}function Zki(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return(t>>>0).toString(36)}function Qki(e){let t=new Map;for(let n of e){if(n.logId){t.set(n,n.logId);continue}let e=n.timestamp instanceof Date?n.timestamp.toISOString():n.timestamp;t.set(n,Zki(`${e}${n.message??``}${n.data?JSON.stringify(n.data):``}`))}return t}function $ki(e,t,n,r){let i=(0,G.useMemo)(()=>Qki(e),[e]),a=(0,G.useMemo)(()=>{let t=new Map;for(let[n,r]of e.entries()){let e=i.get(r);e&&t.set(e,{log:r,idx:n})}return t},[e,i]),o=(t?a.get(t):void 0)?.idx??-1,s=o>=0?e[o]??null:null;return{logIdMap:i,getLogId:(0,G.useCallback)(e=>i.get(e),[i]),featuredLog:s,handleLogClick:(0,G.useCallback)(e=>{let a=i.get(e);a&&n(t===a?{logId:null}:r?{logId:a,traceId:e.traceId??null,spanId:null}:{logId:a})},[i,t,r,n]),handlePreviousLog:o>0?()=>{let t=e[o-1];if(!t)return;let a=i.get(t);a&&n(r?{logId:a,traceId:t.traceId??null,spanId:null}:{logId:a})}:void 0,handleNextLog:o>=0&&o<e.length-1?()=>{let t=e[o+1];if(!t)return;let a=i.get(t);a&&n(r?{logId:a,traceId:t.traceId??null,spanId:null}:{logId:a})}:void 0}}var eAi=`logId`,tAi=`traceId`,nAi=`spanId`,F9=864e5,rAi={"last-24h":F9,"last-3d":3*F9,"last-7d":7*F9,"last-14d":14*F9,"last-30d":30*F9};function iAi(e){e.delete(eAi),e.delete(tAi),e.delete(nAi)}function aAi(e,t,n){let{onRemoveAll:r}=n??{},i=(0,G.useMemo)(()=>{let t=e.get(p7);return t&&Wii.has(t)?t:Vii},[e]),a=e.get(m7),o=e.get(h7),s=(0,G.useMemo)(()=>{if(i===`custom`){if(!a)return;let e=new Date(a);return Number.isNaN(e.getTime())?void 0:e}if(i===`all`)return;let e=rAi[i];return e?new Date(Date.now()-e):void 0},[i,a]),c=(0,G.useMemo)(()=>{if(i!==`custom`||!o)return;let e=new Date(o);return Number.isNaN(e.getTime())?void 0:e},[i,o]),l=(0,G.useRef)(i);l.current=i;let u=e.get(eAi),d=e.get(tAi),f=e.get(nAi),p=(0,G.useMemo)(()=>zii.find(t=>t.entityType===e.get(f7)),[e]),m=(0,G.useMemo)(()=>Qii(e),[e]),h=(0,G.useCallback)(e=>{t(t=>{let n=new URLSearchParams(t);for(let[t,r]of Object.entries(e)){let e=t===`logId`?eAi:t===`traceId`?tAi:nAi;r?n.set(e,r):n.delete(e)}return n},{replace:!0})},[t]),g=(0,G.useCallback)(e=>{t(t=>{let n=new URLSearchParams(t);return eai(n,e),iAi(n),n},{replace:!0})},[t]),_=g,v=(0,G.useCallback)((e,n)=>{if(l.current!==`custom`)return;let r=n===`from`?m7:h7;t(t=>{let n=new URLSearchParams(t);return e?n.set(r,e.toISOString()):n.delete(r),iAi(n),n},{replace:!0})},[t]),y=(0,G.useCallback)(e=>{l.current=e,t(t=>{let n=new URLSearchParams(t);return e===`last-24h`?(n.delete(p7),n.delete(m7),n.delete(h7)):e===`custom`?n.set(p7,`custom`):(n.set(p7,e),n.delete(m7),n.delete(h7)),iAi(n),n},{replace:!0})},[t]),b=(0,G.useCallback)(()=>{t(e=>{let t=new URLSearchParams(e);t.delete(f7);for(let e of _7)t.delete(g7[e]);return t.delete(p7),t.delete(m7),t.delete(h7),iAi(t),t},{replace:!0}),r?.()},[t,r]);return(0,G.useMemo)(()=>({searchParams:e,setSearchParams:t,datePreset:i,selectedDateFrom:s,selectedDateTo:c,datePresetRef:l,featuredLogId:u,featuredTraceId:d,featuredSpanId:f,selectedEntityOption:p,filterTokens:m,handleFeaturedChange:h,handleFilterTokensChange:_,handleDateChange:v,handleDatePresetChange:y,handleRemoveAll:b,applyFilterTokens:g}),[e,t,i,s,c,l,u,d,f,p,m,h,_,v,y,b,g])}var oAi=20,sAi=1e4,cAi={field:`timestamp`,direction:`DESC`};function lAi(e,t,n){if(e?.pagination?.hasMore)return n+1}function uAi(e){let t=new Set,n=[];for(let r of e.pages)for(let e of r.logs??[]){let r=e.logId??JSON.stringify(e);t.has(r)||(t.add(r),n.push(e))}return n}function dAi(e){return RN(e.state.error,`logs`)||zN(e.state.error)?!1:sAi}var fAi=({filters:e,orderBy:t=cAi,queryOptions:n}={})=>{let r=Y(),{inView:i,setRef:a}=$M(),{hasNextPage:o,isFetchingNextPage:s,fetchNextPage:c,data:l,isLoading:u,isError:d,error:f}=O_({queryKey:[`logs`,e,t],queryFn:({pageParam:n})=>r.listLogsVNext({pagination:{page:n,perPage:oAi},filters:e,orderBy:t}),initialPageParam:0,getNextPageParam:lAi,select:uAi,retry:!1,refetchInterval:dAi,...n});return(0,G.useEffect)(()=>{i&&o&&!s&&c()},[i,o,s,c]),{data:l,hasNextPage:o,isFetchingNextPage:s,fetchNextPage:c,isLoading:u,isError:d,error:f,setEndOfListElement:a}},pAi=[eP(`/logs`)];function mAi(){let[e,t]=Rv(),n=Ov(),r=aAi(e,t),i=a5(),{sort:a,onSortChange:o}=u7({searchParams:e,setSearchParams:t,allowedKeys:Hii,defaultSort:Uii}),s=(0,G.useMemo)(()=>({field:`timestamp`,direction:a?.direction===`asc`?`ASC`:`DESC`}),[a?.direction]),c=Xki(e,t),[l,u]=(0,G.useState)(),{data:d=[],isPending:f}=NYr(),{data:p=[],isPending:m}=t8({entityType:r.selectedEntityOption?.entityType,rootOnly:!0}),{data:h=[],isPending:g}=n8(),{data:_=[],isPending:v}=jYr(),y=(0,G.useMemo)(()=>Zii({availableTags:d,availableRootEntityNames:p,availableServiceNames:_,availableEnvironments:h,loading:{tags:f,entityNames:m,serviceNames:v,environments:g}}),[d,p,_,h,f,m,v,g]),{data:b=[],isLoading:x,error:S,isFetchingNextPage:C,hasNextPage:w,setEndOfListElement:T}=fAi({filters:(0,G.useMemo)(()=>tai({rootEntityType:r.selectedEntityOption?.entityType,dateFrom:r.selectedDateFrom,dateTo:r.selectedDateTo,tokens:r.filterTokens}),[r.filterTokens,r.selectedDateFrom,r.selectedDateTo,r.selectedEntityOption]),orderBy:s}),{logIdMap:E,featuredLog:D,handleLogClick:O,handlePreviousLog:k,handleNextLog:A}=$ki(b,r.featuredLogId,r.handleFeaturedChange,r.featuredTraceId),{data:j,isLoading:M}=i8({traceId:r.featuredTraceId??null,queryOptions:{enabled:!!r.featuredTraceId}}),N=(0,G.useCallback)(()=>r.applyFilterTokens(nai(y,r.filterTokens)),[y,r]),P=(0,G.useCallback)(()=>r.handleFeaturedChange({logId:null}),[r]),F=(0,G.useCallback)(e=>r.handleFeaturedChange({traceId:e,spanId:null}),[r]),I=(0,G.useCallback)((e,t)=>r.handleFeaturedChange({traceId:e,spanId:t}),[r]),L=(0,G.useCallback)(()=>r.handleFeaturedChange({traceId:null,spanId:null}),[r]),R=(0,G.useCallback)(e=>r.handleFeaturedChange({spanId:e??null}),[r]),z=(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(TK,{children:(0,K.jsxs)(TK.Start,{children:[(0,K.jsx)(Nhn,{preset:r.datePreset,onPresetChange:r.handleDatePresetChange,dateFrom:r.selectedDateFrom,dateTo:r.selectedDateTo,onDateChange:r.handleDateChange,disabled:x,presets:[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`]}),(0,K.jsx)(Oki,{fields:y,tokens:r.filterTokens,onTokensChange:r.handleFilterTokensChange,disabled:x,onStartTextFilter:u,size:`sm`})]})}),(0,K.jsx)(Hki,{isLoading:x,filterFields:y,filterTokens:r.filterTokens,onFilterTokensChange:r.handleFilterTokensChange,onClear:N,onRemoveAll:r.handleRemoveAll,onSave:c.handleSave,onRemoveSaved:c.hasSavedFilters?c.handleRemoveSaved:void 0,autoFocusFilterFieldId:l})]});if(S)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:pAi}),actionRow:z,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Logs`}),(0,K.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:(0,K.jsx)(jki,{error:S,resource:`logs`,errorTitle:`Failed to load logs`})})]});let B=!!r.selectedEntityOption||r.filterTokens.length>0;return b.length===0&&!x&&!B?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:pAi}),actionRow:z,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Logs`}),(0,K.jsx)(qki,{datePreset:r.datePreset,dateFrom:r.selectedDateFrom,dateTo:r.selectedDateTo})]}):(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:pAi}),actionRow:z,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Logs`}),(0,K.jsx)(Vki,{logs:b,isLoading:x,isFetchingNextPage:C,hasNextPage:w,setEndOfListElement:T,logIdMap:E,featuredLogId:r.featuredLogId,onLogClick:O,timestampSort:a?.direction,onSortChange:o}),(0,K.jsx)(Aki,{log:D??void 0,onClose:P,onTraceClick:F,onSpanClick:I,onPrevious:k,onNext:A}),(0,K.jsx)(n_i,{depth:2,traceId:D?r.featuredTraceId??void 0:void 0,spans:j?.spans,isLoadingSpans:M,selectedSpanId:r.featuredSpanId??null,onSpanSelect:R,onClose:L,withQueryTrace:i.enabled,withFeedback:i.enabled,onOpenScore:(e,t)=>n(CK(e,t))})]})}function hAi(){let e=Y();return T_({queryKey:[`builtin-mcp-server`],queryFn:()=>e.getBuiltinMcpServer(),retry:!1})}var gAi=`<your-token>`;function _Ai(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function vAi(e,{protectedServer:t}){let n=_Ai(e),r=`Authorization: Bearer ${gAi}`,i=t?{headers:{Authorization:`Bearer ${gAi}`}}:{};return[{value:`claude-code`,label:`Claude Code`,lang:`bash`,code:`claude mcp add --transport http mastra ${n}${t?` --header "${r}"`:``}`},{value:`cursor`,label:`Cursor`,lang:`json`,code:JSON.stringify({mcpServers:{mastra:{url:e,...i}}},null,2)},{value:`vscode`,label:`VS Code`,lang:`json`,code:JSON.stringify({servers:{mastra:{type:`http`,url:e,...i}}},null,2)},{value:`inspector`,label:`MCP Inspector`,lang:`bash`,code:`npx @modelcontextprotocol/inspector --cli ${n} --transport http${t?` --header "${r}"`:``} --method tools/list`}]}var yAi=`https://mastra.ai/docs/server/mcp`;function bAi(){let{data:e,error:t}=hAi();return e?(0,K.jsx)(xAi,{descriptor:e}):!t||FN(t)||IN(t)||LN(t)?null:(0,K.jsx)(SAi,{children:(0,K.jsx)(Sk,{variant:`destructive`,children:`Couldn't load the built-in MCP server. Try reloading the page.`})})}function xAi({descriptor:e}){return(0,K.jsx)(SAi,{status:(0,K.jsx)(CAi,{descriptor:e}),children:e.enabled?e.mcpPackageInstalled?(0,K.jsx)(DAi,{descriptor:e}):(0,K.jsx)(EAi,{}):(0,K.jsx)(TAi,{descriptor:e})})}function SAi({status:e,children:t}){return(0,K.jsxs)(nP,{role:`region`,"aria-label":`Mastra (built-in) MCP server`,children:[(0,K.jsxs)(rP,{className:`flex-row flex-wrap items-center gap-3 space-y-0 border-b border-border`,children:[(0,K.jsx)(iP,{className:`shrink-0`,children:`Mastra (built-in)`}),e]}),(0,K.jsx)(oP,{className:`flex flex-col gap-4`,children:t})]})}function CAi({descriptor:e}){let{label:t,variant:n}=wAi(e);return(0,K.jsx)(eC,{variant:n,emphasis:`subtle`,indicator:`dot`,children:t})}function wAi(e){if(!e.enabled)return{label:`Disabled`,variant:`neutral`};if(!e.mcpPackageInstalled)return{label:`Not installed`,variant:`warning`};let{auth:t}=e;return t.type===`protected`?{label:`Protected by ${t.provider??`server auth`}`,variant:`success`}:t.devOnly?{label:`Open in dev only`,variant:`info`}:{label:`Open to anyone`,variant:`warning`}}function TAi({descriptor:e}){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{tone:`muted`,children:e.disabledReason===`config`?(0,K.jsxs)(K.Fragment,{children:[`The built-in MCP server is turned off because `,(0,K.jsx)(uX,{children:`server.mcp.enabled`}),` is`,` `,(0,K.jsx)(uX,{children:`false`}),`.`]}):(0,K.jsxs)(K.Fragment,{children:[`The built-in MCP server only runs under `,(0,K.jsx)(uX,{children:`mastra dev`}),` unless the server has auth. Configure `,(0,K.jsx)(uX,{children:`server.auth`}),`, or set `,(0,K.jsx)(uX,{children:`server.mcp.enabled`}),` to`,` `,(0,K.jsx)(uX,{children:`true`}),`.`]})}),(0,K.jsx)(kAi,{})]})}function EAi(){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(T,{tone:`muted`,children:[`The built-in MCP server is enabled, but it needs the `,(0,K.jsx)(uX,{children:`@mastra/mcp`}),` package. Install it and restart the server.`]}),(0,K.jsx)(pJ,{code:`npm install @mastra/mcp`,lang:`bash`,copyTooltip:`Copy install command`}),(0,K.jsx)(kAi,{})]})}function DAi({descriptor:e}){let t=`${(Y().options.baseUrl||window.location.origin).replace(/\/$/,``)}${e.path}`,n=vAi(t,{protectedServer:e.auth.type===`protected`}),[r,i]=(0,G.useState)(n[0].value),a=n.find(e=>e.value===r)??n[0];return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`muted`,children:`Endpoint`}),(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-3 rounded-lg bg-muted py-2 pr-2 pl-3`,children:[(0,K.jsx)(T,{as:`span`,font:`mono`,className:`min-w-0 break-all`,children:t}),(0,K.jsx)(gC,{tooltip:`Copy MCP endpoint URL`,content:t})]})]}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`muted`,children:`Toolsets`}),(0,K.jsxs)(`ul`,{className:`flex flex-wrap gap-2`,"aria-label":`Toolsets`,children:[e.toolsets.map(e=>(0,K.jsx)(`li`,{children:(0,K.jsx)(eC,{variant:`neutral`,emphasis:`subtle`,children:OAi(e)})},e)),e.readOnly&&(0,K.jsx)(`li`,{children:(0,K.jsx)(eC,{variant:`info`,emphasis:`subtle`,children:`Read-only`})})]})]}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`muted`,children:`Connect a client`}),(0,K.jsx)(pJ,{code:a.code,lang:a.lang,options:n.map(({value:e,label:t})=>({value:e,label:t})),value:r,onValueChange:i,selector:`tabs`,copyTooltip:`Copy snippet`}),(0,K.jsx)(T,{variant:`body-sm`,tone:`muted`,children:`Tools are listed per caller, so connect a client to see the tools your token can use.`})]})]})}function OAi(e){let t=e.replaceAll(`_`,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function kAi(){return(0,K.jsx)(`div`,{children:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:yAi,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(tP,{}),children:`MCP server docs`})})}var AAi={name:e=>e.name||e.id};function jAi({server:e,rowProps:t}){let{paths:n,Link:r}=sn(),i=Y().options.baseUrl,a=e.transports?.includes(`sse`)??!0?`sse`:`mcp`,o=i?`${i}/api/mcp/${e.id}/${a}`:``,{data:s}=QAt({selectedServer:e}),c=Object.values(s||{}),l=c.length,u=c.filter(e=>e.toolType===`agent`).length,d=c.filter(e=>e.toolType===`workflow`).length,f=dJ(e.name,50);return(0,K.jsxs)(Z.RowLink,{to:n.mcpServerLink(e.id),LinkComponent:r,...t,children:[(0,K.jsx)(Z.NameCell,{children:f}),(0,K.jsx)(Z.DescriptionCell,{children:o}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:u||``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:l||``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:d||``})]})}function MAi({mcpServers:e,isLoading:t,search:n=``,sort:r,onSortChange:i}){let a=(0,G.useMemo)(()=>{let t=n.toLowerCase();return IZ(e.filter(e=>e.name?.toLowerCase().includes(t)||e.id?.toLowerCase().includes(t)),r,AAi)},[e,n,r]),{containerRef:o,getRowProps:s}=PZ({count:a.length,global:!0});return t?(0,K.jsx)(DH,{columns:`auto 1fr auto auto auto`}):(0,K.jsxs)(Z,{columns:`auto 1fr auto auto auto`,scrollRef:o,children:[(0,K.jsxs)(Z.Top,{children:[i?(0,K.jsx)(Z.SortableTopCell,{sortKey:`name`,sort:r?.key===`name`?r.direction:void 0,onSortChange:i,children:`Name`}):(0,K.jsx)(Z.TopCell,{children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`URL`}),(0,K.jsx)(Z.TopCellSmart,{long:`Agents`,short:(0,K.jsx)(HN,{}),tooltip:`Agent tools`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Tools`,short:(0,K.jsx)(XN,{}),tooltip:`Tools`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Workflows`,short:(0,K.jsx)(ZS,{}),tooltip:`Workflow tools`,className:`text-center`})]}),a.length===0&&n?(0,K.jsx)(Z.NoMatch,{message:`No MCP Servers match your search`}):null,a.map((e,t)=>(0,K.jsx)(jAi,{server:e,rowProps:s(t)},e.id))]})}var NAi=()=>(0,K.jsx)(Jx,{titleSlot:`No MCP Servers yet`,descriptionSlot:(0,K.jsxs)(K.Fragment,{children:[`MCP servers are not configured yet. `,(0,K.jsx)(`br`,{}),`More information in the documentation.`]}),actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/docs/tools-mcp/mcp-overview`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(tP,{}),children:`MCP documentation`}),variant:`fill`}),I9=[eP(`/mcps`)],PAi=()=>{let{data:e=[],isLoading:t,error:n}=NN(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)();return n&&FN(n)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:I9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsx)(TH,{variant:`fill`})]}):n&&IN(n)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:I9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsx)(wH,{variant:`fill`,resource:`MCP servers`})]}):n?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:I9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load MCP servers`,descriptionSlot:n.message})]}):e.length===0&&!t?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:I9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-6`,children:[(0,K.jsx)(bAi,{}),(0,K.jsx)(NAi,{})]})]}):(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:I9}),actionRow:(0,K.jsx)(TK,{children:(0,K.jsx)(TK.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(MH,{...NH,onValueChange:i,label:`Search MCP servers`,placeholder:`Search by name`})})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-6`,children:[(0,K.jsx)(bAi,{}),(0,K.jsx)(MAi,{mcpServers:e,isLoading:t,search:r,sort:a,onSortChange:(e,t)=>o({key:t,direction:e})})]})]})};function FAi(){let[e,t]=Rv();return{eventName:e.get(`event`)??void 0,close:()=>t(e=>{let t=new URLSearchParams(e);return t.delete(`event`),t},{replace:!0})}}var IAi=e=>`?${new URLSearchParams({event:e}).toString()}`;function LAi(e,{enabled:t=!0}={}){let n=Y();return T_({queryKey:[`mcp-server-events`,e],queryFn:()=>n.getMcpServerEvents(e),enabled:t})}function RAi(e,t){let n=Y();return D_({mutationFn:r=>n.emitMcpServerEvent(e,t,r)})}function zAi(e){if(e instanceof qf&&typeof e.body==`object`&&e.body!==null){let t=`error`in e.body?e.body.error:void 0;if(typeof t==`string`&&t)return t}return`The event request failed.`}var BAi={push:`blue`,poll:`neutral`,webhook:`purple`};function VAi({delivery:e}){return(0,K.jsx)(`span`,{className:`flex flex-wrap items-center gap-1`,children:e.map(e=>(0,K.jsx)(eC,{size:`xs`,variant:BAi[e],emphasis:`subtle`,children:e},e))})}var HAi=0,UAi=()=>`feed-${HAi++}`;function WAi(e,t){return[...t,...e].slice(0,200)}function GAi(e,t){switch(t.type){case`status`:return{...e,status:t.status,error:void 0,warning:void 0};case`cursor`:return t.cursor?{...e,cursor:t.cursor}:e;case`gap`:return{...e,items:WAi(e.items,[{kind:`gap`,key:UAi()}])};case`occurrences`:{let n=[...t.occurrences].reverse().map(e=>({kind:`occurrence`,key:UAi(),occurrence:e}));return{...e,items:WAi(e.items,n)}}case`warning`:return{...e,warning:t.message};case`error`:return{...e,status:`error`,error:t.message}}}var KAi={status:`idle`,items:[]};function qAi(e,t){let n=Y(),[r,i]=(0,G.useReducer)(GAi,KAi),a=(0,G.useRef)(void 0),o=(0,G.useRef)(void 0),s=e=>{e&&(o.current=e),i({type:`cursor`,cursor:e})};(0,G.useEffect)(()=>()=>a.current?.abort(),[]);let c=()=>{a.current?.abort(),a.current=void 0,i({type:`status`,status:`stopped`})},l=async r=>{a.current?.abort();let c=new AbortController;a.current=c,i({type:`status`,status:`connecting`});try{let a=n.streamMcpServerEvent(e,t,{arguments:r,cursor:o.current},{signal:c.signal});for await(let e of a){if(c.signal.aborted)return;if(e.type===`active`)i({type:`status`,status:`live`}),s(e.cursor),e.truncated&&i({type:`gap`});else if(e.type===`event`)i({type:`occurrences`,occurrences:[e.occurrence]}),s(e.occurrence.cursor);else if(e.type===`heartbeat`)s(e.cursor);else if(e.type===`error`)i({type:`warning`,message:e.message});else break}c.signal.aborted||i({type:`status`,status:`stopped`})}catch(e){if(c.signal.aborted)return;i({type:`error`,message:zAi(e)})}finally{a.current===c&&(a.current=void 0)}},u=async r=>{i({type:`status`,status:`polling`});try{let a=await n.pollMcpServerEvent(e,t,{arguments:r,cursor:o.current});a.truncated&&i({type:`gap`}),i({type:`occurrences`,occurrences:a.events}),s(a.cursor),i({type:`status`,status:`polled`})}catch(e){i({type:`error`,message:zAi(e)})}};return{...r,start:l,stop:c,pollOnce:u}}function L9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function JAi(e){return e.map(e=>JSON.stringify(e)).join(` | `)}function YAi(e){return e.map(R9).join(` | `)}function R9(e){return L9(e)?Array.isArray(e.enum)?JAi(e.enum):`const`in e?JSON.stringify(e.const):Array.isArray(e.anyOf)?YAi(e.anyOf):Array.isArray(e.oneOf)?YAi(e.oneOf):Array.isArray(e.type)?e.type.join(` | `):e.type===`array`?`${R9(e.items)}[]`:QAi(e)?`Record<string, ${R9(e.additionalProperties)}>`:typeof e.type==`string`?e.type:`unknown`:`unknown`}function XAi(e,t,n,{defaultsAreOptional:r=!1}){let i=L9(t)?t:{},a=`default`in i;return{name:e,type:R9(i),required:n.has(e)&&!(r&&a),description:typeof i.description==`string`?i.description:void 0,defaultValue:a?JSON.stringify(i.default):void 0}}function ZAi(e,t={}){if(!L9(e)||!L9(e.properties))return[];let n=new Set(Array.isArray(e.required)?e.required.filter(e=>typeof e==`string`):[]);return Object.entries(e.properties).map(([e,r])=>XAi(e,r,n,t))}function QAi(e){return L9(e)&&e.type===`object`&&!L9(e.properties)&&L9(e.additionalProperties)}function $Ai(e){return L9(e)&&(e.type===`object`||L9(e.properties))}var eji=[`type`,`properties`,`items`,`enum`,`const`,`anyOf`,`oneOf`,`allOf`,`$ref`];function tji(e){return!L9(e)||!eji.some(t=>t in e)}function z9(e){return L9(e)?zO(e):J({})}function nji({inputSchema:e,onChange:t}){return tji(e)?(0,K.jsx)(T,{tone:`muted`,children:`This event takes no arguments.`}):(0,K.jsx)(XM,{schema:z9(e),onValuesChange:e=>t(e??{})})}function rji({occurrence:e}){return(0,K.jsx)(nP,{children:(0,K.jsxs)(DC,{children:[(0,K.jsxs)(OC,{className:`flex w-full cursor-pointer items-center gap-2 px-3 py-2 text-left`,children:[(0,K.jsx)(y,{direction:`right`,className:`size-4 shrink-0`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,className:`min-w-0 flex-1 truncate`,children:e.eventId}),e.eventId.startsWith(`mastra-test-`)&&(0,K.jsx)(eC,{size:`xs`,variant:`amber`,emphasis:`subtle`,children:`test`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,tone:`muted`,className:`shrink-0`,children:e.timestamp})]}),(0,K.jsx)(kC,{children:(0,K.jsx)(bw,{value:JSON.stringify(e.data,null,2),language:`json`,editable:!1,lineNumbers:!1,showCopyButton:!1,variant:`embedded`,"aria-label":`Event ${e.eventId} data`,className:`px-3 pb-3`})})]})})}var iji=`Gap: events may have been skipped`;function aji({items:e}){return e.length===0?(0,K.jsx)(Jx,{iconSlot:(0,K.jsx)(G6,{}),titleSlot:`No events yet`,descriptionSlot:`Start listening or poll to see occurrences here.`}):(0,K.jsx)(`ol`,{"aria-label":`Occurrences`,className:`grid grid-cols-1 gap-2`,children:e.map(e=>(0,K.jsx)(`li`,{children:e.kind===`gap`?(0,K.jsx)(Sk,{variant:`warning`,children:iji}):(0,K.jsx)(rji,{occurrence:e.occurrence})},e.key))})}var oji={idle:`Not listening`,connecting:`Connecting…`,polling:`Polling…`,polled:`Polled`,stopped:`Stopped`,error:`Failed`};function sji({status:e,canStream:t}){if(e===`live`)return(0,K.jsx)(eC,{variant:`green`,indicator:`pulse`,size:`sm`,children:`Listening`});let n=e===`idle`&&!t?`Not polled yet`:oji[e];return(0,K.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(e===`connecting`||e===`polling`)&&(0,K.jsx)(It,{size:`sm`}),(0,K.jsx)(T,{as:`span`,tone:`muted`,children:n})]})}function cji({status:e,canStream:t,cursor:n}){return(0,K.jsxs)(`div`,{role:`status`,className:`flex min-w-0 flex-wrap items-center gap-3`,children:[(0,K.jsx)(sji,{status:e,canStream:t}),n&&(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1`,children:[(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:`Cursor`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,className:`min-w-0 truncate`,children:n}),(0,K.jsx)(gC,{tooltip:`Copy cursor`,content:n})]})]})}function lji({serverId:e,event:t,onEmitted:n}){let{mutateAsync:r,isPending:i,isSuccess:a,error:o}=RAi(e,t.name);return(0,K.jsxs)(`section`,{"aria-label":`Send test event`,className:`grid grid-cols-1 gap-3`,children:[(0,K.jsx)(T,{as:`h3`,variant:`subheading`,children:`Send test event`}),(0,K.jsx)(XM,{schema:z9(t.payloadSchema),onSubmit:async e=>{try{await r(e??{}),n?.()}catch{}},isSubmitLoading:i,submitButtonLabel:`Send test event`}),a&&!o&&(0,K.jsx)(T,{tone:`muted`,children:`Test event sent.`}),o&&(0,K.jsx)(Sk,{variant:`destructive`,children:zAi(o)})]})}function uji({serverId:e,event:t,testEmit:n,canEmit:r}){let[i,a]=(0,G.useState)({}),o=qAi(e,t.name),s=t.delivery.includes(`push`),c=o.status===`connecting`||o.status===`live`;return(0,K.jsxs)(`div`,{className:`grid grid-cols-1 content-start gap-6`,children:[(0,K.jsx)(nji,{inputSchema:t.inputSchema,onChange:a}),(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,K.jsx)(cji,{status:o.status,canStream:s,cursor:o.cursor}),s&&c&&(0,K.jsx)(X,{onClick:o.stop,children:`Stop`}),s&&!c&&(0,K.jsx)(X,{variant:`primary`,onClick:()=>void o.start(i),children:`Start`}),!s&&(0,K.jsx)(X,{variant:`primary`,disabled:o.status===`polling`,onClick:()=>void o.pollOnce(i),children:`Poll once`})]}),o.error&&(0,K.jsx)(Sk,{variant:`destructive`,children:o.error}),o.warning&&(0,K.jsx)(Sk,{variant:`warning`,children:o.warning}),n&&t.emittable&&r&&(0,K.jsx)(lji,{serverId:e,event:t,onEmitted:s?void 0:()=>void o.pollOnce(i)}),(0,K.jsx)(aji,{items:o.items})]})}function dji({description:e}){let t=i$({collapsedHeight:140});return(0,K.jsx)(r$,{state:t,expandLabel:`Read more`,children:(0,K.jsx)(xY,{children:e})})}function fji({description:e,overview:t,playground:n,canRun:r}){return(0,K.jsx)(K.Fragment,{children:(0,K.jsxs)(gk,{defaultTab:`overview`,className:`grid flex-1 grid-rows-[auto_1fr] gap-4 overflow-visible`,children:[(0,K.jsxs)(hk,{variant:`pill`,size:`sm`,children:[(0,K.jsx)(_k,{value:`overview`,children:`Overview`}),(0,K.jsx)(_k,{value:`playground`,disabled:!r,disabledTooltip:`You don't have permission to execute tools.`,children:`Playground`})]}),(0,K.jsxs)(vk,{value:`overview`,flush:!0,className:`content-start gap-6`,children:[e&&(0,K.jsx)(nP,{className:`p-4`,children:(0,K.jsx)(dji,{description:e})}),t]}),(0,K.jsx)(vk,{value:`playground`,flush:!0,keepMounted:!0,className:`h-full`,children:r&&n})]})})}function pji(e){return(0,K.jsx)(T5n,{className:`min-h-control-md`,...e})}function mji(){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`span`,{"aria-hidden":!0,className:`ml-0.5 text-destructive-indicator`,children:`*`}),(0,K.jsx)(`span`,{className:`sr-only`,children:` (required)`})]})}function hji({field:e}){return(0,K.jsxs)(K.Fragment,{children:[e.description,e.defaultValue!==void 0&&(0,K.jsxs)(`span`,{className:`block`,children:[`Default `,e.defaultValue]})]})}function gji({field:e}){let t=!!e.description||e.defaultValue!==void 0;return(0,K.jsx)(SZ,{title:(0,K.jsxs)(T,{as:`span`,variant:`body-sm`,font:`mono`,tone:`ink`,children:[e.name,e.required&&(0,K.jsx)(mji,{})]}),description:t?(0,K.jsx)(`span`,{className:`whitespace-normal`,children:(0,K.jsx)(hji,{field:e})}):void 0,children:(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,tone:`muted`,children:e.type})})}function _ji({message:e}){return(0,K.jsx)(xZ,{children:e})}function vji({schema:e,emptyMessage:t,defaultsAreOptional:n}){if(tji(e))return(0,K.jsx)(_ji,{message:t});if(!$Ai(e)||QAi(e))return(0,K.jsx)(SZ,{title:`Type`,children:(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,tone:`muted`,children:R9(e)})});let r=ZAi(e,{defaultsAreOptional:n});return r.length===0?(0,K.jsx)(_ji,{message:t}):r.map(e=>(0,K.jsx)(gji,{field:e},e.name))}function B9({title:e,...t}){return(0,K.jsxs)(yZ,{children:[(0,K.jsx)(pji,{children:(0,K.jsx)(bZ,{children:e})}),(0,K.jsx)(vZ,{children:(0,K.jsx)(vji,{...t})})]})}function yji({serverId:e,eventName:t}){let{canExecute:n,canEdit:r}=fS(),{data:i,isLoading:a}=LAi(e),o=i?.events.find(e=>e.name===t);return a?(0,K.jsx)(jQ.LoadingData,{}):!i||!o?(0,K.jsxs)(jQ.NoData,{children:[`This server has no event "`,t,`".`]}):(0,K.jsx)(fji,{description:o.description,overview:(0,K.jsxs)(`div`,{className:`grid grid-cols-1 gap-6`,children:[(0,K.jsx)(VAi,{delivery:o.delivery}),(0,K.jsx)(B9,{title:`Arguments`,schema:o.inputSchema,emptyMessage:`This event takes no arguments.`,defaultsAreOptional:!0}),(0,K.jsx)(B9,{title:`Payload`,schema:o.payloadSchema,emptyMessage:`No payload schema defined.`})]}),canRun:n(`mcp`),playground:(0,K.jsx)(uji,{serverId:e,event:o,testEmit:i.testEmit,canEmit:r(`mcp`)})})}function bji({serverId:e}){let{eventName:t,close:n}=FAi();return(0,K.jsxs)(jQ,{open:t!==void 0,onClose:n,title:t??``,children:[(0,K.jsxs)(jQ.Header,{children:[(0,K.jsxs)(jQ.Heading,{children:[(0,K.jsx)(Dx,{size:`sm`,className:`text-muted-foreground`,children:(0,K.jsx)(G6,{})}),(0,K.jsx)(`span`,{className:`truncate`,children:t})]}),(0,K.jsx)(jQ.HeaderActions,{children:(0,K.jsx)(jQ.CloseButton,{icon:`x`,tooltip:`Close event`,onClick:n})})]}),(0,K.jsx)(jQ.Content,{className:`flex flex-col gap-4 px-3`,children:t&&(0,K.jsx)(yji,{serverId:e,eventName:t},t)})]})}var xji=new Set([`completed`,`failed`,`cancelled`]),Sji={working:`working`,input_required:`input required`,completed:`completed`,failed:`failed`,cancelled:`cancelled`},Cji=e=>xji.has(e.status),wji=2e3,V9=e=>[`mcp-server-tasks`,e],Tji=e=>!!e?.some(e=>!Cji(e));function Eji(e,t={}){let n=Y();return O_({queryKey:[...V9(e),`list`,t],queryFn:({pageParam:r})=>n.getMcpServerTasks(e,{...t,cursor:r}),initialPageParam:void 0,getNextPageParam:e=>e.nextCursor,refetchInterval:e=>e.state.data?.pages.some(e=>Tji(e.tasks))?wji:!1})}function Dji(e,{enabled:t=!0}={}){let n=Y();return T_({queryKey:[...V9(e),`surfaces`],queryFn:()=>n.getMcpServerTasks(e,{limit:1}),select:e=>e.surfaces,enabled:t})}function Oji(e,t){let n=Y();return T_({queryKey:[...V9(e),`task`,t],queryFn:async()=>(await n.getMcpServerTasks(e,{key:t,limit:1})).tasks[0]??null,enabled:t!==void 0,refetchInterval:e=>e.state.data&&!Cji(e.state.data)?wji:!1})}function kji(e){let t=Y();return D_({mutationFn:n=>t.findMcpServerTask(e,n)})}function Aji(e){let t=Y(),n=u_();return D_({mutationFn:n=>t.cancelMcpServerTask(e,n),onSettled:()=>n.invalidateQueries({queryKey:V9(e)})})}function jji(e){let t=Y(),n=u_();return D_({mutationFn:({taskKey:n,inputResponses:r})=>t.answerMcpServerTaskInput(e,n,r),onSettled:()=>n.invalidateQueries({queryKey:V9(e)})})}function Mji(){let[e,t]=Rv();return{taskKey:e.get(`task`)??void 0,open:e=>t(t=>{let n=new URLSearchParams(t);return n.set(`task`,e),n},{replace:!0}),close:()=>t(e=>{let t=new URLSearchParams(e);return t.delete(`task`),t},{replace:!0})}}var Nji=(e,t=``)=>{let n=new URLSearchParams(t);return n.set(`task`,e),`?${n.toString()}`},Pji=e=>`${e.slice(0,8)}…`,Fji=new Set([`working`,`input_required`,`completed`,`failed`,`cancelled`]);function Iji(){let[e,t]=Rv(),n=e.get(`status`),r=e.get(`surface`),i=e.get(`client`);return{filters:{...n&&Fji.has(n)&&{status:n},...r&&{surface:r},...i&&{client:i}},setFilters:e=>t(t=>{let n=new URLSearchParams(t);for(let t of[`status`,`surface`,`client`]){let r=e[t];r?n.set(t,r):n.delete(t)}return n},{replace:!0})}}var Lji=e=>`${e.slice(0,8)}…`,Rji={working:{variant:`info`,indicator:`pulse`},input_required:{variant:`warning`,indicator:`dot`},completed:{variant:`success`},failed:{variant:`destructive`},cancelled:{variant:`neutral`}};function zji({status:e}){let{variant:t,indicator:n}=Rji[e];return(0,K.jsx)(eC,{size:`sm`,variant:t,emphasis:`subtle`,indicator:n,children:Sji[e]})}function Bji({serverId:e}){let{taskKey:t,close:n}=Mji(),{data:r,isSuccess:i}=Oji(e,t);return(0,K.jsxs)(jQ,{open:t!==void 0,onClose:n,title:r?.surface??`Task`,children:[(0,K.jsxs)(jQ.Header,{children:[(0,K.jsxs)(jQ.Heading,{children:[(0,K.jsx)(Dx,{size:`sm`,className:`text-muted-foreground`,children:(0,K.jsx)(l8n,{})}),(0,K.jsx)(`span`,{className:`truncate`,children:r?`${r.surface} task`:`Task`})]}),(0,K.jsx)(jQ.HeaderActions,{children:(0,K.jsx)(jQ.CloseButton,{icon:`x`,tooltip:`Close task`,onClick:n})})]}),(0,K.jsx)(jQ.Content,{className:`flex flex-col gap-4 px-3`,children:r?(0,K.jsx)(Vji,{serverId:e,task:r},r.taskKey):i&&(0,K.jsx)(T,{tone:`muted`,children:`This task is no longer listed.`})})]})}function Vji({serverId:e,task:t}){let n=Aji(e),{canEdit:r,isLoading:i}=fS(),a=!i&&r(`mcp`),o=Object.entries(t.inputRequests??{});return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(V4,{children:[(0,K.jsx)(V4.Key,{children:`Status`}),(0,K.jsx)(V4.Value,{children:(0,K.jsx)(zji,{status:t.status})}),t.statusMessage&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(V4.Key,{children:`Message`}),(0,K.jsx)(V4.Value,{children:t.statusMessage})]}),(0,K.jsx)(V4.Key,{children:`Created`}),(0,K.jsx)(V4.Value,{children:(0,K.jsx)(Dk,{value:t.createdAt})}),(0,K.jsx)(V4.Key,{children:`Updated`}),(0,K.jsx)(V4.Value,{children:(0,K.jsx)(Dk,{value:t.lastUpdatedAt})}),(0,K.jsx)(V4.Key,{children:`Expires`}),(0,K.jsx)(V4.Value,{children:t.expiresAt?(0,K.jsx)(Dk,{value:t.expiresAt}):`never`}),(0,K.jsx)(V4.Key,{children:`Task key`}),(0,K.jsx)(V4.ValueWithCopyBtn,{copyValue:t.taskKey,copyTooltip:`Copy task key`,children:Pji(t.taskKey)}),t.clientLabel&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(V4.Key,{children:`Client`}),(0,K.jsx)(V4.ValueWithCopyBtn,{copyValue:t.clientLabel,copyTooltip:`Copy client`,children:t.clientLabel})]}),(0,K.jsx)(V4.Key,{children:`Client key`}),(0,K.jsx)(V4.ValueWithCopyBtn,{copyValue:t.principalKey,copyTooltip:`Copy client key`,children:Pji(t.principalKey)})]}),(0,K.jsx)(T,{tone:`muted`,variant:`caption`,children:`Keys are hashes: the task id and the client's credentials stay with the client that started the task.`}),o.map(([n,r])=>(0,K.jsx)(Uji,{serverId:e,taskKey:t.taskKey,inputKey:n,request:r,canAnswer:a},n)),!Cji(t)&&!i&&!a&&(0,K.jsx)(T,{tone:`muted`,variant:`caption`,children:`Cancelling or answering a task needs the mcp:write permission.`}),!Cji(t)&&a&&(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,K.jsx)(X,{variant:`destructive-ghost`,className:`self-start`,disabled:n.isPending,onClick:()=>n.mutate(t.taskKey),children:`Cancel task`}),n.error&&(0,K.jsx)(Sk,{variant:`destructive`,children:Gji(n.error)})]}),t.result&&(0,K.jsx)(Wji,{label:`Result`,value:t.result}),t.error&&(0,K.jsx)(Wji,{label:`Error`,value:t.error})]})}var Hji=J({message:q().optional(),requestedSchema:Ad(q(),hd())});function Uji({serverId:e,taskKey:t,inputKey:n,request:r,canAnswer:i}){let a=jji(e),o=r.method===`elicitation/create`?Hji.safeParse(r.params):void 0,s=e=>a.mutate({taskKey:t,inputResponses:{[n]:e}});return(0,K.jsxs)(`section`,{"aria-label":`Input request ${n}`,className:`flex flex-col gap-3`,children:[(0,K.jsx)(T,{as:`h3`,variant:`subheading`,children:`Input requested`}),o?.success&&!i?(0,K.jsxs)(K.Fragment,{children:[o.data.message&&(0,K.jsx)(T,{children:o.data.message}),(0,K.jsx)(Wji,{label:`Request`,value:r})]}):o?.success?(0,K.jsxs)(K.Fragment,{children:[o.data.message&&(0,K.jsx)(T,{children:o.data.message}),(0,K.jsx)(XM,{schema:z9(o.data.requestedSchema),onSubmit:e=>s({action:`accept`,content:e??{}}),isSubmitLoading:a.isPending,submitButtonLabel:`Accept`,submitButtonVariant:`primary`,submitActions:(0,K.jsx)(X,{type:`button`,disabled:a.isPending,onClick:()=>s({action:`decline`}),children:`Decline`})})]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(T,{tone:`muted`,children:[`Studio can't answer a `,r.method,` request; the client that started the task has to.`]}),(0,K.jsx)(Wji,{label:`Request`,value:r})]}),a.error&&(0,K.jsx)(Sk,{variant:`destructive`,children:Gji(a.error)})]})}function Wji({label:e,value:t}){return(0,K.jsxs)(`section`,{className:`flex flex-col gap-2`,children:[(0,K.jsx)(T,{as:`h3`,variant:`subheading`,children:e}),(0,K.jsx)(bw,{value:JSON.stringify(t,null,2),language:`json`,editable:!1,lineNumbers:!1,"aria-label":`Task ${e.toLowerCase()}`})]})}function Gji(e){let t=zAi(e);return t===`Task not found`?`The task is no longer waiting for this; the list has been refreshed.`:t}function Kji(e){if(!L9(e))return;if(L9(e.ui)&&typeof e.ui.resourceUri==`string`)return e.ui.resourceUri;let t=e[`ui/resourceUri`];return typeof t==`string`?t:void 0}function qji(e){return L9(e)&&e.status===`suspended`}function Jji(e){return e<1e3?`${Math.round(e)} ms`:`${(e/1e3).toFixed(2)} s`}function Yji(e){return e===void 0?`undefined`:JSON.stringify(e,null,2)}function Xji(e){return e.status===`error`?e.error:Yji(e.output)}function Zji({status:e,output:t,error:n},r){if(r!==void 0){if(e===`success`)return{status:`success`,output:t,durationMs:r};if(e===`error`)return{status:`error`,error:Qji(n),durationMs:r}}}function Qji(e){return e instanceof Error?JSON.stringify({error:e.message},null,2):JSON.stringify({error:String(e)},null,2)}function $ji({zodInputSchema:e,isRunning:t,onRun:n,requestContextEntityType:r,requestContextEntityId:i}){let a=!PTt(e),[o,s]=(0,G.useState)({view:`form`,value:void 0}),c=(0,G.useRef)(void 0),[l,u]=(0,G.useState)([]);function d(t){if(t===o.view)return;if(u([]),o.view===`form`)return s({view:`json`,value:JSON.stringify(c.current??{},null,2)});let n=YTt(o.value);if(!n.ok)return u([n.error]);let r=XTt(e,n.value);if(r)return u([r]);c.current=n.value,s({view:`form`,value:n.value})}function f(t){let r=ZTt(e,t);r.ok?n(r.value):u(r.errors)}let p={isSubmitLoading:t,submitButtonLabel:`Run`,submitButtonIcon:(0,K.jsx)(DT,{}),submitButtonVariant:`primary`};return(0,K.jsxs)(yZ,{children:[(0,K.jsx)(pji,{action:(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(mMt,{entityType:r,entityId:i}),(0,K.jsx)(gk,{defaultTab:`form`,value:o.view,onValueChange:d,children:(0,K.jsxs)(hk,{size:`md`,children:[(0,K.jsxs)(_k,{value:`form`,disabled:t,children:[(0,K.jsx)(Dx,{size:`sm`,children:(0,K.jsx)(pgt,{})}),`Form`]}),(0,K.jsxs)(_k,{value:`json`,disabled:t,children:[(0,K.jsx)(Dx,{size:`sm`,children:(0,K.jsx)(JS,{})}),`JSON`]})]})})]}),children:(0,K.jsx)(bZ,{children:`Request`})}),(0,K.jsx)(vZ,{children:(0,K.jsx)(`div`,{className:`p-4`,children:o.view===`json`?(0,K.jsxs)(`div`,{className:`grid gap-4`,children:[(0,K.jsxs)(ak,{invalid:l.length>0,children:[(0,K.jsx)(bw,{variant:`embedded`,language:`json`,value:o.value,onChange:e=>{s({view:`json`,value:e}),u([])},editable:!t,"aria-label":`Request JSON`}),l.length>0&&(0,K.jsx)(lk,{children:l.map(e=>(0,K.jsx)(`span`,{className:`block`,children:e},e))})]}),(0,K.jsx)(kk,{...p,onSubmit:()=>f(o.value)})]}):(0,K.jsx)(XM,{...p,schema:e,defaultValues:o.value,onValuesChange:e=>{c.current=e},onSubmit:n,className:`gap-0`,children:!a&&(0,K.jsx)(T,{variant:`body-sm`,tone:`muted`,className:`pb-4`,children:`This tool takes no input. Run it as is.`})})})})]})}var eMi=U(`IconSend`,()=>(0,K.jsx)(`path`,{d:`M13.1282 21.1524C13.3813 22.1224 14.7454 22.1581 15.0489 21.2027L20.1669 5.09042C20.4124 4.31745 19.6841 3.58908 18.9111 3.83461L2.79884 8.95262C1.84336 9.25613 1.8791 10.6203 2.84916 10.8733L10.4343 12.852C10.7846 12.9434 11.0581 13.217 11.1495 13.5672L13.1282 21.1524Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}));function tMi({isRunning:e,lastRun:t}){return e?(0,K.jsx)(Jx,{iconSlot:(0,K.jsx)(It,{}),titleSlot:`Running…`,descriptionSlot:`Waiting for the tool to respond.`}):t?t.status===`error`?(0,K.jsx)(uC,{code:Xji(t),className:`overflow-x-auto p-4 text-caption whitespace-pre`}):(0,K.jsx)(bw,{value:Xji(t),language:`json`,editable:!1,lineNumbers:!1,showCopyButton:!1,variant:`embedded`,"aria-label":`Tool response`,className:`p-4`}):(0,K.jsx)(Jx,{iconSlot:(0,K.jsx)(eMi,{}),titleSlot:`No response yet`,descriptionSlot:`Run the tool to see its output here.`})}function nMi({run:e}){return(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[e.status===`success`?(0,K.jsx)(eC,{variant:`success`,emphasis:`subtle`,indicator:`dot`,children:`Success`}):(0,K.jsx)(eC,{variant:`destructive`,emphasis:`subtle`,indicator:`dot`,children:`Error`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,tone:`muted`,children:Jji(e.durationMs)}),(0,K.jsx)(gC,{content:Xji(e),copyMessage:`Response copied`,tooltip:`Copy response`,size:`icon-sm`})]})}function rMi({isRunning:e,lastRun:t}){return(0,K.jsxs)(yZ,{className:`h-full`,children:[(0,K.jsx)(pji,{action:!e&&t&&(0,K.jsx)(nMi,{run:t}),children:(0,K.jsx)(bZ,{children:`Response`})}),(0,K.jsx)(vZ,{className:c(`grid min-h-48 flex-1`,e||!t?`content-center`:`content-start`),children:(0,K.jsx)(tMi,{isRunning:e,lastRun:t})})]})}function iMi({zodInputSchema:e,execution:t,requestContextEntityType:n,requestContextEntityId:r}){let[i]=HS(n,r),[a,o]=(0,G.useState)(),s=async e=>{let n=performance.now();await t.execute(e,i).catch(()=>void 0),o(performance.now()-n)},c=t.status===`pending`;return(0,K.jsxs)(`div`,{className:`grid h-full grid-rows-[auto_1fr] gap-6`,children:[(0,K.jsx)($ji,{zodInputSchema:e,isRunning:c,onRun:s,requestContextEntityType:n,requestContextEntityId:r}),(0,K.jsx)(rMi,{isRunning:c,lastRun:Zji(t,a)})]})}function aMi({serverId:e,tool:t}){let n=_mr(e),{mutateAsync:r,status:i,data:a,error:o}=ZAt({serverId:e,toolId:t.name}),{data:s}=JAt({serverId:e,appResourceUri:Kji(t._meta)}),c=z9(t.inputSchema),l={execute:(e,t)=>r({data:e,requestContext:t}),status:i,output:a,error:o};return(0,K.jsxs)(`div`,{className:`grid content-start gap-6`,children:[s&&(0,K.jsx)(fPr,{html:s,toolName:t.name,onToolCall:n}),qji(a)&&(0,K.jsxs)(Sk,{variant:`warning`,children:[`This tool asked for more input, which Studio cannot provide. The suspend payload below shows what it needs. Call it from an MCP client with an `,(0,K.jsx)(uX,{children:`inputRequests`}),` handler to finish the request.`]}),(0,K.jsx)(iMi,{zodInputSchema:c,execution:l,requestContextEntityType:`mcp-tool`,requestContextEntityId:`${e}:${t.name}`})]})}var oMi=(0,G.createContext)(void 0),sMi=oMi.Provider;function cMi(){let e=(0,G.useContext)(oMi);if(e===void 0)throw Error(`useOpenToolId must be used inside ToolDrawer`);return e}function lMi({inputSchema:e,outputSchema:t,requestContextSchema:n,footer:r}){return(0,K.jsxs)(`div`,{className:`grid gap-6`,children:[(0,K.jsx)(B9,{title:`Input`,schema:e,emptyMessage:`This tool takes no input.`,defaultsAreOptional:!0}),(0,K.jsx)(B9,{title:`Output`,schema:t,emptyMessage:`No output schema defined.`}),n!==void 0&&(0,K.jsx)(B9,{title:`Request context`,schema:n,emptyMessage:`No request context fields.`,defaultsAreOptional:!0}),r]})}function uMi({serverId:e}){let t=cMi(),{canExecute:n}=fS(),{data:r,isLoading:i}=XAt({serverId:e,toolId:t});return i?(0,K.jsx)(jQ.LoadingData,{}):r?(0,K.jsx)(fji,{description:r.description,overview:(0,K.jsx)(lMi,{inputSchema:r.inputSchema}),canRun:n(`tools`),playground:(0,K.jsx)(aMi,{serverId:e,tool:r})}):(0,K.jsxs)(jQ.NoData,{children:[`This server has no tool "`,t,`".`]})}var dMi=`auto 1fr auto`;function fMi({server:e}){let{data:t,isLoading:n,isError:r}=LAi(e.id),i=t?.events??[],{Link:a}=sn(),{containerRef:o,getRowProps:s}=PZ({count:i.length});return(0,K.jsxs)(`section`,{className:`flex flex-col gap-3`,children:[(0,K.jsx)(T,{as:`h2`,variant:`heading`,children:`Events`}),n&&(0,K.jsx)(DH,{columns:dMi}),r&&(0,K.jsx)(Sk,{variant:`destructive`,children:`Could not load this server's events.`}),t&&(0,K.jsxs)(Z,{columns:dMi,scrollRef:o,children:[(0,K.jsxs)(Z.Top,{children:[(0,K.jsx)(Z.TopCell,{children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`Description`}),(0,K.jsx)(Z.TopCell,{children:`Delivery`})]}),i.length===0&&(0,K.jsx)(Z.NoMatch,{message:`This server declares no events`}),i.map((t,n)=>(0,K.jsxs)(Z.RowLink,{to:`/mcps/${e.id}${IAi(t.name)}`,LinkComponent:a,...s(n),children:[(0,K.jsx)(Z.NameCell,{children:t.name}),(0,K.jsx)(Z.DescriptionCell,{children:t.description}),(0,K.jsx)(Z.TextCell,{children:(0,K.jsx)(VAi,{delivery:t.delivery})})]},t.name))]})]})}var pMi=`minmax(0,1fr) auto auto auto auto auto auto auto`,mMi={not_listable:`This server's task store can't be listed.`,resource_scoped:`The task list needs a Studio session that is not scoped to a resource.`},hMi=[{id:`is`,label:`is`}],gMi=Object.entries(Sji).map(([e,t])=>({value:e,label:t})),_Mi=e=>e.stopPropagation(),vMi=e=>e.clientLabel??Lji(e.principalKey),yMi=e=>[`status`,`surface`,`client`].flatMap(t=>{let n=e[t];return n?[{id:t,fieldId:t,operatorId:`is`,value:n}]:[]}),bMi=e=>{let t=t=>{let n=e.find(e=>e.fieldId===t)?.value;return typeof n==`string`&&n?n:void 0};return{status:t(`status`),surface:t(`surface`),client:t(`client`)}};function xMi({server:e}){let{filters:t,setFilters:n}=Iji(),{data:r,isLoading:i,isError:a,hasNextPage:o,fetchNextPage:s,isFetchingNextPage:c}=Eji(e.id,t),{data:l=[]}=Dji(e.id),u=(0,G.useMemo)(()=>r?.pages.flatMap(e=>e.tasks)??[],[r]),d=r?.pages[0]?.unavailable,{containerRef:f,getRowProps:p}=PZ({count:u.length}),m=yMi(t).length>0,h=(0,G.useMemo)(()=>{let e=new Map(u.map(e=>[e.principalKey,vMi(e)]));return t.client&&!e.has(t.client)&&e.set(t.client,Lji(t.client)),[...e]},[u,t.client]),g=(0,G.useMemo)(()=>[{id:`status`,label:`Status`,icon:EX,color:sP(`orange`),operators:[`is`],strict:!0,suggestions:gMi},{id:`surface`,label:`Surface`,icon:YS,color:sP(`blue`),operators:[`is`],strict:!0,suggestions:l.map(e=>({value:e.name}))},{id:`client`,label:`Client`,icon:lYr,color:sP(`purple`),operators:[`is`],suggestions:h.map(([e,t])=>({value:e,label:t}))}],[l,h]);return(0,K.jsxs)(`section`,{"aria-label":`Tasks`,className:`flex flex-col gap-3`,children:[(0,K.jsx)(T,{as:`h2`,variant:`heading`,children:`Tasks`}),a&&(0,K.jsx)(Sk,{variant:`destructive`,children:`Could not load this server's tasks.`}),d&&(0,K.jsx)(Sk,{variant:`info`,children:mMi[d]}),!d&&(0,K.jsxs)(TK,{children:[(0,K.jsx)(TK.Start,{children:(0,K.jsxs)(m5,{fields:g,operators:hMi,value:yMi(t),onValueChange:e=>n(bMi(e)),createItemId:e=>e,"aria-label":`Task filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(m5.Chips,{}),(0,K.jsx)(m5.Input,{placeholder:`Filter tasks`})]})}),(0,K.jsx)(TK.End,{children:(0,K.jsx)(CMi,{serverId:e.id})})]}),i&&(0,K.jsx)(DH,{columns:pMi}),r&&!d&&(0,K.jsxs)(Z,{columns:pMi,scrollRef:f,children:[(0,K.jsxs)(Z.Top,{children:[(0,K.jsx)(Z.TopCell,{children:`Surface`}),(0,K.jsx)(Z.TopCell,{children:`Status`}),(0,K.jsx)(Z.TopCell,{children:`Created`}),(0,K.jsx)(Z.TopCell,{children:`Updated`}),(0,K.jsx)(Z.TopCell,{children:`Expires`}),(0,K.jsx)(Z.TopCell,{children:`Inputs`}),(0,K.jsx)(Z.TopCell,{children:`Key`}),(0,K.jsx)(Z.TopCell,{children:`Client`})]}),u.length===0&&(0,K.jsx)(Z.NoMatch,{message:m?`No tasks match these filters`:`No tasks yet`}),u.map((r,i)=>(0,K.jsx)(SMi,{serverId:e.id,task:r,rowProps:p(i),onFilterClient:()=>n({...t,client:r.principalKey})},r.taskKey))]}),o&&(0,K.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,K.jsx)(X,{variant:`default`,size:`sm`,onClick:()=>s(),disabled:c,children:c?`Loading…`:`Load more`}),(0,K.jsxs)(T,{variant:`caption`,tone:`muted`,children:[`Showing the `,u.length,` most recent `,m?`matching `:``,`tasks.`]})]})]})}function SMi({serverId:e,task:t,rowProps:n,onFilterClient:r}){let{Link:i}=sn(),[a]=Rv(),o=(0,G.useRef)(null);return(0,K.jsxs)(Z.RowWrapper,{...n,onSelectRow:()=>o.current?.click(),children:[(0,K.jsxs)(Z.RowLink,{ref:o,colEnd:-2,to:`/mcps/${e}${Nji(t.taskKey,a)}`,LinkComponent:i,tabIndex:-1,onClick:_Mi,"aria-label":`${t.surface} task ${Pji(t.taskKey)}`,children:[(0,K.jsx)(Z.NameCell,{children:t.surface}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(zji,{status:t.status})}),(0,K.jsx)(Z.CreatedCell,{timestamp:t.createdAt,preset:`day-time-seconds`}),(0,K.jsx)(Z.Cell,{className:`text-muted-foreground`,children:(0,K.jsx)(Dk,{value:t.lastUpdatedAt})}),(0,K.jsx)(Z.Cell,{className:`text-muted-foreground`,children:t.expiresAt?(0,K.jsx)(Dk,{value:t.expiresAt}):`never`}),(0,K.jsx)(Z.TextCell,{children:Object.keys(t.inputRequests??{}).length||`—`}),(0,K.jsx)(Z.TextCell,{font:`mono`,className:`text-muted-foreground`,children:Pji(t.taskKey)})]}),(0,K.jsx)(Z.Cell,{className:`pr-2`,children:(0,K.jsx)(X,{type:`button`,variant:`ghost`,size:`sm`,className:`w-full justify-start font-mono`,tooltip:`Show only this client's tasks`,"aria-label":`Show only tasks from client ${vMi(t)}`,onClick:e=>{e.stopPropagation(),r()},children:vMi(t)})})]})}function CMi({serverId:e}){let[t,n]=(0,G.useState)(``),r=kji(e),{open:i}=Mji();return(0,K.jsxs)(`form`,{onSubmit:e=>{e.preventDefault();let a=t.trim();a&&r.mutate(a,{onSuccess:({task:e})=>{n(``),i(e.taskKey)}})},className:`flex items-center gap-2`,"aria-label":`Find a task by MCP task id`,children:[(0,K.jsx)(Jj,{size:`sm`,value:t,onChange:e=>{n(e.target.value),r.reset()},placeholder:`MCP task id`,"aria-label":`MCP task id`,"aria-invalid":r.isError||void 0,className:`w-56 font-mono`}),(0,K.jsx)(X,{type:`submit`,size:`sm`,variant:`default`,disabled:!t.trim()||r.isPending,children:`Find`}),r.isError&&(0,K.jsx)(T,{variant:`caption`,role:`status`,className:`text-destructive-foreground`,children:`No task with that id.`})]})}var wMi={agent:HN,workflow:ZS,tool:XN},TMi=`auto minmax(0, 1fr) auto`,EMi=`auto minmax(0, 1fr) auto auto`,DMi={tool:`Tool`,agent:`Agent`,workflow:`Workflow`};function OMi(e){return e in wMi}function kMi({type:e}){let t=OMi(e)?e:`tool`,n=wMi[t],r=DMi[t];return(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{asChild:!0,children:(0,K.jsx)(`span`,{"aria-label":t,className:`inline-flex text-muted-foreground [&>svg]:size-icon-md`,children:(0,K.jsx)(n,{})})}),(0,K.jsx)(Tx,{children:r})]})}var AMi=J({ui:J({resourceUri:q().optional()}).optional(),"ui/resourceUri":q().optional()});function jMi(e){let t=AMi.safeParse(e);return t.success?!!(t.data.ui?.resourceUri?.startsWith(`ui://`)||t.data[`ui/resourceUri`]?.startsWith(`ui://`)):!1}function MMi({surface:e}){return e?(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{asChild:!0,children:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,K.jsx)(eC,{size:`xs`,variant:e.mode===`always`?`info`:`neutral`,emphasis:`subtle`,children:e.mode}),e.required&&(0,K.jsx)(eC,{size:`xs`,variant:`warning`,emphasis:`subtle`,children:`required`}),e.recover&&(0,K.jsx)(eC,{size:`xs`,variant:`neutral`,emphasis:`subtle`,children:`recover`})]})}),(0,K.jsxs)(Tx,{children:[e.mode===`always`?`Always runs as a task`:`Runs as a task when the client asks for one`,e.required?`; clients without task support are refused`:``,e.recover?`; resumed after a server restart`:``]})]}):null}function NMi({server:e}){let[t,n]=(0,G.useState)(``),{data:r={},isLoading:i}=QAt({selectedServer:e}),{Link:a,paths:o}=sn(),{data:s}=Dji(e.id,{enabled:!!e.tasks_capability}),c=(0,G.useMemo)(()=>new Map(s?.map(e=>[e.name,e])),[s]),l=!!e.tasks_capability,u=l?EMi:TMi,d=(0,G.useMemo)(()=>{let e=t.toLowerCase();return Object.values(r).filter(t=>t.name.toLowerCase().includes(e)||t.description?.toLowerCase().includes(e))},[r,t]),{containerRef:f,getRowProps:p}=PZ({count:d.length});return(0,K.jsxs)(`section`,{className:`flex flex-col gap-3`,children:[(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,K.jsx)(T,{as:`h2`,variant:`heading`,children:`Available tools`}),(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(MH,{size:`sm`,debounceMs:300,className:`max-w-120`,onValueChange:n,label:`Search tools`,placeholder:`Search by name`})})]}),i?(0,K.jsx)(DH,{columns:u}):(0,K.jsxs)(Z,{columns:u,fit:`container`,scrollRef:f,children:[(0,K.jsxs)(Z.Top,{children:[(0,K.jsx)(Z.TopCell,{children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`Description`}),(0,K.jsx)(Z.TopCell,{className:`justify-center text-center`,children:`Type`}),l&&(0,K.jsx)(Z.TopCell,{children:`Task`})]}),d.length===0&&t?(0,K.jsx)(Z.NoMatch,{message:`No tools match your search`}):null,d.map((t,n)=>(0,K.jsxs)(Z.RowLink,{to:o.mcpServerToolLink(e.id,t.name),LinkComponent:a,...p(n),children:[(0,K.jsx)(Z.NameCell,{children:(0,K.jsxs)(`span`,{className:`flex items-center gap-2`,children:[t.name,jMi(t._meta)&&(0,K.jsx)(eC,{size:`xs`,children:`App`})]})}),(0,K.jsx)(Z.DescriptionCell,{children:t.description}),(0,K.jsx)(Z.TextCell,{className:`justify-center text-center`,children:(0,K.jsx)(kMi,{type:t.toolType??`tool`})}),l&&(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(MMi,{surface:c.get(t.name)})})]},t.name))]})]})}var PMi=({isLoading:e,server:t})=>{let[{sseUrl:n,httpStreamUrl:r},i]=(0,G.useState)({sseUrl:``,httpStreamUrl:``});if((0,G.useEffect)(()=>{if(!t)return;let e=window.MASTRA_SERVER_HOST,n=window.MASTRA_SERVER_PORT,r=null;e&&n&&(r=`http://${e}:${n}`);let a=r||`http://localhost:4111`,o=`${a}/api/mcp/${t.id}/sse`,s=`${a}/api/mcp/${t.id}/mcp`;i({sseUrl:o,httpStreamUrl:s})},[t]),e)return null;if(!t)return(0,K.jsx)(T,{as:`h1`,variant:`heading`,tone:`muted`,className:`py-20 text-center`,children:`Server not found`});let a=t.transports?.includes(`sse`)??!0,o=`npx -y mcp-remote ${a?n:r}`,s=[{value:`http`,label:`HTTP`,description:`Use for stateless HTTP transport with streamable responses.`,content:r,tooltip:`Copy HTTP Stream URL`},...a?[{value:`sse`,label:`SSE`,description:`Use for real-time communication via SSE.`,content:n,tooltip:`Copy SSE URL`}]:[],{value:`cli`,label:`CLI`,description:`Use for local command-line access via npx and mcp-remote.`,content:o,tooltip:`Copy command line config`}];return(0,K.jsxs)(`div`,{className:`flex flex-col gap-6 pt-4`,children:[(0,K.jsx)(nP,{children:(0,K.jsxs)(gk,{defaultTab:`http`,children:[(0,K.jsxs)(rP,{className:`flex-row items-center justify-between gap-3 space-y-0 border-b border-border`,children:[(0,K.jsx)(iP,{className:`shrink-0`,children:`Connect`}),(0,K.jsx)(`div`,{className:`min-w-0`,children:(0,K.jsx)(hk,{variant:`pill-ghost`,size:`sm`,children:s.map(e=>(0,K.jsx)(_k,{value:e.value,children:e.label},e.value))})})]}),s.map(e=>(0,K.jsx)(vk,{value:e.value,flush:!0,children:(0,K.jsxs)(oP,{className:`flex flex-col gap-3`,children:[(0,K.jsx)(T,{tone:`muted`,children:e.description}),(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-3 rounded-lg bg-muted py-2 pr-2 pl-3`,children:[(0,K.jsx)(T,{as:`span`,font:`mono`,className:`min-w-0 break-all`,children:e.content}),(0,K.jsx)(gC,{tooltip:e.tooltip,content:e.content})]})]})},e.value))]})}),(0,K.jsx)(NMi,{server:t}),t.tasks_capability&&(0,K.jsx)(xMi,{server:t}),t.events_capability&&(0,K.jsx)(fMi,{server:t})]})};function FMi(){let[e,t]=Rv();return{toolId:e.get(`tool`)??void 0,close:()=>t(e=>{let t=new URLSearchParams(e);return t.delete(`tool`),t},{replace:!0})}}function IMi({children:e}){let{toolId:t,close:n}=FMi();return(0,K.jsxs)(jQ,{open:t!==void 0,onClose:n,title:t??``,children:[(0,K.jsxs)(jQ.Header,{children:[(0,K.jsxs)(jQ.Heading,{children:[(0,K.jsx)(Dx,{size:`sm`,className:`text-muted-foreground`,children:(0,K.jsx)(XN,{})}),(0,K.jsx)(`span`,{className:`truncate`,children:t})]}),(0,K.jsx)(jQ.HeaderActions,{children:(0,K.jsx)(jQ.CloseButton,{icon:`x`,tooltip:`Close tool`,onClick:n})})]}),(0,K.jsx)(jQ.Content,{className:`flex flex-col gap-4 px-3`,children:t&&(0,K.jsx)(sMi,{value:t,children:e},t)})]})}var LMi=()=>{let{serverId:e}=kv(),t=[eP(`/mcps`),nMt],{data:n=[],isLoading:r}=NN(),i=n.find(t=>t.id===e),a=i?.transports?.includes(`sse`)??!0,o=r||i?(0,K.jsxs)(DK,{children:[(0,K.jsx)(DK.Title,{isLoading:r,children:i?.name}),i&&(0,K.jsx)(DK.Meta,{beside:!0,children:(0,K.jsxs)(eC,{size:`sm`,children:[`v`,i.version_detail.version]})}),i&&(0,K.jsx)(DK.Description,{children:a?`This MCP server can be accessed through multiple transport methods. Choose the one that best fits your use case.`:`This MCP server speaks Streamable HTTP only (protocol 2026-07-28).`})]}):void 0;return(0,K.jsxs)(RS,{variant:`narrow`,breadcrumbs:(0,K.jsx)(vN,{crumbs:t}),header:o,children:[(0,K.jsx)(PMi,{isLoading:r,server:i}),e&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(IMi,{children:(0,K.jsx)(uMi,{serverId:e})}),(0,K.jsx)(bji,{serverId:e}),(0,K.jsx)(Bji,{serverId:e})]})]})};function RMi(){let{data:e,isLoading:t}=i5();if(t)return`loading`;let n=e?.capabilities;return n?.traceAggregate===!0&&n.spanAggregate===!0?`unified`:`legacy`}var H9=[eP(`/metrics`)],zMi=e=>e.fieldId===u3r;function BMi({fields:e}){let{filterTokens:t,setFilterTokens:n}=$7(),r=[p5,...gvi(t)];return(0,K.jsxs)(m5,{fields:[d3r,...e],operators:lvi,value:r,onValueChange:e=>n(_vi(e.filter(e=>!zMi(e)))),createItemId:e=>e,"aria-label":`Metrics filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(m5.Chips,{renderChip:e=>zMi(e)?(0,K.jsx)(eyi,{}):(0,K.jsx)(m5.Chip,{item:e})}),(0,K.jsx)(m5.Input,{placeholder:`Filter metrics`})]})}function VMi({children:e,filterFields:t}){return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:H9}),actionRow:(0,K.jsx)(TK,{children:(0,K.jsx)(TK.Start,{children:(0,K.jsx)(BMi,{fields:t})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),e]})}function HMi({error:e}){return FN(e)?(0,K.jsx)(TH,{}):IN(e)?(0,K.jsx)(wH,{resource:`metrics`}):(0,K.jsx)(Jx,{tone:`error`,titleSlot:`Failed to load storage capabilities`,descriptionSlot:e.message})}var UMi=hvi({availableTags:[],availableEntityNames:[],availableServiceNames:[],availableEnvironments:[]});function WMi({children:e}){let{supportsMetrics:t,isLoading:n,error:r}=S7();return n?(0,K.jsx)(VMi,{filterFields:UMi,children:(0,K.jsxs)(`div`,{className:`flex h-full items-center justify-center gap-2`,children:[(0,K.jsx)(It,{"aria-label":`Loading storage capabilities`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:`Loading storage capabilities`})]})}):r?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:H9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),(0,K.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:(0,K.jsx)(HMi,{error:r})})]}):t?e:(0,K.jsx)(VMi,{filterFields:UMi,children:(0,K.jsx)(Jx,{titleSlot:`Metrics are not available with your current storage`,descriptionSlot:`Metrics require ClickHouse, DuckDB, Postgres v-next, Spanner, or in-memory storage for observability. Other relational databases (LibSQL, MSSQL) and document stores (MongoDB) do not support metrics collection. To enable metrics on an existing project, switch the observability storage in the Mastra configuration.`,actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/docs/observability/metrics/overview`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(tP,{}),children:`Metrics documentation`}),variant:`fill`})})}function GMi(e){switch(e){case`24h`:return`last-24h`;case`3d`:return`last-3d`;case`7d`:return`last-7d`;case`14d`:return`last-14d`;case`30d`:return`last-30d`;case`custom`:return`custom`;default:return}}function KMi(e,t,n,r,i,a,o){if(o){e.set(t,`custom`),e.set(n,o.from.toISOString()),e.set(r,o.to.toISOString());return}if(i===`custom`){e.set(t,`custom`),a?.from&&e.set(n,a.from.toISOString()),a?.to&&e.set(r,a.to.toISOString());return}let s=GMi(i);s&&e.set(t,s)}function U9(e,t,n){typeof n==`string`&&n.length>0&&e.set(t,n)}function qMi(e,t,n){if(Array.isArray(n)&&n.length!==0)for(let r of n)r&&e.append(t,r)}function JMi({spanTypes:e,entityName:t,status:n}){let r=[e.length===1?{id:`type`,fieldId:`spans.spanType`,value:e[0]??``}:{id:`type`,fieldId:`spans.spanType`,value:[...e],operatorId:`in`},{id:`entity`,fieldId:`spans.entityName`,value:t}];return n&&r.push({id:`status`,fieldId:`spans.status`,value:n}),{id:`metrics-span`,logic:`and`,nodes:r}}function YMi({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:i=`/traces`}){let a=new URLSearchParams;a.set(_8,`branches`),KMi(a,v8,y8,b8,e,t,r.window);let o=r.rootEntityType??n.rootEntityType;if(o&&a.set(h8,o),r.status&&a.set(g8,r.status),U9(a,S8.entityName,r.entityName??n.entityName),U9(a,S8.threadId,r.threadId??n.threadId),U9(a,S8.resourceId,r.resourceId??n.resourceId),U9(a,S8.runId,n.runId),U9(a,S8.sessionId,r.sessionId??n.sessionId),U9(a,S8.requestId,n.requestId),U9(a,S8.userId,r.userId??n.userId),U9(a,S8.organizationId,n.organizationId),U9(a,S8.experimentId,n.experimentId),U9(a,S8.serviceName,n.serviceName),U9(a,S8.environment,r.environment??n.environment),qMi(a,S8.tags,n.tags),r.span&&a.append(I8,JSON.stringify(JMi(r.span))),r.model){let e={id:`metrics-model`,logic:`and`,nodes:[{id:`model`,fieldId:`spans.model`,value:r.model}]};a.append(I8,JSON.stringify(e))}let s=a.toString();return s?`${i}?${s}`:i}function XMi({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:i=`/logs`}){let a=new URLSearchParams;KMi(a,p7,m7,h7,e,t,r.window);let o=r.rootEntityType??n.rootEntityType;o&&a.set(f7,o),U9(a,g7.entityName,r.entityName??n.entityName),U9(a,g7.threadId,r.threadId??n.threadId),U9(a,g7.resourceId,r.resourceId??n.resourceId),U9(a,g7.runId,n.runId),U9(a,g7.sessionId,n.sessionId),U9(a,g7.requestId,n.requestId),U9(a,g7.userId,n.userId),U9(a,g7.organizationId,n.organizationId),U9(a,g7.experimentId,n.experimentId),U9(a,g7.serviceName,n.serviceName),U9(a,g7.environment,n.environment),qMi(a,g7.tags,n.tags),r.status===`error`&&a.append(g7.level,`error`);let s=a.toString();return s?`${i}?${s}`:i}function ZMi(){let{datePreset:e,customRange:t,dimensionalFilter:n}=$7(),r=Ov(),i={preset:e,customRange:t,dashboardFilter:n};return{openTraces:(e={})=>{r(YMi({...i,scope:e}))},openLogs:(e={})=>{r(XMi({...i,scope:e}))}}}var QMi=`period`,$Mi=`dateFrom`,eNi=`dateTo`;function tNi(){let[e,t]=Rv(),n=e.get(QMi),r=Uvi(n)?n:`24h`,i=(0,G.useMemo)(()=>{if(r!==`custom`)return;let t=e=>{if(!e)return;let t=new Date(e);return Number.isNaN(t.getTime())?void 0:t},n=t(e.get($Mi)),i=t(e.get(eNi));if(n||i)return{from:n,to:i}},[r,e.toString()]),a=(0,G.useMemo)(()=>vvi(e),[e.toString()]),o=(0,G.useCallback)(e=>{t(t=>{let n=new URLSearchParams(t);return e===`24h`?n.delete(QMi):n.set(QMi,e),e!==`custom`&&(n.delete($Mi),n.delete(eNi)),n},{replace:!0})},[t]),s=(0,G.useCallback)(e=>{t(t=>{let n=new URLSearchParams(t);return e?.from?n.set($Mi,e.from.toISOString()):n.delete($Mi),e?.to?n.set(eNi,e.to.toISOString()):n.delete(eNi),n},{replace:!0})},[t]),c=(0,G.useCallback)(e=>{t(t=>{let n=new URLSearchParams(t);return bvi(n,e),avi(n),n},{replace:!0})},[t]),l=(0,G.useRef)(!1);return(0,G.useEffect)(()=>{if(l.current||(l.current=!0,svi(e)))return;let n=ovi();n&&t(e=>{let t=new URLSearchParams(e);for(let[e,r]of n)t.append(e,r);return t},{replace:!0})},[]),(0,K.jsx)(Jvi,{preset:r,filterTokens:a,onPresetChange:o,onFilterTokensChange:c,customRange:i,onCustomRangeChange:s,children:(0,K.jsx)(WMi,{children:(0,K.jsx)(nNi,{})})})}function nNi(){let{error:e}=Lvi(c9()),{isInMemory:t}=S7(),{data:n}=NYr(),{data:r}=t8(),{data:i}=jYr(),{data:a}=n8(),o=hvi({availableTags:n??[],availableEntityNames:r??[],availableServiceNames:i??[],availableEnvironments:a??[]});return e&&FN(e)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:H9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),(0,K.jsx)(TH,{variant:`fill`})]}):e&&IN(e)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:H9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),(0,K.jsx)(wH,{variant:`fill`,resource:`metrics`})]}):e?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:H9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load metrics`,descriptionSlot:e.message})]}):(0,K.jsx)(VMi,{filterFields:o,children:(0,K.jsxs)(`div`,{className:`grid content-start gap-4`,children:[t&&(0,K.jsx)(Sk,{variant:`info`,title:`Metrics are not persisted`,children:(0,K.jsx)(Sk.Message,{children:`This project uses in-memory storage for observability. Metrics will be lost on every server restart. For persistent metrics, switch the observability storage to ClickHouse, DuckDB, Postgres v-next, or Spanner.`})}),(0,K.jsx)(rNi,{})]})})}function rNi(){let{openTraces:e,openLogs:t}=ZMi(),n=Dp.AGENT,r=RMi(),i=(0,K.jsx)(Xyi,{onTimeRangeClick:t=>e({rootEntityType:n,window:t}),onViewErrors:()=>t({rootEntityType:n,status:`error`}),onFailureTimeRangeClick:t=>e({rootEntityType:n,status:`error`,window:t})}),a=(0,K.jsx)(abi,{onViewTraces:t=>e({rootEntityType:t}),onTimeRangeClick:t=>e({window:t})}),o=(0,K.jsx)(Ybi,{onViewTraces:()=>e(),onAgentClick:t=>e({rootEntityType:n,entityName:t}),onModelClick:t=>e({model:t}),onThreadClick:t=>e({threadId:t})}),s=(0,K.jsx)(Wyi,{onViewTraces:()=>e(),onTimeRangeClick:t=>e({window:t})});return r===`unified`?(0,K.jsxs)(`div`,{className:`grid content-start gap-4 pb-6`,children:[(0,K.jsxs)(i9,{columns:2,children:[(0,K.jsx)(i9.Item,{children:s}),(0,K.jsx)(i9.Item,{children:i}),(0,K.jsx)(i9.Item,{children:a}),(0,K.jsx)(i9.Item,{children:(0,K.jsx)(Cxi,{onTimeRangeClick:e})})]}),(0,K.jsx)(wCi,{onRowClick:e})]}):(0,K.jsxs)(`div`,{className:`grid content-start gap-4 pb-6`,children:[s,(0,K.jsxs)(i9,{columns:2,children:[(0,K.jsx)(i9.Item,{children:i}),(0,K.jsx)(i9.Item,{children:a})]}),(0,K.jsxs)(i9,{columns:2,children:[(0,K.jsx)(i9.Item,{children:(0,K.jsx)(Vbi,{onViewTraces:t=>e({rootEntityType:t}),onViewErrors:e=>t({rootEntityType:e,status:`error`}),onEntityClick:(t,n)=>e({rootEntityType:t,entityName:n})})}),(0,K.jsx)(i9.Item,{children:o})]}),(0,K.jsx)(oxi,{})]})}function iNi(){let{isCmsAvailable:e}=w3(),{paths:t}=sn();return e?(0,K.jsx)(G7n,{href:t.cmsPromptBlockCreateLink(),tooltip:`Create a prompt`,children:`New prompt`}):null}var W9=[eP(`/prompts`)],aNi=50,oNi=[`updatedAt`];function sNi(){let[e,t]=(0,G.useState)(``),[n,r]=(0,G.useState)(0),[i,a]=Rv(),{sort:o,onSortChange:s}=u7({searchParams:i,setSearchParams:a,allowedKeys:oNi}),{data:c,isLoading:l,error:u,isPlaceholderData:d}=qWr({page:n,perPage:aNi,orderBy:(0,G.useMemo)(()=>o?{field:o.key,direction:o.direction===`asc`?`ASC`:`DESC`}:void 0,[o])}),f=c?.promptBlocks??[],p=c?.hasMore??!1,m=(0,G.useCallback)(()=>{d||r(e=>e+1)},[d]),h=(0,G.useCallback)(()=>{d||r(e=>Math.max(0,e-1))},[d]),g=(0,G.useCallback)(e=>{t(e),r(0)},[]),_=(0,G.useCallback)((e,t)=>{s(e,t),r(0)},[s]);return u&&FN(u)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(TH,{variant:`fill`})]}):u&&IN(u)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(wH,{variant:`fill`,resource:`prompt blocks`})]}):u?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load prompt blocks`,descriptionSlot:u.message})]}):f.length===0&&!l&&n===0?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(PGr,{})]}):(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:W9}),headerActions:(0,K.jsx)(iNi,{}),actionRow:(0,K.jsx)(TK,{children:(0,K.jsx)(TK.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(MH,{...NH,onValueChange:g,label:`Search prompts`,placeholder:`Search by name or description`})})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(NGr,{promptBlocks:f,isLoading:l,search:e,currentPage:n,hasMore:p,onNextPage:m,onPrevPage:h,updatedSort:o?.direction,onSortChange:_})]})}var cNi=U(`IconEarth`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M13.725 16.8649C14.4822 16.8649 15.1643 16.4076 15.4518 15.7071C15.7636 14.9477 15.5426 14.0737 14.9073 13.5537L13.5144 12.4136C13.1981 12.1547 12.8101 11.999 12.4026 11.9673L11.8411 11.9237C11.3675 11.8868 10.9057 12.0832 10.6037 12.4498C10.2249 12.9095 10.1641 13.5534 10.45 14.0759L11.4075 15.8252C11.7584 16.4663 12.431 16.8649 13.1619 16.8649H13.725Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M4.17188 8.07009L6.08243 9.75205C6.85862 10.4354 8.04586 10.3426 8.70645 9.54695C8.9552 9.24735 9.29283 9.03467 9.67046 8.93967L11.8146 8.40028C12.5298 8.22035 13.088 7.66138 13.2669 6.94588L14.1264 3.50879`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]})),lNi=[eP(`/resources`)],uNi=[{title:`Mastra APIs`,description:`Explore and test the available REST API endpoints with the interactive Swagger UI.`,icon:cNi,href:`/swagger-ui`,external:!1},{title:`Documentation`,description:`Read the official Mastra documentation for guides, references, and tutorials.`,icon:Njt,href:`https://mastra.ai/en/docs`,external:!0},{title:`Github`,description:`Browse the source code, report issues, and contribute to the Mastra project.`,icon:tP,href:`https://github.com/mastra-ai/mastra`,external:!0},{title:`Community`,description:`Join the Mastra Discord community for help, discussion, and collaboration.`,icon:a$,href:`https://discord.gg/mastra-ai`,external:!0},{title:`Share with your team`,description:`Running Mastra Studio locally? Deploy to the cloud so your team can collaborate.`,icon:zFr,href:`https://mastra.ai/cloud`,external:!0},{title:`Talk to our Sales team`,description:`Get a custom demo, discuss on-prem deployments, and how we can help you accelerate getting agents into production.`,icon:I0n,href:`https://mastra.ai/contact?ref=studio`,external:!0}];function dNi(){return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:lNi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Resources`}),(0,K.jsx)(`div`,{children:(0,K.jsx)(`div`,{className:`grid max-w-3xl grid-cols-1 gap-4 sm:grid-cols-2`,children:uNi.map(e=>(0,K.jsxs)(`a`,{href:e.href,...e.external?{target:`_blank`,rel:`noreferrer`}:{},className:`group flex flex-col gap-3 rounded-lg border border-border bg-background state-layer p-5 hover:border-border-strong`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[(0,K.jsx)(e.icon,{className:c(`h-5 w-5 text-muted-foreground group-hover:text-info-indicator`,A)}),(0,K.jsx)(T,{as:`span`,variant:`subheading`,tone:`ink`,children:e.title}),e.external&&(0,K.jsx)(tP,{className:`ml-auto size-icon-sm text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100`})]}),(0,K.jsx)(T,{variant:`caption`,tone:`muted`,children:e.description})]},e.href))})})]})}function fNi(){let{isCmsAvailable:e}=w3(),{paths:t}=sn();return e?(0,K.jsx)(G7n,{href:t.cmsScorersCreateLink(),tooltip:`Create a scorer`,children:`New scorer`}):null}var G9=[eP(`/scorers`)];function pNi(){let{data:e={},isLoading:t,error:n}=VN(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)(`all`),[s,c]=(0,G.useState)();if(n&&FN(n))return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:G9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Scorers`}),(0,K.jsx)(TH,{variant:`fill`})]});if(n&&IN(n))return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:G9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Scorers`}),(0,K.jsx)(wH,{variant:`fill`,resource:`scorers`})]});if(n)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:G9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Scorers`}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load scorers`,descriptionSlot:n.message})]});if(Object.keys(e).length===0&&!t)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:G9}),headerActions:(0,K.jsx)(fNi,{}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Scorers`}),(0,K.jsx)(TLr,{})]});let l=a!==`all`||r!==``;return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:G9}),headerActions:(0,K.jsx)(fNi,{}),actionRow:(0,K.jsx)(DLr,{search:r,onSearchChange:i,sourceFilter:a,onSourceFilterChange:o,onReset:()=>{i(``),o(`all`)},hasActiveFilters:l}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Scorers`}),(0,K.jsx)(wLr,{scorers:e,isLoading:t,search:r,sourceFilter:a,sort:s,onSortChange:(e,t)=>c({key:t,direction:e})})]})}var mNi=[`input`,`entity`],hNi={input:`Input`,entity:`Entity`};function gNi(e){let t=[`auto`,`auto`,`minmax(0, 10rem)`];return e.has(`entity`)&&t.push(`minmax(0, 14rem)`),e.has(`input`)&&t.push(`minmax(0, 40rem)`),t.join(` `)}function _Ni(){let[e,t]=(0,G.useState)(new Set),n=(0,G.useMemo)(()=>new Set(mNi.filter(t=>!e.has(t))),[e]);return{visibleColumns:n,columns:(0,G.useMemo)(()=>gNi(n),[n]),toggleColumn:(0,G.useCallback)(e=>{t(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[])}}function vNi({visibleColumns:e,toggleColumn:t}){return(0,K.jsxs)(rE,{children:[(0,K.jsx)(rE.Trigger,{asChild:!0,children:(0,K.jsx)(X,{icon:(0,K.jsx)(Q0r,{}),children:`Columns`})}),(0,K.jsxs)(rE.Content,{align:`end`,children:[(0,K.jsx)(rE.Label,{children:`Toggle columns`}),mNi.map(n=>(0,K.jsx)(rE.CheckboxItem,{checked:e.has(n),onClick:()=>t(n),children:hNi[n]},n))]})]})}var yNi=[eP(`/scorers`),eMt],bNi=[`date`,`score`];function xNi(){let{scorerId:e}=kv(),[t,n]=Rv(),r=t.get(`scoreId`)??void 0,[i,a]=(0,G.useState)(r),[o,s]=(0,G.useState)(!1),c=Ov(),[l,u]=(0,G.useState)({value:`all`,label:`All Entities`,type:`ALL`}),{scorer:d,error:f}=bjt(e),p=_Ni(),{data:m={},isLoading:h,error:g}=wN(),{isLoading:_,error:v}=eN({}),{sort:y,onSortChange:b}=u7({searchParams:t,setSearchParams:n,allowedKeys:bNi}),{data:x=[],isLoading:S,error:C,isFetchingNextPage:w,hasNextPage:T,setEndOfListElement:E}=yjt({scorerId:e,entityId:l?.value===`all`?void 0:l?.value,entityType:l?.type===`ALL`?void 0:l?.type}),D=(0,G.useMemo)(()=>IZ(x,y,{date:e=>e.createdAt,score:e=>typeof e.score==`number`?e.score:void 0}),[x,y]),O=(0,G.useMemo)(()=>d?.agentIds?.filter(e=>m[e]).map(e=>({value:e,label:m[e].name,type:`AGENT`}))||[],[d?.agentIds,m]),k=(0,G.useMemo)(()=>d?.workflowIds?.map(e=>({value:e,label:e,type:`WORKFLOW`}))||[],[d?.workflowIds]),A=(0,G.useMemo)(()=>[{value:`all`,label:`All Entities`,type:`ALL`},...O,...k],[O,k]),j=t.get(`entity`)??`all`,M=A.find(e=>e.value===j);M&&M.value!==l?.value&&u(M),(0,G.useEffect)(()=>{if(f){let e=f instanceof Error?f.message:`Failed to load scorer`;iS.error(`Error loading scorer: ${e}`)}},[f]),(0,G.useEffect)(()=>{if(g){let e=g instanceof Error?g.message:`Failed to load agents`;iS.error(`Error loading agents: ${e}`)}},[g]),(0,G.useEffect)(()=>{if(v){let e=v instanceof Error?v.message:`Failed to load workflows`;iS.error(`Error loading workflows: ${e}`)}},[v]);let N=e=>{e?.value&&n(t=>{let n=new URLSearchParams(t);return n.set(`entity`,e.value),n})};(0,G.useEffect)(()=>{let e=t.get(`scoreId`)??void 0;e!==i&&(e?D.find(t=>t.id===e)&&a(e):a(void 0))},[t,D]);let P=(0,G.useCallback)(e=>{a(e||void 0),n(t=>{let n=new URLSearchParams(t);return e?n.set(`scoreId`,e):n.delete(`scoreId`),n})},[n]);if(!d)return null;let F=FN(f)||FN(g)||FN(v),I=f&&IN(f),L=!F&&!I&&(f||g||v),R=!S&&D.length===0,z=l?.value!==`all`,B=d?.source===`stored`,V=e?(0,K.jsx)(Qpi,{open:o,onOpenChange:s,initialScorerIds:[e],onSuccess:e=>void c(`/experiments/${e}`)}):null,H=B?(0,K.jsxs)(rE,{children:[(0,K.jsx)(rE.Trigger,{asChild:!0,children:(0,K.jsx)(X,{size:`icon-lg`,"aria-label":`Scorer actions menu`,children:(0,K.jsx)(iE,{})})}),(0,K.jsx)(rE.Content,{align:`end`,className:`w-48`,children:(0,K.jsxs)(rE.Item,{onSelect:()=>void c(`/cms/scorers/${e}/edit`),children:[(0,K.jsx)(iH,{}),` Edit scorer`]})})]}):null;if(F||I||L||R&&!z){let t=(f instanceof Error?f.message:void 0)??(g instanceof Error?g.message:void 0)??(v instanceof Error?v.message:void 0)??`An unexpected error occurred`;return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:yNi}),actionRow:!(F||I||L)&&H?(0,K.jsx)(TK,{children:(0,K.jsx)(TK.End,{children:H})}):void 0,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:F?(0,K.jsx)(TH,{}):I?(0,K.jsx)(wH,{resource:`scorers`}):L?(0,K.jsx)(Jx,{tone:`error`,titleSlot:`Failed to load scorer`,descriptionSlot:t}):(0,K.jsx)(bLr,{onRunExperiment:()=>s(!0)})}),V]})}return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:yNi}),actionRow:(0,K.jsxs)(TK,{children:[(0,K.jsx)(TK.Start,{children:(0,K.jsx)(xLr,{selectedEntity:l,entityOptions:A,onEntityChange:N,onReset:()=>{n(e=>{let t=new URLSearchParams(e);return t.set(`entity`,`all`),t})},isLoading:S||h||_})}),(0,K.jsxs)(TK.End,{children:[(0,K.jsx)(vNi,{visibleColumns:p.visibleColumns,toggleColumn:p.toggleColumn}),(0,K.jsx)(X,{variant:`primary`,onClick:()=>s(!0),icon:(0,K.jsx)(Hx,{}),children:`New experiment`}),H]})]}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(yLr,{scores:D,isLoading:S,selectedScoreId:i,isFetchingNextPage:w,hasNextPage:T,setEndOfListElement:E,onScoreClick:P,errorMsg:C?.message,columnsState:p,sort:y,onSortChange:b}),V]})}var SNi=U(`IconMoon`,()=>(0,K.jsx)(`path`,{d:`M20.9638 12.7674C19.8361 13.5447 18.4693 13.9998 16.9961 13.9998C13.1301 13.9998 9.99609 10.8657 9.99609 6.99975C9.99609 5.52667 10.4511 4.15987 11.2283 3.03223C6.61911 3.42277 3 7.28768 3 11.9979C3 16.9674 7.0286 20.996 11.9981 20.996C16.7084 20.996 20.5734 17.3767 20.9638 12.7674Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})),CNi=U(`IconSun`,()=>(0,K.jsx)(`path`,{d:`M12 3V2M12 22V21M18.3598 5.64005L19.0698 4.93005M4.93016 19.07L5.64016 18.36M21 12H22M2 12H3M18.3598 18.36L19.0698 19.07M4.93016 4.93005L5.64016 5.64005M15.5355 8.46447C17.4882 10.4171 17.4882 13.5829 15.5355 15.5355C13.5829 17.4882 10.4171 17.4882 8.46447 15.5355C6.51185 13.5829 6.51185 10.4171 8.46447 8.46447C10.4171 6.51185 13.5829 6.51185 15.5355 8.46447Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})),wNi=[{value:`system`,label:`System`,icon:(0,K.jsx)(u8n,{})},{value:`light`,label:`Light`,icon:(0,K.jsx)(CNi,{})},{value:`dark`,label:`Dark`,icon:(0,K.jsx)(SNi,{})}];function TNi(e,t){if(e.some(e=>e.value===t))return t;let[n]=e;return n?n.value:`system`}var ENi=({value:e,onChange:t,options:n=wNi,size:r=`md`,"aria-label":i=`Theme`,...a})=>{let{theme:o,setTheme:s}=B(),c=e??o,l=t??s,u=TNi(n,c);return(0,K.jsx)(Eor,{...a,"aria-label":i,iconOnly:!0,size:r===`xs`?`sm`:r,value:u,onValueChange:l,children:n.map(e=>(0,K.jsx)(Dor,{value:e.value,"aria-label":e.label,children:e.icon},e.value))})};function DNi(e){return Object.fromEntries(e.filter(e=>e.name.trim()).map(e=>[e.name.trim(),e.value]))}function ONi(e,t){return e.baseUrl.trim()===t.baseUrl.trim()&&e.apiPrefix.trim()===(t.apiPrefix??``).trim()&&JSON.stringify(DNi(e.headers))===JSON.stringify(t.headers)}function kNi({initialConfig:e}){let{setConfig:t}=yS(),n=(0,G.useRef)(0),r=()=>({baseUrl:e.baseUrl,apiPrefix:e.apiPrefix??``,headers:Object.entries(e.headers).map(([e,t])=>({id:n.current++,name:e,value:t}))}),[i,a]=(0,G.useState)(r),[o,s]=(0,G.useState)(),c=!ONi(i,e),l=(0,K.jsx)(X,{type:`button`,size:`sm`,icon:(0,K.jsx)(Hx,{}),onClick:()=>a(e=>({...e,headers:[...e.headers,{id:n.current++,name:``,value:``}]})),children:`Add header`}),u=(e,t)=>a(n=>({...n,headers:n.headers.map(n=>n.id===e?{...n,...t}:n)}));function d(e){e.preventDefault(),i.baseUrl.trim()?(t({baseUrl:i.baseUrl.trim(),apiPrefix:i.apiPrefix.trim()||void 0,headers:DNi(i.headers)}),iS.success(`Connection saved`)):s(`Enter the server URL`)}function f(){a(r()),s(void 0)}return(0,K.jsx)(`form`,{onSubmit:d,onReset:f,noValidate:!0,children:(0,K.jsxs)(vZ,{children:[(0,K.jsx)(_Z,{label:`Mastra instance URL`,description:`The server this studio talks to.`,errorMsg:o,children:(0,K.jsx)(Jj,{name:`url`,value:i.baseUrl,placeholder:`http://localhost:4111`,spellCheck:!1,onChange:e=>{a(t=>({...t,baseUrl:e.target.value})),s(void 0)}})}),(0,K.jsx)(_Z,{label:`API prefix`,description:`Path in front of every API route.`,children:(0,K.jsx)(Jj,{name:`apiPrefix`,value:i.apiPrefix,placeholder:`/api (default)`,spellCheck:!1,onChange:e=>a(t=>({...t,apiPrefix:e.target.value}))})}),i.headers.length===0?(0,K.jsx)(xZ,{action:l,children:`No request headers`}):(0,K.jsx)(O5n,{action:l,children:i.headers.length===1?`1 request header`:`${i.headers.length} request headers`}),i.headers.map(e=>(0,K.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(Jj,{"aria-label":`Header name`,value:e.name,placeholder:`Authorization`,spellCheck:!1,onChange:t=>u(e.id,{name:t.target.value})}),(0,K.jsx)(Jj,{"aria-label":e.name?`Value of ${e.name}`:`Header value`,value:e.value,placeholder:`Bearer <token>`,spellCheck:!1,onChange:t=>u(e.id,{value:t.target.value})}),(0,K.jsx)(X,{type:`button`,size:`icon-md`,variant:`ghost`,"aria-label":e.name?`Remove ${e.name}`:`Remove header`,tooltip:`Remove header`,onClick:()=>a(t=>({...t,headers:t.headers.filter(t=>t.id!==e.id)})),children:(0,K.jsx)(Kj,{})})]},e.id)),c?(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,K.jsx)(`span`,{className:`text-body-sm text-muted-foreground`,children:`Unsaved changes`}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(X,{type:`reset`,size:`sm`,variant:`ghost`,children:`Discard`}),(0,K.jsx)(X,{type:`submit`,size:`sm`,variant:`primary`,children:`Save changes`})]})]}):null]})})}function ANi(){let{baseUrl:e,apiPrefix:t,headers:n}=yS(),r=JSON.stringify([e,t??``,n]);return(0,K.jsxs)(yZ,{children:[(0,K.jsx)(bZ,{info:`The Mastra instance the studio talks to, the path in front of its API routes, and the headers sent with every request.`,children:`Mastra connection`}),(0,K.jsx)(kNi,{initialConfig:{baseUrl:e,apiPrefix:t,headers:n}},r)]})}var jNi=()=>(0,K.jsx)(RS,{children:(0,K.jsxs)(M5n,{title:`Settings`,children:[(0,K.jsxs)(yZ,{children:[(0,K.jsx)(bZ,{info:`Stored in this browser.`,children:`General`}),(0,K.jsx)(vZ,{children:(0,K.jsx)(_Z,{label:`Theme`,description:`Color scheme for the interface.`,children:(0,K.jsx)(ENi,{})})})]}),(0,K.jsx)(ANi,{})]})});function MNi(){let[e]=Rv(),t=Ov(),n=e.get(`redirect`)||`/`;return(0,K.jsx)(pki,{redirectUri:n,onSuccess:()=>{n.startsWith(`http`)?window.location.href=n:t(n,{replace:!0})},initialMode:`signup`})}function NNi({current:e,features:t}){let n=r2r(),r=i2r(),i=[`traces`];n.enabled&&t?.spanQuery===!0&&i.push(`spans`),r.enabled&&t?.threadQuery===!0&&i.push(`threads`);let a=n.isLoading||r.isLoading;return{views:i,isLoading:a,showSwitch:!a&&i.length>1&&i.includes(e)}}var PNi=[`traces`,`spans`],FNi={traces:{icon:(0,K.jsx)(QN,{}),label:`Traces`},spans:{icon:(0,K.jsx)(YV,{}),label:`Spans`},threads:{icon:(0,K.jsx)(Iq,{}),label:`Threads`}};function INi({current:e,views:t=PNi,onViewChange:n}){return(0,K.jsx)(`nav`,{"aria-label":`Observability views`,children:(0,K.jsx)(gk,{value:e,defaultTab:e,onValueChange:n,children:(0,K.jsx)(hk,{variant:`pill-ghost`,children:t.map(e=>(0,K.jsxs)(_k,{value:e,children:[(0,K.jsx)(Dx,{size:`xs`,children:FNi[e].icon}),(0,K.jsx)(T,{variant:`caption`,className:`text-inherit`,children:FNi[e].label})]},e))})})})}function LNi(){return(0,K.jsxs)(`div`,{role:`status`,"aria-label":`Loading views`,className:`flex min-h-control-md items-center gap-0.5`,children:[(0,K.jsx)(zS,{className:`h-control-md w-20 rounded-full`}),(0,K.jsx)(zS,{className:`h-control-md w-20 rounded-full`})]})}function RNi({current:e,features:t,onViewChange:n,breadcrumbs:r,children:i}){let{views:a,isLoading:o,showSwitch:s}=NNi({current:e,features:t}),[c,l]=(0,G.useState)(null),u=bii(),d;return o?d=(0,K.jsx)(LNi,{}):s&&(d=(0,K.jsx)(INi,{current:e,views:a,onViewChange:n})),(0,K.jsx)(RS,{breadcrumbs:r({current:e,isLoading:o,showSwitch:s}),actionRow:(d||u)&&(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center justify-between gap-3`,children:[d,(0,K.jsx)(`div`,{ref:l,className:`flex min-w-0 grow justify-end`})]}),children:(0,K.jsx)(koi.Provider,{value:c??void 0,children:i})})}function zNi({isLoading:e,enabled:t,heading:n,title:r,description:i,children:a}){return t?a:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:n}),e?(0,K.jsxs)(`div`,{className:`flex h-full items-center justify-center gap-2`,children:[(0,K.jsx)(It,{"aria-label":`Loading storage capabilities`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:`Loading storage capabilities`})]}):(0,K.jsx)(Jx,{variant:`fill`,titleSlot:r,descriptionSlot:i})]})}var BNi={refetchInterval:({state:e})=>zri(e.error),refetchOnWindowFocus:!1};function VNi(e){let[t,n]=(0,G.useState)(()=>new URLSearchParams);return e||{searchParams:t,setSearchParams:e=>n(t=>typeof e==`function`?e(t):e)}}function HNi(e,{sortFields:t,withTokenSearch:n=!1,defaultDatePreset:r=Dii}={}){let{searchParams:i,setSearchParams:a}=VNi(e),o=JSON.stringify(Nii(i,r)),s=JSON.stringify(Fii(i)),{datePreset:c,dateFrom:l,dateTo:u}=(0,G.useMemo)(()=>Nii(i,r),[o]),{tokens:d,groups:f}=(0,G.useMemo)(()=>{let e=Fii(i);return n?e:{...e,tokens:e.tokens.filter(e=>e.operatorId!==`hasAllTokens`)}},[s,n]),p=Lii(i,t??Tii),m=(0,G.useMemo)(()=>({field:p.field,direction:p.direction}),[p.field,p.direction]),h=l?.getTime(),g=u?.getTime(),_=(0,G.useMemo)(()=>{let e=new Date,t=z2r(c,h===void 0?void 0:new Date(h),g===void 0?void 0:new Date(g),e);return d8(t.dateFrom,t.dateTo,e)},[c,h,g]),v=(0,G.useRef)(null);(0,G.useLayoutEffect)(()=>{v.current=null},[i]);let y=e=>{let t=v.current??i,n=new URLSearchParams(t);e(n),n.toString()!==t.toString()&&(v.current=n,a(n,{replace:!0}))},b=e=>y(t=>Pii(t,e(Nii(t,r)),r)),x=(0,G.useRef)(void 0),S=e=>{x.current=void 0,b(e)},C=e=>S(t=>e===`custom`?{...t,datePreset:e}:{datePreset:e}),w=(e,t)=>S(n=>n.datePreset===`custom`?t===`from`?{...n,dateFrom:e}:{...n,dateTo:e}:n),T=(e,t)=>S(n=>n.datePreset===`custom`?{...n,dateFrom:e,dateTo:t}:n),E=(e,t)=>b(n=>(x.current=uii(x.current,n,e,t),{datePreset:`custom`,dateFrom:e,dateTo:t})),D=e=>b(t=>{let n=dii(x.current,t);return x.current=void 0,n??{datePreset:e}}),O=(e,t)=>y(n=>Iii(n,{tokens:e,groups:t})),k=e=>y(t=>Rii(t,e)),A=d.length>0||f.length>0;return{datePreset:c,dateFrom:l,dateTo:u,timeRange:_,rolling:u===void 0,tokens:d,groups:f,sort:m,setSort:k,onDatePresetChange:C,onDateChange:w,onDateRangeChange:T,onZoom:E,onDateReset:D,onFiltersChange:O,contentFiltersApplied:A,filtersApplied:A||c!==r}}function UNi(e){return[`observability-list-head`,...e]}function WNi(e){let t=m_([e]),[n,r]=(0,G.useState)();return{anchorTo:n?.selectionHash===t?n.to:void 0,reanchor:()=>r({selectionHash:t,to:new Date().toISOString()})}}var GNi=()=>({rows:[],watermark:void 0});function KNi({queryKey:e,fetchHead:t,getId:n,getEndedAt:r,enabled:i,since:a,limit:o=50,maxRows:s=500,interval:c=Fri,onOverflow:l}){let u=u_(),d=UNi(e),{data:f}=T_({queryKey:d,queryFn:async()=>{let e=u.getQueryData(d)??GNi(),i=await t(new Date().toISOString()),c=i.map(e=>Date.parse(r(e)??``)).filter(Number.isFinite),f=new Map(e.rows.map(e=>[n(e),e]));for(let e of i)f.set(n(e),e);let p=e.watermark??a;if(p!==void 0&&i.length>=o&&c.length>0&&Math.min(...c)>p||f.size>s)return l?.(),GNi();let m=c.length>0?Math.max(e.watermark??-1/0,...c):e.watermark;return{rows:[...f.values()],watermark:m}},initialData:GNi,staleTime:1/0,enabled:i,refetchInterval:e=>!Lri(e.state.error)&&c,refetchOnWindowFocus:!1,refetchOnReconnect:!1,retry:!1});return{headRows:f.rows}}function qNi(e,t){if(e===t)return!0;let n=e,r=t,i=Object.keys(n);return i.length===Object.keys(r).length&&i.every(e=>Object.is(n[e],r[e]))}function JNi(e,t,n){if(t.length===0)return e;let{getId:r,compare:i,hasNextPage:a}=n,o=new Map(t.map(e=>[r(e),e])),s=!1,c=[];for(let t of e){let e=r(t),n=o.get(e);n===void 0?c.push(t):(o.delete(e),qNi(t,n)?c.push(t):i(t,n)===0?(c.push(n),s=!0):(o.set(e,n),s=!0))}let l=[...o.values()].sort(i);if(l.length===0)return s?c:e;let u=c[c.length-1],d=[],f=0;for(let e of l){if(a&&(u===void 0||i(e,u)>=0))break;for(let t=c[f];t!==void 0&&i(t,e)<=0;t=c[++f])d.push(t);d.push(e),s=!0}return d.push(...c.slice(f)),s?d:e}var YNi={traces:`Traces`,spans:`Spans`,threads:`Threads`};function XNi({current:e,isLoading:t,showSwitch:n}){if(!(t||n||e===`traces`))return YNi[e]}function ZNi(e){let t=e.get(`traceId`),n=e.get(`spanId`);return t&&n?{traceId:t,spanId:n}:void 0}function QNi(e,t){let n=new URLSearchParams(e);return t?(n.set(`traceId`,t.traceId),n.set(`spanId`,t.spanId)):(n.delete(`traceId`),n.delete(`spanId`)),n}function $Ni({traceId:e,spanId:t}){return new URLSearchParams({traceId:e,spanId:t})}function ePi(e){return e.get(`threadId`)??void 0}function tPi(e,t){let n=new URLSearchParams(e);return t?n.set(`threadId`,t):n.delete(`threadId`),n}var nPi=e=>`${e.traceId}:${e.spanId}`;function rPi(e){let{field:t=`startedAt`,direction:n=`desc`}=e?.[0]??{},r=n===`asc`?1:-1;return(e,n)=>{let i=e[t],a=n[t];if(i!==a){if(i==null)return 1;if(a==null)return-1;if(i<a)return-r;if(i>a)return r}return e.traceId.localeCompare(n.traceId)||e.spanId.localeCompare(n.spanId)}}function iPi({query:e,rolling:t,autoRefetch:n=!0,limit:r,enabled:i=!0}){let a=Y(),{anchorTo:o,reanchor:s}=WNi(e),c=(0,G.useMemo)(()=>o?{...e,timeRange:{...e.timeRange,to:o}}:e,[e,o]),l=nXr({query:c,limit:r,enabled:i,queryOptions:BNi}),{headRows:u}=KNi({queryKey:[`spans`,e],fetchHead:async t=>(await a.querySpans({...e,timeRange:{from:e.timeRange.from,to:t},orderBy:[{field:`endedAt`,direction:`desc`}],page:{limit:50}})).spans,getId:nPi,getEndedAt:e=>e.endedAt,since:Date.parse(c.timeRange.to),enabled:i&&t&&n&&l.spans!==void 0&&!l.isFetching&&!l.isError,onOverflow:s}),{orderBy:d}=e,f=l.spans,p=(0,G.useMemo)(()=>f&&JNi(f,u,{getId:nPi,compare:rPi(d),hasNextPage:l.hasNextPage}),[f,u,d,l.hasNextPage]);return{...l,spans:p}}function aPi(e){return{traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId,name:e.name,entityType:e.entityType,entityId:e.entityId,threadId:e.threadId,resourceId:e.resourceId,environment:e.environment,model:e.model,provider:e.provider,status:e.status,outcome:e.outcome,stopReason:e.stopReason,stopReasonContext:e.stopReasonContext,inputPreview:e.inputPreview,outputPreview:e.outputPreview??void 0,errorPreview:e.errorPreview??void 0,startedAt:e.startedAt,endedAt:e.endedAt,createdAt:e.startedAt,timeToFirstChunkMs:e.timeToFirstChunkMs,timeToFirstTokenMs:e.timeToFirstTokenMs}}function oPi({timeRange:e,where:t,onZoom:n}){let r=o2r(),i=(0,G.useMemo)(()=>({timeRange:e,...t?{where:t}:{},interval:k8r(e).interval,measures:[...x8r],limit:1}),[e,t]),a=!r.enabled||A8r(e),{data:o,isLoading:s,isError:c,isPlaceholderData:l}=RYr({request:i,enabled:!a,queryOptions:{placeholderData:__}}),u=(0,G.useMemo)(()=>F8r(o?.rows??[],e),[o,e]);return a?null:(0,K.jsx)(g8r,{label:`Spans over time`,resourceLabel:`Spans`,buckets:u,isLoading:s,isError:c,isUpdating:l,onZoom:n&&(t=>n(I8r(u,t,e)))})}var sPi=[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`],cPi=[];function lPi({timeRange:e,withTokenSearch:t=!1}){let n=Y(),{data:r}=i5(),i=r?.capabilities.spanQueryContextFields??!1,a=r?.capabilities.traceQueryTimeToFirstChunk??!1,o=r?.capabilities.traceQueryTimeToFirstToken??!1,s=r?.capabilities.spanQueryOutcomeFields??!1,c=r?.capabilities.spanQueryModelFields??!1,{data:l=cPi}=t8(),{data:u=cPi}=n8();return(0,G.useMemo)(()=>[d3r,...V6(vai({withContextFields:i,withTimeToFirstChunk:a,withTimeToFirstToken:o,withOutcomeFields:s,withModelFields:c,entityNames:l,environments:u,valueSuggestions:t=>MXr(n,e,`spans`,t)}),t)],[t,i,a,o,s,c,l,u,n,e])}function uPi({tokens:e,groups:t,onFiltersChange:n}){let r=(0,G.useMemo)(()=>P8(e),[e]),i=(0,G.useMemo)(()=>{let e=F8([],t);return{...e,nodes:[p5,...r,...e.nodes]}},[r,t]),a=(0,G.useCallback)(e=>{let t=UZr({...e,nodes:e.nodes.filter(e=>H6(e)||e.fieldId!==`timeRange`)});n(t.tokens,t.groups)},[n]);return{filterBarValue:i,onFilterBarChange:a,onFilterByField:(0,G.useCallback)((e,t)=>{let n=r.filter(t=>t.fieldId!==e),o={id:`${e}:${t}`,fieldId:e,operatorId:`is`,value:t},s=i.nodes.filter(H6);a({...i,nodes:[...n,o,...s]})},[r,i,a])}}var dPi=e=>e;function fPi({withTokenSearch:e=!1,datePreset:t,dateFrom:n,dateTo:r,minDate:i,timeRange:a,tokens:o,groups:s,onDatePresetChange:c,onDateChange:l,onDateRangeChange:u,onDateReset:d,onFiltersChange:f,describeSuggestionsError:p,disabled:m}){let h=lPi({timeRange:a,withTokenSearch:e}),{filterBarValue:g,onFilterBarChange:_}=uPi({tokens:o,groups:s,onFiltersChange:f});return(0,K.jsxs)(m5,{fields:h,operators:gZr,value:g,onValueChange:_,createItemId:dPi,describeSuggestionsError:p,maxDepth:3,"aria-label":`Span filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(m5.Chips,{renderChip:e=>e.fieldId===`timeRange`?(0,K.jsx)(m5.TimeRange,{preset:t,onPresetChange:c,dateFrom:n,dateTo:r,minDate:i,onDateChange:l,onDateRangeChange:u,disabled:m,presets:sPi,defaultPreset:o5.datePreset,onReset:d&&(()=>d(o5.datePreset))}):(0,K.jsx)(m5.Chip,{item:e})}),(0,K.jsx)(m5.Input,{placeholder:`Filter spans`})]})}function pPi({selection:e,onSelectionChange:t,renderPanel:n,urlState:r}){let{data:i,isLoading:a}=i5(),o=!!(i?.capabilities.spanQueryTokenSearch&&i.capabilities.spanAggregateTokenSearch),s=HNi(r,{sortFields:Eii,withTokenSearch:o}),{timeRange:c,tokens:l,groups:u}=s,d=oii({scope:`spans`}),f=i?.capabilities.spanQueryContextFields??!1,p=i?.capabilities.traceQueryTimeToFirstChunk??!1,m=i?.capabilities.traceQueryTimeToFirstToken??!1,h=i?.capabilities.spanQueryOutcomeFields??!1,g=i?.capabilities.spanQueryModelFields??!1,_=(0,G.useMemo)(()=>a?d.preferences:T0r(d.preferences,{withTimeToFirstChunk:p,withTimeToFirstToken:m}),[d.preferences,a,p,m]),v=(0,G.useMemo)(()=>{let e=[`startedAt`];return p&&i?.capabilities.traceQueryTimeToFirstChunkSort&&e5(_,`timeToFirstChunk`)&&e.push(`timeToFirstChunkMs`),m&&i?.capabilities.traceQueryTimeToFirstTokenSort&&e5(_,`timeToFirstToken`)&&e.push(`timeToFirstTokenMs`),e},[i,p,m,_]),y=v.includes(s.sort.field)?s.sort:{field:`startedAt`,direction:`desc`},{field:b,direction:x}=y,S=(0,G.useMemo)(()=>xai(l,u,{withTokenSearch:o,withContextFields:f,withOutcomeFields:h,withModelFields:g,withTimeToFirstChunk:p,withTimeToFirstToken:m}),[l,u,o,f,h,g,p,m]),{spans:C,hasNextPage:w,isFetchingNextPage:T,setEndOfListElement:E,isLoading:D,isError:O,error:k}=iPi({query:(0,G.useMemo)(()=>({timeRange:c,orderBy:[{field:b,direction:x}],where:S}),[c,b,x,S]),enabled:!a,rolling:s.rolling}),A=(0,G.useMemo)(()=>(C??[]).map(aPi),[C]),j=(0,G.useMemo)(()=>A.flatMap(e=>e.spanId?[{traceId:e.traceId,spanId:e.spanId}]:[]),[A]),M=n=>{n.spanId&&t(e?.traceId===n.traceId&&e.spanId===n.spanId?void 0:{traceId:n.traceId,spanId:n.spanId})},N=!D&&!O&&A.length===0&&!s.contentFiltersApplied&&!e;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Spans`}),(0,K.jsx)(Y0r,{toolbar:(0,K.jsxs)(K.Fragment,{children:[r&&(0,K.jsx)(Loi,{page:`spans`,...r,columns:d}),(0,K.jsxs)(TK,{children:[(0,K.jsx)(TK.Start,{children:(0,K.jsx)(fPi,{withTokenSearch:o,datePreset:s.datePreset,dateFrom:s.dateFrom,dateTo:s.dateTo,timeRange:c,tokens:l,groups:u,onDatePresetChange:s.onDatePresetChange,onDateChange:s.onDateChange,onDateRangeChange:s.onDateRangeChange,onDateReset:s.onDateReset,onFiltersChange:s.onFiltersChange,disabled:D})}),(0,K.jsx)(TK.End,{children:(0,K.jsx)(p2r,{scope:`spans`,value:d.preferences,onChange:d.setPreferences})})]})]}),chart:(0,K.jsx)(oPi,{timeRange:c,where:S,onZoom:({from:e,to:t})=>s.onZoom(e,t)}),error:O?(0,K.jsx)(Q8,{error:k,resource:`spans`,errorTitle:`Failed to load spans`}):void 0,empty:N?(0,K.jsx)(r0r,{resource:`spans`,datePreset:s.datePreset,dateFrom:s.dateFrom,dateTo:s.dateTo}):void 0,children:(0,K.jsx)(_7r,{listId:`all-spans`,traces:A,columnPreferences:_,isLoading:D,isFetchingNextPage:T,hasNextPage:w,setEndOfListElement:E,filtersApplied:s.filtersApplied,resource:`spans`,isBranchesMode:!0,sort:y,sortableFields:v,onSortChange:s.setSort,featuredTraceId:e?.traceId,featuredSpanId:e?.spanId,onTraceClick:M})}),n({selection:e,spans:j,onSelect:t,onClose:()=>t(void 0)})]})}function mPi({selection:e,spans:t,onSelect:n,onClose:r,onShowTrace:i}){let{data:a,isLoading:o}=r8({traceId:e.traceId,spanId:e.spanId}),s=t.findIndex(t=>t.traceId===e.traceId&&t.spanId===e.spanId),c=s>0?t[s-1]:void 0,l=s>=0&&s<t.length-1?t[s+1]:void 0;return(0,K.jsx)(Iti,{traceId:e.traceId,spanId:e.spanId,span:a?.span,isLoading:o,onPrevious:c?()=>n(c):void 0,onNext:l?()=>n(l):void 0,onClose:r,onShowTrace:i})}function hPi({selection:e,spans:t,onSelect:n,onClose:r,onShowTrace:i}){let a=Zw();J1r(e?`${e.traceId}:${e.spanId}`:void 0,r);let o=e?(0,K.jsx)(mPi,{selection:e,spans:t,onSelect:n,onClose:r,onShowTrace:i}):null;return a?(0,K.jsx)(jQ,{open:!!e,onClose:r,title:`Span details`,children:o}):o?(0,K.jsx)(Y8,{owner:`span-detail`,children:(0,K.jsx)(jQ,{variant:`inline`,title:`Span details`,children:o})}):null}function gPi(){let{enabled:e,isLoading:t}=r2r(),n=Ov(),[r,i]=Rv();return(0,K.jsx)(zNi,{enabled:e,isLoading:t,heading:`Spans`,title:`Query spans capability not activated`,description:`Your observability storage does not support span queries. Switch to a store that declares the span-query capability to list spans.`,children:(0,K.jsx)(pPi,{urlState:{searchParams:r,setSearchParams:i},selection:ZNi(r),onSelectionChange:e=>i(t=>QNi(t,e),{replace:!0}),renderPanel:e=>(0,K.jsx)(hPi,{...e,onShowTrace:e=>n(`/traces?${$Ni(e)}`)})})})}async function _Pi(){let e=await fetch(`https://mastra.ai/api/templates.json`);if(!e.ok)throw Error(`Failed to fetch templates: ${e.statusText}`);let t=[{title:`Weather Agent`,slug:`weather-agent`,githubUrl:`https://github.com/mastra-ai/weather-agent`,description:`Get weather information of any city.`,longDescription:`One Agent, one Workflow and one Tool to bring you the weather in your city.`,imageURL:``,tags:[`Agent`,`Workflow`,`Tool`],useCase:``,supportedProviders:[`openai`,`anthropic`,`google`,`groq`],agents:[`weatherAgent`],tools:[`weatherTool`],workflows:[`weatherWorkflow`]},...await e.json()];return{templates:t,tags:Array.from(new Set(t.flatMap(e=>e.tags))),providers:Array.from(new Set(t.flatMap(e=>e.supportedProviders)))}}async function vPi({repo:e,owner:t}){let n=await fetch(`https://api.github.com/repos/${t}/${e}`);if(!n.ok)throw Error(`Failed to fetch template: ${n.statusText}`);let r=await n.json();if(!r.is_template)throw Error(`Repo is not a template, please update the repo settings to make it a template`);return{title:r.name,slug:r.name,description:r.description??``,imageURL:``,tags:[],useCase:``,longDescription:r.description??``,githubUrl:r.html_url,supportedProviders:[]}}async function yPi({repoOrSlug:e,owner:t}){let{templates:n}=await _Pi(),r=n.find(t=>t.slug===e);if(!r){if(t===`mastra-ai`&&e.startsWith(`template-`)){let t=n.find(t=>`template-${t.slug}`===e);if(t)return t}let r=await vPi({repo:e,owner:t});if(r)return r;throw Error(`Template ${e} not found`)}return r}async function bPi({repo:e,owner:t,branch:n}){let r=`https://raw.githubusercontent.com/${t}/${e}/${n}/.env.example`,i=await fetch(r);return i.ok?(await i.text()).split(`
|
|
724
|
-
`).reduce((e,t)=>{if(!t||t.startsWith(`#`))return e;let[n,r]=t.split(`=`);return n&&(e[n]=r?.split(``)?.every(e=>e===`*`)?``:r?.replaceAll(`"`,``)),e},{}):{}}var xPi=({queryOptions:e}={})=>T_({queryKey:[`mastra-templates`],queryFn:_Pi,...e}),SPi=({repoOrSlug:e,owner:t,queryOptions:n})=>T_({queryKey:[`template-repo`,e,t],queryFn:()=>yPi({repoOrSlug:e,owner:t}),...n}),CPi=({repo:e,owner:t,branch:n,queryOptions:r})=>T_({queryKey:[`template-repo-env-vars`,e,t,n],queryFn:()=>bPi({repo:e,owner:t,branch:n}),...r}),wPi=({queryOptions:e}={})=>{let t=Y();return T_({queryKey:[`agent-builder-workflow`],queryFn:async()=>await t.getAgentBuilderAction(`merge-template`).details(),...e})},TPi=({queryOptions:e}={})=>{let t=Y();return D_({mutationFn:async({runId:e})=>await t.getAgentBuilderAction(`merge-template`).createRun({runId:e}),...e})},EPi=({queryOptions:e}={})=>{let t=Y();return D_({mutationFn:async({runId:e})=>await t.getAgentBuilderAction(`merge-template`).runById(e),...e})},DPi=e=>{if(typeof e==`string`)return e;if(e==null)return`Unknown error`;if(e instanceof Error)return typeof e.message==`string`&&e.message.length>0?e.message:`Unknown error`;if(typeof e==`object`)try{return JSON.stringify(e)}catch{return String(e)}return String(e)},OPi=(e,t,n)=>{let r={...t};if(!(r.payload?.workflowState?.steps&&Object.keys(r.payload.workflowState.steps).length>0)&&n?.allSteps&&(r.payload={...r.payload,workflowState:{...r.payload?.workflowState,steps:Object.keys(n.allSteps).reduce((e,t)=>(e[t]={id:t,description:n.allSteps[t].description,status:`pending`},e),{})}}),e.type===`start`||e.type===`workflow-start`){let t={};n?.allSteps&&Object.entries(n.allSteps).forEach(([e,n])=>{t[e]={id:n.id,description:n.description,status:`pending`}});let i=e.runId||e.payload?.runId;r={...r,runId:i,eventTimestamp:new Date().toISOString(),status:`running`,phase:`initializing`,payload:{workflowState:{status:`running`,steps:t},currentStep:null}}}if(e.type===`step-start`||e.type===`workflow-step-start`){let t=e.payload.id;r={...r,phase:`processing`,payload:{...r.payload,currentStep:{id:t,status:`running`,startTime:new Date,...e.payload},workflowState:{...r.payload.workflowState,steps:{...r.payload.workflowState.steps,[t]:{...r.payload.workflowState.steps[t],status:`running`,startTime:new Date,...e.payload}}}}}}if(e.type===`step-result`||e.type===`workflow-step-result`){let t=e.payload.id,n=e.payload.status,i=e.payload.error;if(r={...r,payload:{...r.payload,currentStep:{...r.payload.currentStep,status:e.payload.status,output:e.payload.output,error:e.payload.error,endTime:new Date},workflowState:{...r.payload.workflowState,steps:{...r.payload.workflowState.steps,[t]:{...r.payload.workflowState.steps[t],status:e.payload.status,output:e.payload.output,error:e.payload.error,endTime:new Date}}}}},n===`failed`&&i){let n=DPi(i);r={...r,status:`failed`,error:n,phase:`error`,failedStep:{id:t,error:n,description:e.payload.description||t},payload:{...r.payload,workflowState:{...r.payload.workflowState,status:`failed`}},errorTimestamp:new Date}}}if((e.type===`step-finish`||e.type===`workflow-step-finish`)&&(r={...r,payload:{...r.payload,currentStep:null}}),(e.type===`finish`||e.type===`workflow-finish`)&&(r=r.phase===`error`||r.status===`failed`?{...r,completedAt:new Date}:{...r,status:e.payload.status||`completed`,phase:`completed`,payload:{...r.payload,currentStep:null,workflowState:{...r.payload.workflowState,status:e.payload.status||`completed`}},completedAt:new Date}),e.type===`error`){let t=DPi(e.payload.error);r={...r,status:`failed`,error:t,phase:`error`,payload:{...r.payload,workflowState:{...r.payload.workflowState,status:`failed`}},errorTimestamp:new Date}}return{newState:r}},kPi=(e,t)=>{try{localStorage.setItem(`template-install-${e}`,JSON.stringify({state:t,timestamp:Date.now()}))}catch(e){console.warn(`Failed to save template state to localStorage:`,e)}},APi=(e,t)=>{let[n,r]=(0,G.useState)({}),[i,a]=(0,G.useState)(!1);return{streamResult:n,isStreaming:i,processStream:async(n,i)=>{if(a(!0),r({}),!n)throw Error(`No stream returned`);let o=n.getReader(),s={runId:i||t,eventTimestamp:new Date().toISOString(),phase:`running`,payload:{workflowState:{steps:{}},currentStep:null}};try{for(;;){let{done:n,value:a}=await o.read();if(n)break;let{newState:c}=OPi(a,s,e);s=c,r(c),(a.runId||i||t)&&kPi(a.runId||i||t,c)}}catch(t){console.error(`💥 [processStream] Error processing template installation stream:`,t);let{newState:n}=OPi({type:`error`,payload:{error:t instanceof Error?t.message:`Unknown error`}},s,e);r(n)}finally{a(!1),o.releaseLock()}}}},jPi=({workflowInfo:e,queryOptions:t}={})=>{let n=Y(),{streamResult:r,isStreaming:i,processStream:a}=APi(e);return{streamInstall:D_({mutationFn:async({inputData:e,selectedModel:t,runId:r})=>{for(let i=1;i<=3;i++)try{let i=n.getAgentBuilderAction(`merge-template`),o=new On;o.set(`selectedModel`,t);let s=await i.stream({inputData:e,requestContext:o},r);await a(s,r);return}catch(e){console.error(`💥 [streamInstall] Attempt ${i} failed:`,e);let t=e?.message?.includes(`Failed to fetch`)||e?.message?.includes(`NetworkError`)||e?.message?.includes(`network error`)||e?.message?.includes(`fetch`)||e?.code===`NETWORK_ERROR`||e?.name===`TypeError`;if(console.warn(`Stream attempt ${i}/3 failed:`,e),t){let e=r?`Network error during template installation (likely hot reload). Please refresh the page to resume from where you left off using runId: ${r}`:`Network error during template installation (likely hot reload). Please try again.`;throw console.error(`🔌 Stream network error:`,e),Error(e)}throw console.error(`❌ [streamInstall] Non-network error or max retries reached, throwing:`,e),e}},...t?.streamInstall}),streamResult:r,isStreaming:i}},MPi=({workflowInfo:e,queryOptions:t}={})=>{let n=Y(),{streamResult:r,isStreaming:i,processStream:a}=APi(e);return{observeInstall:D_({mutationFn:async({runId:e})=>{let t=2e3;for(let r=1;r<=3;r++)try{let t=await n.getAgentBuilderAction(`merge-template`).observeStream({runId:e});await a(t,e);return}catch(e){console.error(`💥 [observeInstall] Attempt ${r} failed:`,e);let n=e?.message?.includes(`Failed to fetch`)||e?.message?.includes(`NetworkError`)||e?.message?.includes(`network error`)||e?.message?.includes(`fetch`)||e?.code===`NETWORK_ERROR`||e?.name===`TypeError`;if(console.warn(`ObserveStream attempt ${r}/3 failed:`,e),n&&r<3){console.info(`🔄 ObserveStream network error detected (likely hot reload), retrying in ${t}ms... (attempt ${r+1}/3)`),await new Promise(e=>setTimeout(e,t));continue}throw console.error(`❌ [observeInstall] Non-network error or max retries reached, throwing:`,e),e}},...t?.observeInstall}),streamResult:r,isStreaming:i}};function NPi(e){return e.replace(/\/$/,``).split(`/`).pop()}function PPi({templates:e,linkComponent:t,className:n,isLoading:r}){let i=t||`a`;return r?(0,K.jsx)(`div`,{className:c(`grid gap-y-4`,n),children:Array.from({length:5}).map((e,t)=>(0,K.jsx)(`div`,{className:`h-16 animate-pulse rounded-lg bg-card`},t))}):(0,K.jsx)(`div`,{className:c(`grid gap-y-4`,n),children:e.map(e=>{let t=e?.agents||e?.tools||e?.networks||e?.workflows||e?.mcp;return(0,K.jsxs)(`article`,{className:c(Bv,`grid w-full grid-cols-[1fr_auto] overflow-hidden rounded-lg state-layer`),children:[(0,K.jsxs)(i,{to:`/templates/${e.slug}`,className:c(`group grid`,{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":e.imageURL}),children:[e.imageURL&&(0,K.jsx)(`div`,{className:`overflow-hidden`,children:(0,K.jsx)(`div`,{className:`thumb transition-scale h-full w-full bg-cover duration-150`,style:{backgroundImage:`url(${e.imageURL})`}})}),(0,K.jsxs)(`div`,{className:c(`grid w-full gap-0.5 px-4 py-3`,`[&_svg]:h-[1em] [&_svg]:w-[1em] [&_svg]:text-muted-foreground`),children:[(0,K.jsx)(T,{as:`h2`,tone:`ink`,children:e.title}),(0,K.jsx)(T,{className:c(CS,A),children:e.description}),(0,K.jsxs)(`div`,{className:`mt-3 hidden flex-wrap items-center gap-x-8 gap-y-4 text-muted-foreground 2xl:flex`,children:[t&&(0,K.jsxs)(`ul`,{className:c(`text-muted-foreground`,`m-0 flex list-none gap-4 p-0`,`[&>li]:flex [&>li]:items-center [&>li]:gap-0.5`),children:[e?.agents&&e.agents.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(HN,{}),` `,e.agents.length]})}),e?.tools&&e.tools.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(XN,{}),` `,e.tools.length]})}),e?.networks&&e.networks.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(n7e,{}),` `,e.networks.length]})}),e?.workflows&&e.workflows.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(ZS,{}),` `,e.workflows.length]})}),e?.mcp&&e.mcp.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(KN,{}),` `,e.mcp.length]})})]}),(0,K.jsx)(`div`,{className:`flex items-center gap-4`,children:e.supportedProviders.map(e=>(0,K.jsx)(T,{tone:`muted`,as:`span`,variant:`body`,children:e},e))})]})]})]}),(0,K.jsx)(`a`,{href:e.githubUrl,className:c(`group ml-auto hidden items-center gap-2 pr-4`,`lg:flex`),target:`_blank`,rel:`noopener noreferrer`,children:(0,K.jsx)(T,{as:`span`,variant:`body`,children:(0,K.jsxs)(`span`,{className:c(`flex items-center gap-2 rounded bg-sidebar px-2 py-1`,Jze,CS,A),children:[(0,K.jsx)(kZ,{}),` `,NPi(e.githubUrl)]})})})]},e.slug)})})}function FPi({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:i,onProviderChange:a,searchTerm:o,onSearchChange:s,onReset:l,className:u,isLoading:d}){return d?(0,K.jsxs)(`div`,{className:c(`flex h-[6.5rem] items-center gap-5`,`[&>div]:h-8 [&>div]:w-48 [&>div]:animate-pulse [&>div]:bg-card`,u),children:[(0,K.jsx)(`div`,{}),` `,(0,K.jsx)(`div`,{}),` `,(0,K.jsx)(`div`,{})]}):(0,K.jsxs)(`div`,{className:c(`sticky top-0 mx-auto flex flex-wrap gap-1.5 bg-background py-5`,u),children:[(0,K.jsx)(MH,{label:`Search templates`,placeholder:`Search templates`,size:`sm`,value:o,onValueChange:s}),(0,K.jsxs)(Bk,{value:t,onValueChange:i,children:[(0,K.jsx)(Hk,{"aria-label":`Search by tag`,size:`sm`,className:`w-auto`,children:(0,K.jsx)(Vk,{placeholder:`Select an option`})}),(0,K.jsx)(Uk,{children:e.map(e=>(0,K.jsx)(Wk,{value:e.value,children:e.label},e.value))})]}),(0,K.jsxs)(Bk,{value:r,onValueChange:a,children:[(0,K.jsx)(Hk,{"aria-label":`Search by provider`,size:`sm`,className:`w-auto`,children:(0,K.jsx)(Vk,{placeholder:`Select an option`})}),(0,K.jsx)(Uk,{children:n.map(e=>(0,K.jsx)(Wk,{value:e.value,children:e.label},e.value))})]}),l&&(0,K.jsx)(J4,{onClick:l})]})}var IPi=[{id:`templates`,label:`Templates`}];function LPi(){let{data:e,isLoading:t}=xPi(),{templates:n,tags:r,providers:i}=e??{templates:[],tags:[],providers:[]},[a,o]=(0,G.useState)(`all`),[s,l]=(0,G.useState)(`all`),[u,d]=(0,G.useState)(``),f=[{value:`all`,label:`Any tag`}];(r||[]).forEach(e=>{f.push({value:e,label:e})});let p=[{value:`all`,label:`Any provider`}];(i||[]).forEach(e=>{p.push({value:e,label:e})});let m=(e,t)=>{t===`tag`?o(e):t===`provider`&&l(e)},h=e=>{d(e)},g=()=>{o(`all`),l(`all`),d(``)},_=n.filter(e=>!(u&&!e.title.toLowerCase().includes(u)&&!e.description.toLowerCase().includes(u)||a!==`all`&&!e.tags.includes(a)||s!==`all`&&!e.supportedProviders.includes(s))),v=u||a!==`all`||s!==`all`;return(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:IPi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Templates`}),(0,K.jsx)(wS,{children:(0,K.jsxs)(nJe,{children:[(0,K.jsx)(Dx,{children:(0,K.jsx)(OZ,{})}),`Templates`]})}),(0,K.jsxs)(`div`,{className:c(`z-10 h-full w-full overflow-y-auto px-5 pb-12`),children:[(0,K.jsx)(FPi,{selectedTag:a,onTagChange:e=>m(e,`tag`),tagOptions:f,selectedProvider:s,onProviderChange:e=>m(e,`provider`),providerOptions:p,searchTerm:u,onSearchChange:h,onReset:v?g:void 0,className:`max-w-[80rem]`,isLoading:t}),(0,K.jsx)(PPi,{templates:_,linkComponent:Lv,className:`mx-auto max-w-[80rem]`,isLoading:t})]})]})}var RPi=U(`IconEmojiSad`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`circle`,{cx:`12`,cy:`12`,r:`9`,stroke:`currentColor`,strokeWidth:`2`}),(0,K.jsx)(`path`,{d:`M10.75 9.9C10.75 11.0046 10.0784 11.75 9.25 11.75C8.42157 11.75 7.75 11.0046 7.75 9.9C7.75 8.79543 8.42157 8 9.25 8C10.0784 8 10.75 8.79543 10.75 9.9Z`,fill:`currentColor`}),(0,K.jsx)(`path`,{d:`M16.25 9.9C16.25 11.0046 15.5784 11.75 14.75 11.75C13.9216 11.75 13.25 11.0046 13.25 9.9C13.25 8.79543 13.9216 8 14.75 8C15.5784 8 16.25 8.79543 16.25 9.9Z`,fill:`currentColor`}),(0,K.jsx)(`path`,{d:`M7.89328 15.4758C7.7698 15.623 7.69925 15.8109 7.70417 16.0051C7.70903 16.1992 7.78791 16.3827 7.92489 16.5166C8.06187 16.6504 8.24712 16.7251 8.44131 16.7254C8.63557 16.7259 8.82181 16.651 8.9661 16.5242C9.05273 16.4499 9.14033 16.3801 9.23093 16.313C10.042 15.7109 11.0211 15.4001 12.0034 15.4C12.9856 15.3986 13.964 15.7081 14.7725 16.3111C14.8628 16.3783 14.9501 16.4481 15.0364 16.5226C15.1803 16.6498 15.3663 16.7253 15.5606 16.7254C15.7548 16.7256 15.9403 16.6515 16.0776 16.5181C16.215 16.3846 16.2944 16.2014 16.2999 16.0073C16.3054 15.8131 16.2354 15.625 16.1124 15.4774C16.0126 15.3603 15.909 15.2487 15.799 15.1403C14.816 14.1611 13.4082 13.5927 12.002 13.6C10.5957 13.595 9.19111 14.1644 8.20718 15.1399C8.09708 15.2479 7.99334 15.3591 7.89328 15.4758Z`,fill:`currentColor`})]}));function zPi({children:e,className:t}){return(0,K.jsx)(`div`,{className:c(`transition-height mt-12 rounded-lg border border-border px-4 py-5 lg:min-h-[25rem] lg:px-12`,t),children:e})}function BPi({errorMsg:e,validationErrors:t}){let n=typeof e==`string`?e:e==null?void 0:String(e),r=n?.includes(`Invalid schema for function`),i=n?.includes(`validation issue`)||t&&t.length>0,a=()=>i?`Template installation completed but some validation issues remain. The template may still be functional, but you should review and fix these issues.`:r?`There was an issue with the AI model configuration. This may be related to the selected model or AI SDK version compatibility.`:`An unexpected error occurred during template installation.`,{icon:o,title:s}=i?{icon:(0,K.jsx)(Zx,{className:`text-warning-foreground`}),title:`Template Installed with Warnings`}:{icon:(0,K.jsx)(RPi,{}),title:`Template Installation Failed`};return(0,K.jsxs)(zPi,{className:`mb-5 content-center space-y-4 text-muted-foreground`,children:[(0,K.jsxs)(`div`,{className:`grid content-center items-center justify-items-center gap-4 [&>svg]:h-8 [&>svg]:w-8`,children:[o,(0,K.jsxs)(`div`,{className:`space-y-2 text-center`,children:[(0,K.jsx)(T,{variant:`subheading`,tone:`ink`,children:s}),(0,K.jsx)(T,{tone:`muted`,children:a()})]})]}),t&&t.length>0&&(0,K.jsxs)(`details`,{children:[(0,K.jsx)(`summary`,{className:c(`text-muted-foreground hover:text-foreground`,`cursor-pointer text-center select-none`),children:(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[`Show Validation Issues (`,t.length,`)`]})}),(0,K.jsx)(`div`,{className:`mt-4 max-h-60 space-y-2 overflow-auto rounded bg-muted p-3 text-left`,children:t.map((e,t)=>(0,K.jsxs)(`div`,{className:`border-l-2 border-destructive-indicator pl-2`,children:[(0,K.jsx)(T,{as:`p`,variant:`column`,className:`text-destructive-foreground`,children:e.type===`typescript`?`🔴 TypeScript Error`:`⚠️ Lint Error`}),(0,K.jsx)(uC,{className:`mt-1 text-caption wrap-break-word whitespace-pre-wrap text-muted-foreground`,code:e.message})]},t))})]}),n&&!i&&(0,K.jsxs)(`details`,{children:[(0,K.jsx)(`summary`,{className:c(`text-muted-foreground hover:text-foreground`,`cursor-pointer text-center select-none`),children:(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`block`,children:`Show Details`})}),(0,K.jsx)(`div`,{className:`mt-4 max-h-60 overflow-auto rounded bg-muted p-3 text-left`,children:(0,K.jsx)(uC,{className:`text-caption wrap-break-word whitespace-pre-wrap`,code:n})})]})]})}function VPi({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:i,handleInstallTemplate:a,handleVariableChange:o,isLoadingEnvVars:s,isInstalling:l,defaultModelProvider:u,defaultModelId:d,onModelUpdate:f}){return(0,K.jsx)(zPi,{children:(0,K.jsxs)(`div`,{className:`mx-auto my-4 grid max-w-[40rem] gap-5 p-4 lg:p-5`,children:[(0,K.jsxs)(T,{as:`h2`,variant:`heading`,tone:`muted`,className:c(`flex items-center gap-2`,`[&_svg]:h-[1.2em] [&_svg]:opacity-70 [&>svg]:w-[1.2em]`),children:[`Install Template `,(0,K.jsx)(OZ,{})]}),(0,K.jsxs)(ak,{orientation:`horizontal`,children:[(0,K.jsx)(sk,{children:`Template AI Model Provider`}),(0,K.jsx)(Tpt,{className:`flex-1`,children:(0,K.jsxs)(Bk,{name:`template-provider`,value:t,onValueChange:n,children:[(0,K.jsx)(Hk,{size:`md`,children:(0,K.jsx)(Vk,{placeholder:`Select`})}),(0,K.jsx)(Uk,{children:e.map(e=>(0,K.jsx)(Wk,{value:e.value,children:e.label},e.value))})]})})]}),t&&Object.entries(r||{}).length>0&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h3`,tone:`muted`,children:`Set required Environmental Variables`}),(0,K.jsx)(`div`,{className:`grid grid-cols-[1fr_1fr] items-start gap-4`,children:s?(0,K.jsxs)(`div`,{className:c(`text-muted-foreground`,`col-span-2 flex items-center justify-center gap-4`,`[&_svg]:h-[1.1em] [&_svg]:w-[1.1em] [&_svg]:opacity-50`,`animate-in duration-300 fade-in`),children:[(0,K.jsx)(It,{}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[` `,`Loading variables...`]})]}):Object.entries(r).map(([e,t])=>(0,K.jsxs)(G.Fragment,{children:[(0,K.jsxs)(ak,{className:`w-full`,children:[(0,K.jsx)(sk,{className:`sr-only`,children:`Key`}),(0,K.jsx)(Jj,{name:`env-${e}`,value:e,disabled:!0,className:`w-full`})]}),(0,K.jsxs)(ak,{invalid:i.includes(e),className:`w-full`,children:[(0,K.jsx)(sk,{className:`sr-only`,children:`Value`}),(0,K.jsx)(Jj,{name:e,value:t,onChange:o,autoComplete:`off`,className:`w-full`}),(0,K.jsx)(lk,{children:i.includes(e)?`Value is required.`:void 0})]})]},e))}),(0,K.jsxs)(`div`,{className:`relative mt-3.5 border-t border-border pt-12`,children:[(0,K.jsx)(`div`,{className:`absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full bg-background`,children:(0,K.jsx)(T,{tone:`muted`,as:`span`,variant:`caption`,className:`block`,children:`And`})}),(0,K.jsx)(T,{as:`h3`,tone:`muted`,children:`Set AI Model for Template Installation`}),(0,K.jsx)(T,{tone:`muted`,className:`mt-2 mb-5`,children:`This model will be used by the workflow to process and install the template`}),(0,K.jsx)(E1r,{defaultProvider:u||``,defaultModel:d||``,updateModel:f||(()=>Promise.resolve({message:`Updated`})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:`Provider`})]})]}),t&&!s&&(0,K.jsx)(X,{className:c(`mt-4 flex min-h-10 w-full items-center justify-center gap-2 rounded-lg bg-card state-layer text-foreground`,`[&_svg]:h-[1.1em] [&_svg]:text-foreground [&>svg]:w-[1.1em]`),onClick:a,disabled:!t||!u||!d||i.length>0||l,children:l?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(It,{className:`h-4 w-4`}),` Installing...`]}):(0,K.jsxs)(K.Fragment,{children:[`Install `,(0,K.jsx)(oH,{})]})})]})})}function HPi({title:e,description:t,githubUrl:n,isLoading:r,infoData:i,templateSlug:a}){let o=a?`feat/install-template-${a}`:`feat/install-template-[slug]`;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`mt-5 grid items-center`,children:(0,K.jsxs)(`div`,{className:c(`flex items-center gap-3`,`[&>svg]:h-[1.2em] [&>svg]:w-[1.2em] [&>svg]:opacity-50`,{"[&>svg]:opacity-20":r}),children:[(0,K.jsx)(OZ,{}),(0,K.jsx)(`h2`,{className:c({"flex min-w-[50%] rounded-lg bg-muted":r}),children:(0,K.jsx)(T,{as:`span`,variant:`title`,className:`block`,children:r?(0,K.jsx)(K.Fragment,{children:`\xA0`}):e})})]})}),(0,K.jsxs)(`div`,{className:`grid gap-x-24 lg:grid-cols-[1fr_1fr]`,children:[(0,K.jsxs)(`div`,{className:`grid`,children:[(0,K.jsx)(T,{tone:`muted`,className:c(`mt-2 mb-4`,{"rounded-lg bg-muted":r}),children:r?(0,K.jsx)(K.Fragment,{children:`\xA0`}):t}),!r&&a&&(0,K.jsxs)(`div`,{className:c(`mb-4 rounded-lg border border-border bg-background p-4`,`flex items-start gap-3`),children:[(0,K.jsx)(`div`,{className:`mt-0.5 shrink-0`,children:(0,K.jsx)(Yx,{className:`h-[1.1em] w-[1.1em] text-info-indicator`})}),(0,K.jsxs)(`div`,{className:`flex-1 space-y-2`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(KS,{className:`h-[1em] w-[1em] text-muted-foreground`}),(0,K.jsx)(T,{as:`span`,variant:`subheading`,tone:`ink`,children:`A new Git branch will be created`})]}),(0,K.jsxs)(`div`,{className:`space-y-1`,children:[(0,K.jsxs)(T,{tone:`muted`,as:`p`,variant:`caption`,children:[(0,K.jsx)(T,{as:`span`,variant:`column`,children:`Branch name:`}),` `,(0,K.jsx)(uX,{children:o})]}),(0,K.jsx)(T,{tone:`muted`,as:`p`,variant:`caption`,children:`This ensures safe installation with easy rollback if needed. Your main branch remains unchanged.`})]})]})]}),n&&(0,K.jsxs)(`a`,{href:n,target:`_blank`,rel:`noopener noreferrer`,className:c(`text-muted-foreground hover:text-foreground`,`mt-auto flex items-center gap-2`),children:[(0,K.jsx)(kZ,{}),(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:n?.split(`/`)?.pop()})]})]}),i&&(0,K.jsx)(A1r,{data:i,labelsAreHidden:!0,isLoading:r})]})]})}function UPi(e){switch(e){case`running`:return(0,K.jsx)(It,{size:`sm`,"aria-hidden":!0});case`success`:return(0,K.jsx)(pC,{"aria-hidden":!0});case`failed`:return(0,K.jsx)(xw,{"aria-hidden":!0});default:return null}}function WPi(){return(0,K.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`text-placeholder`,"aria-hidden":!0,children:(0,K.jsx)(`circle`,{cx:`12`,cy:`12`,r:`8.5`,pathLength:`48`,fill:`none`,stroke:`currentcolor`,strokeWidth:`2.8`,strokeLinecap:`round`,strokeDasharray:`3 3`})})}function GPi({status:e,variant:t}){return t===`plain`?(0,K.jsx)(`span`,{className:c(`flex size-icon-md items-center justify-center self-center [&>svg]:size-icon-md`,u.colors,{"[&>svg]:text-success-indicator":e===`success`,"[&>svg]:text-destructive-foreground":e===`failed`}),children:e===`pending`?(0,K.jsx)(WPi,{}):UPi(e)}):(0,K.jsx)(`span`,{className:c(`flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none`,u.colors,u.transform,{"[&>svg]:text-success-indicator":e===`success`,"[&>svg]:text-destructive-foreground":e===`failed`,"border border-dashed border-placeholder":e===`pending`,"[&>svg]:size-icon-md":e!==`running`,"bg-success-subtle":e===`success`,"bg-destructive-subtle":e===`failed`,"scale-110":e===`success`||e===`failed`}),children:UPi(e)})}function KPi({step:e,isActive:t,position:n,variant:r=`default`}){let i=t||e.status===`success`?`ink`:`muted`;return(0,K.jsxs)(`div`,{className:c(`grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none`,u.colors,{"border border-transparent":r==="default","border-dashed border-placeholder bg-card":t&&r==="default"}),children:[(0,K.jsxs)(`div`,{className:`grid min-w-0 grid-cols-[auto_1fr] gap-2`,children:[(0,K.jsxs)(T,{as:`span`,tone:i,className:c(`flex min-w-6 justify-end`,u.colors),children:[n,`.`]}),(0,K.jsxs)(`div`,{className:`min-w-0`,children:[(0,K.jsx)(T,{as:`h4`,tone:i,className:u.colors,children:e.title}),e.description&&(0,K.jsx)(T,{tone:`faint`,className:c(`-mt-0.5`,{truncate:r===`plain`}),children:e.description})]})]}),(0,K.jsx)(GPi,{status:e.status,variant:r})]})}function qPi({currentStep:e,steps:t=[],className:n}){return(0,K.jsx)(`div`,{className:c(n),children:t.map((t,n)=>(0,K.jsx)(KPi,{step:t,isActive:e?.id===t.id,position:n+1},t.id))})}function JPi({steps:e}){let t=e.length,n=e.filter(e=>e.status===`success`).length;return(0,K.jsxs)(`div`,{className:`flex w-full flex-col content-center justify-center gap-4`,children:[(0,K.jsx)(`div`,{className:`grid w-full grid-cols-[0_repeat(9,1fr)]`,children:e.map((t,n)=>(0,K.jsx)(`div`,{className:c(`relative flex h-8 items-center justify-end`,u.colors,{"bg-success-subtle":t.status===`success`&&e?.[n-1]?.status===`success`}),children:(0,K.jsx)(`div`,{className:c(`absolute right-0 z-10 flex size-8 translate-x-1/2 items-center justify-center self-center rounded-full bg-fill text-column text-muted-foreground motion-reduce:transition-none`,u.colors,u.transform,{"border border-dashed border-placeholder":t.status===`pending`,"scale-110 bg-success-subtle text-success-subtle-foreground":t.status===`success`,"scale-110 bg-destructive-subtle text-destructive-subtle-foreground":t.status===`failed`}),children:t.status===`running`?(0,K.jsx)(It,{}):n+1})},t.id))}),(0,K.jsxs)(`div`,{className:c(`text-center text-caption text-muted-foreground`,u.colors),children:[n,` of `,t,` steps completed`]})]})}var YPi=(0,G.createContext)(3);function XPi({title:e,description:t,action:n,done:r,className:i,children:a}){let o=(0,G.useContext)(YPi);return(0,K.jsxs)(`li`,{className:c(`group/step grid grid-cols-[1.5rem_minmax(0,1fr)] gap-x-4 [counter-increment:ds-step]`,i),children:[(0,K.jsxs)(`div`,{className:`flex flex-col items-center`,children:[(0,K.jsx)(`span`,{className:c(`flex size-6 shrink-0 items-center justify-center rounded-full`,u.colors,r?`bg-success-indicator/18 text-success-indicator`:`bg-fill text-foreground`),children:r?(0,K.jsx)(pC,{className:`size-icon-sm`,"aria-label":`Done`}):(0,K.jsx)(T,{as:`span`,variant:`column`,className:`before:content-[counter(ds-step)]`,"aria-hidden":!0})}),(0,K.jsx)(`span`,{"aria-hidden":!0,className:`w-px flex-1 bg-border group-last/step:hidden`})]}),(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-3 pb-8 group-last/step:pb-0`,children:[(0,K.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,K.jsxs)(`div`,{className:`flex min-h-6 flex-wrap items-center justify-between gap-x-6 gap-y-2`,children:[(0,K.jsx)(T,{as:o===2?`h2`:`h3`,variant:`label`,className:`text-pretty`,children:e}),n==null?null:(0,K.jsx)(`div`,{className:`flex shrink-0 items-center gap-2`,children:n})]}),t==null?null:(0,K.jsx)(T,{as:`p`,variant:`body-sm`,tone:`muted`,className:`max-w-[70ch] text-pretty`,children:t})]}),a]})]})}function ZPi({headingLevel:e=3,className:t,children:n}){return(0,K.jsx)(YPi.Provider,{value:e,children:(0,K.jsx)(`ol`,{className:c(`flex flex-col [counter-reset:ds-step]`,t),children:n})})}Object.assign(ZPi,{Step:XPi});function QPi({name:e,streamResult:t,runId:n,workflowInfo:r}){let i=t?.phase||`initializing`,a=t?.payload?.workflowState,o=t?.payload?.currentStep,s=t?.error,l=a?.steps||{},u=Object.keys(l).length>0,d=e=>e===`input`||e.endsWith(`.input`)||e.startsWith(`Mapping_`)&&/[0-9a-f]{8}/.test(e)||/[0-9a-f]{8,}/.test(e)?!1:!r?.allSteps||e in r.allSteps,f=Object.entries(l).filter(([e,t])=>d(e)),p=f.length,m=()=>{switch(i){case`initializing`:return`Preparing template installation...`;case`processing`:return`Installing ${e} template`;case`completed`:return`Template installation completed!`;case`error`:return`Template installation failed`;default:return`Installing template...`}},h=f.map(([e,t])=>({id:e,status:t?.status,description:t?.description,title:e.charAt(0).toUpperCase()+e.slice(1).replace(/-/g,` `),isActive:o?.id===e}));return(0,K.jsxs)(zPi,{className:`mb-5 content-center space-y-6 text-muted-foreground`,children:[(0,K.jsxs)(`div`,{className:`text-center`,children:[(0,K.jsx)(T,{as:`h3`,variant:`heading`,tone:`ink`,children:m()}),(t?.runId||n)&&(0,K.jsxs)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`mt-2`,children:[`Run ID: `,t?.runId??n]})]}),u&&p>0&&![`error`].includes(i)&&(0,K.jsx)(`div`,{className:`mx-auto w-full max-w-[30rem] px-4`,children:(0,K.jsx)(JPi,{steps:h})}),s&&i===`error`&&(0,K.jsxs)(`div`,{className:c(`text-foreground`,`flex items-center gap-3 rounded-lg bg-destructive-subtle p-4`,`[&>svg]:h-6 [&>svg]:w-6 [&>svg]:text-destructive-foreground [&>svg]:opacity-70`),children:[(0,K.jsx)(qx,{}),(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:s||`Something went wrong`})]}),u&&(0,K.jsx)(qPi,{steps:h,currentStep:o,className:`pb-4`}),!u&&i===`initializing`&&(0,K.jsxs)(`div`,{className:c(`text-muted-foreground`,`grid justify-items-center gap-4 text-center`),children:[(0,K.jsx)(It,{}),(0,K.jsx)(T,{as:`p`,variant:`body`,children:`This may take some time...`})]})]})}function $Pi({name:e,installedEntities:t}){return(0,K.jsxs)(zPi,{className:c(`grid content-center items-center justify-items-center gap-4`,`[&>svg]:h-8 [&>svg]:w-8`),children:[(0,K.jsx)(OZ,{}),(0,K.jsx)(T,{as:`h2`,variant:`heading`,children:`Done!`}),(0,K.jsxs)(T,{tone:`muted`,className:`text-center`,children:[`The `,(0,K.jsx)(`b`,{className:`text-muted-foreground`,children:e}),` template has been successfully installed.`,t&&t.length>0&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`br`,{}),` Installed entities are listed below.`]})]}),t&&t.length>0&&(0,K.jsx)(A1r,{data:t})]})}function eFi(){let{templateSlug:e}=kv(),t=[{id:`templates`,label:`Templates`,to:`/templates`},{id:`template`,label:Zjt(e)}],[n,r]=Rv(),[i,a]=(0,G.useState)(``),[o,s]=(0,G.useState)(``),[l,u]=(0,G.useState)(``),[d,f]=(0,G.useState)({}),[p,m]=(0,G.useState)([]),[h,g]=(0,G.useState)(null),[_,v]=(0,G.useState)(!1),[y,b]=(0,G.useState)(``),[x,S]=(0,G.useState)(!1),[C,w]=(0,G.useState)(!1),[T,E]=(0,G.useState)([]),{data:D,isLoading:O}=SPi({repoOrSlug:e,owner:`mastra-ai`}),k=`1.85.0-alpha.0`.includes(`beta`)??!1?`beta`:`main`,{data:A,isLoading:j}=CPi({repo:D?.githubUrl?new URL(D.githubUrl).pathname.split(`/`)[2]:`template-${e}`,owner:`mastra-ai`,branch:k}),{data:M,isLoading:N}=wPi(),{mutateAsync:P,isPending:F}=TPi(),{mutateAsync:I}=EPi(),{streamInstall:L,streamResult:R,isStreaming:z}=jPi({workflowInfo:M}),{observeInstall:B,streamResult:V,isStreaming:H}=MPi({workflowInfo:M});(0,G.useEffect)(()=>{let e=n.get(`runId`);!e||_||h||z||H||(console.info(`🔄 Checking completed run after hot reload:`,{runId:e}),b(e),I({runId:e}).then(e=>{let t=e.snapshot;if(t?.status===`success`&&t?.result?.success)v(!0);else if(t?.result?.success===!1){if(t?.result?.validationResults&&!t?.result?.validationResults?.valid&&t?.result?.validationResults?.remainingErrors>0){let{remainingErrors:e,errors:n}=t.result.validationResults,r=`Template installation completed but ${e} validation issue${e>1?`s`:``} remain unresolved.`;g(r),E(n||[])}else{let e=t?.result?.message||t?.result?.error||`Template installation failed`;g(typeof e==`string`?e:String(e))}}}).catch(e=>{console.error(`❌ Failed to fetch run details:`,e),g(`Failed to retrieve installation status after reload`)}))},[n,_,h,z,H,I]),(0,G.useEffect)(()=>{let e=n.get(`runId`),t=n.get(`resume`),i=n.get(`provider`);if(e&&t===`true`&&i&&!z&&!H&&!x&&!C&&M){b(e),S(!0);try{I({runId:e}).then(t=>{if(t.snapshot?.status===`running`)return B.mutateAsync({runId:e})}).then(()=>{r(e=>{let t=new URLSearchParams(e);return t.delete(`resume`),t})}).catch(e=>{console.error(`❌ Failed to resume template installation:`,e),e.message?.includes(`404`)||e.message?.includes(`not found`)?g(`Template installation run not found. It may have expired or been completed.`):g(`Failed to resume template installation. Please try again.`)})}catch(e){console.error(`❌ Auto-resume failed with error:`,e),g(`Failed to resume template installation. Please refresh and try again.`)}}},[n,e,z,H,x,C,M,I,B,r]);let ee=[{value:`openai`,label:`OpenAI`},{value:`anthropic`,label:`Anthropic`},{value:`groq`,label:`Groq`},{value:`google`,label:`Google`}],te=[{key:`tools`,label:`Tools`,value:D?.tools?.length?D.tools.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(XN,{})},{key:`agents`,label:`Agents`,value:D?.agents?.length?D.agents.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(HN,{})},{key:`workflows`,label:`Workflows`,value:D?.workflows?.length?D.workflows.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(ZS,{})},{key:`providers`,label:`Providers`,value:D?.supportedProviders?.length?D.supportedProviders.join(`, `):`n/a`,icon:(0,K.jsx)(k3,{})},{key:`tags`,label:`Tags`,value:D?.tags?.length?D.tags.join(`, `):`n/a`,icon:(0,K.jsx)(wX,{})}],U=[{...te[0]},{...te[1]},{...te[2]}].filter(e=>e.value!==`n/a`);return(0,G.useEffect)(()=>{A&&f(A)},[A]),(0,G.useEffect)(()=>{let e=R||V;e?.phase===`error`&&e?.error&&g(typeof e.error==`string`?e.error:String(e.error))},[R?.phase,R?.error,V?.phase,V?.error]),(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(`div`,{className:c(`h-full w-full overflow-y-scroll lg:px-12`),children:(0,K.jsxs)(`div`,{className:`mx-auto grid w-full max-w-[80rem] gap-y-4 p-4`,children:[(0,K.jsx)(HPi,{isLoading:O,title:D?.title,description:D?.longDescription,imageURL:D?.imageURL,githubUrl:D?.githubUrl,infoData:te,templateSlug:e}),D&&(0,K.jsxs)(K.Fragment,{children:[(z||H)&&(0,K.jsx)(QPi,{name:D.title,streamResult:H?V:R,runId:y,workflowInfo:M}),_&&(0,K.jsx)($Pi,{name:D.title,installedEntities:U,linkComponent:Lv}),h&&(0,K.jsx)(BPi,{errorMsg:h,validationErrors:T.length>0?T:R?.validationResults?.errors||V?.validationResults?.errors}),!z&&!H&&!_&&!h&&(0,K.jsx)(VPi,{providerOptions:ee,selectedProvider:i,onProviderChange:e=>{a(e)},variables:d,setVariables:f,errors:p,setErrors:m,handleInstallTemplate:async()=>{let e=Object.entries(d).reduce((e,[t,n])=>(n===``&&e.push(t),e),[]);if(e.length>0)m(e);else if(D){g(null),v(!1),b(``),w(!0);try{let e={repo:D.githubUrl||`https://github.com/mastra-ai/template-${D.slug}`,ref:k,slug:D.slug,variables:d},{runId:t}=await P({});b(t),r(e=>{let n=new URLSearchParams(e);return n.set(`runId`,t),n.set(`resume`,`true`),n.set(`provider`,i||`openai`),n}),await L.mutateAsync({inputData:e,selectedModel:{provider:o,modelId:l},runId:t})}catch(e){w(!1),g(e?.message||`Template installation failed`),console.error(`Template installation failed`,e)}}},handleVariableChange:e=>{let{name:t,value:n}=e.target;n.trim()===``?m(e=>[...e,t]):m(e=>e.filter(e=>e!==t)),f(e=>({...e,[t]:n}))},isLoadingEnvVars:j||N,isInstalling:F,defaultModelProvider:o,defaultModelId:l,onModelUpdate:async e=>(s(e.provider),u(e.modelId),{message:`Model updated successfully`})})]})]})})]})}var tFi=e=>e.threadId;function nFi(e,t){return`traces`in e?{traces:{...e.traces,to:t}}:{threads:{...e.threads,to:t}}}var rFi=e=>`traces`in e?e.traces:e.threads;function iFi(e){let{field:t=`endedAt`,direction:n=`desc`}=e?.[0]??{},r=n===`asc`?1:-1;return(e,n)=>{let i=e[t],a=n[t];if(i!==a){if(i==null)return 1;if(a==null)return-1;if(i<a)return-r;if(i>a)return r}return e.threadId.localeCompare(n.threadId)}}function aFi({query:e,rolling:t,autoRefetch:n=!0,limit:r,enabled:i=!0}){let a=Y(),{anchorTo:o,reanchor:s}=WNi(e),c=(0,G.useMemo)(()=>o?{...e,timeRange:nFi(e.timeRange,o)}:e,[e,o]),l=iXr({query:c,limit:r,enabled:i,queryOptions:BNi}),{headRows:u}=KNi({queryKey:[`threads`,e],fetchHead:async t=>(await a.queryTraceThreads({...e,timeRange:nFi(e.timeRange,t),orderBy:[{field:`endedAt`,direction:`desc`}],page:{limit:50}})).threads,getId:tFi,getEndedAt:e=>e.endedAt,since:Date.parse(rFi(c.timeRange).to),enabled:i&&t&&n&&l.threads!==void 0&&!l.isFetching&&!l.isError,onOverflow:s}),{orderBy:d}=e,f=l.threads,p=(0,G.useMemo)(()=>f&&JNi(f,u,{getId:tFi,compare:iFi(d),hasNextPage:l.hasNextPage}),[f,u,d,l.hasNextPage]);return{...l,threads:p}}function oFi(e){return{traceId:e.lastTraceId,name:e.entityName??e.threadId,entityType:e.entityType,entityId:e.entityId,entityName:e.entityName,threadId:e.threadId,resourceId:e.resourceId,environment:e.environment,status:e.status,inputPreview:e.inputPreview,outputPreview:e.outputPreview??void 0,errorPreview:e.errorPreview??void 0,startedAt:e.startedAt,endedAt:e.endedAt,traceCount:e.traceCount,timeToFirstChunkMs:e.timeToFirstChunkMs,timeToFirstTokenMs:e.timeToFirstTokenMs,createdAt:e.startedAt}}var sFi=[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`],cFi=[];function lFi(){let{data:e}=i5(),t=e?.capabilities.traceQueryTimeToFirstChunk??!1,n=e?.capabilities.traceQueryTimeToFirstToken??!1,{data:r=cFi}=t8(),{data:i=cFi}=n8();return(0,G.useMemo)(()=>[d3r,...Pai({withTimeToFirstChunk:t,withTimeToFirstToken:n,entityNames:r,environments:i})],[t,n,r,i])}function uFi({tokens:e,groups:t,onFiltersChange:n}){let r=(0,G.useMemo)(()=>P8(e),[e]),i=(0,G.useMemo)(()=>{let e=F8([],t);return{...e,nodes:[p5,...r,...e.nodes]}},[r,t]),a=(0,G.useCallback)(e=>{let t=UZr({...e,nodes:e.nodes.filter(e=>H6(e)||e.fieldId!==`timeRange`)});n(t.tokens,t.groups)},[n]);return{filterBarValue:i,onFilterBarChange:a,onFilterByField:(0,G.useCallback)((e,t)=>{let n=r.filter(t=>t.fieldId!==e),o={id:`${e}:${t}`,fieldId:e,operatorId:`is`,value:t},s=i.nodes.filter(H6);a({...i,nodes:[...n,o,...s]})},[r,i,a])}}var dFi=e=>e;function fFi({datePreset:e,dateFrom:t,dateTo:n,minDate:r,tokens:i,groups:a,onDatePresetChange:o,onDateChange:s,onDateRangeChange:c,onFiltersChange:l,disabled:u}){let d=lFi(),{filterBarValue:f,onFilterBarChange:p}=uFi({tokens:i,groups:a,onFiltersChange:l});return(0,K.jsxs)(m5,{fields:d,operators:gZr,value:f,onValueChange:p,createItemId:dFi,maxDepth:3,"aria-label":`Thread filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(m5.Chips,{renderChip:i=>i.fieldId===`timeRange`?(0,K.jsx)(m5.TimeRange,{preset:e,onPresetChange:o,dateFrom:t,dateTo:n,minDate:r,onDateChange:s,onDateRangeChange:c,disabled:u,presets:sFi,defaultPreset:o5.datePreset}):(0,K.jsx)(m5.Chip,{item:i})}),(0,K.jsx)(m5.Input,{placeholder:`Filter threads`})]})}function pFi({selectedThreadId:e,onSelectedThreadChange:t,onOpenScore:n,urlState:r}){let i=HNi(r),{timeRange:a,tokens:o,groups:s,sort:c}=i,l=a5().enabled,u=u2r().enabled,d=oii({scope:`threads`}),{data:f,isLoading:p}=i5(),m=f?.capabilities.traceQueryTimeToFirstChunk??!1,h=f?.capabilities.traceQueryTimeToFirstToken??!1,g=(0,G.useMemo)(()=>p?d.preferences:T0r(d.preferences,{withTimeToFirstChunk:m,withTimeToFirstToken:h}),[d.preferences,p,m,h]),{threads:_,hasNextPage:v,isFetchingNextPage:y,setEndOfListElement:b,isLoading:x,isError:S,error:C}=aFi({query:(0,G.useMemo)(()=>{let e=Lai(o,s,{withTimeToFirstChunk:m,withTimeToFirstToken:h});return{timeRange:{traces:a},orderBy:[{field:`startedAt`,direction:c.direction}],...e?{where:e}:{}}},[a,c,o,s,m,h]),rolling:i.rolling}),w=(0,G.useMemo)(()=>(_??[]).map(oFi),[_]),T=w.find(t=>t.threadId===e),E=e=>{e.threadId&&t(e.threadId)},D=!x&&!S&&w.length===0&&!i.contentFiltersApplied&&!e;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Threads`}),(0,K.jsx)(Y0r,{toolbar:(0,K.jsxs)(K.Fragment,{children:[r&&(0,K.jsx)(Loi,{page:`threads`,...r,columns:d}),(0,K.jsxs)(TK,{children:[(0,K.jsx)(TK.Start,{children:(0,K.jsx)(fFi,{datePreset:i.datePreset,dateFrom:i.dateFrom,dateTo:i.dateTo,tokens:o,groups:s,onDatePresetChange:i.onDatePresetChange,onDateChange:i.onDateChange,onDateRangeChange:i.onDateRangeChange,onFiltersChange:i.onFiltersChange,disabled:x})}),(0,K.jsx)(TK.End,{children:(0,K.jsx)(p2r,{scope:`threads`,value:d.preferences,onChange:d.setPreferences})})]})]}),error:S?(0,K.jsx)(Q8,{error:C,resource:`threads`,errorTitle:`Failed to load threads`}):void 0,empty:D?(0,K.jsx)(r0r,{resource:`threads`,datePreset:i.datePreset,dateFrom:i.dateFrom,dateTo:i.dateTo}):void 0,children:(0,K.jsx)(_7r,{listId:`all-threads`,columnPreferences:g,outcomeColumn:!1,traces:w,isLoading:x,isFetchingNextPage:y,hasNextPage:v,setEndOfListElement:b,filtersApplied:i.filtersApplied,resource:`threads`,sort:c,onSortChange:e=>i.setSort({field:`startedAt`,direction:e.direction}),featuredTraceId:T?.traceId,onTraceClick:E})}),(0,K.jsx)(Gri,{open:!!e,threadId:e??``,depth:1,closeLabel:`Close`,withQueryTrace:l,withFeedback:u,onOpenScore:n,onClose:()=>t(void 0)})]})}function mFi(){let{enabled:e,isLoading:t}=i2r(),n=Ov(),[r,i]=Rv();return(0,K.jsx)(zNi,{enabled:e,isLoading:t,heading:`Threads`,title:`Query threads capability not activated`,description:`Your observability storage does not support thread row queries. Switch to a store that declares the thread-query-rows capability to list threads.`,children:(0,K.jsx)(pFi,{urlState:{searchParams:r,setSearchParams:i},selectedThreadId:ePi(r),onSelectedThreadChange:e=>i(t=>tPi(t,e),{replace:!0}),onOpenScore:(e,t)=>n(CK(e,t))})})}var hFi=()=>(0,K.jsx)(Jx,{titleSlot:`No Workflows yet`,descriptionSlot:(0,K.jsxs)(K.Fragment,{children:[`Mastra workflows are not configured yet. `,(0,K.jsx)(`br`,{}),`More information in the documentation.`]}),actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/docs/workflows/overview`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(tP,{}),children:`Workflows documentation`}),variant:`fill`});function gFi(e,t,n){return IZ(e,t,{name:e=>e.name,running:e=>n[e.id]?.running??0,suspended:e=>n[e.id]?.suspended??0,steps:e=>Object.keys(e.steps??{}).length})}function _Fi(e){return Object.keys(e.steps??{}).filter(t=>e.allSteps?.[t]?.isWorkflow)}function vFi(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,n),r.name&&t.set(r.name,n);return t}function yFi(e,t,n){let r=vFi(t),i=[],a=(e,o,s,c,l,u)=>{let d=_Fi(e).filter(e=>{let t=r.get(e);return t===void 0||!c.has(t)});if(i.push({kind:`workflow`,workflow:e,pathKey:o,depth:s,nestedIds:d,guides:l,isLastChild:u}),!n.has(o)||d.length===0)return;let f=new Set(c).add(e.id),p=s===0?[]:[...l,!u];for(let[n,c]of d.entries()){let l=n===d.length-1,u=r.get(c);if(u===void 0){i.push({kind:`unregistered`,stepId:c,description:e.allSteps?.[c]?.description,pathKey:`${o}/${c}`,depth:s+1,guides:p,isLastChild:l});continue}let m=t[u];m&&a({...m,id:u},`${o}/${u}`,s+1,f,p,l)}};for(let t of e)a(t,t.id,0,new Set([t.id]),[],!1);return i}var bFi=`auto 24rem minmax(0, 1fr) auto auto auto`;function xFi({guides:e,isLastChild:t}){return(0,K.jsxs)(`span`,{"aria-hidden":!0,className:`-my-6 flex shrink-0 self-stretch`,children:[e.map((e,t)=>(0,K.jsx)(`span`,{className:c(`w-6`,e&&`border-l border-border`)},t)),(0,K.jsxs)(`span`,{className:`relative w-6`,children:[(0,K.jsx)(`span`,{className:c(`absolute top-0 left-0 border-l border-border`,t?`h-1/2`:`h-full`)}),(0,K.jsx)(`span`,{className:`absolute top-1/2 left-0 w-3.5 border-b border-border`})]})]})}function SFi({row:e,isExpanded:t,onToggle:n}){let r=e.kind===`workflow`&&e.nestedIds.length>0,i=e.kind===`workflow`?e.workflow.name:e.stepId;return(0,K.jsx)(`div`,{className:`flex items-center pl-5`,children:r?(0,K.jsx)(`button`,{type:`button`,"aria-expanded":t,"aria-label":`${t?`Collapse`:`Expand`} nested workflows of ${i}`,className:c(SS,`relative grid size-5 shrink-0 place-items-center before:absolute before:-inset-1.5 before:content-['']`),onClick:e=>{e.stopPropagation(),n()},children:(0,K.jsx)(y,{direction:`right`,className:`size-4`})}):(0,K.jsx)(`span`,{className:`size-5 shrink-0`,"aria-hidden":!0})})}var CFi=e=>e.stopPropagation();function wFi({sortKey:e,sort:t,onSortChange:n,children:r}){return n?(0,K.jsx)(Z.SortableTopCell,{sortKey:e,sort:t?.key===e?t.direction:void 0,onSortChange:t=>n(t,e),children:r}):(0,K.jsx)(Z.TopCell,{children:r})}function TFi({row:e,isExpanded:t,onToggle:n,runCount:r,rowProps:i}){let{paths:a,Link:o}=sn(),s=(0,G.useRef)(null),{workflow:c,nestedIds:l}=e,u=dJ(c.name,50),d=dJ(c.description??``,200),f=Object.keys(c.steps??{}).length,p=r?.running??0,m=r?.suspended??0,h=l.length>0;return(0,K.jsxs)(Z.RowWrapper,{...i,onSelectRow:()=>s.current?.click(),children:[(0,K.jsx)(SFi,{row:e,isExpanded:t,onToggle:n}),(0,K.jsxs)(Z.RowLink,{ref:s,colStart:2,to:a.workflowLink(c.id),LinkComponent:o,tabIndex:-1,onClick:CFi,children:[(0,K.jsx)(Z.NameCell,{children:(0,K.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[e.depth>0?(0,K.jsx)(xFi,{guides:e.guides,isLastChild:e.isLastChild}):null,(0,K.jsx)(`span`,{className:`truncate`,children:u}),c.origin===`dynamic`?(0,K.jsx)(eC,{size:`xs`,variant:`blue`,title:`Registered via the dynamic-workflows API`,children:`Dynamic`}):null,h?(0,K.jsxs)(T,{as:`span`,variant:`body-sm`,tone:`muted`,title:`Nested workflows: ${l.join(`, `)}`,className:`inline-flex shrink-0 items-center gap-1`,children:[(0,K.jsx)(ZS,{"aria-hidden":!0,className:`size-icon-sm`}),l.length]}):null]})}),(0,K.jsx)(Z.DescriptionCell,{children:d}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:p>0?(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-info-indicator`,"aria-label":`${p} run${p===1?``:`s`} in progress`,children:[(0,K.jsx)(`span`,{"aria-hidden":!0,className:`size-2 rounded-full bg-info-indicator motion-safe:animate-pulse`}),p]}):``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:m>0?(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-warning-foreground`,"aria-label":`${m} run${m===1?``:`s`} awaiting input`,children:[(0,K.jsx)(ET,{"aria-hidden":!0,className:`size-icon-sm`}),m]}):``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:f||``})]})]})}function EFi({workflows:e,isLoading:t,search:n=``,sort:r,onSortChange:i,requestContext:a}){let[o,s]=(0,G.useState)(new Set),l=wEt({requestContext:a}),u=(0,G.useMemo)(()=>Object.entries(e).map(([e,t])=>({...t,id:e})),[e]),d=(0,G.useMemo)(()=>{let e=n.toLowerCase();return u.filter(t=>t.name?.toLowerCase().includes(e)||t.description?.toLowerCase().includes(e))},[u,n]),f=(0,G.useMemo)(()=>gFi(d,r,l),[d,r,l]),m=(0,G.useMemo)(()=>yFi(f,e,o),[f,e,o]),h=(0,G.useMemo)(()=>{let e=new Map;for(let t of m)t.kind===`workflow`&&e.set(t.pathKey,e.size);return e},[m]),{containerRef:g,getRowProps:_}=PZ({count:h.size,global:!0}),v=e=>{s(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})};return t?(0,K.jsx)(DH,{columns:bFi,fit:`container`}):(0,K.jsxs)(Z,{columns:bFi,fit:`container`,scrollRef:g,children:[(0,K.jsxs)(Z.Top,{children:[(0,K.jsx)(Z.TopCell,{children:(0,K.jsx)(`span`,{className:`sr-only`,children:`Expand`})}),(0,K.jsx)(wFi,{sortKey:`name`,sort:r,onSortChange:i,children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`Description`}),(0,K.jsx)(wFi,{sortKey:`running`,sort:r,onSortChange:i,children:`Running`}),(0,K.jsx)(wFi,{sortKey:`suspended`,sort:r,onSortChange:i,children:`Pending input`}),(0,K.jsx)(wFi,{sortKey:`steps`,sort:r,onSortChange:i,children:`Number of steps`})]}),m.length===0&&n?(0,K.jsx)(Z.NoMatch,{message:`No Workflows match your search`}):null,m.map(e=>{let t=o.has(e.pathKey),n=()=>v(e.pathKey);return e.kind===`unregistered`?(0,K.jsxs)(Z.RowStatic,{className:`gap-0 px-0`,children:[(0,K.jsx)(SFi,{row:e,isExpanded:t,onToggle:n}),(0,K.jsxs)(`div`,{className:`col-span-5 col-start-2 grid grid-cols-subgrid gap-4 px-3`,children:[(0,K.jsx)(Z.NameCell,{children:(0,K.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,K.jsx)(xFi,{guides:e.guides,isLastChild:e.isLastChild}),(0,K.jsx)(`span`,{className:`truncate`,children:dJ(e.stepId,50)}),(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{render:(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`muted`}),role:`note`,tabIndex:0,className:c(`shrink-0 rounded-sm`,p),children:`not registered`}),(0,K.jsx)(Tx,{className:`max-w-72`,children:`Runs as a step of its parent workflow. Add it to the workflows of your Mastra instance to open, run, and inspect it on its own page.`})]})]})}),(0,K.jsx)(Z.DescriptionCell,{children:dJ(e.description??``,200)}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:``})]})]},`workflow-${e.pathKey}`):(0,K.jsx)(TFi,{row:e,isExpanded:t,onToggle:n,runCount:l[e.workflow.id],rowProps:_(h.get(e.pathKey)??-1)},`workflow-${e.pathKey}`)})]})}var K9=[eP(`/workflows`)];function DFi(){let{data:e,isLoading:t,error:n}=eN(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)();return n&&FN(n)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:K9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(TH,{variant:`fill`})]}):n&&IN(n)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:K9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(wH,{variant:`fill`,resource:`workflows`})]}):n?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:K9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load workflows`,descriptionSlot:n.message})]}):Object.keys(e||{}).length===0&&!t?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:K9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(hFi,{})]}):(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:K9}),actionRow:(0,K.jsxs)(TK,{children:[(0,K.jsx)(TK.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(MH,{...NH,onValueChange:i,label:`Search workflows`,placeholder:`Search by name or description`})})}),(0,K.jsx)(TK.End,{children:(0,K.jsx)(X,{render:(0,K.jsx)(Lv,{to:`/workflows/schedules`}),variant:`primary`,icon:(0,K.jsx)(qS,{}),children:`Schedules`})})]}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(EFi,{workflows:e||{},isLoading:t,search:r,sort:a,onSortChange:(e,t)=>o({key:t,direction:e})})]})}var OFi={active:`bg-success-indicator`,paused:`bg-info-indicator`,completed:`bg-muted-foreground`},kFi={active:`text-success-indicator`,paused:`text-info-indicator`,completed:`text-muted-foreground`},AFi=({status:e})=>(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-2 whitespace-nowrap`,children:[(0,K.jsx)(`span`,{className:`h-1.5 w-1.5 rounded-full ${OFi[e]}`,"aria-hidden":!0}),(0,K.jsx)(T,{as:`span`,variant:`caption`,className:kFi[e],children:e})]});function jFi({status:e}){let{icon:t,color:n}=MFi(e);return(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 whitespace-nowrap ${n}`,children:[(0,K.jsx)(`span`,{className:`inline-flex shrink-0 items-center`,"aria-hidden":!0,children:t}),(0,K.jsx)(T,{as:`span`,variant:`caption`,children:e})]})}function MFi(e){switch(e){case`success`:return{icon:(0,K.jsx)(pC,{className:`size-icon-sm`}),color:`text-success-indicator`};case`failed`:return{icon:(0,K.jsx)(xw,{className:`size-icon-sm`}),color:`text-destructive-foreground`};case`running`:return{icon:(0,K.jsx)(It,{}),color:`text-muted-foreground`};case`suspended`:return{icon:(0,K.jsx)(ET,{className:`size-icon-sm`}),color:`text-info-indicator`};case`canceled`:return{icon:(0,K.jsx)(Kx,{className:`size-icon-sm`}),color:`text-muted-foreground`};case`pending`:case`waiting`:return{icon:(0,K.jsx)(tC,{className:`size-icon-sm`}),color:`text-muted-foreground`};default:return{icon:null,color:`text-muted-foreground`}}}var NFi=`auto auto auto auto 1fr`,PFi=3e4,FFi=3e5;function IFi({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:i,setEndOfListElement:a}){let{Link:o,paths:s}=sn(),c=e=>!!(n&&e.runId&&e.outcome!==`failed`),l=e.filter(c).length,{containerRef:u,getRowProps:d}=PZ({count:l}),f=-1;return t?(0,K.jsx)(DH,{columns:NFi}):e.length===0?(0,K.jsx)(T,{variant:`body`,tone:`muted`,className:`p-4`,children:`No trigger history yet.`}):(0,K.jsxs)(Z,{columns:NFi,className:`min-w-0`,scrollRef:u,children:[(0,K.jsxs)(Z.Top,{children:[(0,K.jsx)(Z.TopCell,{children:`Run`}),(0,K.jsx)(Z.TopCell,{children:`Status`}),(0,K.jsx)(Z.TopCell,{children:`Started`}),(0,K.jsx)(Z.TopCell,{children:`Duration`}),(0,K.jsx)(Z.TopCell,{children:` `})]}),e.map(e=>{let t=e.actualFireAt-e.scheduledFireAt,r=iC(t,{signed:!0}),i=e.outcome===`failed`,a=i?e.error:e.run?.error,l=Math.abs(t),u=!i&&l>PFi&&l<=FFi,p=`${e.scheduleId}-${e.runId}-${e.actualFireAt}`,m=c(e);m&&(f+=1);let h=(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,tone:m?`ink`:`muted`,className:`whitespace-nowrap`,children:e.runId}),g=(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Z.Cell,{children:h}),(0,K.jsx)(Z.Cell,{children:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[i?(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`inline-flex items-center gap-1.5 whitespace-nowrap text-destructive-foreground`,children:[(0,K.jsx)(Zx,{className:`size-icon-sm`}),`publish failed`]}):e.run?(0,K.jsx)(jFi,{status:e.run.status}):(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`inline-flex items-center gap-1.5 whitespace-nowrap`,children:`pending`}),a?(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{asChild:!0,children:(0,K.jsx)(`span`,{className:`inline-flex text-destructive-foreground`,children:(0,K.jsx)(Zx,{className:`size-icon-sm`})})}),(0,K.jsx)(Tx,{children:a})]}):null]})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-2 whitespace-nowrap`,children:[e.actualFireAt?(0,K.jsx)(Dk,{value:e.actualFireAt}):`—`,u?(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{asChild:!0,children:(0,K.jsx)(`span`,{className:`inline-flex text-info-indicator`,children:(0,K.jsx)(Zx,{className:`size-icon-sm`})})}),(0,K.jsxs)(Tx,{children:[`Published `,r,` after the scheduled fire time`]})]}):null]})}),(0,K.jsx)(Z.Cell,{children:e.run?(0,K.jsx)(T,{as:`span`,variant:`body-sm`,font:`mono`,children:iC(e.run.durationMs)||`—`}):(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`—`})}),(0,K.jsx)(Z.Cell,{children:` `})]});return m?(0,K.jsx)(Z.RowLink,{to:s.workflowRunLink(n,e.runId),LinkComponent:o,...d(f),children:g},p):(0,K.jsx)(Z.RowStatic,{children:g},p)}),(0,K.jsx)(Z.NextPageLoading,{isLoading:i,hasMore:r,setEndOfListElement:a})]})}var LFi={id:`workflow-schedules`,label:`Schedules`,icon:qS,to:`/workflows/schedules`};function RFi({label:e,children:t}){return(0,K.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,K.jsx)(T,{variant:`meta`,tone:`muted`,className:`uppercase`,children:e}),(0,K.jsx)(`div`,{children:(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:t})})]})}function zFi(){let{scheduleId:e}=kv(),t=[eP(`/workflows`),LFi,{id:`schedule`,label:Zjt(e),icon:qS}],{paths:n}=sn(),{data:r,error:i}=vMt({scheduleId:e,queryOptions:{enabled:!!e}}),{data:a,isLoading:o,error:s,hasNextPage:c,isFetchingNextPage:l,setEndOfListElement:u}=xMt({scheduleId:e,queryOptions:{enabled:!!e}}),d=SMt({scheduleId:e});if(i&&FN(i))return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(TH,{variant:`fill`})]});if(i&&IN(i))return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(wH,{variant:`fill`,resource:`schedules`})]});if(i)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load schedule`,descriptionSlot:i.message})]});let f=r?.workflowId,p=r?.agentId;return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:t}),actionRow:(0,K.jsx)(TK,{children:(0,K.jsxs)(TK.End,{children:[(0,K.jsx)(X,{render:(0,K.jsx)(Lv,{to:n.schedulesLink()}),variant:`ghost`,icon:(0,K.jsx)(sS,{}),children:`Back to schedules`}),f?(0,K.jsx)(X,{icon:(0,K.jsx)(ZS,{}),render:(0,K.jsx)(Lv,{to:n.workflowLink(f)}),variant:`ghost`,children:`Open workflow`}):null,r&&r.status!==`completed`?(0,K.jsx)(X,{onClick:()=>{let e=r.status===`active`?`pause`:`resume`;d.mutate(e,{onSuccess:()=>iS.success(e===`pause`?`Schedule paused`:`Schedule resumed`),onError:e=>iS.error(e.message)})},disabled:d.isPending,"data-testid":`schedule-toggle-button`,children:r.status===`active`?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(ET,{}),`Pause`]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(DT,{}),`Resume`]})}):null]})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),r?(0,K.jsxs)(`div`,{className:`grid h-full grid-cols-[minmax(0,20rem)_1fr] gap-4 overflow-hidden`,children:[(0,K.jsxs)(`div`,{className:`flex h-fit flex-col gap-4 rounded-md border border-border p-4`,children:[(0,K.jsx)(RFi,{label:p?`Agent`:`Workflow`,children:f?(0,K.jsx)(Lv,{to:n.workflowLink(f),className:`text-foreground hover:underline`,children:f}):p?(0,K.jsx)(Lv,{to:n.agentLink(p),className:`text-foreground hover:underline`,children:p}):`—`}),(0,K.jsxs)(RFi,{label:r.cron?`Cron`:`Runs at`,children:[(0,K.jsx)(T,{as:`span`,variant:`body`,font:`mono`,children:r.cron??(r.runAt?new Date(r.runAt).toLocaleString():`—`)}),r.endAt?(0,K.jsxs)(`span`,{className:`ml-2 text-caption text-muted-foreground`,children:[`until `,new Date(r.endAt).toLocaleString()]}):null,r.timezone?(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`ml-2`,children:r.timezone}):null]}),(0,K.jsx)(RFi,{label:`Status`,children:(0,K.jsx)(AFi,{status:r.status})}),(0,K.jsx)(RFi,{label:`Next fire`,children:r.nextFireAt?(0,K.jsx)(Dk,{value:r.nextFireAt}):`—`})]}),(0,K.jsxs)(`div`,{className:`overflow-y-auto`,"data-testid":`schedule-triggers-panel`,children:[(0,K.jsx)(T,{variant:`body`,className:`mb-3`,children:`Trigger history`}),s?(0,K.jsx)(Jx,{tone:`error`,titleSlot:`Failed to load trigger history`,descriptionSlot:s.message}):(0,K.jsx)(IFi,{triggers:a??[],isLoading:o,workflowId:f,hasNextPage:c,isFetchingNextPage:l,setEndOfListElement:u})]})]}):null]})}var BFi={target:e=>e.workflowId??e.agentId??``,status:e=>e.status,nextFireAt:e=>e.nextFireAt,lastFireAt:e=>e.lastFireAt},VFi=`minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto`;function HFi({schedules:e,isLoading:t,search:n=``,sort:r,onSortChange:i}){let{paths:a,Link:o}=sn(),s=(0,G.useMemo)(()=>{let t=n.toLowerCase();return IZ(t?e.filter(e=>e.id.toLowerCase().includes(t)||(e.workflowId??e.agentId??``).toLowerCase().includes(t)):e,r,BFi)},[e,n,r]),{containerRef:c,getRowProps:l}=PZ({count:s.length,global:!0});if(t)return(0,K.jsx)(DH,{columns:VFi});let u=(e,t)=>i?(0,K.jsx)(Z.SortableTopCell,{sortKey:e,sort:r?.key===e?r.direction:void 0,onSortChange:i,children:t}):(0,K.jsx)(Z.TopCell,{children:t});return(0,K.jsxs)(Z,{columns:VFi,className:`min-w-0`,scrollRef:c,children:[(0,K.jsxs)(Z.Top,{children:[u(`target`,`Target`),(0,K.jsx)(Z.TopCell,{children:`Schedule ID`}),(0,K.jsx)(Z.TopCell,{children:`Cron`}),u(`status`,`Status`),u(`nextFireAt`,`Next fire`),u(`lastFireAt`,`Last run`)]}),s.length===0&&n?(0,K.jsx)(Z.NoMatch,{message:`No schedules match your search`}):null,s.length===0&&!n?(0,K.jsx)(Z.NoMatch,{message:`No schedules configured`}):null,s.map((e,t)=>(0,K.jsxs)(Z.RowLink,{to:a.scheduleLink(e.id),LinkComponent:o,...l(t),children:[(0,K.jsx)(Z.NameCell,{children:e.workflowId??e.agentId}),(0,K.jsx)(Z.Cell,{className:`min-w-0`,children:(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`muted`,font:`mono`,className:`block truncate`,title:e.id,children:e.id})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-2 whitespace-nowrap`,children:[(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,children:e.cron??(e.runAt?`once @ ${new Date(e.runAt).toLocaleString()}`:`—`)}),e.timezone?(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:e.timezone}):null]})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(AFi,{status:e.status})}),(0,K.jsx)(Z.Cell,{children:e.nextFireAt?(0,K.jsx)(Dk,{value:e.nextFireAt}):`—`}),(0,K.jsx)(Z.Cell,{children:e.lastRun?(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-2 whitespace-nowrap`,children:[(0,K.jsx)(jFi,{status:e.lastRun.status}),e.lastFireAt?(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:(0,K.jsx)(Dk,{value:e.lastFireAt})}):null]}):e.lastFireAt?(0,K.jsx)(Dk,{value:e.lastFireAt}):(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`Never`})})]},e.id))]})}function UFi({workflowId:e}={}){let{data:t,isLoading:n,error:r}=yMt(e?{workflowId:e}:{}),[i,a]=(0,G.useState)(``),[o,s]=(0,G.useState)();return r?(0,K.jsx)(Jx,{tone:`error`,titleSlot:`Failed to load schedules`,descriptionSlot:r.message}):(0,K.jsxs)(`div`,{className:`grid h-full grid-rows-[auto_1fr] gap-4 overflow-hidden`,children:[(0,K.jsx)(`div`,{className:`max-w-120`,children:(0,K.jsx)(MH,{...NH,onValueChange:a,label:`Search schedules`,placeholder:`Search by id or workflow`})}),(0,K.jsx)(`div`,{className:`overflow-y-auto`,children:(0,K.jsx)(HFi,{schedules:t??[],isLoading:n,search:i,sort:o,onSortChange:(e,t)=>s({key:t,direction:e})})})]})}var WFi=[eP(`/workflows`),LFi];function GFi(){let[e]=Rv(),t=e.get(`workflowId`)??void 0,{error:n}=yMt(t?{workflowId:t}:{});return n&&FN(n)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:WFi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(TH,{variant:`fill`})]}):n&&IN(n)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:WFi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(wH,{variant:`fill`,resource:`schedules`})]}):(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:WFi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(`div`,{className:`h-full`,children:(0,K.jsx)(UFi,{workflowId:t})})]})}var KFi=U(`IconArrowDownLeft`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M6 9V18H15`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M17.75 6.25L7 17`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),3),qFi={"--belt-hue":`var(--warning-indicator)`};function JFi(e){let t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function YFi(e,t){if(e&&typeof e==`object`&&!Array.isArray(e)){let t=Object.keys(e),[n]=t;if(t.length===1&&n)return n}return t}function XFi({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:(0,K.jsxs)(`section`,{className:c(REt,`pointer-events-auto relative isolate`),"data-testid":`workflow-suspended-steps`,"aria-label":`Step suspended`,children:[(0,K.jsxs)(`div`,{className:`max-h-[calc(100cqh-64px)] overflow-y-auto overscroll-contain rounded-[inherit]`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-3 border-b border-border bg-background px-5 py-4`,children:[(0,K.jsxs)(T,{as:`h2`,variant:`column`,tone:`ink`,className:`flex items-center gap-2`,children:[(0,K.jsx)(Dx,{children:(0,K.jsx)(ET,{})}),`Step suspended`]}),(0,K.jsx)(eC,{variant:`orange`,emphasis:`subtle`,children:`Needs input`})]}),e.map(e=>{let n=t.allSteps[e.stepId];if(!n||n.isWorkflow)return null;let i=n?.resumeSchema?zO(nk(n.resumeSchema)):Ad(q(),md());return(0,K.jsx)(ZFi,{step:e,stepSchema:i,description:n.description,onResume:r},`${e.runId}-${e.stepId}`)})]}),(0,K.jsx)(kXe,{status:`ready`,label:`Needs input`,className:`before:hidden`,style:qFi})]})}function ZFi({step:e,stepSchema:t,description:n,onResume:r}){let[i,a]=(0,G.useState)(!1),[o,s]=(0,G.useState)(!1);return(0,K.jsxs)(`div`,{className:`space-y-5 p-5 [&+&]:border-t [&+&]:border-border`,children:[(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(T,{as:`p`,variant:`subheading`,tone:`ink`,className:`break-words`,children:e.stepId}),n&&(0,K.jsx)(T,{as:`p`,variant:`caption`,tone:`muted`,children:n})]}),e.suspendPayload!==void 0&&(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsxs)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`flex items-center gap-2`,children:[(0,K.jsx)(Dx,{children:(0,K.jsx)(KFi,{})}),`The step is asking`]}),(0,K.jsxs)(DC,{open:i,onOpenChange:a,children:[(0,K.jsxs)(OC,{className:c(`bg-card hover:bg-card active:bg-card shadow-raised [--field:var(--field-on-surface)] [--field-disabled:var(--field-on-surface)] [--field-rim:var(--field-rim-on-surface)]`,`flex w-full items-center justify-between gap-2 rounded-lg px-3 py-2.5`),children:[(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(Dx,{children:(0,K.jsx)(y,{direction:`right`,className:`text-muted-foreground`})}),(0,K.jsx)(T,{as:`span`,variant:`body`,tone:`ink`,className:`truncate`,children:YFi(e.suspendPayload,e.stepId)})]}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`shrink-0`,children:JFi(e.suspendPayload)})]}),(0,K.jsx)(kC,{children:(0,K.jsx)(`div`,{"data-testid":`suspended-payload`,className:`pt-2`,children:(0,K.jsx)(bw,{value:JSON.stringify(e.suspendPayload,null,2),editable:!1,className:`w-full overflow-x-auto p-2`,showCopyButton:!1})})})]})]}),(0,K.jsxs)(`div`,{className:`space-y-3`,children:[(0,K.jsxs)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`flex items-center gap-2`,children:[(0,K.jsx)(Dx,{children:(0,K.jsx)(R4,{})}),`Your response`]}),(0,K.jsx)(`div`,{className:`-mx-5`,children:(0,K.jsx)(eEt,{schema:t,isSubmitLoading:o,submitButtonLabel:`Resume`,submitButtonVariant:`primary`,submitButtonIcon:(0,K.jsx)(DT,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:async t=>{s(!0);try{await r({stepId:e.stepId.split(`.`),runId:e.runId,resumeData:t})}catch(e){iS.error(e instanceof Error?e.message:`Error resuming workflow`)}finally{s(!1)}}})})]})]})}function QFi({hidden:e,requestContext:t,canResume:n}){let{result:r,workflow:i,runId:a,isStreamingWorkflow:o}=(0,G.useContext)(WS),s=Gft(r,a),c=Xft(t),l=r?.status===`suspended`&&s.length>0&&!o;return!i||!l||!n?null:(0,K.jsx)(`div`,{hidden:e,"data-testid":`workflow-suspended-overlay`,className:`pointer-events-none absolute top-12 right-2 z-30 w-95 max-w-[calc(100%-16px)] animate-in duration-300 fade-in-0 slide-in-from-top-2 motion-reduce:animate-none`,children:(0,K.jsx)(XFi,{suspendedSteps:s,workflow:i,isStreaming:o,onResume:c})},a)}var $Fi=U(`IconSkip`,()=>(0,K.jsx)(`path`,{d:`M19 5V19M6.52732 5.16646L15.5625 11.1835C16.1458 11.5719 16.1458 12.4281 15.5625 12.8165L6.52732 18.8335C5.87447 19.2683 5 18.8008 5 18.017V5.98298C5 5.1992 5.87447 4.7317 6.52732 5.16646Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})),eIi={success:{label:`Completed`,icon:pC},failed:{label:`Failed`,icon:qx},suspended:{label:`Needs input`,icon:ET},waiting:{label:`Waiting`,icon:XS},paused:{label:`Paused`,icon:ET},skipped:{label:`Skipped`,icon:$Fi},running:{label:`Running`,icon:TT},canceled:{label:`Canceled`,icon:Kx}},tIi={label:`Status unavailable`,icon:Lq};function nIi({row:e,isSelected:t,isHovered:n,onSelectStep:r,onHoverStep:i,onOpenInput:a,onOpenOutput:o}){let s=Object.hasOwn(eIi,e.status)?eIi[e.status]:tIi,l=s.icon,u=Fmt(e.status),d=e.stepId.slice(0,e.stepId.lastIndexOf(`.`)),f=e.isNestedEntry?e.stepId.slice(e.stepId.lastIndexOf(`.`)+1):e.stepId;return(0,K.jsxs)(`div`,{"data-testid":`workflow-timeline-row`,"data-workflow-step-key":e.stepId,onMouseEnter:()=>!e.isNestedEntry&&i(e.stepId),onMouseLeave:()=>!e.isNestedEntry&&i(null),className:c(`grid grid-cols-[minmax(130px,1fr)_minmax(64px,1fr)_56px_64px] items-center gap-3 rounded-md px-2 py-1`,`@max-[540px]/workflow-timeline:grid-cols-[minmax(0,1fr)_48px_64px] @max-[540px]/workflow-timeline:gap-x-1.5 @max-[540px]/workflow-timeline:gap-y-1 @max-[540px]/workflow-timeline:py-2`,(t||n)&&`bg-fill-subtle`),children:[(0,K.jsxs)(`button`,{type:`button`,"aria-disabled":e.isNestedEntry,"aria-pressed":t,onClick:()=>{e.isNestedEntry||r(e.stepId)},title:e.stepId,className:c(`text-foreground`,`flex min-h-9 min-w-0 cursor-pointer items-center gap-2.5 text-left focus-visible:rounded-sm aria-disabled:cursor-default`,p),children:[(0,K.jsx)(`span`,{"aria-label":s.label,className:c(`grid size-6 flex-none place-items-center rounded-md border border-border bg-background`,Imt[u]),children:(0,K.jsx)(l,{"aria-hidden":!0,className:c(`size-3.5`,e.status===`running`&&`motion-safe:animate-spin`)})}),(0,K.jsxs)(`span`,{className:`min-w-0`,children:[(0,K.jsx)(T,{as:`span`,variant:`meta`,className:`block truncate`,children:f}),e.isNestedEntry&&(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`flex min-w-0 items-center gap-1`,children:[(0,K.jsx)(XYe,{"aria-hidden":!0,className:`size-icon-xs shrink-0`}),(0,K.jsx)(`span`,{className:`truncate`,children:d})]})]})]}),(0,K.jsx)(`div`,{className:`relative h-5 min-w-0 overflow-hidden rounded-sm bg-muted @max-[540px]/workflow-timeline:col-span-full @max-[540px]/workflow-timeline:row-start-2 @max-[540px]/workflow-timeline:ml-[34px]`,"aria-hidden":!0,children:e.timing&&(0,K.jsx)(`div`,{"data-testid":`workflow-timeline-bar`,"data-offset":e.timing.offsetPct,"data-width":e.timing.widthPct,className:c(`absolute top-0 h-full min-w-0.5 rounded-sm`,Lmt[u]),style:{left:`${e.timing.offsetPct}%`,width:`${e.timing.widthPct}%`}})}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`text-right whitespace-nowrap`,title:e.timing&&e.spansSuspension?`Includes time spent suspended waiting for input`:void 0,children:e.timing?(0,K.jsx)(T,{as:`span`,variant:`meta`,font:`mono`,children:iC(e.timing.durationMs)}):(0,K.jsx)(`span`,{"aria-label":`Timing unavailable`,children:`—`})}),(0,K.jsxs)(`div`,{className:`flex items-center`,children:[(0,K.jsx)(X,{type:`button`,variant:`ghost`,size:`icon-sm`,tooltip:`View step input`,disabled:e.step.input===void 0,onClick:t=>a(e,t.currentTarget),children:(0,K.jsx)(bk,{})}),(0,K.jsx)(X,{type:`button`,variant:`ghost`,size:`icon-sm`,tooltip:`View step output`,disabled:e.step.output===void 0,onClick:t=>o(e,t.currentTarget),children:(0,K.jsx)(yk,{})})]})]})}var rIi=e=>e.includes(`.`),iIi=e=>e===`input`||e.endsWith(`.input`),aIi=1;function oIi(e,t){let n=Bmt(e),r=n?.isLive?Math.max(t,n.start):n?.end;return{span:n&&r!==void 0?{start:n.start,end:r}:void 0,isLive:n?.isLive??!1,spansSuspension:n?.spansSuspension??!1}}function sIi(e,t){let n=Object.entries(e).filter(([e])=>!iIi(e)).map(([e,n])=>({stepId:e,step:n,...oIi(n,t)})).sort((e,t)=>(e.span?.start??1/0)-(t.span?.start??1/0)||e.stepId.localeCompare(t.stepId)),r=n.flatMap(e=>e.span?[e.span]:[]),i=Math.min(...r.map(e=>e.start)),a=Math.max(i,...r.map(e=>e.end)),o=Math.max(a-i,1);return n.map(({stepId:e,step:t,span:n,isLive:r,spansSuspension:a})=>{let s;if(n){let e=n.end-n.start,t=Math.min((n.start-i)/o*100,99);s={durationMs:e,offsetPct:t,widthPct:Math.min(Math.max(e/o*100,aIi),100-t)}}return{stepId:e,step:t,status:wk(t)?`suspended`:t.status,timing:s,spansSuspension:a,isRunning:r,isNestedEntry:rIi(e)}})}var cIi=U(`IconChevronGrabberVertical`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M8 8.99985L11.2929 5.70696C11.6834 5.31643 12.3166 5.31643 12.7071 5.70696L16 8.99985`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M8 15L11.2929 18.2929C11.6834 18.6834 12.3166 18.6834 12.7071 18.2929L16 15`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]})),lIi=U(`IconChevronGrabberVerticalToward`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M8 18.75L12 14.75L16 18.75`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M8 5.25L12 9.25L16 5.25`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}));function uIi(){let{steps:e}=e$(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:i}=US(),[a,o]=(0,G.useState)(()=>Date.now()),[s,l]=(0,G.useState)(!0),[u,d]=(0,G.useState)(!1),{showData:f}=nN(),p=(0,G.useRef)(null),m=sIi(e,a),h=m.some(e=>e.isRunning);return iJe(p,{enabled:h&&!s}),(0,G.useEffect)(()=>{if(!h||s)return;let e=setInterval(()=>o(Date.now()),100);return()=>clearInterval(e)},[h,s]),m.length===0?null:(0,K.jsx)(`div`,{"data-testid":`workflow-timeline`,className:`relative z-20 shrink-0 px-2 pb-2`,children:(0,K.jsxs)(DC,{open:!s,onOpenChange:e=>l(!e),className:c(Bv,`@container/workflow-timeline pointer-events-auto overflow-hidden rounded-xl`),children:[(0,K.jsxs)(`div`,{className:`flex items-center`,children:[(0,K.jsxs)(OC,{className:`flex min-h-11 min-w-0 flex-1 items-center gap-2 px-3.5 py-2.5 text-caption text-foreground hover:bg-fill-subtle`,"aria-label":s?`Expand timeline`:`Collapse timeline`,children:[(0,K.jsx)(`span`,{children:(0,K.jsx)(YV,{"aria-hidden":!0,className:`size-icon-md text-muted-foreground`})}),(0,K.jsx)(`span`,{children:`Timeline`}),(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,children:[m.length,` events`]}),(0,K.jsx)(`span`,{className:`ml-auto`,children:(0,K.jsx)(y,{direction:`right`,className:`size-4`})})]}),!s&&(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:u?`Restore timeline height`:`Enlarge timeline`,"aria-pressed":u,onClick:()=>d(!u),className:`mr-2 shrink-0`,children:u?(0,K.jsx)(lIi,{}):(0,K.jsx)(cIi,{})})]}),(0,K.jsx)(kC,{children:(0,K.jsx)(`div`,{ref:p,"data-testid":`workflow-timeline-list`,className:c(`overflow-auto overscroll-contain px-1.5 pb-1.5`,u?`max-h-[min(720px,calc(100dvh-112px))]`:`max-h-[min(320px,40dvh)]`),children:m.map(e=>(0,K.jsx)(nIi,{row:e,isSelected:t===e.stepId,isHovered:n===e.stepId,onSelectStep:r,onHoverStep:i,onOpenInput:(e,t)=>f({type:`step-input`,stepId:e.stepId},t),onOpenOutput:(e,t)=>f({type:`step-output`,stepId:e.stepId},t)},e.stepId))})})]})})}var dIi=({workflowId:e,workflow:t,isLoading:n})=>{let[r]=HS(`workflow`,e),{canExecute:i,isLoading:a}=fS(),{stepDetail:o}=nN(),s=Zw(),c=o?.type===`data`,l=(0,K.jsxs)(`div`,{className:`[container-type:size] relative h-full min-h-0`,children:[(0,K.jsx)(eur,{workflowId:e,workflow:t,isLoading:n,requestContext:r}),(0,K.jsx)(QFi,{hidden:c,requestContext:r,canResume:!a&&i(`workflows`)}),c&&(0,K.jsx)(`div`,{className:`pointer-events-auto absolute top-12 right-2 z-30 flex max-h-[calc(100cqh-64px)] w-[440px] max-w-[calc(100%-16px)] flex-col`,children:(0,K.jsx)(n$,{requestContext:r})}),(0,K.jsx)(`div`,{className:`pointer-events-none absolute right-0 bottom-0 left-[var(--workflow-left-panel-width,0px)] z-20`,children:(0,K.jsx)(uIi,{})})]});return s&&o&&!c?(0,K.jsx)(`div`,{className:`h-full min-h-0 overflow-hidden`,children:(0,K.jsx)(n$,{requestContext:r})}):(0,K.jsxs)(`div`,{className:`relative h-full min-h-0`,children:[l,(0,K.jsxs)(p6,{className:`pointer-events-none absolute inset-0 z-30 min-h-0 w-full min-w-0 p-2`,children:[(0,K.jsx)(f6,{id:`workflow-graph`,className:`pointer-events-none min-w-0`}),o&&!c&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(m6,{className:`pointer-events-auto`}),(0,K.jsx)(f6,{id:`workflow-step-detail`,minSize:300,maxSize:`60%`,defaultSize:420,className:`min-w-0`,children:(0,K.jsx)(`div`,{className:`pointer-events-auto h-full min-h-0 overflow-hidden rounded-studio-panel border border-border bg-background`,children:(0,K.jsx)(n$,{requestContext:r})})})]})]})]})},fIi=()=>{let{workflowId:e}=kv(),{data:t,isLoading:n,error:r}=tN({workflowId:e,requestContext:HS(`workflow`,e)[0],queryOptions:{enabled:!!e}});return r&&FN(r)?(0,K.jsx)(TH,{variant:`fill`}):r&&IN(r)?(0,K.jsx)(wH,{variant:`fill`,resource:`workflows`}):(0,K.jsx)(dIi,{workflowId:e,workflow:t??void 0,isLoading:n})};function pIi(){let{workflowId:e}=kv(),{error:t}=yMt(e?{workflowId:e}:{});if(!e)return null;let n;return n=t&&FN(t)?(0,K.jsx)(TH,{variant:`fill`}):t&&IN(t)?(0,K.jsx)(wH,{variant:`fill`,resource:`schedules`}):(0,K.jsx)(`div`,{className:`h-full`,children:(0,K.jsx)(UFi,{workflowId:e})}),(0,K.jsxs)(RS,{children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),n]})}function mIi(){let{workflowId:e}=kv();return e?(0,K.jsx)(Csi,{scopedEntityId:e,scopedEntityType:Dp.WORKFLOW_RUN}):null}var hIi=(0,G.createContext)(null);function q9(){let e=(0,G.useContext)(hIi);if(!e)throw Error(`Workspace components must be rendered inside <Workspace.Root>`);return e}var gIi=e=>e?.status;function _Ii(e,t){return FN(e)?`Your session has expired. Sign in again to continue.`:IN(e)?`You don't have permission to access this.`:LN(e)?`This path no longer exists.`:gIi(e)===501?`This workspace does not support this operation.`:t}function vIi({error:e,fallback:t,className:n}){return(0,K.jsx)(Sk,{variant:`destructive`,className:n,children:(0,K.jsx)(Sk.Message,{children:_Ii(e,t)})})}var yIi=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;function bIi(e){let t=yIi.exec(e);return t?{frontmatter:t[1]??``,body:e.slice(t[0].length)}:{frontmatter:null,body:e}}function xIi({content:e}){let{frontmatter:t,body:n}=bIi(e);return(0,K.jsxs)(K.Fragment,{children:[t!==null&&(0,K.jsx)(`div`,{"data-testid":`workspace-frontmatter`,className:`border-b border-border`,children:(0,K.jsx)(pJ,{code:t,lang:`yaml`,overflow:`wrap`,className:`rounded-none border-0 bg-transparent [&_pre]:p-4`})}),(0,K.jsx)(`div`,{className:`p-4`,children:(0,K.jsx)(xY,{children:n})})]})}function SIi(){let{activeFilePath:e}=q9();return e?(0,K.jsx)(T,{as:`span`,variant:`body-sm`,font:`mono`,tone:`muted`,className:`truncate`,"data-testid":`workspace-file-path`,children:e}):null}function CIi({path:e,content:t,mimeType:n}){return WFn(e,n)?(0,K.jsx)(`div`,{className:`flex justify-center p-4`,children:(0,K.jsx)(`img`,{src:`data:${n||`image/png`};base64,${t}`,alt:e.split(`/`).pop(),className:`max-w-full object-contain`})}):GFn(e,n)?(0,K.jsx)(`div`,{className:`flex justify-center p-4`,children:(0,K.jsx)(`video`,{controls:!0,"aria-label":e.split(`/`).pop(),className:`max-w-full`,children:(0,K.jsx)(`source`,{src:`data:${qFn(e,n)};base64,${t}`,type:qFn(e,n)})})}):JFn(e)?(0,K.jsx)(xIi,{content:t}):(0,K.jsx)(pJ,{code:t,lang:uXe(e),overflow:`scroll`,className:`rounded-none border-0 bg-transparent [&_pre]:p-4`})}function wIi({renderPreview:e}){let{workspaceId:t,activeFilePath:n}=q9(),{data:r,isLoading:i,error:a}=lIn({workspaceId:t,path:n,queryOptions:{enabled:!!n}});if(!n)return null;if(i)return(0,K.jsxs)(`div`,{"aria-busy":`true`,className:`flex flex-col gap-2 p-4`,children:[(0,K.jsx)(zS,{className:`h-4 w-1/2`}),(0,K.jsx)(zS,{className:`h-4 w-5/6`}),(0,K.jsx)(zS,{className:`h-4 w-2/3`})]});if(!r)return(0,K.jsx)(vIi,{error:a,fallback:`Could not load file.`,className:`m-4`});let o={path:n,content:r.content,mimeType:r.mimeType};return e?.(o)??(0,K.jsx)(CIi,{...o})}var TIi=(e,t)=>e===`.`?t:`${e}/${t}`,EIi=e=>e.split(`/`).slice(0,-1).map((e,t,n)=>n.slice(0,t+1).join(`/`)),DIi=e=>{let t=e.lastIndexOf(`/`);return t===-1?`.`:e.slice(0,t)};function OIi({labeled:e=!1}={}){let{workspaceId:t,onCreateDirectory:n,isReadOnly:r}=q9(),i=u_(),[a,o]=(0,G.useState)(!1),[s,c]=(0,G.useState)(``),[l,u]=(0,G.useState)(!1);if(!n||r(`.`))return null;let d=s.trim().replace(/^\.?\/+|\/+$/g,``),f=async()=>{if(d){u(!0);try{await n(d),await i.invalidateQueries({queryKey:[`workspace`,t,`fs`,`list`,DIi(d)]}),o(!1),c(``)}catch{}finally{u(!1)}}};return(0,K.jsxs)(K.Fragment,{children:[e?(0,K.jsx)(X,{variant:`ghost`,icon:(0,K.jsx)(P6,{}),onClick:()=>o(!0),children:`New folder`}):(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`New folder`,onClick:()=>o(!0),children:(0,K.jsx)(P6,{})}),(0,K.jsx)(nT,{open:a,onOpenChange:o,pending:l,children:(0,K.jsx)(rT,{size:`sm`,children:(0,K.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),f()},children:[(0,K.jsx)(iT,{children:(0,K.jsx)(sT,{children:`New folder`})}),(0,K.jsx)(oT,{children:(0,K.jsx)(Jj,{autoFocus:!0,"aria-label":`Folder path`,placeholder:`docs/guides`,value:s,onChange:e=>c(e.target.value)})}),(0,K.jsxs)(aT,{children:[(0,K.jsx)(lT,{children:`Cancel`}),(0,K.jsx)(X,{type:`submit`,variant:`primary`,disabled:!d||l,children:`Create`})]})]})})})]})}function kIi(e){return`${e.topSource}/${e.name}`}function AIi(e){let t=QFn(e.topSource,e.name);return t?`${t.owner}/${t.repo}/${e.name}`:null}function jIi({open:e,onOpenChange:t,workspaceId:n,onInstall:r,isInstalling:i,installedSkillIds:a=[],installedSkillNames:o=[],writableMounts:s,installedSkillPaths:l}){let[u,d]=(0,G.useState)(``),[f,p]=(0,G.useState)(null),[m,h]=(0,G.useState)(),g=s?.some(e=>e.path===m)?m:s?.[0]?.path,{data:_,isLoading:v}=XFn({workspaceId:n,queryOptions:{enabled:!!n}}),y=YFn({workspaceId:n}),b=(0,G.useMemo)(()=>f?.topSource?QFn(f.topSource,f.name):null,[f]),x=(0,G.useMemo)(()=>!b||!f?null:`https://skills.sh/${b.owner}/${b.repo}/${f.name}`,[b,f]),{data:S,isLoading:C}=ZFn({workspaceId:n,owner:b?.owner,repo:b?.repo,skillPath:f?.name,queryOptions:{enabled:!!n&&!!b&&!!f}}),w=cC(e=>{e.trim().length>=2&&y.mutate(e)},300),E=(0,G.useCallback)(e=>{d(e),w(e)},[w]),D=(0,G.useMemo)(()=>u.trim().length>=2?y.data?.skills??[]:_?.skills??[],[u,y.data,_]),O=y.isPending,k=u.trim().length>=2,A=(0,G.useMemo)(()=>{if(!f)return!1;let e=AIi(f);return!!(e&&a.includes(e)||o.includes(f.name))},[f,a,o]),j=(0,G.useCallback)(()=>{f&&b&&r({repository:`${b.owner}/${b.repo}`,skillName:f.name,mount:s&&s.length>1?g:void 0})},[f,b,r,s,g]),M=(0,G.useCallback)(e=>{e||(d(``),p(null),h(void 0)),t(e)},[t]);return(0,K.jsx)(nT,{open:e,onOpenChange:M,pending:i,children:(0,K.jsxs)(rT,{size:`xl`,className:`h-[80vh]`,children:[(0,K.jsxs)(iT,{children:[(0,K.jsx)(sT,{children:`Add Skill`}),(0,K.jsx)(cT,{children:`Search and install skills from the community registry`})]}),(0,K.jsxs)(oT,{layout:`fill`,children:[(0,K.jsx)(MH,{label:`Search skills`,placeholder:`Search skills`,value:u,onValueChange:E}),(0,K.jsxs)(`div`,{className:`flex min-h-0 flex-1 gap-4`,children:[(0,K.jsxs)(`div`,{className:`flex min-h-0 w-1/2 flex-col`,children:[(0,K.jsx)(T,{as:`p`,variant:`eyebrow`,tone:`muted`,className:`mb-2`,children:k?`Search Results`:`Popular Skills`}),(0,K.jsx)(LS,{className:`flex-1 rounded-lg border border-border`,children:(0,K.jsx)(IS,{className:!v&&!O&&D.length===0?`flex flex-col [&>div]:flex [&>div]:flex-1 [&>div]:flex-col`:void 0,children:v||O?(0,K.jsx)(`div`,{className:`flex items-center justify-center py-5`,children:(0,K.jsx)(It,{className:`text-muted-foreground`})}):D.length===0?(0,K.jsx)(Jx,{className:`flex-1`,titleSlot:k?`No skills found`:`No skills available`}):(0,K.jsx)(`div`,{className:`space-y-1 p-2`,children:D.map(e=>{let t=kIi(e),n=AIi(e),r=n&&a.includes(n)||o.includes(e.name),i=f?kIi(f):null;return(0,K.jsx)(`button`,{onClick:()=>p(e),className:c(`w-full rounded-md px-3 py-2 text-left`,`hover:bg-fill-subtle`,i===t&&`border border-border-strong bg-fill-hover`),children:(0,K.jsxs)(`div`,{className:`flex items-start justify-between gap-2`,children:[(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(T,{as:`span`,variant:`subheading`,tone:`ink`,className:`truncate`,children:e.name}),r&&(0,K.jsxs)(T,{as:`span`,variant:`meta`,className:`inline-flex items-center gap-1 rounded bg-info-subtle px-1.5 py-0.5 text-info-subtle-foreground`,children:[(0,K.jsx)(pC,{className:`size-icon-xs`}),`Installed`]})]}),(0,K.jsx)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`truncate`,children:e.topSource})]}),(0,K.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 text-muted-foreground`,children:[(0,K.jsx)(fJ,{className:`size-icon-xs`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,children:e.installs.toLocaleString()})]})]})},t)})})})})]}),(0,K.jsxs)(`div`,{className:`flex min-h-0 w-1/2 flex-col`,children:[(0,K.jsx)(T,{as:`p`,variant:`eyebrow`,tone:`muted`,className:`mb-2`,children:`Preview`}),(0,K.jsx)(`div`,{className:`flex flex-1 flex-col overflow-hidden rounded-lg border border-border`,children:f?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`border-b border-border bg-card p-4`,children:(0,K.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,K.jsx)(`div`,{className:`rounded-lg bg-muted p-2`,children:(0,K.jsx)(AZ,{className:`size-icon-lg text-muted-foreground`})}),(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsx)(T,{as:`h3`,variant:`subheading`,tone:`ink`,className:`truncate`,children:f.name}),(0,K.jsxs)(`div`,{className:`mt-1 flex items-center gap-3 text-muted-foreground`,children:[(0,K.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(kZ,{className:`size-icon-xs`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`block`,children:f.topSource})]}),(0,K.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(fJ,{className:`size-icon-xs`}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[f.installs.toLocaleString(),` installs`]})]})]})]}),b&&(0,K.jsx)(`a`,{href:`https://github.com/${b.owner}/${b.repo}`,target:`_blank`,rel:`noopener noreferrer`,className:c(`text-muted-foreground hover:text-foreground`,`transition-[color] duration-fast ease-out-custom motion-reduce:transition-none`),title:`View on GitHub`,children:(0,K.jsx)(tP,{className:`size-icon-md`})})]})}),C?(0,K.jsx)(`div`,{className:`flex flex-1 items-center justify-center`,children:(0,K.jsx)(It,{className:`text-muted-foreground`})}):S?(0,K.jsx)(LS,{className:`flex-1`,children:(0,K.jsx)(`div`,{className:`p-4`,children:(0,K.jsx)(xY,{children:S})})}):(0,K.jsx)(Jx,{className:`flex-1`,iconSlot:(0,K.jsx)(OZ,{}),titleSlot:`Preview unavailable`,actionSlot:x&&(0,K.jsxs)(`a`,{href:x,target:`_blank`,rel:`noopener noreferrer`,className:`flex items-center gap-1 text-info-indicator hover:underline`,children:[(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[`View on skills.sh`,` `]}),(0,K.jsx)(tP,{className:`size-icon-xs`})]})})]}):(0,K.jsx)(Jx,{variant:`fill`,iconSlot:(0,K.jsx)(OZ,{}),titleSlot:`Select a skill to preview`})})]})]}),f&&s&&s.length>1&&(0,K.jsxs)(ak,{orientation:`horizontal`,className:c(`bg-card hover:bg-card active:bg-card shadow-raised [--field:var(--field-on-surface)] [--field-disabled:var(--field-on-surface)] [--field-rim:var(--field-rim-on-surface)]`,`gap-3 rounded-lg p-3`),children:[(0,K.jsx)($N,{className:`size-icon-md shrink-0 text-muted-foreground`}),(0,K.jsx)(sk,{className:`whitespace-nowrap`,children:`Install to`}),(0,K.jsxs)(Bk,{value:g,onValueChange:h,children:[(0,K.jsx)(Hk,{className:`flex-1`,children:(0,K.jsx)(Vk,{})}),(0,K.jsx)(Uk,{children:s.map(e=>{let t=e.displayName??e.name??e.provider??`unknown`;return(0,K.jsxs)(Wk,{value:e.path,children:[t,` (`,e.path,`)`]},e.path)})})]})]})]}),f&&(0,K.jsxs)(aT,{children:[A&&s&&s.length>1&&(()=>{let e=l?.[f.name];if(!e)return null;let t=s.find(t=>e.startsWith(t.path+`/`)||e===t.path);return t?(0,K.jsxs)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`mr-auto`,children:[`Installed at `,t.path]}):null})(),(0,K.jsx)(lT,{children:`Cancel`}),(0,K.jsx)(tT,{onConfirm:j,disabled:!b||A,"data-testid":`install-skill-button`,children:i?`Installing...`:A?`Already installed`:`Install`})]})]})})}function MIi({labeled:e=!1}){let{workspaceId:t,addSkill:n}=q9(),[r,i]=(0,G.useState)(!1),[a,o]=(0,G.useState)(!1);if(!n)return null;let{onInstall:s,...c}=n,l=async e=>{o(!0);try{await s(e),i(!1)}catch{}finally{o(!1)}};return(0,K.jsxs)(K.Fragment,{children:[e?(0,K.jsxs)(X,{variant:`ghost`,onClick:()=>i(!0),children:[(0,K.jsx)(J5n,{}),`Add skill`]}):(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,"aria-label":`Add skill`,tooltip:`Add skill`,onClick:()=>i(!0),children:(0,K.jsx)(J5n,{})}),(0,K.jsx)(jIi,{...c,open:r,onOpenChange:i,workspaceId:t,onInstall:e=>void l(e),isInstalling:a})]})}function NIi({workspaceId:e,activeFilePath:t,onDelete:n,onCreateDirectory:r,onActiveFileChange:i,readOnlyPaths:a,searchFiles:o=!0,searchSkills:s=!0,fileCount:c,skillCount:l,addSkill:u,children:d}){let[f,p]=(0,G.useState)(!1),[m,h]=(0,G.useState)(``),[g,_]=(0,G.useState)(()=>new Set(EIi(t??``))),[v,y]=(0,G.useState)(t);if(t!==v){y(t);let e=EIi(t??``).filter(e=>!g.has(e));e.length>0&&_(new Set([...g,...e]))}let b=a?.join(`
|
|
724
|
+
`).reduce((e,t)=>{if(!t||t.startsWith(`#`))return e;let[n,r]=t.split(`=`);return n&&(e[n]=r?.split(``)?.every(e=>e===`*`)?``:r?.replaceAll(`"`,``)),e},{}):{}}var xPi=({queryOptions:e}={})=>T_({queryKey:[`mastra-templates`],queryFn:_Pi,...e}),SPi=({repoOrSlug:e,owner:t,queryOptions:n})=>T_({queryKey:[`template-repo`,e,t],queryFn:()=>yPi({repoOrSlug:e,owner:t}),...n}),CPi=({repo:e,owner:t,branch:n,queryOptions:r})=>T_({queryKey:[`template-repo-env-vars`,e,t,n],queryFn:()=>bPi({repo:e,owner:t,branch:n}),...r}),wPi=({queryOptions:e}={})=>{let t=Y();return T_({queryKey:[`agent-builder-workflow`],queryFn:async()=>await t.getAgentBuilderAction(`merge-template`).details(),...e})},TPi=({queryOptions:e}={})=>{let t=Y();return D_({mutationFn:async({runId:e})=>await t.getAgentBuilderAction(`merge-template`).createRun({runId:e}),...e})},EPi=({queryOptions:e}={})=>{let t=Y();return D_({mutationFn:async({runId:e})=>await t.getAgentBuilderAction(`merge-template`).runById(e),...e})},DPi=e=>{if(typeof e==`string`)return e;if(e==null)return`Unknown error`;if(e instanceof Error)return typeof e.message==`string`&&e.message.length>0?e.message:`Unknown error`;if(typeof e==`object`)try{return JSON.stringify(e)}catch{return String(e)}return String(e)},OPi=(e,t,n)=>{let r={...t};if(!(r.payload?.workflowState?.steps&&Object.keys(r.payload.workflowState.steps).length>0)&&n?.allSteps&&(r.payload={...r.payload,workflowState:{...r.payload?.workflowState,steps:Object.keys(n.allSteps).reduce((e,t)=>(e[t]={id:t,description:n.allSteps[t].description,status:`pending`},e),{})}}),e.type===`start`||e.type===`workflow-start`){let t={};n?.allSteps&&Object.entries(n.allSteps).forEach(([e,n])=>{t[e]={id:n.id,description:n.description,status:`pending`}});let i=e.runId||e.payload?.runId;r={...r,runId:i,eventTimestamp:new Date().toISOString(),status:`running`,phase:`initializing`,payload:{workflowState:{status:`running`,steps:t},currentStep:null}}}if(e.type===`step-start`||e.type===`workflow-step-start`){let t=e.payload.id;r={...r,phase:`processing`,payload:{...r.payload,currentStep:{id:t,status:`running`,startTime:new Date,...e.payload},workflowState:{...r.payload.workflowState,steps:{...r.payload.workflowState.steps,[t]:{...r.payload.workflowState.steps[t],status:`running`,startTime:new Date,...e.payload}}}}}}if(e.type===`step-result`||e.type===`workflow-step-result`){let t=e.payload.id,n=e.payload.status,i=e.payload.error;if(r={...r,payload:{...r.payload,currentStep:{...r.payload.currentStep,status:e.payload.status,output:e.payload.output,error:e.payload.error,endTime:new Date},workflowState:{...r.payload.workflowState,steps:{...r.payload.workflowState.steps,[t]:{...r.payload.workflowState.steps[t],status:e.payload.status,output:e.payload.output,error:e.payload.error,endTime:new Date}}}}},n===`failed`&&i){let n=DPi(i);r={...r,status:`failed`,error:n,phase:`error`,failedStep:{id:t,error:n,description:e.payload.description||t},payload:{...r.payload,workflowState:{...r.payload.workflowState,status:`failed`}},errorTimestamp:new Date}}}if((e.type===`step-finish`||e.type===`workflow-step-finish`)&&(r={...r,payload:{...r.payload,currentStep:null}}),(e.type===`finish`||e.type===`workflow-finish`)&&(r=r.phase===`error`||r.status===`failed`?{...r,completedAt:new Date}:{...r,status:e.payload.status||`completed`,phase:`completed`,payload:{...r.payload,currentStep:null,workflowState:{...r.payload.workflowState,status:e.payload.status||`completed`}},completedAt:new Date}),e.type===`error`){let t=DPi(e.payload.error);r={...r,status:`failed`,error:t,phase:`error`,payload:{...r.payload,workflowState:{...r.payload.workflowState,status:`failed`}},errorTimestamp:new Date}}return{newState:r}},kPi=(e,t)=>{try{localStorage.setItem(`template-install-${e}`,JSON.stringify({state:t,timestamp:Date.now()}))}catch(e){console.warn(`Failed to save template state to localStorage:`,e)}},APi=(e,t)=>{let[n,r]=(0,G.useState)({}),[i,a]=(0,G.useState)(!1);return{streamResult:n,isStreaming:i,processStream:async(n,i)=>{if(a(!0),r({}),!n)throw Error(`No stream returned`);let o=n.getReader(),s={runId:i||t,eventTimestamp:new Date().toISOString(),phase:`running`,payload:{workflowState:{steps:{}},currentStep:null}};try{for(;;){let{done:n,value:a}=await o.read();if(n)break;let{newState:c}=OPi(a,s,e);s=c,r(c),(a.runId||i||t)&&kPi(a.runId||i||t,c)}}catch(t){console.error(`💥 [processStream] Error processing template installation stream:`,t);let{newState:n}=OPi({type:`error`,payload:{error:t instanceof Error?t.message:`Unknown error`}},s,e);r(n)}finally{a(!1),o.releaseLock()}}}},jPi=({workflowInfo:e,queryOptions:t}={})=>{let n=Y(),{streamResult:r,isStreaming:i,processStream:a}=APi(e);return{streamInstall:D_({mutationFn:async({inputData:e,selectedModel:t,runId:r})=>{for(let i=1;i<=3;i++)try{let i=n.getAgentBuilderAction(`merge-template`),o=new On;o.set(`selectedModel`,t);let s=await i.stream({inputData:e,requestContext:o},r);await a(s,r);return}catch(e){console.error(`💥 [streamInstall] Attempt ${i} failed:`,e);let t=e?.message?.includes(`Failed to fetch`)||e?.message?.includes(`NetworkError`)||e?.message?.includes(`network error`)||e?.message?.includes(`fetch`)||e?.code===`NETWORK_ERROR`||e?.name===`TypeError`;if(console.warn(`Stream attempt ${i}/3 failed:`,e),t){let e=r?`Network error during template installation (likely hot reload). Please refresh the page to resume from where you left off using runId: ${r}`:`Network error during template installation (likely hot reload). Please try again.`;throw console.error(`🔌 Stream network error:`,e),Error(e)}throw console.error(`❌ [streamInstall] Non-network error or max retries reached, throwing:`,e),e}},...t?.streamInstall}),streamResult:r,isStreaming:i}},MPi=({workflowInfo:e,queryOptions:t}={})=>{let n=Y(),{streamResult:r,isStreaming:i,processStream:a}=APi(e);return{observeInstall:D_({mutationFn:async({runId:e})=>{let t=2e3;for(let r=1;r<=3;r++)try{let t=await n.getAgentBuilderAction(`merge-template`).observeStream({runId:e});await a(t,e);return}catch(e){console.error(`💥 [observeInstall] Attempt ${r} failed:`,e);let n=e?.message?.includes(`Failed to fetch`)||e?.message?.includes(`NetworkError`)||e?.message?.includes(`network error`)||e?.message?.includes(`fetch`)||e?.code===`NETWORK_ERROR`||e?.name===`TypeError`;if(console.warn(`ObserveStream attempt ${r}/3 failed:`,e),n&&r<3){console.info(`🔄 ObserveStream network error detected (likely hot reload), retrying in ${t}ms... (attempt ${r+1}/3)`),await new Promise(e=>setTimeout(e,t));continue}throw console.error(`❌ [observeInstall] Non-network error or max retries reached, throwing:`,e),e}},...t?.observeInstall}),streamResult:r,isStreaming:i}};function NPi(e){return e.replace(/\/$/,``).split(`/`).pop()}function PPi({templates:e,linkComponent:t,className:n,isLoading:r}){let i=t||`a`;return r?(0,K.jsx)(`div`,{className:c(`grid gap-y-4`,n),children:Array.from({length:5}).map((e,t)=>(0,K.jsx)(`div`,{className:`h-16 animate-pulse rounded-lg bg-card`},t))}):(0,K.jsx)(`div`,{className:c(`grid gap-y-4`,n),children:e.map(e=>{let t=e?.agents||e?.tools||e?.networks||e?.workflows||e?.mcp;return(0,K.jsxs)(`article`,{className:c(Bv,`grid w-full grid-cols-[1fr_auto] overflow-hidden rounded-lg state-layer`),children:[(0,K.jsxs)(i,{to:`/templates/${e.slug}`,className:c(`group grid`,{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":e.imageURL}),children:[e.imageURL&&(0,K.jsx)(`div`,{className:`overflow-hidden`,children:(0,K.jsx)(`div`,{className:`thumb transition-scale h-full w-full bg-cover duration-150`,style:{backgroundImage:`url(${e.imageURL})`}})}),(0,K.jsxs)(`div`,{className:c(`grid w-full gap-0.5 px-4 py-3`,`[&_svg]:h-[1em] [&_svg]:w-[1em] [&_svg]:text-muted-foreground`),children:[(0,K.jsx)(T,{as:`h2`,tone:`ink`,children:e.title}),(0,K.jsx)(T,{className:c(CS,A),children:e.description}),(0,K.jsxs)(`div`,{className:`mt-3 hidden flex-wrap items-center gap-x-8 gap-y-4 text-muted-foreground 2xl:flex`,children:[t&&(0,K.jsxs)(`ul`,{className:c(`text-muted-foreground`,`m-0 flex list-none gap-4 p-0`,`[&>li]:flex [&>li]:items-center [&>li]:gap-0.5`),children:[e?.agents&&e.agents.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(HN,{}),` `,e.agents.length]})}),e?.tools&&e.tools.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(XN,{}),` `,e.tools.length]})}),e?.networks&&e.networks.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(n7e,{}),` `,e.networks.length]})}),e?.workflows&&e.workflows.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(ZS,{}),` `,e.workflows.length]})}),e?.mcp&&e.mcp.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(KN,{}),` `,e.mcp.length]})})]}),(0,K.jsx)(`div`,{className:`flex items-center gap-4`,children:e.supportedProviders.map(e=>(0,K.jsx)(T,{tone:`muted`,as:`span`,variant:`body`,children:e},e))})]})]})]}),(0,K.jsx)(`a`,{href:e.githubUrl,className:c(`group ml-auto hidden items-center gap-2 pr-4`,`lg:flex`),target:`_blank`,rel:`noopener noreferrer`,children:(0,K.jsx)(T,{as:`span`,variant:`body`,children:(0,K.jsxs)(`span`,{className:c(`flex items-center gap-2 rounded bg-sidebar px-2 py-1`,Jze,CS,A),children:[(0,K.jsx)(kZ,{}),` `,NPi(e.githubUrl)]})})})]},e.slug)})})}function FPi({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:i,onProviderChange:a,searchTerm:o,onSearchChange:s,onReset:l,className:u,isLoading:d}){return d?(0,K.jsxs)(`div`,{className:c(`flex h-[6.5rem] items-center gap-5`,`[&>div]:h-8 [&>div]:w-48 [&>div]:animate-pulse [&>div]:bg-card`,u),children:[(0,K.jsx)(`div`,{}),` `,(0,K.jsx)(`div`,{}),` `,(0,K.jsx)(`div`,{})]}):(0,K.jsxs)(`div`,{className:c(`sticky top-0 mx-auto flex flex-wrap gap-1.5 bg-background py-5`,u),children:[(0,K.jsx)(MH,{label:`Search templates`,placeholder:`Search templates`,size:`sm`,value:o,onValueChange:s}),(0,K.jsxs)(Bk,{value:t,onValueChange:i,children:[(0,K.jsx)(Hk,{"aria-label":`Search by tag`,size:`sm`,className:`w-auto`,children:(0,K.jsx)(Vk,{placeholder:`Select an option`})}),(0,K.jsx)(Uk,{children:e.map(e=>(0,K.jsx)(Wk,{value:e.value,children:e.label},e.value))})]}),(0,K.jsxs)(Bk,{value:r,onValueChange:a,children:[(0,K.jsx)(Hk,{"aria-label":`Search by provider`,size:`sm`,className:`w-auto`,children:(0,K.jsx)(Vk,{placeholder:`Select an option`})}),(0,K.jsx)(Uk,{children:n.map(e=>(0,K.jsx)(Wk,{value:e.value,children:e.label},e.value))})]}),l&&(0,K.jsx)(J4,{onClick:l})]})}var IPi=[{id:`templates`,label:`Templates`}];function LPi(){let{data:e,isLoading:t}=xPi(),{templates:n,tags:r,providers:i}=e??{templates:[],tags:[],providers:[]},[a,o]=(0,G.useState)(`all`),[s,l]=(0,G.useState)(`all`),[u,d]=(0,G.useState)(``),f=[{value:`all`,label:`Any tag`}];(r||[]).forEach(e=>{f.push({value:e,label:e})});let p=[{value:`all`,label:`Any provider`}];(i||[]).forEach(e=>{p.push({value:e,label:e})});let m=(e,t)=>{t===`tag`?o(e):t===`provider`&&l(e)},h=e=>{d(e)},g=()=>{o(`all`),l(`all`),d(``)},_=n.filter(e=>!(u&&!e.title.toLowerCase().includes(u)&&!e.description.toLowerCase().includes(u)||a!==`all`&&!e.tags.includes(a)||s!==`all`&&!e.supportedProviders.includes(s))),v=u||a!==`all`||s!==`all`;return(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:IPi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Templates`}),(0,K.jsx)(wS,{children:(0,K.jsxs)(nJe,{children:[(0,K.jsx)(Dx,{children:(0,K.jsx)(OZ,{})}),`Templates`]})}),(0,K.jsxs)(`div`,{className:c(`z-10 h-full w-full overflow-y-auto px-5 pb-12`),children:[(0,K.jsx)(FPi,{selectedTag:a,onTagChange:e=>m(e,`tag`),tagOptions:f,selectedProvider:s,onProviderChange:e=>m(e,`provider`),providerOptions:p,searchTerm:u,onSearchChange:h,onReset:v?g:void 0,className:`max-w-[80rem]`,isLoading:t}),(0,K.jsx)(PPi,{templates:_,linkComponent:Lv,className:`mx-auto max-w-[80rem]`,isLoading:t})]})]})}var RPi=U(`IconEmojiSad`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`circle`,{cx:`12`,cy:`12`,r:`9`,stroke:`currentColor`,strokeWidth:`2`}),(0,K.jsx)(`path`,{d:`M10.75 9.9C10.75 11.0046 10.0784 11.75 9.25 11.75C8.42157 11.75 7.75 11.0046 7.75 9.9C7.75 8.79543 8.42157 8 9.25 8C10.0784 8 10.75 8.79543 10.75 9.9Z`,fill:`currentColor`}),(0,K.jsx)(`path`,{d:`M16.25 9.9C16.25 11.0046 15.5784 11.75 14.75 11.75C13.9216 11.75 13.25 11.0046 13.25 9.9C13.25 8.79543 13.9216 8 14.75 8C15.5784 8 16.25 8.79543 16.25 9.9Z`,fill:`currentColor`}),(0,K.jsx)(`path`,{d:`M7.89328 15.4758C7.7698 15.623 7.69925 15.8109 7.70417 16.0051C7.70903 16.1992 7.78791 16.3827 7.92489 16.5166C8.06187 16.6504 8.24712 16.7251 8.44131 16.7254C8.63557 16.7259 8.82181 16.651 8.9661 16.5242C9.05273 16.4499 9.14033 16.3801 9.23093 16.313C10.042 15.7109 11.0211 15.4001 12.0034 15.4C12.9856 15.3986 13.964 15.7081 14.7725 16.3111C14.8628 16.3783 14.9501 16.4481 15.0364 16.5226C15.1803 16.6498 15.3663 16.7253 15.5606 16.7254C15.7548 16.7256 15.9403 16.6515 16.0776 16.5181C16.215 16.3846 16.2944 16.2014 16.2999 16.0073C16.3054 15.8131 16.2354 15.625 16.1124 15.4774C16.0126 15.3603 15.909 15.2487 15.799 15.1403C14.816 14.1611 13.4082 13.5927 12.002 13.6C10.5957 13.595 9.19111 14.1644 8.20718 15.1399C8.09708 15.2479 7.99334 15.3591 7.89328 15.4758Z`,fill:`currentColor`})]}));function zPi({children:e,className:t}){return(0,K.jsx)(`div`,{className:c(`transition-height mt-12 rounded-lg border border-border px-4 py-5 lg:min-h-[25rem] lg:px-12`,t),children:e})}function BPi({errorMsg:e,validationErrors:t}){let n=typeof e==`string`?e:e==null?void 0:String(e),r=n?.includes(`Invalid schema for function`),i=n?.includes(`validation issue`)||t&&t.length>0,a=()=>i?`Template installation completed but some validation issues remain. The template may still be functional, but you should review and fix these issues.`:r?`There was an issue with the AI model configuration. This may be related to the selected model or AI SDK version compatibility.`:`An unexpected error occurred during template installation.`,{icon:o,title:s}=i?{icon:(0,K.jsx)(Zx,{className:`text-warning-foreground`}),title:`Template Installed with Warnings`}:{icon:(0,K.jsx)(RPi,{}),title:`Template Installation Failed`};return(0,K.jsxs)(zPi,{className:`mb-5 content-center space-y-4 text-muted-foreground`,children:[(0,K.jsxs)(`div`,{className:`grid content-center items-center justify-items-center gap-4 [&>svg]:h-8 [&>svg]:w-8`,children:[o,(0,K.jsxs)(`div`,{className:`space-y-2 text-center`,children:[(0,K.jsx)(T,{variant:`subheading`,tone:`ink`,children:s}),(0,K.jsx)(T,{tone:`muted`,children:a()})]})]}),t&&t.length>0&&(0,K.jsxs)(`details`,{children:[(0,K.jsx)(`summary`,{className:c(`text-muted-foreground hover:text-foreground`,`cursor-pointer text-center select-none`),children:(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[`Show Validation Issues (`,t.length,`)`]})}),(0,K.jsx)(`div`,{className:`mt-4 max-h-60 space-y-2 overflow-auto rounded bg-muted p-3 text-left`,children:t.map((e,t)=>(0,K.jsxs)(`div`,{className:`border-l-2 border-destructive-indicator pl-2`,children:[(0,K.jsx)(T,{as:`p`,variant:`column`,className:`text-destructive-foreground`,children:e.type===`typescript`?`🔴 TypeScript Error`:`⚠️ Lint Error`}),(0,K.jsx)(uC,{className:`mt-1 text-caption wrap-break-word whitespace-pre-wrap text-muted-foreground`,code:e.message})]},t))})]}),n&&!i&&(0,K.jsxs)(`details`,{children:[(0,K.jsx)(`summary`,{className:c(`text-muted-foreground hover:text-foreground`,`cursor-pointer text-center select-none`),children:(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`block`,children:`Show Details`})}),(0,K.jsx)(`div`,{className:`mt-4 max-h-60 overflow-auto rounded bg-muted p-3 text-left`,children:(0,K.jsx)(uC,{className:`text-caption wrap-break-word whitespace-pre-wrap`,code:n})})]})]})}function VPi({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:i,handleInstallTemplate:a,handleVariableChange:o,isLoadingEnvVars:s,isInstalling:l,defaultModelProvider:u,defaultModelId:d,onModelUpdate:f}){return(0,K.jsx)(zPi,{children:(0,K.jsxs)(`div`,{className:`mx-auto my-4 grid max-w-[40rem] gap-5 p-4 lg:p-5`,children:[(0,K.jsxs)(T,{as:`h2`,variant:`heading`,tone:`muted`,className:c(`flex items-center gap-2`,`[&_svg]:h-[1.2em] [&_svg]:opacity-70 [&>svg]:w-[1.2em]`),children:[`Install Template `,(0,K.jsx)(OZ,{})]}),(0,K.jsxs)(ak,{orientation:`horizontal`,children:[(0,K.jsx)(sk,{children:`Template AI Model Provider`}),(0,K.jsx)(Tpt,{className:`flex-1`,children:(0,K.jsxs)(Bk,{name:`template-provider`,value:t,onValueChange:n,children:[(0,K.jsx)(Hk,{size:`md`,children:(0,K.jsx)(Vk,{placeholder:`Select`})}),(0,K.jsx)(Uk,{children:e.map(e=>(0,K.jsx)(Wk,{value:e.value,children:e.label},e.value))})]})})]}),t&&Object.entries(r||{}).length>0&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h3`,tone:`muted`,children:`Set required Environmental Variables`}),(0,K.jsx)(`div`,{className:`grid grid-cols-[1fr_1fr] items-start gap-4`,children:s?(0,K.jsxs)(`div`,{className:c(`text-muted-foreground`,`col-span-2 flex items-center justify-center gap-4`,`[&_svg]:h-[1.1em] [&_svg]:w-[1.1em] [&_svg]:opacity-50`,`animate-in duration-300 fade-in`),children:[(0,K.jsx)(It,{}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[` `,`Loading variables...`]})]}):Object.entries(r).map(([e,t])=>(0,K.jsxs)(G.Fragment,{children:[(0,K.jsxs)(ak,{className:`w-full`,children:[(0,K.jsx)(sk,{className:`sr-only`,children:`Key`}),(0,K.jsx)(Jj,{name:`env-${e}`,value:e,disabled:!0,className:`w-full`})]}),(0,K.jsxs)(ak,{invalid:i.includes(e),className:`w-full`,children:[(0,K.jsx)(sk,{className:`sr-only`,children:`Value`}),(0,K.jsx)(Jj,{name:e,value:t,onChange:o,autoComplete:`off`,className:`w-full`}),(0,K.jsx)(lk,{children:i.includes(e)?`Value is required.`:void 0})]})]},e))}),(0,K.jsxs)(`div`,{className:`relative mt-3.5 border-t border-border pt-12`,children:[(0,K.jsx)(`div`,{className:`absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full bg-background`,children:(0,K.jsx)(T,{tone:`muted`,as:`span`,variant:`caption`,className:`block`,children:`And`})}),(0,K.jsx)(T,{as:`h3`,tone:`muted`,children:`Set AI Model for Template Installation`}),(0,K.jsx)(T,{tone:`muted`,className:`mt-2 mb-5`,children:`This model will be used by the workflow to process and install the template`}),(0,K.jsx)(E1r,{defaultProvider:u||``,defaultModel:d||``,updateModel:f||(()=>Promise.resolve({message:`Updated`})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:`Provider`})]})]}),t&&!s&&(0,K.jsx)(X,{className:c(`mt-4 flex min-h-10 w-full items-center justify-center gap-2 rounded-lg bg-card state-layer text-foreground`,`[&_svg]:h-[1.1em] [&_svg]:text-foreground [&>svg]:w-[1.1em]`),onClick:a,disabled:!t||!u||!d||i.length>0||l,children:l?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(It,{className:`h-4 w-4`}),` Installing...`]}):(0,K.jsxs)(K.Fragment,{children:[`Install `,(0,K.jsx)(oH,{})]})})]})})}function HPi({title:e,description:t,githubUrl:n,isLoading:r,infoData:i,templateSlug:a}){let o=a?`feat/install-template-${a}`:`feat/install-template-[slug]`;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`mt-5 grid items-center`,children:(0,K.jsxs)(`div`,{className:c(`flex items-center gap-3`,`[&>svg]:h-[1.2em] [&>svg]:w-[1.2em] [&>svg]:opacity-50`,{"[&>svg]:opacity-20":r}),children:[(0,K.jsx)(OZ,{}),(0,K.jsx)(`h2`,{className:c({"flex min-w-[50%] rounded-lg bg-muted":r}),children:(0,K.jsx)(T,{as:`span`,variant:`title`,className:`block`,children:r?(0,K.jsx)(K.Fragment,{children:`\xA0`}):e})})]})}),(0,K.jsxs)(`div`,{className:`grid gap-x-24 lg:grid-cols-[1fr_1fr]`,children:[(0,K.jsxs)(`div`,{className:`grid`,children:[(0,K.jsx)(T,{tone:`muted`,className:c(`mt-2 mb-4`,{"rounded-lg bg-muted":r}),children:r?(0,K.jsx)(K.Fragment,{children:`\xA0`}):t}),!r&&a&&(0,K.jsxs)(`div`,{className:c(`mb-4 rounded-lg border border-border bg-background p-4`,`flex items-start gap-3`),children:[(0,K.jsx)(`div`,{className:`mt-0.5 shrink-0`,children:(0,K.jsx)(Yx,{className:`h-[1.1em] w-[1.1em] text-info-indicator`})}),(0,K.jsxs)(`div`,{className:`flex-1 space-y-2`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(KS,{className:`h-[1em] w-[1em] text-muted-foreground`}),(0,K.jsx)(T,{as:`span`,variant:`subheading`,tone:`ink`,children:`A new Git branch will be created`})]}),(0,K.jsxs)(`div`,{className:`space-y-1`,children:[(0,K.jsxs)(T,{tone:`muted`,as:`p`,variant:`caption`,children:[(0,K.jsx)(T,{as:`span`,variant:`column`,children:`Branch name:`}),` `,(0,K.jsx)(uX,{children:o})]}),(0,K.jsx)(T,{tone:`muted`,as:`p`,variant:`caption`,children:`This ensures safe installation with easy rollback if needed. Your main branch remains unchanged.`})]})]})]}),n&&(0,K.jsxs)(`a`,{href:n,target:`_blank`,rel:`noopener noreferrer`,className:c(`text-muted-foreground hover:text-foreground`,`mt-auto flex items-center gap-2`),children:[(0,K.jsx)(kZ,{}),(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:n?.split(`/`)?.pop()})]})]}),i&&(0,K.jsx)(A1r,{data:i,labelsAreHidden:!0,isLoading:r})]})]})}function UPi(e){switch(e){case`running`:return(0,K.jsx)(It,{size:`sm`,"aria-hidden":!0});case`success`:return(0,K.jsx)(pC,{"aria-hidden":!0});case`failed`:return(0,K.jsx)(xw,{"aria-hidden":!0});default:return null}}function WPi(){return(0,K.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`text-placeholder`,"aria-hidden":!0,children:(0,K.jsx)(`circle`,{cx:`12`,cy:`12`,r:`8.5`,pathLength:`48`,fill:`none`,stroke:`currentcolor`,strokeWidth:`2.8`,strokeLinecap:`round`,strokeDasharray:`3 3`})})}function GPi({status:e,variant:t}){return t===`plain`?(0,K.jsx)(`span`,{className:c(`flex size-icon-md items-center justify-center self-center [&>svg]:size-icon-md`,u.colors,{"[&>svg]:text-success-indicator":e===`success`,"[&>svg]:text-destructive-foreground":e===`failed`}),children:e===`pending`?(0,K.jsx)(WPi,{}):UPi(e)}):(0,K.jsx)(`span`,{className:c(`flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none`,u.colors,u.transform,{"[&>svg]:text-success-indicator":e===`success`,"[&>svg]:text-destructive-foreground":e===`failed`,"border border-dashed border-placeholder":e===`pending`,"[&>svg]:size-icon-md":e!==`running`,"bg-success-subtle":e===`success`,"bg-destructive-subtle":e===`failed`,"scale-110":e===`success`||e===`failed`}),children:UPi(e)})}function KPi({step:e,isActive:t,position:n,variant:r=`default`}){let i=t||e.status===`success`?`ink`:`muted`;return(0,K.jsxs)(`div`,{className:c(`grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none`,u.colors,{"border border-transparent":r==="default","border-dashed border-placeholder bg-card":t&&r==="default"}),children:[(0,K.jsxs)(`div`,{className:`grid min-w-0 grid-cols-[auto_1fr] gap-2`,children:[(0,K.jsxs)(T,{as:`span`,tone:i,className:c(`flex min-w-6 justify-end`,u.colors),children:[n,`.`]}),(0,K.jsxs)(`div`,{className:`min-w-0`,children:[(0,K.jsx)(T,{as:`h4`,tone:i,className:u.colors,children:e.title}),e.description&&(0,K.jsx)(T,{tone:`faint`,className:c(`-mt-0.5`,{truncate:r===`plain`}),children:e.description})]})]}),(0,K.jsx)(GPi,{status:e.status,variant:r})]})}function qPi({currentStep:e,steps:t=[],className:n}){return(0,K.jsx)(`div`,{className:c(n),children:t.map((t,n)=>(0,K.jsx)(KPi,{step:t,isActive:e?.id===t.id,position:n+1},t.id))})}function JPi({steps:e}){let t=e.length,n=e.filter(e=>e.status===`success`).length;return(0,K.jsxs)(`div`,{className:`flex w-full flex-col content-center justify-center gap-4`,children:[(0,K.jsx)(`div`,{className:`grid w-full grid-cols-[0_repeat(9,1fr)]`,children:e.map((t,n)=>(0,K.jsx)(`div`,{className:c(`relative flex h-8 items-center justify-end`,u.colors,{"bg-success-subtle":t.status===`success`&&e?.[n-1]?.status===`success`}),children:(0,K.jsx)(`div`,{className:c(`absolute right-0 z-10 flex size-8 translate-x-1/2 items-center justify-center self-center rounded-full bg-fill text-column text-muted-foreground motion-reduce:transition-none`,u.colors,u.transform,{"border border-dashed border-placeholder":t.status===`pending`,"scale-110 bg-success-subtle text-success-subtle-foreground":t.status===`success`,"scale-110 bg-destructive-subtle text-destructive-subtle-foreground":t.status===`failed`}),children:t.status===`running`?(0,K.jsx)(It,{}):n+1})},t.id))}),(0,K.jsxs)(`div`,{className:c(`text-center text-caption text-muted-foreground`,u.colors),children:[n,` of `,t,` steps completed`]})]})}var YPi=(0,G.createContext)(3);function XPi({title:e,description:t,action:n,done:r,className:i,children:a}){let o=(0,G.useContext)(YPi);return(0,K.jsxs)(`li`,{className:c(`group/step grid grid-cols-[1.5rem_minmax(0,1fr)] gap-x-4 [counter-increment:ds-step]`,i),children:[(0,K.jsxs)(`div`,{className:`flex flex-col items-center`,children:[(0,K.jsx)(`span`,{className:c(`flex size-6 shrink-0 items-center justify-center rounded-full`,u.colors,r?`bg-success-indicator/18 text-success-indicator`:`bg-fill text-foreground`),children:r?(0,K.jsx)(pC,{className:`size-icon-sm`,"aria-label":`Done`}):(0,K.jsx)(T,{as:`span`,variant:`column`,className:`before:content-[counter(ds-step)]`,"aria-hidden":!0})}),(0,K.jsx)(`span`,{"aria-hidden":!0,className:`w-px flex-1 bg-border group-last/step:hidden`})]}),(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-3 pb-8 group-last/step:pb-0`,children:[(0,K.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,K.jsxs)(`div`,{className:`flex min-h-6 flex-wrap items-center justify-between gap-x-6 gap-y-2`,children:[(0,K.jsx)(T,{as:o===2?`h2`:`h3`,variant:`label`,className:`text-pretty`,children:e}),n==null?null:(0,K.jsx)(`div`,{className:`flex shrink-0 items-center gap-2`,children:n})]}),t==null?null:(0,K.jsx)(T,{as:`p`,variant:`body-sm`,tone:`muted`,className:`max-w-[70ch] text-pretty`,children:t})]}),a]})]})}function ZPi({headingLevel:e=3,className:t,children:n}){return(0,K.jsx)(YPi.Provider,{value:e,children:(0,K.jsx)(`ol`,{className:c(`flex flex-col [counter-reset:ds-step]`,t),children:n})})}Object.assign(ZPi,{Step:XPi});function QPi({name:e,streamResult:t,runId:n,workflowInfo:r}){let i=t?.phase||`initializing`,a=t?.payload?.workflowState,o=t?.payload?.currentStep,s=t?.error,l=a?.steps||{},u=Object.keys(l).length>0,d=e=>e===`input`||e.endsWith(`.input`)||e.startsWith(`Mapping_`)&&/[0-9a-f]{8}/.test(e)||/[0-9a-f]{8,}/.test(e)?!1:!r?.allSteps||e in r.allSteps,f=Object.entries(l).filter(([e,t])=>d(e)),p=f.length,m=()=>{switch(i){case`initializing`:return`Preparing template installation...`;case`processing`:return`Installing ${e} template`;case`completed`:return`Template installation completed!`;case`error`:return`Template installation failed`;default:return`Installing template...`}},h=f.map(([e,t])=>({id:e,status:t?.status,description:t?.description,title:e.charAt(0).toUpperCase()+e.slice(1).replace(/-/g,` `),isActive:o?.id===e}));return(0,K.jsxs)(zPi,{className:`mb-5 content-center space-y-6 text-muted-foreground`,children:[(0,K.jsxs)(`div`,{className:`text-center`,children:[(0,K.jsx)(T,{as:`h3`,variant:`heading`,tone:`ink`,children:m()}),(t?.runId||n)&&(0,K.jsxs)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`mt-2`,children:[`Run ID: `,t?.runId??n]})]}),u&&p>0&&![`error`].includes(i)&&(0,K.jsx)(`div`,{className:`mx-auto w-full max-w-[30rem] px-4`,children:(0,K.jsx)(JPi,{steps:h})}),s&&i===`error`&&(0,K.jsxs)(`div`,{className:c(`text-foreground`,`flex items-center gap-3 rounded-lg bg-destructive-subtle p-4`,`[&>svg]:h-6 [&>svg]:w-6 [&>svg]:text-destructive-foreground [&>svg]:opacity-70`),children:[(0,K.jsx)(qx,{}),(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:s||`Something went wrong`})]}),u&&(0,K.jsx)(qPi,{steps:h,currentStep:o,className:`pb-4`}),!u&&i===`initializing`&&(0,K.jsxs)(`div`,{className:c(`text-muted-foreground`,`grid justify-items-center gap-4 text-center`),children:[(0,K.jsx)(It,{}),(0,K.jsx)(T,{as:`p`,variant:`body`,children:`This may take some time...`})]})]})}function $Pi({name:e,installedEntities:t}){return(0,K.jsxs)(zPi,{className:c(`grid content-center items-center justify-items-center gap-4`,`[&>svg]:h-8 [&>svg]:w-8`),children:[(0,K.jsx)(OZ,{}),(0,K.jsx)(T,{as:`h2`,variant:`heading`,children:`Done!`}),(0,K.jsxs)(T,{tone:`muted`,className:`text-center`,children:[`The `,(0,K.jsx)(`b`,{className:`text-muted-foreground`,children:e}),` template has been successfully installed.`,t&&t.length>0&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`br`,{}),` Installed entities are listed below.`]})]}),t&&t.length>0&&(0,K.jsx)(A1r,{data:t})]})}function eFi(){let{templateSlug:e}=kv(),t=[{id:`templates`,label:`Templates`,to:`/templates`},{id:`template`,label:Zjt(e)}],[n,r]=Rv(),[i,a]=(0,G.useState)(``),[o,s]=(0,G.useState)(``),[l,u]=(0,G.useState)(``),[d,f]=(0,G.useState)({}),[p,m]=(0,G.useState)([]),[h,g]=(0,G.useState)(null),[_,v]=(0,G.useState)(!1),[y,b]=(0,G.useState)(``),[x,S]=(0,G.useState)(!1),[C,w]=(0,G.useState)(!1),[T,E]=(0,G.useState)([]),{data:D,isLoading:O}=SPi({repoOrSlug:e,owner:`mastra-ai`}),k=`1.85.0-alpha.1`.includes(`beta`)??!1?`beta`:`main`,{data:A,isLoading:j}=CPi({repo:D?.githubUrl?new URL(D.githubUrl).pathname.split(`/`)[2]:`template-${e}`,owner:`mastra-ai`,branch:k}),{data:M,isLoading:N}=wPi(),{mutateAsync:P,isPending:F}=TPi(),{mutateAsync:I}=EPi(),{streamInstall:L,streamResult:R,isStreaming:z}=jPi({workflowInfo:M}),{observeInstall:B,streamResult:V,isStreaming:H}=MPi({workflowInfo:M});(0,G.useEffect)(()=>{let e=n.get(`runId`);!e||_||h||z||H||(console.info(`🔄 Checking completed run after hot reload:`,{runId:e}),b(e),I({runId:e}).then(e=>{let t=e.snapshot;if(t?.status===`success`&&t?.result?.success)v(!0);else if(t?.result?.success===!1){if(t?.result?.validationResults&&!t?.result?.validationResults?.valid&&t?.result?.validationResults?.remainingErrors>0){let{remainingErrors:e,errors:n}=t.result.validationResults,r=`Template installation completed but ${e} validation issue${e>1?`s`:``} remain unresolved.`;g(r),E(n||[])}else{let e=t?.result?.message||t?.result?.error||`Template installation failed`;g(typeof e==`string`?e:String(e))}}}).catch(e=>{console.error(`❌ Failed to fetch run details:`,e),g(`Failed to retrieve installation status after reload`)}))},[n,_,h,z,H,I]),(0,G.useEffect)(()=>{let e=n.get(`runId`),t=n.get(`resume`),i=n.get(`provider`);if(e&&t===`true`&&i&&!z&&!H&&!x&&!C&&M){b(e),S(!0);try{I({runId:e}).then(t=>{if(t.snapshot?.status===`running`)return B.mutateAsync({runId:e})}).then(()=>{r(e=>{let t=new URLSearchParams(e);return t.delete(`resume`),t})}).catch(e=>{console.error(`❌ Failed to resume template installation:`,e),e.message?.includes(`404`)||e.message?.includes(`not found`)?g(`Template installation run not found. It may have expired or been completed.`):g(`Failed to resume template installation. Please try again.`)})}catch(e){console.error(`❌ Auto-resume failed with error:`,e),g(`Failed to resume template installation. Please refresh and try again.`)}}},[n,e,z,H,x,C,M,I,B,r]);let ee=[{value:`openai`,label:`OpenAI`},{value:`anthropic`,label:`Anthropic`},{value:`groq`,label:`Groq`},{value:`google`,label:`Google`}],te=[{key:`tools`,label:`Tools`,value:D?.tools?.length?D.tools.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(XN,{})},{key:`agents`,label:`Agents`,value:D?.agents?.length?D.agents.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(HN,{})},{key:`workflows`,label:`Workflows`,value:D?.workflows?.length?D.workflows.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(ZS,{})},{key:`providers`,label:`Providers`,value:D?.supportedProviders?.length?D.supportedProviders.join(`, `):`n/a`,icon:(0,K.jsx)(k3,{})},{key:`tags`,label:`Tags`,value:D?.tags?.length?D.tags.join(`, `):`n/a`,icon:(0,K.jsx)(wX,{})}],U=[{...te[0]},{...te[1]},{...te[2]}].filter(e=>e.value!==`n/a`);return(0,G.useEffect)(()=>{A&&f(A)},[A]),(0,G.useEffect)(()=>{let e=R||V;e?.phase===`error`&&e?.error&&g(typeof e.error==`string`?e.error:String(e.error))},[R?.phase,R?.error,V?.phase,V?.error]),(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(`div`,{className:c(`h-full w-full overflow-y-scroll lg:px-12`),children:(0,K.jsxs)(`div`,{className:`mx-auto grid w-full max-w-[80rem] gap-y-4 p-4`,children:[(0,K.jsx)(HPi,{isLoading:O,title:D?.title,description:D?.longDescription,imageURL:D?.imageURL,githubUrl:D?.githubUrl,infoData:te,templateSlug:e}),D&&(0,K.jsxs)(K.Fragment,{children:[(z||H)&&(0,K.jsx)(QPi,{name:D.title,streamResult:H?V:R,runId:y,workflowInfo:M}),_&&(0,K.jsx)($Pi,{name:D.title,installedEntities:U,linkComponent:Lv}),h&&(0,K.jsx)(BPi,{errorMsg:h,validationErrors:T.length>0?T:R?.validationResults?.errors||V?.validationResults?.errors}),!z&&!H&&!_&&!h&&(0,K.jsx)(VPi,{providerOptions:ee,selectedProvider:i,onProviderChange:e=>{a(e)},variables:d,setVariables:f,errors:p,setErrors:m,handleInstallTemplate:async()=>{let e=Object.entries(d).reduce((e,[t,n])=>(n===``&&e.push(t),e),[]);if(e.length>0)m(e);else if(D){g(null),v(!1),b(``),w(!0);try{let e={repo:D.githubUrl||`https://github.com/mastra-ai/template-${D.slug}`,ref:k,slug:D.slug,variables:d},{runId:t}=await P({});b(t),r(e=>{let n=new URLSearchParams(e);return n.set(`runId`,t),n.set(`resume`,`true`),n.set(`provider`,i||`openai`),n}),await L.mutateAsync({inputData:e,selectedModel:{provider:o,modelId:l},runId:t})}catch(e){w(!1),g(e?.message||`Template installation failed`),console.error(`Template installation failed`,e)}}},handleVariableChange:e=>{let{name:t,value:n}=e.target;n.trim()===``?m(e=>[...e,t]):m(e=>e.filter(e=>e!==t)),f(e=>({...e,[t]:n}))},isLoadingEnvVars:j||N,isInstalling:F,defaultModelProvider:o,defaultModelId:l,onModelUpdate:async e=>(s(e.provider),u(e.modelId),{message:`Model updated successfully`})})]})]})})]})}var tFi=e=>e.threadId;function nFi(e,t){return`traces`in e?{traces:{...e.traces,to:t}}:{threads:{...e.threads,to:t}}}var rFi=e=>`traces`in e?e.traces:e.threads;function iFi(e){let{field:t=`endedAt`,direction:n=`desc`}=e?.[0]??{},r=n===`asc`?1:-1;return(e,n)=>{let i=e[t],a=n[t];if(i!==a){if(i==null)return 1;if(a==null)return-1;if(i<a)return-r;if(i>a)return r}return e.threadId.localeCompare(n.threadId)}}function aFi({query:e,rolling:t,autoRefetch:n=!0,limit:r,enabled:i=!0}){let a=Y(),{anchorTo:o,reanchor:s}=WNi(e),c=(0,G.useMemo)(()=>o?{...e,timeRange:nFi(e.timeRange,o)}:e,[e,o]),l=iXr({query:c,limit:r,enabled:i,queryOptions:BNi}),{headRows:u}=KNi({queryKey:[`threads`,e],fetchHead:async t=>(await a.queryTraceThreads({...e,timeRange:nFi(e.timeRange,t),orderBy:[{field:`endedAt`,direction:`desc`}],page:{limit:50}})).threads,getId:tFi,getEndedAt:e=>e.endedAt,since:Date.parse(rFi(c.timeRange).to),enabled:i&&t&&n&&l.threads!==void 0&&!l.isFetching&&!l.isError,onOverflow:s}),{orderBy:d}=e,f=l.threads,p=(0,G.useMemo)(()=>f&&JNi(f,u,{getId:tFi,compare:iFi(d),hasNextPage:l.hasNextPage}),[f,u,d,l.hasNextPage]);return{...l,threads:p}}function oFi(e){return{traceId:e.lastTraceId,name:e.entityName??e.threadId,entityType:e.entityType,entityId:e.entityId,entityName:e.entityName,threadId:e.threadId,resourceId:e.resourceId,environment:e.environment,status:e.status,inputPreview:e.inputPreview,outputPreview:e.outputPreview??void 0,errorPreview:e.errorPreview??void 0,startedAt:e.startedAt,endedAt:e.endedAt,traceCount:e.traceCount,timeToFirstChunkMs:e.timeToFirstChunkMs,timeToFirstTokenMs:e.timeToFirstTokenMs,createdAt:e.startedAt}}var sFi=[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`],cFi=[];function lFi(){let{data:e}=i5(),t=e?.capabilities.traceQueryTimeToFirstChunk??!1,n=e?.capabilities.traceQueryTimeToFirstToken??!1,{data:r=cFi}=t8(),{data:i=cFi}=n8();return(0,G.useMemo)(()=>[d3r,...Pai({withTimeToFirstChunk:t,withTimeToFirstToken:n,entityNames:r,environments:i})],[t,n,r,i])}function uFi({tokens:e,groups:t,onFiltersChange:n}){let r=(0,G.useMemo)(()=>P8(e),[e]),i=(0,G.useMemo)(()=>{let e=F8([],t);return{...e,nodes:[p5,...r,...e.nodes]}},[r,t]),a=(0,G.useCallback)(e=>{let t=UZr({...e,nodes:e.nodes.filter(e=>H6(e)||e.fieldId!==`timeRange`)});n(t.tokens,t.groups)},[n]);return{filterBarValue:i,onFilterBarChange:a,onFilterByField:(0,G.useCallback)((e,t)=>{let n=r.filter(t=>t.fieldId!==e),o={id:`${e}:${t}`,fieldId:e,operatorId:`is`,value:t},s=i.nodes.filter(H6);a({...i,nodes:[...n,o,...s]})},[r,i,a])}}var dFi=e=>e;function fFi({datePreset:e,dateFrom:t,dateTo:n,minDate:r,tokens:i,groups:a,onDatePresetChange:o,onDateChange:s,onDateRangeChange:c,onFiltersChange:l,disabled:u}){let d=lFi(),{filterBarValue:f,onFilterBarChange:p}=uFi({tokens:i,groups:a,onFiltersChange:l});return(0,K.jsxs)(m5,{fields:d,operators:gZr,value:f,onValueChange:p,createItemId:dFi,maxDepth:3,"aria-label":`Thread filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(m5.Chips,{renderChip:i=>i.fieldId===`timeRange`?(0,K.jsx)(m5.TimeRange,{preset:e,onPresetChange:o,dateFrom:t,dateTo:n,minDate:r,onDateChange:s,onDateRangeChange:c,disabled:u,presets:sFi,defaultPreset:o5.datePreset}):(0,K.jsx)(m5.Chip,{item:i})}),(0,K.jsx)(m5.Input,{placeholder:`Filter threads`})]})}function pFi({selectedThreadId:e,onSelectedThreadChange:t,onOpenScore:n,urlState:r}){let i=HNi(r),{timeRange:a,tokens:o,groups:s,sort:c}=i,l=a5().enabled,u=u2r().enabled,d=oii({scope:`threads`}),{data:f,isLoading:p}=i5(),m=f?.capabilities.traceQueryTimeToFirstChunk??!1,h=f?.capabilities.traceQueryTimeToFirstToken??!1,g=(0,G.useMemo)(()=>p?d.preferences:T0r(d.preferences,{withTimeToFirstChunk:m,withTimeToFirstToken:h}),[d.preferences,p,m,h]),{threads:_,hasNextPage:v,isFetchingNextPage:y,setEndOfListElement:b,isLoading:x,isError:S,error:C}=aFi({query:(0,G.useMemo)(()=>{let e=Lai(o,s,{withTimeToFirstChunk:m,withTimeToFirstToken:h});return{timeRange:{traces:a},orderBy:[{field:`startedAt`,direction:c.direction}],...e?{where:e}:{}}},[a,c,o,s,m,h]),rolling:i.rolling}),w=(0,G.useMemo)(()=>(_??[]).map(oFi),[_]),T=w.find(t=>t.threadId===e),E=e=>{e.threadId&&t(e.threadId)},D=!x&&!S&&w.length===0&&!i.contentFiltersApplied&&!e;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Threads`}),(0,K.jsx)(Y0r,{toolbar:(0,K.jsxs)(K.Fragment,{children:[r&&(0,K.jsx)(Loi,{page:`threads`,...r,columns:d}),(0,K.jsxs)(TK,{children:[(0,K.jsx)(TK.Start,{children:(0,K.jsx)(fFi,{datePreset:i.datePreset,dateFrom:i.dateFrom,dateTo:i.dateTo,tokens:o,groups:s,onDatePresetChange:i.onDatePresetChange,onDateChange:i.onDateChange,onDateRangeChange:i.onDateRangeChange,onFiltersChange:i.onFiltersChange,disabled:x})}),(0,K.jsx)(TK.End,{children:(0,K.jsx)(p2r,{scope:`threads`,value:d.preferences,onChange:d.setPreferences})})]})]}),error:S?(0,K.jsx)(Q8,{error:C,resource:`threads`,errorTitle:`Failed to load threads`}):void 0,empty:D?(0,K.jsx)(r0r,{resource:`threads`,datePreset:i.datePreset,dateFrom:i.dateFrom,dateTo:i.dateTo}):void 0,children:(0,K.jsx)(_7r,{listId:`all-threads`,columnPreferences:g,outcomeColumn:!1,traces:w,isLoading:x,isFetchingNextPage:y,hasNextPage:v,setEndOfListElement:b,filtersApplied:i.filtersApplied,resource:`threads`,sort:c,onSortChange:e=>i.setSort({field:`startedAt`,direction:e.direction}),featuredTraceId:T?.traceId,onTraceClick:E})}),(0,K.jsx)(Gri,{open:!!e,threadId:e??``,depth:1,closeLabel:`Close`,withQueryTrace:l,withFeedback:u,onOpenScore:n,onClose:()=>t(void 0)})]})}function mFi(){let{enabled:e,isLoading:t}=i2r(),n=Ov(),[r,i]=Rv();return(0,K.jsx)(zNi,{enabled:e,isLoading:t,heading:`Threads`,title:`Query threads capability not activated`,description:`Your observability storage does not support thread row queries. Switch to a store that declares the thread-query-rows capability to list threads.`,children:(0,K.jsx)(pFi,{urlState:{searchParams:r,setSearchParams:i},selectedThreadId:ePi(r),onSelectedThreadChange:e=>i(t=>tPi(t,e),{replace:!0}),onOpenScore:(e,t)=>n(CK(e,t))})})}var hFi=()=>(0,K.jsx)(Jx,{titleSlot:`No Workflows yet`,descriptionSlot:(0,K.jsxs)(K.Fragment,{children:[`Mastra workflows are not configured yet. `,(0,K.jsx)(`br`,{}),`More information in the documentation.`]}),actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/docs/workflows/overview`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(tP,{}),children:`Workflows documentation`}),variant:`fill`});function gFi(e,t,n){return IZ(e,t,{name:e=>e.name,running:e=>n[e.id]?.running??0,suspended:e=>n[e.id]?.suspended??0,steps:e=>Object.keys(e.steps??{}).length})}function _Fi(e){return Object.keys(e.steps??{}).filter(t=>e.allSteps?.[t]?.isWorkflow)}function vFi(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,n),r.name&&t.set(r.name,n);return t}function yFi(e,t,n){let r=vFi(t),i=[],a=(e,o,s,c,l,u)=>{let d=_Fi(e).filter(e=>{let t=r.get(e);return t===void 0||!c.has(t)});if(i.push({kind:`workflow`,workflow:e,pathKey:o,depth:s,nestedIds:d,guides:l,isLastChild:u}),!n.has(o)||d.length===0)return;let f=new Set(c).add(e.id),p=s===0?[]:[...l,!u];for(let[n,c]of d.entries()){let l=n===d.length-1,u=r.get(c);if(u===void 0){i.push({kind:`unregistered`,stepId:c,description:e.allSteps?.[c]?.description,pathKey:`${o}/${c}`,depth:s+1,guides:p,isLastChild:l});continue}let m=t[u];m&&a({...m,id:u},`${o}/${u}`,s+1,f,p,l)}};for(let t of e)a(t,t.id,0,new Set([t.id]),[],!1);return i}var bFi=`auto 24rem minmax(0, 1fr) auto auto auto`;function xFi({guides:e,isLastChild:t}){return(0,K.jsxs)(`span`,{"aria-hidden":!0,className:`-my-6 flex shrink-0 self-stretch`,children:[e.map((e,t)=>(0,K.jsx)(`span`,{className:c(`w-6`,e&&`border-l border-border`)},t)),(0,K.jsxs)(`span`,{className:`relative w-6`,children:[(0,K.jsx)(`span`,{className:c(`absolute top-0 left-0 border-l border-border`,t?`h-1/2`:`h-full`)}),(0,K.jsx)(`span`,{className:`absolute top-1/2 left-0 w-3.5 border-b border-border`})]})]})}function SFi({row:e,isExpanded:t,onToggle:n}){let r=e.kind===`workflow`&&e.nestedIds.length>0,i=e.kind===`workflow`?e.workflow.name:e.stepId;return(0,K.jsx)(`div`,{className:`flex items-center pl-5`,children:r?(0,K.jsx)(`button`,{type:`button`,"aria-expanded":t,"aria-label":`${t?`Collapse`:`Expand`} nested workflows of ${i}`,className:c(SS,`relative grid size-5 shrink-0 place-items-center before:absolute before:-inset-1.5 before:content-['']`),onClick:e=>{e.stopPropagation(),n()},children:(0,K.jsx)(y,{direction:`right`,className:`size-4`})}):(0,K.jsx)(`span`,{className:`size-5 shrink-0`,"aria-hidden":!0})})}var CFi=e=>e.stopPropagation();function wFi({sortKey:e,sort:t,onSortChange:n,children:r}){return n?(0,K.jsx)(Z.SortableTopCell,{sortKey:e,sort:t?.key===e?t.direction:void 0,onSortChange:t=>n(t,e),children:r}):(0,K.jsx)(Z.TopCell,{children:r})}function TFi({row:e,isExpanded:t,onToggle:n,runCount:r,rowProps:i}){let{paths:a,Link:o}=sn(),s=(0,G.useRef)(null),{workflow:c,nestedIds:l}=e,u=dJ(c.name,50),d=dJ(c.description??``,200),f=Object.keys(c.steps??{}).length,p=r?.running??0,m=r?.suspended??0,h=l.length>0;return(0,K.jsxs)(Z.RowWrapper,{...i,onSelectRow:()=>s.current?.click(),children:[(0,K.jsx)(SFi,{row:e,isExpanded:t,onToggle:n}),(0,K.jsxs)(Z.RowLink,{ref:s,colStart:2,to:a.workflowLink(c.id),LinkComponent:o,tabIndex:-1,onClick:CFi,children:[(0,K.jsx)(Z.NameCell,{children:(0,K.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[e.depth>0?(0,K.jsx)(xFi,{guides:e.guides,isLastChild:e.isLastChild}):null,(0,K.jsx)(`span`,{className:`truncate`,children:u}),c.origin===`dynamic`?(0,K.jsx)(eC,{size:`xs`,variant:`blue`,title:`Registered via the dynamic-workflows API`,children:`Dynamic`}):null,h?(0,K.jsxs)(T,{as:`span`,variant:`body-sm`,tone:`muted`,title:`Nested workflows: ${l.join(`, `)}`,className:`inline-flex shrink-0 items-center gap-1`,children:[(0,K.jsx)(ZS,{"aria-hidden":!0,className:`size-icon-sm`}),l.length]}):null]})}),(0,K.jsx)(Z.DescriptionCell,{children:d}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:p>0?(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-info-indicator`,"aria-label":`${p} run${p===1?``:`s`} in progress`,children:[(0,K.jsx)(`span`,{"aria-hidden":!0,className:`size-2 rounded-full bg-info-indicator motion-safe:animate-pulse`}),p]}):``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:m>0?(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-warning-foreground`,"aria-label":`${m} run${m===1?``:`s`} awaiting input`,children:[(0,K.jsx)(ET,{"aria-hidden":!0,className:`size-icon-sm`}),m]}):``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:f||``})]})]})}function EFi({workflows:e,isLoading:t,search:n=``,sort:r,onSortChange:i,requestContext:a}){let[o,s]=(0,G.useState)(new Set),l=wEt({requestContext:a}),u=(0,G.useMemo)(()=>Object.entries(e).map(([e,t])=>({...t,id:e})),[e]),d=(0,G.useMemo)(()=>{let e=n.toLowerCase();return u.filter(t=>t.name?.toLowerCase().includes(e)||t.description?.toLowerCase().includes(e))},[u,n]),f=(0,G.useMemo)(()=>gFi(d,r,l),[d,r,l]),m=(0,G.useMemo)(()=>yFi(f,e,o),[f,e,o]),h=(0,G.useMemo)(()=>{let e=new Map;for(let t of m)t.kind===`workflow`&&e.set(t.pathKey,e.size);return e},[m]),{containerRef:g,getRowProps:_}=PZ({count:h.size,global:!0}),v=e=>{s(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})};return t?(0,K.jsx)(DH,{columns:bFi,fit:`container`}):(0,K.jsxs)(Z,{columns:bFi,fit:`container`,scrollRef:g,children:[(0,K.jsxs)(Z.Top,{children:[(0,K.jsx)(Z.TopCell,{children:(0,K.jsx)(`span`,{className:`sr-only`,children:`Expand`})}),(0,K.jsx)(wFi,{sortKey:`name`,sort:r,onSortChange:i,children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`Description`}),(0,K.jsx)(wFi,{sortKey:`running`,sort:r,onSortChange:i,children:`Running`}),(0,K.jsx)(wFi,{sortKey:`suspended`,sort:r,onSortChange:i,children:`Pending input`}),(0,K.jsx)(wFi,{sortKey:`steps`,sort:r,onSortChange:i,children:`Number of steps`})]}),m.length===0&&n?(0,K.jsx)(Z.NoMatch,{message:`No Workflows match your search`}):null,m.map(e=>{let t=o.has(e.pathKey),n=()=>v(e.pathKey);return e.kind===`unregistered`?(0,K.jsxs)(Z.RowStatic,{className:`gap-0 px-0`,children:[(0,K.jsx)(SFi,{row:e,isExpanded:t,onToggle:n}),(0,K.jsxs)(`div`,{className:`col-span-5 col-start-2 grid grid-cols-subgrid gap-4 px-3`,children:[(0,K.jsx)(Z.NameCell,{children:(0,K.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,K.jsx)(xFi,{guides:e.guides,isLastChild:e.isLastChild}),(0,K.jsx)(`span`,{className:`truncate`,children:dJ(e.stepId,50)}),(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{render:(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`muted`}),role:`note`,tabIndex:0,className:c(`shrink-0 rounded-sm`,p),children:`not registered`}),(0,K.jsx)(Tx,{className:`max-w-72`,children:`Runs as a step of its parent workflow. Add it to the workflows of your Mastra instance to open, run, and inspect it on its own page.`})]})]})}),(0,K.jsx)(Z.DescriptionCell,{children:dJ(e.description??``,200)}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:``})]})]},`workflow-${e.pathKey}`):(0,K.jsx)(TFi,{row:e,isExpanded:t,onToggle:n,runCount:l[e.workflow.id],rowProps:_(h.get(e.pathKey)??-1)},`workflow-${e.pathKey}`)})]})}var K9=[eP(`/workflows`)];function DFi(){let{data:e,isLoading:t,error:n}=eN(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)();return n&&FN(n)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:K9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(TH,{variant:`fill`})]}):n&&IN(n)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:K9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(wH,{variant:`fill`,resource:`workflows`})]}):n?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:K9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load workflows`,descriptionSlot:n.message})]}):Object.keys(e||{}).length===0&&!t?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:K9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(hFi,{})]}):(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:K9}),actionRow:(0,K.jsxs)(TK,{children:[(0,K.jsx)(TK.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(MH,{...NH,onValueChange:i,label:`Search workflows`,placeholder:`Search by name or description`})})}),(0,K.jsx)(TK.End,{children:(0,K.jsx)(X,{render:(0,K.jsx)(Lv,{to:`/workflows/schedules`}),variant:`primary`,icon:(0,K.jsx)(qS,{}),children:`Schedules`})})]}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(EFi,{workflows:e||{},isLoading:t,search:r,sort:a,onSortChange:(e,t)=>o({key:t,direction:e})})]})}var OFi={active:`bg-success-indicator`,paused:`bg-info-indicator`,completed:`bg-muted-foreground`},kFi={active:`text-success-indicator`,paused:`text-info-indicator`,completed:`text-muted-foreground`},AFi=({status:e})=>(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-2 whitespace-nowrap`,children:[(0,K.jsx)(`span`,{className:`h-1.5 w-1.5 rounded-full ${OFi[e]}`,"aria-hidden":!0}),(0,K.jsx)(T,{as:`span`,variant:`caption`,className:kFi[e],children:e})]});function jFi({status:e}){let{icon:t,color:n}=MFi(e);return(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 whitespace-nowrap ${n}`,children:[(0,K.jsx)(`span`,{className:`inline-flex shrink-0 items-center`,"aria-hidden":!0,children:t}),(0,K.jsx)(T,{as:`span`,variant:`caption`,children:e})]})}function MFi(e){switch(e){case`success`:return{icon:(0,K.jsx)(pC,{className:`size-icon-sm`}),color:`text-success-indicator`};case`failed`:return{icon:(0,K.jsx)(xw,{className:`size-icon-sm`}),color:`text-destructive-foreground`};case`running`:return{icon:(0,K.jsx)(It,{}),color:`text-muted-foreground`};case`suspended`:return{icon:(0,K.jsx)(ET,{className:`size-icon-sm`}),color:`text-info-indicator`};case`canceled`:return{icon:(0,K.jsx)(Kx,{className:`size-icon-sm`}),color:`text-muted-foreground`};case`pending`:case`waiting`:return{icon:(0,K.jsx)(tC,{className:`size-icon-sm`}),color:`text-muted-foreground`};default:return{icon:null,color:`text-muted-foreground`}}}var NFi=`auto auto auto auto 1fr`,PFi=3e4,FFi=3e5;function IFi({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:i,setEndOfListElement:a}){let{Link:o,paths:s}=sn(),c=e=>!!(n&&e.runId&&e.outcome!==`failed`),l=e.filter(c).length,{containerRef:u,getRowProps:d}=PZ({count:l}),f=-1;return t?(0,K.jsx)(DH,{columns:NFi}):e.length===0?(0,K.jsx)(T,{variant:`body`,tone:`muted`,className:`p-4`,children:`No trigger history yet.`}):(0,K.jsxs)(Z,{columns:NFi,className:`min-w-0`,scrollRef:u,children:[(0,K.jsxs)(Z.Top,{children:[(0,K.jsx)(Z.TopCell,{children:`Run`}),(0,K.jsx)(Z.TopCell,{children:`Status`}),(0,K.jsx)(Z.TopCell,{children:`Started`}),(0,K.jsx)(Z.TopCell,{children:`Duration`}),(0,K.jsx)(Z.TopCell,{children:` `})]}),e.map(e=>{let t=e.actualFireAt-e.scheduledFireAt,r=iC(t,{signed:!0}),i=e.outcome===`failed`,a=i?e.error:e.run?.error,l=Math.abs(t),u=!i&&l>PFi&&l<=FFi,p=`${e.scheduleId}-${e.runId}-${e.actualFireAt}`,m=c(e);m&&(f+=1);let h=(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,tone:m?`ink`:`muted`,className:`whitespace-nowrap`,children:e.runId}),g=(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Z.Cell,{children:h}),(0,K.jsx)(Z.Cell,{children:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[i?(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`inline-flex items-center gap-1.5 whitespace-nowrap text-destructive-foreground`,children:[(0,K.jsx)(Zx,{className:`size-icon-sm`}),`publish failed`]}):e.run?(0,K.jsx)(jFi,{status:e.run.status}):(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`inline-flex items-center gap-1.5 whitespace-nowrap`,children:`pending`}),a?(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{asChild:!0,children:(0,K.jsx)(`span`,{className:`inline-flex text-destructive-foreground`,children:(0,K.jsx)(Zx,{className:`size-icon-sm`})})}),(0,K.jsx)(Tx,{children:a})]}):null]})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-2 whitespace-nowrap`,children:[e.actualFireAt?(0,K.jsx)(Dk,{value:e.actualFireAt}):`—`,u?(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{asChild:!0,children:(0,K.jsx)(`span`,{className:`inline-flex text-info-indicator`,children:(0,K.jsx)(Zx,{className:`size-icon-sm`})})}),(0,K.jsxs)(Tx,{children:[`Published `,r,` after the scheduled fire time`]})]}):null]})}),(0,K.jsx)(Z.Cell,{children:e.run?(0,K.jsx)(T,{as:`span`,variant:`body-sm`,font:`mono`,children:iC(e.run.durationMs)||`—`}):(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`—`})}),(0,K.jsx)(Z.Cell,{children:` `})]});return m?(0,K.jsx)(Z.RowLink,{to:s.workflowRunLink(n,e.runId),LinkComponent:o,...d(f),children:g},p):(0,K.jsx)(Z.RowStatic,{children:g},p)}),(0,K.jsx)(Z.NextPageLoading,{isLoading:i,hasMore:r,setEndOfListElement:a})]})}var LFi={id:`workflow-schedules`,label:`Schedules`,icon:qS,to:`/workflows/schedules`};function RFi({label:e,children:t}){return(0,K.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,K.jsx)(T,{variant:`meta`,tone:`muted`,className:`uppercase`,children:e}),(0,K.jsx)(`div`,{children:(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:t})})]})}function zFi(){let{scheduleId:e}=kv(),t=[eP(`/workflows`),LFi,{id:`schedule`,label:Zjt(e),icon:qS}],{paths:n}=sn(),{data:r,error:i}=vMt({scheduleId:e,queryOptions:{enabled:!!e}}),{data:a,isLoading:o,error:s,hasNextPage:c,isFetchingNextPage:l,setEndOfListElement:u}=xMt({scheduleId:e,queryOptions:{enabled:!!e}}),d=SMt({scheduleId:e});if(i&&FN(i))return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(TH,{variant:`fill`})]});if(i&&IN(i))return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(wH,{variant:`fill`,resource:`schedules`})]});if(i)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load schedule`,descriptionSlot:i.message})]});let f=r?.workflowId,p=r?.agentId;return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:t}),actionRow:(0,K.jsx)(TK,{children:(0,K.jsxs)(TK.End,{children:[(0,K.jsx)(X,{render:(0,K.jsx)(Lv,{to:n.schedulesLink()}),variant:`ghost`,icon:(0,K.jsx)(sS,{}),children:`Back to schedules`}),f?(0,K.jsx)(X,{icon:(0,K.jsx)(ZS,{}),render:(0,K.jsx)(Lv,{to:n.workflowLink(f)}),variant:`ghost`,children:`Open workflow`}):null,r&&r.status!==`completed`?(0,K.jsx)(X,{onClick:()=>{let e=r.status===`active`?`pause`:`resume`;d.mutate(e,{onSuccess:()=>iS.success(e===`pause`?`Schedule paused`:`Schedule resumed`),onError:e=>iS.error(e.message)})},disabled:d.isPending,"data-testid":`schedule-toggle-button`,children:r.status===`active`?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(ET,{}),`Pause`]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(DT,{}),`Resume`]})}):null]})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),r?(0,K.jsxs)(`div`,{className:`grid h-full grid-cols-[minmax(0,20rem)_1fr] gap-4 overflow-hidden`,children:[(0,K.jsxs)(`div`,{className:`flex h-fit flex-col gap-4 rounded-md border border-border p-4`,children:[(0,K.jsx)(RFi,{label:p?`Agent`:`Workflow`,children:f?(0,K.jsx)(Lv,{to:n.workflowLink(f),className:`text-foreground hover:underline`,children:f}):p?(0,K.jsx)(Lv,{to:n.agentLink(p),className:`text-foreground hover:underline`,children:p}):`—`}),(0,K.jsxs)(RFi,{label:r.cron?`Cron`:`Runs at`,children:[(0,K.jsx)(T,{as:`span`,variant:`body`,font:`mono`,children:r.cron??(r.runAt?new Date(r.runAt).toLocaleString():`—`)}),r.endAt?(0,K.jsxs)(`span`,{className:`ml-2 text-caption text-muted-foreground`,children:[`until `,new Date(r.endAt).toLocaleString()]}):null,r.timezone?(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`ml-2`,children:r.timezone}):null]}),(0,K.jsx)(RFi,{label:`Status`,children:(0,K.jsx)(AFi,{status:r.status})}),(0,K.jsx)(RFi,{label:`Next fire`,children:r.nextFireAt?(0,K.jsx)(Dk,{value:r.nextFireAt}):`—`})]}),(0,K.jsxs)(`div`,{className:`overflow-y-auto`,"data-testid":`schedule-triggers-panel`,children:[(0,K.jsx)(T,{variant:`body`,className:`mb-3`,children:`Trigger history`}),s?(0,K.jsx)(Jx,{tone:`error`,titleSlot:`Failed to load trigger history`,descriptionSlot:s.message}):(0,K.jsx)(IFi,{triggers:a??[],isLoading:o,workflowId:f,hasNextPage:c,isFetchingNextPage:l,setEndOfListElement:u})]})]}):null]})}var BFi={target:e=>e.workflowId??e.agentId??``,status:e=>e.status,nextFireAt:e=>e.nextFireAt,lastFireAt:e=>e.lastFireAt},VFi=`minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto`;function HFi({schedules:e,isLoading:t,search:n=``,sort:r,onSortChange:i}){let{paths:a,Link:o}=sn(),s=(0,G.useMemo)(()=>{let t=n.toLowerCase();return IZ(t?e.filter(e=>e.id.toLowerCase().includes(t)||(e.workflowId??e.agentId??``).toLowerCase().includes(t)):e,r,BFi)},[e,n,r]),{containerRef:c,getRowProps:l}=PZ({count:s.length,global:!0});if(t)return(0,K.jsx)(DH,{columns:VFi});let u=(e,t)=>i?(0,K.jsx)(Z.SortableTopCell,{sortKey:e,sort:r?.key===e?r.direction:void 0,onSortChange:i,children:t}):(0,K.jsx)(Z.TopCell,{children:t});return(0,K.jsxs)(Z,{columns:VFi,className:`min-w-0`,scrollRef:c,children:[(0,K.jsxs)(Z.Top,{children:[u(`target`,`Target`),(0,K.jsx)(Z.TopCell,{children:`Schedule ID`}),(0,K.jsx)(Z.TopCell,{children:`Cron`}),u(`status`,`Status`),u(`nextFireAt`,`Next fire`),u(`lastFireAt`,`Last run`)]}),s.length===0&&n?(0,K.jsx)(Z.NoMatch,{message:`No schedules match your search`}):null,s.length===0&&!n?(0,K.jsx)(Z.NoMatch,{message:`No schedules configured`}):null,s.map((e,t)=>(0,K.jsxs)(Z.RowLink,{to:a.scheduleLink(e.id),LinkComponent:o,...l(t),children:[(0,K.jsx)(Z.NameCell,{children:e.workflowId??e.agentId}),(0,K.jsx)(Z.Cell,{className:`min-w-0`,children:(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`muted`,font:`mono`,className:`block truncate`,title:e.id,children:e.id})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-2 whitespace-nowrap`,children:[(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,children:e.cron??(e.runAt?`once @ ${new Date(e.runAt).toLocaleString()}`:`—`)}),e.timezone?(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:e.timezone}):null]})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(AFi,{status:e.status})}),(0,K.jsx)(Z.Cell,{children:e.nextFireAt?(0,K.jsx)(Dk,{value:e.nextFireAt}):`—`}),(0,K.jsx)(Z.Cell,{children:e.lastRun?(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-2 whitespace-nowrap`,children:[(0,K.jsx)(jFi,{status:e.lastRun.status}),e.lastFireAt?(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:(0,K.jsx)(Dk,{value:e.lastFireAt})}):null]}):e.lastFireAt?(0,K.jsx)(Dk,{value:e.lastFireAt}):(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`Never`})})]},e.id))]})}function UFi({workflowId:e}={}){let{data:t,isLoading:n,error:r}=yMt(e?{workflowId:e}:{}),[i,a]=(0,G.useState)(``),[o,s]=(0,G.useState)();return r?(0,K.jsx)(Jx,{tone:`error`,titleSlot:`Failed to load schedules`,descriptionSlot:r.message}):(0,K.jsxs)(`div`,{className:`grid h-full grid-rows-[auto_1fr] gap-4 overflow-hidden`,children:[(0,K.jsx)(`div`,{className:`max-w-120`,children:(0,K.jsx)(MH,{...NH,onValueChange:a,label:`Search schedules`,placeholder:`Search by id or workflow`})}),(0,K.jsx)(`div`,{className:`overflow-y-auto`,children:(0,K.jsx)(HFi,{schedules:t??[],isLoading:n,search:i,sort:o,onSortChange:(e,t)=>s({key:t,direction:e})})})]})}var WFi=[eP(`/workflows`),LFi];function GFi(){let[e]=Rv(),t=e.get(`workflowId`)??void 0,{error:n}=yMt(t?{workflowId:t}:{});return n&&FN(n)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:WFi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(TH,{variant:`fill`})]}):n&&IN(n)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:WFi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(wH,{variant:`fill`,resource:`schedules`})]}):(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:WFi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(`div`,{className:`h-full`,children:(0,K.jsx)(UFi,{workflowId:t})})]})}var KFi=U(`IconArrowDownLeft`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M6 9V18H15`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M17.75 6.25L7 17`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),3),qFi={"--belt-hue":`var(--warning-indicator)`};function JFi(e){let t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function YFi(e,t){if(e&&typeof e==`object`&&!Array.isArray(e)){let t=Object.keys(e),[n]=t;if(t.length===1&&n)return n}return t}function XFi({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:(0,K.jsxs)(`section`,{className:c(REt,`pointer-events-auto relative isolate`),"data-testid":`workflow-suspended-steps`,"aria-label":`Step suspended`,children:[(0,K.jsxs)(`div`,{className:`max-h-[calc(100cqh-64px)] overflow-y-auto overscroll-contain rounded-[inherit]`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-3 border-b border-border bg-background px-5 py-4`,children:[(0,K.jsxs)(T,{as:`h2`,variant:`column`,tone:`ink`,className:`flex items-center gap-2`,children:[(0,K.jsx)(Dx,{children:(0,K.jsx)(ET,{})}),`Step suspended`]}),(0,K.jsx)(eC,{variant:`orange`,emphasis:`subtle`,children:`Needs input`})]}),e.map(e=>{let n=t.allSteps[e.stepId];if(!n||n.isWorkflow)return null;let i=n?.resumeSchema?zO(nk(n.resumeSchema)):Ad(q(),md());return(0,K.jsx)(ZFi,{step:e,stepSchema:i,description:n.description,onResume:r},`${e.runId}-${e.stepId}`)})]}),(0,K.jsx)(kXe,{status:`ready`,label:`Needs input`,className:`before:hidden`,style:qFi})]})}function ZFi({step:e,stepSchema:t,description:n,onResume:r}){let[i,a]=(0,G.useState)(!1),[o,s]=(0,G.useState)(!1);return(0,K.jsxs)(`div`,{className:`space-y-5 p-5 [&+&]:border-t [&+&]:border-border`,children:[(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(T,{as:`p`,variant:`subheading`,tone:`ink`,className:`break-words`,children:e.stepId}),n&&(0,K.jsx)(T,{as:`p`,variant:`caption`,tone:`muted`,children:n})]}),e.suspendPayload!==void 0&&(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsxs)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`flex items-center gap-2`,children:[(0,K.jsx)(Dx,{children:(0,K.jsx)(KFi,{})}),`The step is asking`]}),(0,K.jsxs)(DC,{open:i,onOpenChange:a,children:[(0,K.jsxs)(OC,{className:c(`bg-card hover:bg-card active:bg-card shadow-raised [--field:var(--field-on-surface)] [--field-disabled:var(--field-on-surface)] [--field-rim:var(--field-rim-on-surface)]`,`flex w-full items-center justify-between gap-2 rounded-lg px-3 py-2.5`),children:[(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(Dx,{children:(0,K.jsx)(y,{direction:`right`,className:`text-muted-foreground`})}),(0,K.jsx)(T,{as:`span`,variant:`body`,tone:`ink`,className:`truncate`,children:YFi(e.suspendPayload,e.stepId)})]}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`shrink-0`,children:JFi(e.suspendPayload)})]}),(0,K.jsx)(kC,{children:(0,K.jsx)(`div`,{"data-testid":`suspended-payload`,className:`pt-2`,children:(0,K.jsx)(bw,{value:JSON.stringify(e.suspendPayload,null,2),editable:!1,className:`w-full overflow-x-auto p-2`,showCopyButton:!1})})})]})]}),(0,K.jsxs)(`div`,{className:`space-y-3`,children:[(0,K.jsxs)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`flex items-center gap-2`,children:[(0,K.jsx)(Dx,{children:(0,K.jsx)(R4,{})}),`Your response`]}),(0,K.jsx)(`div`,{className:`-mx-5`,children:(0,K.jsx)(eEt,{schema:t,isSubmitLoading:o,submitButtonLabel:`Resume`,submitButtonVariant:`primary`,submitButtonIcon:(0,K.jsx)(DT,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:async t=>{s(!0);try{await r({stepId:e.stepId.split(`.`),runId:e.runId,resumeData:t})}catch(e){iS.error(e instanceof Error?e.message:`Error resuming workflow`)}finally{s(!1)}}})})]})]})}function QFi({hidden:e,requestContext:t,canResume:n}){let{result:r,workflow:i,runId:a,isStreamingWorkflow:o}=(0,G.useContext)(WS),s=Gft(r,a),c=Xft(t),l=r?.status===`suspended`&&s.length>0&&!o;return!i||!l||!n?null:(0,K.jsx)(`div`,{hidden:e,"data-testid":`workflow-suspended-overlay`,className:`pointer-events-none absolute top-12 right-2 z-30 w-95 max-w-[calc(100%-16px)] animate-in duration-300 fade-in-0 slide-in-from-top-2 motion-reduce:animate-none`,children:(0,K.jsx)(XFi,{suspendedSteps:s,workflow:i,isStreaming:o,onResume:c})},a)}var $Fi=U(`IconSkip`,()=>(0,K.jsx)(`path`,{d:`M19 5V19M6.52732 5.16646L15.5625 11.1835C16.1458 11.5719 16.1458 12.4281 15.5625 12.8165L6.52732 18.8335C5.87447 19.2683 5 18.8008 5 18.017V5.98298C5 5.1992 5.87447 4.7317 6.52732 5.16646Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})),eIi={success:{label:`Completed`,icon:pC},failed:{label:`Failed`,icon:qx},suspended:{label:`Needs input`,icon:ET},waiting:{label:`Waiting`,icon:XS},paused:{label:`Paused`,icon:ET},skipped:{label:`Skipped`,icon:$Fi},running:{label:`Running`,icon:TT},canceled:{label:`Canceled`,icon:Kx}},tIi={label:`Status unavailable`,icon:Lq};function nIi({row:e,isSelected:t,isHovered:n,onSelectStep:r,onHoverStep:i,onOpenInput:a,onOpenOutput:o}){let s=Object.hasOwn(eIi,e.status)?eIi[e.status]:tIi,l=s.icon,u=Fmt(e.status),d=e.stepId.slice(0,e.stepId.lastIndexOf(`.`)),f=e.isNestedEntry?e.stepId.slice(e.stepId.lastIndexOf(`.`)+1):e.stepId;return(0,K.jsxs)(`div`,{"data-testid":`workflow-timeline-row`,"data-workflow-step-key":e.stepId,onMouseEnter:()=>!e.isNestedEntry&&i(e.stepId),onMouseLeave:()=>!e.isNestedEntry&&i(null),className:c(`grid grid-cols-[minmax(130px,1fr)_minmax(64px,1fr)_56px_64px] items-center gap-3 rounded-md px-2 py-1`,`@max-[540px]/workflow-timeline:grid-cols-[minmax(0,1fr)_48px_64px] @max-[540px]/workflow-timeline:gap-x-1.5 @max-[540px]/workflow-timeline:gap-y-1 @max-[540px]/workflow-timeline:py-2`,(t||n)&&`bg-fill-subtle`),children:[(0,K.jsxs)(`button`,{type:`button`,"aria-disabled":e.isNestedEntry,"aria-pressed":t,onClick:()=>{e.isNestedEntry||r(e.stepId)},title:e.stepId,className:c(`text-foreground`,`flex min-h-9 min-w-0 cursor-pointer items-center gap-2.5 text-left focus-visible:rounded-sm aria-disabled:cursor-default`,p),children:[(0,K.jsx)(`span`,{"aria-label":s.label,className:c(`grid size-6 flex-none place-items-center rounded-md border border-border bg-background`,Imt[u]),children:(0,K.jsx)(l,{"aria-hidden":!0,className:c(`size-3.5`,e.status===`running`&&`motion-safe:animate-spin`)})}),(0,K.jsxs)(`span`,{className:`min-w-0`,children:[(0,K.jsx)(T,{as:`span`,variant:`meta`,className:`block truncate`,children:f}),e.isNestedEntry&&(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`flex min-w-0 items-center gap-1`,children:[(0,K.jsx)(XYe,{"aria-hidden":!0,className:`size-icon-xs shrink-0`}),(0,K.jsx)(`span`,{className:`truncate`,children:d})]})]})]}),(0,K.jsx)(`div`,{className:`relative h-5 min-w-0 overflow-hidden rounded-sm bg-muted @max-[540px]/workflow-timeline:col-span-full @max-[540px]/workflow-timeline:row-start-2 @max-[540px]/workflow-timeline:ml-[34px]`,"aria-hidden":!0,children:e.timing&&(0,K.jsx)(`div`,{"data-testid":`workflow-timeline-bar`,"data-offset":e.timing.offsetPct,"data-width":e.timing.widthPct,className:c(`absolute top-0 h-full min-w-0.5 rounded-sm`,Lmt[u]),style:{left:`${e.timing.offsetPct}%`,width:`${e.timing.widthPct}%`}})}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`text-right whitespace-nowrap`,title:e.timing&&e.spansSuspension?`Includes time spent suspended waiting for input`:void 0,children:e.timing?(0,K.jsx)(T,{as:`span`,variant:`meta`,font:`mono`,children:iC(e.timing.durationMs)}):(0,K.jsx)(`span`,{"aria-label":`Timing unavailable`,children:`—`})}),(0,K.jsxs)(`div`,{className:`flex items-center`,children:[(0,K.jsx)(X,{type:`button`,variant:`ghost`,size:`icon-sm`,tooltip:`View step input`,disabled:e.step.input===void 0,onClick:t=>a(e,t.currentTarget),children:(0,K.jsx)(bk,{})}),(0,K.jsx)(X,{type:`button`,variant:`ghost`,size:`icon-sm`,tooltip:`View step output`,disabled:e.step.output===void 0,onClick:t=>o(e,t.currentTarget),children:(0,K.jsx)(yk,{})})]})]})}var rIi=e=>e.includes(`.`),iIi=e=>e===`input`||e.endsWith(`.input`),aIi=1;function oIi(e,t){let n=Bmt(e),r=n?.isLive?Math.max(t,n.start):n?.end;return{span:n&&r!==void 0?{start:n.start,end:r}:void 0,isLive:n?.isLive??!1,spansSuspension:n?.spansSuspension??!1}}function sIi(e,t){let n=Object.entries(e).filter(([e])=>!iIi(e)).map(([e,n])=>({stepId:e,step:n,...oIi(n,t)})).sort((e,t)=>(e.span?.start??1/0)-(t.span?.start??1/0)||e.stepId.localeCompare(t.stepId)),r=n.flatMap(e=>e.span?[e.span]:[]),i=Math.min(...r.map(e=>e.start)),a=Math.max(i,...r.map(e=>e.end)),o=Math.max(a-i,1);return n.map(({stepId:e,step:t,span:n,isLive:r,spansSuspension:a})=>{let s;if(n){let e=n.end-n.start,t=Math.min((n.start-i)/o*100,99);s={durationMs:e,offsetPct:t,widthPct:Math.min(Math.max(e/o*100,aIi),100-t)}}return{stepId:e,step:t,status:wk(t)?`suspended`:t.status,timing:s,spansSuspension:a,isRunning:r,isNestedEntry:rIi(e)}})}var cIi=U(`IconChevronGrabberVertical`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M8 8.99985L11.2929 5.70696C11.6834 5.31643 12.3166 5.31643 12.7071 5.70696L16 8.99985`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M8 15L11.2929 18.2929C11.6834 18.6834 12.3166 18.6834 12.7071 18.2929L16 15`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]})),lIi=U(`IconChevronGrabberVerticalToward`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M8 18.75L12 14.75L16 18.75`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M8 5.25L12 9.25L16 5.25`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}));function uIi(){let{steps:e}=e$(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:i}=US(),[a,o]=(0,G.useState)(()=>Date.now()),[s,l]=(0,G.useState)(!0),[u,d]=(0,G.useState)(!1),{showData:f}=nN(),p=(0,G.useRef)(null),m=sIi(e,a),h=m.some(e=>e.isRunning);return iJe(p,{enabled:h&&!s}),(0,G.useEffect)(()=>{if(!h||s)return;let e=setInterval(()=>o(Date.now()),100);return()=>clearInterval(e)},[h,s]),m.length===0?null:(0,K.jsx)(`div`,{"data-testid":`workflow-timeline`,className:`relative z-20 shrink-0 px-2 pb-2`,children:(0,K.jsxs)(DC,{open:!s,onOpenChange:e=>l(!e),className:c(Bv,`@container/workflow-timeline pointer-events-auto overflow-hidden rounded-xl`),children:[(0,K.jsxs)(`div`,{className:`flex items-center`,children:[(0,K.jsxs)(OC,{className:`flex min-h-11 min-w-0 flex-1 items-center gap-2 px-3.5 py-2.5 text-caption text-foreground hover:bg-fill-subtle`,"aria-label":s?`Expand timeline`:`Collapse timeline`,children:[(0,K.jsx)(`span`,{children:(0,K.jsx)(YV,{"aria-hidden":!0,className:`size-icon-md text-muted-foreground`})}),(0,K.jsx)(`span`,{children:`Timeline`}),(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,children:[m.length,` events`]}),(0,K.jsx)(`span`,{className:`ml-auto`,children:(0,K.jsx)(y,{direction:`right`,className:`size-4`})})]}),!s&&(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:u?`Restore timeline height`:`Enlarge timeline`,"aria-pressed":u,onClick:()=>d(!u),className:`mr-2 shrink-0`,children:u?(0,K.jsx)(lIi,{}):(0,K.jsx)(cIi,{})})]}),(0,K.jsx)(kC,{children:(0,K.jsx)(`div`,{ref:p,"data-testid":`workflow-timeline-list`,className:c(`overflow-auto overscroll-contain px-1.5 pb-1.5`,u?`max-h-[min(720px,calc(100dvh-112px))]`:`max-h-[min(320px,40dvh)]`),children:m.map(e=>(0,K.jsx)(nIi,{row:e,isSelected:t===e.stepId,isHovered:n===e.stepId,onSelectStep:r,onHoverStep:i,onOpenInput:(e,t)=>f({type:`step-input`,stepId:e.stepId},t),onOpenOutput:(e,t)=>f({type:`step-output`,stepId:e.stepId},t)},e.stepId))})})]})})}var dIi=({workflowId:e,workflow:t,isLoading:n})=>{let[r]=HS(`workflow`,e),{canExecute:i,isLoading:a}=fS(),{stepDetail:o}=nN(),s=Zw(),c=o?.type===`data`,l=(0,K.jsxs)(`div`,{className:`[container-type:size] relative h-full min-h-0`,children:[(0,K.jsx)(eur,{workflowId:e,workflow:t,isLoading:n,requestContext:r}),(0,K.jsx)(QFi,{hidden:c,requestContext:r,canResume:!a&&i(`workflows`)}),c&&(0,K.jsx)(`div`,{className:`pointer-events-auto absolute top-12 right-2 z-30 flex max-h-[calc(100cqh-64px)] w-[440px] max-w-[calc(100%-16px)] flex-col`,children:(0,K.jsx)(n$,{requestContext:r})}),(0,K.jsx)(`div`,{className:`pointer-events-none absolute right-0 bottom-0 left-[var(--workflow-left-panel-width,0px)] z-20`,children:(0,K.jsx)(uIi,{})})]});return s&&o&&!c?(0,K.jsx)(`div`,{className:`h-full min-h-0 overflow-hidden`,children:(0,K.jsx)(n$,{requestContext:r})}):(0,K.jsxs)(`div`,{className:`relative h-full min-h-0`,children:[l,(0,K.jsxs)(p6,{className:`pointer-events-none absolute inset-0 z-30 min-h-0 w-full min-w-0 p-2`,children:[(0,K.jsx)(f6,{id:`workflow-graph`,className:`pointer-events-none min-w-0`}),o&&!c&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(m6,{className:`pointer-events-auto`}),(0,K.jsx)(f6,{id:`workflow-step-detail`,minSize:300,maxSize:`60%`,defaultSize:420,className:`min-w-0`,children:(0,K.jsx)(`div`,{className:`pointer-events-auto h-full min-h-0 overflow-hidden rounded-studio-panel border border-border bg-background`,children:(0,K.jsx)(n$,{requestContext:r})})})]})]})]})},fIi=()=>{let{workflowId:e}=kv(),{data:t,isLoading:n,error:r}=tN({workflowId:e,requestContext:HS(`workflow`,e)[0],queryOptions:{enabled:!!e}});return r&&FN(r)?(0,K.jsx)(TH,{variant:`fill`}):r&&IN(r)?(0,K.jsx)(wH,{variant:`fill`,resource:`workflows`}):(0,K.jsx)(dIi,{workflowId:e,workflow:t??void 0,isLoading:n})};function pIi(){let{workflowId:e}=kv(),{error:t}=yMt(e?{workflowId:e}:{});if(!e)return null;let n;return n=t&&FN(t)?(0,K.jsx)(TH,{variant:`fill`}):t&&IN(t)?(0,K.jsx)(wH,{variant:`fill`,resource:`schedules`}):(0,K.jsx)(`div`,{className:`h-full`,children:(0,K.jsx)(UFi,{workflowId:e})}),(0,K.jsxs)(RS,{children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),n]})}function mIi(){let{workflowId:e}=kv();return e?(0,K.jsx)(Csi,{scopedEntityId:e,scopedEntityType:Dp.WORKFLOW_RUN}):null}var hIi=(0,G.createContext)(null);function q9(){let e=(0,G.useContext)(hIi);if(!e)throw Error(`Workspace components must be rendered inside <Workspace.Root>`);return e}var gIi=e=>e?.status;function _Ii(e,t){return FN(e)?`Your session has expired. Sign in again to continue.`:IN(e)?`You don't have permission to access this.`:LN(e)?`This path no longer exists.`:gIi(e)===501?`This workspace does not support this operation.`:t}function vIi({error:e,fallback:t,className:n}){return(0,K.jsx)(Sk,{variant:`destructive`,className:n,children:(0,K.jsx)(Sk.Message,{children:_Ii(e,t)})})}var yIi=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;function bIi(e){let t=yIi.exec(e);return t?{frontmatter:t[1]??``,body:e.slice(t[0].length)}:{frontmatter:null,body:e}}function xIi({content:e}){let{frontmatter:t,body:n}=bIi(e);return(0,K.jsxs)(K.Fragment,{children:[t!==null&&(0,K.jsx)(`div`,{"data-testid":`workspace-frontmatter`,className:`border-b border-border`,children:(0,K.jsx)(pJ,{code:t,lang:`yaml`,overflow:`wrap`,className:`rounded-none border-0 bg-transparent [&_pre]:p-4`})}),(0,K.jsx)(`div`,{className:`p-4`,children:(0,K.jsx)(xY,{children:n})})]})}function SIi(){let{activeFilePath:e}=q9();return e?(0,K.jsx)(T,{as:`span`,variant:`body-sm`,font:`mono`,tone:`muted`,className:`truncate`,"data-testid":`workspace-file-path`,children:e}):null}function CIi({path:e,content:t,mimeType:n}){return WFn(e,n)?(0,K.jsx)(`div`,{className:`flex justify-center p-4`,children:(0,K.jsx)(`img`,{src:`data:${n||`image/png`};base64,${t}`,alt:e.split(`/`).pop(),className:`max-w-full object-contain`})}):GFn(e,n)?(0,K.jsx)(`div`,{className:`flex justify-center p-4`,children:(0,K.jsx)(`video`,{controls:!0,"aria-label":e.split(`/`).pop(),className:`max-w-full`,children:(0,K.jsx)(`source`,{src:`data:${qFn(e,n)};base64,${t}`,type:qFn(e,n)})})}):JFn(e)?(0,K.jsx)(xIi,{content:t}):(0,K.jsx)(pJ,{code:t,lang:uXe(e),overflow:`scroll`,className:`rounded-none border-0 bg-transparent [&_pre]:p-4`})}function wIi({renderPreview:e}){let{workspaceId:t,activeFilePath:n}=q9(),{data:r,isLoading:i,error:a}=lIn({workspaceId:t,path:n,queryOptions:{enabled:!!n}});if(!n)return null;if(i)return(0,K.jsxs)(`div`,{"aria-busy":`true`,className:`flex flex-col gap-2 p-4`,children:[(0,K.jsx)(zS,{className:`h-4 w-1/2`}),(0,K.jsx)(zS,{className:`h-4 w-5/6`}),(0,K.jsx)(zS,{className:`h-4 w-2/3`})]});if(!r)return(0,K.jsx)(vIi,{error:a,fallback:`Could not load file.`,className:`m-4`});let o={path:n,content:r.content,mimeType:r.mimeType};return e?.(o)??(0,K.jsx)(CIi,{...o})}var TIi=(e,t)=>e===`.`?t:`${e}/${t}`,EIi=e=>e.split(`/`).slice(0,-1).map((e,t,n)=>n.slice(0,t+1).join(`/`)),DIi=e=>{let t=e.lastIndexOf(`/`);return t===-1?`.`:e.slice(0,t)};function OIi({labeled:e=!1}={}){let{workspaceId:t,onCreateDirectory:n,isReadOnly:r}=q9(),i=u_(),[a,o]=(0,G.useState)(!1),[s,c]=(0,G.useState)(``),[l,u]=(0,G.useState)(!1);if(!n||r(`.`))return null;let d=s.trim().replace(/^\.?\/+|\/+$/g,``),f=async()=>{if(d){u(!0);try{await n(d),await i.invalidateQueries({queryKey:[`workspace`,t,`fs`,`list`,DIi(d)]}),o(!1),c(``)}catch{}finally{u(!1)}}};return(0,K.jsxs)(K.Fragment,{children:[e?(0,K.jsx)(X,{variant:`ghost`,icon:(0,K.jsx)(P6,{}),onClick:()=>o(!0),children:`New folder`}):(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`New folder`,onClick:()=>o(!0),children:(0,K.jsx)(P6,{})}),(0,K.jsx)(nT,{open:a,onOpenChange:o,pending:l,children:(0,K.jsx)(rT,{size:`sm`,children:(0,K.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),f()},children:[(0,K.jsx)(iT,{children:(0,K.jsx)(sT,{children:`New folder`})}),(0,K.jsx)(oT,{children:(0,K.jsx)(Jj,{autoFocus:!0,"aria-label":`Folder path`,placeholder:`docs/guides`,value:s,onChange:e=>c(e.target.value)})}),(0,K.jsxs)(aT,{children:[(0,K.jsx)(lT,{children:`Cancel`}),(0,K.jsx)(X,{type:`submit`,variant:`primary`,disabled:!d||l,children:`Create`})]})]})})})]})}function kIi(e){return`${e.topSource}/${e.name}`}function AIi(e){let t=QFn(e.topSource,e.name);return t?`${t.owner}/${t.repo}/${e.name}`:null}function jIi({open:e,onOpenChange:t,workspaceId:n,onInstall:r,isInstalling:i,installedSkillIds:a=[],installedSkillNames:o=[],writableMounts:s,installedSkillPaths:l}){let[u,d]=(0,G.useState)(``),[f,p]=(0,G.useState)(null),[m,h]=(0,G.useState)(),g=s?.some(e=>e.path===m)?m:s?.[0]?.path,{data:_,isLoading:v}=XFn({workspaceId:n,queryOptions:{enabled:!!n}}),y=YFn({workspaceId:n}),b=(0,G.useMemo)(()=>f?.topSource?QFn(f.topSource,f.name):null,[f]),x=(0,G.useMemo)(()=>!b||!f?null:`https://skills.sh/${b.owner}/${b.repo}/${f.name}`,[b,f]),{data:S,isLoading:C}=ZFn({workspaceId:n,owner:b?.owner,repo:b?.repo,skillPath:f?.name,queryOptions:{enabled:!!n&&!!b&&!!f}}),w=cC(e=>{e.trim().length>=2&&y.mutate(e)},300),E=(0,G.useCallback)(e=>{d(e),w(e)},[w]),D=(0,G.useMemo)(()=>u.trim().length>=2?y.data?.skills??[]:_?.skills??[],[u,y.data,_]),O=y.isPending,k=u.trim().length>=2,A=(0,G.useMemo)(()=>{if(!f)return!1;let e=AIi(f);return!!(e&&a.includes(e)||o.includes(f.name))},[f,a,o]),j=(0,G.useCallback)(()=>{f&&b&&r({repository:`${b.owner}/${b.repo}`,skillName:f.name,mount:s&&s.length>1?g:void 0})},[f,b,r,s,g]),M=(0,G.useCallback)(e=>{e||(d(``),p(null),h(void 0)),t(e)},[t]);return(0,K.jsx)(nT,{open:e,onOpenChange:M,pending:i,children:(0,K.jsxs)(rT,{size:`xl`,className:`h-[80vh]`,children:[(0,K.jsxs)(iT,{children:[(0,K.jsx)(sT,{children:`Add Skill`}),(0,K.jsx)(cT,{children:`Search and install skills from the community registry`})]}),(0,K.jsxs)(oT,{layout:`fill`,children:[(0,K.jsx)(MH,{label:`Search skills`,placeholder:`Search skills`,value:u,onValueChange:E}),(0,K.jsxs)(`div`,{className:`flex min-h-0 flex-1 gap-4`,children:[(0,K.jsxs)(`div`,{className:`flex min-h-0 w-1/2 flex-col`,children:[(0,K.jsx)(T,{as:`p`,variant:`eyebrow`,tone:`muted`,className:`mb-2`,children:k?`Search Results`:`Popular Skills`}),(0,K.jsx)(LS,{className:`flex-1 rounded-lg border border-border`,children:(0,K.jsx)(IS,{className:!v&&!O&&D.length===0?`flex flex-col [&>div]:flex [&>div]:flex-1 [&>div]:flex-col`:void 0,children:v||O?(0,K.jsx)(`div`,{className:`flex items-center justify-center py-5`,children:(0,K.jsx)(It,{className:`text-muted-foreground`})}):D.length===0?(0,K.jsx)(Jx,{className:`flex-1`,titleSlot:k?`No skills found`:`No skills available`}):(0,K.jsx)(`div`,{className:`space-y-1 p-2`,children:D.map(e=>{let t=kIi(e),n=AIi(e),r=n&&a.includes(n)||o.includes(e.name),i=f?kIi(f):null;return(0,K.jsx)(`button`,{onClick:()=>p(e),className:c(`w-full rounded-md px-3 py-2 text-left`,`hover:bg-fill-subtle`,i===t&&`border border-border-strong bg-fill-hover`),children:(0,K.jsxs)(`div`,{className:`flex items-start justify-between gap-2`,children:[(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(T,{as:`span`,variant:`subheading`,tone:`ink`,className:`truncate`,children:e.name}),r&&(0,K.jsxs)(T,{as:`span`,variant:`meta`,className:`inline-flex items-center gap-1 rounded bg-info-subtle px-1.5 py-0.5 text-info-subtle-foreground`,children:[(0,K.jsx)(pC,{className:`size-icon-xs`}),`Installed`]})]}),(0,K.jsx)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`truncate`,children:e.topSource})]}),(0,K.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 text-muted-foreground`,children:[(0,K.jsx)(fJ,{className:`size-icon-xs`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,children:e.installs.toLocaleString()})]})]})},t)})})})})]}),(0,K.jsxs)(`div`,{className:`flex min-h-0 w-1/2 flex-col`,children:[(0,K.jsx)(T,{as:`p`,variant:`eyebrow`,tone:`muted`,className:`mb-2`,children:`Preview`}),(0,K.jsx)(`div`,{className:`flex flex-1 flex-col overflow-hidden rounded-lg border border-border`,children:f?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`border-b border-border bg-card p-4`,children:(0,K.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,K.jsx)(`div`,{className:`rounded-lg bg-muted p-2`,children:(0,K.jsx)(AZ,{className:`size-icon-lg text-muted-foreground`})}),(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsx)(T,{as:`h3`,variant:`subheading`,tone:`ink`,className:`truncate`,children:f.name}),(0,K.jsxs)(`div`,{className:`mt-1 flex items-center gap-3 text-muted-foreground`,children:[(0,K.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(kZ,{className:`size-icon-xs`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`block`,children:f.topSource})]}),(0,K.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(fJ,{className:`size-icon-xs`}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[f.installs.toLocaleString(),` installs`]})]})]})]}),b&&(0,K.jsx)(`a`,{href:`https://github.com/${b.owner}/${b.repo}`,target:`_blank`,rel:`noopener noreferrer`,className:c(`text-muted-foreground hover:text-foreground`,`transition-[color] duration-fast ease-out-custom motion-reduce:transition-none`),title:`View on GitHub`,children:(0,K.jsx)(tP,{className:`size-icon-md`})})]})}),C?(0,K.jsx)(`div`,{className:`flex flex-1 items-center justify-center`,children:(0,K.jsx)(It,{className:`text-muted-foreground`})}):S?(0,K.jsx)(LS,{className:`flex-1`,children:(0,K.jsx)(`div`,{className:`p-4`,children:(0,K.jsx)(xY,{children:S})})}):(0,K.jsx)(Jx,{className:`flex-1`,iconSlot:(0,K.jsx)(OZ,{}),titleSlot:`Preview unavailable`,actionSlot:x&&(0,K.jsxs)(`a`,{href:x,target:`_blank`,rel:`noopener noreferrer`,className:`flex items-center gap-1 text-info-indicator hover:underline`,children:[(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[`View on skills.sh`,` `]}),(0,K.jsx)(tP,{className:`size-icon-xs`})]})})]}):(0,K.jsx)(Jx,{variant:`fill`,iconSlot:(0,K.jsx)(OZ,{}),titleSlot:`Select a skill to preview`})})]})]}),f&&s&&s.length>1&&(0,K.jsxs)(ak,{orientation:`horizontal`,className:c(`bg-card hover:bg-card active:bg-card shadow-raised [--field:var(--field-on-surface)] [--field-disabled:var(--field-on-surface)] [--field-rim:var(--field-rim-on-surface)]`,`gap-3 rounded-lg p-3`),children:[(0,K.jsx)($N,{className:`size-icon-md shrink-0 text-muted-foreground`}),(0,K.jsx)(sk,{className:`whitespace-nowrap`,children:`Install to`}),(0,K.jsxs)(Bk,{value:g,onValueChange:h,children:[(0,K.jsx)(Hk,{className:`flex-1`,children:(0,K.jsx)(Vk,{})}),(0,K.jsx)(Uk,{children:s.map(e=>{let t=e.displayName??e.name??e.provider??`unknown`;return(0,K.jsxs)(Wk,{value:e.path,children:[t,` (`,e.path,`)`]},e.path)})})]})]})]}),f&&(0,K.jsxs)(aT,{children:[A&&s&&s.length>1&&(()=>{let e=l?.[f.name];if(!e)return null;let t=s.find(t=>e.startsWith(t.path+`/`)||e===t.path);return t?(0,K.jsxs)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`mr-auto`,children:[`Installed at `,t.path]}):null})(),(0,K.jsx)(lT,{children:`Cancel`}),(0,K.jsx)(tT,{onConfirm:j,disabled:!b||A,"data-testid":`install-skill-button`,children:i?`Installing...`:A?`Already installed`:`Install`})]})]})})}function MIi({labeled:e=!1}){let{workspaceId:t,addSkill:n}=q9(),[r,i]=(0,G.useState)(!1),[a,o]=(0,G.useState)(!1);if(!n)return null;let{onInstall:s,...c}=n,l=async e=>{o(!0);try{await s(e),i(!1)}catch{}finally{o(!1)}};return(0,K.jsxs)(K.Fragment,{children:[e?(0,K.jsxs)(X,{variant:`ghost`,onClick:()=>i(!0),children:[(0,K.jsx)(J5n,{}),`Add skill`]}):(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,"aria-label":`Add skill`,tooltip:`Add skill`,onClick:()=>i(!0),children:(0,K.jsx)(J5n,{})}),(0,K.jsx)(jIi,{...c,open:r,onOpenChange:i,workspaceId:t,onInstall:e=>void l(e),isInstalling:a})]})}function NIi({workspaceId:e,activeFilePath:t,onDelete:n,onCreateDirectory:r,onActiveFileChange:i,readOnlyPaths:a,searchFiles:o=!0,searchSkills:s=!0,fileCount:c,skillCount:l,addSkill:u,children:d}){let[f,p]=(0,G.useState)(!1),[m,h]=(0,G.useState)(``),[g,_]=(0,G.useState)(()=>new Set(EIi(t??``))),[v,y]=(0,G.useState)(t);if(t!==v){y(t);let e=EIi(t??``).filter(e=>!g.has(e));e.length>0&&_(new Set([...g,...e]))}let b=a?.join(`
|
|
725
725
|
`)??``,x=(0,G.useMemo)(()=>({workspaceId:e,activeFilePath:t,setActiveFilePath:i,isSearching:f,setSearching:e=>{p(e),e||h(``)},query:m,setQuery:h,onDelete:n,onCreateDirectory:r,isReadOnly:e=>(b?b.split(`
|
|
726
726
|
`):[]).some(t=>t===`.`||e===t||e.startsWith(`${t}/`)),searchFiles:o,searchSkills:s,fileCount:c,skillCount:l,addSkill:u,openFolders:g,setFolderOpen:(e,t)=>_(n=>{if(n.has(e)===t)return n;let r=new Set(n);return t?r.add(e):r.delete(e),r})}),[e,t,f,m,n,r,i,b,o,s,c,l,u,g]);return(0,K.jsx)(hIi.Provider,{value:x,children:d})}var PIi=e=>(0,K.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`-1 -1 18 18`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,...e,children:(0,K.jsx)(`path`,{d:`M9 1.5H4C3.44772 1.5 3 1.94772 3 2.5V13.5C3 14.0523 3.44772 14.5 4 14.5H12C12.5523 14.5 13 14.0523 13 13.5V5.5M9 1.5L13 5.5M9 1.5V5.5H13`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`})}),FIi=e=>(0,K.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`-1 -1 18 18`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,...e,children:(0,K.jsx)(`path`,{d:`M7.25 12.5C10.1495 12.5 12.5 10.1495 12.5 7.25C12.5 4.35051 10.1495 2 7.25 2C4.35051 2 2 4.35051 2 7.25C2 10.1495 4.35051 12.5 7.25 12.5ZM11 11L14 14`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`})});function IIi(){let{isSearching:e,setSearching:t,searchFiles:n,searchSkills:r}=q9();return!n&&!r?null:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`Search files and skills`,"aria-pressed":e,onClick:()=>t(!e),children:(0,K.jsx)(FIi,{})})}function LIi(){let{isSearching:e}=q9();return e?(0,K.jsx)(BIi,{}):(0,K.jsx)(zIi,{})}var RIi=(e,t)=>`${e} ${t}${e===1?``:`s`}`;function zIi(){let{fileCount:e,skillCount:t}=q9();return(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`muted`,className:`block min-w-0`,children:(0,K.jsxs)(AC,{singleLine:!0,children:[(0,K.jsx)(AC.Item,{children:e===void 0?`Files`:RIi(e,`File`)}),t===void 0?null:(0,K.jsx)(AC.Item,{children:RIi(t,`Skill`)})]})})}function BIi(){let{setSearching:e,setQuery:t}=q9(),[n,r]=(0,G.useState)(``),[,i]=(0,G.useTransition)();return(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(Jj,{type:`search`,size:`sm`,autoFocus:!0,"aria-label":`Search query`,placeholder:`Search files and skills`,value:n,onChange:e=>{let n=e.target.value;r(n),i(()=>t(n))},onKeyDown:t=>{t.key===`Escape`&&e(!1)}}),(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`Close search`,onClick:()=>e(!1),children:(0,K.jsx)(xw,{})})]})}function VIi(){let{workspaceId:e,query:t,activeFilePath:n,setActiveFilePath:r,searchFiles:i,searchSkills:a}=q9(),{data:o,isLoading:s,isError:l,error:u}=pIn({workspaceId:e,query:t,files:i,skills:a,queryOptions:{enabled:t.trim().length>0&&(i||a)}});return t.trim()?s?(0,K.jsxs)(`div`,{"aria-busy":`true`,className:`flex flex-col gap-2 p-2`,children:[(0,K.jsx)(zS,{className:`h-4 w-3/4`}),(0,K.jsx)(zS,{className:`h-4 w-2/3`})]}):l?(0,K.jsx)(vIi,{error:u,fallback:`Search failed.`,className:`m-2`}):o?.length?(0,K.jsx)(`ul`,{"aria-label":`Search results`,className:`flex flex-col py-1`,children:o.map(e=>(0,K.jsx)(`li`,{children:(0,K.jsxs)(`button`,{type:`button`,title:e.path,onClick:()=>r(e.path),className:c(`text-foreground`,`flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left hover:bg-fill-subtle`,n===e.path&&`bg-fill`),children:[(0,K.jsx)(Dx,{size:`sm`,children:e.kind===`skill`?(0,K.jsx)(AZ,{}):(0,K.jsx)(PIi,{})}),(0,K.jsx)(T,{as:`span`,variant:`body-sm`,className:`truncate`,children:e.label})]})},e.path))}):(0,K.jsx)(Jx,{titleSlot:`No results`}):(0,K.jsx)(Jx,{titleSlot:`Search files and skills`,descriptionSlot:`Type to find matching content.`})}function HIi({mount:e}){switch(e.icon||e.provider){case`aws-s3`:case`s3`:return(0,K.jsx)(dOn,{className:`text-foreground`});case`google-cloud`:case`google-cloud-storage`:case`gcs`:return(0,K.jsx)(gOn,{});case`azure-blob`:case`azure`:return(0,K.jsx)(mOn,{className:`text-badge-blue-indicator`});case`cloudflare`:case`cloudflare-r2`:case`r2`:return(0,K.jsx)(U6,{className:`text-badge-orange-indicator`});case`neon`:return(0,K.jsx)(U6,{className:`text-badge-green-indicator`});case`minio`:return(0,K.jsx)(hcr,{className:`text-badge-red-indicator`});case`database`:return(0,K.jsx)(uT,{className:`text-badge-green-indicator`});case`local`:case`folder`:return(0,K.jsx)($N,{className:`text-badge-amber-indicator`});case`hard-drive`:return(0,K.jsx)(hcr,{className:`text-muted-foreground`});default:return(0,K.jsx)(U6,{className:`text-muted-foreground`})}}var UIi=e=>(0,K.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`-1 -1 18 18`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,...e,children:(0,K.jsx)(`path`,{d:`M1.5 8.5V8C1.5 7.60218 1.65804 7.22064 1.93934 6.93934C2.22064 6.65804 2.60218 6.5 3 6.5H13C13.3978 6.5 13.7794 6.65804 14.0607 6.93934C14.342 7.22064 14.5 7.60218 14.5 8V8.5M8.70667 4.20667L7.29333 2.79333C7.20048 2.70037 7.09022 2.62661 6.96886 2.57628C6.84749 2.52595 6.71739 2.50003 6.586 2.5H3C2.60218 2.5 2.22064 2.65804 1.93934 2.93934C1.65804 3.22064 1.5 3.60218 1.5 4V12C1.5 12.3978 1.65804 12.7794 1.93934 13.0607C2.22064 13.342 2.60218 13.5 3 13.5H13C13.3978 13.5 13.7794 13.342 14.0607 13.0607C14.342 12.7794 14.5 12.3978 14.5 12V6C14.5 5.60218 14.342 5.22064 14.0607 4.93934C13.7794 4.65804 13.3978 4.5 13 4.5H9.414C9.14887 4.49977 8.89402 4.39426 8.70667 4.20667Z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`})}),WIi=e=>{let t=[`B`,`KB`,`MB`,`GB`,`TB`],n=e>0?Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1):0;return`${parseFloat((e/1024**n).toFixed(1))} ${t[n]}`};function GIi(){let{workspaceId:e,activeFilePath:t,setActiveFilePath:n}=q9(),{data:r,isLoading:i,error:a}=iJ({workspaceId:e,path:`.`}),[o,s]=(0,G.useState)(null);return i?(0,K.jsx)($Ii,{}):r?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(N6,{"aria-label":`Workspace files`,selectedId:t,onSelect:n,className:`py-1`,children:(0,K.jsx)(KIi,{entries:r,parent:`.`,onRequestDelete:s})}),(0,K.jsx)(QIi,{entry:o,onClose:()=>s(null)})]}):(0,K.jsx)(vIi,{error:a,fallback:`Could not load files.`,className:`m-2`})}function KIi({entries:e,parent:t,onRequestDelete:n}){return e.map(e=>{let r=TIi(t,e.name);return e.type===`directory`?(0,K.jsx)(YIi,{name:e.name,path:r,mount:e.mount,onRequestDelete:n},e.name):(0,K.jsx)(ZIi,{name:e.name,size:e.size,path:r,onRequestDelete:n},e.name)})}function qIi({children:e}){return(0,K.jsx)(`span`,{className:`ml-auto flex shrink-0 items-center gap-1 opacity-0 group-focus-within:opacity-100 group-hover:opacity-100`,children:e})}function JIi({name:e,onClick:t}){return(0,K.jsx)(X,{variant:`destructive-ghost`,size:`icon-sm`,tooltip:`Delete ${e}`,onClick:e=>{e.stopPropagation(),t()},onKeyDown:e=>e.stopPropagation(),children:(0,K.jsx)(Kj,{})})}function YIi({name:e,path:t,mount:n,onRequestDelete:r}){let{workspaceId:i,onDelete:a,onCreateDirectory:o,isReadOnly:s,openFolders:c,setFolderOpen:l}=q9(),u=c.has(t),{isLoading:d}=iJ({workspaceId:i,path:t,queryOptions:{enabled:u}}),[f,p]=(0,G.useState)(!1),m=a&&!s(t),h=o&&!s(t);return(0,K.jsxs)(N6.Folder,{id:t,open:u,onOpenChange:e=>l(t,e),children:[(0,K.jsxs)(N6.FolderTrigger,{actions:m||h?(0,K.jsxs)(qIi,{children:[h?(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`New folder in ${e}`,onClick:e=>{e.stopPropagation(),l(t,!0),p(!0)},onKeyDown:e=>e.stopPropagation(),children:(0,K.jsx)(P6,{})}):null,m?(0,K.jsx)(JIi,{name:e,onClick:()=>r({path:t,type:`directory`})}):null]}):void 0,children:[(0,K.jsx)(N6.Icon,{children:n?(0,K.jsx)(`span`,{role:`img`,"aria-label":`Mount: ${n.displayName??n.provider}`,title:[n.displayName??n.provider,n.description].filter(Boolean).join(`: `),className:`flex`,children:(0,K.jsx)(HIi,{mount:n})}):(0,K.jsx)(UIi,{})}),(0,K.jsx)(N6.Label,{children:e}),n?.status===`error`?(0,K.jsx)(`span`,{role:`img`,"aria-label":`Mount error: ${n.error??`unavailable`}`,title:n.error,className:`flex shrink-0`,children:(0,K.jsx)(Xx,{className:`size-icon-xs text-destructive-foreground`})}):null,n&&s(t)?(0,K.jsx)(`span`,{role:`img`,"aria-label":`Read-only`,title:`Read-only`,className:`flex shrink-0`,children:(0,K.jsx)(CH,{className:`size-icon-xs text-muted-foreground`})}):null,u&&d?(0,K.jsx)(`span`,{className:`flex shrink-0 animate-in delay-200 fill-mode-backwards fade-in`,children:(0,K.jsx)(It,{size:`sm`,"aria-label":`Loading ${e}`,className:`size-3 text-muted-foreground`})}):null]}),(0,K.jsx)(N6.FolderContent,{children:u?(0,K.jsx)(XIi,{path:t,creating:f,onCreated:()=>p(!1),onRequestDelete:r}):null})]})}function XIi({path:e,creating:t,onCreated:n,onRequestDelete:r}){let{workspaceId:i,onCreateDirectory:a}=q9(),o=u_(),{data:s,isLoading:c,error:l}=iJ({workspaceId:i,path:e}),u=async t=>{try{await a?.(TIi(e,t.replace(/^\/+|\/+$/g,``)))}catch{return}n(),await o.invalidateQueries({queryKey:[`workspace`,i,`fs`,`list`,e]})};return(0,K.jsxs)(K.Fragment,{children:[t?(0,K.jsx)(N6.Input,{type:`folder`,placeholder:`Folder name`,onSubmit:e=>void u(e),onCancel:n}):null,c?null:s?(0,K.jsx)(KIi,{entries:s,parent:e,onRequestDelete:r}):(0,K.jsx)(vIi,{error:l,fallback:`Could not load folder.`,className:`my-1 mr-1`})]})}function ZIi({name:e,size:t,path:n,onRequestDelete:r}){let{onDelete:i,isReadOnly:a,activeFilePath:o}=q9(),s=i&&!a(n),c=n===o,l=(0,G.useRef)(null);return(0,G.useEffect)(()=>{c&&l.current?.scrollIntoView?.({block:`nearest`})},[c]),(0,K.jsxs)(N6.File,{ref:l,id:n,children:[(0,K.jsx)(N6.Icon,{children:(0,K.jsx)(PIi,{})}),(0,K.jsx)(N6.Label,{children:e}),(0,K.jsxs)(qIi,{children:[t===void 0?null:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`faint`,font:`mono`,children:WIi(t)}),s?(0,K.jsx)(JIi,{name:e,onClick:()=>r({path:n,type:`file`})}):null]})]})}function QIi({entry:e,onClose:t}){let{workspaceId:n,activeFilePath:r,setActiveFilePath:i,onDelete:a}=q9(),o=u_(),[s,c]=(0,G.useState)(!1),l=e?.path.split(`/`).pop(),u=async()=>{if(e&&a){c(!0);try{await a(e)}catch{return}finally{c(!1)}(r===e.path||r?.startsWith(`${e.path}/`))&&i(void 0),o.removeQueries({queryKey:[`workspace`,n,`fs`,`list`,e.path]}),await o.invalidateQueries({queryKey:[`workspace`,n,`fs`,`list`,DIi(e.path)]}),t()}},d=null;return e&&(d=e.type===`directory`?`This permanently deletes the folder "${l}" and everything inside it.`:`This permanently deletes "${l}".`),(0,K.jsx)(QM,{open:e!==null,onOpenChange:e=>{!e&&!s&&t()},children:(0,K.jsxs)(QM.Content,{children:[(0,K.jsxs)(QM.Header,{children:[(0,K.jsxs)(QM.Title,{children:[`Delete `,e?.type===`directory`?`folder`:`file`,`?`]}),(0,K.jsxs)(QM.Description,{children:[d,` This action cannot be undone.`]})]}),(0,K.jsxs)(QM.Footer,{children:[(0,K.jsx)(QM.Cancel,{disabled:s,children:`Cancel`}),(0,K.jsx)(X,{variant:`destructive`,disabled:s,onClick:()=>void u(),children:s?`Deleting…`:`Delete`})]})]})})}function $Ii(){return(0,K.jsxs)(`div`,{"data-testid":`workspace-tree-skeleton`,"aria-busy":`true`,className:`flex flex-col gap-2 py-2 pl-[18px]`,children:[(0,K.jsx)(zS,{className:`h-4 w-3/4`}),(0,K.jsx)(zS,{className:`h-4 w-1/2`}),(0,K.jsx)(zS,{className:`h-4 w-2/3`})]})}function eLi({children:e,...t}){return(0,K.jsx)(NIi,{...t,children:(0,K.jsx)(tLi,{children:e})})}function tLi({children:e}){let{workspaceId:t}=q9(),{data:n,error:r}=iJ({workspaceId:t,path:`.`});return(n?n.length===0:LN(r))?(0,K.jsx)(Jx,{variant:`fill`,titleSlot:`This workspace is empty`,descriptionSlot:`Files written by your agents will show up here.`,actionSlot:(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:[(0,K.jsx)(OIi,{labeled:!0}),(0,K.jsx)(MIi,{labeled:!0})]})}):(0,K.jsx)(`div`,{className:`size-full overflow-hidden`,children:(0,K.jsx)(p6,{className:`size-full min-h-0 min-w-0`,orientation:`horizontal`,children:e})})}function nLi({children:e}){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(wWr,{direction:`left`,id:`workspace-aside`,minSize:200,maxSize:`50%`,defaultSize:`25%`,collapsible:!1,className:`min-w-0`,children:(0,K.jsx)(`div`,{className:`flex h-full min-h-0 flex-col`,children:e})}),(0,K.jsx)(m6,{className:`w-px bg-border`})]})}function rLi({children:e,actions:t}){let{isSearching:n}=q9();return(0,K.jsxs)(`div`,{className:`flex h-11 shrink-0 items-center gap-2 border-b border-border px-3`,children:[(0,K.jsx)(`div`,{className:`min-w-0 flex-1`,children:e}),t&&!n?(0,K.jsx)(`div`,{className:`flex shrink-0 items-center gap-1`,children:t}):null]})}function iLi(){let{isSearching:e}=q9();return(0,K.jsx)(LS,{className:`min-h-0 flex-1 px-2 py-1`,children:e?(0,K.jsx)(VIi,{}):(0,K.jsx)(GIi,{})})}function aLi({children:e}){return(0,K.jsx)(f6,{id:`workspace-active-file`,className:`flex min-w-0 flex-col`,minSize:30,children:e})}function oLi({children:e}){return(0,K.jsx)(`div`,{className:`flex h-11 shrink-0 items-center gap-2 border-b border-border px-4`,children:e})}function sLi({renderPreview:e}){let{activeFilePath:t}=q9();return t?(0,K.jsx)(LS,{className:`min-h-0 flex-1`,children:(0,K.jsx)(wIi,{renderPreview:e})}):(0,K.jsx)(Jx,{variant:`fill`,titleSlot:`Select a file`})}var J9={Root:eLi,Aside:nLi,AsideHeader:rLi,Search:LIi,SearchToggle:IIi,CreateDirectory:OIi,Tree:iLi,ActiveFile:aLi,ActiveFileHeader:oLi,FilePath:SIi,ActiveFileContent:sLi};function cLi({asideActions:e,renderPreview:t,...n}){return(0,K.jsxs)(J9.Root,{...n,children:[(0,K.jsxs)(J9.Aside,{children:[(0,K.jsx)(J9.AsideHeader,{actions:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(J9.SearchToggle,{}),(0,K.jsx)(J9.CreateDirectory,{}),(0,K.jsx)(MIi,{}),e]}),children:(0,K.jsx)(J9.Search,{})}),(0,K.jsx)(J9.Tree,{})]}),(0,K.jsxs)(J9.ActiveFile,{children:[(0,K.jsx)(J9.ActiveFileHeader,{children:(0,K.jsx)(J9.FilePath,{})}),(0,K.jsx)(J9.ActiveFileContent,{renderPreview:t})]})]})}var lLi=()=>(0,K.jsx)(Jx,{titleSlot:`No Workspaces yet`,descriptionSlot:(0,K.jsxs)(K.Fragment,{children:[`Add a workspace to your Mastra configuration to `,(0,K.jsx)(`br`,{}),`manage files, skills, and enable semantic search.`]}),actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/en/docs/workspace/overview`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(tP,{}),children:`Workspaces documentation`}),variant:`fill`}),uLi=()=>(0,K.jsx)(Jx,{titleSlot:`Workspace Not Configured`,descriptionSlot:(0,K.jsxs)(K.Fragment,{children:[`No workspace is configured. Add a workspace to your `,(0,K.jsx)(`br`,{}),`Mastra configuration to manage files, skills, and enable semantic search.`]}),actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/en/docs/workspace/overview`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(tP,{}),children:`Workspaces documentation`}),variant:`fill`}),dLi=()=>(0,K.jsx)(Jx,{titleSlot:`Workspace Not Supported`,descriptionSlot:(0,K.jsxs)(K.Fragment,{children:[`The workspace feature requires a newer version of `,(0,K.jsx)(`code`,{className:`text-foreground`,children:`@mastra/core`}),`.`,(0,K.jsx)(`br`,{}),`Please upgrade your dependencies to enable workspace functionality.`]}),actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/en/docs/workspace/overview`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(tP,{}),children:`Workspaces documentation`}),variant:`fill`}),fLi=`.agents/skills`,pLi=e=>e.replace(/^\.?\/+|\/+$/g,``);function mLi({workspaceId:e,showInitWarning:t,skills:n}){let{data:r}=iJ({workspaceId:e,path:fLi,queryOptions:{enabled:!!n}}),i=n&&r?r.filter(e=>e.type===`directory`&&!n.some(t=>t.name===e.name||pLi(t.path)===`${fLi}/${e.name}`)):[];return!t&&i.length===0?null:(0,K.jsxs)(`div`,{className:`flex shrink-0 flex-col gap-2 border-b border-border p-3`,children:[t&&(0,K.jsx)(Sk,{variant:`warning`,children:(0,K.jsxs)(Sk.Message,{children:[`File search requires `,(0,K.jsx)(`code`,{children:`workspace.init()`}),` to index files from your configured`,` `,(0,K.jsx)(`code`,{children:`autoIndexPaths`}),`.`]})}),i.length>0&&(0,K.jsx)(Sk,{variant:`warning`,title:`Skills installed but not discovered`,children:(0,K.jsxs)(Sk.Message,{children:[i.map(e=>e.name).join(`, `),` `,i.length===1?`is`:`are`,` in`,` `,(0,K.jsx)(`code`,{children:fLi}),` but not discovered. Add this path to your workspace skills configuration to see `,i.length===1?`it`:`them`,`.`]})})]})}var Y9=[eP(`/workspaces`)],hLi=e=>IN(e)?`you don't have permission to modify this workspace`:e instanceof Error?e.message:`Unknown error`;function gLi(){let{workspaceId:e}=kv(),[t,n]=Rv(),r=Ov(),i=u_(),a=t.get(`file`),{data:o,error:s,isLoading:c}=iIn(),l=o?.workspaces??[],u=e??l[0]?.id,{data:d,isLoading:f,error:p}=rIn({workspaceId:u,queryOptions:{enabled:!!u}}),m=FN(s)||FN(p),h=IN(s)||IN(p),g=zFn(s)||zFn(p),_=u?l.find(e=>e.id===u):void 0,v=e=>{let r=new URLSearchParams(t);for(let[t,n]of Object.entries(e))n===null?r.delete(t):r.set(t,n);n(r)},y=e=>{r(`/workspaces/${e}`)},b=e=>{v({file:e??null})},x=a??void 0,S=oIn(),C=sIn(),w=d?.isWorkspaceConfigured??!1,T=d?.capabilities?.hasDynamicFilesystem??!1,E=(d?.capabilities?.hasFilesystem??!1)&&!T,D=d?.capabilities?.hasSkills??!1,{data:O,refetch:k}=mIn({workspaceId:u,queryOptions:{enabled:!!u&&E}}),A=$Fn(),j=eIn(),M=tIn(),N=e=>{let t=/^\.agents\/skills\/([^/]+)$/.exec(e);if(t)return re.find(t=>t.path?.replace(/^\.?\/+|\/+$/g,``)===e)?.name??t[1]},P=async()=>{if(u)try{let e=await j.mutateAsync({workspaceId:u}),t=e.updated.filter(e=>!e.success);t.length>0?iS.error(`Failed to update ${t.map(e=>e.skillName).join(`, `)}`):iS.success(`${e.updated.length} skill(s) updated`),i.invalidateQueries({queryKey:[`workspace`,u,`fs`]})}catch(e){iS.error(`Failed to update skills: ${e instanceof Error?e.message:`Unknown error`}`)}},F=async({path:e,type:t})=>{if(!u)return;let n=t===`directory`?N(e):void 0;if(n)try{if(!(await M.mutateAsync({workspaceId:u,skillName:n})).success)throw Error(`Failed to remove skill "${n}"`);iS.success(`Skill "${n}" removed`),k()}catch(e){throw iS.error(e instanceof Error?e.message:`Failed to remove skill`),e}else try{await S.mutateAsync({path:e,recursive:!0,force:!0,workspaceId:u})}catch(t){throw iS.error(`Failed to delete ${e}: ${hLi(t)}`),t}},I=_?.safety?.readOnly??!1,{canEdit:L,canDelete:R,canExecute:z,isLoading:B}=fS(),V=!B&&L(`workspaces`)&&!I,H=!B&&R(`workspaces`)&&!I,ee=!B&&z(`workspaces`),te=E&&D&&V,U=d?.mounts,W=U?.filter(e=>!e.readOnly).map(e=>({path:e.path,displayName:e.displayName,icon:e.icon,provider:e.provider,name:e.name})),ne=async e=>{if(u)try{let t=await A.mutateAsync({...e,workspaceId:u});if(!t.success)throw Error(`Unknown error`);i.invalidateQueries({queryKey:[`workspace`,u,`fs`]}),k(),iS.success(`Skill "${t.skillName}" installed successfully (${t.filesWritten} files)`)}catch(e){throw iS.error(`Failed to install skill: ${e instanceof Error?e.message:`Unknown error`}`),e}},re=O?.skills??[],ie=O?.isSkillsConfigured??!1,ae=ee&&E&&!!(d?.capabilities?.canBM25||d?.capabilities?.canVector),oe=ee&&D&&ie&&re.length>0,se=I?[`.`]:(U??[]).filter(e=>e.readOnly).map(e=>e.path.replace(/^\/+|\/+$/g,``)||`.`);if(c)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:Y9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(It,{fill:!0})]});if(m)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:Y9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(TH,{variant:`fill`})]});if(h)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:Y9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(wH,{variant:`fill`,resource:`workspaces`})]});if(g)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:Y9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(dLi,{})]});let ce=s||p;if(ce)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:Y9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load workspace`,descriptionSlot:ce.message})]});if(!c&&l.length===0)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:Y9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(lLi,{})]});if(!f&&!c&&!w)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:Y9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(uLi,{})]});let le=l.map(e=>({value:e.id,label:e.name,description:e.source===`agent`?`Agent: ${e.agentName}`:`Global workspace`,end:(0,K.jsxs)(`span`,{className:`flex shrink-0 gap-1`,children:[e.safety?.readOnly&&(0,K.jsx)(eC,{size:`xs`,variant:`warning`,children:`Read-only`}),e.capabilities.hasFilesystem&&(0,K.jsx)(eC,{size:`xs`,children:`FS`}),e.capabilities.hasSandbox&&(0,K.jsx)(eC,{size:`xs`,children:`Sandbox`}),e.capabilities.hasSkills&&(0,K.jsx)(eC,{size:`xs`,children:`Skills`})]})}));return(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:Y9}),headerActions:(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(_N,{"aria-label":`Workspace`,variant:`ghost`,className:`w-auto`,options:le,value:_?.id,onValueChange:y,placeholder:`Select workspace`,searchPlaceholder:`Search workspaces`,emptyText:`No workspaces found.`}),I&&(0,K.jsx)(eC,{size:`xs`,variant:`warning`,children:`Read-only`})]}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsxs)(`div`,{className:`flex min-h-0 flex-col`,children:[E&&u&&(0,K.jsx)(mLi,{workspaceId:u,showInitWarning:ae&&!f&&d?.status!==`ready`,skills:D&&O?re:void 0}),E&&u&&(0,K.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,K.jsx)(cLi,{workspaceId:u,activeFilePath:x,onActiveFileChange:b,readOnlyPaths:se,skillCount:D&&O?re.length:void 0,searchFiles:ae,searchSkills:oe,onCreateDirectory:V?async e=>{try{await C.mutateAsync({path:e,recursive:!0,workspaceId:u})}catch(t){throw iS.error(`Failed to create ${e}: ${hLi(t)}`),t}}:void 0,asideActions:te&&re.some(e=>e.path?.includes(`.agents/skills/`))?(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`Update skills`,disabled:j.isPending,onClick:()=>void P(),children:(0,K.jsx)(xS,{className:j.isPending?`animate-spin`:void 0})}):void 0,addSkill:te?{onInstall:ne,installedSkillIds:re.filter(e=>e.skillsShSource).map(e=>`${e.skillsShSource.owner}/${e.skillsShSource.repo}/${e.name}`),installedSkillNames:re.filter(e=>!e.skillsShSource).map(e=>e.name),writableMounts:W,installedSkillPaths:Object.fromEntries(re.filter(e=>e.path).map(e=>[e.name,e.path]))}:void 0,onDelete:H?F:void 0},u)}),T&&!f&&(0,K.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,K.jsx)(Jx,{variant:`fill`,titleSlot:`Filesystem resolved per request`,descriptionSlot:`This workspace creates its filesystem when an agent runs, so its files can't be browsed here.`})}),!E&&!T&&!f&&(0,K.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,K.jsx)(Jx,{variant:`fill`,titleSlot:`No filesystem or skills configured`,descriptionSlot:`Add a filesystem or skills to this workspace to browse its files here.`})})]})]})}function _Li({children:e,className:t,edgeToEdge:n,mobileHeader:r,ref:i,sidebar:a,...o}){let s=n!==void 0;return(0,K.jsxs)(`div`,{ref:i,"data-slot":`app-shell`,className:c(`h-full min-h-0`,a&&`lg:grid lg:grid-cols-[auto_minmax(0,1fr)] lg:grid-rows-[1fr]`,t),...o,children:[a,(0,K.jsxs)(`div`,{"data-slot":`app-shell-content`,className:`flex h-full min-h-0 min-w-0 flex-col`,"data-sidebar-reveal-layer":`page`,children:[r,(0,K.jsx)(`div`,{"data-slot":`app-shell-body`,className:c(`flex min-h-0 flex-1 flex-col`,s&&`transition-[padding] duration-(--resize-dur) ease-(--resize-ease) motion-reduce:transition-none!`,s&&`in-data-[sidebar-gesture=active]:transition-none!`,!n&&`lg:py-2 lg:pr-2`,!n&&(a?`lg:pl-0`:`lg:pl-2`)),children:e})]})]})}function vLi({children:e,className:t,edgeToEdge:n}){let r=n!==void 0;return(0,K.jsx)(`div`,{"data-slot":`main-card`,className:c(`relative min-h-0 flex-1 overflow-hidden`,r&&`transition-[border-radius,padding,box-shadow] duration-(--resize-dur) ease-(--resize-ease) motion-reduce:transition-none!`,r&&`in-data-[sidebar-gesture=active]:transition-none!`,!n&&`lg:rounded-studio-frame lg:p-px lg:shadow-raised`,Kze,t),children:e})}function yLi(){return(0,K.jsxs)(`div`,{className:`h-screen bg-sidebar`,children:[(0,K.jsx)(aS,{position:`bottom-right`}),(0,K.jsx)(M,{defaultTheme:`system`,children:(0,K.jsx)(Sx,{delayDuration:0,children:(0,K.jsx)(_Li,{children:(0,K.jsx)(vLi,{className:`flex items-center justify-center overflow-y-auto`,children:(0,K.jsx)(Iv,{})})})})})]})}function bLi(){let{data:e,isLoading:t}=A_(),{isLoading:n,canAccessAgentBuilder:r}=pS();return t||n||!e||e.enabled&&!k_(e)?{isVisible:!1}:{isVisible:r}}function xLi(){let{isImpersonating:e,impersonatedRole:t,stopImpersonation:n}=dS();return!e||!t?null:(0,K.jsxs)(`div`,{className:`mx-3 mb-2 flex items-center gap-2 rounded-md border border-info-edge bg-info-subtle px-3 py-1.5`,children:[(0,K.jsx)(cS,{className:`size-icon-sm shrink-0 text-info-subtle-foreground`}),(0,K.jsxs)(T,{variant:`meta`,className:`truncate text-info-subtle-foreground`,children:[`Previewing `,(0,K.jsx)(`span`,{className:`font-medium capitalize`,children:t.name}),` experience`]}),(0,K.jsx)(`button`,{type:`button`,onClick:n,className:`ml-auto shrink-0 rounded p-0.5 text-info-subtle-foreground hover:bg-info-edge`,title:`Exit role preview`,children:(0,K.jsx)(xw,{className:`size-icon-xs`})})]})}function SLi({children:e,contentClassName:t,commandClassName:n,showOverlay:r=!0,overlayClassName:i,...a}){return(0,K.jsx)(sNn,{size:`xl`,showOverlay:r,overlayClassName:c(`bg-sidebar/40 backdrop-blur-none`,i),contentClassName:c(`command-palette-popup overflow-visible bg-transparent shadow-none`,t),commandClassName:c(`command-palette-shell gap-2 overflow-visible rounded-none bg-transparent text-muted-foreground shadow-none backdrop-blur-none`,`[&_[data-slot=command-input-wrapper]_svg]:text-muted-foreground`,`**:[[cmdk-input]]:h-full **:[[cmdk-input]]:text-body`,`**:[[cmdk-group-heading]]:px-2 **:[[cmdk-group-heading]]:pt-2 **:[[cmdk-group-heading]]:pb-1 **:[[cmdk-group]]:p-0`,`**:[[cmdk-item]]:px-2 **:[[cmdk-item]]:py-1.5`,n),...a,children:e})}function CLi({wrapperClassName:e,...t}){return(0,K.jsx)(wq,{wrapperClassName:c(`command-palette-surface command-palette-surface-input`,Nx,`h-11 shrink-0 rounded-xl border-0 px-3 pr-11`,e),...t})}function wLi({children:e,className:t,...n}){return(0,K.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,K.jsx)(`div`,{className:c(`grid h-full min-h-0 grid-rows-[auto_minmax(0,1fr)] gap-2 md:grid-cols-[13rem_minmax(0,1fr)] md:grid-rows-none`,t),...n,children:e})})}function TLi({children:e,className:t,...n}){return(0,K.jsx)(`aside`,{className:c(`command-palette-surface command-palette-surface-rail flex max-h-[min(14rem,32dvh)] min-h-0 flex-col overflow-hidden rounded-xl p-2 md:h-full md:max-h-none`,Vv,t),...n,children:(0,K.jsx)(LS,{className:`-m-1 min-h-0 flex-1 p-1`,children:(0,K.jsx)(IS,{className:`pr-1`,children:(0,K.jsx)(`div`,{className:`flex flex-col gap-1`,children:e})})})})}function ELi({icon:e,label:t,count:n,active:r,onSelect:i}){return(0,K.jsxs)(`button`,{type:`button`,className:c(SS,`flex h-9 w-full cursor-pointer items-center gap-2 rounded-lg border border-transparent px-2.5 text-left text-body-sm hover:border-border hover:bg-fill-subtle data-[active=true]:border-border data-[active=true]:bg-fill-hover data-[active=true]:text-foreground`,`transition-[color,transform] duration-fast ease-out-custom active:scale-[0.99] motion-reduce:transition-none`),"data-active":r,"aria-pressed":r,onClick:i,children:[(0,K.jsx)(`span`,{className:`flex size-icon-md shrink-0 items-center justify-center [&>svg]:size-icon-md`,children:e}),(0,K.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:t}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`rounded-md border border-border bg-muted/70 px-1.5 py-0.5 leading-none`,children:n})]})}function DLi({children:e,footer:t,...n}){return(0,K.jsxs)(`div`,{role:`region`,className:c(`command-palette-surface command-palette-surface-results command-palette-results-panel relative flex min-h-0 min-w-0 flex-col overflow-hidden rounded-xl`,Vv),...n,children:[(0,K.jsx)(Tq,{scrollArea:!0,scrollAreaClassName:`min-h-0 flex-1 rounded-none`,scrollAreaViewportClassName:`command-palette-scroll-viewport`,className:`command-palette-list max-h-none rounded-none border-none bg-transparent shadow-none`,children:e}),t]})}function X9({icon:e,title:t,subtitle:n,path:r,badge:i,shortcut:a,className:o,...s}){return(0,K.jsxs)(Oq,{className:c(`group h-auto items-start gap-3 rounded-lg border border-transparent px-3 py-2.5 data-[selected=true]:border-border`,o),...s,children:[(0,K.jsx)(`span`,{className:c(`mt-0.5 flex size-4 max-w-4 min-w-4 shrink-0 basis-4 items-center justify-center text-muted-foreground group-data-[selected=true]:text-foreground [&>svg]:!size-4 [&>svg]:shrink-0`),children:e}),(0,K.jsxs)(`span`,{className:`flex min-w-0 flex-1 flex-col gap-1`,children:[(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`ink`,className:`truncate`,children:t}),i&&(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`shrink-0 rounded-md border border-border bg-muted/60 px-1.5 py-0.5 leading-none uppercase`,children:i})]}),(n||r)&&(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`flex min-w-0 items-center gap-2`,children:[n&&(0,K.jsx)(`span`,{className:`min-w-0 truncate`,children:n}),r&&(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,font:`mono`,className:`max-w-52 truncate rounded-md border border-border bg-muted/70 px-1.5 py-0.5 leading-none`,children:r})]})]}),a&&(0,K.jsx)(lNn,{children:a})]})}function OLi({label:e}){return(0,K.jsxs)(`div`,{className:`command-palette-footer pointer-events-none absolute inset-x-0 bottom-0 z-20 flex items-end justify-between gap-3 px-3 pt-3 pb-2 text-meta text-muted-foreground`,children:[(0,K.jsx)(`span`,{className:`truncate`,children:e}),(0,K.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1.5`,children:[(0,K.jsx)(Vx,{size:`sm`,children:`↑`}),(0,K.jsx)(Vx,{size:`sm`,children:`↓`}),(0,K.jsx)(Vx,{size:`sm`,children:`↵`}),(0,K.jsx)(Vx,{size:`sm`,children:`Esc`})]})]})}var kLi=!1,ALi=new Set,jLi=()=>{ALi.forEach(e=>e())},MLi=e=>(ALi.add(e),()=>ALi.delete(e)),NLi=()=>kLi,PLi=e=>{let t=typeof e==`function`?e(kLi):e;t!==kLi&&(kLi=t,jLi())},FLi=({enableShortcut:e=!0}={})=>{let t=(0,G.useSyncExternalStore)(MLi,NLi,NLi),n=(0,G.useCallback)(e=>{PLi(e)},[]),r=(0,G.useCallback)(()=>{PLi(e=>!e)},[]);return(0,G.useEffect)(()=>{if(!e)return;let t=e=>{e.key===`k`&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),r())};return document.addEventListener(`keydown`,t),()=>document.removeEventListener(`keydown`,t)},[e,r]),{open:t,setOpen:n,toggle:r}};function ILi(e,t){return[e.name,e.url,t,`path route navigate`].filter(Boolean).join(` `)}function LLi(e){return!e||e===`Studio`?`Path`:e}function RLi(e){return`/traces?entity=${encodeURIComponent(e)}`}var zLi=({scopeOptions:e,activeScope:t,onScopeChange:n})=>(0,K.jsx)(TLi,{"aria-label":`Search categories`,children:e.map(e=>(0,K.jsx)(ELi,{icon:e.icon,label:e.label,count:e.count,active:t===e.id,onSelect:()=>n(e.id)},e.id))}),BLi=({sidebar:e,activeScope:t,closeCommand:n})=>!e||t!==`all`&&t!==`settings`?null:(0,K.jsx)(Dq,{heading:`Commands`,children:(0,K.jsx)(X9,{value:`toggle sidebar collapse expand layout panel`,onSelect:()=>{e.toggleSidebar(),n()},icon:(0,K.jsx)(gRr,{}),title:`Toggle sidebar`,subtitle:`Studio layout`})}),VLi=({sections:e,handleSelect:t})=>(0,K.jsx)(K.Fragment,{children:e.map(e=>(0,K.jsx)(Dq,{heading:e.title,children:e.items.map(n=>{let r=n.Icon;return(0,K.jsx)(X9,{value:ILi(n,e.title),onSelect:()=>t(n.url),icon:(0,K.jsx)(r,{}),title:n.name,subtitle:`Studio path`,path:n.url,badge:LLi(e.title)},n.url)})},e.key))}),HLi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(Dq,{heading:`Agents`,children:t.map(([e,t])=>(0,K.jsx)(X9,{value:`${t.name} ${e} chat agent conversation thread ${n.agentLink(e)}`,onSelect:()=>r(n.agentLink(e)),icon:(0,K.jsx)(HN,{}),title:t.name,subtitle:`Agent chat`,path:n.agentLink(e),badge:`Agent`},e))}),ULi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(Dq,{heading:`Workflows`,children:t.map(([e,t])=>(0,K.jsx)(X9,{value:`${t.name} ${e} graph workflow view ${n.workflowLink(e)}`,onSelect:()=>r(n.workflowLink(e)),icon:(0,K.jsx)(ZS,{}),title:t.name,subtitle:`Workflow graph`,path:n.workflowLink(e),badge:`Workflow`},e))}),WLi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(Dq,{heading:`Tools`,children:t.map(([e,t])=>(0,K.jsx)(X9,{value:`tool ${t.id} ${e} ${n.toolLink(e)}`,onSelect:()=>r(n.toolLink(e)),icon:(0,K.jsx)(XN,{}),title:t.id,subtitle:`Tool definition`,path:n.toolLink(e),badge:`Tool`},e))}),GLi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(Dq,{heading:`Processors`,children:t.map(e=>{let t=e.name||e.id,i=e.isWorkflow?n.workflowLink(e.id)+`/graph`:n.processorLink(e.id);return(0,K.jsx)(X9,{value:`processor ${t} ${e.id} ${i}`,onSelect:()=>r(i),icon:(0,K.jsx)(mP,{}),title:t,subtitle:e.isWorkflow?`Workflow processor`:`Processor`,path:i,badge:`Processor`},e.id)})}),KLi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(Dq,{heading:`MCP Servers`,children:t.map(e=>(0,K.jsx)(X9,{value:`mcp server ${e.name} ${e.id} ${n.mcpServerLink(e.id)}`,onSelect:()=>r(n.mcpServerLink(e.id)),icon:(0,K.jsx)(KN,{}),title:e.name,subtitle:`MCP server`,path:n.mcpServerLink(e.id),badge:`MCP`},e.id))}),qLi=({visible:e,agentEntries:t,workflowEntries:n,handleSelect:r})=>e?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(Dq,{heading:`Observability`,children:[(0,K.jsx)(X9,{value:`observability traces telemetry signals /traces`,onSelect:()=>r(`/traces`),icon:(0,K.jsx)(cS,{}),title:`Traces`,subtitle:`Runtime traces`,path:`/traces`,badge:`Signal`}),(0,K.jsx)(X9,{value:`metrics usage latency performance tokens /metrics`,onSelect:()=>r(`/metrics`),icon:(0,K.jsx)(G4,{}),title:`Metrics`,subtitle:`Runtime metrics`,path:`/metrics`,badge:`Signal`}),(0,K.jsx)(X9,{value:`logs events runtime /logs`,onSelect:()=>r(`/logs`),icon:(0,K.jsx)(cS,{}),title:`Logs`,subtitle:`Runtime logs`,path:`/logs`,badge:`Signal`})]}),t.length>0&&(0,K.jsx)(Dq,{heading:`Agent Traces`,children:t.map(([e,t])=>{let n=RLi(e);return(0,K.jsx)(X9,{value:`${t.name} ${e} traces agent observability telemetry`,onSelect:()=>r(n),icon:(0,K.jsx)(cS,{}),title:t.name,subtitle:`Agent traces`,path:n,badge:`Trace`},e)})}),n.length>0&&(0,K.jsx)(Dq,{heading:`Workflow Traces`,children:n.map(([e,t])=>{let n=RLi(t.name);return(0,K.jsx)(X9,{value:`${t.name} ${e} traces workflow observability telemetry`,onSelect:()=>r(n),icon:(0,K.jsx)(cS,{}),title:t.name,subtitle:`Workflow traces`,path:n,badge:`Trace`},e)})})]}):null,JLi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(Dq,{heading:`Scorers`,children:t.map(([e,t])=>{let i=t.scorer?.config?.name||t.scorer?.config?.id||e;return(0,K.jsx)(X9,{value:`scorer score evaluation ${i} ${e} ${n.scorerLink(e)}`,onSelect:()=>r(n.scorerLink(e)),icon:(0,K.jsx)(G4,{}),title:i,subtitle:`Evaluation scorer`,path:n.scorerLink(e),badge:`Scorer`},e)})}),YLi=()=>{let{open:e,setOpen:t}=FLi(),{navigate:n,paths:r}=sn(),{isMastraPlatform:i}=Z8(),a=n3(),[o,s]=G.useState(`all`),{data:c={}}=wN(),{data:l={}}=eN(),{data:u={}}=Fq(),{data:d={}}=PN(),{data:f=[]}=NN(),{data:p={}}=VN(),{isCmsAvailable:m,isLoading:h}=w3(),{hasPermission:g,hasAnyPermission:_,isLoading:v}=fS(),y=e=>{t(e),e||s(`all`)},b=()=>y(!1),x=e=>{n(e),b()},S=G.useCallback(e=>{if(e.hidden||e.url===`/prompts`&&!m&&!h||i&&!e.isOnMastraPlatform)return!1;let t=gS(e.url);return v&&t&&t!==`public`?!1:_S(t,g,_)},[_,g,m,h,i,v]),C=Object.entries(c),w=Object.entries(l),T=Object.entries(u),E=Object.values(d).filter(e=>e.phases&&e.phases.length>0),D=Object.entries(p),O=G.useMemo(()=>{let e=[];for(let t of qjt){let n=t.items.filter(S);n.length>0&&e.push({key:t.key,title:t.title,items:n})}let t=[...Jjt.filter(S),...i?[]:[{name:`Templates`,url:`/templates`,Icon:OZ,isOnMastraPlatform:!1}]];return t.length===0?e:[...e,{key:`studio`,title:`Studio`,items:t}]},[S,i]),k=O.reduce((e,t)=>e+t.items.length,0),A=T.length+E.length+f.length,j=D.length,M=C.length+w.length+3,N=O.find(e=>e.key===`studio`)?.items.length??0,P=k+C.length+w.length+A+j+M,F=[{id:`all`,label:`All`,icon:(0,K.jsx)(oN,{}),count:P},{id:`paths`,label:`Paths`,icon:(0,K.jsx)(Emn,{}),count:k},{id:`agents`,label:`Agents`,icon:(0,K.jsx)(HN,{}),count:C.length},{id:`workflows`,label:`Workflows`,icon:(0,K.jsx)(ZS,{}),count:w.length},{id:`tooling`,label:`Tooling`,icon:(0,K.jsx)(joi,{}),count:A},{id:`evaluation`,label:`Evaluation`,icon:(0,K.jsx)(G4,{}),count:j},{id:`observability`,label:`Intelligence`,icon:(0,K.jsx)(cS,{}),count:M},{id:`settings`,label:`Studio`,icon:(0,K.jsx)(zq,{}),count:N}],I=o===`all`||o===`paths`,L=o===`all`||o===`agents`,R=o===`all`||o===`workflows`,z=o===`all`||o===`tooling`,B=o===`all`||o===`evaluation`,V=o===`all`||o===`observability`,H=o===`settings`,ee=G.useMemo(()=>{let e=[];for(let t of O)H?t.key===`studio`&&e.push(t):(o===`evaluation`&&t.key===`evaluation`||o===`observability`&&t.key===`observability`||I&&(o===`all`||t.key!==`studio`))&&e.push(t);return e},[o,O,I,H]);return(0,K.jsxs)(SLi,{open:e,onOpenChange:y,title:`Mastra Studio Search`,description:`Search Studio routes and runtime entities`,children:[(0,K.jsx)(CLi,{placeholder:`Search Studio, agents, workflows, tools, paths`}),(0,K.jsxs)(wLi,{children:[(0,K.jsx)(zLi,{scopeOptions:F,activeScope:o,onScopeChange:s}),(0,K.jsxs)(DLi,{"aria-label":`Search results`,footer:(0,K.jsx)(OLi,{label:`Studio search`}),children:[(0,K.jsx)(Eq,{children:`No matching results.`}),(0,K.jsx)(BLi,{sidebar:a,activeScope:o,closeCommand:b}),(0,K.jsx)(VLi,{sections:ee,handleSelect:x}),(0,K.jsx)(HLi,{visible:L,entries:C,paths:r,handleSelect:x}),(0,K.jsx)(ULi,{visible:R,entries:w,paths:r,handleSelect:x}),(0,K.jsx)(WLi,{visible:z,entries:T,paths:r,handleSelect:x}),(0,K.jsx)(GLi,{visible:z,entries:E,paths:r,handleSelect:x}),(0,K.jsx)(KLi,{visible:z,entries:f,paths:r,handleSelect:x}),(0,K.jsx)(qLi,{visible:V,agentEntries:C,workflowEntries:w,handleSelect:x}),(0,K.jsx)(JLi,{visible:B,entries:D,paths:r,handleSelect:x})]})]})]})};function XLi(e,t,n=[]){let r=e=>t===e||t.startsWith(e+`/`);return n.some(t=>t!==e&&t.url.startsWith(e.url+`/`)&&r(t.url))?!1:r(e.url)?!0:e.activePaths?.some(r)??!1}function ZLi(e){let{Icon:t}=e;return{name:e.name,url:e.url,icon:(0,K.jsx)(t,{})}}function QLi(){let{state:e,isMobile:t,setOpenMobile:n}=r3(),{setOpen:r}=FLi({enableShortcut:!1}),i=U2r(`K`),a=Dv().pathname,{isMastraPlatform:o}=Z8(),{data:s}=A_(),{isCmsAvailable:c,isLoading:l}=w3(),{hasPermission:u,hasAnyPermission:d,isLoading:f}=fS(),{data:p}=Bdr(),m=p!==void 0&&p.status!==`not-mounted`,h=s&&k_(s),g=new Set([`/prompts`]),{isVisible:_}=bLi(),v=a===`/agent-builder`||a.startsWith(`/agent-builder/`),y=()=>{t&&n(!1),r(!0)},b=e=>{if(e.hidden||e.url===`/connections`&&!m||g.has(e.url)&&!c&&!l||o&&!e.isOnMastraPlatform)return!1;if(f){let t=gS(e.url);if(t&&t!==`public`)return!1}return!!_S(gS(e.url),u,d)},{data:x}=NN(),{data:S}=iIn(),C=Jjt.filter(b),w=qjt.map(e=>{let t=e.items.filter(b),n=e=>({...ZLi(e),isActive:XLi(e,a,t)});return{key:e.key,title:e.title,href:e.href,isHeaderActive:!(!e.href||a!==e.href||t.some(e=>XLi(e,a,t))),links:t.filter(e=>!e.foldable).map(n),moreLinks:t.filter(e=>e.foldable).map(e=>({...n(e),defaultVisible:e.url===`/mcps`&&!!x?.length||e.url===`/workspaces`&&!!S?.workspaces.length}))}});return(0,K.jsxs)(f3,{"aria-label":`Sidebar`,children:[(0,K.jsxs)(f3.Header,{collapsedLogo:(0,K.jsx)(UZ,{className:`size-6`}),actions:h&&(0,K.jsx)(V9n,{}),children:[(0,K.jsx)(f3.Brand,{logo:(0,K.jsx)(UZ,{className:`size-6`}),title:`Mastra Studio`}),!t&&(0,K.jsx)(f3.SearchTrigger,{"aria-label":`Search and navigate`,shortcut:i,onClick:y}),(0,K.jsx)(f3.Trigger,{})]}),_&&(0,K.jsx)(f3.NavList,{className:`mb-1`,children:(0,K.jsx)(f3.NavLink,{state:e,link:{name:`Agent Builder`,url:`/agent-builder`,icon:(0,K.jsx)(YS,{})},isActive:v})}),(0,K.jsx)(xLi,{}),(0,K.jsx)(f3.Nav,{children:(0,K.jsx)(f3.Sections,{sections:w,visibilityStorageKey:`mastra:studio:sidebar-visibility`})}),(0,K.jsx)(f3.Footer,{children:(0,K.jsxs)(f3.NavList,{children:[C.map(t=>(0,K.jsx)(f3.NavLink,{state:e,link:ZLi(t),isActive:XLi(t,a)},t.name)),(0,K.jsx)(iVr,{state:e})]})})]})}var $Li=()=>{let{baseUrl:e,headers:t,apiPrefix:n,setConfig:r}=yS(),[i,a]=(0,G.useState)(()=>Object.entries(t).map(([e,t])=>({name:e,value:t})));return(0,K.jsx)(Sx,{delayDuration:0,children:(0,K.jsxs)(ZV,{onSubmit:t=>{t.preventDefault();let a=new FormData(t.currentTarget),o={};for(let e=0;e<i.length;e++){let t=a.get(`headers.${e}.name`),n=a.get(`headers.${e}.value`);typeof t==`string`&&typeof n==`string`&&(o[t]=n)}r({headers:o,baseUrl:e,apiPrefix:n}),iS.success(`Headers saved`)},className:`w-full max-w-md gap-6 text-left`,children:[(0,K.jsx)(pRr,{headers:i,onAddHeader:e=>{a(t=>[...t,e])},onRemoveHeader:e=>{a(t=>t.filter((t,n)=>n!==e))}}),(0,K.jsxs)(X,{type:`submit`,className:`ml-auto`,children:[(0,K.jsx)(W4,{}),`Save headers`]})]})})};function eRi({children:e,loginUrl:t=`/login`,signupUrl:n=`/signup`}){let{data:r,isLoading:i}=A_();if(i||!r?.enabled||k_(r))return(0,K.jsx)(K.Fragment,{children:e});let a=typeof window<`u`?window.location.href:void 0;return r.login?(0,K.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,K.jsxs)(`div`,{className:`flex flex-col items-center space-y-6 text-center`,children:[(0,K.jsx)(UZ,{className:`h-16 w-16 opacity-50`}),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(T,{as:`h2`,variant:`heading`,tone:`ink`,children:`Sign in to continue`}),(0,K.jsx)(`p`,{className:`max-w-sm text-muted-foreground`,children:`You need to sign in to access this page.`})]}),r.login.description&&(0,K.jsxs)(`div`,{className:`flex items-start gap-2.5 rounded-md border border-border bg-background p-3 text-left`,children:[(0,K.jsx)(CH,{className:`mt-0.5 size-icon-md shrink-0 text-muted-foreground`}),(0,K.jsx)(T,{tone:`muted`,className:`max-w-sm`,children:r.login.description})]}),(0,K.jsx)(L9n,{config:r.login,redirectUri:a,loginUrl:t}),(r.login.type===`credentials`||r.login.type===`both`)&&r.login.signUpEnabled!==!1&&(0,K.jsxs)(`div`,{children:[(0,K.jsx)(T,{as:`span`,variant:`body`,tone:`muted`,children:`Don't have an account? `}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>{let e=new URL(WZ(n),window.location.origin);a&&e.searchParams.set(`redirect`,a),window.location.href=e.toString()},className:`text-foreground hover:underline`,children:(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:`Sign up`})})]})]})}):(0,K.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,K.jsxs)(`div`,{className:`flex flex-col items-center space-y-6 text-center`,children:[(0,K.jsx)(UZ,{className:`h-16 w-16 opacity-50`}),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(T,{as:`h2`,variant:`heading`,tone:`ink`,children:`Authentication Required`}),(0,K.jsx)(`p`,{className:`max-w-sm text-muted-foreground`,children:`Add the authorization header that Studio needs to reach your Mastra server.`})]}),(0,K.jsx)($Li,{})]})})}var tRi=`experimental-ui:`,nRi=`current`,rRi=G.createContext(null);function iRi(e,t){let n=window.localStorage.getItem(tRi+e);return n&&t.has(n)?n:nRi}function aRi({experiments:e,children:t}){let n=G.useMemo(()=>new Map(e.map(e=>[e.key,new Set(e.variants.map(e=>e.value))])),[e]),[r,i]=G.useState({});G.useLayoutEffect(()=>{let t={};for(let r of e){let e=n.get(r.key);t[r.key]=iRi(r.key,e)}i(t)},[e,n]);let a=G.useCallback(e=>r[e]??nRi,[r]),o=G.useCallback((e,t)=>{window.localStorage.setItem(tRi+e,t),i(n=>({...n,[e]:t}))},[]),s=G.useMemo(()=>({experiments:e,getVariant:a,setVariant:o}),[e,a,o]);return(0,K.jsx)(rRi.Provider,{value:s,children:t})}var oRi=[{key:`entity-list-page`,name:`Entity List page UI`,path:[`/agents`,`/prompts`,`/tools`,`/datasets`,`/scorers`,`/mcps`,`/workflows`,`/processors`],variants:[{value:`current`,label:`Current state`},{value:`new-proposal`,label:`New proposal`}]}],sRi=()=>({experimentalUIEnabled:typeof window<`u`&&window.MASTRA_EXPERIMENTAL_UI===`true`}),cRi=()=>{let{toggleSidebar:e}=r3();return Ux({"[":e},{repeat:!1}),null};function lRi(){let{setOpenMobile:e}=r3(),{setOpen:t}=FLi({enableShortcut:!1});return(0,K.jsxs)(`header`,{className:`sticky top-0 z-20 flex h-12 shrink-0 items-center justify-between gap-3 border-b border-border bg-sidebar px-3 lg:hidden`,children:[(0,K.jsxs)(`div`,{className:`flex min-w-0 items-center gap-3`,children:[(0,K.jsx)(f3.MobileTrigger,{}),(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(UZ,{className:`size-[1.5rem] shrink-0`}),(0,K.jsx)(T,{variant:`body-sm`,font:`display`,as:`span`,className:`whitespace-nowrap`,children:`Mastra Studio`})]})]}),(0,K.jsx)(X,{type:`button`,variant:`ghost`,size:`icon-md`,tooltip:`Search`,"aria-label":`Search and navigate`,onClick:()=>{e(!1),t(!0)},className:`shrink-0`,children:(0,K.jsx)(oN,{})})]})}var uRi={"studio-frame":100,"route-side-panel":0},dRi={overflow:`visible`};function fRi({children:e,className:t}){let n=Zw(),{hasPanel:r,panelHandle:i,onPanelResize:a}=X8(),{defaultLayout:o,onLayoutChange:s}=pWr({id:`studio-frame-layout-v1`,storage:localStorage});return(0,K.jsx)(`div`,{className:`relative flex min-h-0 flex-1`,children:(0,K.jsxs)(p6,{className:`min-h-0 flex-1`,style:dRi,orientation:`horizontal`,defaultLayout:o??uRi,onLayoutChange:s,children:[(0,K.jsx)(f6,{id:`studio-frame`,className:c(`min-w-0`,t),style:dRi,children:e}),r&&!n&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(m6,{className:`w-2`}),(0,K.jsx)(wWr,{id:`route-side-panel`,ref:i,direction:`right`,collapsible:!0,collapsedSize:0,hideExpandButton:!0,minSize:370,maxSize:`50%`,defaultSize:560,className:`min-w-0`,onResize:e=>a(e.inPixels),children:(0,K.jsx)(G1r,{className:`h-full min-h-0`})})]})]})})}function pRi({children:e}){let{data:t,isFetched:n}=A_(),{pathname:r}=Dv(),i=!(n&&t?.enabled&&!k_(t));return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(YLi,{}),(0,K.jsx)(_Li,{sidebar:i?(0,K.jsx)(QLi,{}):void 0,mobileHeader:i?(0,K.jsx)(lRi,{}):void 0,children:(0,K.jsx)(fRi,{className:`flex min-h-0 flex-1 flex-col`,children:(0,K.jsx)(vLi,{children:(0,K.jsx)(eRi,{children:(0,K.jsx)(eJe,{resetKeys:[r],children:e})})})})})]})}var mRi=({children:e})=>{let{experimentalUIEnabled:t}=sRi(),{Link:n}=sn();return(0,K.jsxs)(`div`,{className:`h-screen bg-sidebar`,children:[(0,K.jsx)(aS,{position:`bottom-right`}),(0,K.jsx)(M,{defaultTheme:`system`,children:(0,K.jsx)(Sx,{delayDuration:0,children:(0,K.jsx)(aRi,{experiments:t?oRi:[],children:(0,K.jsxs)(f3.Provider,{LinkComponent:n,children:[(0,K.jsx)(cRi,{}),(0,K.jsx)(W1r,{children:(0,K.jsx)(pRi,{children:e})})]})})})})]})},hRi=({children:e})=>(0,K.jsxs)(`div`,{className:`h-screen bg-sidebar`,children:[(0,K.jsx)(aS,{position:`bottom-right`}),(0,K.jsx)(M,{defaultTheme:`system`,children:(0,K.jsx)(Sx,{delayDuration:0,children:(0,K.jsx)(`div`,{className:`h-full overflow-y-auto`,children:(0,K.jsx)(eRi,{children:e})})})})]}),gRi={name:`Agents`,url:`/agent-builder/agents`,icon:(0,K.jsx)(HN,{})},_Ri={name:`Skills`,url:`/agent-builder/skills`,icon:(0,K.jsx)(pdr,{className:`size-icon-lg`})},vRi={name:`Favorites`,url:`/agent-builder/favorite`,icon:(0,K.jsx)(AK,{className:`size-icon-lg`})},yRi={name:`Library`,url:`/agent-builder/library`,icon:(0,K.jsx)(WN,{className:`size-icon-lg`})},bRi={name:`Infra`,url:`/agent-builder/infrastructure`,icon:(0,K.jsx)(oYr,{className:`size-icon-lg`})};function xRi(){let{Link:e}=sn(),{pathname:t}=Dv(),n=jK(),{canManageSkills:r,canUseFavorites:i}=pS(),{hasPermission:a}=fS(),o=a(`infrastructure:read`),s=(0,G.useMemo)(()=>{let e=[gRi];return n.skills&&r&&e.push(_Ri),i&&e.push(vRi),e.push(yRi),o&&e.push(bRi),e},[n.skills,r,i,o]);return(0,K.jsx)(`nav`,{"aria-label":`Primary`,className:`fixed inset-x-0 bottom-0 z-40 border-t border-border bg-sidebar/95 pb-[env(safe-area-inset-bottom)] backdrop-blur-sm md:hidden`,children:(0,K.jsx)(`ul`,{className:`grid`,style:{gridTemplateColumns:`repeat(${s.length}, minmax(0, 1fr))`},children:s.map(n=>{let r=t.startsWith(n.url);return(0,K.jsx)(`li`,{children:(0,K.jsxs)(e,{href:n.url,"aria-current":r?`page`:void 0,className:c(r?`text-foreground`:`text-muted-foreground`,`relative flex flex-col items-center justify-center gap-1 py-2`,A,r?`before:absolute before:inset-x-0 before:-top-px before:h-0.5 before:bg-current`:`hover:text-foreground`),children:[(0,K.jsx)(`span`,{className:`flex size-6 items-center justify-center`,"aria-hidden":`true`,children:(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`block`,children:n.icon})}),(0,K.jsx)(T,{as:`span`,variant:`caption`,children:n.name})]})},n.name)})})})}var SRi={name:`My agents`,url:`/agent-builder/agents`,icon:(0,K.jsx)(HN,{})},CRi={name:`Favorites`,url:`/agent-builder/favorite`,icon:(0,K.jsx)(AK,{})},wRi={name:`Library`,url:`/agent-builder/library`,icon:(0,K.jsx)(WN,{})},TRi={name:`Skills`,url:`/agent-builder/skills`,icon:(0,K.jsx)(pdr,{className:`size-icon-md`})},ERi={name:`Infrastructure`,url:`/agent-builder/infrastructure`,icon:(0,K.jsx)(oYr,{className:`size-icon-md`})};function DRi({forceExpanded:e=!1}={}){let{Link:t}=sn(),{state:n,isMobile:r}=r3(),{pathname:i}=Dv(),a=jK(),{canManageSkills:o,canUseFavorites:s}=pS(),{hasPermission:c}=fS(),l=c(`infrastructure:read`),u=e?`default`:n,{data:d}=A_(),f=d&&k_(d),p=[SRi];a.skills&&o&&p.push(TRi),s&&p.push(CRi),p.push(wRi);let m=(0,K.jsx)(t,{href:`/agents`,"aria-label":`Back to Mastra Studio`,children:(0,K.jsx)(UZ,{className:`size-6`})});return(0,K.jsxs)(f3,{className:`h-full`,mobileMode:`drawer`,children:[!e&&(0,K.jsxs)(f3.Header,{collapsedLogo:m,actions:f&&(0,K.jsx)(V9n,{}),children:[(0,K.jsx)(t,{href:`/agents`,"aria-label":`Back to Mastra Studio`,className:`min-w-0 flex-1`,children:(0,K.jsx)(f3.Brand,{logo:(0,K.jsx)(UZ,{className:`size-6`}),title:`Mastra Studio`})}),!r&&(0,K.jsx)(f3.Trigger,{})]}),(0,K.jsx)(xLi,{}),(0,K.jsx)(f3.Nav,{children:(0,K.jsx)(f3.NavSection,{children:(0,K.jsx)(f3.NavList,{children:p.map(e=>{let n=i.startsWith(e.url);return(0,K.jsx)(f3.NavLink,{LinkComponent:t,state:u,link:e,isActive:n},e.name)})})})}),!e&&(0,K.jsx)(f3.Footer,{children:l&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(f3.NavSeparator,{}),(0,K.jsx)(f3.NavSection,{children:(0,K.jsx)(f3.NavList,{children:(0,K.jsx)(f3.NavLink,{LinkComponent:t,state:u,link:ERi,isActive:i.startsWith(ERi.url)})})})]})})]})}var Z9=()=>(0,K.jsx)(`div`,{className:`h-screen bg-sidebar`,children:(0,K.jsxs)(Ezr,{children:[(0,K.jsxs)(`div`,{className:`grid h-full grid-rows-1 md:grid-cols-[auto_1fr] md:divide-x md:divide-border`,children:[(0,K.jsx)(`div`,{className:`hidden md:block`,children:(0,K.jsx)(DRi,{})}),(0,K.jsx)(`div`,{className:`flex h-full min-h-0 flex-col`,children:(0,K.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto bg-transparent pb-[calc(3.5rem+env(safe-area-inset-bottom))] md:pb-0`,children:(0,K.jsx)(Iv,{})})})]}),(0,K.jsx)(xRi,{})]})}),ORi=()=>(0,K.jsx)(`div`,{className:`grid h-screen grid-cols-[minmax(0,1fr)] grid-rows-1 bg-sidebar`,children:(0,K.jsx)(Iv,{})});function kRi({agentId:e,children:t,disabled:n=!1}){let r=Zw(),i=(0,K.jsx)(RZ,{children:(0,K.jsx)(Y1r,{agentId:e})},e);return n?t:(0,K.jsxs)(Hw,{side:`right`,children:[t,r?(0,K.jsxs)(Ww,{children:[(0,K.jsx)(Gw,{}),(0,K.jsx)(Kw,{children:(0,K.jsxs)(qw,{className:`w-[calc(100vw-2.5rem)] max-w-md`,children:[(0,K.jsx)(Yw,{className:`sr-only`,children:`Config`}),(0,K.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:i})]})})]}):(0,K.jsx)(Y8,{owner:`agent-detail`,children:i})]})}var ARi=()=>{let{toggle:e}=X8();return Ux({"]":e}),null};function jRi(){let e=Zw(),{isCollapsed:t,toggle:n}=X8();return e?(0,K.jsx)(Uw,{asChild:!0,children:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,type:`button`,"aria-label":`Config`,tooltip:`Show config panel`,"data-testid":`agent-overview-panel-toggle`,children:(0,K.jsx)(O3,{side:`right`})})}):(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,type:`button`,"aria-label":`Config`,"aria-pressed":!t,tooltip:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[t?`Show config panel`:`Hide config panel`,(0,K.jsx)(Vx,{size:`xs`,children:`]`})]}),"data-testid":`agent-overview-panel-toggle`,onClick:n,children:(0,K.jsx)(O3,{side:`right`})})}function MRi({agentId:e,showConfig:t=!0}){let{data:n}=CN({agentId:e,requestContext:HS(`agent`,e)[0],queryOptions:{enabled:!!e}}),{canCreateAgent:r}=cOn(),{Link:i,paths:a}=sn(),{handleCopy:o,isCopied:s}=hC({text:`${window.location.origin}${WZ(`/agents/${encodeURIComponent(e)}/session`)}`,copyMessage:`Session URL copied to clipboard!`}),c=a.cmsAgentEditLink(e),l=r&&n?.source===`stored`&&!!c;return(0,K.jsxs)(K.Fragment,{children:[l&&(0,K.jsx)(X,{variant:`ghost`,size:`sm`,render:(0,K.jsx)(i,{href:c}),icon:(0,K.jsx)(iH,{}),children:`Edit`}),(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,type:`button`,"aria-label":`Copy session URL`,onClick:o,tooltip:`Copy session URL to share with your team`,"data-testid":`agent-entity-header-share`,children:s?(0,K.jsx)(pC,{}):(0,K.jsx)(tZ,{})}),t&&(0,K.jsx)(jRi,{})]})}function NRi(e){if(e)try{return nk(e)}catch{return}}function PRi(e){let t=NRi(e.inputSchema);return{inputSchema:t,outputSchema:NRi(e.outputSchema),requestContextSchema:NRi(e.requestContextSchema),zodInputSchema:z9(t)}}function FRi(e,t){let{data:n={},isLoading:r,isError:i}=wN(),a=Object.entries(n).filter(([,t])=>Object.values(t.tools??{}).some(t=>t.id===e)).map(([e,t])=>({id:e,name:t.name||e}));return{agents:[...a.filter(e=>e.id===t),...a.filter(e=>e.id!==t)],isLoading:r,isError:i}}function IRi({agent:e,isCurrent:t}){let{Link:n,paths:r}=sn(),i=(0,K.jsx)(Z.NameCell,{children:(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(Dx,{size:`sm`,className:`shrink-0 text-muted-foreground`,children:(0,K.jsx)(HN,{})}),e.name]})});return t?(0,K.jsxs)(Z.RowStatic,{children:[i,(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(eC,{variant:`neutral`,emphasis:`subtle`,children:`Current`})})]}):(0,K.jsxs)(Z.RowLink,{to:r.agentLink(e.id),LinkComponent:n,children:[i,(0,K.jsx)(`span`,{})]})}function LRi({isLoading:e,isError:t,isEmpty:n}){if(e)return`Loading agents…`;if(t)return`Couldn't load the agents that use this tool.`;if(n)return`No agents use this tool yet.`}function RRi({toolId:e,currentAgentId:t}){let{agents:n,isLoading:r,isError:i}=FRi(e,t),a=LRi({isLoading:r,isError:i,isEmpty:n.length===0});return a?(0,K.jsx)(vZ,{children:(0,K.jsx)(_ji,{message:a})}):(0,K.jsx)(Z,{columns:`minmax(0,1fr) auto`,fit:`container`,children:n.map(e=>(0,K.jsx)(IRi,{agent:e,isCurrent:e.id===t},e.id))})}function zRi(e){return(0,K.jsxs)(yZ,{children:[(0,K.jsx)(pji,{children:(0,K.jsx)(bZ,{children:`Used by`})}),(0,K.jsx)(RRi,{...e})]})}function BRi({tool:e,execution:t,currentAgentId:n,requestContextEntityType:r,requestContextEntityId:i}){let{canExecute:a}=fS(),{inputSchema:o,outputSchema:s,requestContextSchema:c,zodInputSchema:l}=PRi(e);return(0,K.jsx)(fji,{description:e.description,overview:(0,K.jsx)(lMi,{inputSchema:o,outputSchema:s,requestContextSchema:c,footer:(0,K.jsx)(zRi,{toolId:e.id,currentAgentId:n})}),canRun:a(`tools`),playground:(0,K.jsx)(iMi,{zodInputSchema:l,execution:t,requestContextEntityType:r,requestContextEntityId:i})})}function VRi({agentId:e}){let t=cMi(),[n]=HS(`agent`,e),{data:r,isLoading:i}=CN({agentId:e,requestContext:n}),{mutateAsync:a,status:o,data:s,error:c}=lAt(),l=Object.values(r?.tools??{}).find(e=>e.id===t),u={execute:(n,r)=>a({agentId:e,toolId:t,input:n,playgroundRequestContext:r}),status:o,output:s,error:c};return i?(0,K.jsx)(jQ.LoadingData,{}):l?(0,K.jsx)(BRi,{tool:l,execution:u,currentAgentId:e,requestContextEntityType:`agent-tool`,requestContextEntityId:`${e}:${l.id}`}):(0,K.jsxs)(jQ.NoData,{children:[`This agent has no tool "`,t,`".`]})}var HRi=[eP(`/agents`),$jt],URi=({agentId:e})=>{let t=Ov();return Ux({"g$+t":()=>t(`/agents/${e}/traces`)}),null},WRi=S8.threadId;function GRi(e,t,n){if(e===`chat`){let e=B_(`/agents/:agentId/threads/:threadId`,t)?.params.threadId;return e===`new`?void 0:e}if(e===`traces`){let e=new URLSearchParams(n),t=e.get(w8(WRi));return t&&t!==`is`?void 0:e.get(WRi)||void 0}}var KRi=({children:e})=>{let{agentId:t}=kv(),n=Dv(),{isCmsAvailable:r}=w3(),{hasObservability:i}=Pkt(),a=At.has(`datasets`),o=r&&a,s=i&&a,{data:c}=CN({agentId:t,requestContext:HS(`agent`,t)[0],queryOptions:{enabled:!!t}}),l=MK(c?.provider??``),u=c?.modelId??``,d=n.pathname.includes(`/threads`)?`chat`:n.pathname.includes(`/editor`)?`versions`:n.pathname.includes(`/traces`)?`traces`:`none`,f=GRi(d,n.pathname,n.search);return(0,K.jsx)(Xer,{defaultProvider:l,defaultModel:u,children:(0,K.jsxs)(tn,{children:[(0,K.jsx)(URi,{agentId:t}),(0,K.jsx)(ARi,{}),(0,K.jsx)(IMi,{children:(0,K.jsx)(VRi,{agentId:t})}),(0,K.jsx)(kRi,{agentId:t,disabled:d===`versions`,children:(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:HRi}),headerActions:(0,K.jsx)(MRi,{agentId:t,showConfig:d!==`versions`}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:t}),(0,K.jsxs)(`div`,{className:`grid h-full min-h-0 grid-cols-[minmax(0,1fr)] grid-rows-[auto_minmax(0,1fr)]`,children:[(0,K.jsx)(tQr,{agentId:t,activeTab:d,threadId:f,showPlayground:o,showObservability:s}),e]})]})})]})},`${t}:${l}/${u}`)};function qRi(e,t){let n=e.page,r=new Map([...e.ancestors,n].map(e=>[e.id,e]));return{name:n.name,kind:n.isScope?n.displayLabel??`Scope`:`Page`,pageRef:$wi(n,r),childCount:t?.pages.length?`${t.pages.length}${t.nextCursor?`+`:``}`:void 0}}function JRi(e,t){let n=e.split(`#`)[0]?.split(`:`)[0];return!!(n&&e.includes(`:`)&&t?.pages.some(e=>e.isScope&&e.address?.split(`:`)[0]===n))}function YRi(e){let t=Y(),n=QOi().data?.[0]?.key,r=e.pageId??e.pageRef,i=T_({queryKey:[`knowledge`,n,`tree`,null,null],queryFn:n?async()=>t.getKnowledge(n).tree({}):v_,staleTime:3e4}),a=e.pageId!==void 0||e.pageRef!==void 0&&JRi(e.pageRef,i.data),{data:o}=T_({queryKey:[`knowledge`,n,`page`,r,null],queryFn:n&&r&&a?async()=>t.getKnowledge(n).page(r):v_,retry:!1,staleTime:3e4}),s=o?.page.id,c=T_({queryKey:[`knowledge`,n,`tree`,s??null,null],queryFn:n&&s?async()=>t.getKnowledge(n).tree({parentId:s}):v_,staleTime:3e4});return o?qRi(o,c.data):void 0}function XRi({children:e}){return(0,K.jsx)(I1n,{pageHref:hX,refHref:hX,usePagePreview:YRi,children:e})}var ZRi=()=>{let e=Ov();return Ux({"g$+a":()=>e(`/agents`),"g$+p":()=>e(`/prompts`),"g$+w":()=>e(`/workflows`),"g$+c":()=>e(`/processors`),"g$+m":()=>e(`/mcps`),"g$+o":()=>e(`/tools`),"g$+k":()=>e(`/workspaces`),"g$+s":()=>e(`/scorers`),"g$+d":()=>e(`/datasets`),"g$+x":()=>e(`/experiments`),"g$+q":()=>e(`/experiments/review-queue`),"g$+n":()=>e(`/metrics`),"g$+t":()=>e(`/traces`),"g$+l":()=>e(`/logs`),"g$+,":()=>e(`/settings`),"g$+h":()=>e(`/resources`)}),null},QRi=eP(`/traces`);function $Ri(e){return e.startsWith(`/spans`)?`spans`:e.startsWith(`/threads`)?`threads`:`traces`}function ezi({children:e}){let{pathname:t}=Dv(),n=Ov();return(0,K.jsx)(RNi,{current:$Ri(t),features:Boi,onViewChange:e=>n(`/${e}`),breadcrumbs:e=>{let t=XNi(e);return(0,K.jsx)(vN,{crumbs:t?[QRi,{id:e.current,label:t}]:[QRi]})},children:e})}var tzi=()=>(0,K.jsx)(Jx,{titleSlot:`No Processors yet`,descriptionSlot:`Configure processors. Add input or output processors to your agents to transform messages.`,actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/docs/agents/processors`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(tP,{}),children:`Processors documentation`}),variant:`fill`}),nzi=[`input`,`inputStep`,`outputStep`,`outputStream`,`outputResult`],rzi={name:e=>e.name||e.id,agents:e=>e.agentIds?.length??0};function izi({processors:e,isLoading:t,search:n=``,sort:r,onSortChange:i}){let{paths:a,Link:o}=sn(),s=(0,G.useMemo)(()=>Object.values(e??{}).filter(e=>e.phases&&e.phases.length>0),[e]),c=(0,G.useMemo)(()=>{let e=n.toLowerCase();return IZ(s.filter(t=>t.id.toLowerCase().includes(e)||(t.name||``).toLowerCase().includes(e)),r,rzi)},[s,n,r]),{containerRef:l,getRowProps:u}=PZ({count:c.length,global:!0});if(t)return(0,K.jsx)(DH,{columns:`auto 1fr auto auto auto auto auto auto`});let d=e=>r?.key===e?r.direction:void 0;return(0,K.jsxs)(Z,{columns:`auto 1fr auto auto auto auto auto auto`,scrollRef:l,children:[(0,K.jsxs)(Z.Top,{children:[i?(0,K.jsx)(Z.SortableTopCell,{sortKey:`name`,sort:d(`name`),onSortChange:i,children:`Name`}):(0,K.jsx)(Z.TopCell,{children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`Description`}),(0,K.jsx)(Z.TopCellSmart,{long:`Input`,short:`Input`,tooltip:`Contains input phase`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Input Step`,short:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(H4,{}),` Step`]}),tooltip:`Contains input step phase`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Output Step`,short:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(U4,{}),` Step`]}),tooltip:`Contains output step phase`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Output Stream`,short:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(U4,{}),` Stream`]}),tooltip:`Contains output stream phase`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Output Result`,short:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(U4,{}),` Result`]}),tooltip:`Contains output result phase`,className:`text-center`}),i?(0,K.jsx)(Z.SortableTopCell,{sortKey:`agents`,sort:d(`agents`),onSortChange:i,align:`end`,children:`Used by`}):(0,K.jsx)(Z.TopCellSmart,{short:`Used by`,long:`Used by Agents`,className:`text-center`})]}),c.length===0&&n?(0,K.jsx)(Z.NoMatch,{message:`No Processors match your search`}):null,c.map((e,t)=>{let n=dJ(e.name||e.id,50),r=dJ(e.description??``,200),i=e.agentIds?.length??0,s=new Set(e.phases||[]),c=e.isWorkflow?a.workflowLink(e.id)+`/graph`:a.processorLink(e.id);return(0,K.jsxs)(Z.RowLink,{to:c,LinkComponent:o,...u(t),children:[(0,K.jsx)(Z.NameCell,{children:n}),(0,K.jsx)(Z.DescriptionCell,{children:r}),nzi.map(e=>(0,K.jsx)(Z.TextCell,{className:`text-center`,children:s.has(e)&&(0,K.jsx)(pC,{className:`mx-auto size-icon-md`})},e)),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:i||``})]},e.id)})]})}var Q9=[eP(`/processors`)];function azi(){let{data:e={},isLoading:t,error:n}=PN(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)();return n&&FN(n)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:Q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Processors`}),(0,K.jsx)(TH,{variant:`fill`})]}):n&&IN(n)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:Q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Processors`}),(0,K.jsx)(wH,{variant:`fill`,resource:`processors`})]}):n?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:Q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Processors`}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load processors`,descriptionSlot:n.message})]}):Object.keys(e).length===0&&!t?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:Q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Processors`}),(0,K.jsx)(tzi,{})]}):(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:Q9}),actionRow:(0,K.jsx)(TK,{children:(0,K.jsx)(TK.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(MH,{...NH,onValueChange:i,label:`Search processors`,placeholder:`Search by name`})})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Processors`}),(0,K.jsx)(izi,{processors:e,isLoading:t,search:r,sort:a,onSortChange:(e,t)=>o({key:t,direction:e})})]})}var ozi={input:`Input - Process input messages before LLM (once at start)`,inputStep:`Input Step - Process at each agentic loop step`,outputStream:`Output Stream - Process streaming chunks`,outputResult:`Output Result - Process complete output after streaming`,outputStep:`Output Step - Process after each LLM response (before tools)`,toolResult:`Tool Result - Process tool output before it is added to the message list`,llmRequest:`LLM Request - Transform the provider prompt before each LLM call`};function szi({processorId:e}){let{data:t,isLoading:n,error:r}=ajt({processorId:e,queryOptions:{enabled:!!e}});return(0,G.useEffect)(()=>{if(r){let e=r instanceof Error?r.message:`Failed to load processor`;iS.error(`Error loading processor: ${e}`)}},[r]),n?(0,K.jsxs)(`div`,{className:`p-4`,children:[(0,K.jsx)(zS,{className:`mb-4 h-8 w-48`}),(0,K.jsx)(zS,{className:`h-32 w-full`})]}):r?null:t?(0,K.jsx)(czi,{processor:t}):(0,K.jsx)(`div`,{className:`px-4 py-8 text-center`,children:(0,K.jsx)(T,{variant:`heading`,tone:`muted`,children:`Processor not found`})})}function czi({processor:e}){let t=yw(),[n,r]=(0,G.useState)(e.phases[0]||`input`),[i,a]=(0,G.useState)(e.configurations[0]?.agentId||``),[o,s]=(0,G.useState)(`Hello, this is a test message.`),[c,l]=(0,G.useState)(null),[u,d]=(0,G.useState)(),f=ojt(),p=async()=>{d(void 0),l(null);let t=n===`outputStep`||n===`outputResult`?`assistant`:`user`,r=[{id:crypto.randomUUID(),role:t,createdAt:new Date,content:{format:2,parts:[{type:`text`,text:o}]}}];try{let t=await f.mutateAsync({processorId:e.id,phase:n,messages:r,agentId:i||void 0});l(t),!t.success&&t.error&&d(t.error)}catch(e){d(e.message||`An error occurred`)}},m=c?JSON.stringify(c,null,2):`{}`;return(0,K.jsxs)(`div`,{className:`relative grid h-full min-w-min grid-cols-[auto_1fr] overflow-x-auto overflow-y-auto`,children:[(0,K.jsxs)(`div`,{className:`w-[22rem] overflow-y-auto border-r border-border`,children:[(0,K.jsx)(lzi,{processor:e}),(0,K.jsxs)(`div`,{className:`space-y-5 p-5`,children:[(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{children:`Phase`}),(0,K.jsxs)(Bk,{value:n,onValueChange:t=>{let n=e.phases.find(e=>e===t);n&&r(n)},children:[(0,K.jsx)(Hk,{className:`w-full`,children:(0,K.jsx)(Vk,{placeholder:`Select phase`})}),(0,K.jsx)(Uk,{children:e.phases.map(e=>(0,K.jsx)(Wk,{value:e,children:e},e))})]})]}),(0,K.jsx)(T,{variant:`meta`,tone:`muted`,children:ozi[n]})]}),e.configurations.length>1&&(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{children:`Agent Configuration`}),(0,K.jsxs)(Bk,{value:i,onValueChange:a,children:[(0,K.jsx)(Hk,{className:`w-full`,children:(0,K.jsx)(Vk,{placeholder:`Select agent`})}),(0,K.jsx)(Uk,{children:e.configurations.map(e=>(0,K.jsxs)(Wk,{value:e.agentId,children:[e.agentName,` (`,e.type,`)`]},e.agentId))})]})]}),(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{children:`Test Message`}),(0,K.jsx)(qk,{value:o,onChange:e=>s(e.target.value),placeholder:`Enter a test message`,rows:4})]}),(0,K.jsx)(X,{icon:(0,K.jsx)(DT,{}),onClick:p,disabled:f.isPending||n===`outputStream`||n===`llmRequest`,className:`w-full`,children:f.isPending?`Running...`:`Run processor`}),n===`outputStream`&&(0,K.jsx)(T,{variant:`meta`,className:`text-warning-foreground`,children:`Output Stream phase cannot be executed directly. Use streaming instead.`}),n===`llmRequest`&&(0,K.jsx)(T,{variant:`meta`,className:`text-warning-foreground`,children:`LLM Request phase cannot be executed directly. It runs on the provider prompt during an agent call.`}),c&&(0,K.jsxs)(`div`,{className:`space-y-2 border-t border-border pt-4`,children:[(0,K.jsx)(T,{variant:`caption`,tone:`muted`,children:`Status`}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(eC,{variant:c.success?`success`:`destructive`,children:c.success?`Success`:`Failed`}),c.tripwire?.triggered&&(0,K.jsx)(eC,{variant:`info`,children:`Tripwire Triggered`})]}),c.tripwire?.triggered&&c.tripwire.reason&&(0,K.jsxs)(`div`,{className:`mt-2 rounded-md border border-warning-edge bg-warning-subtle p-3`,children:[(0,K.jsx)(T,{variant:`column`,className:`text-warning-subtle-foreground`,children:`Tripwire Reason`}),(0,K.jsx)(T,{variant:`caption`,tone:`muted`,className:`mt-1`,children:c.tripwire.reason})]})]})]})]}),(0,K.jsx)(`div`,{className:`absolute top-4 right-4 z-10`,children:(0,K.jsx)(gC,{content:m,tooltip:`Copy JSON result to clipboard`})}),(0,K.jsx)(`div`,{className:`relative h-full overflow-x-auto overflow-y-auto p-5`,children:(0,K.jsx)(_w,{value:u||m,editable:!0,theme:t,extensions:[mt,vw],basicSetup:{foldGutter:!1}})})]})}function lzi({processor:e}){return(0,K.jsxs)(`div`,{className:`border-b border-border px-5 pt-5 pb-4`,children:[(0,K.jsx)(T,{variant:`heading`,tone:`faint`,className:`mb-2`,children:e.name||e.id}),e.name&&e.name!==e.id&&(0,K.jsx)(T,{variant:`caption`,tone:`muted`,className:`mb-3`,children:e.id}),(0,K.jsx)(`div`,{className:`mt-3 flex flex-wrap gap-1`,children:e.phases.map(e=>(0,K.jsx)(eC,{children:e},e))}),(0,K.jsx)(`div`,{className:`mt-3`,children:(0,K.jsxs)(T,{variant:`meta`,tone:`muted`,children:[`Attached to `,e.configurations.length,` agent`,e.configurations.length===1?``:`s`]})})]})}var uzi=[eP(`/processors`),tMt];function dzi(){let{processorId:e}=kv(),{data:t,isLoading:n,error:r}=ajt({processorId:e,queryOptions:{enabled:!!e}});return r&&FN(r)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:uzi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(TH,{variant:`fill`})]}):r&&IN(r)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:uzi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(wH,{variant:`fill`,resource:`processors`})]}):!n&&t?.isWorkflow?(0,K.jsx)(Fv,{to:`/workflows/${e}/graph`,replace:!0}):n?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:uzi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(zS,{className:`mb-4 h-8 w-48`}),(0,K.jsx)(zS,{className:`h-32 w-full`})]}):(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:uzi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(`div`,{className:`h-full w-full overflow-y-hidden`,children:(0,K.jsx)(szi,{processorId:e})})]})}function fzi(){let e=cMi(),{data:t,isLoading:n}=ZNn({toolId:e}),{mutateAsync:r,status:i,data:a,error:o}=QNn(),s={execute:(t,n)=>r({toolId:e,input:t,requestContext:n}),status:i,output:a,error:o};return n?(0,K.jsx)(jQ.LoadingData,{}):t?(0,K.jsx)(BRi,{tool:t,execution:s,requestContextEntityType:`tool`,requestContextEntityId:t.id}):(0,K.jsxs)(jQ.NoData,{children:[`Tool "`,e,`" not found.`]})}var pzi=()=>(0,K.jsx)(Jx,{titleSlot:`No Tools yet`,descriptionSlot:(0,K.jsxs)(K.Fragment,{children:[`Mastra tools are not configured yet. `,(0,K.jsx)(`br`,{}),`More information in the documentation.`]}),actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/docs/agents/using-tools-and-mcp`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(tP,{}),children:`Tools documentation`}),variant:`fill`}),mzi=(e,t)=>{let n=new Map,r=Object.keys(t);for(let e of r){let r=t[e],i=r.tools,a=Object.keys(i);for(let t of a){let a=i[t];n.has(a.id)||n.set(a.id,{...a,agents:[]}),n.get(a.id).agents.push({...r,id:e})}}for(let[t,r]of Object.entries(e))n.has(r.id)||n.set(r.id,{...r,agents:[]});return Array.from(n.values())},hzi={name:e=>e.id,agents:e=>e.agents.length};function gzi({tools:e,agents:t,isLoading:n,search:r=``,sort:i,onSortChange:a,selectedToolId:o}){let{paths:s,Link:c}=sn(),l=(0,G.useMemo)(()=>mzi(e,t),[e,t]),u=(0,G.useMemo)(()=>IZ(l.filter(e=>e.id.toLowerCase().includes(r.toLowerCase())),i,hzi),[l,r,i]),{containerRef:d,getRowProps:f}=PZ({count:u.length,global:!0});if(n)return(0,K.jsx)(DH,{columns:`auto 1fr auto`});let p=e=>i?.key===e?i.direction:void 0;return(0,K.jsxs)(Z,{columns:`auto 1fr auto`,scrollRef:d,children:[(0,K.jsxs)(Z.Top,{children:[a?(0,K.jsx)(Z.SortableTopCell,{sortKey:`name`,sort:p(`name`),onSortChange:a,children:`Name`}):(0,K.jsx)(Z.TopCell,{children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`Description`}),a?(0,K.jsx)(Z.SortableTopCell,{sortKey:`agents`,sort:p(`agents`),onSortChange:a,align:`end`,children:`Agents`}):(0,K.jsx)(Z.TopCellSmart,{long:`Agents`,short:(0,K.jsx)(HN,{}),tooltip:`Attached agents`,className:`text-center`})]}),u.length===0&&r?(0,K.jsx)(Z.NoMatch,{message:`No Tools match your search`}):null,u.map((e,t)=>{let n=dJ(e.id,50),r=dJ(e.description??``,200),i=e.agents.length;return(0,K.jsxs)(Z.RowLink,{to:s.toolLink(e.id),LinkComponent:c,featured:e.id===o,...f(t),children:[(0,K.jsx)(Z.NameCell,{children:n}),(0,K.jsx)(Z.DescriptionCell,{children:r}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:i||``})]},e.id)})]})}var $9=[eP(`/tools`)];function _zi(){let{data:e={},isLoading:t,error:n}=wN(),{data:r={},isLoading:i,error:a}=Fq(),[o,s]=(0,G.useState)(``),[c,l]=(0,G.useState)(),{toolId:u}=FMi(),d=t||i,f=a||n;return f&&FN(f)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:$9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Tools`}),(0,K.jsx)(TH,{variant:`fill`})]}):f&&IN(f)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:$9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Tools`}),(0,K.jsx)(wH,{variant:`fill`,resource:`tools`})]}):f?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:$9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Tools`}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load tools`,descriptionSlot:f.message})]}):Object.keys(r).length===0&&!d?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:$9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Tools`}),(0,K.jsx)(pzi,{})]}):(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:$9}),actionRow:(0,K.jsx)(TK,{children:(0,K.jsx)(TK.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(MH,{...NH,onValueChange:s,label:`Search tools`,placeholder:`Search by name`})})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Tools`}),(0,K.jsx)(gzi,{tools:r,agents:e,isLoading:d,search:o,sort:c,onSortChange:(e,t)=>l({key:t,direction:e}),selectedToolId:u}),(0,K.jsx)(IMi,{children:(0,K.jsx)(fzi,{})})]})}var vzi=()=>{let e=Ov();return(0,K.jsx)(on,{Link:mS,navigate:t=>e(t),paths:xDn,children:(0,K.jsxs)(en,{children:[(0,K.jsx)(ZRi,{}),(0,K.jsx)(XRi,{children:(0,K.jsx)(mRi,{children:(0,K.jsx)(Lqe,{children:(0,K.jsx)(Iv,{})})})})]})})},yzi=()=>{let e=Ov();return(0,K.jsx)(on,{Link:mS,navigate:t=>e(t),paths:xDn,children:(0,K.jsx)(hRi,{children:(0,K.jsx)(Iv,{})})})},bzi=!!window.MASTRA_CLOUD_API_ENDPOINT,xzi=At.has(`datasets`),Szi=[{index:!0,element:(0,K.jsx)(Nsi,{})},{path:`instruction-blocks`,element:(0,K.jsx)(Psi,{})},{path:`tools`,element:(0,K.jsx)(Rsi,{})},{path:`agents`,element:(0,K.jsx)(Tsi,{})},{path:`scorers`,element:(0,K.jsx)(Isi,{})},{path:`workflows`,element:(0,K.jsx)(Bsi,{})},{path:`skills`,element:(0,K.jsx)(Lsi,{})},{path:`memory`,element:(0,K.jsx)(Fsi,{})},{path:`variables`,element:(0,K.jsx)(zsi,{})}],Czi=[{element:(0,K.jsx)(yLi,{}),children:[{path:`/login`,element:(0,K.jsx)(mki,{})},{path:`/signup`,element:(0,K.jsx)(MNi,{})}]},{path:`/agent-builder`,element:(0,K.jsx)(jqe,{paths:xDn}),children:[{index:!0,element:(0,K.jsx)(wDn,{})},{path:`agents`,element:(0,K.jsx)(Z9,{}),children:[{index:!0,element:(0,K.jsx)(XNn,{})}]},{path:`agents`,element:(0,K.jsx)(ORi,{}),children:[{path:`create`,element:(0,K.jsx)(lPn,{})},{path:`:id`,loader:({params:e})=>K_(`/agent-builder/agents/${e.id}/view`)},{path:`:id/edit`,element:(0,K.jsx)(q6n,{})},{path:`:id/view`,element:(0,K.jsx)(i5n,{})}]},{path:`skills`,element:(0,K.jsx)(Z9,{}),children:[{index:!0,element:(0,K.jsx)(i7n,{})}]},{path:`skills`,element:(0,K.jsx)(ORi,{}),children:[{path:`create`,element:(0,K.jsx)(c7n,{})},{path:`:id`,loader:({params:e})=>K_(`/agent-builder/skills/${e.id}/edit`)},{path:`:id/edit`,element:(0,K.jsx)(P7n,{})},{path:`:id/view`,element:(0,K.jsx)(H7n,{})}]},{path:`infrastructure`,element:(0,K.jsx)(Z9,{}),children:[{index:!0,element:(0,K.jsx)(K5n,{})}]},{path:`favorite`,element:(0,K.jsx)(Z9,{}),children:[{index:!0,element:(0,K.jsx)(h5n,{})}]},{path:`library`,element:(0,K.jsx)(Z9,{}),children:[{index:!0,element:(0,K.jsx)(q5n,{})}]}]},{element:(0,K.jsx)(yzi,{}),children:[{path:`/agents/:agentId/session`,element:(0,K.jsx)(BQr,{})},{path:`/agents/:agentId/session/:threadId`,element:(0,K.jsx)(BQr,{})}]},{element:(0,K.jsx)(vzi,{}),children:[...bzi?[]:[{path:`/settings`,element:(0,K.jsx)(jNi,{})},{path:`/templates`,element:(0,K.jsx)(LPi,{})},{path:`/templates/:templateSlug`,element:(0,K.jsx)(eFi,{})}],{path:`/logs`,element:(0,K.jsx)(mAi,{})},{path:`/scorers`,element:(0,K.jsx)(pNi,{})},{path:`/scorers/:scorerId`,element:(0,K.jsx)(xNi,{})},{path:`/metrics`,element:(0,K.jsx)(tNi,{})},{path:`/intelligence`,element:(0,K.jsx)(bhn,{})},{path:`/intelligence/entities/:entityType/:entityId`,element:(0,K.jsx)(Uhn,{})},{element:(0,K.jsx)(ezi,{children:(0,K.jsx)(Iv,{})}),children:[{path:`/traces`,element:(0,K.jsx)(Csi,{})},{path:`/spans`,element:(0,K.jsx)(gPi,{})},{path:`/threads`,element:(0,K.jsx)(mFi,{})}]},{path:`/traces/:traceId`,loader:({params:e,request:t})=>{let n=new URL(t.url).searchParams;return n.set(`traceId`,e.traceId??``),K_(`/traces?${n.toString()}`)}},{path:`/observability`,loader:({request:e})=>K_(`/traces${new URL(e.url).search}`)},{path:`/resources`,element:(0,K.jsx)(dNi,{})},{path:`/agents`,element:(0,K.jsx)(S9n,{})},{path:`/cms/agents/create`,element:(0,K.jsx)(Dsi,{}),children:Szi},{path:`/cms/agents/:agentId/edit`,element:(0,K.jsx)(Msi,{}),children:Szi},{path:`/cms/scorers/create`,element:(0,K.jsx)(Ysi,{})},{path:`/cms/scorers/:scorerId/edit`,element:(0,K.jsx)($si,{})},{path:`/prompts`,element:(0,K.jsx)(sNi,{})},{path:`/cms/prompts/create`,element:(0,K.jsx)(Hsi,{})},{path:`/cms/prompts/:promptBlockId/edit`,element:(0,K.jsx)(qsi,{})},{path:`/agents/:agentId`,element:(0,K.jsx)(KRi,{children:(0,K.jsx)(Iv,{})}),children:[{index:!0,loader:_Dn},{path:`chat`,loader:vDn},{path:`chat/:threadId`,loader:vDn},{path:`threads`,loader:gDn},{path:`threads/:threadId`,element:(0,K.jsx)(v1r,{})},{path:`overview`,loader:bDn},{path:`settings`,loader:bDn},...xzi?[{path:`editor`,element:(0,K.jsx)(e0r,{})}]:[],{path:`traces`,element:(0,K.jsx)(wsi,{})},{path:`channels`,loader:({params:e})=>K_(`/agents/${e.agentId}/threads/new`)}]},{path:`/tools`,element:(0,K.jsx)(_zi,{})},{path:`/integrations`,element:(0,K.jsx)(bwi,{})},{path:`/connections`,element:(0,K.jsx)(eli,{})},{path:`/processors`,element:(0,K.jsx)(azi,{})},{path:`/processors/:processorId`,element:(0,K.jsx)(dzi,{})},{path:`/mcps`,element:(0,K.jsx)(PAi,{})},{path:`/mcps/:serverId`,element:(0,K.jsx)(LMi,{})},{path:`/workspaces`,element:(0,K.jsx)(gLi,{})},{path:`/workspaces/:workspaceId`,element:(0,K.jsx)(gLi,{})},{path:`/workspaces/:workspaceId/skills/:skillName`,loader:({params:e,request:t})=>K_(wK(e.workspaceId,new URL(t.url).searchParams.get(`path`)))},{path:`/workflows`,element:(0,K.jsx)(DFi,{})},{path:`/workflows/schedules`,element:(0,K.jsx)(GFi,{})},{path:`/workflows/schedules/:scheduleId`,element:(0,K.jsx)(zFi,{})},{path:`/workflows/:workflowId`,element:(0,K.jsx)(TMt,{children:(0,K.jsx)(Iv,{})}),children:[{index:!0,loader:({params:e})=>K_(`/workflows/${e.workflowId}/graph`)},{path:`graph`,element:(0,K.jsx)(fIi,{})},{path:`graph/:runId`,element:(0,K.jsx)(fIi,{})},{path:`traces`,element:(0,K.jsx)(mIi,{})},{path:`schedules`,element:(0,K.jsx)(pIi,{})}]},{path:`/knowledge`,element:(0,K.jsx)(dki,{})},...xzi?[{path:`/datasets`,element:(0,K.jsx)(Fli,{})},{path:`/datasets/:datasetId`,element:(0,K.jsx)(dhi,{}),children:[{path:`items/:itemId`,element:null}]},{path:`/datasets/:datasetId/edit`,element:(0,K.jsx)(vhi,{})},{path:`/datasets/:datasetId/items/:itemId/versions`,element:(0,K.jsx)(Chi,{})},{path:`/experiments`,element:(0,K.jsx)(g_i,{})},{path:`/experiments/compare`,element:(0,K.jsx)(j_i,{})},{path:`/experiments/review-queue`,element:(0,K.jsx)(lwi,{})},{path:`/experiments/:experimentId`,element:(0,K.jsx)(GCi,{}),children:[{path:`items/:itemId`,element:null}]},{path:`/datasets/:datasetId/versions`,element:(0,K.jsx)(Dhi,{})}]:[],{index:!0,element:(0,K.jsx)(SDn,{})}]}];function wzi(){let e=window.MASTRA_STUDIO_BASE_PATH||``,{baseUrl:t,headers:n,apiPrefix:r,isLoading:i}=yS(),a=(0,G.useMemo)(()=>t?vFe(t,r):void 0,[t,r]),o=(0,G.useMemo)(()=>({...n,"x-mastra-client-type":`studio`}),[n]),s=(0,G.useMemo)(()=>jze(Czi,{basename:e}),[e]);return i?(0,K.jsx)(`div`,{className:`flex h-screen w-full items-center justify-center`,children:(0,K.jsx)(It,{})}):t?(0,K.jsx)(tPe,{baseUrl:t,headers:o,apiPrefix:r,customFetch:a,children:(0,K.jsx)(Dqe,{children:(0,K.jsx)(hDn,{children:(0,K.jsx)(Yqe,{baseUrl:t,children:(0,K.jsx)(dze,{router:s})})})})}):(0,K.jsx)(aVr,{})}function Tzi(){let e=window.MASTRA_SERVER_PROTOCOL||`http`,t=window.MASTRA_SERVER_HOST||`localhost`,n=window.MASTRA_SERVER_PORT||4111,r=window.MASTRA_API_PREFIX||`/api`,i=window.MASTRA_CLOUD_API_ENDPOINT||``,a=window.MASTRA_AUTO_DETECT_URL===`true`,o=i||(a?window.location.origin:`${e}://${t}:${n}`);return(0,K.jsx)(dhn,{children:(0,K.jsx)(Jqe,{endpoint:o,defaultApiPrefix:r,children:(0,K.jsx)(wzi,{})})})}function Ezi(){(0,kt.createRoot)(document.getElementById(`root`)).render((0,K.jsx)(G.StrictMode,{children:(0,K.jsx)(Tzi,{})}))}export{Ezi as startStudio};
|