@mastra/deployer-cloud 1.83.0 → 1.84.0-alpha.0

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.
@@ -721,6 +721,6 @@ window.parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/sandbox-proxy-
721
721
  ]`,Zhi=[{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 Qhi(){let{isCopied:e,handleCopy:t}=Aw({text:Xhi,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:Zhi.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)(uZ,{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)(bw,{variant:`success`,size:`xs`,children:`required`}):(0,K.jsx)(bw,{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)(Bn,{}):(0,K.jsx)(xr,{}),variant:`ghost`,size:`sm`,onClick:t,children:e?`Copied`:`Copy`})]}),(0,K.jsx)(FT,{variant:`embedded`,language:`json`,editable:!1,lineNumbers:!1,showCopyButton:!1,value:Xhi,className:`p-3`})]}),(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:Yhi,target:`_blank`,rel:`noopener noreferrer`}),className:`self-start`,icon:(0,K.jsx)(Br,{}),children:`Datasets documentation`})]})}var $hi=10,egi=`[
722
722
  { "input": "…", "groundTruth": "…" }
723
723
  ]`,tgi=`flex min-h-0 flex-1 flex-col py-0`;function ngi({tab:e,onTabChange:t,file:n,onFileSelect:r,onReplace:i,pastedText:a,onPastedTextChange:o,validation:s,isImporting:c}){return(0,K.jsxs)(CA,{value:e,defaultTab:`upload`,onValueChange:t,className:`flex h-full flex-col gap-3`,children:[(0,K.jsxs)(SA,{variant:`pill`,children:[(0,K.jsx)(wA,{value:`upload`,children:`Upload file`}),(0,K.jsx)(wA,{value:`paste`,children:`Paste JSON`})]}),(0,K.jsx)(TA,{value:`upload`,className:tgi,children:n?(0,K.jsx)(ogi,{file:n,validation:s,onReplace:i,isImporting:c}):(0,K.jsx)(rgi,{onFileSelect:r,disabled:c})}),(0,K.jsx)(TA,{value:`paste`,className:tgi,children:(0,K.jsx)(FT,{"aria-label":`JSON items`,language:`json`,lineNumbers:!1,showCopyButton:!1,placeholder:egi,value:a,onChange:o,editable:!c,className:`min-h-50 flex-1`})})]})}function rgi({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:m(`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)(kc,{className:`size-4`})}),(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 `,ppi]})]})}function igi(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`}function agi(e){return typeof e==`string`?e:JSON.stringify(e)??``}function ogi({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,$hi);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)(qr,{className:`size-4 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:igi(e.size)}),(0,K.jsx)(X,{icon:(0,K.jsx)(Zo,{}),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:agi(e.input)}),e.hasInput?e.hasGroundTruth?null:(0,K.jsx)(bw,{variant:`warning`,size:`xs`,children:`no groundTruth`}):(0,K.jsx)(bw,{variant:`destructive`,size:`xs`,children:`no input`})]},e.index)),a>$hi&&(0,K.jsxs)(T,{as:`p`,variant:`meta`,tone:`muted`,className:`border-t border-border px-3 py-1.5`,children:[`+ `,a-$hi,` more`]})]})}var sgi=e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsText(e)});function cgi({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}=zP(),x=a===`upload`?l:p,S=(0,G.useMemo)(()=>a===`upload`&&d?{status:`error`,kind:`parse`,message:d}:gpi(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 ${ppi}`);else try{let n=await sgi(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}),UC.success(`Imported ${S.total} item${S.total===1?``:`s`}`),i?.(),r(!1),E()}catch(e){UC.error(e instanceof Error?e.message:`Failed to import items`)}finally{g(!1)}}},[S,b,e,i,r,E]);return(0,K.jsx)(_E,{open:n,onOpenChange:D,pending:h,children:(0,K.jsxs)(vE,{size:`xl`,children:[(0,K.jsxs)(yE,{children:[(0,K.jsx)(SE,{children:`Import into dataset`}),(0,K.jsxs)(CE,{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)(xE,{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)(ngi,{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)(Qhi,{})})]})}),(0,K.jsxs)(bE,{children:[(0,K.jsx)(lgi,{validation:S}),(0,K.jsx)(wE,{children:`Cancel`}),(0,K.jsxs)(gE,{onConfirm:O,disabled:S.status!==`ready`,children:[h&&(0,K.jsx)(Zc,{}),S.status===`ready`?`Import ${S.total} item${S.total===1?``:`s`}`:`Import`]})]})]})})}function lgi({validation:e}){let t=m(`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)(Gw,{singleLine:!0,children:[(0,K.jsxs)(Gw.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)(Gw.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 ${ppi}`;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)(uZ,{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 ugi(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 dgi({active:e,onPrevious:t,onNext:n,onClose:r}){(0,G.useEffect)(()=>{if(!e)return;let i=e=>{e.defaultPrevented||ugi(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 fgi=(0,G.createContext)(null);function pgi({datasetId:e,items:t,isLoadingItems:n,children:r}){let i=kb(),a=KWe(`/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]);dgi({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)(fgi.Provider,{value:d,children:r})}function mgi(){let e=(0,G.useContext)(fgi);if(!e)throw Error(`useDatasetItemPanel must be used within a DatasetItemPanelProvider`);return e}var hgi=[`createdAt`];function ggi({datasetId:e,onAddItemClick:t,onNavigateToDataset:n,toolbarActionsSlot:r}){let[i,a]=Hb(),{activeVersion:o}=GP(i,a),{sort:s,onSortChange:c}=c7({searchParams:i,setSearchParams:a,allowedKeys:hgi}),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]=Ew(O,300),{data:j}=VP({datasetId:e,queryOptions:{enabled:!!e}}),{data:M=[],isLoading:N,setEndOfListElement:P,isFetchingNextPage:F,hasNextPage:I}=RP({datasetId:e,search:A||void 0,version:o,orderBy:l,queryOptions:{enabled:!!e}}),{deleteItems:L}=zP(),{currentItemId:R,openItem:z,close:B}=mgi();return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`grid h-full overflow-auto`,children:(0,K.jsx)(Jhi,{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)(Bhi,{datasetId:e,open:u,onOpenChange:d}),(0,K.jsx)(cgi,{datasetId:e,datasetName:j?.name,open:f,onOpenChange:p}),(0,K.jsx)(Tpi,{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)(Epi,{open:v,onOpenChange:e=>{y(e),e||(x([]),D(e=>e+1))},items:b,currentDatasetId:e}),(0,K.jsx)(aP,{open:S,onOpenChange:C,children:(0,K.jsxs)(aP.Content,{children:[(0,K.jsxs)(aP.Header,{children:[(0,K.jsx)(aP.Title,{children:`Delete Items`}),(0,K.jsxs)(aP.Description,{children:[`Are you sure you want to delete `,w.length,` item`,w.length===1?``:`s`,`? This action cannot be undone.`]})]}),(0,K.jsxs)(aP.Footer,{children:[(0,K.jsx)(aP.Cancel,{children:`Cancel`}),(0,K.jsx)(aP.Action,{onClick:async()=>{await L.mutateAsync({datasetId:e,itemIds:w}),UC.success(`Deleted ${w.length} items`),C(!1),T([]),D(e=>e+1)},children:L.isPending?`Deleting...`:`Delete`})]})]})})]})}var _gi=`__create_tag__`;function vgi({datasetId:e}){let{data:t}=VP({datasetId:e,queryOptions:{enabled:!!e}}),{data:n}=BP(),{updateDataset:r}=zP(),[i,a]=(0,G.useState)(``),o=(0,G.useMemo)(()=>Array.isArray(t?.tags)?t.tags:[],[t?.tags]),s=(0,G.useMemo)(()=>Efi(n?.datasets??[]),[n?.datasets]),c=(0,G.useMemo)(()=>{let e=s.map(e=>({label:e,value:e,end:o.includes(e)?(0,K.jsx)(Bn,{"data-testid":`tag-applied`,className:`size-3.5`}):void 0})),t=i.trim();return t.length>0&&!s.includes(t)&&!o.includes(t)?[{label:`Create "${t}"`,value:_gi},...e]:e},[s,o,i]),l=t=>{r.mutate({datasetId:e,tags:t},{onError:()=>UC.error(`Failed to update tags`)})},u=e=>{let t=e===_gi?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)(Ofi,{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)(Vc,{className:`size-3`})})]},e)),(0,K.jsx)(TP,{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 N7=e=>JSON.stringify(e??null,null,2),ygi=e=>e==null||e===``||typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0,bgi=[{key:`input`,title:`Input`,icon:(0,K.jsx)(Qr,{}),value:e=>N7(e.input),payload:e=>e.input},{key:`groundTruth`,title:`Ground Truth`,icon:(0,K.jsx)(ei,{}),value:e=>ygi(e.groundTruth)?void 0:N7(e.groundTruth),payload:e=>ygi(e.groundTruth)?null:e.groundTruth},{key:`expectedTrajectory`,title:`Expected Trajectory`,icon:(0,K.jsx)(cs,{}),value:e=>e.expectedTrajectory==null?void 0:N7(e.expectedTrajectory)},{key:`toolMocks`,title:`Tool Mocks`,icon:(0,K.jsx)(zc,{}),value:e=>e.toolMocks?.length?N7(e.toolMocks):void 0},{key:`requestContext`,title:`Request Context`,icon:(0,K.jsx)(Cn,{}),value:e=>e.requestContext==null?void 0:N7(e.requestContext)},{key:`metadata`,title:`Metadata`,icon:(0,K.jsx)(Zs,{}),value:e=>N7(e.metadata)}],xgi=e=>e.toFixed(2);function Sgi({delta:e,format:t=xgi,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),c=(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-3.5 shrink-0 [&>svg]:size-3.5`,children:e>0?(0,K.jsx)(Jt,{}):e<0?(0,K.jsx)(At,{}):null})]}),l=m(`inline-flex items-center gap-1 tabular-nums`,i);return s?(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{render:(0,K.jsx)(`span`,{tabIndex:0,className:l}),children:c}),(0,K.jsx)(CC,{children:o})]}):(0,K.jsx)(`span`,{className:l,children:c})}function Cgi({scorerId:e}){let{Link:t,paths:n}=gl();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 wgi({metrics:e}){if(e.length===0)return null;let t=e.some(e=>e.delta!=null);return(0,K.jsx)(`dl`,{className:m(`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:c,emphasis:l})=>(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-3.5 [&>svg]:shrink-0`,children:[n,r]}),(0,K.jsx)(`dd`,{className:m(`flex min-w-0 justify-end text-right text-foreground tabular-nums`,l?`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)(Sgi,{delta:a,format:o,higherIsBetter:c,baseline:s==null?void 0:s-a})})]},e))})}function P7({value:e}){return(0,K.jsx)(`div`,{className:`min-w-0 p-3 text-foreground`,children:typeof e==`string`?(0,K.jsx)(xX,{children:e}):(0,K.jsx)(FT,{value:JSON.stringify(e??null,null,2),language:`json`,editable:!1,lineNumbers:!1,showCopyButton:!1,variant:`embedded`,"aria-label":`JSON payload`})})}var Tgi=`grid content-start gap-5`;function F7({title:e,actions:t,tone:n=`default`,collapsible:r=!0,framed:i=!1,expanded:a,onExpandedChange:o,children:s}){let c=W$({collapsedHeight:160}),l=a===void 0||!o?c:{...c,isExpanded:a,setExpanded:o,toggleExpanded:()=>o(!a)},u=r?(0,K.jsx)(U$,{state:l,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)(m$.SectionHeading,{className:m(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:u}):(0,K.jsx)(dF,{className:`min-w-0 overflow-hidden`,children:u}):u,r&&l.isExpanded&&l.isClipped&&(0,K.jsx)(`div`,{className:`flex justify-center pt-1`,children:(0,K.jsx)(X,{size:`sm`,variant:`ghost`,icon:(0,K.jsx)(ro,{}),onClick:()=>l.setExpanded(!1),children:`Collapse`})})]})]})}function Egi({item:e,diff:t}){return(0,K.jsxs)(`div`,{className:Tgi,children:[(0,K.jsx)(wgi,{metrics:Dgi(e)}),bgi.map(n=>{if(n.payload&&!t){let t=n.payload(e);return t==null?null:(0,K.jsx)(F7,{title:n.title,framed:!0,actions:(0,K.jsx)(jw,{content:typeof t==`string`?t:JSON.stringify(t,null,2)}),children:(0,K.jsx)(P7,{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)(m$.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)(m$.CodeSection,{title:n.title,icon:n.icon,codeStr:r,diff:t?{against:i??``,side:t.side}:void 0},n.key)})]})}function Dgi(e){let t=e.updatedAt&&new Date(e.updatedAt).getTime()!==new Date(e.createdAt).getTime(),n=[{id:`item-id`,icon:(0,K.jsx)(ui,{}),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:hU(e.id)}),(0,K.jsx)(jw,{content:e.id,tooltip:`Copy item ID to clipboard`,variant:`link`})]}),delta:null},{id:`created`,icon:(0,K.jsx)(Fn,{}),label:`Created`,value:Fw(e.createdAt,`date-time`),delta:null}];return t&&n.push({id:`updated`,icon:(0,K.jsx)(Nn,{}),label:`Updated`,value:Fw(e.updatedAt,`date-time`),delta:null}),n}function Ogi({field:e,errors:t}){return t.length===0?null:(0,K.jsx)(gA,{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 kgi({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)(Lo,{className:`h-5 w-5`}),` Edit Item`]})}),(0,K.jsxs)(`div`,{className:`space-y-6`,children:[(0,K.jsxs)(fA,{invalid:f?.field===`input`,children:[(0,K.jsx)(mA,{required:!0,children:`Input (JSON)`}),(0,K.jsx)(FT,{value:e,onChange:t,showCopyButton:!1,className:`min-h-[120px]`}),f?.field===`input`&&(0,K.jsx)(Ogi,{field:`input`,errors:f.errors})]}),(0,K.jsxs)(fA,{invalid:f?.field===`groundTruth`,children:[(0,K.jsx)(mA,{children:`Ground Truth (JSON, optional)`}),(0,K.jsx)(FT,{value:n,onChange:r,showCopyButton:!1,className:`min-h-[100px]`}),f?.field===`groundTruth`&&(0,K.jsx)(Ogi,{field:`groundTruth`,errors:f.errors})]}),(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{children:`Expected Trajectory (JSON, optional)`}),(0,K.jsx)(FT,{value:o,onChange:s,showCopyButton:!1,className:`min-h-[80px]`})]}),(0,K.jsxs)(fA,{invalid:f?.field===`toolMocks`,children:[(0,K.jsx)(mA,{children:`Tool Mocks (JSON array, optional)`}),(0,K.jsxs)(hA,{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)(FT,{value:c,onChange:l,showCopyButton:!1,className:`min-h-[100px]`}),f?.field===`toolMocks`&&(0,K.jsx)(Ogi,{field:`toolMocks`,errors:f.errors})]}),(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{children:`Request Context (JSON, optional)`}),(0,K.jsx)(FT,{value:u,onChange:d,showCopyButton:!1,className:`min-h-[80px]`})]}),(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{children:`Metadata (JSON, optional)`}),(0,K.jsx)(FT,{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)(Bn,{}),variant:`primary`,onClick:p,disabled:h,children:h?`Saving...`:`Save changes`}),(0,K.jsx)(X,{icon:(0,K.jsx)(Vc,{}),onClick:m,disabled:h,children:`Cancel`})]})]})]})}function Agi(){return(0,K.jsxs)(Uw,{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 jgi({provider:e,modelId:t,canReset:n,onProviderChange:r,onModelIdChange:i,onReset:a,container:o}){let s=GC(),{isLoading:c}=FJ(),[l,u]=(0,G.useState)(!1);return s.active&&s.pickerVisible===!1?(0,K.jsxs)(_A,{className:`gap-2`,children:[(0,K.jsx)(vA,{children:`Model`}),(0,K.jsx)(`div`,{children:(0,K.jsx)(bw,{icon:(0,K.jsx)(Aa,{}),children:`Locked by admin`})})]}):(0,K.jsxs)(_A,{className:`gap-2`,children:[(0,K.jsx)(vA,{children:`Model`}),c?(0,K.jsx)(dw,{className:`h-control-md w-60 rounded-full`}):(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsxs)(fU,{className:`min-w-0`,children:[(0,K.jsx)(LJ,{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)(RJ,{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)(os,{})})]})]})}var Mgi=(e,t)=>`${e}:${t}`,Ngi=(e,t)=>e?.value===t?.value;function Pgi({datasets:e,datasetId:t,version:n,onDatasetChange:r,container:i}){let{total:a}=RP({datasetId:t,search:void 0,version:n,queryOptions:{enabled:!!t}}),o=e.find(e=>e.value===t)??null;return(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{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)(bP,{items:e,value:o,onValueChange:e=>e&&r(e.value),isItemEqualToValue:Ngi,autoHighlight:!0,children:[(0,K.jsx)(BPt,{placeholder:`Select a dataset`,children:a!==void 0&&(0,K.jsxs)(Gw,{children:[(0,K.jsxs)(Gw.Item,{children:[a,` `,a===1?`item`:`items`]}),(0,K.jsx)(Gw.Item,{children:n===void 0?`latest`:`v${n}`})]})}),(0,K.jsxs)(xP,{container:i,children:[(0,K.jsx)(wP,{children:`No datasets found`}),(0,K.jsx)(SP,{children:e=>(0,K.jsx)(CP,{value:e,children:e.label},e.value)})]})]})]})}function Fgi(e,t){return t!==void 0||(e??1)>1}function Igi({datasetId:e,version:t,onVersionChange:n,container:r}){let{data:i}=VP({datasetId:e,queryOptions:{enabled:!!e}});return Fgi(i?.version,t)?(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{children:`Dataset version`}),(0,K.jsx)(jIt,{datasetId:e,value:t??null,onValueChange:e=>n(e??void 0),container:r})]}):null}function Lgi({description:e,onDescriptionChange:t,disabled:n}){return(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{children:`Description`}),(0,K.jsx)(ZA,{value:e,onChange:e=>t(e.target.value),placeholder:`Optional`,rows:2,disabled:n})]})}function Rgi({name:e,defaultName:t,onNameChange:n,disabled:r}){return(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{children:`Experiment name`}),(0,K.jsx)(ZM,{value:e,placeholder:t,onChange:e=>n(e.target.value),disabled:r})]})}function zgi(e){try{return Kk(e)}catch(e){console.error(`Failed to parse requestContextSchema:`,e);return}}function Bgi({requestContextSchema:e,onChange:t}){let[n]=(0,G.useState)(()=>zgi(e));return n?(0,K.jsxs)(_A,{children:[(0,K.jsx)(vA,{children:`Request context`}),(0,K.jsx)(nP,{schema:n,onValuesChange:t,className:`[&_button[type=submit]]:hidden`})]}):(0,K.jsx)(`div`,{role:`alert`,children:(0,K.jsx)(EA,{variant:`destructive`,children:`Failed to parse request context schema`})})}function Vgi({schema:e,raw:t,onRawChange:n,onValuesChange:r}){return e?(0,K.jsx)(Bgi,{requestContextSchema:e,onChange:r}):(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{children:`Request context (JSON)`}),(0,K.jsx)(FT,{value:t,onChange:n,showCopyButton:!1,"aria-label":`Request context JSON`,className:`min-h-[120px]`})]})}function Hgi({onRun:e,canRun:t,isRunning:n}){return(0,K.jsx)(gE,{onConfirm:e,disabled:!t,children:(0,K.jsx)(Ugi,{isRunning:n})})}function Ugi({isRunning:e}){return e?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Zc,{className:`h-4 w-4`}),`Starting…`]}):`Run experiment`}function Wgi({scorer:e}){let t=(0,K.jsx)(CP,{value:e,children:e.label});return e.description?(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{render:t}),(0,K.jsx)(CC,{side:`right`,className:`max-w-64`,children:e.description})]}):t}function Ggi(){let{data:e}=eF();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 Kgi(e,t){return e.map(e=>t.find(t=>t.value===e)??{value:e,label:e})}function qgi({scorerIds:e,usesDefaultScorers:t,onScorerIdsChange:n,container:r}){let i=Ggi();return(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{info:`Grade each output automatically. Outputs are saved either way, so you can always review them yourself.`,children:`Scorers`}),(0,K.jsxs)(bP,{multiple:!0,items:i,value:Kgi(e,i),onValueChange:e=>n(e.map(e=>e.value)),isItemEqualToValue:Ngi,autoHighlight:!0,children:[(0,K.jsx)(qPt,{children:(0,K.jsx)(IPt,{children:e=>(0,K.jsxs)(K.Fragment,{children:[e.map(e=>(0,K.jsx)(JPt,{children:e.label},e.value)),(0,K.jsx)(YPt,{placeholder:e.length===0?`No scoring, read the outputs yourself`:void 0})]})})}),(0,K.jsxs)(xP,{container:r,children:[(0,K.jsx)(wP,{children:`No scorers registered`}),(0,K.jsx)(SP,{children:e=>(0,K.jsx)(Wgi,{scorer:e},e.value)})]})]}),t&&(0,K.jsx)(hA,{children:`The dataset's default scorers.`})]})}var Jgi=[{type:`agent`,label:`Agents`},{type:`workflow`,label:`Workflows`},{type:`scorer`,label:`Scorers`}];function Ygi(e){return Jgi.map(t=>({value:t.label,items:e.filter(e=>e.type===t.type)})).filter(e=>e.items.length>0)}function Xgi({options:e,isLoading:t,target:n,onTargetValueChange:r,container:i,className:a}){return(0,K.jsxs)(fA,{className:a,children:[(0,K.jsx)(mA,{required:!0,info:`What runs on each item: an agent, a workflow, or a scorer you want to test.`,children:`Target`}),(0,K.jsxs)(bP,{items:Ygi(e),value:n??null,onValueChange:e=>r(e?.value??``),isItemEqualToValue:Ngi,disabled:t,autoHighlight:!0,children:[(0,K.jsx)(BPt,{placeholder:`Pick an agent, workflow or scorer`}),(0,K.jsxs)(xP,{container:i,children:[(0,K.jsx)(wP,{children:`Nothing to run`}),(0,K.jsx)(SP,{children:(e,t)=>(0,K.jsxs)(UPt,{items:e.items,children:[t>0?(0,K.jsx)(KPt,{}):null,(0,K.jsx)(WPt,{children:e.value}),(0,K.jsx)(GPt,{children:e=>(0,K.jsx)(CP,{value:e,children:e.label},e.value)})]},e.value)})]})]})]})}var Zgi=(e,t)=>e.provider===t?.provider&&e.modelId===t?.modelId;function Qgi(e){let[t,n]=(0,G.useState)(null),r=t??e??{provider:``,modelId:``},i=t?.provider&&t.modelId&&!Zgi(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&&!Zgi(t,e),agentModel:i}}function $gi(e,t){return e||(t[0]?.value??``)}function e_i({initialDatasetId:e,initialDatasetVersion:t}){let{data:n}=BP(),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:$gi(i,r),version:o,setVersion:s,selectDataset:e=>{a(e),s(void 0)}}}function t_i({initialName:e,targetLabel:t}){let[n,r]=(0,G.useState)(e??``),[i]=(0,G.useState)(Pui),a=Fui(t??`experiment`,i);return{name:n,setName:r,defaultName:a,runName:n.trim()||a}}var n_i=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function r_i(e){if(n_i(e)&&Object.keys(e).length!==0)return e}function i_i(e){try{return{ok:!0,value:JSON.parse(e)}}catch{return{ok:!1}}}function a_i(e){if(!e.trim())return{ok:!0};let t=i_i(e);return t.ok?n_i(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 o_i(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 s_i(e){let{data:t}=VP({datasetId:e,queryOptions:{enabled:!!e}}),[n,r]=(0,G.useState)(``),[i,a]=(0,G.useState)({}),o=r_i(t?.requestContextSchema);return{schema:o,raw:n,setRaw:r,setValues:a,resetValues:()=>a({}),resolve:()=>o?o_i(i):a_i(n)}}function c_i({datasetId:e,initialScorerIds:t}){let{data:n}=VP({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 l_i=(e,t,n,r)=>({value:Mgi(e,t),label:n,type:e,id:t,defaultModel:r});function u_i(e,t){if(e&&t)return{provider:Lq(e),modelId:t}}function d_i(){let{data:e,isLoading:t}=PP(),{data:n,isLoading:r}=sP({}),{data:i,isLoading:a}=eF();return{options:[...Object.entries(e??{}).map(([e,t])=>l_i(`agent`,e,t.name||e,u_i(t.provider,t.modelId))),...Object.entries(n??{}).map(([e,t])=>l_i(`workflow`,e,t.name||e)),...Object.entries(i??{}).map(([e,t])=>l_i(`scorer`,e,t.scorer?.config?.name||e))],isLoading:t||r||a}}function f_i({initialTargetType:e,initialTargetId:t}){return!e||!t?``:Mgi(e,t)}function p_i(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 m_i(e){let{options:t,isLoading:n}=d_i(),[r,i]=(0,G.useState)(()=>f_i(e));return{options:t,isLoading:n,target:p_i(t,r,e),setTargetValue:i}}var h_i=e=>(e.metaKey||e.ctrlKey)&&e.key===`Enter`,g_i=e=>e.trim()||void 0,__i=e=>e.length>0?e:void 0;function v_i({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=m_i({initialTargetType:s,initialTargetId:c}),p=e_i({initialDatasetId:i,initialDatasetVersion:a}),m=c_i({datasetId:p.datasetId,initialScorerIds:o}),h=s_i(p.datasetId),{target:g}=f,_=Qgi(g?.defaultModel),v=g?.type===`agent`,y=v?_.agentModel:void 0,b=t_i({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}=zP(),{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)BC.error(e.message);else try{let n=await T.mutateAsync({datasetId:E,name:b.runName,description:g_i(x),targetType:g.type,targetId:g.id,agentModel:y,scorerIds:__i(m.scorerIds),version:p.version,requestContext:e.requestContext});BC.success(`Experiment started`),t(!1),r?.(n.experimentId)}catch(e){BC.error(e instanceof Error?e.message:`Failed to start experiment`)}};return(0,K.jsx)(_E,{open:e,onOpenChange:t,onOpenChangeComplete:n,pending:D,children:(0,K.jsxs)(vE,{ref:d,size:`lg`,onKeyDown:e=>{h_i(e)&&k&&(e.preventDefault(),M())},children:[(0,K.jsxs)(yE,{children:[(0,K.jsx)(SE,{children:`New experiment`}),(0,K.jsx)(CE,{children:`Run every item in a dataset through an agent, workflow or scorer.`})]}),(0,K.jsx)(xE,{children:(0,K.jsxs)(Hw,{open:C,onOpenChange:w,className:`py-3`,children:[(0,K.jsxs)(`div`,{className:`space-y-6`,children:[(0,K.jsx)(Rgi,{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)(Xgi,{options:f.options,isLoading:f.isLoading,target:g,onTargetValueChange:A,container:d,className:`min-w-0 flex-1`}),v&&(0,K.jsx)(jgi,{provider:_.provider,modelId:_.modelId,canReset:_.canReset,onProviderChange:_.setProvider,onModelIdChange:_.setModelId,onReset:_.reset,container:d})]}),(0,K.jsx)(Pgi,{datasets:p.datasets,datasetId:E,version:p.version,onDatasetChange:j,container:d}),(0,K.jsx)(qgi,{scorerIds:m.scorerIds,usesDefaultScorers:m.usesDefaultScorers,onScorerIdsChange:m.setScorerIds,container:d})]}),(0,K.jsx)(`div`,{className:`mt-6`,children:(0,K.jsx)(Agi,{})}),(0,K.jsxs)(Ww,{className:`space-y-6 pt-4`,children:[E&&(0,K.jsx)(Igi,{datasetId:E,version:p.version,onVersionChange:p.setVersion,container:d}),(0,K.jsx)(Lgi,{description:x,onDescriptionChange:S,disabled:D}),(0,K.jsx)(Vgi,{schema:h.schema,raw:h.raw,onRawChange:h.setRaw,onValuesChange:h.setValues},O)]})]})}),(0,K.jsxs)(bE,{children:[(0,K.jsx)(wE,{children:`Cancel`}),(0,K.jsx)(Hgi,{onRun:M,canRun:k,isRunning:D})]})]})})}function y_i({open:e,onOpenChange:t,onSuccess:n,...r}){let[i,a]=(0,G.useState)(0);return(0,K.jsx)(v_i,{open:e,onOpenChange:t,onOpenChangeComplete:e=>{e||a(e=>e+1)},onSuccess:n,...r},`${i}:${JSON.stringify(r)}`)}var b_i=`mastra_model_total_input_tokens`,x_i=`mastra_model_total_output_tokens`,S_i=()=>({estimatedCost:0,costUnits:new Set,hasUnknownCostUnit:!1});function C_i(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 w_i(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 T_i(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 E_i=2e3;function D_i(e){let t=S_i(),n=new Map;for(let r of e.groups){let e=C_i(r);if(!e)continue;w_i(t,e,r);let i=r.dimensions.traceId;i&&w_i(s8(n,i,S_i),e,r)}let r={};for(let[e,t]of n)r[e]=T_i(t);return{summary:T_i(t),traces:r}}var O_i=5,k_i=e=>!e||Object.keys(e.traces).length===0&&e.summary.inputTokens===void 0&&e.summary.outputTokens===void 0,A_i=({experiments:e,supportsMetrics:t})=>{let n=Y(),r=LP(e.map(e=>e.id));return Ty({queries:e.map(({id:e,status:r})=>{let i=r!==`running`&&r!==`pending`;return{queryKey:[`experiment-item-usage`,e,i],queryFn:async()=>D_i(await n.getMetricBreakdown({name:[b_i,x_i],aggregation:`sum`,groupBy:[`traceId`,`name`],filters:{experimentId:e}})),enabled:t&&i,refetchInterval:e=>k_i(e.state.data)&&e.state.dataUpdateCount<O_i?E_i:!1}}),combine:r})},j_i=({experimentId:e,experimentStatus:t,supportsMetrics:n,queryOptions:r})=>{let i=Y(),a=!!e&&n,o=Ey({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}},M_i=({traceId:e,queryOptions:t})=>{let n=Y();return Ey({queryKey:[`experiment-trace-light`,e],queryFn:async()=>{if(!e)throw Error(`Trace ID is required`);return n.getTraceLight(e)},...t})};function N_i({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),Ey({queryKey:e?[`dataset-experiments`,e,i]:[`experiments`,i],queryFn:()=>e?r.listDatasetExperiments(e,i):r.listExperiments(i),...n})}var P_i=`mastra_agent_duration_ms`,F_i=500,I_i=5e3;function L_i(e){let t=[];for(let n=0;n<e.length;n+=F_i)t.push(e.slice(n,n+F_i));return t}function R_i(e){return e.flatMap(e=>e.status===`fulfilled`?[e.value]:[])}function z_i(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=C_i(e);t&&r.has(t)&&n&&w_i(s8(i,t,S_i),n,e)}let a=new Map;for(let[e,t]of i)a.set(e,T_i(t));for(let e of n.flatMap(e=>e.groups)){let t=e.dimensions.experimentId;t&&r.has(t)&&(s8(a,t,()=>({})).avgDurationMs=e.value)}return a}var B_i=({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 Ey({queryKey:[`experiments-list-metrics`,r],enabled:t&&r.length>0,queryFn:async()=>{let e=L_i(r),[t,i]=await Promise.all([Promise.allSettled(e.map(e=>n.getMetricBreakdown({name:[b_i,x_i],aggregation:`sum`,groupBy:[`experimentId`,`name`],filters:{experimentIds:e},limit:e.length*2}))),Promise.allSettled(e.map(e=>n.getMetricBreakdown({name:[P_i],aggregation:`avg`,groupBy:[`experimentId`],filters:{experimentIds:e},limit:e.length})))]);return z_i(r,R_i(t),R_i(i))},placeholderData:vy,refetchInterval:i?I_i:!1})};function V_i({datasetId:e,target:t,orderBy:n,queryOptions:r}){let i=Y(),{inView:a,setRef:o}=oP(),s=t?.targetType||void 0,c=t?.targetId||void 0,l=ky({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 H_i=(0,G.createContext)(null);function U_i({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:i,hasNextPage:a,children:o}){let s=kb(),c=KWe(`/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]);dgi({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)(H_i.Provider,{value:m,children:o})}function W_i(){let e=(0,G.useContext)(H_i);if(!e)throw Error(`useExperimentItemPanel must be used within an ExperimentItemPanelProvider`);return e}function G_i(e,t){if(!e||typeof e!=`object`||!(t in e))return;let n=e[t];return typeof n==`string`&&n?n:void 0}function K_i(e){if(e.targetType===`agent`)return G_i(e.output,`text`)}function q_i(e){if(e.targetType)return K_i(e);let{output:t}=e;if(t!=null&&t!==``)return typeof t==`string`?t:JSON.stringify(t)}function J_i(e){let t=[];return e.some(e=>q_i(e))&&t.push({name:`output`,label:`Output`,size:`20rem`}),e.some(e=>I7(e))&&t.push({name:`error`,label:`Error`,size:`20rem`}),t}function I7(e){let t=G_i(e.error,`message`);if(t)return t;if(e.targetType===`agent`&&e.output&&typeof e.output==`object`)return G_i(e.output.error,`message`)}function Y_i(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function X_i(e){return Array.isArray(e)?e.flatMap(e=>Y_i(e)&&Y_i(e.payload)?[e.payload]:[]):[]}function Z_i(e){if(e.targetType!==`agent`||!Y_i(e.output))return[];let t=new Map(X_i(e.output.toolResults).map(e=>[e.toolCallId,e]));return X_i(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 Q_i(e){if(K_i(e)||I7(e))return;let t=Z_i(e).length;if(t!==0)return`No final text response after ${t} tool ${t===1?`call`:`calls`}`}var L7=e=>e==null?`-`:e.toFixed(2),$_i=e=>xw(e)??`-`,evi=(e,t)=>e!=null&&t!=null?e-t:null,tvi=new Set(Intl.supportedValuesOf(`currency`)),nvi={minimumFractionDigits:3,maximumFractionDigits:3},R7=(e,t)=>{if(e===void 0)return`-`;let n=(t??`usd`).toUpperCase();return tvi.has(n)?new Intl.NumberFormat(`en-US`,{style:`currency`,currency:n,...nvi}).format(e):`${new Intl.NumberFormat(`en-US`,nvi).format(e)} ${t}`},rvi=e=>t=>R7(t,e),ivi=new Intl.NumberFormat(`en-US`),z7=e=>e===void 0?`-`:ivi.format(e),B7=e=>{if(e?.inputTokens!==void 0||e?.outputTokens!==void 0)return(e.inputTokens??0)+(e.outputTokens??0)};function avi({scorerId:e,reason:t,nested:n=!1}){let r=`text-muted-foreground hover:text-foreground [&>svg]:size-3.5`;return(0,K.jsxs)(yZ,{children:[(0,K.jsx)(bZ,{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)(Xi,{})}),(0,K.jsx)(xZ,{side:`left`,align:`start`,className:`max-h-80 max-w-100 overflow-y-auto`,onClick:e=>e.stopPropagation(),children:(0,K.jsx)(xX,{children:t})})]})}var ovi=new Set([`itemId`,`id`,`status`,`input`,`output`,`error`,`tags`,`scores`,`cost`,`tokens`,`duration`]);function svi({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}=gl(),g=!!(d&&f),_=i.filter(e=>ovi.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}=_Q({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-3.5 [&>svg]:shrink-0`,children:[(0,K.jsx)(iF,{}),(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)(NU,{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)(Jti,{status:e.status}):(0,K.jsx)(`span`,{className:`text-placeholder`,children:`—`})}),S&&(0,K.jsx)(Z.TextCell,{font:`mono`,children:dvi(uvi(e.input),200)}),C&&(0,K.jsx)(Z.Cell,{className:`truncate font-mono`,"data-testid":`result-output-${e.id}`,children:q_i(e)??``}),w&&(0,K.jsx)(Z.Cell,{className:`truncate text-destructive-foreground`,"data-testid":`result-error-${e.id}`,children:I7(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)(Ofi,{value:e,className:`shrink-0`},e))}),E&&(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(cvi,{scores:e.scores})}),D&&(0,K.jsx)(Z.Cell,{className:`text-muted-foreground tabular-nums`,"data-testid":`result-cost-${e.id}`,children:R7(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:z7(B7(e.usage))}),k&&(0,K.jsx)(Z.Cell,{className:`text-muted-foreground tabular-nums`,"data-testid":`result-duration-${e.id}`,children:xw(lvi(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)(avi,{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 cvi({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)(TC,{size:`xs`,className:`text-muted-foreground`,children:(0,K.jsx)(Di,{})}),(0,K.jsx)(T,{variant:`meta`,tone:`muted`,font:`mono`,children:t[0].toFixed(2)}),t.length>1&&(0,K.jsxs)(bw,{children:[`+`,t.length-1]})]})}function lvi({startedAt:e,completedAt:t}){if(e&&t)return new Date(t).getTime()-new Date(e).getTime()}function uvi(e){return e==null?`-`:typeof e==`string`?e:JSON.stringify(e,null,2)}function dvi(e,t){return e.length<=t?e:e.slice(0,t-1)+`...`}function fvi({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}=W_i(),m=(0,G.useMemo)(()=>d?n.find(e=>e.itemId===d)?.id??null:null,[n,d]),{data:h}=WP({experimentId:e,experimentStatus:t,queryOptions:{enabled:!!e}}),{data:g}=A_i({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`},...J_i(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)(svi,{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 pvi({children:e,className:t}){return(0,K.jsx)(`div`,{className:m(`grid content-start gap-4 overflow-y-auto`,t),children:e})}function mvi({children:e,className:t}){return(0,K.jsx)(`div`,{className:`flex w-full overflow-y-auto`,children:(0,K.jsx)(`div`,{className:m(`grid w-full content-start gap-4 overflow-y-auto`,t),children:e})})}function hvi({children:e,className:t}){return(0,K.jsx)(`div`,{className:m(`flex w-full flex-wrap items-center justify-between gap-3 gap-x-4`,t),children:e})}var gvi=Object.assign(mvi,{Content:pvi,Toolbar:hvi});function _vi({children:e,className:t}){return(0,K.jsx)(`div`,{className:m(`grid size-full grid-cols-1 overflow-y-auto`,t),children:e})}function vvi({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){let{data:i}=EIt({datasetId:e,queryOptions:{enabled:!!e}}),a=(i??[]).map(e=>{let t=`v${e.version}`,n=Fw(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)(Gw,{children:[(0,K.jsx)(Gw.Item,{children:t}),n&&(0,K.jsx)(Gw.Item,{children:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:n})}),r&&(0,K.jsx)(Gw.Item,{children:r})]})}});return(0,K.jsxs)(gvi.Toolbar,{className:`grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4`,children:[(0,K.jsx)(`div`,{}),(0,K.jsxs)(WA,{items:a,value:t??``,onValueChange:e=>r?.(e,n??``),children:[(0,K.jsx)(KA,{"aria-label":`Version A`,size:`md`,children:(0,K.jsx)(GA,{placeholder:`Select version`})}),(0,K.jsx)(qA,{children:a.map(e=>(0,K.jsx)(JA,{value:e.value,label:e.label,children:e.content},e.value))})]}),(0,K.jsxs)(WA,{items:a,value:n??``,onValueChange:e=>r?.(t??``,e),children:[(0,K.jsx)(KA,{"aria-label":`Version B`,size:`md`,children:(0,K.jsx)(GA,{placeholder:`Select an option`})}),(0,K.jsx)(qA,{children:a.map(e=>(0,K.jsx)(JA,{value:e.value,label:e.label,children:e.content},e.value))})]}),(0,K.jsx)(`div`,{})]})}var yvi={added:{badgeVariant:`info`,borderColor:`border-info-edge`,icon:(0,K.jsx)(Ho,{}),tooltip:`Added in this version`},changed:{badgeVariant:`warning`,borderColor:`border-warning-edge`,icon:(0,K.jsx)(nte,{}),tooltip:`Changed in this version`},same:{badgeVariant:`success`,borderColor:`border-success-edge`,icon:(0,K.jsx)(Ir,{}),tooltip:`Same in both versions`}};function bvi({red:e=!1,tooltip:t}){return(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{render:(0,K.jsx)(`span`,{}),role:`img`,tabIndex:0,"aria-label":t,className:m(`rounded`,_),children:(0,K.jsx)(nn,{className:m(`h-5 w-5 text-muted-foreground/40`,{"text-destructive-foreground":e})})}),(0,K.jsx)(CC,{children:t})]})}function xvi({href:e,tooltip:t,className:n,children:r}){let{Link:i}=gl(),a=(0,K.jsx)(i,{href:e,className:m(`flex w-full items-center justify-center gap-4 rounded-lg px-3 py-2 text-left hover:bg-fill-subtle`,b.colors,_,n),children:r});return t===void 0?a:(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{render:a}),(0,K.jsx)(CC,{children:t})]})}function Svi({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}=yvi[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)(bw,{variant:n,size:`xs`,icon:r})})]})}function Cvi(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?`same`:e&&t&&e.datasetVersion!==t.datasetVersion?`changed`:e?`added`:`removed`}function wvi({otherVersionExists:e,status:t,isNewer:n}){if(!e&&n)return`added`;if(t===`changed`&&n)return`changed`}function Tvi({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=Cvi(n,r),c=wvi({otherVersionExists:r!==void 0,status:s,isNewer:o}),l=wvi({otherVersionExists:n!==void 0,status:s,isNewer:!o});return(0,K.jsxs)(`li`,{className:m(`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`,b.colors),children:[(0,K.jsx)(T,{as:`p`,variant:`body`,tone:`faint`,className:`truncate py-[0.6rem]`,children:t}),s===`same`?(0,K.jsx)(xvi,{href:`/datasets/${e}/items/${t}`,className:`col-span-2 gap-2`,tooltip:yvi.same.tooltip,children:(0,K.jsx)(Svi,{variant:`same`,version:r?.datasetVersion})}):(0,K.jsxs)(K.Fragment,{children:[n?.datasetVersion?(0,K.jsx)(xvi,{href:`/datasets/${e}/items/${t}`,className:`gap-2`,tooltip:c?yvi[c].tooltip:void 0,children:(0,K.jsx)(Svi,{variant:c,version:n.datasetVersion})}):(0,K.jsx)(`div`,{className:`flex items-center justify-center`,children:(0,K.jsx)(bvi,{red:o,tooltip:o?`Deleted in this version`:`Not present in this version`})}),r?.datasetVersion?(0,K.jsx)(xvi,{href:`/datasets/${e}/items/${t}`,className:`gap-2`,tooltip:l?yvi[l].tooltip:void 0,children:(0,K.jsx)(Svi,{variant:l,version:r.datasetVersion})}):(0,K.jsx)(`div`,{className:`flex items-center justify-center`,children:(0,K.jsx)(bvi,{red:!o,tooltip:o?`Not present in this version`:`Deleted in this version`})})]}),s===`changed`?(0,K.jsx)(xvi,{href:`/datasets/${e}/items/${t}/versions?version=${n?.datasetVersion}&compare=${r?.datasetVersion}`,children:`Compare`}):(0,K.jsx)(`div`,{children:(0,K.jsx)(bvi,{tooltip:`Comparing is available only for changed items`})})]},t)})})})}function Evi(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 Dvi({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)(Ovi,{item:e,onClose:r,...a},e.id):t?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(m$.Header,{children:[(0,K.jsx)(m$.Heading,{children:`Dataset item`}),(0,K.jsx)(m$.HeaderActions,{children:(0,K.jsx)(m$.CloseButton,{icon:`x`,onClick:r,tooltip:`Close detail panel`})})]}),n]}):null;return i===`inline`?c?(0,K.jsx)(m$,{variant:`inline`,title:s,children:c}):null:(0,K.jsx)(m$,{open:!!o,onClose:r,title:s,children:c})}function Ovi({datasetId:e,item:t,items:n,onItemChange:r,onClose:i}){let{navigate:a}=gl(),{updateItem:o,deleteItem:s}=zP(),[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)(m$.Header,{children:[(0,K.jsx)(m$.Heading,{children:`Dataset item`}),(0,K.jsxs)(m$.HeaderActions,{children:[!c&&(0,K.jsxs)(mD,{children:[(0,K.jsx)(mD.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)(Ar,{})})}),(0,K.jsxs)(mD.Content,{align:`end`,className:`w-48`,children:[(0,K.jsxs)(mD.Item,{onSelect:()=>a(`/datasets/${e}/items/${t.id}/versions?version=${t.datasetVersion}`),children:[(0,K.jsx)(is,{}),`Item versions`]}),(0,K.jsxs)(mD.Item,{onSelect:()=>l(!0),children:[(0,K.jsx)(Lo,{}),`Edit`]}),(0,K.jsxs)(mD.Item,{onSelect:()=>T(!0),variant:`destructive`,children:[(0,K.jsx)(xc,{}),`Delete item`]})]})]}),(0,K.jsx)(m$.NextPrevNav,{onPrevious:D,onNext:O,previousLabel:`Go to previous item`,nextLabel:`Go to next item`}),(0,K.jsx)(m$.CloseButton,{icon:`x`,onClick:i,tooltip:`Close detail panel`})]})]}),(0,K.jsx)(m$.Content,{children:c?(0,K.jsx)(kgi,{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{UC.error(`Input must be valid JSON`);return}let r;if(f.trim())try{r=JSON.parse(f)}catch{UC.error(`Ground Truth must be valid JSON`);return}let i;if(m.trim())try{i=JSON.parse(m)}catch{UC.error(`Metadata must be valid JSON`);return}let a=null;if(g.trim())try{a=JSON.parse(g)}catch{UC.error(`Expected Trajectory must be valid JSON`);return}let s;if(v.trim())try{let e=JSON.parse(v);if(!Array.isArray(e)){UC.error(`Tool Mocks must be a JSON array`);return}s=e}catch{UC.error(`Tool Mocks must be valid JSON`);return}else s=[];let c;if(b.trim())try{c=JSON.parse(b)}catch{UC.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}),UC.success(`Item updated successfully`),l(!1),C(null)}catch(e){let t=Evi(e);t?C(t):UC.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)(Egi,{item:t})}),(0,K.jsx)(aP,{open:w,onOpenChange:T,children:(0,K.jsxs)(aP.Content,{children:[(0,K.jsxs)(aP.Header,{children:[(0,K.jsx)(aP.Title,{children:`Delete Item`}),(0,K.jsx)(aP.Description,{children:`Are you sure you want to delete this item? This action cannot be undone.`})]}),(0,K.jsxs)(aP.Footer,{children:[(0,K.jsx)(aP.Cancel,{children:`Cancel`}),(0,K.jsx)(aP.Action,{onClick:async()=>{try{await s.mutateAsync({datasetId:e,itemId:t.id}),UC.success(`Item deleted successfully`),T(!1),i()}catch(e){UC.error(`Failed to delete item: ${e instanceof Error?e.message:`Unknown error`}`)}},children:s.isPending?`Deleting...`:`Yes, delete`})]})]})})]})}function kvi(){let{datasetId:e,items:t,isLoadingItems:n,currentItemId:r,openItem:i,close:a}=mgi(),o=fE();S3r(r,a);let s=(0,G.useMemo)(()=>r?t.find(e=>e.id===r):void 0,[t,r]),{data:c,isLoading:l}=oIt({datasetId:s?``:e,itemId:!s&&r?r:``,queryOptions:{enabled:!(s||!e)&&!!(!s&&r&&r)}}),u=(0,K.jsx)(Dvi,{datasetId:e,item:s??c??void 0,itemId:r,fallback:n||l?(0,K.jsx)(m$.LoadingData,{}):(0,K.jsxs)(m$.NoData,{children:[`No loaded item "`,r,`".`]}),items:t,onItemChange:i,onClose:a,variant:o?`drawer`:`inline`});return o?u:r?(0,K.jsx)(q8,{owner:`dataset-item`,children:u}):null}function Avi({crumbs:e,children:t}){return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{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 jvi(){let{datasetId:e}=Ab(),t=kb(),[n,r]=Hb(),{activeVersion:i}=GP(n,r),a=[sF(`/datasets`),cF],o=[...a,WLt],[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}=VP({datasetId:e,queryOptions:{enabled:!!e}}),{data:b=[],isLoading:x}=RP({datasetId:e,search:void 0,version:i,queryOptions:{enabled:!!e}});if(y)return null;if(v&&JP(v))return(0,K.jsx)(Avi,{crumbs:a,children:(0,K.jsx)(jU,{})});if(v&&YP(v))return(0,K.jsx)(Avi,{crumbs:a,children:(0,K.jsx)(AU,{resource:`datasets`})});if(v&&XP(v)||!y&&!v&&!_)return(0,K.jsx)(Avi,{crumbs:a,children:(0,K.jsx)(RC,{titleSlot:`Dataset not found`,descriptionSlot:`No dataset with id "${e}".`,actionSlot:(0,K.jsx)(X,{render:(0,K.jsx)(Vb,{to:`/datasets`}),icon:(0,K.jsx)(Rt,{}),children:`Back to datasets`})})});if(v)return(0,K.jsx)(Avi,{crumbs:a,children:(0,K.jsx)(RC,{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)(Ho,{}),children:`New experiment`}),E&&(0,K.jsx)(X,{variant:`ghost`,size:`sm`,render:(0,K.jsx)(Vb,{to:`/experiments?dataset=${e}`}),icon:(0,K.jsx)(wLt,{}),children:`Experiments`}),(0,K.jsx)(X,{variant:`ghost`,size:`sm`,onClick:()=>g(!0),icon:(0,K.jsx)(Cn,{}),children:`Schema`}),(0,K.jsxs)(mD,{children:[(0,K.jsx)(mD.Trigger,{asChild:!0,children:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,"aria-label":`Dataset actions menu`,children:(0,K.jsx)(Ar,{})})}),(0,K.jsxs)(mD.Content,{align:`end`,className:`w-48`,children:[(0,K.jsxs)(mD.Item,{onSelect:()=>void t(`/datasets/${e}/edit`),children:[(0,K.jsx)(Lo,{}),` Edit dataset`]}),(0,K.jsxs)(mD.Item,{onSelect:()=>m(!0),children:[(0,K.jsx)(xr,{}),` Duplicate dataset`]}),(0,K.jsxs)(mD.Item,{onSelect:()=>f(!0),variant:`destructive`,children:[(0,K.jsx)(xc,{}),` Delete dataset`]})]})]})]});return(0,K.jsxs)(pgi,{datasetId:e,items:b,isLoadingItems:x,children:[(0,K.jsxs)(`div`,{className:`h-full`,children:[(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:o}),headerActions:O,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(`div`,{children:(0,K.jsx)(ggi,{datasetId:e,onAddItemClick:()=>u(!0),toolbarActionsSlot:D?(0,K.jsx)(vgi,{datasetId:e}):void 0})})]}),(0,K.jsx)(kvi,{})]}),(0,K.jsx)(y_i,{initialDatasetId:e,initialDatasetVersion:i??void 0,open:s,onOpenChange:c,onSuccess:S},`${e}:${i??`latest`}`),(0,K.jsx)(Ndr,{datasetId:e,open:l,onOpenChange:u}),_&&(0,K.jsx)(Dpi,{open:p,onOpenChange:m,sourceDatasetId:_.id,sourceDatasetName:_.name,sourceDatasetDescription:_.description,sourceDatasetTargetType:_.targetType}),_&&(0,K.jsx)(Ohi,{open:h,onOpenChange:g,dataset:_}),_&&(0,K.jsx)(Kpi,{open:d,onOpenChange:f,datasetId:_.id,datasetName:_.name,onSuccess:C})]})}function Mvi({children:e,className:t}){return(0,K.jsx)(`div`,{className:m(`grid content-start`,t),children:e})}function Nvi({children:e,isLoading:t}){return(0,K.jsx)(T,{variant:`caption`,tone:`muted`,className:m(`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 Pvi({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:m(`grid w-full grid-cols-[1fr_auto] gap-8`,{"mt-6 mb-4":a},i),children:e}):(0,K.jsxs)(`header`,{className:m(`grid gap-1 py-3`,i),children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,tone:`ink`,className:m(`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:m(`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 Fvi({children:e,isLoading:t}){return(0,K.jsx)(T,{as:`h1`,variant:`heading`,tone:`ink`,className:m(`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 V7=Object.assign(Pvi,{Title:Fvi,Description:Nvi,Column:Mvi}),Ivi=[sF(`/datasets`),cF,{id:`dataset-edit`,label:`Edit dataset`}];function Lvi({children:e}){return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Ivi}),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 Rvi(){let{datasetId:e}=Ab(),t=kb(),{data:n,error:r,isLoading:i}=VP({datasetId:e,queryOptions:{enabled:!!e}}),a=()=>void t(`/datasets/${e}`);return i?null:r&&JP(r)?(0,K.jsx)(Lvi,{children:(0,K.jsx)(jU,{})}):r&&YP(r)?(0,K.jsx)(Lvi,{children:(0,K.jsx)(AU,{resource:`datasets`})}):r||!n?(0,K.jsx)(Lvi,{children:(0,K.jsx)(RC,{tone:`error`,titleSlot:`Failed to load dataset`,descriptionSlot:r instanceof Error?r.message:`An unexpected error occurred. Please try again.`})}):(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Ivi}),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)(V7,{className:`mb-6 p-0`,children:(0,K.jsxs)(V7.Column,{children:[(0,K.jsxs)(V7.Title,{children:[(0,K.jsx)(Tr,{}),` Edit dataset`]}),(0,K.jsx)(V7.Description,{children:n.name})]})}),(0,K.jsx)(dF,{className:`p-4`,children:(0,K.jsx)(Gpi,{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})})]})})]})}function zvi(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 Bvi(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)(Gw,{children:[(0,K.jsx)(Gw.Item,{children:(0,K.jsxs)(`b`,{children:[`v. `,e.datasetVersion]})}),(0,K.jsx)(Gw.Item,{children:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:Fw(n,`date-time`)})})]}),e.isLatest?(0,K.jsx)(bw,{variant:`blue`,size:`xs`,className:`ml-auto`,children:`Latest`}):null]}),disabled:t?.has(e.datasetVersion)??!1}})}function Vvi(e){let t=Number(e);return e!=null&&Number.isFinite(t)&&t>0?t:null}function Hvi(){let{datasetId:e,itemId:t}=Ab(),[n,r]=Hb(),i=[sF(`/datasets`),cF,{id:`dataset-item`,label:RLt(t),to:e&&t?`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}`:void 0},{id:`dataset-item-versions`,label:`Item Version History`}],a=Vvi(n.get(`version`)),o=Vvi(n.get(`compare`)),s=n.get(`view`)===`diff`,{data:c,error:l}=VP({datasetId:e??``,queryOptions:{enabled:!!e}}),{data:u,isLoading:d}=CIt({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}=wIt({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&&JP(l))return(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:i}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Item Version History`}),(0,K.jsx)(jU,{variant:`fill`})]});if(l&&YP(l))return(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:i}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Item Version History`}),(0,K.jsx)(AU,{variant:`fill`,resource:`datasets`})]});if(!e||!t)return(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{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?zvi(f,e):null,x=h?zvi(h,e):null,S=(f?.datasetVersion??0)<(h?.datasetVersion??0);return(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{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)(gr,{}),` Default view`]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(ji,{}),` 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)(dF,{className:`grid min-h-0 grid-rows-[auto_1fr] overflow-hidden`,children:[(0,K.jsx)(fF,{children:(0,K.jsx)(Uvi,{label:`Version`,value:p==null?``:String(p),options:Bvi(u??[],m==null?void 0:new Set([m])),onValueChange:e=>_(`version`,Number(e))})}),(0,K.jsx)(hF,{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)(Egi,{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)(dF,{className:`grid min-h-0 grid-rows-[auto_1fr] overflow-hidden`,children:[(0,K.jsx)(fF,{children:(0,K.jsx)(Uvi,{label:`Compare version`,value:m==null?``:String(m),placeholder:`Select a version to compare`,options:Bvi(u??[],p==null?void 0:new Set([p])),onValueChange:e=>_(`compare`,Number(e))})}),(0,K.jsx)(hF,{className:`grid content-start gap-5 overflow-y-auto`,children:m==null?(0,K.jsx)(RC,{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)(Egi,{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 Uvi({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)(is,{className:`size-4 opacity-50`}),(0,K.jsxs)(WA,{value:t,onValueChange:i,children:[(0,K.jsx)(KA,{"aria-label":e,className:`w-full`,children:(0,K.jsx)(GA,{placeholder:r,className:`flex-1`})}),(0,K.jsx)(qA,{children:n.map(e=>(0,K.jsx)(JA,{value:e.value,disabled:e.disabled,children:e.label},e.value))})]})]})}var Wvi=[sF(`/datasets`),cF,{id:`dataset-versions`,label:`Versions`}];function Gvi(){let{datasetId:e}=Ab(),[t]=Hb(),n=t.get(`ids`)?.split(`,`).map(Number).filter(e=>!isNaN(e)&&e>0)??[],r=kb(),{data:i,error:a}=VP({datasetId:e??``,queryOptions:{enabled:!!e}}),o=RP({datasetId:e??``,search:void 0,version:n[0]??null,queryOptions:{enabled:!!e}}),s=RP({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&&JP(a)?(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:Wvi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Versions`}),(0,K.jsx)(jU,{variant:`fill`})]}):a&&YP(a)?(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:Wvi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Versions`}),(0,K.jsx)(AU,{variant:`fill`,resource:`datasets`})]}):!e||n.length<2?(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:Wvi}),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)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:Wvi}),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)(V7,{children:[(0,K.jsxs)(V7.Column,{children:[(0,K.jsxs)(V7.Title,{children:[(0,K.jsx)(yte,{}),` Compare Dataset Versions`]}),(0,K.jsx)(V7.Description,{children:(0,K.jsxs)(gQ,{children:[(0,K.jsx)(is,{}),` Comparing `,n.length,` versions of`,` `,i?.name||e?.slice(0,8)]})})]}),(0,K.jsx)(V7.Column,{children:(0,K.jsx)(X,{render:(0,K.jsx)(Vb,{to:`/datasets/${e}`}),icon:(0,K.jsx)(Rt,{}),children:`Back to dataset`})})]}),(0,K.jsx)(_vi,{children:(0,K.jsxs)(gvi,{children:[(0,K.jsx)(vvi,{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)(Tvi,{datasetId:e,versionA:n[0],versionB:n[1],allItems:u,itemsAMap:d,itemsBMap:f})]})})]})})]})}var Kvi=100,qvi=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:Kvi,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}},Jvi=(e,{experimentId:t,targetType:n,targetId:r,experiments:i,isLoadingExperiments:a=!1,queryOptions:o})=>{let s=Y(),{inView:c,setRef:l}=oP(),u=i!==void 0,{data:d,isLoading:f}=N_i({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=ky({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 qvi(s,e,t);for(;n.items.length===0&&n.next;)n=await qvi(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}},Yvi=(e={})=>Jvi(`needs-review`,e),Xvi=(e={})=>Jvi(`complete`,e);function Zvi({queryOptions:e}={}){let t=Y();return Ey({queryKey:[`experiment-review-summary`],queryFn:()=>t.getExperimentReviewSummary(),...e})}var Qvi={baseline:`purple`,contender:`blue`},H7=e=>e===0?`Baseline`:`Contender ${e}`;function $vi({open:e,onOpenChange:t,experimentId:n,experimentName:r,onSuccess:i}){let{deleteExperiment:a}=zP();return(0,K.jsx)(aP,{open:e,onOpenChange:t,children:(0,K.jsxs)(aP.Content,{children:[(0,K.jsxs)(aP.Header,{children:[(0,K.jsx)(aP.Title,{children:`Delete Experiment`}),(0,K.jsxs)(aP.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)(aP.Footer,{children:[(0,K.jsx)(aP.Cancel,{children:`Cancel`}),(0,K.jsx)(X,{icon:(0,K.jsx)(xc,{}),variant:`primary`,onClick:async()=>{try{await a.mutateAsync(n),UC.success(`Experiment deleted successfully`),t(!1),i?.()}catch(e){UC.error(`Failed to delete experiment: ${e instanceof Error?e.message:`Unknown error`}`)}},disabled:a.isPending,children:a.isPending?`Deleting...`:`Delete`})]})]})})}var eyi=`minmax(9rem,1fr)`,tyi=`minmax(8rem,16rem)`,nyi=`auto auto auto auto auto auto auto auto`,ryi=`auto auto auto`,U7={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`},iyi={completed:`neutral`,running:`warning`,failed:`destructive`,pending:`neutral`},W7={completed:`Run completed`,running:`Run in progress`,failed:`Run failed`,pending:`Run queued`};function ayi(e){let t=hU(e.id)??e.id;return e.name||`Experiment #${t}`}var oyi=60;function syi({experiment:e}){return(0,K.jsx)(`span`,{className:`block min-w-0 truncate text-left text-muted-foreground`,children:ayi(e)})}function cyi({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<=oyi?n:(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{asChild:!0,children:n}),(0,K.jsx)(CC,{children:t})]})}function lyi(){let{data:e}=PP(),{data:t}=sP(),{data:n}=eF(),{data:r}=qP();return{agents:e,workflows:t,scorers:n,processors:r}}var uyi={agent:tF,workflow:rP,scorer:iF,processor:rF},dyi={agent:`Agent`,workflow:`Workflow`,scorer:`Scorer`,processor:`Processor`},fyi=`External (caller-run)`;function pyi(e,{agents:t,workflows:n,scorers:r,processors:i}){let{targetType:a,targetId:o}=e;if(!o)return fyi;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 myi({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)(bw,{variant:r.variant,className:`shrink-0`,children:r.label}),(0,K.jsx)(syi,{experiment:e})]}):(0,K.jsx)(syi,{experiment:e})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(cyi,{experiment:e})}),t!==void 0&&(0,K.jsx)(Z.TextCell,{children:t}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(vyi,{experiment:e})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(bw,{variant:iyi[o]??`neutral`,indicator:`dot`,children:W7[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)(_yi,{value:hyi(e),format:xw}),i&&(0,K.jsx)(gyi,{metrics:a}),(0,K.jsx)(Z.Cell,{className:`text-center`,children:(0,K.jsx)(yyi,{review:n})}),(0,K.jsx)(Z.TextCell,{children:Fw(e.createdAt,`date`)??`—`})]})}function hyi(e){if(e.startedAt&&e.completedAt)return new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime()}function gyi({metrics:e}){let t=e?.avgDurationMs===void 0?void 0:Math.round(e.avgDurationMs);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(_yi,{value:t,format:xw}),(0,K.jsx)(_yi,{value:B7(e),format:j5}),(0,K.jsx)(_yi,{value:e?.estimatedCost,format:t=>R7(t,e?.costUnit)})]})}function _yi({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 vyi({experiment:e}){let t=pyi(e,lyi()),n=e.targetId?e.targetType:null,r=n?uyi[n]:null;return(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5 [&_svg]:size-3.5 [&_svg]:shrink-0`,children:[r&&(0,K.jsx)(`span`,{className:`flex text-muted-foreground`,role:`img`,"aria-label":dyi[n],children:(0,K.jsx)(r,{})}),(0,K.jsx)(`span`,{className:n?`truncate`:`truncate text-placeholder`,children:t})]})}function yyi({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)(bw,{size:`xs`,variant:`warning`,children:[e.needsReview,` pending`]}):(0,K.jsxs)(bw,{size:`xs`,variant:`success`,children:[e.complete,`/`,t,` reviewed`]})}var byi=`${eyi} ${tyi} 1fr ${nyi}`,xyi=`${byi} auto`,Syi=`${byi} ${ryi} auto`,Cyi=[{label:U7.avgDuration,className:`text-center`},{label:U7.tokens,className:`text-center`},{label:U7.cost,className:`text-center`}],wyi=e=>[{label:U7.experiment},{label:U7.description},{label:U7.dataset},{label:U7.target},{label:U7.status,sortKey:`status`},{label:U7.items,className:`text-center`},{label:U7.succeeded,className:`text-center`},{label:U7.failed,className:`text-center`},{label:U7.duration,className:`text-center`},...e?Cyi:[],{label:U7.review,className:`text-center`},{label:U7.date,sortKey:`createdAt`}],Tyi=e=>e.stopPropagation();function Eyi({experiment:e,rowProps:t,onSelect:n,featured:r,onDelete:i,leadingCell:a,children:o}){let s=a?2:void 0,{paths:c,Link:l}=gl(),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:Tyi,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)(xc,{className:`size-4`})})})]})}function Dyi({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}=_Q({count:y.length,global:d}),[S,C]=(0,G.useState)(null),w=r!==void 0,T=w?Syi:xyi;if(i)return(0,K.jsx)(NU,{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=wyi(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)??hU(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)(myi,{experiment:e,datasetName:i,review:n?.get(e.id),showUsage:w,metrics:r?.get(e.id),selectionRole:o?{label:H7(a),variant:a===0?Qvi.baseline:Qvi.contender}:void 0});return(0,K.jsx)(Eyi,{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)($vi,{open:!0,onOpenChange:e=>{e||C(null)},experimentId:S.id,experimentName:S.name??void 0})]})}var Oyi=[{value:`all`,label:`All statuses`},{value:`completed`,label:`Completed`},{value:`running`,label:`Running`},{value:`failed`,label:`Failed`},{value:`pending`,label:`Pending`}];function kyi(e){return[{value:`all`,label:`All datasets`},...(e??[]).map(e=>({value:e.id,label:e.name}))]}var Ayi=({onRunExperiment:e})=>(0,K.jsx)(RC,{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)(Ho,{}),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)(Br,{}),children:`Experiments documentation`})]}),variant:`fill`}),jyi=e=>`${e} experiment${e===1?``:`s`}`;function Myi({experimentIds:e,onDeleted:t}){let[n,r]=(0,G.useState)(!1),[i,a]=(0,G.useState)(!1),{deleteExperiment:o}=zP(),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)(xc,{}),onClick:()=>r(!0),children:`Delete`}),(0,K.jsx)(aP,{open:n,onOpenChange:r,children:(0,K.jsxs)(aP.Content,{children:[(0,K.jsxs)(aP.Header,{children:[(0,K.jsxs)(aP.Title,{children:[`Delete `,jyi(s)]}),(0,K.jsxs)(aP.Description,{children:[s===1?`Its`:`Their`,` results and traces will be deleted too. This can't be undone.`]})]}),(0,K.jsxs)(aP.Footer,{children:[(0,K.jsx)(aP.Cancel,{children:`Cancel`}),(0,K.jsx)(X,{icon:(0,K.jsx)(xc,{}),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?UC.error(`Failed to delete ${i} of ${jyi(s)}`):(UC.success(`Deleted ${jyi(s)}`),r(!1),t())},disabled:i,children:i?`Deleting…`:s===1?`Delete experiment`:`Delete experiments`})]})]})})]})}function Nyi({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)(Vc,{}),onClick:t,tooltip:a?void 0:`Clear selection`,className:`mr-2 tabular-nums`,children:[i,` selected`]}),(0,K.jsx)(Myi,{experimentIds:e,onDeleted:t}),r?(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{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)(Ni,{}),children:`Compare`})}),(0,K.jsx)(CC,{children:r})]}):(0,K.jsx)(X,{size:`sm`,onClick:n,icon:(0,K.jsx)(Ni,{}),children:`Compare`})]})}function Pyi({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 Fyi=`search`,Iyi=`status`,Lyi=`dataset`,G7=`all`,Ryi=[{id:`contains`,label:`contains`},{id:`is`,label:`is`}],zyi=Oyi.filter(e=>e.value!==G7),Byi=({search:e,statusFilter:t,datasetFilter:n,targetType:r,targetId:i})=>{let a=[];return e&&a.push(C7(Fyi,e,`contains`)),a.push(...Wfi({targetType:r,targetId:i})),t!==G7&&a.push(C7(Iyi,t)),n!==G7&&a.push(C7(Lyi,n)),a},Vyi=e=>({...Gfi(e),search:w7(e,Fyi),statusFilter:w7(e,Iyi)||G7,datasetFilter:w7(e,Lyi)||G7});function Hyi({search:e,statusFilter:t,datasetFilter:n,targetType:r,targetId:i,datasetOptions:a,onChange:o}){let s=Kfi(r),c=(0,G.useMemo)(()=>[{id:Fyi,label:`Search`,icon:gs,search:!0,operators:[`contains`]},...s,{id:Iyi,label:`Status`,icon:Wn,color:_F(`orange`),operators:[`is`],strict:!0,suggestions:zyi},{id:Lyi,label:`Dataset`,icon:Tr,color:_F(`blue`),operators:[`is`],strict:!0,suggestions:a.filter(e=>e.value!==G7)}],[s,a]),l=(0,G.useMemo)(()=>Byi({search:e,statusFilter:t,datasetFilter:n,targetType:r,targetId:i}),[e,t,n,r,i]);return(0,K.jsxs)(f5,{fields:c,operators:Ryi,value:l,onValueChange:e=>o(Vyi(e)),createItemId:e=>e,"aria-label":`Experiments filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(f5.Chips,{}),(0,K.jsx)(f5.Input,{placeholder:`Filter experiments`})]})}function Uyi({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)(jq,{children:(0,K.jsx)(jq.Start,{children:(0,K.jsx)(Hyi,{search:e,statusFilter:t,datasetFilter:n,datasetOptions:r,targetType:i,targetId:a,onChange:o})})}),(0,K.jsxs)(jq,{children:[(0,K.jsx)(jq.Start,{className:`self-end`,children:(0,K.jsx)(Pyi,{dataset:c})}),(0,K.jsx)(jq.End,{children:(0,K.jsx)(Nyi,{...s})})]})]})}var Wyi={present:!1,targetType:null,output:null,metadata:null,comment:null,error:null,startedAt:null,completedAt:null,scores:[]},Gyi=e=>e?e instanceof Date?e.toISOString():e:null,Kyi=e=>{let t=new Map;for(let n of e??[])t.set(n.itemId,n);return t},qyi=(e,t,n,r)=>{if(!e)return Wyi;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:Gyi(t?.startedAt),completedAt:Gyi(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}},Jyi=(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 K7(e){return!e.startedAt||!e.completedAt?null:new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime()}function Yyi(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 Xyi=(e,t)=>{let n=Yyi(e),r=Yyi(t);return n!=null&&r!=null?r-n:void 0},Zyi=(e,t)=>{let n=K7(e),r=K7(t);return n!=null&&r!=null?r-n:null},Qyi=(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},$yi=(e,t)=>{let n=B7(e.usage),r=B7(t.usage);return n!==void 0&&r!==void 0?r-n:void 0},ebi=({comparison:e,experimentIds:t,resultsById:n,scoresById:r,usageById:i})=>{if(!e)return[];let a=new Map(t.map(e=>[e,Kyi(n?.[e])]));return e.items.map(e=>{let n=t.map(t=>qyi(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:Jyi(o,e),durationDeltaMs:n===0?null:Zyi(o,e),costDelta:n===0?void 0:Qyi(o,e),tokenDelta:n===0?void 0:$yi(o,e),averageScoreDelta:n===0?void 0:Xyi(o,e)}))}})};function tbi({datasetId:e,itemId:t,onClose:n}){let{data:r,isLoading:i}=oIt({datasetId:e,itemId:t??``,queryOptions:{enabled:!!e&&!!t}});return(0,K.jsx)(Dvi,{datasetId:e,item:r,itemId:t,fallback:i?(0,K.jsx)(m$.LoadingData,{}):(0,K.jsxs)(m$.NoData,{children:[`Dataset item "`,t,`" not found.`]}),items:r?[r]:[],onItemChange:()=>{},onClose:n})}function nbi({label:e,value:t,expanded:n,onExpandedChange:r}){return t==null?null:(0,K.jsx)(F7,{title:e,framed:!0,expanded:n,onExpandedChange:r,children:(0,K.jsx)(P7,{value:t})})}function rbi({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)(mr,{}),label:`Cost`,value:R7(e?.estimatedCost,c),rawValue:e?.estimatedCost,delta:r??null,formatDelta:rvi(c),higherIsBetter:!1}]:[],u=t?[{id:`tokens`,icon:(0,K.jsx)(Gi,{}),label:`Tokens`,value:z7(B7(e)),rawValue:B7(e),delta:i??null,formatDelta:z7,higherIsBetter:!1}]:[],d=n==null?[]:[{id:`duration`,icon:(0,K.jsx)(lr,{}),label:`Duration`,value:xw(n)??`-`,rawValue:n,delta:a??null,formatDelta:$_i,higherIsBetter:!1}],f=o?[{id:`avg-score`,icon:(0,K.jsx)(Di,{}),label:`Avg score`,value:L7(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)(iF,{}),label:e.label??(0,K.jsx)(Cgi,{scorerId:e.scorerId}),value:e.reason?.trim()?(0,K.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[L7(e.value),(0,K.jsx)(avi,{scorerId:e.scorerId,reason:e.reason})]}):L7(e.value),rawValue:e.value,delta:e.delta??null}))]}function ibi({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 abi(e){return(0,G.useSyncExternalStore)(e.subscribe,e.read,()=>e.defaultValue)}var obi={cost:`cost`,"total-cost":`cost`,duration:`duration`,"avg-duration":`duration`,"avg-score":`average`,tokens:`tokens`,"total-tokens":`tokens`,errors:`errors`};function sbi(e){return e.startsWith(`scorer:`)?e:obi[e]}var cbi=[],lbi=ibi({key:`mastra:experiments-compare:hidden-metrics`,defaultValue:cbi,parse:e=>Mp(q()).parse(e)});function ubi(){let e=abi(lbi);return{isHidden:t=>e.includes(t),isMetricVisible:t=>{let n=sbi(t);return n===void 0||!e.includes(n)},toggle:t=>lbi.write(e.includes(t)?e.filter(e=>e!==t):[...e,t]),reset:()=>lbi.write(cbi)}}function dbi(e){return e==null?`-`:typeof e==`string`?e:JSON.stringify(e,null,2)}function fbi(e,t){return rbi({usage:e.usage,showUsage:t,durationMs:K7(e),costDelta:e.costDelta,tokenDelta:e.tokenDelta,durationDeltaMs:e.durationDeltaMs,averageScore:e.scores.length>0?{value:Yyi(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 pbi({column:e,isLoading:t,showUsage:n=!1,outputExpanded:r,onOutputExpandedChange:i,onShowTrace:a}){let{isMetricVisible:o}=ubi();if(t)return(0,K.jsx)(`div`,{className:`flex h-32 items-center justify-center`,children:(0,K.jsx)(Zc,{})});if(!e.present)return(0,K.jsx)(T,{tone:`muted`,className:`py-5 text-center`,children:`Not present in this experiment`});let s=dbi(e.output),c=K_i(e),l=I7(e),u=Z_i(e),d=Q_i(e),f=fbi(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)(oF,{})}):void 0,h=f.length>0,g=e=>(0,K.jsxs)(K.Fragment,{children:[!h&&m,(0,K.jsx)(jw,{content:e,variant:`ghost`})]});return(0,K.jsxs)(`div`,{className:Tgi,children:[h&&(0,K.jsx)(F7,{title:`Metrics`,collapsible:!1,actions:m,children:(0,K.jsx)(wgi,{metrics:f})}),l?(0,K.jsx)(F7,{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)(F7,{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)(P7,{value:c??e.output})}),u.length>0&&(0,K.jsx)(F7,{title:`Tool calls (${u.length})`,children:(0,K.jsx)(Fri,{toolCalls:u})}),e.comment&&(0,K.jsx)(F7,{title:`Comment`,framed:!0,children:(0,K.jsx)(P7,{value:e.comment})}),e.metadata&&Object.keys(e.metadata).length>0&&(0,K.jsx)(F7,{title:`Metadata`,framed:!0,actions:(0,K.jsx)(jw,{content:dbi(e.metadata),variant:`ghost`}),children:(0,K.jsx)(P7,{value:e.metadata})})]})}function mbi({experiment:e,open:t,onOpenChange:n}){let[r,i]=(0,G.useState)(e.name??``),[a,o]=(0,G.useState)(e.description??``),{updateExperiment:s}=zP(),c=!!r.trim();return(0,K.jsx)(_E,{open:t,onOpenChange:n,pending:s.isPending,children:(0,K.jsxs)(vE,{children:[(0,K.jsx)(yE,{children:(0,K.jsx)(SE,{children:`Rename Experiment`})}),(0,K.jsxs)(uU,{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()}),UC.success(`Experiment renamed`),n(!1)}catch(e){UC.error(`Failed to rename experiment: ${e instanceof Error?e.message:`Unknown error`}`)}},children:[(0,K.jsxs)(xE,{children:[(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{required:!0,children:`Name`}),(0,K.jsx)(ZM,{required:!0,value:r,onChange:e=>i(e.target.value),placeholder:`Enter experiment name`,autoFocus:!0})]}),(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{children:`Description`}),(0,K.jsx)(ZM,{value:a,onChange:e=>o(e.target.value),placeholder:`Enter experiment description (optional)`})]})]}),(0,K.jsxs)(bE,{children:[(0,K.jsx)(wE,{children:`Cancel`}),(0,K.jsx)(gE,{type:`submit`,disabled:!c,children:s.isPending?`Saving...`:`Save`})]})]})]})})}function hbi({datasetId:e,version:t,differsFromBaseline:n}){let{Link:r,paths:i}=gl();return(0,K.jsxs)(`span`,{className:m(`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 gbi({role:e,label:t,experiment:n,onSetBaseline:r}){let{Link:i}=gl(),[a,o]=(0,G.useState)(!1),s=n?hU(n.id)??n.id:null,c=!!n?.datasetId;return(0,K.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[n&&(0,K.jsxs)(mD,{children:[(0,K.jsx)(mD.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)(h,{"aria-hidden":!0})]})}),(0,K.jsxs)(mD.Content,{align:`start`,className:`min-w-48`,children:[(0,K.jsxs)(mD.Item,{render:(0,K.jsx)(i,{href:`/experiments/${n.id}`}),children:[(0,K.jsx)(la,{}),` View experiment`]}),c&&(0,K.jsxs)(mD.Item,{onSelect:()=>o(!0),children:[(0,K.jsx)(Lo,{}),` Rename experiment`]})]})]}),n&&a&&(0,K.jsx)(mbi,{experiment:n,open:!0,onOpenChange:o}),(0,K.jsx)(`div`,{className:`ml-auto shrink-0`,children:r?(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{render:(0,K.jsx)(`button`,{type:`button`,"aria-label":`Set as baseline`,onClick:r,className:m(`cursor-pointer rounded-[7px] hover:brightness-110`,_)}),children:(0,K.jsx)(bw,{variant:Qvi[e],size:`md`,icon:(0,K.jsx)(Ks,{}),children:t})}),(0,K.jsx)(CC,{children:`Set as baseline`})]}):(0,K.jsx)(bw,{variant:Qvi[e],size:`md`,icon:e===`baseline`?(0,K.jsx)(Ks,{className:`fill-current`}):(0,K.jsx)(Ks,{}),children:t})})]})}function _bi({role:e,experiment:t,summary:n,metrics:r,baselineMetrics:i,versionMismatch:a,showUsage:o=!1}){let{Link:s,paths:c}=gl(),{isMetricVisible:l}=ubi(),u=t?.createdAt?new Date(t.createdAt):null,d=e===`contender`,f=(e,t)=>d?evi(e,t):null,p=t?[...t.targetId?[{id:`target`,icon:t.targetType===`agent`?(0,K.jsx)(tF,{}):(0,K.jsx)(ec,{}),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)(is,{}),label:`Dataset version`,value:(0,K.jsx)(hbi,{datasetId:t.datasetId,version:t.datasetVersion,differsFromBaseline:a}),delta:null}]:[],...u?[{id:`created-at`,icon:(0,K.jsx)(Fn,{}),label:`Created`,value:Fw(u,`date`),delta:null}]:[]]:[],m=o?r:void 0,h=[...m?[{id:`total-cost`,icon:(0,K.jsx)(mr,{}),label:`Total cost`,value:R7(m.cost,m.costUnit),rawValue:m.cost,delta:m.costUnit===i?.costUnit?f(m.cost,i?.cost):null,formatDelta:rvi(m.costUnit),higherIsBetter:!1,emphasis:!0}]:[],...r?[{id:`avg-duration`,icon:(0,K.jsx)(lr,{}),label:`Avg duration`,value:xw(r.averageDurationMs)??`-`,rawValue:r.averageDurationMs,delta:f(r.averageDurationMs,i?.averageDurationMs),formatDelta:$_i,higherIsBetter:!1,emphasis:!0}]:[],...r&&n&&n.length>0?[{id:`avg-score`,icon:(0,K.jsx)(Di,{}),label:`Avg score`,value:L7(r.averageScore),rawValue:r.averageScore,delta:f(r.averageScore,i?.averageScore),emphasis:!0}]:[],...m?[{id:`total-tokens`,icon:(0,K.jsx)(Gi,{}),label:`Total tokens`,value:z7(m.tokens),rawValue:m.tokens,delta:f(m.tokens,i?.tokens),formatDelta:z7,higherIsBetter:!1}]:[],...p,...r?[{id:`errors`,icon:(0,K.jsx)(Un,{}),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)(iF,{}),label:(0,K.jsx)(Cgi,{scorerId:e}),value:L7(t),rawValue:t,delta:d?n:null}))].filter(e=>l(e.id));return h.length===0?null:(0,K.jsx)(F7,{title:`Summary`,collapsible:!1,children:(0,K.jsx)(wgi,{metrics:h})})}function vbi(e){return(0,K.jsx)(vsi,{...e,headerActionsSlot:e.traceId?(0,K.jsx)(Uui,{traceId:e.traceId,spans:e.spans},e.traceId):void 0})}function ybi({traceId:e,onClose:t,withQueryTrace:n,withFeedback:r}){let{navigate:i}=gl(),[a,o]=(0,G.useState)(),{data:s,isLoading:c}=M_i({traceId:e,queryOptions:{enabled:!!e}}),l=s?.spans,u=l?.find(e=>!e.parentSpanId),{data:d}=x8({traceId:e,queryOptions:{enabled:r&&!!e}}),{data:f}=W$r({traceId:e,spanId:a,queryOptions:{enabled:r&&!!e&&!!a}}),{data:p}=$P({traceId:e,spanId:u?.spanId,page:0,queryOptions:{enabled:!!e&&!!u?.spanId}});return(0,K.jsx)(vbi,{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(kq(e,t)),feedbackTabBadge:r?d?.pagination?.total??void 0:void 0,feedbackTabSlot:r?({traceId:e})=>(0,K.jsx)(R5,{traceId:e}):void 0,scoresTabBadge:p?.pagination?.total??void 0,scoresTabSlot:({traceId:e,rootSpanId:t})=>t?(0,K.jsx)(MVr,{traceId:e,spanId:t,onScoreSelect:t=>i(kq(e,t))}):null,spanFeedbackTabBadge:r?f?.pagination?.total??void 0:void 0,spanFeedbackTabSlot:r?({traceId:e,spanId:t})=>e&&t?(0,K.jsx)(Eni,{traceId:e,spanId:t},`${e}:${t}`):null:void 0})}var q7=`min-w-0 px-4 py-3`,bbi=`grid grid-cols-[minmax(22rem,26rem)_repeat(var(--compare-cols),minmax(32rem,1fr))] divide-x divide-border border-border`,xbi=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,Sbi=()=>!!window.getSelection()?.toString(),Cbi=e=>e!=null,wbi=e=>e.length>0?e.reduce((e,t)=>e+t,0)/e.length:null,Tbi=(e,t,n)=>wbi(e.map(e=>e.sides[t]?.scores.find(e=>e.scorerId===n)?.value??null).filter(Cbi)),Ebi=(e,t)=>{let n=e.map(e=>e.sides[t]).filter(e=>e?.present);return{errorCount:n.filter(e=>e.error).length,averageScore:wbi(n.flatMap(e=>e.scores.map(e=>e.value)).filter(Cbi)),averageDurationMs:wbi(n.map(K7).filter(Cbi))}};function Dbi({datasetId:e,baselineId:t,contenderIds:n,onSetBaseline:r}){let i=(0,G.useMemo)(()=>[t,...n],[t,n]),[a,o]=(0,G.useState)(),[s,c]=(0,G.useState)(),l=r5(),u=e=>{c(void 0),o(e)},d=e=>{o(void 0),c(e)},{data:f,isLoading:p,error:h}=fIt({datasetId:e,experimentIds:i,baselineId:t,queryOptions:{enabled:!!e&&!!t&&n.length>0}}),{data:g,isLoading:_}=yIt({datasetId:e,experimentIds:i}),v=(0,G.useMemo)(()=>i.map(e=>({id:e,status:g[e]?.status})),[i,g]),{data:y,isLoading:b}=xIt({datasetId:e,experiments:v}),{data:x}=SIt({experiments:v}),{supportsMetrics:S,isLoading:C}=b7(),{data:w,isLoading:E}=A_i({experiments:v,supportsMetrics:S}),D=(0,G.useMemo)(()=>ebi({comparison:f,experimentIds:i,resultsById:y,scoresById:x,usageById:w}),[f,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=Tbi(D,n,e),r=Tbi(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{...Ebi(D,t),cost:n?.estimatedCost,costUnit:n?.costUnit,tokens:B7(n)}}),[D,i,w]);if(p||_||C||E)return(0,K.jsx)(`div`,{className:`pointer-events-none fixed inset-0 flex items-center justify-center`,children:(0,K.jsx)(Zc,{})});if(h)return(0,K.jsx)(EA,{variant:`warning`,title:`Error loading comparison`,children:(0,K.jsx)(EA.Message,{children:h instanceof Error?h.message:`Unknown error`})});if(!f||f.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:m(bbi,`sticky top-0 z-20 bg-background`),children:[(0,K.jsx)(`div`,{role:`columnheader`,"aria-label":`Items`,className:q7}),i.map((e,t)=>(0,K.jsx)(`div`,{role:`columnheader`,"aria-label":H7(t),className:m(q7,`border-b`),children:(0,K.jsx)(gbi,{role:t===0?`baseline`:`contender`,label:H7(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:m(bbi,`border-b`),children:[(0,K.jsx)(`div`,{role:`cell`,"aria-label":`Items`,className:q7}),i.map((e,t)=>{let n=g[e]??void 0;return(0,K.jsx)(`div`,{role:`cell`,"aria-label":H7(t),className:q7,children:(0,K.jsx)(_bi,{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)(Obi,{row:e,isLoading:b,showUsage:S,onOpen:()=>u(e.itemId),onShowTrace:d},e.itemId))]}),(0,K.jsx)(tbi,{datasetId:e,itemId:a,onClose:()=>o(void 0)}),(0,K.jsx)(ybi,{traceId:s,onClose:()=>c(void 0),withQueryTrace:l.enabled,withFeedback:l.enabled})]})}function Obi({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}))}),c=s(`output`);return(0,K.jsxs)(`div`,{role:`row`,"aria-label":e.itemId,tabIndex:0,onClick:e=>{xbi(e)||Sbi()||r()},onKeyDown:e=>{e.target!==e.currentTarget||e.key!==`Enter`&&e.key!==` `||(e.preventDefault(),r())},className:m(bbi,`cursor-pointer border-b transition-colors duration-normal ease-out-custom hover:bg-fill-subtle`,U),children:[(0,K.jsxs)(`div`,{role:`cell`,className:m(q7,Tgi),children:[(0,K.jsx)(nbi,{label:`Input`,value:e.input,...s(`input`)}),(0,K.jsx)(nbi,{label:`Ground truth`,value:e.groundTruth,...s(`groundTruth`)})]}),e.sides.map((e,r)=>(0,K.jsx)(`div`,{role:`cell`,"aria-label":H7(r),className:q7,children:(0,K.jsx)(pbi,{column:e,isLoading:t,showUsage:n,outputExpanded:c.expanded,onOutputExpandedChange:c.onExpandedChange,onShowTrace:i})},e.experimentId))]})}function kbi(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 J7=[sF(`/experiments`)],Abi=[`createdAt`,`status`],jbi=new Map;function Mbi(){let[e,t]=(0,G.useState)(``),[n,r]=(0,G.useState)(`all`),[i,a]=(0,G.useState)(!1),[o,s]=(0,G.useState)([]),c=kb(),[l,u]=Hb(),{sort:d,onSortChange:f}=c7({searchParams:l,setSearchParams:u,allowedKeys:Abi}),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}=npi(),_=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(E7,e.targetType),r(D7,e.targetType===h?e.targetId:``),n},{replace:!0})},{data:v,isLoading:y,error:b}=BP(),{data:x,isLoading:S,error:C,isFetchingNextPage:w,hasNextPage:T,setEndOfListElement:E}=V_i({datasetId:m===`all`?void 0:m,target:{targetType:h,targetId:g},orderBy:p}),{data:D}=Zvi(),{supportsMetrics:O}=b7(),k=(0,G.useMemo)(()=>v?.datasets??[],[v?.datasets]),A=(0,G.useMemo)(()=>x??[],[x]),j=(0,G.useMemo)(()=>kyi(k),[k]),{data:M}=dIt({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}=B_i({experiments:A,supportsMetrics:O}),F=O?P??jbi:void 0,I=(0,G.useMemo)(()=>kbi(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&&JP(R))return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:J7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(jU,{variant:`fill`})]});if(C&&YP(C))return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:J7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(AU,{variant:`fill`,resource:`experiments`})]});if(b&&YP(b))return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:J7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(AU,{variant:`fill`,resource:`datasets`})]});if(R)return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:J7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load experiments`,descriptionSlot:R.message})]});let ne=(0,K.jsx)(y_i,{open:i,onOpenChange:a,onSuccess:e=>void c(`/experiments/${e}`)});return A.length===0&&!L&&m===`all`&&!h?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:J7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(Ayi,{onRunExperiment:()=>a(!0)}),ne]}):(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:J7}),headerActions:(0,K.jsx)(X,{variant:`primary`,size:`sm`,icon:(0,K.jsx)(Ho,{}),onClick:()=>a(!0),children:`New experiment`}),actionRow:(0,K.jsx)(Uyi,{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)(Dyi,{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 Nbi={baseline:`bg-badge-purple-indicator`,contender:`bg-badge-blue-indicator`};function Pbi({experimentId:e,name:t,role:n,className:r,trailing:i}){let{Link:a,paths:o}=gl(),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:m(`max-w-48 min-w-0`,r),"aria-label":`Open experiment ${s}`,children:[n&&(0,K.jsx)(`span`,{"aria-hidden":`true`,className:m(`size-1.5 shrink-0 rounded-full`,Nbi[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 Fbi(){let[e]=Hb(),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 Ibi(){let{datasetId:e,baselineId:t,contenderIds:n}=Fbi();return{datasetId:e,experimentIds:e&&t&&n.length>0&&t?[t,...n]:[]}}function Lbi(){let{experimentIds:e}=Ibi();return e.length>0?`Comparing ${e.length} experiments`:`Comparing`}function Rbi(){let{datasetId:e,experimentIds:t}=Ibi(),{data:n}=yIt({datasetId:e??``,experimentIds:t});return t.length===0?null:(0,K.jsxs)(yZ,{children:[(0,K.jsx)(bZ,{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)(h,{})})}),(0,K.jsx)(xZ,{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)(Pbi,{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)(bw,{variant:`purple`,size:`sm`,icon:(0,K.jsx)(Ks,{className:`fill-current`}),children:`Baseline`})})},e))})})]})}function zbi({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)(Pbi,{experimentId:t}),n<e.length-2&&`,`]})]},t))}function Bbi({datasetId:e,baselineId:t,contenderIds:n}){let[,r]=Hb(),i=(0,G.useMemo)(()=>[t,...n],[t,n]),{data:a,isLoading:o,error:s}=yIt({datasetId:e,experimentIds:i});return s&&JP(s)?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Compare`}),(0,K.jsx)(jU,{variant:`fill`})]}):s&&YP(s)?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Compare`}),(0,K.jsx)(AU,{variant:`fill`,resource:`experiments`})]}):s&&!XP(s)?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Compare`}),(0,K.jsx)(RC,{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)(zbi,{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)(Dbi,{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 Vbi(){let{datasetId:e,baselineId:t,contenderIds:n}=Fbi();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)(Bbi,{datasetId:e,baselineId:t,contenderIds:n})}function Hbi(){let{datasetId:e}=Fbi(),{Link:t,paths:n}=gl(),{data:r,isLoading:i}=VP({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:m(`flex max-w-64 min-w-0 rounded-[7px] hover:brightness-110`,_),children:(0,K.jsx)(bw,{size:`md`,icon:(0,K.jsx)(Tr,{}),className:`max-w-full min-w-0`,children:(0,K.jsx)(`span`,{className:`min-w-0 truncate`,children:a})})})}var Ubi=[{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 Wbi({datasetId:e,baselineId:t,contenderIds:n}){let{data:r}=fIt({datasetId:e,experimentIds:(0,G.useMemo)(()=>[t,...n],[t,n]),baselineId:t}),{supportsMetrics:i}=b7(),{isHidden:a,toggle:o,reset:s}=ubi(),c=(0,G.useMemo)(()=>[...new Set((r?.items??[]).flatMap(e=>Object.values(e.results).flatMap(e=>e?Object.keys(e.scores):[])))].sort(),[r]),l=Ubi.filter(e=>i||!e.usage);return(0,K.jsxs)(mD,{children:[(0,K.jsx)(mD.Trigger,{render:(0,K.jsx)(X,{variant:`ghost`,size:`md`,icon:(0,K.jsx)(vr,{"aria-hidden":!0}),children:`Metrics`})}),(0,K.jsxs)(mD.Content,{align:`end`,className:`min-w-56`,children:[(0,K.jsx)(mD.Label,{children:`Run metrics`}),l.map(e=>(0,K.jsx)(mD.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)(mD.Separator,{}),(0,K.jsx)(mD.Label,{children:`Scorers`}),c.map(e=>{let t=`scorer:${e}`;return(0,K.jsx)(mD.CheckboxItem,{checked:!a(t),onCheckedChange:()=>o(t),children:e},t)})]}),(0,K.jsx)(mD.Separator,{}),(0,K.jsx)(mD.Item,{onSelect:s,children:`Show all metrics`})]})]})}function Gbi(){let{datasetId:e,baselineId:t,contenderIds:n}=Fbi();return(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[e&&t&&n.length>0&&(0,K.jsx)(Wbi,{datasetId:e,baselineId:t,contenderIds:n}),(0,K.jsx)(Hbi,{})]})}var Kbi=[sF(`/experiments`),{id:`experiments-compare`,Component:Lbi,Switcher:Rbi}];function qbi(){return(0,K.jsx)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:Kbi}),headerActions:(0,K.jsx)(Gbi,{}),children:(0,K.jsx)(Vbi,{})})}function Jbi(e){let{data:t}=WP({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 Ybi=[`agent`,`workflow`,`scorer`];function Xbi({experiment:e}){let[t,n]=(0,G.useState)(!1),r=kb(),{paths:i}=gl(),a=Jbi(e),o=Ybi.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)(Vo,{}),children:`Rerun`}),t&&(0,K.jsx)(y_i,{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 Zbi({experiment:e,onDeleteClick:t}){let[n,r]=(0,G.useState)(!1),i=!!e.datasetId;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Xbi,{experiment:e}),(i||!!t)&&(0,K.jsxs)(mD,{children:[(0,K.jsx)(mD.Trigger,{asChild:!0,children:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,"aria-label":`Experiment actions menu`,children:(0,K.jsx)(Ar,{})})}),(0,K.jsxs)(mD.Content,{align:`end`,className:`w-48`,children:[i&&(0,K.jsxs)(mD.Item,{onSelect:()=>r(!0),children:[(0,K.jsx)(Lo,{}),` Rename experiment`]}),t&&(0,K.jsxs)(mD.Item,{onSelect:t,variant:`destructive`,children:[(0,K.jsx)(xc,{}),` Delete experiment`]})]})]}),n&&(0,K.jsx)(mbi,{experiment:e,open:!0,onOpenChange:r})]})}function Qbi(e){let{data:t,isLoading:n}=y8({traceId:e,queryOptions:{enabled:!!e}}),r=t?.spans.find(e=>!e.parentSpanId)?.entityType===`agent`,{supportsMetrics:i,isLoading:a}=b7(),o=r&&i,s=V$r({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 $bi=`__create_tag__`;function exi({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)(Bn,{"data-testid":`tag-applied`,className:`size-3.5`}):void 0})),t=a.trim();return t.length>0&&!s.includes(t)?[{label:`Create "${t}"`,value:$bi},...e]:e},[s,c,a]);return(0,K.jsx)(TP,{"data-testid":`experiment-results-tag-picker`,options:l,value:void 0,onValueChange:e=>{let t=e===$bi?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 txi(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function nxi({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)(m$.SectionHeading,{icon:(0,K.jsx)(zc,{}),children:`Tool Mocks`}),i&&(0,K.jsx)(EA,{variant:`destructive`,title:`Mock mismatch`,children:(0,K.jsxs)(EA.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)(uZ,{children:txi(i.args)})]}),n.length>0&&(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`mt-1 block`,children:[`Unconsumed mocks: `,(0,K.jsx)(uZ,{children:n.map(e=>txi(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:txi(e.args)})]}),(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`shrink-0 rounded px-2 py-0.5 ${rxi(e.outcome)}`,children:e.outcome})]},`${e.outcome}-${e.toolName}-${t}`))})]})}function rxi(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 ixi({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)(axi,{result:e,onClose:i,...o}):t?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(m$.Header,{children:[(0,K.jsxs)(m$.Heading,{children:[`Experiment item`,(0,K.jsx)(m$.CopyId,{id:t})]}),(0,K.jsx)(m$.HeaderActions,{children:(0,K.jsx)(m$.CloseButton,{icon:`x`,onClick:i})})]}),n]}):null;return a===`inline`?c?(0,K.jsx)(m$,{variant:`inline`,title:s,children:c}):null:(0,K.jsx)(m$,{open:!!(e??t),onClose:i,title:s,depth:1,children:c})}function axi({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=cxi(e.input),g=cxi(e.output),_=K_i(e),v=Z_i(e),y=Q_i(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}=gl(),E=m&&e.traceId?e.traceId:void 0,{data:D}=x8({traceId:E,queryOptions:{enabled:!!E}}),{usage:O,isLoading:k}=Qbi(e.traceId),A=k&&(e.targetType==null||e.targetType===`agent`),j=rbi({usage:O,showUsage:!!O||A,durationMs:K7(e),scores:[]}).map(e=>A&&(e.id===`cost`||e.id===`tokens`)?{...e,value:(0,K.jsx)(dw,{"aria-hidden":!0,className:`h-4 w-14`})}:e),M=typeof e.error==`string`&&e.error?e.error:I7(e),N=[...j,{id:`item-id`,icon:(0,K.jsx)(ui,{}),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:hU(e.itemId)}),(0,K.jsx)(jw,{content:e.itemId,tooltip:`Copy item ID to clipboard`,variant:`link`})]}),delta:null},...e.createdAt?[{id:`created`,icon:(0,K.jsx)(Fn,{}),label:`Created`,value:Fw(e.createdAt,`date-time`),delta:null}]:[],...e.status?[{id:`status`,icon:(0,K.jsx)(bee,{}),label:`Status`,value:(0,K.jsx)(Jti,{status:e.status}),delta:null}]:[],...C?[{id:`tags`,icon:(0,K.jsx)(Zs,{}),label:`Tags`,value:(0,K.jsx)(sxi,{tags:x,selectedResults:S,onTagsChange:l,tagVocabulary:u,isUpdatingTags:d}),delta:null}]:[],...rbi({showUsage:!1,durationMs:null,scores:(t??[]).map(e=>({scorerId:e.scorerId,value:e.score,reason:e.reason,label:o?(0,K.jsx)(oxi,{scorerId:e.scorerId,featured:s===e.id,onClick:()=>o(e.id)}):void 0}))})],P=(0,K.jsx)(m$.Content,{children:(0,K.jsxs)(`div`,{className:Tgi,children:[(0,K.jsx)(wgi,{metrics:N}),(0,K.jsx)(F7,{title:`Input`,framed:!0,actions:(0,K.jsx)(jw,{content:h}),children:(0,K.jsx)(P7,{value:e.input})}),e.groundTruth!=null&&(0,K.jsx)(F7,{title:`Ground Truth`,framed:!0,actions:(0,K.jsx)(jw,{content:cxi(e.groundTruth)}),children:(0,K.jsx)(P7,{value:e.groundTruth})}),M?(0,K.jsx)(F7,{title:`Error`,tone:`negative`,framed:!0,actions:(0,K.jsx)(jw,{content:M}),children:(0,K.jsx)(T,{tone:`muted`,className:`p-3 break-words`,children:M})}):(0,K.jsx)(F7,{title:`Output`,framed:!0,actions:(0,K.jsx)(jw,{content:g}),children:y?(0,K.jsx)(T,{tone:`muted`,className:`p-3 break-words`,children:y}):(0,K.jsx)(P7,{value:_??e.output})}),v.length>0&&(0,K.jsx)(F7,{title:`Tool calls (${v.length})`,children:(0,K.jsx)(Fri,{toolCalls:v})}),e.toolMockReport&&(0,K.jsx)(nxi,{report:e.toolMockReport})]})});return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(m$.Header,{children:[b&&(0,K.jsx)(X,{size:`sm`,variant:`primary`,onClick:()=>c(e.id),icon:(0,K.jsx)(or,{}),children:`Request review`}),p&&e.status===`needs-review`&&(0,K.jsx)(X,{size:`sm`,variant:`primary`,onClick:p,icon:(0,K.jsx)(Wn,{}),children:`Mark as reviewed`}),(0,K.jsxs)(m$.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)(mi,{})}),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)(oF,{})}),(0,K.jsx)(m$.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:`Go to previous result`,nextLabel:`Go to next result`}),(0,K.jsx)(m$.CloseButton,{icon:`x`,onClick:i})]})]}),E?(0,K.jsxs)(CA,{defaultTab:`details`,className:`grid h-full min-h-0 grid-rows-[auto_1fr]`,children:[(0,K.jsx)(m$.Header,{children:(0,K.jsxs)(SA,{variant:`pill-ghost`,size:`sm`,children:[(0,K.jsx)(wA,{value:`details`,children:`Details`}),(0,K.jsxs)(wA,{value:`feedback`,children:[`Feedback`,D?.pagination?.total!=null&&(0,K.jsxs)(K.Fragment,{children:[` (`,D.pagination.total,`)`]})]})]})}),(0,K.jsx)(TA,{value:`details`,flush:!0,children:P}),(0,K.jsx)(TA,{value:`feedback`,flush:!0,children:(0,K.jsx)(m$.Content,{children:m({traceId:E})})})]}):P]})}function oxi({scorerId:e,featured:t,onClick:n}){return(0,K.jsx)(`button`,{type:`button`,"aria-pressed":t,onClick:n,className:m(`min-w-0 cursor-pointer truncate hover:text-foreground hover:underline`,t&&`text-foreground`),children:e})}function sxi({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)(Ofi,{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)(Vc,{className:`size-3`})})]},t)),n&&(0,K.jsx)(exi,{selectedResults:t,vocabulary:r,onAddTag:t=>n([...e,t]),disabled:i,variant:`ghost`})]})}function cxi(e){return e==null?`-`:typeof e==`string`?e:JSON.stringify(e,null,2)}function lxi(e){let t=e.scorer;return t?.hasJudge===!1||t?.hasJudge!==!0&&!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function uxi({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:i}){return(0,K.jsx)(m$,{open:!!e,onClose:r,title:e?`Score ${e.scorerId}`:`Score`,depth:2,children:e&&(0,K.jsx)(dxi,{score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:i})})}function dxi({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:i}){let a=lxi(e),o=a?`Not applicable (code-based scorer)`:`Step not configured`;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(m$.Header,{children:[(0,K.jsx)(m$.CloseButton,{onClick:r,tooltip:`Close score panel`}),(0,K.jsxs)(m$.Heading,{children:[`Score`,(0,K.jsx)(m$.CopyId,{id:e.scorerId})]}),(0,K.jsxs)(m$.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)(oF,{})}),(n||t)&&(0,K.jsx)(m$.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:`Go to previous score`,nextLabel:`Go to next score`})]})]}),(0,K.jsx)(m$.Content,{children:(0,K.jsxs)(`div`,{className:`grid gap-3`,children:[(0,K.jsx)(m$.CodeSection,{title:`Score: ${e.score}`,icon:(0,K.jsx)(Di,{}),codeStr:e.reason||o,simplified:!0}),!a&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(m$.CodeSection,{title:`Preprocess Prompt`,icon:(0,K.jsx)(Ko,{}),codeStr:e.preprocessPrompt||o,simplified:!0}),(0,K.jsx)(m$.CodeSection,{title:`Analyze Prompt`,icon:(0,K.jsx)(Ko,{}),codeStr:e.analyzePrompt||o,simplified:!0}),(0,K.jsx)(m$.CodeSection,{title:`Generate Score Prompt`,icon:(0,K.jsx)(Ko,{}),codeStr:e.generateScorePrompt||o,simplified:!0}),(0,K.jsx)(m$.CodeSection,{title:`Generate Reason Prompt`,icon:(0,K.jsx)(Ko,{}),codeStr:e.generateReasonPrompt||o,simplified:!0})]})]})})]})}function fxi(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 pxi({result:e,scores:t,state:n,withQueryTrace:r,withFeedback:i,...a}){let o=fxi(t,e?.id),{navigate:s}=gl(),{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}=M_i({traceId:c,queryOptions:{enabled:!!c}}),x=y?.spans,S=x?.find(e=>!e.parentSpanId),{data:C}=x8({traceId:c??void 0,queryOptions:{enabled:i&&!!c}}),{data:w}=W$r({traceId:c??void 0,spanId:u,queryOptions:{enabled:i&&!!c&&!!u}}),{data:T}=$P({traceId:c??void 0,spanId:S?.spanId,page:0,queryOptions:{enabled:!!c&&!!S?.spanId}});return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(ixi,{...a,result:e,scores:t,onScoreClick:h,featuredScoreId:f,onShowTrace:e?.traceId?()=>g(e.traceId):void 0,feedbackTabSlot:i?({traceId:e})=>(0,K.jsx)(R5,{traceId:e},e):void 0}),(0,K.jsx)(uxi,{score:m??void 0,onNext:_(),onPrevious:v(),onClose:()=>p(null),onShowTrace:m?()=>g(m.traceId):void 0}),(0,K.jsx)(vbi,{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(kq(e,t)),feedbackTabBadge:i?C?.pagination?.total??void 0:void 0,feedbackTabSlot:i?({traceId:e})=>(0,K.jsx)(R5,{traceId:e}):void 0,scoresTabBadge:T?.pagination?.total??void 0,scoresTabSlot:({traceId:e,rootSpanId:n})=>n?(0,K.jsx)(MVr,{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)(Eni,{traceId:e,spanId:t},`${e}:${t}`):null:void 0})]})}function mxi({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}=W_i(),p=(0,G.useMemo)(()=>r?s.find(e=>e.itemId===r):void 0,[s,r]),{data:m}=WP({experimentId:i,experimentStatus:o,queryOptions:{enabled:!!i}}),{updateExperimentResult:h}=zP(),g=(0,G.useCallback)(async e=>{try{await h.mutateAsync({datasetId:a,experimentId:i,resultId:e,status:`needs-review`}),UC(`Result flagged for review`)}catch{UC.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`}),UC(`Result marked as reviewed`)}catch{UC.error(`Failed to complete result`)}},[a,i,h]),v=p?m?.[p.itemId]:void 0,y=fxi(v,p?.id);return(0,K.jsx)(pxi,{variant:n,result:p,itemId:r,fallback:c||l?(0,K.jsx)(m$.LoadingData,{}):(0,K.jsxs)(m$.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 hxi(e){let{currentItemId:t,close:n}=W_i(),r=fE();return S3r(t,n),r?(0,K.jsx)(mxi,{...e}):t?(0,K.jsx)(q8,{owner:`experiment-item`,children:(0,K.jsx)(mxi,{...e,variant:`inline`})}):null}function gxi({children:e,className:t}){return(0,K.jsx)(`div`,{className:`@container`,children:(0,K.jsx)(`div`,{className:m(`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 _xi=[{label:`Agent`,entityType:`agent`},{label:`Workflow`,entityType:`workflow_run`},{label:`Scorer`,entityType:`scorer`},{label:`Ingest`,entityType:`rag_ingestion`},{label:`Classifier`,entityType:`classifier`}],Y7=`rootEntityType`,X7={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`},vxi=Object.keys(X7),yxi=`mastra:metrics:saved-filters`;function bxi(e){let t=Pxi(e);try{localStorage.setItem(yxi,t.toString())}catch{}}function xxi(){try{let e=localStorage.getItem(yxi);if(!e)return null;let t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function Sxi(e){if(e.has(`rootEntityType`))return!0;for(let t of vxi)if(e.has(X7[t]))return!0;return!1}var Cxi=`hasAll`,wxi=[{id:`is`,label:`is`},{id:Cxi,label:`has all of`,arity:`many`}],Txi={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`},Exi={provider:fr,model:wr},Dxi=[`threadId`,`resourceId`,`userId`,`organizationId`,`runId`,`sessionId`,`requestId`,`experimentId`],Oxi=e=>({id:e,label:Txi[e],icon:Exi[e]??a0r(e),color:F8(e)}),kxi=(e,t)=>e.label.localeCompare(t.label);function Axi({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r}){let i=(e,t)=>({...Oxi(e),operators:[`is`],strict:!0,suggestions:t}),a=e=>({...Oxi(e),operators:[`is`]}),o=e=>e.map(e=>({value:e})),s=[i(`rootEntityType`,_xi.map(e=>({value:e.entityType,label:e.label}))),i(`entityName`,o(t)),{...i(`tags`,o(e)),operators:[Cxi]},i(`serviceName`,o(n)),i(`environment`,o(r))],c=Dxi.map(a),l=[`provider`,`model`].map(e=>({...a(e),hidden:!0}));return[...s.toSorted(kxi),...c.toSorted(kxi),...l]}function jxi(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:Cxi,value:t}}let t=Array.isArray(e.value)?e.value[0]??``:e.value;return{id:e.fieldId,fieldId:e.fieldId,operatorId:`is`,value:Lxi(t)?``:t}})}function Mxi(e){return e.map(e=>({fieldId:e.fieldId,value:Array.isArray(e.value)?e.value.map(String):String(e.value)}))}function Nxi(e){let t=[],n=new Map([[Y7,`rootEntityType`]]);for(let e of vxi)n.set(X7[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 Pxi(e){let t=new URLSearchParams,n=e.getAll(Y7);for(let e of n)t.append(Y7,e);for(let n of vxi){let r=X7[n],i=e.getAll(r);for(let e of i)t.append(r,e)}return t}function Fxi(e,t){e.delete(Y7);for(let t of vxi)e.delete(X7[t]);for(let n of t){let t=n.fieldId===`rootEntityType`?Y7:X7[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 Ixi=`Any`;function Lxi(e){let t=e.trim();return t===``||t===Ixi}var Rxi=new Set(_xi.map(e=>e.entityType));function zxi(e){let t=e.trim();return Rxi.has(t)?t:void 0}function Bxi(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=>!Lxi(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:zxi(e);n&&(t.rootEntityType=n)}else t[e]=r[0]}else if(typeof n.value==`string`){if(Lxi(n.value))continue;let r=n.value.trim();if(e===`rootEntityType`){let e=zxi(r);e&&(t.rootEntityType=e)}else t[e]=r}}return t}var Vxi={first:0,normal:1,last:2},Hxi=class extends Error{constructor(){super(`Skipped: nothing is waiting for this request any more`),this.name=`SkippedRequestError`}};function Uxi(e){let t=0,n=[],r=()=>{t<e&&n.shift()?.start()};return{run(i,{priority:a=Vxi.normal,isWanted:o}={}){return new Promise((s,c)=>{let l=e=>{e&&o&&!o()?(c(new Hxi),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 Wxi=(0,G.createContext)(void 0);function Gxi(){let e=(0,G.use)(Wxi);if(!e)throw Error(`useAggregateLimiter must be used inside MetricsProvider or AggregateLimiterProvider`);return e}function Kxi(e,t){let n=Gxi(),r=dy();return({queryKey:i})=>n.run(e,{priority:t,isWanted:()=>(r.getQueryCache().find({queryKey:i,exact:!0})?.getObserversCount()??0)>0})}function qxi({children:e}){let t=(0,G.use)(Wxi),[n]=(0,G.useState)(()=>t?void 0:Uxi(3));return(0,K.jsx)(Wxi,{value:t??n,children:e})}var Jxi=864e5,Yxi={"24h":Jxi,"3d":2592e5,"7d":6048e5,"14d":12096e5,"30d":2592e6};function Xxi(e,t,n){if(e!==`custom`){let t=Yxi[e]??Jxi;return{start:new Date(n-t),end:new Date(n)}}return{start:t?.from??new Date(n-Jxi),end:t?.to??new Date(n)}}function Zxi({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)(()=>Xxi(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 Qxi(e){let t=Y(),{filters:n,filterKey:r,queryOptions:i}=e;return Ey({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 $xi(e){let t=Y(),{filters:n,filterKey:r,queryOptions:i}=e;return Ey({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=>s8(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 eSi(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=s8(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 tSi(e){let t=Y(),{filters:n,filterKey:r,queryOptions:i}=e;return Ey({queryKey:[`metrics`,`trace-volume`,r],queryFn:async()=>{let[e,r,i]=await Promise.all([eSi(t,`mastra_agent_duration_ms`,n),eSi(t,`mastra_workflow_duration_ms`,n),eSi(t,`mastra_tool_duration_ms`,n)]);return{agentData:e,workflowData:r,toolData:i}},...i})}var nSi=[{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`}],rSi=new Set(nSi.map(e=>e.value));function iSi(e){return typeof e==`string`&&(rSi.has(e)||e===`custom`)}var aSi=(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 Z7(){return(0,G.useContext)(aSi)}function oSi(e,t){return e===`custom`?t?.from?t.to?`${Pw(t.from)} – ${Pw(t.to)}`:Pw(t.from)??``:`Custom range`:nSi.find(t=>t.value===e)?.label??e}var sSi=36e5;function cSi(e,t){if(e!==`custom`)return`vs previous ${e}`;let n=t?.to?.getTime()??Date.now(),r=t?.from?.getTime()??n-24*sSi,i=Math.round((n-r)/sSi);return`vs previous ${i>24&&i%24==0?`${i/24}d`:`${i}h`}`}function lSi({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)(()=>Bxi(l),[l]),d=(0,G.useMemo)(()=>JSON.stringify(u),[u]),f=Zxi({datePreset:t,customRange:a,dimensionalFilter:u,dimensionalFilterKey:d}),p=(0,G.useMemo)(()=>s??{},[s]),m=oSi(t,a),h=cSi(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)(aSi.Provider,{value:g,children:(0,K.jsx)(qxi,{children:e})})}var uSi=[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`];function dSi(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 fSi(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 pSi=864e5;function mSi(){let{data:e}=n5(),t=e?.capabilities.traceRetentionDays;if(t===void 0)return;let n=new Date(Date.now()-t*pSi);return new Date(n.getFullYear(),n.getMonth(),n.getDate())}function hSi(){let{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=Z7(),i=mSi();return(0,K.jsx)(z5r,{preset:dSi(e),onPresetChange:e=>t(fSi(e)),dateFrom:n?.from,dateTo:n?.to,onDateRangeChange:(e,t)=>r({from:e,to:t}),presets:uSi,minDate:i})}var gSi=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}));gSi.displayName=`MetricsCardAction`;function _Si({children:e,className:t}){return(0,K.jsx)(`div`,{className:m(`-my-1 flex shrink-0 items-center gap-1 self-start`,t),children:e})}function vSi({children:e,className:t}){return(0,K.jsx)(`div`,{className:m(`overflow-x-auto overflow-y-hidden [&_tbody>tr:last-child]:border-b-0`,t),children:e})}function ySi({className:e,...t}){return(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,className:m(`-my-1 shrink-0 cursor-grab active:cursor-grabbing`,e),...t,children:(0,K.jsx)(Vi,{})})}function bSi({message:e=`Failed to load data`,className:t}){return(0,K.jsx)(`div`,{className:m(`flex flex-col items-center justify-center gap-3`,t),children:(0,K.jsx)(T,{variant:`caption`,className:`text-destructive-foreground`,children:e})})}function xSi({label:e,value:t,change:n,isLoading:r=!1,className:i}){return(0,K.jsxs)(`div`,{className:m(`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:m(`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)(dw,{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 SSi({className:e}){return(0,K.jsx)(`div`,{className:m(`flex items-center justify-center`,e),children:(0,K.jsx)(Zc,{size:`md`,variant:`pulse`,className:`text-placeholder`})})}function CSi({message:e=`No data yet`,className:t}){return(0,K.jsx)(`div`,{className:m(`flex h-full items-center justify-center`,t),children:(0,K.jsx)(T,{tone:`faint`,children:e})})}function wSi({children:e,className:t}){return(0,K.jsx)(dF,{className:m(`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 TSi({children:e,className:t,as:n=`h3`}){return(0,K.jsx)(n,{className:m(`text-subheading text-foreground`,t),children:e})}function ESi({title:e,value:t,onValueChange:n,options:r,className:i}){return(0,K.jsx)(`div`,{className:`flex min-w-0`,children:(0,K.jsxs)(mD,{modal:!1,children:[(0,K.jsxs)(mD.Trigger,{render:(0,K.jsx)(`button`,{type:`button`,className:m(`-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)(h,{className:`size-3.5 text-muted-foreground`})]}),(0,K.jsx)(mD.Content,{align:`start`,children:(0,K.jsx)(mD.RadioOptions,{options:r,value:t,onValueChange:n,closeOnSelect:!0})})]})})}function DSi({children:e,className:t}){return(0,K.jsx)(`div`,{className:m(`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 OSi({children:e,className:t}){return(0,K.jsx)(`div`,{className:m(`flex items-start gap-4 [&>:first-child]:min-w-0 [&>:first-child]:flex-1`,t),children:e})}function kSi({value:e,isLoading:t=!1,className:n}){return(0,K.jsx)(`span`,{className:m(`order-last shrink-0 text-subheading text-foreground tabular-nums`,n),children:(0,K.jsx)(ASi,{value:e,isLoading:t})})}function ASi({value:e,isLoading:t}){return t?(0,K.jsx)(fw,{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 Q7=Object.assign(wSi,{Root:wSi,Kpi:v3,TopBar:OSi,Toolbar:DSi,Actions:_Si,Action:gSi,DragHandle:ySi,Title:TSi,TitleMenu:ESi,Total:kSi,Headline:xSi,Loading:SSi,Error:bSi,Content:vSi,NoData:CSi}),jSi=`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 MSi({onClick:e}){return(0,K.jsx)(Q7.Action,{label:`View in traces`,className:jSi,onClick:e,children:(0,K.jsx)(oF,{})})}function NSi({onClick:e}){return(0,K.jsx)(Q7.Action,{label:`View errors in logs`,className:jSi,onClick:e,children:(0,K.jsx)(Ia,{})})}function $7({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:m(`flex min-h-0 flex-1 flex-col`,e&&`invisible [&_.recharts-xAxis-tick-labels]:visible`),children:(0,K.jsx)(v7r.Provider,{value:e,children:n})}),e&&(0,K.jsx)(FSi,{message:t})]})}function PSi({className:e}){return(0,K.jsx)(`div`,{"aria-hidden":!0,className:m(`h-px bg-[linear-gradient(to_right,var(--border)_3px,transparent_3px)] bg-size-[6px_1px] opacity-50`,e)})}function FSi({message:e}){return(0,K.jsxs)(`div`,{className:`absolute inset-0 flex flex-col justify-between`,style:{paddingTop:y5.top,paddingBottom:22},children:[(0,K.jsx)(PSi,{}),(0,K.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,K.jsx)(PSi,{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)(PSi,{className:`flex-1`})]}),(0,K.jsx)(PSi,{})]})}function e9({variant:e=`default`,title:t,href:n,LinkComponent:r,titleMenu:i,dragHandle:a,onTitleChange:o,total:s,change:c,isLoading:l=!1,actions:u,toolbar:d,isUpdating:f=!1,bodyHeight:p=`fixed`,className:h,children:g}){let _=m(`transition-opacity duration-200`,f&&`opacity-50`),v=e===`compact`,y=e===`hero`,b=!y&&p===`fixed`;return(0,K.jsxs)(Q7,{className:m(`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)(Q7.TopBar,{children:[y?(0,K.jsx)(Q7.Headline,{label:t,value:typeof s==`string`?s:`—`,change:c,isLoading:l,className:_}):(0,K.jsx)(LSi,{title:t,href:n,LinkComponent:r,titleMenu:i,dragHandle:a,onTitleChange:o}),u&&(0,K.jsx)(Q7.Actions,{className:m(y&&`my-0 self-center`),children:u}),!y&&s!==void 0&&(0,K.jsx)(Q7.Total,{value:s,isLoading:l,className:_})]}),(0,K.jsxs)(Q7.Content,{className:m(`flex flex-col gap-4 overflow-visible`,v&&`min-h-0`),children:[d||b&&d!==void 0&&(0,K.jsx)(`div`,{"aria-hidden":!0,className:`min-h-6`}),(0,K.jsx)(`div`,{className:m(`relative flex min-h-0 min-w-0 flex-col`,ISi(e,p),_),children:g})]})]})}function ISi(e,t){if(e===`compact`)return`flex-1`;if(e!==`hero`)return t===`fit`?`min-h-60`:`min-h-60 flex-1`}function LSi({dragHandle:e,...t}){return e?(0,K.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1.5`,children:[(0,K.jsx)(Q7.DragHandle,{...e}),(0,K.jsx)(RSi,{...t})]}):(0,K.jsx)(RSi,{...t})}function RSi({title:e,href:t,LinkComponent:n,titleMenu:r,onTitleChange:i}){return r?(0,K.jsx)(Q7.TitleMenu,{title:e,...r}):t?(0,K.jsx)(`h3`,{className:`flex`,children:(0,K.jsx)(BSi,{href:t,LinkComponent:n,children:e})}):i?(0,K.jsx)(zSi,{title:e,onTitleChange:i}):(0,K.jsx)(Q7.Title,{children:e})}function zSi({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,...YA,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:m(`-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 BSi({href:e,LinkComponent:t,children:n}){return(0,K.jsxs)(t??`a`,{href:e,className:m(`-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)(Ra,{"aria-hidden":!0,className:`size-3.5 text-muted-foreground`})]})}function t9({error:e,onRetry:t}){return JP(e)?(0,K.jsx)(jU,{}):YP(e)?(0,K.jsx)(AU,{resource:`traces`}):(0,K.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3`,children:[(0,K.jsx)(Q7.Error,{message:`Couldn't load this data. Try again in a moment.`}),t&&(0,K.jsx)(X,{size:`sm`,icon:(0,K.jsx)(os,{}),onClick:t,children:`Retry`})]})}function VSi({label:e,icon:t,isError:n=!1,...r}){return(0,K.jsxs)(v3,{busy:!n&&(r.isLoading||r.isUpdating),children:[(0,K.jsx)(v3.Label,{icon:t&&(0,K.jsx)(t,{}),children:e}),n?(0,K.jsx)(HSi,{}):(0,K.jsx)(USi,{...r})]})}function HSi(){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(v3.ValueRow,{className:`mt-1`,children:(0,K.jsx)(v3.Value,{children:`—`})}),(0,K.jsx)(v3.Footer,{detail:(0,K.jsx)(`span`,{className:`text-destructive-foreground`,children:`Couldn't load`})})]})}function USi({value:e,change:t,lowerIsBetter:n,detail:r,previous:i,comparison:a,isLoading:o=!1,isUpdating:s=!1}){let c=m(`transition-opacity duration-200`,s&&`opacity-50`);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(v3.ValueRow,{className:m(`mt-1`,c),isLoading:o,children:[(0,K.jsx)(v3.Value,{children:e}),t!==void 0&&(0,K.jsx)(v3.Change,{changePct:t,comparison:a,lowerIsBetter:n,prevValue:i})]}),(0,K.jsx)(v3.Footer,{detail:r,prevValue:t===void 0?void 0:i,isLoading:o,className:c})]})}var WSi={2:`@3xl:grid-cols-2`,3:`@3xl:grid-cols-2 @7xl:grid-cols-3`},GSi={1:``,2:`@3xl:col-span-2`,full:`col-span-full`};function n9({children:e,columns:t=3,className:n}){return(0,K.jsx)(`div`,{className:m(`@container`,n),children:(0,K.jsx)(`div`,{className:m(`grid gap-4`,WSi[t]),children:e})})}function KSi({children:e,span:t=1,className:n}){return(0,K.jsx)(`div`,{className:m(`min-w-0 *:size-full *:min-w-0!`,GSi[t],n),children:e})}n9.Item=KSi;var qSi=864e5;function r9(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 i9=e=>e===`1h`?1:24;function JSi(e,t){if(t>=24)return Math.floor(e/qSi)*qSi;let n=new Date(e),r=Math.floor(n.getHours()/t)*t;return new Date(n.getFullYear(),n.getMonth(),n.getDate(),r).getTime()}function YSi(e,t){if(t>=24)return JSi(e,t)+qSi;let n=new Date(e);return JSi(new Date(n.getFullYear(),n.getMonth(),n.getDate(),n.getHours()+t).getTime(),t)}function XSi(e,t,n){let r=W9r(e,t),i=[];for(let a=JSi(e.getTime(),n);a<=t.getTime();a=YSi(a,n))i.push(q9r(a,n,r));return i}function ZSi(e,t){let n=new Map(e.map((e,t)=>[e.ts,t]));return e=>n.get(JSi(new Date(e.timestamp).getTime(),t))}function a9(e,t){return{from:new Date(e),to:new Date(YSi(e,t))}}function o9(){let{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r,queryFilters:i}=Z7(),a=Zxi({datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r});return i??a}var QSi={input:`mastra_model_total_input_tokens`,output:`mastra_model_total_output_tokens`,cacheRead:`mastra_model_input_cache_read_tokens`},$Si=`mastra_agent_duration_ms`;function eCi(){let e=Y(),{filters:t,filterKey:n,timestamp:r}=o9(),{interval:i,stepHours:a}=r9(r.start,r.end);return Ey({queryKey:[`metrics`,`activity`,n,i],placeholderData:vy,queryFn:async()=>{let n=n=>e.getMetricTimeSeries({name:[n],interval:i,aggregation:`sum`,filters:t}),[o,s,c,l]=await Promise.all([n(QSi.input),n(QSi.output),n(QSi.cacheRead),e.getMetricTimeSeries({name:[$Si],interval:i,aggregation:`count`,groupBy:[`status`],filters:t})]),u=XSi(r.start,r.end,a).map(e=>({...e,input:0,cacheRead:0,output:0,cost:0,completed:0,failed:0,failureRate:0})),d=ZSi(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 tCi=[{dataKey:`input`,label:`Input`,color:m5.green},{dataKey:`cacheRead`,label:`Cache read`,color:m5.violet},{dataKey:`output`,label:`Output`,color:m5.sky}],nCi=[{dataKey:`cost`,label:`Cost`,color:m5.green}],rCi={tokens:`Token usage`,cost:`Model cost`},iCi=[{value:`tokens`,label:rCi.tokens},{value:`cost`,label:rCi.cost}];function aCi({onViewTraces:e,onTimeRangeClick:t}){let[n,r]=(0,G.useState)(`tokens`),{data:i=[],isLoading:a,isError:o,isPlaceholderData:s}=eCi(),{timestamp:c}=o9(),{stepHours:l}=r9(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?tCi:nCi,m={title:rCi[n],titleMenu:{value:n,onValueChange:r,options:iCi},actions:e&&(0,K.jsx)(MSi,{onClick:e}),toolbar:(0,K.jsx)(Q7.Toolbar,{children:(0,K.jsx)(C5,{series:p})})};return o?(0,K.jsx)(e9,{...m,children:(0,K.jsx)(t9,{})}):(0,K.jsx)(e9,{...m,total:f?g5(u):v5(d),isLoading:a,isUpdating:s,children:(0,K.jsx)($7,{isEmpty:!a&&u===0&&d===0,children:(0,K.jsx)(F9r,{data:i,series:p,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:f?g5:v5,axisFormatter:f?h7r:g7r,onBucketClick:t&&(e=>t(a9(Number(e.ts),l))),isLoading:a,...p5})})})}var oCi=[{dataKey:`failureRate`,label:`Failed runs`,color:m5.error}],sCi=e=>`${Math.round(e*100)}%`;function cCi({onViewErrors:e,onTimeRangeClick:t,titleMenu:n}){let{data:r=[],isLoading:i,isError:a,isPlaceholderData:o}=eCi(),{timestamp:s}=o9(),{stepHours:c}=r9(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)(NSi,{onClick:e}),toolbar:(0,K.jsx)(Q7.Toolbar,{children:(0,K.jsx)(C5,{series:oCi})})};return a?(0,K.jsx)(e9,{...f,children:(0,K.jsx)(t9,{})}):(0,K.jsx)(e9,{...f,total:_5(l>0?u/l:0),isLoading:i,isUpdating:o,children:(0,K.jsx)($7,{isEmpty:!i&&l===0,children:(0,K.jsx)(p9r,{lineStyle:`thin`,data:r,series:oCi,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:_5,axisFormatter:sCi,yDomain:d,onBucketClick:t&&(e=>t(a9(Number(e.ts),c))),isLoading:i,...p5})})})}var lCi=[{dataKey:`completed`,label:`Completed`,color:m5.green},{dataKey:`failed`,label:`Failed`,color:m5.error}],uCi=[{value:`runs`,label:`Agent runs`},{value:`failure`,label:`Failure rate`}];function dCi({onTimeRangeClick:e,onFailureTimeRangeClick:t,onViewErrors:n}){let[r,i]=(0,G.useState)(`runs`),a={value:r,onValueChange:i,options:uCi};return r===`failure`?(0,K.jsx)(cCi,{titleMenu:a,onViewErrors:n,onTimeRangeClick:t}):(0,K.jsx)(fCi,{titleMenu:a,onTimeRangeClick:e})}function fCi({onTimeRangeClick:e,titleMenu:t}){let{data:n=[],isLoading:r,isError:i,isPlaceholderData:a}=eCi(),{timestamp:o}=o9(),{stepHours:s}=r9(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)(Q7.Toolbar,{children:(0,K.jsx)(C5,{series:lCi})})};return i?(0,K.jsx)(e9,{...l,children:(0,K.jsx)(t9,{})}):(0,K.jsx)(e9,{...l,total:g5(c),isLoading:r,isUpdating:a,children:(0,K.jsx)($7,{isEmpty:!r&&c===0,children:(0,K.jsx)(F9r,{data:n,series:lCi,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:g5,onBucketClick:e&&(t=>e(a9(Number(t.ts),s))),isLoading:r,...p5})})})}var pCi={.5:`p50`,.95:`p95`,.99:`p99`},mCi={agents:`mastra_agent_duration_ms`,workflows:`mastra_workflow_duration_ms`,tools:`mastra_tool_duration_ms`};function hCi(e){let t=Y(),{filters:n,filterKey:r,timestamp:i}=o9(),{interval:a}=r9(i.start,i.end),o=i9(a);return Ey({queryKey:[`metrics`,`latency-percentiles`,e,r,a],placeholderData:vy,queryFn:async()=>{let r=await t.getMetricPercentiles({name:mCi[e],percentiles:[.5,.95,.99],interval:a,filters:n}),s=XSi(i.start,i.end,o),c=ZSi(s,o);for(let e of r.series){let t=pCi[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 gCi={agents:kh.AGENT,workflows:kh.WORKFLOW_RUN,tools:kh.TOOL},_Ci=[{dataKey:`p50`,label:`P50`,color:m5.sky},{dataKey:`p95`,label:`P95`,color:m5.green,emphasis:!0},{dataKey:`p99`,label:`P99`,color:m5.violet}],vCi={agents:`Agent latency`,workflows:`Workflow latency`,tools:`Tool latency`},yCi=[{value:`agents`,label:vCi.agents},{value:`workflows`,label:vCi.workflows},{value:`tools`,label:vCi.tools}];function bCi({onViewTraces:e,onTimeRangeClick:t}){let[n,r]=(0,G.useState)(`agents`),{data:i=[],isLoading:a,isError:o,isPlaceholderData:s}=hCi(n),{timestamp:c}=o9(),l=i9(r9(c.start,c.end).interval),u=Math.max(0,...i.map(e=>e.p95??0)),d={title:vCi[n],titleMenu:{value:n,onValueChange:r,options:yCi},actions:e&&(0,K.jsx)(MSi,{onClick:()=>e(gCi[n])}),toolbar:(0,K.jsx)(Q7.Toolbar,{children:(0,K.jsx)(C5,{series:_Ci})})};return o?(0,K.jsx)(e9,{...d,children:(0,K.jsx)(t9,{})}):(0,K.jsx)(e9,{...d,total:m7r(u),isLoading:a,isUpdating:s,children:(0,K.jsx)($7,{isEmpty:!a&&u===0,children:(0,K.jsx)(p9r,{lineStyle:`thin`,data:i,series:_Ci,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:m7r,axisFormatter:_7r,onBucketClick:t&&(e=>t(a9(Number(e.ts),l))),isLoading:a,...p5})})})}var xCi=`-mx-2 flex w-[calc(100%+1rem)] items-center gap-3 rounded-md px-2 py-1 text-left`,s9=`shrink-0 text-right text-body-sm tabular-nums`;function SCi({row:e,columns:t,valueWidth:n,share:r,highlighted:i,dimmed:a,onHover:o,LinkComponent:s}){let c=m(xCi,i&&`bg-fill-subtle`,(e.href||e.onClick)&&`hover:bg-fill-subtle`);return(0,K.jsx)(`li`,{children:(0,K.jsxs)(CCi,{row:e,LinkComponent:s,className:c,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)(wCi,{row:e}),t.map((t,n)=>(0,K.jsx)(`span`,{className:m(s9,`text-muted-foreground`,t.width??`w-16`),children:e.cells?.[n]},t.label)),(0,K.jsx)(`span`,{className:m(s9,`w-12 text-muted-foreground`),children:r}),(0,K.jsx)(`span`,{className:m(s9,`text-foreground`,n),children:e.value})]})})}function CCi({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 wCi({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 TCi=`var(--chart-share-1)`,ECi=[1,2,3,4,5].map(e=>`var(--chart-share-${e})`),DCi=[3,4,2,5,1].map(e=>`var(--chart-share-${e})`),OCi=[1,.7,.48,.32,.2,.14],kCi={color:`var(--chart-share-rest)`,alpha:1},ACi=50,jCi=`__rest`;function MCi(e,t,n){if(n===`hues`){let n=ECi.includes(e)?[e,...ECi.filter(t=>t!==e)]:[e,...DCi];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:OCi[n]??.1}))}var NCi=e=>e.reduce((e,t)=>e+Math.max(t.share,0),0);function PCi(e){return e.map(e=>Number.isFinite(e.share)&&e.share>0?e:{...e,share:0}).toSorted((e,t)=>t.share-e.share)}function FCi(e,{limit:t,other:n,color:r,palette:i}){if(e.length<=t+1){let t=ICi(e,r,i);return{shown:t,bar:t,rest:[]}}let a=e.slice(t),o=n?.(a),s={key:jCi,label:`Other (${a.length})`,share:NCi(a),value:o?.value,cells:o?.cells,paint:kCi,segment:jCi},c=ICi(e.slice(0,t),r,i);return{shown:[...c,s],bar:c,rest:a}}function ICi(e,t,n){let r=MCi(t,e.length,n);return e.map((e,t)=>({...e,paint:LCi(e)??r[t]??kCi,segment:e.key}))}var LCi=e=>e.color?{color:e.color,alpha:1}:void 0;function RCi(e,{count:t,color:n,palette:r}){let i=Math.min(t,e.length,ACi),a=ICi(e.slice(0,i),n,r),o=e.slice(i,t).map(e=>({...e,paint:kCi,segment:jCi}));return{shown:[...a,...o],bar:a,rest:e.slice(i)}}function zCi(e,t){let n=e.map(e=>({key:e.key,share:e.share,paint:e.paint})),r=t.length?[{key:jCi,share:NCi(t),paint:kCi}]:[],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 BCi(e,t){if(t!==void 0)return e.find(e=>e.key===t)?.segment??t}var VCi=(e,t)=>t!==void 0&&t!==e;function HCi(e,t){return t===void 0||t===e.key?!1:t!==`__rest`||e.segment!==`__rest`}var UCi=(e,t)=>{let n=e/(t||1);return n>0?n<.001?`<0.1%`:`${(n*100).toFixed(+(n<.1))}%`:`0%`};function WCi({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)(h,{className:`size-3.5 shrink-0`}),`Show `,Math.min(o,r),` more`]}),e>n&&(0,K.jsxs)(`button`,{type:`button`,onClick:a,className:s,children:[(0,K.jsx)(l,{className:`size-3.5 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 GCi=[`w-32`,`w-24`,`w-36`,`w-20`,`w-28`];function KCi({className:e}){return(0,K.jsxs)(K.Fragment,{children:[`​`,(0,K.jsx)(dw,{className:m(`absolute top-1/2 h-3.5 -translate-y-1/2`,e)})]})}function qCi({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)(dw,{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:xCi,children:[(0,K.jsx)(dw,{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)(KCi,{className:m(`left-0`,GCi[r%GCi.length])})})}),t.map(e=>(0,K.jsx)(`span`,{className:m(s9,`relative`,e.width??`w-16`),children:(0,K.jsx)(KCi,{className:`right-0 w-10`})},e.label)),(0,K.jsx)(`span`,{className:m(s9,`relative w-12`),children:(0,K.jsx)(KCi,{className:`right-0 w-9`})}),(0,K.jsx)(`span`,{className:m(s9,`relative`,n),children:(0,K.jsx)(KCi,{className:`right-0 w-12`})})]},r))})]})}function JCi({className:e,...t}){return(0,K.jsx)(`div`,{className:m(`grid grid-cols-1`,e),children:(0,K.jsx)(YCi,{...t})})}function YCi({rows:e,columns:t=[],valueLabel:n,valueWidth:r=`w-14`,palette:i=`shades`,color:a=TCi,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)(XCi,{columns:t,valueLabel:n,valueWidth:r});if(d)return(0,K.jsx)(qCi,{rows:s===`other`?o+1:o,columns:t,valueWidth:r,header:v});let y=PCi(e);if(y.length===0)return(0,K.jsx)(T,{variant:`body-sm`,tone:`muted`,className:`py-6 text-center`,children:u});let b=NCi(y),x=s===`more`,{shown:S,bar:C,rest:w}=x?RCi(y,{count:_,color:a,palette:i}):FCi(y,{limit:o,other:l,color:a,palette:i}),E=zCi(C,w),D=BCi(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*(VCi(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)(SCi,{row:e,columns:t,valueWidth:r,share:UCi(e.share,b),highlighted:p===e.key,dimmed:HCi(e,p),onHover:()=>m(e.key),LinkComponent:f},e.key)),x&&(0,K.jsx)(WCi,{shown:Math.min(_,y.length),total:y.length,limit:o,pageSize:c,onMore:()=>g(e=>e+1),onLess:()=>g(0)})]})]})}function XCi({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:m(`shrink-0 text-right whitespace-nowrap`,e.width),children:e.label},e.label))})}var ZCi={agents:kh.AGENT,workflows:kh.WORKFLOW_RUN,tools:kh.TOOL},QCi=[{label:`Error rate`}],$Ci={agents:`Agent runs`,workflows:`Workflow runs`,tools:`Tool calls`},ewi=[{value:`agents`,label:$Ci.agents},{value:`workflows`,label:$Ci.workflows},{value:`tools`,label:$Ci.tools}],twi=(e,t)=>_5(t>0?e/t:0);function nwi({onViewTraces:e,onViewErrors:t,onEntityClick:n}){let[r,i]=(0,G.useState)(`agents`),a=ZCi[r],o=tSi({...o9(),queryOptions:{placeholderData:vy}}),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:g5(e.completed+e.errors),cells:[twi(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:$Ci[r],titleMenu:{value:r,onValueChange:i,options:ewi},actions:(e||t)&&(0,K.jsxs)(K.Fragment,{children:[e&&(0,K.jsx)(MSi,{onClick:()=>e(a)}),t&&(0,K.jsx)(NSi,{onClick:()=>t(a)})]})};return o.isError?(0,K.jsx)(e9,{...d,children:(0,K.jsx)(t9,{})}):(0,K.jsx)(e9,{...d,total:g5(u),isLoading:o.isLoading,isUpdating:o.isPlaceholderData,children:(0,K.jsx)($7,{children:(0,K.jsx)(JCi,{rows:c,columns:QCi,valueLabel:`Runs`,color:m5.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:g5(n),cells:[twi(t,n)]}},emptyState:`No runs in this range.`,isLoading:o.isLoading},r)})})}var rwi=[`mastra_model_total_input_tokens`,`mastra_model_total_output_tokens`],iwi=100;function awi(e){let t=Y(),{filters:n,filterKey:r}=o9();return Ey({queryKey:[`metrics`,`token-spend`,e,r],placeholderData:vy,queryFn:async()=>{let{groups:r}=await t.getMetricBreakdown({name:rwi,groupBy:[e],aggregation:`sum`,orderDirection:`DESC`,limit:iwi,filters:n});return r.map(t=>({key:String(t.dimensions[e]??`unknown`),tokens:t.value,cost:t.estimatedCost??0}))}})}var owi={agents:`Usage by agent`,models:`Usage by model`,threads:`Usage by thread`},swi=[{value:`agents`,label:owi.agents},{value:`models`,label:owi.models},{value:`threads`,label:owi.threads}],cwi={placeholderData:vy},lwi=[{label:`Tokens`}];function uwi(e){let[t,n]=(0,G.useState)(`agents`);return t===`models`?(0,K.jsx)(fwi,{...e,onViewChange:n}):t===`threads`?(0,K.jsx)(pwi,{...e,onViewChange:n}):(0,K.jsx)(dwi,{...e,onViewChange:n})}function dwi(e){let{onAgentClick:t}=e,{data:n=[],isLoading:r,isPlaceholderData:i,isError:a}=$xi({...o9(),queryOptions:cwi}),o=n.map(e=>({key:e.name,cost:e.cost??0,tokens:e.total,onClick:t&&(()=>t(e.name))}));return(0,K.jsx)(mwi,{view:`agents`,...e,rows:o,isLoading:r,isUpdating:i,isError:a})}function fwi(e){let{onModelClick:t}=e,{data:n=[],isLoading:r,isPlaceholderData:i,isError:a}=awi(`model`),o=n.map(e=>({...e,onClick:t&&(()=>t(e.key))}));return(0,K.jsx)(mwi,{view:`models`,...e,rows:o,isLoading:r,isUpdating:i,isError:a})}function pwi(e){let{onThreadClick:t}=e,{data:n=[],isLoading:r,isPlaceholderData:i,isError:a}=awi(`threadId`),o=n.map(e=>({...e,onClick:t&&(()=>t(e.key))}));return(0,K.jsx)(mwi,{view:`threads`,...e,rows:o,isLoading:r,isUpdating:i,isError:a})}function mwi({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:v5(e.cost),cells:[g5(e.tokens)],onClick:e.onClick})),l={title:owi[e],titleMenu:{value:e,onValueChange:t,options:swi},actions:n&&(0,K.jsx)(MSi,{onClick:n})};return o?(0,K.jsx)(e9,{...l,children:(0,K.jsx)(t9,{})}):(0,K.jsx)(e9,{...l,total:v5(r.reduce((e,t)=>e+t.cost,0)),isLoading:i,isUpdating:a,children:(0,K.jsx)($7,{children:(0,K.jsx)(JCi,{rows:c,columns:lwi,valueLabel:`Cost`,color:m5.green,other:e=>({value:v5(e.reduce((e,t)=>e+t.share,0)),cells:[g5(e.reduce((e,t)=>e+(s.get(t.key)??0),0))]}),emptyState:`No model usage in this range.`,isLoading:i})})})}var hwi=100;function gwi(){let e=Y(),{filters:t,filterKey:n,timestamp:r}=o9(),{interval:i}=r9(r.start,r.end),a=i9(i);return Ey({queryKey:[`metrics`,`scores`,n,i],placeholderData:vy,queryFn:async()=>{let n=await e.listScores({filters:t,pagination:{page:0,perPage:hwi}}),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=XSi(r.start,r.end,a),u=ZSi(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 _wi=[m5.green,m5.sky,m5.violet,m5.teal,m5.indigo],vwi=e=>e.toFixed(2),ywi=e=>String(+e.toFixed(2));function bwi(e){return e.map(({scorerId:e,name:t},n)=>({dataKey:e,label:t,color:_wi[n%_wi.length]??m5.neutral}))}function xwi(){let{data:e,isLoading:t,isError:n,isPlaceholderData:r}=gwi(),i=e?.scorers??[],a={title:`Scores`};return n?(0,K.jsx)(e9,{...a,children:(0,K.jsx)(t9,{})}):(0,K.jsx)(e9,{...a,isUpdating:r,children:(0,K.jsx)($7,{isEmpty:!t&&i.length===0,children:(0,K.jsx)(p9r,{lineStyle:`thin`,data:e?.buckets??[],series:bwi(i),height:`fill`,yDomain:[0,1],valueFormatter:vwi,axisFormatter:ywi,isLoading:t,...f7r})})})}var Swi=[`entityName`,`environment`,`threadId`,`resourceId`,`userId`,`organizationId`,`runId`,`sessionId`],Cwi=[`provider`,`model`],wwi=[`serviceName`,`requestId`,`experimentId`],Twi=(e,t)=>({op:`eq`,left:{path:e},right:{literal:t}});function Ewi(e){let t=wwi.filter(t=>e[t]!==void 0);if(t.length)return{supported:!1,unsupportedFields:t};let n=[];e.rootEntityType&&n.push(Twi(`entityType`,e.rootEntityType));for(let t of Swi){let r=e[t];r!==void 0&&n.push(Twi(t,r))}for(let t of e.tags??[])n.push({op:`includes`,path:`tags`,value:t});for(let t of Cwi){let r=e[t];r!==void 0&&n.push({spans:{some:Twi(t,r)}})}return n.length===0?{supported:!0,where:void 0}:{supported:!0,where:n.length===1?n[0]:{op:`and`,args:n}}}var Dwi=({start:e,end:t})=>({from:e.toISOString(),to:t.toISOString()}),Owi=({start:e,end:t})=>r9(e,t).interval;function kwi(e,t){let n=i9(Owi(t)),r=XSi(t.start,t.end,n).map(e=>({...e,rows:[]})),i=ZSi(r,n);for(let t of e)t.bucket&&r[i({timestamp:t.bucket,value:0})??-1]?.rows.push(t);return r}function Awi({requiresRootSpanFields:e=!1}={}){let{data:t,isLoading:n}=n5(),{timestamp:r,dimensionalFilter:i}=o9();if(n)return{status:`loading`};let a=t?.capabilities;if(a?.traceAggregate!==!0||e&&a.traceQueryRootSpanFields!==!0)return{status:`unavailable`};let o=Ewi(i);return o.supported?{status:`ready`,scope:{timeRange:Dwi(r),...o.where?{where:o.where}:{},interval:Owi(r),window:r}}:{status:`unsupported-filter`,unsupportedFields:o.unsupportedFields}}function c9(e,{priority:t,enabled:n}={}){let r=Y();return m$r({request:e,enabled:n,queryOptions:{queryFn:Kxi(()=>r.aggregateTraces(e),t),placeholderData:vy,staleTime:1/0}})}var jwi=[{measure:`countDistinct.resourceId`,dataKey:`resources`,label:`Resources`,color:m5.sky},{measure:`countDistinct.threadId`,dataKey:`threads`,label:`Threads`,color:m5.green},{measure:`countDistinct.userId`,dataKey:`users`,label:`Users`,color:m5.violet},{measure:`countDistinct.sessionId`,dataKey:`sessions`,label:`Sessions`,color:m5.teal}],Mwi=jwi.map(e=>e.measure),Nwi=`Resources and threads`;function Pwi(e,t){return e?.measures[t.measure]??0}function Fwi({scope:e,onTimeRangeClick:t}){let n=c9({timeRange:e.timeRange,where:e.where,interval:e.interval,measures:Mwi,limit:10}),r=c9({timeRange:e.timeRange,where:e.where,measures:Mwi}),i=r.data?.rows[0],a=jwi.filter(e=>Pwi(i,e)>0),o=a.map((e,t)=>({dataKey:e.dataKey,label:e.label,color:e.color,emphasis:t===0})),s=kwi(n.data?.rows??[],e.window).map(({rows:e,...t})=>({...t,...Object.fromEntries(a.map(t=>[t.dataKey,Pwi(e[0],t)]))})),c=i9(e.interval===`1d`?`1d`:`1h`),l=n.error??r.error,u=n.isLoading||r.isLoading,d={title:Nwi,total:l?void 0:a.length?a.map(e=>({label:e.label,value:g5(Pwi(i,e)),color:e.color})):g5(0),isLoading:r.isLoading,toolbar:o.length>0&&(0,K.jsx)(Q7.Toolbar,{children:(0,K.jsx)(C5,{series:o})})};return l?(0,K.jsx)(e9,{...d,children:(0,K.jsx)(t9,{error:l,onRetry:()=>{n.error&&n.refetch(),r.error&&r.refetch()}})}):(0,K.jsx)(e9,{...d,isUpdating:n.isPlaceholderData||r.isPlaceholderData,children:(0,K.jsx)($7,{isEmpty:!u&&a.length===0,children:(0,K.jsx)(p9r,{lineStyle:`thin`,data:s,series:o,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:g5,axisFormatter:h7r,onBucketClick:t&&(e=>t({window:a9(Number(e.ts),c)})),isLoading:u,...p5})})})}var Iwi={serviceName:`service`,requestId:`request ID`,experimentId:`experiment`};function Lwi({requiresRootSpanFields:e,children:t,...n}){let r=Awi({requiresRootSpanFields:e});return r.status===`unavailable`?null:r.status===`ready`?t(r.scope):(0,K.jsx)(e9,{...n,toolbar:null,children:r.status===`loading`?(0,K.jsx)(Q7.Loading,{}):(0,K.jsx)(Q7.NoData,{message:`Not available with a ${r.unsupportedFields.map(e=>Iwi[e]??e).join(` or `)} filter.`})})}function Rwi(e){return(0,K.jsx)(Lwi,{title:Nwi,children:t=>(0,K.jsx)(Fwi,{scope:t,...e})})}function zwi(){return Z7().scope}var Bwi=[`entityName`,`environment`,`serviceName`,`threadId`,`resourceId`,`userId`,`organizationId`,`runId`,`sessionId`,`requestId`,`experimentId`],Vwi=[`tags`,`provider`,`model`],Hwi=(e,t)=>({op:`eq`,left:{path:e},right:{literal:t}});function Uwi(e){let t=Vwi.filter(t=>e[t]!==void 0);if(t.length)return{supported:!1,unsupportedFields:t};let n=[];e.rootEntityType&&n.push(Hwi(`entityType`,e.rootEntityType));for(let t of Bwi){let r=e[t];r!==void 0&&n.push(Hwi(t,r))}return n.length===0?{supported:!0,where:void 0}:{supported:!0,where:n.length===1?n[0]:{op:`and`,args:n}}}function Wwi(){let{data:e,isLoading:t}=n5(),{timestamp:n,dimensionalFilter:r}=o9();if(t)return{status:`loading`};if(e?.capabilities.spanAggregate!==!0)return{status:`unavailable`};let i=Uwi(r);return i.supported?{status:`ready`,scope:{timeRange:Dwi(n),...i.where?{where:i.where}:{},interval:Owi(n),window:n}}:{status:`unsupported-filter`,unsupportedFields:i.unsupportedFields}}function Gwi(e,{priority:t,enabled:n}={}){let r=Y();return p$r({request:e,enabled:n,queryOptions:{queryFn:Kxi(()=>r.aggregateSpans(e),t),placeholderData:vy,staleTime:1/0}})}var Kwi=`Breakdown`,qwi={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 Jwi({tab:e,tabs:t,onTabChange:n,isUpdating:r,children:i}){return(0,K.jsx)(e9,{title:qwi[e],titleMenu:t.length>1?{value:e,onValueChange:n,options:t.map(e=>({value:e,label:qwi[e]}))}:void 0,isUpdating:r,bodyHeight:`fit`,children:i})}var Ywi={agents:[`agent_run`],workflows:[`workflow_run`],tools:[`tool_call`,`mcp_tool_call`]},Xwi=e=>e in Ywi;function Zwi(e){let t=Ywi[e];return t.length===1?{op:`eq`,left:{path:`spanType`},right:{literal:t[0]??``}}:{op:`in`,value:{path:`spanType`},set:[...t]}}var Qwi=e=>e!==`workflows`&&e!==`tools`,$wi=e=>e!==`models`,eTi=e=>e===`tools`||e===`models`;function l9(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 u9={trace:1e3,span:500};function tTi({timeRange:e,where:t}){return{timeRange:e,...t?{where:t}:{},groupBy:[`projectId`],measures:[`count`,`errorRate`,`duration.p95`,`countDistinct.resourceId`,`countDistinct.threadId`],limit:u9.trace}}function nTi({timeRange:e,where:t},n){return{timeRange:e,...t?{where:t}:{},groupBy:l9(`environments`,n),measures:[`count`,`errorRate`,`duration.p95`],limit:u9.trace}}function rTi(e){let t={op:`exists`,path:`threadId`};return e?{op:`and`,args:[t,e]}:t}function iTi({timeRange:e,where:t},n){return{timeRange:e,where:rTi(t),groupBy:n?[`projectId`,`threadId`]:[`resourceId`,`threadId`],measures:[`count`,`errorRate`,`duration.p95`],limit:u9.trace}}function aTi(e,t,n){return e===`projects`?tTi(t):e===`environments`?nTi(t,n):iTi(t,n)}function oTi({timeRange:e,where:t}){return{timeRange:e,where:rTi(t),groupBy:[`resourceId`,`threadId`],measures:[`count`],limit:u9.trace}}function sTi(e){let t=new Map;for(let n of e){let e=uTi(n,`resourceId`);e&&t.set(uTi(n,`threadId`),e)}return t}var cTi=e=>e===`agents`||e===`workflows`?`countDistinct.traceId`:`count`;function lTi(e,{timeRange:t,where:n},r){let i=Zwi(e);return{timeRange:t,where:n?{op:`and`,args:[i,n]}:i,groupBy:l9(e,r),measures:[`count`,...cTi(e)===`count`?[]:[`countDistinct.traceId`],`errorCount`,`errorRate`,`duration.p95`],limit:u9.span}}var d9=(e,t)=>{let n=e.measures[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0},uTi=(e,t)=>{let n=e.dimensions?.[t];return n==null?``:String(n)},dTi=(e,t)=>t.map(t=>e.dimensions[t]==null?``:String(e.dimensions[t])).join(`|`);function fTi({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=cTi(e);for(let e of n){let n=l(t.map(t=>uTi(e,t)).join(`|`));n.count=d9(e,u)??0,n.errorRate=d9(e,`errorRate`),n.p95=d9(e,`duration.p95`),n.resources=d9(e,`countDistinct.resourceId`),n.threads=d9(e,`countDistinct.threadId`)}for(let e of i)l(dTi(e,t)).count=e.value;for(let e of r??[]){let n=l(dTi(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 pTi({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=cTi(e);for(let e of n){let n=o(t.map(t=>uTi(e,t)).join(`|`));n.count=d9(e,s)??0,n.errorRate=d9(e,`errorRate`),n.p95=d9(e,`duration.p95`)}for(let e of i)o(dTi(e,t)).count=e.value;for(let e of r){let n=o(dTi(e,t));n.tokens=e.value,n.cost=e.estimatedCost??void 0}return a}function mTi(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 hTi(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:gTi(n,a,i),isNew:!1}}function gTi(e,t,n){return e===`errorRate`?t:n>0?t/n:void 0}function _Ti(e,t){if(e.delta!==void 0&&e.delta!==0)return e.delta>0==(t===`count`)?`good`:`bad`}var vTi=[`mastra_model_total_input_tokens`,`mastra_model_total_output_tokens`];function f9({groupBy:e,filters:t,window:n,measure:r=`tokens`,enabled:i=!0}){let a=Y(),{filters:o,filterKey:s}=o9();return Ey({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`?vTi:[`mastra_model_total_input_tokens`],groupBy:e,aggregation:r===`tokens`?`sum`:`count`,orderDirection:`DESC`,limit:1e3,filters:{...o,...t,timestamp:n}})})}function yTi({start:e,end:t}){return{start:new Date(2*e.getTime()-t.getTime()),end:new Date(e.getTime())}}var bTi=[`count`,`errorRate`,`p95`,`tokens`,`cost`],xTi=e=>bTi.includes(e),STi=e=>eTi(e)?`Spans`:`Traces`,CTi=`A trace is one end-to-end request, with every step it took.`,wTi=`A span is one step inside a trace, such as a tool call or a model call. One trace can have many.`,TTi=e=>eTi(e)?wTi:CTi,ETi={errorRate:`Errors`,p95:`P95 latency`,tokens:`Tokens`,cost:`Cost`},DTi=e=>e.toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`}),OTi=({start:e,end:t})=>`${DTi(e)} – ${DTi(t)}`;function kTi(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: ${OTi(e)}`,previous:`Previous: ${OTi(yTi(e))}`}}var ATi=(e,t)=>t&&e!==`projects`,jTi=(e,t)=>t===`count`?STi(e):ETi[t];function MTi({tab:e,built:t,previous:n,truncated:r,groupBy:i,usage:a}){return e===`threads`?t.filter(e=>e.name!==``):!n||r?t:mTi(t,n,i,a)}function NTi(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 PTi=(e,t)=>e===`projects`?t.key:t.projectId;function FTi(e,t){let n=PTi(e,t),r=n?{projectId:n}:{};return Xwi(e)?{...r,span:{spanTypes:Ywi[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 ITi(e,t){return t&&t.toUpperCase()!==`USD`?`${g5(e)} ${t}`:v5(e)}function LTi(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}${_5(r)}`}function RTi(e){let t=yTi(e.window);return{...e,window:t,timeRange:Dwi(t)}}var zTi={good:`text-badge-green-foreground`,bad:`text-badge-red-foreground`};function BTi({trend:e,children:t}){return t===void 0?(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`—`}):(0,K.jsx)(`span`,{className:e?zTi[e]:`text-muted-foreground`,children:t})}function VTi({change:e,metric:t}){return e?(0,K.jsx)(BTi,{trend:_Ti(e,t),children:LTi(e,t)}):(0,K.jsx)(BTi,{trend:void 0})}function HTi({window:e,label:t}){let{summary:n,current:r,previous:i}=kTi(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 UTi(){return(0,K.jsx)(`span`,{title:`No price for this model`,children:`Not priced`})}function WTi({row:e}){return e.cost===void 0?e.tokens?(0,K.jsx)(UTi,{}):`—`:ITi(e.cost,e.costUnit)}function p9({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 GTi({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)(qai,{parts:mPn(n.name,n.provider)}):t})]})}var KTi=e=>(0,K.jsxs)(`svg`,{width:`17`,height:`16`,viewBox:`0 0 17 16`,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`})]}),qTi={agent:tF,workflow:rP,tool:aF},JTi={agents:`agent`,workflows:`workflow`,tools:`tool`};function YTi({entity:e}){let t=qTi[e];return(0,K.jsx)(gPn,{icon:(0,K.jsx)(t,{className:`size-3`})})}function XTi({provider:e}){return e?(0,K.jsx)(_Pn,{provider:e}):(0,K.jsx)(gPn,{icon:(0,K.jsx)(KTi,{className:`size-3`})})}function ZTi({tab:e,row:t}){let n=JTi[e];return n?(0,K.jsx)(YTi,{entity:n}):e===`models`?(0,K.jsx)(XTi,{provider:t.provider}):null}function QTi({tab:e,row:t}){let{projectLabel:n}=zwi();return(0,K.jsx)(GTi,{mark:(0,K.jsx)(ZTi,{tab:e,row:t}),title:NTi(e,t,n),model:e===`models`&&t.name!==``?{name:t.name,provider:t.provider}:void 0})}function $Ti({text:e}){return(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`muted`,className:`truncate`,title:e,children:e})}var eEi={asc:Qt,desc:Pt},tEi=`focus-visible:outline-1 focus-visible:outline-solid focus-visible:outline-border-focus focus-visible:-outline-offset-1`,nEi=`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 rEi({header:e,explained:t,sorted:n,className:r,...i}){let a=n&&eEi[n];return(0,K.jsxs)(`button`,{type:`button`,...i,className:m(`group/header flex items-center gap-1 rounded whitespace-nowrap hover:text-muted-foreground`,tEi,r),children:[(0,K.jsx)(`span`,{className:m(t&&nEi),children:e}),a&&(0,K.jsx)(a,{"aria-hidden":!0,className:`size-3`})]})}function iEi({header:e,explained:t,className:n,...r}){return(0,K.jsx)(`span`,{tabIndex:t?0:void 0,...r,className:m(`group/header rounded whitespace-nowrap`,tEi,n),children:(0,K.jsx)(`span`,{className:m(t&&nEi),children:e})})}function aEi({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)(rEi,{header:e,explained:a,sorted:n,onClick:r,"aria-describedby":o}):(0,K.jsx)(iEi,{header:e,explained:a,"aria-describedby":o});return a?(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{render:s}),(0,K.jsx)(CC,{id:i,keepMounted:!0,side:`top`,className:`max-w-72`,children:t})]}):s}var oEi=`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)]`,sEi=`pt-1.75 pb-2 text-body-sm`,cEi=m(`relative col-span-full grid grid-cols-subgrid items-center px-3`,sEi,oEi),lEi=[`w-32`,`w-24`,`w-36`,`w-20`,`w-28`],uEi=`a, button, input, select, textarea, label, [role="button"], [role="link"], [contenteditable]`;function dEi(e){if(!(e.target instanceof Element))return!1;let t=e.target.closest(uEi);return!!(t&&e.currentTarget.contains(t))}function fEi(e,t,n){return e.align===`end`?`right-0 w-10`:t>0?`left-0 w-16`:m(`left-0`,lEi[n%lEi.length])}function pEi({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)(hEi,{columns:e,rowIndex:n},n)):t.length===0?i?r===void 0?(0,K.jsx)(mEi,{count:i}):(0,K.jsxs)(`div`,{role:`row`,className:`col-span-full grid *:col-start-1 *:row-start-1`,children:[(0,K.jsx)(mEi,{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)(gEi,{row:t,columns:e,...o},n(t)))}function mEi({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:sEi,children:`​`},t))})}function hEi({columns:e,rowIndex:t}){return(0,K.jsx)(`div`,{role:`row`,"aria-busy":!0,className:cEi,children:e.map((e,n)=>(0,K.jsxs)(`div`,{role:`cell`,className:m(`relative flex min-w-0`,e.align===`end`&&`justify-end`),children:[`​`,(0,K.jsx)(dw,{className:m(`absolute top-1/2 h-3.5 -translate-y-1/2`,fEi(e,n,t))})]},e.id))})}function gEi({row:e,columns:t,onRowClick:n,onRowHover:r,isRowDimmed:i,isRowActive:a,rowTitle:o}){let s=a?.(e)??!1,c=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=>{dEi(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:m(cEi,`rounded text-foreground transition-opacity duration-150`,n&&m(`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`,c&&`opacity-40`),children:t.map(t=>(0,K.jsx)(`div`,{role:`cell`,className:m(`flex min-w-0 items-center`,t.align===`end`&&`justify-end text-right`),children:t.cell(e)},t.id))})}var _Ei=`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)]`,vEi={asc:`ascending`,desc:`descending`};function yEi(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 bEi(e,t){return typeof e==`number`&&typeof t==`number`?e-t:String(e).localeCompare(String(t))}function xEi(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*bEi(n,a)})}var SEi=e=>e.width??(e.align===`end`?`minmax(max-content,1fr)`:`max-content`);function CEi({columns:e,rows:t,getRowKey:n,sort:r,defaultSort:i,onSortChange:a,onRowClick:o,onRowHover:s,isRowDimmed:c,isRowActive:l,rowTitle:u,empty:d,pageSize:f,isLoading:p=!1,"aria-label":h,className:g}){let[_,v]=(0,G.useState)(i),[y,b]=(0,G.useState)(0),x=r??_,S=xEi(t,e,x),C=f?Math.ceil(S.length/f):1,w=Math.min(y,Math.max(0,C-1)),T=f?S.slice(w*f,(w+1)*f):S,E={gridTemplateColumns:e.map(SEi).join(` `)},D=!p&&C>1,O=e=>{let t=yEi(x,e)??i;v(t),b(0),a?.(t)};return(0,K.jsxs)(`div`,{className:m(`grid min-w-0 gap-3`,g),children:[(0,K.jsxs)(lw,{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:m(`relative col-span-full grid grid-cols-subgrid items-end px-3 pb-1.5 text-label text-placeholder`,_Ei),children:e.map(e=>{let t=x?.column===e.id?x.direction:void 0;return(0,K.jsx)(`div`,{role:`columnheader`,"aria-sort":t&&vEi[t],className:m(`flex min-w-0 items-center gap-1`,e.align===`end`&&`justify-end text-right`),children:(0,K.jsx)(aEi,{header:e.header,description:e.description,sorted:t,onSort:e.sortValue?()=>O(e):void 0})},e.id)})}),(0,K.jsx)(pEi,{columns:e,rows:T,getRowKey:n,onRowClick:o,onRowHover:s,isRowDimmed:c,isRowActive:l,rowTitle:u,empty:d,pageSize:f,isLoading:p})]}),f!==void 0&&!p&&T.length>0&&(0,K.jsx)(mEi,{count:f-T.length})]}),D&&(0,K.jsx)(Hdi,{page:w,pageCount:C,onPageChange:b})]})}var wEi=10,TEi={column:`count`,direction:`desc`},EEi={projects:`Project`,agents:`Agent`,workflows:`Workflow`,tools:`Tool`,models:`Model`,threads:`Thread`,environments:`Environment`},DEi={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 OEi({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=zwi(),[p,m]=(0,G.useState)(TEi),[h,g]=(0,G.useState)(`count`),_=(e=TEi)=>{m(e),xTi(e.column)&&g(e.column)},v=[r,i,a].filter(e=>e!==void 0);if(v.some(e=>e.isError))return(0,K.jsx)(Jwi,{...d,tab:e,children:(0,K.jsx)(t9,{onRetry:()=>v.forEach(e=>e.isError&&void e.refetch())})});let y=v.some(e=>e.isLoading),b=$wi(e),x=i!==void 0,S=ATi(e,d.byProject),C=r?.data?.truncated===!0,w=y?[]:fTi({tab:e,groupBy:t,aggregateRows:r?.data?.rows,usageGroups:i?.data?.groups,spanGroups:a?.data?.groups,resources:o?.data?sTi(o.data.rows):void 0}),E=[s,c,l].every(e=>!e||!e.isLoading&&!e.isError)&&!y?pTi({tab:e,groupBy:t,aggregateRows:s?.data?.rows,usageGroups:c?.data?.groups,spanGroups:l?.data?.groups}):void 0,D=MTi({tab:e,built:w,previous:E,truncated:C,groupBy:t,usage:x}),O=STi(e),k=e=>E?hTi(e,E.get(e.key),h):void 0,A=e=>e.projectId?f.projectLabel?.(e.projectId)??e.projectId:`—`,j={id:`name`,header:EEi[e],width:`minmax(12rem,3fr)`,cell:t=>(0,K.jsx)(QTi,{tab:e,row:t})},M={id:`project`,header:`Project`,width:`minmax(8rem,2fr)`,cell:e=>(0,K.jsx)($Ti,{text:A(e)})},N={id:`resource`,header:`Resource`,width:`minmax(6rem,1fr)`,cell:e=>(0,K.jsx)($Ti,{text:e.resource??`—`})},P=[{id:`errorRate`,header:`Errors`,align:`end`,sortValue:e=>e.errorRate,cell:e=>(0,K.jsx)(p9,{muted:!0,children:e.errorRate===void 0?`—`:_5(e.errorRate)})},{id:`p95`,header:`P95 latency`,align:`end`,sortValue:e=>e.p95,cell:e=>(0,K.jsx)(p9,{muted:!0,children:e.p95===void 0?`—`:m7r(e.p95)})}],F=[{id:`tokens`,header:`Tokens`,align:`end`,sortValue:e=>e.tokens,cell:e=>(0,K.jsx)(p9,{muted:!0,children:e.tokens===void 0?`—`:g5(e.tokens)})},{id:`cost`,header:`Cost`,align:`end`,sortValue:e=>e.cost,cell:e=>(0,K.jsx)(p9,{muted:!0,children:(0,K.jsx)(WTi,{row:e})})}],I={id:`count`,header:O,align:`end`,description:TTi(e),sortValue:e=>e.count,cell:e=>(0,K.jsx)(p9,{children:g5(e.count)})},L={id:`change`,header:`% Change`,align:`end`,description:(0,K.jsx)(HTi,{window:n,label:jTi(e,h)}),sortValue:e=>k(e)?.change,cell:e=>(0,K.jsx)(p9,{children:(0,K.jsx)(VTi,{change:k(e),metric:h})})},R=[j,...S?[M]:[],...e===`threads`?[N]:[],...b?P:[],...x?F:[],I,L];return(0,K.jsx)(Jwi,{...d,tab:e,isUpdating:r?.isPlaceholderData,children:(0,K.jsxs)($7,{children:[(0,K.jsx)(CEi,{"aria-label":`${EEi[e]} breakdown`,columns:R,rows:D,getRowKey:e=>e.key,sort:p,defaultSort:TEi,onSortChange:_,onRowClick:d.onRowClick&&(t=>d.onRowClick?.(FTi(e,t))),pageSize:wEi,isLoading:y,empty:DEi[e]},e),!y&&C&&(0,K.jsxs)(T,{variant:`caption`,tone:`muted`,className:`pt-2`,children:[`Showing the `,g5(u),` busiest; sorting covers only these.`]})]})})}var kEi={entityType:`agent`};function AEi({tab:e,scope:t,...n}){let r=l9(e,n.byProject),i=Qwi(e),a=RTi(t),o=Gwi(lTi(e,t,n.byProject)),s=Gwi(lTi(e,a,n.byProject),{priority:Vxi.last}),c=f9({groupBy:r,filters:kEi,window:t.window,enabled:i}),l=f9({groupBy:r,filters:kEi,window:a.window,enabled:i});return(0,K.jsx)(OEi,{...n,tab:e,groupBy:r,window:t.window,aggregate:o,totals:i?c:void 0,previousAggregate:s,previousUsage:i?l:void 0,limit:u9.span})}function jEi(e){let t=l9(`models`,e.byProject),{timestamp:n}=o9(),r=yTi(n),i=f9({groupBy:t,window:n}),a=f9({groupBy:t,window:n,measure:`modelSpans`}),o=f9({groupBy:t,window:r}),s=f9({groupBy:t,window:r,measure:`modelSpans`});return(0,K.jsx)(OEi,{...e,tab:`models`,groupBy:t,window:n,totals:i,spans:a,previousUsage:o,previousSpans:s,limit:u9.trace})}function MEi({tab:e,scope:t,...n}){let r=l9(e,n.byProject),i=RTi(t),a=c9(aTi(e,t,n.byProject)),o=c9(aTi(e,i,n.byProject),{priority:Vxi.last}),s=c9(oTi(t),{enabled:e===`threads`&&n.byProject}),c=f9({groupBy:r,window:t.window}),l=n.byProject?s:a,u=f9({groupBy:r,window:i.window});return(0,K.jsx)(OEi,{...n,tab:e,groupBy:r,window:t.window,aggregate:a,totals:c,resources:e===`threads`?l:void 0,previousAggregate:o,previousUsage:u,limit:u9.trace})}var NEi={serviceName:`service`,requestId:`request ID`,experimentId:`experiment`,tags:`tags`,provider:`provider`,model:`model`};function PEi({tab:e,traceGate:t,spanGate:n,...r}){if(e===`models`)return(0,K.jsx)(jEi,{...r},e);let i=Xwi(e)?n:t;return i.status===`unsupported-filter`?(0,K.jsx)(Jwi,{...r,tab:e,children:(0,K.jsx)(Q7.NoData,{message:`Not available with a ${i.unsupportedFields.map(e=>NEi[e]??e).join(` or `)} filter.`})}):Xwi(e)?n.status===`ready`&&(0,K.jsx)(AEi,{...r,tab:e,scope:n.scope},e):t.status===`ready`&&(0,K.jsx)(MEi,{...r,tab:e,scope:t.scope},e)}function FEi({chosen:e,traceScope:t,spanGate:n,...r}){let i=c9(tTi(t)).data?.rows.filter(e=>(e.measures.count??0)>0).length,a=e??IEi(i);return(0,K.jsx)(PEi,{...r,tab:a,traceGate:{status:`ready`,scope:t},spanGate:n})}function IEi(e){return e===void 0||e>=2?`projects`:`agents`}var LEi=[`projects`,`agents`,`workflows`,`tools`,`models`,`threads`,`environments`],REi=LEi.filter(e=>e!==`projects`);function zEi({onRowClick:e}){let t=zwi().projectLabel!==void 0,n=Awi(),r=Wwi(),[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)(e9,{title:Kwi,bodyHeight:`fit`,children:(0,K.jsx)(Q7.Loading,{})});let o={tabs:t?LEi:REi,onTabChange:a,onRowClick:e,byProject:t};return t&&n.status===`ready`?(0,K.jsx)(FEi,{...o,chosen:i,traceScope:n.scope,spanGate:r}):(0,K.jsx)(PEi,{...o,tab:i??`agents`,traceGate:n,spanGate:r})}function BEi({experiment:e,metrics:t}){let{data:n}=WP({experimentId:e.id,experimentStatus:e.status,queryOptions:{enabled:!!e.id}}),{data:r,isLoading:i}=A_i({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?`—`:xw(new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime())??`—`,l=r[e.id]?.summary,u=B7(l),d=l?.inputTokens===void 0&&l?.outputTokens===void 0?`input + output`:(0,K.jsxs)(Gw,{singleLine:!0,children:[(0,K.jsxs)(Gw.Item,{children:[z7(l.inputTokens??0),` in`]}),(0,K.jsxs)(Gw.Item,{children:[z7(l.outputTokens??0),` out`]})]}),f=t?.isEnabled?t.data?.avgAgentDurationMs:void 0,p=f==null?void 0:xw(Math.round(f)),m=p?`${p} avg per item`:s?`started ${Fw(new Date(s),`date-time`)}`:`not started`;return(0,K.jsxs)(gxi,{children:[t?.isEnabled&&(0,K.jsx)(VSi,{label:`Total cost`,icon:mr,value:l?.estimatedCost===void 0?`—`:R7(l.estimatedCost,l.costUnit),detail:`estimated`,isLoading:a}),(0,K.jsx)(VSi,{label:`Run duration`,icon:_c,value:c,detail:m}),t?.isEnabled&&(0,K.jsx)(VSi,{label:`Total tokens`,icon:Gi,value:u===void 0?`—`:z7(u),detail:d,isLoading:a}),(0,K.jsx)(VSi,{label:`Avg score`,icon:Di,value:o==null?`—`:o.toFixed(3),detail:o==null?`no scores`:`across all scorers`,isLoading:o===void 0})]})}function VEi({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)(Vc,{}),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)(or,{}),children:`Request review`}),(0,K.jsx)(exi,{selectedResults:n,vocabulary:r,onAddTag:e.addTagToSelected,disabled:o})]})]})}var HEi=e=>Math.floor(Math.random()*e);function UEi({messages:e,intervalMs:t=3e3}){let n=e.length,[r,i]=(0,G.useState)(()=>HEi(n));return(0,G.useEffect)(()=>{if(n<2)return;let e=setInterval(()=>i(e=>(e+1+HEi(n-1))%n),t);return()=>clearInterval(e)},[n,t]),n===0?null:(0,K.jsx)(K.Fragment,{children:e[r%n]})}function WEi(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 GEi=[`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…`],KEi=`Waiting to start…`;function qEi({experiment:e}){let{status:t,totalItems:n,succeededCount:r,failedCount:i,startedAt:a}=e,o=WEi(),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?xw(u):void 0;return(0,K.jsx)(RC,{variant:`fill`,as:`h2`,iconSlot:(0,K.jsx)(Zc,{}),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?KEi:(0,K.jsx)(UEi,{messages:GEi})}),(0,K.jsxs)(Gw,{className:`justify-center tabular-nums`,children:[(0,K.jsxs)(Gw.Item,{children:[s,` / `,n,` `,c,` finished`]}),d&&(0,K.jsxs)(Gw.Item,{children:[d,` elapsed`]})]})]})})}var JEi={pending:{icon:(0,K.jsx)(lr,{className:`size-4 text-warning-foreground`}),label:W7.pending},running:{icon:(0,K.jsx)(Zc,{size:`sm`}),label:W7.running},completed:{icon:(0,K.jsx)(Kn,{className:`size-4 text-muted-foreground`}),label:W7.completed},failed:{icon:(0,K.jsx)(ir,{className:`size-4 text-destructive-foreground`}),label:W7.failed}};function YEi({status:e,className:t}){let n=JEi[e]??JEi.pending;return(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{render:(0,K.jsx)(`span`,{tabIndex:0,className:m(`flex shrink-0 items-center`,t),children:n.icon})}),(0,K.jsx)(CC,{children:n.label})]})}var XEi=()=>{let{experimentId:e}=Ab(),{data:t}=OIt({experimentId:e??``,queryOptions:{enabled:!!e,retryOnMount:!1}});return{experimentId:e,experiment:t}},ZEi=()=>{let{experimentId:e,experiment:t}=XEi(),n=t?.datasetId??``,{data:r}=vIt({datasetId:n,experimentId:e??``,queryOptions:{enabled:!!(n&&e),retryOnMount:!1}});return r??t};function QEi(){let{experimentId:e,experiment:t}=XEi();if(!e)return null;let n=e.length>8?`${e.slice(0,8)}...`:e;return t?.name||n}function $Ei(){let e=ZEi();return e?.status?(0,K.jsx)(YEi,{status:e.status}):null}function eDi(){let e=ZEi();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)(Gw,{children:[(0,K.jsx)(Gw.Item,{children:r}),n>0&&(0,K.jsxs)(Gw.Item,{children:[n,` errored`]})]})})}function tDi({datasetId:e,experimentId:t}){let[n,r]=(0,G.useState)(!1),{updateExperimentResult:i}=zP();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?UC(`Tag "${a}" added to ${c} result${c>1?`s`:``}`):UC.error(`Failed to add tag`)},[e,t,n,i]),isPending:n}}function nDi(e,t){let{data:n}=VP({datasetId:e,queryOptions:{enabled:!!e}});return(0,G.useMemo)(()=>[...new Set([...n?.tags??[],...t.flatMap(e=>e.tags??[])])].sort(),[n?.tags,t])}function rDi({datasetId:e,experimentId:t,results:n}){let[r,i]=(0,G.useState)(new Set),[a,o]=(0,G.useState)(!1),{updateExperimentResult:s}=zP(),{addTag:c,isPending:l}=tDi({datasetId:e,experimentId:t}),u=nDi(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}),UC(`${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 iDi=[];function aDi({crumbs:e,children:t}){return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{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 oDi(){let{experimentId:e}=Ab(),t=[sF(`/experiments`),{id:`experiment`,Component:QEi,icon:$Ei,Action:eDi}],n=kb(),[r,i]=(0,G.useState)(!1),a=r5(),{data:o,isLoading:s,error:c}=OIt({experimentId:e??``,queryOptions:{enabled:!!e}}),l=o?.datasetId??``,{data:u,isLoading:d,error:f}=vIt({datasetId:l,experimentId:e??``,queryOptions:{enabled:!!l&&!!e}}),p=u?.status===`completed`||u?.status===`failed`,{data:m,isLoading:h,setEndOfListElement:g,isFetchingNextPage:_,hasNextPage:v}=bIt({datasetId:l,experimentId:e??``,experimentStatus:u?.status,queryOptions:{enabled:!!l&&!!e&&p}}),{supportsMetrics:y}=b7(),b=j_i({experimentId:e,experimentStatus:u?.status,supportsMetrics:y,queryOptions:{enabled:!!e&&y&&p}}),x=rDi({datasetId:l,experimentId:e??``,results:m??iDi}),S=c??f;if(!e||s||d)return null;if(S&&JP(S))return(0,K.jsx)(aDi,{crumbs:t,children:(0,K.jsx)(jU,{})});if(S&&YP(S))return(0,K.jsx)(aDi,{crumbs:t,children:(0,K.jsx)(AU,{resource:`datasets`})});let C=(0,K.jsx)(aDi,{crumbs:t,children:(0,K.jsx)(RC,{titleSlot:`Experiment not found`,descriptionSlot:`No experiment with id "${e}".`,actionSlot:(0,K.jsx)(X,{render:(0,K.jsx)(Vb,{to:`/experiments`}),icon:(0,K.jsx)(Rt,{}),children:`Back to experiments`})})});return S&&XP(S)?C:S?(0,K.jsx)(aDi,{crumbs:t,children:(0,K.jsx)(RC,{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)(U_i,{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)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:t}),headerActions:(0,K.jsx)(Zbi,{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)(BEi,{experiment:u,metrics:b}),(0,K.jsxs)(`div`,{className:`grid content-start gap-1`,children:[(0,K.jsx)(VEi,{selection:x}),(0,K.jsx)(fvi,{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)(qEi,{experiment:u})]}),(0,K.jsx)(hxi,{withQueryTrace:a.enabled,withFeedback:a.enabled}),(0,K.jsx)($vi,{open:r,onOpenChange:i,experimentId:e,experimentName:u.name??void 0,onSuccess:()=>n(`/experiments`)})]})})}function sDi({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 c=()=>{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)(ZM,{variant:`unstyled`,ref:s,value:a,onChange:e=>o(e.target.value),onKeyDown:t=>{t.key===`Enter`&&(t.preventDefault(),c()),t.key===`Escape`&&(o(e),i(!1))},onBlur:c,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(),c()},className:m(ZC,`p-0.5`),children:(0,K.jsx)(Bn,{className:`h-3 w-3`})})]}):(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:m(ZC,`p-0.5 opacity-0 transition-opacity group-hover:opacity-100`),title:`Edit tag`,children:(0,K.jsx)(Lo,{className:`h-3 w-3`})}),(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)(Vc,{className:`h-3 w-3`})})]})}function cDi({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)($M,{open:o,onOpenChange:s,children:[(0,K.jsx)(eN,{asChild:!0,children:(0,K.jsxs)(X,{size:a,icon:(0,K.jsx)(Zs,{}),children:[`Tag `,e,` items`]})}),(0,K.jsxs)(tN,{className:`w-56 p-2`,align:`end`,children:[(0,K.jsx)(ZM,{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)(Vc,{className:`h-3 w-3`})})]},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 lDi=[{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`}],uDi=`__untagged__`,dDi=`all`,fDi=[{value:`review`,label:`Review queue`},{value:`completed`,label:`Completed`}];function pDi({datasetId:e,experimentId:t,experiments:n,isLoadingExperiments:r,targetType:i,targetId:a,featuredItemId:o,toolbarStart:s,renderFilters:c,toolbarEnd:l,onCreateScorer:u,breadcrumbs:d,withQueryTrace:f,withFeedback:p}){let h=Y(),{paths:g}=gl(),{data:_}=VP({datasetId:e??``,queryOptions:{enabled:!!e}}),v=Yvi({experimentId:t,targetType:i,targetId:a,experiments:n,isLoadingExperiments:r}),y=Xvi({experimentId:t,targetType:i,targetId:a,experiments:n,isLoadingExperiments:r}),{data:b,isLoading:x}=v,{data:S,isLoading:C}=y,{updateExperimentResult:w}=zP(),[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===uDi?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:dDi,label:`All tags`},...t>0?[{value:uDi,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===uDi?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}=WP({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=!!u&&!M&&ae.length>0,Ie=M?`completed`:`review`,Le=e=>{N(e===`completed`),D(null)},Re=(0,K.jsxs)(jq,{children:[(0,K.jsx)(jq.Start,{children:c?(0,K.jsxs)(K.Fragment,{children:[s,c({status:Ie,onStatusChange:Le,tag:O,onTagChange:k,tagOptions:oe.filter(e=>e.value!==dDi)})]}):(0,K.jsxs)(K.Fragment,{children:[s,(0,K.jsxs)(WA,{value:Ie,onValueChange:e=>Le(e===`completed`?`completed`:`review`),children:[(0,K.jsx)(KA,{"aria-label":`Status`,size:`md`,className:`whitespace-nowrap`,children:(0,K.jsx)(GA,{placeholder:`Select an option`})}),(0,K.jsx)(qA,{children:fDi.map(e=>(0,K.jsx)(JA,{value:e.value,children:e.label},e.value))})]}),oe.length>1&&(0,K.jsxs)(WA,{value:O??dDi,onValueChange:e=>k(e===dDi?null:e),children:[(0,K.jsx)(KA,{"aria-label":`Tags`,size:`md`,className:`whitespace-nowrap`,children:(0,K.jsx)(GA,{placeholder:`Select an option`})}),(0,K.jsx)(qA,{children:oe.map(e=>(0,K.jsx)(JA,{value:e.value,children:e.label},e.value))})]}),se&&(0,K.jsx)(X,{onClick:ce,size:`sm`,variant:`default`,icon:(0,K.jsx)(Vc,{}),children:`Reset`})]})}),(Pe||l||Fe)&&(0,K.jsxs)(jq.End,{children:[l,Fe&&(0,K.jsxs)(X,{size:`md`,onClick:()=>u?.(ae.map(e=>({input:e.input,output:e.output}))),children:[(0,K.jsx)(TC,{size:`xs`,children:(0,K.jsx)(Di,{})}),`Create scorer`]}),Pe&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(cDi,{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)(Wn,{}),children:`Mark as reviewed`}),(0,K.jsxs)(mD,{children:[(0,K.jsx)(mD.Trigger,{asChild:!0,children:(0,K.jsx)(X,{size:`icon-md`,disabled:P,"aria-label":`More actions`,children:P?(0,K.jsx)(Zc,{className:`h-4 w-4`}):(0,K.jsx)(Mr,{})})}),(0,K.jsxs)(mD.Content,{align:`end`,children:[(0,K.jsxs)(mD.Item,{onSelect:Ce,children:[(0,K.jsx)(TC,{size:`xs`,children:(0,K.jsx)(zs,{})}),`Analyze`]}),(0,K.jsx)(mD.Separator,{}),(0,K.jsxs)(mD.Item,{onSelect:Se,children:[(0,K.jsx)(TC,{size:`xs`,children:(0,K.jsx)(xc,{})}),`Remove from queue`]})]})]})]})]})]});if(x)return(0,K.jsxs)(uw,{breadcrumbs:d,actionRow:Re,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(Zc,{fill:!0})]});let ze=(0,K.jsx)(pxi,{withQueryTrace:f,withFeedback:p,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)(uw,{breadcrumbs:d,actionRow:Re,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(_E,{open:I,onOpenChange:L,children:(0,K.jsxs)(vE,{children:[(0,K.jsxs)(yE,{children:[(0,K.jsx)(SE,{children:`Analyze Items`}),(0,K.jsx)(CE,{children:`Use an LLM to automatically suggest tags for the selected items.`})]}),(0,K.jsxs)(xE,{children:[(0,K.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[(0,K.jsxs)(fA,{className:`gap-1`,children:[(0,K.jsx)(mA,{children:`Provider`}),(0,K.jsx)(LJ,{value:B,onValueChange:V})]}),(0,K.jsxs)(fA,{className:`gap-1`,children:[(0,K.jsx)(mA,{children:`Model`}),(0,K.jsx)(RJ,{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)(fA,{className:`gap-1`,children:[(0,K.jsx)(mA,{children:`Instructions (optional)`}),(0,K.jsx)(ZA,{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)(bE,{children:[(0,K.jsx)(wE,{children:`Cancel`}),(0,K.jsx)(gE,{onConfirm:we,disabled:!B||!H||P,children:`Analyze`})]})]})}),(0,K.jsx)(_E,{open:W,onOpenChange:ne,children:(0,K.jsxs)(vE,{size:`lg`,children:[(0,K.jsxs)(yE,{children:[(0,K.jsx)(SE,{children:`Review Proposed Tags`}),(0,K.jsxs)(CE,{children:[te.filter(e=>e.accepted).length,` of `,te.length,` proposals selected`]})]}),(0,K.jsx)(xE,{children:te.map((e,t)=>{let n=re.find(t=>t.id===e.itemId);return(0,K.jsx)(`div`,{className:m(`rounded-lg border p-3`,!e.accepted&&`opacity-50`),children:(0,K.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,K.jsx)(XM,{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)(sDi,{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)(bE,{children:[(0,K.jsx)(wE,{children:`Cancel`}),(0,K.jsxs)(gE,{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)(Zc,{fill:!0}):fe.length===0?(0,K.jsx)(RC,{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)(svi,{results:fe,isLoading:!1,featuredResultId:E,onResultClick:Ee,columns:lDi,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 mDi=`experiment`,hDi=`status`,gDi=[{value:`review`,label:`Review queue`},{value:`completed`,label:`Completed`}],_Di=[{id:`is`,label:`is`}],vDi=({targetType:e,targetId:t,experimentId:n,status:r,tag:i})=>{let a=Wfi({targetType:e,targetId:t});return n&&a.push(C7(mDi,n)),r!==`review`&&a.push(C7(hDi,r)),i&&a.push(C7(`tag`,i)),a},yDi=e=>({...Gfi(e),experimentId:w7(e,mDi),status:w7(e,`status`)===`completed`?`completed`:`review`,tag:w7(e,`tag`)||null});function bDi({targetType:e,targetId:t,experimentId:n,status:r,tag:i,experiments:a,tagOptions:o,onChange:s}){let c=Kfi(e),l=(0,G.useMemo)(()=>[...c,{id:mDi,label:`Experiment`,icon:mi,color:_F(`pink`),strict:!0,suggestions:a.map(e=>({value:e.id,label:ayi(e)}))},{id:hDi,label:`Status`,icon:Wn,color:_F(`orange`),strict:!0,suggestions:gDi},{id:`tag`,label:`Tag`,icon:Zs,color:_F(`pink`),strict:!0,hidden:o.length===0,suggestions:o}],[c,a,o]),u=(0,G.useMemo)(()=>vDi({targetType:e,targetId:t,experimentId:n,status:r,tag:i}),[e,t,n,r,i]);return(0,K.jsxs)(f5,{fields:l,operators:_Di,value:u,onValueChange:e=>s(yDi(e)),createItemId:e=>e,"aria-label":`Review queue filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(f5.Chips,{}),(0,K.jsx)(f5.Input,{placeholder:`Filter review queue`})]})}var xDi=[sF(`/experiments`),sF(`/experiments/review-queue`)],SDi=`experiment`,CDi=`review`;function wDi(){let[e,t]=Hb(),n=e.get(E7),r=Bfi(n)?n:``,i=r?e.get(`targetId`)??``:``,a=e.get(SDi),o=e.get(CDi),{Link:s,paths:c}=gl(),l=r5(),{data:u,error:d}=N_i({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(E7,e.targetType):n.delete(E7),s?n.set(D7,s):n.delete(D7),o?n.set(SDi,o):n.delete(SDi),n.delete(CDi),n},{replace:!0})};return d&&JP(d)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:xDi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(jU,{variant:`fill`})]}):d&&YP(d)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:xDi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(AU,{variant:`fill`,resource:`experiments`})]}):d?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:xDi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load experiments`,descriptionSlot:d.message})]}):(0,K.jsx)(pDi,{withQueryTrace:l.enabled,withFeedback:l.enabled,breadcrumbs:(0,K.jsx)(EP,{crumbs:xDi}),datasetId:f?.datasetId??void 0,experimentId:a??void 0,targetType:r,targetId:i,featuredItemId:o,renderFilters:e=>(0,K.jsx)(bDi,{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)(Jt,{}),children:`See experiment`}):void 0})}function TDi({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)(Gw,{children:[(0,K.jsx)(Gw.Item,{children:(0,K.jsx)(T,{as:`span`,variant:`caption`,children:e.label??`(no label)`})}),(0,K.jsx)(Gw.Item,{children:(0,K.jsx)(bw,{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 EDi({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return(0,K.jsx)(`ul`,{className:`space-y-1`,children:e.map(e=>(0,K.jsx)(TDi,{connection:e,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(e.connectionId)},e.connectionId))})}function DDi({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)(EDi,{connections:i,isAdmin:t,disconnectPending:n,onDisconnect:r})]},e))})}function ODi({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)(DDi,{groups:r,isAdmin:i,disconnectPending:s,onDisconnect:l}):(0,K.jsx)(EDi,{connections:n,isAdmin:i,disconnectPending:s,onDisconnect:l}),c?(0,K.jsx)(`p`,{className:`text-destructive-foreground`,children:String(c)}):null]})}function kDi({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)(fA,{invalid:!!o,disabled:a,children:[(0,K.jsx)(mA,{children:`Provider`}),(0,K.jsxs)(WA,{value:n,onValueChange:f,children:[(0,K.jsx)(KA,{children:(0,K.jsx)(GA,{placeholder:a?`Loading providers…`:`Select provider`})}),(0,K.jsx)(qA,{children:e.map(e=>(0,K.jsx)(JA,{value:e.id,children:`${e.displayName??e.name} (${e.id})`},e.id))})]}),(0,K.jsx)(gA,{children:o?String(o):void 0})]}),(0,K.jsxs)(fA,{invalid:!!c,disabled:!n||s,children:[(0,K.jsx)(mA,{children:`Toolkit`}),(0,K.jsxs)(WA,{value:r,onValueChange:p,children:[(0,K.jsx)(KA,{children:(0,K.jsx)(GA,{placeholder:s?`Loading toolkits…`:`Select toolkit`})}),(0,K.jsx)(qA,{children:t.map(e=>(0,K.jsx)(JA,{value:e.slug,children:`${e.name} (${e.slug})`},e.slug))})]}),(0,K.jsx)(gA,{children:c?String(c):void 0})]}),(0,K.jsxs)(fA,{disabled:!n||!r,children:[(0,K.jsx)(mA,{children:`Label (optional)`}),(0,K.jsx)(ZM,{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)(EA,{variant:`destructive`,children:String(u)})}):null,d?(0,K.jsxs)(EA,{variant:`success`,children:[`Authorized: `,d.connectionId,` (status: `,d.status,`)`]}):null]})}var ADi=e=>e.authorId?.trim()||`shared`,jDi=(e,t)=>{if(!t||new Set(e.map(ADi)).size<=1)return null;let n=new Map;for(let t of e){let e=ADi(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},MDi=[`*`,`tool-providers:*`,`tool-providers:admin`];function NDi(){let{data:e}=My();return e?.permissions?.some(e=>MDi.includes(e))??!1}var PDi=[{id:`integrations`,label:`Integrations`}];function FDi(){let[e,t]=(0,G.useState)(``),[n,r]=(0,G.useState)(``),[i,a]=(0,G.useState)(``),o=HJ(),s=WJ({providerId:e||null,queryOptions:{enabled:!!e}}),c=Nzn({providerId:e||null,toolkit:n||null}),l=jzn(),u=Mzn(),d=NDi(),f=o.data?.providers??[],p=s.data?.data??[],m=(0,G.useMemo)(()=>c.data?.items??[],[c.data?.items]),h=(0,G.useMemo)(()=>jDi(m,d),[m,d]);return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:PDi}),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)(kDi,{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)(ODi,{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 m9(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 IDi(e){return!e.deletedAt&&!e.mergedInto}function LDi(e){let t=new Map;for(let n of e)IDi(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)=>m9(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)=>m9(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)=>m9(e.page,t.page));for(let t of e)s(t.children)};return s(n),n}function RDi(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 zDi(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 h9(e){return e.childCountCapped?`${e.childCount??0}+`:String(e.childCount??0)}function BDi(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&&!g9(e)).slice(0,8).forEach(e=>n.add(e.id)),n}var VDi=`more:`,HDi=`rest:`,UDi=`group:`;function g9(e){return e.id.startsWith(VDi)}function _9(e){return e.id.startsWith(HDi)}function v9(e){return e.id.startsWith(UDi)}function WDi(e){return e.filter(e=>!e.deletedAt&&!e.mergedInto)}function GDi(e,t,n=ZDi){let r=WDi(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(m9);o.sort(m9);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&&!v9(e)&&!g9(e)&&l.has(e.id)&&m.set(e.id,`scope`);let h=BDi(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))&&!g9(e),i=t!==void 0&&m.has(e.id)&&!g9(e),a=t===void 0&&n.has(e.id)&&!g9(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 KDi=230,qDi=300,JDi=150,YDi=70,XDi=28,y9=16,ZDi=new Set;function QDi(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+y9,u=l+a;for(let e=0;c.length&&e<12;e++){let e=Math.asin(Math.min(1,(a+y9/2)/l)),t=2*Math.asin(Math.min(1,(a*2+y9)/(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+y9}return{points:s,reach:u}}function $Di(e,t,n,r=ZDi){let i=WDi(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*qDi))),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(KDi,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?JDi:YDi,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/XDi)),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*XDi);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+y9+e,C.length*(e*2+y9)/(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=QDi(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+y9+r/2),x();let i=QDi(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*XDi/(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)+YDi;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 eOi=[`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 tOi(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,eOi[t%eOi.length]]))}var nOi=.7,rOi=.7;function iOi(e){return e<=16?1:Math.max(rOi,Math.sqrt(16/e))}var aOi={author:``};function oOi(e,t,n){return{id:e,scopeId:t.scopeId,parentId:t.id,isScope:!1,position:``,name:``,version:0,createdBy:aOi,updatedBy:aOi,createdAt:``,updatedAt:``,...n}}function sOi(e){if(!e.isScope||!e.address)return null;let t=e.address.indexOf(`:`);return t>0?e.address.slice(0,t):null}function cOi(e){let t=e.cap??48,n=WDi(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(m9);a.sort(m9);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=BDi(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=oOi(`${VDi}${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=sOi(e);t&&g.set(t,[...g.get(t)??[],e])}let _=new Set;if(n!==f?.id)for(let[t,r]of g){let i=`${UDi}${n}:${t}`;if(r.length<3||e.openGroups.has(i))continue;for(let e of r)_.add(e.id);let c=oOi(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=oOi(`${HDi}${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&&!v9(e)&&!g9(e)&&!_9(e));return m.push(...h.slice(0,24).map(e=>e.id)),{pages:[...s.values()],hiddenChildren:c,wanted:m,hub:f?.id??null}}var lOi={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:pQ},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:MNn}};function uOi(e){if(!e.isScope||!e.address)return;let t=e.address.slice(0,e.address.indexOf(`:`));return Object.hasOwn(lOi,t)?lOi[t]:void 0}function b9(e){let t=uOi(e);return t&&e.name===e.address?t.label:e.name}function dOi(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 fOi(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 pOi(e){return e.normalize(`NFKC`).trim().replace(/\s+/g,` `).toLowerCase()}function mOi(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=pOi(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(pOi(i))??void 0}}}function hOi(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&&gOi(n,c,l,t)?[n]:[]});return u.length===1?u[0]:void 0}function gOi(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 _Oi=/\[\[([^\]]+)\]\]/g,vOi=/^(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:^\1[ \t]*$|(?![\s\S]))/gm,yOi=/(`+)[\s\S]*?\1/g;function bOi(e){return[...e.replace(vOi,``).replace(yOi,``).matchAll(_Oi)].map(e=>e[1]??``)}function xOi(e){let t=mOi(e),n=[];for(let r of e){if(!r.body||r.deletedAt||r.mergedInto)continue;let e=new Map;for(let n of bOi(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 SOi=(0,G.createContext)(new Map),COi=12,wOi=320;function TOi({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+COi,maxHeight:Math.min(wOi,e.y-COi-8)};let r=t.height>0?t.height-e.y-COi-8:wOi;return{left:n,top:e.y+COi,maxHeight:Math.min(wOi,r)}}function EOi(e,t){let n=(0,G.useRef)(e);return t(n.current,e)||(n.current=e),n.current}var DOi=/\[\[([^\]]+)\]\]/g;function OOi(e){let t=[],n=0;for(let r of e.matchAll(DOi))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 kOi({page:e,className:t}){let n=uOi(e)?.icon;return n?(0,K.jsx)(n,{"aria-hidden":!0,className:m(`shrink-0 text-foreground`,t)}):null}function x9({label:e,children:t}){return(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{render:t}),(0,K.jsx)(CC,{children:e})]})}var AOi={"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 jOi(e){return e.startsWith(`importer:`)?`Importer`:e}function MOi({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 NOi(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 POi=(0,G.createContext)(null);function FOi({node:e,...t}){let n=(0,G.useContext)(POi),r=e?.properties[wZ];if(typeof r!=`string`||!n)return(0,K.jsx)(`span`,{...t});let i=n.index.resolve(r);return i?(0,K.jsx)(x9,{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)(x9,{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 IOi=[c8n],LOi={span:FOi};function S9({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 ROi({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 zOi=new WeakMap;function BOi(e,t){let n=zOi.get(e);n||zOi.set(e,n=new WeakMap);let r=n.get(t);return r||n.set(t,r=mOi(e.values(),t)),r}function VOi({note:e,pagesById:t,onPageClick:n,highlighted:r,itemRef:i,showPage:a,compact:o}){let s=BOi(t,(0,G.useContext)(SOi)),c=n=>hOi(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)(MOi,{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:jOi(e.provenance.author)}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:(0,K.jsx)(jA,{value:e.updatedAt})}),u?(0,K.jsxs)(T,{as:`span`,variant:`caption`,tone:`muted`,children:[`on `,(0,K.jsx)(ROi,{page:u,onPageClick:n})]}):null]}),(0,K.jsx)(`p`,{className:`text-ui-md wrap-anywhere text-foreground`,children:OOi(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)(x9,{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)(bw,{variant:`neutral`,size:`xs`,title:l(e),children:(0,K.jsx)(`span`,{className:`truncate`,children:l(e)})},e))}):null]})]})}function HOi({page:e,notes:t,pin:n,pagesById:r,onPageClick:i,highlightMentionOf:a,ancestors:o=[],mentionedBy:s=[],notesMore:c,childPages:l,activity:u,compact:d=!1}){let f=(0,G.useRef)(null);(0,G.useEffect)(()=>{f.current?.scrollIntoView?.({block:`nearest`})},[a,t]);let p=!1,m=e.isScope?e:o.find(t=>t.id===e.scopeId)??r.get(e.scopeId),h=NOi(e,o),g=e.isScope?e.displayLabel??`Scope`:`Page`,_=(0,G.useMemo)(()=>new Map([...r,...[...o,e].map(e=>[e.id,e])]),[r,o,e]),v=(0,G.useContext)(SOi),y=(0,G.useMemo)(()=>mOi([...r.values(),...o,e],v),[r,o,e,v]),b=(0,G.useMemo)(()=>({index:y,onPageClick:i}),[y,i]);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:d?`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)(uP,{label:`Breadcrumb`,className:`ml-[-.9em] min-w-0`,listClassName:`overflow-hidden`,children:[o.map(e=>(0,K.jsx)(fP,{as:`button`,onClick:()=>i(e),children:b9(e)},e.id)),(0,K.jsx)(fP,{as:`span`,isCurrent:!0,children:b9(e)})]}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[d?null:(0,K.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(kOi,{page:e,className:`size-icon-lg`}),(0,K.jsx)(x9,{label:(e.isScope?e.address:h)??e.name,children:(0,K.jsx)(T,{as:`h2`,variant:`title`,className:`min-w-0 break-words`,"data-testid":`knowledge-page-title`,children:b9(e)})}),(0,K.jsxs)(bw,{variant:`neutral`,size:`sm`,className:`shrink-0 tabular-nums`,children:[`v`,e.version]})]}),e.description?(0,K.jsx)(T,{variant:`body`,tone:`muted`,children:e.description}):null,(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,K.jsx)(bw,{variant:e.isScope?`info`:`neutral`,size:`sm`,children:g}),n?(0,K.jsx)(bw,{variant:`warning`,size:`sm`,icon:(0,K.jsx)(zo,{size:10,"aria-hidden":!0}),children:n.audience.length>0?`Pinned for ${n.audience.join(`, `)}`:`Pinned`}):null,(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,"data-testid":`knowledge-page-version`,children:(0,K.jsxs)(Gw,{children:[e.isScope?null:(0,K.jsxs)(Gw.Item,{children:[`In `,m?b9(m):e.scopeId]}),d?(0,K.jsxs)(Gw.Item,{children:[`v`,e.version]}):null,(0,K.jsxs)(Gw.Item,{children:[`Updated`,` `,(0,K.jsx)(jA,{value:e.updatedAt,label:`Updated by ${jOi(e.updatedBy.author)}`})]})]})})]})]})]}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-8 ${d?`p-4`:`p-6`} @4xl:flex-row`,children:[(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-8 @4xl:flex-1`,children:[e.body?(0,K.jsx)(`div`,{"data-testid":`knowledge-page-body`,className:`max-w-3xl`,children:(0,K.jsx)(POi.Provider,{value:b,children:(0,K.jsx)(xX,{remarkPlugins:IOi,components:LOi,children:e.body})})}):(0,K.jsxs)(T,{variant:`body`,tone:`muted`,children:[`This `,e.isScope?`scope`:`page`,` has no body yet.`]}),t.length>0||c?(0,K.jsxs)(S9,{label:`Notes`,count:c?void 0:t.length,children:[(0,K.jsx)(`ul`,{className:`flex flex-col gap-2`,children:t.map(e=>{let t=!!a&&e.mentions.includes(a),n=t&&!p;return n&&(p=!0),(0,K.jsx)(VOi,{note:e,pagesById:_,onPageClick:i,highlighted:t,itemRef:n?e=>{f.current=e}:void 0},e.id)})}),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 @4xl:w-72 @4xl:shrink-0 @4xl:border-t-0 @4xl:border-l @4xl:pl-8 @4xl:*:first:pt-0`,children:[l,s.length>0?(0,K.jsx)(S9,{label:`Mentioned in`,count:s.length,children:(0,K.jsx)(`ul`,{className:`flex flex-col gap-2`,children:s.map(e=>(0,K.jsx)(VOi,{note:e,pagesById:_,onPageClick:i,showPage:!0,compact:!0},e.id))})}):null,u&&u.length>0?(0,K.jsx)(S9,{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:AOi[e.action]??e.action}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`min-w-0`,children:(0,K.jsxs)(Gw,{singleLine:!0,children:[(0,K.jsx)(Gw.Item,{className:`min-w-0`,children:(0,K.jsx)(x9,{label:e.provenance.author,children:(0,K.jsx)(`span`,{className:`truncate`,children:jOi(e.provenance.author)})})}),(0,K.jsx)(Gw.Item,{className:`shrink-0`,children:(0,K.jsx)(jA,{value:e.createdAt})})]})})]},e.id))})}):null]})]})]},e.id)}function UOi(e,t){return e.split(/(\s+|(?<=:))/).map(e=>e.length>t&&!/^\s+$/.test(e)?`${e.slice(0,t-1)}\u2026`:e).join(``)}function C9(){return typeof window<`u`&&!!window.matchMedia?.(`(prefers-reduced-motion: no-preference)`).matches}function WOi(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 GOi=.15,KOi={left:0,right:0};function qOi(e,t){return e-t.left-t.right>0?t:KOi}function JOi({bounds:e,width:t,height:n,ring:r,anchor:i,insets:a=KOi}){let o=qOi(t,a),s=r?GOi:nOi,c=t-o.left-o.right,l=JO(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 YOi=.05,XOi=3e3;function ZOi({bounds:e,nodes:t,width:n,height:r,legend:i,insets:a=KOi}){let o=qOi(n,a),s=(t,i)=>{let a=JO(e,n-t-o.right,r-i,GOi,1,YOi);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 w9=e=>e?700:0;function QOi(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 $Oi(e){let t=+this._x.call(null,e),n=+this._y.call(null,e);return eki(this.cover(t,n),t,n,e)}function eki(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 tki(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)eki(this,n[i],r[i],e[i]);return this}function nki(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 rki(){var e=[];return this.visit(function(t){if(!t.length)do e.push(t.data);while(t=t.next)}),e}function iki(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 T9(e,t,n,r,i){this.node=e,this.x0=t,this.y0=n,this.x1=r,this.y1=i}function aki(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 T9(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 T9(p[3],g,_,c,l),new T9(p[2],o,_,g,l),new T9(p[1],g,s,c,_),new T9(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 oki(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 ski(e){for(var t=0,n=e.length;t<n;++t)this.remove(e[t]);return this}function cki(){return this._root}function lki(){var e=0;return this.visit(function(t){if(!t.length)do++e;while(t=t.next)}),e}function uki(e){var t=[],n,r=this._root,i,a,o,s,c;for(r&&t.push(new T9(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 T9(i,l,u,s,c)),(i=r[2])&&t.push(new T9(i,a,u,l,c)),(i=r[1])&&t.push(new T9(i,l,o,s,u)),(i=r[0])&&t.push(new T9(i,a,o,l,u))}return this}function dki(e){var t=[],n=[],r;for(this._root&&t.push(new T9(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 T9(a,o,s,u,d)),(a=i[1])&&t.push(new T9(a,u,s,c,d)),(a=i[2])&&t.push(new T9(a,o,d,u,l)),(a=i[3])&&t.push(new T9(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 fki(e){return e[0]}function pki(e){return arguments.length?(this._x=e,this):this._x}function mki(e){return e[1]}function hki(e){return arguments.length?(this._y=e,this):this._y}function gki(e,t,n){var r=new _ki(t??fki,n??mki,NaN,NaN,NaN,NaN);return e==null?r:r.addAll(e)}function _ki(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 vki(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}var E9=gki.prototype=_ki.prototype;E9.copy=function(){var e=new _ki(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=vki(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]=vki(r));return e},E9.add=$Oi,E9.addAll=tki,E9.cover=nki,E9.data=rki,E9.extent=iki,E9.find=aki,E9.remove=oki,E9.removeAll=ski,E9.root=cki,E9.size=lki,E9.visit=uki,E9.visitAfter=dki,E9.x=pki,E9.y=hki;function yki(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 D9(e){return function(){return e}}function O9(e){return(e()-.5)*1e-6}function bki(e){return e.x+e.vx}function xki(e){return e.y+e.vy}function Ski(e){var t,n,r,i=1,a=1;typeof e!=`function`&&(e=D9(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=gki(t,bki,xki).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=O9(r),_+=h*h),g===0&&(g=O9(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:D9(+t),c(),o):e},o}function Cki(e){return e.index}function wki(e,t){var n=e.get(t);if(!n)throw Error(`node not found: `+t);return n}function Tki(e){var t=Cki,n=d,r,i=D9(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||O9(l),m=f.y+f.vy-d.y-d.vy||O9(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=wki(u,d.source)),typeof d.target!=`object`&&(d.target=wki(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:D9(+e),m(),f):n},f.distance=function(e){return arguments.length?(i=typeof e==`function`?e:D9(+e),h(),f):i},f}var Eki=1664525,Dki=1013904223,Oki=4294967296;function kki(){let e=1;return()=>(e=(Eki*e+Dki)%Oki)/Oki}function Aki(e){return e.x}function jki(e){return e.y}var Mki=10,Nki=Math.PI*(3-Math.sqrt(5));function Pki(e){var t,n=1,r=.001,i=1-r**(1/300),a=0,o=.6,s=new Map,c=Zst(d),l=gD(`tick`,`end`),u=kki();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=Mki*Math.sqrt(.5+t),a=t*Nki;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 Fki(){var e,t,n,r,i=D9(-30),a,o=1,s=1/0,c=.81;function l(n){var i,a=e.length,o=gki(e,Aki,jki).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=O9(n),m+=d*d),f===0&&(f=O9(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=O9(n),m+=d*d),f===0&&(f=O9(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:D9(+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 Iki(e){var t=D9(.1),n,r,i;typeof e!=`function`&&(e=D9(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:D9(+e),o(),a):t},a.x=function(t){return arguments.length?(e=typeof t==`function`?t:D9(+t),o(),a):e},a}function Lki(e){var t=D9(.1),n,r,i;typeof e!=`function`&&(e=D9(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:D9(+e),o(),a):t},a.y=function(t){return arguments.length?(e=typeof t==`function`?t:D9(+t),o(),a):e},a}var Rki=28,zki=300;function Bki(e,t,n={}){let r=n.ticks??zki,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??Rki,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}));Pki(i).force(`link`,Tki(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`,Fki().strength(e=>e.size<=24?-60:-700)).force(`collide`,Ski().radius(e=>e.size/2+e.padding).strength(1).iterations(3)).force(`center`,yki(0,0)).force(`x`,Iki(0).strength(.06)).force(`y`,Lki(0).strength(.08)).stop().tick(r),Vki(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 Vki(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 Hki(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 Uki(e){return`unplaced:${e}`}function Wki(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=Uki(e.principal),r.has(t)||r.set(t,Gki(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 Gki(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 Kki(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 qki(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 Jki=[`top`,`bottom`,`right`,`left`];function Yki(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 Xki(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 Zki(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 Qki(e){let t=e=>(e.right-e.left)*(e.bottom-e.top),n=`top`,r=1/0;for(let i of Jki){let a=Yki(i,e),o=(t(a)-Xki(a,e.bounds))*100;for(let t of e.obstacles)o+=Xki(a,t)*4;for(let t of e.lines)Zki(a,t.from,t.to)&&(o+=2e3);o<r&&(n=i,r=o)}return n}var $ki={left:0,right:0},eAi={"--knowledge-color":`var(--chart-blue)`,background:`color-mix(in oklab, var(--chart-blue) 16%, var(--card))`},tAi={"--knowledge-color":`var(--border-strong)`},nAi=`var(--muted-foreground)`,rAi={"--knowledge-color":nAi,background:nAi},iAi={stroke:`var(--foreground)`,strokeOpacity:.45,strokeDasharray:`4 4`,strokeWidth:1.25},aAi=`var(--chart-cyan)`,oAi={stroke:aAi,strokeWidth:2.25},sAi={type:MO.ArrowClosed,color:aAi,width:14,height:14},cAi=`var(--chart-blue)`,lAi=`var(--muted-foreground)`,uAi={type:MO.Arrow,color:lAi,width:12,height:12,strokeWidth:1.5},dAi=`var(--chart-purple)`,fAi={stroke:dAi,strokeWidth:1.75,strokeDasharray:`8 3 2 3`},pAi={type:MO.ArrowClosed,color:dAi,width:13,height:13},k9=`var(--chart-green)`,mAi={stroke:k9,strokeWidth:1.25},hAi={type:MO.ArrowClosed,color:k9,width:12,height:12},gAi={out:{stroke:k9},in:{stroke:`var(--chart-orange)`,strokeDasharray:`6 3`}},_Ai={out:hAi,in:{type:MO.ArrowClosed,color:`var(--chart-orange)`,width:12,height:12}},vAi={stroke:`var(--foreground)`,strokeOpacity:.2,strokeWidth:1},yAi={background:`var(--card)`,borderColor:`var(--chart-purple)`,borderStyle:`dashed`};function bAi(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 xAi=150,SAi=4e3,CAi=3;function wAi(e){let{left:t,top:n,right:r,bottom:i}=e.getBoundingClientRect();return{left:t,top:n,right:r,bottom:i}}function TAi(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 EAi={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 DAi({level:e}){return(0,K.jsx)(e===`scope`?na:Xt,{"aria-hidden":!0,"data-testid":`knowledge-level-icon-${e}`,className:`mr-1 inline-block size-3 align-text-bottom`})}function OAi({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=uk(e=>e.transform[2]),h=Math.min(Math.max(1/m,1),CAi),g=g9(t),_=v9(t),v=g?`Hover or click to load them`:_?`Click to show them`:null,y=!v&&t.childCount?`${h9(t)} ${t.childCount===1?`child`:`children`}`:null,b=t.isScope?t.displayLabel??`Scope`:`Page`,x=o&&(o.in>0||o.out>0)?_Z(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=wAi(e),i=wAi(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(wAi).filter(e=>e.right>e.left&&(e.left!==i.left||e.top!==i.top)&&(e.left!==r.left||e.top!==r.top));p(Qki({dot:r,tip:{width:a,height:o},gap:8,bounds:wAi(n),obstacles:s,lines:TAi(n)}))},[c,h]);let C=EAi[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)(Gw,{children:[_&&(0,K.jsx)(Gw.Item,{children:i}),(0,K.jsx)(Gw.Item,{children:v})]})})]}):(0,K.jsx)(M6n,{name:t.name,kind:b,pageRef:a,path:i,childCount:t.childCount?h9(t):void 0,links:o,notShown:s})]}):null,(0,K.jsx)(yk,{type:`target`,position:NO.Top,className:`!invisible`}),(0,K.jsx)(yk,{type:`source`,position:NO.Bottom,className:`!invisible`})]})}var kAi=96,AAi=.74;function jAi({data:e}){if(e.form===`dot`)return(0,K.jsx)(OAi,{data:e});let{page:t,size:n,selected:r,pinned:i,badge:a}=e,o=v9(t),s=t.isScope?t.displayLabel??`Scope`:`Page`,c=NAi(t),l=_9(t),u=n<kAi,d=Math.max(4,Math.floor(n*AAi/(u?6.5:7.5))),f=MAi(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)(x9,{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?yAi:e.far?rAi:t.isScope?eAi:tAi,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)(DAi,{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)(PAi,{text:UOi(b9(t),d)})})]})}),i?(0,K.jsx)(FAi,{size:n}):null,e.hiddenLinks&&(e.hiddenLinks.in>0||e.hiddenLinks.out>0)?(0,K.jsx)(x9,{label:_Z(e.hiddenLinks),children:(0,K.jsxs)(`span`,{"data-testid":`knowledge-hidden-links`,"aria-label":_Z(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:k9},children:[e.hiddenLinks.out,`→`]}):null]})}):null,a?(0,K.jsx)(x9,{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)(yk,{type:`target`,position:NO.Top,className:`!invisible`}),(0,K.jsx)(yk,{type:`source`,position:NO.Bottom,className:`!invisible`})]})}function MAi(e,t){let{page:n,links:r,notShown:i}=e;if(NAi(n))return`${t}: ${n.address}. Nothing written to it yet.`;if(_9(n))return`Show ${Math.min(12,n.childCount??12)} more of ${n.childCount??`the rest`}`;if(v9(n))return`${n.name}: click to show them`;if(n.isScope&&n.address){let e=b9(n);return e===n.address?`${t}: ${e}`:`${t}: ${e} (${n.address})`}return r&&r.in+r.out>0?`${n.name}: ${_Z(r,i)}`:n.name}function NAi(e){return e.id.startsWith(`unplaced:`)}function PAi({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 FAi({size:e}){let{badge:t,style:n}=bAi(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)(zo,{size:Math.round(t*.6),"aria-hidden":!0})})}function IAi(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 LAi({id:e,data:t,style:n,markerEnd:r}){if(!t)return null;let{x1:i,y1:a,x2:o,y2:s}=IAi(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)(xk,{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 RAi={rim:(0,G.memo)(LAi)},zAi={page:(0,G.memo)(jAi)};function BAi(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 VAi=`knowledge-circle inline-block size-3 shrink-0 rounded-full border-2`;function HAi({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)(Xi,{}),"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:VAi,style:{...eAi},"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)(na,{"aria-hidden":!0,className:`size-3 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)(Xt,{"aria-hidden":!0,className:`size-3 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:VAi,style:{...tAi},"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:VAi,style:{...tAi,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,JAi).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)(x9,{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>JAi?(0,K.jsx)(`li`,{className:`pl-0.5`,children:(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,children:[`+`,o.length-JAi,` 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:k9,strokeWidth:`1.5`}),(0,K.jsx)(`polygon`,{points:`11,1 16,4 11,7`,fill:k9})]}),(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:cAi,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`,...mAi}),(0,K.jsx)(`polygon`,{points:`11,1 16,4 11,7`,fill:k9})]}),(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`,...vAi,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`,...oAi}),(0,K.jsx)(`polygon`,{points:`9,1 15,4 9,7`,fill:aAi})]}),(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`,...iAi,strokeDasharray:`3 2`}),(0,K.jsx)(`polyline`,{points:`10,1 14,4 10,7`,fill:`none`,stroke:lAi,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:k9},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`,...fAi,strokeDasharray:`4 2 1 2`,strokeWidth:`1.5`}),(0,K.jsx)(`polygon`,{points:`11,1 16,4 11,7`,fill:dAi})]}),(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`,"aria-hidden":!0,children:(0,K.jsx)(zo,{size:8})}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Pinned`})]})]})]})}var UAi=4,WAi=`knowledge-neighbour`;function GAi(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 KAi=1.2,qAi=.8,JAi=4,YAi=40;function XAi(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),xAi),n=setTimeout(()=>i(!0),SAi);return()=>{clearTimeout(e),clearTimeout(n)}},[t,e.selectedPageId]),(0,K.jsxs)(Sk,{children:[(0,K.jsx)(ZAi,{...o}),s&&a?(0,K.jsx)(`p`,{role:`status`,"data-testid":`knowledge-graph-loading`,className:`text-ui-sm 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-muted-foreground shadow-overlay`,children:`Loading pages…`}):null]})}function ZAi({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=$ki,collapsibleLegend:y}){let{graphPages:b,allEdges:x}=(0,G.useMemo)(()=>{let n=Wki(e,r);return{graphPages:n.placeholders.length?[...e,...n.placeholders]:e,allEdges:[...Hki(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=GDi(b,i??a??null,c),t=tOi(b,e),n=qki(b,x);for(let t of n.nodes)if(e.form.get(t.id)===`dot`){let e=C.get(t.id),n=f&&!g9(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*KAi):t.data.size=Math.round(108*(e.linked.has(t.id)?qAi:1));let r=n.nodes.filter(t=>e.depth.get(t.id)===1&&e.form.get(t.id)===`full`),o=iOi(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=$Di(b,e,e=>s.get(e.id)??20,c),u=Bki(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`||g9(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??b9(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&&!g9(t)&&!_9(t)&&e.set(t.parentId,(e.get(t.parentId)??0)+1);return new Set(b.filter(t=>!v9(t)&&!_9(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>=YAi))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)?Kki(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:NO.Top,x:e.data.size/2,y:0,width:1,height:1},{type:`source`,position:NO.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)?h9(e.data.page):void 0,path:dOi(e.data.page,D),hiddenLinks:E.shape.form.get(e.id)===`full`?o?.get(e.id):void 0,ref:fOi(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?{...gAi[s],strokeWidth:r?2:1.5}:r?{stroke:cAi,strokeWidth:Math.min(1.5+(t.data?.count??1)*.5,4)}:c?oAi:i?fAi:a?mAi:o?vAi:iAi,markerEnd:s?_Ai[s]:c?sAi:r?{type:MO.ArrowClosed,color:cAi,width:14,height:14}:i?pAi:a?hAi:o?void 0:uAi}}),drawnEdgeStyles:e}},[E,F,_,L,O]),H=GAi(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:WAi}:{},...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,WAi].filter(Boolean).join(` `)}:e):H,[H,R]),U=(0,G.useMemo)(()=>new Map(e.map(e=>[e.id,e])),[e]),W=_k(),ne=(0,G.useRef)(null),re=z.length>0,ie=WOi(ee,C9()),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=BAi(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=JOi({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=ZOi({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=qOi(n,c),d=s.getViewport(),f=QOi(l.position.x*d.zoom+d.x-u.left,(l.width??0)*d.zoom,n-u.left-u.right),p=QOi(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(w9(C9()))},[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(w9(C9()))},[i,me,fe]);let be=e=>{if(g9(e)||v9(e)||_9(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)=>{NAi(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)>UAi||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)(HAi,{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)(Wmt,{nodes:ie,edges:te,nodeTypes:zAi,edgeTypes:RAi,onInit:()=>{he.current=!0,ge.current=Date.now()+XOi,_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)(rht,{variant:Ck.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)(fU,{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:w9(C9())}),children:(0,K.jsx)(ao,{})}),(0,K.jsx)(X,{size:`icon-sm`,tooltip:`Zoom in`,"aria-label":`Zoom in`,onClick:()=>void W.zoomIn({duration:w9(C9())}),children:(0,K.jsx)(Ho,{})}),(0,K.jsx)(X,{size:`icon-sm`,tooltip:`Fit view`,"aria-label":`Fit view`,onClick:()=>ue(w9(C9())),children:(0,K.jsx)(Ba,{})})]})})]}):(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 QAi(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 $Ai=1/3,eji=.1,tji=.7;function nji({pages:e,pinnedIds:t,selectedPageId:n,onSelect:r,initiallyExpanded:i,mayHaveChildren:a,onExpandedChange:o,loadMore:s,"aria-label":c=`Knowledge pages`}){let l=(0,G.useMemo)(()=>LDi(e),[e]),u=(0,G.useMemo)(()=>new Set(t),[t]),[d,f]=(0,G.useState)(()=>new Set(i??l.map(e=>e.page.id))),[p,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=zDi(e,n),r=[n,...t].join(`/`);_.current!==r&&(_.current=r,f(e=>t.every(t=>e.has(t))?e:new Set([...e,...t])))},[e,n]),(0,G.useEffect)(()=>{o?.(d)},[d,o]);let v=(0,G.useMemo)(()=>RDi(l,d).map(e=>!e.hasChildren&&a?.(e.page)?{...e,hasChildren:!0}:e),[l,d,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=QAi(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*eji&&i.bottom<=r.top+r.height*tji)return;e.style.scrollMarginTop=`${r.height*$Ai}px`}e.scrollIntoView?.({block:`start`,behavior:t&&C9()?`smooth`:`auto`}),e.style.scrollMarginTop=``}},[v,n]);let C=p&&v.some(e=>e.page.id===p)?p:v.find(e=>e.page.id===n)?.page.id??v[0]?.page.id,w=(e,t)=>f(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":c,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:m(`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-3.5`,"aria-hidden":!0,children:e.page.isScope&&b9(e.page)!==e.page.name?(0,K.jsx)(kOi,{page:e.page}):e.hasChildren?(0,K.jsx)(Ci,{}):(0,K.jsx)(oi,{})}),(0,K.jsx)(`span`,{className:m(`min-w-0 flex-1 truncate`,e.page.isScope&&`font-medium`),children:b9(e.page)}),e.page.childCount?(0,K.jsx)(`span`,{"data-testid":`knowledge-tree-count`,"aria-label":`${h9(e.page)} below`,className:`shrink-0 text-caption text-placeholder tabular-nums`,children:h9(e.page)}):null,u.has(e.page.id)?(0,K.jsx)(zo,{size:12,className:`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 rji=/^[0-9A-Z]{26}$/,iji=6e4,aji=e=>Date.now()-Date.parse(e.createdAt)<iji,oji=2,sji=40;function cji(e){return`${e.kind}\u0000${e.source}\u0000${e.target}`}function lji(e,t,n,r){let i=new Map;for(let t of e)t.source!==t.target&&!i.has(cji(t))&&i.set(cji(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(cji(e))),hidden:l,more:s}}function uji(e,t){return t?`page`:e===`tree`?`tree`:`graph`}var dji=296,fji=44;function pji(e,t){return e?t?dji:fji:0}var mji=392,hji=()=>[],gji=[],_ji=()=>[],vji=()=>({isPending:!1,isError:!1,error:null}),yji=150;function bji(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 xji=()=>({isPending:!1,isError:!1,error:null});function Sji(e){return!!e&&typeof e==`object`&&`status`in e&&e.status===404}function Cji(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 wji(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 Tji=[`w-32`,`w-24`,`w-40`,`w-28`,`w-36`,`w-20`];function Eji({label:e,rows:t}){return(0,K.jsx)(`div`,{role:`status`,"aria-label":e,className:`flex flex-col`,children:Tji.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)(dw,{className:`size-3.5 shrink-0`}),(0,K.jsx)(fw,{className:e})]},e))})}function Dji(){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)(fw,{className:`w-24`}),(0,K.jsx)(fw,{className:`w-full`}),(0,K.jsx)(fw,{className:`w-2/3`})]},e))})}function Oji({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)(fw,{line:`text-caption`,className:`w-28`}),e?null:(0,K.jsx)(fw,{line:`text-title`,className:`h-5 w-56`}),(0,K.jsx)(fw,{className:`w-72 max-w-full`}),(0,K.jsx)(fw,{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)(fw,{className:`w-full max-w-3xl`}),(0,K.jsx)(fw,{className:`w-5/6 max-w-2xl`}),(0,K.jsx)(fw,{className:`w-2/3 max-w-xl`})]})]})}function kji({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 Aji({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)(()=>Cji(r,a.data?.related??[]),[a.data,r]);if(a.isPending)return(0,K.jsx)(Dji,{});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)(VOi,{note:e,pagesById:c,onPageClick:i},e.id))}),l?o?(0,K.jsx)(Aji,{source:e,pageId:t,cursor:l,pagesById:r,onPageClick:i}):(0,K.jsx)(kji,{label:`Load more notes`,onClick:()=>s(!0)}):null]})}function jji({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)(S9,{label:`Pages`,children:(0,K.jsx)(Eji,{label:`Loading pages`,rows:3})});let c=s?.data?.nextCursor;return o.length===0&&!c?null:(0,K.jsxs)(S9,{label:`Pages`,children:[(0,K.jsx)(`div`,{className:`rounded-xl p-1 ${Wb}`,children:(0,K.jsx)(e8,{className:`rounded-lg bg-background p-1`,onSelect:n,children:(0,K.jsx)(Mji,{pages:o,useTreeLevels:e,onOpen:n})})}),c?(0,K.jsx)(kji,{onClick:()=>i(e=>[...e,c])}):null]})}function Mji({pages:e,useTreeLevels:t,onOpen:n}){return e.map(e=>e.childCount===0?(0,K.jsxs)(e8.File,{id:e.id,children:[(0,K.jsx)(e8.Icon,{className:`text-muted-foreground`,children:(0,K.jsx)(oi,{})}),(0,K.jsx)(Nji,{page:e})]},e.id):(0,K.jsx)(Pji,{page:e,useTreeLevels:t,onOpen:n},e.id))}function Nji({page:e}){return e.description?(0,K.jsx)(x9,{label:e.description,children:(0,K.jsx)(e8.Label,{children:e.name})}):(0,K.jsx)(e8.Label,{children:e.name})}function Pji({page:e,useTreeLevels:t,onOpen:n}){let[r,i]=(0,G.useState)(!1);return(0,K.jsxs)(e8.Folder,{id:e.id,open:r,onOpenChange:i,children:[(0,K.jsxs)(e8.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)(Ht,{})}),children:[(0,K.jsx)(e8.Icon,{className:`text-muted-foreground`,children:(0,K.jsx)(Ci,{})}),(0,K.jsx)(Nji,{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)(e8.FolderContent,{children:r?(0,K.jsx)(Fji,{parentId:e.id,useTreeLevels:t,onOpen:n}):null})]})}function Fji({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)(Eji,{label:`Loading pages`,rows:2})}):a[0]?.isError?(0,K.jsx)(Iji,{children:`Couldn’t load the pages under this one.`}):o.length===0&&!s?(0,K.jsx)(Iji,{children:`No pages under this one.`}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Mji,{pages:o,useTreeLevels:t,onOpen:n}),s?(0,K.jsx)(`li`,{role:`none`,className:`pl-9`,children:(0,K.jsx)(kji,{onClick:()=>i(e=>[...e,s])})}):null]})}function Iji({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 Lji({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:TOi(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)(Vc,{size:14,"aria-hidden":!0})})]}),(0,K.jsx)(`div`,{className:`min-h-0 overflow-y-auto`,children:a.isPending?(0,K.jsx)(Dji,{}):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)(VOi,{note:e,pagesById:Cji(n,a.data?[...a.data.related,...a.data.ancestors,a.data.page]:[]),onPageClick:e=>r(e.id),compact:!0},e.id))})})]})}function Rji({source:e,pageId:t,pagesById:n,onSelect:r,highlightMentionOf:i,compact:a}){let o=e.usePage(t),s=(e.useActivity??xji)(t),[c,l]=(0,G.useState)(null),u=(0,G.useMemo)(()=>o.data?Cji(n,[...o.data.ancestors,...o.data.related]):n,[o.data,n]);if(o.isPending)return(0,K.jsx)(Oji,{compact:a});if(o.isError||!o.data){let e=Sji(o.error);return(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:e?`Page not found`:`Failed to load the page`,descriptionSlot:e?`It may have been deleted or merged.`:o.error?.message??``})}let d=e=>r(e.id),f=o.data.notesNextCursor;return(0,K.jsx)(HOi,{compact:a,page:o.data.page,notes:o.data.notes,pin:o.data.pin??void 0,pagesById:u,onPageClick:d,highlightMentionOf:i,ancestors:o.data.ancestors,mentionedBy:o.data.mentionedBy,activity:s.data?.events,childPages:e.useTreeLevels?(0,K.jsx)(jji,{useTreeLevels:e.useTreeLevels,parentId:t,onOpen:r},t):void 0,notesMore:f?c?.pageId===t?(0,K.jsx)(Aji,{source:e,pageId:t,cursor:f,pagesById:u,onPageClick:d}):(0,K.jsx)(kji,{label:`Load more notes`,onClick:()=>l({pageId:t})}):void 0})}function zji({source:e,onSelect:t}){let[n,r]=(0,G.useState)(``),i=e.useSearch(n),a=n.trim().length>=oji?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)(RU,{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 ${Gb}`,children:(0,K.jsx)(lw,{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:m(BE,`whitespace-normal`),onClick:()=>{t(e.id),r(``)},children:(0,K.jsx)(`div`,{className:`line-clamp-2`,children:e.name})})},e.id))})})}):null]})}function Bji(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 Vji(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??hji)(c),{pages:u,loaded:d,failed:f,nextCursor:p}=EOi((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]),Bji),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?!aji(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 Hji({graph:e,source:t,selectedPageId:n,onSelect:r,view:i,onViewChange:a,toolbarEnd:o,flush:s=!1}){let c=fE(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=Vji(t,e,u.data,f),E=(0,G.useMemo)(()=>d?cOi({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??vji)(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=mOi(t.values()),i=e.page.id,a=e.notes.flatMap(e=>e.mentions).filter(e=>e&&e!==i),o=bOi(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(`:`)&&!rji.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,sji-_(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??gji,j=(t.useLinkedPages??_ji)(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`),...xOi(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)(()=>lji(V,L,n,b),[V,L,n,b]),ee=H.edges,te=(0,G.useMemo)(()=>I.pages.filter(e=>!g9(e)&&!_9(e)&&!v9(e)).map(e=>e.id).sort(),[I.pages]),U=(t.useLinkCounts??vji)(l===`graph`?te:[]),W=(0,G.useMemo)(()=>U.data?new Map(Object.entries(U.data)):void 0,[U.data]),ne=(0,G.useMemo)(()=>W?bji(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),yji):ie(null)},[]);(0,G.useEffect)(()=>()=>clearTimeout(ae.current),[]);let se=(t.usePageLinks??vji)(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&&!wji([...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=wji(t.useTreeLevels?w.pages:e.pages,Re?z:null),Be=(0,G.useMemo)(()=>wji(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)(xa,{}),narrowOnly:!0},{value:`graph`,label:`Graph`,icon:(0,K.jsx)(go,{}),narrowOnly:!1},{value:`page`,label:`Page`,icon:(0,K.jsx)(oi,{}),narrowOnly:!1}],Ue=uji(l,Te),We=he&&!Te&&n&&!Sji(u.error)&&n?n:void 0;We&&We!==ve&&ye(We);let Ge=We??ve,Ke={left:pji(he,ge),right:We?mji:0},qe={"--knowledge-tree-inset":`${Ke.left}px`,"--knowledge-tree-drawer-inset":`${he&&ge?dji:0}px`,"--knowledge-drawer-inset":`${Ke.right}px`},Je=()=>be.current?.querySelector(`[role="tab"][aria-selected="true"]`)?.focus(),Ye=e=>{e&&Ce.current&&(Ce.current=!1,Je())},Xe=e=>{(0,Xc.flushSync)(()=>_e(e)),(e?Se:xe).current?.focus()},Ze=he&&!ge,Qe=he?(0,K.jsxs)(m$.Header,{children:[(0,K.jsx)(m$.Heading,{children:`Pages`}),(0,K.jsx)(m$.HeaderActions,{children:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`Hide pages`,"aria-label":`Hide pages`,ref:Se,onClick:()=>Xe(!1),children:(0,K.jsx)(Qee,{})})})]}):null,$e=(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)(kOi,{page:Re,className:`size-3.5`}),(0,K.jsx)(x9,{label:Re.address??Re.name,children:(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`ink`,className:`truncate`,children:b9(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)(Eji,{label:`Loading pages`,rows:6})}):(0,K.jsx)(nji,{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`)})]}),et=Ge?L.get(Ge)??w.pages.find(e=>e.id===Ge):void 0;return(0,K.jsx)(SOi.Provider,{value:N,children:(0,K.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col ${s?``:`gap-2`}`,children:[(0,K.jsxs)(jq,{className:s?`shrink-0 border-b border-surface-rim px-3 py-2`:void 0,children:[(0,K.jsxs)(jq.Start,{children:[(0,K.jsx)(CA,{ref:be,value:Ue,defaultTab:Ue,onValueChange:e=>a(e),"aria-label":`View`,children:(0,K.jsx)(SA,{variant:`pill-ghost`,size:`sm`,children:He.map(e=>(0,K.jsxs)(wA,{value:e.value,disabled:e.value===`page`&&!n,className:e.narrowOnly?`lg:hidden`:void 0,children:[(0,K.jsx)(TC,{size:`xs`,children:e.icon}),(0,K.jsx)(T,{variant:`caption`,className:`text-inherit`,children:e.label})]},e.value))})}),(0,K.jsx)(zji,{source:t,onSelect:Le})]}),o?(0,K.jsx)(jq.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&&Sji(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:qe,className:`relative flex min-h-0 flex-1 flex-col gap-3 lg:flex-row`,children:[he?(0,K.jsx)(`div`,{inert:Ze,"aria-hidden":Ze||void 0,"data-state":Ze?`closed`:`open`,className:`absolute inset-y-2 left-2 z-10 flex w-72 transition duration-slow ease-out-custom motion-reduce:transition-none ${Ze?`pointer-events-none -translate-x-4 opacity-0`:`translate-x-0 opacity-100`}`,children:(0,K.jsxs)(m$,{variant:`inline`,title:`Pages`,className:`shadow-overlay`,children:[Qe,$e]})}):(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:$e}),he?(0,K.jsx)(X,{tooltip:`Show pages`,"aria-label":`Show pages`,size:`icon-sm`,inert:!Ze,"aria-hidden":!Ze||void 0,className:`absolute top-3 left-3 z-10 shadow-overlay transition-opacity duration-slow ease-out-custom motion-reduce:transition-none ${Ze?`opacity-100`:`pointer-events-none opacity-0`}`,ref:xe,onClick:()=>Xe(!0),children:(0,K.jsx)($ee,{})}):null,Te?(0,K.jsx)(`section`,{ref:Ye,"aria-label":`Selected page`,className:`flex min-h-0 min-w-0 flex-1 flex-col ${he?`bg-background p-2 pl-[calc(var(--knowledge-tree-inset)+0.5rem)] transition-[padding] duration-slow ease-out-custom motion-reduce:transition-none ${s?``:`rounded-xl border border-border`}`:`overflow-hidden rounded-lg border border-border bg-card`}`,children:(0,K.jsx)(`div`,{className:he?`flex min-h-0 flex-1 flex-col overflow-hidden rounded-studio-frame ${Kb}`:`contents`,children:(0,K.jsx)(Rji,{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-background lg:block lg:h-full ${s?``:`rounded-xl border border-border`} ${l===`graph`?`block`:`hidden`}`,"data-testid":`knowledge-graph-container`,children:[me?(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)(fU,{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)(Rt,{})}),(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)(la,{})}),(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)(Gi,{})})]})}):null,me?(0,K.jsx)(XAi,{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:Ke,collapsibleLegend:he,showCounts:S,onPreview:e=>{g9(e)&&e.parentId&&R(e.parentId)},onSelect:e=>{if(g9(e))return e.parentId?R(e.parentId):void 0;if(_9(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(v9(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:!We,"aria-hidden":!We||void 0,"data-state":We?`open`:`closed`,onTransitionEnd:e=>{!We&&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 ${We?`translate-x-0 opacity-100`:`pointer-events-none translate-x-4 opacity-0`}`,children:Ge?(0,K.jsxs)(m$,{variant:`inline`,title:`Page details`,className:`shadow-overlay`,children:[(0,K.jsxs)(m$.Header,{children:[(0,K.jsx)(m$.Heading,{className:`min-w-0 flex-1 shrink`,children:(0,K.jsx)(`span`,{className:`truncate`,children:et?.name??`Page`})}),(0,K.jsxs)(m$.HeaderActions,{children:[(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`Open page`,"aria-label":`Open page`,onClick:()=>{Ce.current=!0,Me(Ge)},children:(0,K.jsx)(Cte,{})}),(0,K.jsx)(m$.CloseButton,{icon:`x`,label:`Close page details`,tooltip:`Close`,onClick:()=>{Je(),r(null)}})]})]}),(0,K.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden`,children:(0,K.jsx)(Rji,{source:t,pageId:Ge,pagesById:L,onSelect:Le,highlightMentionOf:we,compact:!0})})]}):null}):null,le&&me?(0,K.jsx)(Lji,{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 Uji=2,Wji=5e3,Gji=6e4,Kji=5e3,qji=150,A9=e=>e?Gji:Wji,Jji=e=>e instanceof Ym&&(e.status>=400&&e.status<500||e.status===501);function Yji(e,t){return new Promise(n=>{let r=setTimeout(n,e);t.addEventListener(`abort`,()=>(clearTimeout(r),n()),{once:!0})})}function Xji(e){return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)}var Zji=()=>document.visibilityState!==`hidden`;function Qji(e){let t=Y(),n=dy(),[r,i]=(0,G.useState)(!1),a=(0,G.useSyncExternalStore)(Xji,Zji,()=>!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]}),qji)};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(Jji(e)){i(!1);return}}if(r.signal.aborted)return;i(!1),await Yji(Kji,r.signal)}})(),()=>{r.abort(),clearTimeout(s),i(!1)}},[t,n,e,a]),r}function $ji(){let e=Y();return Ey({queryKey:[`knowledge`,`instances`],queryFn:async()=>(await e.listKnowledge()).instances})}function eMi(e,t){let n=Y();return Ey({queryKey:[`knowledge`,e,`graph`],queryFn:e?async()=>n.getKnowledge(e).graph():yy,refetchInterval:A9(t)})}function tMi(e,t,n,r){let i=Y();return Ey({queryKey:[`knowledge`,e,`page`,n,r??null],queryFn:e&&n?async()=>i.getKnowledge(e).page(n,{noteCursor:r}):yy,refetchInterval:!r&&A9(t)})}function nMi(e,t){let n=Y();return Ty({queries:t.map(t=>({queryKey:[`knowledge`,e,`page`,t,null],queryFn:e?async()=>n.getKnowledge(e).page(t):yy,retry:(e,t)=>!(t&&`status`in t&&t.status===404)&&e<2,staleTime:3e4}))})}function rMi(e,t,n){let r=Y();return Ty({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}):yy,refetchInterval:!n.cursor&&A9(t)}))})}var iMi=200,aMi=(e,t)=>!Jji(t)&&e<2;function oMi(e,t,n){let r=Y();return Ey({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+=iMi)i.push(n.slice(e,e+iMi));let a=await Promise.all(i.map(e=>t.linkCounts(e)));return Object.assign({},...a.map(e=>e.counts))}:yy,placeholderData:vy,retry:aMi,refetchInterval:A9(t)})}function sMi(e,t){let n=Y();return Ey({queryKey:[`knowledge`,e,`page-links`,t],queryFn:e&&t?async()=>n.getKnowledge(e).pageLinks(t):yy,staleTime:3e4,retry:aMi})}function cMi(e,t,n){let r=Y();return Ey({queryKey:[`knowledge`,e,`activity`,n],queryFn:e?async()=>r.getKnowledge(e).activity({pageId:n}):yy,refetchInterval:A9(t)})}function lMi(e,t){let n=Y(),r=t.trim();return Ey({queryKey:[`knowledge`,e,`search`,r],queryFn:e&&r.length>=Uji?async()=>n.getKnowledge(e).search(r):yy,placeholderData:vy})}var uMi=[sF(`/knowledge`)];function j9({children:e}){return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:uMi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Knowledge`}),e]})}function dMi({knowledgeKey:e,live:t,graph:n}){let[r,i]=Hb(),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)=>tMi(e,t,n,r),useSearch:t=>lMi(e,t),useTreeLevels:n=>rMi(e,t,n),useLinkCounts:n=>oMi(e,t,n),usePageLinks:t=>sMi(e,t),useLinkedPages:t=>nMi(e,t),useActivity:n=>cMi(e,t,n)}),[e,t]),l=tMi(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)(Hji,{graph:n,source:c,selectedPageId:a,onSelect:e=>d(`page`,e),view:s,onViewChange:e=>d(`view`,e)})}function fMi(){let[e,t]=Hb(),n=$ji(),r=e.get(`instance`)??n.data?.[0]?.key,i=Qji(r),a=eMi(r,i),o=n.error??a.error;return o&&JP(o)?(0,K.jsx)(j9,{children:(0,K.jsx)(jU,{variant:`fill`})}):o&&YP(o)?(0,K.jsx)(j9,{children:(0,K.jsx)(AU,{variant:`fill`,resource:`knowledge`})}):n.error&&!n.data&&XP(n.error)?(0,K.jsx)(j9,{children:(0,K.jsx)(RC,{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)(j9,{children:(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load Knowledge`,descriptionSlot:n.error.message})}):n.data&&n.data.length===0?(0,K.jsx)(j9,{children:(0,K.jsx)(RC,{variant:`fill`,titleSlot:`No Knowledge instances`,descriptionSlot:`Register one on your Mastra instance with the knowledge option to browse it here.`})}):(0,K.jsx)(j9,{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)(RC,{variant:`fill`,titleSlot:`No pages yet`,descriptionSlot:`Agents add pages and notes to Knowledge as they run. They will appear here.`}):(0,K.jsx)(dMi,{knowledgeKey:r,live:i,graph:a.data}):(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load Knowledge`,descriptionSlot:a.error?.message})]})})}function pMi({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)(EQ,{className:`h-10 w-10`}),(0,K.jsx)(T,{as:`h1`,variant:`heading`,tone:`ink`,children:e})]}),t,n,r]})}function mMi({redirectUri:e,onSuccess:t,initialMode:n=`signin`,errorMessage:r}){let{data:i,isLoading:a}=jy(),{mutate:o,isPending:s,error:c}=eHe(),{mutate:l,isPending:u,error:d}=nHe(),{mutate:f,isPending:p}=rHe(),[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=DQ(`/`)},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)(Aa,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}),(0,K.jsx)(T,{tone:`muted`,children:S.description})]}):null;return(0,K.jsxs)(pMi,{title:O?`Sign in to Mastra Studio`:`Create your account`,description:F,errorBanner:r?(0,K.jsx)(`div`,{role:`alert`,children:(0,K.jsx)(EA,{variant:`destructive`,children:r})}):null,children:[w&&(0,K.jsxs)(uU,{onSubmit:M,children:[!O&&(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{children:`Name`}),(0,K.jsx)(ZM,{name:`name`,type:`text`,autoComplete:`name`,value:g,onChange:e=>_(e.target.value),placeholder:`Your name`,variant:`default`,size:`lg`})]}),(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{required:!0,children:`Email`}),(0,K.jsx)(ZM,{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)(gA,{})]}),(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{required:!0,children:`Password`}),(0,K.jsx)(ZM,{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)(gA,{})]}),A?(0,K.jsx)(`div`,{role:`alert`,children:(0,K.jsx)(EA,{variant:`destructive`,children:A.message})}):null,(0,K.jsx)(X,{icon:(0,K.jsx)(Ma,{}),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 hMi(){let[e]=Hb(),t=kb(),n=e.get(`redirect`)||`/`,r=e.get(`mode`)===`signup`?`signup`:`signin`,i=e.get(`error_description`)||e.get(`error`)||null;return(0,K.jsx)(mMi,{redirectUri:n,onSuccess:()=>{n.startsWith(`http`)?window.location.href=n:t(n,{replace:!0})},initialMode:r,errorMessage:i})}function gMi({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)(Vc,{}),children:`Clear`}),a&&(0,K.jsxs)(mD,{children:[(0,K.jsx)(mD.Trigger,{asChild:!0,children:(0,K.jsx)(X,{disabled:e,size:`icon-md`,"aria-label":`More filter actions`,children:(0,K.jsx)(Ar,{})})}),(0,K.jsxs)(mD.Content,{align:`end`,children:[n&&(0,K.jsxs)(mD.Item,{onSelect:()=>n(),children:[(0,K.jsx)(Vc,{}),`Remove all filters`]}),n&&(r||i)&&(0,K.jsx)(mD.Separator,{}),r&&(0,K.jsxs)(mD.Item,{onSelect:()=>r(),children:[(0,K.jsx)(ds,{}),`Save filters for next time`]}),i&&(0,K.jsxs)(mD.Item,{onSelect:()=>i(),children:[(0,K.jsx)(xc,{}),`Remove saved filters`]})]})]})]})}var _Mi=m(BE,`min-w-0`);function vMi({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:_Mi,onClick:r,children:[(0,K.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:n}),t&&(0,K.jsx)(`span`,{className:HE,children:(0,K.jsx)(Bn,{})})]})}function yMi({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]),c=typeof s?.value==`string`?s.value:e.multi?void 0:e.defaultValue,l=(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:KE.container,children:[(0,K.jsx)(gs,{className:KE.icon}),(0,K.jsx)(`input`,{type:`text`,value:r,onChange:e=>i(e.target.value),placeholder:`Search ${e.label.toLowerCase()}`,className:KE.input,...YA,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:m(pnt,`m-1`),children:[(0,K.jsx)(Zc,{size:`sm`,className:`size-3 text-muted-foreground`}),`Loading options…`]}):o.length===0?(0,K.jsx)(`div`,{className:m(pnt,`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=l.includes(t.value);return(0,K.jsx)(vMi,{role:`checkbox`,checked:r,label:t.label,onClick:()=>n(e.id,r?l.filter(e=>e!==t.value):[...l,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)(vMi,{role:`radio`,checked:c===t.value,label:t.label,onClick:()=>n(e.id,t.value)},t.value)),!e.omitAnyOption&&(0,K.jsx)(vMi,{role:`radio`,checked:c===`Any`,label:`Any`,onClick:()=>n(e.id,`Any`)})]})})]})}function bMi(e){return Array.isArray(e)?e.length===0?`Any`:e.join(`, `):e}var xMi=`This filter is set by the current context and cannot be removed here.`;function SMi(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:bMi(t)}function CMi({field:e,value:t,tooltipContent:n}){let r=SMi(e,t),i=`${e.label} filter is locked by context`;return(0,K.jsx)(bC,{delayDuration:150,children:(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{asChild:!0,children:(0,K.jsxs)(fU,{"data-locked-field-id":e.id,"data-property-filter-pill":`locked`,tabIndex:0,"aria-label":i,children:[(0,K.jsx)(pU,{children:e.label}),(0,K.jsx)(pU,{children:`is`}),(0,K.jsx)(pU,{children:r}),(0,K.jsx)(pU,{children:(0,K.jsx)(Aa,{})})]})}),(0,K.jsx)(CC,{children:n})]})})}function wMi({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)(fU,{children:[(0,K.jsx)(pU,{children:e.label}),(0,K.jsx)(pU,{children:`is`}),(0,K.jsx)(ZM,{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)(Vc,{})})]})}function TMi({field:e,token:t,tokens:n,onChange:r,onRemove:i,disabled:a}){let[o,s]=(0,G.useState)(!1);return(0,K.jsxs)(fU,{children:[(0,K.jsx)(pU,{children:e.label}),(0,K.jsx)(pU,{children:`is`}),(0,K.jsxs)($M,{open:o,onOpenChange:s,children:[(0,K.jsx)(eN,{asChild:!0,children:(0,K.jsx)(X,{type:`button`,disabled:a,children:bMi(t.value)})}),(0,K.jsx)(tN,{align:`start`,sideOffset:4,className:`w-64 p-0`,"data-pick-multi-panel":!0,children:(0,K.jsx)(yMi,{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)(Vc,{})})]})}function EMi({fields:e,tokens:t,onTokensChange:n,disabled:r,autoFocusFieldId:i,lockedFieldIds:a,lockedTooltipContent:o=xMi}){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)(CMi,{field:u,value:n.value,tooltipContent:o},`${n.fieldId}-${a}`):u.kind===`text`&&!Array.isArray(n.value)?(0,K.jsx)(wMi,{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)(TMi,{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)(fU,{children:[(0,K.jsx)(pU,{children:u.label}),(0,K.jsx)(pU,{children:`is`}),(0,K.jsx)(pU,{children:bMi(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)(Vc,{})})]},`${n.fieldId}-${a}`):null})})}var DMi=(0,G.forwardRef)((e,t)=>(0,K.jsx)(`button`,{type:`button`,role:`menuitem`,"data-filter-item":``,ref:t,...e}));DMi.displayName=`FilterMenuButton`;function OMi({fields:e,tokens:t,onTokensChange:n,label:r=`Add filter`,disabled:i,size:a,onStartTextFilter:o,hiddenFieldIds:s}){let c=(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]),[l,u]=(0,G.useState)(!1),[d,f]=(0,G.useState)(),[p,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)(()=>{l||y(void 0)},[l]);let C=(0,G.useMemo)(()=>c.find(e=>e.id===d),[c,d]),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)(()=>{f(void 0),h([]),_(void 0)},[]);(0,G.useEffect)(()=>{l||E()},[l,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.`):p.length===0?_(`Choose at least one ${C.label.toLowerCase()} value.`):(n([...t,{fieldId:C.id,value:p}]),u(!1)):_(`Choose a property first.`)},[p,n,C,w,t]);return(0,K.jsxs)($M,{open:l,onOpenChange:u,children:[(0,K.jsx)(eN,{asChild:!0,children:(0,K.jsx)(X,{size:a,disabled:i,icon:(0,K.jsx)(ha,{}),children:r})}),(0,K.jsx)(tN,{align:`start`,sideOffset:4,className:m(`w-64`,C?`p-3`:`p-1`),initialFocus:!1,finalFocus:()=>!b.current||(b.current=!1,!1),children:(0,K.jsxs)(`div`,{className:m(`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:m(`text-muted-foreground hover:text-foreground`,`transition-[color] duration-fast ease-out-custom motion-reduce:transition-none`),onClick:E,children:(0,K.jsx)(Rt,{className:`size-4`})}),(0,K.jsx)(Ti,{className:`size-4 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:c.length>0?c.map(e=>{let r=w.has(e.id);return e.kind===`pick-multi`?(0,K.jsx)(kMi,{field:e,tokens:t,onChange:D,open:v===e.id,onToggle:x,onClose:S},e.id):(0,K.jsxs)(DMi,{className:m(BE,`group`),disabled:r,onClick:()=>{_(void 0),e.kind===`text`?(n([...t,{fieldId:e.id,value:``}]),o?.(e.id),b.current=!0,u(!1)):f(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:m(VE,`text-muted-foreground opacity-0 group-hover:opacity-100 group-focus:opacity-100`),children:(0,K.jsx)(Ho,{})})]},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)(fA,{invalid:!!g,children:[(0,K.jsx)(TP,{multiple:!0,options:C.options??[],value:p,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)(gA,{children:g})]}),C&&(0,K.jsxs)(`div`,{className:`flex items-center justify-end gap-2`,children:[(0,K.jsx)(X,{icon:(0,K.jsx)(Vc,{}),variant:`ghost`,size:`md`,onClick:()=>u(!1),children:`Cancel`}),(0,K.jsx)(X,{icon:(0,K.jsx)(ha,{}),size:`md`,onClick:O,children:`Add filter`})]})]})})]})}function kMi({field:e,tokens:t,onChange:n,open:r,onToggle:i,onClose:a}){let o=(0,G.useRef)(null);return(0,K.jsxs)($M,{open:r,onOpenChange:t=>{t?i(e.id):a()},children:[(0,K.jsx)(eN,{asChild:!0,children:(0,K.jsxs)(DMi,{className:BE,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)(c,{className:`text-muted-foreground`}),(0,K.jsx)(`span`,{className:`truncate`,children:e.label}),!r&&(0,K.jsx)(`span`,{className:m(VE,`text-muted-foreground`),children:(0,K.jsx)(c,{})})]})}),(0,K.jsx)(tN,{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)(yMi,{field:e,tokens:t,onChange:n})})]})}function AMi({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:i,onNext:a,depth:o}){let s=e?Iw(e.timestamp)??``:``;return(0,K.jsx)(m$,{open:!!e,onClose:t,title:e?`Log ${s}`:`Log`,depth:o,children:e&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(m$.Header,{children:[(0,K.jsx)(m$.CloseButton,{onClick:t}),(0,K.jsx)(m$.Heading,{children:`Log`}),(0,K.jsx)(m$.Metadata,{children:(0,K.jsx)(m$.Meta,{tooltip:s,children:s})}),(0,K.jsx)(m$.HeaderActions,{children:(0,K.jsx)(m$.NextPrevNav,{onPrevious:i,onNext:a,previousLabel:`Go to previous log`,nextLabel:`Go to next log`})})]}),(0,K.jsx)(m$.Content,{children:(0,K.jsxs)(`div`,{className:`grid gap-6 p-2`,children:[(0,K.jsxs)(b3,{children:[e.entityType&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(b3.Key,{children:`Entity Type`}),(0,K.jsx)(b3.Value,{children:e.entityType})]}),e.entityName&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(b3.Key,{children:`Entity Name`}),(0,K.jsx)(b3.Value,{children:e.entityName})]}),e.serviceName&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(b3.Key,{children:`Service`}),(0,K.jsx)(b3.Value,{children:e.serviceName})]}),e.environment&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(b3.Key,{children:`Environment`}),(0,K.jsx)(b3.Value,{children:e.environment})]}),e.source&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(b3.Key,{children:`Source`}),(0,K.jsx)(b3.Value,{children:e.source})]}),e.metadata&&Object.entries(e.metadata).map(([e,t])=>(0,K.jsxs)(G.Fragment,{children:[(0,K.jsx)(b3.Key,{children:e}),(0,K.jsx)(b3.Value,{children:String(t)})]},e))]}),(0,K.jsx)(m$.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)(fU,{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)(Ht,{}),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)(jw,{content:e.traceId,tooltip:`Copy trace ID to clipboard`})]}),e.spanId&&(0,K.jsxs)(fU,{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)(Ht,{}),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)(jw,{content:e.spanId,tooltip:`Copy span ID to clipboard`})]})]}),e.data&&Object.keys(e.data).length>0&&(0,K.jsx)(m$.CodeSection,{title:`Data`,codeStr:JSON.stringify(e.data,null,2)})]})})]})})}function jMi({error:e,resource:t,errorTitle:n}){if(JP(e))return(0,K.jsx)(jU,{});if(YP(e))return(0,K.jsx)(AU,{resource:t});if(QP(e))return(0,K.jsx)(RC,{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(ZP(e,`logs`))return(0,K.jsx)(RC,{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)(RC,{tone:`error`,titleSlot:n,descriptionSlot:r??`Unknown error`})}var MMi={debug:`neutral`,info:`info`,warn:`warning`,error:`destructive`,fatal:`destructive`};function NMi({level:e}){return(0,K.jsx)(_U,{children:(0,K.jsx)(bw,{variant:MMi[e],children:e})})}function PMi({entityType:e,className:t}){let n=m(`size-3.5 shrink-0 text-placeholder`,t);switch(e.toLowerCase()){case`agent`:return(0,K.jsx)(tF,{className:n,"aria-hidden":!0});case`workflow`:case`workflow_run`:return(0,K.jsx)(rP,{className:n,"aria-hidden":!0});case`tool`:return(0,K.jsx)(aF,{className:n,"aria-hidden":!0});default:return null}}function FMi({entityType:e,entityName:t}){return(0,K.jsxs)(_U,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(PMi,{entityType:e??``}),t?(0,K.jsx)(T,{as:`span`,variant:`body-sm`,className:`min-w-0 truncate`,children:t}):`-`]})}function IMi({message:e}){return(0,K.jsx)(_U,{className:`min-w-0 truncate font-mono text-body-sm text-muted-foreground`,children:e})}function LMi({data:e}){if(!e||Object.keys(e).length===0)return(0,K.jsx)(_U,{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)(bU,{font:`mono`,children:t})}var M9=Object.assign(wU,{Top:kU,TopCell:EU,SortableTopCell:OU,TopCellWithTooltip:DU,TopCellSmart:Pyn,RowWrapper:kyn,RowButton:TU,RowLink:Dyn,Spacer:Byn,NoMatch:SU,DateCell:Yvn,TimeCell:Zvn,LevelCell:NMi,EntityCell:FMi,MessageCell:IMi,DataCell:LMi,NextPageLoading:xU}),RMi=`6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)`,zMi=36,BMi=8;function VMi({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=Pti({count:e.length,getScrollElement:()=>u.current,estimateSize:()=>zMi,overscan:BMi}),{getRowProps:f}=_Q({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)(NU,{columns:RMi,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)(M9,{columns:RMi,scrollRef:u,className:`min-w-0`,fit:`container`,children:[(0,K.jsxs)(M9.Top,{children:[l?(0,K.jsx)(M9.SortableTopCell,{sortKey:`timestamp`,sort:c,onSortChange:l,children:`Date`}):(0,K.jsx)(M9.TopCell,{children:`Date`}),(0,K.jsx)(M9.TopCell,{children:`Time`}),(0,K.jsx)(M9.TopCell,{children:`Level`}),(0,K.jsx)(M9.TopCell,{children:`Entity`}),(0,K.jsx)(M9.TopCell,{children:`Message`}),(0,K.jsx)(M9.TopCell,{children:`Data`})]}),e.length===0?(0,K.jsx)(M9.NoMatch,{message:`No logs match your search`}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(M9.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)(M9.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)(M9.DateCell,{timestamp:n.timestamp}),(0,K.jsx)(M9.TimeCell,{timestamp:n.timestamp}),(0,K.jsx)(M9.LevelCell,{level:n.level}),(0,K.jsx)(M9.EntityCell,{entityType:n.entityType,entityName:n.entityName}),(0,K.jsx)(M9.MessageCell,{message:n.message}),(0,K.jsx)(M9.DataCell,{data:n.data})]},r)}),(0,K.jsx)(M9.Spacer,{height:_})]}),(0,K.jsx)(M9.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:i})]})}function HMi({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:i,filterFields:a,filterTokens:o,onFilterTokensChange:s,autoFocusFilterFieldId:c}){let l=o.length>0,u=o.some(e=>UMi(e,a));return l?(0,K.jsxs)(`div`,{className:m(`grid grid-cols-[1fr_auto] items-start gap-3`),children:[(0,K.jsx)(EMi,{fields:a,tokens:o,onTokensChange:s,disabled:i,autoFocusFieldId:c}),l&&(0,K.jsx)(gMi,{disabled:i,onClear:u?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]}):null}function UMi(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 WMi={"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`},GMi=`Pick a wider range or lower the logging level. Verbose entries (debug, info) may be filtered out.`;function KMi({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!==`all`&&e!==`custom`?{title:`No logs for ${WMi[e]}`,description:GMi}:t&&n?{title:`No logs between ${Fw(t,`date-time`)} and ${Fw(n,`date-time`)}`,description:GMi}:t?{title:`No logs since ${Fw(t,`date-time`)}`,description:GMi}:{title:`No logs yet`,description:`Logs will appear here once agents, workflows, or tools are executed.`}}var qMi=({datePreset:e,dateFrom:t,dateTo:n}={})=>{let{title:r,description:i}=KMi({datePreset:e,dateFrom:t,dateTo:n});return(0,K.jsx)(RC,{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)(Br,{}),children:`Logging documentation`}),variant:`fill`})},JMi=`Filters setting for Logs saved`,YMi=`Filters setting for Logs cleared up`;function XMi(e,t,n){let{storageKey:r,messages:i,skipHydration:a}=n??{},[o,s]=(0,G.useState)(()=>bci(r)!==null),c=(0,G.useCallback)(()=>{vci(e,r),s(!0);let t=i?.saved??JMi;t!==!1&&UC.success(t)},[e,r,i?.saved]),l=(0,G.useCallback)(()=>{yci(r),s(!1);let e=i?.cleared??YMi;e!==!1&&UC.success(e)},[r,i?.cleared]),u=(0,G.useRef)(!1);return(0,G.useEffect)(()=>{if(a||u.current||(u.current=!0,xci(e)))return;let n=bci(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 ZMi(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 QMi(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,ZMi(`${e}${n.message??``}${n.data?JSON.stringify(n.data):``}`))}return t}function $Mi(e,t,n,r){let i=(0,G.useMemo)(()=>QMi(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 eNi=`logId`,tNi=`traceId`,nNi=`spanId`,N9=864e5,rNi={"last-24h":N9,"last-3d":3*N9,"last-7d":7*N9,"last-14d":14*N9,"last-30d":30*N9};function iNi(e){e.delete(eNi),e.delete(tNi),e.delete(nNi)}function aNi(e,t,n){let{onRemoveAll:r}=n??{},i=(0,G.useMemo)(()=>{let t=e.get(d7);return t&&hci.has(t)?t:fci},[e]),a=e.get(f7),o=e.get(p7),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=rNi[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(eNi),d=e.get(tNi),f=e.get(nNi),p=(0,G.useMemo)(()=>uci.find(t=>t.entityType===e.get(u7)),[e]),m=(0,G.useMemo)(()=>Cci(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`?eNi:t===`traceId`?tNi:nNi;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 Tci(n,e),iNi(n),n},{replace:!0})},[t]),_=g,v=(0,G.useCallback)((e,n)=>{if(l.current!==`custom`)return;let r=n===`from`?f7:p7;t(t=>{let n=new URLSearchParams(t);return e?n.set(r,e.toISOString()):n.delete(r),iNi(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(d7),n.delete(f7),n.delete(p7)):e===`custom`?n.set(d7,`custom`):(n.set(d7,e),n.delete(f7),n.delete(p7)),iNi(n),n},{replace:!0})},[t]),b=(0,G.useCallback)(()=>{t(e=>{let t=new URLSearchParams(e);t.delete(u7);for(let e of h7)t.delete(m7[e]);return t.delete(d7),t.delete(f7),t.delete(p7),iNi(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 oNi=20,sNi=1e4,cNi={field:`timestamp`,direction:`DESC`};function lNi(e,t,n){if(e?.pagination?.hasMore)return n+1}function uNi(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 dNi(e){return ZP(e.state.error,`logs`)||QP(e.state.error)?!1:sNi}var fNi=({filters:e,orderBy:t=cNi,queryOptions:n}={})=>{let r=Y(),{inView:i,setRef:a}=oP(),{hasNextPage:o,isFetchingNextPage:s,fetchNextPage:c,data:l,isLoading:u,isError:d,error:f}=ky({queryKey:[`logs`,e,t],queryFn:({pageParam:n})=>r.listLogsVNext({pagination:{page:n,perPage:oNi},filters:e,orderBy:t}),initialPageParam:0,getNextPageParam:lNi,select:uNi,retry:!1,refetchInterval:dNi,...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}},pNi=[sF(`/logs`)];function mNi(){let[e,t]=Hb(),n=kb(),r=aNi(e,t),i=r5(),{sort:a,onSortChange:o}=c7({searchParams:e,setSearchParams:t,allowedKeys:pci,defaultSort:mci}),s=(0,G.useMemo)(()=>({field:`timestamp`,direction:a?.direction===`asc`?`ASC`:`DESC`}),[a?.direction]),c=XMi(e,t),[l,u]=(0,G.useState)(),{data:d=[],isPending:f}=c$r(),{data:p=[],isPending:m}=g8({entityType:r.selectedEntityOption?.entityType,rootOnly:!0}),{data:h=[],isPending:g}=_8(),{data:_=[],isPending:v}=o$r(),y=(0,G.useMemo)(()=>Sci({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}=fNi({filters:(0,G.useMemo)(()=>Eci({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}=$Mi(b,r.featuredLogId,r.handleFeaturedChange,r.featuredTraceId),{data:j,isLoading:M}=y8({traceId:r.featuredTraceId??null,queryOptions:{enabled:!!r.featuredTraceId}}),N=(0,G.useCallback)(()=>r.applyFilterTokens(Dci(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)(jq,{children:(0,K.jsxs)(jq.Start,{children:[(0,K.jsx)(Ybn,{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)(OMi,{fields:y,tokens:r.filterTokens,onTokensChange:r.handleFilterTokensChange,disabled:x,onStartTextFilter:u,size:`sm`})]})}),(0,K.jsx)(HMi,{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)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:pNi}),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)(jMi,{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)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:pNi}),actionRow:z,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Logs`}),(0,K.jsx)(qMi,{datePreset:r.datePreset,dateFrom:r.selectedDateFrom,dateTo:r.selectedDateTo})]}):(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:pNi}),actionRow:z,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Logs`}),(0,K.jsx)(VMi,{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)(AMi,{log:D??void 0,onClose:P,onTraceClick:F,onSpanClick:I,onPrevious:k,onNext:A}),(0,K.jsx)(vbi,{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(kq(e,t))})]})}function hNi(){let e=Y();return Ey({queryKey:[`builtin-mcp-server`],queryFn:()=>e.getBuiltinMcpServer(),retry:!1})}var gNi=`<your-token>`;function _Ni(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function vNi(e,{protectedServer:t}){let n=_Ni(e),r=`Authorization: Bearer ${gNi}`,i=t?{headers:{Authorization:`Bearer ${gNi}`}}:{};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 yNi=`https://mastra.ai/docs/server/mcp`;function bNi(){let{data:e,error:t}=hNi();return e?(0,K.jsx)(xNi,{descriptor:e}):!t||JP(t)||YP(t)||XP(t)?null:(0,K.jsx)(SNi,{children:(0,K.jsx)(EA,{variant:`destructive`,children:`Couldn't load the built-in MCP server. Try reloading the page.`})})}function xNi({descriptor:e}){return(0,K.jsx)(SNi,{status:(0,K.jsx)(CNi,{descriptor:e}),children:e.enabled?e.mcpPackageInstalled?(0,K.jsx)(DNi,{descriptor:e}):(0,K.jsx)(ENi,{}):(0,K.jsx)(TNi,{descriptor:e})})}function SNi({status:e,children:t}){return(0,K.jsxs)(dF,{role:`region`,"aria-label":`Mastra (built-in) MCP server`,children:[(0,K.jsxs)(fF,{className:`flex-row flex-wrap items-center gap-3 space-y-0 border-b border-border`,children:[(0,K.jsx)(pF,{className:`shrink-0`,children:`Mastra (built-in)`}),e]}),(0,K.jsx)(hF,{className:`flex flex-col gap-4`,children:t})]})}function CNi({descriptor:e}){let{label:t,variant:n}=wNi(e);return(0,K.jsx)(bw,{variant:n,emphasis:`subtle`,indicator:`dot`,children:t})}function wNi(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 TNi({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)(uZ,{children:`server.mcp.enabled`}),` is`,` `,(0,K.jsx)(uZ,{children:`false`}),`.`]}):(0,K.jsxs)(K.Fragment,{children:[`The built-in MCP server only runs under `,(0,K.jsx)(uZ,{children:`mastra dev`}),` unless the server has auth. Configure `,(0,K.jsx)(uZ,{children:`server.auth`}),`, or set `,(0,K.jsx)(uZ,{children:`server.mcp.enabled`}),` to`,` `,(0,K.jsx)(uZ,{children:`true`}),`.`]})}),(0,K.jsx)(kNi,{})]})}function ENi(){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)(uZ,{children:`@mastra/mcp`}),` package. Install it and restart the server.`]}),(0,K.jsx)(pY,{code:`npm install @mastra/mcp`,lang:`bash`,copyTooltip:`Copy install command`}),(0,K.jsx)(kNi,{})]})}function DNi({descriptor:e}){let t=`${(Y().options.baseUrl||window.location.origin).replace(/\/$/,``)}${e.path}`,n=vNi(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)(jw,{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)(bw,{variant:`neutral`,emphasis:`subtle`,children:ONi(e)})},e)),e.readOnly&&(0,K.jsx)(`li`,{children:(0,K.jsx)(bw,{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)(pY,{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 ONi(e){let t=e.replaceAll(`_`,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function kNi(){return(0,K.jsx)(`div`,{children:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:yNi,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(Br,{}),children:`MCP server docs`})})}var ANi={name:e=>e.name||e.id};function jNi({server:e,rowProps:t}){let{paths:n,Link:r}=gl(),i=Y().options.baseUrl,a=e.transports?.includes(`sse`)??!0?`sse`:`mcp`,o=i?`${i}/api/mcp/${e.id}/${a}`:``,{data:s}=HIt({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=fY(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 MNi({mcpServers:e,isLoading:t,search:n=``,sort:r,onSortChange:i}){let a=(0,G.useMemo)(()=>{let t=n.toLowerCase();return yQ(e.filter(e=>e.name?.toLowerCase().includes(t)||e.id?.toLowerCase().includes(t)),r,ANi)},[e,n,r]),{containerRef:o,getRowProps:s}=_Q({count:a.length,global:!0});return t?(0,K.jsx)(NU,{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)(tF,{}),tooltip:`Agent tools`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Tools`,short:(0,K.jsx)(aF,{}),tooltip:`Tools`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Workflows`,short:(0,K.jsx)(rP,{}),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)(jNi,{server:e,rowProps:s(t)},e.id))]})}var NNi=()=>(0,K.jsx)(RC,{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)(Br,{}),children:`MCP documentation`}),variant:`fill`}),P9=[sF(`/mcps`)],PNi=()=>{let{data:e=[],isLoading:t,error:n}=KP(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)();return n&&JP(n)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:P9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsx)(jU,{variant:`fill`})]}):n&&YP(n)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:P9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsx)(AU,{variant:`fill`,resource:`MCP servers`})]}):n?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:P9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load MCP servers`,descriptionSlot:n.message})]}):e.length===0&&!t?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:P9}),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)(bNi,{}),(0,K.jsx)(NNi,{})]})]}):(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:P9}),actionRow:(0,K.jsx)(jq,{children:(0,K.jsx)(jq.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(zU,{onSearch:i,label:`Filter MCP servers`,placeholder:`Filter 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)(bNi,{}),(0,K.jsx)(MNi,{mcpServers:e,isLoading:t,search:r,sort:a,onSortChange:(e,t)=>o({key:t,direction:e})})]})]})};function FNi(){let[e,t]=Hb();return{eventName:e.get(`event`)??void 0,close:()=>t(e=>{let t=new URLSearchParams(e);return t.delete(`event`),t},{replace:!0})}}var INi=e=>`?${new URLSearchParams({event:e}).toString()}`;function LNi(e,{enabled:t=!0}={}){let n=Y();return Ey({queryKey:[`mcp-server-events`,e],queryFn:()=>n.getMcpServerEvents(e),enabled:t})}function RNi(e,t){let n=Y();return Oy({mutationFn:r=>n.emitMcpServerEvent(e,t,r)})}function zNi(e){if(e instanceof Ym&&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 BNi={push:`blue`,poll:`neutral`,webhook:`purple`};function VNi({delivery:e}){return(0,K.jsx)(`span`,{className:`flex flex-wrap items-center gap-1`,children:e.map(e=>(0,K.jsx)(bw,{size:`xs`,variant:BNi[e],emphasis:`subtle`,children:e},e))})}var HNi=0,UNi=()=>`feed-${HNi++}`;function WNi(e,t){return[...t,...e].slice(0,200)}function GNi(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:WNi(e.items,[{kind:`gap`,key:UNi()}])};case`occurrences`:{let n=[...t.occurrences].reverse().map(e=>({kind:`occurrence`,key:UNi(),occurrence:e}));return{...e,items:WNi(e.items,n)}}case`warning`:return{...e,warning:t.message};case`error`:return{...e,status:`error`,error:t.message}}}var KNi={status:`idle`,items:[]};function qNi(e,t){let n=Y(),[r,i]=(0,G.useReducer)(GNi,KNi),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:zNi(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:zNi(e)})}};return{...r,start:l,stop:c,pollOnce:u}}function F9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function JNi(e){return e.map(e=>JSON.stringify(e)).join(` | `)}function YNi(e){return e.map(I9).join(` | `)}function I9(e){return F9(e)?Array.isArray(e.enum)?JNi(e.enum):`const`in e?JSON.stringify(e.const):Array.isArray(e.anyOf)?YNi(e.anyOf):Array.isArray(e.oneOf)?YNi(e.oneOf):Array.isArray(e.type)?e.type.join(` | `):e.type===`array`?`${I9(e.items)}[]`:QNi(e)?`Record<string, ${I9(e.additionalProperties)}>`:typeof e.type==`string`?e.type:`unknown`:`unknown`}function XNi(e,t,n,{defaultsAreOptional:r=!1}){let i=F9(t)?t:{},a=`default`in i;return{name:e,type:I9(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 ZNi(e,t={}){if(!F9(e)||!F9(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])=>XNi(e,r,n,t))}function QNi(e){return F9(e)&&e.type===`object`&&!F9(e.properties)&&F9(e.additionalProperties)}function $Ni(e){return F9(e)&&(e.type===`object`||F9(e.properties))}var ePi=[`type`,`properties`,`items`,`enum`,`const`,`anyOf`,`oneOf`,`allOf`,`$ref`];function tPi(e){return!F9(e)||!ePi.some(t=>t in e)}function L9(e){return F9(e)?Kk(e):J({})}function nPi({inputSchema:e,onChange:t}){return tPi(e)?(0,K.jsx)(T,{tone:`muted`,children:`This event takes no arguments.`}):(0,K.jsx)(nP,{schema:L9(e),onValuesChange:e=>t(e??{})})}function rPi({occurrence:e}){return(0,K.jsx)(dF,{children:(0,K.jsxs)(Hw,{children:[(0,K.jsxs)(Uw,{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)(bw,{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)(Ww,{children:(0,K.jsx)(FT,{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 iPi=`Gap: events may have been skipped`;function aPi({items:e}){return e.length===0?(0,K.jsx)(RC,{iconSlot:(0,K.jsx)(Wo,{}),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)(EA,{variant:`warning`,children:iPi}):(0,K.jsx)(rPi,{occurrence:e.occurrence})},e.key))})}var oPi={idle:`Not listening`,connecting:`Connecting…`,polling:`Polling…`,polled:`Polled`,stopped:`Stopped`,error:`Failed`};function sPi({status:e,canStream:t}){if(e===`live`)return(0,K.jsx)(bw,{variant:`green`,indicator:`pulse`,size:`sm`,children:`Listening`});let n=e===`idle`&&!t?`Not polled yet`:oPi[e];return(0,K.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(e===`connecting`||e===`polling`)&&(0,K.jsx)(Zc,{size:`sm`}),(0,K.jsx)(T,{as:`span`,tone:`muted`,children:n})]})}function cPi({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)(sPi,{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)(jw,{tooltip:`Copy cursor`,content:n})]})]})}function lPi({serverId:e,event:t,onEmitted:n}){let{mutateAsync:r,isPending:i,isSuccess:a,error:o}=RNi(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)(nP,{schema:L9(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)(EA,{variant:`destructive`,children:zNi(o)})]})}function uPi({serverId:e,event:t,testEmit:n,canEmit:r}){let[i,a]=(0,G.useState)({}),o=qNi(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)(nPi,{inputSchema:t.inputSchema,onChange:a}),(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,K.jsx)(cPi,{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)(EA,{variant:`destructive`,children:o.error}),o.warning&&(0,K.jsx)(EA,{variant:`warning`,children:o.warning}),n&&t.emittable&&r&&(0,K.jsx)(lPi,{serverId:e,event:t,onEmitted:s?void 0:()=>void o.pollOnce(i)}),(0,K.jsx)(aPi,{items:o.items})]})}function dPi({description:e}){let t=W$({collapsedHeight:140});return(0,K.jsx)(U$,{state:t,expandLabel:`Read more`,children:(0,K.jsx)(xX,{children:e})})}function fPi({description:e,overview:t,playground:n,canRun:r}){return(0,K.jsx)(K.Fragment,{children:(0,K.jsxs)(CA,{defaultTab:`overview`,className:`grid flex-1 grid-rows-[auto_1fr] gap-4 overflow-visible`,children:[(0,K.jsxs)(SA,{variant:`pill`,size:`sm`,children:[(0,K.jsx)(wA,{value:`overview`,children:`Overview`}),(0,K.jsx)(wA,{value:`playground`,disabled:!r,disabledTooltip:`You don't have permission to execute tools.`,children:`Playground`})]}),(0,K.jsxs)(TA,{value:`overview`,flush:!0,className:`content-start gap-6`,children:[e&&(0,K.jsx)(dF,{className:`p-4`,children:(0,K.jsx)(dPi,{description:e})}),t]}),(0,K.jsx)(TA,{value:`playground`,flush:!0,keepMounted:!0,className:`h-full`,children:r&&n})]})})}function pPi(e){return(0,K.jsx)(vdr,{className:`min-h-control-md`,...e})}function mPi(){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 hPi({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 gPi({field:e}){let t=!!e.description||e.defaultValue!==void 0;return(0,K.jsx)(g$,{label:(0,K.jsxs)(T,{as:`span`,variant:`body-sm`,font:`mono`,tone:`ink`,children:[e.name,e.required&&(0,K.jsx)(mPi,{})]}),description:t&&(0,K.jsx)(hPi,{field:e}),children:(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,tone:`muted`,children:e.type})})}function _Pi({message:e}){return(0,K.jsx)(Cdr,{children:e})}function vPi({schema:e,emptyMessage:t,defaultsAreOptional:n}){if(tPi(e))return(0,K.jsx)(_Pi,{message:t});if(!$Ni(e)||QNi(e))return(0,K.jsx)(g$,{label:`Type`,children:(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,tone:`muted`,children:I9(e)})});let r=ZNi(e,{defaultsAreOptional:n});return r.length===0?(0,K.jsx)(_Pi,{message:t}):r.map(e=>(0,K.jsx)(gPi,{field:e},e.name))}function R9({title:e,...t}){return(0,K.jsxs)(v$,{children:[(0,K.jsx)(pPi,{children:(0,K.jsx)(y$,{children:e})}),(0,K.jsx)(_$,{children:(0,K.jsx)(vPi,{...t})})]})}function yPi({serverId:e,eventName:t}){let{canExecute:n,canEdit:r}=KC(),{data:i,isLoading:a}=LNi(e),o=i?.events.find(e=>e.name===t);return a?(0,K.jsx)(m$.LoadingData,{}):!i||!o?(0,K.jsxs)(m$.NoData,{children:[`This server has no event "`,t,`".`]}):(0,K.jsx)(fPi,{description:o.description,overview:(0,K.jsxs)(`div`,{className:`grid grid-cols-1 gap-6`,children:[(0,K.jsx)(VNi,{delivery:o.delivery}),(0,K.jsx)(R9,{title:`Arguments`,schema:o.inputSchema,emptyMessage:`This event takes no arguments.`,defaultsAreOptional:!0}),(0,K.jsx)(R9,{title:`Payload`,schema:o.payloadSchema,emptyMessage:`No payload schema defined.`})]}),canRun:n(`mcp`),playground:(0,K.jsx)(uPi,{serverId:e,event:o,testEmit:i.testEmit,canEmit:r(`mcp`)})})}function bPi({serverId:e}){let{eventName:t,close:n}=FNi();return(0,K.jsxs)(m$,{open:t!==void 0,onClose:n,title:t??``,children:[(0,K.jsxs)(m$.Header,{children:[(0,K.jsxs)(m$.Heading,{children:[(0,K.jsx)(TC,{size:`sm`,className:`text-muted-foreground`,children:(0,K.jsx)(Wo,{})}),(0,K.jsx)(`span`,{className:`truncate`,children:t})]}),(0,K.jsx)(m$.HeaderActions,{children:(0,K.jsx)(m$.CloseButton,{icon:`x`,tooltip:`Close event`,onClick:n})})]}),(0,K.jsx)(m$.Content,{className:`flex flex-col gap-4 px-3`,children:t&&(0,K.jsx)(yPi,{serverId:e,eventName:t},t)})]})}var xPi=new Set([`completed`,`failed`,`cancelled`]),SPi={working:`working`,input_required:`input required`,completed:`completed`,failed:`failed`,cancelled:`cancelled`},CPi=e=>xPi.has(e.status),wPi=2e3,z9=e=>[`mcp-server-tasks`,e],TPi=e=>!!e?.some(e=>!CPi(e));function EPi(e,t={}){let n=Y();return ky({queryKey:[...z9(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=>TPi(e.tasks))?wPi:!1})}function DPi(e,{enabled:t=!0}={}){let n=Y();return Ey({queryKey:[...z9(e),`surfaces`],queryFn:()=>n.getMcpServerTasks(e,{limit:1}),select:e=>e.surfaces,enabled:t})}function OPi(e,t){let n=Y();return Ey({queryKey:[...z9(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&&!CPi(e.state.data)?wPi:!1})}function kPi(e){let t=Y();return Oy({mutationFn:n=>t.findMcpServerTask(e,n)})}function APi(e){let t=Y(),n=dy();return Oy({mutationFn:n=>t.cancelMcpServerTask(e,n),onSettled:()=>n.invalidateQueries({queryKey:z9(e)})})}function jPi(e){let t=Y(),n=dy();return Oy({mutationFn:({taskKey:n,inputResponses:r})=>t.answerMcpServerTaskInput(e,n,r),onSettled:()=>n.invalidateQueries({queryKey:z9(e)})})}function MPi(){let[e,t]=Hb();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 NPi=(e,t=``)=>{let n=new URLSearchParams(t);return n.set(`task`,e),`?${n.toString()}`},PPi=e=>`${e.slice(0,8)}…`,FPi=new Set([`working`,`input_required`,`completed`,`failed`,`cancelled`]);function IPi(){let[e,t]=Hb(),n=e.get(`status`),r=e.get(`surface`),i=e.get(`client`);return{filters:{...n&&FPi.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 LPi=e=>`${e.slice(0,8)}…`,RPi={working:{variant:`info`,indicator:`pulse`},input_required:{variant:`warning`,indicator:`dot`},completed:{variant:`success`},failed:{variant:`destructive`},cancelled:{variant:`neutral`}};function zPi({status:e}){let{variant:t,indicator:n}=RPi[e];return(0,K.jsx)(bw,{size:`sm`,variant:t,emphasis:`subtle`,indicator:n,children:SPi[e]})}function BPi({serverId:e}){let{taskKey:t,close:n}=MPi(),{data:r,isSuccess:i}=OPi(e,t);return(0,K.jsxs)(m$,{open:t!==void 0,onClose:n,title:r?.surface??`Task`,children:[(0,K.jsxs)(m$.Header,{children:[(0,K.jsxs)(m$.Heading,{children:[(0,K.jsx)(TC,{size:`sm`,className:`text-muted-foreground`,children:(0,K.jsx)(pa,{})}),(0,K.jsx)(`span`,{className:`truncate`,children:r?`${r.surface} task`:`Task`})]}),(0,K.jsx)(m$.HeaderActions,{children:(0,K.jsx)(m$.CloseButton,{icon:`x`,tooltip:`Close task`,onClick:n})})]}),(0,K.jsx)(m$.Content,{className:`flex flex-col gap-4 px-3`,children:r?(0,K.jsx)(VPi,{serverId:e,task:r},r.taskKey):i&&(0,K.jsx)(T,{tone:`muted`,children:`This task is no longer listed.`})})]})}function VPi({serverId:e,task:t}){let n=APi(e),{canEdit:r,isLoading:i}=KC(),a=!i&&r(`mcp`),o=Object.entries(t.inputRequests??{});return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(b3,{children:[(0,K.jsx)(b3.Key,{children:`Status`}),(0,K.jsx)(b3.Value,{children:(0,K.jsx)(zPi,{status:t.status})}),t.statusMessage&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(b3.Key,{children:`Message`}),(0,K.jsx)(b3.Value,{children:t.statusMessage})]}),(0,K.jsx)(b3.Key,{children:`Created`}),(0,K.jsx)(b3.Value,{children:(0,K.jsx)(jA,{value:t.createdAt})}),(0,K.jsx)(b3.Key,{children:`Updated`}),(0,K.jsx)(b3.Value,{children:(0,K.jsx)(jA,{value:t.lastUpdatedAt})}),(0,K.jsx)(b3.Key,{children:`Expires`}),(0,K.jsx)(b3.Value,{children:t.expiresAt?(0,K.jsx)(jA,{value:t.expiresAt}):`never`}),(0,K.jsx)(b3.Key,{children:`Task key`}),(0,K.jsx)(b3.ValueWithCopyBtn,{copyValue:t.taskKey,copyTooltip:`Copy task key`,children:PPi(t.taskKey)}),t.clientLabel&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(b3.Key,{children:`Client`}),(0,K.jsx)(b3.ValueWithCopyBtn,{copyValue:t.clientLabel,copyTooltip:`Copy client`,children:t.clientLabel})]}),(0,K.jsx)(b3.Key,{children:`Client key`}),(0,K.jsx)(b3.ValueWithCopyBtn,{copyValue:t.principalKey,copyTooltip:`Copy client key`,children:PPi(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)(UPi,{serverId:e,taskKey:t.taskKey,inputKey:n,request:r,canAnswer:a},n)),!CPi(t)&&!i&&!a&&(0,K.jsx)(T,{tone:`muted`,variant:`caption`,children:`Cancelling or answering a task needs the mcp:write permission.`}),!CPi(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)(EA,{variant:`destructive`,children:GPi(n.error)})]}),t.result&&(0,K.jsx)(WPi,{label:`Result`,value:t.result}),t.error&&(0,K.jsx)(WPi,{label:`Error`,value:t.error})]})}var HPi=J({message:q().optional(),requestedSchema:Rp(q(),Ap())});function UPi({serverId:e,taskKey:t,inputKey:n,request:r,canAnswer:i}){let a=jPi(e),o=r.method===`elicitation/create`?HPi.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)(WPi,{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)(nP,{schema:L9(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)(WPi,{label:`Request`,value:r})]}),a.error&&(0,K.jsx)(EA,{variant:`destructive`,children:GPi(a.error)})]})}function WPi({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)(FT,{value:JSON.stringify(t,null,2),language:`json`,editable:!1,lineNumbers:!1,"aria-label":`Task ${e.toLowerCase()}`})]})}function GPi(e){let t=zNi(e);return t===`Task not found`?`The task is no longer waiting for this; the list has been refreshed.`:t}function KPi(e){if(!F9(e))return;if(F9(e.ui)&&typeof e.ui.resourceUri==`string`)return e.ui.resourceUri;let t=e[`ui/resourceUri`];return typeof t==`string`?t:void 0}function qPi(e){return F9(e)&&e.status===`suspended`}function JPi(e){return e<1e3?`${Math.round(e)} ms`:`${(e/1e3).toFixed(2)} s`}function YPi(e){return e===void 0?`undefined`:JSON.stringify(e,null,2)}function XPi(e){return e.status===`error`?e.error:YPi(e.output)}function ZPi({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:QPi(n),durationMs:r}}}function QPi(e){return e instanceof Error?JSON.stringify({error:e.message},null,2):JSON.stringify({error:String(e)},null,2)}function $Pi({zodInputSchema:e,isRunning:t,onRun:n,requestContextEntityType:r,requestContextEntityId:i}){let a=!ZN(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=Kjt(o.value);if(!n.ok)return u([n.error]);let r=qjt(e,n.value);if(r)return u([r]);c.current=n.value,s({view:`form`,value:n.value})}function f(t){let r=Jjt(e,t);r.ok?n(r.value):u(r.errors)}let p={isSubmitLoading:t,submitButtonLabel:`Run`,submitButtonIcon:(0,K.jsx)(Vo,{}),submitButtonVariant:`primary`};return(0,K.jsxs)(v$,{children:[(0,K.jsx)(pPi,{action:(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(QLt,{entityType:r,entityId:i}),(0,K.jsx)(CA,{defaultTab:`form`,value:o.view,onValueChange:d,children:(0,K.jsxs)(SA,{size:`md`,children:[(0,K.jsxs)(wA,{value:`form`,disabled:t,children:[(0,K.jsx)(TC,{size:`sm`,children:(0,K.jsx)(Jo,{})}),`Form`]}),(0,K.jsxs)(wA,{value:`json`,disabled:t,children:[(0,K.jsx)(TC,{size:`sm`,children:(0,K.jsx)(Cn,{})}),`JSON`]})]})})]}),children:(0,K.jsx)(y$,{children:`Request`})}),(0,K.jsx)(_$,{children:(0,K.jsx)(`div`,{className:`p-4`,children:o.view===`json`?(0,K.jsxs)(`div`,{className:`grid gap-4`,children:[(0,K.jsxs)(fA,{invalid:l.length>0,children:[(0,K.jsx)(FT,{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)(gA,{children:l.map(e=>(0,K.jsx)(`span`,{className:`block`,children:e},e))})]}),(0,K.jsx)(NA,{...p,onSubmit:()=>f(o.value)})]}):(0,K.jsx)(nP,{...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.`})})})})]})}function eFi({isRunning:e,lastRun:t}){return e?(0,K.jsx)(RC,{iconSlot:(0,K.jsx)(Zc,{}),titleSlot:`Running…`,descriptionSlot:`Waiting for the tool to respond.`}):t?t.status===`error`?(0,K.jsx)(Dw,{code:XPi(t),className:`overflow-x-auto p-4 text-caption whitespace-pre`}):(0,K.jsx)(FT,{value:XPi(t),language:`json`,editable:!1,lineNumbers:!1,showCopyButton:!1,variant:`embedded`,"aria-label":`Tool response`,className:`p-4`}):(0,K.jsx)(RC,{iconSlot:(0,K.jsx)(vs,{}),titleSlot:`No response yet`,descriptionSlot:`Run the tool to see its output here.`})}function tFi({run:e}){return(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[e.status===`success`?(0,K.jsx)(bw,{variant:`success`,emphasis:`subtle`,indicator:`dot`,children:`Success`}):(0,K.jsx)(bw,{variant:`destructive`,emphasis:`subtle`,indicator:`dot`,children:`Error`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,tone:`muted`,children:JPi(e.durationMs)}),(0,K.jsx)(jw,{content:XPi(e),copyMessage:`Response copied`,tooltip:`Copy response`,size:`icon-sm`})]})}function nFi({isRunning:e,lastRun:t}){return(0,K.jsxs)(v$,{className:`h-full`,children:[(0,K.jsx)(pPi,{action:!e&&t&&(0,K.jsx)(tFi,{run:t}),children:(0,K.jsx)(y$,{children:`Response`})}),(0,K.jsx)(_$,{className:m(`grid min-h-48 flex-1`,e||!t?`content-center`:`content-start`),children:(0,K.jsx)(eFi,{isRunning:e,lastRun:t})})]})}function rFi({zodInputSchema:e,execution:t,requestContextEntityType:n,requestContextEntityId:r}){let[i]=mw(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)($Pi,{zodInputSchema:e,isRunning:c,onRun:s,requestContextEntityType:n,requestContextEntityId:r}),(0,K.jsx)(nFi,{isRunning:c,lastRun:ZPi(t,a)})]})}function iFi({serverId:e,tool:t}){let n=Xvr(e),{mutateAsync:r,status:i,data:a,error:o}=VIt({serverId:e,toolId:t.name}),{data:s}=RIt({serverId:e,appResourceUri:KPi(t._meta)}),c=L9(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)(GRr,{html:s,toolName:t.name,onToolCall:n}),qPi(a)&&(0,K.jsxs)(EA,{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)(uZ,{children:`inputRequests`}),` handler to finish the request.`]}),(0,K.jsx)(rFi,{zodInputSchema:c,execution:l,requestContextEntityType:`mcp-tool`,requestContextEntityId:`${e}:${t.name}`})]})}var aFi=(0,G.createContext)(void 0),oFi=aFi.Provider;function sFi(){let e=(0,G.useContext)(aFi);if(e===void 0)throw Error(`useOpenToolId must be used inside ToolDrawer`);return e}function cFi({inputSchema:e,outputSchema:t,requestContextSchema:n,footer:r}){return(0,K.jsxs)(`div`,{className:`grid gap-6`,children:[(0,K.jsx)(R9,{title:`Input`,schema:e,emptyMessage:`This tool takes no input.`,defaultsAreOptional:!0}),(0,K.jsx)(R9,{title:`Output`,schema:t,emptyMessage:`No output schema defined.`}),n!==void 0&&(0,K.jsx)(R9,{title:`Request context`,schema:n,emptyMessage:`No request context fields.`,defaultsAreOptional:!0}),r]})}function lFi({serverId:e}){let t=sFi(),{canExecute:n}=KC(),{data:r,isLoading:i}=BIt({serverId:e,toolId:t});return i?(0,K.jsx)(m$.LoadingData,{}):r?(0,K.jsx)(fPi,{description:r.description,overview:(0,K.jsx)(cFi,{inputSchema:r.inputSchema}),canRun:n(`tools`),playground:(0,K.jsx)(iFi,{serverId:e,tool:r})}):(0,K.jsxs)(m$.NoData,{children:[`This server has no tool "`,t,`".`]})}var uFi=`auto 1fr auto`;function dFi({server:e}){let{data:t,isLoading:n,isError:r}=LNi(e.id),i=t?.events??[],{Link:a}=gl(),{containerRef:o,getRowProps:s}=_Q({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)(NU,{columns:uFi}),r&&(0,K.jsx)(EA,{variant:`destructive`,children:`Could not load this server's events.`}),t&&(0,K.jsxs)(Z,{columns:uFi,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}${INi(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)(VNi,{delivery:t.delivery})})]},t.name))]})]})}var fFi=`minmax(0,1fr) auto auto auto auto auto auto auto`,pFi={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.`},mFi=[{id:`is`,label:`is`}],hFi=Object.entries(SPi).map(([e,t])=>({value:e,label:t})),gFi=e=>e.stopPropagation(),_Fi=e=>e.clientLabel??LPi(e.principalKey),vFi=e=>[`status`,`surface`,`client`].flatMap(t=>{let n=e[t];return n?[{id:t,fieldId:t,operatorId:`is`,value:n}]:[]}),yFi=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 bFi({server:e}){let{filters:t,setFilters:n}=IPi(),{data:r,isLoading:i,isError:a,hasNextPage:o,fetchNextPage:s,isFetchingNextPage:c}=EPi(e.id,t),{data:l=[]}=DPi(e.id),u=(0,G.useMemo)(()=>r?.pages.flatMap(e=>e.tasks)??[],[r]),d=r?.pages[0]?.unavailable,{containerRef:f,getRowProps:p}=_Q({count:u.length}),m=vFi(t).length>0,h=(0,G.useMemo)(()=>{let e=new Map(u.map(e=>[e.principalKey,_Fi(e)]));return t.client&&!e.has(t.client)&&e.set(t.client,LPi(t.client)),[...e]},[u,t.client]),g=(0,G.useMemo)(()=>[{id:`status`,label:`Status`,icon:Wn,color:_F(`orange`),operators:[`is`],strict:!0,suggestions:hFi},{id:`surface`,label:`Surface`,icon:zc,color:_F(`blue`),operators:[`is`],strict:!0,suggestions:l.map(e=>({value:e.name}))},{id:`client`,label:`Client`,icon:jc,color:_F(`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)(EA,{variant:`destructive`,children:`Could not load this server's tasks.`}),d&&(0,K.jsx)(EA,{variant:`info`,children:pFi[d]}),!d&&(0,K.jsxs)(jq,{children:[(0,K.jsx)(jq.Start,{children:(0,K.jsxs)(f5,{fields:g,operators:mFi,value:vFi(t),onValueChange:e=>n(yFi(e)),createItemId:e=>e,"aria-label":`Task filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(f5.Chips,{}),(0,K.jsx)(f5.Input,{placeholder:`Filter tasks`})]})}),(0,K.jsx)(jq.End,{children:(0,K.jsx)(SFi,{serverId:e.id})})]}),i&&(0,K.jsx)(NU,{columns:fFi}),r&&!d&&(0,K.jsxs)(Z,{columns:fFi,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)(xFi,{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 xFi({serverId:e,task:t,rowProps:n,onFilterClient:r}){let{Link:i}=gl(),[a]=Hb(),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}${NPi(t.taskKey,a)}`,LinkComponent:i,tabIndex:-1,onClick:gFi,"aria-label":`${t.surface} task ${PPi(t.taskKey)}`,children:[(0,K.jsx)(Z.NameCell,{children:t.surface}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(zPi,{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)(jA,{value:t.lastUpdatedAt})}),(0,K.jsx)(Z.Cell,{className:`text-muted-foreground`,children:t.expiresAt?(0,K.jsx)(jA,{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:PPi(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 ${_Fi(t)}`,onClick:e=>{e.stopPropagation(),r()},children:_Fi(t)})})]})}function SFi({serverId:e}){let[t,n]=(0,G.useState)(``),r=kPi(e),{open:i}=MPi();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)(ZM,{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 CFi={agent:tF,workflow:rP,tool:aF},wFi=`auto minmax(0, 1fr) auto`,TFi=`auto minmax(0, 1fr) auto auto`,EFi={tool:`Tool`,agent:`Agent`,workflow:`Workflow`};function DFi(e){return e in CFi}function OFi({type:e}){let t=DFi(e)?e:`tool`,n=CFi[t],r=EFi[t];return(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{asChild:!0,children:(0,K.jsx)(`span`,{"aria-label":t,className:`inline-flex text-muted-foreground [&>svg]:size-4`,children:(0,K.jsx)(n,{})})}),(0,K.jsx)(CC,{children:r})]})}var kFi=J({ui:J({resourceUri:q().optional()}).optional(),"ui/resourceUri":q().optional()});function AFi(e){let t=kFi.safeParse(e);return t.success?!!(t.data.ui?.resourceUri?.startsWith(`ui://`)||t.data[`ui/resourceUri`]?.startsWith(`ui://`)):!1}function jFi({surface:e}){return e?(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{asChild:!0,children:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,K.jsx)(bw,{size:`xs`,variant:e.mode===`always`?`info`:`neutral`,emphasis:`subtle`,children:e.mode}),e.required&&(0,K.jsx)(bw,{size:`xs`,variant:`warning`,emphasis:`subtle`,children:`required`}),e.recover&&(0,K.jsx)(bw,{size:`xs`,variant:`neutral`,emphasis:`subtle`,children:`recover`})]})}),(0,K.jsxs)(CC,{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 MFi({server:e}){let[t,n]=(0,G.useState)(``),{data:r={},isLoading:i}=HIt({selectedServer:e}),{Link:a,paths:o}=gl(),{data:s}=DPi(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?TFi:wFi,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}=_Q({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)(zU,{onSearch:n,label:`Filter tools`,placeholder:`Filter by name`,shortcutDisabled:!0})})]}),i?(0,K.jsx)(NU,{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,AFi(t._meta)&&(0,K.jsx)(bw,{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)(OFi,{type:t.toolType??`tool`})}),l&&(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(jFi,{surface:c.get(t.name)})})]},t.name))]})]})}var NFi=({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)(dF,{children:(0,K.jsxs)(CA,{defaultTab:`http`,children:[(0,K.jsxs)(fF,{className:`flex-row items-center justify-between gap-3 space-y-0 border-b border-border`,children:[(0,K.jsx)(pF,{className:`shrink-0`,children:`Connect`}),(0,K.jsx)(`div`,{className:`min-w-0`,children:(0,K.jsx)(SA,{variant:`pill-ghost`,size:`sm`,children:s.map(e=>(0,K.jsx)(wA,{value:e.value,children:e.label},e.value))})})]}),s.map(e=>(0,K.jsx)(TA,{value:e.value,flush:!0,children:(0,K.jsxs)(hF,{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)(jw,{tooltip:e.tooltip,content:e.content})]})]})},e.value))]})}),(0,K.jsx)(MFi,{server:t}),t.tasks_capability&&(0,K.jsx)(bFi,{server:t}),t.events_capability&&(0,K.jsx)(dFi,{server:t})]})};function PFi(){let[e,t]=Hb();return{toolId:e.get(`tool`)??void 0,close:()=>t(e=>{let t=new URLSearchParams(e);return t.delete(`tool`),t},{replace:!0})}}function FFi({children:e}){let{toolId:t,close:n}=PFi();return(0,K.jsxs)(m$,{open:t!==void 0,onClose:n,title:t??``,children:[(0,K.jsxs)(m$.Header,{children:[(0,K.jsxs)(m$.Heading,{children:[(0,K.jsx)(TC,{size:`sm`,className:`text-muted-foreground`,children:(0,K.jsx)(aF,{})}),(0,K.jsx)(`span`,{className:`truncate`,children:t})]}),(0,K.jsx)(m$.HeaderActions,{children:(0,K.jsx)(m$.CloseButton,{icon:`x`,tooltip:`Close tool`,onClick:n})})]}),(0,K.jsx)(m$.Content,{className:`flex flex-col gap-4 px-3`,children:t&&(0,K.jsx)(oFi,{value:t,children:e},t)})]})}var IFi=()=>{let{serverId:e}=Ab(),t=[sF(`/mcps`),HLt],{data:n=[],isLoading:r}=KP(),i=n.find(t=>t.id===e),a=i?.transports?.includes(`sse`)??!0,o=r||i?(0,K.jsxs)(Nq,{children:[(0,K.jsx)(Nq.Title,{isLoading:r,children:i?.name}),i&&(0,K.jsx)(Nq.Meta,{beside:!0,children:(0,K.jsxs)(bw,{size:`sm`,children:[`v`,i.version_detail.version]})}),i&&(0,K.jsx)(Nq.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)(uw,{variant:`narrow`,breadcrumbs:(0,K.jsx)(EP,{crumbs:t}),header:o,children:[(0,K.jsx)(NFi,{isLoading:r,server:i}),e&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(FFi,{children:(0,K.jsx)(lFi,{serverId:e})}),(0,K.jsx)(bPi,{serverId:e}),(0,K.jsx)(BPi,{serverId:e})]})]})};function LFi(){let{data:e,isLoading:t}=n5();if(t)return`loading`;let n=e?.capabilities;return n?.traceAggregate===!0&&n.spanAggregate===!0?`unified`:`legacy`}var B9=[sF(`/metrics`)],RFi=e=>e.fieldId===L5r;function zFi({fields:e}){let{filterTokens:t,setFilterTokens:n}=Z7(),r=[d5,...jxi(t)];return(0,K.jsxs)(f5,{fields:[R5r,...e],operators:wxi,value:r,onValueChange:e=>n(Mxi(e.filter(e=>!RFi(e)))),createItemId:e=>e,"aria-label":`Metrics filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(f5.Chips,{renderChip:e=>RFi(e)?(0,K.jsx)(hSi,{}):(0,K.jsx)(f5.Chip,{item:e})}),(0,K.jsx)(f5.Input,{placeholder:`Filter metrics`})]})}function BFi({children:e,filterFields:t}){return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:B9}),actionRow:(0,K.jsx)(jq,{children:(0,K.jsx)(jq.Start,{children:(0,K.jsx)(zFi,{fields:t})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),e]})}function VFi({error:e}){return JP(e)?(0,K.jsx)(jU,{}):YP(e)?(0,K.jsx)(AU,{resource:`metrics`}):(0,K.jsx)(RC,{tone:`error`,titleSlot:`Failed to load storage capabilities`,descriptionSlot:e.message})}var HFi=Axi({availableTags:[],availableEntityNames:[],availableServiceNames:[],availableEnvironments:[]});function UFi({children:e}){let{supportsMetrics:t,isLoading:n,error:r}=b7();return n?(0,K.jsx)(BFi,{filterFields:HFi,children:(0,K.jsxs)(`div`,{className:`flex h-full items-center justify-center gap-2`,children:[(0,K.jsx)(Zc,{"aria-label":`Loading storage capabilities`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:`Loading storage capabilities`})]})}):r?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:B9}),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)(VFi,{error:r})})]}):t?e:(0,K.jsx)(BFi,{filterFields:HFi,children:(0,K.jsx)(RC,{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)(Br,{}),children:`Metrics documentation`}),variant:`fill`})})}function WFi(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 GFi(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=WFi(i);s&&e.set(t,s)}function V9(e,t,n){typeof n==`string`&&n.length>0&&e.set(t,n)}function KFi(e,t,n){if(Array.isArray(n)&&n.length!==0)for(let r of n)r&&e.append(t,r)}function qFi({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 JFi({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:i=`/traces`}){let a=new URLSearchParams;a.set(w8,`branches`),GFi(a,T8,E8,D8,e,t,r.window);let o=r.rootEntityType??n.rootEntityType;o&&a.set(E1r,o),r.status&&a.set(D1r,r.status),V9(a,O8.entityName,r.entityName??n.entityName),V9(a,O8.threadId,r.threadId??n.threadId),V9(a,O8.resourceId,r.resourceId??n.resourceId),V9(a,O8.runId,n.runId),V9(a,O8.sessionId,r.sessionId??n.sessionId),V9(a,O8.requestId,n.requestId),V9(a,O8.userId,r.userId??n.userId),V9(a,O8.organizationId,n.organizationId),V9(a,O8.experimentId,n.experimentId),V9(a,O8.serviceName,n.serviceName),V9(a,O8.environment,r.environment??n.environment),KFi(a,O8.tags,n.tags),r.span&&a.append(R8,JSON.stringify(qFi(r.span)));let s=a.toString();return s?`${i}?${s}`:i}function YFi({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:i=`/logs`}){let a=new URLSearchParams;GFi(a,d7,f7,p7,e,t,r.window);let o=r.rootEntityType??n.rootEntityType;o&&a.set(u7,o),V9(a,m7.entityName,r.entityName??n.entityName),V9(a,m7.threadId,r.threadId??n.threadId),V9(a,m7.resourceId,r.resourceId??n.resourceId),V9(a,m7.runId,n.runId),V9(a,m7.sessionId,n.sessionId),V9(a,m7.requestId,n.requestId),V9(a,m7.userId,n.userId),V9(a,m7.organizationId,n.organizationId),V9(a,m7.experimentId,n.experimentId),V9(a,m7.serviceName,n.serviceName),V9(a,m7.environment,n.environment),KFi(a,m7.tags,n.tags),r.status===`error`&&a.append(m7.level,`error`);let s=a.toString();return s?`${i}?${s}`:i}function XFi(){let{datePreset:e,customRange:t,dimensionalFilter:n}=Z7(),r=kb(),i={preset:e,customRange:t,dashboardFilter:n};return{openTraces:(e={})=>{r(JFi({...i,scope:e}))},openLogs:(e={})=>{r(YFi({...i,scope:e}))}}}var ZFi=`period`,QFi=`dateFrom`,$Fi=`dateTo`;function eIi(){let[e,t]=Hb(),n=e.get(ZFi),r=iSi(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(QFi)),i=t(e.get($Fi));if(n||i)return{from:n,to:i}},[r,e.toString()]),a=(0,G.useMemo)(()=>Nxi(e),[e.toString()]),o=(0,G.useCallback)(e=>{t(t=>{let n=new URLSearchParams(t);return e===`24h`?n.delete(ZFi):n.set(ZFi,e),e!==`custom`&&(n.delete(QFi),n.delete($Fi)),n},{replace:!0})},[t]),s=(0,G.useCallback)(e=>{t(t=>{let n=new URLSearchParams(t);return e?.from?n.set(QFi,e.from.toISOString()):n.delete(QFi),e?.to?n.set($Fi,e.to.toISOString()):n.delete($Fi),n},{replace:!0})},[t]),c=(0,G.useCallback)(e=>{t(t=>{let n=new URLSearchParams(t);return Fxi(n,e),bxi(n),n},{replace:!0})},[t]),l=(0,G.useRef)(!1);return(0,G.useEffect)(()=>{if(l.current||(l.current=!0,Sxi(e)))return;let n=xxi();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)(lSi,{preset:r,filterTokens:a,onPresetChange:o,onFilterTokensChange:c,customRange:i,onCustomRangeChange:s,children:(0,K.jsx)(UFi,{children:(0,K.jsx)(tIi,{})})})}function tIi(){let{error:e}=Qxi(o9()),{isInMemory:t}=b7(),{data:n}=c$r(),{data:r}=g8(),{data:i}=o$r(),{data:a}=_8(),o=Axi({availableTags:n??[],availableEntityNames:r??[],availableServiceNames:i??[],availableEnvironments:a??[]});return e&&JP(e)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:B9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),(0,K.jsx)(jU,{variant:`fill`})]}):e&&YP(e)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:B9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),(0,K.jsx)(AU,{variant:`fill`,resource:`metrics`})]}):e?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:B9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load metrics`,descriptionSlot:e.message})]}):(0,K.jsx)(BFi,{filterFields:o,children:(0,K.jsxs)(`div`,{className:`grid content-start gap-4`,children:[t&&(0,K.jsx)(EA,{variant:`info`,title:`Metrics are not persisted`,children:(0,K.jsx)(EA.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)(nIi,{})]})})}function nIi(){let{openTraces:e,openLogs:t}=XFi(),n=kh.AGENT,r=LFi(),i=(0,K.jsx)(dCi,{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)(bCi,{onViewTraces:t=>e({rootEntityType:t}),onTimeRangeClick:t=>e({window:t})}),o=(0,K.jsx)(uwi,{onViewTraces:()=>e(),onAgentClick:t=>e({rootEntityType:n,entityName:t}),onModelClick:t=>e({model:t}),onThreadClick:t=>e({threadId:t})}),s=(0,K.jsx)(aCi,{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)(n9,{columns:2,children:[(0,K.jsx)(n9.Item,{children:s}),(0,K.jsx)(n9.Item,{children:i}),(0,K.jsx)(n9.Item,{children:a}),(0,K.jsx)(n9.Item,{children:(0,K.jsx)(Rwi,{onTimeRangeClick:e})})]}),(0,K.jsx)(zEi,{onRowClick:e})]}):(0,K.jsxs)(`div`,{className:`grid content-start gap-4 pb-6`,children:[s,(0,K.jsxs)(n9,{columns:2,children:[(0,K.jsx)(n9.Item,{children:i}),(0,K.jsx)(n9.Item,{children:a})]}),(0,K.jsxs)(n9,{columns:2,children:[(0,K.jsx)(n9.Item,{children:(0,K.jsx)(nwi,{onViewTraces:t=>e({rootEntityType:t}),onViewErrors:e=>t({rootEntityType:e,status:`error`}),onEntityClick:(t,n)=>e({rootEntityType:t,entityName:n})})}),(0,K.jsx)(n9.Item,{children:o})]}),(0,K.jsx)(xwi,{})]})}function rIi(){let{isCmsAvailable:e}=K3(),{paths:t}=gl();return e?(0,K.jsx)(Arr,{href:t.cmsPromptBlockCreateLink(),tooltip:`Create a prompt`,children:`New prompt`}):null}var H9=[sF(`/prompts`)],iIi=50,aIi=[`updatedAt`];function oIi(){let[e,t]=(0,G.useState)(``),[n,r]=(0,G.useState)(0),[i,a]=Hb(),{sort:o,onSortChange:s}=c7({searchParams:i,setSearchParams:a,allowedKeys:aIi}),{data:c,isLoading:l,error:u,isPlaceholderData:d}=zJr({page:n,perPage:iIi,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&&JP(u)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:H9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(jU,{variant:`fill`})]}):u&&YP(u)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:H9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(AU,{variant:`fill`,resource:`prompt blocks`})]}):u?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:H9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load prompt blocks`,descriptionSlot:u.message})]}):f.length===0&&!l&&n===0?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:H9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(EYr,{})]}):(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:H9}),headerActions:(0,K.jsx)(rIi,{}),actionRow:(0,K.jsx)(jq,{children:(0,K.jsx)(jq.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(zU,{onSearch:g,label:`Filter prompts`,placeholder:`Filter by name or description`})})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(TYr,{promptBlocks:f,isLoading:l,search:e,currentPage:n,hasMore:p,onNextPage:m,onPrevPage:h,updatedSort:o?.direction,onSortChange:_})]})}var sIi=[sF(`/resources`)],cIi=[{title:`Mastra APIs`,description:`Explore and test the available REST API endpoints with the interactive Swagger UI.`,icon:Pee,href:`/swagger-ui`,external:!1},{title:`Documentation`,description:`Read the official Mastra documentation for guides, references, and tutorials.`,icon:pn,href:`https://mastra.ai/en/docs`,external:!0},{title:`Github`,description:`Browse the source code, report issues, and contribute to the Mastra project.`,icon:Br,href:`https://github.com/mastra-ai/mastra`,external:!0},{title:`Community`,description:`Join the Mastra Discord community for help, discussion, and collaboration.`,icon:Qa,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:dr,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:An,href:`https://mastra.ai/contact?ref=studio`,external:!0}];function lIi(){return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:sIi}),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:cIi.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:m(`h-5 w-5 text-muted-foreground group-hover:text-info-indicator`,f)}),(0,K.jsx)(T,{as:`span`,variant:`subheading`,tone:`ink`,children:e.title}),e.external&&(0,K.jsx)(Br,{className:`ml-auto h-3.5 w-3.5 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 uIi(){let{isCmsAvailable:e}=K3(),{paths:t}=gl();return e?(0,K.jsx)(Arr,{href:t.cmsScorersCreateLink(),tooltip:`Create a scorer`,children:`New scorer`}):null}var U9=[sF(`/scorers`)];function dIi(){let{data:e={},isLoading:t,error:n}=eF(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)(`all`),[s,c]=(0,G.useState)();if(n&&JP(n))return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:U9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Scorers`}),(0,K.jsx)(jU,{variant:`fill`})]});if(n&&YP(n))return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:U9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Scorers`}),(0,K.jsx)(AU,{variant:`fill`,resource:`scorers`})]});if(n)return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:U9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Scorers`}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load scorers`,descriptionSlot:n.message})]});if(Object.keys(e).length===0&&!t)return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:U9}),headerActions:(0,K.jsx)(uIi,{}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Scorers`}),(0,K.jsx)(tHr,{})]});let l=a!==`all`||r!==``;return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:U9}),headerActions:(0,K.jsx)(uIi,{}),actionRow:(0,K.jsx)(rHr,{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)(eHr,{scorers:e,isLoading:t,search:r,sourceFilter:a,sort:s,onSortChange:(e,t)=>c({key:t,direction:e})})]})}var fIi=[`input`,`entity`],pIi={input:`Input`,entity:`Entity`};function mIi(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 hIi(){let[e,t]=(0,G.useState)(new Set),n=(0,G.useMemo)(()=>new Set(fIi.filter(t=>!e.has(t))),[e]);return{visibleColumns:n,columns:(0,G.useMemo)(()=>mIi(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 gIi({visibleColumns:e,toggleColumn:t}){return(0,K.jsxs)(mD,{children:[(0,K.jsx)(mD.Trigger,{asChild:!0,children:(0,K.jsx)(X,{icon:(0,K.jsx)(vr,{}),children:`Columns`})}),(0,K.jsxs)(mD.Content,{align:`end`,children:[(0,K.jsx)(mD.Label,{children:`Toggle columns`}),fIi.map(n=>(0,K.jsx)(mD.CheckboxItem,{checked:e.has(n),onClick:()=>t(n),children:pIi[n]},n))]})]})}var _Ii=[sF(`/scorers`),BLt],vIi=[`date`,`score`];function yIi(){let{scorerId:e}=Ab(),[t,n]=Hb(),r=t.get(`scoreId`)??void 0,[i,a]=(0,G.useState)(r),[o,s]=(0,G.useState)(!1),c=kb(),[l,u]=(0,G.useState)({value:`all`,label:`All Entities`,type:`ALL`}),{scorer:d,error:f}=uLt(e),p=hIi(),{data:m={},isLoading:h,error:g}=PP(),{isLoading:_,error:v}=sP({}),{sort:y,onSortChange:b}=c7({searchParams:t,setSearchParams:n,allowedKeys:vIi}),{data:x=[],isLoading:S,error:C,isFetchingNextPage:w,hasNextPage:T,setEndOfListElement:E}=lLt({scorerId:e,entityId:l?.value===`all`?void 0:l?.value,entityType:l?.type===`ALL`?void 0:l?.type}),D=(0,G.useMemo)(()=>yQ(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`;UC.error(`Error loading scorer: ${e}`)}},[f]),(0,G.useEffect)(()=>{if(g){let e=g instanceof Error?g.message:`Failed to load agents`;UC.error(`Error loading agents: ${e}`)}},[g]),(0,G.useEffect)(()=>{if(v){let e=v instanceof Error?v.message:`Failed to load workflows`;UC.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=JP(f)||JP(g)||JP(v),I=f&&YP(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)(y_i,{open:o,onOpenChange:s,initialScorerIds:[e],onSuccess:e=>void c(`/experiments/${e}`)}):null,H=B?(0,K.jsxs)(mD,{children:[(0,K.jsx)(mD.Trigger,{asChild:!0,children:(0,K.jsx)(X,{size:`icon-lg`,"aria-label":`Scorer actions menu`,children:(0,K.jsx)(Ar,{})})}),(0,K.jsx)(mD.Content,{align:`end`,className:`w-48`,children:(0,K.jsxs)(mD.Item,{onSelect:()=>void c(`/cms/scorers/${e}/edit`),children:[(0,K.jsx)(Lo,{}),` 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)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:_Ii}),actionRow:!(F||I||L)&&H?(0,K.jsx)(jq,{children:(0,K.jsx)(jq.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)(jU,{}):I?(0,K.jsx)(AU,{resource:`scorers`}):L?(0,K.jsx)(RC,{tone:`error`,titleSlot:`Failed to load scorer`,descriptionSlot:t}):(0,K.jsx)(XVr,{onRunExperiment:()=>s(!0)})}),V]})}return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:_Ii}),actionRow:(0,K.jsxs)(jq,{children:[(0,K.jsx)(jq.Start,{children:(0,K.jsx)(ZVr,{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)(jq.End,{children:[(0,K.jsx)(gIi,{visibleColumns:p.visibleColumns,toggleColumn:p.toggleColumn}),(0,K.jsx)(X,{variant:`primary`,onClick:()=>s(!0),icon:(0,K.jsx)(Ho,{}),children:`New experiment`}),H]})]}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(YVr,{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 bIi=[{value:`system`,label:`System`,icon:(0,K.jsx)(so,{})},{value:`light`,label:`Light`,icon:(0,K.jsx)(Ete,{})},{value:`dark`,label:`Dark`,icon:(0,K.jsx)(lo,{})}];function xIi(e,t){if(e.some(e=>e.value===t))return t;let[n]=e;return n?n.value:`system`}var SIi=({value:e,onChange:t,options:n=bIi,size:r=`md`,"aria-label":i=`Theme`,...a})=>{let{theme:o,setTheme:s}=B(),c=e??o,l=t??s,u=xIi(n,c);return(0,K.jsx)(udr,{...a,"aria-label":i,iconOnly:!0,size:r===`xs`?`sm`:r,value:u,onValueChange:l,children:n.map(e=>(0,K.jsx)(ddr,{value:e.value,"aria-label":e.label,children:e.icon},e.value))})};function CIi(e){return Object.fromEntries(e.filter(e=>e.name.trim()).map(e=>[e.name.trim(),e.value]))}function wIi(e,t){return e.baseUrl.trim()===t.baseUrl.trim()&&e.apiPrefix.trim()===(t.apiPrefix??``).trim()&&JSON.stringify(CIi(e.headers))===JSON.stringify(t.headers)}function TIi(e){return e===0?`No request headers`:e===1?`1 request header`:`${e} request headers`}function EIi({initialConfig:e}){let{setConfig:t}=YC(),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=!wIi(i,e),l=(e,t)=>a(n=>({...n,headers:n.headers.map(n=>n.id===e?{...n,...t}:n)}));function u(e){e.preventDefault(),i.baseUrl.trim()?(t({baseUrl:i.baseUrl.trim(),apiPrefix:i.apiPrefix.trim()||void 0,headers:CIi(i.headers)}),UC.success(`Connection saved`)):s(`Enter the server URL`)}function d(){a(r()),s(void 0)}return(0,K.jsx)(`form`,{onSubmit:u,onReset:d,noValidate:!0,children:(0,K.jsxs)(_$,{children:[(0,K.jsx)(g$,{label:`Mastra instance URL`,description:`The server this studio talks to.`,errorMsg:o,children:(0,K.jsx)(ZM,{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)(g$,{label:`API prefix`,description:`Path in front of every API route.`,children:(0,K.jsx)(ZM,{name:`apiPrefix`,value:i.apiPrefix,placeholder:`/api (default)`,spellCheck:!1,onChange:e=>a(t=>({...t,apiPrefix:e.target.value}))})}),(0,K.jsx)(Sdr,{action:(0,K.jsx)(X,{type:`button`,size:`sm`,icon:(0,K.jsx)(Ho,{}),onClick:()=>a(e=>({...e,headers:[...e.headers,{id:n.current++,name:``,value:``}]})),children:`Add header`}),children:TIi(i.headers.length)}),i.headers.map(e=>(0,K.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(ZM,{"aria-label":`Header name`,value:e.name,placeholder:`Authorization`,spellCheck:!1,onChange:t=>l(e.id,{name:t.target.value})}),(0,K.jsx)(ZM,{"aria-label":e.name?`Value of ${e.name}`:`Header value`,value:e.value,placeholder:`Bearer <token>`,spellCheck:!1,onChange:t=>l(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)(xc,{})})]},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 DIi(){let{baseUrl:e,apiPrefix:t,headers:n}=YC(),r=JSON.stringify([e,t??``,n]);return(0,K.jsxs)(v$,{children:[(0,K.jsx)(y$,{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)(EIi,{initialConfig:{baseUrl:e,apiPrefix:t,headers:n}},r)]})}var OIi=()=>(0,K.jsx)(uw,{children:(0,K.jsxs)(bdr,{title:`Settings`,children:[(0,K.jsxs)(v$,{children:[(0,K.jsx)(y$,{info:`Stored in this browser.`,children:`General`}),(0,K.jsx)(_$,{children:(0,K.jsx)(g$,{label:`Theme`,description:`Color scheme for the interface.`,children:(0,K.jsx)(SIi,{})})})]}),(0,K.jsx)(DIi,{})]})});function kIi(){let[e]=Hb(),t=kb(),n=e.get(`redirect`)||`/`;return(0,K.jsx)(mMi,{redirectUri:n,onSuccess:()=>{n.startsWith(`http`)?window.location.href=n:t(n,{replace:!0})},initialMode:`signup`})}function AIi({current:e,features:t}){let n=A6r(),r=j6r(),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 jIi=[`traces`,`spans`],MIi={traces:{icon:(0,K.jsx)(oF,{}),label:`Traces`},spans:{icon:(0,K.jsx)(zn,{}),label:`Spans`},threads:{icon:(0,K.jsx)(eo,{}),label:`Threads`}};function NIi({current:e,views:t=jIi,onViewChange:n}){return(0,K.jsx)(`nav`,{"aria-label":`Observability views`,children:(0,K.jsx)(CA,{value:e,defaultTab:e,onValueChange:n,children:(0,K.jsx)(SA,{variant:`pill-ghost`,children:t.map(e=>(0,K.jsxs)(wA,{value:e,children:[(0,K.jsx)(TC,{size:`xs`,children:MIi[e].icon}),(0,K.jsx)(T,{variant:`caption`,className:`text-inherit`,children:MIi[e].label})]},e))})})})}function PIi(){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)(dw,{className:`h-control-md w-20 rounded-full`}),(0,K.jsx)(dw,{className:`h-control-md w-20 rounded-full`})]})}function FIi({current:e,features:t,onViewChange:n,breadcrumbs:r,children:i}){let{views:a,isLoading:o,showSwitch:s}=AIi({current:e,features:t}),[c,l]=(0,G.useState)(null),u=Gsi(),d;return o?d=(0,K.jsx)(PIi,{}):s&&(d=(0,K.jsx)(NIi,{current:e,views:a,onViewChange:n})),(0,K.jsx)(uw,{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)(eui.Provider,{value:c??void 0,children:i})})}function IIi({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)(Zc,{"aria-label":`Loading storage capabilities`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:`Loading storage capabilities`})]}):(0,K.jsx)(RC,{variant:`fill`,titleSlot:r,descriptionSlot:i})]})}var LIi={refetchInterval:({state:e})=>usi(e.error),refetchOnWindowFocus:!1};function RIi(e){let[t,n]=(0,G.useState)(()=>new URLSearchParams);return e||{searchParams:t,setSearchParams:e=>n(t=>typeof e==`function`?e(t):e)}}function zIi(e,{sortFields:t,defaultDatePreset:n=Qsi}={}){let{searchParams:r,setSearchParams:i}=RIi(e),a=JSON.stringify(ici(r,n)),o=JSON.stringify(oci(r)),{datePreset:s,dateFrom:c,dateTo:l}=(0,G.useMemo)(()=>ici(r,n),[a]),{tokens:u,groups:d}=(0,G.useMemo)(()=>oci(r),[o]),f=cci(r,t??Xsi),p=(0,G.useMemo)(()=>({field:f.field,direction:f.direction}),[f.field,f.direction]),m=c?.getTime(),h=l?.getTime(),g=(0,G.useMemo)(()=>{let e=new Date,t=f8r(s,m===void 0?void 0:new Date(m),h===void 0?void 0:new Date(h),e);return g1r(t.dateFrom,t.dateTo,e)},[s,m,h]),_=(0,G.useRef)(null);(0,G.useLayoutEffect)(()=>{_.current=null},[r]);let v=e=>{let t=_.current??r,n=new URLSearchParams(t);e(n),n.toString()!==t.toString()&&(_.current=n,i(n,{replace:!0}))},y=e=>v(t=>aci(t,e(ici(t,n)),n)),b=(0,G.useRef)(void 0),x=e=>{b.current=void 0,y(e)},S=e=>x(t=>e===`custom`?{...t,datePreset:e}:{datePreset:e}),C=(e,t)=>x(n=>n.datePreset===`custom`?t===`from`?{...n,dateFrom:e}:{...n,dateTo:e}:n),w=(e,t)=>x(n=>n.datePreset===`custom`?{...n,dateFrom:e,dateTo:t}:n),T=(e,t)=>y(n=>(b.current=Fsi(b.current,n,e,t),{datePreset:`custom`,dateFrom:e,dateTo:t})),E=e=>y(t=>{let n=Isi(b.current,t);return b.current=void 0,n??{datePreset:e}}),D=(e,t)=>v(n=>sci(n,{tokens:e,groups:t})),O=e=>v(t=>lci(t,e)),k=u.length>0||d.length>0;return{datePreset:s,dateFrom:c,dateTo:l,timeRange:g,rolling:l===void 0,tokens:u,groups:d,sort:p,setSort:O,onDatePresetChange:S,onDateChange:C,onDateRangeChange:w,onZoom:T,onDateReset:E,onFiltersChange:D,contentFiltersApplied:k,filtersApplied:k||s!==n}}function BIi(e){return[`observability-list-head`,...e]}function VIi(e){let t=hy([e]),[n,r]=(0,G.useState)();return{anchorTo:n?.selectionHash===t?n.to:void 0,reanchor:()=>r({selectionHash:t,to:new Date().toISOString()})}}var HIi=()=>({rows:[],watermark:void 0});function UIi({queryKey:e,fetchHead:t,getId:n,getEndedAt:r,enabled:i,since:a,limit:o=50,maxRows:s=500,interval:c=osi,onOverflow:l}){let u=dy(),d=BIi(e),{data:f}=Ey({queryKey:d,queryFn:async()=>{let e=u.getQueryData(d)??HIi(),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?.(),HIi();let m=c.length>0?Math.max(e.watermark??-1/0,...c):e.watermark;return{rows:[...f.values()],watermark:m}},initialData:HIi,staleTime:1/0,enabled:i,refetchInterval:e=>!csi(e.state.error)&&c,refetchOnWindowFocus:!1,refetchOnReconnect:!1,retry:!1});return{headRows:f.rows}}function WIi(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 GIi(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),WIi(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 KIi={traces:`Traces`,spans:`Spans`,threads:`Threads`};function qIi({current:e,isLoading:t,showSwitch:n}){if(!(t||n||e===`traces`))return KIi[e]}function JIi(e){let t=e.get(`traceId`),n=e.get(`spanId`);return t&&n?{traceId:t,spanId:n}:void 0}function YIi(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 XIi({traceId:e,spanId:t}){return new URLSearchParams({traceId:e,spanId:t})}function ZIi(e){return e.get(`threadId`)??void 0}function QIi(e,t){let n=new URLSearchParams(e);return t?n.set(`threadId`,t):n.delete(`threadId`),n}var $Ii=e=>`${e.traceId}:${e.spanId}`;function eLi(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 tLi({query:e,rolling:t,autoRefetch:n=!0,limit:r,enabled:i=!0}){let a=Y(),{anchorTo:o,reanchor:s}=VIi(e),c=(0,G.useMemo)(()=>o?{...e,timeRange:{...e.timeRange,to:o}}:e,[e,o]),l=j$r({query:c,limit:r,enabled:i,queryOptions:LIi}),{headRows:u}=UIi({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:$Ii,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&&GIi(f,u,{getId:$Ii,compare:eLi(d),hasNextPage:l.hasNextPage}),[f,u,d,l.hasNextPage]);return{...l,spans:p}}function nLi(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 rLi({timeRange:e,where:t,onZoom:n}){let r=N6r(),i=(0,G.useMemo)(()=>({timeRange:e,...t?{where:t}:{},interval:nei(e).interval,measures:[...J9r],limit:1}),[e,t]),a=!r.enabled||rei(e),{data:o,isLoading:s,isError:c,isPlaceholderData:l}=p$r({request:i,enabled:!a,queryOptions:{placeholderData:vy}}),u=(0,G.useMemo)(()=>cei(o?.rows??[],e),[o,e]);return a?null:(0,K.jsx)(U9r,{label:`Spans over time`,resourceLabel:`Spans`,buckets:u,isLoading:s,isError:c,isUpdating:l,onZoom:n&&(t=>n(lei(u,t,e)))})}var iLi=[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`],aLi=[];function oLi({timeRange:e}){let t=Y(),{data:n}=n5(),r=n?.capabilities.spanQueryContextFields??!1,i=n?.capabilities.traceQueryTimeToFirstChunk??!1,a=n?.capabilities.traceQueryTimeToFirstToken??!1,o=n?.capabilities.spanQueryOutcomeFields??!1,s=n?.capabilities.spanQueryModelFields??!1,{data:c=aLi}=g8(),{data:l=aLi}=_8();return(0,G.useMemo)(()=>[R5r,...Uci({withContextFields:r,withTimeToFirstChunk:i,withTimeToFirstToken:a,withOutcomeFields:o,withModelFields:s,entityNames:c,environments:l,valueSuggestions:n=>X$r(t,e,`spans`,n)})],[r,i,a,o,s,c,l,t,e])}function sLi({tokens:e,groups:t,onFiltersChange:n}){let r=(0,G.useMemo)(()=>m0r(e),[e]),i=(0,G.useMemo)(()=>{let e=_0r([],t);return{...e,nodes:[d5,...r,...e.nodes]}},[r,t]),a=(0,G.useCallback)(e=>{let t=y0r({...e,nodes:e.nodes.filter(e=>o8(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(o8);a({...i,nodes:[...n,o,...s]})},[r,i,a])}}var cLi=e=>e;function lLi({datePreset:e,dateFrom:t,dateTo:n,minDate:r,timeRange:i,tokens:a,groups:o,onDatePresetChange:s,onDateChange:c,onDateRangeChange:l,onDateReset:u,onFiltersChange:d,describeSuggestionsError:f,disabled:p}){let m=oLi({timeRange:i}),{filterBarValue:h,onFilterBarChange:g}=sLi({tokens:a,groups:o,onFiltersChange:d});return(0,K.jsxs)(f5,{fields:m,operators:H1r,value:h,onValueChange:g,createItemId:cLi,describeSuggestionsError:f,maxDepth:3,"aria-label":`Span filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(f5.Chips,{renderChip:i=>i.fieldId===`timeRange`?(0,K.jsx)(f5.TimeRange,{preset:e,onPresetChange:s,dateFrom:t,dateTo:n,minDate:r,onDateChange:c,onDateRangeChange:l,disabled:p,presets:iLi,defaultPreset:i5.datePreset,onReset:u&&(()=>u(i5.datePreset))}):(0,K.jsx)(f5.Chip,{item:i})}),(0,K.jsx)(f5.Input,{placeholder:`Filter spans`})]})}function uLi({selection:e,onSelectionChange:t,renderPanel:n,urlState:r}){let i=zIi(r,{sortFields:Zsi}),{timeRange:a,tokens:o,groups:s}=i,c=jsi({scope:`spans`}),{data:l,isLoading:u}=n5(),d=l?.capabilities.spanQueryContextFields??!1,f=l?.capabilities.traceQueryTimeToFirstChunk??!1,p=l?.capabilities.traceQueryTimeToFirstToken??!1,m=l?.capabilities.spanQueryOutcomeFields??!1,h=l?.capabilities.spanQueryModelFields??!1,g=(0,G.useMemo)(()=>u?c.preferences:$3r(c.preferences,{withTimeToFirstChunk:f,withTimeToFirstToken:p}),[c.preferences,u,f,p]),_=(0,G.useMemo)(()=>{let e=[`startedAt`];return f&&l?.capabilities.traceQueryTimeToFirstChunkSort&&Q8(g,`timeToFirstChunk`)&&e.push(`timeToFirstChunkMs`),p&&l?.capabilities.traceQueryTimeToFirstTokenSort&&Q8(g,`timeToFirstToken`)&&e.push(`timeToFirstTokenMs`),e},[l,f,p,g]),v=_.includes(i.sort.field)?i.sort:{field:`startedAt`,direction:`desc`},{field:y,direction:b}=v,x=(0,G.useMemo)(()=>Kci(o,s,{withContextFields:d,withOutcomeFields:m,withModelFields:h,withTimeToFirstChunk:f,withTimeToFirstToken:p}),[o,s,d,m,h,f,p]),{spans:S,hasNextPage:C,isFetchingNextPage:w,setEndOfListElement:T,isLoading:E,isError:D,error:O}=tLi({query:(0,G.useMemo)(()=>({timeRange:a,orderBy:[{field:y,direction:b}],...x?{where:x}:{}}),[a,y,b,x]),rolling:i.rolling}),k=(0,G.useMemo)(()=>(S??[]).map(nLi),[S]),A=(0,G.useMemo)(()=>k.flatMap(e=>e.spanId?[{traceId:e.traceId,spanId:e.spanId}]:[]),[k]),j=n=>{n.spanId&&t(e?.traceId===n.traceId&&e.spanId===n.spanId?void 0:{traceId:n.traceId,spanId:n.spanId})},M=!E&&!D&&k.length===0&&!i.contentFiltersApplied&&!e;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Spans`}),(0,K.jsx)(C6r,{toolbar:(0,K.jsxs)(K.Fragment,{children:[r&&(0,K.jsx)(sui,{page:`spans`,...r,columns:c}),(0,K.jsxs)(jq,{children:[(0,K.jsx)(jq.Start,{children:(0,K.jsx)(lLi,{datePreset:i.datePreset,dateFrom:i.dateFrom,dateTo:i.dateTo,timeRange:a,tokens:o,groups:s,onDatePresetChange:i.onDatePresetChange,onDateChange:i.onDateChange,onDateRangeChange:i.onDateRangeChange,onDateReset:i.onDateReset,onFiltersChange:i.onFiltersChange,disabled:E})}),(0,K.jsx)(jq.End,{children:(0,K.jsx)(B6r,{scope:`spans`,value:c.preferences,onChange:c.setPreferences})})]})]}),chart:(0,K.jsx)(rLi,{timeRange:a,where:x,onZoom:({from:e,to:t})=>i.onZoom(e,t)}),error:D?(0,K.jsx)(X8,{error:O,resource:`spans`,errorTitle:`Failed to load spans`}):void 0,empty:M?(0,K.jsx)(j3r,{resource:`spans`,datePreset:i.datePreset,dateFrom:i.dateFrom,dateTo:i.dateTo}):void 0,children:(0,K.jsx)(Wti,{listId:`all-spans`,traces:k,columnPreferences:g,isLoading:E,isFetchingNextPage:w,hasNextPage:C,setEndOfListElement:T,filtersApplied:i.filtersApplied,resource:`spans`,isBranchesMode:!0,sort:v,sortableFields:_,onSortChange:i.setSort,featuredTraceId:e?.traceId,featuredSpanId:e?.spanId,onTraceClick:j})}),n({selection:e,spans:A,onSelect:t,onClose:()=>t(void 0)})]})}function dLi({selection:e,spans:t,onSelect:n,onClose:r,onShowTrace:i}){let{data:a,isLoading:o}=v8({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)(cai,{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 fLi({selection:e,spans:t,onSelect:n,onClose:r,onShowTrace:i}){let a=fE();S3r(e?`${e.traceId}:${e.spanId}`:void 0,r);let o=e?(0,K.jsx)(dLi,{selection:e,spans:t,onSelect:n,onClose:r,onShowTrace:i}):null;return a?(0,K.jsx)(m$,{open:!!e,onClose:r,title:`Span details`,children:o}):o?(0,K.jsx)(q8,{owner:`span-detail`,children:(0,K.jsx)(m$,{variant:`inline`,title:`Span details`,children:o})}):null}function pLi(){let{enabled:e,isLoading:t}=A6r(),n=kb(),[r,i]=Hb();return(0,K.jsx)(IIi,{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)(uLi,{urlState:{searchParams:r,setSearchParams:i},selection:JIi(r),onSelectionChange:e=>i(t=>YIi(t,e),{replace:!0}),renderPanel:e=>(0,K.jsx)(fLi,{...e,onShowTrace:e=>n(`/traces?${XIi(e)}`)})})})}async function mLi(){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 hLi({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 gLi({repoOrSlug:e,owner:t}){let{templates:n}=await mLi(),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 hLi({repo:e,owner:t});if(r)return r;throw Error(`Template ${e} not found`)}return r}async function _Li({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 vLi=({queryOptions:e}={})=>Ey({queryKey:[`mastra-templates`],queryFn:mLi,...e}),yLi=({repoOrSlug:e,owner:t,queryOptions:n})=>Ey({queryKey:[`template-repo`,e,t],queryFn:()=>gLi({repoOrSlug:e,owner:t}),...n}),bLi=({repo:e,owner:t,branch:n,queryOptions:r})=>Ey({queryKey:[`template-repo-env-vars`,e,t,n],queryFn:()=>_Li({repo:e,owner:t,branch:n}),...r}),xLi=({queryOptions:e}={})=>{let t=Y();return Ey({queryKey:[`agent-builder-workflow`],queryFn:async()=>await t.getAgentBuilderAction(`merge-template`).details(),...e})},SLi=({queryOptions:e}={})=>{let t=Y();return Oy({mutationFn:async({runId:e})=>await t.getAgentBuilderAction(`merge-template`).createRun({runId:e}),...e})},CLi=({queryOptions:e}={})=>{let t=Y();return Oy({mutationFn:async({runId:e})=>await t.getAgentBuilderAction(`merge-template`).runById(e),...e})},wLi=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)},TLi=(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=wLi(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=wLi(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}},ELi=(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)}},DLi=(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}=TLi(a,s,e);s=c,r(c),(a.runId||i||t)&&ELi(a.runId||i||t,c)}}catch(t){console.error(`💥 [processStream] Error processing template installation stream:`,t);let{newState:n}=TLi({type:`error`,payload:{error:t instanceof Error?t.message:`Unknown error`}},s,e);r(n)}finally{a(!1),o.releaseLock()}}}},OLi=({workflowInfo:e,queryOptions:t}={})=>{let n=Y(),{streamResult:r,isStreaming:i,processStream:a}=DLi(e);return{streamInstall:Oy({mutationFn:async({inputData:e,selectedModel:t,runId:r})=>{for(let i=1;i<=3;i++)try{let i=n.getAgentBuilderAction(`merge-template`),o=new Il;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}},kLi=({workflowInfo:e,queryOptions:t}={})=>{let n=Y(),{streamResult:r,isStreaming:i,processStream:a}=DLi(e);return{observeInstall:Oy({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 ALi(e){return e.replace(/\/$/,``).split(`/`).pop()}function jLi({templates:e,linkComponent:t,className:n,isLoading:r}){let i=t||`a`;return r?(0,K.jsx)(`div`,{className:m(`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:m(`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:m(Wb,`grid w-full grid-cols-[1fr_auto] overflow-hidden rounded-lg state-layer`),children:[(0,K.jsxs)(i,{to:`/templates/${e.slug}`,className:m(`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:m(`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:m(QC,f),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:m(`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)(tF,{}),` `,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)(aF,{}),` `,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)(go,{}),` `,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)(Lc,{}),` `,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)(nF,{}),` `,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:m(`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:m(`flex items-center gap-2 rounded bg-sidebar px-2 py-1`,mKe,QC,f),children:[(0,K.jsx)(pQ,{}),` `,ALi(e.githubUrl)]})})})]},e.slug)})})}function MLi({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:i,onProviderChange:a,searchTerm:o,onSearchChange:s,onReset:c,className:l,isLoading:u}){return u?(0,K.jsxs)(`div`,{className:m(`flex h-[6.5rem] items-center gap-5`,`[&>div]:h-8 [&>div]:w-48 [&>div]:animate-pulse [&>div]:bg-card`,l),children:[(0,K.jsx)(`div`,{}),` `,(0,K.jsx)(`div`,{}),` `,(0,K.jsx)(`div`,{})]}):(0,K.jsxs)(`div`,{className:m(`sticky top-0 mx-auto flex flex-wrap gap-1.5 bg-background py-5`,l),children:[(0,K.jsx)(RU,{label:`Search templates`,placeholder:`Search templates`,size:`sm`,value:o,onValueChange:s}),(0,K.jsxs)(WA,{value:t,onValueChange:i,children:[(0,K.jsx)(KA,{"aria-label":`Filter by tag`,size:`sm`,className:`w-auto`,children:(0,K.jsx)(GA,{placeholder:`Select an option`})}),(0,K.jsx)(qA,{children:e.map(e=>(0,K.jsx)(JA,{value:e.value,children:e.label},e.value))})]}),(0,K.jsxs)(WA,{value:r,onValueChange:a,children:[(0,K.jsx)(KA,{"aria-label":`Filter by provider`,size:`sm`,className:`w-auto`,children:(0,K.jsx)(GA,{placeholder:`Select an option`})}),(0,K.jsx)(qA,{children:n.map(e=>(0,K.jsx)(JA,{value:e.value,children:e.label},e.value))})]}),c&&(0,K.jsx)(S3,{onClick:c})]})}var NLi=[{id:`templates`,label:`Templates`}];function PLi(){let{data:e,isLoading:t}=vLi(),{templates:n,tags:r,providers:i}=e??{templates:[],tags:[],providers:[]},[a,o]=(0,G.useState)(`all`),[s,c]=(0,G.useState)(`all`),[l,u]=(0,G.useState)(``),d=[{value:`all`,label:`Any tag`}];(r||[]).forEach(e=>{d.push({value:e,label:e})});let f=[{value:`all`,label:`Any provider`}];(i||[]).forEach(e=>{f.push({value:e,label:e})});let p=(e,t)=>{t===`tag`?o(e):t===`provider`&&c(e)},h=e=>{u(e)},g=()=>{o(`all`),c(`all`),u(``)},_=n.filter(e=>!(l&&!e.title.toLowerCase().includes(l)&&!e.description.toLowerCase().includes(l)||a!==`all`&&!e.tags.includes(a)||s!==`all`&&!e.supportedProviders.includes(s))),v=l||a!==`all`||s!==`all`;return(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:NLi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Templates`}),(0,K.jsx)($C,{children:(0,K.jsxs)(B1e,{children:[(0,K.jsx)(TC,{children:(0,K.jsx)(Eo,{})}),`Templates`]})}),(0,K.jsxs)(`div`,{className:m(`z-10 h-full w-full overflow-y-auto px-5 pb-12`),children:[(0,K.jsx)(MLi,{selectedTag:a,onTagChange:e=>p(e,`tag`),tagOptions:d,selectedProvider:s,onProviderChange:e=>p(e,`provider`),providerOptions:f,searchTerm:l,onSearchChange:h,onReset:v?g:void 0,className:`max-w-[80rem]`,isLoading:t}),(0,K.jsx)(jLi,{templates:_,linkComponent:Vb,className:`mx-auto max-w-[80rem]`,isLoading:t})]})]})}function FLi({children:e,className:t}){return(0,K.jsx)(`div`,{className:m(`transition-height mt-12 rounded-lg border border-border px-4 py-5 lg:min-h-[25rem] lg:px-12`,t),children:e})}function ILi({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)(Cc,{className:`text-warning-foreground`}),title:`Template Installed with Warnings`}:{icon:(0,K.jsx)(Gr,{}),title:`Template Installation Failed`};return(0,K.jsxs)(FLi,{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:m(`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)(Dw,{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:m(`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)(Dw,{className:`text-caption wrap-break-word whitespace-pre-wrap`,code:n})})]})]})}function LLi({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:i,handleInstallTemplate:a,handleVariableChange:o,isLoadingEnvVars:s,isInstalling:c,defaultModelProvider:l,defaultModelId:u,onModelUpdate:d}){return(0,K.jsx)(FLi,{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:m(`flex items-center gap-2`,`[&_svg]:h-[1.2em] [&_svg]:opacity-70 [&>svg]:w-[1.2em]`),children:[`Install Template `,(0,K.jsx)(wo,{})]}),(0,K.jsxs)(fA,{orientation:`horizontal`,children:[(0,K.jsx)(mA,{children:`Template AI Model Provider`}),(0,K.jsx)(Oyt,{className:`flex-1`,children:(0,K.jsxs)(WA,{name:`template-provider`,value:t,onValueChange:n,children:[(0,K.jsx)(KA,{size:`md`,children:(0,K.jsx)(GA,{placeholder:`Select`})}),(0,K.jsx)(qA,{children:e.map(e=>(0,K.jsx)(JA,{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:m(`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)(Zc,{}),(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)(fA,{className:`w-full`,children:[(0,K.jsx)(mA,{className:`sr-only`,children:`Key`}),(0,K.jsx)(ZM,{name:`env-${e}`,value:e,disabled:!0,className:`w-full`})]}),(0,K.jsxs)(fA,{invalid:i.includes(e),className:`w-full`,children:[(0,K.jsx)(mA,{className:`sr-only`,children:`Value`}),(0,K.jsx)(ZM,{name:e,value:t,onChange:o,autoComplete:`off`,className:`w-full`}),(0,K.jsx)(gA,{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)(t3r,{defaultProvider:l||``,defaultModel:u||``,updateModel:d||(()=>Promise.resolve({message:`Updated`})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:`Provider`})]})]}),t&&!s&&(0,K.jsx)(X,{className:m(`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||!l||!u||i.length>0||c,children:c?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Zc,{className:`h-4 w-4`}),` Installing...`]}):(0,K.jsxs)(K.Fragment,{children:[`Install `,(0,K.jsx)(Ht,{})]})})]})})}function RLi({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:m(`flex items-center gap-3`,`[&>svg]:h-[1.2em] [&>svg]:w-[1.2em] [&>svg]:opacity-50`,{"[&>svg]:opacity-20":r}),children:[(0,K.jsx)(Eo,{}),(0,K.jsx)(`h2`,{className:m({"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:m(`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:m(`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)(Xi,{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)(ki,{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)(uZ,{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:m(`text-muted-foreground hover:text-foreground`,`mt-auto flex items-center gap-2`),children:[(0,K.jsx)(pQ,{}),(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:n?.split(`/`)?.pop()})]})]}),i&&(0,K.jsx)(a3r,{data:i,labelsAreHidden:!0,isLoading:r})]})]})}function zLi(e){switch(e){case`running`:return(0,K.jsx)(Zc,{size:`sm`,"aria-hidden":!0});case`success`:return(0,K.jsx)(Bn,{"aria-hidden":!0});case`failed`:return(0,K.jsx)(Vc,{"aria-hidden":!0});default:return null}}function BLi(){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 VLi({status:e,variant:t}){return t===`plain`?(0,K.jsx)(`span`,{className:m(`flex size-4 items-center justify-center self-center [&>svg]:size-4`,b.colors,{"[&>svg]:text-success-indicator":e===`success`,"[&>svg]:text-destructive-foreground":e===`failed`}),children:e===`pending`?(0,K.jsx)(BLi,{}):zLi(e)}):(0,K.jsx)(`span`,{className:m(`flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none`,b.colors,b.transform,{"[&>svg]:text-success-indicator":e===`success`,"[&>svg]:text-destructive-foreground":e===`failed`,"border border-dashed border-placeholder":e===`pending`,"[&>svg]:size-4":e!==`running`,"bg-success-subtle":e===`success`,"bg-destructive-subtle":e===`failed`,"scale-110":e===`success`||e===`failed`}),children:zLi(e)})}function HLi({step:e,isActive:t,position:n,variant:r=`default`}){let i=t||e.status===`success`?`ink`:`muted`;return(0,K.jsxs)(`div`,{className:m(`grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none`,b.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:m(`flex min-w-6 justify-end`,b.colors),children:[n,`.`]}),(0,K.jsxs)(`div`,{className:`min-w-0`,children:[(0,K.jsx)(T,{as:`h4`,tone:i,className:b.colors,children:e.title}),e.description&&(0,K.jsx)(T,{tone:`faint`,className:m(`-mt-0.5`,{truncate:r===`plain`}),children:e.description})]})]}),(0,K.jsx)(VLi,{status:e.status,variant:r})]})}function ULi({currentStep:e,steps:t=[],className:n}){return(0,K.jsx)(`div`,{className:m(n),children:t.map((t,n)=>(0,K.jsx)(HLi,{step:t,isActive:e?.id===t.id,position:n+1},t.id))})}function WLi({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:m(`relative flex h-8 items-center justify-end`,b.colors,{"bg-success-subtle":t.status===`success`&&e?.[n-1]?.status===`success`}),children:(0,K.jsx)(`div`,{className:m(`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`,b.colors,b.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)(Zc,{}):n+1})},t.id))}),(0,K.jsxs)(`div`,{className:m(`text-center text-caption text-muted-foreground`,b.colors),children:[n,` of `,t,` steps completed`]})]})}var GLi=(0,G.createContext)(3);function KLi({title:e,description:t,action:n,done:r,className:i,children:a}){let o=(0,G.useContext)(GLi);return(0,K.jsxs)(`li`,{className:m(`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:m(`flex size-6 shrink-0 items-center justify-center rounded-full`,b.colors,r?`bg-success-indicator/18 text-success-indicator`:`bg-fill text-foreground`),children:r?(0,K.jsx)(Bn,{className:`size-3.5`,"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 qLi({headingLevel:e=3,className:t,children:n}){return(0,K.jsx)(GLi.Provider,{value:e,children:(0,K.jsx)(`ol`,{className:m(`flex flex-col [counter-reset:ds-step]`,t),children:n})})}Object.assign(qLi,{Step:KLi});function JLi({name:e,streamResult:t,runId:n,workflowInfo:r}){let i=t?.phase||`initializing`,a=t?.payload?.workflowState,o=t?.payload?.currentStep,s=t?.error,c=a?.steps||{},l=Object.keys(c).length>0,u=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,d=Object.entries(c).filter(([e,t])=>u(e)),f=d.length,p=()=>{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=d.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)(FLi,{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:p()}),(t?.runId||n)&&(0,K.jsxs)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`mt-2`,children:[`Run ID: `,t?.runId??n]})]}),l&&f>0&&![`error`].includes(i)&&(0,K.jsx)(`div`,{className:`mx-auto w-full max-w-[30rem] px-4`,children:(0,K.jsx)(WLi,{steps:h})}),s&&i===`error`&&(0,K.jsxs)(`div`,{className:m(`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)(xo,{}),(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:s||`Something went wrong`})]}),l&&(0,K.jsx)(ULi,{steps:h,currentStep:o,className:`pb-4`}),!l&&i===`initializing`&&(0,K.jsxs)(`div`,{className:m(`text-muted-foreground`,`grid justify-items-center gap-4 text-center`),children:[(0,K.jsx)(Zc,{}),(0,K.jsx)(T,{as:`p`,variant:`body`,children:`This may take some time...`})]})]})}function YLi({name:e,installedEntities:t}){return(0,K.jsxs)(FLi,{className:m(`grid content-center items-center justify-items-center gap-4`,`[&>svg]:h-8 [&>svg]:w-8`),children:[(0,K.jsx)(wo,{}),(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)(a3r,{data:t})]})}function XLi(){let{templateSlug:e}=Ab(),t=[{id:`templates`,label:`Templates`,to:`/templates`},{id:`template`,label:LLt(e)}],[n,r]=Hb(),[i,a]=(0,G.useState)(``),[o,s]=(0,G.useState)(``),[c,l]=(0,G.useState)(``),[u,d]=(0,G.useState)({}),[f,p]=(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}=yLi({repoOrSlug:e,owner:`mastra-ai`}),k=`1.83.0`.includes(`beta`)??!1?`beta`:`main`,{data:A,isLoading:j}=bLi({repo:D?.githubUrl?new URL(D.githubUrl).pathname.split(`/`)[2]:`template-${e}`,owner:`mastra-ai`,branch:k}),{data:M,isLoading:N}=xLi(),{mutateAsync:P,isPending:F}=SLi(),{mutateAsync:I}=CLi(),{streamInstall:L,streamResult:R,isStreaming:z}=OLi({workflowInfo:M}),{observeInstall:B,streamResult:V,isStreaming:H}=kLi({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)(aF,{})},{key:`agents`,label:`Agents`,value:D?.agents?.length?D.agents.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(tF,{})},{key:`workflows`,label:`Workflows`,value:D?.workflows?.length?D.workflows.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(Lc,{})},{key:`providers`,label:`Providers`,value:D?.supportedProviders?.length?D.supportedProviders.join(`, `):`n/a`,icon:(0,K.jsx)(Dn,{})},{key:`tags`,label:`Tags`,value:D?.tags?.length?D.tags.join(`, `):`n/a`,icon:(0,K.jsx)(Zs,{})}],U=[{...te[0]},{...te[1]},{...te[2]}].filter(e=>e.value!==`n/a`);return(0,G.useEffect)(()=>{A&&d(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)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(`div`,{className:m(`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)(RLi,{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)(JLi,{name:D.title,streamResult:H?V:R,runId:y,workflowInfo:M}),_&&(0,K.jsx)(YLi,{name:D.title,installedEntities:U,linkComponent:Vb}),h&&(0,K.jsx)(ILi,{errorMsg:h,validationErrors:T.length>0?T:R?.validationResults?.errors||V?.validationResults?.errors}),!z&&!H&&!_&&!h&&(0,K.jsx)(LLi,{providerOptions:ee,selectedProvider:i,onProviderChange:e=>{a(e)},variables:u,setVariables:d,errors:f,setErrors:p,handleInstallTemplate:async()=>{let e=Object.entries(u).reduce((e,[t,n])=>(n===``&&e.push(t),e),[]);if(e.length>0)p(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:u},{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:c},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()===``?p(e=>[...e,t]):p(e=>e.filter(e=>e!==t)),d(e=>({...e,[t]:n}))},isLoadingEnvVars:j||N,isInstalling:F,defaultModelProvider:o,defaultModelId:c,onModelUpdate:async e=>(s(e.provider),l(e.modelId),{message:`Model updated successfully`})})]})]})})]})}var ZLi=e=>e.threadId;function QLi(e,t){return`traces`in e?{traces:{...e.traces,to:t}}:{threads:{...e.threads,to:t}}}var $Li=e=>`traces`in e?e.traces:e.threads;function eRi(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 tRi({query:e,rolling:t,autoRefetch:n=!0,limit:r,enabled:i=!0}){let a=Y(),{anchorTo:o,reanchor:s}=VIi(e),c=(0,G.useMemo)(()=>o?{...e,timeRange:QLi(e.timeRange,o)}:e,[e,o]),l=N$r({query:c,limit:r,enabled:i,queryOptions:LIi}),{headRows:u}=UIi({queryKey:[`threads`,e],fetchHead:async t=>(await a.queryTraceThreads({...e,timeRange:QLi(e.timeRange,t),orderBy:[{field:`endedAt`,direction:`desc`}],page:{limit:50}})).threads,getId:ZLi,getEndedAt:e=>e.endedAt,since:Date.parse($Li(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&&GIi(f,u,{getId:ZLi,compare:eRi(d),hasNextPage:l.hasNextPage}),[f,u,d,l.hasNextPage]);return{...l,threads:p}}function nRi(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 rRi=[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`],iRi=[];function aRi(){let{data:e}=n5(),t=e?.capabilities.traceQueryTimeToFirstChunk??!1,n=e?.capabilities.traceQueryTimeToFirstToken??!1,{data:r=iRi}=g8(),{data:i=iRi}=_8();return(0,G.useMemo)(()=>[R5r,...ali({withTimeToFirstChunk:t,withTimeToFirstToken:n,entityNames:r,environments:i})],[t,n,r,i])}function oRi({tokens:e,groups:t,onFiltersChange:n}){let r=(0,G.useMemo)(()=>m0r(e),[e]),i=(0,G.useMemo)(()=>{let e=_0r([],t);return{...e,nodes:[d5,...r,...e.nodes]}},[r,t]),a=(0,G.useCallback)(e=>{let t=y0r({...e,nodes:e.nodes.filter(e=>o8(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(o8);a({...i,nodes:[...n,o,...s]})},[r,i,a])}}var sRi=e=>e;function cRi({datePreset:e,dateFrom:t,dateTo:n,minDate:r,tokens:i,groups:a,onDatePresetChange:o,onDateChange:s,onDateRangeChange:c,onFiltersChange:l,disabled:u}){let d=aRi(),{filterBarValue:f,onFilterBarChange:p}=oRi({tokens:i,groups:a,onFiltersChange:l});return(0,K.jsxs)(f5,{fields:d,operators:H1r,value:f,onValueChange:p,createItemId:sRi,maxDepth:3,"aria-label":`Thread filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(f5.Chips,{renderChip:i=>i.fieldId===`timeRange`?(0,K.jsx)(f5.TimeRange,{preset:e,onPresetChange:o,dateFrom:t,dateTo:n,minDate:r,onDateChange:s,onDateRangeChange:c,disabled:u,presets:rRi,defaultPreset:i5.datePreset}):(0,K.jsx)(f5.Chip,{item:i})}),(0,K.jsx)(f5.Input,{placeholder:`Filter threads`})]})}function lRi({selectedThreadId:e,onSelectedThreadChange:t,onOpenScore:n,urlState:r}){let i=zIi(r),{timeRange:a,tokens:o,groups:s,sort:c}=i,l=r5().enabled,u=L6r().enabled,d=jsi({scope:`threads`}),{data:f,isLoading:p}=n5(),m=f?.capabilities.traceQueryTimeToFirstChunk??!1,h=f?.capabilities.traceQueryTimeToFirstToken??!1,g=(0,G.useMemo)(()=>p?d.preferences:$3r(d.preferences,{withTimeToFirstChunk:m,withTimeToFirstToken:h}),[d.preferences,p,m,h]),{threads:_,hasNextPage:v,isFetchingNextPage:y,setEndOfListElement:b,isLoading:x,isError:S,error:C}=tRi({query:(0,G.useMemo)(()=>{let e=cli(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(nRi),[_]),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)(C6r,{toolbar:(0,K.jsxs)(K.Fragment,{children:[r&&(0,K.jsx)(sui,{page:`threads`,...r,columns:d}),(0,K.jsxs)(jq,{children:[(0,K.jsx)(jq.Start,{children:(0,K.jsx)(cRi,{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)(jq.End,{children:(0,K.jsx)(B6r,{scope:`threads`,value:d.preferences,onChange:d.setPreferences})})]})]}),error:S?(0,K.jsx)(X8,{error:C,resource:`threads`,errorTitle:`Failed to load threads`}):void 0,empty:D?(0,K.jsx)(j3r,{resource:`threads`,datePreset:i.datePreset,dateFrom:i.dateFrom,dateTo:i.dateTo}):void 0,children:(0,K.jsx)(Wti,{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)(gsi,{open:!!e,threadId:e??``,depth:1,closeLabel:`Close`,withQueryTrace:l,withFeedback:u,onOpenScore:n,onClose:()=>t(void 0)})]})}function uRi(){let{enabled:e,isLoading:t}=j6r(),n=kb(),[r,i]=Hb();return(0,K.jsx)(IIi,{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)(lRi,{urlState:{searchParams:r,setSearchParams:i},selectedThreadId:ZIi(r),onSelectedThreadChange:e=>i(t=>QIi(t,e),{replace:!0}),onOpenScore:(e,t)=>n(kq(e,t))})})}var dRi=()=>(0,K.jsx)(RC,{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)(Br,{}),children:`Workflows documentation`}),variant:`fill`});function fRi(e,t,n){return yQ(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 pRi(e){return Object.keys(e.steps??{}).filter(t=>e.allSteps?.[t]?.isWorkflow)}function mRi(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 hRi(e,t,n){let r=mRi(t),i=[],a=(e,o,s,c,l,u)=>{let d=pRi(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 gRi=`auto 24rem minmax(0, 1fr) auto auto auto`;function _Ri({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:m(`w-6`,e&&`border-l border-border`)},t)),(0,K.jsxs)(`span`,{className:`relative w-6`,children:[(0,K.jsx)(`span`,{className:m(`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 vRi({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:m(ZC,`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 yRi=e=>e.stopPropagation();function bRi({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 xRi({row:e,isExpanded:t,onToggle:n,runCount:r,rowProps:i}){let{paths:a,Link:o}=gl(),s=(0,G.useRef)(null),{workflow:c,nestedIds:l}=e,u=fY(c.name,50),d=fY(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)(vRi,{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:yRi,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)(_Ri,{guides:e.guides,isLastChild:e.isLastChild}):null,(0,K.jsx)(`span`,{className:`truncate`,children:u}),c.origin===`dynamic`?(0,K.jsx)(bw,{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)(Lc,{"aria-hidden":!0,className:`size-3.5`}),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)(No,{"aria-hidden":!0,className:`size-3.5`}),m]}):``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:f||``})]})]})}function SRi({workflows:e,isLoading:t,search:n=``,sort:r,onSortChange:i,requestContext:a}){let[o,s]=(0,G.useState)(new Set),c=xMt({requestContext:a}),l=(0,G.useMemo)(()=>Object.entries(e).map(([e,t])=>({...t,id:e})),[e]),u=(0,G.useMemo)(()=>{let e=n.toLowerCase();return l.filter(t=>t.name?.toLowerCase().includes(e)||t.description?.toLowerCase().includes(e))},[l,n]),d=(0,G.useMemo)(()=>fRi(u,r,c),[u,r,c]),f=(0,G.useMemo)(()=>hRi(d,e,o),[d,e,o]),p=(0,G.useMemo)(()=>{let e=new Map;for(let t of f)t.kind===`workflow`&&e.set(t.pathKey,e.size);return e},[f]),{containerRef:h,getRowProps:g}=_Q({count:p.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)(NU,{columns:gRi,fit:`container`}):(0,K.jsxs)(Z,{columns:gRi,fit:`container`,scrollRef:h,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)(bRi,{sortKey:`name`,sort:r,onSortChange:i,children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`Description`}),(0,K.jsx)(bRi,{sortKey:`running`,sort:r,onSortChange:i,children:`Running`}),(0,K.jsx)(bRi,{sortKey:`suspended`,sort:r,onSortChange:i,children:`Pending input`}),(0,K.jsx)(bRi,{sortKey:`steps`,sort:r,onSortChange:i,children:`Number of steps`})]}),f.length===0&&n?(0,K.jsx)(Z.NoMatch,{message:`No Workflows match your search`}):null,f.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)(vRi,{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)(_Ri,{guides:e.guides,isLastChild:e.isLastChild}),(0,K.jsx)(`span`,{className:`truncate`,children:fY(e.stepId,50)}),(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{render:(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`muted`}),role:`note`,tabIndex:0,className:m(`shrink-0 rounded-sm`,_),children:`not registered`}),(0,K.jsx)(CC,{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:fY(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)(xRi,{row:e,isExpanded:t,onToggle:n,runCount:c[e.workflow.id],rowProps:g(p.get(e.pathKey)??-1)},`workflow-${e.pathKey}`)})]})}var W9=[sF(`/workflows`)];function CRi(){let{data:e,isLoading:t,error:n}=sP(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)();return n&&JP(n)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(jU,{variant:`fill`})]}):n&&YP(n)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(AU,{variant:`fill`,resource:`workflows`})]}):n?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load workflows`,descriptionSlot:n.message})]}):Object.keys(e||{}).length===0&&!t?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(dRi,{})]}):(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:W9}),actionRow:(0,K.jsxs)(jq,{children:[(0,K.jsx)(jq.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(zU,{onSearch:i,label:`Filter workflows`,placeholder:`Filter by name or description`})})}),(0,K.jsx)(jq.End,{children:(0,K.jsx)(X,{render:(0,K.jsx)(Vb,{to:`/workflows/schedules`}),variant:`primary`,icon:(0,K.jsx)(Nn,{}),children:`Schedules`})})]}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(SRi,{workflows:e||{},isLoading:t,search:r,sort:a,onSortChange:(e,t)=>o({key:t,direction:e})})]})}var wRi={active:`bg-success-indicator`,paused:`bg-info-indicator`,completed:`bg-muted-foreground`},TRi={active:`text-success-indicator`,paused:`text-info-indicator`,completed:`text-muted-foreground`},ERi=({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 ${wRi[e]}`,"aria-hidden":!0}),(0,K.jsx)(T,{as:`span`,variant:`caption`,className:TRi[e],children:e})]});function DRi({status:e}){let{icon:t,color:n}=ORi(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 ORi(e){switch(e){case`success`:return{icon:(0,K.jsx)(Bn,{size:14}),color:`text-success-indicator`};case`failed`:return{icon:(0,K.jsx)(Vc,{size:14}),color:`text-destructive-foreground`};case`running`:return{icon:(0,K.jsx)(Zc,{}),color:`text-muted-foreground`};case`suspended`:return{icon:(0,K.jsx)(Zn,{size:14}),color:`text-info-indicator`};case`canceled`:return{icon:(0,K.jsx)(tr,{size:14}),color:`text-muted-foreground`};case`pending`:case`waiting`:return{icon:(0,K.jsx)(lr,{size:14}),color:`text-muted-foreground`};default:return{icon:null,color:`text-muted-foreground`}}}var kRi=`auto auto auto auto 1fr`,ARi=3e4,jRi=3e5;function MRi({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:i,setEndOfListElement:a}){let{Link:o,paths:s}=gl(),c=e=>!!(n&&e.runId&&e.outcome!==`failed`),l=e.filter(c).length,{containerRef:u,getRowProps:d}=_Q({count:l}),f=-1;return t?(0,K.jsx)(NU,{columns:kRi}):e.length===0?(0,K.jsx)(T,{variant:`body`,tone:`muted`,className:`p-4`,children:`No trigger history yet.`}):(0,K.jsxs)(Z,{columns:kRi,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=xw(t,{signed:!0}),i=e.outcome===`failed`,a=i?e.error:e.run?.error,l=Math.abs(t),u=!i&&l>ARi&&l<=jRi,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)(Cc,{size:14}),`publish failed`]}):e.run?(0,K.jsx)(DRi,{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)(xC,{children:[(0,K.jsx)(SC,{asChild:!0,children:(0,K.jsx)(`span`,{className:`inline-flex text-destructive-foreground`,children:(0,K.jsx)(Cc,{size:14})})}),(0,K.jsx)(CC,{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)(jA,{value:e.actualFireAt}):`—`,u?(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{asChild:!0,children:(0,K.jsx)(`span`,{className:`inline-flex text-info-indicator`,children:(0,K.jsx)(Cc,{size:14})})}),(0,K.jsxs)(CC,{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:xw(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 NRi={id:`workflow-schedules`,label:`Schedules`,icon:Nn,to:`/workflows/schedules`};function PRi({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 FRi(){let{scheduleId:e}=Ab(),t=[sF(`/workflows`),NRi,{id:`schedule`,label:LLt(e),icon:Nn}],{paths:n}=gl(),{data:r,error:i}=tRt({scheduleId:e,queryOptions:{enabled:!!e}}),{data:a,isLoading:o,error:s,hasNextPage:c,isFetchingNextPage:l,setEndOfListElement:u}=rRt({scheduleId:e,queryOptions:{enabled:!!e}}),d=iRt({scheduleId:e});if(i&&JP(i))return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(jU,{variant:`fill`})]});if(i&&YP(i))return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(AU,{variant:`fill`,resource:`schedules`})]});if(i)return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load schedule`,descriptionSlot:i.message})]});let f=r?.workflowId,p=r?.agentId;return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:t}),actionRow:(0,K.jsx)(jq,{children:(0,K.jsxs)(jq.End,{children:[(0,K.jsx)(X,{render:(0,K.jsx)(Vb,{to:n.schedulesLink()}),variant:`ghost`,icon:(0,K.jsx)(Rt,{}),children:`Back to schedules`}),f?(0,K.jsx)(X,{icon:(0,K.jsx)(rP,{}),render:(0,K.jsx)(Vb,{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:()=>UC.success(e===`pause`?`Schedule paused`:`Schedule resumed`),onError:e=>UC.error(e.message)})},disabled:d.isPending,"data-testid":`schedule-toggle-button`,children:r.status===`active`?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(No,{}),`Pause`]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Vo,{}),`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)(PRi,{label:p?`Agent`:`Workflow`,children:f?(0,K.jsx)(Vb,{to:n.workflowLink(f),className:`text-foreground hover:underline`,children:f}):p?(0,K.jsx)(Vb,{to:n.agentLink(p),className:`text-foreground hover:underline`,children:p}):`—`}),(0,K.jsxs)(PRi,{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)(PRi,{label:`Status`,children:(0,K.jsx)(ERi,{status:r.status})}),(0,K.jsx)(PRi,{label:`Next fire`,children:r.nextFireAt?(0,K.jsx)(jA,{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)(RC,{tone:`error`,titleSlot:`Failed to load trigger history`,descriptionSlot:s.message}):(0,K.jsx)(MRi,{triggers:a??[],isLoading:o,workflowId:f,hasNextPage:c,isFetchingNextPage:l,setEndOfListElement:u})]})]}):null]})}var IRi={target:e=>e.workflowId??e.agentId??``,status:e=>e.status,nextFireAt:e=>e.nextFireAt,lastFireAt:e=>e.lastFireAt},LRi=`minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto`;function RRi({schedules:e,isLoading:t,search:n=``,sort:r,onSortChange:i}){let{paths:a,Link:o}=gl(),s=(0,G.useMemo)(()=>{let t=n.toLowerCase();return yQ(t?e.filter(e=>e.id.toLowerCase().includes(t)||(e.workflowId??e.agentId??``).toLowerCase().includes(t)):e,r,IRi)},[e,n,r]),{containerRef:c,getRowProps:l}=_Q({count:s.length,global:!0});if(t)return(0,K.jsx)(NU,{columns:LRi});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:LRi,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)(ERi,{status:e.status})}),(0,K.jsx)(Z.Cell,{children:e.nextFireAt?(0,K.jsx)(jA,{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)(DRi,{status:e.lastRun.status}),e.lastFireAt?(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:(0,K.jsx)(jA,{value:e.lastFireAt})}):null]}):e.lastFireAt?(0,K.jsx)(jA,{value:e.lastFireAt}):(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`Never`})})]},e.id))]})}function zRi({workflowId:e}={}){let{data:t,isLoading:n,error:r}=uF(e?{workflowId:e}:{}),[i,a]=(0,G.useState)(``),[o,s]=(0,G.useState)();return r?(0,K.jsx)(RC,{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)(zU,{onSearch:a,label:`Filter schedules`,placeholder:`Filter by id or workflow`})}),(0,K.jsx)(`div`,{className:`overflow-y-auto`,children:(0,K.jsx)(RRi,{schedules:t??[],isLoading:n,search:i,sort:o,onSortChange:(e,t)=>s({key:t,direction:e})})})]})}var BRi=[sF(`/workflows`),NRi];function VRi(){let[e]=Hb(),t=e.get(`workflowId`)??void 0,{error:n}=uF(t?{workflowId:t}:{});return n&&JP(n)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:BRi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(jU,{variant:`fill`})]}):n&&YP(n)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:BRi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(AU,{variant:`fill`,resource:`schedules`})]}):(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:BRi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(`div`,{className:`h-full`,children:(0,K.jsx)(zRi,{workflowId:t})})]})}var HRi={"--belt-hue":`var(--warning-indicator)`};function URi(e){let t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function WRi(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 GRi({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:(0,K.jsxs)(`section`,{className:m(FMt,`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)(TC,{children:(0,K.jsx)(Zn,{})}),`Step suspended`]}),(0,K.jsx)(bw,{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?Kk(lA(n.resumeSchema)):Rp(q(),kp());return(0,K.jsx)(KRi,{step:e,stepSchema:i,description:n.description,onResume:r},`${e.runId}-${e.stepId}`)})]}),(0,K.jsx)(c4e,{status:`ready`,label:`Needs input`,className:`before:hidden`,style:HRi})]})}function KRi({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)(TC,{children:(0,K.jsx)(fo,{})}),`The step is asking`]}),(0,K.jsxs)(Hw,{open:i,onOpenChange:a,children:[(0,K.jsxs)(Uw,{className:m(`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)(TC,{children:(0,K.jsx)(y,{direction:`right`,className:`text-muted-foreground`})}),(0,K.jsx)(T,{as:`span`,variant:`body`,tone:`ink`,className:`truncate`,children:WRi(e.suspendPayload,e.stepId)})]}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`shrink-0`,children:URi(e.suspendPayload)})]}),(0,K.jsx)(Ww,{children:(0,K.jsx)(`div`,{"data-testid":`suspended-payload`,className:`pt-2`,children:(0,K.jsx)(FT,{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)(TC,{children:(0,K.jsx)(mo,{})}),`Your response`]}),(0,K.jsx)(`div`,{className:`-mx-5`,children:(0,K.jsx)(Zjt,{schema:t,isSubmitLoading:o,submitButtonLabel:`Resume`,submitButtonVariant:`primary`,submitButtonIcon:(0,K.jsx)(Vo,{}),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){UC.error(e instanceof Error?e.message:`Error resuming workflow`)}finally{s(!1)}}})})]})]})}function qRi({hidden:e,requestContext:t,canResume:n}){let{result:r,workflow:i,runId:a,isStreamingWorkflow:o}=(0,G.useContext)(gw),s=Yvt(r,a),c=eyt(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)(GRi,{suspendedSteps:s,workflow:i,isStreaming:o,onResume:c})},a)}var JRi={success:{label:`Completed`,icon:Bn},failed:{label:`Failed`,icon:ir},suspended:{label:`Needs input`,icon:No},waiting:{label:`Waiting`,icon:_c},paused:{label:`Paused`,icon:No},skipped:{label:`Skipped`,icon:Ns},running:{label:`Running`,icon:Ea},canceled:{label:`Canceled`,icon:tr}},YRi={label:`Status unavailable`,icon:Cee};function XRi({row:e,isSelected:t,isHovered:n,onSelectStep:r,onHoverStep:i,onOpenInput:a,onOpenOutput:o}){let s=Object.hasOwn(JRi,e.status)?JRi[e.status]:YRi,c=s.icon,l=Rbt(e.status),u=e.stepId.slice(0,e.stepId.lastIndexOf(`.`)),d=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:m(`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:m(`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`,_),children:[(0,K.jsx)(`span`,{"aria-label":s.label,className:m(`grid size-6 flex-none place-items-center rounded-md border border-border bg-background`,zbt[l]),children:(0,K.jsx)(c,{"aria-hidden":!0,className:m(`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:d}),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)(Cr,{"aria-hidden":!0,className:`size-3 shrink-0`}),(0,K.jsx)(`span`,{className:`truncate`,children:u})]})]})]}),(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:m(`absolute top-0 h-full min-w-0.5 rounded-sm`,Bbt[l]),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:xw(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)(Mt,{})}),(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)(Kt,{})})]})]})}var ZRi=e=>e.includes(`.`),QRi=e=>e===`input`||e.endsWith(`.input`),$Ri=1;function ezi(e,t){let n=Ubt(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 tzi(e,t){let n=Object.entries(e).filter(([e])=>!QRi(e)).map(([e,n])=>({stepId:e,step:n,...ezi(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,$Ri),100-t)}}return{stepId:e,step:t,status:OA(t)?`suspended`:t.status,timing:s,spansSuspension:a,isRunning:r,isNestedEntry:ZRi(e)}})}function nzi(){let{steps:e}=B$(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:i}=hw(),[a,o]=(0,G.useState)(()=>Date.now()),[s,c]=(0,G.useState)(!0),[l,u]=(0,G.useState)(!1),{showData:d}=lP(),f=(0,G.useRef)(null),p=tzi(e,a),h=p.some(e=>e.isRunning);return H1e(f,{enabled:h&&!s}),(0,G.useEffect)(()=>{if(!h||s)return;let e=setInterval(()=>o(Date.now()),100);return()=>clearInterval(e)},[h,s]),p.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)(Hw,{open:!s,onOpenChange:e=>c(!e),className:m(Wb,`@container/workflow-timeline pointer-events-auto overflow-hidden rounded-xl`),children:[(0,K.jsxs)(`div`,{className:`flex items-center`,children:[(0,K.jsxs)(Uw,{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)(zn,{"aria-hidden":!0,className:`size-4 text-muted-foreground`})}),(0,K.jsx)(`span`,{children:`Timeline`}),(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,children:[p.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:l?`Restore timeline height`:`Enlarge timeline`,"aria-pressed":l,onClick:()=>u(!l),className:`mr-2 shrink-0`,children:l?(0,K.jsx)(lee,{}):(0,K.jsx)(hee,{})})]}),(0,K.jsx)(Ww,{children:(0,K.jsx)(`div`,{ref:f,"data-testid":`workflow-timeline-list`,className:m(`overflow-auto overscroll-contain px-1.5 pb-1.5`,l?`max-h-[min(720px,calc(100dvh-112px))]`:`max-h-[min(320px,40dvh)]`),children:p.map(e=>(0,K.jsx)(XRi,{row:e,isSelected:t===e.stepId,isHovered:n===e.stepId,onSelectStep:r,onHoverStep:i,onOpenInput:(e,t)=>d({type:`step-input`,stepId:e.stepId},t),onOpenOutput:(e,t)=>d({type:`step-output`,stepId:e.stepId},t)},e.stepId))})})]})})}var rzi=({workflowId:e,workflow:t,isLoading:n})=>{let[r]=mw(`workflow`,e),{canExecute:i,isLoading:a}=KC(),{stepDetail:o}=lP(),s=fE(),c=o?.type===`data`,l=(0,K.jsxs)(`div`,{className:`[container-type:size] relative h-full min-h-0`,children:[(0,K.jsx)(zmr,{workflowId:e,workflow:t,isLoading:n,requestContext:r}),(0,K.jsx)(qRi,{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)(H$,{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)(nzi,{})})]});return s&&o&&!c?(0,K.jsx)(`div`,{className:`h-full min-h-0 overflow-hidden`,children:(0,K.jsx)(H$,{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)(N6,{id:`workflow-graph`,className:`pointer-events-none min-w-0`}),o&&!c&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(F6,{className:`pointer-events-auto`}),(0,K.jsx)(N6,{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)(H$,{requestContext:r})})})]})]})]})},izi=()=>{let{workflowId:e}=Ab(),{data:t,isLoading:n,error:r}=cP({workflowId:e,requestContext:mw(`workflow`,e)[0],queryOptions:{enabled:!!e}});return r&&JP(r)?(0,K.jsx)(jU,{variant:`fill`}):r&&YP(r)?(0,K.jsx)(AU,{variant:`fill`,resource:`workflows`}):(0,K.jsx)(rzi,{workflowId:e,workflow:t??void 0,isLoading:n})};function azi(){let{workflowId:e}=Ab(),{error:t}=uF(e?{workflowId:e}:{});if(!e)return null;let n;return n=t&&JP(t)?(0,K.jsx)(jU,{variant:`fill`}):t&&YP(t)?(0,K.jsx)(AU,{variant:`fill`,resource:`schedules`}):(0,K.jsx)(`div`,{className:`h-full`,children:(0,K.jsx)(zRi,{workflowId:e})}),(0,K.jsxs)(uw,{children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),n]})}function ozi(){let{workflowId:e}=Ab();return e?(0,K.jsx)(qui,{scopedEntityId:e,scopedEntityType:kh.WORKFLOW_RUN}):null}var szi=(0,G.createContext)(null);function G9(){let e=(0,G.useContext)(szi);if(!e)throw Error(`Workspace components must be rendered inside <Workspace.Root>`);return e}var czi=e=>e?.status;function lzi(e,t){return JP(e)?`Your session has expired. Sign in again to continue.`:YP(e)?`You don't have permission to access this.`:XP(e)?`This path no longer exists.`:czi(e)===501?`This workspace does not support this operation.`:t}function uzi({error:e,fallback:t,className:n}){return(0,K.jsx)(EA,{variant:`destructive`,className:n,children:(0,K.jsx)(EA.Message,{children:lzi(e,t)})})}var dzi=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;function fzi(e){let t=dzi.exec(e);return t?{frontmatter:t[1]??``,body:e.slice(t[0].length)}:{frontmatter:null,body:e}}function pzi({content:e}){let{frontmatter:t,body:n}=fzi(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)(pY,{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)(xX,{children:n})})]})}function mzi(){let{activeFilePath:e}=G9();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 hzi({path:e,content:t,mimeType:n}){return oVn(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`})}):sVn(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:${lVn(e,n)};base64,${t}`,type:lVn(e,n)})})}):uVn(e)?(0,K.jsx)(pzi,{content:t}):(0,K.jsx)(pY,{code:t,lang:U2e(e),overflow:`scroll`,className:`rounded-none border-0 bg-transparent [&_pre]:p-4`})}function gzi({renderPreview:e}){let{workspaceId:t,activeFilePath:n}=G9(),{data:r,isLoading:i,error:a}=TVn({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)(dw,{className:`h-4 w-1/2`}),(0,K.jsx)(dw,{className:`h-4 w-5/6`}),(0,K.jsx)(dw,{className:`h-4 w-2/3`})]});if(!r)return(0,K.jsx)(uzi,{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)(hzi,{...o})}var _zi=(e,t)=>e===`.`?t:`${e}/${t}`,vzi=e=>e.split(`/`).slice(0,-1).map((e,t,n)=>n.slice(0,t+1).join(`/`)),yzi=e=>{let t=e.lastIndexOf(`/`);return t===-1?`.`:e.slice(0,t)};function bzi({labeled:e=!1}={}){let{workspaceId:t,onCreateDirectory:n,isReadOnly:r}=G9(),i=dy(),[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`,yzi(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)(xi,{}),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)(xi,{})}),(0,K.jsx)(_E,{open:a,onOpenChange:o,pending:l,children:(0,K.jsx)(vE,{size:`sm`,children:(0,K.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),f()},children:[(0,K.jsx)(yE,{children:(0,K.jsx)(SE,{children:`New folder`})}),(0,K.jsx)(xE,{children:(0,K.jsx)(ZM,{autoFocus:!0,"aria-label":`Folder path`,placeholder:`docs/guides`,value:s,onChange:e=>c(e.target.value)})}),(0,K.jsxs)(bE,{children:[(0,K.jsx)(wE,{children:`Cancel`}),(0,K.jsx)(X,{type:`submit`,variant:`primary`,disabled:!d||l,children:`Create`})]})]})})})]})}function xzi(e){return`${e.topSource}/${e.name}`}function Szi(e){let t=mVn(e.topSource,e.name);return t?`${t.owner}/${t.repo}/${e.name}`:null}function Czi({open:e,onOpenChange:t,workspaceId:n,onInstall:r,isInstalling:i,installedSkillIds:a=[],installedSkillNames:o=[],writableMounts:s,installedSkillPaths:c}){let[l,u]=(0,G.useState)(``),[d,f]=(0,G.useState)(null),[p,h]=(0,G.useState)(),g=s?.some(e=>e.path===p)?p:s?.[0]?.path,{data:_,isLoading:v}=fVn({workspaceId:n,queryOptions:{enabled:!!n}}),y=dVn({workspaceId:n}),b=(0,G.useMemo)(()=>d?.topSource?mVn(d.topSource,d.name):null,[d]),x=(0,G.useMemo)(()=>!b||!d?null:`https://skills.sh/${b.owner}/${b.repo}/${d.name}`,[b,d]),{data:S,isLoading:C}=pVn({workspaceId:n,owner:b?.owner,repo:b?.repo,skillPath:d?.name,queryOptions:{enabled:!!n&&!!b&&!!d}}),w=Tw(e=>{e.trim().length>=2&&y.mutate(e)},300),E=(0,G.useCallback)(e=>{u(e),w(e)},[w]),D=(0,G.useMemo)(()=>l.trim().length>=2?y.data?.skills??[]:_?.skills??[],[l,y.data,_]),O=y.isPending,k=l.trim().length>=2,A=(0,G.useMemo)(()=>{if(!d)return!1;let e=Szi(d);return!!(e&&a.includes(e)||o.includes(d.name))},[d,a,o]),j=(0,G.useCallback)(()=>{d&&b&&r({repository:`${b.owner}/${b.repo}`,skillName:d.name,mount:s&&s.length>1?g:void 0})},[d,b,r,s,g]),M=(0,G.useCallback)(e=>{e||(u(``),f(null),h(void 0)),t(e)},[t]);return(0,K.jsx)(_E,{open:e,onOpenChange:M,pending:i,children:(0,K.jsxs)(vE,{size:`xl`,className:`h-[80vh]`,children:[(0,K.jsxs)(yE,{children:[(0,K.jsx)(SE,{children:`Add Skill`}),(0,K.jsx)(CE,{children:`Search and install skills from the community registry`})]}),(0,K.jsxs)(xE,{layout:`fill`,children:[(0,K.jsx)(RU,{label:`Search skills`,placeholder:`Search skills`,value:l,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)(lw,{className:`flex-1 rounded-lg border border-border`,children:(0,K.jsx)(cw,{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)(Ea,{className:`size-6 animate-spin text-muted-foreground`})}):D.length===0?(0,K.jsxs)(`div`,{className:`flex flex-1 flex-col items-center-safe justify-center-safe py-5 text-muted-foreground`,children:[(0,K.jsx)(tr,{className:`mb-2 size-8`}),(0,K.jsx)(T,{children:k?`No skills found`:`No skills available`})]}):(0,K.jsx)(`div`,{className:`space-y-1 p-2`,children:D.map(e=>{let t=xzi(e),n=Szi(e),r=n&&a.includes(n)||o.includes(e.name),i=d?xzi(d):null;return(0,K.jsx)(`button`,{onClick:()=>f(e),className:m(`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)(Bn,{className:`size-2.5`}),`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)(Dr,{className:`size-3`}),(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:d?(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)(mQ,{className:`size-5 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:d.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)(pQ,{className:`size-3`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`block`,children:d.topSource})]}),(0,K.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(Dr,{className:`size-3`}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[d.installs.toLocaleString(),` installs`]})]})]})]}),b&&(0,K.jsx)(`a`,{href:`https://github.com/${b.owner}/${b.repo}`,target:`_blank`,rel:`noopener noreferrer`,className:m(`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)(Br,{className:`size-4`})})]})}),C?(0,K.jsx)(`div`,{className:`flex flex-1 items-center justify-center`,children:(0,K.jsx)(Ea,{className:`size-6 animate-spin text-muted-foreground`})}):S?(0,K.jsx)(lw,{className:`flex-1`,children:(0,K.jsx)(`div`,{className:`p-4`,children:(0,K.jsx)(xX,{children:S})})}):(0,K.jsxs)(`div`,{className:`flex flex-1 flex-col items-center justify-center text-muted-foreground`,children:[(0,K.jsx)(Eo,{className:`mb-2 size-8`}),(0,K.jsx)(T,{children:`Preview unavailable`}),x&&(0,K.jsxs)(`a`,{href:x,target:`_blank`,rel:`noopener noreferrer`,className:`mt-2 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)(Br,{className:`size-3`})]})]})]}):(0,K.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center text-muted-foreground`,children:[(0,K.jsx)(Eo,{className:`mb-2 size-8`}),(0,K.jsx)(T,{children:`Select a skill to preview`})]})})]})]}),d&&s&&s.length>1&&(0,K.jsxs)(fA,{orientation:`horizontal`,className:m(`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)(Ci,{className:`size-4 shrink-0 text-muted-foreground`}),(0,K.jsx)(mA,{className:`whitespace-nowrap`,children:`Install to`}),(0,K.jsxs)(WA,{value:g,onValueChange:h,children:[(0,K.jsx)(KA,{className:`flex-1`,children:(0,K.jsx)(GA,{})}),(0,K.jsx)(qA,{children:s.map(e=>{let t=e.displayName??e.name??e.provider??`unknown`;return(0,K.jsxs)(JA,{value:e.path,children:[t,` (`,e.path,`)`]},e.path)})})]})]})]}),d&&(0,K.jsxs)(bE,{children:[A&&s&&s.length>1&&(()=>{let e=c?.[d.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)(wE,{children:`Cancel`}),(0,K.jsx)(gE,{onConfirm:j,disabled:!b||A,"data-testid":`install-skill-button`,children:i?`Installing...`:A?`Already installed`:`Install`})]})]})})}function wzi({labeled:e=!1}){let{workspaceId:t,addSkill:n}=G9(),[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)(Nc,{}),`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)(Nc,{})}),(0,K.jsx)(Czi,{...c,open:r,onOpenChange:i,workspaceId:t,onInstall:e=>void l(e),isInstalling:a})]})}function Tzi({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(vzi(t??``))),[v,y]=(0,G.useState)(t);if(t!==v){y(t);let e=vzi(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 vLi=({queryOptions:e}={})=>Ey({queryKey:[`mastra-templates`],queryFn:mLi,...e}),yLi=({repoOrSlug:e,owner:t,queryOptions:n})=>Ey({queryKey:[`template-repo`,e,t],queryFn:()=>gLi({repoOrSlug:e,owner:t}),...n}),bLi=({repo:e,owner:t,branch:n,queryOptions:r})=>Ey({queryKey:[`template-repo-env-vars`,e,t,n],queryFn:()=>_Li({repo:e,owner:t,branch:n}),...r}),xLi=({queryOptions:e}={})=>{let t=Y();return Ey({queryKey:[`agent-builder-workflow`],queryFn:async()=>await t.getAgentBuilderAction(`merge-template`).details(),...e})},SLi=({queryOptions:e}={})=>{let t=Y();return Oy({mutationFn:async({runId:e})=>await t.getAgentBuilderAction(`merge-template`).createRun({runId:e}),...e})},CLi=({queryOptions:e}={})=>{let t=Y();return Oy({mutationFn:async({runId:e})=>await t.getAgentBuilderAction(`merge-template`).runById(e),...e})},wLi=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)},TLi=(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=wLi(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=wLi(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}},ELi=(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)}},DLi=(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}=TLi(a,s,e);s=c,r(c),(a.runId||i||t)&&ELi(a.runId||i||t,c)}}catch(t){console.error(`💥 [processStream] Error processing template installation stream:`,t);let{newState:n}=TLi({type:`error`,payload:{error:t instanceof Error?t.message:`Unknown error`}},s,e);r(n)}finally{a(!1),o.releaseLock()}}}},OLi=({workflowInfo:e,queryOptions:t}={})=>{let n=Y(),{streamResult:r,isStreaming:i,processStream:a}=DLi(e);return{streamInstall:Oy({mutationFn:async({inputData:e,selectedModel:t,runId:r})=>{for(let i=1;i<=3;i++)try{let i=n.getAgentBuilderAction(`merge-template`),o=new Il;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}},kLi=({workflowInfo:e,queryOptions:t}={})=>{let n=Y(),{streamResult:r,isStreaming:i,processStream:a}=DLi(e);return{observeInstall:Oy({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 ALi(e){return e.replace(/\/$/,``).split(`/`).pop()}function jLi({templates:e,linkComponent:t,className:n,isLoading:r}){let i=t||`a`;return r?(0,K.jsx)(`div`,{className:m(`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:m(`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:m(Wb,`grid w-full grid-cols-[1fr_auto] overflow-hidden rounded-lg state-layer`),children:[(0,K.jsxs)(i,{to:`/templates/${e.slug}`,className:m(`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:m(`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:m(QC,f),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:m(`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)(tF,{}),` `,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)(aF,{}),` `,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)(go,{}),` `,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)(Lc,{}),` `,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)(nF,{}),` `,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:m(`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:m(`flex items-center gap-2 rounded bg-sidebar px-2 py-1`,mKe,QC,f),children:[(0,K.jsx)(pQ,{}),` `,ALi(e.githubUrl)]})})})]},e.slug)})})}function MLi({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:i,onProviderChange:a,searchTerm:o,onSearchChange:s,onReset:c,className:l,isLoading:u}){return u?(0,K.jsxs)(`div`,{className:m(`flex h-[6.5rem] items-center gap-5`,`[&>div]:h-8 [&>div]:w-48 [&>div]:animate-pulse [&>div]:bg-card`,l),children:[(0,K.jsx)(`div`,{}),` `,(0,K.jsx)(`div`,{}),` `,(0,K.jsx)(`div`,{})]}):(0,K.jsxs)(`div`,{className:m(`sticky top-0 mx-auto flex flex-wrap gap-1.5 bg-background py-5`,l),children:[(0,K.jsx)(RU,{label:`Search templates`,placeholder:`Search templates`,size:`sm`,value:o,onValueChange:s}),(0,K.jsxs)(WA,{value:t,onValueChange:i,children:[(0,K.jsx)(KA,{"aria-label":`Filter by tag`,size:`sm`,className:`w-auto`,children:(0,K.jsx)(GA,{placeholder:`Select an option`})}),(0,K.jsx)(qA,{children:e.map(e=>(0,K.jsx)(JA,{value:e.value,children:e.label},e.value))})]}),(0,K.jsxs)(WA,{value:r,onValueChange:a,children:[(0,K.jsx)(KA,{"aria-label":`Filter by provider`,size:`sm`,className:`w-auto`,children:(0,K.jsx)(GA,{placeholder:`Select an option`})}),(0,K.jsx)(qA,{children:n.map(e=>(0,K.jsx)(JA,{value:e.value,children:e.label},e.value))})]}),c&&(0,K.jsx)(S3,{onClick:c})]})}var NLi=[{id:`templates`,label:`Templates`}];function PLi(){let{data:e,isLoading:t}=vLi(),{templates:n,tags:r,providers:i}=e??{templates:[],tags:[],providers:[]},[a,o]=(0,G.useState)(`all`),[s,c]=(0,G.useState)(`all`),[l,u]=(0,G.useState)(``),d=[{value:`all`,label:`Any tag`}];(r||[]).forEach(e=>{d.push({value:e,label:e})});let f=[{value:`all`,label:`Any provider`}];(i||[]).forEach(e=>{f.push({value:e,label:e})});let p=(e,t)=>{t===`tag`?o(e):t===`provider`&&c(e)},h=e=>{u(e)},g=()=>{o(`all`),c(`all`),u(``)},_=n.filter(e=>!(l&&!e.title.toLowerCase().includes(l)&&!e.description.toLowerCase().includes(l)||a!==`all`&&!e.tags.includes(a)||s!==`all`&&!e.supportedProviders.includes(s))),v=l||a!==`all`||s!==`all`;return(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:NLi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Templates`}),(0,K.jsx)($C,{children:(0,K.jsxs)(B1e,{children:[(0,K.jsx)(TC,{children:(0,K.jsx)(Eo,{})}),`Templates`]})}),(0,K.jsxs)(`div`,{className:m(`z-10 h-full w-full overflow-y-auto px-5 pb-12`),children:[(0,K.jsx)(MLi,{selectedTag:a,onTagChange:e=>p(e,`tag`),tagOptions:d,selectedProvider:s,onProviderChange:e=>p(e,`provider`),providerOptions:f,searchTerm:l,onSearchChange:h,onReset:v?g:void 0,className:`max-w-[80rem]`,isLoading:t}),(0,K.jsx)(jLi,{templates:_,linkComponent:Vb,className:`mx-auto max-w-[80rem]`,isLoading:t})]})]})}function FLi({children:e,className:t}){return(0,K.jsx)(`div`,{className:m(`transition-height mt-12 rounded-lg border border-border px-4 py-5 lg:min-h-[25rem] lg:px-12`,t),children:e})}function ILi({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)(Cc,{className:`text-warning-foreground`}),title:`Template Installed with Warnings`}:{icon:(0,K.jsx)(Gr,{}),title:`Template Installation Failed`};return(0,K.jsxs)(FLi,{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:m(`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)(Dw,{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:m(`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)(Dw,{className:`text-caption wrap-break-word whitespace-pre-wrap`,code:n})})]})]})}function LLi({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:i,handleInstallTemplate:a,handleVariableChange:o,isLoadingEnvVars:s,isInstalling:c,defaultModelProvider:l,defaultModelId:u,onModelUpdate:d}){return(0,K.jsx)(FLi,{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:m(`flex items-center gap-2`,`[&_svg]:h-[1.2em] [&_svg]:opacity-70 [&>svg]:w-[1.2em]`),children:[`Install Template `,(0,K.jsx)(wo,{})]}),(0,K.jsxs)(fA,{orientation:`horizontal`,children:[(0,K.jsx)(mA,{children:`Template AI Model Provider`}),(0,K.jsx)(Oyt,{className:`flex-1`,children:(0,K.jsxs)(WA,{name:`template-provider`,value:t,onValueChange:n,children:[(0,K.jsx)(KA,{size:`md`,children:(0,K.jsx)(GA,{placeholder:`Select`})}),(0,K.jsx)(qA,{children:e.map(e=>(0,K.jsx)(JA,{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:m(`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)(Zc,{}),(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)(fA,{className:`w-full`,children:[(0,K.jsx)(mA,{className:`sr-only`,children:`Key`}),(0,K.jsx)(ZM,{name:`env-${e}`,value:e,disabled:!0,className:`w-full`})]}),(0,K.jsxs)(fA,{invalid:i.includes(e),className:`w-full`,children:[(0,K.jsx)(mA,{className:`sr-only`,children:`Value`}),(0,K.jsx)(ZM,{name:e,value:t,onChange:o,autoComplete:`off`,className:`w-full`}),(0,K.jsx)(gA,{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)(t3r,{defaultProvider:l||``,defaultModel:u||``,updateModel:d||(()=>Promise.resolve({message:`Updated`})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:`Provider`})]})]}),t&&!s&&(0,K.jsx)(X,{className:m(`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||!l||!u||i.length>0||c,children:c?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Zc,{className:`h-4 w-4`}),` Installing...`]}):(0,K.jsxs)(K.Fragment,{children:[`Install `,(0,K.jsx)(Ht,{})]})})]})})}function RLi({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:m(`flex items-center gap-3`,`[&>svg]:h-[1.2em] [&>svg]:w-[1.2em] [&>svg]:opacity-50`,{"[&>svg]:opacity-20":r}),children:[(0,K.jsx)(Eo,{}),(0,K.jsx)(`h2`,{className:m({"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:m(`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:m(`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)(Xi,{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)(ki,{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)(uZ,{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:m(`text-muted-foreground hover:text-foreground`,`mt-auto flex items-center gap-2`),children:[(0,K.jsx)(pQ,{}),(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:n?.split(`/`)?.pop()})]})]}),i&&(0,K.jsx)(a3r,{data:i,labelsAreHidden:!0,isLoading:r})]})]})}function zLi(e){switch(e){case`running`:return(0,K.jsx)(Zc,{size:`sm`,"aria-hidden":!0});case`success`:return(0,K.jsx)(Bn,{"aria-hidden":!0});case`failed`:return(0,K.jsx)(Vc,{"aria-hidden":!0});default:return null}}function BLi(){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 VLi({status:e,variant:t}){return t===`plain`?(0,K.jsx)(`span`,{className:m(`flex size-4 items-center justify-center self-center [&>svg]:size-4`,b.colors,{"[&>svg]:text-success-indicator":e===`success`,"[&>svg]:text-destructive-foreground":e===`failed`}),children:e===`pending`?(0,K.jsx)(BLi,{}):zLi(e)}):(0,K.jsx)(`span`,{className:m(`flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none`,b.colors,b.transform,{"[&>svg]:text-success-indicator":e===`success`,"[&>svg]:text-destructive-foreground":e===`failed`,"border border-dashed border-placeholder":e===`pending`,"[&>svg]:size-4":e!==`running`,"bg-success-subtle":e===`success`,"bg-destructive-subtle":e===`failed`,"scale-110":e===`success`||e===`failed`}),children:zLi(e)})}function HLi({step:e,isActive:t,position:n,variant:r=`default`}){let i=t||e.status===`success`?`ink`:`muted`;return(0,K.jsxs)(`div`,{className:m(`grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none`,b.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:m(`flex min-w-6 justify-end`,b.colors),children:[n,`.`]}),(0,K.jsxs)(`div`,{className:`min-w-0`,children:[(0,K.jsx)(T,{as:`h4`,tone:i,className:b.colors,children:e.title}),e.description&&(0,K.jsx)(T,{tone:`faint`,className:m(`-mt-0.5`,{truncate:r===`plain`}),children:e.description})]})]}),(0,K.jsx)(VLi,{status:e.status,variant:r})]})}function ULi({currentStep:e,steps:t=[],className:n}){return(0,K.jsx)(`div`,{className:m(n),children:t.map((t,n)=>(0,K.jsx)(HLi,{step:t,isActive:e?.id===t.id,position:n+1},t.id))})}function WLi({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:m(`relative flex h-8 items-center justify-end`,b.colors,{"bg-success-subtle":t.status===`success`&&e?.[n-1]?.status===`success`}),children:(0,K.jsx)(`div`,{className:m(`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`,b.colors,b.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)(Zc,{}):n+1})},t.id))}),(0,K.jsxs)(`div`,{className:m(`text-center text-caption text-muted-foreground`,b.colors),children:[n,` of `,t,` steps completed`]})]})}var GLi=(0,G.createContext)(3);function KLi({title:e,description:t,action:n,done:r,className:i,children:a}){let o=(0,G.useContext)(GLi);return(0,K.jsxs)(`li`,{className:m(`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:m(`flex size-6 shrink-0 items-center justify-center rounded-full`,b.colors,r?`bg-success-indicator/18 text-success-indicator`:`bg-fill text-foreground`),children:r?(0,K.jsx)(Bn,{className:`size-3.5`,"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 qLi({headingLevel:e=3,className:t,children:n}){return(0,K.jsx)(GLi.Provider,{value:e,children:(0,K.jsx)(`ol`,{className:m(`flex flex-col [counter-reset:ds-step]`,t),children:n})})}Object.assign(qLi,{Step:KLi});function JLi({name:e,streamResult:t,runId:n,workflowInfo:r}){let i=t?.phase||`initializing`,a=t?.payload?.workflowState,o=t?.payload?.currentStep,s=t?.error,c=a?.steps||{},l=Object.keys(c).length>0,u=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,d=Object.entries(c).filter(([e,t])=>u(e)),f=d.length,p=()=>{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=d.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)(FLi,{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:p()}),(t?.runId||n)&&(0,K.jsxs)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`mt-2`,children:[`Run ID: `,t?.runId??n]})]}),l&&f>0&&![`error`].includes(i)&&(0,K.jsx)(`div`,{className:`mx-auto w-full max-w-[30rem] px-4`,children:(0,K.jsx)(WLi,{steps:h})}),s&&i===`error`&&(0,K.jsxs)(`div`,{className:m(`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)(xo,{}),(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:s||`Something went wrong`})]}),l&&(0,K.jsx)(ULi,{steps:h,currentStep:o,className:`pb-4`}),!l&&i===`initializing`&&(0,K.jsxs)(`div`,{className:m(`text-muted-foreground`,`grid justify-items-center gap-4 text-center`),children:[(0,K.jsx)(Zc,{}),(0,K.jsx)(T,{as:`p`,variant:`body`,children:`This may take some time...`})]})]})}function YLi({name:e,installedEntities:t}){return(0,K.jsxs)(FLi,{className:m(`grid content-center items-center justify-items-center gap-4`,`[&>svg]:h-8 [&>svg]:w-8`),children:[(0,K.jsx)(wo,{}),(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)(a3r,{data:t})]})}function XLi(){let{templateSlug:e}=Ab(),t=[{id:`templates`,label:`Templates`,to:`/templates`},{id:`template`,label:LLt(e)}],[n,r]=Hb(),[i,a]=(0,G.useState)(``),[o,s]=(0,G.useState)(``),[c,l]=(0,G.useState)(``),[u,d]=(0,G.useState)({}),[f,p]=(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}=yLi({repoOrSlug:e,owner:`mastra-ai`}),k=`1.84.0-alpha.0`.includes(`beta`)??!1?`beta`:`main`,{data:A,isLoading:j}=bLi({repo:D?.githubUrl?new URL(D.githubUrl).pathname.split(`/`)[2]:`template-${e}`,owner:`mastra-ai`,branch:k}),{data:M,isLoading:N}=xLi(),{mutateAsync:P,isPending:F}=SLi(),{mutateAsync:I}=CLi(),{streamInstall:L,streamResult:R,isStreaming:z}=OLi({workflowInfo:M}),{observeInstall:B,streamResult:V,isStreaming:H}=kLi({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)(aF,{})},{key:`agents`,label:`Agents`,value:D?.agents?.length?D.agents.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(tF,{})},{key:`workflows`,label:`Workflows`,value:D?.workflows?.length?D.workflows.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(Lc,{})},{key:`providers`,label:`Providers`,value:D?.supportedProviders?.length?D.supportedProviders.join(`, `):`n/a`,icon:(0,K.jsx)(Dn,{})},{key:`tags`,label:`Tags`,value:D?.tags?.length?D.tags.join(`, `):`n/a`,icon:(0,K.jsx)(Zs,{})}],U=[{...te[0]},{...te[1]},{...te[2]}].filter(e=>e.value!==`n/a`);return(0,G.useEffect)(()=>{A&&d(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)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(`div`,{className:m(`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)(RLi,{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)(JLi,{name:D.title,streamResult:H?V:R,runId:y,workflowInfo:M}),_&&(0,K.jsx)(YLi,{name:D.title,installedEntities:U,linkComponent:Vb}),h&&(0,K.jsx)(ILi,{errorMsg:h,validationErrors:T.length>0?T:R?.validationResults?.errors||V?.validationResults?.errors}),!z&&!H&&!_&&!h&&(0,K.jsx)(LLi,{providerOptions:ee,selectedProvider:i,onProviderChange:e=>{a(e)},variables:u,setVariables:d,errors:f,setErrors:p,handleInstallTemplate:async()=>{let e=Object.entries(u).reduce((e,[t,n])=>(n===``&&e.push(t),e),[]);if(e.length>0)p(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:u},{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:c},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()===``?p(e=>[...e,t]):p(e=>e.filter(e=>e!==t)),d(e=>({...e,[t]:n}))},isLoadingEnvVars:j||N,isInstalling:F,defaultModelProvider:o,defaultModelId:c,onModelUpdate:async e=>(s(e.provider),l(e.modelId),{message:`Model updated successfully`})})]})]})})]})}var ZLi=e=>e.threadId;function QLi(e,t){return`traces`in e?{traces:{...e.traces,to:t}}:{threads:{...e.threads,to:t}}}var $Li=e=>`traces`in e?e.traces:e.threads;function eRi(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 tRi({query:e,rolling:t,autoRefetch:n=!0,limit:r,enabled:i=!0}){let a=Y(),{anchorTo:o,reanchor:s}=VIi(e),c=(0,G.useMemo)(()=>o?{...e,timeRange:QLi(e.timeRange,o)}:e,[e,o]),l=N$r({query:c,limit:r,enabled:i,queryOptions:LIi}),{headRows:u}=UIi({queryKey:[`threads`,e],fetchHead:async t=>(await a.queryTraceThreads({...e,timeRange:QLi(e.timeRange,t),orderBy:[{field:`endedAt`,direction:`desc`}],page:{limit:50}})).threads,getId:ZLi,getEndedAt:e=>e.endedAt,since:Date.parse($Li(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&&GIi(f,u,{getId:ZLi,compare:eRi(d),hasNextPage:l.hasNextPage}),[f,u,d,l.hasNextPage]);return{...l,threads:p}}function nRi(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 rRi=[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`],iRi=[];function aRi(){let{data:e}=n5(),t=e?.capabilities.traceQueryTimeToFirstChunk??!1,n=e?.capabilities.traceQueryTimeToFirstToken??!1,{data:r=iRi}=g8(),{data:i=iRi}=_8();return(0,G.useMemo)(()=>[R5r,...ali({withTimeToFirstChunk:t,withTimeToFirstToken:n,entityNames:r,environments:i})],[t,n,r,i])}function oRi({tokens:e,groups:t,onFiltersChange:n}){let r=(0,G.useMemo)(()=>m0r(e),[e]),i=(0,G.useMemo)(()=>{let e=_0r([],t);return{...e,nodes:[d5,...r,...e.nodes]}},[r,t]),a=(0,G.useCallback)(e=>{let t=y0r({...e,nodes:e.nodes.filter(e=>o8(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(o8);a({...i,nodes:[...n,o,...s]})},[r,i,a])}}var sRi=e=>e;function cRi({datePreset:e,dateFrom:t,dateTo:n,minDate:r,tokens:i,groups:a,onDatePresetChange:o,onDateChange:s,onDateRangeChange:c,onFiltersChange:l,disabled:u}){let d=aRi(),{filterBarValue:f,onFilterBarChange:p}=oRi({tokens:i,groups:a,onFiltersChange:l});return(0,K.jsxs)(f5,{fields:d,operators:H1r,value:f,onValueChange:p,createItemId:sRi,maxDepth:3,"aria-label":`Thread filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(f5.Chips,{renderChip:i=>i.fieldId===`timeRange`?(0,K.jsx)(f5.TimeRange,{preset:e,onPresetChange:o,dateFrom:t,dateTo:n,minDate:r,onDateChange:s,onDateRangeChange:c,disabled:u,presets:rRi,defaultPreset:i5.datePreset}):(0,K.jsx)(f5.Chip,{item:i})}),(0,K.jsx)(f5.Input,{placeholder:`Filter threads`})]})}function lRi({selectedThreadId:e,onSelectedThreadChange:t,onOpenScore:n,urlState:r}){let i=zIi(r),{timeRange:a,tokens:o,groups:s,sort:c}=i,l=r5().enabled,u=L6r().enabled,d=jsi({scope:`threads`}),{data:f,isLoading:p}=n5(),m=f?.capabilities.traceQueryTimeToFirstChunk??!1,h=f?.capabilities.traceQueryTimeToFirstToken??!1,g=(0,G.useMemo)(()=>p?d.preferences:$3r(d.preferences,{withTimeToFirstChunk:m,withTimeToFirstToken:h}),[d.preferences,p,m,h]),{threads:_,hasNextPage:v,isFetchingNextPage:y,setEndOfListElement:b,isLoading:x,isError:S,error:C}=tRi({query:(0,G.useMemo)(()=>{let e=cli(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(nRi),[_]),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)(C6r,{toolbar:(0,K.jsxs)(K.Fragment,{children:[r&&(0,K.jsx)(sui,{page:`threads`,...r,columns:d}),(0,K.jsxs)(jq,{children:[(0,K.jsx)(jq.Start,{children:(0,K.jsx)(cRi,{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)(jq.End,{children:(0,K.jsx)(B6r,{scope:`threads`,value:d.preferences,onChange:d.setPreferences})})]})]}),error:S?(0,K.jsx)(X8,{error:C,resource:`threads`,errorTitle:`Failed to load threads`}):void 0,empty:D?(0,K.jsx)(j3r,{resource:`threads`,datePreset:i.datePreset,dateFrom:i.dateFrom,dateTo:i.dateTo}):void 0,children:(0,K.jsx)(Wti,{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)(gsi,{open:!!e,threadId:e??``,depth:1,closeLabel:`Close`,withQueryTrace:l,withFeedback:u,onOpenScore:n,onClose:()=>t(void 0)})]})}function uRi(){let{enabled:e,isLoading:t}=j6r(),n=kb(),[r,i]=Hb();return(0,K.jsx)(IIi,{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)(lRi,{urlState:{searchParams:r,setSearchParams:i},selectedThreadId:ZIi(r),onSelectedThreadChange:e=>i(t=>QIi(t,e),{replace:!0}),onOpenScore:(e,t)=>n(kq(e,t))})})}var dRi=()=>(0,K.jsx)(RC,{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)(Br,{}),children:`Workflows documentation`}),variant:`fill`});function fRi(e,t,n){return yQ(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 pRi(e){return Object.keys(e.steps??{}).filter(t=>e.allSteps?.[t]?.isWorkflow)}function mRi(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 hRi(e,t,n){let r=mRi(t),i=[],a=(e,o,s,c,l,u)=>{let d=pRi(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 gRi=`auto 24rem minmax(0, 1fr) auto auto auto`;function _Ri({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:m(`w-6`,e&&`border-l border-border`)},t)),(0,K.jsxs)(`span`,{className:`relative w-6`,children:[(0,K.jsx)(`span`,{className:m(`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 vRi({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:m(ZC,`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 yRi=e=>e.stopPropagation();function bRi({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 xRi({row:e,isExpanded:t,onToggle:n,runCount:r,rowProps:i}){let{paths:a,Link:o}=gl(),s=(0,G.useRef)(null),{workflow:c,nestedIds:l}=e,u=fY(c.name,50),d=fY(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)(vRi,{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:yRi,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)(_Ri,{guides:e.guides,isLastChild:e.isLastChild}):null,(0,K.jsx)(`span`,{className:`truncate`,children:u}),c.origin===`dynamic`?(0,K.jsx)(bw,{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)(Lc,{"aria-hidden":!0,className:`size-3.5`}),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)(No,{"aria-hidden":!0,className:`size-3.5`}),m]}):``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:f||``})]})]})}function SRi({workflows:e,isLoading:t,search:n=``,sort:r,onSortChange:i,requestContext:a}){let[o,s]=(0,G.useState)(new Set),c=xMt({requestContext:a}),l=(0,G.useMemo)(()=>Object.entries(e).map(([e,t])=>({...t,id:e})),[e]),u=(0,G.useMemo)(()=>{let e=n.toLowerCase();return l.filter(t=>t.name?.toLowerCase().includes(e)||t.description?.toLowerCase().includes(e))},[l,n]),d=(0,G.useMemo)(()=>fRi(u,r,c),[u,r,c]),f=(0,G.useMemo)(()=>hRi(d,e,o),[d,e,o]),p=(0,G.useMemo)(()=>{let e=new Map;for(let t of f)t.kind===`workflow`&&e.set(t.pathKey,e.size);return e},[f]),{containerRef:h,getRowProps:g}=_Q({count:p.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)(NU,{columns:gRi,fit:`container`}):(0,K.jsxs)(Z,{columns:gRi,fit:`container`,scrollRef:h,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)(bRi,{sortKey:`name`,sort:r,onSortChange:i,children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`Description`}),(0,K.jsx)(bRi,{sortKey:`running`,sort:r,onSortChange:i,children:`Running`}),(0,K.jsx)(bRi,{sortKey:`suspended`,sort:r,onSortChange:i,children:`Pending input`}),(0,K.jsx)(bRi,{sortKey:`steps`,sort:r,onSortChange:i,children:`Number of steps`})]}),f.length===0&&n?(0,K.jsx)(Z.NoMatch,{message:`No Workflows match your search`}):null,f.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)(vRi,{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)(_Ri,{guides:e.guides,isLastChild:e.isLastChild}),(0,K.jsx)(`span`,{className:`truncate`,children:fY(e.stepId,50)}),(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{render:(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`muted`}),role:`note`,tabIndex:0,className:m(`shrink-0 rounded-sm`,_),children:`not registered`}),(0,K.jsx)(CC,{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:fY(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)(xRi,{row:e,isExpanded:t,onToggle:n,runCount:c[e.workflow.id],rowProps:g(p.get(e.pathKey)??-1)},`workflow-${e.pathKey}`)})]})}var W9=[sF(`/workflows`)];function CRi(){let{data:e,isLoading:t,error:n}=sP(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)();return n&&JP(n)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(jU,{variant:`fill`})]}):n&&YP(n)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(AU,{variant:`fill`,resource:`workflows`})]}):n?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load workflows`,descriptionSlot:n.message})]}):Object.keys(e||{}).length===0&&!t?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(dRi,{})]}):(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:W9}),actionRow:(0,K.jsxs)(jq,{children:[(0,K.jsx)(jq.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(zU,{onSearch:i,label:`Filter workflows`,placeholder:`Filter by name or description`})})}),(0,K.jsx)(jq.End,{children:(0,K.jsx)(X,{render:(0,K.jsx)(Vb,{to:`/workflows/schedules`}),variant:`primary`,icon:(0,K.jsx)(Nn,{}),children:`Schedules`})})]}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(SRi,{workflows:e||{},isLoading:t,search:r,sort:a,onSortChange:(e,t)=>o({key:t,direction:e})})]})}var wRi={active:`bg-success-indicator`,paused:`bg-info-indicator`,completed:`bg-muted-foreground`},TRi={active:`text-success-indicator`,paused:`text-info-indicator`,completed:`text-muted-foreground`},ERi=({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 ${wRi[e]}`,"aria-hidden":!0}),(0,K.jsx)(T,{as:`span`,variant:`caption`,className:TRi[e],children:e})]});function DRi({status:e}){let{icon:t,color:n}=ORi(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 ORi(e){switch(e){case`success`:return{icon:(0,K.jsx)(Bn,{size:14}),color:`text-success-indicator`};case`failed`:return{icon:(0,K.jsx)(Vc,{size:14}),color:`text-destructive-foreground`};case`running`:return{icon:(0,K.jsx)(Zc,{}),color:`text-muted-foreground`};case`suspended`:return{icon:(0,K.jsx)(Zn,{size:14}),color:`text-info-indicator`};case`canceled`:return{icon:(0,K.jsx)(tr,{size:14}),color:`text-muted-foreground`};case`pending`:case`waiting`:return{icon:(0,K.jsx)(lr,{size:14}),color:`text-muted-foreground`};default:return{icon:null,color:`text-muted-foreground`}}}var kRi=`auto auto auto auto 1fr`,ARi=3e4,jRi=3e5;function MRi({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:i,setEndOfListElement:a}){let{Link:o,paths:s}=gl(),c=e=>!!(n&&e.runId&&e.outcome!==`failed`),l=e.filter(c).length,{containerRef:u,getRowProps:d}=_Q({count:l}),f=-1;return t?(0,K.jsx)(NU,{columns:kRi}):e.length===0?(0,K.jsx)(T,{variant:`body`,tone:`muted`,className:`p-4`,children:`No trigger history yet.`}):(0,K.jsxs)(Z,{columns:kRi,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=xw(t,{signed:!0}),i=e.outcome===`failed`,a=i?e.error:e.run?.error,l=Math.abs(t),u=!i&&l>ARi&&l<=jRi,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)(Cc,{size:14}),`publish failed`]}):e.run?(0,K.jsx)(DRi,{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)(xC,{children:[(0,K.jsx)(SC,{asChild:!0,children:(0,K.jsx)(`span`,{className:`inline-flex text-destructive-foreground`,children:(0,K.jsx)(Cc,{size:14})})}),(0,K.jsx)(CC,{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)(jA,{value:e.actualFireAt}):`—`,u?(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{asChild:!0,children:(0,K.jsx)(`span`,{className:`inline-flex text-info-indicator`,children:(0,K.jsx)(Cc,{size:14})})}),(0,K.jsxs)(CC,{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:xw(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 NRi={id:`workflow-schedules`,label:`Schedules`,icon:Nn,to:`/workflows/schedules`};function PRi({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 FRi(){let{scheduleId:e}=Ab(),t=[sF(`/workflows`),NRi,{id:`schedule`,label:LLt(e),icon:Nn}],{paths:n}=gl(),{data:r,error:i}=tRt({scheduleId:e,queryOptions:{enabled:!!e}}),{data:a,isLoading:o,error:s,hasNextPage:c,isFetchingNextPage:l,setEndOfListElement:u}=rRt({scheduleId:e,queryOptions:{enabled:!!e}}),d=iRt({scheduleId:e});if(i&&JP(i))return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(jU,{variant:`fill`})]});if(i&&YP(i))return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(AU,{variant:`fill`,resource:`schedules`})]});if(i)return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load schedule`,descriptionSlot:i.message})]});let f=r?.workflowId,p=r?.agentId;return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:t}),actionRow:(0,K.jsx)(jq,{children:(0,K.jsxs)(jq.End,{children:[(0,K.jsx)(X,{render:(0,K.jsx)(Vb,{to:n.schedulesLink()}),variant:`ghost`,icon:(0,K.jsx)(Rt,{}),children:`Back to schedules`}),f?(0,K.jsx)(X,{icon:(0,K.jsx)(rP,{}),render:(0,K.jsx)(Vb,{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:()=>UC.success(e===`pause`?`Schedule paused`:`Schedule resumed`),onError:e=>UC.error(e.message)})},disabled:d.isPending,"data-testid":`schedule-toggle-button`,children:r.status===`active`?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(No,{}),`Pause`]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Vo,{}),`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)(PRi,{label:p?`Agent`:`Workflow`,children:f?(0,K.jsx)(Vb,{to:n.workflowLink(f),className:`text-foreground hover:underline`,children:f}):p?(0,K.jsx)(Vb,{to:n.agentLink(p),className:`text-foreground hover:underline`,children:p}):`—`}),(0,K.jsxs)(PRi,{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)(PRi,{label:`Status`,children:(0,K.jsx)(ERi,{status:r.status})}),(0,K.jsx)(PRi,{label:`Next fire`,children:r.nextFireAt?(0,K.jsx)(jA,{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)(RC,{tone:`error`,titleSlot:`Failed to load trigger history`,descriptionSlot:s.message}):(0,K.jsx)(MRi,{triggers:a??[],isLoading:o,workflowId:f,hasNextPage:c,isFetchingNextPage:l,setEndOfListElement:u})]})]}):null]})}var IRi={target:e=>e.workflowId??e.agentId??``,status:e=>e.status,nextFireAt:e=>e.nextFireAt,lastFireAt:e=>e.lastFireAt},LRi=`minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto`;function RRi({schedules:e,isLoading:t,search:n=``,sort:r,onSortChange:i}){let{paths:a,Link:o}=gl(),s=(0,G.useMemo)(()=>{let t=n.toLowerCase();return yQ(t?e.filter(e=>e.id.toLowerCase().includes(t)||(e.workflowId??e.agentId??``).toLowerCase().includes(t)):e,r,IRi)},[e,n,r]),{containerRef:c,getRowProps:l}=_Q({count:s.length,global:!0});if(t)return(0,K.jsx)(NU,{columns:LRi});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:LRi,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)(ERi,{status:e.status})}),(0,K.jsx)(Z.Cell,{children:e.nextFireAt?(0,K.jsx)(jA,{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)(DRi,{status:e.lastRun.status}),e.lastFireAt?(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:(0,K.jsx)(jA,{value:e.lastFireAt})}):null]}):e.lastFireAt?(0,K.jsx)(jA,{value:e.lastFireAt}):(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`Never`})})]},e.id))]})}function zRi({workflowId:e}={}){let{data:t,isLoading:n,error:r}=uF(e?{workflowId:e}:{}),[i,a]=(0,G.useState)(``),[o,s]=(0,G.useState)();return r?(0,K.jsx)(RC,{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)(zU,{onSearch:a,label:`Filter schedules`,placeholder:`Filter by id or workflow`})}),(0,K.jsx)(`div`,{className:`overflow-y-auto`,children:(0,K.jsx)(RRi,{schedules:t??[],isLoading:n,search:i,sort:o,onSortChange:(e,t)=>s({key:t,direction:e})})})]})}var BRi=[sF(`/workflows`),NRi];function VRi(){let[e]=Hb(),t=e.get(`workflowId`)??void 0,{error:n}=uF(t?{workflowId:t}:{});return n&&JP(n)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:BRi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(jU,{variant:`fill`})]}):n&&YP(n)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:BRi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(AU,{variant:`fill`,resource:`schedules`})]}):(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:BRi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(`div`,{className:`h-full`,children:(0,K.jsx)(zRi,{workflowId:t})})]})}var HRi={"--belt-hue":`var(--warning-indicator)`};function URi(e){let t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function WRi(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 GRi({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:(0,K.jsxs)(`section`,{className:m(FMt,`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)(TC,{children:(0,K.jsx)(Zn,{})}),`Step suspended`]}),(0,K.jsx)(bw,{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?Kk(lA(n.resumeSchema)):Rp(q(),kp());return(0,K.jsx)(KRi,{step:e,stepSchema:i,description:n.description,onResume:r},`${e.runId}-${e.stepId}`)})]}),(0,K.jsx)(c4e,{status:`ready`,label:`Needs input`,className:`before:hidden`,style:HRi})]})}function KRi({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)(TC,{children:(0,K.jsx)(fo,{})}),`The step is asking`]}),(0,K.jsxs)(Hw,{open:i,onOpenChange:a,children:[(0,K.jsxs)(Uw,{className:m(`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)(TC,{children:(0,K.jsx)(y,{direction:`right`,className:`text-muted-foreground`})}),(0,K.jsx)(T,{as:`span`,variant:`body`,tone:`ink`,className:`truncate`,children:WRi(e.suspendPayload,e.stepId)})]}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`shrink-0`,children:URi(e.suspendPayload)})]}),(0,K.jsx)(Ww,{children:(0,K.jsx)(`div`,{"data-testid":`suspended-payload`,className:`pt-2`,children:(0,K.jsx)(FT,{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)(TC,{children:(0,K.jsx)(mo,{})}),`Your response`]}),(0,K.jsx)(`div`,{className:`-mx-5`,children:(0,K.jsx)(Zjt,{schema:t,isSubmitLoading:o,submitButtonLabel:`Resume`,submitButtonVariant:`primary`,submitButtonIcon:(0,K.jsx)(Vo,{}),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){UC.error(e instanceof Error?e.message:`Error resuming workflow`)}finally{s(!1)}}})})]})]})}function qRi({hidden:e,requestContext:t,canResume:n}){let{result:r,workflow:i,runId:a,isStreamingWorkflow:o}=(0,G.useContext)(gw),s=Yvt(r,a),c=eyt(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)(GRi,{suspendedSteps:s,workflow:i,isStreaming:o,onResume:c})},a)}var JRi={success:{label:`Completed`,icon:Bn},failed:{label:`Failed`,icon:ir},suspended:{label:`Needs input`,icon:No},waiting:{label:`Waiting`,icon:_c},paused:{label:`Paused`,icon:No},skipped:{label:`Skipped`,icon:Ns},running:{label:`Running`,icon:Ea},canceled:{label:`Canceled`,icon:tr}},YRi={label:`Status unavailable`,icon:Cee};function XRi({row:e,isSelected:t,isHovered:n,onSelectStep:r,onHoverStep:i,onOpenInput:a,onOpenOutput:o}){let s=Object.hasOwn(JRi,e.status)?JRi[e.status]:YRi,c=s.icon,l=Rbt(e.status),u=e.stepId.slice(0,e.stepId.lastIndexOf(`.`)),d=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:m(`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:m(`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`,_),children:[(0,K.jsx)(`span`,{"aria-label":s.label,className:m(`grid size-6 flex-none place-items-center rounded-md border border-border bg-background`,zbt[l]),children:(0,K.jsx)(c,{"aria-hidden":!0,className:m(`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:d}),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)(Cr,{"aria-hidden":!0,className:`size-3 shrink-0`}),(0,K.jsx)(`span`,{className:`truncate`,children:u})]})]})]}),(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:m(`absolute top-0 h-full min-w-0.5 rounded-sm`,Bbt[l]),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:xw(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)(Mt,{})}),(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)(Kt,{})})]})]})}var ZRi=e=>e.includes(`.`),QRi=e=>e===`input`||e.endsWith(`.input`),$Ri=1;function ezi(e,t){let n=Ubt(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 tzi(e,t){let n=Object.entries(e).filter(([e])=>!QRi(e)).map(([e,n])=>({stepId:e,step:n,...ezi(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,$Ri),100-t)}}return{stepId:e,step:t,status:OA(t)?`suspended`:t.status,timing:s,spansSuspension:a,isRunning:r,isNestedEntry:ZRi(e)}})}function nzi(){let{steps:e}=B$(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:i}=hw(),[a,o]=(0,G.useState)(()=>Date.now()),[s,c]=(0,G.useState)(!0),[l,u]=(0,G.useState)(!1),{showData:d}=lP(),f=(0,G.useRef)(null),p=tzi(e,a),h=p.some(e=>e.isRunning);return H1e(f,{enabled:h&&!s}),(0,G.useEffect)(()=>{if(!h||s)return;let e=setInterval(()=>o(Date.now()),100);return()=>clearInterval(e)},[h,s]),p.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)(Hw,{open:!s,onOpenChange:e=>c(!e),className:m(Wb,`@container/workflow-timeline pointer-events-auto overflow-hidden rounded-xl`),children:[(0,K.jsxs)(`div`,{className:`flex items-center`,children:[(0,K.jsxs)(Uw,{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)(zn,{"aria-hidden":!0,className:`size-4 text-muted-foreground`})}),(0,K.jsx)(`span`,{children:`Timeline`}),(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,children:[p.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:l?`Restore timeline height`:`Enlarge timeline`,"aria-pressed":l,onClick:()=>u(!l),className:`mr-2 shrink-0`,children:l?(0,K.jsx)(lee,{}):(0,K.jsx)(hee,{})})]}),(0,K.jsx)(Ww,{children:(0,K.jsx)(`div`,{ref:f,"data-testid":`workflow-timeline-list`,className:m(`overflow-auto overscroll-contain px-1.5 pb-1.5`,l?`max-h-[min(720px,calc(100dvh-112px))]`:`max-h-[min(320px,40dvh)]`),children:p.map(e=>(0,K.jsx)(XRi,{row:e,isSelected:t===e.stepId,isHovered:n===e.stepId,onSelectStep:r,onHoverStep:i,onOpenInput:(e,t)=>d({type:`step-input`,stepId:e.stepId},t),onOpenOutput:(e,t)=>d({type:`step-output`,stepId:e.stepId},t)},e.stepId))})})]})})}var rzi=({workflowId:e,workflow:t,isLoading:n})=>{let[r]=mw(`workflow`,e),{canExecute:i,isLoading:a}=KC(),{stepDetail:o}=lP(),s=fE(),c=o?.type===`data`,l=(0,K.jsxs)(`div`,{className:`[container-type:size] relative h-full min-h-0`,children:[(0,K.jsx)(zmr,{workflowId:e,workflow:t,isLoading:n,requestContext:r}),(0,K.jsx)(qRi,{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)(H$,{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)(nzi,{})})]});return s&&o&&!c?(0,K.jsx)(`div`,{className:`h-full min-h-0 overflow-hidden`,children:(0,K.jsx)(H$,{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)(N6,{id:`workflow-graph`,className:`pointer-events-none min-w-0`}),o&&!c&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(F6,{className:`pointer-events-auto`}),(0,K.jsx)(N6,{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)(H$,{requestContext:r})})})]})]})]})},izi=()=>{let{workflowId:e}=Ab(),{data:t,isLoading:n,error:r}=cP({workflowId:e,requestContext:mw(`workflow`,e)[0],queryOptions:{enabled:!!e}});return r&&JP(r)?(0,K.jsx)(jU,{variant:`fill`}):r&&YP(r)?(0,K.jsx)(AU,{variant:`fill`,resource:`workflows`}):(0,K.jsx)(rzi,{workflowId:e,workflow:t??void 0,isLoading:n})};function azi(){let{workflowId:e}=Ab(),{error:t}=uF(e?{workflowId:e}:{});if(!e)return null;let n;return n=t&&JP(t)?(0,K.jsx)(jU,{variant:`fill`}):t&&YP(t)?(0,K.jsx)(AU,{variant:`fill`,resource:`schedules`}):(0,K.jsx)(`div`,{className:`h-full`,children:(0,K.jsx)(zRi,{workflowId:e})}),(0,K.jsxs)(uw,{children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),n]})}function ozi(){let{workflowId:e}=Ab();return e?(0,K.jsx)(qui,{scopedEntityId:e,scopedEntityType:kh.WORKFLOW_RUN}):null}var szi=(0,G.createContext)(null);function G9(){let e=(0,G.useContext)(szi);if(!e)throw Error(`Workspace components must be rendered inside <Workspace.Root>`);return e}var czi=e=>e?.status;function lzi(e,t){return JP(e)?`Your session has expired. Sign in again to continue.`:YP(e)?`You don't have permission to access this.`:XP(e)?`This path no longer exists.`:czi(e)===501?`This workspace does not support this operation.`:t}function uzi({error:e,fallback:t,className:n}){return(0,K.jsx)(EA,{variant:`destructive`,className:n,children:(0,K.jsx)(EA.Message,{children:lzi(e,t)})})}var dzi=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;function fzi(e){let t=dzi.exec(e);return t?{frontmatter:t[1]??``,body:e.slice(t[0].length)}:{frontmatter:null,body:e}}function pzi({content:e}){let{frontmatter:t,body:n}=fzi(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)(pY,{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)(xX,{children:n})})]})}function mzi(){let{activeFilePath:e}=G9();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 hzi({path:e,content:t,mimeType:n}){return oVn(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`})}):sVn(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:${lVn(e,n)};base64,${t}`,type:lVn(e,n)})})}):uVn(e)?(0,K.jsx)(pzi,{content:t}):(0,K.jsx)(pY,{code:t,lang:U2e(e),overflow:`scroll`,className:`rounded-none border-0 bg-transparent [&_pre]:p-4`})}function gzi({renderPreview:e}){let{workspaceId:t,activeFilePath:n}=G9(),{data:r,isLoading:i,error:a}=TVn({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)(dw,{className:`h-4 w-1/2`}),(0,K.jsx)(dw,{className:`h-4 w-5/6`}),(0,K.jsx)(dw,{className:`h-4 w-2/3`})]});if(!r)return(0,K.jsx)(uzi,{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)(hzi,{...o})}var _zi=(e,t)=>e===`.`?t:`${e}/${t}`,vzi=e=>e.split(`/`).slice(0,-1).map((e,t,n)=>n.slice(0,t+1).join(`/`)),yzi=e=>{let t=e.lastIndexOf(`/`);return t===-1?`.`:e.slice(0,t)};function bzi({labeled:e=!1}={}){let{workspaceId:t,onCreateDirectory:n,isReadOnly:r}=G9(),i=dy(),[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`,yzi(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)(xi,{}),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)(xi,{})}),(0,K.jsx)(_E,{open:a,onOpenChange:o,pending:l,children:(0,K.jsx)(vE,{size:`sm`,children:(0,K.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),f()},children:[(0,K.jsx)(yE,{children:(0,K.jsx)(SE,{children:`New folder`})}),(0,K.jsx)(xE,{children:(0,K.jsx)(ZM,{autoFocus:!0,"aria-label":`Folder path`,placeholder:`docs/guides`,value:s,onChange:e=>c(e.target.value)})}),(0,K.jsxs)(bE,{children:[(0,K.jsx)(wE,{children:`Cancel`}),(0,K.jsx)(X,{type:`submit`,variant:`primary`,disabled:!d||l,children:`Create`})]})]})})})]})}function xzi(e){return`${e.topSource}/${e.name}`}function Szi(e){let t=mVn(e.topSource,e.name);return t?`${t.owner}/${t.repo}/${e.name}`:null}function Czi({open:e,onOpenChange:t,workspaceId:n,onInstall:r,isInstalling:i,installedSkillIds:a=[],installedSkillNames:o=[],writableMounts:s,installedSkillPaths:c}){let[l,u]=(0,G.useState)(``),[d,f]=(0,G.useState)(null),[p,h]=(0,G.useState)(),g=s?.some(e=>e.path===p)?p:s?.[0]?.path,{data:_,isLoading:v}=fVn({workspaceId:n,queryOptions:{enabled:!!n}}),y=dVn({workspaceId:n}),b=(0,G.useMemo)(()=>d?.topSource?mVn(d.topSource,d.name):null,[d]),x=(0,G.useMemo)(()=>!b||!d?null:`https://skills.sh/${b.owner}/${b.repo}/${d.name}`,[b,d]),{data:S,isLoading:C}=pVn({workspaceId:n,owner:b?.owner,repo:b?.repo,skillPath:d?.name,queryOptions:{enabled:!!n&&!!b&&!!d}}),w=Tw(e=>{e.trim().length>=2&&y.mutate(e)},300),E=(0,G.useCallback)(e=>{u(e),w(e)},[w]),D=(0,G.useMemo)(()=>l.trim().length>=2?y.data?.skills??[]:_?.skills??[],[l,y.data,_]),O=y.isPending,k=l.trim().length>=2,A=(0,G.useMemo)(()=>{if(!d)return!1;let e=Szi(d);return!!(e&&a.includes(e)||o.includes(d.name))},[d,a,o]),j=(0,G.useCallback)(()=>{d&&b&&r({repository:`${b.owner}/${b.repo}`,skillName:d.name,mount:s&&s.length>1?g:void 0})},[d,b,r,s,g]),M=(0,G.useCallback)(e=>{e||(u(``),f(null),h(void 0)),t(e)},[t]);return(0,K.jsx)(_E,{open:e,onOpenChange:M,pending:i,children:(0,K.jsxs)(vE,{size:`xl`,className:`h-[80vh]`,children:[(0,K.jsxs)(yE,{children:[(0,K.jsx)(SE,{children:`Add Skill`}),(0,K.jsx)(CE,{children:`Search and install skills from the community registry`})]}),(0,K.jsxs)(xE,{layout:`fill`,children:[(0,K.jsx)(RU,{label:`Search skills`,placeholder:`Search skills`,value:l,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)(lw,{className:`flex-1 rounded-lg border border-border`,children:(0,K.jsx)(cw,{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)(Ea,{className:`size-6 animate-spin text-muted-foreground`})}):D.length===0?(0,K.jsxs)(`div`,{className:`flex flex-1 flex-col items-center-safe justify-center-safe py-5 text-muted-foreground`,children:[(0,K.jsx)(tr,{className:`mb-2 size-8`}),(0,K.jsx)(T,{children:k?`No skills found`:`No skills available`})]}):(0,K.jsx)(`div`,{className:`space-y-1 p-2`,children:D.map(e=>{let t=xzi(e),n=Szi(e),r=n&&a.includes(n)||o.includes(e.name),i=d?xzi(d):null;return(0,K.jsx)(`button`,{onClick:()=>f(e),className:m(`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)(Bn,{className:`size-2.5`}),`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)(Dr,{className:`size-3`}),(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:d?(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)(mQ,{className:`size-5 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:d.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)(pQ,{className:`size-3`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`block`,children:d.topSource})]}),(0,K.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(Dr,{className:`size-3`}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[d.installs.toLocaleString(),` installs`]})]})]})]}),b&&(0,K.jsx)(`a`,{href:`https://github.com/${b.owner}/${b.repo}`,target:`_blank`,rel:`noopener noreferrer`,className:m(`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)(Br,{className:`size-4`})})]})}),C?(0,K.jsx)(`div`,{className:`flex flex-1 items-center justify-center`,children:(0,K.jsx)(Ea,{className:`size-6 animate-spin text-muted-foreground`})}):S?(0,K.jsx)(lw,{className:`flex-1`,children:(0,K.jsx)(`div`,{className:`p-4`,children:(0,K.jsx)(xX,{children:S})})}):(0,K.jsxs)(`div`,{className:`flex flex-1 flex-col items-center justify-center text-muted-foreground`,children:[(0,K.jsx)(Eo,{className:`mb-2 size-8`}),(0,K.jsx)(T,{children:`Preview unavailable`}),x&&(0,K.jsxs)(`a`,{href:x,target:`_blank`,rel:`noopener noreferrer`,className:`mt-2 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)(Br,{className:`size-3`})]})]})]}):(0,K.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center text-muted-foreground`,children:[(0,K.jsx)(Eo,{className:`mb-2 size-8`}),(0,K.jsx)(T,{children:`Select a skill to preview`})]})})]})]}),d&&s&&s.length>1&&(0,K.jsxs)(fA,{orientation:`horizontal`,className:m(`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)(Ci,{className:`size-4 shrink-0 text-muted-foreground`}),(0,K.jsx)(mA,{className:`whitespace-nowrap`,children:`Install to`}),(0,K.jsxs)(WA,{value:g,onValueChange:h,children:[(0,K.jsx)(KA,{className:`flex-1`,children:(0,K.jsx)(GA,{})}),(0,K.jsx)(qA,{children:s.map(e=>{let t=e.displayName??e.name??e.provider??`unknown`;return(0,K.jsxs)(JA,{value:e.path,children:[t,` (`,e.path,`)`]},e.path)})})]})]})]}),d&&(0,K.jsxs)(bE,{children:[A&&s&&s.length>1&&(()=>{let e=c?.[d.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)(wE,{children:`Cancel`}),(0,K.jsx)(gE,{onConfirm:j,disabled:!b||A,"data-testid":`install-skill-button`,children:i?`Installing...`:A?`Already installed`:`Install`})]})]})})}function wzi({labeled:e=!1}){let{workspaceId:t,addSkill:n}=G9(),[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)(Nc,{}),`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)(Nc,{})}),(0,K.jsx)(Czi,{...c,open:r,onOpenChange:i,workspaceId:t,onInstall:e=>void l(e),isInstalling:a})]})}function Tzi({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(vzi(t??``))),[v,y]=(0,G.useState)(t);if(t!==v){y(t);let e=vzi(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)(szi.Provider,{value:x,children:d})}var Ezi=e=>(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,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`})}),Dzi=e=>(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,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 Ozi(){let{isSearching:e,setSearching:t,searchFiles:n,searchSkills:r}=G9();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)(Dzi,{})})}function kzi(){let{isSearching:e}=G9();return e?(0,K.jsx)(Mzi,{}):(0,K.jsx)(jzi,{})}var Azi=(e,t)=>`${e} ${t}${e===1?``:`s`}`;function jzi(){let{fileCount:e,skillCount:t}=G9();return(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`muted`,className:`block min-w-0`,children:(0,K.jsxs)(Gw,{singleLine:!0,children:[(0,K.jsx)(Gw.Item,{children:e===void 0?`Files`:Azi(e,`File`)}),t===void 0?null:(0,K.jsx)(Gw.Item,{children:Azi(t,`Skill`)})]})})}function Mzi(){let{setSearching:e,setQuery:t}=G9(),[n,r]=(0,G.useState)(``),[,i]=(0,G.useTransition)();return(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(ZM,{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)(Vc,{})})]})}function Nzi(){let{workspaceId:e,query:t,activeFilePath:n,setActiveFilePath:r,searchFiles:i,searchSkills:a}=G9(),{data:o,isLoading:s,isError:c,error:l}=kVn({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)(dw,{className:`h-4 w-3/4`}),(0,K.jsx)(dw,{className:`h-4 w-2/3`})]}):c?(0,K.jsx)(uzi,{error:l,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:m(`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)(TC,{size:`sm`,children:e.kind===`skill`?(0,K.jsx)(mQ,{}):(0,K.jsx)(Ezi,{})}),(0,K.jsx)(T,{as:`span`,variant:`body-sm`,className:`truncate`,children:e.label})]})},e.path))}):(0,K.jsx)(RC,{titleSlot:`No results`}):(0,K.jsx)(RC,{titleSlot:`Search files and skills`,descriptionSlot:`Type to find matching content.`})}function Pzi({mount:e}){switch(e.icon||e.provider){case`aws-s3`:case`s3`:return(0,K.jsx)(DNn,{className:`text-foreground`});case`google-cloud`:case`google-cloud-storage`:case`gcs`:return(0,K.jsx)(MNn,{});case`azure-blob`:case`azure`:return(0,K.jsx)(ANn,{className:`text-badge-blue-indicator`});case`cloudflare`:case`cloudflare-r2`:case`r2`:return(0,K.jsx)(fr,{className:`text-badge-orange-indicator`});case`neon`:return(0,K.jsx)(fr,{className:`text-badge-green-indicator`});case`minio`:return(0,K.jsx)(Ui,{className:`text-badge-red-indicator`});case`database`:return(0,K.jsx)(Tr,{className:`text-badge-green-indicator`});case`local`:case`folder`:return(0,K.jsx)(Ci,{className:`text-badge-amber-indicator`});case`hard-drive`:return(0,K.jsx)(Ui,{className:`text-muted-foreground`});default:return(0,K.jsx)(fr,{className:`text-muted-foreground`})}}var Fzi=e=>(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,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`})}),Izi=e=>(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,...e,children:(0,K.jsx)(`path`,{d:`M2.5 4H13.5M6 4V2.5H10V4M4 4L4.75 13.5H11.25L12 4M6.75 6.5V11M9.25 6.5V11`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`})}),Lzi=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 Rzi(){let{workspaceId:e,activeFilePath:t,setActiveFilePath:n}=G9(),{data:r,isLoading:i,error:a}=aY({workspaceId:e,path:`.`}),[o,s]=(0,G.useState)(null);return i?(0,K.jsx)(Kzi,{}):r?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(e8,{"aria-label":`Workspace files`,selectedId:t,onSelect:n,className:`py-1`,children:(0,K.jsx)(zzi,{entries:r,parent:`.`,onRequestDelete:s})}),(0,K.jsx)(Gzi,{entry:o,onClose:()=>s(null)})]}):(0,K.jsx)(uzi,{error:a,fallback:`Could not load files.`,className:`m-2`})}function zzi({entries:e,parent:t,onRequestDelete:n}){return e.map(e=>{let r=_zi(t,e.name);return e.type===`directory`?(0,K.jsx)(Hzi,{name:e.name,path:r,mount:e.mount,onRequestDelete:n},e.name):(0,K.jsx)(Wzi,{name:e.name,size:e.size,path:r,onRequestDelete:n},e.name)})}function Bzi({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 Vzi({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)(Izi,{})})}function Hzi({name:e,path:t,mount:n,onRequestDelete:r}){let{workspaceId:i,onDelete:a,onCreateDirectory:o,isReadOnly:s,openFolders:c,setFolderOpen:l}=G9(),u=c.has(t),{isLoading:d}=aY({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)(e8.Folder,{id:t,open:u,onOpenChange:e=>l(t,e),children:[(0,K.jsxs)(e8.FolderTrigger,{actions:m||h?(0,K.jsxs)(Bzi,{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)(xi,{})}):null,m?(0,K.jsx)(Vzi,{name:e,onClick:()=>r({path:t,type:`directory`})}):null]}):void 0,children:[(0,K.jsx)(e8.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)(Pzi,{mount:n})}):(0,K.jsx)(Fzi,{})}),(0,K.jsx)(e8.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)(Un,{className:`size-3 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)(Aa,{className:`size-3 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)(Zc,{size:`sm`,"aria-label":`Loading ${e}`,className:`size-3 text-muted-foreground`})}):null]}),(0,K.jsx)(e8.FolderContent,{children:u?(0,K.jsx)(Uzi,{path:t,creating:f,onCreated:()=>p(!1),onRequestDelete:r}):null})]})}function Uzi({path:e,creating:t,onCreated:n,onRequestDelete:r}){let{workspaceId:i,onCreateDirectory:a}=G9(),o=dy(),{data:s,isLoading:c,error:l}=aY({workspaceId:i,path:e}),u=async t=>{try{await a?.(_zi(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)(e8.Input,{type:`folder`,placeholder:`Folder name`,onSubmit:e=>void u(e),onCancel:n}):null,c?null:s?(0,K.jsx)(zzi,{entries:s,parent:e,onRequestDelete:r}):(0,K.jsx)(uzi,{error:l,fallback:`Could not load folder.`,className:`my-1 mr-1`})]})}function Wzi({name:e,size:t,path:n,onRequestDelete:r}){let{onDelete:i,isReadOnly:a,activeFilePath:o}=G9(),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)(e8.File,{ref:l,id:n,children:[(0,K.jsx)(e8.Icon,{children:(0,K.jsx)(Ezi,{})}),(0,K.jsx)(e8.Label,{children:e}),(0,K.jsxs)(Bzi,{children:[t===void 0?null:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`faint`,font:`mono`,children:Lzi(t)}),s?(0,K.jsx)(Vzi,{name:e,onClick:()=>r({path:n,type:`file`})}):null]})]})}function Gzi({entry:e,onClose:t}){let{workspaceId:n,activeFilePath:r,setActiveFilePath:i,onDelete:a}=G9(),o=dy(),[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`,yzi(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)(aP,{open:e!==null,onOpenChange:e=>{!e&&!s&&t()},children:(0,K.jsxs)(aP.Content,{children:[(0,K.jsxs)(aP.Header,{children:[(0,K.jsxs)(aP.Title,{children:[`Delete `,e?.type===`directory`?`folder`:`file`,`?`]}),(0,K.jsxs)(aP.Description,{children:[d,` This action cannot be undone.`]})]}),(0,K.jsxs)(aP.Footer,{children:[(0,K.jsx)(aP.Cancel,{disabled:s,children:`Cancel`}),(0,K.jsx)(X,{variant:`destructive`,disabled:s,onClick:()=>void u(),children:s?`Deleting…`:`Delete`})]})]})})}function Kzi(){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)(dw,{className:`h-4 w-3/4`}),(0,K.jsx)(dw,{className:`h-4 w-1/2`}),(0,K.jsx)(dw,{className:`h-4 w-2/3`})]})}function qzi({children:e,...t}){return(0,K.jsx)(Tzi,{...t,children:(0,K.jsx)(Jzi,{children:e})})}function Jzi({children:e}){let{workspaceId:t}=G9(),{data:n,error:r}=aY({workspaceId:t,path:`.`});return(n?n.length===0:XP(r))?(0,K.jsx)(RC,{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)(bzi,{labeled:!0}),(0,K.jsx)(wzi,{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 Yzi({children:e}){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(vJr,{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)(F6,{className:`w-px bg-border`})]})}function Xzi({children:e,actions:t}){let{isSearching:n}=G9();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 Zzi(){let{isSearching:e}=G9();return(0,K.jsx)(lw,{className:`min-h-0 flex-1 px-2 py-1`,children:e?(0,K.jsx)(Nzi,{}):(0,K.jsx)(Rzi,{})})}function Qzi({children:e}){return(0,K.jsx)(N6,{id:`workspace-active-file`,className:`flex min-w-0 flex-col`,minSize:30,children:e})}function $zi({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 eBi({renderPreview:e}){let{activeFilePath:t}=G9();return t?(0,K.jsx)(lw,{className:`min-h-0 flex-1`,children:(0,K.jsx)(gzi,{renderPreview:e})}):(0,K.jsx)(RC,{variant:`fill`,titleSlot:`Select a file`})}var K9={Root:qzi,Aside:Yzi,AsideHeader:Xzi,Search:kzi,SearchToggle:Ozi,CreateDirectory:bzi,Tree:Zzi,ActiveFile:Qzi,ActiveFileHeader:$zi,FilePath:mzi,ActiveFileContent:eBi};function tBi({asideActions:e,renderPreview:t,...n}){return(0,K.jsxs)(K9.Root,{...n,children:[(0,K.jsxs)(K9.Aside,{children:[(0,K.jsx)(K9.AsideHeader,{actions:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(K9.SearchToggle,{}),(0,K.jsx)(K9.CreateDirectory,{}),(0,K.jsx)(wzi,{}),e]}),children:(0,K.jsx)(K9.Search,{})}),(0,K.jsx)(K9.Tree,{})]}),(0,K.jsxs)(K9.ActiveFile,{children:[(0,K.jsx)(K9.ActiveFileHeader,{children:(0,K.jsx)(K9.FilePath,{})}),(0,K.jsx)(K9.ActiveFileContent,{renderPreview:t})]})]})}var nBi=()=>(0,K.jsx)(RC,{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)(Br,{}),children:`Workspaces documentation`}),variant:`fill`}),rBi=()=>(0,K.jsx)(RC,{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)(Br,{}),children:`Workspaces documentation`}),variant:`fill`}),iBi=()=>(0,K.jsx)(RC,{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)(Br,{}),children:`Workspaces documentation`}),variant:`fill`}),aBi=`.agents/skills`,oBi=e=>e.replace(/^\.?\/+|\/+$/g,``);function sBi({workspaceId:e,showInitWarning:t,skills:n}){let{data:r}=aY({workspaceId:e,path:aBi,queryOptions:{enabled:!!n}}),i=n&&r?r.filter(e=>e.type===`directory`&&!n.some(t=>t.name===e.name||oBi(t.path)===`${aBi}/${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)(EA,{variant:`warning`,children:(0,K.jsxs)(EA.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)(EA,{variant:`warning`,title:`Skills installed but not discovered`,children:(0,K.jsxs)(EA.Message,{children:[i.map(e=>e.name).join(`, `),` `,i.length===1?`is`:`are`,` in`,` `,(0,K.jsx)(`code`,{children:aBi}),` but not discovered. Add this path to your workspace skills configuration to see `,i.length===1?`it`:`them`,`.`]})})]})}var q9=[sF(`/workspaces`)],cBi=e=>YP(e)?`you don't have permission to modify this workspace`:e instanceof Error?e.message:`Unknown error`;function lBi(){let{workspaceId:e}=Ab(),[t,n]=Hb(),r=kb(),i=dy(),a=t.get(`file`),{data:o,error:s,isLoading:c}=bVn(),l=o?.workspaces??[],u=e??l[0]?.id,{data:d,isLoading:f,error:p}=yVn({workspaceId:u,queryOptions:{enabled:!!u}}),m=JP(s)||JP(p),h=YP(s)||YP(p),g=tVn(s)||tVn(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=SVn(),C=CVn(),w=d?.isWorkspaceConfigured??!1,T=d?.capabilities?.hasDynamicFilesystem??!1,E=(d?.capabilities?.hasFilesystem??!1)&&!T,D=d?.capabilities?.hasSkills??!1,{data:O,refetch:k}=AVn({workspaceId:u,queryOptions:{enabled:!!u&&E}}),A=hVn(),j=gVn(),M=_Vn(),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?UC.error(`Failed to update ${t.map(e=>e.skillName).join(`, `)}`):UC.success(`${e.updated.length} skill(s) updated`),i.invalidateQueries({queryKey:[`workspace`,u,`fs`]})}catch(e){UC.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}"`);UC.success(`Skill "${n}" removed`),k()}catch(e){throw UC.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 UC.error(`Failed to delete ${e}: ${cBi(t)}`),t}},I=_?.safety?.readOnly??!1,{canEdit:L,canDelete:R,canExecute:z,isLoading:B}=KC(),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(),UC.success(`Skill "${t.skillName}" installed successfully (${t.filesWritten} files)`)}catch(e){throw UC.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)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(Zc,{fill:!0})]});if(m)return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(jU,{variant:`fill`})]});if(h)return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(AU,{variant:`fill`,resource:`workspaces`})]});if(g)return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(iBi,{})]});let ce=s||p;if(ce)return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load workspace`,descriptionSlot:ce.message})]});if(!c&&l.length===0)return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(nBi,{})]});if(!f&&!c&&!w)return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(rBi,{})]});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)(bw,{size:`xs`,variant:`warning`,children:`Read-only`}),e.capabilities.hasFilesystem&&(0,K.jsx)(bw,{size:`xs`,children:`FS`}),e.capabilities.hasSandbox&&(0,K.jsx)(bw,{size:`xs`,children:`Sandbox`}),e.capabilities.hasSkills&&(0,K.jsx)(bw,{size:`xs`,children:`Skills`})]})}));return(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:q9}),headerActions:(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(TP,{"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)(bw,{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)(sBi,{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)(tBi,{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 UC.error(`Failed to create ${e}: ${cBi(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)(Zo,{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)(RC,{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)(RC,{variant:`fill`,titleSlot:`No filesystem or skills configured`,descriptionSlot:`Add a filesystem or skills to this workspace to browse its files here.`})})]})]})}function uBi({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:m(`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`,children:[r,(0,K.jsx)(`div`,{"data-slot":`app-shell-body`,className:m(`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 dBi({children:e,className:t,edgeToEdge:n}){let r=n!==void 0;return(0,K.jsx)(`div`,{"data-slot":`main-card`,className:m(`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`,fKe,t),children:e})}function fBi(){return(0,K.jsxs)(`div`,{className:`h-screen bg-sidebar`,children:[(0,K.jsx)(t1e,{position:`bottom-right`}),(0,K.jsx)(M,{defaultTheme:`system`,children:(0,K.jsx)(bC,{delayDuration:0,children:(0,K.jsx)(uBi,{children:(0,K.jsx)(dBi,{className:`flex items-center justify-center overflow-y-auto`,children:(0,K.jsx)(Lb,{})})})})})]})}function pBi(){let{data:e,isLoading:t}=jy(),{isLoading:n,canAccessAgentBuilder:r}=qC();return t||n||!e||e.enabled&&!Ay(e)?{isVisible:!1}:{isVisible:r}}function mBi(){let{isImpersonating:e,impersonatedRole:t,stopImpersonation:n}=l1e();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)(Hr,{className:`h-3.5 w-3.5 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)(Vc,{className:`h-3 w-3`})})]})}function hBi({children:e,contentClassName:t,commandClassName:n,showOverlay:r=!0,overlayClassName:i,...a}){return(0,K.jsx)(CRn,{size:`xl`,showOverlay:r,overlayClassName:m(`bg-sidebar/40 backdrop-blur-none`,i),contentClassName:m(`command-palette-popup overflow-visible bg-transparent shadow-none`,t),commandClassName:m(`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 gBi({wrapperClassName:e,...t}){return(0,K.jsx)(kJ,{wrapperClassName:m(`command-palette-surface command-palette-surface-input`,LQe,`h-11 shrink-0 rounded-xl border-0 px-3 pr-11`,e),...t})}function _Bi({children:e,className:t,...n}){return(0,K.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,K.jsx)(`div`,{className:m(`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 vBi({children:e,className:t,...n}){return(0,K.jsx)(`aside`,{className:m(`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`,Gb,t),...n,children:(0,K.jsx)(lw,{className:`-m-1 min-h-0 flex-1 p-1`,children:(0,K.jsx)(cw,{className:`pr-1`,children:(0,K.jsx)(`div`,{className:`flex flex-col gap-1`,children:e})})})})}function yBi({icon:e,label:t,count:n,active:r,onSelect:i}){return(0,K.jsxs)(`button`,{type:`button`,className:m(ZC,`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-4 shrink-0 items-center justify-center [&>svg]:size-4`,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 bBi({children:e,footer:t,...n}){return(0,K.jsxs)(`div`,{role:`region`,className:m(`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`,Gb),...n,children:[(0,K.jsx)(AJ,{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 J9({icon:e,title:t,subtitle:n,path:r,badge:i,shortcut:a,className:o,...s}){return(0,K.jsxs)(NJ,{className:m(`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:m(`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)(TRn,{children:a})]})}function xBi({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)(PC,{size:`sm`,children:`↑`}),(0,K.jsx)(PC,{size:`sm`,children:`↓`}),(0,K.jsx)(PC,{size:`sm`,children:`↵`}),(0,K.jsx)(PC,{size:`sm`,children:`Esc`})]})]})}var Y9=!1,SBi=new Set,CBi=()=>{SBi.forEach(e=>e())},wBi=e=>(SBi.add(e),()=>SBi.delete(e)),TBi=()=>Y9,EBi=e=>{let t=typeof e==`function`?e(Y9):e;t!==Y9&&(Y9=t,CBi())},DBi=({enableShortcut:e=!0}={})=>{let t=(0,G.useSyncExternalStore)(wBi,TBi,TBi),n=(0,G.useCallback)(e=>{EBi(e)},[]),r=(0,G.useCallback)(()=>{EBi(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 OBi(e,t){return[e.name,e.url,t,`path route navigate`].filter(Boolean).join(` `)}function kBi(e){return!e||e===`Studio`?`Path`:e}function ABi(e){return`/traces?entity=${encodeURIComponent(e)}`}var jBi=({scopeOptions:e,activeScope:t,onScopeChange:n})=>(0,K.jsx)(vBi,{"aria-label":`Search categories`,children:e.map(e=>(0,K.jsx)(yBi,{icon:e.icon,label:e.label,count:e.count,active:t===e.id,onSelect:()=>n(e.id)},e.id))}),MBi=({sidebar:e,activeScope:t,closeCommand:n})=>!e||t!==`all`&&t!==`settings`?null:(0,K.jsx)(MJ,{heading:`Commands`,children:(0,K.jsx)(J9,{value:`toggle sidebar collapse expand layout panel`,onSelect:()=>{e.toggleSidebar(),n()},icon:(0,K.jsx)(ete,{}),title:`Toggle sidebar`,subtitle:`Studio layout`})}),NBi=({sections:e,handleSelect:t})=>(0,K.jsx)(K.Fragment,{children:e.map(e=>(0,K.jsx)(MJ,{heading:e.title,children:e.items.map(n=>{let r=n.Icon;return(0,K.jsx)(J9,{value:OBi(n,e.title),onSelect:()=>t(n.url),icon:(0,K.jsx)(r,{}),title:n.name,subtitle:`Studio path`,path:n.url,badge:kBi(e.title)},n.url)})},e.key))}),PBi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(MJ,{heading:`Agents`,children:t.map(([e,t])=>(0,K.jsx)(J9,{value:`${t.name} ${e} chat agent conversation thread ${n.agentLink(e)}`,onSelect:()=>r(n.agentLink(e)),icon:(0,K.jsx)(tF,{}),title:t.name,subtitle:`Agent chat`,path:n.agentLink(e),badge:`Agent`},e))}),FBi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(MJ,{heading:`Workflows`,children:t.map(([e,t])=>(0,K.jsx)(J9,{value:`${t.name} ${e} graph workflow view ${n.workflowLink(e)}`,onSelect:()=>r(n.workflowLink(e)),icon:(0,K.jsx)(rP,{}),title:t.name,subtitle:`Workflow graph`,path:n.workflowLink(e),badge:`Workflow`},e))}),IBi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(MJ,{heading:`Tools`,children:t.map(([e,t])=>(0,K.jsx)(J9,{value:`tool ${t.id} ${e} ${n.toolLink(e)}`,onSelect:()=>r(n.toolLink(e)),icon:(0,K.jsx)(aF,{}),title:t.id,subtitle:`Tool definition`,path:n.toolLink(e),badge:`Tool`},e))}),LBi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(MJ,{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)(J9,{value:`processor ${t} ${e.id} ${i}`,onSelect:()=>r(i),icon:(0,K.jsx)(wr,{}),title:t,subtitle:e.isWorkflow?`Workflow processor`:`Processor`,path:i,badge:`Processor`},e.id)})}),RBi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(MJ,{heading:`MCP Servers`,children:t.map(e=>(0,K.jsx)(J9,{value:`mcp server ${e.name} ${e.id} ${n.mcpServerLink(e.id)}`,onSelect:()=>r(n.mcpServerLink(e.id)),icon:(0,K.jsx)(nF,{}),title:e.name,subtitle:`MCP server`,path:n.mcpServerLink(e.id),badge:`MCP`},e.id))}),zBi=({visible:e,agentEntries:t,workflowEntries:n,handleSelect:r})=>e?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(MJ,{heading:`Observability`,children:[(0,K.jsx)(J9,{value:`observability traces telemetry signals /traces`,onSelect:()=>r(`/traces`),icon:(0,K.jsx)(Hr,{}),title:`Traces`,subtitle:`Runtime traces`,path:`/traces`,badge:`Signal`}),(0,K.jsx)(J9,{value:`metrics usage latency performance tokens /metrics`,onSelect:()=>r(`/metrics`),icon:(0,K.jsx)(Di,{}),title:`Metrics`,subtitle:`Runtime metrics`,path:`/metrics`,badge:`Signal`}),(0,K.jsx)(J9,{value:`logs events runtime /logs`,onSelect:()=>r(`/logs`),icon:(0,K.jsx)(Hr,{}),title:`Logs`,subtitle:`Runtime logs`,path:`/logs`,badge:`Signal`})]}),t.length>0&&(0,K.jsx)(MJ,{heading:`Agent Traces`,children:t.map(([e,t])=>{let n=ABi(e);return(0,K.jsx)(J9,{value:`${t.name} ${e} traces agent observability telemetry`,onSelect:()=>r(n),icon:(0,K.jsx)(Hr,{}),title:t.name,subtitle:`Agent traces`,path:n,badge:`Trace`},e)})}),n.length>0&&(0,K.jsx)(MJ,{heading:`Workflow Traces`,children:n.map(([e,t])=>{let n=ABi(t.name);return(0,K.jsx)(J9,{value:`${t.name} ${e} traces workflow observability telemetry`,onSelect:()=>r(n),icon:(0,K.jsx)(Hr,{}),title:t.name,subtitle:`Workflow traces`,path:n,badge:`Trace`},e)})})]}):null,BBi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(MJ,{heading:`Scorers`,children:t.map(([e,t])=>{let i=t.scorer?.config?.name||t.scorer?.config?.id||e;return(0,K.jsx)(J9,{value:`scorer score evaluation ${i} ${e} ${n.scorerLink(e)}`,onSelect:()=>r(n.scorerLink(e)),icon:(0,K.jsx)(Di,{}),title:i,subtitle:`Evaluation scorer`,path:n.scorerLink(e),badge:`Scorer`},e)})}),VBi=()=>{let{open:e,setOpen:t}=DBi(),{navigate:n,paths:r}=gl(),{isMastraPlatform:i}=Y8(),a=k3(),[o,s]=G.useState(`all`),{data:c={}}=PP(),{data:l={}}=sP(),{data:u={}}=BJ(),{data:d={}}=qP(),{data:f=[]}=KP(),{data:p={}}=eF(),{isCmsAvailable:m,isLoading:h}=K3(),{hasPermission:g,hasAnyPermission:_,isLoading:v}=KC(),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=y1e(e.url);return v&&t&&t!==`public`?!1:b1e(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 NLt){let n=t.items.filter(S);n.length>0&&e.push({key:t.key,title:t.title,items:n})}let t=[...PLt.filter(S),...i?[]:[{name:`Templates`,url:`/templates`,Icon:Eo,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)(gs,{}),count:P},{id:`paths`,label:`Paths`,icon:(0,K.jsx)(cs,{}),count:k},{id:`agents`,label:`Agents`,icon:(0,K.jsx)(tF,{}),count:C.length},{id:`workflows`,label:`Workflows`,icon:(0,K.jsx)(rP,{}),count:w.length},{id:`tooling`,label:`Tooling`,icon:(0,K.jsx)(na,{}),count:A},{id:`evaluation`,label:`Evaluation`,icon:(0,K.jsx)(Di,{}),count:j},{id:`observability`,label:`Intelligence`,icon:(0,K.jsx)(Hr,{}),count:M},{id:`settings`,label:`Studio`,icon:(0,K.jsx)(Ls,{}),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)(hBi,{open:e,onOpenChange:y,title:`Mastra Studio Search`,description:`Search Studio routes and runtime entities`,children:[(0,K.jsx)(gBi,{placeholder:`Search Studio, agents, workflows, tools, paths`}),(0,K.jsxs)(_Bi,{children:[(0,K.jsx)(jBi,{scopeOptions:F,activeScope:o,onScopeChange:s}),(0,K.jsxs)(bBi,{"aria-label":`Search results`,footer:(0,K.jsx)(xBi,{label:`Studio search`}),children:[(0,K.jsx)(jJ,{children:`No matching results.`}),(0,K.jsx)(MBi,{sidebar:a,activeScope:o,closeCommand:b}),(0,K.jsx)(NBi,{sections:ee,handleSelect:x}),(0,K.jsx)(PBi,{visible:L,entries:C,paths:r,handleSelect:x}),(0,K.jsx)(FBi,{visible:R,entries:w,paths:r,handleSelect:x}),(0,K.jsx)(IBi,{visible:z,entries:T,paths:r,handleSelect:x}),(0,K.jsx)(LBi,{visible:z,entries:E,paths:r,handleSelect:x}),(0,K.jsx)(RBi,{visible:z,entries:f,paths:r,handleSelect:x}),(0,K.jsx)(zBi,{visible:V,agentEntries:C,workflowEntries:w,handleSelect:x}),(0,K.jsx)(BBi,{visible:B,entries:D,paths:r,handleSelect:x})]})]})]})};function HBi(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 UBi(e){let{Icon:t}=e;return{name:e.name,url:e.url,icon:(0,K.jsx)(t,{})}}function WBi(){let{state:e,isMobile:t,setOpenMobile:n}=A3(),{setOpen:r}=DBi({enableShortcut:!1}),i=g8r(`K`),a=Ob().pathname,{isMastraPlatform:o}=Y8(),{data:s}=jy(),{isCmsAvailable:c,isLoading:l}=K3(),{hasPermission:u,hasAnyPermission:d,isLoading:f}=KC(),{data:p}=ygr(),m=p!==void 0&&p.status!==`not-mounted`,h=s&&Ay(s),g=new Set([`/prompts`]),{isVisible:_}=pBi(),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=y1e(e.url);if(t&&t!==`public`)return!1}return!!b1e(y1e(e.url),u,d)},{data:x}=KP(),{data:S}=bVn(),C=PLt.filter(b),w=NLt.map(e=>{let t=e.items.filter(b),n=e=>({...UBi(e),isActive:HBi(e,a,t)});return{key:e.key,title:e.title,href:e.href,isHeaderActive:!(!e.href||a!==e.href||t.some(e=>HBi(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)(P3,{"aria-label":`Sidebar`,children:[(0,K.jsxs)(P3.Header,{collapsedLogo:(0,K.jsx)(EQ,{className:`size-6`}),actions:h&&(0,K.jsx)(Tir,{}),children:[(0,K.jsx)(P3.Brand,{logo:(0,K.jsx)(EQ,{className:`size-6`}),title:`Mastra Studio`}),!t&&(0,K.jsx)(P3.SearchTrigger,{"aria-label":`Search and navigate`,shortcut:i,onClick:y}),(0,K.jsx)(P3.Trigger,{})]}),_&&(0,K.jsx)(P3.NavList,{className:`mb-1`,children:(0,K.jsx)(P3.NavLink,{state:e,link:{name:`Agent Builder`,url:`/agent-builder`,icon:(0,K.jsx)(zc,{})},isActive:v})}),(0,K.jsx)(mBi,{}),(0,K.jsx)(P3.Nav,{children:(0,K.jsx)(P3.Sections,{sections:w,visibilityStorageKey:`mastra:studio:sidebar-visibility`})}),(0,K.jsx)(P3.Footer,{children:(0,K.jsxs)(P3.NavList,{children:[C.map(t=>(0,K.jsx)(P3.NavLink,{state:e,link:UBi(t),isActive:HBi(t,a)},t.name)),(0,K.jsx)($Wr,{state:e})]})})]})}var GBi=()=>{let{baseUrl:e,headers:t,apiPrefix:n,setConfig:r}=YC(),[i,a]=(0,G.useState)(()=>Object.entries(t).map(([e,t])=>({name:e,value:t})));return(0,K.jsx)(bC,{delayDuration:0,children:(0,K.jsxs)(uU,{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}),UC.success(`Headers saved`)},className:`w-full max-w-md gap-6 text-left`,children:[(0,K.jsx)(PHr,{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)(ds,{}),`Save headers`]})]})})};function KBi({children:e,loginUrl:t=`/login`,signupUrl:n=`/signup`}){let{data:r,isLoading:i}=jy();if(i||!r?.enabled||Ay(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)(EQ,{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)(Aa,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}),(0,K.jsx)(T,{tone:`muted`,className:`max-w-sm`,children:r.login.description})]}),(0,K.jsx)(Sir,{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(DQ(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)(EQ,{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)(GBi,{})]})})}var qBi=`experimental-ui:`,JBi=`current`,YBi=G.createContext(null);function XBi(e,t){let n=window.localStorage.getItem(qBi+e);return n&&t.has(n)?n:JBi}function ZBi({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]=XBi(r.key,e)}i(t)},[e,n]);let a=G.useCallback(e=>r[e]??JBi,[r]),o=G.useCallback((e,t)=>{window.localStorage.setItem(qBi+e,t),i(n=>({...n,[e]:t}))},[]),s=G.useMemo(()=>({experiments:e,getVariant:a,setVariant:o}),[e,a,o]);return(0,K.jsx)(YBi.Provider,{value:s,children:t})}var QBi=[{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`}]}],$Bi=()=>({experimentalUIEnabled:typeof window<`u`&&window.MASTRA_EXPERIMENTAL_UI===`true`}),eVi=()=>{let{toggleSidebar:e}=A3();return FC({"[":e},{repeat:!1}),null};function tVi(){let{setOpenMobile:e}=A3(),{setOpen:t}=DBi({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)(P3.MobileTrigger,{}),(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(EQ,{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)(gs,{})})]})}var nVi={"studio-frame":100,"route-side-panel":0},rVi={overflow:`visible`};function iVi({children:e,className:t}){let n=fE(),{hasPanel:r,panelHandle:i,onPanelResize:a}=J8(),{defaultLayout:o,onLayoutChange:s}=sJr({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:rVi,orientation:`horizontal`,defaultLayout:o??nVi,onLayoutChange:s,children:[(0,K.jsx)(N6,{id:`studio-frame`,className:m(`min-w-0`,t),style:rVi,children:e}),r&&!n&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(F6,{className:`w-2`}),(0,K.jsx)(vJr,{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)(y3r,{className:`h-full min-h-0`})})]})]})})}function aVi({children:e}){let{data:t,isFetched:n}=jy(),{pathname:r}=Ob(),i=!(n&&t?.enabled&&!Ay(t));return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(VBi,{}),(0,K.jsx)(uBi,{sidebar:i?(0,K.jsx)(WBi,{}):void 0,mobileHeader:i?(0,K.jsx)(tVi,{}):void 0,children:(0,K.jsx)(iVi,{className:`flex min-h-0 flex-1 flex-col`,children:(0,K.jsx)(dBi,{children:(0,K.jsx)(KBi,{children:(0,K.jsx)(R1e,{resetKeys:[r],children:e})})})})})]})}var oVi=({children:e})=>{let{experimentalUIEnabled:t}=$Bi(),{Link:n}=gl();return(0,K.jsxs)(`div`,{className:`h-screen bg-sidebar`,children:[(0,K.jsx)(t1e,{position:`bottom-right`}),(0,K.jsx)(M,{defaultTheme:`system`,children:(0,K.jsx)(bC,{delayDuration:0,children:(0,K.jsx)(ZBi,{experiments:t?QBi:[],children:(0,K.jsxs)(P3.Provider,{LinkComponent:n,children:[(0,K.jsx)(eVi,{}),(0,K.jsx)(v3r,{children:(0,K.jsx)(aVi,{children:e})})]})})})})]})},sVi=({children:e})=>(0,K.jsxs)(`div`,{className:`h-screen bg-sidebar`,children:[(0,K.jsx)(t1e,{position:`bottom-right`}),(0,K.jsx)(M,{defaultTheme:`system`,children:(0,K.jsx)(bC,{delayDuration:0,children:(0,K.jsx)(`div`,{className:`h-full overflow-y-auto`,children:(0,K.jsx)(KBi,{children:e})})})})]}),cVi={name:`Agents`,url:`/agent-builder/agents`,icon:(0,K.jsx)(tF,{})},lVi={name:`Skills`,url:`/agent-builder/skills`,icon:(0,K.jsx)(sn,{className:`size-5`})},uVi={name:`Favorites`,url:`/agent-builder/favorite`,icon:(0,K.jsx)(Ks,{className:`size-5`})},dVi={name:`Library`,url:`/agent-builder/library`,icon:(0,K.jsx)(aa,{className:`size-5`})},fVi={name:`Infra`,url:`/agent-builder/infrastructure`,icon:(0,K.jsx)(bte,{className:`size-5`})};function pVi(){let{Link:e}=gl(),{pathname:t}=Ob(),n=Iq(),{canManageSkills:r,canUseFavorites:i}=qC(),{hasPermission:a}=KC(),o=a(`infrastructure:read`),s=(0,G.useMemo)(()=>{let e=[cVi];return n.skills&&r&&e.push(lVi),i&&e.push(uVi),e.push(dVi),o&&e.push(fVi),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:m(r?`text-foreground`:`text-muted-foreground`,`relative flex flex-col items-center justify-center gap-1 py-2`,f,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 mVi={name:`My agents`,url:`/agent-builder/agents`,icon:(0,K.jsx)(tF,{})},hVi={name:`Favorites`,url:`/agent-builder/favorite`,icon:(0,K.jsx)(Ks,{})},gVi={name:`Library`,url:`/agent-builder/library`,icon:(0,K.jsx)(aa,{})},_Vi={name:`Skills`,url:`/agent-builder/skills`,icon:(0,K.jsx)(sn,{className:`h-4 w-4`})},vVi={name:`Infrastructure`,url:`/agent-builder/infrastructure`,icon:(0,K.jsx)(bte,{className:`h-4 w-4`})};function yVi({forceExpanded:e=!1}={}){let{Link:t}=gl(),{state:n,isMobile:r}=A3(),{pathname:i}=Ob(),a=Iq(),{canManageSkills:o,canUseFavorites:s}=qC(),{hasPermission:c}=KC(),l=c(`infrastructure:read`),u=e?`default`:n,{data:d}=jy(),f=d&&Ay(d),p=[mVi];a.skills&&o&&p.push(_Vi),s&&p.push(hVi),p.push(gVi);let m=(0,K.jsx)(t,{href:`/agents`,"aria-label":`Back to Mastra Studio`,children:(0,K.jsx)(EQ,{className:`size-6`})});return(0,K.jsxs)(P3,{className:`h-full`,mobileMode:`drawer`,children:[!e&&(0,K.jsxs)(P3.Header,{collapsedLogo:m,actions:f&&(0,K.jsx)(Tir,{}),children:[(0,K.jsx)(t,{href:`/agents`,"aria-label":`Back to Mastra Studio`,className:`min-w-0 flex-1`,children:(0,K.jsx)(P3.Brand,{logo:(0,K.jsx)(EQ,{className:`size-6`}),title:`Mastra Studio`})}),!r&&(0,K.jsx)(P3.Trigger,{})]}),(0,K.jsx)(mBi,{}),(0,K.jsx)(P3.Nav,{children:(0,K.jsx)(P3.NavSection,{children:(0,K.jsx)(P3.NavList,{children:p.map(e=>{let n=i.startsWith(e.url);return(0,K.jsx)(P3.NavLink,{LinkComponent:t,state:u,link:e,isActive:n},e.name)})})})}),!e&&(0,K.jsx)(P3.Footer,{children:l&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(P3.NavSeparator,{}),(0,K.jsx)(P3.NavSection,{children:(0,K.jsx)(P3.NavList,{children:(0,K.jsx)(P3.NavLink,{LinkComponent:t,state:u,link:vVi,isActive:i.startsWith(vVi.url)})})})]})})]})}var X9=()=>(0,K.jsx)(`div`,{className:`h-screen bg-sidebar`,children:(0,K.jsxs)(WUr,{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)(yVi,{})}),(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)(Lb,{})})})]}),(0,K.jsx)(pVi,{})]})}),bVi=()=>(0,K.jsx)(`div`,{className:`grid h-screen grid-cols-[minmax(0,1fr)] grid-rows-1 bg-sidebar`,children:(0,K.jsx)(Lb,{})});function xVi({agentId:e,children:t,disabled:n=!1}){let r=fE(),i=(0,K.jsx)(xQ,{children:(0,K.jsx)(C3r,{agentId:e})},e);return n?t:(0,K.jsxs)(nE,{side:`right`,children:[t,r?(0,K.jsxs)(aE,{children:[(0,K.jsx)(oE,{}),(0,K.jsx)(sE,{children:(0,K.jsxs)(cE,{className:`w-[calc(100vw-2.5rem)] max-w-md`,children:[(0,K.jsx)(uE,{className:`sr-only`,children:`Config`}),(0,K.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:i})]})})]}):(0,K.jsx)(q8,{owner:`agent-detail`,children:i})]})}var SVi=()=>{let{toggle:e}=J8();return FC({"]":e}),null};function CVi(){let e=fE(),{isCollapsed:t,toggle:n}=J8();return e?(0,K.jsx)(rE,{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)(X3,{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)(PC,{size:`xs`,children:`]`})]}),"data-testid":`agent-overview-panel-toggle`,onClick:n,children:(0,K.jsx)(X3,{side:`right`})})}function wVi({agentId:e,showConfig:t=!0}){let{data:n}=NP({agentId:e,requestContext:mw(`agent`,e)[0],queryOptions:{enabled:!!e}}),{canCreateAgent:r}=wNn(),{Link:i,paths:a}=gl(),{handleCopy:o,isCopied:s}=Aw({text:`${window.location.origin}${DQ(`/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)(Lo,{}),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)(Bn,{}):(0,K.jsx)(da,{})}),t&&(0,K.jsx)(CVi,{})]})}function TVi(e){if(e)try{return lA(e)}catch{return}}function EVi(e){let t=TVi(e.inputSchema);return{inputSchema:t,outputSchema:TVi(e.outputSchema),requestContextSchema:TVi(e.requestContextSchema),zodInputSchema:L9(t)}}function DVi(e,t){let{data:n={},isLoading:r,isError:i}=PP(),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 OVi({agent:e,isCurrent:t}){let{Link:n,paths:r}=gl(),i=(0,K.jsx)(Z.NameCell,{children:(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(TC,{size:`sm`,className:`shrink-0 text-muted-foreground`,children:(0,K.jsx)(tF,{})}),e.name]})});return t?(0,K.jsxs)(Z.RowStatic,{children:[i,(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(bw,{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 kVi({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 AVi({toolId:e,currentAgentId:t}){let{agents:n,isLoading:r,isError:i}=DVi(e,t),a=kVi({isLoading:r,isError:i,isEmpty:n.length===0});return a?(0,K.jsx)(_$,{children:(0,K.jsx)(_Pi,{message:a})}):(0,K.jsx)(Z,{columns:`minmax(0,1fr) auto`,fit:`container`,children:n.map(e=>(0,K.jsx)(OVi,{agent:e,isCurrent:e.id===t},e.id))})}function jVi(e){return(0,K.jsxs)(v$,{children:[(0,K.jsx)(pPi,{children:(0,K.jsx)(y$,{children:`Used by`})}),(0,K.jsx)(AVi,{...e})]})}function MVi({tool:e,execution:t,currentAgentId:n,requestContextEntityType:r,requestContextEntityId:i}){let{canExecute:a}=KC(),{inputSchema:o,outputSchema:s,requestContextSchema:c,zodInputSchema:l}=EVi(e);return(0,K.jsx)(fPi,{description:e.description,overview:(0,K.jsx)(cFi,{inputSchema:o,outputSchema:s,requestContextSchema:c,footer:(0,K.jsx)(jVi,{toolId:e.id,currentAgentId:n})}),canRun:a(`tools`),playground:(0,K.jsx)(rFi,{zodInputSchema:l,execution:t,requestContextEntityType:r,requestContextEntityId:i})})}function NVi({agentId:e}){let t=sFi(),[n]=mw(`agent`,e),{data:r,isLoading:i}=NP({agentId:e,requestContext:n}),{mutateAsync:a,status:o,data:s,error:c}=nIt(),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)(m$.LoadingData,{}):l?(0,K.jsx)(MVi,{tool:l,execution:u,currentAgentId:e,requestContextEntityType:`agent-tool`,requestContextEntityId:`${e}:${l.id}`}):(0,K.jsxs)(m$.NoData,{children:[`This agent has no tool "`,t,`".`]})}var PVi=[sF(`/agents`),zLt],FVi=({agentId:e})=>{let t=kb();return FC({"g$+t":()=>t(`/agents/${e}/traces`)}),null},IVi=O8.threadId;function LVi(e,t,n){if(e===`chat`){let e=Vy(`/agents/:agentId/threads/:threadId`,t)?.params.threadId;return e===`new`?void 0:e}if(e===`traces`){let e=new URLSearchParams(n),t=e.get(A8(IVi));return t&&t!==`is`?void 0:e.get(IVi)||void 0}}var RVi=({children:e})=>{let{agentId:t}=Ab(),n=Ob(),{isCmsAvailable:r}=K3(),{hasObservability:i}=kFt(),a=Kc.has(`datasets`),o=r&&a,s=i&&a,{data:c}=NP({agentId:t,requestContext:mw(`agent`,t)[0],queryOptions:{enabled:!!t}}),l=Lq(c?.provider??``),u=c?.modelId??``,d=n.pathname.includes(`/threads`)?`chat`:n.pathname.includes(`/editor`)?`versions`:n.pathname.includes(`/traces`)?`traces`:`none`,f=LVi(d,n.pathname,n.search);return(0,K.jsx)(Far,{defaultProvider:l,defaultModel:u,children:(0,K.jsxs)(Rte,{children:[(0,K.jsx)(FVi,{agentId:t}),(0,K.jsx)(SVi,{}),(0,K.jsx)(FFi,{children:(0,K.jsx)(NVi,{agentId:t})}),(0,K.jsx)(xVi,{agentId:t,disabled:d===`versions`,children:(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:PVi}),headerActions:(0,K.jsx)(wVi,{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)(M0r,{agentId:t,activeTab:d,threadId:f,showPlayground:o,showObservability:s}),e]})]})})]})},`${t}:${l}/${u}`)};function zVi(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:fOi(n,r),childCount:t?.pages.length?`${t.pages.length}${t.nextCursor?`+`:``}`:void 0}}function BVi(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 VVi(e){let t=Y(),n=$ji().data?.[0]?.key,r=e.pageId??e.pageRef,i=Ey({queryKey:[`knowledge`,n,`tree`,null,null],queryFn:n?async()=>t.getKnowledge(n).tree({}):yy,staleTime:3e4}),a=e.pageId!==void 0||e.pageRef!==void 0&&BVi(e.pageRef,i.data),{data:o}=Ey({queryKey:[`knowledge`,n,`page`,r,null],queryFn:n&&r&&a?async()=>t.getKnowledge(n).page(r):yy,retry:!1,staleTime:3e4}),s=o?.page.id,c=Ey({queryKey:[`knowledge`,n,`tree`,s??null,null],queryFn:n&&s?async()=>t.getKnowledge(n).tree({parentId:s}):yy,staleTime:3e4});return o?zVi(o,c.data):void 0}function HVi({children:e}){return(0,K.jsx)(X6n,{pageHref:hZ,refHref:hZ,usePagePreview:VVi,children:e})}var UVi=()=>{let e=kb();return FC({"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},WVi=sF(`/traces`);function GVi(e){return e.startsWith(`/spans`)?`spans`:e.startsWith(`/threads`)?`threads`:`traces`}function KVi({children:e}){let{pathname:t}=Ob(),n=kb();return(0,K.jsx)(FIi,{current:GVi(t),features:uui,onViewChange:e=>n(`/${e}`),breadcrumbs:e=>{let t=qIi(e);return(0,K.jsx)(EP,{crumbs:t?[WVi,{id:e.current,label:t}]:[WVi]})},children:e})}var qVi=()=>(0,K.jsx)(RC,{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)(Br,{}),children:`Processors documentation`}),variant:`fill`}),JVi=[`input`,`inputStep`,`outputStep`,`outputStream`,`outputResult`],YVi={name:e=>e.name||e.id,agents:e=>e.agentIds?.length??0};function XVi({processors:e,isLoading:t,search:n=``,sort:r,onSortChange:i}){let{paths:a,Link:o}=gl(),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 yQ(s.filter(t=>t.id.toLowerCase().includes(e)||(t.name||``).toLowerCase().includes(e)),r,YVi)},[s,n,r]),{containerRef:l,getRowProps:u}=_Q({count:c.length,global:!0});if(t)return(0,K.jsx)(NU,{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)(Qr,{}),` 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)(ei,{}),` 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)(ei,{}),` 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)(ei,{}),` 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=fY(e.name||e.id,50),r=fY(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}),JVi.map(e=>(0,K.jsx)(Z.TextCell,{className:`text-center`,children:s.has(e)&&(0,K.jsx)(Bn,{className:`mx-auto size-4`})},e)),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:i||``})]},e.id)})]})}var Z9=[sF(`/processors`)];function ZVi(){let{data:e={},isLoading:t,error:n}=qP(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)();return n&&JP(n)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Z9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Processors`}),(0,K.jsx)(jU,{variant:`fill`})]}):n&&YP(n)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Z9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Processors`}),(0,K.jsx)(AU,{variant:`fill`,resource:`processors`})]}):n?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Z9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Processors`}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load processors`,descriptionSlot:n.message})]}):Object.keys(e).length===0&&!t?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Z9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Processors`}),(0,K.jsx)(qVi,{})]}):(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Z9}),actionRow:(0,K.jsx)(jq,{children:(0,K.jsx)(jq.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(zU,{onSearch:i,label:`Filter processors`,placeholder:`Filter by name`})})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Processors`}),(0,K.jsx)(XVi,{processors:e,isLoading:t,search:r,sort:a,onSortChange:(e,t)=>o({key:t,direction:e})})]})}var QVi={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 $Vi({processorId:e}){let{data:t,isLoading:n,error:r}=YIt({processorId:e,queryOptions:{enabled:!!e}});return(0,G.useEffect)(()=>{if(r){let e=r instanceof Error?r.message:`Failed to load processor`;UC.error(`Error loading processor: ${e}`)}},[r]),n?(0,K.jsxs)(`div`,{className:`p-4`,children:[(0,K.jsx)(dw,{className:`mb-4 h-8 w-48`}),(0,K.jsx)(dw,{className:`h-32 w-full`})]}):r?null:t?(0,K.jsx)(eHi,{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 eHi({processor:e}){let t=PT(),[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=XIt(),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)(tHi,{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)(fA,{children:[(0,K.jsx)(mA,{children:`Phase`}),(0,K.jsxs)(WA,{value:n,onValueChange:t=>{let n=e.phases.find(e=>e===t);n&&r(n)},children:[(0,K.jsx)(KA,{className:`w-full`,children:(0,K.jsx)(GA,{placeholder:`Select phase`})}),(0,K.jsx)(qA,{children:e.phases.map(e=>(0,K.jsx)(JA,{value:e,children:e},e))})]})]}),(0,K.jsx)(T,{variant:`meta`,tone:`muted`,children:QVi[n]})]}),e.configurations.length>1&&(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{children:`Agent Configuration`}),(0,K.jsxs)(WA,{value:i,onValueChange:a,children:[(0,K.jsx)(KA,{className:`w-full`,children:(0,K.jsx)(GA,{placeholder:`Select agent`})}),(0,K.jsx)(qA,{children:e.configurations.map(e=>(0,K.jsxs)(JA,{value:e.agentId,children:[e.agentName,` (`,e.type,`)`]},e.agentId))})]})]}),(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{children:`Test Message`}),(0,K.jsx)(ZA,{value:o,onChange:e=>s(e.target.value),placeholder:`Enter a test message`,rows:4})]}),(0,K.jsx)(X,{icon:(0,K.jsx)(Vo,{}),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)(bw,{variant:c.success?`success`:`destructive`,children:c.success?`Success`:`Failed`}),c.tripwire?.triggered&&(0,K.jsx)(bw,{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)(jw,{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)(MT,{value:u||m,editable:!0,theme:t,extensions:[mt,NT],basicSetup:{foldGutter:!1}})})]})}function tHi({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)(bw,{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 Q9=[sF(`/processors`),VLt];function nHi(){let{processorId:e}=Ab(),{data:t,isLoading:n,error:r}=YIt({processorId:e,queryOptions:{enabled:!!e}});return r&&JP(r)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(jU,{variant:`fill`})]}):r&&YP(r)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(AU,{variant:`fill`,resource:`processors`})]}):!n&&t?.isWorkflow?(0,K.jsx)(Ib,{to:`/workflows/${e}/graph`,replace:!0}):n?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(dw,{className:`mb-4 h-8 w-48`}),(0,K.jsx)(dw,{className:`h-32 w-full`})]}):(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:Q9}),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)($Vi,{processorId:e})})]})}function rHi(){let e=sFi(),{data:t,isLoading:n}=mzn({toolId:e}),{mutateAsync:r,status:i,data:a,error:o}=hzn(),s={execute:(t,n)=>r({toolId:e,input:t,requestContext:n}),status:i,output:a,error:o};return n?(0,K.jsx)(m$.LoadingData,{}):t?(0,K.jsx)(MVi,{tool:t,execution:s,requestContextEntityType:`tool`,requestContextEntityId:t.id}):(0,K.jsxs)(m$.NoData,{children:[`Tool "`,e,`" not found.`]})}var iHi=()=>(0,K.jsx)(RC,{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)(Br,{}),children:`Tools documentation`}),variant:`fill`}),aHi=(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())},oHi={name:e=>e.id,agents:e=>e.agents.length};function sHi({tools:e,agents:t,isLoading:n,search:r=``,sort:i,onSortChange:a,selectedToolId:o}){let{paths:s,Link:c}=gl(),l=(0,G.useMemo)(()=>aHi(e,t),[e,t]),u=(0,G.useMemo)(()=>yQ(l.filter(e=>e.id.toLowerCase().includes(r.toLowerCase())),i,oHi),[l,r,i]),{containerRef:d,getRowProps:f}=_Q({count:u.length,global:!0});if(n)return(0,K.jsx)(NU,{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)(tF,{}),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=fY(e.id,50),r=fY(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=[sF(`/tools`)];function cHi(){let{data:e={},isLoading:t,error:n}=PP(),{data:r={},isLoading:i,error:a}=BJ(),[o,s]=(0,G.useState)(``),[c,l]=(0,G.useState)(),{toolId:u}=PFi(),d=t||i,f=a||n;return f&&JP(f)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:$9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Tools`}),(0,K.jsx)(jU,{variant:`fill`})]}):f&&YP(f)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:$9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Tools`}),(0,K.jsx)(AU,{variant:`fill`,resource:`tools`})]}):f?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:$9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Tools`}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load tools`,descriptionSlot:f.message})]}):Object.keys(r).length===0&&!d?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:$9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Tools`}),(0,K.jsx)(iHi,{})]}):(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:$9}),actionRow:(0,K.jsx)(jq,{children:(0,K.jsx)(jq.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(zU,{onSearch:s,label:`Filter tools`,placeholder:`Filter by name`})})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Tools`}),(0,K.jsx)(sHi,{tools:r,agents:e,isLoading:d,search:o,sort:c,onSortChange:(e,t)=>l({key:t,direction:e}),selectedToolId:u}),(0,K.jsx)(FFi,{children:(0,K.jsx)(rHi,{})})]})}var lHi=()=>{let e=kb();return(0,K.jsx)(hl,{Link:JC,navigate:t=>e(t),paths:LMn,children:(0,K.jsxs)(Lte,{children:[(0,K.jsx)(UVi,{}),(0,K.jsx)(HVi,{children:(0,K.jsx)(oVi,{children:(0,K.jsx)(S1e,{children:(0,K.jsx)(Lb,{})})})})]})})},uHi=()=>{let e=kb();return(0,K.jsx)(hl,{Link:JC,navigate:t=>e(t),paths:LMn,children:(0,K.jsx)(sVi,{children:(0,K.jsx)(Lb,{})})})},dHi=!!window.MASTRA_CLOUD_API_ENDPOINT,fHi=Kc.has(`datasets`),pHi=[{index:!0,element:(0,K.jsx)(ndi,{})},{path:`instruction-blocks`,element:(0,K.jsx)(rdi,{})},{path:`tools`,element:(0,K.jsx)(sdi,{})},{path:`agents`,element:(0,K.jsx)(Yui,{})},{path:`scorers`,element:(0,K.jsx)(adi,{})},{path:`workflows`,element:(0,K.jsx)(ldi,{})},{path:`skills`,element:(0,K.jsx)(odi,{})},{path:`memory`,element:(0,K.jsx)(idi,{})},{path:`variables`,element:(0,K.jsx)(cdi,{})}],mHi=[{element:(0,K.jsx)(fBi,{}),children:[{path:`/login`,element:(0,K.jsx)(hMi,{})},{path:`/signup`,element:(0,K.jsx)(kIi,{})}]},{path:`/agent-builder`,element:(0,K.jsx)(p1e,{paths:LMn}),children:[{index:!0,element:(0,K.jsx)(BMn,{})},{path:`agents`,element:(0,K.jsx)(X9,{}),children:[{index:!0,element:(0,K.jsx)(pzn,{})}]},{path:`agents`,element:(0,K.jsx)(bVi,{}),children:[{path:`create`,element:(0,K.jsx)(Tzn,{})},{path:`:id`,loader:({params:e})=>qy(`/agent-builder/agents/${e.id}/view`)},{path:`:id/edit`,element:(0,K.jsx)(atr,{})},{path:`:id/view`,element:(0,K.jsx)(mnr,{})}]},{path:`skills`,element:(0,K.jsx)(X9,{}),children:[{index:!0,element:(0,K.jsx)(Unr,{})}]},{path:`skills`,element:(0,K.jsx)(bVi,{}),children:[{path:`create`,element:(0,K.jsx)(qnr,{})},{path:`:id`,loader:({params:e})=>qy(`/agent-builder/skills/${e.id}/edit`)},{path:`:id/edit`,element:(0,K.jsx)(yrr,{})},{path:`:id/view`,element:(0,K.jsx)(Drr,{})}]},{path:`infrastructure`,element:(0,K.jsx)(X9,{}),children:[{index:!0,element:(0,K.jsx)(Mnr,{})}]},{path:`favorite`,element:(0,K.jsx)(X9,{}),children:[{index:!0,element:(0,K.jsx)(Enr,{})}]},{path:`library`,element:(0,K.jsx)(X9,{}),children:[{index:!0,element:(0,K.jsx)(Nnr,{})}]}]},{element:(0,K.jsx)(uHi,{}),children:[{path:`/agents/:agentId/session`,element:(0,K.jsx)(g2r,{})},{path:`/agents/:agentId/session/:threadId`,element:(0,K.jsx)(g2r,{})}]},{element:(0,K.jsx)(lHi,{}),children:[...dHi?[]:[{path:`/settings`,element:(0,K.jsx)(OIi,{})},{path:`/templates`,element:(0,K.jsx)(PLi,{})},{path:`/templates/:templateSlug`,element:(0,K.jsx)(XLi,{})}],{path:`/logs`,element:(0,K.jsx)(mNi,{})},{path:`/scorers`,element:(0,K.jsx)(dIi,{})},{path:`/scorers/:scorerId`,element:(0,K.jsx)(yIi,{})},{path:`/metrics`,element:(0,K.jsx)(eIi,{})},{path:`/intelligence`,element:(0,K.jsx)(Ibn,{})},{path:`/intelligence/entities/:entityType/:entityId`,element:(0,K.jsx)(axn,{})},{element:(0,K.jsx)(KVi,{children:(0,K.jsx)(Lb,{})}),children:[{path:`/traces`,element:(0,K.jsx)(qui,{})},{path:`/spans`,element:(0,K.jsx)(pLi,{})},{path:`/threads`,element:(0,K.jsx)(uRi,{})}]},{path:`/traces/:traceId`,loader:({params:e,request:t})=>{let n=new URL(t.url).searchParams;return n.set(`traceId`,e.traceId??``),qy(`/traces?${n.toString()}`)}},{path:`/observability`,loader:({request:e})=>qy(`/traces${new URL(e.url).search}`)},{path:`/resources`,element:(0,K.jsx)(lIi,{})},{path:`/agents`,element:(0,K.jsx)(sir,{})},{path:`/cms/agents/create`,element:(0,K.jsx)(Zui,{}),children:pHi},{path:`/cms/agents/:agentId/edit`,element:(0,K.jsx)(tdi,{}),children:pHi},{path:`/cms/scorers/create`,element:(0,K.jsx)(vdi,{})},{path:`/cms/scorers/:scorerId/edit`,element:(0,K.jsx)(Sdi,{})},{path:`/prompts`,element:(0,K.jsx)(oIi,{})},{path:`/cms/prompts/create`,element:(0,K.jsx)(ddi,{})},{path:`/cms/prompts/:promptBlockId/edit`,element:(0,K.jsx)(gdi,{})},{path:`/agents/:agentId`,element:(0,K.jsx)(RVi,{children:(0,K.jsx)(Lb,{})}),children:[{index:!0,loader:NMn},{path:`chat`,loader:PMn},{path:`chat/:threadId`,loader:PMn},{path:`threads`,loader:MMn},{path:`threads/:threadId`,element:(0,K.jsx)(J4r,{})},{path:`overview`,loader:IMn},{path:`settings`,loader:IMn},...fHi?[{path:`editor`,element:(0,K.jsx)(O3r,{})}]:[],{path:`traces`,element:(0,K.jsx)(Jui,{})},{path:`channels`,loader:({params:e})=>qy(`/agents/${e.agentId}/threads/new`)}]},{path:`/tools`,element:(0,K.jsx)(cHi,{})},{path:`/integrations`,element:(0,K.jsx)(FDi,{})},{path:`/connections`,element:(0,K.jsx)(Cfi,{})},{path:`/processors`,element:(0,K.jsx)(ZVi,{})},{path:`/processors/:processorId`,element:(0,K.jsx)(nHi,{})},{path:`/mcps`,element:(0,K.jsx)(PNi,{})},{path:`/mcps/:serverId`,element:(0,K.jsx)(IFi,{})},{path:`/workspaces`,element:(0,K.jsx)(lBi,{})},{path:`/workspaces/:workspaceId`,element:(0,K.jsx)(lBi,{})},{path:`/workspaces/:workspaceId/skills/:skillName`,loader:({params:e,request:t})=>qy(Aq(e.workspaceId,new URL(t.url).searchParams.get(`path`)))},{path:`/workflows`,element:(0,K.jsx)(CRi,{})},{path:`/workflows/schedules`,element:(0,K.jsx)(VRi,{})},{path:`/workflows/schedules/:scheduleId`,element:(0,K.jsx)(FRi,{})},{path:`/workflows/:workflowId`,element:(0,K.jsx)(sRt,{children:(0,K.jsx)(Lb,{})}),children:[{index:!0,loader:({params:e})=>qy(`/workflows/${e.workflowId}/graph`)},{path:`graph`,element:(0,K.jsx)(izi,{})},{path:`graph/:runId`,element:(0,K.jsx)(izi,{})},{path:`traces`,element:(0,K.jsx)(ozi,{})},{path:`schedules`,element:(0,K.jsx)(azi,{})}]},{path:`/knowledge`,element:(0,K.jsx)(fMi,{})},...fHi?[{path:`/datasets`,element:(0,K.jsx)(ipi,{})},{path:`/datasets/:datasetId`,element:(0,K.jsx)(jvi,{}),children:[{path:`items/:itemId`,element:null}]},{path:`/datasets/:datasetId/edit`,element:(0,K.jsx)(Rvi,{})},{path:`/datasets/:datasetId/items/:itemId/versions`,element:(0,K.jsx)(Hvi,{})},{path:`/experiments`,element:(0,K.jsx)(Mbi,{})},{path:`/experiments/compare`,element:(0,K.jsx)(qbi,{})},{path:`/experiments/review-queue`,element:(0,K.jsx)(wDi,{})},{path:`/experiments/:experimentId`,element:(0,K.jsx)(oDi,{}),children:[{path:`items/:itemId`,element:null}]},{path:`/datasets/:datasetId/versions`,element:(0,K.jsx)(Gvi,{})}]:[],{index:!0,element:(0,K.jsx)(RMn,{})}]}];function hHi(){let e=window.MASTRA_STUDIO_BASE_PATH||``,{baseUrl:t,headers:n,apiPrefix:r,isLoading:i}=YC(),a=(0,G.useMemo)(()=>t?HVe(t,r):void 0,[t,r]),o=(0,G.useMemo)(()=>({...n,"x-mastra-client-type":`studio`}),[n]),s=(0,G.useMemo)(()=>QGe(mHi,{basename:e}),[e]);return i?(0,K.jsx)(`div`,{className:`flex h-screen w-full items-center justify-center`,children:(0,K.jsx)(Zc,{})}):t?(0,K.jsx)(TBe,{baseUrl:t,headers:o,apiPrefix:r,customFetch:a,children:(0,K.jsx)(c1e,{children:(0,K.jsx)(jMn,{children:(0,K.jsx)(P1e,{baseUrl:t,children:(0,K.jsx)(FGe,{router:s})})})})}):(0,K.jsx)(eGr,{})}function gHi(){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)(Dbn,{children:(0,K.jsx)(N1e,{endpoint:o,defaultApiPrefix:r,children:(0,K.jsx)(hHi,{})})})}function _Hi(){(0,Nte.createRoot)(document.getElementById(`root`)).render((0,K.jsx)(G.StrictMode,{children:(0,K.jsx)(gHi,{})}))}export{_Hi as startStudio};