@mastra/deployer-cloud 1.81.0-alpha.2 → 1.81.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.
|
@@ -692,7 +692,7 @@ window.parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/sandbox-proxy-
|
|
|
692
692
|
]`,rni=[{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 ini(){let{isCopied:e,handleCopy:t}=dT({text:nni,showToast:!1});return(0,K.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,K.jsx)(U,{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:rni.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:Ge({tone:`ink`,variant:`meta`}),children:(0,K.jsx)(FY,{children:e.name})}),(0,K.jsxs)(`dd`,{className:`flex flex-col items-start gap-1.5 text-muted-foreground`,children:[(0,K.jsx)(U,{as:`span`,variant:`meta`,children:e.description}),e.required?(0,K.jsx)(hT,{variant:`success`,size:`xs`,children:`required`}):(0,K.jsx)(hT,{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)(U,{as:`span`,variant:`meta`,tone:`muted`,font:`mono`,children:`example.json`}),(0,K.jsx)(X,{icon:e?(0,K.jsx)(Ln,{}):(0,K.jsx)(br,{}),variant:`ghost`,size:`sm`,onClick:t,children:e?`Copied`:`Copy`})]}),(0,K.jsx)(BD,{variant:`embedded`,language:`json`,editable:!1,lineNumbers:!1,showCopyButton:!1,value:nni,className:`p-3`})]}),(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:tni,target:`_blank`,rel:`noopener noreferrer`}),className:`self-start`,icon:(0,K.jsx)(Lr,{}),children:`Datasets documentation`})]})}var ani=10,oni=`[
|
|
693
693
|
{ "input": "…", "groundTruth": "…" }
|
|
694
694
|
]`,sni=`flex min-h-0 flex-1 flex-col py-0`;function cni({tab:e,onTabChange:t,file:n,onFileSelect:r,onReplace:i,pastedText:a,onPastedTextChange:o,validation:s,isImporting:c}){return(0,K.jsxs)(zA,{value:e,defaultTab:`upload`,onValueChange:t,className:`flex h-full flex-col gap-3`,children:[(0,K.jsxs)(RA,{variant:`pill`,children:[(0,K.jsx)(BA,{value:`upload`,children:`Upload file`}),(0,K.jsx)(BA,{value:`paste`,children:`Paste JSON`})]}),(0,K.jsx)(VA,{value:`upload`,className:sni,children:n?(0,K.jsx)(fni,{file:n,validation:s,onReplace:i,isImporting:c}):(0,K.jsx)(lni,{onFileSelect:r,disabled:c})}),(0,K.jsx)(VA,{value:`paste`,className:sni,children:(0,K.jsx)(BD,{"aria-label":`JSON items`,language:`json`,lineNumbers:!1,showCopyButton:!1,placeholder:oni,value:a,onChange:o,editable:!c,className:`min-h-50 flex-1`})})]})}function lni({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:H(`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)(U,{tone:`ink`,children:`Drop a JSON file here`}),(0,K.jsxs)(U,{variant:`caption`,tone:`muted`,children:[`or `,(0,K.jsx)(`span`,{className:`underline`,children:`choose a file`}),` from your computer`]})]}),(0,K.jsxs)(U,{variant:`meta`,tone:`muted`,children:[`.json · an array of items · up to `,E9r]})]})}function uni(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`}function dni(e){return typeof e==`string`?e:JSON.stringify(e)??``}function fni({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,ani);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)(Gr,{className:`size-4 shrink-0 text-muted-foreground`}),(0,K.jsx)(U,{as:`span`,variant:`caption`,tone:`ink`,font:`mono`,className:`min-w-0 flex-1 truncate`,children:e.name}),(0,K.jsx)(U,{as:`span`,variant:`meta`,tone:`muted`,className:`shrink-0`,children:uni(e.size)}),(0,K.jsx)(X,{icon:(0,K.jsx)(is,{}),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)(U,{as:`span`,variant:`meta`,tone:`muted`,children:e.index}),(0,K.jsx)(U,{as:`span`,variant:`caption`,tone:`ink`,font:`mono`,className:`truncate`,children:dni(e.input)}),e.hasInput?e.hasGroundTruth?null:(0,K.jsx)(hT,{variant:`warning`,size:`xs`,children:`no groundTruth`}):(0,K.jsx)(hT,{variant:`destructive`,size:`xs`,children:`no input`})]},e.index)),a>ani&&(0,K.jsxs)(U,{as:`p`,variant:`meta`,tone:`muted`,className:`border-t border-border px-3 py-1.5`,children:[`+ `,a-ani,` more`]})]})}var pni=e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsText(e)});function mni({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}=BP(),x=a===`upload`?l:p,S=(0,G.useMemo)(()=>a===`upload`&&d?{status:`error`,kind:`parse`,message:d}:k9r(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 ${E9r}`);else try{let n=await pni(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}),yw.success(`Imported ${S.total} item${S.total===1?``:`s`}`),i?.(),r(!1),E()}catch(e){yw.error(e instanceof Error?e.message:`Failed to import items`)}finally{g(!1)}}},[S,b,e,i,r,E]);return(0,K.jsx)(UE,{open:n,onOpenChange:D,pending:h,children:(0,K.jsxs)(WE,{size:`xl`,children:[(0,K.jsxs)(GE,{children:[(0,K.jsx)(JE,{children:`Import into dataset`}),(0,K.jsxs)(YE,{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)(qE,{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)(cni,{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)(ini,{})})]})}),(0,K.jsxs)(KE,{children:[(0,K.jsx)(hni,{validation:S}),(0,K.jsx)(XE,{children:`Cancel`}),(0,K.jsxs)(HE,{onConfirm:O,disabled:S.status!==`ready`,children:[h&&(0,K.jsx)($c,{}),S.status===`ready`?`Import ${S.total} item${S.total===1?``:`s`}`:`Import`]})]})]})})}function hni({validation:e}){let t=H(`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)(K.Fragment,{children:[(0,K.jsx)(U,{as:`b`,variant:`label`,tone:`ink`,children:e.total}),` `,`item`,e.total===1?``:`s`,` ready`,e.missingGroundTruthCount>0&&` · ${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 ${E9r}`;break;case`missing-input`:n=(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(U,{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)(FY,{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)(U,{tone:`muted`,as:`span`,variant:`caption`,className:`truncate`,children:n})]})}function gni(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 _ni({active:e,onPrevious:t,onNext:n,onClose:r}){(0,G.useEffect)(()=>{if(!e)return;let i=e=>{e.defaultPrevented||gni(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 vni=(0,G.createContext)(null);function yni({datasetId:e,items:t,isLoadingItems:n,children:r}){let i=zb(),a=TUe(`/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]);_ni({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)(vni.Provider,{value:d,children:r})}function bni(){let e=(0,G.useContext)(vni);if(!e)throw Error(`useDatasetItemPanel must be used within a DatasetItemPanelProvider`);return e}var xni=[`createdAt`];function Sni({datasetId:e,onAddItemClick:t,onNavigateToDataset:n,toolbarActionsSlot:r}){let[i,a]=Qb(),{activeVersion:o}=KP(i,a),{sort:s,onSortChange:c}=e5({searchParams:i,setSearchParams:a,allowedKeys:xni}),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]=MT(O,300),{data:j}=HP({datasetId:e,queryOptions:{enabled:!!e}}),{data:M=[],isLoading:N,setEndOfListElement:P,isFetchingNextPage:F,hasNextPage:I}=zP({datasetId:e,search:A||void 0,version:o,orderBy:l,queryOptions:{enabled:!!e}}),{deleteItems:L}=BP(),{currentItemId:R,openItem:ee,close:z}=bni();return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`grid h-full overflow-auto`,children:(0,K.jsx)(eni,{items:M,toolbarActionsSlot:r,isLoading:N,onItemClick:e=>{R===e?z():ee(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)(Kti,{datasetId:e,open:u,onOpenChange:d}),(0,K.jsx)(mni,{datasetId:e,datasetName:j?.name,open:f,onOpenChange:p}),(0,K.jsx)(R9r,{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)(z9r,{open:v,onOpenChange:e=>{y(e),e||(x([]),D(e=>e+1))},items:b,currentDatasetId:e}),(0,K.jsx)(sP,{open:S,onOpenChange:C,children:(0,K.jsxs)(sP.Content,{children:[(0,K.jsxs)(sP.Header,{children:[(0,K.jsx)(sP.Title,{children:`Delete Items`}),(0,K.jsxs)(sP.Description,{children:[`Are you sure you want to delete `,w.length,` item`,w.length===1?``:`s`,`? This action cannot be undone.`]})]}),(0,K.jsxs)(sP.Footer,{children:[(0,K.jsx)(sP.Cancel,{children:`Cancel`}),(0,K.jsx)(sP.Action,{onClick:async()=>{await L.mutateAsync({datasetId:e,itemIds:w}),yw.success(`Deleted ${w.length} items`),C(!1),T([]),D(e=>e+1)},children:L.isPending?`Deleting...`:`Delete`})]})]})})]})}var Cni=`__create_tag__`;function wni({datasetId:e}){let{data:t}=HP({datasetId:e,queryOptions:{enabled:!!e}}),{data:n}=VP(),{updateDataset:r}=BP(),[i,a]=(0,G.useState)(``),o=(0,G.useMemo)(()=>Array.isArray(t?.tags)?t.tags:[],[t?.tags]),s=(0,G.useMemo)(()=>B7r(n?.datasets??[]),[n?.datasets]),c=(0,G.useMemo)(()=>{let e=s.map(e=>({label:e,value:e,end:o.includes(e)?(0,K.jsx)(Ln,{"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:Cni},...e]:e},[s,o,i]),l=t=>{r.mutate({datasetId:e,tags:t},{onError:()=>yw.error(`Failed to update tags`)})},u=e=>{let t=e===Cni?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)(Y5,{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)(Bc,{className:`size-3`})})]},e)),(0,K.jsx)(EP,{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 p7=e=>JSON.stringify(e??null,null,2),Tni=e=>e==null||e===``||typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0,Eni=[{key:`input`,title:`Input`,icon:(0,K.jsx)(Qr,{}),value:e=>p7(e.input),payload:e=>e.input},{key:`groundTruth`,title:`Ground Truth`,icon:(0,K.jsx)(ei,{}),value:e=>Tni(e.groundTruth)?void 0:p7(e.groundTruth),payload:e=>Tni(e.groundTruth)?null:e.groundTruth},{key:`expectedTrajectory`,title:`Expected Trajectory`,icon:(0,K.jsx)(gs,{}),value:e=>e.expectedTrajectory==null?void 0:p7(e.expectedTrajectory)},{key:`toolMocks`,title:`Tool Mocks`,icon:(0,K.jsx)(Rc,{}),value:e=>e.toolMocks?.length?p7(e.toolMocks):void 0},{key:`requestContext`,title:`Request Context`,icon:(0,K.jsx)(yn,{}),value:e=>e.requestContext==null?void 0:p7(e.requestContext)},{key:`metadata`,title:`Metadata`,icon:(0,K.jsx)(nc,{}),value:e=>p7(e.metadata)}],Dni=e=>e.toFixed(2);function Oni({delta:e,format:t=Dni,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=H(`inline-flex items-center gap-1 tabular-nums`,i);return s?(0,K.jsxs)(JC,{children:[(0,K.jsx)(YC,{render:(0,K.jsx)(`span`,{tabIndex:0,className:l}),children:c}),(0,K.jsx)(XC,{children:o})]}):(0,K.jsx)(`span`,{className:l,children:c})}function kni({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 m7({metrics:e}){if(e.length===0)return null;let t=e.some(e=>e.delta!=null);return(0,K.jsx)(`dl`,{className:H(`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:H(`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)(Oni,{delta:a,format:o,higherIsBetter:c,baseline:s==null?void 0:s-a})})]},e))})}function h7({value:e}){return(0,K.jsx)(`div`,{className:`min-w-0 p-3 text-foreground`,children:typeof e==`string`?(0,K.jsx)(_Y,{children:e}):(0,K.jsx)(BD,{value:JSON.stringify(e??null,null,2),language:`json`,editable:!1,lineNumbers:!1,showCopyButton:!1,variant:`embedded`,"aria-label":`JSON payload`})})}var g7=`grid content-start gap-5`;function _7({title:e,actions:t,tone:n=`default`,collapsible:r=!0,framed:i=!1,expanded:a,onExpandedChange:o,children:s}){let c=uQ({collapsedHeight:160}),l=a===void 0||!o?c:{...c,isExpanded:a,setExpanded:o,toggleExpanded:()=>o(!a)},u=r?(0,K.jsx)(lQ,{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)(zZ.SectionHeading,{className:H(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)(SF,{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)(io,{}),onClick:()=>l.setExpanded(!1),children:`Collapse`})})]})]})}function Ani({item:e,diff:t}){return(0,K.jsxs)(`div`,{className:g7,children:[(0,K.jsx)(m7,{metrics:jni(e)}),Eni.map(n=>{if(n.payload&&!t){let t=n.payload(e);return t==null?null:(0,K.jsx)(_7,{title:n.title,framed:!0,actions:(0,K.jsx)(fT,{content:typeof t==`string`?t:JSON.stringify(t,null,2)}),children:(0,K.jsx)(h7,{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)(zZ.SectionHeading,{icon:n.icon,children:n.title}),(0,K.jsx)(U,{as:`p`,variant:`body`,tone:`muted`,children:`Not set in this version`})]},n.key):(0,K.jsx)(zZ.CodeSection,{title:n.title,icon:n.icon,codeStr:r,diff:t?{against:i??``,side:t.side}:void 0},n.key)})]})}function jni(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:mU(e.id)}),(0,K.jsx)(fT,{content:e.id,tooltip:`Copy item ID to clipboard`,variant:`link`})]}),delta:null},{id:`created`,icon:(0,K.jsx)(Mn,{}),label:`Created`,value:xT(e.createdAt,`date-time`),delta:null}];return t&&n.push({id:`updated`,icon:(0,K.jsx)(An,{}),label:`Updated`,value:xT(e.updatedAt,`date-time`),delta:null}),n}function Mni({field:e,errors:t}){return t.length===0?null:(0,K.jsx)(MA,{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 Nni({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)(U,{as:`h3`,variant:`heading`,className:`flex items-center gap-2`,children:[(0,K.jsx)(Io,{className:`h-5 w-5`}),` Edit Item`]})}),(0,K.jsxs)(`div`,{className:`space-y-6`,children:[(0,K.jsxs)(OA,{invalid:f?.field===`input`,children:[(0,K.jsx)(AA,{required:!0,children:`Input (JSON)`}),(0,K.jsx)(BD,{value:e,onChange:t,showCopyButton:!1,className:`min-h-[120px]`}),f?.field===`input`&&(0,K.jsx)(Mni,{field:`input`,errors:f.errors})]}),(0,K.jsxs)(OA,{invalid:f?.field===`groundTruth`,children:[(0,K.jsx)(AA,{children:`Ground Truth (JSON, optional)`}),(0,K.jsx)(BD,{value:n,onChange:r,showCopyButton:!1,className:`min-h-[100px]`}),f?.field===`groundTruth`&&(0,K.jsx)(Mni,{field:`groundTruth`,errors:f.errors})]}),(0,K.jsxs)(OA,{children:[(0,K.jsx)(AA,{children:`Expected Trajectory (JSON, optional)`}),(0,K.jsx)(BD,{value:o,onChange:s,showCopyButton:!1,className:`min-h-[80px]`})]}),(0,K.jsxs)(OA,{invalid:f?.field===`toolMocks`,children:[(0,K.jsx)(AA,{children:`Tool Mocks (JSON array, optional)`}),(0,K.jsxs)(jA,{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)(BD,{value:c,onChange:l,showCopyButton:!1,className:`min-h-[100px]`}),f?.field===`toolMocks`&&(0,K.jsx)(Mni,{field:`toolMocks`,errors:f.errors})]}),(0,K.jsxs)(OA,{children:[(0,K.jsx)(AA,{children:`Request Context (JSON, optional)`}),(0,K.jsx)(BD,{value:u,onChange:d,showCopyButton:!1,className:`min-h-[80px]`})]}),(0,K.jsxs)(OA,{children:[(0,K.jsx)(AA,{children:`Metadata (JSON, optional)`}),(0,K.jsx)(BD,{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)(Ln,{}),variant:`primary`,onClick:p,disabled:h,children:h?`Saving...`:`Save changes`}),(0,K.jsx)(X,{icon:(0,K.jsx)(Bc,{}),onClick:m,disabled:h,children:`Cancel`})]})]})]})}function Pni(){return(0,K.jsxs)(aT,{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)(rt,{direction:`right`,className:`-mr-0.5 -ml-[4.3px] size-icon-md in-aria-expanded:translate-x-[2px]`}),`Advanced`]})}function Fni({provider:e,modelId:t,canReset:n,onProviderChange:r,onModelIdChange:i,onReset:a,container:o}){let s=Cw(),{isLoading:c}=pq(),[l,u]=(0,G.useState)(!1);return s.active&&s.pickerVisible===!1?(0,K.jsxs)(NA,{className:`gap-2`,children:[(0,K.jsx)(PA,{children:`Model`}),(0,K.jsx)(`div`,{children:(0,K.jsx)(hT,{icon:(0,K.jsx)(ja,{}),children:`Locked by admin`})})]}):(0,K.jsxs)(NA,{className:`gap-2`,children:[(0,K.jsx)(PA,{children:`Model`}),c?(0,K.jsx)(Yw,{className:`h-control-md w-60 rounded-full`}):(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsxs)(oU,{className:`min-w-0`,children:[(0,K.jsx)(hq,{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)(gq,{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)(ms,{})})]})]})}var Ini=(e,t)=>`${e}:${t}`,Lni=(e,t)=>e?.value===t?.value;function Rni(e,t){if(e!==void 0)return`${`${e} ${e===1?`item`:`items`}`} · ${t===void 0?`latest`:`v${t}`}`}function zni({datasets:e,datasetId:t,version:n,onDatasetChange:r,container:i}){let{total:a}=zP({datasetId:t,search:void 0,version:n,queryOptions:{enabled:!!t}}),o=e.find(e=>e.value===t)??null;return(0,K.jsxs)(OA,{children:[(0,K.jsx)(AA,{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)(xP,{items:e,value:o,onValueChange:e=>e&&r(e.value),isItemEqualToValue:Lni,autoHighlight:!0,children:[(0,K.jsx)(Ujt,{placeholder:`Select a dataset`,children:Rni(a,n)}),(0,K.jsxs)(SP,{container:i,children:[(0,K.jsx)(TP,{children:`No datasets found`}),(0,K.jsx)(CP,{children:e=>(0,K.jsx)(wP,{value:e,children:e.label},e.value)})]})]})]})}function Bni(e,t){return t!==void 0||(e??1)>1}function Vni({datasetId:e,version:t,onVersionChange:n,container:r}){let{data:i}=HP({datasetId:e,queryOptions:{enabled:!!e}});return Bni(i?.version,t)?(0,K.jsxs)(OA,{children:[(0,K.jsx)(AA,{children:`Dataset version`}),(0,K.jsx)(PNt,{datasetId:e,value:t??null,onValueChange:e=>n(e??void 0),container:r})]}):null}function Hni({description:e,onDescriptionChange:t,disabled:n}){return(0,K.jsxs)(OA,{children:[(0,K.jsx)(AA,{children:`Description`}),(0,K.jsx)(cj,{value:e,onChange:e=>t(e.target.value),placeholder:`Optional`,rows:2,disabled:n})]})}function Uni({name:e,defaultName:t,onNameChange:n,disabled:r}){return(0,K.jsxs)(OA,{children:[(0,K.jsx)(AA,{children:`Experiment name`}),(0,K.jsx)(lN,{value:e,placeholder:t,onChange:e=>n(e.target.value),disabled:r})]})}function Wni(e){try{return fA(e)}catch(e){console.error(`Failed to parse requestContextSchema:`,e);return}}function Gni({requestContextSchema:e,onChange:t}){let[n]=(0,G.useState)(()=>Wni(e));return n?(0,K.jsxs)(NA,{children:[(0,K.jsx)(PA,{children:`Request context`}),(0,K.jsx)(iP,{schema:n,onValuesChange:t,className:`[&_button[type=submit]]:hidden`})]}):(0,K.jsx)(`div`,{role:`alert`,children:(0,K.jsx)(HA,{variant:`destructive`,children:`Failed to parse request context schema`})})}function Kni({schema:e,raw:t,onRawChange:n,onValuesChange:r}){return e?(0,K.jsx)(Gni,{requestContextSchema:e,onChange:r}):(0,K.jsxs)(OA,{children:[(0,K.jsx)(AA,{children:`Request context (JSON)`}),(0,K.jsx)(BD,{value:t,onChange:n,showCopyButton:!1,"aria-label":`Request context JSON`,className:`min-h-[120px]`})]})}function qni({onRun:e,canRun:t,isRunning:n}){return(0,K.jsx)(HE,{onConfirm:e,disabled:!t,children:(0,K.jsx)(Jni,{isRunning:n})})}function Jni({isRunning:e}){return e?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)($c,{className:`h-4 w-4`}),`Starting…`]}):`Run experiment`}function Yni({scorer:e}){let t=(0,K.jsx)(wP,{value:e,children:e.label});return e.description?(0,K.jsxs)(JC,{children:[(0,K.jsx)(YC,{render:t}),(0,K.jsx)(XC,{side:`right`,className:`max-w-64`,children:e.description})]}):t}function Xni(){let{data:e}=tF();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 Zni(e,t){return e.map(e=>t.find(t=>t.value===e)??{value:e,label:e})}function Qni({scorerIds:e,usesDefaultScorers:t,onScorerIdsChange:n,container:r}){let i=Xni();return(0,K.jsxs)(OA,{children:[(0,K.jsx)(AA,{info:`Grade each output automatically. Outputs are saved either way, so you can always review them yourself.`,children:`Scorers`}),(0,K.jsxs)(xP,{multiple:!0,items:i,value:Zni(e,i),onValueChange:e=>n(e.map(e=>e.value)),isItemEqualToValue:Lni,autoHighlight:!0,children:[(0,K.jsx)(Xjt,{children:(0,K.jsx)(zjt,{children:e=>(0,K.jsxs)(K.Fragment,{children:[e.map(e=>(0,K.jsx)(Zjt,{children:e.label},e.value)),(0,K.jsx)(Qjt,{placeholder:e.length===0?`No scoring, read the outputs yourself`:void 0})]})})}),(0,K.jsxs)(SP,{container:r,children:[(0,K.jsx)(TP,{children:`No scorers registered`}),(0,K.jsx)(CP,{children:e=>(0,K.jsx)(Yni,{scorer:e},e.value)})]})]}),t&&(0,K.jsx)(jA,{children:`The dataset's default scorers.`})]})}var $ni=[{type:`agent`,label:`Agents`},{type:`workflow`,label:`Workflows`},{type:`scorer`,label:`Scorers`}];function eri(e){return $ni.map(t=>({value:t.label,items:e.filter(e=>e.type===t.type)})).filter(e=>e.items.length>0)}function tri({options:e,isLoading:t,target:n,onTargetValueChange:r,container:i,className:a}){return(0,K.jsxs)(OA,{className:a,children:[(0,K.jsx)(AA,{required:!0,info:`What runs on each item: an agent, a workflow, or a scorer you want to test.`,children:`Target`}),(0,K.jsxs)(xP,{items:eri(e),value:n??null,onValueChange:e=>r(e?.value??``),isItemEqualToValue:Lni,disabled:t,autoHighlight:!0,children:[(0,K.jsx)(Ujt,{placeholder:`Pick an agent, workflow or scorer`}),(0,K.jsxs)(SP,{container:i,children:[(0,K.jsx)(TP,{children:`Nothing to run`}),(0,K.jsx)(CP,{children:(e,t)=>(0,K.jsxs)(Kjt,{items:e.items,children:[t>0?(0,K.jsx)(Yjt,{}):null,(0,K.jsx)(qjt,{children:e.value}),(0,K.jsx)(Jjt,{children:e=>(0,K.jsx)(wP,{value:e,children:e.label},e.value)})]},e.value)})]})]})]})}var nri=(e,t)=>e.provider===t?.provider&&e.modelId===t?.modelId;function rri(e){let[t,n]=(0,G.useState)(null),r=t??e??{provider:``,modelId:``},i=t?.provider&&t.modelId&&!nri(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&&!nri(t,e),agentModel:i}}function iri(e,t){return e||(t[0]?.value??``)}function ari({initialDatasetId:e,initialDatasetVersion:t}){let{data:n}=VP(),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:iri(i,r),version:o,setVersion:s,selectDataset:e=>{a(e),s(void 0)}}}function ori({initialName:e,targetLabel:t}){let[n,r]=(0,G.useState)(e??``),[i]=(0,G.useState)(x3r),a=S3r(t??`experiment`,i);return{name:n,setName:r,defaultName:a,runName:n.trim()||a}}var sri=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function cri(e){if(sri(e)&&Object.keys(e).length!==0)return e}function lri(e){try{return{ok:!0,value:JSON.parse(e)}}catch{return{ok:!1}}}function uri(e){if(!e.trim())return{ok:!0};let t=lri(e);return t.ok?sri(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 dri(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 fri(e){let{data:t}=HP({datasetId:e,queryOptions:{enabled:!!e}}),[n,r]=(0,G.useState)(``),[i,a]=(0,G.useState)({}),o=cri(t?.requestContextSchema);return{schema:o,raw:n,setRaw:r,setValues:a,resetValues:()=>a({}),resolve:()=>o?dri(i):uri(n)}}function pri({datasetId:e,initialScorerIds:t}){let{data:n}=HP({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 mri=(e,t,n,r)=>({value:Ini(e,t),label:n,type:e,id:t,defaultModel:r});function hri(e,t){if(e&&t)return{provider:uq(e),modelId:t}}function gri(){let{data:e,isLoading:t}=FP(),{data:n,isLoading:r}=lP({}),{data:i,isLoading:a}=tF();return{options:[...Object.entries(e??{}).map(([e,t])=>mri(`agent`,e,t.name||e,hri(t.provider,t.modelId))),...Object.entries(n??{}).map(([e,t])=>mri(`workflow`,e,t.name||e)),...Object.entries(i??{}).map(([e,t])=>mri(`scorer`,e,t.scorer?.config?.name||e))],isLoading:t||r||a}}function _ri({initialTargetType:e,initialTargetId:t}){return!e||!t?``:Ini(e,t)}function vri(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 yri(e){let{options:t,isLoading:n}=gri(),[r,i]=(0,G.useState)(()=>_ri(e));return{options:t,isLoading:n,target:vri(t,r,e),setTargetValue:i}}var bri=e=>(e.metaKey||e.ctrlKey)&&e.key===`Enter`,xri=e=>e.trim()||void 0,Sri=e=>e.length>0?e:void 0;function Cri({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=yri({initialTargetType:s,initialTargetId:c}),p=ari({initialDatasetId:i,initialDatasetVersion:a}),m=pri({datasetId:p.datasetId,initialScorerIds:o}),h=fri(p.datasetId),{target:g}=f,_=rri(g?.defaultModel),v=g?.type===`agent`,y=v?_.agentModel:void 0,b=ori({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}=BP(),{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)mw.error(e.message);else try{let n=await T.mutateAsync({datasetId:E,name:b.runName,description:xri(x),targetType:g.type,targetId:g.id,agentModel:y,scorerIds:Sri(m.scorerIds),version:p.version,requestContext:e.requestContext});mw.success(`Experiment started`),t(!1),r?.(n.experimentId)}catch(e){mw.error(e instanceof Error?e.message:`Failed to start experiment`)}};return(0,K.jsx)(UE,{open:e,onOpenChange:t,onOpenChangeComplete:n,pending:D,children:(0,K.jsxs)(WE,{ref:d,size:`lg`,onKeyDown:e=>{bri(e)&&k&&(e.preventDefault(),M())},children:[(0,K.jsxs)(GE,{children:[(0,K.jsx)(JE,{children:`New experiment`}),(0,K.jsx)(YE,{children:`Run every item in a dataset through an agent, workflow or scorer.`})]}),(0,K.jsx)(qE,{children:(0,K.jsxs)(iT,{open:C,onOpenChange:w,className:`py-3`,children:[(0,K.jsxs)(`div`,{className:`space-y-6`,children:[(0,K.jsx)(Uni,{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)(tri,{options:f.options,isLoading:f.isLoading,target:g,onTargetValueChange:A,container:d,className:`min-w-0 flex-1`}),v&&(0,K.jsx)(Fni,{provider:_.provider,modelId:_.modelId,canReset:_.canReset,onProviderChange:_.setProvider,onModelIdChange:_.setModelId,onReset:_.reset,container:d})]}),(0,K.jsx)(zni,{datasets:p.datasets,datasetId:E,version:p.version,onDatasetChange:j,container:d}),(0,K.jsx)(Qni,{scorerIds:m.scorerIds,usesDefaultScorers:m.usesDefaultScorers,onScorerIdsChange:m.setScorerIds,container:d})]}),(0,K.jsx)(`div`,{className:`mt-6`,children:(0,K.jsx)(Pni,{})}),(0,K.jsxs)(oT,{className:`space-y-6 pt-4`,children:[E&&(0,K.jsx)(Vni,{datasetId:E,version:p.version,onVersionChange:p.setVersion,container:d}),(0,K.jsx)(Hni,{description:x,onDescriptionChange:S,disabled:D}),(0,K.jsx)(Kni,{schema:h.schema,raw:h.raw,onRawChange:h.setRaw,onValuesChange:h.setValues},O)]})]})}),(0,K.jsxs)(KE,{children:[(0,K.jsx)(XE,{children:`Cancel`}),(0,K.jsx)(qni,{onRun:M,canRun:k,isRunning:D})]})]})})}function v7({open:e,onOpenChange:t,onSuccess:n,...r}){let[i,a]=(0,G.useState)(0);return(0,K.jsx)(Cri,{open:e,onOpenChange:t,onOpenChangeComplete:e=>{e||a(e=>e+1)},onSuccess:n,...r},`${i}:${JSON.stringify(r)}`)}var wri=`mastra_model_total_input_tokens`,Tri=`mastra_model_total_output_tokens`,Eri=()=>({estimatedCost:0,costUnits:new Set,hasUnknownCostUnit:!1});function Dri(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 Ori(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 kri(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 Ari=2e3;function jri(e){let t=Eri(),n=new Map;for(let r of e.groups){let e=Dri(r);if(!e)continue;Ori(t,e,r);let i=r.dimensions.traceId;i&&Ori(u3(n,i,Eri),e,r)}let r={};for(let[e,t]of n)r[e]=kri(t);return{summary:kri(t),traces:r}}var Mri=5,Nri=e=>!e||Object.keys(e.traces).length===0&&e.summary.inputTokens===void 0&&e.summary.outputTokens===void 0,Pri=({experiments:e,supportsMetrics:t})=>{let n=Y(),r=RP(e.map(e=>e.id));return Fy({queries:e.map(({id:e,status:r})=>{let i=r!==`running`&&r!==`pending`;return{queryKey:[`experiment-item-usage`,e,i],queryFn:async()=>jri(await n.getMetricBreakdown({name:[wri,Tri],aggregation:`sum`,groupBy:[`traceId`,`name`],filters:{experimentId:e}})),enabled:t&&i,refetchInterval:e=>Nri(e.state.data)&&e.state.dataUpdateCount<Mri?Ari:!1}}),combine:r})},Fri=({experimentId:e,experimentStatus:t,supportsMetrics:n,queryOptions:r})=>{let i=Y(),a=!!e&&n,o=Iy({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}},Iri=({traceId:e,queryOptions:t})=>{let n=Y();return Iy({queryKey:[`experiment-trace-light`,e],queryFn:async()=>{if(!e)throw Error(`Trace ID is required`);return n.getTraceLight(e)},...t})};function Lri({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),Iy({queryKey:e?[`dataset-experiments`,e,i]:[`experiments`,i],queryFn:()=>e?r.listDatasetExperiments(e,i):r.listExperiments(i),...n})}var Rri=`mastra_agent_duration_ms`,zri=500,Bri=5e3;function Vri(e){let t=[];for(let n=0;n<e.length;n+=zri)t.push(e.slice(n,n+zri));return t}function Hri(e){return e.flatMap(e=>e.status===`fulfilled`?[e.value]:[])}function Uri(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=Dri(e);t&&r.has(t)&&n&&Ori(u3(i,t,Eri),n,e)}let a=new Map;for(let[e,t]of i)a.set(e,kri(t));for(let e of n.flatMap(e=>e.groups)){let t=e.dimensions.experimentId;t&&r.has(t)&&(u3(a,t,()=>({})).avgDurationMs=e.value)}return a}var Wri=({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 Iy({queryKey:[`experiments-list-metrics`,r],enabled:t&&r.length>0,queryFn:async()=>{let e=Vri(r),[t,i]=await Promise.all([Promise.allSettled(e.map(e=>n.getMetricBreakdown({name:[wri,Tri],aggregation:`sum`,groupBy:[`experimentId`,`name`],filters:{experimentIds:e},limit:e.length*2}))),Promise.allSettled(e.map(e=>n.getMetricBreakdown({name:[Rri],aggregation:`avg`,groupBy:[`experimentId`],filters:{experimentIds:e},limit:e.length})))]);return Uri(r,Hri(t),Hri(i))},placeholderData:Oy,refetchInterval:i?Bri:!1})};function Gri({datasetId:e,target:t,orderBy:n,queryOptions:r}){let i=Y(),{inView:a,setRef:o}=cP(),s=t?.targetType||void 0,c=t?.targetId||void 0,l=zy({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 Kri=(0,G.createContext)(null);function qri({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:i,hasNextPage:a,children:o}){let s=zb(),c=TUe(`/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]);_ni({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)(Kri.Provider,{value:m,children:o})}function Jri(){let e=(0,G.useContext)(Kri);if(!e)throw Error(`useExperimentItemPanel must be used within an ExperimentItemPanelProvider`);return e}function Yri(e,t){if(!e||typeof e!=`object`||!(t in e))return;let n=e[t];return typeof n==`string`&&n?n:void 0}function y7(e){if(e.targetType===`agent`)return Yri(e.output,`text`)}function Xri(e){if(e.targetType)return y7(e);let{output:t}=e;if(t!=null&&t!==``)return typeof t==`string`?t:JSON.stringify(t)}function Zri(e){let t=[];return e.some(e=>Xri(e))&&t.push({name:`output`,label:`Output`,size:`20rem`}),e.some(e=>b7(e))&&t.push({name:`error`,label:`Error`,size:`20rem`}),t}function b7(e){let t=Yri(e.error,`message`);if(t)return t;if(e.targetType===`agent`&&e.output&&typeof e.output==`object`)return Yri(e.output.error,`message`)}function Qri(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $ri(e){return Array.isArray(e)?e.flatMap(e=>Qri(e)&&Qri(e.payload)?[e.payload]:[]):[]}function eii(e){if(e.targetType!==`agent`||!Qri(e.output))return[];let t=new Map($ri(e.output.toolResults).map(e=>[e.toolCallId,e]));return $ri(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 tii(e){if(y7(e)||b7(e))return;let t=eii(e).length;if(t!==0)return`No final text response after ${t} tool ${t===1?`call`:`calls`}`}var x7=e=>e==null?`-`:e.toFixed(2),nii=e=>lT(e)??`-`,rii=(e,t)=>e!=null&&t!=null?e-t:null,iii=new Set(Intl.supportedValuesOf(`currency`)),aii={minimumFractionDigits:3,maximumFractionDigits:3},S7=(e,t)=>{if(e===void 0)return`-`;let n=(t??`usd`).toUpperCase();return iii.has(n)?new Intl.NumberFormat(`en-US`,{style:`currency`,currency:n,...aii}).format(e):`${new Intl.NumberFormat(`en-US`,aii).format(e)} ${t}`},oii=e=>t=>S7(t,e),sii=new Intl.NumberFormat(`en-US`),C7=e=>e===void 0?`-`:sii.format(e),w7=e=>{if(e?.inputTokens!==void 0||e?.outputTokens!==void 0)return(e.inputTokens??0)+(e.outputTokens??0)};function cii({scorerId:e,reason:t,nested:n=!1}){let r=`text-muted-foreground hover:text-foreground [&>svg]:size-3.5`;return(0,K.jsxs)(YX,{children:[(0,K.jsx)(XX,{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)(Yi,{})}),(0,K.jsx)(ZX,{side:`left`,align:`start`,className:`max-h-80 max-w-100 overflow-y-auto`,onClick:e=>e.stopPropagation(),children:(0,K.jsx)(_Y,{children:t})})]})}var lii=new Set([`itemId`,`id`,`status`,`input`,`output`,`error`,`tags`,`scores`,`cost`,`tokens`,`duration`]);function uii({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=>lii.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}=$X({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)(aF,{}),(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)(OU,{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)(nXr,{status:e.status}):(0,K.jsx)(`span`,{className:`text-placeholder`,children:`—`})}),S&&(0,K.jsx)(Z.TextCell,{font:`mono`,children:mii(pii(e.input),200)}),C&&(0,K.jsx)(Z.Cell,{className:`truncate font-mono`,"data-testid":`result-output-${e.id}`,children:Xri(e)??``}),w&&(0,K.jsx)(Z.Cell,{className:`truncate text-destructive-foreground`,"data-testid":`result-error-${e.id}`,children:b7(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)(Y5,{value:e,className:`shrink-0`},e))}),E&&(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(dii,{scores:e.scores})}),D&&(0,K.jsx)(Z.Cell,{className:`text-muted-foreground tabular-nums`,"data-testid":`result-cost-${e.id}`,children:S7(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:C7(w7(e.usage))}),k&&(0,K.jsx)(Z.Cell,{className:`text-muted-foreground tabular-nums`,"data-testid":`result-duration-${e.id}`,children:lT(fii(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)(cii,{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 dii({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)(U,{variant:`meta`,tone:`faint`,children:`—`}):(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(QC,{size:`xs`,className:`text-muted-foreground`,children:(0,K.jsx)(Ei,{})}),(0,K.jsx)(U,{variant:`meta`,tone:`muted`,font:`mono`,children:t[0].toFixed(2)}),t.length>1&&(0,K.jsxs)(hT,{children:[`+`,t.length-1]})]})}function fii({startedAt:e,completedAt:t}){if(e&&t)return new Date(t).getTime()-new Date(e).getTime()}function pii(e){return e==null?`-`:typeof e==`string`?e:JSON.stringify(e,null,2)}function mii(e,t){return e.length<=t?e:e.slice(0,t-1)+`...`}function hii({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}=Jri(),m=(0,G.useMemo)(()=>d?n.find(e=>e.itemId===d)?.id??null:null,[n,d]),{data:h}=GP({experimentId:e,experimentStatus:t,queryOptions:{enabled:!!e}}),{data:g}=Pri({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`},...Zri(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)(uii,{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 gii({children:e,className:t}){return(0,K.jsx)(`div`,{className:H(`grid content-start gap-4 overflow-y-auto`,t),children:e})}function _ii({children:e,className:t}){return(0,K.jsx)(`div`,{className:`flex w-full overflow-y-auto`,children:(0,K.jsx)(`div`,{className:H(`grid w-full content-start gap-4 overflow-y-auto`,t),children:e})})}function vii({children:e,className:t}){return(0,K.jsx)(`div`,{className:H(`flex w-full flex-wrap items-center justify-between gap-3 gap-x-4`,t),children:e})}var yii=Object.assign(_ii,{Content:gii,Toolbar:vii});function bii({children:e,className:t}){return(0,K.jsx)(`div`,{className:H(`grid size-full grid-cols-1 overflow-y-auto`,t),children:e})}function xii(e,t){return t?`v${e} ${xT(typeof t==`string`?new Date(t):t,`date-time`)}`:`v${e}`}function Sii({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){let{data:i}=kNt({datasetId:e,queryOptions:{enabled:!!e}}),a=(i??[]).map(e=>({value:String(e.version),label:`${xii(e.version,e.createdAt)}${e.isCurrent?` (current)`:``}`}));return(0,K.jsxs)(yii.Toolbar,{className:`grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4`,children:[(0,K.jsx)(`div`,{}),(0,K.jsxs)(tj,{value:t??``,onValueChange:e=>r?.(e,n??``),children:[(0,K.jsx)(rj,{"aria-label":`Version A`,size:`md`,children:(0,K.jsx)(nj,{placeholder:`Select version`})}),(0,K.jsx)(ij,{children:a.map(e=>(0,K.jsx)(aj,{value:e.value,children:e.label},e.value))})]}),(0,K.jsxs)(tj,{value:n??``,onValueChange:e=>r?.(t??``,e),children:[(0,K.jsx)(rj,{"aria-label":`Version B`,size:`md`,children:(0,K.jsx)(nj,{placeholder:`Select an option`})}),(0,K.jsx)(ij,{children:a.map(e=>(0,K.jsx)(aj,{value:e.value,children:e.label},e.value))})]}),(0,K.jsx)(`div`,{})]})}var T7={added:{badgeVariant:`info`,borderColor:`border-info-edge`,icon:(0,K.jsx)(Yo,{}),tooltip:`Added in this version`},changed:{badgeVariant:`warning`,borderColor:`border-warning-edge`,icon:(0,K.jsx)(Po,{}),tooltip:`Changed in this version`},same:{badgeVariant:`success`,borderColor:`border-success-edge`,icon:(0,K.jsx)(Oee,{}),tooltip:`Same in both versions`}};function Cii({red:e=!1,tooltip:t}){return(0,K.jsxs)(JC,{children:[(0,K.jsx)(YC,{render:(0,K.jsx)(`span`,{}),role:`img`,tabIndex:0,"aria-label":t,className:H(`rounded`,vt),children:(0,K.jsx)(en,{className:H(`h-5 w-5 text-muted-foreground/40`,{"text-destructive-foreground":e})})}),(0,K.jsx)(XC,{children:t})]})}function E7({href:e,tooltip:t,className:n,children:r}){let{Link:i}=gl(),a=(0,K.jsx)(i,{href:e,className:H(`flex w-full items-center justify-center gap-4 rounded-lg px-3 py-2 text-left hover:bg-fill-subtle`,bt.colors,vt,n),children:r});return t===void 0?a:(0,K.jsxs)(JC,{children:[(0,K.jsx)(YC,{render:a}),(0,K.jsx)(XC,{children:t})]})}function wii({variant:e,version:t}){if(!e)return(0,K.jsxs)(U,{as:`span`,tone:`muted`,children:[`v. `,t]});let{badgeVariant:n,icon:r,tooltip:i}=T7[e];return(0,K.jsxs)(`div`,{className:`grid grid-cols-[1fr_auto]`,children:[t!==void 0&&(0,K.jsxs)(U,{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)(hT,{variant:n,size:`xs`,icon:r})})]})}function Tii(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?`same`:e&&t&&e.datasetVersion!==t.datasetVersion?`changed`:e?`added`:`removed`}function Eii({otherVersionExists:e,status:t,isNewer:n}){if(!e&&n)return`added`;if(t===`changed`&&n)return`changed`}function Dii({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=Tii(n,r),c=Eii({otherVersionExists:r!==void 0,status:s,isNewer:o}),l=Eii({otherVersionExists:n!==void 0,status:s,isNewer:!o});return(0,K.jsxs)(`li`,{className:H(`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`,bt.colors),children:[(0,K.jsx)(U,{as:`p`,variant:`body`,tone:`faint`,className:`truncate py-[0.6rem]`,children:t}),s===`same`?(0,K.jsx)(E7,{href:`/datasets/${e}/items/${t}`,className:`col-span-2 gap-2`,tooltip:T7.same.tooltip,children:(0,K.jsx)(wii,{variant:`same`,version:r?.datasetVersion})}):(0,K.jsxs)(K.Fragment,{children:[n?.datasetVersion?(0,K.jsx)(E7,{href:`/datasets/${e}/items/${t}`,className:`gap-2`,tooltip:c?T7[c].tooltip:void 0,children:(0,K.jsx)(wii,{variant:c,version:n.datasetVersion})}):(0,K.jsx)(`div`,{className:`flex items-center justify-center`,children:(0,K.jsx)(Cii,{red:o,tooltip:o?`Deleted in this version`:`Not present in this version`})}),r?.datasetVersion?(0,K.jsx)(E7,{href:`/datasets/${e}/items/${t}`,className:`gap-2`,tooltip:l?T7[l].tooltip:void 0,children:(0,K.jsx)(wii,{variant:l,version:r.datasetVersion})}):(0,K.jsx)(`div`,{className:`flex items-center justify-center`,children:(0,K.jsx)(Cii,{red:!o,tooltip:o?`Not present in this version`:`Deleted in this version`})})]}),s===`changed`?(0,K.jsx)(E7,{href:`/datasets/${e}/items/${t}/versions?version=${n?.datasetVersion}&compare=${r?.datasetVersion}`,children:`Compare`}):(0,K.jsx)(`div`,{children:(0,K.jsx)(Cii,{tooltip:`Comparing is available only for changed items`})})]},t)})})})}function Oii(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 kii({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)(Aii,{item:e,onClose:r,...a},e.id):t?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(zZ.Header,{children:[(0,K.jsx)(zZ.Heading,{children:`Dataset item`}),(0,K.jsx)(zZ.HeaderActions,{children:(0,K.jsx)(zZ.CloseButton,{icon:`x`,onClick:r,tooltip:`Close detail panel`})})]}),n]}):null;return i===`inline`?c?(0,K.jsx)(zZ,{variant:`inline`,title:s,children:c}):null:(0,K.jsx)(zZ,{open:!!o,onClose:r,title:s,children:c})}function Aii({datasetId:e,item:t,items:n,onItemChange:r,onClose:i}){let{navigate:a}=gl(),{updateItem:o,deleteItem:s}=BP(),[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)(zZ.Header,{children:[(0,K.jsx)(zZ.Heading,{children:`Dataset item`}),(0,K.jsxs)(zZ.HeaderActions,{children:[!c&&(0,K.jsxs)(gE,{children:[(0,K.jsx)(gE.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)(jr,{})})}),(0,K.jsxs)(gE.Content,{align:`end`,className:`w-48`,children:[(0,K.jsxs)(gE.Item,{onSelect:()=>a(`/datasets/${e}/items/${t.id}/versions?version=${t.datasetVersion}`),children:[(0,K.jsx)(fs,{}),`Item versions`]}),(0,K.jsxs)(gE.Item,{onSelect:()=>l(!0),children:[(0,K.jsx)(Io,{}),`Edit`]}),(0,K.jsxs)(gE.Item,{onSelect:()=>T(!0),variant:`destructive`,children:[(0,K.jsx)(xc,{}),`Delete item`]})]})]}),(0,K.jsx)(zZ.NextPrevNav,{onPrevious:D,onNext:O,previousLabel:`Go to previous item`,nextLabel:`Go to next item`}),(0,K.jsx)(zZ.CloseButton,{icon:`x`,onClick:i,tooltip:`Close detail panel`})]})]}),(0,K.jsx)(zZ.Content,{children:c?(0,K.jsx)(Nni,{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{yw.error(`Input must be valid JSON`);return}let r;if(f.trim())try{r=JSON.parse(f)}catch{yw.error(`Ground Truth must be valid JSON`);return}let i;if(m.trim())try{i=JSON.parse(m)}catch{yw.error(`Metadata must be valid JSON`);return}let a=null;if(g.trim())try{a=JSON.parse(g)}catch{yw.error(`Expected Trajectory must be valid JSON`);return}let s;if(v.trim())try{let e=JSON.parse(v);if(!Array.isArray(e)){yw.error(`Tool Mocks must be a JSON array`);return}s=e}catch{yw.error(`Tool Mocks must be valid JSON`);return}else s=[];let c;if(b.trim())try{c=JSON.parse(b)}catch{yw.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}),yw.success(`Item updated successfully`),l(!1),C(null)}catch(e){let t=Oii(e);t?C(t):yw.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)(Ani,{item:t})}),(0,K.jsx)(sP,{open:w,onOpenChange:T,children:(0,K.jsxs)(sP.Content,{children:[(0,K.jsxs)(sP.Header,{children:[(0,K.jsx)(sP.Title,{children:`Delete Item`}),(0,K.jsx)(sP.Description,{children:`Are you sure you want to delete this item? This action cannot be undone.`})]}),(0,K.jsxs)(sP.Footer,{children:[(0,K.jsx)(sP.Cancel,{children:`Cancel`}),(0,K.jsx)(sP.Action,{onClick:async()=>{try{await s.mutateAsync({datasetId:e,itemId:t.id}),yw.success(`Item deleted successfully`),T(!1),i()}catch(e){yw.error(`Failed to delete item: ${e instanceof Error?e.message:`Unknown error`}`)}},children:s.isPending?`Deleting...`:`Yes, delete`})]})]})})]})}var D7=(0,G.createContext)(null);function jii({children:e}){let[t,n]=(0,G.useState)(null),[r,i]=(0,G.useState)([]),[a,o]=(0,G.useState)(!0),s=!RE()&&a,c=(0,G.useRef)(null),l=(0,G.useRef)(0),u=(0,G.useCallback)((e,t)=>{let n=l.current+1;return l.current=n,i(r=>[...r.filter(t=>t.owner!==e),{owner:e,priority:t,order:n}]),()=>{i(t=>t.filter(t=>t.owner!==e||t.order!==n))}},[]),d=(0,G.useMemo)(()=>{let e;for(let t of r)(!e||t.priority>e.priority||t.priority===e.priority&&t.order>e.order)&&(e=t);return e?.owner??null},[r]),f=(0,G.useCallback)(()=>c.current?.toggle(),[]),p=(0,G.useCallback)(e=>o(e<=0),[]),m=(0,G.useMemo)(()=>({el:t,setEl:n,activeOwner:d,register:u,panelHandle:c,isCollapsed:s,onPanelResize:p,toggle:f}),[d,t,s,p,u,f]);return(0,K.jsx)(D7.Provider,{value:m,children:e})}function Mii(e){let t=(0,G.use)(D7);return(0,K.jsx)(`div`,{ref:t?.setEl??void 0,...e})}function O7({owner:e,priority:t=0,children:n}){let r=(0,G.use)(D7),i=r?.register;return(0,G.useEffect)(()=>{if(i)return i(e,t)},[e,t,i]),!r?.el||r.activeOwner!==e?null:(0,Zc.createPortal)(n,r.el)}var Nii=()=>{},Pii={current:null};function k7(){let e=(0,G.use)(D7);if(!e)return{hasPanel:!1,isCollapsed:!0,onPanelResize:Nii,panelHandle:Pii,toggle:Nii};let{activeOwner:t,isCollapsed:n,onPanelResize:r,panelHandle:i,toggle:a}=e;return{hasPanel:t!==null,isCollapsed:n,onPanelResize:r,panelHandle:i,toggle:a}}function Fii(e,t){let{hasPanel:n,isCollapsed:r,panelHandle:i}=k7(),a=(0,G.useRef)(!1);(0,G.useEffect)(()=>{if(!e||!n)return;let t=requestAnimationFrame(()=>i.current?.expand());return()=>cancelAnimationFrame(t)},[e,n,i]);let o=(0,G.useEffectEvent)(()=>t());(0,G.useEffect)(()=>{if(!n)a.current=!1;else if(!r)a.current=!0;else if(a.current&&e){if(a.current=!1,!document.querySelector(`[data-separator="active"]`))o();else return window.addEventListener(`pointerup`,o,{once:!0}),()=>window.removeEventListener(`pointerup`,o)}},[n,r,e])}function Iii(){let{datasetId:e,items:t,isLoadingItems:n,currentItemId:r,openItem:i,close:a}=bni(),o=RE();Fii(r,a);let s=(0,G.useMemo)(()=>r?t.find(e=>e.id===r):void 0,[t,r]),{data:c,isLoading:l}=lNt({datasetId:s?``:e,itemId:!s&&r?r:``,queryOptions:{enabled:!(s||!e)&&!!(!s&&r&&r)}}),u=(0,K.jsx)(kii,{datasetId:e,item:s??c??void 0,itemId:r,fallback:n||l?(0,K.jsx)(zZ.LoadingData,{}):(0,K.jsxs)(zZ.NoData,{children:[`No loaded item "`,r,`".`]}),items:t,onItemChange:i,onClose:a,variant:o?`drawer`:`inline`});return o?u:r?(0,K.jsx)(O7,{owner:`dataset-item`,children:u}):null}function A7({crumbs:e,children:t}){return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{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 Lii(){let{datasetId:e}=Bb(),t=zb(),[n,r]=Qb(),{activeVersion:i}=KP(n,r),a=[cF(`/datasets`),lF],o=[...a,GPt],[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}=HP({datasetId:e,queryOptions:{enabled:!!e}}),{data:b=[],isLoading:x}=zP({datasetId:e,search:void 0,version:i,queryOptions:{enabled:!!e}});if(y)return null;if(v&&YP(v))return(0,K.jsx)(A7,{crumbs:a,children:(0,K.jsx)(fU,{})});if(v&&XP(v))return(0,K.jsx)(A7,{crumbs:a,children:(0,K.jsx)(dU,{resource:`datasets`})});if(v&&ZP(v)||!y&&!v&&!_)return(0,K.jsx)(A7,{crumbs:a,children:(0,K.jsx)(fw,{titleSlot:`Dataset not found`,descriptionSlot:`No dataset with id "${e}".`,actionSlot:(0,K.jsx)(X,{render:(0,K.jsx)(Zb,{to:`/datasets`}),icon:(0,K.jsx)(Rt,{}),children:`Back to datasets`})})});if(v)return(0,K.jsx)(A7,{crumbs:a,children:(0,K.jsx)(fw,{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)(Yo,{}),children:`New experiment`}),E&&(0,K.jsx)(X,{variant:`ghost`,size:`sm`,render:(0,K.jsx)(Zb,{to:`/experiments?dataset=${e}`}),icon:(0,K.jsx)(DPt,{}),children:`Experiments`}),(0,K.jsx)(X,{variant:`ghost`,size:`sm`,onClick:()=>g(!0),icon:(0,K.jsx)(yn,{}),children:`Schema`}),(0,K.jsxs)(gE,{children:[(0,K.jsx)(gE.Trigger,{asChild:!0,children:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,"aria-label":`Dataset actions menu`,children:(0,K.jsx)(jr,{})})}),(0,K.jsxs)(gE.Content,{align:`end`,className:`w-48`,children:[(0,K.jsxs)(gE.Item,{onSelect:()=>void t(`/datasets/${e}/edit`),children:[(0,K.jsx)(Io,{}),` Edit dataset`]}),(0,K.jsxs)(gE.Item,{onSelect:()=>m(!0),children:[(0,K.jsx)(br,{}),` Duplicate dataset`]}),(0,K.jsxs)(gE.Item,{onSelect:()=>f(!0),variant:`destructive`,children:[(0,K.jsx)(xc,{}),` Delete dataset`]})]})]})]});return(0,K.jsxs)(yni,{datasetId:e,items:b,isLoadingItems:x,children:[(0,K.jsxs)(`div`,{className:`h-full`,children:[(0,K.jsxs)(Jw,{variant:`fit`,breadcrumbs:(0,K.jsx)(DP,{crumbs:o}),headerActions:O,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(`div`,{children:(0,K.jsx)(Sni,{datasetId:e,onAddItemClick:()=>u(!0),toolbarActionsSlot:D?(0,K.jsx)(wni,{datasetId:e}):void 0})})]}),(0,K.jsx)(Iii,{})]}),(0,K.jsx)(v7,{initialDatasetId:e,initialDatasetVersion:i??void 0,open:s,onOpenChange:c,onSuccess:S},`${e}:${i??`latest`}`),(0,K.jsx)(R9n,{datasetId:e,open:l,onOpenChange:u}),_&&(0,K.jsx)(B9r,{open:p,onOpenChange:m,sourceDatasetId:_.id,sourceDatasetName:_.name,sourceDatasetDescription:_.description,sourceDatasetTargetType:_.targetType}),_&&(0,K.jsx)(Pti,{open:h,onOpenChange:g,dataset:_}),_&&(0,K.jsx)(aei,{open:d,onOpenChange:f,datasetId:_.id,datasetName:_.name,onSuccess:C})]})}function Rii({children:e,className:t}){return(0,K.jsx)(`div`,{className:H(`grid content-start`,t),children:e})}function zii({children:e,isLoading:t}){return(0,K.jsx)(U,{variant:`caption`,tone:`muted`,className:H(`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 Bii({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:H(`grid w-full grid-cols-[1fr_auto] gap-8`,{"mt-6 mb-4":a},i),children:e}):(0,K.jsxs)(`header`,{className:H(`grid gap-1 py-3`,i),children:[(0,K.jsx)(U,{as:`h1`,variant:`heading`,tone:`ink`,className:H(`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)(U,{variant:`caption`,tone:`muted`,className:H(`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 Vii({children:e,isLoading:t}){return(0,K.jsx)(U,{as:`h1`,variant:`heading`,tone:`ink`,className:H(`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 j7=Object.assign(Bii,{Title:Vii,Description:zii,Column:Rii}),Hii=[cF(`/datasets`),lF,{id:`dataset-edit`,label:`Edit dataset`}];function Uii({children:e}){return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:Hii}),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 Wii(){let{datasetId:e}=Bb(),t=zb(),{data:n,error:r,isLoading:i}=HP({datasetId:e,queryOptions:{enabled:!!e}}),a=()=>void t(`/datasets/${e}`);return i?null:r&&YP(r)?(0,K.jsx)(Uii,{children:(0,K.jsx)(fU,{})}):r&&XP(r)?(0,K.jsx)(Uii,{children:(0,K.jsx)(dU,{resource:`datasets`})}):r||!n?(0,K.jsx)(Uii,{children:(0,K.jsx)(fw,{tone:`error`,titleSlot:`Failed to load dataset`,descriptionSlot:r instanceof Error?r.message:`An unexpected error occurred. Please try again.`})}):(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:Hii}),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)(j7,{className:`mb-6 p-0`,children:(0,K.jsxs)(j7.Column,{children:[(0,K.jsxs)(j7.Title,{children:[(0,K.jsx)(Er,{}),` Edit dataset`]}),(0,K.jsx)(j7.Description,{children:n.name})]})}),(0,K.jsx)(SF,{className:`p-4`,children:(0,K.jsx)(iei,{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 Gii(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 Kii(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)(`span`,{children:[(0,K.jsxs)(`b`,{children:[`v. `,e.datasetVersion]}),` · `,xT(n,`date-time`)]}),e.isLatest?(0,K.jsx)(hT,{variant:`blue`,size:`xs`,className:`ml-auto`,children:`Latest`}):null]}),disabled:t?.has(e.datasetVersion)??!1}})}function qii(e){let t=Number(e);return e!=null&&Number.isFinite(t)&&t>0?t:null}function Jii(){let{datasetId:e,itemId:t}=Bb(),[n,r]=Qb(),i=[cF(`/datasets`),lF,{id:`dataset-item`,label:zPt(t),to:e&&t?`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}`:void 0},{id:`dataset-item-versions`,label:`Item Version History`}],a=qii(n.get(`version`)),o=qii(n.get(`compare`)),s=n.get(`view`)===`diff`,{data:c,error:l}=HP({datasetId:e??``,queryOptions:{enabled:!!e}}),{data:u,isLoading:d}=ENt({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}=DNt({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&&YP(l))return(0,K.jsxs)(Jw,{variant:`fit`,breadcrumbs:(0,K.jsx)(DP,{crumbs:i}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Item Version History`}),(0,K.jsx)(fU,{variant:`fill`})]});if(l&&XP(l))return(0,K.jsxs)(Jw,{variant:`fit`,breadcrumbs:(0,K.jsx)(DP,{crumbs:i}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Item Version History`}),(0,K.jsx)(dU,{variant:`fill`,resource:`datasets`})]});if(!e||!t)return(0,K.jsxs)(Jw,{variant:`fit`,breadcrumbs:(0,K.jsx)(DP,{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?Gii(f,e):null,x=h?Gii(h,e):null,S=(f?.datasetVersion??0)<(h?.datasetVersion??0);return(0,K.jsxs)(Jw,{variant:`fit`,breadcrumbs:(0,K.jsx)(DP,{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)(pr,{}),` Default view`]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Ai,{}),` 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)(SF,{className:`grid min-h-0 grid-rows-[auto_1fr] overflow-hidden`,children:[(0,K.jsx)(CF,{children:(0,K.jsx)(Yii,{label:`Version`,value:p==null?``:String(p),options:Kii(u??[],m==null?void 0:new Set([m])),onValueChange:e=>_(`version`,Number(e))})}),(0,K.jsx)(EF,{className:`grid content-start gap-5 overflow-y-auto`,children:d?(0,K.jsx)(U,{as:`p`,variant:`body`,tone:`muted`,children:`Loading...`}):b?(0,K.jsx)(Ani,{item:b,diff:y&&x?{against:x,side:S?`a`:`b`}:void 0}):(0,K.jsx)(U,{as:`p`,variant:`body`,tone:`muted`,children:`Item data not available`})})]}),(0,K.jsxs)(SF,{className:`grid min-h-0 grid-rows-[auto_1fr] overflow-hidden`,children:[(0,K.jsx)(CF,{children:(0,K.jsx)(Yii,{label:`Compare version`,value:m==null?``:String(m),placeholder:`Select a version to compare`,options:Kii(u??[],p==null?void 0:new Set([p])),onValueChange:e=>_(`compare`,Number(e))})}),(0,K.jsx)(EF,{className:`grid content-start gap-5 overflow-y-auto`,children:m==null?(0,K.jsx)(fw,{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)(U,{as:`p`,variant:`body`,tone:`muted`,children:`Loading...`}):x?(0,K.jsx)(Ani,{item:x,diff:y&&b?{against:b,side:S?`b`:`a`}:void 0}):(0,K.jsxs)(U,{as:`p`,variant:`body`,tone:`muted`,children:[`Version `,m,` not found`]})})]})]})]})}function Yii({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)(fs,{className:`size-4 opacity-50`}),(0,K.jsxs)(tj,{value:t,onValueChange:i,children:[(0,K.jsx)(rj,{"aria-label":e,className:`w-full`,children:(0,K.jsx)(nj,{placeholder:r,className:`flex-1`})}),(0,K.jsx)(ij,{children:n.map(e=>(0,K.jsx)(aj,{value:e.value,disabled:e.disabled,children:e.label},e.value))})]})]})}var M7=[cF(`/datasets`),lF,{id:`dataset-versions`,label:`Versions`}];function Xii(){let{datasetId:e}=Bb(),[t]=Qb(),n=t.get(`ids`)?.split(`,`).map(Number).filter(e=>!isNaN(e)&&e>0)??[],r=zb(),{data:i,error:a}=HP({datasetId:e??``,queryOptions:{enabled:!!e}}),o=zP({datasetId:e??``,search:void 0,version:n[0]??null,queryOptions:{enabled:!!e}}),s=zP({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&&YP(a)?(0,K.jsxs)(Jw,{variant:`fit`,breadcrumbs:(0,K.jsx)(DP,{crumbs:M7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Versions`}),(0,K.jsx)(fU,{variant:`fill`})]}):a&&XP(a)?(0,K.jsxs)(Jw,{variant:`fit`,breadcrumbs:(0,K.jsx)(DP,{crumbs:M7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Versions`}),(0,K.jsx)(dU,{variant:`fill`,resource:`datasets`})]}):!e||n.length<2?(0,K.jsxs)(Jw,{variant:`fit`,breadcrumbs:(0,K.jsx)(DP,{crumbs:M7}),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)(Jw,{variant:`fit`,breadcrumbs:(0,K.jsx)(DP,{crumbs:M7}),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)(j7,{children:[(0,K.jsxs)(j7.Column,{children:[(0,K.jsxs)(j7.Title,{children:[(0,K.jsx)(Zee,{}),` Compare Dataset Versions`]}),(0,K.jsx)(j7.Description,{children:(0,K.jsxs)(QX,{children:[(0,K.jsx)(fs,{}),` Comparing `,n.length,` versions of`,` `,i?.name||e?.slice(0,8)]})})]}),(0,K.jsx)(j7.Column,{children:(0,K.jsx)(X,{render:(0,K.jsx)(Zb,{to:`/datasets/${e}`}),icon:(0,K.jsx)(Rt,{}),children:`Back to dataset`})})]}),(0,K.jsx)(bii,{children:(0,K.jsxs)(yii,{children:[(0,K.jsx)(Sii,{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)(Dii,{datasetId:e,versionA:n[0],versionB:n[1],allItems:u,itemsAMap:d,itemsBMap:f})]})})]})})]})}var Zii=(e,{experimentId:t,targetType:n,targetId:r,experiments:i,isLoadingExperiments:a=!1,queryOptions:o})=>{let s=Y(),c=i!==void 0,{data:l,isLoading:u}=Lri({datasetId:void 0,target:{targetType:n,targetId:r},queryOptions:{enabled:!c}}),d=c?i:l?.experiments,f=c?a:u,p=t?d?.filter(e=>e.id===t):d,m=Iy({queryKey:[`review-items`,e,t??`all`,c?`supplied`:`discovered`,c?void 0:n||`all`,c?void 0:r||`all`,p?.map(e=>[e.datasetId,e.id])],queryFn:async()=>!p||p.length===0?[]:(await Promise.all(p.map(async t=>{if(!t.datasetId)return[];try{let{results:n}=await s.listDatasetExperimentResults(t.datasetId,t.id);return n.filter(t=>t.status===e).map(e=>({id:e.id,input:e.input,output:e.output,error:e.error,itemId:e.itemId,experimentId:e.experimentId,datasetId:t.datasetId??void 0,traceId:e.traceId??void 0,scores:e.scores?Object.fromEntries(e.scores.map(e=>[e.scorerId,e.score??0])):{},tags:e.tags??[],targetType:e.targetType,createdAt:e.createdAt,startedAt:e.startedAt,completedAt:e.completedAt,status:e.status,groundTruth:e.groundTruth,toolMockReport:e.toolMockReport}))}catch{return[]}}))).flat(),enabled:!!d,refetchOnWindowFocus:!1,...o});return{...m,isLoading:m.isLoading||f}},Qii=(e={})=>Zii(`needs-review`,e),$ii=(e={})=>Zii(`complete`,e);function eai({queryOptions:e}={}){let t=Y();return Iy({queryKey:[`experiment-review-summary`],queryFn:()=>t.getExperimentReviewSummary(),...e})}var N7={baseline:`purple`,contender:`blue`},P7=e=>e===0?`Baseline`:`Contender ${e}`;function tai({open:e,onOpenChange:t,experimentId:n,experimentName:r,onSuccess:i}){let{deleteExperiment:a}=BP();return(0,K.jsx)(sP,{open:e,onOpenChange:t,children:(0,K.jsxs)(sP.Content,{children:[(0,K.jsxs)(sP.Header,{children:[(0,K.jsx)(sP.Title,{children:`Delete Experiment`}),(0,K.jsxs)(sP.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)(sP.Footer,{children:[(0,K.jsx)(sP.Cancel,{children:`Cancel`}),(0,K.jsx)(X,{icon:(0,K.jsx)(xc,{}),variant:`primary`,onClick:async()=>{try{await a.mutateAsync(n),yw.success(`Experiment deleted successfully`),t(!1),i?.()}catch(e){yw.error(`Failed to delete experiment: ${e instanceof Error?e.message:`Unknown error`}`)}},disabled:a.isPending,children:a.isPending?`Deleting...`:`Delete`})]})]})})}var nai=`minmax(9rem,1fr)`,rai=`minmax(8rem,16rem)`,iai=`auto auto auto auto auto auto auto auto`,aai=`auto auto auto`,F7={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`},oai={completed:`neutral`,running:`warning`,failed:`destructive`,pending:`neutral`},I7={completed:`Run completed`,running:`Run in progress`,failed:`Run failed`,pending:`Run queued`};function sai(e){let t=mU(e.id)??e.id;return e.name||`Experiment #${t}`}var cai=60;function lai({experiment:e}){return(0,K.jsx)(`span`,{className:`block min-w-0 truncate text-left text-muted-foreground`,children:sai(e)})}function uai({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<=cai?n:(0,K.jsxs)(JC,{children:[(0,K.jsx)(YC,{asChild:!0,children:n}),(0,K.jsx)(XC,{children:t})]})}function dai(){let{data:e}=FP(),{data:t}=lP(),{data:n}=tF(),{data:r}=JP();return{agents:e,workflows:t,scorers:n,processors:r}}var fai={agent:nF,workflow:aP,scorer:aF,processor:iF},pai={agent:`Agent`,workflow:`Workflow`,scorer:`Scorer`,processor:`Processor`},mai=`External (caller-run)`;function hai(e,{agents:t,workflows:n,scorers:r,processors:i}){let{targetType:a,targetId:o}=e;if(!o)return mai;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 gai({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)(hT,{variant:r.variant,className:`shrink-0`,children:r.label}),(0,K.jsx)(lai,{experiment:e})]}):(0,K.jsx)(lai,{experiment:e})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(uai,{experiment:e})}),t!==void 0&&(0,K.jsx)(Z.TextCell,{children:t}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(yai,{experiment:e})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(hT,{variant:oai[o]??`neutral`,indicator:`dot`,children:I7[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)(L7,{value:_ai(e),format:lT}),i&&(0,K.jsx)(vai,{metrics:a}),(0,K.jsx)(Z.Cell,{className:`text-center`,children:(0,K.jsx)(bai,{review:n})}),(0,K.jsx)(Z.TextCell,{children:xT(e.createdAt,`date`)??`—`})]})}function _ai(e){if(e.startedAt&&e.completedAt)return new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime()}function vai({metrics:e}){let t=e?.avgDurationMs===void 0?void 0:Math.round(e.avgDurationMs);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(L7,{value:t,format:lT}),(0,K.jsx)(L7,{value:w7(e),format:l8}),(0,K.jsx)(L7,{value:e?.estimatedCost,format:t=>S7(t,e?.costUnit)})]})}function L7({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 yai({experiment:e}){let t=hai(e,dai()),n=e.targetId?e.targetType:null,r=n?fai[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":pai[n],children:(0,K.jsx)(r,{})}),(0,K.jsx)(`span`,{className:n?`truncate`:`truncate text-placeholder`,children:t})]})}function bai({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)(hT,{size:`xs`,variant:`warning`,children:[e.needsReview,` pending`]}):(0,K.jsxs)(hT,{size:`xs`,variant:`success`,children:[e.complete,`/`,t,` reviewed`]})}var xai=`${nai} ${rai} 1fr ${iai}`,Sai=`${xai} auto`,Cai=`${xai} ${aai} auto`,wai=[{label:F7.avgDuration,className:`text-center`},{label:F7.tokens,className:`text-center`},{label:F7.cost,className:`text-center`}],Tai=e=>[{label:F7.experiment},{label:F7.description},{label:F7.dataset},{label:F7.target},{label:F7.status,sortKey:`status`},{label:F7.items,className:`text-center`},{label:F7.succeeded,className:`text-center`},{label:F7.failed,className:`text-center`},{label:F7.duration,className:`text-center`},...e?wai:[],{label:F7.review,className:`text-center`},{label:F7.date,sortKey:`createdAt`}],Eai=e=>e.stopPropagation();function Dai({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:Eai,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 Oai({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}=$X({count:y.length,global:d}),[S,C]=(0,G.useState)(null),w=r!==void 0,T=w?Cai:Sai;if(i)return(0,K.jsx)(OU,{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=Tai(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)??mU(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)(gai,{experiment:e,datasetName:i,review:n?.get(e.id),showUsage:w,metrics:r?.get(e.id),selectionRole:o?{label:P7(a),variant:a===0?N7.baseline:N7.contender}:void 0});return(0,K.jsx)(Dai,{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)(tai,{open:!0,onOpenChange:e=>{e||C(null)},experimentId:S.id,experimentName:S.name??void 0})]})}var kai=[{value:`all`,label:`All statuses`},{value:`completed`,label:`Completed`},{value:`running`,label:`Running`},{value:`failed`,label:`Failed`},{value:`pending`,label:`Pending`}];function Aai(e){return[{value:`all`,label:`All datasets`},...(e??[]).map(e=>({value:e.id,label:e.name}))]}var jai=({onRunExperiment:e})=>(0,K.jsx)(fw,{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)(Yo,{}),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)(Lr,{}),children:`Experiments documentation`})]}),variant:`fill`}),Mai=e=>`${e} experiment${e===1?``:`s`}`;function Nai({experimentIds:e,onDeleted:t}){let[n,r]=(0,G.useState)(!1),[i,a]=(0,G.useState)(!1),{deleteExperiment:o}=BP(),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)(sP,{open:n,onOpenChange:r,children:(0,K.jsxs)(sP.Content,{children:[(0,K.jsxs)(sP.Header,{children:[(0,K.jsxs)(sP.Title,{children:[`Delete `,Mai(s)]}),(0,K.jsxs)(sP.Description,{children:[s===1?`Its`:`Their`,` results and traces will be deleted too. This can't be undone.`]})]}),(0,K.jsxs)(sP.Footer,{children:[(0,K.jsx)(sP.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?yw.error(`Failed to delete ${i} of ${Mai(s)}`):(yw.success(`Deleted ${Mai(s)}`),r(!1),t())},disabled:i,children:i?`Deleting…`:s===1?`Delete experiment`:`Delete experiments`})]})]})})]})}function Pai({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)(Bc,{}),onClick:t,tooltip:a?void 0:`Clear selection`,className:`mr-2 tabular-nums`,children:[i,` selected`]}),(0,K.jsx)(Nai,{experimentIds:e,onDeleted:t}),r?(0,K.jsxs)(JC,{children:[(0,K.jsx)(YC,{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)(Mi,{}),children:`Compare`})}),(0,K.jsx)(XC,{children:r})]}):(0,K.jsx)(X,{size:`sm`,onClick:n,icon:(0,K.jsx)(Mi,{}),children:`Compare`})]})}function Fai({dataset:e}){return(0,K.jsx)(U,{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)(U,{as:`span`,variant:`body-sm`,tone:`ink`,title:e.id,children:e.name})]}):`Select an experiment to pick the dataset to compare`})}var Iai=`search`,Lai=`status`,Rai=`dataset`,R7=`all`,zai=[{id:`contains`,label:`contains`},{id:`is`,label:`is`}],Bai=kai.filter(e=>e.value!==R7),Vai=({search:e,statusFilter:t,datasetFilter:n,targetType:r,targetId:i})=>{let a=[];return e&&a.push(X5(Iai,e,`contains`)),a.push(...r9r({targetType:r,targetId:i})),t!==R7&&a.push(X5(Lai,t)),n!==R7&&a.push(X5(Rai,n)),a},Hai=e=>({...i9r(e),search:Z5(e,Iai),statusFilter:Z5(e,Lai)||R7,datasetFilter:Z5(e,Rai)||R7});function Uai({search:e,statusFilter:t,datasetFilter:n,targetType:r,targetId:i,datasetOptions:a,onChange:o}){let s=a9r(r),c=(0,G.useMemo)(()=>[{id:Iai,label:`Search`,icon:Ss,search:!0,operators:[`contains`]},...s,{id:Lai,label:`Status`,icon:Hn,color:pF(`orange`),operators:[`is`],strict:!0,suggestions:Bai},{id:Rai,label:`Dataset`,icon:Er,color:pF(`blue`),operators:[`is`],strict:!0,suggestions:a.filter(e=>e.value!==R7)}],[s,a]),l=(0,G.useMemo)(()=>Vai({search:e,statusFilter:t,datasetFilter:n,targetType:r,targetId:i}),[e,t,n,r,i]);return(0,K.jsxs)(W6,{fields:c,operators:zai,value:l,onValueChange:e=>o(Hai(e)),createItemId:e=>e,"aria-label":`Experiments filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(W6.Chips,{}),(0,K.jsx)(W6.Input,{placeholder:`Filter experiments…`})]})}function Wai({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)(iq,{children:(0,K.jsx)(iq.Start,{children:(0,K.jsx)(Uai,{search:e,statusFilter:t,datasetFilter:n,datasetOptions:r,targetType:i,targetId:a,onChange:o})})}),(0,K.jsxs)(iq,{children:[(0,K.jsx)(iq.Start,{className:`self-end`,children:(0,K.jsx)(Fai,{dataset:c})}),(0,K.jsx)(iq.End,{children:(0,K.jsx)(Pai,{...s})})]})]})}var Gai={present:!1,targetType:null,output:null,metadata:null,comment:null,error:null,startedAt:null,completedAt:null,scores:[]},Kai=e=>e?e instanceof Date?e.toISOString():e:null,qai=e=>{let t=new Map;for(let n of e??[])t.set(n.itemId,n);return t},Jai=(e,t,n,r)=>{if(!e)return Gai;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:Kai(t?.startedAt),completedAt:Kai(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}},Yai=(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 z7(e){return!e.startedAt||!e.completedAt?null:new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime()}function Xai(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 Zai=(e,t)=>{let n=Xai(e),r=Xai(t);return n!=null&&r!=null?r-n:void 0},Qai=(e,t)=>{let n=z7(e),r=z7(t);return n!=null&&r!=null?r-n:null},$ai=(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},eoi=(e,t)=>{let n=w7(e.usage),r=w7(t.usage);return n!==void 0&&r!==void 0?r-n:void 0},toi=({comparison:e,experimentIds:t,resultsById:n,scoresById:r,usageById:i})=>{if(!e)return[];let a=new Map(t.map(e=>[e,qai(n?.[e])]));return e.items.map(e=>{let n=t.map(t=>Jai(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:Yai(o,e),durationDeltaMs:n===0?null:Qai(o,e),costDelta:n===0?void 0:$ai(o,e),tokenDelta:n===0?void 0:eoi(o,e),averageScoreDelta:n===0?void 0:Zai(o,e)}))}})};function noi({datasetId:e,itemId:t,onClose:n}){let{data:r,isLoading:i}=lNt({datasetId:e,itemId:t??``,queryOptions:{enabled:!!e&&!!t}});return(0,K.jsx)(kii,{datasetId:e,item:r,itemId:t,fallback:i?(0,K.jsx)(zZ.LoadingData,{}):(0,K.jsxs)(zZ.NoData,{children:[`Dataset item "`,t,`" not found.`]}),items:r?[r]:[],onItemChange:()=>{},onClose:n})}function roi({label:e,value:t,expanded:n,onExpandedChange:r}){return t==null?null:(0,K.jsx)(_7,{title:e,framed:!0,expanded:n,onExpandedChange:r,children:(0,K.jsx)(h7,{value:t})})}function ioi({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)(hr,{}),label:`Cost`,value:S7(e?.estimatedCost,c),rawValue:e?.estimatedCost,delta:r??null,formatDelta:oii(c),higherIsBetter:!1}]:[],u=t?[{id:`tokens`,icon:(0,K.jsx)(Ki,{}),label:`Tokens`,value:C7(w7(e)),rawValue:w7(e),delta:i??null,formatDelta:C7,higherIsBetter:!1}]:[],d=n==null?[]:[{id:`duration`,icon:(0,K.jsx)(cr,{}),label:`Duration`,value:lT(n)??`-`,rawValue:n,delta:a??null,formatDelta:nii,higherIsBetter:!1}],f=o?[{id:`avg-score`,icon:(0,K.jsx)(Ei,{}),label:`Avg score`,value:x7(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)(aF,{}),label:e.label??(0,K.jsx)(kni,{scorerId:e.scorerId}),value:e.reason?.trim()?(0,K.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[x7(e.value),(0,K.jsx)(cii,{scorerId:e.scorerId,reason:e.reason})]}):x7(e.value),rawValue:e.value,delta:e.delta??null}))]}function aoi({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 ooi(e){return(0,G.useSyncExternalStore)(e.subscribe,e.read,()=>e.defaultValue)}var soi={cost:`cost`,"total-cost":`cost`,duration:`duration`,"avg-duration":`duration`,"avg-score":`average`,tokens:`tokens`,"total-tokens":`tokens`,errors:`errors`};function coi(e){return e.startsWith(`scorer:`)?e:soi[e]}var loi=[],uoi=aoi({key:`mastra:experiments-compare:hidden-metrics`,defaultValue:loi,parse:e=>Qp(q()).parse(e)});function doi(){let e=ooi(uoi);return{isHidden:t=>e.includes(t),isMetricVisible:t=>{let n=coi(t);return n===void 0||!e.includes(n)},toggle:t=>uoi.write(e.includes(t)?e.filter(e=>e!==t):[...e,t]),reset:()=>uoi.write(loi)}}function foi(e){return e==null?`-`:typeof e==`string`?e:JSON.stringify(e,null,2)}function poi(e,t){return ioi({usage:e.usage,showUsage:t,durationMs:z7(e),costDelta:e.costDelta,tokenDelta:e.tokenDelta,durationDeltaMs:e.durationDeltaMs,averageScore:e.scores.length>0?{value:Xai(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 moi({column:e,isLoading:t,showUsage:n=!1,outputExpanded:r,onOutputExpandedChange:i,onShowTrace:a}){let{isMetricVisible:o}=doi();if(t)return(0,K.jsx)(`div`,{className:`flex h-32 items-center justify-center`,children:(0,K.jsx)($c,{})});if(!e.present)return(0,K.jsx)(U,{tone:`muted`,className:`py-5 text-center`,children:`Not present in this experiment`});let s=foi(e.output),c=y7(e),l=b7(e),u=eii(e),d=tii(e),f=poi(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)(sF,{})}):void 0,h=f.length>0,g=e=>(0,K.jsxs)(K.Fragment,{children:[!h&&m,(0,K.jsx)(fT,{content:e,variant:`ghost`})]});return(0,K.jsxs)(`div`,{className:g7,children:[h&&(0,K.jsx)(_7,{title:`Metrics`,collapsible:!1,actions:m,children:(0,K.jsx)(m7,{metrics:f})}),l?(0,K.jsx)(_7,{title:`Error`,tone:`negative`,framed:!0,actions:g(l),children:(0,K.jsx)(U,{tone:`muted`,className:`p-3 break-words`,children:l})}):(0,K.jsx)(_7,{title:`Output`,framed:!0,actions:g(s),expanded:r,onExpandedChange:i,children:d?(0,K.jsx)(U,{tone:`muted`,className:`p-3 break-words`,children:d}):(0,K.jsx)(h7,{value:c??e.output})}),u.length>0&&(0,K.jsx)(_7,{title:`Tool calls (${u.length})`,children:(0,K.jsx)(VZr,{toolCalls:u})}),e.comment&&(0,K.jsx)(_7,{title:`Comment`,framed:!0,children:(0,K.jsx)(h7,{value:e.comment})}),e.metadata&&Object.keys(e.metadata).length>0&&(0,K.jsx)(_7,{title:`Metadata`,framed:!0,actions:(0,K.jsx)(fT,{content:foi(e.metadata),variant:`ghost`}),children:(0,K.jsx)(h7,{value:e.metadata})})]})}function hoi({experiment:e,open:t,onOpenChange:n}){let[r,i]=(0,G.useState)(e.name??``),[a,o]=(0,G.useState)(e.description??``),{updateExperiment:s}=BP(),c=!!r.trim();return(0,K.jsx)(UE,{open:t,onOpenChange:n,pending:s.isPending,children:(0,K.jsxs)(WE,{children:[(0,K.jsx)(GE,{children:(0,K.jsx)(JE,{children:`Rename Experiment`})}),(0,K.jsxs)(lU,{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()}),yw.success(`Experiment renamed`),n(!1)}catch(e){yw.error(`Failed to rename experiment: ${e instanceof Error?e.message:`Unknown error`}`)}},children:[(0,K.jsxs)(qE,{children:[(0,K.jsxs)(OA,{children:[(0,K.jsx)(AA,{required:!0,children:`Name`}),(0,K.jsx)(lN,{required:!0,value:r,onChange:e=>i(e.target.value),placeholder:`Enter experiment name`,autoFocus:!0})]}),(0,K.jsxs)(OA,{children:[(0,K.jsx)(AA,{children:`Description`}),(0,K.jsx)(lN,{value:a,onChange:e=>o(e.target.value),placeholder:`Enter experiment description (optional)`})]})]}),(0,K.jsxs)(KE,{children:[(0,K.jsx)(XE,{children:`Cancel`}),(0,K.jsx)(HE,{type:`submit`,disabled:!c,children:s.isPending?`Saving...`:`Save`})]})]})]})})}function goi({datasetId:e,version:t,differsFromBaseline:n}){let{Link:r,paths:i}=gl();return(0,K.jsxs)(`span`,{className:H(`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 _oi({role:e,label:t,experiment:n,onSetBaseline:r}){let{Link:i}=gl(),[a,o]=(0,G.useState)(!1),s=n?mU(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)(gE,{children:[(0,K.jsx)(gE.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)(ut,{"aria-hidden":!0})]})}),(0,K.jsxs)(gE.Content,{align:`start`,className:`min-w-48`,children:[(0,K.jsxs)(gE.Item,{render:(0,K.jsx)(i,{href:`/experiments/${n.id}`}),children:[(0,K.jsx)(la,{}),` View experiment`]}),c&&(0,K.jsxs)(gE.Item,{onSelect:()=>o(!0),children:[(0,K.jsx)(Io,{}),` Rename experiment`]})]})]}),n&&a&&(0,K.jsx)(hoi,{experiment:n,open:!0,onOpenChange:o}),(0,K.jsx)(`div`,{className:`ml-auto shrink-0`,children:r?(0,K.jsxs)(JC,{children:[(0,K.jsx)(YC,{render:(0,K.jsx)(`button`,{type:`button`,"aria-label":`Set as baseline`,onClick:r,className:H(`cursor-pointer rounded-[7px] hover:brightness-110`,vt)}),children:(0,K.jsx)(hT,{variant:N7[e],size:`md`,icon:(0,K.jsx)(Xs,{}),children:t})}),(0,K.jsx)(XC,{children:`Set as baseline`})]}):(0,K.jsx)(hT,{variant:N7[e],size:`md`,icon:e===`baseline`?(0,K.jsx)(Xs,{className:`fill-current`}):(0,K.jsx)(Xs,{}),children:t})})]})}function voi({role:e,experiment:t,summary:n,metrics:r,baselineMetrics:i,versionMismatch:a,showUsage:o=!1}){let{Link:s,paths:c}=gl(),{isMetricVisible:l}=doi(),u=t?.createdAt?new Date(t.createdAt):null,d=e===`contender`,f=(e,t)=>d?rii(e,t):null,p=t?[...t.targetId?[{id:`target`,icon:t.targetType===`agent`?(0,K.jsx)(nF,{}):(0,K.jsx)(ac,{}),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)(fs,{}),label:`Dataset version`,value:(0,K.jsx)(goi,{datasetId:t.datasetId,version:t.datasetVersion,differsFromBaseline:a}),delta:null}]:[],...u?[{id:`created-at`,icon:(0,K.jsx)(Mn,{}),label:`Created`,value:xT(u,`date`),delta:null}]:[]]:[],m=o?r:void 0,h=[...m?[{id:`total-cost`,icon:(0,K.jsx)(hr,{}),label:`Total cost`,value:S7(m.cost,m.costUnit),rawValue:m.cost,delta:m.costUnit===i?.costUnit?f(m.cost,i?.cost):null,formatDelta:oii(m.costUnit),higherIsBetter:!1,emphasis:!0}]:[],...r?[{id:`avg-duration`,icon:(0,K.jsx)(cr,{}),label:`Avg duration`,value:lT(r.averageDurationMs)??`-`,rawValue:r.averageDurationMs,delta:f(r.averageDurationMs,i?.averageDurationMs),formatDelta:nii,higherIsBetter:!1,emphasis:!0}]:[],...r&&n&&n.length>0?[{id:`avg-score`,icon:(0,K.jsx)(Ei,{}),label:`Avg score`,value:x7(r.averageScore),rawValue:r.averageScore,delta:f(r.averageScore,i?.averageScore),emphasis:!0}]:[],...m?[{id:`total-tokens`,icon:(0,K.jsx)(Ki,{}),label:`Total tokens`,value:C7(m.tokens),rawValue:m.tokens,delta:f(m.tokens,i?.tokens),formatDelta:C7,higherIsBetter:!1}]:[],...p,...r?[{id:`errors`,icon:(0,K.jsx)(Vn,{}),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)(aF,{}),label:(0,K.jsx)(kni,{scorerId:e}),value:x7(t),rawValue:t,delta:d?n:null}))].filter(e=>l(e.id));return h.length===0?null:(0,K.jsx)(_7,{title:`Summary`,collapsible:!1,children:(0,K.jsx)(m7,{metrics:h})})}function yoi(e){return(0,K.jsx)(b0r,{...e,headerActionsSlot:e.traceId?(0,K.jsx)(A3r,{traceId:e.traceId,spans:e.spans},e.traceId):void 0})}function boi({traceId:e,onClose:t,withQueryTrace:n,withFeedback:r}){let{navigate:i}=gl(),[a,o]=(0,G.useState)(),{data:s,isLoading:c}=Iri({traceId:e,queryOptions:{enabled:!!e}}),l=s?.spans,u=l?.find(e=>!e.parentSpanId),{data:d}=T3({traceId:e,queryOptions:{enabled:r&&!!e}}),{data:f}=w3({traceId:e,spanId:a,queryOptions:{enabled:r&&!!e&&!!a}}),{data:p}=eF({traceId:e,spanId:u?.spanId,page:0,queryOptions:{enabled:!!e&&!!u?.spanId}});return(0,K.jsx)(yoi,{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(nq(e,t)),feedbackTabBadge:r?d?.pagination?.total??void 0:void 0,feedbackTabSlot:r?({traceId:e})=>(0,K.jsx)(S8,{traceId:e}):void 0,scoresTabBadge:p?.pagination?.total??void 0,scoresTabSlot:({traceId:e,rootSpanId:t})=>t?(0,K.jsx)(ZEr,{traceId:e,spanId:t,onScoreSelect:t=>i(nq(e,t))}):null,spanFeedbackTabBadge:r?f?.pagination?.total??void 0:void 0,spanFeedbackTabSlot:r?({traceId:e,spanId:t})=>e&&t?(0,K.jsx)(PXr,{traceId:e,spanId:t},`${e}:${t}`):null:void 0})}var B7=`min-w-0 px-4 py-3`,xoi=`grid grid-cols-[minmax(22rem,26rem)_repeat(var(--compare-cols),minmax(32rem,1fr))] divide-x divide-border border-border`,Soi=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,Coi=()=>!!window.getSelection()?.toString(),woi=e=>e!=null,Toi=e=>e.length>0?e.reduce((e,t)=>e+t,0)/e.length:null,Eoi=(e,t,n)=>Toi(e.map(e=>e.sides[t]?.scores.find(e=>e.scorerId===n)?.value??null).filter(woi)),Doi=(e,t)=>{let n=e.map(e=>e.sides[t]).filter(e=>e?.present);return{errorCount:n.filter(e=>e.error).length,averageScore:Toi(n.flatMap(e=>e.scores.map(e=>e.value)).filter(woi)),averageDurationMs:Toi(n.map(z7).filter(woi))}};function Ooi({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=D6(),u=e=>{c(void 0),o(e)},d=e=>{o(void 0),c(e)},{data:f,isLoading:p,error:m}=hNt({datasetId:e,experimentIds:i,baselineId:t,queryOptions:{enabled:!!e&&!!t&&n.length>0}}),{data:h,isLoading:g}=SNt({datasetId:e,experimentIds:i}),_=(0,G.useMemo)(()=>i.map(e=>({id:e,status:h[e]?.status})),[i,h]),{data:v,isLoading:y}=wNt({datasetId:e,experiments:_}),{data:b}=TNt({experiments:_}),{supportsMetrics:x,isLoading:S}=v5(),{data:C,isLoading:w}=Pri({experiments:_,supportsMetrics:x}),T=(0,G.useMemo)(()=>toi({comparison:f,experimentIds:i,resultsById:v,scoresById:b,usageById:C}),[f,i,v,b,C]),E=(0,G.useMemo)(()=>{let e=[...new Set(T.flatMap(e=>e.sides.flatMap(e=>e.scores.map(e=>e.scorerId))))].sort();return i.map((t,n)=>e.map(e=>{let t=Eoi(T,n,e),r=Eoi(T,0,e);return{scorerId:e,average:t,delta:n>0&&t!=null&&r!=null?t-r:null}}))},[T,i]),D=(0,G.useMemo)(()=>i.map((e,t)=>{let n=C[e]?.summary;return{...Doi(T,t),cost:n?.estimatedCost,costUnit:n?.costUnit,tokens:w7(n)}}),[T,i,C]);if(p||g||S||w)return(0,K.jsx)(`div`,{className:`pointer-events-none fixed inset-0 flex items-center justify-center`,children:(0,K.jsx)($c,{})});if(m)return(0,K.jsx)(HA,{variant:`warning`,title:`Error loading comparison`,children:(0,K.jsx)(HA.Message,{children:m instanceof Error?m.message:`Unknown error`})});if(!f||f.items.length===0)return(0,K.jsx)(U,{as:`p`,variant:`body`,tone:`muted`,className:`py-5 text-center`,children:`No comparison data`});let O=h[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:H(xoi,`sticky top-0 z-20 bg-background`),children:[(0,K.jsx)(`div`,{role:`columnheader`,"aria-label":`Items`,className:B7}),i.map((e,t)=>(0,K.jsx)(`div`,{role:`columnheader`,"aria-label":P7(t),className:H(B7,`border-b`),children:(0,K.jsx)(_oi,{role:t===0?`baseline`:`contender`,label:P7(t),experiment:h[e]??void 0,onSetBaseline:t>0&&r?()=>r(e):void 0})},e))]}),(0,K.jsxs)(`div`,{role:`row`,"aria-label":`Summary`,className:H(xoi,`border-b`),children:[(0,K.jsx)(`div`,{role:`cell`,"aria-label":`Items`,className:B7}),i.map((e,t)=>{let n=h[e]??void 0;return(0,K.jsx)(`div`,{role:`cell`,"aria-label":P7(t),className:B7,children:(0,K.jsx)(voi,{role:t===0?`baseline`:`contender`,experiment:n,summary:E[t],metrics:y?void 0:D[t],baselineMetrics:y?void 0:D[0],versionMismatch:t>0&&n&&O?n?.datasetVersion!==O?.datasetVersion:void 0,showUsage:x})},e)})]}),T.map(e=>(0,K.jsx)(koi,{row:e,isLoading:y,showUsage:x,onOpen:()=>u(e.itemId),onShowTrace:d},e.itemId))]}),(0,K.jsx)(noi,{datasetId:e,itemId:a,onClose:()=>o(void 0)}),(0,K.jsx)(boi,{traceId:s,onClose:()=>c(void 0),withQueryTrace:l.enabled,withFeedback:l.enabled})]})}function koi({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=>{Soi(e)||Coi()||r()},onKeyDown:e=>{e.target!==e.currentTarget||e.key!==`Enter`&&e.key!==` `||(e.preventDefault(),r())},className:H(xoi,`cursor-pointer border-b transition-colors duration-normal ease-out-custom hover:bg-fill-subtle`,xt),children:[(0,K.jsxs)(`div`,{role:`cell`,className:H(B7,g7),children:[(0,K.jsx)(roi,{label:`Input`,value:e.input,...s(`input`)}),(0,K.jsx)(roi,{label:`Ground truth`,value:e.groundTruth,...s(`groundTruth`)})]}),e.sides.map((e,r)=>(0,K.jsx)(`div`,{role:`cell`,"aria-label":P7(r),className:B7,children:(0,K.jsx)(moi,{column:e,isLoading:t,showUsage:n,outputExpanded:c.expanded,onOutputExpandedChange:c.onExpandedChange,onShowTrace:i})},e.experimentId))]})}function Aoi(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 V7=[cF(`/experiments`)],joi=[`createdAt`,`status`],Moi=new Map;function Noi(){let[e,t]=(0,G.useState)(``),[n,r]=(0,G.useState)(`all`),[i,a]=(0,G.useState)(!1),[o,s]=(0,G.useState)([]),c=zb(),[l,u]=Qb(),{sort:d,onSortChange:f}=e5({searchParams:l,setSearchParams:u,allowedKeys:joi}),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}=h9r(),_=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($5,e.targetType),r(e7,e.targetType===h?e.targetId:``),n},{replace:!0})},{data:v,isLoading:y,error:b}=VP(),{data:x,isLoading:S,error:C,isFetchingNextPage:w,hasNextPage:T,setEndOfListElement:E}=Gri({datasetId:m===`all`?void 0:m,target:{targetType:h,targetId:g},orderBy:p}),{data:D}=eai(),{supportsMetrics:O}=v5(),k=(0,G.useMemo)(()=>v?.datasets??[],[v?.datasets]),A=(0,G.useMemo)(()=>x??[],[x]),j=(0,G.useMemo)(()=>Aai(k),[k]),{data:M}=mNt({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}=Wri({experiments:A,supportsMetrics:O}),F=O?P??Moi:void 0,I=(0,G.useMemo)(()=>Aoi(D),[D]),L=y||S,R=C||b,ee=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]})},z=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:B,selectedDatasetIds:V}=(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]),te=A.find(e=>e.id===B[0])?.datasetId??void 0,ne=te?{id:te,name:N.find(e=>e.id===te)?.name??te}:void 0,re=B.length<2?`Select at least two experiments to compare`:V.size===1?void 0:`Only experiments from the same dataset can be compared`,ie=()=>{if(B.length<2||re)return;let[e,...t]=B,[n]=V;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&&YP(R))return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:V7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(fU,{variant:`fill`})]});if(C&&XP(C))return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:V7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(dU,{variant:`fill`,resource:`experiments`})]});if(b&&XP(b))return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:V7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(dU,{variant:`fill`,resource:`datasets`})]});if(R)return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:V7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(fw,{tone:`error`,variant:`fill`,titleSlot:`Failed to load experiments`,descriptionSlot:R.message})]});let ae=(0,K.jsx)(v7,{open:i,onOpenChange:a,onSuccess:e=>void c(`/experiments/${e}`)});return A.length===0&&!L&&m===`all`&&!h?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:V7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(jai,{onRunExperiment:()=>a(!0)}),ae]}):(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:V7}),headerActions:(0,K.jsx)(X,{variant:`primary`,size:`sm`,icon:(0,K.jsx)(Yo,{}),onClick:()=>a(!0),children:`New experiment`}),actionRow:(0,K.jsx)(Wai,{search:e,statusFilter:n,datasetFilter:m,datasetOptions:j,targetType:h,targetId:g,onFiltersChange:_,selection:{selectedIds:B,onClearSelection:()=>s([]),onCompare:ie,compareDisabledReason:re},comparableDataset:ne}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(Oai,{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:B,onToggleSelection:ee,onToggleAll:z,comparableDatasetId:te}}),ae]})}var Poi={baseline:`bg-badge-purple-indicator`,contender:`bg-badge-blue-indicator`};function Foi({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:H(`max-w-48 min-w-0`,r),"aria-label":`Open experiment ${s}`,children:[n&&(0,K.jsx)(`span`,{"aria-hidden":`true`,className:H(`size-1.5 shrink-0 rounded-full`,Poi[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 H7(){let[e]=Qb(),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 Ioi(){let{datasetId:e,baselineId:t,contenderIds:n}=H7();return{datasetId:e,experimentIds:e&&t&&n.length>0&&t?[t,...n]:[]}}function Loi(){let{experimentIds:e}=Ioi();return e.length>0?`Comparing ${e.length} experiments`:`Comparing`}function Roi(){let{datasetId:e,experimentIds:t}=Ioi(),{data:n}=SNt({datasetId:e??``,experimentIds:t});return t.length===0?null:(0,K.jsxs)(YX,{children:[(0,K.jsx)(XX,{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)(ut,{})})}),(0,K.jsx)(ZX,{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)(Foi,{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)(hT,{variant:`purple`,size:`sm`,icon:(0,K.jsx)(Xs,{className:`fill-current`}),children:`Baseline`})})},e))})})]})}function zoi({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)(Foi,{experimentId:t}),n<e.length-2&&`,`]})]},t))}function Boi({datasetId:e,baselineId:t,contenderIds:n}){let[,r]=Qb(),i=(0,G.useMemo)(()=>[t,...n],[t,n]),{data:a,isLoading:o,error:s}=SNt({datasetId:e,experimentIds:i});return s&&YP(s)?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(U,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Compare`}),(0,K.jsx)(fU,{variant:`fill`})]}):s&&XP(s)?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(U,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Compare`}),(0,K.jsx)(dU,{variant:`fill`,resource:`experiments`})]}):s&&!ZP(s)?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(U,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Compare`}),(0,K.jsx)(fw,{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)(U,{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)(U,{as:`p`,children:[`Experiments must belong to the same dataset (`,e,`) to be compared.`]}),(0,K.jsxs)(U,{className:`mt-2 flex items-center justify-center gap-2`,children:[`One of`,(0,K.jsx)(zoi,{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)(U,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Experiments comparison`}),(0,K.jsx)(Ooi,{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 Voi(){let{datasetId:e,baselineId:t,contenderIds:n}=H7();return!e||!t||n.length===0?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(U,{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)(U,{as:`p`,children:`Select two to ten experiments to compare.`}),(0,K.jsxs)(U,{className:`mt-2`,children:[`Use the URL format: /experiments/compare?dataset=`,`{datasetId}`,`&baseline=`,`{experimentId}`,`&contender=`,`{experimentId}`,`&contender=`,`{experimentId}`]})]})})]}):(0,K.jsx)(Boi,{datasetId:e,baselineId:t,contenderIds:n})}function Hoi(){let{datasetId:e}=H7(),{Link:t,paths:n}=gl(),{data:r,isLoading:i}=HP({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:H(`flex max-w-64 min-w-0 rounded-[7px] hover:brightness-110`,vt),children:(0,K.jsx)(hT,{size:`md`,icon:(0,K.jsx)(Er,{}),className:`max-w-full min-w-0`,children:(0,K.jsx)(`span`,{className:`min-w-0 truncate`,children:a})})})}var Uoi=[{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 Woi({datasetId:e,baselineId:t,contenderIds:n}){let{data:r}=hNt({datasetId:e,experimentIds:(0,G.useMemo)(()=>[t,...n],[t,n]),baselineId:t}),{supportsMetrics:i}=v5(),{isHidden:a,toggle:o,reset:s}=doi(),c=(0,G.useMemo)(()=>[...new Set((r?.items??[]).flatMap(e=>Object.values(e.results).flatMap(e=>e?Object.keys(e.scores):[])))].sort(),[r]),l=Uoi.filter(e=>i||!e.usage);return(0,K.jsxs)(gE,{children:[(0,K.jsx)(gE.Trigger,{render:(0,K.jsx)(X,{variant:`ghost`,size:`md`,icon:(0,K.jsx)(_r,{"aria-hidden":!0}),children:`Metrics`})}),(0,K.jsxs)(gE.Content,{align:`end`,className:`min-w-56`,children:[(0,K.jsx)(gE.Label,{children:`Run metrics`}),l.map(e=>(0,K.jsx)(gE.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)(gE.Separator,{}),(0,K.jsx)(gE.Label,{children:`Scorers`}),c.map(e=>{let t=`scorer:${e}`;return(0,K.jsx)(gE.CheckboxItem,{checked:!a(t),onCheckedChange:()=>o(t),children:e},t)})]}),(0,K.jsx)(gE.Separator,{}),(0,K.jsx)(gE.Item,{onSelect:s,children:`Show all metrics`})]})]})}function Goi(){let{datasetId:e,baselineId:t,contenderIds:n}=H7();return(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[e&&t&&n.length>0&&(0,K.jsx)(Woi,{datasetId:e,baselineId:t,contenderIds:n}),(0,K.jsx)(Hoi,{})]})}var Koi=[cF(`/experiments`),{id:`experiments-compare`,Component:Loi,Switcher:Roi}];function qoi(){return(0,K.jsx)(Jw,{variant:`fit`,breadcrumbs:(0,K.jsx)(DP,{crumbs:Koi}),headerActions:(0,K.jsx)(Goi,{}),children:(0,K.jsx)(Voi,{})})}function Joi(e){let{data:t}=GP({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 Yoi=[`agent`,`workflow`,`scorer`];function Xoi({experiment:e}){let[t,n]=(0,G.useState)(!1),r=zb(),{paths:i}=gl(),a=Joi(e),o=Yoi.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)(Go,{}),children:`Rerun`}),t&&(0,K.jsx)(v7,{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 Zoi({experiment:e,onDeleteClick:t}){let[n,r]=(0,G.useState)(!1),i=!!e.datasetId;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Xoi,{experiment:e}),(i||!!t)&&(0,K.jsxs)(gE,{children:[(0,K.jsx)(gE.Trigger,{asChild:!0,children:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,"aria-label":`Experiment actions menu`,children:(0,K.jsx)(jr,{})})}),(0,K.jsxs)(gE.Content,{align:`end`,className:`w-48`,children:[i&&(0,K.jsxs)(gE.Item,{onSelect:()=>r(!0),children:[(0,K.jsx)(Io,{}),` Rename experiment`]}),t&&(0,K.jsxs)(gE.Item,{onSelect:t,variant:`destructive`,children:[(0,K.jsx)(xc,{}),` Delete experiment`]})]})]}),n&&(0,K.jsx)(hoi,{experiment:e,open:!0,onOpenChange:r})]})}function Qoi(e){let{data:t,isLoading:n}=S3({traceId:e,queryOptions:{enabled:!!e}}),r=t?.spans.find(e=>!e.parentSpanId)?.entityType===`agent`,{supportsMetrics:i,isLoading:a}=v5(),o=r&&i,s=tzr({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 $oi=`__create_tag__`;function esi({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)(Ln,{"data-testid":`tag-applied`,className:`size-3.5`}):void 0})),t=a.trim();return t.length>0&&!s.includes(t)?[{label:`Create "${t}"`,value:$oi},...e]:e},[s,c,a]);return(0,K.jsx)(EP,{"data-testid":`experiment-results-tag-picker`,options:l,value:void 0,onValueChange:e=>{let t=e===$oi?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 tsi(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function nsi({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)(zZ.SectionHeading,{icon:(0,K.jsx)(Rc,{}),children:`Tool Mocks`}),i&&(0,K.jsx)(HA,{variant:`destructive`,title:`Mock mismatch`,children:(0,K.jsxs)(HA.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)(U,{as:`span`,variant:`caption`,className:`mt-1 block`,children:[`Called with: `,(0,K.jsx)(FY,{children:tsi(i.args)})]}),n.length>0&&(0,K.jsxs)(U,{as:`span`,variant:`caption`,className:`mt-1 block`,children:[`Unconsumed mocks: `,(0,K.jsx)(FY,{children:n.map(e=>tsi(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)(U,{as:`span`,variant:`body`,className:`min-w-0 truncate`,children:[(0,K.jsx)(U,{as:`span`,variant:`body-sm`,tone:`muted`,font:`mono`,children:e.toolName}),(0,K.jsx)(U,{as:`span`,variant:`caption`,tone:`muted`,font:`mono`,className:`ml-2`,children:tsi(e.args)})]}),(0,K.jsx)(U,{as:`span`,variant:`caption`,className:`shrink-0 rounded px-2 py-0.5 ${rsi(e.outcome)}`,children:e.outcome})]},`${e.outcome}-${e.toolName}-${t}`))})]})}function rsi(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 isi({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)(asi,{result:e,onClose:i,...o}):t?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(zZ.Header,{children:[(0,K.jsxs)(zZ.Heading,{children:[`Experiment item`,(0,K.jsx)(zZ.CopyId,{id:t})]}),(0,K.jsx)(zZ.HeaderActions,{children:(0,K.jsx)(zZ.CloseButton,{icon:`x`,onClick:i})})]}),n]}):null;return a===`inline`?c?(0,K.jsx)(zZ,{variant:`inline`,title:s,children:c}):null:(0,K.jsx)(zZ,{open:!!(e??t),onClose:i,title:s,depth:1,children:c})}function asi({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=csi(e.input),g=csi(e.output),_=y7(e),v=eii(e),y=tii(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(),T=m&&e.traceId?e.traceId:void 0,{data:E}=T3({traceId:T,queryOptions:{enabled:!!T}}),{usage:D,isLoading:O}=Qoi(e.traceId),k=O&&(e.targetType==null||e.targetType===`agent`),A=ioi({usage:D,showUsage:!!D||k,durationMs:z7(e),scores:[]}).map(e=>k&&(e.id===`cost`||e.id===`tokens`)?{...e,value:(0,K.jsx)(Yw,{"aria-hidden":!0,className:`h-4 w-14`})}:e),j=typeof e.error==`string`&&e.error?e.error:b7(e),M=[...A,{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:mU(e.itemId)}),(0,K.jsx)(fT,{content:e.itemId,tooltip:`Copy item ID to clipboard`,variant:`link`})]}),delta:null},...e.createdAt?[{id:`created`,icon:(0,K.jsx)(Mn,{}),label:`Created`,value:xT(e.createdAt,`date-time`),delta:null}]:[],...e.status?[{id:`status`,icon:(0,K.jsx)(hee,{}),label:`Status`,value:(0,K.jsx)(nXr,{status:e.status}),delta:null}]:[],...C?[{id:`tags`,icon:(0,K.jsx)(nc,{}),label:`Tags`,value:(0,K.jsx)(ssi,{tags:x,selectedResults:S,onTagsChange:l,tagVocabulary:u,isUpdatingTags:d}),delta:null}]:[],...ioi({showUsage:!1,durationMs:null,scores:(t??[]).map(e=>({scorerId:e.scorerId,value:e.score,reason:e.reason,label:o?(0,K.jsx)(osi,{scorerId:e.scorerId,featured:s===e.id,onClick:()=>o(e.id)}):void 0}))})],N=(0,K.jsx)(zZ.Content,{children:(0,K.jsxs)(`div`,{className:g7,children:[(0,K.jsx)(m7,{metrics:M}),(0,K.jsx)(_7,{title:`Input`,framed:!0,actions:(0,K.jsx)(fT,{content:h}),children:(0,K.jsx)(h7,{value:e.input})}),e.groundTruth!=null&&(0,K.jsx)(_7,{title:`Ground Truth`,framed:!0,actions:(0,K.jsx)(fT,{content:csi(e.groundTruth)}),children:(0,K.jsx)(h7,{value:e.groundTruth})}),j?(0,K.jsx)(_7,{title:`Error`,tone:`negative`,framed:!0,actions:(0,K.jsx)(fT,{content:j}),children:(0,K.jsx)(U,{tone:`muted`,className:`p-3 break-words`,children:j})}):(0,K.jsx)(_7,{title:`Output`,framed:!0,actions:(0,K.jsx)(fT,{content:g}),children:y?(0,K.jsx)(U,{tone:`muted`,className:`p-3 break-words`,children:y}):(0,K.jsx)(h7,{value:_??e.output})}),v.length>0&&(0,K.jsx)(_7,{title:`Tool calls (${v.length})`,children:(0,K.jsx)(VZr,{toolCalls:v})}),e.toolMockReport&&(0,K.jsx)(nsi,{report:e.toolMockReport})]})});return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(zZ.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)(Hn,{}),children:`Mark as reviewed`}),(0,K.jsxs)(zZ.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)(sF,{})}),(0,K.jsx)(zZ.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:`Go to previous result`,nextLabel:`Go to next result`}),(0,K.jsx)(zZ.CloseButton,{icon:`x`,onClick:i})]})]}),T?(0,K.jsxs)(zA,{defaultTab:`details`,className:`grid h-full min-h-0 grid-rows-[auto_1fr]`,children:[(0,K.jsx)(zZ.Header,{children:(0,K.jsxs)(RA,{variant:`pill-ghost`,size:`sm`,children:[(0,K.jsx)(BA,{value:`details`,children:`Details`}),(0,K.jsxs)(BA,{value:`feedback`,children:[`Feedback`,E?.pagination?.total!=null&&(0,K.jsxs)(K.Fragment,{children:[` (`,E.pagination.total,`)`]})]})]})}),(0,K.jsx)(VA,{value:`details`,flush:!0,children:N}),(0,K.jsx)(VA,{value:`feedback`,flush:!0,children:(0,K.jsx)(zZ.Content,{children:m({traceId:T})})})]}):N]})}function osi({scorerId:e,featured:t,onClick:n}){return(0,K.jsx)(`button`,{type:`button`,"aria-pressed":t,onClick:n,className:H(`min-w-0 cursor-pointer truncate hover:text-foreground hover:underline`,t&&`text-foreground`),children:e})}function ssi({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)(Y5,{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)(Bc,{className:`size-3`})})]},t)),n&&(0,K.jsx)(esi,{selectedResults:t,vocabulary:r,onAddTag:t=>n([...e,t]),disabled:i,variant:`ghost`})]})}function csi(e){return e==null?`-`:typeof e==`string`?e:JSON.stringify(e,null,2)}function lsi(e){let t=e.scorer;return t?.hasJudge===!1||t?.hasJudge!==!0&&!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function usi({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:i}){return(0,K.jsx)(zZ,{open:!!e,onClose:r,title:e?`Score ${e.scorerId}`:`Score`,depth:2,children:e&&(0,K.jsx)(dsi,{score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:i})})}function dsi({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:i}){let a=lsi(e),o=a?`N/A — code-based scorer`:`N/A — step not configured`;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(zZ.Header,{children:[(0,K.jsx)(zZ.CloseButton,{onClick:r,tooltip:`Close score panel`}),(0,K.jsxs)(zZ.Heading,{children:[`Score`,(0,K.jsx)(zZ.CopyId,{id:e.scorerId})]}),(0,K.jsxs)(zZ.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)(sF,{})}),(n||t)&&(0,K.jsx)(zZ.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:`Go to previous score`,nextLabel:`Go to next score`})]})]}),(0,K.jsx)(zZ.Content,{children:(0,K.jsxs)(`div`,{className:`grid gap-3`,children:[(0,K.jsx)(zZ.CodeSection,{title:`Score: ${e.score}`,icon:(0,K.jsx)(Ei,{}),codeStr:e.reason||o,simplified:!0}),!a&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(zZ.CodeSection,{title:`Preprocess Prompt`,icon:(0,K.jsx)($o,{}),codeStr:e.preprocessPrompt||o,simplified:!0}),(0,K.jsx)(zZ.CodeSection,{title:`Analyze Prompt`,icon:(0,K.jsx)($o,{}),codeStr:e.analyzePrompt||o,simplified:!0}),(0,K.jsx)(zZ.CodeSection,{title:`Generate Score Prompt`,icon:(0,K.jsx)($o,{}),codeStr:e.generateScorePrompt||o,simplified:!0}),(0,K.jsx)(zZ.CodeSection,{title:`Generate Reason Prompt`,icon:(0,K.jsx)($o,{}),codeStr:e.generateReasonPrompt||o,simplified:!0})]})]})})]})}function fsi(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 psi({result:e,scores:t,state:n,withQueryTrace:r,withFeedback:i,...a}){let o=fsi(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}=Iri({traceId:c,queryOptions:{enabled:!!c}}),x=y?.spans,S=x?.find(e=>!e.parentSpanId),{data:C}=T3({traceId:c??void 0,queryOptions:{enabled:i&&!!c}}),{data:w}=w3({traceId:c??void 0,spanId:u,queryOptions:{enabled:i&&!!c&&!!u}}),{data:T}=eF({traceId:c??void 0,spanId:S?.spanId,page:0,queryOptions:{enabled:!!c&&!!S?.spanId}});return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(isi,{...a,result:e,scores:t,onScoreClick:h,featuredScoreId:f,onShowTrace:e?.traceId?()=>g(e.traceId):void 0,feedbackTabSlot:i?({traceId:e})=>(0,K.jsx)(S8,{traceId:e},e):void 0}),(0,K.jsx)(usi,{score:m??void 0,onNext:_(),onPrevious:v(),onClose:()=>p(null),onShowTrace:m?()=>g(m.traceId):void 0}),(0,K.jsx)(yoi,{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(nq(e,t)),feedbackTabBadge:i?C?.pagination?.total??void 0:void 0,feedbackTabSlot:i?({traceId:e})=>(0,K.jsx)(S8,{traceId:e}):void 0,scoresTabBadge:T?.pagination?.total??void 0,scoresTabSlot:({traceId:e,rootSpanId:n})=>n?(0,K.jsx)(ZEr,{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)(PXr,{traceId:e,spanId:t},`${e}:${t}`):null:void 0})]})}function msi({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}=Jri(),p=(0,G.useMemo)(()=>r?s.find(e=>e.itemId===r):void 0,[s,r]),{data:m}=GP({experimentId:i,experimentStatus:o,queryOptions:{enabled:!!i}}),{updateExperimentResult:h}=BP(),g=(0,G.useCallback)(async e=>{try{await h.mutateAsync({datasetId:a,experimentId:i,resultId:e,status:`needs-review`}),yw(`Result flagged for review`)}catch{yw.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`}),yw(`Result marked as reviewed`)}catch{yw.error(`Failed to complete result`)}},[a,i,h]),v=p?m?.[p.itemId]:void 0,y=fsi(v,p?.id);return(0,K.jsx)(psi,{variant:n,result:p,itemId:r,fallback:c||l?(0,K.jsx)(zZ.LoadingData,{}):(0,K.jsxs)(zZ.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 hsi(e){let{currentItemId:t,close:n}=Jri(),r=RE();return Fii(t,n),r?(0,K.jsx)(msi,{...e}):t?(0,K.jsx)(O7,{owner:`experiment-item`,children:(0,K.jsx)(msi,{...e,variant:`inline`})}):null}function gsi({children:e,className:t}){return(0,K.jsx)(`div`,{className:`@container`,children:(0,K.jsx)(`div`,{className:H(`grid gap-4 *:min-w-0! @xl:grid-cols-2 @3xl:has-[>:nth-child(5)]:grid-cols-3 @4xl:grid-cols-[repeat(auto-fit,minmax(12rem,1fr))] @6xl:has-[>:nth-child(5)]:grid-cols-[repeat(auto-fit,minmax(12rem,1fr))]!`,t),children:e})})}var _si={first:0,normal:1,last:2},vsi=class extends Error{constructor(){super(`Skipped: nothing is waiting for this request any more`),this.name=`SkippedRequestError`}};function ysi(e){let t=0,n=[],r=()=>{t<e&&n.shift()?.start()};return{run(i,{priority:a=_si.normal,isWanted:o}={}){return new Promise((s,c)=>{let l=e=>{e&&o&&!o()?(c(new vsi),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 bsi=(0,G.createContext)(void 0);function xsi(){let e=(0,G.use)(bsi);if(!e)throw Error(`useAggregateLimiter must be used inside MetricsProvider or AggregateLimiterProvider`);return e}function Ssi(e,t){let n=xsi(),r=xy();return({queryKey:i})=>n.run(e,{priority:t,isWanted:()=>(r.getQueryCache().find({queryKey:i,exact:!0})?.getObserversCount()??0)>0})}function Csi({children:e}){let t=(0,G.use)(bsi),[n]=(0,G.useState)(()=>t?void 0:ysi(3));return(0,K.jsx)(bsi,{value:t??n,children:e})}function U7({label:e,icon:t,isError:n=!1,...r}){return(0,K.jsxs)(C2,{busy:!n&&(r.isLoading||r.isUpdating),children:[(0,K.jsx)(C2.Label,{icon:(0,K.jsx)(t,{}),children:e}),n?(0,K.jsx)(wsi,{}):(0,K.jsx)(Tsi,{...r})]})}function wsi(){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(C2.ValueRow,{className:`mt-1`,children:(0,K.jsx)(C2.Value,{children:`—`})}),(0,K.jsx)(C2.Footer,{detail:(0,K.jsx)(`span`,{className:`text-destructive-foreground`,children:`Couldn't load`})})]})}function Tsi({value:e,change:t,lowerIsBetter:n,detail:r,previous:i,comparison:a,isLoading:o=!1,isUpdating:s=!1}){let c=H(`transition-opacity duration-200`,s&&`opacity-50`);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(C2.ValueRow,{className:H(`mt-1`,c),isLoading:o,children:[(0,K.jsx)(C2.Value,{children:e}),t!==void 0&&(0,K.jsx)(C2.Change,{changePct:t,comparison:a,lowerIsBetter:n,prevValue:i})]}),(0,K.jsx)(C2.Footer,{detail:r,prevValue:t===void 0?void 0:i,isLoading:o,className:c})]})}function Esi({children:e,reveal:t=`always`,className:n}){return(0,K.jsx)(`div`,{className:H(`-my-1 flex shrink-0 items-center gap-1 self-start`,t===`hover`&&`opacity-0 transition-opacity duration-150 group-hover/metrics-card:opacity-100 focus-within:opacity-100`,n),children:e})}function Dsi({children:e,className:t}){return(0,K.jsx)(`div`,{className:H(`overflow-x-auto overflow-y-hidden [&_tbody>tr:last-child]:border-b-0`,t),children:e})}function Osi({message:e=`Failed to load data`,className:t}){return(0,K.jsx)(`div`,{className:H(`flex flex-col items-center justify-center gap-3`,t),children:(0,K.jsx)(U,{variant:`caption`,className:`text-destructive-foreground`,children:e})})}function ksi({label:e,value:t,change:n,isLoading:r=!1,className:i}){return(0,K.jsxs)(`div`,{className:H(`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:`text-title text-foreground tabular-nums [text-box:trim-both_cap_alphabetic]`,children:r?(0,K.jsx)(Xw,{line:`text-title`,className:`w-24`}):t}),!r&&n&&(0,K.jsxs)(`span`,{className:`text-body-sm text-muted-foreground tabular-nums`,children:[n,` vs previous`]})]})]})}function Asi({className:e}){return(0,K.jsx)(`div`,{className:H(`flex items-center justify-center`,e),children:(0,K.jsx)($c,{size:`md`,variant:`pulse`,className:`text-placeholder`})})}function jsi({message:e=`No data yet`,className:t}){return(0,K.jsx)(`div`,{className:H(`flex h-full items-center justify-center`,t),children:(0,K.jsx)(U,{tone:`faint`,children:e})})}function Msi({children:e,className:t}){return(0,K.jsx)(SF,{className:H(`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 Nsi({children:e,className:t,as:n=`h3`}){return(0,K.jsx)(n,{className:H(`text-body font-medium text-foreground`,t),children:e})}function Psi({title:e,value:t,onValueChange:n,options:r,className:i}){return(0,K.jsx)(`div`,{className:`flex min-w-0`,children:(0,K.jsxs)(gE,{children:[(0,K.jsxs)(gE.Trigger,{render:(0,K.jsx)(`button`,{type:`button`,className:H(`-mx-1.5 -my-0.5 flex items-center gap-1 self-start rounded-md px-1.5 py-0.5 text-left text-body font-medium text-foreground hover:bg-fill-subtle`,i)}),children:[e,(0,K.jsx)(ut,{className:`size-3.5 text-muted-foreground`})]}),(0,K.jsx)(gE.Content,{align:`start`,children:(0,K.jsx)(gE.RadioOptions,{options:r,value:t,onValueChange:n,closeOnSelect:!0})})]})})}function Fsi({children:e,className:t}){return(0,K.jsx)(`div`,{className:H(`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 Isi({children:e,className:t}){return(0,K.jsx)(`div`,{className:H(`flex items-start gap-4 [&>:first-child]:min-w-0 [&>:first-child]:flex-1`,t),children:e})}function Lsi({value:e,isLoading:t=!1,className:n}){return(0,K.jsx)(`span`,{className:H(`order-last shrink-0 text-body font-medium text-foreground tabular-nums`,n),children:(0,K.jsx)(Rsi,{value:e,isLoading:t})})}function Rsi({value:e,isLoading:t}){return t?(0,K.jsx)(Xw,{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 W7=Object.assign(Msi,{Root:Msi,Kpi:C2,TopBar:Isi,Toolbar:Fsi,Actions:Esi,Title:Nsi,TitleMenu:Psi,Total:Lsi,Headline:ksi,Loading:Asi,Error:Osi,Content:Dsi,NoData:jsi});function G7({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`,children:[n,e&&(0,K.jsx)(W7.NoData,{message:t,className:`absolute inset-0`})]})}function K7({variant:e=`default`,title:t,href:n,LinkComponent:r,titleMenu:i,total:a,change:o,isLoading:s=!1,actions:c,toolbar:l,isUpdating:u=!1,bodyHeight:d=`fixed`,className:f,children:p}){let m=H(`transition-opacity duration-200`,u&&`opacity-50`),h=e===`compact`,g=e===`hero`,_=!g&&d===`fixed`;return(0,K.jsxs)(W7,{className:H(`min-h-0! min-w-0! grid-cols-1`,h&&`h-84`,f),children:[(0,K.jsxs)(W7.TopBar,{children:[g?(0,K.jsx)(W7.Headline,{label:t,value:typeof a==`string`?a:`—`,change:o,isLoading:s,className:m}):(0,K.jsx)(Bsi,{title:t,href:n,LinkComponent:r,titleMenu:i}),c&&(0,K.jsx)(W7.Actions,{reveal:g?`always`:`hover`,className:H(g&&`my-0 self-center`),children:c}),!g&&a!==void 0&&(0,K.jsx)(W7.Total,{value:a,isLoading:s,className:m})]}),(0,K.jsxs)(W7.Content,{className:H(`flex flex-col gap-4 overflow-visible`,h&&`min-h-0`),children:[l||_&&l!==void 0&&(0,K.jsx)(`div`,{"aria-hidden":!0,className:`min-h-6`}),(0,K.jsx)(`div`,{className:H(`relative flex min-h-0 min-w-0 flex-col`,zsi(e,d),m),children:p})]})]})}function zsi(e,t){if(e===`compact`)return`flex-1`;if(e!==`hero`)return t===`fit`?`min-h-60`:`min-h-60 flex-1`}function Bsi({title:e,href:t,LinkComponent:n,titleMenu:r}){return r?(0,K.jsx)(W7.TitleMenu,{title:e,...r}):t?(0,K.jsx)(`h3`,{className:`flex`,children:(0,K.jsx)(Vsi,{href:t,LinkComponent:n,children:e})}):(0,K.jsx)(W7.Title,{children:e})}function Vsi({href:e,LinkComponent:t,children:n}){return(0,K.jsxs)(t??`a`,{href:e,className:H(`-mx-1.5 -my-0.5 inline-flex items-center gap-1.5 rounded-md px-1.5 py-0.5 text-body font-medium 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 q7({error:e,onRetry:t}){return YP(e)?(0,K.jsx)(fU,{}):XP(e)?(0,K.jsx)(dU,{resource:`traces`}):(0,K.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3`,children:[(0,K.jsx)(W7.Error,{message:`Couldn't load this data. Try again in a moment.`}),t&&(0,K.jsx)(X,{size:`sm`,icon:(0,K.jsx)(ms,{}),onClick:t,children:`Retry`})]})}function J7({onClick:e}){return(0,K.jsx)(X,{onClick:e,variant:`ghost`,size:`icon-sm`,tooltip:`View in traces`,"aria-label":`View in traces`,children:(0,K.jsx)(sF,{})})}function Hsi({onClick:e}){return(0,K.jsx)(X,{onClick:e,variant:`ghost`,size:`icon-sm`,tooltip:`View errors in logs`,"aria-label":`View errors in logs`,children:(0,K.jsx)(Ree,{})})}var Usi=[{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`},Z7=Object.keys(X7),Wsi=`mastra:metrics:saved-filters`;function Gsi(e){let t=aci(e);try{localStorage.setItem(Wsi,t.toString())}catch{}}function Ksi(){try{let e=localStorage.getItem(Wsi);if(!e)return null;let t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function qsi(e){if(e.has(`rootEntityType`))return!0;for(let t of Z7)if(e.has(X7[t]))return!0;return!1}var Jsi=`hasAll`,Ysi=[{id:`is`,label:`is`},{id:Jsi,label:`has all of`,arity:`many`}],Xsi={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`},Zsi={provider:dr,model:wr},Qsi=[`threadId`,`resourceId`,`userId`,`organizationId`,`runId`,`sessionId`,`requestId`,`experimentId`],$si=e=>({id:e,label:Xsi[e],icon:Zsi[e]??J3(e),color:Y3(e)}),eci=(e,t)=>e.label.localeCompare(t.label);function tci({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r}){let i=(e,t)=>({...$si(e),operators:[`is`],strict:!0,suggestions:t}),a=e=>({...$si(e),operators:[`is`]}),o=e=>e.map(e=>({value:e})),s=[i(`rootEntityType`,Usi.map(e=>({value:e.entityType,label:e.label}))),i(`entityName`,o(t)),{...i(`tags`,o(e)),operators:[Jsi]},i(`serviceName`,o(n)),i(`environment`,o(r))],c=Qsi.map(a),l=[`provider`,`model`].map(e=>({...a(e),hidden:!0}));return[...s.toSorted(eci),...c.toSorted(eci),...l]}function nci(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:Jsi,value:t}}let t=Array.isArray(e.value)?e.value[0]??``:e.value;return{id:e.fieldId,fieldId:e.fieldId,operatorId:`is`,value:cci(t)?``:t}})}function rci(e){return e.map(e=>({fieldId:e.fieldId,value:Array.isArray(e.value)?e.value.map(String):String(e.value)}))}function ici(e){let t=[],n=new Map([[Y7,`rootEntityType`]]);for(let e of Z7)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 aci(e){let t=new URLSearchParams,n=e.getAll(Y7);for(let e of n)t.append(Y7,e);for(let n of Z7){let r=X7[n],i=e.getAll(r);for(let e of i)t.append(r,e)}return t}function oci(e,t){e.delete(Y7);for(let t of Z7)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 sci=`Any`;function cci(e){let t=e.trim();return t===``||t===sci}var lci=new Set(Usi.map(e=>e.entityType));function uci(e){let t=e.trim();return lci.has(t)?t:void 0}function dci(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=>!cci(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:uci(e);n&&(t.rootEntityType=n)}else t[e]=r[0]}else if(typeof n.value==`string`){if(cci(n.value))continue;let r=n.value.trim();if(e===`rootEntityType`){let e=uci(r);e&&(t.rootEntityType=e)}else t[e]=r}}return t}var fci=864e5,pci={"24h":fci,"3d":2592e5,"7d":6048e5,"14d":12096e5,"30d":2592e6};function mci(e,t,n){if(e!==`custom`){let t=pci[e]??fci;return{start:new Date(n-t),end:new Date(n)}}return{start:t?.from??new Date(n-fci),end:t?.to??new Date(n)}}function hci({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)(()=>mci(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 gci(e){let t=Y(),{filters:n,filterKey:r,queryOptions:i}=e;return Iy({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 _ci(e){let t=Y(),{filters:n,filterKey:r,queryOptions:i}=e;return Iy({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=>u3(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 vci(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=u3(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 yci(e){let t=Y(),{filters:n,filterKey:r,queryOptions:i}=e;return Iy({queryKey:[`metrics`,`trace-volume`,r],queryFn:async()=>{let[e,r,i]=await Promise.all([vci(t,`mastra_agent_duration_ms`,n),vci(t,`mastra_workflow_duration_ms`,n),vci(t,`mastra_tool_duration_ms`,n)]);return{agentData:e,workflowData:r,toolData:i}},...i})}var bci=[{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`}],xci=new Set(bci.map(e=>e.value));function Sci(e){return typeof e==`string`&&(xci.has(e)||e===`custom`)}var Cci=(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 Q7(){return(0,G.useContext)(Cci)}function wci(e,t){return e===`custom`?t?.from?t.to?`${bT(t.from)} – ${bT(t.to)}`:bT(t.from)??``:`Custom range`:bci.find(t=>t.value===e)?.label??e}var Tci=36e5;function Eci(e,t){if(e!==`custom`)return`vs previous ${e}`;let n=t?.to?.getTime()??Date.now(),r=t?.from?.getTime()??n-24*Tci,i=Math.round((n-r)/Tci);return`vs previous ${i>24&&i%24==0?`${i/24}d`:`${i}h`}`}function Dci({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)(()=>dci(l),[l]),d=(0,G.useMemo)(()=>JSON.stringify(u),[u]),f=hci({datePreset:t,customRange:a,dimensionalFilter:u,dimensionalFilterKey:d}),p=(0,G.useMemo)(()=>s??{},[s]),m=wci(t,a),h=Eci(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)(Cci.Provider,{value:g,children:(0,K.jsx)(Csi,{children:e})})}function $7(){let{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r,queryFilters:i}=Q7(),a=hci({datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r});return i??a}var Oci=864e5;function e9(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 t9=e=>e===`1h`?1:24;function n9(e,t){if(t>=24)return Math.floor(e/Oci)*Oci;let n=new Date(e),r=Math.floor(n.getHours()/t)*t;return new Date(n.getFullYear(),n.getMonth(),n.getDate(),r).getTime()}function kci(e,t){if(t>=24)return n9(e,t)+Oci;let n=new Date(e);return n9(new Date(n.getFullYear(),n.getMonth(),n.getDate(),n.getHours()+t).getTime(),t)}function r9(e,t,n){let r=qqr(e,t),i=[];for(let a=n9(e.getTime(),n);a<=t.getTime();a=kci(a,n))i.push(Xqr(a,n,r));return i}function i9(e,t){let n=new Map(e.map((e,t)=>[e.ts,t]));return e=>n.get(n9(new Date(e.timestamp).getTime(),t))}function a9(e,t){return{from:new Date(e),to:new Date(kci(e,t))}}var Aci={input:`mastra_model_total_input_tokens`,output:`mastra_model_total_output_tokens`,cacheRead:`mastra_model_input_cache_read_tokens`},jci=`mastra_agent_duration_ms`;function Mci(){let e=Y(),{filters:t,filterKey:n,timestamp:r}=$7(),{interval:i,stepHours:a}=e9(r.start,r.end);return Iy({queryKey:[`metrics`,`activity`,n,i],placeholderData:Oy,queryFn:async()=>{let n=n=>e.getMetricTimeSeries({name:[n],interval:i,aggregation:`sum`,filters:t}),[o,s,c,l]=await Promise.all([n(Aci.input),n(Aci.output),n(Aci.cacheRead),e.getMetricTimeSeries({name:[jci],interval:i,aggregation:`count`,groupBy:[`status`],filters:t})]),u=r9(r.start,r.end,a).map(e=>({...e,input:0,cacheRead:0,output:0,cost:0,completed:0,failed:0,failureRate:0})),d=i9(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 Nci=[{dataKey:`failureRate`,label:`Failed runs`,color:Z6.error}],Pci=e=>`${Math.round(e*100)}%`;function Fci({onViewErrors:e,onTimeRangeClick:t,titleMenu:n}){let{data:r=[],isLoading:i,isError:a,isPlaceholderData:o}=Mci(),{timestamp:s}=$7(),{stepHours:c}=e9(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)(Hsi,{onClick:e}),toolbar:(0,K.jsx)(W7.Toolbar,{children:(0,K.jsx)(r8,{series:Nci})})};return a?(0,K.jsx)(K7,{...f,children:(0,K.jsx)(q7,{})}):(0,K.jsx)(K7,{...f,total:J6(l>0?u/l:0),isLoading:i,isUpdating:o,children:(0,K.jsx)(G7,{isEmpty:!i&&l===0,emptyMessage:`No agent runs in this range.`,children:(0,K.jsx)(i8,{data:r,series:Nci,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:J6,axisFormatter:Pci,yDomain:d,onBucketClick:t&&(e=>t(a9(Number(e.ts),c))),isLoading:i,...X6})})})}var Ici=[{dataKey:`completed`,label:`Completed`,color:Z6.green},{dataKey:`failed`,label:`Failed`,color:Z6.error}],Lci=[{value:`runs`,label:`Agent runs`},{value:`failure`,label:`Failure rate`}];function Rci({onTimeRangeClick:e,onFailureTimeRangeClick:t,onViewErrors:n}){let[r,i]=(0,G.useState)(`runs`),a={value:r,onValueChange:i,options:Lci};return r===`failure`?(0,K.jsx)(Fci,{titleMenu:a,onViewErrors:n,onTimeRangeClick:t}):(0,K.jsx)(zci,{titleMenu:a,onTimeRangeClick:e})}function zci({onTimeRangeClick:e,titleMenu:t}){let{data:n=[],isLoading:r,isError:i,isPlaceholderData:a}=Mci(),{timestamp:o}=$7(),{stepHours:s}=e9(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)(W7.Toolbar,{children:(0,K.jsx)(r8,{series:Ici})})};return i?(0,K.jsx)(K7,{...l,children:(0,K.jsx)(q7,{})}):(0,K.jsx)(K7,{...l,total:q6(c),isLoading:r,isUpdating:a,children:(0,K.jsx)(G7,{isEmpty:!r&&c===0,emptyMessage:`No agent runs in this range.`,children:(0,K.jsx)(Rqr,{data:n,series:Ici,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:q6,onBucketClick:e&&(t=>e(a9(Number(t.ts),s))),isLoading:r,...X6})})})}var Bci=[`entityName`,`environment`,`serviceName`,`threadId`,`resourceId`,`userId`,`organizationId`,`runId`,`sessionId`,`requestId`,`experimentId`],Vci=[`tags`,`provider`,`model`],Hci=(e,t)=>({op:`eq`,left:{path:e},right:{literal:t}});function Uci(e){let t=Vci.filter(t=>e[t]!==void 0);if(t.length)return{supported:!1,unsupportedFields:t};let n=[];e.rootEntityType&&n.push(Hci(`entityType`,e.rootEntityType));for(let t of Bci){let r=e[t];r!==void 0&&n.push(Hci(t,r))}return n.length===0?{supported:!0,where:void 0}:{supported:!0,where:n.length===1?n[0]:{op:`and`,args:n}}}var Wci=[`entityName`,`environment`,`threadId`,`resourceId`,`userId`,`organizationId`,`runId`,`sessionId`],Gci=[`provider`,`model`],Kci=[`serviceName`,`requestId`,`experimentId`],qci=(e,t)=>({op:`eq`,left:{path:e},right:{literal:t}});function Jci(e){let t=Kci.filter(t=>e[t]!==void 0);if(t.length)return{supported:!1,unsupportedFields:t};let n=[];e.rootEntityType&&n.push(qci(`entityType`,e.rootEntityType));for(let t of Wci){let r=e[t];r!==void 0&&n.push(qci(t,r))}for(let t of e.tags??[])n.push({op:`includes`,path:`tags`,value:t});for(let t of Gci){let r=e[t];r!==void 0&&n.push({spans:{some:qci(t,r)}})}return n.length===0?{supported:!0,where:void 0}:{supported:!0,where:n.length===1?n[0]:{op:`and`,args:n}}}var Yci=({start:e,end:t})=>({from:e.toISOString(),to:t.toISOString()}),Xci=({start:e,end:t})=>e9(e,t).interval;function Zci(e,t){let n=t9(Xci(t)),r=r9(t.start,t.end,n).map(e=>({...e,rows:[]})),i=i9(r,n);for(let t of e)t.bucket&&r[i({timestamp:t.bucket,value:0})??-1]?.rows.push(t);return r}function Qci(){let{data:e,isLoading:t}=E6(),{timestamp:n,dimensionalFilter:r}=$7();if(t)return{status:`loading`};if(e?.capabilities.spanAggregate!==!0)return{status:`unavailable`};let i=Uci(r);return i.supported?{status:`ready`,scope:{timeRange:Yci(n),...i.where?{where:i.where}:{},interval:Xci(n),window:n}}:{status:`unsupported-filter`,unsupportedFields:i.unsupportedFields}}function $ci(e,{priority:t,enabled:n}={}){let r=Y();return DRr({request:e,enabled:n,queryOptions:{queryFn:Ssi(()=>r.aggregateSpans(e),t),placeholderData:Oy,staleTime:1/0}})}function eli({requiresRootSpanFields:e=!1}={}){let{data:t,isLoading:n}=E6(),{timestamp:r,dimensionalFilter:i}=$7();if(n)return{status:`loading`};let a=t?.capabilities;if(a?.traceAggregate!==!0||e&&a.traceQueryRootSpanFields!==!0)return{status:`unavailable`};let o=Jci(i);return o.supported?{status:`ready`,scope:{timeRange:Yci(r),...o.where?{where:o.where}:{},interval:Xci(r),window:r}}:{status:`unsupported-filter`,unsupportedFields:o.unsupportedFields}}function o9(e,{priority:t,enabled:n}={}){let r=Y();return ORr({request:e,enabled:n,queryOptions:{queryFn:Ssi(()=>r.aggregateTraces(e),t),placeholderData:Oy,staleTime:1/0}})}function tli(){return Q7().scope}var nli=`Breakdown`,rli={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 ili({tab:e,tabs:t,onTabChange:n,isUpdating:r,children:i}){return(0,K.jsx)(K7,{title:rli[e],titleMenu:t.length>1?{value:e,onValueChange:n,options:t.map(e=>({value:e,label:rli[e]}))}:void 0,isUpdating:r,bodyHeight:`fit`,children:i})}var ali={agents:[`agent_run`],workflows:[`workflow_run`],tools:[`tool_call`,`mcp_tool_call`]},oli=e=>e in ali;function sli(e){let t=ali[e];return t.length===1?{op:`eq`,left:{path:`spanType`},right:{literal:t[0]??``}}:{op:`in`,value:{path:`spanType`},set:[...t]}}var cli=e=>e!==`workflows`&&e!==`tools`,lli=e=>e!==`models`,uli=e=>e===`tools`||e===`models`;function s9(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 c9={trace:1e3,span:500};function dli({timeRange:e,where:t}){return{timeRange:e,...t?{where:t}:{},groupBy:[`projectId`],measures:[`count`,`errorRate`,`duration.p95`,`countDistinct.resourceId`,`countDistinct.threadId`],limit:c9.trace}}function fli({timeRange:e,where:t},n){return{timeRange:e,...t?{where:t}:{},groupBy:s9(`environments`,n),measures:[`count`,`errorRate`,`duration.p95`],limit:c9.trace}}function pli(e){let t={op:`exists`,path:`threadId`};return e?{op:`and`,args:[t,e]}:t}function mli({timeRange:e,where:t},n){return{timeRange:e,where:pli(t),groupBy:n?[`projectId`,`threadId`]:[`resourceId`,`threadId`],measures:[`count`,`errorRate`,`duration.p95`],limit:c9.trace}}function hli(e,t,n){return e===`projects`?dli(t):e===`environments`?fli(t,n):mli(t,n)}function gli({timeRange:e,where:t}){return{timeRange:e,where:pli(t),groupBy:[`resourceId`,`threadId`],measures:[`count`],limit:c9.trace}}function _li(e){let t=new Map;for(let n of e){let e=u9(n,`resourceId`);e&&t.set(u9(n,`threadId`),e)}return t}var vli=e=>e===`agents`||e===`workflows`?`countDistinct.traceId`:`count`;function yli(e,{timeRange:t,where:n},r){let i=sli(e);return{timeRange:t,where:n?{op:`and`,args:[i,n]}:i,groupBy:s9(e,r),measures:[`count`,...vli(e)===`count`?[]:[`countDistinct.traceId`],`errorCount`,`errorRate`,`duration.p95`],limit:c9.span}}var l9=(e,t)=>{let n=e.measures[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0},u9=(e,t)=>{let n=e.dimensions?.[t];return n==null?``:String(n)},d9=(e,t)=>t.map(t=>e.dimensions[t]==null?``:String(e.dimensions[t])).join(`|`);function bli({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=vli(e);for(let e of n){let n=l(t.map(t=>u9(e,t)).join(`|`));n.count=l9(e,u)??0,n.errorRate=l9(e,`errorRate`),n.p95=l9(e,`duration.p95`),n.resources=l9(e,`countDistinct.resourceId`),n.threads=l9(e,`countDistinct.threadId`)}for(let e of i)l(d9(e,t)).count=e.value;for(let e of r??[]){let n=l(d9(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 xli({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=vli(e);for(let e of n){let n=o(t.map(t=>u9(e,t)).join(`|`));n.count=l9(e,s)??0,n.errorRate=l9(e,`errorRate`),n.p95=l9(e,`duration.p95`)}for(let e of i)o(d9(e,t)).count=e.value;for(let e of r){let n=o(d9(e,t));n.tokens=e.value,n.cost=e.estimatedCost??void 0}return a}function Sli(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 Cli(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:wli(n,a,i),isNew:!1}}function wli(e,t,n){return e===`errorRate`?t:n>0?t/n:void 0}function Tli(e,t){if(e.delta!==void 0&&e.delta!==0)return e.delta>0==(t===`count`)?`good`:`bad`}function Eli({start:e,end:t}){return{start:new Date(2*e.getTime()-t.getTime()),end:new Date(e.getTime())}}var Dli=[`count`,`errorRate`,`p95`,`tokens`,`cost`],Oli=e=>Dli.includes(e),kli=e=>uli(e)?`Spans`:`Traces`,Ali=`A trace is one end-to-end request, with every step it took.`,jli=`A span is one step inside a trace, such as a tool call or a model call. One trace can have many.`,Mli=e=>uli(e)?jli:Ali,Nli={errorRate:`Errors`,p95:`P95 latency`,tokens:`Tokens`,cost:`Cost`},Pli=e=>e.toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`}),Fli=({start:e,end:t})=>`${Pli(e)} – ${Pli(t)}`;function Ili(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: ${Fli(e)}`,previous:`Previous: ${Fli(Eli(e))}`}}var Lli=(e,t)=>t&&e!==`projects`,Rli=(e,t)=>t===`count`?kli(e):Nli[t];function zli({tab:e,built:t,previous:n,truncated:r,groupBy:i,usage:a}){return e===`threads`?t.filter(e=>e.name!==``):!n||r?t:Sli(t,n,i,a)}function Bli(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 Vli=(e,t)=>e===`projects`?t.key:t.projectId;function Hli(e,t){let n=Vli(e,t),r=n?{projectId:n}:{};return oli(e)?{...r,span:{spanTypes:ali[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 Uli(e,t){return t&&t.toUpperCase()!==`USD`?`${q6(e)} ${t}`:Y6(e)}function Wli(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}${J6(r)}`}function Gli(e){let t=Eli(e.window);return{...e,window:t,timeRange:Yci(t)}}var Kli=[`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}=$7();return Iy({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`?Kli:[`mastra_model_total_input_tokens`],groupBy:e,aggregation:r===`tokens`?`sum`:`count`,orderDirection:`DESC`,limit:1e3,filters:{...o,...t,timestamp:n}})})}function qli({window:e,label:t}){let{summary:n,current:r,previous:i}=Ili(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 p9({muted:e=!1,children:t}){return(0,K.jsx)(U,{as:`span`,variant:`body-sm`,tone:e?`muted`:void 0,className:`tabular-nums`,children:t})}function Jli({text:e}){return(0,K.jsx)(U,{as:`span`,variant:`body-sm`,tone:`muted`,className:`truncate`,title:e,children:e})}var Yli={asc:Xt,desc:Pt},Xli=`focus-visible:outline-1 focus-visible:outline-solid focus-visible:outline-border-focus focus-visible:-outline-offset-1`,Zli=`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 Qli({header:e,explained:t,sorted:n,className:r,...i}){let a=n&&Yli[n];return(0,K.jsxs)(`button`,{type:`button`,...i,className:H(`group/header flex items-center gap-1 rounded whitespace-nowrap hover:text-muted-foreground`,Xli,r),children:[(0,K.jsx)(`span`,{className:H(t&&Zli),children:e}),a&&(0,K.jsx)(a,{"aria-hidden":!0,className:`size-3`})]})}function $li({header:e,explained:t,className:n,...r}){return(0,K.jsx)(`span`,{tabIndex:t?0:void 0,...r,className:H(`group/header rounded whitespace-nowrap`,Xli,n),children:(0,K.jsx)(`span`,{className:H(t&&Zli),children:e})})}function eui({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)(Qli,{header:e,explained:a,sorted:n,onClick:r,"aria-describedby":o}):(0,K.jsx)($li,{header:e,explained:a,"aria-describedby":o});return a?(0,K.jsxs)(JC,{children:[(0,K.jsx)(YC,{render:s}),(0,K.jsx)(XC,{id:i,keepMounted:!0,side:`top`,className:`max-w-72`,children:t})]}):s}var tui=H(`relative col-span-full grid grid-cols-subgrid items-center px-3 pt-1.75 pb-2 text-body-sm`,`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)]`),nui=[`w-32`,`w-24`,`w-36`,`w-20`,`w-28`],rui=`a, button, input, select, textarea, label, [role="button"], [role="link"], [contenteditable]`;function iui(e){if(!(e.target instanceof Element))return!1;let t=e.target.closest(rui);return!!(t&&e.currentTarget.contains(t))}function aui(e,t,n){return e.align===`end`?`right-0 w-10`:t>0?`left-0 w-16`:H(`left-0`,nui[n%nui.length])}function oui({columns:e,rows:t,getRowKey:n,empty:r,skeletonRows:i,isLoading:a,...o}){return a?Array.from({length:i},(t,n)=>(0,K.jsx)(sui,{columns:e,rowIndex:n},n)):t.length===0?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)(cui,{row:t,columns:e,...o},n(t)))}function sui({columns:e,rowIndex:t}){return(0,K.jsx)(`div`,{role:`row`,"aria-busy":!0,className:tui,children:e.map((e,n)=>(0,K.jsxs)(`div`,{role:`cell`,className:H(`relative flex min-w-0`,e.align===`end`&&`justify-end`),children:[``,(0,K.jsx)(Yw,{className:H(`absolute top-1/2 h-3.5 -translate-y-1/2`,aui(e,n,t))})]},e.id))})}function cui({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=>{iui(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:H(tui,`rounded text-foreground transition-opacity duration-150`,n&&H(`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:H(`flex min-w-0 items-center`,t.align===`end`&&`justify-end text-right`),children:t.cell(e)},t.id))})}var lui=`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)]`,uui={asc:`ascending`,desc:`descending`};function dui(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 fui(e,t){return typeof e==`number`&&typeof t==`number`?e-t:String(e).localeCompare(String(t))}function pui(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*fui(n,a)})}var mui=e=>e.width??(e.align===`end`?`minmax(max-content,1fr)`:`max-content`);function hui({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":m,className:h}){let[g,_]=(0,G.useState)(i),[v,y]=(0,G.useState)(0),b=r??g,x=pui(t,e,b),S=f?Math.ceil(x.length/f):1,C=Math.min(v,Math.max(0,S-1)),w=f?x.slice(C*f,(C+1)*f):x,T={gridTemplateColumns:e.map(mui).join(` `)},E=!p&&S>1,D=e=>{let t=dui(b,e)??i;_(t),y(0),a?.(t)};return(0,K.jsxs)(`div`,{className:H(`grid min-w-0 gap-3`,h),children:[(0,K.jsx)(Kw,{orientation:`horizontal`,children:(0,K.jsxs)(`div`,{role:`table`,"aria-label":m,className:`grid min-w-min gap-x-4`,style:T,children:[(0,K.jsx)(`div`,{role:`row`,className:H(`relative col-span-full grid grid-cols-subgrid items-end px-3 pb-1.5 text-body-sm font-medium text-placeholder`,lui),children:e.map(e=>{let t=b?.column===e.id?b.direction:void 0;return(0,K.jsx)(`div`,{role:`columnheader`,"aria-sort":t&&uui[t],className:H(`flex min-w-0 items-center gap-1`,e.align===`end`&&`justify-end text-right`),children:(0,K.jsx)(eui,{header:e.header,description:e.description,sorted:t,onSort:e.sortValue?()=>D(e):void 0})},e.id)})}),(0,K.jsx)(oui,{columns:e,rows:w,getRowKey:n,onRowClick:o,onRowHover:s,isRowDimmed:c,isRowActive:l,rowTitle:u,empty:d,skeletonRows:f??5,isLoading:p})]})}),E&&(0,K.jsx)(r7r,{page:C,pageCount:S,onPageChange:y})]})}var gui={good:`text-badge-green-foreground`,bad:`text-badge-red-foreground`};function _ui({trend:e,children:t}){return t===void 0?(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`—`}):(0,K.jsx)(`span`,{className:e?gui[e]:`text-muted-foreground`,children:t})}function vui({change:e,metric:t}){return e?(0,K.jsx)(_ui,{trend:Tli(e,t),children:Wli(e,t)}):(0,K.jsx)(_ui,{trend:void 0})}function yui(){return(0,K.jsx)(`span`,{title:`No price for this model`,children:`Not priced`})}function bui({row:e}){return e.cost===void 0?e.tokens?(0,K.jsx)(yui,{}):`—`:Uli(e.cost,e.costUnit)}function xui({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)($$r,{parts:Fkn(n.name,n.provider)}):t})]})}var Sui=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`})]}),Cui={agent:nF,workflow:aP,tool:oF},wui={agents:`agent`,workflows:`workflow`,tools:`tool`};function Tui({entity:e}){let t=Cui[e];return(0,K.jsx)(Lkn,{icon:(0,K.jsx)(t,{className:`size-3`})})}function Eui({provider:e}){return e?(0,K.jsx)(Rkn,{provider:e}):(0,K.jsx)(Lkn,{icon:(0,K.jsx)(Sui,{className:`size-3`})})}function Dui({tab:e,row:t}){let n=wui[e];return n?(0,K.jsx)(Tui,{entity:n}):e===`models`?(0,K.jsx)(Eui,{provider:t.provider}):null}function Oui({tab:e,row:t}){let{projectLabel:n}=tli();return(0,K.jsx)(xui,{mark:(0,K.jsx)(Dui,{tab:e,row:t}),title:Bli(e,t,n),model:e===`models`&&t.name!==``?{name:t.name,provider:t.provider}:void 0})}var kui=13,Aui={column:`count`,direction:`desc`},jui={projects:`Project`,agents:`Agent`,workflows:`Workflow`,tools:`Tool`,models:`Model`,threads:`Thread`,environments:`Environment`},Mui={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 Nui({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=tli(),[p,m]=(0,G.useState)(Aui),[h,g]=(0,G.useState)(`count`),_=(e=Aui)=>{m(e),Oli(e.column)&&g(e.column)},v=[r,i,a].filter(e=>e!==void 0);if(v.some(e=>e.isError))return(0,K.jsx)(ili,{...d,tab:e,children:(0,K.jsx)(q7,{onRetry:()=>v.forEach(e=>e.isError&&void e.refetch())})});let y=v.some(e=>e.isLoading),b=lli(e),x=i!==void 0,S=Lli(e,d.byProject),C=r?.data?.truncated===!0,w=y?[]:bli({tab:e,groupBy:t,aggregateRows:r?.data?.rows,usageGroups:i?.data?.groups,spanGroups:a?.data?.groups,resources:o?.data?_li(o.data.rows):void 0}),T=[s,c,l].every(e=>!e||!e.isLoading&&!e.isError)&&!y?xli({tab:e,groupBy:t,aggregateRows:s?.data?.rows,usageGroups:c?.data?.groups,spanGroups:l?.data?.groups}):void 0,E=zli({tab:e,built:w,previous:T,truncated:C,groupBy:t,usage:x}),D=kli(e),O=e=>T?Cli(e,T.get(e.key),h):void 0,k=e=>e.projectId?f.projectLabel?.(e.projectId)??e.projectId:`—`,A={id:`name`,header:jui[e],width:`minmax(12rem,3fr)`,cell:t=>(0,K.jsx)(Oui,{tab:e,row:t})},j={id:`project`,header:`Project`,width:`minmax(8rem,2fr)`,cell:e=>(0,K.jsx)(Jli,{text:k(e)})},M={id:`resource`,header:`Resource`,width:`minmax(6rem,1fr)`,cell:e=>(0,K.jsx)(Jli,{text:e.resource??`—`})},N=[{id:`errorRate`,header:`Errors`,align:`end`,sortValue:e=>e.errorRate,cell:e=>(0,K.jsx)(p9,{muted:!0,children:e.errorRate===void 0?`—`:J6(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?`—`:bKr(e.p95)})}],P=[{id:`tokens`,header:`Tokens`,align:`end`,sortValue:e=>e.tokens,cell:e=>(0,K.jsx)(p9,{muted:!0,children:e.tokens===void 0?`—`:q6(e.tokens)})},{id:`cost`,header:`Cost`,align:`end`,sortValue:e=>e.cost,cell:e=>(0,K.jsx)(p9,{muted:!0,children:(0,K.jsx)(bui,{row:e})})}],F={id:`count`,header:D,align:`end`,description:Mli(e),sortValue:e=>e.count,cell:e=>(0,K.jsx)(p9,{children:q6(e.count)})},I={id:`change`,header:`% Change`,align:`end`,description:(0,K.jsx)(qli,{window:n,label:Rli(e,h)}),sortValue:e=>O(e)?.change,cell:e=>(0,K.jsx)(p9,{children:(0,K.jsx)(vui,{change:O(e),metric:h})})},L=[A,...S?[j]:[],...e===`threads`?[M]:[],...b?N:[],...x?P:[],F,I];return(0,K.jsx)(ili,{...d,tab:e,isUpdating:r?.isPlaceholderData,children:(0,K.jsxs)(G7,{children:[(0,K.jsx)(hui,{"aria-label":`${jui[e]} breakdown`,columns:L,rows:E,getRowKey:e=>e.key,sort:p,defaultSort:Aui,onSortChange:_,onRowClick:d.onRowClick&&(t=>d.onRowClick?.(Hli(e,t))),pageSize:kui,isLoading:y,empty:Mui[e]},e),!y&&C&&(0,K.jsxs)(U,{variant:`caption`,tone:`muted`,className:`pt-2`,children:[`Showing the `,q6(u),` busiest; sorting covers only these.`]})]})})}var Pui={entityType:`agent`};function Fui({tab:e,scope:t,...n}){let r=s9(e,n.byProject),i=cli(e),a=Gli(t),o=$ci(yli(e,t,n.byProject)),s=$ci(yli(e,a,n.byProject),{priority:_si.last}),c=f9({groupBy:r,filters:Pui,window:t.window,enabled:i}),l=f9({groupBy:r,filters:Pui,window:a.window,enabled:i});return(0,K.jsx)(Nui,{...n,tab:e,groupBy:r,window:t.window,aggregate:o,totals:i?c:void 0,previousAggregate:s,previousUsage:i?l:void 0,limit:c9.span})}function Iui(e){let t=s9(`models`,e.byProject),{timestamp:n}=$7(),r=Eli(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)(Nui,{...e,tab:`models`,groupBy:t,window:n,totals:i,spans:a,previousUsage:o,previousSpans:s,limit:c9.trace})}function Lui({tab:e,scope:t,...n}){let r=s9(e,n.byProject),i=Gli(t),a=o9(hli(e,t,n.byProject)),o=o9(hli(e,i,n.byProject),{priority:_si.last}),s=o9(gli(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)(Nui,{...n,tab:e,groupBy:r,window:t.window,aggregate:a,totals:c,resources:e===`threads`?l:void 0,previousAggregate:o,previousUsage:u,limit:c9.trace})}var Rui={serviceName:`service`,requestId:`request ID`,experimentId:`experiment`,tags:`tags`,provider:`provider`,model:`model`};function zui({tab:e,traceGate:t,spanGate:n,...r}){if(e===`models`)return(0,K.jsx)(Iui,{...r},e);let i=oli(e)?n:t;return i.status===`unsupported-filter`?(0,K.jsx)(ili,{...r,tab:e,children:(0,K.jsx)(W7.NoData,{message:`Not available with a ${i.unsupportedFields.map(e=>Rui[e]??e).join(` or `)} filter.`})}):oli(e)?n.status===`ready`&&(0,K.jsx)(Fui,{...r,tab:e,scope:n.scope},e):t.status===`ready`&&(0,K.jsx)(Lui,{...r,tab:e,scope:t.scope},e)}function Bui({chosen:e,traceScope:t,spanGate:n,...r}){let i=o9(dli(t)).data?.rows.filter(e=>(e.measures.count??0)>0).length,a=e??Vui(i);return(0,K.jsx)(zui,{...r,tab:a,traceGate:{status:`ready`,scope:t},spanGate:n})}function Vui(e){return e===void 0||e>=2?`projects`:`agents`}var Hui=[`projects`,`agents`,`workflows`,`tools`,`models`,`threads`,`environments`],Uui=Hui.filter(e=>e!==`projects`);function Wui({onRowClick:e}){let t=tli().projectLabel!==void 0,n=eli(),r=Qci(),[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)(K7,{title:nli,bodyHeight:`fit`,children:(0,K.jsx)(W7.Loading,{})});let o={tabs:t?Hui:Uui,onTabChange:a,onRowClick:e,byProject:t};return t&&n.status===`ready`?(0,K.jsx)(Bui,{...o,chosen:i,traceScope:n.scope,spanGate:r}):(0,K.jsx)(zui,{...o,tab:i??`agents`,traceGate:n,spanGate:r})}var Gui=[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`];function Kui(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 qui(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 Jui=[{measure:`countDistinct.resourceId`,dataKey:`resources`,label:`Resources`,color:Z6.sky},{measure:`countDistinct.threadId`,dataKey:`threads`,label:`Threads`,color:Z6.green},{measure:`countDistinct.userId`,dataKey:`users`,label:`Users`,color:Z6.violet},{measure:`countDistinct.sessionId`,dataKey:`sessions`,label:`Sessions`,color:Z6.teal}],Yui=Jui.map(e=>e.measure),Xui=`Resources and threads`;function Zui(e,t){return e?.measures[t.measure]??0}function Qui({scope:e,onTimeRangeClick:t}){let n=o9({timeRange:e.timeRange,where:e.where,interval:e.interval,measures:Yui,limit:10}),r=o9({timeRange:e.timeRange,where:e.where,measures:Yui}),i=r.data?.rows[0],a=Jui.filter(e=>Zui(i,e)>0),o=a.map((e,t)=>({dataKey:e.dataKey,label:e.label,color:e.color,emphasis:t===0})),s=Zci(n.data?.rows??[],e.window).map(({rows:e,...t})=>({...t,...Object.fromEntries(a.map(t=>[t.dataKey,Zui(e[0],t)]))})),c=t9(e.interval===`1d`?`1d`:`1h`),l=n.error??r.error,u=n.isLoading||r.isLoading,d={title:Xui,total:a.map(e=>({label:e.label,value:q6(Zui(i,e)),color:e.color})),isLoading:r.isLoading,toolbar:o.length>0&&(0,K.jsx)(W7.Toolbar,{children:(0,K.jsx)(r8,{series:o})})};return l?(0,K.jsx)(K7,{...d,children:(0,K.jsx)(q7,{error:l,onRetry:()=>{n.error&&n.refetch(),r.error&&r.refetch()}})}):(0,K.jsx)(K7,{...d,isUpdating:n.isPlaceholderData||r.isPlaceholderData,children:(0,K.jsx)(G7,{isEmpty:!u&&a.length===0,emptyMessage:`No traces in this range set a resource, thread, user or session id.`,children:(0,K.jsx)(i8,{data:s,series:o,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:q6,axisFormatter:xKr,onBucketClick:t&&(e=>t({window:a9(Number(e.ts),c)})),isLoading:u,...X6})})})}var $ui={serviceName:`service`,requestId:`request ID`,experimentId:`experiment`};function edi({requiresRootSpanFields:e,children:t,...n}){let r=eli({requiresRootSpanFields:e});return r.status===`unavailable`?null:r.status===`ready`?t(r.scope):(0,K.jsx)(K7,{...n,toolbar:null,children:r.status===`loading`?(0,K.jsx)(W7.Loading,{}):(0,K.jsx)(W7.NoData,{message:`Not available with a ${r.unsupportedFields.map(e=>$ui[e]??e).join(` or `)} filter.`})})}function tdi(e){return(0,K.jsx)(edi,{title:Xui,children:t=>(0,K.jsx)(Qui,{scope:t,...e})})}var ndi=864e5;function rdi(){let{data:e}=E6(),t=e?.capabilities.traceRetentionDays;if(t===void 0)return;let n=new Date(Date.now()-t*ndi);return new Date(n.getFullYear(),n.getMonth(),n.getDate())}function idi(){let{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=Q7(),i=rdi();return(0,K.jsx)(U6,{preset:Kui(e),onPresetChange:e=>t(qui(e)),dateFrom:n?.from,dateTo:n?.to,onDateRangeChange:(e,t)=>r({from:e,to:t}),presets:Gui,minDate:i})}var adi={2:`@3xl:grid-cols-2`,3:`@3xl:grid-cols-2 @7xl:grid-cols-3`},odi={1:``,2:`@3xl:col-span-2`,full:`col-span-full`};function m9({children:e,columns:t=3,className:n}){return(0,K.jsx)(`div`,{className:H(`@container`,n),children:(0,K.jsx)(`div`,{className:H(`grid gap-4`,adi[t]),children:e})})}function sdi({children:e,span:t=1,className:n}){return(0,K.jsx)(`div`,{className:H(`min-w-0 *:size-full *:min-w-0!`,odi[t],n),children:e})}m9.Item=sdi;var cdi=[{dataKey:`input`,label:`Input`,color:Z6.green},{dataKey:`cacheRead`,label:`Cache read`,color:Z6.violet},{dataKey:`output`,label:`Output`,color:Z6.sky}],ldi=[{dataKey:`cost`,label:`Cost`,color:Z6.green}],udi={tokens:`Token usage`,cost:`Model cost`},ddi=[{value:`tokens`,label:udi.tokens},{value:`cost`,label:udi.cost}];function fdi({onViewTraces:e,onTimeRangeClick:t}){let[n,r]=(0,G.useState)(`tokens`),{data:i=[],isLoading:a,isError:o,isPlaceholderData:s}=Mci(),{timestamp:c}=$7(),{stepHours:l}=e9(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?cdi:ldi,m={title:udi[n],titleMenu:{value:n,onValueChange:r,options:ddi},actions:e&&(0,K.jsx)(J7,{onClick:e}),toolbar:(0,K.jsx)(W7.Toolbar,{children:(0,K.jsx)(r8,{series:p})})};return o?(0,K.jsx)(K7,{...m,children:(0,K.jsx)(q7,{})}):(0,K.jsx)(K7,{...m,total:f?q6(u):Y6(d),isLoading:a,isUpdating:s,children:(0,K.jsx)(G7,{isEmpty:!a&&u===0&&d===0,emptyMessage:`No model calls in this range.`,children:(0,K.jsx)(Rqr,{data:i,series:p,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:f?q6:Y6,axisFormatter:f?xKr:SKr,onBucketClick:t&&(e=>t(a9(Number(e.ts),l))),isLoading:a,...X6})})})}var pdi={.5:`p50`,.95:`p95`,.99:`p99`},mdi={agents:`mastra_agent_duration_ms`,workflows:`mastra_workflow_duration_ms`,tools:`mastra_tool_duration_ms`};function hdi(e){let t=Y(),{filters:n,filterKey:r,timestamp:i}=$7(),{interval:a}=e9(i.start,i.end),o=t9(a);return Iy({queryKey:[`metrics`,`latency-percentiles`,e,r,a],placeholderData:Oy,queryFn:async()=>{let r=await t.getMetricPercentiles({name:mdi[e],percentiles:[.5,.95,.99],interval:a,filters:n}),s=r9(i.start,i.end,o),c=i9(s,o);for(let e of r.series){let t=pdi[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 gdi={agents:Uh.AGENT,workflows:Uh.WORKFLOW_RUN,tools:Uh.TOOL},_di=[{dataKey:`p50`,label:`P50`,color:Z6.sky},{dataKey:`p95`,label:`P95`,color:Z6.green,emphasis:!0},{dataKey:`p99`,label:`P99`,color:Z6.violet}],h9={agents:`Agent latency`,workflows:`Workflow latency`,tools:`Tool latency`},vdi=[{value:`agents`,label:h9.agents},{value:`workflows`,label:h9.workflows},{value:`tools`,label:h9.tools}],ydi={agents:`agent runs`,workflows:`workflow runs`,tools:`tool calls`};function bdi({onViewTraces:e,onTimeRangeClick:t}){let[n,r]=(0,G.useState)(`agents`),{data:i=[],isLoading:a,isError:o,isPlaceholderData:s}=hdi(n),{timestamp:c}=$7(),l=t9(e9(c.start,c.end).interval),u=Math.max(0,...i.map(e=>e.p95??0)),d={title:h9[n],titleMenu:{value:n,onValueChange:r,options:vdi},actions:e&&(0,K.jsx)(J7,{onClick:()=>e(gdi[n])}),toolbar:(0,K.jsx)(W7.Toolbar,{children:(0,K.jsx)(r8,{series:_di})})};return o?(0,K.jsx)(K7,{...d,children:(0,K.jsx)(q7,{})}):(0,K.jsx)(K7,{...d,total:u>0?bKr(u):`—`,isLoading:a,isUpdating:s,children:(0,K.jsx)(G7,{isEmpty:!a&&u===0,emptyMessage:`No ${ydi[n]} in this range.`,children:(0,K.jsx)(i8,{data:i,series:_di,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:bKr,axisFormatter:CKr,onBucketClick:t&&(e=>t(a9(Number(e.ts),l))),isLoading:a,...X6})})})}var xdi=`-mx-2 flex w-[calc(100%+1rem)] items-center gap-3 rounded-md px-2 py-1 text-left`,g9=`shrink-0 text-right text-body-sm tabular-nums`;function Sdi({row:e,columns:t,valueWidth:n,share:r,highlighted:i,dimmed:a,onHover:o,LinkComponent:s}){let c=H(xdi,i&&`bg-fill-subtle`,(e.href||e.onClick)&&`hover:bg-fill-subtle`);return(0,K.jsx)(`li`,{children:(0,K.jsxs)(Cdi,{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)(wdi,{row:e}),t.map((t,n)=>(0,K.jsx)(`span`,{className:H(g9,`text-muted-foreground`,t.width??`w-16`),children:e.cells?.[n]},t.label)),(0,K.jsx)(`span`,{className:H(g9,`w-12 text-muted-foreground`),children:r}),(0,K.jsx)(`span`,{className:H(g9,`text-foreground`,n),children:e.value})]})})}function Cdi({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 wdi({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)(U,{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 Tdi=`var(--chart-share-1)`,Edi=[1,2,3,4,5].map(e=>`var(--chart-share-${e})`),Ddi=[3,4,2,5,1].map(e=>`var(--chart-share-${e})`),Odi=[1,.7,.48,.32,.2,.14],_9={color:`var(--chart-share-rest)`,alpha:1},kdi=50,v9=`__rest`;function Adi(e,t,n){if(n===`hues`){let n=Edi.includes(e)?[e,...Edi.filter(t=>t!==e)]:[e,...Ddi];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:Odi[n]??.1}))}var jdi=e=>e.reduce((e,t)=>e+Math.max(t.share,0),0);function Mdi(e){return e.map(e=>Number.isFinite(e.share)&&e.share>0?e:{...e,share:0}).toSorted((e,t)=>t.share-e.share)}function Ndi(e,{limit:t,other:n,color:r,palette:i}){if(e.length<=t+1){let t=Pdi(e,r,i);return{shown:t,bar:t,rest:[]}}let a=e.slice(t),o=n?.(a),s={key:v9,label:`Other (${a.length})`,share:jdi(a),value:o?.value,cells:o?.cells,paint:_9,segment:v9},c=Pdi(e.slice(0,t),r,i);return{shown:[...c,s],bar:c,rest:a}}function Pdi(e,t,n){let r=Adi(t,e.length,n);return e.map((e,t)=>({...e,paint:Fdi(e)??r[t]??_9,segment:e.key}))}var Fdi=e=>e.color?{color:e.color,alpha:1}:void 0;function Idi(e,{count:t,color:n,palette:r}){let i=Math.min(t,e.length,kdi),a=Pdi(e.slice(0,i),n,r),o=e.slice(i,t).map(e=>({...e,paint:_9,segment:v9}));return{shown:[...a,...o],bar:a,rest:e.slice(i)}}function Ldi(e,t){let n=e.map(e=>({key:e.key,share:e.share,paint:e.paint})),r=t.length?[{key:v9,share:jdi(t),paint:_9}]:[],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 Rdi(e,t){if(t!==void 0)return e.find(e=>e.key===t)?.segment??t}var zdi=(e,t)=>t!==void 0&&t!==e;function Bdi(e,t){return t===void 0||t===e.key?!1:t!==`__rest`||e.segment!==`__rest`}var Vdi=(e,t)=>{let n=e/(t||1);return n>0?n<.001?`<0.1%`:`${(n*100).toFixed(+(n<.1))}%`:`0%`};function Hdi({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-body-sm font-medium 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)(ut,{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)(it,{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 Udi=[`w-32`,`w-24`,`w-36`,`w-20`,`w-28`];function y9({className:e}){return(0,K.jsxs)(K.Fragment,{children:[``,(0,K.jsx)(Yw,{className:H(`absolute top-1/2 h-3.5 -translate-y-1/2`,e)})]})}function Wdi({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)(Yw,{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:xdi,children:[(0,K.jsx)(Yw,{className:`size-2 shrink-0 rounded-[2px]`}),(0,K.jsx)(`span`,{className:`min-w-0 flex-1`,children:(0,K.jsx)(U,{as:`span`,variant:`body-sm`,className:`relative`,children:(0,K.jsx)(y9,{className:H(`left-0`,Udi[r%Udi.length])})})}),t.map(e=>(0,K.jsx)(`span`,{className:H(g9,`relative`,e.width??`w-16`),children:(0,K.jsx)(y9,{className:`right-0 w-10`})},e.label)),(0,K.jsx)(`span`,{className:H(g9,`relative w-12`),children:(0,K.jsx)(y9,{className:`right-0 w-9`})}),(0,K.jsx)(`span`,{className:H(g9,`relative`,n),children:(0,K.jsx)(y9,{className:`right-0 w-12`})})]},r))})]})}function Gdi({className:e,...t}){return(0,K.jsx)(`div`,{className:H(`grid grid-cols-1`,e),children:(0,K.jsx)(Kdi,{...t})})}function Kdi({rows:e,columns:t=[],valueLabel:n,valueWidth:r=`w-14`,palette:i=`shades`,color:a=Tdi,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)(qdi,{columns:t,valueLabel:n,valueWidth:r});if(d)return(0,K.jsx)(Wdi,{rows:s===`other`?o+1:o,columns:t,valueWidth:r,header:v});let y=Mdi(e);if(y.length===0)return(0,K.jsx)(U,{variant:`body-sm`,tone:`muted`,className:`py-6 text-center`,children:u});let b=jdi(y),x=s===`more`,{shown:S,bar:C,rest:w}=x?Idi(y,{count:_,color:a,palette:i}):Ndi(y,{limit:o,other:l,color:a,palette:i}),T=Ldi(C,w),E=Rdi(S,p),D=()=>m(void 0);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`flex h-2 gap-0.5`,onMouseLeave:D,children:T.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*(zdi(e.key,E)?.3:1)}},e.key))}),v,(0,K.jsxs)(`ul`,{className:`grid min-w-0 grid-cols-1 gap-0.5`,onMouseLeave:D,children:[S.map(e=>(0,K.jsx)(Sdi,{row:e,columns:t,valueWidth:r,share:Vdi(e.share,b),highlighted:p===e.key,dimmed:Bdi(e,p),onHover:()=>m(e.key),LinkComponent:f},e.key)),x&&(0,K.jsx)(Hdi,{shown:Math.min(_,y.length),total:y.length,limit:o,pageSize:c,onMore:()=>g(e=>e+1),onLess:()=>g(0)})]})]})}function qdi({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:H(`shrink-0 text-right whitespace-nowrap`,e.width),children:e.label},e.label))})}var Jdi={agents:Uh.AGENT,workflows:Uh.WORKFLOW_RUN,tools:Uh.TOOL},Ydi=[{label:`Error rate`}],b9={agents:`Agent runs`,workflows:`Workflow runs`,tools:`Tool calls`},Xdi=[{value:`agents`,label:b9.agents},{value:`workflows`,label:b9.workflows},{value:`tools`,label:b9.tools}],Zdi=(e,t)=>J6(t>0?e/t:0);function Qdi({onViewTraces:e,onViewErrors:t,onEntityClick:n}){let[r,i]=(0,G.useState)(`agents`),a=Jdi[r],o=yci({...$7(),queryOptions:{placeholderData:Oy}}),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:q6(e.completed+e.errors),cells:[Zdi(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:b9[r],titleMenu:{value:r,onValueChange:i,options:Xdi},actions:(e||t)&&(0,K.jsxs)(K.Fragment,{children:[e&&(0,K.jsx)(J7,{onClick:()=>e(a)}),t&&(0,K.jsx)(Hsi,{onClick:()=>t(a)})]})};return o.isError?(0,K.jsx)(K7,{...d,children:(0,K.jsx)(q7,{})}):(0,K.jsx)(K7,{...d,total:q6(u),isLoading:o.isLoading,isUpdating:o.isPlaceholderData,children:(0,K.jsx)(G7,{children:(0,K.jsx)(Gdi,{rows:c,columns:Ydi,valueLabel:`Runs`,color:Z6.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:q6(n),cells:[Zdi(t,n)]}},emptyState:`No runs in this range.`,isLoading:o.isLoading},r)})})}var $di=[`mastra_model_total_input_tokens`,`mastra_model_total_output_tokens`],efi=100;function tfi(e){let t=Y(),{filters:n,filterKey:r}=$7();return Iy({queryKey:[`metrics`,`token-spend`,e,r],placeholderData:Oy,queryFn:async()=>{let{groups:r}=await t.getMetricBreakdown({name:$di,groupBy:[e],aggregation:`sum`,orderDirection:`DESC`,limit:efi,filters:n});return r.map(t=>({key:String(t.dimensions[e]??`unknown`),tokens:t.value,cost:t.estimatedCost??0}))}})}var x9={agents:`Usage by agent`,models:`Usage by model`,threads:`Usage by thread`},nfi=[{value:`agents`,label:x9.agents},{value:`models`,label:x9.models},{value:`threads`,label:x9.threads}],rfi={placeholderData:Oy},ifi=[{label:`Tokens`}];function afi(e){let[t,n]=(0,G.useState)(`agents`);return t===`models`?(0,K.jsx)(sfi,{...e,onViewChange:n}):t===`threads`?(0,K.jsx)(cfi,{...e,onViewChange:n}):(0,K.jsx)(ofi,{...e,onViewChange:n})}function ofi(e){let{onAgentClick:t}=e,{data:n=[],isLoading:r,isPlaceholderData:i,isError:a}=_ci({...$7(),queryOptions:rfi}),o=n.map(e=>({key:e.name,cost:e.cost??0,tokens:e.total,onClick:t&&(()=>t(e.name))}));return(0,K.jsx)(lfi,{view:`agents`,...e,rows:o,isLoading:r,isUpdating:i,isError:a})}function sfi(e){let{onModelClick:t}=e,{data:n=[],isLoading:r,isPlaceholderData:i,isError:a}=tfi(`model`),o=n.map(e=>({...e,onClick:t&&(()=>t(e.key))}));return(0,K.jsx)(lfi,{view:`models`,...e,rows:o,isLoading:r,isUpdating:i,isError:a})}function cfi(e){let{onThreadClick:t}=e,{data:n=[],isLoading:r,isPlaceholderData:i,isError:a}=tfi(`threadId`),o=n.map(e=>({...e,onClick:t&&(()=>t(e.key))}));return(0,K.jsx)(lfi,{view:`threads`,...e,rows:o,isLoading:r,isUpdating:i,isError:a})}function lfi({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:Y6(e.cost),cells:[q6(e.tokens)],onClick:e.onClick})),l={title:x9[e],titleMenu:{value:e,onValueChange:t,options:nfi},actions:n&&(0,K.jsx)(J7,{onClick:n})};return o?(0,K.jsx)(K7,{...l,children:(0,K.jsx)(q7,{})}):(0,K.jsx)(K7,{...l,total:Y6(r.reduce((e,t)=>e+t.cost,0)),isLoading:i,isUpdating:a,children:(0,K.jsx)(G7,{children:(0,K.jsx)(Gdi,{rows:c,columns:ifi,valueLabel:`Cost`,color:Z6.green,other:e=>({value:Y6(e.reduce((e,t)=>e+t.share,0)),cells:[q6(e.reduce((e,t)=>e+(s.get(t.key)??0),0))]}),emptyState:`No model usage in this range.`,isLoading:i})})})}var ufi=100;function dfi(){let e=Y(),{filters:t,filterKey:n,timestamp:r}=$7(),{interval:i}=e9(r.start,r.end),a=t9(i);return Iy({queryKey:[`metrics`,`scores`,n,i],placeholderData:Oy,queryFn:async()=>{let n=await e.listScores({filters:t,pagination:{page:0,perPage:ufi}}),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=r9(r.start,r.end,a),u=i9(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 ffi=[Z6.green,Z6.sky,Z6.violet,Z6.teal,Z6.indigo],pfi=e=>e.toFixed(2),mfi=e=>String(+e.toFixed(2));function hfi(e){return e.map(({scorerId:e,name:t},n)=>({dataKey:e,label:t,color:ffi[n%ffi.length]??Z6.neutral}))}function gfi(){let{data:e,isLoading:t,isError:n,isPlaceholderData:r}=dfi(),i=e?.scorers??[],a={title:`Scores`};return n?(0,K.jsx)(K7,{...a,children:(0,K.jsx)(q7,{})}):(0,K.jsx)(K7,{...a,isUpdating:r,children:(0,K.jsx)(G7,{isEmpty:!t&&i.length===0,emptyMessage:`No scores in this range.`,children:(0,K.jsx)(i8,{data:e?.buckets??[],series:hfi(i),height:`fill`,yDomain:[0,1],valueFormatter:pfi,axisFormatter:mfi,isLoading:t,...wKr})})})}function _fi({experiment:e,metrics:t}){let{data:n}=GP({experimentId:e.id,experimentStatus:e.status,queryOptions:{enabled:!!e.id}}),{data:r,isLoading:i}=Pri({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?`—`:lT(new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime())??`—`,l=r[e.id]?.summary,u=w7(l),d=l?.inputTokens===void 0&&l?.outputTokens===void 0?`input + output`:`${C7(l.inputTokens??0)} in · ${C7(l.outputTokens??0)} out`,f=t?.isEnabled?t.data?.avgAgentDurationMs:void 0,p=f==null?void 0:lT(Math.round(f)),m=p?`${p} avg per item`:s?`started ${xT(new Date(s),`date-time`)}`:`not started`;return(0,K.jsxs)(gsi,{children:[t?.isEnabled&&(0,K.jsx)(U7,{label:`Total cost`,icon:hr,value:l?.estimatedCost===void 0?`—`:S7(l.estimatedCost,l.costUnit),detail:`estimated`,isLoading:a}),(0,K.jsx)(U7,{label:`Run duration`,icon:_c,value:c,detail:m}),t?.isEnabled&&(0,K.jsx)(U7,{label:`Total tokens`,icon:Ki,value:u===void 0?`—`:C7(u),detail:d,isLoading:a}),(0,K.jsx)(U7,{label:`Avg score`,icon:Ei,value:o==null?`—`:o.toFixed(3),detail:o==null?`no scores`:`across all scorers`,isLoading:o===void 0})]})}function vfi({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)(Bc,{}),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)(esi,{selectedResults:n,vocabulary:r,onAddTag:e.addTagToSelected,disabled:o})]})]})}var yfi=e=>Math.floor(Math.random()*e);function bfi({messages:e,intervalMs:t=3e3}){let n=e.length,[r,i]=(0,G.useState)(()=>yfi(n));return(0,G.useEffect)(()=>{if(n<2)return;let e=setInterval(()=>i(e=>(e+1+yfi(n-1))%n),t);return()=>clearInterval(e)},[n,t]),n===0?null:(0,K.jsx)(K.Fragment,{children:e[r%n]})}function xfi(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 Sfi=[`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…`],Cfi=`Waiting to start…`;function wfi({experiment:e}){let{status:t,totalItems:n,succeededCount:r,failedCount:i,startedAt:a}=e,o=xfi(),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?lT(u):void 0;return(0,K.jsx)(fw,{variant:`fill`,as:`h2`,iconSlot:(0,K.jsx)($c,{}),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?Cfi:(0,K.jsx)(bfi,{messages:Sfi})}),(0,K.jsxs)(`span`,{className:`tabular-nums`,children:[(0,K.jsxs)(`span`,{children:[s,` / `,n,` `,c,` finished`]}),d&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`span`,{"aria-hidden":!0,children:` · `}),(0,K.jsxs)(`span`,{children:[d,` elapsed`]})]})]})]})})}var Tfi={pending:{icon:(0,K.jsx)(cr,{className:`size-4 text-warning-foreground`}),label:I7.pending},running:{icon:(0,K.jsx)($c,{size:`sm`}),label:I7.running},completed:{icon:(0,K.jsx)(Un,{className:`size-4 text-muted-foreground`}),label:I7.completed},failed:{icon:(0,K.jsx)(er,{className:`size-4 text-destructive-foreground`}),label:I7.failed}};function Efi({status:e,className:t}){let n=Tfi[e]??Tfi.pending;return(0,K.jsxs)(JC,{children:[(0,K.jsx)(YC,{render:(0,K.jsx)(`span`,{tabIndex:0,className:H(`flex shrink-0 items-center`,t),children:n.icon})}),(0,K.jsx)(XC,{children:n.label})]})}var Dfi=()=>{let{experimentId:e}=Bb(),{data:t}=jNt({experimentId:e??``,queryOptions:{enabled:!!e,retryOnMount:!1}});return{experimentId:e,experiment:t}},Ofi=()=>{let{experimentId:e,experiment:t}=Dfi(),n=t?.datasetId??``,{data:r}=xNt({datasetId:n,experimentId:e??``,queryOptions:{enabled:!!(n&&e),retryOnMount:!1}});return r??t};function kfi(){let{experimentId:e,experiment:t}=Dfi();if(!e)return null;let n=e.length>8?`${e.slice(0,8)}...`:e;return t?.name||n}function Afi(){let e=Ofi();return e?.status?(0,K.jsx)(Efi,{status:e.status}):null}function jfi(){let e=Ofi();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)(U,{as:`span`,variant:`caption`,tone:`muted`,className:`whitespace-nowrap tabular-nums`,children:n>0?`${r} · ${n} errored`:r})}function Mfi({datasetId:e,experimentId:t}){let[n,r]=(0,G.useState)(!1),{updateExperimentResult:i}=BP();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?yw(`Tag "${a}" added to ${c} result${c>1?`s`:``}`):yw.error(`Failed to add tag`)},[e,t,n,i]),isPending:n}}function Nfi(e,t){let{data:n}=HP({datasetId:e,queryOptions:{enabled:!!e}});return(0,G.useMemo)(()=>[...new Set([...n?.tags??[],...t.flatMap(e=>e.tags??[])])].sort(),[n?.tags,t])}function Pfi({datasetId:e,experimentId:t,results:n}){let[r,i]=(0,G.useState)(new Set),[a,o]=(0,G.useState)(!1),{updateExperimentResult:s}=BP(),{addTag:c,isPending:l}=Mfi({datasetId:e,experimentId:t}),u=Nfi(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}),yw(`${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 Ffi=[];function S9({crumbs:e,children:t}){return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{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 Ifi(){let{experimentId:e}=Bb(),t=[cF(`/experiments`),{id:`experiment`,Component:kfi,icon:Afi,Action:jfi}],n=zb(),[r,i]=(0,G.useState)(!1),a=D6(),{data:o,isLoading:s,error:c}=jNt({experimentId:e??``,queryOptions:{enabled:!!e}}),l=o?.datasetId??``,{data:u,isLoading:d,error:f}=xNt({datasetId:l,experimentId:e??``,queryOptions:{enabled:!!l&&!!e}}),p=u?.status===`completed`||u?.status===`failed`,{data:m,isLoading:h,setEndOfListElement:g,isFetchingNextPage:_,hasNextPage:v}=CNt({datasetId:l,experimentId:e??``,experimentStatus:u?.status,queryOptions:{enabled:!!l&&!!e&&p}}),{supportsMetrics:y}=v5(),b=Fri({experimentId:e,experimentStatus:u?.status,supportsMetrics:y,queryOptions:{enabled:!!e&&y&&p}}),x=Pfi({datasetId:l,experimentId:e??``,results:m??Ffi}),S=c??f;if(!e||s||d)return null;if(S&&YP(S))return(0,K.jsx)(S9,{crumbs:t,children:(0,K.jsx)(fU,{})});if(S&&XP(S))return(0,K.jsx)(S9,{crumbs:t,children:(0,K.jsx)(dU,{resource:`datasets`})});let C=(0,K.jsx)(S9,{crumbs:t,children:(0,K.jsx)(fw,{titleSlot:`Experiment not found`,descriptionSlot:`No experiment with id "${e}".`,actionSlot:(0,K.jsx)(X,{render:(0,K.jsx)(Zb,{to:`/experiments`}),icon:(0,K.jsx)(Rt,{}),children:`Back to experiments`})})});return S&&ZP(S)?C:S?(0,K.jsx)(S9,{crumbs:t,children:(0,K.jsx)(fw,{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)(qri,{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)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:t}),headerActions:(0,K.jsx)(Zoi,{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)(_fi,{experiment:u,metrics:b}),(0,K.jsxs)(`div`,{className:`grid content-start gap-1`,children:[(0,K.jsx)(vfi,{selection:x}),(0,K.jsx)(hii,{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)(wfi,{experiment:u})]}),(0,K.jsx)(hsi,{withQueryTrace:a.enabled,withFeedback:a.enabled}),(0,K.jsx)(tai,{open:r,onOpenChange:i,experimentId:e,experimentName:u.name??void 0,onSuccess:()=>n(`/experiments`)})]})})}function Lfi({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)(lN,{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:H(Nw,`p-0.5`),children:(0,K.jsx)(Ln,{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)(U,{as:`span`,variant:`caption`,children:e}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>{o(e),i(!0)},className:H(Nw,`p-0.5 opacity-0 transition-opacity group-hover:opacity-100`),title:`Edit tag`,children:(0,K.jsx)(Io,{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)(Bc,{className:`h-3 w-3`})})]})}function Rfi({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)(oN,{open:o,onOpenChange:s,children:[(0,K.jsx)(sN,{asChild:!0,children:(0,K.jsxs)(X,{size:a,icon:(0,K.jsx)(nc,{}),children:[`Tag `,e,` items`]})}),(0,K.jsxs)(cN,{className:`w-56 p-2`,align:`end`,children:[(0,K.jsx)(lN,{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)(U,{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)(Bc,{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)(U,{as:`span`,variant:`caption`,className:`block`,children:[`Create & apply "`,c.trim(),`"`]})})]})]})]})}var zfi=[{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`}],Bfi=`__untagged__`,C9=`all`,Vfi=[{value:`review`,label:`Review queue`},{value:`completed`,label:`Completed`}];function Hfi({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 m=Y(),{paths:h}=gl(),{data:g}=HP({datasetId:e??``,queryOptions:{enabled:!!e}}),{data:_,isLoading:v}=Qii({experimentId:t,targetType:i,targetId:a,experiments:n,isLoadingExperiments:r}),{data:y,isLoading:b}=$ii({experimentId:t,targetType:i,targetId:a,experiments:n,isLoadingExperiments:r}),{updateExperimentResult:x}=BP(),[S,C]=(0,G.useState)(o??null);(0,G.useEffect)(()=>{o!==void 0&&C(o)},[o]);let[w,T]=(0,G.useState)(null),[E,D]=(0,G.useState)(new Set),[O,k]=(0,G.useState)(!1),[A,j]=(0,G.useState)(!1),[M,N]=(0,G.useState)(!1),[P,F]=(0,G.useState)(``),[I,L]=(0,G.useState)(``),[R,ee]=(0,G.useState)(``),[z,B]=(0,G.useState)([]),[V,te]=(0,G.useState)(!1),ne=(0,G.useMemo)(()=>_??[],[_]),re=(0,G.useMemo)(()=>{let e=new Set;if(g?.tags)for(let t of g.tags)e.add(t);for(let t of ne)for(let n of t.tags)e.add(n);return[...e].sort()},[g,ne]),ie=(0,G.useMemo)(()=>w?w===Bfi?ne.filter(e=>e.tags.length===0):ne.filter(e=>e.tags.includes(w)):ne,[ne,w]),ae=(0,G.useMemo)(()=>{let e=new Map,t=0;for(let n of ne){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:C9,label:`All tags`},...t>0?[{value:Bfi,label:`Untagged`}]:[],...n]},[ne]),oe=!!w||O,se=(0,G.useCallback)(()=>{T(null),k(!1),C(null)},[]),ce=(0,G.useCallback)((e,t)=>{let n=ne.find(t=>t.id===e);n?.experimentId&&n?.datasetId&&x.mutate({datasetId:n.datasetId,experimentId:n.experimentId,resultId:n.id,tags:t})},[ne,x]),le=(0,G.useCallback)(e=>{let t=ne.find(t=>t.id===e);D(t=>{let n=new Set(t);return n.delete(e),n}),S===e&&C(null),t?.experimentId&&t?.datasetId&&x.mutate({datasetId:t.datasetId,experimentId:t.experimentId,resultId:t.id,status:null})},[ne,x,S]),ue=(0,G.useCallback)(e=>{let t=ne.find(t=>t.id===e);D(t=>{let n=new Set(t);return n.delete(e),n}),S===e&&C(null),t?.experimentId&&t?.datasetId&&x.mutate({datasetId:t.datasetId,experimentId:t.experimentId,resultId:t.id,status:`complete`})},[ne,x,S]),de=(0,G.useMemo)(()=>{let e=O?y??[]:ie;return!O||!w?e:w===Bfi?e.filter(e=>e.tags.length===0):e.filter(e=>e.tags.includes(w))},[O,y,ie,w]),fe=O?b:!1,pe=(0,G.useMemo)(()=>new Set(de.map(e=>e.id)),[de]),me=(0,G.useMemo)(()=>[...E].filter(e=>pe.has(e)).length,[E,pe]),he=de.length>0&&me===de.length,ge=(0,G.useCallback)(e=>{D(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),_e=(0,G.useCallback)(()=>{D(he?new Set:new Set(de.map(e=>e.id)))},[he,de]),ve=(0,G.useCallback)(e=>{for(let t of E){let n=ne.find(e=>e.id===t);n&&!n.tags.includes(e)&&ce(t,[...n.tags,e])}},[ne,E,ce]),ye=(0,G.useCallback)(e=>{for(let t of E){let n=ne.find(e=>e.id===t);n&&n.tags.includes(e)&&ce(t,n.tags.filter(t=>t!==e))}},[ne,E,ce]),be=(0,G.useCallback)(()=>{for(let e of E)ue(e);D(new Set)},[E,ue]),xe=(0,G.useCallback)(()=>{for(let e of E)le(e);D(new Set)},[E,le]),Se=(0,G.useCallback)(()=>{F(``),N(!0)},[]),Ce=(0,G.useCallback)(async()=>{if(I&&R){j(!0),N(!1);try{let e=ne.filter(e=>E.has(e.id));if(e.length===0){j(!1);return}let t=await m.clusterFailures({modelId:`${I}/${R}`,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:re.length>0?re:void 0,prompt:P||void 0});t.proposedTags&&t.proposedTags.length>0&&(B(t.proposedTags.map(e=>({...e,accepted:!0}))),te(!0))}catch(e){console.error(`Analysis failed:`,e)}finally{j(!1)}}},[I,R,ne,E,m,re,P]),we=(0,G.useCallback)(()=>{for(let e of z){if(!e.accepted)continue;let t=ne.find(t=>t.id===e.itemId);if(t){let n=[...new Set([...t.tags,...e.tags])];ce(t.id,n)}}te(!1)},[z,ne,ce]),Te=(0,G.useCallback)(e=>{C(t=>t===e?null:e)},[]),Ee=(0,G.useMemo)(()=>S?de.find(e=>e.id===S)??null:null,[S,de]),{data:De}=GP({experimentId:Ee?.experimentId??``,queryOptions:{enabled:!!Ee?.experimentId}}),Oe=S?de.findIndex(e=>e.id===S):-1,ke=Oe>0?()=>C(de[Oe-1].id):void 0,Ae=Oe>=0&&Oe<de.length-1?()=>C(de[Oe+1].id):void 0,je=!O&&E.size>0,Me=!!u&&!O&&ie.length>0,Ne=O?`completed`:`review`,Pe=e=>{k(e===`completed`),C(null)},Fe=(0,K.jsxs)(iq,{children:[(0,K.jsx)(iq.Start,{children:c?(0,K.jsxs)(K.Fragment,{children:[s,c({status:Ne,onStatusChange:Pe,tag:w,onTagChange:T,tagOptions:ae.filter(e=>e.value!==C9)})]}):(0,K.jsxs)(K.Fragment,{children:[s,(0,K.jsxs)(tj,{value:Ne,onValueChange:e=>Pe(e===`completed`?`completed`:`review`),children:[(0,K.jsx)(rj,{"aria-label":`Status`,size:`md`,className:`whitespace-nowrap`,children:(0,K.jsx)(nj,{placeholder:`Select an option`})}),(0,K.jsx)(ij,{children:Vfi.map(e=>(0,K.jsx)(aj,{value:e.value,children:e.label},e.value))})]}),ae.length>1&&(0,K.jsxs)(tj,{value:w??C9,onValueChange:e=>T(e===C9?null:e),children:[(0,K.jsx)(rj,{"aria-label":`Tags`,size:`md`,className:`whitespace-nowrap`,children:(0,K.jsx)(nj,{placeholder:`Select an option`})}),(0,K.jsx)(ij,{children:ae.map(e=>(0,K.jsx)(aj,{value:e.value,children:e.label},e.value))})]}),oe&&(0,K.jsx)(X,{onClick:se,size:`sm`,variant:`default`,icon:(0,K.jsx)(Bc,{}),children:`Reset`})]})}),(je||l||Me)&&(0,K.jsxs)(iq.End,{children:[l,Me&&(0,K.jsxs)(X,{size:`md`,onClick:()=>u?.(ie.map(e=>({input:e.input,output:e.output}))),children:[(0,K.jsx)(QC,{size:`xs`,children:(0,K.jsx)(Ei,{})}),`Create scorer`]}),je&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Rfi,{size:`md`,selectedCount:E.size,vocabulary:re,onApplyTag:ve,onRemoveTag:ye,onNewTag:e=>ve(e)}),(0,K.jsx)(X,{variant:`primary`,onClick:be,icon:(0,K.jsx)(Hn,{}),children:`Mark as reviewed`}),(0,K.jsxs)(gE,{children:[(0,K.jsx)(gE.Trigger,{asChild:!0,children:(0,K.jsx)(X,{size:`icon-md`,disabled:A,"aria-label":`More actions`,children:A?(0,K.jsx)($c,{className:`h-4 w-4`}):(0,K.jsx)(Ar,{})})}),(0,K.jsxs)(gE.Content,{align:`end`,children:[(0,K.jsxs)(gE.Item,{onSelect:Se,children:[(0,K.jsx)(QC,{size:`xs`,children:(0,K.jsx)(Gs,{})}),`Analyze`]}),(0,K.jsx)(gE.Separator,{}),(0,K.jsxs)(gE.Item,{onSelect:xe,children:[(0,K.jsx)(QC,{size:`xs`,children:(0,K.jsx)(xc,{})}),`Remove from queue`]})]})]})]})]})]});if(v)return(0,K.jsxs)(Jw,{breadcrumbs:d,actionRow:Fe,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)($c,{fill:!0})]});let Ie=(0,K.jsx)(psi,{withQueryTrace:f,withFeedback:p,result:Ee??void 0,title:`Review item ${Ee?.id??``}`,scores:Ee?De?.[Ee.itemId]:void 0,experimentLink:Ee?.experimentId?h.experimentItemLink(Ee.experimentId,Ee.itemId):void 0,onComplete:O||!Ee?void 0:()=>ue(Ee.id),onPrevious:ke,onNext:Ae,onClose:()=>C(null)});return(0,K.jsxs)(Jw,{breadcrumbs:d,actionRow:Fe,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(UE,{open:M,onOpenChange:N,children:(0,K.jsxs)(WE,{children:[(0,K.jsxs)(GE,{children:[(0,K.jsx)(JE,{children:`Analyze Items`}),(0,K.jsx)(YE,{children:`Use an LLM to automatically suggest tags for the selected items.`})]}),(0,K.jsxs)(qE,{children:[(0,K.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[(0,K.jsxs)(OA,{className:`gap-1`,children:[(0,K.jsx)(AA,{children:`Provider`}),(0,K.jsx)(hq,{value:I,onValueChange:L})]}),(0,K.jsxs)(OA,{className:`gap-1`,children:[(0,K.jsx)(AA,{children:`Model`}),(0,K.jsx)(gq,{llmId:I,value:R,onValueChange:ee})]})]}),(0,K.jsxs)(U,{variant:`meta`,tone:`muted`,children:[E.size,` item`,E.size===1?``:`s`,` will be analyzed`]}),(0,K.jsxs)(OA,{className:`gap-1`,children:[(0,K.jsx)(AA,{children:`Instructions (optional)`}),(0,K.jsx)(cj,{className:`text-caption`,value:P,onChange:e=>F(e.target.value),placeholder:`E.g., Focus on safety issues and factual errors...`,rows:3})]})]}),(0,K.jsxs)(KE,{children:[(0,K.jsx)(XE,{children:`Cancel`}),(0,K.jsx)(HE,{onConfirm:Ce,disabled:!I||!R||A,children:`Analyze`})]})]})}),(0,K.jsx)(UE,{open:V,onOpenChange:te,children:(0,K.jsxs)(WE,{size:`lg`,children:[(0,K.jsxs)(GE,{children:[(0,K.jsx)(JE,{children:`Review Proposed Tags`}),(0,K.jsxs)(YE,{children:[z.filter(e=>e.accepted).length,` of `,z.length,` proposals selected`]})]}),(0,K.jsx)(qE,{children:z.map((e,t)=>{let n=ne.find(t=>t.id===e.itemId);return(0,K.jsx)(`div`,{className:H(`rounded-lg border p-3`,!e.accepted&&`opacity-50`),children:(0,K.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,K.jsx)(iN,{checked:e.accepted,onCheckedChange:e=>B(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)(U,{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)(Lfi,{tag:e,onRename:e=>B(r=>r.map((r,i)=>i===t?{...r,tags:r.tags.map((t,r)=>r===n?e:t)}:r)),onRemove:()=>B(e=>e.map((e,r)=>r===t?{...e,tags:e.tags.filter((e,t)=>t!==n)}:e))},`${e}-${n}`))}),e.reason&&(0,K.jsx)(U,{variant:`meta`,tone:`muted`,className:`mt-1 block italic`,children:e.reason})]})]})},e.itemId)})}),(0,K.jsxs)(KE,{children:[(0,K.jsx)(XE,{children:`Cancel`}),(0,K.jsxs)(HE,{onConfirm:we,disabled:z.filter(e=>e.accepted).length===0,children:[`Accept `,z.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:fe?(0,K.jsx)($c,{fill:!0}):de.length===0?(0,K.jsx)(fw,{titleSlot:O?`No completed reviews yet`:`No items to review`,descriptionSlot:O?`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)(uii,{results:de,isLoading:!1,featuredResultId:S,onResultClick:Te,columns:zfi,selectedIds:O?void 0:E,onToggleSelect:O?void 0:ge,onToggleSelectAll:O?void 0:_e})}),Ie]})]})}var Ufi=`experiment`,Wfi=`status`,Gfi=[{value:`review`,label:`Review queue`},{value:`completed`,label:`Completed`}],Kfi=[{id:`is`,label:`is`}],qfi=({targetType:e,targetId:t,experimentId:n,status:r,tag:i})=>{let a=r9r({targetType:e,targetId:t});return n&&a.push(X5(Ufi,n)),r!==`review`&&a.push(X5(Wfi,r)),i&&a.push(X5(`tag`,i)),a},Jfi=e=>({...i9r(e),experimentId:Z5(e,Ufi),status:Z5(e,`status`)===`completed`?`completed`:`review`,tag:Z5(e,`tag`)||null});function Yfi({targetType:e,targetId:t,experimentId:n,status:r,tag:i,experiments:a,tagOptions:o,onChange:s}){let c=a9r(e),l=(0,G.useMemo)(()=>[...c,{id:Ufi,label:`Experiment`,icon:mi,color:pF(`pink`),strict:!0,suggestions:a.map(e=>({value:e.id,label:sai(e)}))},{id:Wfi,label:`Status`,icon:Hn,color:pF(`orange`),strict:!0,suggestions:Gfi},{id:`tag`,label:`Tag`,icon:nc,color:pF(`pink`),strict:!0,hidden:o.length===0,suggestions:o}],[c,a,o]),u=(0,G.useMemo)(()=>qfi({targetType:e,targetId:t,experimentId:n,status:r,tag:i}),[e,t,n,r,i]);return(0,K.jsxs)(W6,{fields:l,operators:Kfi,value:u,onValueChange:e=>s(Jfi(e)),createItemId:e=>e,"aria-label":`Review queue filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(W6.Chips,{}),(0,K.jsx)(W6.Input,{placeholder:`Filter review queue…`})]})}var w9=[cF(`/experiments`),cF(`/experiments/review-queue`)],Xfi=`experiment`,Zfi=`review`;function Qfi(){let[e,t]=Qb(),n=e.get($5),r=$7r(n)?n:``,i=r?e.get(`targetId`)??``:``,a=e.get(Xfi),o=e.get(Zfi),{Link:s,paths:c}=gl(),l=D6(),{data:u,error:d}=Lri({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($5,e.targetType):n.delete($5),s?n.set(e7,s):n.delete(e7),o?n.set(Xfi,o):n.delete(Xfi),n.delete(Zfi),n},{replace:!0})};return d&&YP(d)?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:w9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(fU,{variant:`fill`})]}):d&&XP(d)?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:w9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(dU,{variant:`fill`,resource:`experiments`})]}):d?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:w9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(fw,{tone:`error`,variant:`fill`,titleSlot:`Failed to load experiments`,descriptionSlot:d.message})]}):(0,K.jsx)(Hfi,{withQueryTrace:l.enabled,withFeedback:l.enabled,breadcrumbs:(0,K.jsx)(DP,{crumbs:w9}),datasetId:f?.datasetId??void 0,experimentId:a??void 0,targetType:r,targetId:i,featuredItemId:o,renderFilters:e=>(0,K.jsx)(Yfi,{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 $fi({connection:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return(0,K.jsxs)(`li`,{className:`flex items-center justify-between border-b py-2`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(U,{as:`p`,variant:`caption`,font:`mono`,children:e.connectionId}),(0,K.jsxs)(U,{as:`p`,variant:`caption`,tone:`muted`,children:[e.label??`(no label)`,` · `,e.status,e.scope?` · ${e.scope}`:``,t&&e.authorId?` · author: ${e.authorId}`:``]})]}),(0,K.jsx)(`button`,{type:`button`,className:`text-destructive-foreground underline disabled:opacity-50`,onClick:r,disabled:n,children:`Disconnect`})]})}function epi({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return(0,K.jsx)(`ul`,{className:`space-y-1`,children:e.map(e=>(0,K.jsx)($fi,{connection:e,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(e.connectionId)},e.connectionId))})}function tpi({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)(U,{as:`h3`,variant:`subheading`,tone:`ink`,"data-testid":`integration-author-group-${e}`,children:e===`shared`?`Shared`:`Owned by ${e}`}),(0,K.jsx)(epi,{connections:i,isAdmin:t,disconnectPending:n,onDisconnect:r})]},e))})}function npi({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)(U,{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)(tpi,{groups:r,isAdmin:i,disconnectPending:s,onDisconnect:l}):(0,K.jsx)(epi,{connections:n,isAdmin:i,disconnectPending:s,onDisconnect:l}),c?(0,K.jsx)(`p`,{className:`text-destructive-foreground`,children:String(c)}):null]})}function rpi({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)(OA,{invalid:!!o,disabled:a,children:[(0,K.jsx)(AA,{children:`Provider`}),(0,K.jsxs)(tj,{value:n,onValueChange:f,children:[(0,K.jsx)(rj,{children:(0,K.jsx)(nj,{placeholder:a?`Loading providers…`:`Select provider`})}),(0,K.jsx)(ij,{children:e.map(e=>(0,K.jsx)(aj,{value:e.id,children:`${e.displayName??e.name} (${e.id})`},e.id))})]}),(0,K.jsx)(MA,{children:o?String(o):void 0})]}),(0,K.jsxs)(OA,{invalid:!!c,disabled:!n||s,children:[(0,K.jsx)(AA,{children:`Toolkit`}),(0,K.jsxs)(tj,{value:r,onValueChange:p,children:[(0,K.jsx)(rj,{children:(0,K.jsx)(nj,{placeholder:s?`Loading toolkits…`:`Select toolkit`})}),(0,K.jsx)(ij,{children:t.map(e=>(0,K.jsx)(aj,{value:e.slug,children:`${e.name} (${e.slug})`},e.slug))})]}),(0,K.jsx)(MA,{children:c?String(c):void 0})]}),(0,K.jsxs)(OA,{disabled:!n||!r,children:[(0,K.jsx)(AA,{children:`Label (optional)`}),(0,K.jsx)(lN,{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)(HA,{variant:`destructive`,children:String(u)})}):null,d?(0,K.jsxs)(HA,{variant:`success`,children:[`Authorized: `,d.connectionId,` (status: `,d.status,`)`]}):null]})}var ipi=e=>e.authorId?.trim()||`shared`,api=(e,t)=>{if(!t||new Set(e.map(ipi)).size<=1)return null;let n=new Map;for(let t of e){let e=ipi(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},opi=[`*`,`tool-providers:*`,`tool-providers:admin`];function spi(){let{data:e}=Hy();return e?.permissions?.some(e=>opi.includes(e))??!1}var cpi=[{id:`integrations`,label:`Integrations`}];function lpi(){let[e,t]=(0,G.useState)(``),[n,r]=(0,G.useState)(``),[i,a]=(0,G.useState)(``),o=bq(),s=Sq({providerId:e||null,queryOptions:{enabled:!!e}}),c=wAn({providerId:e||null,toolkit:n||null}),l=SAn(),u=CAn(),d=spi(),f=o.data?.providers??[],p=s.data?.data??[],m=(0,G.useMemo)(()=>c.data?.items??[],[c.data?.items]),h=(0,G.useMemo)(()=>api(m,d),[m,d]);return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:cpi}),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)(U,{as:`p`,variant:`body`,tone:`muted`,children:`Minimal page to verify the ToolProvider backend. Pick a provider and toolkit, then connect.`}),(0,K.jsx)(rpi,{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)(npi,{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 upi({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)(cZ,{className:`h-10 w-10`}),(0,K.jsx)(U,{as:`h1`,variant:`heading`,tone:`ink`,children:e})]}),t,n,r]})}function dpi({redirectUri:e,onSuccess:t,initialMode:n=`signin`,errorMessage:r}){let{data:i,isLoading:a}=Vy(),{mutate:o,isPending:s,error:c}=NBe(),{mutate:l,isPending:u,error:d}=FBe(),{mutate:f,isPending:p}=IBe(),[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`,T=S.sso,E=S.signUpEnabled!==!1,D=m===`signin`||!E,O=D?s:u,k=D?c:d,A=()=>{t?t():e?window.location.href=e:window.location.href=lZ(`/`)},j=e=>{e.preventDefault(),D?o({email:v,password:b},{onSuccess:A}):l({email:v,password:b,name:g||void 0},{onSuccess:A})},M=()=>{f({redirectUri:e},{onSuccess:e=>{window.location.href=e.url}})},N=()=>{h(D?`signup`:`signin`)},P=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)(ja,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}),(0,K.jsx)(U,{tone:`muted`,children:S.description})]}):null;return(0,K.jsxs)(upi,{title:D?`Sign in to Mastra Studio`:`Create your account`,description:P,errorBanner:r?(0,K.jsx)(`div`,{role:`alert`,children:(0,K.jsx)(HA,{variant:`destructive`,children:r})}):null,children:[w&&(0,K.jsxs)(lU,{onSubmit:j,children:[!D&&(0,K.jsxs)(OA,{children:[(0,K.jsx)(AA,{children:`Name`}),(0,K.jsx)(lN,{name:`name`,type:`text`,autoComplete:`name`,value:g,onChange:e=>_(e.target.value),placeholder:`Your name`,variant:`default`,size:`lg`})]}),(0,K.jsxs)(OA,{children:[(0,K.jsx)(AA,{required:!0,children:`Email`}),(0,K.jsx)(lN,{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)(MA,{})]}),(0,K.jsxs)(OA,{children:[(0,K.jsx)(AA,{required:!0,children:`Password`}),(0,K.jsx)(lN,{name:`password`,type:`password`,autoComplete:D?`current-password`:`new-password`,value:b,onChange:e=>x(e.target.value),placeholder:D?`Enter your password`:`Create a password`,required:!0,variant:`default`,size:`lg`}),(0,K.jsx)(MA,{})]}),k?(0,K.jsx)(`div`,{role:`alert`,children:(0,K.jsx)(HA,{variant:`destructive`,children:k.message})}):null,(0,K.jsx)(X,{icon:(0,K.jsx)(Na,{}),type:`submit`,disabled:O,className:`w-full`,size:`lg`,children:O?D?`Signing in...`:`Creating account...`:D?`Sign in`:`Create account`}),E&&(0,K.jsxs)(`div`,{className:`text-center`,children:[(0,K.jsx)(U,{as:`span`,variant:`body`,tone:`muted`,children:D?`Don't have an account? `:`Already have an account? `}),(0,K.jsx)(`button`,{type:`button`,onClick:N,className:`text-foreground hover:underline`,children:(0,K.jsx)(U,{as:`span`,variant:`body`,className:`block`,children:D?`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)(U,{as:`span`,variant:`body`,tone:`muted`,className:`bg-sidebar px-2`,children:`or continue with`})})]}),C&&T&&(0,K.jsxs)(X,{onClick:M,disabled:p,className:`w-full`,size:`lg`,children:[T.icon&&(0,K.jsx)(`span`,{className:`mr-2`,children:T.icon}),p?`Redirecting...`:T.text||`Sign in`]})]})}function fpi(){let[e]=Qb(),t=zb(),n=e.get(`redirect`)||`/`,r=e.get(`mode`)===`signup`?`signup`:`signin`,i=e.get(`error_description`)||e.get(`error`)||null;return(0,K.jsx)(dpi,{redirectUri:n,onSuccess:()=>{n.startsWith(`http`)?window.location.href=n:t(n,{replace:!0})},initialMode:r,errorMessage:i})}function ppi({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)(Bc,{}),children:`Clear`}),a&&(0,K.jsxs)(gE,{children:[(0,K.jsx)(gE.Trigger,{asChild:!0,children:(0,K.jsx)(X,{disabled:e,size:`icon-md`,"aria-label":`More filter actions`,children:(0,K.jsx)(jr,{})})}),(0,K.jsxs)(gE.Content,{align:`end`,children:[n&&(0,K.jsxs)(gE.Item,{onSelect:()=>n(),children:[(0,K.jsx)(Bc,{}),`Remove all filters`]}),n&&(r||i)&&(0,K.jsx)(gE.Separator,{}),r&&(0,K.jsxs)(gE.Item,{onSelect:()=>r(),children:[(0,K.jsx)(ys,{}),`Save filters for next time`]}),i&&(0,K.jsxs)(gE.Item,{onSelect:()=>i(),children:[(0,K.jsx)(xc,{}),`Remove saved filters`]})]})]})]})}var mpi=H(n2e,`min-w-0`);function hpi({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:mpi,onClick:r,children:[(0,K.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:n}),t&&(0,K.jsx)(`span`,{className:IT,children:(0,K.jsx)(Ln,{})})]})}function gpi({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:BT.container,children:[(0,K.jsx)(Ss,{className:BT.icon}),(0,K.jsx)(`input`,{type:`text`,value:r,onChange:e=>i(e.target.value),placeholder:`Search ${e.label.toLowerCase()}...`,className:BT.input,...oj,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:H(a2e,`m-1`),children:[(0,K.jsx)($c,{size:`sm`,className:`size-3 text-muted-foreground`}),`Loading options…`]}):o.length===0?(0,K.jsx)(`div`,{className:H(a2e,`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)(hpi,{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)(hpi,{role:`radio`,checked:c===t.value,label:t.label,onClick:()=>n(e.id,t.value)},t.value)),!e.omitAnyOption&&(0,K.jsx)(hpi,{role:`radio`,checked:c===`Any`,label:`Any`,onClick:()=>n(e.id,`Any`)})]})})]})}function _pi(e){return Array.isArray(e)?e.length===0?`Any`:e.join(`, `):e}var vpi=`This filter is set by the current context and cannot be removed here.`;function ypi(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:_pi(t)}function bpi({field:e,value:t,tooltipContent:n}){let r=ypi(e,t),i=`${e.label} filter is locked by context`;return(0,K.jsx)(qC,{delayDuration:150,children:(0,K.jsxs)(JC,{children:[(0,K.jsx)(YC,{asChild:!0,children:(0,K.jsxs)(oU,{"data-locked-field-id":e.id,"data-property-filter-pill":`locked`,tabIndex:0,"aria-label":i,children:[(0,K.jsx)(sU,{children:e.label}),(0,K.jsx)(sU,{children:`is`}),(0,K.jsx)(sU,{children:r}),(0,K.jsx)(sU,{children:(0,K.jsx)(ja,{})})]})}),(0,K.jsx)(XC,{children:n})]})})}function xpi({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)(oU,{children:[(0,K.jsx)(sU,{children:e.label}),(0,K.jsx)(sU,{children:`is`}),(0,K.jsx)(lN,{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)(Bc,{})})]})}function Spi({field:e,token:t,tokens:n,onChange:r,onRemove:i,disabled:a}){let[o,s]=(0,G.useState)(!1);return(0,K.jsxs)(oU,{children:[(0,K.jsx)(sU,{children:e.label}),(0,K.jsx)(sU,{children:`is`}),(0,K.jsxs)(oN,{open:o,onOpenChange:s,children:[(0,K.jsx)(sN,{asChild:!0,children:(0,K.jsx)(X,{type:`button`,disabled:a,children:_pi(t.value)})}),(0,K.jsx)(cN,{align:`start`,sideOffset:4,className:`w-64 p-0`,"data-pick-multi-panel":!0,children:(0,K.jsx)(gpi,{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)(Bc,{})})]})}function Cpi({fields:e,tokens:t,onTokensChange:n,disabled:r,autoFocusFieldId:i,lockedFieldIds:a,lockedTooltipContent:o=vpi}){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)(bpi,{field:u,value:n.value,tooltipContent:o},`${n.fieldId}-${a}`):u.kind===`text`&&!Array.isArray(n.value)?(0,K.jsx)(xpi,{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)(Spi,{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)(oU,{children:[(0,K.jsx)(sU,{children:u.label}),(0,K.jsx)(sU,{children:`is`}),(0,K.jsx)(sU,{children:_pi(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)(Bc,{})})]},`${n.fieldId}-${a}`):null})})}var wpi=(0,G.forwardRef)((e,t)=>(0,K.jsx)(`button`,{type:`button`,role:`menuitem`,"data-filter-item":``,ref:t,...e}));wpi.displayName=`FilterMenuButton`;function Tpi({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,m]=(0,G.useState)([]),[h,g]=(0,G.useState)(),[_,v]=(0,G.useState)(),y=(0,G.useRef)(!1),b=(0,G.useCallback)(e=>{v(t=>t===e?void 0:e)},[]),x=(0,G.useCallback)(()=>v(void 0),[]);(0,G.useEffect)(()=>{l||v(void 0)},[l]);let S=(0,G.useMemo)(()=>c.find(e=>e.id===d),[c,d]),C=(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]),w=(0,G.useCallback)(()=>{f(void 0),m([]),g(void 0)},[]);(0,G.useEffect)(()=>{l||w()},[l,w]);let T=(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]),E=(0,G.useCallback)(()=>{S?C.has(S.id)?g(`Remove the existing ${S.label} filter before adding another.`):p.length===0?g(`Choose at least one ${S.label.toLowerCase()} value.`):(n([...t,{fieldId:S.id,value:p}]),u(!1)):g(`Choose a property first.`)},[p,n,S,C,t]);return(0,K.jsxs)(oN,{open:l,onOpenChange:u,children:[(0,K.jsx)(sN,{asChild:!0,children:(0,K.jsx)(X,{size:a,disabled:i,icon:(0,K.jsx)(ha,{}),children:r})}),(0,K.jsx)(cN,{align:`start`,sideOffset:4,className:H(`w-64`,S?`p-3`:`p-1`),initialFocus:!1,finalFocus:()=>!y.current||(y.current=!1,!1),children:(0,K.jsxs)(`div`,{className:H(`grid`,S&&`gap-3`),children:[S&&(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`button`,{type:`button`,"aria-label":`Back to properties`,className:H(`text-muted-foreground hover:text-foreground`,`transition-[color] duration-fast ease-out-custom motion-reduce:transition-none`),onClick:w,children:(0,K.jsx)(Rt,{className:`size-4`})}),(0,K.jsx)(Mee,{className:`size-4 shrink-0 text-muted-foreground`}),(0,K.jsx)(U,{as:`span`,variant:`caption`,tone:`muted`,children:`${S.label} · is`})]}),!S&&(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=C.has(e.id);return e.kind===`pick-multi`?(0,K.jsx)(Epi,{field:e,tokens:t,onChange:T,open:_===e.id,onToggle:b,onClose:x},e.id):(0,K.jsxs)(wpi,{className:H(n2e,`group`),disabled:r,onClick:()=>{g(void 0),e.kind===`text`?(n([...t,{fieldId:e.id,value:``}]),o?.(e.id),y.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:H(FT,`text-muted-foreground opacity-0 group-hover:opacity-100 group-focus:opacity-100`),children:(0,K.jsx)(Yo,{})})]},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.`})})}),S&&(0,K.jsxs)(OA,{invalid:!!h,children:[(0,K.jsx)(EP,{multiple:!0,options:S.options??[],value:p,onValueChange:e=>{m(e),g(void 0)},placeholder:S.placeholder??`Choose ${S.label}`,searchPlaceholder:`Search ${S.label.toLowerCase()}...`,emptyText:S.emptyText??`No option found.`,size:`md`,"aria-label":S.label}),(0,K.jsx)(MA,{children:h})]}),S&&(0,K.jsxs)(`div`,{className:`flex items-center justify-end gap-2`,children:[(0,K.jsx)(X,{icon:(0,K.jsx)(Bc,{}),variant:`ghost`,size:`md`,onClick:()=>u(!1),children:`Cancel`}),(0,K.jsx)(X,{icon:(0,K.jsx)(ha,{}),size:`md`,onClick:E,children:`Add filter`})]})]})})]})}function Epi({field:e,tokens:t,onChange:n,open:r,onToggle:i,onClose:a}){let o=(0,G.useRef)(null);return(0,K.jsxs)(oN,{open:r,onOpenChange:t=>{t?i(e.id):a()},children:[(0,K.jsx)(sN,{asChild:!0,children:(0,K.jsxs)(wpi,{className:n2e,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)(pt,{className:`text-muted-foreground`}),(0,K.jsx)(`span`,{className:`truncate`,children:e.label}),!r&&(0,K.jsx)(`span`,{className:H(FT,`text-muted-foreground`),children:(0,K.jsx)(pt,{})})]})}),(0,K.jsx)(cN,{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)(gpi,{field:e,tokens:t,onChange:n})})]})}function Dpi({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:i,onNext:a,depth:o}){let s=e?ST(e.timestamp)??``:``;return(0,K.jsx)(zZ,{open:!!e,onClose:t,title:e?`Log ${s}`:`Log`,depth:o,children:e&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(zZ.Header,{children:[(0,K.jsx)(zZ.CloseButton,{onClick:t}),(0,K.jsxs)(zZ.Heading,{children:[`Log · `,s]}),(0,K.jsx)(zZ.HeaderActions,{children:(0,K.jsx)(zZ.NextPrevNav,{onPrevious:i,onNext:a,previousLabel:`Go to previous log`,nextLabel:`Go to next log`})})]}),(0,K.jsx)(zZ.Content,{children:(0,K.jsxs)(`div`,{className:`grid gap-6 p-2`,children:[(0,K.jsxs)(T2,{children:[e.entityType&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T2.Key,{children:`Entity Type`}),(0,K.jsx)(T2.Value,{children:e.entityType})]}),e.entityName&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T2.Key,{children:`Entity Name`}),(0,K.jsx)(T2.Value,{children:e.entityName})]}),e.serviceName&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T2.Key,{children:`Service`}),(0,K.jsx)(T2.Value,{children:e.serviceName})]}),e.environment&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T2.Key,{children:`Environment`}),(0,K.jsx)(T2.Value,{children:e.environment})]}),e.source&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T2.Key,{children:`Source`}),(0,K.jsx)(T2.Value,{children:e.source})]}),e.metadata&&Object.entries(e.metadata).map(([e,t])=>(0,K.jsxs)(G.Fragment,{children:[(0,K.jsx)(T2.Key,{children:e}),(0,K.jsx)(T2.Value,{children:String(t)})]},e))]}),(0,K.jsx)(zZ.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)(oU,{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)(U,{as:`span`,variant:`caption`,tone:`faint`,className:`ml-auto min-w-0 truncate`,children:[`# `,e.traceId]})]}),(0,K.jsx)(fT,{content:e.traceId,tooltip:`Copy trace ID to clipboard`})]}),e.spanId&&(0,K.jsxs)(oU,{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)(U,{as:`span`,variant:`caption`,tone:`faint`,className:`ml-auto min-w-0 truncate`,children:[`# `,e.spanId]})]}),(0,K.jsx)(fT,{content:e.spanId,tooltip:`Copy span ID to clipboard`})]})]}),e.data&&Object.keys(e.data).length>0&&(0,K.jsx)(zZ.CodeSection,{title:`Data`,codeStr:JSON.stringify(e.data,null,2)})]})})]})})}function Opi({error:e,resource:t,errorTitle:n}){if(YP(e))return(0,K.jsx)(fU,{});if(XP(e))return(0,K.jsx)(dU,{resource:t});if($P(e))return(0,K.jsx)(fw,{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(QP(e,`logs`))return(0,K.jsx)(fw,{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)(fw,{tone:`error`,titleSlot:n,descriptionSlot:r??`Unknown error`})}var kpi={debug:`neutral`,info:`info`,warn:`warning`,error:`destructive`,fatal:`destructive`};function Api({level:e}){return(0,K.jsx)(gU,{children:(0,K.jsx)(hT,{variant:kpi[e],children:e})})}function jpi({entityType:e,className:t}){let n=H(`size-3.5 shrink-0 text-placeholder`,t);switch(e.toLowerCase()){case`agent`:return(0,K.jsx)(nF,{className:n,"aria-hidden":!0});case`workflow`:case`workflow_run`:return(0,K.jsx)(aP,{className:n,"aria-hidden":!0});case`tool`:return(0,K.jsx)(oF,{className:n,"aria-hidden":!0});default:return null}}function Mpi({entityType:e,entityName:t}){return(0,K.jsxs)(gU,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(jpi,{entityType:e??``}),t?(0,K.jsx)(U,{as:`span`,variant:`body-sm`,className:`min-w-0 truncate`,children:t}):`-`]})}function Npi({message:e}){return(0,K.jsx)(gU,{className:`min-w-0 truncate font-mono text-body-sm text-muted-foreground`,children:e})}function Ppi({data:e}){if(!e||Object.keys(e).length===0)return(0,K.jsx)(gU,{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)(yU,{font:`mono`,children:t})}var T9=Object.assign(SU,{Top:DU,TopCell:wU,SortableTopCell:EU,TopCellWithTooltip:TU,TopCellSmart:mgn,RowWrapper:lgn,RowButton:CU,RowLink:sgn,Spacer:bgn,NoMatch:xU,DateCell:Phn,TimeCell:Ihn,LevelCell:Api,EntityCell:Mpi,MessageCell:Npi,DataCell:Ppi,NextPageLoading:bU}),Fpi=`6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)`,Ipi=36,Lpi=8;function Rpi({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=PYr({count:e.length,getScrollElement:()=>u.current,estimateSize:()=>Ipi,overscan:Lpi}),{getRowProps:f}=$X({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)(OU,{columns:Fpi,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)(T9,{columns:Fpi,scrollRef:u,className:`min-w-0`,fit:`container`,children:[(0,K.jsxs)(T9.Top,{children:[l?(0,K.jsx)(T9.SortableTopCell,{sortKey:`timestamp`,sort:c,onSortChange:l,children:`Date`}):(0,K.jsx)(T9.TopCell,{children:`Date`}),(0,K.jsx)(T9.TopCell,{children:`Time`}),(0,K.jsx)(T9.TopCell,{children:`Level`}),(0,K.jsx)(T9.TopCell,{children:`Entity`}),(0,K.jsx)(T9.TopCell,{children:`Message`}),(0,K.jsx)(T9.TopCell,{children:`Data`})]}),e.length===0?(0,K.jsx)(T9.NoMatch,{message:`No logs match your search`}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T9.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)(T9.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)(T9.DateCell,{timestamp:n.timestamp}),(0,K.jsx)(T9.TimeCell,{timestamp:n.timestamp}),(0,K.jsx)(T9.LevelCell,{level:n.level}),(0,K.jsx)(T9.EntityCell,{entityType:n.entityType,entityName:n.entityName}),(0,K.jsx)(T9.MessageCell,{message:n.message}),(0,K.jsx)(T9.DataCell,{data:n.data})]},r)}),(0,K.jsx)(T9.Spacer,{height:_})]}),(0,K.jsx)(T9.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:i})]})}function zpi({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=>Bpi(e,a));return l?(0,K.jsxs)(`div`,{className:H(`grid grid-cols-[1fr_auto] items-start gap-3`),children:[(0,K.jsx)(Cpi,{fields:a,tokens:o,onTokensChange:s,disabled:i,autoFocusFieldId:c}),l&&(0,K.jsx)(ppi,{disabled:i,onClear:u?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]}):null}function Bpi(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 Vpi={"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`},Hpi=`Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.`;function Upi({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!==`all`&&e!==`custom`?{title:`No logs for ${Vpi[e]}`,description:Hpi}:t&&n?{title:`No logs between ${xT(t,`date-time`)} and ${xT(n,`date-time`)}`,description:Hpi}:t?{title:`No logs since ${xT(t,`date-time`)}`,description:Hpi}:{title:`No logs yet`,description:`Logs will appear here once agents, workflows, or tools are executed.`}}var Wpi=({datePreset:e,dateFrom:t,dateTo:n}={})=>{let{title:r,description:i}=Upi({datePreset:e,dateFrom:t,dateTo:n});return(0,K.jsx)(fw,{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)(Lr,{}),children:`Logging documentation`}),variant:`fill`})},Gpi=`Filters setting for Logs saved`,Kpi=`Filters setting for Logs cleared up`;function qpi(e,t,n){let{storageKey:r,messages:i,skipHydration:a}=n??{},[o,s]=(0,G.useState)(()=>f2r(r)!==null),c=(0,G.useCallback)(()=>{u2r(e,r),s(!0);let t=i?.saved??Gpi;t!==!1&&yw.success(t)},[e,r,i?.saved]),l=(0,G.useCallback)(()=>{d2r(r),s(!1);let e=i?.cleared??Kpi;e!==!1&&yw.success(e)},[r,i?.cleared]),u=(0,G.useRef)(!1);return(0,G.useEffect)(()=>{if(a||u.current||(u.current=!0,p2r(e)))return;let n=f2r(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 Jpi(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 Ypi(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,Jpi(`${e}${n.message??``}${n.data?JSON.stringify(n.data):``}`))}return t}function Xpi(e,t,n,r){let i=(0,G.useMemo)(()=>Ypi(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 Zpi=`logId`,Qpi=`traceId`,$pi=`spanId`,E9=864e5,emi={"last-24h":E9,"last-3d":3*E9,"last-7d":7*E9,"last-14d":14*E9,"last-30d":30*E9};function D9(e){e.delete(Zpi),e.delete(Qpi),e.delete($pi)}function tmi(e,t,n){let{onRemoveAll:r}=n??{},i=(0,G.useMemo)(()=>{let t=e.get(i5);return t&&s2r.has(t)?t:i2r},[e]),a=e.get(a5),o=e.get(o5),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=emi[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(Zpi),d=e.get(Qpi),f=e.get($pi),p=(0,G.useMemo)(()=>n2r.find(t=>t.entityType===e.get(r5)),[e]),m=(0,G.useMemo)(()=>h2r(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`?Zpi:t===`traceId`?Qpi:$pi;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 _2r(n,e),D9(n),n},{replace:!0})},[t]),_=g,v=(0,G.useCallback)((e,n)=>{if(l.current!==`custom`)return;let r=n===`from`?a5:o5;t(t=>{let n=new URLSearchParams(t);return e?n.set(r,e.toISOString()):n.delete(r),D9(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(i5),n.delete(a5),n.delete(o5)):e===`custom`?n.set(i5,`custom`):(n.set(i5,e),n.delete(a5),n.delete(o5)),D9(n),n},{replace:!0})},[t]),b=(0,G.useCallback)(()=>{t(e=>{let t=new URLSearchParams(e);t.delete(r5);for(let e of c5)t.delete(s5[e]);return t.delete(i5),t.delete(a5),t.delete(o5),D9(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 nmi=20,rmi=1e4,imi={field:`timestamp`,direction:`DESC`};function ami(e,t,n){if(e?.pagination?.hasMore)return n+1}function omi(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 smi(e){return QP(e.state.error,`logs`)||$P(e.state.error)?!1:rmi}var cmi=({filters:e,orderBy:t=imi,queryOptions:n}={})=>{let r=Y(),{inView:i,setRef:a}=cP(),{hasNextPage:o,isFetchingNextPage:s,fetchNextPage:c,data:l,isLoading:u,isError:d,error:f}=zy({queryKey:[`logs`,e,t],queryFn:({pageParam:n})=>r.listLogsVNext({pagination:{page:n,perPage:nmi},filters:e,orderBy:t}),initialPageParam:0,getNextPageParam:ami,select:omi,retry:!1,refetchInterval:smi,...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}},lmi=[cF(`/logs`)];function umi(){let[e,t]=Qb(),n=zb(),r=tmi(e,t),i=D6(),{sort:a,onSortChange:o}=e5({searchParams:e,setSearchParams:t,allowedKeys:a2r,defaultSort:o2r}),s=(0,G.useMemo)(()=>({field:`timestamp`,direction:a?.direction===`asc`?`ASC`:`DESC`}),[a?.direction]),c=qpi(e,t),[l,u]=(0,G.useState)(),{data:d=[],isPending:f}=SRr(),{data:p=[],isPending:m}=y3({entityType:r.selectedEntityOption?.entityType,rootOnly:!0}),{data:h=[],isPending:g}=b3(),{data:_=[],isPending:v}=bRr(),y=(0,G.useMemo)(()=>m2r({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}=cmi({filters:(0,G.useMemo)(()=>v2r({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}=Xpi(b,r.featuredLogId,r.handleFeaturedChange,r.featuredTraceId),{data:j,isLoading:M}=S3({traceId:r.featuredTraceId??null,queryOptions:{enabled:!!r.featuredTraceId}}),N=(0,G.useCallback)(()=>r.applyFilterTokens(y2r(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]),ee=(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(iq,{children:(0,K.jsxs)(iq.Start,{children:[(0,K.jsx)(D_n,{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)(Tpi,{fields:y,tokens:r.filterTokens,onTokensChange:r.handleFilterTokensChange,disabled:x,onStartTextFilter:u})]})}),(0,K.jsx)(zpi,{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)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:lmi}),actionRow:ee,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)(Opi,{error:S,resource:`logs`,errorTitle:`Failed to load logs`})})]});let z=!!r.selectedEntityOption||r.filterTokens.length>0;return b.length===0&&!x&&!z?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:lmi}),actionRow:ee,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Logs`}),(0,K.jsx)(Wpi,{datePreset:r.datePreset,dateFrom:r.selectedDateFrom,dateTo:r.selectedDateTo})]}):(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:lmi}),actionRow:ee,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Logs`}),(0,K.jsx)(Rpi,{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)(Dpi,{log:D??void 0,onClose:P,onTraceClick:F,onSpanClick:I,onPrevious:k,onNext:A}),(0,K.jsx)(yoi,{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(nq(e,t))})]})}var dmi={name:e=>e.name||e.id};function fmi({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}=GNt({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=Uq(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 pmi({mcpServers:e,isLoading:t,search:n=``,sort:r,onSortChange:i}){let a=(0,G.useMemo)(()=>{let t=n.toLowerCase();return tZ(e.filter(e=>e.name?.toLowerCase().includes(t)||e.id?.toLowerCase().includes(t)),r,dmi)},[e,n,r]),{containerRef:o,getRowProps:s}=$X({count:a.length,global:!0});return t?(0,K.jsx)(OU,{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)(nF,{}),tooltip:`Agent tools`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Tools`,short:(0,K.jsx)(oF,{}),tooltip:`Tools`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Workflows`,short:(0,K.jsx)(aP,{}),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)(fmi,{server:e,rowProps:s(t)},e.id))]})}var mmi=()=>(0,K.jsx)(fw,{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)(Lr,{}),children:`MCP documentation`}),variant:`fill`}),O9=[cF(`/mcps`)],hmi=()=>{let{data:e=[],isLoading:t,error:n}=qP(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)();return n&&YP(n)?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:O9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsx)(fU,{variant:`fill`})]}):n&&XP(n)?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:O9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsx)(dU,{variant:`fill`,resource:`MCP servers`})]}):n?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:O9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsx)(fw,{tone:`error`,variant:`fill`,titleSlot:`Failed to load MCP servers`,descriptionSlot:n.message})]}):e.length===0&&!t?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:O9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsx)(mmi,{})]}):(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:O9}),actionRow:(0,K.jsx)(iq,{children:(0,K.jsx)(iq.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(PU,{onSearch:i,label:`Filter MCP servers`,placeholder:`Filter by name`})})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsx)(pmi,{mcpServers:e,isLoading:t,search:r,sort:a,onSortChange:(e,t)=>o({key:t,direction:e})})]})};function gmi(){let[e,t]=Qb();return{eventName:e.get(`event`)??void 0,close:()=>t(e=>{let t=new URLSearchParams(e);return t.delete(`event`),t},{replace:!0})}}var _mi=e=>`?${new URLSearchParams({event:e}).toString()}`;function vmi(e,{enabled:t=!0}={}){let n=Y();return Iy({queryKey:[`mcp-server-events`,e],queryFn:()=>n.getMcpServerEvents(e),enabled:t})}function ymi(e,t){let n=Y();return Ry({mutationFn:r=>n.emitMcpServerEvent(e,t,r)})}function k9(e){if(e instanceof uh&&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 bmi={push:`blue`,poll:`neutral`,webhook:`purple`};function xmi({delivery:e}){return(0,K.jsx)(`span`,{className:`flex flex-wrap items-center gap-1`,children:e.map(e=>(0,K.jsx)(hT,{size:`xs`,variant:bmi[e],emphasis:`subtle`,children:e},e))})}var Smi=0,Cmi=()=>`feed-${Smi++}`;function wmi(e,t){return[...t,...e].slice(0,200)}function Tmi(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:wmi(e.items,[{kind:`gap`,key:Cmi()}])};case`occurrences`:{let n=[...t.occurrences].reverse().map(e=>({kind:`occurrence`,key:Cmi(),occurrence:e}));return{...e,items:wmi(e.items,n)}}case`warning`:return{...e,warning:t.message};case`error`:return{...e,status:`error`,error:t.message}}}var Emi={status:`idle`,items:[]};function Dmi(e,t){let n=Y(),[r,i]=(0,G.useReducer)(Tmi,Emi),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:k9(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:k9(e)})}};return{...r,start:l,stop:c,pollOnce:u}}function A9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Omi(e){return e.map(e=>JSON.stringify(e)).join(` | `)}function kmi(e){return e.map(j9).join(` | `)}function j9(e){return A9(e)?Array.isArray(e.enum)?Omi(e.enum):`const`in e?JSON.stringify(e.const):Array.isArray(e.anyOf)?kmi(e.anyOf):Array.isArray(e.oneOf)?kmi(e.oneOf):Array.isArray(e.type)?e.type.join(` | `):e.type===`array`?`${j9(e.items)}[]`:Mmi(e)?`Record<string, ${j9(e.additionalProperties)}>`:typeof e.type==`string`?e.type:`unknown`:`unknown`}function Ami(e,t,n,{defaultsAreOptional:r=!1}){let i=A9(t)?t:{},a=`default`in i;return{name:e,type:j9(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 jmi(e,t={}){if(!A9(e)||!A9(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])=>Ami(e,r,n,t))}function Mmi(e){return A9(e)&&e.type===`object`&&!A9(e.properties)&&A9(e.additionalProperties)}function Nmi(e){return A9(e)&&(e.type===`object`||A9(e.properties))}var Pmi=[`type`,`properties`,`items`,`enum`,`const`,`anyOf`,`oneOf`,`allOf`,`$ref`];function Fmi(e){return!A9(e)||!Pmi.some(t=>t in e)}function M9(e){return A9(e)?fA(e):J({})}function Imi({inputSchema:e,onChange:t}){return Fmi(e)?(0,K.jsx)(U,{tone:`muted`,children:`This event takes no arguments.`}):(0,K.jsx)(iP,{schema:M9(e),onValuesChange:e=>t(e??{})})}function Lmi({occurrence:e}){return(0,K.jsx)(SF,{children:(0,K.jsxs)(iT,{children:[(0,K.jsxs)(aT,{className:`flex w-full cursor-pointer items-center gap-2 px-3 py-2 text-left`,children:[(0,K.jsx)(rt,{direction:`right`,className:`size-4 shrink-0`}),(0,K.jsx)(U,{as:`span`,variant:`caption`,font:`mono`,className:`min-w-0 flex-1 truncate`,children:e.eventId}),e.eventId.startsWith(`mastra-test-`)&&(0,K.jsx)(hT,{size:`xs`,variant:`amber`,emphasis:`subtle`,children:`test`}),(0,K.jsx)(U,{as:`span`,variant:`caption`,font:`mono`,tone:`muted`,className:`shrink-0`,children:e.timestamp})]}),(0,K.jsx)(oT,{children:(0,K.jsx)(BD,{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 Rmi=`Gap: events may have been skipped`;function zmi({items:e}){return e.length===0?(0,K.jsx)(fw,{iconSlot:(0,K.jsx)(Zo,{}),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)(HA,{variant:`warning`,children:Rmi}):(0,K.jsx)(Lmi,{occurrence:e.occurrence})},e.key))})}var Bmi={idle:`Not listening`,connecting:`Connecting…`,polling:`Polling…`,polled:`Polled`,stopped:`Stopped`,error:`Failed`};function Vmi({status:e,canStream:t}){if(e===`live`)return(0,K.jsx)(hT,{variant:`green`,indicator:`pulse`,size:`sm`,children:`Listening`});let n=e===`idle`&&!t?`Not polled yet`:Bmi[e];return(0,K.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(e===`connecting`||e===`polling`)&&(0,K.jsx)($c,{size:`sm`}),(0,K.jsx)(U,{as:`span`,tone:`muted`,children:n})]})}function Hmi({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)(Vmi,{status:e,canStream:t}),n&&(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1`,children:[(0,K.jsx)(U,{as:`span`,variant:`caption`,tone:`muted`,children:`Cursor`}),(0,K.jsx)(U,{as:`span`,variant:`caption`,font:`mono`,className:`min-w-0 truncate`,children:n}),(0,K.jsx)(fT,{tooltip:`Copy cursor`,content:n})]})]})}function Umi({serverId:e,event:t,onEmitted:n}){let{mutateAsync:r,isPending:i,isSuccess:a,error:o}=ymi(e,t.name);return(0,K.jsxs)(`section`,{"aria-label":`Send test event`,className:`grid grid-cols-1 gap-3`,children:[(0,K.jsx)(U,{as:`h3`,variant:`subheading`,children:`Send test event`}),(0,K.jsx)(iP,{schema:M9(t.payloadSchema),onSubmit:async e=>{try{await r(e??{}),n?.()}catch{}},isSubmitLoading:i,submitButtonLabel:`Send test event`}),a&&!o&&(0,K.jsx)(U,{tone:`muted`,children:`Test event sent.`}),o&&(0,K.jsx)(HA,{variant:`destructive`,children:k9(o)})]})}function Wmi({serverId:e,event:t,testEmit:n,canEmit:r}){let[i,a]=(0,G.useState)({}),o=Dmi(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)(Imi,{inputSchema:t.inputSchema,onChange:a}),(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,K.jsx)(Hmi,{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)(HA,{variant:`destructive`,children:o.error}),o.warning&&(0,K.jsx)(HA,{variant:`warning`,children:o.warning}),n&&t.emittable&&r&&(0,K.jsx)(Umi,{serverId:e,event:t,onEmitted:s?void 0:()=>void o.pollOnce(i)}),(0,K.jsx)(zmi,{items:o.items})]})}function Gmi({description:e}){let t=uQ({collapsedHeight:140});return(0,K.jsx)(lQ,{state:t,expandLabel:`Read more`,children:(0,K.jsx)(_Y,{children:e})})}function Kmi({description:e,overview:t,playground:n,canRun:r}){return(0,K.jsx)(K.Fragment,{children:(0,K.jsxs)(zA,{defaultTab:`overview`,className:`grid flex-1 grid-rows-[auto_1fr] gap-4 overflow-visible`,children:[(0,K.jsxs)(RA,{variant:`pill`,size:`sm`,children:[(0,K.jsx)(BA,{value:`overview`,children:`Overview`}),(0,K.jsx)(BA,{value:`playground`,disabled:!r,disabledTooltip:`You don't have permission to execute tools.`,children:`Playground`})]}),(0,K.jsxs)(VA,{value:`overview`,flush:!0,className:`content-start gap-6`,children:[e&&(0,K.jsx)(SF,{className:`p-4`,children:(0,K.jsx)(Gmi,{description:e})}),t]}),(0,K.jsx)(VA,{value:`playground`,flush:!0,keepMounted:!0,className:`h-full`,children:r&&n})]})})}function N9(e){return(0,K.jsx)(eOr,{className:`min-h-control-md`,...e})}function qmi(){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 Jmi({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 Ymi({field:e}){let t=!!e.description||e.defaultValue!==void 0;return(0,K.jsx)(UZ,{label:(0,K.jsxs)(U,{as:`span`,variant:`body-sm`,font:`mono`,tone:`ink`,children:[e.name,e.required&&(0,K.jsx)(qmi,{})]}),description:t&&(0,K.jsx)(Jmi,{field:e}),children:(0,K.jsx)(U,{as:`span`,variant:`caption`,font:`mono`,tone:`muted`,children:e.type})})}function Xmi({message:e}){return(0,K.jsx)(UZ,{label:(0,K.jsx)(U,{as:`span`,variant:`body-sm`,tone:`muted`,children:e})})}function Zmi({schema:e,emptyMessage:t,defaultsAreOptional:n}){if(Fmi(e))return(0,K.jsx)(Xmi,{message:t});if(!Nmi(e)||Mmi(e))return(0,K.jsx)(UZ,{label:`Type`,children:(0,K.jsx)(U,{as:`span`,variant:`caption`,font:`mono`,tone:`muted`,children:j9(e)})});let r=jmi(e,{defaultsAreOptional:n});return r.length===0?(0,K.jsx)(Xmi,{message:t}):r.map(e=>(0,K.jsx)(Ymi,{field:e},e.name))}function P9({title:e,...t}){return(0,K.jsxs)(M2,{children:[(0,K.jsx)(N9,{children:(0,K.jsx)(N2,{children:e})}),(0,K.jsx)(VZ,{children:(0,K.jsx)(Zmi,{...t})})]})}function Qmi({serverId:e,eventName:t}){let{canExecute:n,canEdit:r}=Tw(),{data:i,isLoading:a}=vmi(e),o=i?.events.find(e=>e.name===t);return a?(0,K.jsx)(zZ.LoadingData,{}):!i||!o?(0,K.jsxs)(zZ.NoData,{children:[`This server has no event "`,t,`".`]}):(0,K.jsx)(Kmi,{description:o.description,overview:(0,K.jsxs)(`div`,{className:`grid grid-cols-1 gap-6`,children:[(0,K.jsx)(xmi,{delivery:o.delivery}),(0,K.jsx)(P9,{title:`Arguments`,schema:o.inputSchema,emptyMessage:`This event takes no arguments.`,defaultsAreOptional:!0}),(0,K.jsx)(P9,{title:`Payload`,schema:o.payloadSchema,emptyMessage:`No payload schema defined.`})]}),canRun:n(`mcp`),playground:(0,K.jsx)(Wmi,{serverId:e,event:o,testEmit:i.testEmit,canEmit:r(`mcp`)})})}function $mi({serverId:e}){let{eventName:t,close:n}=gmi();return(0,K.jsxs)(zZ,{open:t!==void 0,onClose:n,title:t??``,children:[(0,K.jsxs)(zZ.Header,{children:[(0,K.jsxs)(zZ.Heading,{children:[(0,K.jsx)(QC,{size:`sm`,className:`text-muted-foreground`,children:(0,K.jsx)(Zo,{})}),(0,K.jsx)(`span`,{className:`truncate`,children:t})]}),(0,K.jsx)(zZ.HeaderActions,{children:(0,K.jsx)(zZ.CloseButton,{icon:`x`,tooltip:`Close event`,onClick:n})})]}),(0,K.jsx)(zZ.Content,{className:`flex flex-col gap-4 px-3`,children:t&&(0,K.jsx)(Qmi,{serverId:e,eventName:t},t)})]})}var ehi=new Set([`completed`,`failed`,`cancelled`]),thi={working:`working`,input_required:`input required`,completed:`completed`,failed:`failed`,cancelled:`cancelled`},F9=e=>ehi.has(e.status),nhi=2e3,I9=e=>[`mcp-server-tasks`,e],rhi=e=>!!e?.some(e=>!F9(e));function ihi(e,t={}){let n=Y();return zy({queryKey:[...I9(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=>rhi(e.tasks))?nhi:!1})}function ahi(e,{enabled:t=!0}={}){let n=Y();return Iy({queryKey:[...I9(e),`surfaces`],queryFn:()=>n.getMcpServerTasks(e,{limit:1}),select:e=>e.surfaces,enabled:t})}function ohi(e,t){let n=Y();return Iy({queryKey:[...I9(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&&!F9(e.state.data)?nhi:!1})}function shi(e){let t=Y();return Ry({mutationFn:n=>t.findMcpServerTask(e,n)})}function chi(e){let t=Y(),n=xy();return Ry({mutationFn:n=>t.cancelMcpServerTask(e,n),onSettled:()=>n.invalidateQueries({queryKey:I9(e)})})}function lhi(e){let t=Y(),n=xy();return Ry({mutationFn:({taskKey:n,inputResponses:r})=>t.answerMcpServerTaskInput(e,n,r),onSettled:()=>n.invalidateQueries({queryKey:I9(e)})})}function uhi(){let[e,t]=Qb();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 dhi=(e,t=``)=>{let n=new URLSearchParams(t);return n.set(`task`,e),`?${n.toString()}`},L9=e=>`${e.slice(0,8)}…`,fhi=new Set([`working`,`input_required`,`completed`,`failed`,`cancelled`]);function phi(){let[e,t]=Qb(),n=e.get(`status`),r=e.get(`surface`),i=e.get(`client`);return{filters:{...n&&fhi.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 mhi=e=>`${e.slice(0,8)}…`,hhi={working:{variant:`info`,indicator:`pulse`},input_required:{variant:`warning`,indicator:`dot`},completed:{variant:`success`},failed:{variant:`destructive`},cancelled:{variant:`neutral`}};function ghi({status:e}){let{variant:t,indicator:n}=hhi[e];return(0,K.jsx)(hT,{size:`sm`,variant:t,emphasis:`subtle`,indicator:n,children:thi[e]})}function _hi({serverId:e}){let{taskKey:t,close:n}=uhi(),{data:r,isSuccess:i}=ohi(e,t);return(0,K.jsxs)(zZ,{open:t!==void 0,onClose:n,title:r?.surface??`Task`,children:[(0,K.jsxs)(zZ.Header,{children:[(0,K.jsxs)(zZ.Heading,{children:[(0,K.jsx)(QC,{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)(zZ.HeaderActions,{children:(0,K.jsx)(zZ.CloseButton,{icon:`x`,tooltip:`Close task`,onClick:n})})]}),(0,K.jsx)(zZ.Content,{className:`flex flex-col gap-4 px-3`,children:r?(0,K.jsx)(vhi,{serverId:e,task:r},r.taskKey):i&&(0,K.jsx)(U,{tone:`muted`,children:`This task is no longer listed.`})})]})}function vhi({serverId:e,task:t}){let n=chi(e),{canEdit:r,isLoading:i}=Tw(),a=!i&&r(`mcp`),o=Object.entries(t.inputRequests??{});return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(T2,{children:[(0,K.jsx)(T2.Key,{children:`Status`}),(0,K.jsx)(T2.Value,{children:(0,K.jsx)(ghi,{status:t.status})}),t.statusMessage&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T2.Key,{children:`Message`}),(0,K.jsx)(T2.Value,{children:t.statusMessage})]}),(0,K.jsx)(T2.Key,{children:`Created`}),(0,K.jsx)(T2.Value,{children:(0,K.jsx)(TT,{value:t.createdAt})}),(0,K.jsx)(T2.Key,{children:`Updated`}),(0,K.jsx)(T2.Value,{children:(0,K.jsx)(TT,{value:t.lastUpdatedAt})}),(0,K.jsx)(T2.Key,{children:`Expires`}),(0,K.jsx)(T2.Value,{children:t.expiresAt?(0,K.jsx)(TT,{value:t.expiresAt}):`never`}),(0,K.jsx)(T2.Key,{children:`Task key`}),(0,K.jsx)(T2.ValueWithCopyBtn,{copyValue:t.taskKey,copyTooltip:`Copy task key`,children:L9(t.taskKey)}),t.clientLabel&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T2.Key,{children:`Client`}),(0,K.jsx)(T2.ValueWithCopyBtn,{copyValue:t.clientLabel,copyTooltip:`Copy client`,children:t.clientLabel})]}),(0,K.jsx)(T2.Key,{children:`Client key`}),(0,K.jsx)(T2.ValueWithCopyBtn,{copyValue:t.principalKey,copyTooltip:`Copy client key`,children:L9(t.principalKey)})]}),(0,K.jsx)(U,{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)(bhi,{serverId:e,taskKey:t.taskKey,inputKey:n,request:r,canAnswer:a},n)),!F9(t)&&!i&&!a&&(0,K.jsx)(U,{tone:`muted`,variant:`caption`,children:`Cancelling or answering a task needs the mcp:write permission.`}),!F9(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)(HA,{variant:`destructive`,children:xhi(n.error)})]}),t.result&&(0,K.jsx)(R9,{label:`Result`,value:t.result}),t.error&&(0,K.jsx)(R9,{label:`Error`,value:t.error})]})}var yhi=J({message:q().optional(),requestedSchema:nm(q(),Xp())});function bhi({serverId:e,taskKey:t,inputKey:n,request:r,canAnswer:i}){let a=lhi(e),o=r.method===`elicitation/create`?yhi.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)(U,{as:`h3`,variant:`subheading`,children:`Input requested`}),o?.success&&!i?(0,K.jsxs)(K.Fragment,{children:[o.data.message&&(0,K.jsx)(U,{children:o.data.message}),(0,K.jsx)(R9,{label:`Request`,value:r})]}):o?.success?(0,K.jsxs)(K.Fragment,{children:[o.data.message&&(0,K.jsx)(U,{children:o.data.message}),(0,K.jsx)(iP,{schema:M9(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)(U,{tone:`muted`,children:[`Studio can't answer a `,r.method,` request; the client that started the task has to.`]}),(0,K.jsx)(R9,{label:`Request`,value:r})]}),a.error&&(0,K.jsx)(HA,{variant:`destructive`,children:xhi(a.error)})]})}function R9({label:e,value:t}){return(0,K.jsxs)(`section`,{className:`flex flex-col gap-2`,children:[(0,K.jsx)(U,{as:`h3`,variant:`subheading`,children:e}),(0,K.jsx)(BD,{value:JSON.stringify(t,null,2),language:`json`,editable:!1,lineNumbers:!1,"aria-label":`Task ${e.toLowerCase()}`})]})}function xhi(e){let t=k9(e);return t===`Task not found`?`The task is no longer waiting for this; the list has been refreshed.`:t}function Shi(e){if(!A9(e))return;if(A9(e.ui)&&typeof e.ui.resourceUri==`string`)return e.ui.resourceUri;let t=e[`ui/resourceUri`];return typeof t==`string`?t:void 0}function Chi(e){return A9(e)&&e.status===`suspended`}function whi(e){return e<1e3?`${Math.round(e)} ms`:`${(e/1e3).toFixed(2)} s`}function Thi(e){return e===void 0?`undefined`:JSON.stringify(e,null,2)}function Ehi(e){return e.status===`error`?e.error:Thi(e.output)}function Dhi({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:Ohi(n),durationMs:r}}}function Ohi(e){return e instanceof Error?JSON.stringify({error:e.message},null,2):JSON.stringify({error:String(e)},null,2)}function khi({zodInputSchema:e,isRunning:t,onRun:n,requestContextEntityType:r,requestContextEntityId:i}){let a=!$N(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=YOt(o.value);if(!n.ok)return u([n.error]);let r=XOt(e,n.value);if(r)return u([r]);c.current=n.value,s({view:`form`,value:n.value})}function f(t){let r=ZOt(e,t);r.ok?n(r.value):u(r.errors)}let p={isSubmitLoading:t,submitButtonLabel:`Run`,submitButtonIcon:(0,K.jsx)(Go,{}),submitButtonVariant:`primary`};return(0,K.jsxs)(M2,{children:[(0,K.jsx)(N9,{action:(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsx)($Pt,{entityType:r,entityId:i}),(0,K.jsx)(zA,{defaultTab:`form`,value:o.view,onValueChange:d,children:(0,K.jsxs)(RA,{size:`md`,children:[(0,K.jsxs)(BA,{value:`form`,disabled:t,children:[(0,K.jsx)(QC,{size:`sm`,children:(0,K.jsx)(ts,{})}),`Form`]}),(0,K.jsxs)(BA,{value:`json`,disabled:t,children:[(0,K.jsx)(QC,{size:`sm`,children:(0,K.jsx)(yn,{})}),`JSON`]})]})})]}),children:(0,K.jsx)(N2,{children:`Request`})}),(0,K.jsx)(VZ,{children:(0,K.jsx)(`div`,{className:`p-4`,children:o.view===`json`?(0,K.jsxs)(`div`,{className:`grid gap-4`,children:[(0,K.jsxs)(OA,{invalid:l.length>0,children:[(0,K.jsx)(BD,{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)(MA,{children:l.map(e=>(0,K.jsx)(`span`,{className:`block`,children:e},e))})]}),(0,K.jsx)(WA,{...p,onSubmit:()=>f(o.value)})]}):(0,K.jsx)(iP,{...p,schema:e,defaultValues:o.value,onValuesChange:e=>{c.current=e},onSubmit:n,className:`gap-0`,children:!a&&(0,K.jsx)(U,{variant:`body-sm`,tone:`muted`,className:`pb-4`,children:`This tool takes no input. Run it as is.`})})})})]})}function Ahi({isRunning:e,lastRun:t}){return e?(0,K.jsx)(fw,{iconSlot:(0,K.jsx)($c,{}),titleSlot:`Running…`,descriptionSlot:`Waiting for the tool to respond.`}):t?t.status===`error`?(0,K.jsx)(NT,{code:Ehi(t),className:`overflow-x-auto p-4 text-caption whitespace-pre`}):(0,K.jsx)(BD,{value:Ehi(t),language:`json`,editable:!1,lineNumbers:!1,showCopyButton:!1,variant:`embedded`,"aria-label":`Tool response`,className:`p-4`}):(0,K.jsx)(fw,{iconSlot:(0,K.jsx)(ete,{}),titleSlot:`No response yet`,descriptionSlot:`Run the tool to see its output here.`})}function jhi({run:e}){return(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[e.status===`success`?(0,K.jsx)(hT,{variant:`success`,emphasis:`subtle`,indicator:`dot`,children:`Success`}):(0,K.jsx)(hT,{variant:`destructive`,emphasis:`subtle`,indicator:`dot`,children:`Error`}),(0,K.jsx)(U,{as:`span`,variant:`caption`,font:`mono`,tone:`muted`,children:whi(e.durationMs)}),(0,K.jsx)(fT,{content:Ehi(e),copyMessage:`Response copied`,tooltip:`Copy response`,size:`icon-sm`})]})}function Mhi({isRunning:e,lastRun:t}){return(0,K.jsxs)(M2,{className:`h-full`,children:[(0,K.jsx)(N9,{action:!e&&t&&(0,K.jsx)(jhi,{run:t}),children:(0,K.jsx)(N2,{children:`Response`})}),(0,K.jsx)(VZ,{className:H(`grid min-h-48 flex-1`,e||!t?`content-center`:`content-start`),children:(0,K.jsx)(Ahi,{isRunning:e,lastRun:t})})]})}function Nhi({zodInputSchema:e,execution:t,requestContextEntityType:n,requestContextEntityId:r}){let[i]=Qw(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)(khi,{zodInputSchema:e,isRunning:c,onRun:s,requestContextEntityType:n,requestContextEntityId:r}),(0,K.jsx)(Mhi,{isRunning:c,lastRun:Dhi(t,a)})]})}function Phi({serverId:e,tool:t}){let{mutateAsync:n,status:r,data:i,error:a}=WNt({serverId:e,toolId:t.name}),{data:o}=VNt({serverId:e,appResourceUri:Shi(t._meta)}),s=M9(t.inputSchema),c={execute:(e,t)=>n({data:e,requestContext:t}),status:r,output:i,error:a};return(0,K.jsxs)(`div`,{className:`grid content-start gap-6`,children:[o&&(0,K.jsx)(dwr,{html:o,toolName:t.name,onToolCall:(e,t)=>n({data:t})}),Chi(i)&&(0,K.jsxs)(HA,{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)(FY,{children:`inputRequests`}),` handler to finish the request.`]}),(0,K.jsx)(Nhi,{zodInputSchema:s,execution:c,requestContextEntityType:`mcp-tool`,requestContextEntityId:`${e}:${t.name}`})]})}var Fhi=(0,G.createContext)(void 0),Ihi=Fhi.Provider;function Lhi(){let e=(0,G.useContext)(Fhi);if(e===void 0)throw Error(`useOpenToolId must be used inside ToolDrawer`);return e}function Rhi({inputSchema:e,outputSchema:t,requestContextSchema:n,footer:r}){return(0,K.jsxs)(`div`,{className:`grid gap-6`,children:[(0,K.jsx)(P9,{title:`Input`,schema:e,emptyMessage:`This tool takes no input.`,defaultsAreOptional:!0}),(0,K.jsx)(P9,{title:`Output`,schema:t,emptyMessage:`No output schema defined.`}),n!==void 0&&(0,K.jsx)(P9,{title:`Request context`,schema:n,emptyMessage:`No request context fields.`,defaultsAreOptional:!0}),r]})}function zhi({serverId:e}){let t=Lhi(),{canExecute:n}=Tw(),{data:r,isLoading:i}=UNt({serverId:e,toolId:t});return i?(0,K.jsx)(zZ.LoadingData,{}):r?(0,K.jsx)(Kmi,{description:r.description,overview:(0,K.jsx)(Rhi,{inputSchema:r.inputSchema}),canRun:n(`tools`),playground:(0,K.jsx)(Phi,{serverId:e,tool:r})}):(0,K.jsxs)(zZ.NoData,{children:[`This server has no tool "`,t,`".`]})}var Bhi=`auto 1fr auto`;function Vhi({server:e}){let{data:t,isLoading:n,isError:r}=vmi(e.id),i=t?.events??[],{Link:a}=gl(),{containerRef:o,getRowProps:s}=$X({count:i.length});return(0,K.jsxs)(`section`,{className:`flex flex-col gap-3`,children:[(0,K.jsx)(U,{as:`h2`,variant:`heading`,children:`Events`}),n&&(0,K.jsx)(OU,{columns:Bhi}),r&&(0,K.jsx)(HA,{variant:`destructive`,children:`Could not load this server's events.`}),t&&(0,K.jsxs)(Z,{columns:Bhi,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}${_mi(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)(xmi,{delivery:t.delivery})})]},t.name))]})]})}var Hhi=`minmax(0,1fr) auto auto auto auto auto auto auto`,Uhi={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.`},Whi=[{id:`is`,label:`is`}],Ghi=Object.entries(thi).map(([e,t])=>({value:e,label:t})),Khi=e=>e.stopPropagation(),qhi=e=>e.clientLabel??mhi(e.principalKey),Jhi=e=>[`status`,`surface`,`client`].flatMap(t=>{let n=e[t];return n?[{id:t,fieldId:t,operatorId:`is`,value:n}]:[]}),Yhi=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 Xhi({server:e}){let{filters:t,setFilters:n}=phi(),{data:r,isLoading:i,isError:a,hasNextPage:o,fetchNextPage:s,isFetchingNextPage:c}=ihi(e.id,t),{data:l=[]}=ahi(e.id),u=(0,G.useMemo)(()=>r?.pages.flatMap(e=>e.tasks)??[],[r]),d=r?.pages[0]?.unavailable,{containerRef:f,getRowProps:p}=$X({count:u.length}),m=Jhi(t).length>0,h=(0,G.useMemo)(()=>{let e=new Map(u.map(e=>[e.principalKey,qhi(e)]));return t.client&&!e.has(t.client)&&e.set(t.client,mhi(t.client)),[...e]},[u,t.client]),g=(0,G.useMemo)(()=>[{id:`status`,label:`Status`,icon:Hn,color:pF(`orange`),operators:[`is`],strict:!0,suggestions:Ghi},{id:`surface`,label:`Surface`,icon:Rc,color:pF(`blue`),operators:[`is`],strict:!0,suggestions:l.map(e=>({value:e.name}))},{id:`client`,label:`Client`,icon:jc,color:pF(`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)(U,{as:`h2`,variant:`heading`,children:`Tasks`}),a&&(0,K.jsx)(HA,{variant:`destructive`,children:`Could not load this server's tasks.`}),d&&(0,K.jsx)(HA,{variant:`info`,children:Uhi[d]}),!d&&(0,K.jsxs)(iq,{children:[(0,K.jsx)(iq.Start,{children:(0,K.jsxs)(W6,{fields:g,operators:Whi,value:Jhi(t),onValueChange:e=>n(Yhi(e)),createItemId:e=>e,"aria-label":`Task filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(W6.Chips,{}),(0,K.jsx)(W6.Input,{placeholder:`Filter tasks…`})]})}),(0,K.jsx)(iq.End,{children:(0,K.jsx)(Qhi,{serverId:e.id})})]}),i&&(0,K.jsx)(OU,{columns:Hhi}),r&&!d&&(0,K.jsxs)(Z,{columns:Hhi,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)(Zhi,{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)(U,{variant:`caption`,tone:`muted`,children:[`Showing the `,u.length,` most recent `,m?`matching `:``,`tasks.`]})]})]})}function Zhi({serverId:e,task:t,rowProps:n,onFilterClient:r}){let{Link:i}=gl(),[a]=Qb(),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}${dhi(t.taskKey,a)}`,LinkComponent:i,tabIndex:-1,onClick:Khi,"aria-label":`${t.surface} task ${L9(t.taskKey)}`,children:[(0,K.jsx)(Z.NameCell,{children:t.surface}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(ghi,{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)(TT,{value:t.lastUpdatedAt})}),(0,K.jsx)(Z.Cell,{className:`text-muted-foreground`,children:t.expiresAt?(0,K.jsx)(TT,{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:L9(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 ${qhi(t)}`,onClick:e=>{e.stopPropagation(),r()},children:qhi(t)})})]})}function Qhi({serverId:e}){let[t,n]=(0,G.useState)(``),r=shi(e),{open:i}=uhi();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)(lN,{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)(U,{variant:`caption`,role:`status`,className:`text-destructive-foreground`,children:`No task with that id.`})]})}var $hi={agent:nF,workflow:aP,tool:oF},egi=`auto minmax(0, 1fr) auto`,tgi=`auto minmax(0, 1fr) auto auto`,ngi={tool:`Tool`,agent:`Agent`,workflow:`Workflow`};function rgi(e){return e in $hi}function igi({type:e}){let t=rgi(e)?e:`tool`,n=$hi[t],r=ngi[t];return(0,K.jsxs)(JC,{children:[(0,K.jsx)(YC,{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)(XC,{children:r})]})}var agi=J({ui:J({resourceUri:q().optional()}).optional(),"ui/resourceUri":q().optional()});function ogi(e){let t=agi.safeParse(e);return t.success?!!(t.data.ui?.resourceUri?.startsWith(`ui://`)||t.data[`ui/resourceUri`]?.startsWith(`ui://`)):!1}function sgi({surface:e}){return e?(0,K.jsxs)(JC,{children:[(0,K.jsx)(YC,{asChild:!0,children:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,K.jsx)(hT,{size:`xs`,variant:e.mode===`always`?`info`:`neutral`,emphasis:`subtle`,children:e.mode}),e.required&&(0,K.jsx)(hT,{size:`xs`,variant:`warning`,emphasis:`subtle`,children:`required`}),e.recover&&(0,K.jsx)(hT,{size:`xs`,variant:`neutral`,emphasis:`subtle`,children:`recover`})]})}),(0,K.jsxs)(XC,{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 cgi({server:e}){let[t,n]=(0,G.useState)(``),{data:r={},isLoading:i}=GNt({selectedServer:e}),{Link:a,paths:o}=gl(),{data:s}=ahi(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?tgi:egi,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}=$X({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)(U,{as:`h2`,variant:`heading`,children:`Available tools`}),(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(PU,{onSearch:n,label:`Filter tools`,placeholder:`Filter by name`,shortcutDisabled:!0})})]}),i?(0,K.jsx)(OU,{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,ogi(t._meta)&&(0,K.jsx)(hT,{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)(igi,{type:t.toolType??`tool`})}),l&&(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(sgi,{surface:c.get(t.name)})})]},t.name))]})]})}var lgi=({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)(U,{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)(SF,{children:(0,K.jsxs)(zA,{defaultTab:`http`,children:[(0,K.jsxs)(CF,{className:`flex-row items-center justify-between gap-3 space-y-0 border-b border-border`,children:[(0,K.jsx)(wF,{className:`shrink-0`,children:`Connect`}),(0,K.jsx)(`div`,{className:`min-w-0`,children:(0,K.jsx)(RA,{variant:`pill-ghost`,size:`sm`,children:s.map(e=>(0,K.jsx)(BA,{value:e.value,children:e.label},e.value))})})]}),s.map(e=>(0,K.jsx)(VA,{value:e.value,flush:!0,children:(0,K.jsxs)(EF,{className:`flex flex-col gap-3`,children:[(0,K.jsx)(U,{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)(U,{as:`span`,font:`mono`,className:`min-w-0 break-all`,children:e.content}),(0,K.jsx)(fT,{tooltip:e.tooltip,content:e.content})]})]})},e.value))]})}),(0,K.jsx)(cgi,{server:t}),t.tasks_capability&&(0,K.jsx)(Xhi,{server:t}),t.events_capability&&(0,K.jsx)(Vhi,{server:t})]})};function ugi(){let[e,t]=Qb();return{toolId:e.get(`tool`)??void 0,close:()=>t(e=>{let t=new URLSearchParams(e);return t.delete(`tool`),t},{replace:!0})}}function dgi({children:e}){let{toolId:t,close:n}=ugi();return(0,K.jsxs)(zZ,{open:t!==void 0,onClose:n,title:t??``,children:[(0,K.jsxs)(zZ.Header,{children:[(0,K.jsxs)(zZ.Heading,{children:[(0,K.jsx)(QC,{size:`sm`,className:`text-muted-foreground`,children:(0,K.jsx)(oF,{})}),(0,K.jsx)(`span`,{className:`truncate`,children:t})]}),(0,K.jsx)(zZ.HeaderActions,{children:(0,K.jsx)(zZ.CloseButton,{icon:`x`,tooltip:`Close tool`,onClick:n})})]}),(0,K.jsx)(zZ.Content,{className:`flex flex-col gap-4 px-3`,children:t&&(0,K.jsx)(Ihi,{value:t,children:e},t)})]})}var fgi=()=>{let{serverId:e}=Bb(),t=[cF(`/mcps`),UPt],{data:n=[],isLoading:r}=qP(),i=n.find(t=>t.id===e),a=i?.transports?.includes(`sse`)??!0,o=r||i?(0,K.jsxs)(oq,{children:[(0,K.jsx)(oq.Title,{isLoading:r,children:i?.name}),i&&(0,K.jsx)(oq.Meta,{beside:!0,children:(0,K.jsxs)(hT,{size:`sm`,children:[`v`,i.version_detail.version]})}),i&&(0,K.jsx)(oq.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)(Jw,{variant:`narrow`,breadcrumbs:(0,K.jsx)(DP,{crumbs:t}),header:o,children:[(0,K.jsx)(lgi,{isLoading:r,server:i}),e&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(dgi,{children:(0,K.jsx)(zhi,{serverId:e})}),(0,K.jsx)($mi,{serverId:e}),(0,K.jsx)(_hi,{serverId:e})]})]})};function pgi(){let{data:e,isLoading:t}=E6();if(t)return`loading`;let n=e?.capabilities;return n?.traceAggregate===!0&&n.spanAggregate===!0?`unified`:`legacy`}var z9=[cF(`/metrics`)],mgi=e=>e.fieldId===B6;function hgi({fields:e}){let{filterTokens:t,setFilterTokens:n}=Q7(),r=[H6,...nci(t)];return(0,K.jsxs)(W6,{fields:[V6,...e],operators:Ysi,value:r,onValueChange:e=>n(rci(e.filter(e=>!mgi(e)))),createItemId:e=>e,"aria-label":`Metrics filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(W6.Chips,{renderChip:e=>mgi(e)?(0,K.jsx)(idi,{}):(0,K.jsx)(W6.Chip,{item:e})}),(0,K.jsx)(W6.Input,{placeholder:`Filter metrics…`})]})}function ggi({children:e,filterFields:t}){return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:z9}),actionRow:(0,K.jsx)(iq,{children:(0,K.jsx)(iq.Start,{children:(0,K.jsx)(hgi,{fields:t})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),e]})}function _gi({error:e}){return YP(e)?(0,K.jsx)(fU,{}):XP(e)?(0,K.jsx)(dU,{resource:`metrics`}):(0,K.jsx)(fw,{tone:`error`,titleSlot:`Failed to load storage capabilities`,descriptionSlot:e.message})}var vgi=tci({availableTags:[],availableEntityNames:[],availableServiceNames:[],availableEnvironments:[]});function ygi({children:e}){let{supportsMetrics:t,isLoading:n,error:r}=v5();return n?(0,K.jsx)(ggi,{filterFields:vgi,children:(0,K.jsxs)(`div`,{className:`flex h-full items-center justify-center gap-2`,children:[(0,K.jsx)($c,{"aria-label":`Loading storage capabilities`}),(0,K.jsx)(U,{as:`span`,variant:`caption`,tone:`muted`,children:`Loading storage capabilities`})]})}):r?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:z9}),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)(_gi,{error:r})})]}):t?e:(0,K.jsx)(ggi,{filterFields:vgi,children:(0,K.jsx)(fw,{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)(Lr,{}),children:`Metrics documentation`}),variant:`fill`})})}function bgi(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 xgi(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=bgi(i);s&&e.set(t,s)}function B9(e,t,n){typeof n==`string`&&n.length>0&&e.set(t,n)}function Sgi(e,t,n){if(Array.isArray(n)&&n.length!==0)for(let r of n)r&&e.append(t,r)}function Cgi({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 wgi({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:i=`/traces`}){let a=new URLSearchParams;a.set(F3,`branches`),xgi(a,I3,L3,R3,e,t,r.window);let o=r.rootEntityType??n.rootEntityType;o&&a.set(N3,o),r.status&&a.set(P3,r.status),B9(a,B3.entityName,r.entityName??n.entityName),B9(a,B3.threadId,r.threadId??n.threadId),B9(a,B3.resourceId,r.resourceId??n.resourceId),B9(a,B3.runId,n.runId),B9(a,B3.sessionId,r.sessionId??n.sessionId),B9(a,B3.requestId,n.requestId),B9(a,B3.userId,r.userId??n.userId),B9(a,B3.organizationId,n.organizationId),B9(a,B3.experimentId,n.experimentId),B9(a,B3.serviceName,n.serviceName),B9(a,B3.environment,r.environment??n.environment),Sgi(a,B3.tags,n.tags),r.span&&a.append(e6,JSON.stringify(Cgi(r.span)));let s=a.toString();return s?`${i}?${s}`:i}function Tgi({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:i=`/logs`}){let a=new URLSearchParams;xgi(a,i5,a5,o5,e,t,r.window);let o=r.rootEntityType??n.rootEntityType;o&&a.set(r5,o),B9(a,s5.entityName,r.entityName??n.entityName),B9(a,s5.threadId,r.threadId??n.threadId),B9(a,s5.resourceId,r.resourceId??n.resourceId),B9(a,s5.runId,n.runId),B9(a,s5.sessionId,n.sessionId),B9(a,s5.requestId,n.requestId),B9(a,s5.userId,n.userId),B9(a,s5.organizationId,n.organizationId),B9(a,s5.experimentId,n.experimentId),B9(a,s5.serviceName,n.serviceName),B9(a,s5.environment,n.environment),Sgi(a,s5.tags,n.tags),r.status===`error`&&a.append(s5.level,`error`);let s=a.toString();return s?`${i}?${s}`:i}function Egi(){let{datePreset:e,customRange:t,dimensionalFilter:n}=Q7(),r=zb(),i={preset:e,customRange:t,dashboardFilter:n};return{openTraces:(e={})=>{r(wgi({...i,scope:e}))},openLogs:(e={})=>{r(Tgi({...i,scope:e}))}}}var Dgi=`period`,V9=`dateFrom`,H9=`dateTo`;function Ogi(){let[e,t]=Qb(),n=e.get(Dgi),r=Sci(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(V9)),i=t(e.get(H9));if(n||i)return{from:n,to:i}},[r,e.toString()]),a=(0,G.useMemo)(()=>ici(e),[e.toString()]),o=(0,G.useCallback)(e=>{t(t=>{let n=new URLSearchParams(t);return e===`24h`?n.delete(Dgi):n.set(Dgi,e),e!==`custom`&&(n.delete(V9),n.delete(H9)),n},{replace:!0})},[t]),s=(0,G.useCallback)(e=>{t(t=>{let n=new URLSearchParams(t);return e?.from?n.set(V9,e.from.toISOString()):n.delete(V9),e?.to?n.set(H9,e.to.toISOString()):n.delete(H9),n},{replace:!0})},[t]),c=(0,G.useCallback)(e=>{t(t=>{let n=new URLSearchParams(t);return oci(n,e),Gsi(n),n},{replace:!0})},[t]),l=(0,G.useRef)(!1);return(0,G.useEffect)(()=>{if(l.current||(l.current=!0,qsi(e)))return;let n=Ksi();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)(Dci,{preset:r,filterTokens:a,onPresetChange:o,onFilterTokensChange:c,customRange:i,onCustomRangeChange:s,children:(0,K.jsx)(ygi,{children:(0,K.jsx)(kgi,{})})})}function kgi(){let{error:e}=gci($7()),{isInMemory:t}=v5(),{data:n}=SRr(),{data:r}=y3(),{data:i}=bRr(),{data:a}=b3(),o=tci({availableTags:n??[],availableEntityNames:r??[],availableServiceNames:i??[],availableEnvironments:a??[]});return e&&YP(e)?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:z9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),(0,K.jsx)(fU,{variant:`fill`})]}):e&&XP(e)?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:z9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),(0,K.jsx)(dU,{variant:`fill`,resource:`metrics`})]}):e?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:z9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),(0,K.jsx)(fw,{tone:`error`,variant:`fill`,titleSlot:`Failed to load metrics`,descriptionSlot:e.message})]}):(0,K.jsx)(ggi,{filterFields:o,children:(0,K.jsxs)(`div`,{className:`grid content-start gap-4`,children:[t&&(0,K.jsx)(HA,{variant:`info`,title:`Metrics are not persisted`,children:(0,K.jsx)(HA.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)(Agi,{})]})})}function Agi(){let{openTraces:e,openLogs:t}=Egi(),n=Uh.AGENT,r=pgi(),i=(0,K.jsx)(Rci,{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)(bdi,{onViewTraces:t=>e({rootEntityType:t}),onTimeRangeClick:t=>e({window:t})}),o=(0,K.jsx)(afi,{onViewTraces:()=>e(),onAgentClick:t=>e({rootEntityType:n,entityName:t}),onModelClick:t=>e({model:t}),onThreadClick:t=>e({threadId:t})}),s=(0,K.jsx)(fdi,{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)(m9,{columns:2,children:[(0,K.jsx)(m9.Item,{children:s}),(0,K.jsx)(m9.Item,{children:i}),(0,K.jsx)(m9.Item,{children:a}),(0,K.jsx)(m9.Item,{children:(0,K.jsx)(tdi,{onTimeRangeClick:e})})]}),(0,K.jsx)(Wui,{onRowClick:e})]}):(0,K.jsxs)(`div`,{className:`grid content-start gap-4 pb-6`,children:[s,(0,K.jsxs)(m9,{columns:2,children:[(0,K.jsx)(m9.Item,{children:i}),(0,K.jsx)(m9.Item,{children:a})]}),(0,K.jsxs)(m9,{columns:2,children:[(0,K.jsx)(m9.Item,{children:(0,K.jsx)(Qdi,{onViewTraces:t=>e({rootEntityType:t}),onViewErrors:e=>t({rootEntityType:e,status:`error`}),onEntityClick:(t,n)=>e({rootEntityType:t,entityName:n})})}),(0,K.jsx)(m9.Item,{children:o})]}),(0,K.jsx)(gfi,{})]})}function jgi(){let{isCmsAvailable:e}=Z2(),{paths:t}=gl();return e?(0,K.jsx)(d4n,{href:t.cmsPromptBlockCreateLink(),tooltip:`Create a prompt`,children:`New prompt`}):null}var U9=[cF(`/prompts`)],Mgi=50,Ngi=[`updatedAt`];function Pgi(){let[e,t]=(0,G.useState)(``),[n,r]=(0,G.useState)(0),[i,a]=Qb(),{sort:o,onSortChange:s}=e5({searchParams:i,setSearchParams:a,allowedKeys:Ngi}),{data:c,isLoading:l,error:u,isPlaceholderData:d}=tPr({page:n,perPage:Mgi,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&&YP(u)?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:U9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(fU,{variant:`fill`})]}):u&&XP(u)?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:U9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(dU,{variant:`fill`,resource:`prompt blocks`})]}):u?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:U9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(fw,{tone:`error`,variant:`fill`,titleSlot:`Failed to load prompt blocks`,descriptionSlot:u.message})]}):f.length===0&&!l&&n===0?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:U9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(HPr,{})]}):(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:U9}),headerActions:(0,K.jsx)(jgi,{}),actionRow:(0,K.jsx)(iq,{children:(0,K.jsx)(iq.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(PU,{onSearch:g,label:`Filter prompts`,placeholder:`Filter by name or description`})})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(VPr,{promptBlocks:f,isLoading:l,search:e,currentPage:n,hasMore:p,onNextPage:m,onPrevPage:h,updatedSort:o?.direction,onSortChange:_})]})}var Fgi=[cF(`/resources`)],Igi=[{title:`Mastra APIs`,description:`Explore and test the available REST API endpoints with the interactive Swagger UI.`,icon:Tee,href:`/swagger-ui`,external:!1},{title:`Documentation`,description:`Read the official Mastra documentation for guides, references, and tutorials.`,icon:ln,href:`https://mastra.ai/en/docs`,external:!0},{title:`Github`,description:`Browse the source code, report issues, and contribute to the Mastra project.`,icon:Lr,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:lr,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:Dn,href:`https://mastra.ai/contact?ref=studio`,external:!0}];function Lgi(){return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:Fgi}),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:Igi.map(e=>(0,K.jsxs)(`a`,{href:e.href,...e.external?{target:`_blank`,rel:`noreferrer`}:{},className:`group state-layer flex flex-col gap-3 rounded-lg border border-border bg-background 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:H(`h-5 w-5 text-muted-foreground group-hover:text-info-indicator`,$e)}),(0,K.jsx)(U,{as:`span`,variant:`subheading`,tone:`ink`,children:e.title}),e.external&&(0,K.jsx)(Lr,{className:`ml-auto h-3.5 w-3.5 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100`})]}),(0,K.jsx)(U,{variant:`caption`,tone:`muted`,children:e.description})]},e.href))})})]})}function Rgi(){let{isCmsAvailable:e}=Z2(),{paths:t}=gl();return e?(0,K.jsx)(d4n,{href:t.cmsScorersCreateLink(),tooltip:`Create a scorer`,children:`New scorer`}):null}var W9=[cF(`/scorers`)];function zgi(){let{data:e={},isLoading:t,error:n}=tF(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)(`all`),[s,c]=(0,G.useState)();if(n&&YP(n))return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Scorers`}),(0,K.jsx)(fU,{variant:`fill`})]});if(n&&XP(n))return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Scorers`}),(0,K.jsx)(dU,{variant:`fill`,resource:`scorers`})]});if(n)return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Scorers`}),(0,K.jsx)(fw,{tone:`error`,variant:`fill`,titleSlot:`Failed to load scorers`,descriptionSlot:n.message})]});if(Object.keys(e).length===0&&!t)return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:W9}),headerActions:(0,K.jsx)(Rgi,{}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Scorers`}),(0,K.jsx)(bDr,{})]});let l=a!==`all`||r!==``;return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:W9}),headerActions:(0,K.jsx)(Rgi,{}),actionRow:(0,K.jsx)(SDr,{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)(yDr,{scorers:e,isLoading:t,search:r,sourceFilter:a,sort:s,onSortChange:(e,t)=>c({key:t,direction:e})})]})}var Bgi=[`input`,`entity`],Vgi={input:`Input`,entity:`Entity`};function Hgi(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 Ugi(){let[e,t]=(0,G.useState)(new Set),n=(0,G.useMemo)(()=>new Set(Bgi.filter(t=>!e.has(t))),[e]);return{visibleColumns:n,columns:(0,G.useMemo)(()=>Hgi(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 Wgi({visibleColumns:e,toggleColumn:t}){return(0,K.jsxs)(gE,{children:[(0,K.jsx)(gE.Trigger,{asChild:!0,children:(0,K.jsx)(X,{icon:(0,K.jsx)(_r,{}),children:`Columns`})}),(0,K.jsxs)(gE.Content,{align:`end`,children:[(0,K.jsx)(gE.Label,{children:`Toggle columns`}),Bgi.map(n=>(0,K.jsx)(gE.CheckboxItem,{checked:e.has(n),onClick:()=>t(n),children:Vgi[n]},n))]})]})}var Ggi=[cF(`/scorers`),VPt],Kgi=[`date`,`score`];function qgi(){let{scorerId:e}=Bb(),[t,n]=Qb(),r=t.get(`scoreId`)??void 0,[i,a]=(0,G.useState)(r),[o,s]=(0,G.useState)(!1),c=zb(),[l,u]=(0,G.useState)({value:`all`,label:`All Entities`,type:`ALL`}),{scorer:d,error:f}=pPt(e),p=Ugi(),{data:m={},isLoading:h,error:g}=FP(),{isLoading:_,error:v}=lP({}),{sort:y,onSortChange:b}=e5({searchParams:t,setSearchParams:n,allowedKeys:Kgi}),{data:x=[],isLoading:S,error:C,isFetchingNextPage:w,hasNextPage:T,setEndOfListElement:E}=fPt({scorerId:e,entityId:l?.value===`all`?void 0:l?.value,entityType:l?.type===`ALL`?void 0:l?.type}),D=(0,G.useMemo)(()=>tZ(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`;yw.error(`Error loading scorer: ${e}`)}},[f]),(0,G.useEffect)(()=>{if(g){let e=g instanceof Error?g.message:`Failed to load agents`;yw.error(`Error loading agents: ${e}`)}},[g]),(0,G.useEffect)(()=>{if(v){let e=v instanceof Error?v.message:`Failed to load workflows`;yw.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=YP(f)||YP(g)||YP(v),I=f&&XP(f),L=!F&&!I&&(f||g||v),R=!S&&D.length===0,ee=l?.value!==`all`,z=d?.source===`stored`,B=e?(0,K.jsx)(v7,{open:o,onOpenChange:s,initialScorerIds:[e],onSuccess:e=>void c(`/experiments/${e}`)}):null,V=z?(0,K.jsxs)(gE,{children:[(0,K.jsx)(gE.Trigger,{asChild:!0,children:(0,K.jsx)(X,{size:`icon-lg`,"aria-label":`Scorer actions menu`,children:(0,K.jsx)(jr,{})})}),(0,K.jsx)(gE.Content,{align:`end`,className:`w-48`,children:(0,K.jsxs)(gE.Item,{onSelect:()=>void c(`/cms/scorers/${e}/edit`),children:[(0,K.jsx)(Io,{}),` Edit scorer`]})})]}):null;if(F||I||L||R&&!ee){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)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:Ggi}),actionRow:!(F||I||L)&&V?(0,K.jsx)(iq,{children:(0,K.jsx)(iq.End,{children:V})}):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)(fU,{}):I?(0,K.jsx)(dU,{resource:`scorers`}):L?(0,K.jsx)(fw,{tone:`error`,titleSlot:`Failed to load scorer`,descriptionSlot:t}):(0,K.jsx)(hDr,{onRunExperiment:()=>s(!0)})}),B]})}return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:Ggi}),actionRow:(0,K.jsxs)(iq,{children:[(0,K.jsx)(iq.Start,{children:(0,K.jsx)(gDr,{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)(iq.End,{children:[(0,K.jsx)(Wgi,{visibleColumns:p.visibleColumns,toggleColumn:p.toggleColumn}),(0,K.jsx)(X,{variant:`primary`,onClick:()=>s(!0),icon:(0,K.jsx)(Yo,{}),children:`New experiment`}),V]})]}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(mDr,{scores:D,isLoading:S,selectedScoreId:i,isFetchingNextPage:w,hasNextPage:T,setEndOfListElement:E,onScoreClick:P,errorMsg:C?.message,columnsState:p,sort:y,onSortChange:b}),B]})}var Jgi=[{value:`system`,label:`System`,icon:(0,K.jsx)(so,{})},{value:`light`,label:`Light`,icon:(0,K.jsx)(ec,{})},{value:`dark`,label:`Dark`,icon:(0,K.jsx)(Bee,{})}];function Ygi(e,t){if(e.some(e=>e.value===t))return t;let[n]=e;return n?n.value:`system`}var Xgi=({value:e,onChange:t,options:n=Jgi,size:r=`md`,"aria-label":i=`Theme`,...a})=>{let{theme:o,setTheme:s}=_t(),c=e??o,l=t??s,u=Ygi(n,c);return(0,K.jsx)(C9n,{...a,"aria-label":i,iconOnly:!0,size:r===`xs`?`sm`:r,value:u,onValueChange:l,children:n.map(e=>(0,K.jsx)(w9n,{value:e.value,"aria-label":e.label,children:e.icon},e.value))})},Zgi=[cF(`/settings`)],Qgi=()=>{let{baseUrl:e,headers:t,apiPrefix:n}=jw();return(0,K.jsxs)(Jw,{variant:`fit`,breadcrumbs:(0,K.jsx)(DP,{crumbs:Zgi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Settings`}),(0,K.jsx)(nOr,{children:(0,K.jsxs)(`div`,{className:`mx-auto flex max-w-4xl flex-col gap-8`,children:[(0,K.jsxs)(M2,{children:[(0,K.jsxs)(eOr,{children:[(0,K.jsx)(N2,{children:`General`}),(0,K.jsx)(tOr,{children:`Stored in this browser.`})]}),(0,K.jsx)(VZ,{children:(0,K.jsx)(UZ,{label:`Theme`,description:`Customize the appearance of the studio.`,children:(0,K.jsx)(Xgi,{})})})]}),(0,K.jsxs)(M2,{children:[(0,K.jsxs)(eOr,{children:[(0,K.jsx)(N2,{children:`Mastra Connection`}),(0,K.jsx)(tOr,{children:`Configure the Mastra instance URL, API prefix, and request headers used by the studio.`})]}),(0,K.jsx)(aOr,{variant:`factory`,initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})]})]})})]})};function $gi(){let[e]=Qb(),t=zb(),n=e.get(`redirect`)||`/`;return(0,K.jsx)(dpi,{redirectUri:n,onSuccess:()=>{n.startsWith(`http`)?window.location.href=n:t(n,{replace:!0})},initialMode:`signup`})}function e_i({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)($c,{"aria-label":`Loading storage capabilities`}),(0,K.jsx)(U,{as:`span`,variant:`caption`,tone:`muted`,children:`Loading storage capabilities`})]}):(0,K.jsx)(fw,{variant:`fill`,titleSlot:r,descriptionSlot:i})]})}function t_i({current:e,features:t}){let n=O6(),r=k6(),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 n_i=[`traces`,`spans`],r_i={traces:{icon:(0,K.jsx)(sF,{}),label:`Traces`},spans:{icon:(0,K.jsx)(Fn,{}),label:`Spans`},threads:{icon:(0,K.jsx)(eo,{}),label:`Threads`}};function i_i({current:e,views:t=n_i,onViewChange:n}){return(0,K.jsx)(`nav`,{"aria-label":`Observability views`,children:(0,K.jsx)(zA,{value:e,defaultTab:e,onValueChange:n,children:(0,K.jsx)(RA,{variant:`pill-ghost`,children:t.map(e=>(0,K.jsxs)(BA,{value:e,children:[(0,K.jsx)(QC,{size:`xs`,children:r_i[e].icon}),(0,K.jsx)(U,{variant:`caption`,className:`text-inherit`,children:r_i[e].label})]},e))})})})}function a_i(){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)(Yw,{className:`h-control-md w-20 rounded-full`}),(0,K.jsx)(Yw,{className:`h-control-md w-20 rounded-full`})]})}function o_i({current:e,features:t,onViewChange:n,breadcrumbs:r,children:i}){let{views:a,isLoading:o,showSwitch:s}=t_i({current:e,features:t}),[c,l]=(0,G.useState)(null),u=z0r(),d;return o?d=(0,K.jsx)(a_i,{}):s&&(d=(0,K.jsx)(i_i,{current:e,views:a,onViewChange:n})),(0,K.jsx)(Jw,{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)(H4r.Provider,{value:c??void 0,children:i})})}function s_i(e){return[`observability-list-head`,...e]}function c_i(e){let t=Ty([e]),[n,r]=(0,G.useState)();return{anchorTo:n?.selectionHash===t?n.to:void 0,reanchor:()=>r({selectionHash:t,to:new Date().toISOString()})}}var l_i=()=>({rows:[],watermark:void 0});function u_i({queryKey:e,fetchHead:t,getId:n,getEndedAt:r,enabled:i,since:a,limit:o=50,maxRows:s=500,interval:c=S1r,onOverflow:l}){let u=xy(),d=s_i(e),{data:f}=Iy({queryKey:d,queryFn:async()=>{let e=u.getQueryData(d)??l_i(),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?.(),l_i();let m=c.length>0?Math.max(e.watermark??-1/0,...c):e.watermark;return{rows:[...f.values()],watermark:m}},initialData:l_i,staleTime:1/0,enabled:i,refetchInterval:e=>!w1r(e.state.error)&&c,refetchOnWindowFocus:!1,refetchOnReconnect:!1,retry:!1});return{headRows:f.rows}}var d_i={refetchInterval:({state:e})=>E1r(e.error),refetchOnWindowFocus:!1};function f_i(e){let[t,n]=(0,G.useState)(()=>new URLSearchParams);return e||{searchParams:t,setSearchParams:e=>n(t=>typeof e==`function`?e(t):e)}}function p_i(e,{sortFields:t,defaultDatePreset:n=t5}={}){let{searchParams:r,setSearchParams:i}=f_i(e),a=JSON.stringify(X0r(r,n)),o=JSON.stringify(Q0r(r)),{datePreset:s,dateFrom:c,dateTo:l}=(0,G.useMemo)(()=>X0r(r,n),[a]),{tokens:u,groups:d}=(0,G.useMemo)(()=>Q0r(r),[o]),f=e2r(r,t??U0r),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=xUr(s,m===void 0?void 0:new Date(m),h===void 0?void 0:new Date(h));return k3(e.dateFrom,e.dateTo,new Date)},[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=>Z0r(t,e(X0r(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=w0r(b.current,n,e,t),{datePreset:`custom`,dateFrom:e,dateTo:t})),E=e=>y(t=>{let n=T0r(b.current,t);return b.current=void 0,n??{datePreset:e}}),D=(e,t)=>v(n=>$0r(n,{tokens:e,groups:t})),O=e=>v(t=>t2r(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 m_i(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 h_i(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),m_i(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 g_i={traces:`Traces`,spans:`Spans`,threads:`Threads`};function __i({current:e,isLoading:t,showSwitch:n}){if(!(t||n||e===`traces`))return g_i[e]}function v_i(e){let t=e.get(`traceId`),n=e.get(`spanId`);return t&&n?{traceId:t,spanId:n}:void 0}function y_i(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 b_i({traceId:e,spanId:t}){return new URLSearchParams({traceId:e,spanId:t})}function x_i(e){return e.get(`threadId`)??void 0}function S_i(e,t){let n=new URLSearchParams(e);return t?n.set(`threadId`,t):n.delete(`threadId`),n}var C_i=e=>`${e.traceId}:${e.spanId}`;function w_i(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 T_i({query:e,rolling:t,autoRefetch:n=!0,limit:r,enabled:i=!0}){let a=Y(),{anchorTo:o,reanchor:s}=c_i(e),c=(0,G.useMemo)(()=>o?{...e,timeRange:{...e.timeRange,to:o}}:e,[e,o]),l=GRr({query:c,limit:r,enabled:i,queryOptions:d_i}),{headRows:u}=u_i({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:C_i,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&&h_i(f,u,{getId:C_i,compare:w_i(d),hasNextPage:l.hasNextPage}),[f,u,d,l.hasNextPage]);return{...l,spans:p}}function E_i(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 D_i({timeRange:e,where:t,onZoom:n}){let r=_Wr(),i=(0,G.useMemo)(()=>({timeRange:e,...t?{where:t}:{},interval:iJr(e).interval,measures:[...Zqr],limit:1}),[e,t]),a=!r.enabled||aJr(e),{data:o,isLoading:s,isError:c,isPlaceholderData:l}=DRr({request:i,enabled:!a,queryOptions:{placeholderData:Oy}}),u=(0,G.useMemo)(()=>uJr(o?.rows??[],e),[o,e]);return a?null:(0,K.jsx)(Kqr,{label:`Spans over time`,resourceLabel:`Spans`,buckets:u,isLoading:s,isError:c,isUpdating:l,onZoom:n&&(t=>n(dJr(u,t,e)))})}var O_i=[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`],k_i=[];function A_i({timeRange:e}){let t=Y(),{data:n}=E6(),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=k_i}=y3(),{data:l=k_i}=b3();return(0,G.useMemo)(()=>[V6,...N2r({withContextFields:r,withTimeToFirstChunk:i,withTimeToFirstToken:a,withOutcomeFields:o,withModelFields:s,entityNames:c,environments:l,valueSuggestions:n=>lzr(t,e,`spans`,n)})],[r,i,a,o,s,c,l,t,e])}function j_i({tokens:e,groups:t,onFiltersChange:n}){let r=(0,G.useMemo)(()=>Q3(e),[e]),i=(0,G.useMemo)(()=>{let e=$3([],t);return{...e,nodes:[H6,...r,...e.nodes]}},[r,t]),a=(0,G.useCallback)(e=>{let t=bBr({...e,nodes:e.nodes.filter(e=>l3(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(l3);a({...i,nodes:[...n,o,...s]})},[r,i,a])}}var M_i=e=>e;function N_i({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=A_i({timeRange:i}),{filterBarValue:h,onFilterBarChange:g}=j_i({tokens:a,groups:o,onFiltersChange:d});return(0,K.jsxs)(W6,{fields:m,operators:qzr,value:h,onValueChange:g,createItemId:M_i,describeSuggestionsError:f,maxDepth:3,"aria-label":`Span filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(W6.Chips,{renderChip:i=>i.fieldId===`timeRange`?(0,K.jsx)(U6,{preset:e,onPresetChange:s,dateFrom:t,dateTo:n,minDate:r,onDateChange:c,onDateRangeChange:l,disabled:p,presets:O_i,defaultPreset:m6.datePreset,onReset:u&&(()=>u(m6.datePreset))}):(0,K.jsx)(W6.Chip,{item:i})}),(0,K.jsx)(W6.Input,{placeholder:`Filter spans…`})]})}function P_i({selection:e,onSelectionChange:t,renderPanel:n,urlState:r}){let i=p_i(r,{sortFields:W0r}),{timeRange:a,tokens:o,groups:s}=i,c=O0r({scope:`spans`}),{data:l,isLoading:u}=E6(),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:VUr(c.preferences,{withTimeToFirstChunk:f,withTimeToFirstToken:p}),[c.preferences,u,f,p]),_=(0,G.useMemo)(()=>{let e=[`startedAt`];return f&&l?.capabilities.traceQueryTimeToFirstChunkSort&&y6(g,`timeToFirstChunk`)&&e.push(`timeToFirstChunkMs`),p&&l?.capabilities.traceQueryTimeToFirstTokenSort&&y6(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)(()=>I2r(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}=T_i({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(E_i),[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)(cWr,{toolbar:(0,K.jsxs)(K.Fragment,{children:[r&&(0,K.jsx)(Y4r,{page:`spans`,...r,columns:c}),(0,K.jsx)(iq,{children:(0,K.jsxs)(iq.Start,{children:[(0,K.jsx)(DWr,{scope:`spans`,value:c.preferences,onChange:c.setPreferences}),(0,K.jsx)(N_i,{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})]})})]}),chart:(0,K.jsx)(D_i,{timeRange:a,where:x,onZoom:({from:e,to:t})=>i.onZoom(e,t)}),error:D?(0,K.jsx)(T6,{error:O,resource:`spans`,errorTitle:`Failed to load spans`}):void 0,empty:M?(0,K.jsx)(dWr,{resource:`spans`,datePreset:i.datePreset,dateFrom:i.dateFrom,dateTo:i.dateTo}):void 0,children:(0,K.jsx)(WYr,{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 F_i({selection:e,spans:t,onSelect:n,onClose:r,onShowTrace:i}){let{data:a,isLoading:o}=x3({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)(f$r,{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 I_i({selection:e,spans:t,onSelect:n,onClose:r,onShowTrace:i}){let a=RE();Fii(e?`${e.traceId}:${e.spanId}`:void 0,r);let o=e?(0,K.jsx)(F_i,{selection:e,spans:t,onSelect:n,onClose:r,onShowTrace:i}):null;return a?(0,K.jsx)(zZ,{open:!!e,onClose:r,title:`Span details`,children:o}):o?(0,K.jsx)(O7,{owner:`span-detail`,children:(0,K.jsx)(zZ,{variant:`inline`,title:`Span details`,children:o})}):null}function L_i(){let{enabled:e,isLoading:t}=O6(),n=zb(),[r,i]=Qb();return(0,K.jsx)(e_i,{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)(P_i,{urlState:{searchParams:r,setSearchParams:i},selection:v_i(r),onSelectionChange:e=>i(t=>y_i(t,e),{replace:!0}),renderPanel:e=>(0,K.jsx)(I_i,{...e,onShowTrace:e=>n(`/traces?${b_i(e)}`)})})})}async function R_i(){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 z_i({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 B_i({repoOrSlug:e,owner:t}){let{templates:n}=await R_i(),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 z_i({repo:e,owner:t});if(r)return r;throw Error(`Template ${e} not found`)}return r}async function V_i({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(`
|
|
695
|
-
`).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 H_i=({queryOptions:e}={})=>Iy({queryKey:[`mastra-templates`],queryFn:R_i,...e}),U_i=({repoOrSlug:e,owner:t,queryOptions:n})=>Iy({queryKey:[`template-repo`,e,t],queryFn:()=>B_i({repoOrSlug:e,owner:t}),...n}),W_i=({repo:e,owner:t,branch:n,queryOptions:r})=>Iy({queryKey:[`template-repo-env-vars`,e,t,n],queryFn:()=>V_i({repo:e,owner:t,branch:n}),...r}),G_i=({queryOptions:e}={})=>{let t=Y();return Iy({queryKey:[`agent-builder-workflow`],queryFn:async()=>await t.getAgentBuilderAction(`merge-template`).details(),...e})},K_i=({queryOptions:e}={})=>{let t=Y();return Ry({mutationFn:async({runId:e})=>await t.getAgentBuilderAction(`merge-template`).createRun({runId:e}),...e})},q_i=({queryOptions:e}={})=>{let t=Y();return Ry({mutationFn:async({runId:e})=>await t.getAgentBuilderAction(`merge-template`).runById(e),...e})},J_i=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)},Y_i=(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=J_i(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=J_i(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}},X_i=(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)}},Z_i=(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}=Y_i(a,s,e);s=c,r(c),(a.runId||i||t)&&X_i(a.runId||i||t,c)}}catch(t){console.error(`💥 [processStream] Error processing template installation stream:`,t);let{newState:n}=Y_i({type:`error`,payload:{error:t instanceof Error?t.message:`Unknown error`}},s,e);r(n)}finally{a(!1),o.releaseLock()}}}},Q_i=({workflowInfo:e,queryOptions:t}={})=>{let n=Y(),{streamResult:r,isStreaming:i,processStream:a}=Z_i(e);return{streamInstall:Ry({mutationFn:async({inputData:e,selectedModel:t,runId:r})=>{for(let i=1;i<=3;i++)try{let i=n.getAgentBuilderAction(`merge-template`),o=new Rl;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}},$_i=({workflowInfo:e,queryOptions:t}={})=>{let n=Y(),{streamResult:r,isStreaming:i,processStream:a}=Z_i(e);return{observeInstall:Ry({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 evi(e){return e.replace(/\/$/,``).split(`/`).pop()}function tvi({templates:e,linkComponent:t,className:n,isLoading:r}){let i=t||`a`;return r?(0,K.jsx)(`div`,{className:H(`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:H(`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:H(ex,`state-layer grid w-full grid-cols-[1fr_auto] overflow-hidden rounded-lg`),children:[(0,K.jsxs)(i,{to:`/templates/${e.slug}`,className:H(`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:H(`grid w-full gap-0.5 px-4 py-3`,`[&_svg]:h-[1em] [&_svg]:w-[1em] [&_svg]:text-muted-foreground`),children:[(0,K.jsx)(U,{as:`h2`,tone:`ink`,children:e.title}),(0,K.jsx)(U,{className:H(Pw,$e),children:e.description}),(0,K.jsxs)(`div`,{className:`mt-3 hidden flex-wrap items-center gap-4 text-muted-foreground 2xl:flex`,children:[t&&(0,K.jsxs)(`ul`,{className:H(`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)(U,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(nF,{}),` `,e.agents.length]})}),e?.tools&&e.tools.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(U,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(oF,{}),` `,e.tools.length]})}),e?.networks&&e.networks.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(U,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(po,{}),` `,e.networks.length]})}),e?.workflows&&e.workflows.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(U,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(Ic,{}),` `,e.workflows.length]})}),e?.mcp&&e.mcp.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(U,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(rF,{}),` `,e.mcp.length]})})]}),t&&e.supportedProviders&&(0,K.jsx)(`small`,{children:(0,K.jsx)(U,{as:`span`,variant:`body`,children:`|`})}),(0,K.jsx)(`div`,{className:`flex items-center gap-4`,children:e.supportedProviders.map(e=>(0,K.jsx)(U,{tone:`muted`,as:`span`,variant:`body`,children:e},e))})]})]})]}),(0,K.jsx)(`a`,{href:e.githubUrl,className:H(`group ml-auto hidden items-center gap-2 pr-4`,`lg:flex`),target:`_blank`,rel:`noopener noreferrer`,children:(0,K.jsx)(U,{as:`span`,variant:`body`,children:(0,K.jsxs)(`span`,{className:H(`flex items-center gap-2 rounded bg-sidebar px-2 py-1`,qWe,Pw,$e),children:[(0,K.jsx)(GX,{}),` `,evi(e.githubUrl)]})})})]},e.slug)})})}function nvi({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:H(`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:H(`sticky top-0 mx-auto flex flex-wrap gap-4 bg-background py-5`,l),children:[(0,K.jsx)(NU,{label:`Search templates`,placeholder:`Search Template`,value:o,onValueChange:s}),(0,K.jsxs)(tj,{value:t,onValueChange:i,children:[(0,K.jsx)(rj,{"aria-label":`Filter by tag`,size:`md`,children:(0,K.jsx)(nj,{placeholder:`Select an option`})}),(0,K.jsx)(ij,{children:e.map(e=>(0,K.jsx)(aj,{value:e.value,children:e.label},e.value))})]}),(0,K.jsxs)(tj,{value:r,onValueChange:a,children:[(0,K.jsx)(rj,{"aria-label":`Filter by provider`,size:`md`,children:(0,K.jsx)(nj,{placeholder:`Select an option`})}),(0,K.jsx)(ij,{children:n.map(e=>(0,K.jsx)(aj,{value:e.value,children:e.label},e.value))})]}),c&&(0,K.jsx)(X,{onClick:c,icon:(0,K.jsx)(Bc,{}),children:`Reset`})]})}var rvi=[{id:`templates`,label:`Templates`}];function ivi(){let{data:e,isLoading:t}=H_i(),{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)},m=e=>{u(e)},h=()=>{o(`all`),c(`all`),u(``)},g=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))),_=l||a!==`all`||s!==`all`;return(0,K.jsxs)(Jw,{variant:`fit`,breadcrumbs:(0,K.jsx)(DP,{crumbs:rvi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Templates`}),(0,K.jsx)(qw,{children:(0,K.jsxs)(K$e,{children:[(0,K.jsx)(QC,{children:(0,K.jsx)(To,{})}),`Templates`]})}),(0,K.jsxs)(`div`,{className:H(`z-10 h-full w-full overflow-y-auto px-5 pb-12`),children:[(0,K.jsx)(nvi,{selectedTag:a,onTagChange:e=>p(e,`tag`),tagOptions:d,selectedProvider:s,onProviderChange:e=>p(e,`provider`),providerOptions:f,searchTerm:l,onSearchChange:m,onReset:_?h:void 0,className:`max-w-[80rem]`,isLoading:t}),(0,K.jsx)(tvi,{templates:g,linkComponent:Zb,className:`mx-auto max-w-[80rem]`,isLoading:t})]})]})}function avi({children:e,className:t}){return(0,K.jsx)(`div`,{className:H(`transition-height mt-12 rounded-lg border border-border px-4 py-5 lg:min-h-[25rem] lg:px-12`,t),children:e})}function ovi({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)(Ur,{}),title:`Template Installation Failed`};return(0,K.jsxs)(avi,{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)(U,{variant:`subheading`,tone:`ink`,children:s}),(0,K.jsx)(U,{tone:`muted`,children:a()})]})]}),t&&t.length>0&&(0,K.jsxs)(`details`,{children:[(0,K.jsx)(`summary`,{className:H(`text-muted-foreground hover:text-foreground`,`cursor-pointer text-center select-none`),children:(0,K.jsxs)(U,{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)(U,{as:`p`,variant:`column`,className:`text-destructive-foreground`,children:e.type===`typescript`?`🔴 TypeScript Error`:`⚠️ Lint Error`}),(0,K.jsx)(NT,{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:H(`text-muted-foreground hover:text-foreground`,`cursor-pointer text-center select-none`),children:(0,K.jsx)(U,{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)(NT,{className:`text-caption wrap-break-word whitespace-pre-wrap`,code:n})})]})]})}var svi=(0,G.createContext)(null);function cvi(){return(0,G.useContext)(svi)||{registerResetFn:()=>{},triggerReset:()=>{}}}var lvi=({defaultProvider:e,defaultModel:t,updateModel:n,resetModel:r})=>{let[i]=(0,G.useState)(e),[a]=(0,G.useState)(t),[o,s]=(0,G.useState)(t),[c,l]=(0,G.useState)(e||``),[u,d]=(0,G.useState)(!1),[f,p]=(0,G.useState)(!1),[m,h]=(0,G.useState)(!1),{data:g,isLoading:_}=pq(),v=Cw(),{models:y}=_q(),b=(0,G.useMemo)(()=>g?.providers||[],[g]);(0,G.useEffect)(()=>{s(t),l(e||``)},[t,e]);let x=uq(c),S=mq(b,x)?.id||x,C=async r=>{if(s(r),r&&S){d(!0);try{let e=await n({provider:S,modelId:r});console.info(`Model updated:`,e)}catch(n){s(t),l(e||``),console.error(`Failed to update model:`,n)}finally{d(!1)}}},w=e=>{let t=uq(e);l(t),t!==x&&(s(``),h(!0))},{registerResetFn:T}=cvi();if((0,G.useEffect)(()=>(T(()=>{if(!(f||m)&&x&&x!==i&&(!o||o===``)){l(uq(i)),s(a);let e=mq(b,i)?.id||i;e&&a&&n({provider:e,modelId:a}).catch(e=>{console.error(`Failed to reset model:`,e)})}}),()=>{T(null)}),[T,x,o,i,a,n,f,m,b]),_)return(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)($c,{}),(0,K.jsx)(U,{as:`span`,tone:`muted`,children:`Loading providers...`})]});let E=async()=>{if(!r)console.warn(`Reset model function not provided`);else try{d(!0),await r()}catch(e){console.error(`Failed to reset model:`,e)}finally{d(!1)}},D=mq(b,x);if(v.active&&v.pickerVisible===!1){let e=v.default&&v.default.provider&&v.default.modelId?`${v.default.provider}/${v.default.modelId}`:c&&o?`${c}/${o}`:`Locked by admin`;return(0,K.jsxs)(`div`,{className:H(ex,`flex items-center gap-2 rounded-md px-3 py-2`),"data-testid":`agent-metadata-model-locked`,children:[(0,K.jsx)(ja,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,K.jsx)(U,{as:`span`,variant:`caption`,tone:`ink`,className:`truncate`,children:e}),(0,K.jsx)(U,{as:`span`,variant:`meta`,tone:`muted`,className:`ml-auto shrink-0`,children:`Set by admin`})]})}let O=!!(x&&o)&&v.active&&v.allowed!==void 0&&!y.some(e=>uq(e.provider)===x&&e.model===o);return(0,K.jsxs)(`div`,{className:`@container`,children:[(0,K.jsxs)(`div`,{className:`flex w-full flex-col items-stretch gap-2 @xs:flex-row @xs:items-center`,children:[(0,K.jsx)(`div`,{className:`w-full @xs:w-2/5`,children:(0,K.jsx)(hq,{value:x,onValueChange:w,open:f,onOpenChange:p})}),(0,K.jsx)(`div`,{className:`w-full @xs:w-3/5`,children:(0,K.jsx)(gq,{llmId:x,value:o,onValueChange:C,open:m,onOpenChange:h})}),(0,K.jsx)(X,{variant:`default`,size:`icon-md`,onClick:E,disabled:u,tooltip:`Reset to original model`,children:(0,K.jsx)(ms,{})})]}),O&&(0,K.jsx)(`div`,{className:`p-2 pt-2`,"data-testid":`agent-metadata-model-stale-warning`,children:(0,K.jsx)(HA,{variant:`warning`,title:`Model not allowed`,children:(0,K.jsxs)(HA.Message,{children:[(0,K.jsxs)(`code`,{className:`rounded bg-fill-hover px-1 py-0.5`,children:[c,`/`,o]}),` `,`is no longer allowed by the admin policy. Pick a different model to save changes.`]})})}),D&&!D.connected&&(0,K.jsx)(`div`,{className:`p-2 pt-2`,children:(0,K.jsx)(HA,{variant:`warning`,title:`Provider not connected`,children:(0,K.jsxs)(HA.Message,{children:[`Set the`,` `,(0,K.jsx)(`code`,{className:`rounded bg-fill-hover px-1 py-0.5`,children:Array.isArray(D.envVar)?D.envVar.join(`, `):D.envVar}),` `,`environment`,` `,Array.isArray(D.envVar)&&D.envVar.length>1?`variables`:`variable`,` to use this provider.`]})})})]})};function uvi({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)(avi,{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)(U,{as:`h2`,variant:`heading`,tone:`muted`,className:H(`flex items-center gap-2`,`[&_svg]:h-[1.2em] [&_svg]:opacity-70 [&>svg]:w-[1.2em]`),children:[`Install Template `,(0,K.jsx)(Co,{})]}),(0,K.jsxs)(OA,{orientation:`horizontal`,children:[(0,K.jsx)(AA,{children:`Template AI Model Provider`}),(0,K.jsx)(a_t,{className:`flex-1`,children:(0,K.jsxs)(tj,{name:`template-provider`,value:t,onValueChange:n,children:[(0,K.jsx)(rj,{size:`md`,children:(0,K.jsx)(nj,{placeholder:`Select`})}),(0,K.jsx)(ij,{children:e.map(e=>(0,K.jsx)(aj,{value:e.value,children:e.label},e.value))})]})})]}),t&&Object.entries(r||{}).length>0&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(U,{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:H(`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)($c,{}),(0,K.jsxs)(U,{as:`span`,variant:`caption`,className:`block`,children:[` `,`Loading variables...`]})]}):Object.entries(r).map(([e,t])=>(0,K.jsxs)(G.Fragment,{children:[(0,K.jsxs)(OA,{className:`w-full`,children:[(0,K.jsx)(AA,{className:`sr-only`,children:`Key`}),(0,K.jsx)(lN,{name:`env-${e}`,value:e,disabled:!0,className:`w-full`})]}),(0,K.jsxs)(OA,{invalid:i.includes(e),className:`w-full`,children:[(0,K.jsx)(AA,{className:`sr-only`,children:`Value`}),(0,K.jsx)(lN,{name:e,value:t,onChange:o,autoComplete:`off`,className:`w-full`}),(0,K.jsx)(MA,{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)(U,{tone:`muted`,as:`span`,variant:`caption`,className:`block`,children:`And`})}),(0,K.jsx)(U,{as:`h3`,tone:`muted`,children:`Set AI Model for Template Installation`}),(0,K.jsx)(U,{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)(lvi,{defaultProvider:l||``,defaultModel:u||``,updateModel:d||(()=>Promise.resolve({message:`Updated`})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:`Provider`})]})]}),t&&!s&&(0,K.jsx)(X,{className:H(`state-layer mt-4 flex min-h-10 w-full items-center justify-center gap-2 rounded-lg bg-card 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)($c,{className:`h-4 w-4`}),` Installing...`]}):(0,K.jsxs)(K.Fragment,{children:[`Install `,(0,K.jsx)(Ht,{})]})})]})})}function dvi({data:e,className:t,labelsAreHidden:n,isLoading:r,LinkComponent:i}){let a=({children:e})=>n?(0,K.jsx)(bX,{children:e}):e;return!e||e.length===0?null:(0,K.jsx)(`dl`,{className:H(`grid grid-cols-[auto_1fr] content-start items-start gap-x-4`,t),children:e.map(({key:e,label:t,value:o,icon:s,separator:c},l)=>{let u=Array.isArray(o);return(0,K.jsxs)(G.Fragment,{children:[(0,K.jsxs)(`dt`,{className:H(`flex min-h-9 items-center justify-between gap-8 text-body text-muted-foreground`),children:[(0,K.jsxs)(`span`,{className:H(`flex items-center gap-2`,`[&>svg]:size-[1.4em] [&>svg]:text-muted-foreground [&>svg]:opacity-50`,{"[&>svg]:opacity-20":r}),children:[s,` `,(0,K.jsx)(a,{children:t})]}),!n&&(0,K.jsx)(`span`,{className:H(`text-muted-foreground`,`[&>svg]:size-[1em] [&>svg]:text-muted-foreground`),children:c})]}),(0,K.jsx)(`dd`,{className:H(`flex min-h-9 flex-wrap items-center gap-2 py-1 text-body text-wrap text-foreground`,`truncate [&>a]:flex [&>a]:min-h-7 [&>a]:w-auto [&>a]:max-w-full [&>a]:items-center [&>a]:gap-2 [&>a]:rounded-md [&>a]:bg-muted [&>a]:px-2 [&>a]:py-0.5 [&>a]:text-body [&>a]:leading-none [&>a]:text-foreground [&>a]:transition-colors`,`[&>a:hover]:bg-fill-subtle [&>a:hover]:text-foreground`,`[&>a>svg]:ml-[-0.5em] [&>a>svg]:size-[1em] [&>a>svg]:text-muted-foreground`),children:r?(0,K.jsx)(`span`,{className:H(`w-full rounded-e-lg bg-muted`),style:{width:`${Math.floor(Math.random()*61)+50}%`},children:`\xA0`}):u?o?.map(e=>e.path&&i?(0,K.jsx)(fvi,{description:e.description,children:(0,K.jsxs)(i,{href:e.path,children:[e?.name,` `,(0,K.jsx)(pt,{})]})},e.id):e.path?(0,K.jsx)(fvi,{description:e.description,children:(0,K.jsxs)(`a`,{href:e.path,children:[e?.name,` `,(0,K.jsx)(pt,{})]})},e.id):(0,K.jsx)(`span`,{children:e?.name},e.id)):(0,K.jsx)(K.Fragment,{children:o||(0,K.jsx)(U,{as:`span`,variant:`caption`,tone:`muted`,children:`n/a`})})})]},e??l)})})}function fvi({description:e,children:t}){return e?(0,K.jsxs)(YX,{children:[(0,K.jsx)(XX,{render:G.isValidElement(t)?t:void 0}),(0,K.jsx)(ZX,{className:`max-w-60 text-center`,children:e})]}):t}function pvi({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:H(`flex items-center gap-3`,`[&>svg]:h-[1.2em] [&>svg]:w-[1.2em] [&>svg]:opacity-50`,{"[&>svg]:opacity-20":r}),children:[(0,K.jsx)(To,{}),(0,K.jsx)(`h2`,{className:H({"flex min-w-[50%] rounded-lg bg-muted":r}),children:(0,K.jsx)(U,{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)(U,{tone:`muted`,className:H(`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:H(`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)(Yi,{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)(Oi,{className:`h-[1em] w-[1em] text-muted-foreground`}),(0,K.jsx)(U,{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)(U,{tone:`muted`,as:`p`,variant:`caption`,children:[(0,K.jsx)(U,{as:`span`,variant:`column`,children:`Branch name:`}),` `,(0,K.jsx)(FY,{children:o})]}),(0,K.jsx)(U,{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:H(`text-muted-foreground hover:text-foreground`,`mt-auto flex items-center gap-2`),children:[(0,K.jsx)(GX,{}),(0,K.jsx)(U,{as:`span`,variant:`body`,className:`block`,children:n?.split(`/`)?.pop()})]})]}),i&&(0,K.jsx)(dvi,{data:i,labelsAreHidden:!0,isLoading:r})]})]})}function mvi(e){switch(e){case`running`:return(0,K.jsx)($c,{size:`sm`,"aria-hidden":!0});case`success`:return(0,K.jsx)(Ln,{"aria-hidden":!0});case`failed`:return(0,K.jsx)(Bc,{"aria-hidden":!0});default:return null}}function hvi(){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 gvi({status:e,variant:t}){return t===`plain`?(0,K.jsx)(`span`,{className:H(`flex size-4 items-center justify-center self-center [&>svg]:size-4`,bt.colors,{"[&>svg]:text-success-indicator":e===`success`,"[&>svg]:text-destructive-foreground":e===`failed`}),children:e===`pending`?(0,K.jsx)(hvi,{}):mvi(e)}):(0,K.jsx)(`span`,{className:H(`flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none`,bt.colors,bt.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:mvi(e)})}function _vi({step:e,isActive:t,position:n,variant:r=`default`}){let i=t||e.status===`success`?`ink`:`muted`;return(0,K.jsxs)(`div`,{className:H(`grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none`,bt.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)(U,{as:`span`,tone:i,className:H(`flex min-w-6 justify-end`,bt.colors),children:[n,`.`]}),(0,K.jsxs)(`div`,{className:`min-w-0`,children:[(0,K.jsx)(U,{as:`h4`,tone:i,className:bt.colors,children:e.title}),e.description&&(0,K.jsx)(U,{tone:`faint`,className:H(`-mt-0.5`,{truncate:r===`plain`}),children:e.description})]})]}),(0,K.jsx)(gvi,{status:e.status,variant:r})]})}function vvi({currentStep:e,steps:t=[],className:n}){return(0,K.jsx)(`div`,{className:H(n),children:t.map((t,n)=>(0,K.jsx)(_vi,{step:t,isActive:e?.id===t.id,position:n+1},t.id))})}function yvi({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:H(`relative flex h-8 items-center justify-end`,bt.colors,{"bg-success-subtle":t.status===`success`&&e?.[n-1]?.status===`success`}),children:(0,K.jsx)(`div`,{className:H(`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`,bt.colors,bt.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)($c,{}):n+1})},t.id))}),(0,K.jsxs)(`div`,{className:H(`text-center text-caption text-muted-foreground`,bt.colors),children:[n,` of `,t,` steps completed`]})]})}function bvi({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...`}},m=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)(avi,{className:`mb-5 content-center space-y-6 text-muted-foreground`,children:[(0,K.jsxs)(`div`,{className:`text-center`,children:[(0,K.jsx)(U,{as:`h3`,variant:`heading`,tone:`ink`,children:p()}),(t?.runId||n)&&(0,K.jsxs)(U,{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)(yvi,{steps:m})}),s&&i===`error`&&(0,K.jsxs)(`div`,{className:H(`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)(yo,{}),(0,K.jsx)(U,{as:`span`,variant:`body`,className:`block`,children:s||`Something went wrong`})]}),l&&(0,K.jsx)(vvi,{steps:m,currentStep:o,className:`pb-4`}),!l&&i===`initializing`&&(0,K.jsxs)(`div`,{className:H(`text-muted-foreground`,`grid justify-items-center gap-4 text-center`),children:[(0,K.jsx)($c,{}),(0,K.jsx)(U,{as:`p`,variant:`body`,children:`This may take some time...`})]})]})}function xvi({name:e,installedEntities:t}){return(0,K.jsxs)(avi,{className:H(`grid content-center items-center justify-items-center gap-4`,`[&>svg]:h-8 [&>svg]:w-8`),children:[(0,K.jsx)(Co,{}),(0,K.jsx)(U,{as:`h2`,variant:`heading`,children:`Done!`}),(0,K.jsxs)(U,{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)(dvi,{data:t})]})}function Svi(){let{templateSlug:e}=Bb(),t=[{id:`templates`,label:`Templates`,to:`/templates`},{id:`template`,label:RPt(e)}],[n,r]=Qb(),[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)([]),[m,h]=(0,G.useState)(null),[g,_]=(0,G.useState)(!1),[v,y]=(0,G.useState)(``),[b,x]=(0,G.useState)(!1),[S,C]=(0,G.useState)(!1),[w,T]=(0,G.useState)([]),{data:E,isLoading:D}=U_i({repoOrSlug:e,owner:`mastra-ai`}),O=`1.81.0-alpha.2`.includes(`beta`)??!1?`beta`:`main`,{data:k,isLoading:A}=W_i({repo:E?.githubUrl?new URL(E.githubUrl).pathname.split(`/`)[2]:`template-${e}`,owner:`mastra-ai`,branch:O}),{data:j,isLoading:M}=G_i(),{mutateAsync:N,isPending:P}=K_i(),{mutateAsync:F}=q_i(),{streamInstall:I,streamResult:L,isStreaming:R}=Q_i({workflowInfo:j}),{observeInstall:ee,streamResult:z,isStreaming:B}=$_i({workflowInfo:j});(0,G.useEffect)(()=>{let e=n.get(`runId`);!e||g||m||R||B||(console.info(`🔄 Checking completed run after hot reload:`,{runId:e}),y(e),F({runId:e}).then(e=>{let t=e.snapshot;if(t?.status===`success`&&t?.result?.success)_(!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.`;h(r),T(n||[])}else{let e=t?.result?.message||t?.result?.error||`Template installation failed`;h(typeof e==`string`?e:String(e))}}}).catch(e=>{console.error(`❌ Failed to fetch run details:`,e),h(`Failed to retrieve installation status after reload`)}))},[n,g,m,R,B,F]),(0,G.useEffect)(()=>{let e=n.get(`runId`),t=n.get(`resume`),i=n.get(`provider`);if(e&&t===`true`&&i&&!R&&!B&&!b&&!S&&j){y(e),x(!0);try{F({runId:e}).then(t=>{if(t.snapshot?.status===`running`)return ee.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`)?h(`Template installation run not found. It may have expired or been completed.`):h(`Failed to resume template installation. Please try again.`)})}catch(e){console.error(`❌ Auto-resume failed with error:`,e),h(`Failed to resume template installation. Please refresh and try again.`)}}},[n,e,R,B,b,S,j,F,ee,r]);let V=[{value:`openai`,label:`OpenAI`},{value:`anthropic`,label:`Anthropic`},{value:`groq`,label:`Groq`},{value:`google`,label:`Google`}],te=[{key:`tools`,label:`Tools`,value:E?.tools?.length?E.tools.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(oF,{})},{key:`agents`,label:`Agents`,value:E?.agents?.length?E.agents.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(nF,{})},{key:`workflows`,label:`Workflows`,value:E?.workflows?.length?E.workflows.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(Ic,{})},{key:`providers`,label:`Providers`,value:E?.supportedProviders?.length?E.supportedProviders.join(`, `):`n/a`,icon:(0,K.jsx)(Cn,{})},{key:`tags`,label:`Tags`,value:E?.tags?.length?E.tags.join(`, `):`n/a`,icon:(0,K.jsx)(nc,{})}],ne=[{...te[0]},{...te[1]},{...te[2]}].filter(e=>e.value!==`n/a`);return(0,G.useEffect)(()=>{k&&d(k)},[k]),(0,G.useEffect)(()=>{let e=L||z;e?.phase===`error`&&e?.error&&h(typeof e.error==`string`?e.error:String(e.error))},[L?.phase,L?.error,z?.phase,z?.error]),(0,K.jsxs)(Jw,{variant:`fit`,breadcrumbs:(0,K.jsx)(DP,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(`div`,{className:H(`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)(pvi,{isLoading:D,title:E?.title,description:E?.longDescription,imageURL:E?.imageURL,githubUrl:E?.githubUrl,infoData:te,templateSlug:e}),E&&(0,K.jsxs)(K.Fragment,{children:[(R||B)&&(0,K.jsx)(bvi,{name:E.title,streamResult:B?z:L,runId:v,workflowInfo:j}),g&&(0,K.jsx)(xvi,{name:E.title,installedEntities:ne,linkComponent:Zb}),m&&(0,K.jsx)(ovi,{errorMsg:m,validationErrors:w.length>0?w:L?.validationResults?.errors||z?.validationResults?.errors}),!R&&!B&&!g&&!m&&(0,K.jsx)(uvi,{providerOptions:V,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(E){h(null),_(!1),y(``),C(!0);try{let e={repo:E.githubUrl||`https://github.com/mastra-ai/template-${E.slug}`,ref:O,slug:E.slug,variables:u},{runId:t}=await N({});y(t),r(e=>{let n=new URLSearchParams(e);return n.set(`runId`,t),n.set(`resume`,`true`),n.set(`provider`,i||`openai`),n}),await I.mutateAsync({inputData:e,selectedModel:{provider:o,modelId:c},runId:t})}catch(e){C(!1),h(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:A||M,isInstalling:P,defaultModelProvider:o,defaultModelId:c,onModelUpdate:async e=>(s(e.provider),l(e.modelId),{message:`Model updated successfully`})})]})]})})]})}var Cvi=e=>e.threadId;function wvi(e,t){return`traces`in e?{traces:{...e.traces,to:t}}:{threads:{...e.threads,to:t}}}var Tvi=e=>`traces`in e?e.traces:e.threads;function Evi(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 Dvi({query:e,rolling:t,autoRefetch:n=!0,limit:r,enabled:i=!0}){let a=Y(),{anchorTo:o,reanchor:s}=c_i(e),c=(0,G.useMemo)(()=>o?{...e,timeRange:wvi(e.timeRange,o)}:e,[e,o]),l=qRr({query:c,limit:r,enabled:i,queryOptions:d_i}),{headRows:u}=u_i({queryKey:[`threads`,e],fetchHead:async t=>(await a.queryTraceThreads({...e,timeRange:wvi(e.timeRange,t),orderBy:[{field:`endedAt`,direction:`desc`}],page:{limit:50}})).threads,getId:Cvi,getEndedAt:e=>e.endedAt,since:Date.parse(Tvi(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&&h_i(f,u,{getId:Cvi,compare:Evi(d),hasNextPage:l.hasNextPage}),[f,u,d,l.hasNextPage]);return{...l,threads:p}}function Ovi(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 kvi=[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`],Avi=[];function jvi(){let{data:e}=E6(),t=e?.capabilities.traceQueryTimeToFirstChunk??!1,n=e?.capabilities.traceQueryTimeToFirstToken??!1,{data:r=Avi}=y3(),{data:i=Avi}=b3();return(0,G.useMemo)(()=>[V6,...Y2r({withTimeToFirstChunk:t,withTimeToFirstToken:n,entityNames:r,environments:i})],[t,n,r,i])}function Mvi({tokens:e,groups:t,onFiltersChange:n}){let r=(0,G.useMemo)(()=>Q3(e),[e]),i=(0,G.useMemo)(()=>{let e=$3([],t);return{...e,nodes:[H6,...r,...e.nodes]}},[r,t]),a=(0,G.useCallback)(e=>{let t=bBr({...e,nodes:e.nodes.filter(e=>l3(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(l3);a({...i,nodes:[...n,o,...s]})},[r,i,a])}}var Nvi=e=>e;function Pvi({datePreset:e,dateFrom:t,dateTo:n,minDate:r,tokens:i,groups:a,onDatePresetChange:o,onDateChange:s,onDateRangeChange:c,onFiltersChange:l,disabled:u}){let d=jvi(),{filterBarValue:f,onFilterBarChange:p}=Mvi({tokens:i,groups:a,onFiltersChange:l});return(0,K.jsxs)(W6,{fields:d,operators:qzr,value:f,onValueChange:p,createItemId:Nvi,maxDepth:3,"aria-label":`Thread filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(W6.Chips,{renderChip:i=>i.fieldId===`timeRange`?(0,K.jsx)(U6,{preset:e,onPresetChange:o,dateFrom:t,dateTo:n,minDate:r,onDateChange:s,onDateRangeChange:c,disabled:u,presets:kvi,defaultPreset:m6.datePreset}):(0,K.jsx)(W6.Chip,{item:i})}),(0,K.jsx)(W6.Input,{placeholder:`Filter threads…`})]})}function Fvi({selectedThreadId:e,onSelectedThreadChange:t,onOpenScore:n,urlState:r}){let i=p_i(r),{timeRange:a,tokens:o,groups:s,sort:c}=i,l=D6().enabled,u=xWr().enabled,d=O0r({scope:`threads`}),{data:f,isLoading:p}=E6(),m=f?.capabilities.traceQueryTimeToFirstChunk??!1,h=f?.capabilities.traceQueryTimeToFirstToken??!1,g=(0,G.useMemo)(()=>p?d.preferences:VUr(d.preferences,{withTimeToFirstChunk:m,withTimeToFirstToken:h}),[d.preferences,p,m,h]),{threads:_,hasNextPage:v,isFetchingNextPage:y,setEndOfListElement:b,isLoading:x,isError:S,error:C}=Dvi({query:(0,G.useMemo)(()=>{let e=Q2r(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(Ovi),[_]),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)(cWr,{toolbar:(0,K.jsxs)(K.Fragment,{children:[r&&(0,K.jsx)(Y4r,{page:`threads`,...r,columns:d}),(0,K.jsx)(iq,{children:(0,K.jsxs)(iq.Start,{children:[(0,K.jsx)(DWr,{scope:`threads`,value:d.preferences,onChange:d.setPreferences}),(0,K.jsx)(Pvi,{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})]})})]}),error:S?(0,K.jsx)(T6,{error:C,resource:`threads`,errorTitle:`Failed to load threads`}):void 0,empty:D?(0,K.jsx)(dWr,{resource:`threads`,datePreset:i.datePreset,dateFrom:i.dateFrom,dateTo:i.dateTo}):void 0,children:(0,K.jsx)(WYr,{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)(N1r,{open:!!e,threadId:e??``,depth:1,closeLabel:`Close`,withQueryTrace:l,withFeedback:u,onOpenScore:n,onClose:()=>t(void 0)})]})}function Ivi(){let{enabled:e,isLoading:t}=k6(),n=zb(),[r,i]=Qb();return(0,K.jsx)(e_i,{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)(Fvi,{urlState:{searchParams:r,setSearchParams:i},selectedThreadId:x_i(r),onSelectedThreadChange:e=>i(t=>S_i(t,e),{replace:!0}),onOpenScore:(e,t)=>n(nq(e,t))})})}var Lvi=()=>(0,K.jsx)(fw,{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)(Lr,{}),children:`Workflows documentation`}),variant:`fill`});function Rvi(e,t,n){return tZ(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 zvi(e){return Object.keys(e.steps??{}).filter(t=>e.allSteps?.[t]?.isWorkflow)}function Bvi(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 Vvi(e,t,n){let r=Bvi(t),i=[],a=(e,o,s,c,l,u)=>{let d=zvi(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 Hvi=`auto 24rem minmax(0, 1fr) auto auto auto`;function Uvi({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:H(`w-6`,e&&`border-l border-border`)},t)),(0,K.jsxs)(`span`,{className:`relative w-6`,children:[(0,K.jsx)(`span`,{className:H(`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 Wvi({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:H(Nw,`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)(rt,{direction:`right`,className:`size-4`})}):(0,K.jsx)(`span`,{className:`size-5 shrink-0`,"aria-hidden":!0})})}var Gvi=e=>e.stopPropagation();function Kvi({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 qvi({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=Uq(c.name,50),d=Uq(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)(Wvi,{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:Gvi,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)(Uvi,{guides:e.guides,isLastChild:e.isLastChild}):null,(0,K.jsx)(`span`,{className:`truncate`,children:u}),c.origin===`dynamic`?(0,K.jsx)(hT,{size:`xs`,variant:`blue`,title:`Registered via the dynamic-workflows API`,children:`Dynamic`}):null,h?(0,K.jsxs)(U,{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)(Ic,{"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)(jo,{"aria-hidden":!0,className:`size-3.5`}),m]}):``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:f||``})]})]})}function Jvi({workflows:e,isLoading:t,search:n=``,sort:r,onSortChange:i,requestContext:a}){let[o,s]=(0,G.useState)(new Set),c=wkt({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)(()=>Rvi(u,r,c),[u,r,c]),f=(0,G.useMemo)(()=>Vvi(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:m,getRowProps:h}=$X({count:p.size,global:!0}),g=e=>{s(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})};return t?(0,K.jsx)(OU,{columns:Hvi,fit:`container`}):(0,K.jsxs)(Z,{columns:Hvi,fit:`container`,scrollRef:m,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)(Kvi,{sortKey:`name`,sort:r,onSortChange:i,children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`Description`}),(0,K.jsx)(Kvi,{sortKey:`running`,sort:r,onSortChange:i,children:`Running`}),(0,K.jsx)(Kvi,{sortKey:`suspended`,sort:r,onSortChange:i,children:`Pending input`}),(0,K.jsx)(Kvi,{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=()=>g(e.pathKey);return e.kind===`unregistered`?(0,K.jsxs)(Z.RowStatic,{className:`gap-0 px-0`,children:[(0,K.jsx)(Wvi,{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)(Uvi,{guides:e.guides,isLastChild:e.isLastChild}),(0,K.jsx)(`span`,{className:`truncate`,children:Uq(e.stepId,50)}),(0,K.jsxs)(JC,{children:[(0,K.jsx)(YC,{render:(0,K.jsx)(U,{as:`span`,variant:`body-sm`,tone:`muted`}),role:`note`,tabIndex:0,className:H(`shrink-0 rounded-sm`,vt),children:`not registered`}),(0,K.jsx)(XC,{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:Uq(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)(qvi,{row:e,isExpanded:t,onToggle:n,runCount:c[e.workflow.id],rowProps:h(p.get(e.pathKey)??-1)},`workflow-${e.pathKey}`)})]})}var G9=[cF(`/workflows`)];function Yvi(){let{data:e,isLoading:t,error:n}=lP(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)();return n&&YP(n)?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:G9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(fU,{variant:`fill`})]}):n&&XP(n)?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:G9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(dU,{variant:`fill`,resource:`workflows`})]}):n?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:G9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(fw,{tone:`error`,variant:`fill`,titleSlot:`Failed to load workflows`,descriptionSlot:n.message})]}):Object.keys(e||{}).length===0&&!t?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:G9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(Lvi,{})]}):(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:G9}),actionRow:(0,K.jsxs)(iq,{children:[(0,K.jsx)(iq.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(PU,{onSearch:i,label:`Filter workflows`,placeholder:`Filter by name or description`})})}),(0,K.jsx)(iq.End,{children:(0,K.jsx)(X,{render:(0,K.jsx)(Zb,{to:`/workflows/schedules`}),variant:`primary`,icon:(0,K.jsx)(An,{}),children:`Schedules`})})]}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(Jvi,{workflows:e||{},isLoading:t,search:r,sort:a,onSortChange:(e,t)=>o({key:t,direction:e})})]})}var Xvi={active:`bg-success-indicator`,paused:`bg-info-indicator`,completed:`bg-muted-foreground`},Zvi={active:`text-success-indicator`,paused:`text-info-indicator`,completed:`text-muted-foreground`},Qvi=({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 ${Xvi[e]}`,"aria-hidden":!0}),(0,K.jsx)(U,{as:`span`,variant:`caption`,className:Zvi[e],children:e})]});function $vi({status:e}){let{icon:t,color:n}=eyi(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)(U,{as:`span`,variant:`caption`,children:e})]})}function eyi(e){switch(e){case`success`:return{icon:(0,K.jsx)(Ln,{size:14}),color:`text-success-indicator`};case`failed`:return{icon:(0,K.jsx)(Bc,{size:14}),color:`text-destructive-foreground`};case`running`:return{icon:(0,K.jsx)($c,{}),color:`text-muted-foreground`};case`suspended`:return{icon:(0,K.jsx)(Jn,{size:14}),color:`text-info-indicator`};case`canceled`:return{icon:(0,K.jsx)(Zn,{size:14}),color:`text-muted-foreground`};case`pending`:case`waiting`:return{icon:(0,K.jsx)(cr,{size:14}),color:`text-muted-foreground`};default:return{icon:null,color:`text-muted-foreground`}}}var tyi=`auto auto auto auto 1fr`,nyi=3e4,ryi=3e5;function iyi({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}=$X({count:l}),f=-1;return t?(0,K.jsx)(OU,{columns:tyi}):e.length===0?(0,K.jsx)(U,{variant:`body`,tone:`muted`,className:`p-4`,children:`No trigger history yet.`}):(0,K.jsxs)(Z,{columns:tyi,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=lT(t,{signed:!0}),i=e.outcome===`failed`,a=i?e.error:e.run?.error,l=Math.abs(t),u=!i&&l>nyi&&l<=ryi,p=`${e.scheduleId}-${e.runId}-${e.actualFireAt}`,m=c(e);m&&(f+=1);let h=(0,K.jsx)(U,{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)(U,{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)($vi,{status:e.run.status}):(0,K.jsx)(U,{as:`span`,variant:`caption`,tone:`muted`,className:`inline-flex items-center gap-1.5 whitespace-nowrap`,children:`pending`}),a?(0,K.jsxs)(JC,{children:[(0,K.jsx)(YC,{asChild:!0,children:(0,K.jsx)(`span`,{className:`inline-flex text-destructive-foreground`,children:(0,K.jsx)(Cc,{size:14})})}),(0,K.jsx)(XC,{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)(TT,{value:e.actualFireAt}):`—`,u?(0,K.jsxs)(JC,{children:[(0,K.jsx)(YC,{asChild:!0,children:(0,K.jsx)(`span`,{className:`inline-flex text-info-indicator`,children:(0,K.jsx)(Cc,{size:14})})}),(0,K.jsxs)(XC,{children:[`Published `,r,` after the scheduled fire time`]})]}):null]})}),(0,K.jsx)(Z.Cell,{children:e.run?(0,K.jsx)(U,{as:`span`,variant:`body-sm`,font:`mono`,children:lT(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 ayi={id:`workflow-schedules`,label:`Schedules`,icon:An,to:`/workflows/schedules`};function oyi({label:e,children:t}){return(0,K.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,K.jsx)(U,{variant:`meta`,tone:`muted`,className:`uppercase`,children:e}),(0,K.jsx)(`div`,{children:(0,K.jsx)(U,{as:`span`,variant:`body`,className:`block`,children:t})})]})}function syi(){let{scheduleId:e}=Bb(),t=[cF(`/workflows`),ayi,{id:`schedule`,label:RPt(e),icon:An}],{paths:n}=gl(),{data:r,error:i}=nFt({scheduleId:e,queryOptions:{enabled:!!e}}),{data:a,isLoading:o,error:s,hasNextPage:c,isFetchingNextPage:l,setEndOfListElement:u}=iFt({scheduleId:e,queryOptions:{enabled:!!e}}),d=aFt({scheduleId:e});if(i&&YP(i))return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(fU,{variant:`fill`})]});if(i&&XP(i))return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(dU,{variant:`fill`,resource:`schedules`})]});if(i)return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(fw,{tone:`error`,variant:`fill`,titleSlot:`Failed to load schedule`,descriptionSlot:i.message})]});let f=r?.workflowId,p=r?.agentId;return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:t}),actionRow:(0,K.jsx)(iq,{children:(0,K.jsxs)(iq.End,{children:[(0,K.jsx)(X,{render:(0,K.jsx)(Zb,{to:n.schedulesLink()}),variant:`ghost`,icon:(0,K.jsx)(Rt,{}),children:`Back to schedules`}),f?(0,K.jsx)(X,{icon:(0,K.jsx)(aP,{}),render:(0,K.jsx)(Zb,{to:n.workflowLink(f)}),variant:`ghost`,children:`Open workflow`}):null,r?(0,K.jsx)(X,{onClick:()=>{let e=r.status===`active`?`pause`:`resume`;d.mutate(e,{onSuccess:()=>yw.success(e===`pause`?`Schedule paused`:`Schedule resumed`),onError:e=>yw.error(e.message)})},disabled:d.isPending,"data-testid":`schedule-toggle-button`,children:r.status===`active`?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(jo,{}),`Pause`]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Go,{}),`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)(oyi,{label:p?`Agent`:`Workflow`,children:f?(0,K.jsx)(Zb,{to:n.workflowLink(f),className:`text-foreground hover:underline`,children:f}):p?(0,K.jsx)(Zb,{to:n.agentLink(p),className:`text-foreground hover:underline`,children:p}):`—`}),(0,K.jsxs)(oyi,{label:`Cron`,children:[(0,K.jsx)(U,{as:`span`,variant:`body`,font:`mono`,children:r.cron}),r.timezone?(0,K.jsx)(U,{as:`span`,variant:`caption`,tone:`muted`,className:`ml-2`,children:r.timezone}):null]}),(0,K.jsx)(oyi,{label:`Status`,children:(0,K.jsx)(Qvi,{status:r.status})}),(0,K.jsx)(oyi,{label:`Next fire`,children:r.nextFireAt?(0,K.jsx)(TT,{value:r.nextFireAt}):`—`})]}),(0,K.jsxs)(`div`,{className:`overflow-y-auto`,"data-testid":`schedule-triggers-panel`,children:[(0,K.jsx)(U,{variant:`body`,className:`mb-3`,children:`Trigger history`}),s?(0,K.jsx)(fw,{tone:`error`,titleSlot:`Failed to load trigger history`,descriptionSlot:s.message}):(0,K.jsx)(iyi,{triggers:a??[],isLoading:o,workflowId:f,hasNextPage:c,isFetchingNextPage:l,setEndOfListElement:u})]})]}):null]})}var cyi={target:e=>e.workflowId??e.agentId??``,status:e=>e.status,nextFireAt:e=>e.nextFireAt,lastFireAt:e=>e.lastFireAt},lyi=`minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto`;function uyi({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 tZ(t?e.filter(e=>e.id.toLowerCase().includes(t)||(e.workflowId??e.agentId??``).toLowerCase().includes(t)):e,r,cyi)},[e,n,r]),{containerRef:c,getRowProps:l}=$X({count:s.length,global:!0});if(t)return(0,K.jsx)(OU,{columns:lyi});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:lyi,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)(U,{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)(U,{as:`span`,variant:`caption`,font:`mono`,children:e.cron}),e.timezone?(0,K.jsx)(U,{as:`span`,variant:`meta`,tone:`muted`,children:e.timezone}):null]})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(Qvi,{status:e.status})}),(0,K.jsx)(Z.Cell,{children:e.nextFireAt?(0,K.jsx)(TT,{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)($vi,{status:e.lastRun.status}),e.lastFireAt?(0,K.jsx)(U,{as:`span`,variant:`caption`,tone:`muted`,children:(0,K.jsx)(TT,{value:e.lastFireAt})}):null]}):e.lastFireAt?(0,K.jsx)(TT,{value:e.lastFireAt}):(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`Never`})})]},e.id))]})}function dyi({workflowId:e}={}){let{data:t,isLoading:n,error:r}=dF(e?{workflowId:e}:{}),[i,a]=(0,G.useState)(``),[o,s]=(0,G.useState)();return r?(0,K.jsx)(fw,{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)(PU,{onSearch:a,label:`Filter schedules`,placeholder:`Filter by id or workflow`})}),(0,K.jsx)(`div`,{className:`overflow-y-auto`,children:(0,K.jsx)(uyi,{schedules:t??[],isLoading:n,search:i,sort:o,onSortChange:(e,t)=>s({key:t,direction:e})})})]})}var fyi=[cF(`/workflows`),ayi];function pyi(){let[e]=Qb(),t=e.get(`workflowId`)??void 0,{error:n}=dF(t?{workflowId:t}:{});return n&&YP(n)?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:fyi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(fU,{variant:`fill`})]}):n&&XP(n)?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:fyi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(dU,{variant:`fill`,resource:`schedules`})]}):(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:fyi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(`div`,{className:`h-full`,children:(0,K.jsx)(dyi,{workflowId:t})})]})}var myi={"--belt-hue":`var(--warning-indicator)`};function hyi(e){let t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function gyi(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 _yi({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:(0,K.jsxs)(`section`,{className:H(Rkt,`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)(U,{as:`h2`,variant:`column`,tone:`ink`,className:`flex items-center gap-2`,children:[(0,K.jsx)(QC,{children:(0,K.jsx)(Jn,{})}),`Step suspended`]}),(0,K.jsx)(hT,{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?fA(TA(n.resumeSchema)):nm(q(),Yp());return(0,K.jsx)(vyi,{step:e,stepSchema:i,description:n.description,onResume:r},`${e.runId}-${e.stepId}`)})]}),(0,K.jsx)(Ptt,{status:`ready`,label:`Needs input`,className:`before:hidden`,style:myi})]})}function vyi({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)(U,{as:`p`,variant:`subheading`,tone:`ink`,className:`break-words`,children:e.stepId}),n&&(0,K.jsx)(U,{as:`p`,variant:`caption`,tone:`muted`,children:n})]}),e.suspendPayload!==void 0&&(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsxs)(U,{as:`p`,variant:`caption`,tone:`muted`,className:`flex items-center gap-2`,children:[(0,K.jsx)(QC,{children:(0,K.jsx)(Vee,{})}),`The step is asking`]}),(0,K.jsxs)(iT,{open:i,onOpenChange:a,children:[(0,K.jsxs)(aT,{className:H(`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)(QC,{children:(0,K.jsx)(rt,{direction:`right`,className:`text-muted-foreground`})}),(0,K.jsx)(U,{as:`span`,variant:`body`,tone:`ink`,className:`truncate`,children:gyi(e.suspendPayload,e.stepId)})]}),(0,K.jsx)(U,{as:`span`,variant:`caption`,tone:`muted`,className:`shrink-0`,children:hyi(e.suspendPayload)})]}),(0,K.jsx)(oT,{children:(0,K.jsx)(`div`,{"data-testid":`suspended-payload`,className:`pt-2`,children:(0,K.jsx)(BD,{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)(U,{as:`p`,variant:`caption`,tone:`muted`,className:`flex items-center gap-2`,children:[(0,K.jsx)(QC,{children:(0,K.jsx)(Hee,{})}),`Your response`]}),(0,K.jsx)(`div`,{className:`-mx-5`,children:(0,K.jsx)(ekt,{schema:t,isSubmitLoading:o,submitButtonLabel:`Resume`,submitButtonVariant:`primary`,submitButtonIcon:(0,K.jsx)(Go,{}),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){yw.error(e instanceof Error?e.message:`Error resuming workflow`)}finally{s(!1)}}})})]})]})}function yyi({hidden:e,requestContext:t,canResume:n}){let{result:r,workflow:i,runId:a,isStreamingWorkflow:o}=(0,G.useContext)(sT),s=Egt(r,a),c=jgt(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)(_yi,{suspendedSteps:s,workflow:i,isStreaming:o,onResume:c})},a)}var byi={success:{label:`Completed`,icon:Ln},failed:{label:`Failed`,icon:er},suspended:{label:`Needs input`,icon:jo},waiting:{label:`Waiting`,icon:_c},paused:{label:`Paused`,icon:jo},skipped:{label:`Skipped`,icon:zs},running:{label:`Running`,icon:Da},canceled:{label:`Canceled`,icon:Zn}},xyi={label:`Status unavailable`,icon:yee};function Syi({row:e,isSelected:t,isHovered:n,onSelectStep:r,onHoverStep:i,onOpenInput:a,onOpenOutput:o}){let s=Object.hasOwn(byi,e.status)?byi[e.status]:xyi,c=s.icon,l=G1e(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:H(`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:H(`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`,vt),children:[(0,K.jsx)(`span`,{"aria-label":s.label,className:H(`grid size-6 flex-none place-items-center rounded-md border border-border bg-background`,K1e[l]),children:(0,K.jsx)(c,{"aria-hidden":!0,className:H(`size-3.5`,e.status===`running`&&`motion-safe:animate-spin`)})}),(0,K.jsxs)(`span`,{className:`min-w-0`,children:[(0,K.jsx)(U,{as:`span`,variant:`meta`,className:`block truncate`,children:d}),e.isNestedEntry&&(0,K.jsxs)(U,{as:`span`,variant:`meta`,tone:`muted`,className:`flex min-w-0 items-center gap-1`,children:[(0,K.jsx)(Sr,{"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:H(`absolute top-0 h-full min-w-0.5 rounded-sm`,q1e[l]),style:{left:`${e.timing.offsetPct}%`,width:`${e.timing.widthPct}%`}})}),(0,K.jsx)(U,{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)(U,{as:`span`,variant:`meta`,font:`mono`,children:lT(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 Cyi=e=>e.includes(`.`),wyi=e=>e===`input`||e.endsWith(`.input`),Tyi=1;function Eyi(e,t){let n=H1e(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 Dyi(e,t){let n=Object.entries(e).filter(([e])=>!wyi(e)).map(([e,n])=>({stepId:e,step:n,...Eyi(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,Tyi),100-t)}}return{stepId:e,step:t,status:_T(t)?`suspended`:t.status,timing:s,spansSuspension:a,isRunning:r,isNestedEntry:Cyi(e)}})}function Oyi(){let{steps:e}=oQ(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:i}=cT(),[a,o]=(0,G.useState)(()=>Date.now()),[s,c]=(0,G.useState)(!0),[l,u]=(0,G.useState)(!1),{showData:d}=dP(),f=(0,G.useRef)(null),p=Dyi(e,a),m=p.some(e=>e.isRunning);return WQe(f,{enabled:m&&!s}),(0,G.useEffect)(()=>{if(!m||s)return;let e=setInterval(()=>o(Date.now()),100);return()=>clearInterval(e)},[m,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)(iT,{open:!s,onOpenChange:e=>c(!e),className:H(ex,`@container/workflow-timeline pointer-events-auto overflow-hidden rounded-xl`),children:[(0,K.jsxs)(`div`,{className:`flex items-center`,children:[(0,K.jsxs)(aT,{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)(Fn,{"aria-hidden":!0,className:`size-4 text-muted-foreground`})}),(0,K.jsx)(`span`,{children:`Timeline`}),(0,K.jsxs)(U,{as:`span`,variant:`meta`,tone:`muted`,children:[p.length,` events`]}),(0,K.jsx)(`span`,{className:`ml-auto`,children:(0,K.jsx)(rt,{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)(iee,{}):(0,K.jsx)(Bn,{})})]}),(0,K.jsx)(oT,{children:(0,K.jsx)(`div`,{ref:f,"data-testid":`workflow-timeline-list`,className:H(`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)(Syi,{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 kyi=({workflowId:e,workflow:t,isLoading:n})=>{let[r]=Qw(`workflow`,e),{canExecute:i,isLoading:a}=Tw(),{stepDetail:o}=dP(),s=RE(),c=o?.type===`data`,l=(0,K.jsxs)(`div`,{className:`[container-type:size] relative h-full min-h-0`,children:[(0,K.jsx)($tr,{workflowId:e,workflow:t,isLoading:n,requestContext:r}),(0,K.jsx)(yyi,{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)(cQ,{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)(Oyi,{})})]});return s&&o&&!c?(0,K.jsx)(`div`,{className:`h-full min-h-0 overflow-hidden`,children:(0,K.jsx)(cQ,{requestContext:r})}):(0,K.jsxs)(`div`,{className:`relative h-full min-h-0`,children:[l,(0,K.jsxs)(R4,{className:`pointer-events-none absolute inset-0 z-30 min-h-0 w-full min-w-0 p-2`,children:[(0,K.jsx)(L4,{id:`workflow-graph`,className:`pointer-events-none min-w-0`}),o&&!c&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(z4,{className:`pointer-events-auto`}),(0,K.jsx)(L4,{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)(cQ,{requestContext:r})})})]})]})]})},Ayi=()=>{let{workflowId:e}=Bb(),{data:t,isLoading:n,error:r}=uP({workflowId:e,requestContext:Qw(`workflow`,e)[0],queryOptions:{enabled:!!e}});return r&&YP(r)?(0,K.jsx)(fU,{variant:`fill`}):r&&XP(r)?(0,K.jsx)(dU,{variant:`fill`,resource:`workflows`}):(0,K.jsx)(kyi,{workflowId:e,workflow:t??void 0,isLoading:n})};function jyi(){let{workflowId:e}=Bb(),{error:t}=dF(e?{workflowId:e}:{});if(!e)return null;let n;return n=t&&YP(t)?(0,K.jsx)(fU,{variant:`fill`}):t&&XP(t)?(0,K.jsx)(dU,{variant:`fill`,resource:`schedules`}):(0,K.jsx)(`div`,{className:`h-full`,children:(0,K.jsx)(dyi,{workflowId:e})}),(0,K.jsxs)(Jw,{children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),n]})}function Myi(){let{workflowId:e}=Bb();return e?(0,K.jsx)(P3r,{scopedEntityId:e,scopedEntityType:Uh.WORKFLOW_RUN}):null}var Nyi=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;function Pyi(e){let t=Nyi.exec(e);return t?{frontmatter:t[1]??``,body:e.slice(t[0].length)}:{frontmatter:null,body:e}}var Fyi=(0,G.createContext)(null);function K9(){let e=(0,G.useContext)(Fyi);if(!e)throw Error(`Workspace components must be rendered inside <Workspace.Root>`);return e}function Iyi({content:e}){let{frontmatter:t,body:n}=Pyi(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)(uJ,{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)(_Y,{children:n})})]})}var Lyi=e=>e?.status;function Ryi(e,t){return YP(e)?`Your session has expired. Sign in again to continue.`:XP(e)?`You don't have permission to access this.`:ZP(e)?`This path no longer exists.`:Lyi(e)===501?`This workspace does not support this operation.`:t}function zyi({error:e,fallback:t,className:n}){return(0,K.jsx)(HA,{variant:`destructive`,className:n,children:(0,K.jsx)(HA.Message,{children:Ryi(e,t)})})}function Byi(){let{activeFilePath:e}=K9();return e?(0,K.jsx)(U,{as:`span`,variant:`body-sm`,font:`mono`,tone:`muted`,className:`truncate`,"data-testid":`workspace-file-path`,children:e}):null}function Vyi({path:e,content:t,mimeType:n}){return Zjn(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`})}):Qjn(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:${eMn(e,n)};base64,${t}`,type:eMn(e,n)})})}):tMn(e)?(0,K.jsx)(Iyi,{content:t}):(0,K.jsx)(uJ,{code:t,lang:Y0e(e),overflow:`scroll`,className:`rounded-none border-0 bg-transparent [&_pre]:p-4`})}function Hyi({renderPreview:e}){let{workspaceId:t,activeFilePath:n}=K9(),{data:r,isLoading:i,error:a}=gMn({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)(Yw,{className:`h-4 w-1/2`}),(0,K.jsx)(Yw,{className:`h-4 w-5/6`}),(0,K.jsx)(Yw,{className:`h-4 w-2/3`})]});if(!r)return(0,K.jsx)(zyi,{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)(Vyi,{...o})}var Uyi=(e,t)=>e===`.`?t:`${e}/${t}`,Wyi=e=>e.split(`/`).slice(0,-1).map((e,t,n)=>n.slice(0,t+1).join(`/`)),Gyi=e=>{let t=e.lastIndexOf(`/`);return t===-1?`.`:e.slice(0,t)};function Kyi({labeled:e=!1}={}){let{workspaceId:t,onCreateDirectory:n,isReadOnly:r}=K9(),i=xy(),[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`,Gyi(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)(UE,{open:a,onOpenChange:o,pending:l,children:(0,K.jsx)(WE,{size:`sm`,children:(0,K.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),f()},children:[(0,K.jsx)(GE,{children:(0,K.jsx)(JE,{children:`New folder`})}),(0,K.jsx)(qE,{children:(0,K.jsx)(lN,{autoFocus:!0,"aria-label":`Folder path`,placeholder:`docs/guides`,value:s,onChange:e=>c(e.target.value)})}),(0,K.jsxs)(KE,{children:[(0,K.jsx)(XE,{children:`Cancel`}),(0,K.jsx)(X,{type:`submit`,variant:`primary`,disabled:!d||l,children:`Create`})]})]})})})]})}var qyi=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`})}),Jyi=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 Yyi(){let{isSearching:e,setSearching:t,searchFiles:n,searchSkills:r}=K9();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)(Jyi,{})})}function Xyi(){let{isSearching:e}=K9();return e?(0,K.jsx)($yi,{}):(0,K.jsx)(Qyi,{})}var Zyi=(e,t)=>`${e} ${t}${e===1?``:`s`}`;function Qyi(){let{fileCount:e,skillCount:t}=K9();return(0,K.jsxs)(U,{as:`span`,variant:`label`,tone:`muted`,className:`block min-w-0 truncate`,children:[(0,K.jsx)(`span`,{children:e===void 0?`Files`:Zyi(e,`File`)}),t===void 0?null:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(U,{as:`span`,variant:`label`,tone:`faint`,"aria-hidden":!0,className:`mx-1.5`,children:`·`}),(0,K.jsx)(`span`,{children:Zyi(t,`Skill`)})]})]})}function $yi(){let{setSearching:e,setQuery:t}=K9(),[n,r]=(0,G.useState)(``),[,i]=(0,G.useTransition)();return(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(lN,{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)(Bc,{})})]})}function ebi(){let{workspaceId:e,query:t,activeFilePath:n,setActiveFilePath:r,searchFiles:i,searchSkills:a}=K9(),{data:o,isLoading:s,isError:c,error:l}=bMn({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)(Yw,{className:`h-4 w-3/4`}),(0,K.jsx)(Yw,{className:`h-4 w-2/3`})]}):c?(0,K.jsx)(zyi,{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:H(`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)(QC,{size:`sm`,children:e.kind===`skill`?(0,K.jsx)(KX,{}):(0,K.jsx)(qyi,{})}),(0,K.jsx)(U,{as:`span`,variant:`body-sm`,className:`truncate`,children:e.label})]})},e.path))}):(0,K.jsx)(fw,{titleSlot:`No results`}):(0,K.jsx)(fw,{titleSlot:`Search files and skills`,descriptionSlot:`Type to find matching content.`})}function tbi(e){return`${e.topSource}/${e.name}`}function nbi(e){let t=aMn(e.topSource,e.name);return t?`${t.owner}/${t.repo}/${e.name}`:null}function rbi({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,m]=(0,G.useState)(),h=s?.some(e=>e.path===p)?p:s?.[0]?.path,{data:g,isLoading:_}=rMn({workspaceId:n,queryOptions:{enabled:!!n}}),v=nMn({workspaceId:n}),y=(0,G.useMemo)(()=>d?.topSource?aMn(d.topSource,d.name):null,[d]),b=(0,G.useMemo)(()=>!y||!d?null:`https://skills.sh/${y.owner}/${y.repo}/${d.name}`,[y,d]),{data:x,isLoading:S}=iMn({workspaceId:n,owner:y?.owner,repo:y?.repo,skillPath:d?.name,queryOptions:{enabled:!!n&&!!y&&!!d}}),C=jT(e=>{e.trim().length>=2&&v.mutate(e)},300),w=(0,G.useCallback)(e=>{u(e),C(e)},[C]),T=(0,G.useMemo)(()=>l.trim().length>=2?v.data?.skills??[]:g?.skills??[],[l,v.data,g]),E=v.isPending,D=l.trim().length>=2,O=(0,G.useMemo)(()=>{if(!d)return!1;let e=nbi(d);return!!(e&&a.includes(e)||o.includes(d.name))},[d,a,o]),k=(0,G.useCallback)(()=>{d&&y&&r({repository:`${y.owner}/${y.repo}`,skillName:d.name,mount:s&&s.length>1?h:void 0})},[d,y,r,s,h]),A=(0,G.useCallback)(e=>{e||(u(``),f(null),m(void 0)),t(e)},[t]);return(0,K.jsx)(UE,{open:e,onOpenChange:A,pending:i,children:(0,K.jsxs)(WE,{size:`xl`,className:`h-[80vh]`,children:[(0,K.jsxs)(GE,{children:[(0,K.jsx)(JE,{children:`Add Skill`}),(0,K.jsx)(YE,{children:`Search and install skills from the community registry`})]}),(0,K.jsxs)(qE,{layout:`fill`,children:[(0,K.jsx)(NU,{label:`Search skills`,placeholder:`Search skills...`,value:l,onValueChange:w}),(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)(U,{as:`p`,variant:`eyebrow`,tone:`muted`,className:`mb-2`,children:D?`Search Results`:`Popular Skills`}),(0,K.jsx)(Kw,{className:`flex-1 rounded-lg border border-border`,children:(0,K.jsx)(Gw,{className:!_&&!E&&T.length===0?`flex flex-col [&>div]:flex [&>div]:flex-1 [&>div]:flex-col`:void 0,children:_||E?(0,K.jsx)(`div`,{className:`flex items-center justify-center py-5`,children:(0,K.jsx)(Da,{className:`size-6 animate-spin text-muted-foreground`})}):T.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)(Zn,{className:`mb-2 size-8`}),(0,K.jsx)(U,{children:D?`No skills found`:`No skills available`})]}):(0,K.jsx)(`div`,{className:`space-y-1 p-2`,children:T.map(e=>{let t=tbi(e),n=nbi(e),r=n&&a.includes(n)||o.includes(e.name),i=d?tbi(d):null;return(0,K.jsx)(`button`,{onClick:()=>f(e),className:H(`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)(U,{as:`span`,variant:`subheading`,tone:`ink`,className:`truncate`,children:e.name}),r&&(0,K.jsxs)(U,{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)(Ln,{className:`size-2.5`}),`Installed`]})]}),(0,K.jsx)(U,{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)(Or,{className:`size-3`}),(0,K.jsx)(U,{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)(U,{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)(KX,{className:`size-5 text-muted-foreground`})}),(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsx)(U,{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)(GX,{className:`size-3`}),(0,K.jsx)(U,{as:`span`,variant:`caption`,className:`block`,children:d.topSource})]}),(0,K.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(Or,{className:`size-3`}),(0,K.jsxs)(U,{as:`span`,variant:`caption`,className:`block`,children:[d.installs.toLocaleString(),` installs`]})]})]})]}),y&&(0,K.jsx)(`a`,{href:`https://github.com/${y.owner}/${y.repo}`,target:`_blank`,rel:`noopener noreferrer`,className:H(`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)(Lr,{className:`size-4`})})]})}),S?(0,K.jsx)(`div`,{className:`flex flex-1 items-center justify-center`,children:(0,K.jsx)(Da,{className:`size-6 animate-spin text-muted-foreground`})}):x?(0,K.jsx)(Kw,{className:`flex-1`,children:(0,K.jsx)(`div`,{className:`p-4`,children:(0,K.jsx)(_Y,{children:x})})}):(0,K.jsxs)(`div`,{className:`flex flex-1 flex-col items-center justify-center text-muted-foreground`,children:[(0,K.jsx)(To,{className:`mb-2 size-8`}),(0,K.jsx)(U,{children:`Preview unavailable`}),b&&(0,K.jsxs)(`a`,{href:b,target:`_blank`,rel:`noopener noreferrer`,className:`mt-2 flex items-center gap-1 text-info-indicator hover:underline`,children:[(0,K.jsxs)(U,{as:`span`,variant:`caption`,className:`block`,children:[`View on skills.sh`,` `]}),(0,K.jsx)(Lr,{className:`size-3`})]})]})]}):(0,K.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center text-muted-foreground`,children:[(0,K.jsx)(To,{className:`mb-2 size-8`}),(0,K.jsx)(U,{children:`Select a skill to preview`})]})})]})]}),d&&s&&s.length>1&&(0,K.jsxs)(OA,{orientation:`horizontal`,className:H(`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)(AA,{className:`whitespace-nowrap`,children:`Install to`}),(0,K.jsxs)(tj,{value:h,onValueChange:m,children:[(0,K.jsx)(rj,{className:`flex-1`,children:(0,K.jsx)(nj,{})}),(0,K.jsx)(ij,{children:s.map(e=>{let t=e.displayName??e.name??e.provider??`unknown`;return(0,K.jsxs)(aj,{value:e.path,children:[t,` (`,e.path,`)`]},e.path)})})]})]})]}),d&&(0,K.jsxs)(KE,{children:[O&&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)(U,{as:`span`,variant:`caption`,tone:`muted`,className:`mr-auto`,children:[`Installed at `,t.path]}):null})(),(0,K.jsx)(XE,{children:`Cancel`}),(0,K.jsx)(HE,{onConfirm:k,disabled:!y||O,"data-testid":`install-skill-button`,children:i?`Installing...`:O?`Already installed`:`Install`})]})]})})}function ibi({labeled:e=!1}){let{workspaceId:t,addSkill:n}=K9(),[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)(Mc,{}),`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)(Mc,{})}),(0,K.jsx)(rbi,{...c,open:r,onOpenChange:i,workspaceId:t,onInstall:e=>void l(e),isInstalling:a})]})}function abi({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(Wyi(t??``))),[v,y]=(0,G.useState)(t);if(t!==v){y(t);let e=Wyi(t??``).filter(e=>!g.has(e));e.length>0&&_(new Set([...g,...e]))}let b=a?.join(`
|
|
695
|
+
`).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 H_i=({queryOptions:e}={})=>Iy({queryKey:[`mastra-templates`],queryFn:R_i,...e}),U_i=({repoOrSlug:e,owner:t,queryOptions:n})=>Iy({queryKey:[`template-repo`,e,t],queryFn:()=>B_i({repoOrSlug:e,owner:t}),...n}),W_i=({repo:e,owner:t,branch:n,queryOptions:r})=>Iy({queryKey:[`template-repo-env-vars`,e,t,n],queryFn:()=>V_i({repo:e,owner:t,branch:n}),...r}),G_i=({queryOptions:e}={})=>{let t=Y();return Iy({queryKey:[`agent-builder-workflow`],queryFn:async()=>await t.getAgentBuilderAction(`merge-template`).details(),...e})},K_i=({queryOptions:e}={})=>{let t=Y();return Ry({mutationFn:async({runId:e})=>await t.getAgentBuilderAction(`merge-template`).createRun({runId:e}),...e})},q_i=({queryOptions:e}={})=>{let t=Y();return Ry({mutationFn:async({runId:e})=>await t.getAgentBuilderAction(`merge-template`).runById(e),...e})},J_i=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)},Y_i=(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=J_i(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=J_i(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}},X_i=(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)}},Z_i=(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}=Y_i(a,s,e);s=c,r(c),(a.runId||i||t)&&X_i(a.runId||i||t,c)}}catch(t){console.error(`💥 [processStream] Error processing template installation stream:`,t);let{newState:n}=Y_i({type:`error`,payload:{error:t instanceof Error?t.message:`Unknown error`}},s,e);r(n)}finally{a(!1),o.releaseLock()}}}},Q_i=({workflowInfo:e,queryOptions:t}={})=>{let n=Y(),{streamResult:r,isStreaming:i,processStream:a}=Z_i(e);return{streamInstall:Ry({mutationFn:async({inputData:e,selectedModel:t,runId:r})=>{for(let i=1;i<=3;i++)try{let i=n.getAgentBuilderAction(`merge-template`),o=new Rl;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}},$_i=({workflowInfo:e,queryOptions:t}={})=>{let n=Y(),{streamResult:r,isStreaming:i,processStream:a}=Z_i(e);return{observeInstall:Ry({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 evi(e){return e.replace(/\/$/,``).split(`/`).pop()}function tvi({templates:e,linkComponent:t,className:n,isLoading:r}){let i=t||`a`;return r?(0,K.jsx)(`div`,{className:H(`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:H(`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:H(ex,`state-layer grid w-full grid-cols-[1fr_auto] overflow-hidden rounded-lg`),children:[(0,K.jsxs)(i,{to:`/templates/${e.slug}`,className:H(`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:H(`grid w-full gap-0.5 px-4 py-3`,`[&_svg]:h-[1em] [&_svg]:w-[1em] [&_svg]:text-muted-foreground`),children:[(0,K.jsx)(U,{as:`h2`,tone:`ink`,children:e.title}),(0,K.jsx)(U,{className:H(Pw,$e),children:e.description}),(0,K.jsxs)(`div`,{className:`mt-3 hidden flex-wrap items-center gap-4 text-muted-foreground 2xl:flex`,children:[t&&(0,K.jsxs)(`ul`,{className:H(`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)(U,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(nF,{}),` `,e.agents.length]})}),e?.tools&&e.tools.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(U,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(oF,{}),` `,e.tools.length]})}),e?.networks&&e.networks.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(U,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(po,{}),` `,e.networks.length]})}),e?.workflows&&e.workflows.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(U,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(Ic,{}),` `,e.workflows.length]})}),e?.mcp&&e.mcp.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(U,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(rF,{}),` `,e.mcp.length]})})]}),t&&e.supportedProviders&&(0,K.jsx)(`small`,{children:(0,K.jsx)(U,{as:`span`,variant:`body`,children:`|`})}),(0,K.jsx)(`div`,{className:`flex items-center gap-4`,children:e.supportedProviders.map(e=>(0,K.jsx)(U,{tone:`muted`,as:`span`,variant:`body`,children:e},e))})]})]})]}),(0,K.jsx)(`a`,{href:e.githubUrl,className:H(`group ml-auto hidden items-center gap-2 pr-4`,`lg:flex`),target:`_blank`,rel:`noopener noreferrer`,children:(0,K.jsx)(U,{as:`span`,variant:`body`,children:(0,K.jsxs)(`span`,{className:H(`flex items-center gap-2 rounded bg-sidebar px-2 py-1`,qWe,Pw,$e),children:[(0,K.jsx)(GX,{}),` `,evi(e.githubUrl)]})})})]},e.slug)})})}function nvi({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:H(`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:H(`sticky top-0 mx-auto flex flex-wrap gap-4 bg-background py-5`,l),children:[(0,K.jsx)(NU,{label:`Search templates`,placeholder:`Search Template`,value:o,onValueChange:s}),(0,K.jsxs)(tj,{value:t,onValueChange:i,children:[(0,K.jsx)(rj,{"aria-label":`Filter by tag`,size:`md`,children:(0,K.jsx)(nj,{placeholder:`Select an option`})}),(0,K.jsx)(ij,{children:e.map(e=>(0,K.jsx)(aj,{value:e.value,children:e.label},e.value))})]}),(0,K.jsxs)(tj,{value:r,onValueChange:a,children:[(0,K.jsx)(rj,{"aria-label":`Filter by provider`,size:`md`,children:(0,K.jsx)(nj,{placeholder:`Select an option`})}),(0,K.jsx)(ij,{children:n.map(e=>(0,K.jsx)(aj,{value:e.value,children:e.label},e.value))})]}),c&&(0,K.jsx)(X,{onClick:c,icon:(0,K.jsx)(Bc,{}),children:`Reset`})]})}var rvi=[{id:`templates`,label:`Templates`}];function ivi(){let{data:e,isLoading:t}=H_i(),{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)},m=e=>{u(e)},h=()=>{o(`all`),c(`all`),u(``)},g=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))),_=l||a!==`all`||s!==`all`;return(0,K.jsxs)(Jw,{variant:`fit`,breadcrumbs:(0,K.jsx)(DP,{crumbs:rvi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Templates`}),(0,K.jsx)(qw,{children:(0,K.jsxs)(K$e,{children:[(0,K.jsx)(QC,{children:(0,K.jsx)(To,{})}),`Templates`]})}),(0,K.jsxs)(`div`,{className:H(`z-10 h-full w-full overflow-y-auto px-5 pb-12`),children:[(0,K.jsx)(nvi,{selectedTag:a,onTagChange:e=>p(e,`tag`),tagOptions:d,selectedProvider:s,onProviderChange:e=>p(e,`provider`),providerOptions:f,searchTerm:l,onSearchChange:m,onReset:_?h:void 0,className:`max-w-[80rem]`,isLoading:t}),(0,K.jsx)(tvi,{templates:g,linkComponent:Zb,className:`mx-auto max-w-[80rem]`,isLoading:t})]})]})}function avi({children:e,className:t}){return(0,K.jsx)(`div`,{className:H(`transition-height mt-12 rounded-lg border border-border px-4 py-5 lg:min-h-[25rem] lg:px-12`,t),children:e})}function ovi({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)(Ur,{}),title:`Template Installation Failed`};return(0,K.jsxs)(avi,{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)(U,{variant:`subheading`,tone:`ink`,children:s}),(0,K.jsx)(U,{tone:`muted`,children:a()})]})]}),t&&t.length>0&&(0,K.jsxs)(`details`,{children:[(0,K.jsx)(`summary`,{className:H(`text-muted-foreground hover:text-foreground`,`cursor-pointer text-center select-none`),children:(0,K.jsxs)(U,{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)(U,{as:`p`,variant:`column`,className:`text-destructive-foreground`,children:e.type===`typescript`?`🔴 TypeScript Error`:`⚠️ Lint Error`}),(0,K.jsx)(NT,{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:H(`text-muted-foreground hover:text-foreground`,`cursor-pointer text-center select-none`),children:(0,K.jsx)(U,{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)(NT,{className:`text-caption wrap-break-word whitespace-pre-wrap`,code:n})})]})]})}var svi=(0,G.createContext)(null);function cvi(){return(0,G.useContext)(svi)||{registerResetFn:()=>{},triggerReset:()=>{}}}var lvi=({defaultProvider:e,defaultModel:t,updateModel:n,resetModel:r})=>{let[i]=(0,G.useState)(e),[a]=(0,G.useState)(t),[o,s]=(0,G.useState)(t),[c,l]=(0,G.useState)(e||``),[u,d]=(0,G.useState)(!1),[f,p]=(0,G.useState)(!1),[m,h]=(0,G.useState)(!1),{data:g,isLoading:_}=pq(),v=Cw(),{models:y}=_q(),b=(0,G.useMemo)(()=>g?.providers||[],[g]);(0,G.useEffect)(()=>{s(t),l(e||``)},[t,e]);let x=uq(c),S=mq(b,x)?.id||x,C=async r=>{if(s(r),r&&S){d(!0);try{let e=await n({provider:S,modelId:r});console.info(`Model updated:`,e)}catch(n){s(t),l(e||``),console.error(`Failed to update model:`,n)}finally{d(!1)}}},w=e=>{let t=uq(e);l(t),t!==x&&(s(``),h(!0))},{registerResetFn:T}=cvi();if((0,G.useEffect)(()=>(T(()=>{if(!(f||m)&&x&&x!==i&&(!o||o===``)){l(uq(i)),s(a);let e=mq(b,i)?.id||i;e&&a&&n({provider:e,modelId:a}).catch(e=>{console.error(`Failed to reset model:`,e)})}}),()=>{T(null)}),[T,x,o,i,a,n,f,m,b]),_)return(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)($c,{}),(0,K.jsx)(U,{as:`span`,tone:`muted`,children:`Loading providers...`})]});let E=async()=>{if(!r)console.warn(`Reset model function not provided`);else try{d(!0),await r()}catch(e){console.error(`Failed to reset model:`,e)}finally{d(!1)}},D=mq(b,x);if(v.active&&v.pickerVisible===!1){let e=v.default&&v.default.provider&&v.default.modelId?`${v.default.provider}/${v.default.modelId}`:c&&o?`${c}/${o}`:`Locked by admin`;return(0,K.jsxs)(`div`,{className:H(ex,`flex items-center gap-2 rounded-md px-3 py-2`),"data-testid":`agent-metadata-model-locked`,children:[(0,K.jsx)(ja,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,K.jsx)(U,{as:`span`,variant:`caption`,tone:`ink`,className:`truncate`,children:e}),(0,K.jsx)(U,{as:`span`,variant:`meta`,tone:`muted`,className:`ml-auto shrink-0`,children:`Set by admin`})]})}let O=!!(x&&o)&&v.active&&v.allowed!==void 0&&!y.some(e=>uq(e.provider)===x&&e.model===o);return(0,K.jsxs)(`div`,{className:`@container`,children:[(0,K.jsxs)(`div`,{className:`flex w-full flex-col items-stretch gap-2 @xs:flex-row @xs:items-center`,children:[(0,K.jsx)(`div`,{className:`w-full @xs:w-2/5`,children:(0,K.jsx)(hq,{value:x,onValueChange:w,open:f,onOpenChange:p})}),(0,K.jsx)(`div`,{className:`w-full @xs:w-3/5`,children:(0,K.jsx)(gq,{llmId:x,value:o,onValueChange:C,open:m,onOpenChange:h})}),(0,K.jsx)(X,{variant:`default`,size:`icon-md`,onClick:E,disabled:u,tooltip:`Reset to original model`,children:(0,K.jsx)(ms,{})})]}),O&&(0,K.jsx)(`div`,{className:`p-2 pt-2`,"data-testid":`agent-metadata-model-stale-warning`,children:(0,K.jsx)(HA,{variant:`warning`,title:`Model not allowed`,children:(0,K.jsxs)(HA.Message,{children:[(0,K.jsxs)(`code`,{className:`rounded bg-fill-hover px-1 py-0.5`,children:[c,`/`,o]}),` `,`is no longer allowed by the admin policy. Pick a different model to save changes.`]})})}),D&&!D.connected&&(0,K.jsx)(`div`,{className:`p-2 pt-2`,children:(0,K.jsx)(HA,{variant:`warning`,title:`Provider not connected`,children:(0,K.jsxs)(HA.Message,{children:[`Set the`,` `,(0,K.jsx)(`code`,{className:`rounded bg-fill-hover px-1 py-0.5`,children:Array.isArray(D.envVar)?D.envVar.join(`, `):D.envVar}),` `,`environment`,` `,Array.isArray(D.envVar)&&D.envVar.length>1?`variables`:`variable`,` to use this provider.`]})})})]})};function uvi({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)(avi,{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)(U,{as:`h2`,variant:`heading`,tone:`muted`,className:H(`flex items-center gap-2`,`[&_svg]:h-[1.2em] [&_svg]:opacity-70 [&>svg]:w-[1.2em]`),children:[`Install Template `,(0,K.jsx)(Co,{})]}),(0,K.jsxs)(OA,{orientation:`horizontal`,children:[(0,K.jsx)(AA,{children:`Template AI Model Provider`}),(0,K.jsx)(a_t,{className:`flex-1`,children:(0,K.jsxs)(tj,{name:`template-provider`,value:t,onValueChange:n,children:[(0,K.jsx)(rj,{size:`md`,children:(0,K.jsx)(nj,{placeholder:`Select`})}),(0,K.jsx)(ij,{children:e.map(e=>(0,K.jsx)(aj,{value:e.value,children:e.label},e.value))})]})})]}),t&&Object.entries(r||{}).length>0&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(U,{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:H(`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)($c,{}),(0,K.jsxs)(U,{as:`span`,variant:`caption`,className:`block`,children:[` `,`Loading variables...`]})]}):Object.entries(r).map(([e,t])=>(0,K.jsxs)(G.Fragment,{children:[(0,K.jsxs)(OA,{className:`w-full`,children:[(0,K.jsx)(AA,{className:`sr-only`,children:`Key`}),(0,K.jsx)(lN,{name:`env-${e}`,value:e,disabled:!0,className:`w-full`})]}),(0,K.jsxs)(OA,{invalid:i.includes(e),className:`w-full`,children:[(0,K.jsx)(AA,{className:`sr-only`,children:`Value`}),(0,K.jsx)(lN,{name:e,value:t,onChange:o,autoComplete:`off`,className:`w-full`}),(0,K.jsx)(MA,{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)(U,{tone:`muted`,as:`span`,variant:`caption`,className:`block`,children:`And`})}),(0,K.jsx)(U,{as:`h3`,tone:`muted`,children:`Set AI Model for Template Installation`}),(0,K.jsx)(U,{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)(lvi,{defaultProvider:l||``,defaultModel:u||``,updateModel:d||(()=>Promise.resolve({message:`Updated`})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:`Provider`})]})]}),t&&!s&&(0,K.jsx)(X,{className:H(`state-layer mt-4 flex min-h-10 w-full items-center justify-center gap-2 rounded-lg bg-card 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)($c,{className:`h-4 w-4`}),` Installing...`]}):(0,K.jsxs)(K.Fragment,{children:[`Install `,(0,K.jsx)(Ht,{})]})})]})})}function dvi({data:e,className:t,labelsAreHidden:n,isLoading:r,LinkComponent:i}){let a=({children:e})=>n?(0,K.jsx)(bX,{children:e}):e;return!e||e.length===0?null:(0,K.jsx)(`dl`,{className:H(`grid grid-cols-[auto_1fr] content-start items-start gap-x-4`,t),children:e.map(({key:e,label:t,value:o,icon:s,separator:c},l)=>{let u=Array.isArray(o);return(0,K.jsxs)(G.Fragment,{children:[(0,K.jsxs)(`dt`,{className:H(`flex min-h-9 items-center justify-between gap-8 text-body text-muted-foreground`),children:[(0,K.jsxs)(`span`,{className:H(`flex items-center gap-2`,`[&>svg]:size-[1.4em] [&>svg]:text-muted-foreground [&>svg]:opacity-50`,{"[&>svg]:opacity-20":r}),children:[s,` `,(0,K.jsx)(a,{children:t})]}),!n&&(0,K.jsx)(`span`,{className:H(`text-muted-foreground`,`[&>svg]:size-[1em] [&>svg]:text-muted-foreground`),children:c})]}),(0,K.jsx)(`dd`,{className:H(`flex min-h-9 flex-wrap items-center gap-2 py-1 text-body text-wrap text-foreground`,`truncate [&>a]:flex [&>a]:min-h-7 [&>a]:w-auto [&>a]:max-w-full [&>a]:items-center [&>a]:gap-2 [&>a]:rounded-md [&>a]:bg-muted [&>a]:px-2 [&>a]:py-0.5 [&>a]:text-body [&>a]:leading-none [&>a]:text-foreground [&>a]:transition-colors`,`[&>a:hover]:bg-fill-subtle [&>a:hover]:text-foreground`,`[&>a>svg]:ml-[-0.5em] [&>a>svg]:size-[1em] [&>a>svg]:text-muted-foreground`),children:r?(0,K.jsx)(`span`,{className:H(`w-full rounded-e-lg bg-muted`),style:{width:`${Math.floor(Math.random()*61)+50}%`},children:`\xA0`}):u?o?.map(e=>e.path&&i?(0,K.jsx)(fvi,{description:e.description,children:(0,K.jsxs)(i,{href:e.path,children:[e?.name,` `,(0,K.jsx)(pt,{})]})},e.id):e.path?(0,K.jsx)(fvi,{description:e.description,children:(0,K.jsxs)(`a`,{href:e.path,children:[e?.name,` `,(0,K.jsx)(pt,{})]})},e.id):(0,K.jsx)(`span`,{children:e?.name},e.id)):(0,K.jsx)(K.Fragment,{children:o||(0,K.jsx)(U,{as:`span`,variant:`caption`,tone:`muted`,children:`n/a`})})})]},e??l)})})}function fvi({description:e,children:t}){return e?(0,K.jsxs)(YX,{children:[(0,K.jsx)(XX,{render:G.isValidElement(t)?t:void 0}),(0,K.jsx)(ZX,{className:`max-w-60 text-center`,children:e})]}):t}function pvi({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:H(`flex items-center gap-3`,`[&>svg]:h-[1.2em] [&>svg]:w-[1.2em] [&>svg]:opacity-50`,{"[&>svg]:opacity-20":r}),children:[(0,K.jsx)(To,{}),(0,K.jsx)(`h2`,{className:H({"flex min-w-[50%] rounded-lg bg-muted":r}),children:(0,K.jsx)(U,{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)(U,{tone:`muted`,className:H(`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:H(`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)(Yi,{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)(Oi,{className:`h-[1em] w-[1em] text-muted-foreground`}),(0,K.jsx)(U,{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)(U,{tone:`muted`,as:`p`,variant:`caption`,children:[(0,K.jsx)(U,{as:`span`,variant:`column`,children:`Branch name:`}),` `,(0,K.jsx)(FY,{children:o})]}),(0,K.jsx)(U,{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:H(`text-muted-foreground hover:text-foreground`,`mt-auto flex items-center gap-2`),children:[(0,K.jsx)(GX,{}),(0,K.jsx)(U,{as:`span`,variant:`body`,className:`block`,children:n?.split(`/`)?.pop()})]})]}),i&&(0,K.jsx)(dvi,{data:i,labelsAreHidden:!0,isLoading:r})]})]})}function mvi(e){switch(e){case`running`:return(0,K.jsx)($c,{size:`sm`,"aria-hidden":!0});case`success`:return(0,K.jsx)(Ln,{"aria-hidden":!0});case`failed`:return(0,K.jsx)(Bc,{"aria-hidden":!0});default:return null}}function hvi(){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 gvi({status:e,variant:t}){return t===`plain`?(0,K.jsx)(`span`,{className:H(`flex size-4 items-center justify-center self-center [&>svg]:size-4`,bt.colors,{"[&>svg]:text-success-indicator":e===`success`,"[&>svg]:text-destructive-foreground":e===`failed`}),children:e===`pending`?(0,K.jsx)(hvi,{}):mvi(e)}):(0,K.jsx)(`span`,{className:H(`flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none`,bt.colors,bt.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:mvi(e)})}function _vi({step:e,isActive:t,position:n,variant:r=`default`}){let i=t||e.status===`success`?`ink`:`muted`;return(0,K.jsxs)(`div`,{className:H(`grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none`,bt.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)(U,{as:`span`,tone:i,className:H(`flex min-w-6 justify-end`,bt.colors),children:[n,`.`]}),(0,K.jsxs)(`div`,{className:`min-w-0`,children:[(0,K.jsx)(U,{as:`h4`,tone:i,className:bt.colors,children:e.title}),e.description&&(0,K.jsx)(U,{tone:`faint`,className:H(`-mt-0.5`,{truncate:r===`plain`}),children:e.description})]})]}),(0,K.jsx)(gvi,{status:e.status,variant:r})]})}function vvi({currentStep:e,steps:t=[],className:n}){return(0,K.jsx)(`div`,{className:H(n),children:t.map((t,n)=>(0,K.jsx)(_vi,{step:t,isActive:e?.id===t.id,position:n+1},t.id))})}function yvi({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:H(`relative flex h-8 items-center justify-end`,bt.colors,{"bg-success-subtle":t.status===`success`&&e?.[n-1]?.status===`success`}),children:(0,K.jsx)(`div`,{className:H(`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`,bt.colors,bt.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)($c,{}):n+1})},t.id))}),(0,K.jsxs)(`div`,{className:H(`text-center text-caption text-muted-foreground`,bt.colors),children:[n,` of `,t,` steps completed`]})]})}function bvi({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...`}},m=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)(avi,{className:`mb-5 content-center space-y-6 text-muted-foreground`,children:[(0,K.jsxs)(`div`,{className:`text-center`,children:[(0,K.jsx)(U,{as:`h3`,variant:`heading`,tone:`ink`,children:p()}),(t?.runId||n)&&(0,K.jsxs)(U,{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)(yvi,{steps:m})}),s&&i===`error`&&(0,K.jsxs)(`div`,{className:H(`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)(yo,{}),(0,K.jsx)(U,{as:`span`,variant:`body`,className:`block`,children:s||`Something went wrong`})]}),l&&(0,K.jsx)(vvi,{steps:m,currentStep:o,className:`pb-4`}),!l&&i===`initializing`&&(0,K.jsxs)(`div`,{className:H(`text-muted-foreground`,`grid justify-items-center gap-4 text-center`),children:[(0,K.jsx)($c,{}),(0,K.jsx)(U,{as:`p`,variant:`body`,children:`This may take some time...`})]})]})}function xvi({name:e,installedEntities:t}){return(0,K.jsxs)(avi,{className:H(`grid content-center items-center justify-items-center gap-4`,`[&>svg]:h-8 [&>svg]:w-8`),children:[(0,K.jsx)(Co,{}),(0,K.jsx)(U,{as:`h2`,variant:`heading`,children:`Done!`}),(0,K.jsxs)(U,{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)(dvi,{data:t})]})}function Svi(){let{templateSlug:e}=Bb(),t=[{id:`templates`,label:`Templates`,to:`/templates`},{id:`template`,label:RPt(e)}],[n,r]=Qb(),[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)([]),[m,h]=(0,G.useState)(null),[g,_]=(0,G.useState)(!1),[v,y]=(0,G.useState)(``),[b,x]=(0,G.useState)(!1),[S,C]=(0,G.useState)(!1),[w,T]=(0,G.useState)([]),{data:E,isLoading:D}=U_i({repoOrSlug:e,owner:`mastra-ai`}),O=`1.81.0`.includes(`beta`)??!1?`beta`:`main`,{data:k,isLoading:A}=W_i({repo:E?.githubUrl?new URL(E.githubUrl).pathname.split(`/`)[2]:`template-${e}`,owner:`mastra-ai`,branch:O}),{data:j,isLoading:M}=G_i(),{mutateAsync:N,isPending:P}=K_i(),{mutateAsync:F}=q_i(),{streamInstall:I,streamResult:L,isStreaming:R}=Q_i({workflowInfo:j}),{observeInstall:ee,streamResult:z,isStreaming:B}=$_i({workflowInfo:j});(0,G.useEffect)(()=>{let e=n.get(`runId`);!e||g||m||R||B||(console.info(`🔄 Checking completed run after hot reload:`,{runId:e}),y(e),F({runId:e}).then(e=>{let t=e.snapshot;if(t?.status===`success`&&t?.result?.success)_(!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.`;h(r),T(n||[])}else{let e=t?.result?.message||t?.result?.error||`Template installation failed`;h(typeof e==`string`?e:String(e))}}}).catch(e=>{console.error(`❌ Failed to fetch run details:`,e),h(`Failed to retrieve installation status after reload`)}))},[n,g,m,R,B,F]),(0,G.useEffect)(()=>{let e=n.get(`runId`),t=n.get(`resume`),i=n.get(`provider`);if(e&&t===`true`&&i&&!R&&!B&&!b&&!S&&j){y(e),x(!0);try{F({runId:e}).then(t=>{if(t.snapshot?.status===`running`)return ee.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`)?h(`Template installation run not found. It may have expired or been completed.`):h(`Failed to resume template installation. Please try again.`)})}catch(e){console.error(`❌ Auto-resume failed with error:`,e),h(`Failed to resume template installation. Please refresh and try again.`)}}},[n,e,R,B,b,S,j,F,ee,r]);let V=[{value:`openai`,label:`OpenAI`},{value:`anthropic`,label:`Anthropic`},{value:`groq`,label:`Groq`},{value:`google`,label:`Google`}],te=[{key:`tools`,label:`Tools`,value:E?.tools?.length?E.tools.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(oF,{})},{key:`agents`,label:`Agents`,value:E?.agents?.length?E.agents.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(nF,{})},{key:`workflows`,label:`Workflows`,value:E?.workflows?.length?E.workflows.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(Ic,{})},{key:`providers`,label:`Providers`,value:E?.supportedProviders?.length?E.supportedProviders.join(`, `):`n/a`,icon:(0,K.jsx)(Cn,{})},{key:`tags`,label:`Tags`,value:E?.tags?.length?E.tags.join(`, `):`n/a`,icon:(0,K.jsx)(nc,{})}],ne=[{...te[0]},{...te[1]},{...te[2]}].filter(e=>e.value!==`n/a`);return(0,G.useEffect)(()=>{k&&d(k)},[k]),(0,G.useEffect)(()=>{let e=L||z;e?.phase===`error`&&e?.error&&h(typeof e.error==`string`?e.error:String(e.error))},[L?.phase,L?.error,z?.phase,z?.error]),(0,K.jsxs)(Jw,{variant:`fit`,breadcrumbs:(0,K.jsx)(DP,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(`div`,{className:H(`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)(pvi,{isLoading:D,title:E?.title,description:E?.longDescription,imageURL:E?.imageURL,githubUrl:E?.githubUrl,infoData:te,templateSlug:e}),E&&(0,K.jsxs)(K.Fragment,{children:[(R||B)&&(0,K.jsx)(bvi,{name:E.title,streamResult:B?z:L,runId:v,workflowInfo:j}),g&&(0,K.jsx)(xvi,{name:E.title,installedEntities:ne,linkComponent:Zb}),m&&(0,K.jsx)(ovi,{errorMsg:m,validationErrors:w.length>0?w:L?.validationResults?.errors||z?.validationResults?.errors}),!R&&!B&&!g&&!m&&(0,K.jsx)(uvi,{providerOptions:V,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(E){h(null),_(!1),y(``),C(!0);try{let e={repo:E.githubUrl||`https://github.com/mastra-ai/template-${E.slug}`,ref:O,slug:E.slug,variables:u},{runId:t}=await N({});y(t),r(e=>{let n=new URLSearchParams(e);return n.set(`runId`,t),n.set(`resume`,`true`),n.set(`provider`,i||`openai`),n}),await I.mutateAsync({inputData:e,selectedModel:{provider:o,modelId:c},runId:t})}catch(e){C(!1),h(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:A||M,isInstalling:P,defaultModelProvider:o,defaultModelId:c,onModelUpdate:async e=>(s(e.provider),l(e.modelId),{message:`Model updated successfully`})})]})]})})]})}var Cvi=e=>e.threadId;function wvi(e,t){return`traces`in e?{traces:{...e.traces,to:t}}:{threads:{...e.threads,to:t}}}var Tvi=e=>`traces`in e?e.traces:e.threads;function Evi(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 Dvi({query:e,rolling:t,autoRefetch:n=!0,limit:r,enabled:i=!0}){let a=Y(),{anchorTo:o,reanchor:s}=c_i(e),c=(0,G.useMemo)(()=>o?{...e,timeRange:wvi(e.timeRange,o)}:e,[e,o]),l=qRr({query:c,limit:r,enabled:i,queryOptions:d_i}),{headRows:u}=u_i({queryKey:[`threads`,e],fetchHead:async t=>(await a.queryTraceThreads({...e,timeRange:wvi(e.timeRange,t),orderBy:[{field:`endedAt`,direction:`desc`}],page:{limit:50}})).threads,getId:Cvi,getEndedAt:e=>e.endedAt,since:Date.parse(Tvi(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&&h_i(f,u,{getId:Cvi,compare:Evi(d),hasNextPage:l.hasNextPage}),[f,u,d,l.hasNextPage]);return{...l,threads:p}}function Ovi(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 kvi=[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`],Avi=[];function jvi(){let{data:e}=E6(),t=e?.capabilities.traceQueryTimeToFirstChunk??!1,n=e?.capabilities.traceQueryTimeToFirstToken??!1,{data:r=Avi}=y3(),{data:i=Avi}=b3();return(0,G.useMemo)(()=>[V6,...Y2r({withTimeToFirstChunk:t,withTimeToFirstToken:n,entityNames:r,environments:i})],[t,n,r,i])}function Mvi({tokens:e,groups:t,onFiltersChange:n}){let r=(0,G.useMemo)(()=>Q3(e),[e]),i=(0,G.useMemo)(()=>{let e=$3([],t);return{...e,nodes:[H6,...r,...e.nodes]}},[r,t]),a=(0,G.useCallback)(e=>{let t=bBr({...e,nodes:e.nodes.filter(e=>l3(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(l3);a({...i,nodes:[...n,o,...s]})},[r,i,a])}}var Nvi=e=>e;function Pvi({datePreset:e,dateFrom:t,dateTo:n,minDate:r,tokens:i,groups:a,onDatePresetChange:o,onDateChange:s,onDateRangeChange:c,onFiltersChange:l,disabled:u}){let d=jvi(),{filterBarValue:f,onFilterBarChange:p}=Mvi({tokens:i,groups:a,onFiltersChange:l});return(0,K.jsxs)(W6,{fields:d,operators:qzr,value:f,onValueChange:p,createItemId:Nvi,maxDepth:3,"aria-label":`Thread filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(W6.Chips,{renderChip:i=>i.fieldId===`timeRange`?(0,K.jsx)(U6,{preset:e,onPresetChange:o,dateFrom:t,dateTo:n,minDate:r,onDateChange:s,onDateRangeChange:c,disabled:u,presets:kvi,defaultPreset:m6.datePreset}):(0,K.jsx)(W6.Chip,{item:i})}),(0,K.jsx)(W6.Input,{placeholder:`Filter threads…`})]})}function Fvi({selectedThreadId:e,onSelectedThreadChange:t,onOpenScore:n,urlState:r}){let i=p_i(r),{timeRange:a,tokens:o,groups:s,sort:c}=i,l=D6().enabled,u=xWr().enabled,d=O0r({scope:`threads`}),{data:f,isLoading:p}=E6(),m=f?.capabilities.traceQueryTimeToFirstChunk??!1,h=f?.capabilities.traceQueryTimeToFirstToken??!1,g=(0,G.useMemo)(()=>p?d.preferences:VUr(d.preferences,{withTimeToFirstChunk:m,withTimeToFirstToken:h}),[d.preferences,p,m,h]),{threads:_,hasNextPage:v,isFetchingNextPage:y,setEndOfListElement:b,isLoading:x,isError:S,error:C}=Dvi({query:(0,G.useMemo)(()=>{let e=Q2r(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(Ovi),[_]),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)(cWr,{toolbar:(0,K.jsxs)(K.Fragment,{children:[r&&(0,K.jsx)(Y4r,{page:`threads`,...r,columns:d}),(0,K.jsx)(iq,{children:(0,K.jsxs)(iq.Start,{children:[(0,K.jsx)(DWr,{scope:`threads`,value:d.preferences,onChange:d.setPreferences}),(0,K.jsx)(Pvi,{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})]})})]}),error:S?(0,K.jsx)(T6,{error:C,resource:`threads`,errorTitle:`Failed to load threads`}):void 0,empty:D?(0,K.jsx)(dWr,{resource:`threads`,datePreset:i.datePreset,dateFrom:i.dateFrom,dateTo:i.dateTo}):void 0,children:(0,K.jsx)(WYr,{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)(N1r,{open:!!e,threadId:e??``,depth:1,closeLabel:`Close`,withQueryTrace:l,withFeedback:u,onOpenScore:n,onClose:()=>t(void 0)})]})}function Ivi(){let{enabled:e,isLoading:t}=k6(),n=zb(),[r,i]=Qb();return(0,K.jsx)(e_i,{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)(Fvi,{urlState:{searchParams:r,setSearchParams:i},selectedThreadId:x_i(r),onSelectedThreadChange:e=>i(t=>S_i(t,e),{replace:!0}),onOpenScore:(e,t)=>n(nq(e,t))})})}var Lvi=()=>(0,K.jsx)(fw,{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)(Lr,{}),children:`Workflows documentation`}),variant:`fill`});function Rvi(e,t,n){return tZ(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 zvi(e){return Object.keys(e.steps??{}).filter(t=>e.allSteps?.[t]?.isWorkflow)}function Bvi(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 Vvi(e,t,n){let r=Bvi(t),i=[],a=(e,o,s,c,l,u)=>{let d=zvi(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 Hvi=`auto 24rem minmax(0, 1fr) auto auto auto`;function Uvi({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:H(`w-6`,e&&`border-l border-border`)},t)),(0,K.jsxs)(`span`,{className:`relative w-6`,children:[(0,K.jsx)(`span`,{className:H(`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 Wvi({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:H(Nw,`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)(rt,{direction:`right`,className:`size-4`})}):(0,K.jsx)(`span`,{className:`size-5 shrink-0`,"aria-hidden":!0})})}var Gvi=e=>e.stopPropagation();function Kvi({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 qvi({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=Uq(c.name,50),d=Uq(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)(Wvi,{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:Gvi,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)(Uvi,{guides:e.guides,isLastChild:e.isLastChild}):null,(0,K.jsx)(`span`,{className:`truncate`,children:u}),c.origin===`dynamic`?(0,K.jsx)(hT,{size:`xs`,variant:`blue`,title:`Registered via the dynamic-workflows API`,children:`Dynamic`}):null,h?(0,K.jsxs)(U,{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)(Ic,{"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)(jo,{"aria-hidden":!0,className:`size-3.5`}),m]}):``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:f||``})]})]})}function Jvi({workflows:e,isLoading:t,search:n=``,sort:r,onSortChange:i,requestContext:a}){let[o,s]=(0,G.useState)(new Set),c=wkt({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)(()=>Rvi(u,r,c),[u,r,c]),f=(0,G.useMemo)(()=>Vvi(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:m,getRowProps:h}=$X({count:p.size,global:!0}),g=e=>{s(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})};return t?(0,K.jsx)(OU,{columns:Hvi,fit:`container`}):(0,K.jsxs)(Z,{columns:Hvi,fit:`container`,scrollRef:m,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)(Kvi,{sortKey:`name`,sort:r,onSortChange:i,children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`Description`}),(0,K.jsx)(Kvi,{sortKey:`running`,sort:r,onSortChange:i,children:`Running`}),(0,K.jsx)(Kvi,{sortKey:`suspended`,sort:r,onSortChange:i,children:`Pending input`}),(0,K.jsx)(Kvi,{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=()=>g(e.pathKey);return e.kind===`unregistered`?(0,K.jsxs)(Z.RowStatic,{className:`gap-0 px-0`,children:[(0,K.jsx)(Wvi,{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)(Uvi,{guides:e.guides,isLastChild:e.isLastChild}),(0,K.jsx)(`span`,{className:`truncate`,children:Uq(e.stepId,50)}),(0,K.jsxs)(JC,{children:[(0,K.jsx)(YC,{render:(0,K.jsx)(U,{as:`span`,variant:`body-sm`,tone:`muted`}),role:`note`,tabIndex:0,className:H(`shrink-0 rounded-sm`,vt),children:`not registered`}),(0,K.jsx)(XC,{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:Uq(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)(qvi,{row:e,isExpanded:t,onToggle:n,runCount:c[e.workflow.id],rowProps:h(p.get(e.pathKey)??-1)},`workflow-${e.pathKey}`)})]})}var G9=[cF(`/workflows`)];function Yvi(){let{data:e,isLoading:t,error:n}=lP(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)();return n&&YP(n)?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:G9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(fU,{variant:`fill`})]}):n&&XP(n)?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:G9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(dU,{variant:`fill`,resource:`workflows`})]}):n?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:G9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(fw,{tone:`error`,variant:`fill`,titleSlot:`Failed to load workflows`,descriptionSlot:n.message})]}):Object.keys(e||{}).length===0&&!t?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:G9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(Lvi,{})]}):(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:G9}),actionRow:(0,K.jsxs)(iq,{children:[(0,K.jsx)(iq.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(PU,{onSearch:i,label:`Filter workflows`,placeholder:`Filter by name or description`})})}),(0,K.jsx)(iq.End,{children:(0,K.jsx)(X,{render:(0,K.jsx)(Zb,{to:`/workflows/schedules`}),variant:`primary`,icon:(0,K.jsx)(An,{}),children:`Schedules`})})]}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(Jvi,{workflows:e||{},isLoading:t,search:r,sort:a,onSortChange:(e,t)=>o({key:t,direction:e})})]})}var Xvi={active:`bg-success-indicator`,paused:`bg-info-indicator`,completed:`bg-muted-foreground`},Zvi={active:`text-success-indicator`,paused:`text-info-indicator`,completed:`text-muted-foreground`},Qvi=({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 ${Xvi[e]}`,"aria-hidden":!0}),(0,K.jsx)(U,{as:`span`,variant:`caption`,className:Zvi[e],children:e})]});function $vi({status:e}){let{icon:t,color:n}=eyi(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)(U,{as:`span`,variant:`caption`,children:e})]})}function eyi(e){switch(e){case`success`:return{icon:(0,K.jsx)(Ln,{size:14}),color:`text-success-indicator`};case`failed`:return{icon:(0,K.jsx)(Bc,{size:14}),color:`text-destructive-foreground`};case`running`:return{icon:(0,K.jsx)($c,{}),color:`text-muted-foreground`};case`suspended`:return{icon:(0,K.jsx)(Jn,{size:14}),color:`text-info-indicator`};case`canceled`:return{icon:(0,K.jsx)(Zn,{size:14}),color:`text-muted-foreground`};case`pending`:case`waiting`:return{icon:(0,K.jsx)(cr,{size:14}),color:`text-muted-foreground`};default:return{icon:null,color:`text-muted-foreground`}}}var tyi=`auto auto auto auto 1fr`,nyi=3e4,ryi=3e5;function iyi({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}=$X({count:l}),f=-1;return t?(0,K.jsx)(OU,{columns:tyi}):e.length===0?(0,K.jsx)(U,{variant:`body`,tone:`muted`,className:`p-4`,children:`No trigger history yet.`}):(0,K.jsxs)(Z,{columns:tyi,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=lT(t,{signed:!0}),i=e.outcome===`failed`,a=i?e.error:e.run?.error,l=Math.abs(t),u=!i&&l>nyi&&l<=ryi,p=`${e.scheduleId}-${e.runId}-${e.actualFireAt}`,m=c(e);m&&(f+=1);let h=(0,K.jsx)(U,{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)(U,{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)($vi,{status:e.run.status}):(0,K.jsx)(U,{as:`span`,variant:`caption`,tone:`muted`,className:`inline-flex items-center gap-1.5 whitespace-nowrap`,children:`pending`}),a?(0,K.jsxs)(JC,{children:[(0,K.jsx)(YC,{asChild:!0,children:(0,K.jsx)(`span`,{className:`inline-flex text-destructive-foreground`,children:(0,K.jsx)(Cc,{size:14})})}),(0,K.jsx)(XC,{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)(TT,{value:e.actualFireAt}):`—`,u?(0,K.jsxs)(JC,{children:[(0,K.jsx)(YC,{asChild:!0,children:(0,K.jsx)(`span`,{className:`inline-flex text-info-indicator`,children:(0,K.jsx)(Cc,{size:14})})}),(0,K.jsxs)(XC,{children:[`Published `,r,` after the scheduled fire time`]})]}):null]})}),(0,K.jsx)(Z.Cell,{children:e.run?(0,K.jsx)(U,{as:`span`,variant:`body-sm`,font:`mono`,children:lT(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 ayi={id:`workflow-schedules`,label:`Schedules`,icon:An,to:`/workflows/schedules`};function oyi({label:e,children:t}){return(0,K.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,K.jsx)(U,{variant:`meta`,tone:`muted`,className:`uppercase`,children:e}),(0,K.jsx)(`div`,{children:(0,K.jsx)(U,{as:`span`,variant:`body`,className:`block`,children:t})})]})}function syi(){let{scheduleId:e}=Bb(),t=[cF(`/workflows`),ayi,{id:`schedule`,label:RPt(e),icon:An}],{paths:n}=gl(),{data:r,error:i}=nFt({scheduleId:e,queryOptions:{enabled:!!e}}),{data:a,isLoading:o,error:s,hasNextPage:c,isFetchingNextPage:l,setEndOfListElement:u}=iFt({scheduleId:e,queryOptions:{enabled:!!e}}),d=aFt({scheduleId:e});if(i&&YP(i))return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(fU,{variant:`fill`})]});if(i&&XP(i))return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(dU,{variant:`fill`,resource:`schedules`})]});if(i)return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(fw,{tone:`error`,variant:`fill`,titleSlot:`Failed to load schedule`,descriptionSlot:i.message})]});let f=r?.workflowId,p=r?.agentId;return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:t}),actionRow:(0,K.jsx)(iq,{children:(0,K.jsxs)(iq.End,{children:[(0,K.jsx)(X,{render:(0,K.jsx)(Zb,{to:n.schedulesLink()}),variant:`ghost`,icon:(0,K.jsx)(Rt,{}),children:`Back to schedules`}),f?(0,K.jsx)(X,{icon:(0,K.jsx)(aP,{}),render:(0,K.jsx)(Zb,{to:n.workflowLink(f)}),variant:`ghost`,children:`Open workflow`}):null,r?(0,K.jsx)(X,{onClick:()=>{let e=r.status===`active`?`pause`:`resume`;d.mutate(e,{onSuccess:()=>yw.success(e===`pause`?`Schedule paused`:`Schedule resumed`),onError:e=>yw.error(e.message)})},disabled:d.isPending,"data-testid":`schedule-toggle-button`,children:r.status===`active`?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(jo,{}),`Pause`]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Go,{}),`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)(oyi,{label:p?`Agent`:`Workflow`,children:f?(0,K.jsx)(Zb,{to:n.workflowLink(f),className:`text-foreground hover:underline`,children:f}):p?(0,K.jsx)(Zb,{to:n.agentLink(p),className:`text-foreground hover:underline`,children:p}):`—`}),(0,K.jsxs)(oyi,{label:`Cron`,children:[(0,K.jsx)(U,{as:`span`,variant:`body`,font:`mono`,children:r.cron}),r.timezone?(0,K.jsx)(U,{as:`span`,variant:`caption`,tone:`muted`,className:`ml-2`,children:r.timezone}):null]}),(0,K.jsx)(oyi,{label:`Status`,children:(0,K.jsx)(Qvi,{status:r.status})}),(0,K.jsx)(oyi,{label:`Next fire`,children:r.nextFireAt?(0,K.jsx)(TT,{value:r.nextFireAt}):`—`})]}),(0,K.jsxs)(`div`,{className:`overflow-y-auto`,"data-testid":`schedule-triggers-panel`,children:[(0,K.jsx)(U,{variant:`body`,className:`mb-3`,children:`Trigger history`}),s?(0,K.jsx)(fw,{tone:`error`,titleSlot:`Failed to load trigger history`,descriptionSlot:s.message}):(0,K.jsx)(iyi,{triggers:a??[],isLoading:o,workflowId:f,hasNextPage:c,isFetchingNextPage:l,setEndOfListElement:u})]})]}):null]})}var cyi={target:e=>e.workflowId??e.agentId??``,status:e=>e.status,nextFireAt:e=>e.nextFireAt,lastFireAt:e=>e.lastFireAt},lyi=`minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto`;function uyi({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 tZ(t?e.filter(e=>e.id.toLowerCase().includes(t)||(e.workflowId??e.agentId??``).toLowerCase().includes(t)):e,r,cyi)},[e,n,r]),{containerRef:c,getRowProps:l}=$X({count:s.length,global:!0});if(t)return(0,K.jsx)(OU,{columns:lyi});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:lyi,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)(U,{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)(U,{as:`span`,variant:`caption`,font:`mono`,children:e.cron}),e.timezone?(0,K.jsx)(U,{as:`span`,variant:`meta`,tone:`muted`,children:e.timezone}):null]})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(Qvi,{status:e.status})}),(0,K.jsx)(Z.Cell,{children:e.nextFireAt?(0,K.jsx)(TT,{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)($vi,{status:e.lastRun.status}),e.lastFireAt?(0,K.jsx)(U,{as:`span`,variant:`caption`,tone:`muted`,children:(0,K.jsx)(TT,{value:e.lastFireAt})}):null]}):e.lastFireAt?(0,K.jsx)(TT,{value:e.lastFireAt}):(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`Never`})})]},e.id))]})}function dyi({workflowId:e}={}){let{data:t,isLoading:n,error:r}=dF(e?{workflowId:e}:{}),[i,a]=(0,G.useState)(``),[o,s]=(0,G.useState)();return r?(0,K.jsx)(fw,{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)(PU,{onSearch:a,label:`Filter schedules`,placeholder:`Filter by id or workflow`})}),(0,K.jsx)(`div`,{className:`overflow-y-auto`,children:(0,K.jsx)(uyi,{schedules:t??[],isLoading:n,search:i,sort:o,onSortChange:(e,t)=>s({key:t,direction:e})})})]})}var fyi=[cF(`/workflows`),ayi];function pyi(){let[e]=Qb(),t=e.get(`workflowId`)??void 0,{error:n}=dF(t?{workflowId:t}:{});return n&&YP(n)?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:fyi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(fU,{variant:`fill`})]}):n&&XP(n)?(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:fyi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(dU,{variant:`fill`,resource:`schedules`})]}):(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:fyi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(`div`,{className:`h-full`,children:(0,K.jsx)(dyi,{workflowId:t})})]})}var myi={"--belt-hue":`var(--warning-indicator)`};function hyi(e){let t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function gyi(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 _yi({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:(0,K.jsxs)(`section`,{className:H(Rkt,`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)(U,{as:`h2`,variant:`column`,tone:`ink`,className:`flex items-center gap-2`,children:[(0,K.jsx)(QC,{children:(0,K.jsx)(Jn,{})}),`Step suspended`]}),(0,K.jsx)(hT,{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?fA(TA(n.resumeSchema)):nm(q(),Yp());return(0,K.jsx)(vyi,{step:e,stepSchema:i,description:n.description,onResume:r},`${e.runId}-${e.stepId}`)})]}),(0,K.jsx)(Ptt,{status:`ready`,label:`Needs input`,className:`before:hidden`,style:myi})]})}function vyi({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)(U,{as:`p`,variant:`subheading`,tone:`ink`,className:`break-words`,children:e.stepId}),n&&(0,K.jsx)(U,{as:`p`,variant:`caption`,tone:`muted`,children:n})]}),e.suspendPayload!==void 0&&(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsxs)(U,{as:`p`,variant:`caption`,tone:`muted`,className:`flex items-center gap-2`,children:[(0,K.jsx)(QC,{children:(0,K.jsx)(Vee,{})}),`The step is asking`]}),(0,K.jsxs)(iT,{open:i,onOpenChange:a,children:[(0,K.jsxs)(aT,{className:H(`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)(QC,{children:(0,K.jsx)(rt,{direction:`right`,className:`text-muted-foreground`})}),(0,K.jsx)(U,{as:`span`,variant:`body`,tone:`ink`,className:`truncate`,children:gyi(e.suspendPayload,e.stepId)})]}),(0,K.jsx)(U,{as:`span`,variant:`caption`,tone:`muted`,className:`shrink-0`,children:hyi(e.suspendPayload)})]}),(0,K.jsx)(oT,{children:(0,K.jsx)(`div`,{"data-testid":`suspended-payload`,className:`pt-2`,children:(0,K.jsx)(BD,{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)(U,{as:`p`,variant:`caption`,tone:`muted`,className:`flex items-center gap-2`,children:[(0,K.jsx)(QC,{children:(0,K.jsx)(Hee,{})}),`Your response`]}),(0,K.jsx)(`div`,{className:`-mx-5`,children:(0,K.jsx)(ekt,{schema:t,isSubmitLoading:o,submitButtonLabel:`Resume`,submitButtonVariant:`primary`,submitButtonIcon:(0,K.jsx)(Go,{}),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){yw.error(e instanceof Error?e.message:`Error resuming workflow`)}finally{s(!1)}}})})]})]})}function yyi({hidden:e,requestContext:t,canResume:n}){let{result:r,workflow:i,runId:a,isStreamingWorkflow:o}=(0,G.useContext)(sT),s=Egt(r,a),c=jgt(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)(_yi,{suspendedSteps:s,workflow:i,isStreaming:o,onResume:c})},a)}var byi={success:{label:`Completed`,icon:Ln},failed:{label:`Failed`,icon:er},suspended:{label:`Needs input`,icon:jo},waiting:{label:`Waiting`,icon:_c},paused:{label:`Paused`,icon:jo},skipped:{label:`Skipped`,icon:zs},running:{label:`Running`,icon:Da},canceled:{label:`Canceled`,icon:Zn}},xyi={label:`Status unavailable`,icon:yee};function Syi({row:e,isSelected:t,isHovered:n,onSelectStep:r,onHoverStep:i,onOpenInput:a,onOpenOutput:o}){let s=Object.hasOwn(byi,e.status)?byi[e.status]:xyi,c=s.icon,l=G1e(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:H(`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:H(`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`,vt),children:[(0,K.jsx)(`span`,{"aria-label":s.label,className:H(`grid size-6 flex-none place-items-center rounded-md border border-border bg-background`,K1e[l]),children:(0,K.jsx)(c,{"aria-hidden":!0,className:H(`size-3.5`,e.status===`running`&&`motion-safe:animate-spin`)})}),(0,K.jsxs)(`span`,{className:`min-w-0`,children:[(0,K.jsx)(U,{as:`span`,variant:`meta`,className:`block truncate`,children:d}),e.isNestedEntry&&(0,K.jsxs)(U,{as:`span`,variant:`meta`,tone:`muted`,className:`flex min-w-0 items-center gap-1`,children:[(0,K.jsx)(Sr,{"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:H(`absolute top-0 h-full min-w-0.5 rounded-sm`,q1e[l]),style:{left:`${e.timing.offsetPct}%`,width:`${e.timing.widthPct}%`}})}),(0,K.jsx)(U,{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)(U,{as:`span`,variant:`meta`,font:`mono`,children:lT(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 Cyi=e=>e.includes(`.`),wyi=e=>e===`input`||e.endsWith(`.input`),Tyi=1;function Eyi(e,t){let n=H1e(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 Dyi(e,t){let n=Object.entries(e).filter(([e])=>!wyi(e)).map(([e,n])=>({stepId:e,step:n,...Eyi(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,Tyi),100-t)}}return{stepId:e,step:t,status:_T(t)?`suspended`:t.status,timing:s,spansSuspension:a,isRunning:r,isNestedEntry:Cyi(e)}})}function Oyi(){let{steps:e}=oQ(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:i}=cT(),[a,o]=(0,G.useState)(()=>Date.now()),[s,c]=(0,G.useState)(!0),[l,u]=(0,G.useState)(!1),{showData:d}=dP(),f=(0,G.useRef)(null),p=Dyi(e,a),m=p.some(e=>e.isRunning);return WQe(f,{enabled:m&&!s}),(0,G.useEffect)(()=>{if(!m||s)return;let e=setInterval(()=>o(Date.now()),100);return()=>clearInterval(e)},[m,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)(iT,{open:!s,onOpenChange:e=>c(!e),className:H(ex,`@container/workflow-timeline pointer-events-auto overflow-hidden rounded-xl`),children:[(0,K.jsxs)(`div`,{className:`flex items-center`,children:[(0,K.jsxs)(aT,{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)(Fn,{"aria-hidden":!0,className:`size-4 text-muted-foreground`})}),(0,K.jsx)(`span`,{children:`Timeline`}),(0,K.jsxs)(U,{as:`span`,variant:`meta`,tone:`muted`,children:[p.length,` events`]}),(0,K.jsx)(`span`,{className:`ml-auto`,children:(0,K.jsx)(rt,{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)(iee,{}):(0,K.jsx)(Bn,{})})]}),(0,K.jsx)(oT,{children:(0,K.jsx)(`div`,{ref:f,"data-testid":`workflow-timeline-list`,className:H(`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)(Syi,{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 kyi=({workflowId:e,workflow:t,isLoading:n})=>{let[r]=Qw(`workflow`,e),{canExecute:i,isLoading:a}=Tw(),{stepDetail:o}=dP(),s=RE(),c=o?.type===`data`,l=(0,K.jsxs)(`div`,{className:`[container-type:size] relative h-full min-h-0`,children:[(0,K.jsx)($tr,{workflowId:e,workflow:t,isLoading:n,requestContext:r}),(0,K.jsx)(yyi,{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)(cQ,{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)(Oyi,{})})]});return s&&o&&!c?(0,K.jsx)(`div`,{className:`h-full min-h-0 overflow-hidden`,children:(0,K.jsx)(cQ,{requestContext:r})}):(0,K.jsxs)(`div`,{className:`relative h-full min-h-0`,children:[l,(0,K.jsxs)(R4,{className:`pointer-events-none absolute inset-0 z-30 min-h-0 w-full min-w-0 p-2`,children:[(0,K.jsx)(L4,{id:`workflow-graph`,className:`pointer-events-none min-w-0`}),o&&!c&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(z4,{className:`pointer-events-auto`}),(0,K.jsx)(L4,{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)(cQ,{requestContext:r})})})]})]})]})},Ayi=()=>{let{workflowId:e}=Bb(),{data:t,isLoading:n,error:r}=uP({workflowId:e,requestContext:Qw(`workflow`,e)[0],queryOptions:{enabled:!!e}});return r&&YP(r)?(0,K.jsx)(fU,{variant:`fill`}):r&&XP(r)?(0,K.jsx)(dU,{variant:`fill`,resource:`workflows`}):(0,K.jsx)(kyi,{workflowId:e,workflow:t??void 0,isLoading:n})};function jyi(){let{workflowId:e}=Bb(),{error:t}=dF(e?{workflowId:e}:{});if(!e)return null;let n;return n=t&&YP(t)?(0,K.jsx)(fU,{variant:`fill`}):t&&XP(t)?(0,K.jsx)(dU,{variant:`fill`,resource:`schedules`}):(0,K.jsx)(`div`,{className:`h-full`,children:(0,K.jsx)(dyi,{workflowId:e})}),(0,K.jsxs)(Jw,{children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),n]})}function Myi(){let{workflowId:e}=Bb();return e?(0,K.jsx)(P3r,{scopedEntityId:e,scopedEntityType:Uh.WORKFLOW_RUN}):null}var Nyi=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;function Pyi(e){let t=Nyi.exec(e);return t?{frontmatter:t[1]??``,body:e.slice(t[0].length)}:{frontmatter:null,body:e}}var Fyi=(0,G.createContext)(null);function K9(){let e=(0,G.useContext)(Fyi);if(!e)throw Error(`Workspace components must be rendered inside <Workspace.Root>`);return e}function Iyi({content:e}){let{frontmatter:t,body:n}=Pyi(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)(uJ,{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)(_Y,{children:n})})]})}var Lyi=e=>e?.status;function Ryi(e,t){return YP(e)?`Your session has expired. Sign in again to continue.`:XP(e)?`You don't have permission to access this.`:ZP(e)?`This path no longer exists.`:Lyi(e)===501?`This workspace does not support this operation.`:t}function zyi({error:e,fallback:t,className:n}){return(0,K.jsx)(HA,{variant:`destructive`,className:n,children:(0,K.jsx)(HA.Message,{children:Ryi(e,t)})})}function Byi(){let{activeFilePath:e}=K9();return e?(0,K.jsx)(U,{as:`span`,variant:`body-sm`,font:`mono`,tone:`muted`,className:`truncate`,"data-testid":`workspace-file-path`,children:e}):null}function Vyi({path:e,content:t,mimeType:n}){return Zjn(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`})}):Qjn(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:${eMn(e,n)};base64,${t}`,type:eMn(e,n)})})}):tMn(e)?(0,K.jsx)(Iyi,{content:t}):(0,K.jsx)(uJ,{code:t,lang:Y0e(e),overflow:`scroll`,className:`rounded-none border-0 bg-transparent [&_pre]:p-4`})}function Hyi({renderPreview:e}){let{workspaceId:t,activeFilePath:n}=K9(),{data:r,isLoading:i,error:a}=gMn({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)(Yw,{className:`h-4 w-1/2`}),(0,K.jsx)(Yw,{className:`h-4 w-5/6`}),(0,K.jsx)(Yw,{className:`h-4 w-2/3`})]});if(!r)return(0,K.jsx)(zyi,{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)(Vyi,{...o})}var Uyi=(e,t)=>e===`.`?t:`${e}/${t}`,Wyi=e=>e.split(`/`).slice(0,-1).map((e,t,n)=>n.slice(0,t+1).join(`/`)),Gyi=e=>{let t=e.lastIndexOf(`/`);return t===-1?`.`:e.slice(0,t)};function Kyi({labeled:e=!1}={}){let{workspaceId:t,onCreateDirectory:n,isReadOnly:r}=K9(),i=xy(),[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`,Gyi(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)(UE,{open:a,onOpenChange:o,pending:l,children:(0,K.jsx)(WE,{size:`sm`,children:(0,K.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),f()},children:[(0,K.jsx)(GE,{children:(0,K.jsx)(JE,{children:`New folder`})}),(0,K.jsx)(qE,{children:(0,K.jsx)(lN,{autoFocus:!0,"aria-label":`Folder path`,placeholder:`docs/guides`,value:s,onChange:e=>c(e.target.value)})}),(0,K.jsxs)(KE,{children:[(0,K.jsx)(XE,{children:`Cancel`}),(0,K.jsx)(X,{type:`submit`,variant:`primary`,disabled:!d||l,children:`Create`})]})]})})})]})}var qyi=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`})}),Jyi=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 Yyi(){let{isSearching:e,setSearching:t,searchFiles:n,searchSkills:r}=K9();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)(Jyi,{})})}function Xyi(){let{isSearching:e}=K9();return e?(0,K.jsx)($yi,{}):(0,K.jsx)(Qyi,{})}var Zyi=(e,t)=>`${e} ${t}${e===1?``:`s`}`;function Qyi(){let{fileCount:e,skillCount:t}=K9();return(0,K.jsxs)(U,{as:`span`,variant:`label`,tone:`muted`,className:`block min-w-0 truncate`,children:[(0,K.jsx)(`span`,{children:e===void 0?`Files`:Zyi(e,`File`)}),t===void 0?null:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(U,{as:`span`,variant:`label`,tone:`faint`,"aria-hidden":!0,className:`mx-1.5`,children:`·`}),(0,K.jsx)(`span`,{children:Zyi(t,`Skill`)})]})]})}function $yi(){let{setSearching:e,setQuery:t}=K9(),[n,r]=(0,G.useState)(``),[,i]=(0,G.useTransition)();return(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(lN,{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)(Bc,{})})]})}function ebi(){let{workspaceId:e,query:t,activeFilePath:n,setActiveFilePath:r,searchFiles:i,searchSkills:a}=K9(),{data:o,isLoading:s,isError:c,error:l}=bMn({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)(Yw,{className:`h-4 w-3/4`}),(0,K.jsx)(Yw,{className:`h-4 w-2/3`})]}):c?(0,K.jsx)(zyi,{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:H(`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)(QC,{size:`sm`,children:e.kind===`skill`?(0,K.jsx)(KX,{}):(0,K.jsx)(qyi,{})}),(0,K.jsx)(U,{as:`span`,variant:`body-sm`,className:`truncate`,children:e.label})]})},e.path))}):(0,K.jsx)(fw,{titleSlot:`No results`}):(0,K.jsx)(fw,{titleSlot:`Search files and skills`,descriptionSlot:`Type to find matching content.`})}function tbi(e){return`${e.topSource}/${e.name}`}function nbi(e){let t=aMn(e.topSource,e.name);return t?`${t.owner}/${t.repo}/${e.name}`:null}function rbi({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,m]=(0,G.useState)(),h=s?.some(e=>e.path===p)?p:s?.[0]?.path,{data:g,isLoading:_}=rMn({workspaceId:n,queryOptions:{enabled:!!n}}),v=nMn({workspaceId:n}),y=(0,G.useMemo)(()=>d?.topSource?aMn(d.topSource,d.name):null,[d]),b=(0,G.useMemo)(()=>!y||!d?null:`https://skills.sh/${y.owner}/${y.repo}/${d.name}`,[y,d]),{data:x,isLoading:S}=iMn({workspaceId:n,owner:y?.owner,repo:y?.repo,skillPath:d?.name,queryOptions:{enabled:!!n&&!!y&&!!d}}),C=jT(e=>{e.trim().length>=2&&v.mutate(e)},300),w=(0,G.useCallback)(e=>{u(e),C(e)},[C]),T=(0,G.useMemo)(()=>l.trim().length>=2?v.data?.skills??[]:g?.skills??[],[l,v.data,g]),E=v.isPending,D=l.trim().length>=2,O=(0,G.useMemo)(()=>{if(!d)return!1;let e=nbi(d);return!!(e&&a.includes(e)||o.includes(d.name))},[d,a,o]),k=(0,G.useCallback)(()=>{d&&y&&r({repository:`${y.owner}/${y.repo}`,skillName:d.name,mount:s&&s.length>1?h:void 0})},[d,y,r,s,h]),A=(0,G.useCallback)(e=>{e||(u(``),f(null),m(void 0)),t(e)},[t]);return(0,K.jsx)(UE,{open:e,onOpenChange:A,pending:i,children:(0,K.jsxs)(WE,{size:`xl`,className:`h-[80vh]`,children:[(0,K.jsxs)(GE,{children:[(0,K.jsx)(JE,{children:`Add Skill`}),(0,K.jsx)(YE,{children:`Search and install skills from the community registry`})]}),(0,K.jsxs)(qE,{layout:`fill`,children:[(0,K.jsx)(NU,{label:`Search skills`,placeholder:`Search skills...`,value:l,onValueChange:w}),(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)(U,{as:`p`,variant:`eyebrow`,tone:`muted`,className:`mb-2`,children:D?`Search Results`:`Popular Skills`}),(0,K.jsx)(Kw,{className:`flex-1 rounded-lg border border-border`,children:(0,K.jsx)(Gw,{className:!_&&!E&&T.length===0?`flex flex-col [&>div]:flex [&>div]:flex-1 [&>div]:flex-col`:void 0,children:_||E?(0,K.jsx)(`div`,{className:`flex items-center justify-center py-5`,children:(0,K.jsx)(Da,{className:`size-6 animate-spin text-muted-foreground`})}):T.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)(Zn,{className:`mb-2 size-8`}),(0,K.jsx)(U,{children:D?`No skills found`:`No skills available`})]}):(0,K.jsx)(`div`,{className:`space-y-1 p-2`,children:T.map(e=>{let t=tbi(e),n=nbi(e),r=n&&a.includes(n)||o.includes(e.name),i=d?tbi(d):null;return(0,K.jsx)(`button`,{onClick:()=>f(e),className:H(`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)(U,{as:`span`,variant:`subheading`,tone:`ink`,className:`truncate`,children:e.name}),r&&(0,K.jsxs)(U,{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)(Ln,{className:`size-2.5`}),`Installed`]})]}),(0,K.jsx)(U,{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)(Or,{className:`size-3`}),(0,K.jsx)(U,{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)(U,{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)(KX,{className:`size-5 text-muted-foreground`})}),(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsx)(U,{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)(GX,{className:`size-3`}),(0,K.jsx)(U,{as:`span`,variant:`caption`,className:`block`,children:d.topSource})]}),(0,K.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(Or,{className:`size-3`}),(0,K.jsxs)(U,{as:`span`,variant:`caption`,className:`block`,children:[d.installs.toLocaleString(),` installs`]})]})]})]}),y&&(0,K.jsx)(`a`,{href:`https://github.com/${y.owner}/${y.repo}`,target:`_blank`,rel:`noopener noreferrer`,className:H(`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)(Lr,{className:`size-4`})})]})}),S?(0,K.jsx)(`div`,{className:`flex flex-1 items-center justify-center`,children:(0,K.jsx)(Da,{className:`size-6 animate-spin text-muted-foreground`})}):x?(0,K.jsx)(Kw,{className:`flex-1`,children:(0,K.jsx)(`div`,{className:`p-4`,children:(0,K.jsx)(_Y,{children:x})})}):(0,K.jsxs)(`div`,{className:`flex flex-1 flex-col items-center justify-center text-muted-foreground`,children:[(0,K.jsx)(To,{className:`mb-2 size-8`}),(0,K.jsx)(U,{children:`Preview unavailable`}),b&&(0,K.jsxs)(`a`,{href:b,target:`_blank`,rel:`noopener noreferrer`,className:`mt-2 flex items-center gap-1 text-info-indicator hover:underline`,children:[(0,K.jsxs)(U,{as:`span`,variant:`caption`,className:`block`,children:[`View on skills.sh`,` `]}),(0,K.jsx)(Lr,{className:`size-3`})]})]})]}):(0,K.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center text-muted-foreground`,children:[(0,K.jsx)(To,{className:`mb-2 size-8`}),(0,K.jsx)(U,{children:`Select a skill to preview`})]})})]})]}),d&&s&&s.length>1&&(0,K.jsxs)(OA,{orientation:`horizontal`,className:H(`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)(AA,{className:`whitespace-nowrap`,children:`Install to`}),(0,K.jsxs)(tj,{value:h,onValueChange:m,children:[(0,K.jsx)(rj,{className:`flex-1`,children:(0,K.jsx)(nj,{})}),(0,K.jsx)(ij,{children:s.map(e=>{let t=e.displayName??e.name??e.provider??`unknown`;return(0,K.jsxs)(aj,{value:e.path,children:[t,` (`,e.path,`)`]},e.path)})})]})]})]}),d&&(0,K.jsxs)(KE,{children:[O&&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)(U,{as:`span`,variant:`caption`,tone:`muted`,className:`mr-auto`,children:[`Installed at `,t.path]}):null})(),(0,K.jsx)(XE,{children:`Cancel`}),(0,K.jsx)(HE,{onConfirm:k,disabled:!y||O,"data-testid":`install-skill-button`,children:i?`Installing...`:O?`Already installed`:`Install`})]})]})})}function ibi({labeled:e=!1}){let{workspaceId:t,addSkill:n}=K9(),[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)(Mc,{}),`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)(Mc,{})}),(0,K.jsx)(rbi,{...c,open:r,onOpenChange:i,workspaceId:t,onInstall:e=>void l(e),isInstalling:a})]})}function abi({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(Wyi(t??``))),[v,y]=(0,G.useState)(t);if(t!==v){y(t);let e=Wyi(t??``).filter(e=>!g.has(e));e.length>0&&_(new Set([...g,...e]))}let b=a?.join(`
|
|
696
696
|
`)??``,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(`
|
|
697
697
|
`):[]).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)(Fyi.Provider,{value:x,children:d})}var obi=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`})}),sbi=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`})});function cbi({mount:e}){switch(e.icon||e.provider){case`aws-s3`:case`s3`:return(0,K.jsx)(ckn,{className:`text-foreground`});case`google-cloud`:case`google-cloud-storage`:case`gcs`:return(0,K.jsx)(skn,{});case`azure-blob`:case`azure`:return(0,K.jsx)(dkn,{className:`text-badge-blue-indicator`});case`cloudflare`:case`cloudflare-r2`:case`r2`:return(0,K.jsx)(dr,{className:`text-badge-orange-indicator`});case`neon`:return(0,K.jsx)(dr,{className:`text-badge-green-indicator`});case`minio`:return(0,K.jsx)(Wi,{className:`text-badge-red-indicator`});case`database`:return(0,K.jsx)(Er,{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)(Wi,{className:`text-muted-foreground`});default:return(0,K.jsx)(dr,{className:`text-muted-foreground`})}}var lbi=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 ubi(){let{workspaceId:e,activeFilePath:t,setActiveFilePath:n}=K9(),{data:r,isLoading:i,error:a}=Lq({workspaceId:e,path:`.`}),[o,s]=(0,G.useState)(null);return i?(0,K.jsx)(vbi,{}):r?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(i3,{"aria-label":`Workspace files`,selectedId:t,onSelect:n,className:`py-1`,children:(0,K.jsx)(dbi,{entries:r,parent:`.`,onRequestDelete:s})}),(0,K.jsx)(_bi,{entry:o,onClose:()=>s(null)})]}):(0,K.jsx)(zyi,{error:a,fallback:`Could not load files.`,className:`m-2`})}function dbi({entries:e,parent:t,onRequestDelete:n}){return e.map(e=>{let r=Uyi(t,e.name);return e.type===`directory`?(0,K.jsx)(mbi,{name:e.name,path:r,mount:e.mount,onRequestDelete:n},e.name):(0,K.jsx)(gbi,{name:e.name,size:e.size,path:r,onRequestDelete:n},e.name)})}function fbi({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 pbi({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)(sbi,{})})}function mbi({name:e,path:t,mount:n,onRequestDelete:r}){let{workspaceId:i,onDelete:a,onCreateDirectory:o,isReadOnly:s,openFolders:c,setFolderOpen:l}=K9(),u=c.has(t),{isLoading:d}=Lq({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)(i3.Folder,{id:t,open:u,onOpenChange:e=>l(t,e),children:[(0,K.jsxs)(i3.FolderTrigger,{actions:m||h?(0,K.jsxs)(fbi,{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)(pbi,{name:e,onClick:()=>r({path:t,type:`directory`})}):null]}):void 0,children:[(0,K.jsx)(i3.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)(cbi,{mount:n})}):(0,K.jsx)(obi,{})}),(0,K.jsx)(i3.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)(Vn,{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)(ja,{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)($c,{size:`sm`,"aria-label":`Loading ${e}`,className:`size-3 text-muted-foreground`})}):null]}),(0,K.jsx)(i3.FolderContent,{children:u?(0,K.jsx)(hbi,{path:t,creating:f,onCreated:()=>p(!1),onRequestDelete:r}):null})]})}function hbi({path:e,creating:t,onCreated:n,onRequestDelete:r}){let{workspaceId:i,onCreateDirectory:a}=K9(),o=xy(),{data:s,isLoading:c,error:l}=Lq({workspaceId:i,path:e}),u=async t=>{try{await a?.(Uyi(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)(i3.Input,{type:`folder`,placeholder:`Folder name`,onSubmit:e=>void u(e),onCancel:n}):null,c?null:s?(0,K.jsx)(dbi,{entries:s,parent:e,onRequestDelete:r}):(0,K.jsx)(zyi,{error:l,fallback:`Could not load folder.`,className:`my-1 mr-1`})]})}function gbi({name:e,size:t,path:n,onRequestDelete:r}){let{onDelete:i,isReadOnly:a,activeFilePath:o}=K9(),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)(i3.File,{ref:l,id:n,children:[(0,K.jsx)(i3.Icon,{children:(0,K.jsx)(qyi,{})}),(0,K.jsx)(i3.Label,{children:e}),(0,K.jsxs)(fbi,{children:[t===void 0?null:(0,K.jsx)(U,{as:`span`,variant:`caption`,tone:`faint`,font:`mono`,children:lbi(t)}),s?(0,K.jsx)(pbi,{name:e,onClick:()=>r({path:n,type:`file`})}):null]})]})}function _bi({entry:e,onClose:t}){let{workspaceId:n,activeFilePath:r,setActiveFilePath:i,onDelete:a}=K9(),o=xy(),[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`,Gyi(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)(sP,{open:e!==null,onOpenChange:e=>{!e&&!s&&t()},children:(0,K.jsxs)(sP.Content,{children:[(0,K.jsxs)(sP.Header,{children:[(0,K.jsxs)(sP.Title,{children:[`Delete `,e?.type===`directory`?`folder`:`file`,`?`]}),(0,K.jsxs)(sP.Description,{children:[d,` This action cannot be undone.`]})]}),(0,K.jsxs)(sP.Footer,{children:[(0,K.jsx)(sP.Cancel,{disabled:s,children:`Cancel`}),(0,K.jsx)(X,{variant:`destructive`,disabled:s,onClick:()=>void u(),children:s?`Deleting…`:`Delete`})]})]})})}function vbi(){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)(Yw,{className:`h-4 w-3/4`}),(0,K.jsx)(Yw,{className:`h-4 w-1/2`}),(0,K.jsx)(Yw,{className:`h-4 w-2/3`})]})}function ybi({children:e,...t}){return(0,K.jsx)(abi,{...t,children:(0,K.jsx)(bbi,{children:e})})}function bbi({children:e}){let{workspaceId:t}=K9(),{data:n,error:r}=Lq({workspaceId:t,path:`.`});return(n?n.length===0:ZP(r))?(0,K.jsx)(fw,{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)(Kyi,{labeled:!0}),(0,K.jsx)(ibi,{labeled:!0})]})}):(0,K.jsx)(`div`,{className:`size-full overflow-hidden`,children:(0,K.jsx)(R4,{className:`size-full min-h-0 min-w-0`,orientation:`horizontal`,children:e})})}function xbi({children:e}){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(PNr,{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)(z4,{className:`w-px bg-border`})]})}function Sbi({children:e,actions:t}){let{isSearching:n}=K9();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 Cbi(){let{isSearching:e}=K9();return(0,K.jsx)(Kw,{className:`min-h-0 flex-1 px-2 py-1`,children:e?(0,K.jsx)(ebi,{}):(0,K.jsx)(ubi,{})})}function wbi({children:e}){return(0,K.jsx)(L4,{id:`workspace-active-file`,className:`flex min-w-0 flex-col`,minSize:30,children:e})}function Tbi({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}=K9();return t?(0,K.jsx)(Kw,{className:`min-h-0 flex-1`,children:(0,K.jsx)(Hyi,{renderPreview:e})}):(0,K.jsx)(fw,{variant:`fill`,titleSlot:`Select a file`})}var q9={Root:ybi,Aside:xbi,AsideHeader:Sbi,Search:Xyi,SearchToggle:Yyi,CreateDirectory:Kyi,Tree:Cbi,ActiveFile:wbi,ActiveFileHeader:Tbi,FilePath:Byi,ActiveFileContent:Ebi};function Dbi({asideActions:e,renderPreview:t,...n}){return(0,K.jsxs)(q9.Root,{...n,children:[(0,K.jsxs)(q9.Aside,{children:[(0,K.jsx)(q9.AsideHeader,{actions:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(q9.SearchToggle,{}),(0,K.jsx)(q9.CreateDirectory,{}),(0,K.jsx)(ibi,{}),e]}),children:(0,K.jsx)(q9.Search,{})}),(0,K.jsx)(q9.Tree,{})]}),(0,K.jsxs)(q9.ActiveFile,{children:[(0,K.jsx)(q9.ActiveFileHeader,{children:(0,K.jsx)(q9.FilePath,{})}),(0,K.jsx)(q9.ActiveFileContent,{renderPreview:t})]})]})}var Obi=()=>(0,K.jsx)(fw,{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)(Lr,{}),children:`Workspaces documentation`}),variant:`fill`}),kbi=()=>(0,K.jsx)(fw,{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)(Lr,{}),children:`Workspaces documentation`}),variant:`fill`}),Abi=()=>(0,K.jsx)(fw,{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)(Lr,{}),children:`Workspaces documentation`}),variant:`fill`}),jbi=`.agents/skills`,Mbi=e=>e.replace(/^\.?\/+|\/+$/g,``);function Nbi({workspaceId:e,showInitWarning:t,skills:n}){let{data:r}=Lq({workspaceId:e,path:jbi,queryOptions:{enabled:!!n}}),i=n&&r?r.filter(e=>e.type===`directory`&&!n.some(t=>t.name===e.name||Mbi(t.path)===`${jbi}/${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)(HA,{variant:`warning`,children:(0,K.jsxs)(HA.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)(HA,{variant:`warning`,title:`Skills installed but not discovered`,children:(0,K.jsxs)(HA.Message,{children:[i.map(e=>e.name).join(`, `),` `,i.length===1?`is`:`are`,` in`,` `,(0,K.jsx)(`code`,{children:jbi}),` but not discovered. Add this path to your workspace skills configuration to see `,i.length===1?`it`:`them`,`.`]})})]})}var J9=[cF(`/workspaces`)],Pbi=e=>XP(e)?`you don't have permission to modify this workspace`:e instanceof Error?e.message:`Unknown error`;function Fbi(){let{workspaceId:e}=Bb(),[t,n]=Qb(),r=zb(),i=xy(),a=t.get(`file`),{data:o,error:s,isLoading:c}=dMn(),l=o?.workspaces??[],u=e??l[0]?.id,{data:d,isLoading:f,error:p}=uMn({workspaceId:u,queryOptions:{enabled:!!u}}),m=YP(s)||YP(p),h=XP(s)||XP(p),g=Kjn(s)||Kjn(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=pMn(),C=mMn(),w=d?.isWorkspaceConfigured??!1,T=d?.capabilities?.hasDynamicFilesystem??!1,E=(d?.capabilities?.hasFilesystem??!1)&&!T,D=d?.capabilities?.hasSkills??!1,{data:O,refetch:k}=xMn({workspaceId:u,queryOptions:{enabled:!!u&&E}}),A=oMn(),j=sMn(),M=cMn(),N=e=>{let t=/^\.agents\/skills\/([^/]+)$/.exec(e);if(t)return oe.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?yw.error(`Failed to update ${t.map(e=>e.skillName).join(`, `)}`):yw.success(`${e.updated.length} skill(s) updated`),i.invalidateQueries({queryKey:[`workspace`,u,`fs`]})}catch(e){yw.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}"`);yw.success(`Skill "${n}" removed`),k()}catch(e){throw yw.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 yw.error(`Failed to delete ${e}: ${Pbi(t)}`),t}},I=_?.safety?.readOnly??!1,{canEdit:L,canDelete:R,canExecute:ee,isLoading:z}=Tw(),B=!z&&L(`workspaces`)&&!I,V=!z&&R(`workspaces`)&&!I,te=!z&&ee(`workspaces`),ne=E&&D&&B,re=d?.mounts,ie=re?.filter(e=>!e.readOnly).map(e=>({path:e.path,displayName:e.displayName,icon:e.icon,provider:e.provider,name:e.name})),ae=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(),yw.success(`Skill "${t.skillName}" installed successfully (${t.filesWritten} files)`)}catch(e){throw yw.error(`Failed to install skill: ${e instanceof Error?e.message:`Unknown error`}`),e}},oe=O?.skills??[],se=O?.isSkillsConfigured??!1,ce=te&&E&&!!(d?.capabilities?.canBM25||d?.capabilities?.canVector),le=te&&D&&se&&oe.length>0,ue=I?[`.`]:(re??[]).filter(e=>e.readOnly).map(e=>e.path.replace(/^\/+|\/+$/g,``)||`.`);if(c)return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:J9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)($c,{fill:!0})]});if(m)return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:J9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(fU,{variant:`fill`})]});if(h)return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:J9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(dU,{variant:`fill`,resource:`workspaces`})]});if(g)return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:J9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(Abi,{})]});let de=s||p;if(de)return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:J9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(fw,{tone:`error`,variant:`fill`,titleSlot:`Failed to load workspace`,descriptionSlot:de.message})]});if(!c&&l.length===0)return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:J9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(Obi,{})]});if(!f&&!c&&!w)return(0,K.jsxs)(Jw,{breadcrumbs:(0,K.jsx)(DP,{crumbs:J9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(kbi,{})]});let fe=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)(hT,{size:`xs`,variant:`warning`,children:`Read-only`}),e.capabilities.hasFilesystem&&(0,K.jsx)(hT,{size:`xs`,children:`FS`}),e.capabilities.hasSandbox&&(0,K.jsx)(hT,{size:`xs`,children:`Sandbox`}),e.capabilities.hasSkills&&(0,K.jsx)(hT,{size:`xs`,children:`Skills`})]})}));return(0,K.jsxs)(Jw,{variant:`fit`,breadcrumbs:(0,K.jsx)(DP,{crumbs:J9}),headerActions:(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(EP,{"aria-label":`Workspace`,variant:`ghost`,className:`w-auto`,options:fe,value:_?.id,onValueChange:y,placeholder:`Select workspace`,searchPlaceholder:`Search workspaces...`,emptyText:`No workspaces found.`}),I&&(0,K.jsx)(hT,{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)(Nbi,{workspaceId:u,showInitWarning:ce&&!f&&d?.status!==`ready`,skills:D&&O?oe:void 0}),E&&u&&(0,K.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,K.jsx)(Dbi,{workspaceId:u,activeFilePath:x,onActiveFileChange:b,readOnlyPaths:ue,skillCount:D&&O?oe.length:void 0,searchFiles:ce,searchSkills:le,onCreateDirectory:B?async e=>{try{await C.mutateAsync({path:e,recursive:!0,workspaceId:u})}catch(t){throw yw.error(`Failed to create ${e}: ${Pbi(t)}`),t}}:void 0,asideActions:ne&&oe.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)(is,{className:j.isPending?`animate-spin`:void 0})}):void 0,addSkill:ne?{onInstall:ae,installedSkillIds:oe.filter(e=>e.skillsShSource).map(e=>`${e.skillsShSource.owner}/${e.skillsShSource.repo}/${e.name}`),installedSkillNames:oe.filter(e=>!e.skillsShSource).map(e=>e.name),writableMounts:ie,installedSkillPaths:Object.fromEntries(oe.filter(e=>e.path).map(e=>[e.name,e.path]))}:void 0,onDelete:V?F:void 0},u)}),T&&!f&&(0,K.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,K.jsx)(fw,{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)(fw,{variant:`fill`,titleSlot:`No filesystem or skills configured`,descriptionSlot:`Add a filesystem or skills to this workspace to browse its files here.`})})]})]})}function Ibi({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:H(`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:H(`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 Lbi({children:e,className:t,edgeToEdge:n}){let r=n!==void 0;return(0,K.jsx)(`div`,{"data-slot":`main-card`,className:H(`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`,KWe,t),children:e})}function Rbi(){return(0,K.jsxs)(`div`,{className:`h-screen bg-sidebar`,children:[(0,K.jsx)(bw,{position:`bottom-right`}),(0,K.jsx)(lt,{defaultTheme:`system`,children:(0,K.jsx)(qC,{delayDuration:0,children:(0,K.jsx)(Ibi,{children:(0,K.jsx)(Lbi,{className:`flex items-center justify-center overflow-y-auto`,children:(0,K.jsx)(qb,{})})})})})]})}function zbi(){let{data:e,isLoading:t}=Vy(),{isLoading:n,canAccessAgentBuilder:r}=Ew();return t||n||!e||e.enabled&&!By(e)?{isVisible:!1}:{isVisible:r}}function Bbi(){let{isImpersonating:e,impersonatedRole:t,stopImpersonation:n}=ww();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)(Vr,{className:`h-3.5 w-3.5 shrink-0 text-info-subtle-foreground`}),(0,K.jsxs)(U,{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)(Bc,{className:`h-3 w-3`})})]})}function Vbi({children:e,contentClassName:t,commandClassName:n,showOverlay:r=!0,overlayClassName:i,...a}){return(0,K.jsx)(N5r,{size:`xl`,showOverlay:r,overlayClassName:H(`bg-sidebar/40 backdrop-blur-none`,i),contentClassName:H(`command-palette-popup overflow-visible bg-transparent shadow-none`,t),commandClassName:H(`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 Hbi({wrapperClassName:e,...t}){return(0,K.jsx)(P5r,{wrapperClassName:H(`command-palette-surface command-palette-surface-input`,nw,`h-11 shrink-0 rounded-xl border-0 px-3 pr-11`,e),...t})}function Ubi({children:e,className:t,...n}){return(0,K.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,K.jsx)(`div`,{className:H(`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 Wbi({children:e,className:t,...n}){return(0,K.jsx)(`aside`,{className:H(`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`,tx,t),...n,children:(0,K.jsx)(Kw,{className:`-m-1 min-h-0 flex-1 p-1`,children:(0,K.jsx)(Gw,{className:`pr-1`,children:(0,K.jsx)(`div`,{className:`flex flex-col gap-1`,children:e})})})})}function Gbi({icon:e,label:t,count:n,active:r,onSelect:i}){return(0,K.jsxs)(`button`,{type:`button`,className:H(Nw,`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)(U,{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 Kbi({children:e,footer:t,...n}){return(0,K.jsxs)(`div`,{role:`region`,className:H(`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`,tx),...n,children:[(0,K.jsx)(F5r,{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 Y9({icon:e,title:t,subtitle:n,path:r,badge:i,shortcut:a,className:o,...s}){return(0,K.jsxs)(R5r,{className:H(`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:H(`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)(U,{as:`span`,variant:`label`,tone:`ink`,className:`truncate`,children:t}),i&&(0,K.jsx)(U,{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)(U,{as:`span`,variant:`meta`,tone:`muted`,className:`flex min-w-0 items-center gap-2`,children:[n&&(0,K.jsx)(`span`,{className:`truncate`,children:n}),r&&(0,K.jsx)(U,{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)(z5r,{children:a})]})}function qbi({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)(lw,{size:`sm`,children:`↑`}),(0,K.jsx)(lw,{size:`sm`,children:`↓`}),(0,K.jsx)(lw,{size:`sm`,children:`↵`}),(0,K.jsx)(lw,{size:`sm`,children:`Esc`})]})]})}var Jbi=!1,Ybi=new Set,Xbi=()=>{Ybi.forEach(e=>e())},Zbi=e=>(Ybi.add(e),()=>Ybi.delete(e)),Qbi=()=>Jbi,$bi=e=>{let t=typeof e==`function`?e(Jbi):e;t!==Jbi&&(Jbi=t,Xbi())},exi=({enableShortcut:e=!0}={})=>{let t=(0,G.useSyncExternalStore)(Zbi,Qbi,Qbi),n=(0,G.useCallback)(e=>{$bi(e)},[]),r=(0,G.useCallback)(()=>{$bi(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 txi(e,t){return[e.name,e.url,t,`path route navigate`].filter(Boolean).join(` `)}function nxi(e){return!e||e===`Studio`?`Path`:e}function rxi(e){return`/traces?entity=${encodeURIComponent(e)}`}var ixi=({scopeOptions:e,activeScope:t,onScopeChange:n})=>(0,K.jsx)(Wbi,{"aria-label":`Search categories`,children:e.map(e=>(0,K.jsx)(Gbi,{icon:e.icon,label:e.label,count:e.count,active:t===e.id,onSelect:()=>n(e.id)},e.id))}),axi=({sidebar:e,activeScope:t,closeCommand:n})=>!e||t!==`all`&&t!==`settings`?null:(0,K.jsx)(W5,{heading:`Commands`,children:(0,K.jsx)(Y9,{value:`toggle sidebar collapse expand layout panel`,onSelect:()=>{e.toggleSidebar(),n()},icon:(0,K.jsx)(Do,{}),title:`Toggle sidebar`,subtitle:`Studio layout`})}),oxi=({sections:e,handleSelect:t})=>(0,K.jsx)(K.Fragment,{children:e.map(e=>(0,K.jsx)(W5,{heading:e.title,children:e.items.map(n=>{let r=n.Icon;return(0,K.jsx)(Y9,{value:txi(n,e.title),onSelect:()=>t(n.url),icon:(0,K.jsx)(r,{}),title:n.name,subtitle:`Studio path`,path:n.url,badge:nxi(e.title)},n.url)})},e.key))}),sxi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(W5,{heading:`Agents`,children:t.map(([e,t])=>(0,K.jsx)(Y9,{value:`${t.name} ${e} chat agent conversation thread ${n.agentLink(e)}`,onSelect:()=>r(n.agentLink(e)),icon:(0,K.jsx)(nF,{}),title:t.name,subtitle:`Agent chat`,path:n.agentLink(e),badge:`Agent`},e))}),cxi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(W5,{heading:`Workflows`,children:t.map(([e,t])=>(0,K.jsx)(Y9,{value:`${t.name} ${e} graph workflow view ${n.workflowLink(e)}`,onSelect:()=>r(n.workflowLink(e)),icon:(0,K.jsx)(aP,{}),title:t.name,subtitle:`Workflow graph`,path:n.workflowLink(e),badge:`Workflow`},e))}),lxi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(W5,{heading:`Tools`,children:t.map(([e,t])=>(0,K.jsx)(Y9,{value:`tool ${t.id} ${e} ${n.toolLink(e)}`,onSelect:()=>r(n.toolLink(e)),icon:(0,K.jsx)(oF,{}),title:t.id,subtitle:`Tool definition`,path:n.toolLink(e),badge:`Tool`},e))}),uxi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(W5,{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)(Y9,{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)})}),dxi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(W5,{heading:`MCP Servers`,children:t.map(e=>(0,K.jsx)(Y9,{value:`mcp server ${e.name} ${e.id} ${n.mcpServerLink(e.id)}`,onSelect:()=>r(n.mcpServerLink(e.id)),icon:(0,K.jsx)(rF,{}),title:e.name,subtitle:`MCP server`,path:n.mcpServerLink(e.id),badge:`MCP`},e.id))}),fxi=({visible:e,agentEntries:t,workflowEntries:n,handleSelect:r})=>e?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(W5,{heading:`Observability`,children:[(0,K.jsx)(Y9,{value:`observability traces telemetry signals /traces`,onSelect:()=>r(`/traces`),icon:(0,K.jsx)(Vr,{}),title:`Traces`,subtitle:`Runtime traces`,path:`/traces`,badge:`Signal`}),(0,K.jsx)(Y9,{value:`metrics usage latency performance tokens /metrics`,onSelect:()=>r(`/metrics`),icon:(0,K.jsx)(Ei,{}),title:`Metrics`,subtitle:`Runtime metrics`,path:`/metrics`,badge:`Signal`}),(0,K.jsx)(Y9,{value:`logs events runtime /logs`,onSelect:()=>r(`/logs`),icon:(0,K.jsx)(Vr,{}),title:`Logs`,subtitle:`Runtime logs`,path:`/logs`,badge:`Signal`})]}),t.length>0&&(0,K.jsx)(W5,{heading:`Agent Traces`,children:t.map(([e,t])=>{let n=rxi(e);return(0,K.jsx)(Y9,{value:`${t.name} ${e} traces agent observability telemetry`,onSelect:()=>r(n),icon:(0,K.jsx)(Vr,{}),title:t.name,subtitle:`Agent traces`,path:n,badge:`Trace`},e)})}),n.length>0&&(0,K.jsx)(W5,{heading:`Workflow Traces`,children:n.map(([e,t])=>{let n=rxi(t.name);return(0,K.jsx)(Y9,{value:`${t.name} ${e} traces workflow observability telemetry`,onSelect:()=>r(n),icon:(0,K.jsx)(Vr,{}),title:t.name,subtitle:`Workflow traces`,path:n,badge:`Trace`},e)})})]}):null,pxi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(W5,{heading:`Scorers`,children:t.map(([e,t])=>{let i=t.scorer?.config?.name||t.scorer?.config?.id||e;return(0,K.jsx)(Y9,{value:`scorer score evaluation ${i} ${e} ${n.scorerLink(e)}`,onSelect:()=>r(n.scorerLink(e)),icon:(0,K.jsx)(Ei,{}),title:i,subtitle:`Evaluation scorer`,path:n.scorerLink(e),badge:`Scorer`},e)})}),mxi=()=>{let{open:e,setOpen:t}=exi(),{navigate:n,paths:r}=gl(),{isMastraPlatform:i}=p6(),a=F2(),[o,s]=G.useState(`all`),{data:c={}}=FP(),{data:l={}}=lP(),{data:u={}}=vq(),{data:d={}}=JP(),{data:f=[]}=qP(),{data:p={}}=tF(),{isCmsAvailable:m,isLoading:h}=Z2(),{hasPermission:g,hasAnyPermission:_,isLoading:v}=Tw(),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=kw(e.url);return v&&t&&t!==`public`?!1:Aw(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 PPt){let n=t.items.filter(S);n.length>0&&e.push({key:t.key,title:t.title,items:n})}let t=[...FPt.filter(S),...i?[]:[{name:`Templates`,url:`/templates`,Icon:To,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)(Ss,{}),count:P},{id:`paths`,label:`Paths`,icon:(0,K.jsx)(gs,{}),count:k},{id:`agents`,label:`Agents`,icon:(0,K.jsx)(nF,{}),count:C.length},{id:`workflows`,label:`Workflows`,icon:(0,K.jsx)(aP,{}),count:w.length},{id:`tooling`,label:`Tooling`,icon:(0,K.jsx)(ta,{}),count:A},{id:`evaluation`,label:`Evaluation`,icon:(0,K.jsx)(Ei,{}),count:j},{id:`observability`,label:`Intelligence`,icon:(0,K.jsx)(Vr,{}),count:M},{id:`settings`,label:`Studio`,icon:(0,K.jsx)(Vs,{}),count:N}],I=o===`all`||o===`paths`,L=o===`all`||o===`agents`,R=o===`all`||o===`workflows`,ee=o===`all`||o===`tooling`,z=o===`all`||o===`evaluation`,B=o===`all`||o===`observability`,V=o===`settings`,te=G.useMemo(()=>{let e=[];for(let t of O)V?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,V]);return(0,K.jsxs)(Vbi,{open:e,onOpenChange:y,title:`Mastra Studio Search`,description:`Search Studio routes and runtime entities`,children:[(0,K.jsx)(Hbi,{placeholder:`Search Studio, agents, workflows, tools, paths...`}),(0,K.jsxs)(Ubi,{children:[(0,K.jsx)(ixi,{scopeOptions:F,activeScope:o,onScopeChange:s}),(0,K.jsxs)(Kbi,{"aria-label":`Search results`,footer:(0,K.jsx)(qbi,{label:`Studio search`}),children:[(0,K.jsx)(I5r,{children:`No matching results.`}),(0,K.jsx)(axi,{sidebar:a,activeScope:o,closeCommand:b}),(0,K.jsx)(oxi,{sections:te,handleSelect:x}),(0,K.jsx)(sxi,{visible:L,entries:C,paths:r,handleSelect:x}),(0,K.jsx)(cxi,{visible:R,entries:w,paths:r,handleSelect:x}),(0,K.jsx)(lxi,{visible:ee,entries:T,paths:r,handleSelect:x}),(0,K.jsx)(uxi,{visible:ee,entries:E,paths:r,handleSelect:x}),(0,K.jsx)(dxi,{visible:ee,entries:f,paths:r,handleSelect:x}),(0,K.jsx)(fxi,{visible:B,agentEntries:C,workflowEntries:w,handleSelect:x}),(0,K.jsx)(pxi,{visible:z,entries:D,paths:r,handleSelect:x})]})]})]})};function hxi(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 gxi(e){let{Icon:t}=e;return{name:e.name,url:e.url,icon:(0,K.jsx)(t,{})}}function _xi(){let{state:e,isMobile:t,setOpenMobile:n}=I2(),{setOpen:r}=exi({enableShortcut:!1}),i=MWr(`K`),a=Rb().pathname,{isMastraPlatform:o}=p6(),{data:s}=Vy(),{isCmsAvailable:c,isLoading:l}=Z2(),{hasPermission:u,hasAnyPermission:d,isLoading:f}=Tw(),{data:p}=nir(),m=p!==void 0&&p.status!==`not-mounted`,h=s&&By(s),g=new Set([`/prompts`]),{isVisible:_}=zbi(),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=kw(e.url);if(t&&t!==`public`)return!1}return!!Aw(kw(e.url),u,d)},{data:x}=qP(),{data:S}=dMn(),C=FPt.filter(b),w=PPt.map(e=>{let t=e.items.filter(b),n=e=>({...gxi(e),isActive:hxi(e,a,t)});return{key:e.key,title:e.title,href:e.href,isHeaderActive:!(!e.href||a!==e.href||t.some(e=>hxi(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)(z2,{"aria-label":`Sidebar`,children:[(0,K.jsxs)(z2.Header,{collapsedLogo:(0,K.jsx)(cZ,{className:`size-6`}),actions:h&&(0,K.jsx)(C3n,{}),children:[(0,K.jsx)(z2.Brand,{logo:(0,K.jsx)(cZ,{className:`size-6`}),title:`Mastra Studio`}),!t&&(0,K.jsx)(z2.SearchTrigger,{"aria-label":`Search and navigate`,shortcut:i,onClick:y}),(0,K.jsx)(z2.Trigger,{})]}),_&&(0,K.jsx)(z2.NavList,{className:`mb-1`,children:(0,K.jsx)(z2.NavLink,{state:e,link:{name:`Agent Builder`,url:`/agent-builder`,icon:(0,K.jsx)(Rc,{})},isActive:v})}),(0,K.jsx)(Bbi,{}),(0,K.jsx)(z2.Nav,{children:(0,K.jsx)(z2.Sections,{sections:w,visibilityStorageKey:`mastra:studio:sidebar-visibility`})}),(0,K.jsx)(z2.Footer,{children:(0,K.jsxs)(z2.NavList,{children:[C.map(t=>(0,K.jsx)(z2.NavLink,{state:e,link:gxi(t),isActive:hxi(t,a)},t.name)),(0,K.jsx)(bAr,{state:e})]})})]})}var vxi=()=>{let{baseUrl:e,headers:t,apiPrefix:n,setConfig:r}=jw(),[i,a]=(0,G.useState)(()=>Object.entries(t).map(([e,t])=>({name:e,value:t})));return(0,K.jsx)(qC,{delayDuration:0,children:(0,K.jsxs)(lU,{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}),yw.success(`Headers saved`)},className:`w-full max-w-md gap-6 text-left`,children:[(0,K.jsx)(rOr,{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)(ys,{}),`Save headers`]})]})})};function yxi({children:e,loginUrl:t=`/login`,signupUrl:n=`/signup`}){let{data:r,isLoading:i}=Vy();if(i||!r?.enabled||By(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)(cZ,{className:`h-16 w-16 opacity-50`}),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(U,{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)(ja,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}),(0,K.jsx)(U,{tone:`muted`,className:`max-w-sm`,children:r.login.description})]}),(0,K.jsx)(b3n,{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)(U,{as:`span`,variant:`body`,tone:`muted`,children:`Don't have an account? `}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>{let e=new URL(lZ(n),window.location.origin);a&&e.searchParams.set(`redirect`,a),window.location.href=e.toString()},className:`text-foreground hover:underline`,children:(0,K.jsx)(U,{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)(cZ,{className:`h-16 w-16 opacity-50`}),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(U,{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)(vxi,{})]})})}var bxi=`experimental-ui:`,xxi=`current`,Sxi=G.createContext(null);function Cxi(e,t){let n=window.localStorage.getItem(bxi+e);return n&&t.has(n)?n:xxi}function wxi({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]=Cxi(r.key,e)}i(t)},[e,n]);let a=G.useCallback(e=>r[e]??xxi,[r]),o=G.useCallback((e,t)=>{window.localStorage.setItem(bxi+e,t),i(n=>({...n,[e]:t}))},[]),s=G.useMemo(()=>({experiments:e,getVariant:a,setVariant:o}),[e,a,o]);return(0,K.jsx)(Sxi.Provider,{value:s,children:t})}var Txi=[{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`}]}],Exi=()=>({experimentalUIEnabled:typeof window<`u`&&window.MASTRA_EXPERIMENTAL_UI===`true`}),Dxi=()=>{let{toggleSidebar:e}=I2();return uw({"[":e},{repeat:!1}),null};function Oxi(){let{setOpenMobile:e}=I2(),{setOpen:t}=exi({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)(z2.MobileTrigger,{}),(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(cZ,{className:`size-[1.5rem] shrink-0`}),(0,K.jsx)(U,{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)(Ss,{})})]})}var kxi={"studio-frame":100,"route-side-panel":0},Axi={overflow:`visible`};function jxi({children:e,className:t}){let n=RE(),{hasPanel:r,panelHandle:i,onPanelResize:a}=k7(),{defaultLayout:o,onLayoutChange:s}=wNr({id:`studio-frame-layout-v1`,storage:localStorage});return(0,K.jsx)(`div`,{className:`relative flex min-h-0 flex-1`,children:(0,K.jsxs)(R4,{className:`min-h-0 flex-1`,style:Axi,orientation:`horizontal`,defaultLayout:o??kxi,onLayoutChange:s,children:[(0,K.jsx)(L4,{id:`studio-frame`,className:H(`min-w-0`,t),style:Axi,children:e}),r&&!n&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(z4,{className:`w-2`}),(0,K.jsx)(PNr,{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)(Mii,{className:`h-full min-h-0`})})]})]})})}function Mxi({children:e}){let{data:t,isFetched:n}=Vy(),{pathname:r}=Rb(),i=!(n&&t?.enabled&&!By(t));return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(mxi,{}),(0,K.jsx)(Ibi,{sidebar:i?(0,K.jsx)(_xi,{}):void 0,mobileHeader:i?(0,K.jsx)(Oxi,{}):void 0,children:(0,K.jsx)(jxi,{className:`flex min-h-0 flex-1 flex-col`,children:(0,K.jsx)(Lbi,{children:(0,K.jsx)(yxi,{children:(0,K.jsx)(VQe,{resetKeys:[r],children:e})})})})})]})}var Nxi=({children:e})=>{let{experimentalUIEnabled:t}=Exi(),{Link:n}=gl();return(0,K.jsxs)(`div`,{className:`h-screen bg-sidebar`,children:[(0,K.jsx)(bw,{position:`bottom-right`}),(0,K.jsx)(lt,{defaultTheme:`system`,children:(0,K.jsx)(qC,{delayDuration:0,children:(0,K.jsx)(wxi,{experiments:t?Txi:[],children:(0,K.jsxs)(z2.Provider,{LinkComponent:n,children:[(0,K.jsx)(Dxi,{}),(0,K.jsx)(jii,{children:(0,K.jsx)(Mxi,{children:e})})]})})})})]})},Pxi=({children:e})=>(0,K.jsxs)(`div`,{className:`h-screen bg-sidebar`,children:[(0,K.jsx)(bw,{position:`bottom-right`}),(0,K.jsx)(lt,{defaultTheme:`system`,children:(0,K.jsx)(qC,{delayDuration:0,children:(0,K.jsx)(`div`,{className:`h-full overflow-y-auto`,children:(0,K.jsx)(yxi,{children:e})})})})]}),Fxi={name:`Agents`,url:`/agent-builder/agents`,icon:(0,K.jsx)(nF,{})},Ixi={name:`Skills`,url:`/agent-builder/skills`,icon:(0,K.jsx)(an,{className:`size-5`})},Lxi={name:`Favorites`,url:`/agent-builder/favorite`,icon:(0,K.jsx)(Xs,{className:`size-5`})},Rxi={name:`Library`,url:`/agent-builder/library`,icon:(0,K.jsx)(aa,{className:`size-5`})},zxi={name:`Infra`,url:`/agent-builder/infrastructure`,icon:(0,K.jsx)(Ts,{className:`size-5`})};function Bxi(){let{Link:e}=gl(),{pathname:t}=Rb(),n=lq(),{canManageSkills:r,canUseFavorites:i}=Ew(),{hasPermission:a}=Tw(),o=a(`infrastructure:read`),s=(0,G.useMemo)(()=>{let e=[Fxi];return n.skills&&r&&e.push(Ixi),i&&e.push(Lxi),e.push(Rxi),o&&e.push(zxi),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:H(r?`text-foreground`:`text-muted-foreground`,`relative flex flex-col items-center justify-center gap-1 py-2`,$e,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)(U,{as:`span`,variant:`caption`,className:`block`,children:n.icon})}),(0,K.jsx)(U,{as:`span`,variant:`caption`,children:n.name})]})},n.name)})})})}var Vxi={name:`My agents`,url:`/agent-builder/agents`,icon:(0,K.jsx)(nF,{})},Hxi={name:`Favorites`,url:`/agent-builder/favorite`,icon:(0,K.jsx)(Xs,{})},Uxi={name:`Library`,url:`/agent-builder/library`,icon:(0,K.jsx)(aa,{})},Wxi={name:`Skills`,url:`/agent-builder/skills`,icon:(0,K.jsx)(an,{className:`h-4 w-4`})},Gxi={name:`Infrastructure`,url:`/agent-builder/infrastructure`,icon:(0,K.jsx)(Ts,{className:`h-4 w-4`})};function Kxi({forceExpanded:e=!1}={}){let{Link:t}=gl(),{state:n,isMobile:r}=I2(),{pathname:i}=Rb(),a=lq(),{canManageSkills:o,canUseFavorites:s}=Ew(),{hasPermission:c}=Tw(),l=c(`infrastructure:read`),u=e?`default`:n,{data:d}=Vy(),f=d&&By(d),p=[Vxi];a.skills&&o&&p.push(Wxi),s&&p.push(Hxi),p.push(Uxi);let m=(0,K.jsx)(t,{href:`/agents`,"aria-label":`Back to Mastra Studio`,children:(0,K.jsx)(cZ,{className:`size-6`})});return(0,K.jsxs)(z2,{className:`h-full`,mobileMode:`drawer`,children:[!e&&(0,K.jsxs)(z2.Header,{collapsedLogo:m,actions:f&&(0,K.jsx)(C3n,{}),children:[(0,K.jsx)(t,{href:`/agents`,"aria-label":`Back to Mastra Studio`,className:`min-w-0 flex-1`,children:(0,K.jsx)(z2.Brand,{logo:(0,K.jsx)(cZ,{className:`size-6`}),title:`Mastra Studio`})}),!r&&(0,K.jsx)(z2.Trigger,{})]}),(0,K.jsx)(Bbi,{}),(0,K.jsx)(z2.Nav,{children:(0,K.jsx)(z2.NavSection,{children:(0,K.jsx)(z2.NavList,{children:p.map(e=>{let n=i.startsWith(e.url);return(0,K.jsx)(z2.NavLink,{LinkComponent:t,state:u,link:e,isActive:n},e.name)})})})}),!e&&(0,K.jsx)(z2.Footer,{children:l&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(z2.NavSeparator,{}),(0,K.jsx)(z2.NavSection,{children:(0,K.jsx)(z2.NavList,{children:(0,K.jsx)(z2.NavLink,{LinkComponent:t,state:u,link:Gxi,isActive:i.startsWith(Gxi.url)})})})]})})]})}var X9=()=>(0,K.jsx)(`div`,{className:`h-screen bg-sidebar`,children:(0,K.jsxs)(fkr,{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)(Kxi,{})}),(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)(qb,{})})})]}),(0,K.jsx)(Bxi,{})]})}),qxi=()=>(0,K.jsx)(`div`,{className:`grid h-screen grid-cols-[minmax(0,1fr)] grid-rows-1 bg-sidebar`,children:(0,K.jsx)(qb,{})}),Jxi=({agentId:e})=>{let{data:t,isLoading:n}=LP();return n?(0,K.jsx)(`div`,{className:`space-y-2`,children:(0,K.jsx)(Yw,{className:`h-9 w-full`})}):!t||t.length===0?(0,K.jsx)(U,{variant:`caption`,tone:`ink`,children:`No channel platforms configured.`}):(0,K.jsx)(`ul`,{className:`divide-y divide-border`,children:t.map(t=>(0,K.jsx)(Yxi,{platform:t,agentId:e},t.id))})};function Yxi({platform:e,agentId:t}){let{data:n,isLoading:r}=tNt({platform:e.id,agentId:t,queryOptions:{enabled:!!(e.id&&t)}}),{connect:i,isConnecting:a}=OX(e.id),{mutate:o,isPending:s}=iNt({platform:e.id}),c=n?.find(e=>e.status===`active`),l=n?.some(e=>e.status===`pending`)??!1;return S$n({platform:e.id,agentId:t,hasPendingInstall:l}),(0,K.jsxs)(`li`,{className:`flex items-center gap-3 py-2.5`,children:[(0,K.jsx)(DX,{platform:e.id,className:`h-5 w-5 shrink-0`}),(0,K.jsxs)(`span`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,K.jsx)(U,{as:`span`,variant:`body`,tone:`ink`,className:`truncate`,children:e.name}),c?(0,K.jsx)(U,{variant:`meta`,tone:`muted`,className:`truncate`,children:c.displayName||`Workspace`}):null]}),r?null:c?(0,K.jsx)(hT,{variant:`success`,size:`sm`,indicator:`dot`,children:`Connected`}):e.isConfigured?null:(0,K.jsx)(hT,{variant:`warning`,size:`sm`,indicator:`dot`,children:`Not configured`}),r?null:c?(0,K.jsx)(X,{icon:(0,K.jsx)(Dc,{}),size:`sm`,variant:`ghost`,onClick:()=>{o(t,{onError:e=>{yw.error(e.body?.error||e.message||`Failed to disconnect channel`)}})},disabled:s,className:`shrink-0`,children:s?`Removing...`:`Remove`}):e.isConfigured?(0,K.jsx)(X,{icon:(0,K.jsx)(qo,{}),size:`sm`,variant:`default`,onClick:()=>{i(t)},disabled:a,children:a?`Connecting...`:`Connect`}):null]})}var Xxi=({modelList:e,updateModelInModelList:t,reorderModelList:n,editable:r=!0})=>{let[i,a]=(0,G.useState)(()=>e),o=i.length>1,s=i.filter(e=>e.enabled!==!1).length;(0,G.useEffect)(()=>{a(e)},[e]);let c=async e=>{if(!e.destination)return;let t=Array.from(i),[r]=t.splice(e.source.index,1);t.splice(e.destination.index,0,r),a(t);try{await n({reorderedModelIds:t.map(e=>e.id)})}catch{a(i)}},l=async e=>{let n=i;a(t=>t.map(t=>t.id===e.modelConfigId?{...t,enabled:e.enabled??t.enabled,maxRetries:e.maxRetries??t.maxRetries,model:{modelId:e.model?.modelId??t.model.modelId,provider:e.model?.provider??t.model.provider,modelVersion:t.model.modelVersion}}:t));try{return await t(e)}catch(e){throw a(n),e}};return r?(0,K.jsx)(GI,{onDragEnd:c,children:(0,K.jsx)(YI,{droppableId:`model-list`,children:e=>(0,K.jsxs)(`div`,{...e.droppableProps,ref:e.innerRef,className:`flex flex-col gap-2`,children:[i.map((e,t)=>(0,K.jsx)(qI,{draggableId:e.id,index:t,children:t=>(0,K.jsx)(`div`,{ref:t.innerRef,...t.draggableProps,style:t.draggableProps.style,children:(0,K.jsx)(Qxi,{modelConfig:e,updateModelInModelList:l,showDragHandle:o,dragHandleProps:t.dragHandleProps,isLastEnabled:e.enabled!==!1&&s===1})})},e.id)),e.placeholder]})})}):(0,K.jsx)(Zxi,{modelList:e})},Zxi=({modelList:e})=>(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,K.jsx)(U,{variant:`caption`,tone:`muted`,children:`This model list is dynamically set and cannot be edited in Studio.`}),e.map(e=>(0,K.jsxs)(`div`,{className:`flex items-center gap-2 rounded-lg bg-sidebar p-2`,children:[(0,K.jsxs)(U,{as:`span`,variant:`caption`,tone:`ink`,className:`min-w-0 flex-1 truncate`,children:[e.model.provider,`/`,e.model.modelId]}),(0,K.jsx)(U,{as:`span`,variant:`meta`,tone:`muted`,className:`shrink-0`,children:e.enabled===!1?`Disabled`:`Enabled`})]},e.id))]}),Qxi=({modelConfig:e,updateModelInModelList:t,showDragHandle:n,dragHandleProps:r,isLastEnabled:i})=>(0,K.jsx)(`div`,{className:`state-layer rounded-lg bg-sidebar`,children:(0,K.jsxs)(`div`,{className:`flex items-center gap-2 p-2`,children:[n&&(0,K.jsx)(`div`,{...r,className:`shrink-0 cursor-grab text-muted-foreground active:cursor-grabbing`,children:(0,K.jsx)(QC,{children:(0,K.jsx)(Ui,{})})}),(0,K.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,K.jsx)(lvi,{defaultProvider:e.model.provider,defaultModel:e.model.modelId,updateModel:n=>t({modelConfigId:e.id,model:n}),autoSave:!0})}),i?(0,K.jsx)(qC,{children:(0,K.jsxs)(JC,{children:[(0,K.jsx)(YC,{asChild:!0,children:(0,K.jsx)(`span`,{className:`shrink-0`,children:(0,K.jsx)(FA,{checked:e.enabled,disabled:!0,className:`pointer-events-none`})})}),(0,K.jsx)(XC,{children:(0,K.jsx)(`p`,{children:`At least one model must be enabled`})})]})}):(0,K.jsx)(FA,{checked:e.enabled,onCheckedChange:n=>{t({modelConfigId:e.id,enabled:n}).catch(()=>void 0)},className:`shrink-0`})]})}),Z9=em([q(),Kp()]).optional().catch(`Unavailable`),$xi=J({scope:Z9,topK:Z9,messageRange:em([J({before:Z9,after:Z9}),Z9])});function eSi(e){if(typeof e==`string`)return e;let t=typeof e==`object`?e.before:e,n=typeof e==`object`?e.after:e;return`${t??1} before, ${n??1} after`}function tSi(e){return e===void 0?`Default`:typeof e==`number`?`${e.toLocaleString()} tokens`:`${e.min.toLocaleString()}–${e.max.toLocaleString()} tokens`}function nSi(e){let t=[{title:`General`,items:[{label:`Status`,value:!0},{label:`Last Messages`,value:e.lastMessages??`Default`},{label:`Auto-generate Titles`,value:`generateTitle`in e&&!!e.generateTitle}]}];if(e.semanticRecall){let n=$xi.safeParse(e.semanticRecall===!0?{}:e.semanticRecall);n.success?t.push({title:`Semantic Recall`,items:[{label:`Status`,value:!0},{label:`Scope`,value:n.data.scope??`resource`},{label:`Top K Results`,value:n.data.topK??4},{label:`Message Range`,value:eSi(n.data.messageRange)}]}):t.push({title:`Semantic Recall`,items:[{label:`Configuration`,value:`Unavailable`}]})}let n=e.observationalMemory;return n?.enabled&&t.push({title:`Observational Memory`,items:[{label:`Status`,value:!0},{label:`Scope`,value:n.scope??`thread`},{label:`Message Tokens`,value:tSi(n.messageTokens)},{label:`Observation Tokens`,value:tSi(n.observationTokens)},...n.observationModel?[{label:`Observation Model`,value:n.observationModel}]:[],...n.reflectionModel?[{label:`Reflection Model`,value:n.reflectionModel}]:[]]}),t}function rSi(e){return typeof e==`boolean`?e?`Enabled`:`Disabled`:e}function iSi({items:e}){return(0,K.jsx)(dvi,{className:`grid-cols-2`,data:e.map(e=>({key:e.label,label:(0,K.jsx)(U,{as:`span`,variant:`body-sm`,children:e.label}),value:(0,K.jsx)(hT,{variant:e.value===!0?`success`:`neutral`,indicator:typeof e.value==`boolean`?`dot`:void 0,className:`h-auto min-h-5 min-w-0 break-words whitespace-normal`,children:rSi(e.value)})}))})}function aSi({agentId:e}){let{data:t,isLoading:n,isError:r,isFetching:i,refetch:a}=sZ({agentId:e,requestContext:Qw(`agent`,e)[0],queryOptions:{enabled:!!e}});return n?(0,K.jsx)(Yw,{className:`h-28 w-full`}):r&&!t?(0,K.jsxs)(`div`,{role:`alert`,className:`flex flex-col items-start gap-2`,children:[(0,K.jsx)(U,{variant:`caption`,tone:`muted`,children:`Unable to load memory configuration`}),(0,K.jsx)(X,{size:`sm`,disabled:i,onClick:()=>void a(),children:`Retry`})]}):t?.config?(0,K.jsx)(`div`,{className:`flex flex-col gap-3`,children:nSi(t.config).map(e=>e.title===`General`?(0,K.jsx)(iSi,{items:e.items},e.title):(0,K.jsxs)(iT,{defaultOpen:e.title!==`Observational Memory`,children:[(0,K.jsxs)(aT,{className:`flex w-full items-center justify-between gap-2`,children:[(0,K.jsx)(U,{as:`span`,variant:`body-sm`,children:e.title}),(0,K.jsx)(rt,{direction:`right`,className:`size-4`})]}),(0,K.jsx)(oT,{className:`pt-2`,children:(0,K.jsx)(iSi,{items:e.items})})]},e.title))}):(0,K.jsx)(U,{variant:`caption`,tone:`muted`,children:`No memory configuration available`})}function oSi(e){let t=e.split(`
|
|
698
698
|
`),n=t.filter(e=>e.trim().length>0),r=n[0];if(r===void 0)return e;let i=r.match(/^[\t ]*/)?.[0]??``;for(let t of n){for(;!t.startsWith(i);)i=i.slice(0,-1);if(i.length===0)return e}return t.map(e=>e.startsWith(i)?e.slice(i.length):e).join(`
|