@mastra/deployer-cloud 1.83.0-alpha.10 → 1.83.0-alpha.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -721,6 +721,6 @@ window.parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/sandbox-proxy-
|
|
|
721
721
|
]`,qhi=[{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 Jhi(){let{isCopied:e,handleCopy:t}=Aw({text:Khi,showToast:!1});return(0,K.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,K.jsx)(T,{variant:`column`,tone:`ink`,className:`flex h-8 items-center`,children:`Each item looks like this`}),(0,K.jsx)(`dl`,{className:`divide-y divide-border rounded-lg border border-border`,children:qhi.map(e=>(0,K.jsxs)(`div`,{className:`grid grid-cols-[7rem_1fr] gap-3 px-3 py-2.5`,children:[(0,K.jsx)(`dt`,{className:H({tone:`ink`,variant:`meta`}),children:(0,K.jsx)(uZ,{children:e.name})}),(0,K.jsxs)(`dd`,{className:`flex flex-col items-start gap-1.5 text-muted-foreground`,children:[(0,K.jsx)(T,{as:`span`,variant:`meta`,children:e.description}),e.required?(0,K.jsx)(bw,{variant:`success`,size:`xs`,children:`required`}):(0,K.jsx)(bw,{variant:`neutral`,emphasis:`subtle`,size:`xs`,children:`optional`})]})]},e.name))}),(0,K.jsxs)(`div`,{className:`overflow-hidden rounded-lg border border-border`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between border-b border-border bg-card py-1.5 pr-1.5 pl-3`,children:[(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,font:`mono`,children:`example.json`}),(0,K.jsx)(X,{icon:e?(0,K.jsx)(Bn,{}):(0,K.jsx)(xr,{}),variant:`ghost`,size:`sm`,onClick:t,children:e?`Copied`:`Copy`})]}),(0,K.jsx)(FT,{variant:`embedded`,language:`json`,editable:!1,lineNumbers:!1,showCopyButton:!1,value:Khi,className:`p-3`})]}),(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:Ghi,target:`_blank`,rel:`noopener noreferrer`}),className:`self-start`,icon:(0,K.jsx)(Br,{}),children:`Datasets documentation`})]})}var Yhi=10,Xhi=`[
|
|
722
722
|
{ "input": "…", "groundTruth": "…" }
|
|
723
723
|
]`,Zhi=`flex min-h-0 flex-1 flex-col py-0`;function Qhi({tab:e,onTabChange:t,file:n,onFileSelect:r,onReplace:i,pastedText:a,onPastedTextChange:o,validation:s,isImporting:c}){return(0,K.jsxs)(CA,{value:e,defaultTab:`upload`,onValueChange:t,className:`flex h-full flex-col gap-3`,children:[(0,K.jsxs)(SA,{variant:`pill`,children:[(0,K.jsx)(wA,{value:`upload`,children:`Upload file`}),(0,K.jsx)(wA,{value:`paste`,children:`Paste JSON`})]}),(0,K.jsx)(TA,{value:`upload`,className:Zhi,children:n?(0,K.jsx)(ngi,{file:n,validation:s,onReplace:i,isImporting:c}):(0,K.jsx)($hi,{onFileSelect:r,disabled:c})}),(0,K.jsx)(TA,{value:`paste`,className:Zhi,children:(0,K.jsx)(FT,{"aria-label":`JSON items`,language:`json`,lineNumbers:!1,showCopyButton:!1,placeholder:Xhi,value:a,onChange:o,editable:!c,className:`min-h-50 flex-1`})})]})}function $hi({onFileSelect:e,disabled:t}){let[n,r]=(0,G.useState)(!1),i=(0,G.useCallback)(t=>{let n=t.target.files?.[0];n&&e(n),t.target.value=``},[e]),a=(0,G.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),r(!0)},[]),o=(0,G.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),r(!1)},[]),s=(0,G.useCallback)(n=>{if(n.preventDefault(),n.stopPropagation(),r(!1),t)return;let i=n.dataTransfer.files?.[0];i&&e(i)},[t,e]);return(0,K.jsxs)(`div`,{"data-testid":`json-dropzone`,onDragOver:a,onDragLeave:o,onDrop:s,className:m(`relative flex flex-1 flex-col items-center justify-center gap-3 rounded-lg border border-dashed border-border bg-card px-4 py-6 text-center`,`hover:border-success-edge hover:bg-success-subtle`,n&&`border-success-edge bg-success-subtle`,t&&`cursor-wait opacity-60`),children:[(0,K.jsx)(`input`,{type:`file`,accept:`.json,application/json`,"aria-label":`Choose a JSON file`,onChange:i,disabled:t,className:`absolute inset-0 cursor-pointer opacity-0`}),(0,K.jsx)(`div`,{className:`flex size-9 items-center justify-center rounded-md border border-border bg-background text-muted-foreground`,children:(0,K.jsx)(Ac,{className:`size-4`})}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,K.jsx)(T,{tone:`ink`,children:`Drop a JSON file here`}),(0,K.jsxs)(T,{variant:`caption`,tone:`muted`,children:[`or `,(0,K.jsx)(`span`,{className:`underline`,children:`choose a file`}),` from your computer`]})]}),(0,K.jsxs)(T,{variant:`meta`,tone:`muted`,children:[`.json files containing an array of items, up to `,lpi]})]})}function egi(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`}function tgi(e){return typeof e==`string`?e:JSON.stringify(e)??``}function ngi({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,Yhi);return(0,K.jsxs)(`div`,{"data-testid":`json-file-card`,className:`rounded-lg border border-border`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2`,children:[(0,K.jsx)(qr,{className:`size-4 shrink-0 text-muted-foreground`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`ink`,font:`mono`,className:`min-w-0 flex-1 truncate`,children:e.name}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`shrink-0`,children:egi(e.size)}),(0,K.jsx)(X,{icon:(0,K.jsx)(Qo,{}),variant:`ghost`,size:`sm`,onClick:n,disabled:r,children:`Replace`})]}),o.map(e=>(0,K.jsxs)(`div`,{className:`grid grid-cols-[2rem_1fr_auto] items-center gap-2 border-t border-border px-3 py-1.5`,children:[(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:e.index}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`ink`,font:`mono`,className:`truncate`,children:tgi(e.input)}),e.hasInput?e.hasGroundTruth?null:(0,K.jsx)(bw,{variant:`warning`,size:`xs`,children:`no groundTruth`}):(0,K.jsx)(bw,{variant:`destructive`,size:`xs`,children:`no input`})]},e.index)),a>Yhi&&(0,K.jsxs)(T,{as:`p`,variant:`meta`,tone:`muted`,className:`border-t border-border px-3 py-1.5`,children:[`+ `,a-Yhi,` more`]})]})}var rgi=e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsText(e)});function igi({datasetId:e,datasetName:t,open:n,onOpenChange:r,onSuccess:i}){let[a,o]=(0,G.useState)(`upload`),[s,c]=(0,G.useState)(null),[l,u]=(0,G.useState)(``),[d,f]=(0,G.useState)(null),[p,m]=(0,G.useState)(``),[h,g]=(0,G.useState)(!1),_=(0,G.useRef)(0),v=(0,G.useRef)(void 0),y=(0,G.useRef)(!1),{batchInsertItems:b}=zP(),x=a===`upload`?l:p,S=(0,G.useMemo)(()=>a===`upload`&&d?{status:`error`,kind:`parse`,message:d}:fpi(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 ${lpi}`);else try{let n=await rgi(e);if(t!==_.current)return;c({name:e.name,size:e.size}),u(n),f(null)}catch{if(t!==_.current)return;f(`Could not read the file`)}},[]),w=(0,G.useCallback)(()=>{_.current++,c(null),u(``),f(null)},[]),T=(0,G.useCallback)(()=>{_.current++,o(`upload`),c(null),u(``),f(null),m(``)},[]),E=(0,G.useCallback)(()=>{clearTimeout(v.current),y.current&&(v.current=setTimeout(T,150))},[T]);(0,G.useEffect)(()=>(y.current=!0,()=>{y.current=!1,clearTimeout(v.current)}),[]);let D=(0,G.useCallback)(()=>{r(!1),E()},[r,E]),O=(0,G.useCallback)(async()=>{if(S.status===`ready`){g(!0);try{await b.mutateAsync({datasetId:e,items:S.items}),UC.success(`Imported ${S.total} item${S.total===1?``:`s`}`),i?.(),r(!1),E()}catch(e){UC.error(e instanceof Error?e.message:`Failed to import items`)}finally{g(!1)}}},[S,b,e,i,r,E]);return(0,K.jsx)(_E,{open:n,onOpenChange:D,pending:h,children:(0,K.jsxs)(vE,{size:`xl`,children:[(0,K.jsxs)(yE,{children:[(0,K.jsx)(SE,{children:`Import into dataset`}),(0,K.jsxs)(CE,{children:[`Add items to `,t?(0,K.jsx)(`span`,{className:`text-foreground`,children:t}):`this dataset`,` from a JSON file or paste them directly.`]})]}),(0,K.jsx)(xE,{flush:!0,children:(0,K.jsxs)(`div`,{className:`grid divide-y divide-border md:grid-cols-[1.15fr_1fr] md:divide-x md:divide-y-0`,children:[(0,K.jsx)(`div`,{className:`flex min-h-[360px] flex-col p-4`,children:(0,K.jsx)(Qhi,{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)(Jhi,{})})]})}),(0,K.jsxs)(bE,{children:[(0,K.jsx)(agi,{validation:S}),(0,K.jsx)(wE,{children:`Cancel`}),(0,K.jsxs)(gE,{onConfirm:O,disabled:S.status!==`ready`,children:[h&&(0,K.jsx)(Qc,{}),S.status===`ready`?`Import ${S.total} item${S.total===1?``:`s`}`:`Import`]})]})]})})}function agi({validation:e}){let t=m(`size-1.5 shrink-0 rounded-full`,e.status===`idle`&&`bg-muted-foreground`,e.status===`ready`&&`bg-success-indicator`,e.status===`error`&&`bg-destructive-indicator`),n;switch(e.status){case`idle`:n=`No items yet`;break;case`ready`:n=(0,K.jsxs)(Gw,{singleLine:!0,children:[(0,K.jsxs)(Gw.Item,{className:`shrink-0`,children:[(0,K.jsx)(T,{as:`b`,variant:`label`,tone:`ink`,children:e.total}),` `,`item`,e.total===1?``:`s`,` ready`]}),e.missingGroundTruthCount>0&&(0,K.jsxs)(Gw.Item,{children:[e.missingGroundTruthCount,` without groundTruth`]})]});break;case`error`:switch(e.kind){case`parse`:n=`Not valid JSON: ${e.message}`;break;case`not-array`:n=`Top level must be an array of items`;break;case`empty`:n=`The array has no items`;break;case`too-large`:n=`JSON is larger than ${lpi}`;break;case`missing-input`:n=(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`b`,variant:`label`,tone:`ink`,children:e.missingInputCount}),` `,`of `,e.total,` item`,e.total===1?``:`s`,` `,e.missingInputCount===1?`has`:`have`,` no`,` `,(0,K.jsx)(uZ,{children:`input`})]})}}return(0,K.jsxs)(`div`,{role:`status`,className:`mr-auto flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(`span`,{className:t}),(0,K.jsx)(T,{tone:`muted`,as:`span`,variant:`caption`,className:`truncate`,children:n})]})}function ogi(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 sgi({active:e,onPrevious:t,onNext:n,onClose:r}){(0,G.useEffect)(()=>{if(!e)return;let i=e=>{e.defaultPrevented||ogi(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 cgi=(0,G.createContext)(null);function lgi({datasetId:e,items:t,isLoadingItems:n,children:r}){let i=kb(),a=KWe(`/datasets/:datasetId/items/:itemId`)?.params.itemId,o=(0,G.useCallback)(t=>{i(`/datasets/${e}/items/${encodeURIComponent(t)}`)},[i,e]),s=(0,G.useCallback)(()=>{i(`/datasets/${e}`)},[i,e]),c=(0,G.useMemo)(()=>a?t.findIndex(e=>e.id===a):-1,[t,a]),l=(0,G.useMemo)(()=>{if(c<=0)return;let e=t[c-1].id;return()=>o(e)},[c,t,o]),u=(0,G.useMemo)(()=>{if(c<0||c>=t.length-1)return;let e=t[c+1].id;return()=>o(e)},[c,t,o]);sgi({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)(cgi.Provider,{value:d,children:r})}function ugi(){let e=(0,G.useContext)(cgi);if(!e)throw Error(`useDatasetItemPanel must be used within a DatasetItemPanelProvider`);return e}var dgi=[`createdAt`];function fgi({datasetId:e,onAddItemClick:t,onNavigateToDataset:n,toolbarActionsSlot:r}){let[i,a]=Hb(),{activeVersion:o}=GP(i,a),{sort:s,onSortChange:c}=l7({searchParams:i,setSearchParams:a,allowedKeys:dgi}),l=(0,G.useMemo)(()=>s?{field:s.key,direction:s.direction===`asc`?`ASC`:`DESC`}:void 0,[s]),[u,d]=(0,G.useState)(!1),[f,p]=(0,G.useState)(!1),[m,h]=(0,G.useState)(!1),[g,_]=(0,G.useState)([]),[v,y]=(0,G.useState)(!1),[b,x]=(0,G.useState)([]),[S,C]=(0,G.useState)(!1),[w,T]=(0,G.useState)([]),[E,D]=(0,G.useState)(0),[O,k]=(0,G.useState)(``),[A]=Ew(O,300),{data:j}=VP({datasetId:e,queryOptions:{enabled:!!e}}),{data:M=[],isLoading:N,setEndOfListElement:P,isFetchingNextPage:F,hasNextPage:I}=RP({datasetId:e,search:A||void 0,version:o,orderBy:l,queryOptions:{enabled:!!e}}),{deleteItems:L}=zP(),{currentItemId:R,openItem:z,close:B}=ugi();return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`grid h-full overflow-auto`,children:(0,K.jsx)(Whi,{items:M,toolbarActionsSlot:r,isLoading:N,onItemClick:e=>{R===e?B():z(e)},featuredItemId:R,onAddClick:t??(()=>{}),onImportClick:()=>d(!0),onImportJsonClick:()=>p(!0),onBulkDeleteClick:e=>{T(e),C(!0)},onCreateDatasetClick:e=>{_(e),h(!0)},onAddToDatasetClick:e=>{x(e),y(!0)},datasetName:j?.name,clearSelectionTrigger:E,setEndOfListElement:P,isFetchingNextPage:F,hasNextPage:I,searchQuery:O,activeSearchQuery:A,onSearchChange:k,sort:s,onSortChange:c,currentDatasetVersion:j?.version})}),(0,K.jsx)(Ihi,{datasetId:e,open:u,onOpenChange:d}),(0,K.jsx)(igi,{datasetId:e,datasetName:j?.name,open:f,onOpenChange:p}),(0,K.jsx)(xpi,{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)(Spi,{open:v,onOpenChange:e=>{y(e),e||(x([]),D(e=>e+1))},items:b,currentDatasetId:e}),(0,K.jsx)(aP,{open:S,onOpenChange:C,children:(0,K.jsxs)(aP.Content,{children:[(0,K.jsxs)(aP.Header,{children:[(0,K.jsx)(aP.Title,{children:`Delete Items`}),(0,K.jsxs)(aP.Description,{children:[`Are you sure you want to delete `,w.length,` item`,w.length===1?``:`s`,`? This action cannot be undone.`]})]}),(0,K.jsxs)(aP.Footer,{children:[(0,K.jsx)(aP.Cancel,{children:`Cancel`}),(0,K.jsx)(aP.Action,{onClick:async()=>{await L.mutateAsync({datasetId:e,itemIds:w}),UC.success(`Deleted ${w.length} items`),C(!1),T([]),D(e=>e+1)},children:L.isPending?`Deleting...`:`Delete`})]})]})})]})}var pgi=`__create_tag__`;function mgi({datasetId:e}){let{data:t}=VP({datasetId:e,queryOptions:{enabled:!!e}}),{data:n}=BP(),{updateDataset:r}=zP(),[i,a]=(0,G.useState)(``),o=(0,G.useMemo)(()=>Array.isArray(t?.tags)?t.tags:[],[t?.tags]),s=(0,G.useMemo)(()=>Sfi(n?.datasets??[]),[n?.datasets]),c=(0,G.useMemo)(()=>{let e=s.map(e=>({label:e,value:e,end:o.includes(e)?(0,K.jsx)(Bn,{"data-testid":`tag-applied`,className:`size-3.5`}):void 0})),t=i.trim();return t.length>0&&!s.includes(t)&&!o.includes(t)?[{label:`Create "${t}"`,value:pgi},...e]:e},[s,o,i]),l=t=>{r.mutate({datasetId:e,tags:t},{onError:()=>UC.error(`Failed to update tags`)})},u=e=>{let t=e===pgi?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)(wfi,{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)(Hc,{className:`size-3`})})]},e)),(0,K.jsx)(TP,{options:c,value:void 0,onValueChange:u,onInputValueChange:a,placeholder:`Add tag`,searchPlaceholder:`Search or create tag`,emptyText:`Type to create a tag`,variant:`ghost`,size:`sm`,className:`w-auto min-w-0`,disabled:r.isPending})]})}var P7=e=>JSON.stringify(e??null,null,2),hgi=e=>e==null||e===``||typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0,ggi=[{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=>hgi(e.groundTruth)?void 0:P7(e.groundTruth),payload:e=>hgi(e.groundTruth)?null:e.groundTruth},{key:`expectedTrajectory`,title:`Expected Trajectory`,icon:(0,K.jsx)(ls,{}),value:e=>e.expectedTrajectory==null?void 0:P7(e.expectedTrajectory)},{key:`toolMocks`,title:`Tool Mocks`,icon:(0,K.jsx)(Bc,{}),value:e=>e.toolMocks?.length?P7(e.toolMocks):void 0},{key:`requestContext`,title:`Request Context`,icon:(0,K.jsx)(Cn,{}),value:e=>e.requestContext==null?void 0:P7(e.requestContext)},{key:`metadata`,title:`Metadata`,icon:(0,K.jsx)(Qs,{}),value:e=>P7(e.metadata)}],_gi=e=>e.toFixed(2);function vgi({delta:e,format:t=_gi,higherIsBetter:n=!0,baseline:r}){let i=e===0?`text-muted-foreground`:(n?e>0:e<0)?`text-success-indicator`:`text-destructive-foreground`,a=e>0?`+`:e<0?`-`:``,o=`${a}${t(Math.abs(e))}`,s=r!==void 0&&r!==0&&Number.isFinite(r),c=(0,K.jsxs)(K.Fragment,{children:[a,s?`${(Math.abs(e)/Math.abs(r)*100).toFixed(1)}%`:t(Math.abs(e)),(0,K.jsx)(`span`,{"aria-hidden":!0,className:`inline-flex size-3.5 shrink-0 [&>svg]:size-3.5`,children:e>0?(0,K.jsx)(Jt,{}):e<0?(0,K.jsx)(At,{}):null})]}),l=m(`inline-flex items-center gap-1 tabular-nums`,i);return s?(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{render:(0,K.jsx)(`span`,{tabIndex:0,className:l}),children:c}),(0,K.jsx)(CC,{children:o})]}):(0,K.jsx)(`span`,{className:l,children:c})}function ygi({scorerId:e}){let{Link:t,paths:n}=_l();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 bgi({metrics:e}){if(e.length===0)return null;let t=e.some(e=>e.delta!=null);return(0,K.jsx)(`dl`,{className:m(`grid auto-rows-[minmax(1.5rem,auto)] items-center gap-x-4 gap-y-1`,t?`grid-cols-[minmax(0,1fr)_auto_auto]`:`grid-cols-[minmax(0,1fr)_auto]`),children:e.map(({id:e,icon:n,label:r,value:i,delta:a,formatDelta:o,rawValue:s,higherIsBetter:c,emphasis:l})=>(0,K.jsxs)(G.Fragment,{children:[(0,K.jsxs)(`dt`,{className:`flex min-w-0 items-center gap-1.5 text-body-sm text-muted-foreground [&>svg]:size-3.5 [&>svg]:shrink-0`,children:[n,r]}),(0,K.jsx)(`dd`,{className:m(`flex min-w-0 justify-end text-right text-foreground tabular-nums`,l?`text-heading font-semibold`:`text-body-sm`),children:i}),t&&(0,K.jsx)(`dd`,{className:`flex justify-end text-body-sm`,children:a!=null&&(0,K.jsx)(vgi,{delta:a,format:o,higherIsBetter:c,baseline:s==null?void 0:s-a})})]},e))})}function F7({value:e}){return(0,K.jsx)(`div`,{className:`min-w-0 p-3 text-foreground`,children:typeof e==`string`?(0,K.jsx)(xX,{children:e}):(0,K.jsx)(FT,{value:JSON.stringify(e??null,null,2),language:`json`,editable:!1,lineNumbers:!1,showCopyButton:!1,variant:`embedded`,"aria-label":`JSON payload`})})}var xgi=`grid content-start gap-5`;function I7({title:e,actions:t,tone:n=`default`,collapsible:r=!0,framed:i=!1,expanded:a,onExpandedChange:o,children:s}){let c=U$({collapsedHeight:160}),l=a===void 0||!o?c:{...c,isExpanded:a,setExpanded:o,toggleExpanded:()=>o(!a)},u=r?(0,K.jsx)(H$,{state:l,expandLabel:`Expand`,children:s}):s;return(0,K.jsxs)(`section`,{className:`grid min-w-0 gap-2`,children:[(0,K.jsxs)(`div`,{className:`flex h-7 items-center justify-between gap-2`,children:[(0,K.jsx)(m$.SectionHeading,{className:m(n===`negative`&&`text-destructive-foreground`),children:e}),(0,K.jsx)(`div`,{className:`ml-auto flex items-center gap-1`,children:t})]}),(0,K.jsxs)(`div`,{role:`region`,"aria-label":e,className:`min-w-0`,children:[i?n===`negative`?(0,K.jsx)(`div`,{className:`min-w-0 overflow-hidden rounded-lg border border-destructive-edge bg-destructive-subtle`,children:u}):(0,K.jsx)(dF,{className:`min-w-0 overflow-hidden`,children:u}):u,r&&l.isExpanded&&l.isClipped&&(0,K.jsx)(`div`,{className:`flex justify-center pt-1`,children:(0,K.jsx)(X,{size:`sm`,variant:`ghost`,icon:(0,K.jsx)(io,{}),onClick:()=>l.setExpanded(!1),children:`Collapse`})})]})]})}function Sgi({item:e,diff:t}){return(0,K.jsxs)(`div`,{className:xgi,children:[(0,K.jsx)(bgi,{metrics:Cgi(e)}),ggi.map(n=>{if(n.payload&&!t){let t=n.payload(e);return t==null?null:(0,K.jsx)(I7,{title:n.title,framed:!0,actions:(0,K.jsx)(jw,{content:typeof t==`string`?t:JSON.stringify(t,null,2)}),children:(0,K.jsx)(F7,{value:t})},n.key)}let r=n.value(e),i=t?n.value(t.against):void 0;return r===void 0&&i===void 0?null:r===void 0?(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,K.jsx)(m$.SectionHeading,{icon:n.icon,children:n.title}),(0,K.jsx)(T,{as:`p`,variant:`body`,tone:`muted`,children:`Not set in this version`})]},n.key):(0,K.jsx)(m$.CodeSection,{title:n.title,icon:n.icon,codeStr:r,diff:t?{against:i??``,side:t.side}:void 0},n.key)})]})}function Cgi(e){let t=e.updatedAt&&new Date(e.updatedAt).getTime()!==new Date(e.createdAt).getTime(),n=[{id:`item-id`,icon:(0,K.jsx)(ui,{}),label:`Item Id`,value:(0,K.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,K.jsx)(`span`,{className:`font-mono`,title:e.id,children:hU(e.id)}),(0,K.jsx)(jw,{content:e.id,tooltip:`Copy item ID to clipboard`,variant:`link`})]}),delta:null},{id:`created`,icon:(0,K.jsx)(Fn,{}),label:`Created`,value:Fw(e.createdAt,`date-time`),delta:null}];return t&&n.push({id:`updated`,icon:(0,K.jsx)(Nn,{}),label:`Updated`,value:Fw(e.updatedAt,`date-time`),delta:null}),n}function wgi({field:e,errors:t}){return t.length===0?null:(0,K.jsx)(gA,{children:(0,K.jsx)(`span`,{className:`space-y-1`,children:t.map(t=>(0,K.jsxs)(`span`,{className:`block`,children:[(0,K.jsxs)(`code`,{className:`rounded bg-destructive-subtle px-1`,children:[e,t.path===`/`?``:t.path]}),`: `,t.message]},`${t.path}:${t.message}`))})})}function Tgi({inputValue:e,setInputValue:t,groundTruthValue:n,setGroundTruthValue:r,metadataValue:i,setMetadataValue:a,trajectoryValue:o,setTrajectoryValue:s,toolMocksValue:c,setToolMocksValue:l,requestContextValue:u,setRequestContextValue:d,validationErrors:f,onSave:p,onCancel:m,isSaving:h}){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`mb-4`,children:(0,K.jsxs)(T,{as:`h3`,variant:`heading`,className:`flex items-center gap-2`,children:[(0,K.jsx)(Ro,{className:`h-5 w-5`}),` Edit Item`]})}),(0,K.jsxs)(`div`,{className:`space-y-6`,children:[(0,K.jsxs)(fA,{invalid:f?.field===`input`,children:[(0,K.jsx)(mA,{required:!0,children:`Input (JSON)`}),(0,K.jsx)(FT,{value:e,onChange:t,showCopyButton:!1,className:`min-h-[120px]`}),f?.field===`input`&&(0,K.jsx)(wgi,{field:`input`,errors:f.errors})]}),(0,K.jsxs)(fA,{invalid:f?.field===`groundTruth`,children:[(0,K.jsx)(mA,{children:`Ground Truth (JSON, optional)`}),(0,K.jsx)(FT,{value:n,onChange:r,showCopyButton:!1,className:`min-h-[100px]`}),f?.field===`groundTruth`&&(0,K.jsx)(wgi,{field:`groundTruth`,errors:f.errors})]}),(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{children:`Expected Trajectory (JSON, optional)`}),(0,K.jsx)(FT,{value:o,onChange:s,showCopyButton:!1,className:`min-h-[80px]`})]}),(0,K.jsxs)(fA,{invalid:f?.field===`toolMocks`,children:[(0,K.jsx)(mA,{children:`Tool Mocks (JSON array, optional)`}),(0,K.jsxs)(hA,{children:[`Ordered static mocks served in place of executing the tool. Each entry is`,` `,(0,K.jsx)(`code`,{children:`{ "toolName", "args", "output" }`}),`. Calling a mocked tool with non-matching args fails the item; unmocked tools run live.`]}),(0,K.jsx)(FT,{value:c,onChange:l,showCopyButton:!1,className:`min-h-[100px]`}),f?.field===`toolMocks`&&(0,K.jsx)(wgi,{field:`toolMocks`,errors:f.errors})]}),(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{children:`Request Context (JSON, optional)`}),(0,K.jsx)(FT,{value:u,onChange:d,showCopyButton:!1,className:`min-h-[80px]`})]}),(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{children:`Metadata (JSON, optional)`}),(0,K.jsx)(FT,{value:i,onChange:a,showCopyButton:!1,className:`min-h-[80px]`})]}),(0,K.jsxs)(`div`,{className:`flex gap-2 pt-4`,children:[(0,K.jsx)(X,{icon:(0,K.jsx)(Bn,{}),variant:`primary`,onClick:p,disabled:h,children:h?`Saving...`:`Save changes`}),(0,K.jsx)(X,{icon:(0,K.jsx)(Hc,{}),onClick:m,disabled:h,children:`Cancel`})]})]})]})}function Egi(){return(0,K.jsxs)(Uw,{className:`inline-flex h-control-md w-fit cursor-pointer items-center gap-1.5 rounded-sm text-label text-muted-foreground focus-visible:outline-offset-2`,children:[(0,K.jsx)(y,{direction:`right`,className:`-mr-0.5 -ml-[4.3px] size-icon-md in-aria-expanded:translate-x-[2px]`}),`Advanced`]})}function Dgi({provider:e,modelId:t,canReset:n,onProviderChange:r,onModelIdChange:i,onReset:a,container:o}){let s=GC(),{isLoading:c}=FJ(),[l,u]=(0,G.useState)(!1);return s.active&&s.pickerVisible===!1?(0,K.jsxs)(_A,{className:`gap-2`,children:[(0,K.jsx)(vA,{children:`Model`}),(0,K.jsx)(`div`,{children:(0,K.jsx)(bw,{icon:(0,K.jsx)(ja,{}),children:`Locked by admin`})})]}):(0,K.jsxs)(_A,{className:`gap-2`,children:[(0,K.jsx)(vA,{children:`Model`}),c?(0,K.jsx)(dw,{className:`h-control-md w-60 rounded-full`}):(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsxs)(fU,{className:`min-w-0`,children:[(0,K.jsx)(LJ,{value:e,onValueChange:e=>{r(e),u(!0)},container:o,"aria-label":`Model provider`,className:`w-auto min-w-0 shrink-0 gap-1 px-3`}),(0,K.jsx)(RJ,{llmId:e,value:t,onValueChange:i,open:l,onOpenChange:u,container:o,disabled:!e,"aria-label":`Model`,className:`w-auto min-w-0 gap-1 px-3`})]}),n&&(0,K.jsx)(X,{variant:`ghost`,size:`icon-md`,tooltip:`Use the agent's model`,onClick:a,children:(0,K.jsx)(ss,{})})]})]})}var Ogi=(e,t)=>`${e}:${t}`,kgi=(e,t)=>e?.value===t?.value;function Agi({datasets:e,datasetId:t,version:n,onDatasetChange:r,container:i}){let{total:a}=RP({datasetId:t,search:void 0,version:n,queryOptions:{enabled:!!t}}),o=e.find(e=>e.value===t)??null;return(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{required:!0,info:`The items to run. Each item's input goes to the target. Runs on the latest version unless you pick one under Advanced.`,children:`Dataset`}),(0,K.jsxs)(bP,{items:e,value:o,onValueChange:e=>e&&r(e.value),isItemEqualToValue:kgi,autoHighlight:!0,children:[(0,K.jsx)(BPt,{placeholder:`Select a dataset`,children:a!==void 0&&(0,K.jsxs)(Gw,{children:[(0,K.jsxs)(Gw.Item,{children:[a,` `,a===1?`item`:`items`]}),(0,K.jsx)(Gw.Item,{children:n===void 0?`latest`:`v${n}`})]})}),(0,K.jsxs)(xP,{container:i,children:[(0,K.jsx)(wP,{children:`No datasets found`}),(0,K.jsx)(SP,{children:e=>(0,K.jsx)(CP,{value:e,children:e.label},e.value)})]})]})]})}function jgi(e,t){return t!==void 0||(e??1)>1}function Mgi({datasetId:e,version:t,onVersionChange:n,container:r}){let{data:i}=VP({datasetId:e,queryOptions:{enabled:!!e}});return jgi(i?.version,t)?(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{children:`Dataset version`}),(0,K.jsx)(jIt,{datasetId:e,value:t??null,onValueChange:e=>n(e??void 0),container:r})]}):null}function Ngi({description:e,onDescriptionChange:t,disabled:n}){return(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{children:`Description`}),(0,K.jsx)(ZA,{value:e,onChange:e=>t(e.target.value),placeholder:`Optional`,rows:2,disabled:n})]})}function Pgi({name:e,defaultName:t,onNameChange:n,disabled:r}){return(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{children:`Experiment name`}),(0,K.jsx)(ZM,{value:e,placeholder:t,onChange:e=>n(e.target.value),disabled:r})]})}function Fgi(e){try{return Kk(e)}catch(e){console.error(`Failed to parse requestContextSchema:`,e);return}}function Igi({requestContextSchema:e,onChange:t}){let[n]=(0,G.useState)(()=>Fgi(e));return n?(0,K.jsxs)(_A,{children:[(0,K.jsx)(vA,{children:`Request context`}),(0,K.jsx)(nP,{schema:n,onValuesChange:t,className:`[&_button[type=submit]]:hidden`})]}):(0,K.jsx)(`div`,{role:`alert`,children:(0,K.jsx)(EA,{variant:`destructive`,children:`Failed to parse request context schema`})})}function Lgi({schema:e,raw:t,onRawChange:n,onValuesChange:r}){return e?(0,K.jsx)(Igi,{requestContextSchema:e,onChange:r}):(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{children:`Request context (JSON)`}),(0,K.jsx)(FT,{value:t,onChange:n,showCopyButton:!1,"aria-label":`Request context JSON`,className:`min-h-[120px]`})]})}function Rgi({onRun:e,canRun:t,isRunning:n}){return(0,K.jsx)(gE,{onConfirm:e,disabled:!t,children:(0,K.jsx)(zgi,{isRunning:n})})}function zgi({isRunning:e}){return e?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Qc,{className:`h-4 w-4`}),`Starting…`]}):`Run experiment`}function Bgi({scorer:e}){let t=(0,K.jsx)(CP,{value:e,children:e.label});return e.description?(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{render:t}),(0,K.jsx)(CC,{side:`right`,className:`max-w-64`,children:e.description})]}):t}function Vgi(){let{data:e}=eF();return Object.entries(e??{}).filter(([,e])=>e.isRegistered).map(([e,t])=>({value:e,label:t.scorer?.config?.name||e,description:t.scorer?.config?.description||void 0}))}function Hgi(e,t){return e.map(e=>t.find(t=>t.value===e)??{value:e,label:e})}function Ugi({scorerIds:e,usesDefaultScorers:t,onScorerIdsChange:n,container:r}){let i=Vgi();return(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{info:`Grade each output automatically. Outputs are saved either way, so you can always review them yourself.`,children:`Scorers`}),(0,K.jsxs)(bP,{multiple:!0,items:i,value:Hgi(e,i),onValueChange:e=>n(e.map(e=>e.value)),isItemEqualToValue:kgi,autoHighlight:!0,children:[(0,K.jsx)(qPt,{children:(0,K.jsx)(IPt,{children:e=>(0,K.jsxs)(K.Fragment,{children:[e.map(e=>(0,K.jsx)(JPt,{children:e.label},e.value)),(0,K.jsx)(YPt,{placeholder:e.length===0?`No scoring, read the outputs yourself`:void 0})]})})}),(0,K.jsxs)(xP,{container:r,children:[(0,K.jsx)(wP,{children:`No scorers registered`}),(0,K.jsx)(SP,{children:e=>(0,K.jsx)(Bgi,{scorer:e},e.value)})]})]}),t&&(0,K.jsx)(hA,{children:`The dataset's default scorers.`})]})}var Wgi=[{type:`agent`,label:`Agents`},{type:`workflow`,label:`Workflows`},{type:`scorer`,label:`Scorers`}];function Ggi(e){return Wgi.map(t=>({value:t.label,items:e.filter(e=>e.type===t.type)})).filter(e=>e.items.length>0)}function Kgi({options:e,isLoading:t,target:n,onTargetValueChange:r,container:i,className:a}){return(0,K.jsxs)(fA,{className:a,children:[(0,K.jsx)(mA,{required:!0,info:`What runs on each item: an agent, a workflow, or a scorer you want to test.`,children:`Target`}),(0,K.jsxs)(bP,{items:Ggi(e),value:n??null,onValueChange:e=>r(e?.value??``),isItemEqualToValue:kgi,disabled:t,autoHighlight:!0,children:[(0,K.jsx)(BPt,{placeholder:`Pick an agent, workflow or scorer`}),(0,K.jsxs)(xP,{container:i,children:[(0,K.jsx)(wP,{children:`Nothing to run`}),(0,K.jsx)(SP,{children:(e,t)=>(0,K.jsxs)(UPt,{items:e.items,children:[t>0?(0,K.jsx)(KPt,{}):null,(0,K.jsx)(WPt,{children:e.value}),(0,K.jsx)(GPt,{children:e=>(0,K.jsx)(CP,{value:e,children:e.label},e.value)})]},e.value)})]})]})]})}var qgi=(e,t)=>e.provider===t?.provider&&e.modelId===t?.modelId;function Jgi(e){let[t,n]=(0,G.useState)(null),r=t??e??{provider:``,modelId:``},i=t?.provider&&t.modelId&&!qgi(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&&!qgi(t,e),agentModel:i}}function Ygi(e,t){return e||(t[0]?.value??``)}function Xgi({initialDatasetId:e,initialDatasetVersion:t}){let{data:n}=BP(),r=(n?.datasets??[]).map(e=>({value:e.id,label:e.name})),[i,a]=(0,G.useState)(e??``),[o,s]=(0,G.useState)(t);return{datasets:r,datasetId:Ygi(i,r),version:o,setVersion:s,selectDataset:e=>{a(e),s(void 0)}}}function Zgi({initialName:e,targetLabel:t}){let[n,r]=(0,G.useState)(e??``),[i]=(0,G.useState)(Aui),a=jui(t??`experiment`,i);return{name:n,setName:r,defaultName:a,runName:n.trim()||a}}var Qgi=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function $gi(e){if(Qgi(e)&&Object.keys(e).length!==0)return e}function e_i(e){try{return{ok:!0,value:JSON.parse(e)}}catch{return{ok:!1}}}function t_i(e){if(!e.trim())return{ok:!0};let t=e_i(e);return t.ok?Qgi(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 n_i(e){let t=Object.entries(e).filter(([,e])=>e!==void 0&&e!==``);return t.length===0?{ok:!0}:{ok:!0,requestContext:Object.fromEntries(t)}}function r_i(e){let{data:t}=VP({datasetId:e,queryOptions:{enabled:!!e}}),[n,r]=(0,G.useState)(``),[i,a]=(0,G.useState)({}),o=$gi(t?.requestContextSchema);return{schema:o,raw:n,setRaw:r,setValues:a,resetValues:()=>a({}),resolve:()=>o?n_i(i):t_i(n)}}function i_i({datasetId:e,initialScorerIds:t}){let{data:n}=VP({datasetId:e,queryOptions:{enabled:!!e}}),[r,i]=(0,G.useState)(t),a=n?.scorerIds??[];return{scorerIds:r??a,usesDefaultScorers:r===void 0&&a.length>0,setScorerIds:i,resetScorers:()=>i(void 0)}}var a_i=(e,t,n,r)=>({value:Ogi(e,t),label:n,type:e,id:t,defaultModel:r});function o_i(e,t){if(e&&t)return{provider:Lq(e),modelId:t}}function s_i(){let{data:e,isLoading:t}=PP(),{data:n,isLoading:r}=sP({}),{data:i,isLoading:a}=eF();return{options:[...Object.entries(e??{}).map(([e,t])=>a_i(`agent`,e,t.name||e,o_i(t.provider,t.modelId))),...Object.entries(n??{}).map(([e,t])=>a_i(`workflow`,e,t.name||e)),...Object.entries(i??{}).map(([e,t])=>a_i(`scorer`,e,t.scorer?.config?.name||e))],isLoading:t||r||a}}function c_i({initialTargetType:e,initialTargetId:t}){return!e||!t?``:Ogi(e,t)}function l_i(e,t,{initialTargetType:n,initialTargetId:r}){let i=e.find(e=>e.value===t);if(i)return i;if(n&&r&&t)return{value:t,label:r,type:n,id:r}}function u_i(e){let{options:t,isLoading:n}=s_i(),[r,i]=(0,G.useState)(()=>c_i(e));return{options:t,isLoading:n,target:l_i(t,r,e),setTargetValue:i}}var d_i=e=>(e.metaKey||e.ctrlKey)&&e.key===`Enter`,f_i=e=>e.trim()||void 0,p_i=e=>e.length>0?e:void 0;function m_i({open:e,onOpenChange:t,onOpenChangeComplete:n,onSuccess:r,initialDatasetId:i,initialDatasetVersion:a,initialScorerIds:o,initialTargetType:s,initialTargetId:c,initialName:l,initialDescription:u}){let d=(0,G.useRef)(null),f=u_i({initialTargetType:s,initialTargetId:c}),p=Xgi({initialDatasetId:i,initialDatasetVersion:a}),m=i_i({datasetId:p.datasetId,initialScorerIds:o}),h=r_i(p.datasetId),{target:g}=f,_=Jgi(g?.defaultModel),v=g?.type===`agent`,y=v?_.agentModel:void 0,b=Zgi({initialName:l,targetLabel:y&&g?`${g.label} ${y.modelId}`:g?.label}),[x,S]=(0,G.useState)(u??``),[C,w]=(0,G.useState)(!1),{triggerExperiment:T}=zP(),{datasetId:E}=p,D=T.isPending,O=h.schema?E:void 0,k=!!(E&&g)&&!f.isLoading&&!D,A=e=>{f.setTargetValue(e),_.reset()},j=e=>{p.selectDataset(e),m.resetScorers(),h.resetValues()},M=async()=>{if(!k||!g)return;let e=h.resolve();if(!e.ok)BC.error(e.message);else try{let n=await T.mutateAsync({datasetId:E,name:b.runName,description:f_i(x),targetType:g.type,targetId:g.id,agentModel:y,scorerIds:p_i(m.scorerIds),version:p.version,requestContext:e.requestContext});BC.success(`Experiment started`),t(!1),r?.(n.experimentId)}catch(e){BC.error(e instanceof Error?e.message:`Failed to start experiment`)}};return(0,K.jsx)(_E,{open:e,onOpenChange:t,onOpenChangeComplete:n,pending:D,children:(0,K.jsxs)(vE,{ref:d,size:`lg`,onKeyDown:e=>{d_i(e)&&k&&(e.preventDefault(),M())},children:[(0,K.jsxs)(yE,{children:[(0,K.jsx)(SE,{children:`New experiment`}),(0,K.jsx)(CE,{children:`Run every item in a dataset through an agent, workflow or scorer.`})]}),(0,K.jsx)(xE,{children:(0,K.jsxs)(Hw,{open:C,onOpenChange:w,className:`py-3`,children:[(0,K.jsxs)(`div`,{className:`space-y-6`,children:[(0,K.jsx)(Pgi,{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)(Kgi,{options:f.options,isLoading:f.isLoading,target:g,onTargetValueChange:A,container:d,className:`min-w-0 flex-1`}),v&&(0,K.jsx)(Dgi,{provider:_.provider,modelId:_.modelId,canReset:_.canReset,onProviderChange:_.setProvider,onModelIdChange:_.setModelId,onReset:_.reset,container:d})]}),(0,K.jsx)(Agi,{datasets:p.datasets,datasetId:E,version:p.version,onDatasetChange:j,container:d}),(0,K.jsx)(Ugi,{scorerIds:m.scorerIds,usesDefaultScorers:m.usesDefaultScorers,onScorerIdsChange:m.setScorerIds,container:d})]}),(0,K.jsx)(`div`,{className:`mt-6`,children:(0,K.jsx)(Egi,{})}),(0,K.jsxs)(Ww,{className:`space-y-6 pt-4`,children:[E&&(0,K.jsx)(Mgi,{datasetId:E,version:p.version,onVersionChange:p.setVersion,container:d}),(0,K.jsx)(Ngi,{description:x,onDescriptionChange:S,disabled:D}),(0,K.jsx)(Lgi,{schema:h.schema,raw:h.raw,onRawChange:h.setRaw,onValuesChange:h.setValues},O)]})]})}),(0,K.jsxs)(bE,{children:[(0,K.jsx)(wE,{children:`Cancel`}),(0,K.jsx)(Rgi,{onRun:M,canRun:k,isRunning:D})]})]})})}function h_i({open:e,onOpenChange:t,onSuccess:n,...r}){let[i,a]=(0,G.useState)(0);return(0,K.jsx)(m_i,{open:e,onOpenChange:t,onOpenChangeComplete:e=>{e||a(e=>e+1)},onSuccess:n,...r},`${i}:${JSON.stringify(r)}`)}var g_i=`mastra_model_total_input_tokens`,__i=`mastra_model_total_output_tokens`,v_i=()=>({estimatedCost:0,costUnits:new Set,hasUnknownCostUnit:!1});function y_i(e){let t=e.dimensions.name;if(t===`mastra_model_total_input_tokens`)return`inputTokens`;if(t===`mastra_model_total_output_tokens`)return`outputTokens`}function b_i(e,t,n){e[t]=(e[t]??0)+n.value,n.estimatedCost!=null&&(e.estimatedCost+=n.estimatedCost,n.costUnit?e.costUnits.add(n.costUnit.toLowerCase()):e.hasUnknownCostUnit=!0)}function x_i(e){let t=!e.hasUnknownCostUnit&&e.costUnits.size===1;return{inputTokens:e.inputTokens,outputTokens:e.outputTokens,estimatedCost:t?e.estimatedCost:void 0,costUnit:t?[...e.costUnits][0]:void 0}}var S_i=2e3;function C_i(e){let t=v_i(),n=new Map;for(let r of e.groups){let e=y_i(r);if(!e)continue;b_i(t,e,r);let i=r.dimensions.traceId;i&&b_i(c8(n,i,v_i),e,r)}let r={};for(let[e,t]of n)r[e]=x_i(t);return{summary:x_i(t),traces:r}}var w_i=5,T_i=e=>!e||Object.keys(e.traces).length===0&&e.summary.inputTokens===void 0&&e.summary.outputTokens===void 0,E_i=({experiments:e,supportsMetrics:t})=>{let n=Y(),r=LP(e.map(e=>e.id));return Ty({queries:e.map(({id:e,status:r})=>{let i=r!==`running`&&r!==`pending`;return{queryKey:[`experiment-item-usage`,e,i],queryFn:async()=>C_i(await n.getMetricBreakdown({name:[g_i,__i],aggregation:`sum`,groupBy:[`traceId`,`name`],filters:{experimentId:e}})),enabled:t&&i,refetchInterval:e=>T_i(e.state.data)&&e.state.dataUpdateCount<w_i?S_i:!1}}),combine:r})},D_i=({experimentId:e,experimentStatus:t,supportsMetrics:n,queryOptions:r})=>{let i=Y(),a=!!e&&n,o=Ey({queryKey:[`experiment-metrics`,e],refetchInterval:t===`running`||t===`pending`?2e3:!1,queryFn:async()=>{if(!e)throw Error(`experimentId is required`);let t={experimentId:e},[n,r,a]=await Promise.all([i.getMetricAggregate({name:[`mastra_model_total_input_tokens`,`mastra_model_total_output_tokens`],aggregation:`sum`,filters:t}),i.getMetricAggregate({name:[`mastra_agent_duration_ms`],aggregation:`avg`,filters:t}),i.getMetricAggregate({name:[`mastra_agent_duration_ms`],aggregation:`count`,filters:t})]);return{totalTokens:n.value??null,estimatedCost:n.estimatedCost??null,costUnit:n.costUnit??null,avgAgentDurationMs:r.value??null,agentRuns:a.value??null}},...r});return{data:o.data,isLoading:o.isLoading,isEnabled:a}},O_i=({traceId:e,queryOptions:t})=>{let n=Y();return Ey({queryKey:[`experiment-trace-light`,e],queryFn:async()=>{if(!e)throw Error(`Trace ID is required`);return n.getTraceLight(e)},...t})};function k_i({datasetId:e,target:t,queryOptions:n}){let r=Y(),i={perPage:100};return t?.targetType&&(i.targetType=t.targetType),t?.targetId&&(i.targetId=t.targetId),Ey({queryKey:e?[`dataset-experiments`,e,i]:[`experiments`,i],queryFn:()=>e?r.listDatasetExperiments(e,i):r.listExperiments(i),...n})}var A_i=`mastra_agent_duration_ms`,j_i=500,M_i=5e3;function N_i(e){let t=[];for(let n=0;n<e.length;n+=j_i)t.push(e.slice(n,n+j_i));return t}function P_i(e){return e.flatMap(e=>e.status===`fulfilled`?[e.value]:[])}function F_i(e,t,n){let r=new Set(e),i=new Map;for(let e of t.flatMap(e=>e.groups)){let t=e.dimensions.experimentId,n=y_i(e);t&&r.has(t)&&n&&b_i(c8(i,t,v_i),n,e)}let a=new Map;for(let[e,t]of i)a.set(e,x_i(t));for(let e of n.flatMap(e=>e.groups)){let t=e.dimensions.experimentId;t&&r.has(t)&&(c8(a,t,()=>({})).avgDurationMs=e.value)}return a}var I_i=({experiments:e,supportsMetrics:t})=>{let n=Y(),r=[...new Set(e.map(e=>e.id))].toSorted(),i=e.some(({status:e})=>e===`running`||e===`pending`);return Ey({queryKey:[`experiments-list-metrics`,r],enabled:t&&r.length>0,queryFn:async()=>{let e=N_i(r),[t,i]=await Promise.all([Promise.allSettled(e.map(e=>n.getMetricBreakdown({name:[g_i,__i],aggregation:`sum`,groupBy:[`experimentId`,`name`],filters:{experimentIds:e},limit:e.length*2}))),Promise.allSettled(e.map(e=>n.getMetricBreakdown({name:[A_i],aggregation:`avg`,groupBy:[`experimentId`],filters:{experimentIds:e},limit:e.length})))]);return F_i(r,P_i(t),P_i(i))},placeholderData:vy,refetchInterval:i?M_i:!1})};function L_i({datasetId:e,target:t,orderBy:n,queryOptions:r}){let i=Y(),{inView:a,setRef:o}=oP(),s=t?.targetType||void 0,c=t?.targetId||void 0,l=ky({queryKey:e?[`dataset-experiments`,e,`infinite`,{targetType:s,targetId:c,orderBy:n}]:[`experiments`,`infinite`,{targetType:s,targetId:c,orderBy:n}],queryFn:({pageParam:t})=>{let r={page:t,perPage:100};return s&&(r.targetType=s),c&&(r.targetId=c),n&&(r.orderBy=n),e?i.listDatasetExperiments(e,r):i.listExperiments(r)},initialPageParam:0,getNextPageParam:(e,t,n)=>{if(e?.experiments?.length&&e.pagination?.hasMore)return n+1},select:e=>e.pages.flatMap(e=>e?.experiments??[]),...r});return(0,G.useEffect)(()=>{a&&l.hasNextPage&&!l.isFetchingNextPage&&l.fetchNextPage()},[a,l]),{...l,setEndOfListElement:o}}var R_i=(0,G.createContext)(null);function z_i({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:i,hasNextPage:a,children:o}){let s=kb(),c=KWe(`/experiments/:experimentId/items/:itemId`)?.params.itemId,l=(0,G.useCallback)(t=>{s(`/experiments/${e}/items/${encodeURIComponent(t)}`)},[s,e]),u=(0,G.useCallback)(()=>{s(`/experiments/${e}`)},[s,e]),d=(0,G.useMemo)(()=>c?r.findIndex(e=>e.itemId===c):-1,[r,c]),f=(0,G.useMemo)(()=>{if(d<=0)return;let e=r[d-1].itemId;return()=>l(e)},[d,r,l]),p=(0,G.useMemo)(()=>{if(d<0||d>=r.length-1)return;let e=r[d+1].itemId;return()=>l(e)},[d,r,l]);sgi({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)(R_i.Provider,{value:m,children:o})}function B_i(){let e=(0,G.useContext)(R_i);if(!e)throw Error(`useExperimentItemPanel must be used within an ExperimentItemPanelProvider`);return e}function V_i(e,t){if(!e||typeof e!=`object`||!(t in e))return;let n=e[t];return typeof n==`string`&&n?n:void 0}function H_i(e){if(e.targetType===`agent`)return V_i(e.output,`text`)}function U_i(e){if(e.targetType)return H_i(e);let{output:t}=e;if(t!=null&&t!==``)return typeof t==`string`?t:JSON.stringify(t)}function W_i(e){let t=[];return e.some(e=>U_i(e))&&t.push({name:`output`,label:`Output`,size:`20rem`}),e.some(e=>L7(e))&&t.push({name:`error`,label:`Error`,size:`20rem`}),t}function L7(e){let t=V_i(e.error,`message`);if(t)return t;if(e.targetType===`agent`&&e.output&&typeof e.output==`object`)return V_i(e.output.error,`message`)}function G_i(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function K_i(e){return Array.isArray(e)?e.flatMap(e=>G_i(e)&&G_i(e.payload)?[e.payload]:[]):[]}function q_i(e){if(e.targetType!==`agent`||!G_i(e.output))return[];let t=new Map(K_i(e.output.toolResults).map(e=>[e.toolCallId,e]));return K_i(e.output.toolCalls).flatMap(e=>{if(typeof e.toolName!=`string`)return[];let n=t.get(e.toolCallId);return[{toolName:e.toolName,args:e.args,...n&&{result:n.result,isError:n.isError===!0}}]})}function J_i(e){if(H_i(e)||L7(e))return;let t=q_i(e).length;if(t!==0)return`No final text response after ${t} tool ${t===1?`call`:`calls`}`}var R7=e=>e==null?`-`:e.toFixed(2),Y_i=e=>xw(e)??`-`,X_i=(e,t)=>e!=null&&t!=null?e-t:null,Z_i=new Set(Intl.supportedValuesOf(`currency`)),Q_i={minimumFractionDigits:3,maximumFractionDigits:3},z7=(e,t)=>{if(e===void 0)return`-`;let n=(t??`usd`).toUpperCase();return Z_i.has(n)?new Intl.NumberFormat(`en-US`,{style:`currency`,currency:n,...Q_i}).format(e):`${new Intl.NumberFormat(`en-US`,Q_i).format(e)} ${t}`},$_i=e=>t=>z7(t,e),evi=new Intl.NumberFormat(`en-US`),B7=e=>e===void 0?`-`:evi.format(e),V7=e=>{if(e?.inputTokens!==void 0||e?.outputTokens!==void 0)return(e.inputTokens??0)+(e.outputTokens??0)};function tvi({scorerId:e,reason:t,nested:n=!1}){let r=`text-muted-foreground hover:text-foreground [&>svg]:size-3.5`;return(0,K.jsxs)(yZ,{children:[(0,K.jsx)(bZ,{delay:0,closeDelay:100,render:n?(0,K.jsx)(`span`,{"aria-hidden":!0,"data-testid":`score-reason-${e}`,className:`flex ${r}`}):(0,K.jsx)(`button`,{type:`button`,"aria-label":`Show ${e} reason`,className:`cursor-pointer ${r}`}),children:(0,K.jsx)(Xi,{})}),(0,K.jsx)(xZ,{side:`left`,align:`start`,className:`max-h-80 max-w-100 overflow-y-auto`,onClick:e=>e.stopPropagation(),children:(0,K.jsx)(xX,{children:t})})]})}var nvi=new Set([`itemId`,`id`,`status`,`input`,`output`,`error`,`tags`,`scores`,`cost`,`tokens`,`duration`]);function rvi({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}=_l(),g=!!(d&&f),_=i.filter(e=>nvi.has(e.name)||o?.includes(e.name)),v=[g?`2rem`:``,..._.map(e=>e.size)].filter(Boolean).join(` `),y=e=>_.some(t=>t.name===e),b=y(`itemId`)||y(`id`),x=y(`status`),S=y(`input`),C=y(`output`),w=y(`error`),T=y(`tags`),E=y(`scores`),D=y(`cost`),O=y(`tokens`),k=y(`duration`),A=d?e.filter(e=>d.has(e.id)).length:0,j=e.length>0&&A===e.length,{containerRef:M,getRowProps:N}=_Q({count:e.length}),P=e=>o?.includes(e.name)?(0,K.jsx)(Z.TopCell,{children:(0,K.jsxs)(m,{href:h.scorerLink(e.name),className:`flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0`,children:[(0,K.jsx)(iF,{}),(0,K.jsx)(`span`,{className:`min-w-0 truncate`,children:e.label})]})},e.name):(0,K.jsx)(Z.TopCell,{children:e.label},e.name);return t?(0,K.jsx)(NU,{columns:v}):(0,K.jsxs)(Z,{columns:v,className:`min-w-0`,scrollRef:M,children:[(0,K.jsxs)(Z.Top,{hasLeadingCell:g,children:[g&&(p?(0,K.jsx)(Z.TopSelectCell,{checked:j?!0:A>0&&`indeterminate`,onToggle:p,"aria-label":`Select all`}):(0,K.jsx)(Z.TopCell,{children:`\xA0`})),g?(0,K.jsx)(Z.TopCells,{colStart:2,children:_.map(P)}):_.map(P)]}),e.length===0?(0,K.jsx)(Z.NoMatch,{message:u}):(0,K.jsxs)(K.Fragment,{children:[e.map((e,t)=>{let i=!!e.error,s=e.id===n,c=(0,K.jsxs)(K.Fragment,{children:[b&&(0,K.jsx)(Z.Cell,{className:`text-muted-foreground`,children:e.itemId?.slice(0,8)??``}),x&&(0,K.jsx)(Z.Cell,{className:`flex items-center`,"data-testid":`result-status-${e.id}`,children:e.status?(0,K.jsx)(Wti,{status:e.status}):(0,K.jsx)(`span`,{className:`text-placeholder`,children:`—`})}),S&&(0,K.jsx)(Z.TextCell,{font:`mono`,children:svi(ovi(e.input),200)}),C&&(0,K.jsx)(Z.Cell,{className:`truncate font-mono`,"data-testid":`result-output-${e.id}`,children:U_i(e)??``}),w&&(0,K.jsx)(Z.Cell,{className:`truncate text-destructive-foreground`,"data-testid":`result-error-${e.id}`,children:L7(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)(wfi,{value:e,className:`shrink-0`},e))}),E&&(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(ivi,{scores:e.scores})}),D&&(0,K.jsx)(Z.Cell,{className:`text-muted-foreground tabular-nums`,"data-testid":`result-cost-${e.id}`,children:z7(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:B7(V7(e.usage))}),k&&(0,K.jsx)(Z.Cell,{className:`text-muted-foreground tabular-nums`,"data-testid":`result-duration-${e.id}`,children:xw(avi(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)(tvi,{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 ivi({scores:e}){let t=Array.isArray(e)?e.map(e=>e.score).filter(e=>e!=null):Object.values(e??{});return t.length===0?(0,K.jsx)(T,{variant:`meta`,tone:`faint`,children:`—`}):(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(TC,{size:`xs`,className:`text-muted-foreground`,children:(0,K.jsx)(Di,{})}),(0,K.jsx)(T,{variant:`meta`,tone:`muted`,font:`mono`,children:t[0].toFixed(2)}),t.length>1&&(0,K.jsxs)(bw,{children:[`+`,t.length-1]})]})}function avi({startedAt:e,completedAt:t}){if(e&&t)return new Date(t).getTime()-new Date(e).getTime()}function ovi(e){return e==null?`-`:typeof e==`string`?e:JSON.stringify(e,null,2)}function svi(e,t){return e.length<=t?e:e.slice(0,t-1)+`...`}function cvi({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}=B_i(),m=(0,G.useMemo)(()=>d?n.find(e=>e.itemId===d)?.id??null:null,[n,d]),{data:h}=WP({experimentId:e,experimentStatus:t,queryOptions:{enabled:!!e}}),{data:g}=E_i({experiments:(0,G.useMemo)(()=>[{id:e,status:t}],[e,t]),supportsMetrics:u}),_=g[e]?.traces,v=(0,G.useMemo)(()=>_?n.map(e=>({...e,usage:e.traceId?_[e.traceId]:void 0})):n,[n,_]),y=(0,G.useMemo)(()=>{if(!h)return[];let e=new Set;for(let t of Object.values(h))for(let n of t)e.add(n.scorerId);return[...e].sort()},[h]),b=(0,G.useCallback)(e=>{let t=n.find(t=>t.id===e);t&&(t.itemId===d?p():f(t.itemId))},[n,d,p,f]),x=(0,G.useMemo)(()=>[{name:`itemId`,label:`Item ID`,size:`7rem`},{name:`input`,label:`Input`,size:`20rem`},...W_i(n),...u?[{name:`cost`,label:`Cost`,size:`auto`},{name:`tokens`,label:`Tokens`,size:`auto`}]:[],{name:`duration`,label:`Duration`,size:`auto`},...y.map(e=>({name:e,label:e,size:`auto`}))],[n,y,u]);return(0,K.jsx)(`div`,{className:`h-full min-h-0 min-w-0 overflow-y-auto`,children:(0,K.jsx)(rvi,{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 lvi({children:e,className:t}){return(0,K.jsx)(`div`,{className:m(`grid content-start gap-4 overflow-y-auto`,t),children:e})}function uvi({children:e,className:t}){return(0,K.jsx)(`div`,{className:`flex w-full overflow-y-auto`,children:(0,K.jsx)(`div`,{className:m(`grid w-full content-start gap-4 overflow-y-auto`,t),children:e})})}function dvi({children:e,className:t}){return(0,K.jsx)(`div`,{className:m(`flex w-full flex-wrap items-center justify-between gap-3 gap-x-4`,t),children:e})}var fvi=Object.assign(uvi,{Content:lvi,Toolbar:dvi});function pvi({children:e,className:t}){return(0,K.jsx)(`div`,{className:m(`grid size-full grid-cols-1 overflow-y-auto`,t),children:e})}function mvi({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){let{data:i}=EIt({datasetId:e,queryOptions:{enabled:!!e}}),a=(i??[]).map(e=>{let t=`v${e.version}`,n=Fw(e.createdAt,`date-time`),r=e.isCurrent?`(current)`:void 0;return{value:String(e.version),label:[t,n,r].filter(e=>e!==void 0).join(` `),content:(0,K.jsxs)(Gw,{children:[(0,K.jsx)(Gw.Item,{children:t}),n&&(0,K.jsx)(Gw.Item,{children:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:n})}),r&&(0,K.jsx)(Gw.Item,{children:r})]})}});return(0,K.jsxs)(fvi.Toolbar,{className:`grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4`,children:[(0,K.jsx)(`div`,{}),(0,K.jsxs)(WA,{items:a,value:t??``,onValueChange:e=>r?.(e,n??``),children:[(0,K.jsx)(KA,{"aria-label":`Version A`,size:`md`,children:(0,K.jsx)(GA,{placeholder:`Select version`})}),(0,K.jsx)(qA,{children:a.map(e=>(0,K.jsx)(JA,{value:e.value,label:e.label,children:e.content},e.value))})]}),(0,K.jsxs)(WA,{items:a,value:n??``,onValueChange:e=>r?.(t??``,e),children:[(0,K.jsx)(KA,{"aria-label":`Version B`,size:`md`,children:(0,K.jsx)(GA,{placeholder:`Select an option`})}),(0,K.jsx)(qA,{children:a.map(e=>(0,K.jsx)(JA,{value:e.value,label:e.label,children:e.content},e.value))})]}),(0,K.jsx)(`div`,{})]})}var hvi={added:{badgeVariant:`info`,borderColor:`border-info-edge`,icon:(0,K.jsx)(Uo,{}),tooltip:`Added in this version`},changed:{badgeVariant:`warning`,borderColor:`border-warning-edge`,icon:(0,K.jsx)(tte,{}),tooltip:`Changed in this version`},same:{badgeVariant:`success`,borderColor:`border-success-edge`,icon:(0,K.jsx)(Ir,{}),tooltip:`Same in both versions`}};function gvi({red:e=!1,tooltip:t}){return(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{render:(0,K.jsx)(`span`,{}),role:`img`,tabIndex:0,"aria-label":t,className:m(`rounded`,_),children:(0,K.jsx)(nn,{className:m(`h-5 w-5 text-muted-foreground/40`,{"text-destructive-foreground":e})})}),(0,K.jsx)(CC,{children:t})]})}function _vi({href:e,tooltip:t,className:n,children:r}){let{Link:i}=_l(),a=(0,K.jsx)(i,{href:e,className:m(`flex w-full items-center justify-center gap-4 rounded-lg px-3 py-2 text-left hover:bg-fill-subtle`,b.colors,_,n),children:r});return t===void 0?a:(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{render:a}),(0,K.jsx)(CC,{children:t})]})}function vvi({variant:e,version:t}){if(!e)return(0,K.jsxs)(T,{as:`span`,tone:`muted`,children:[`v. `,t]});let{badgeVariant:n,icon:r,tooltip:i}=hvi[e];return(0,K.jsxs)(`div`,{className:`grid grid-cols-[1fr_auto]`,children:[t!==void 0&&(0,K.jsxs)(T,{as:`span`,tone:`muted`,className:`flex min-w-16 justify-end pr-3`,children:[`v. `,t]}),(0,K.jsx)(`span`,{className:`inline-flex`,role:`img`,"aria-label":i,children:(0,K.jsx)(bw,{variant:n,size:`xs`,icon:r})})]})}function yvi(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?`same`:e&&t&&e.datasetVersion!==t.datasetVersion?`changed`:e?`added`:`removed`}function bvi({otherVersionExists:e,status:t,isNewer:n}){if(!e&&n)return`added`;if(t===`changed`&&n)return`changed`}function xvi({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=yvi(n,r),c=bvi({otherVersionExists:r!==void 0,status:s,isNewer:o}),l=bvi({otherVersionExists:n!==void 0,status:s,isNewer:!o});return(0,K.jsxs)(`li`,{className:m(`text-foreground`,`grid grid-cols-[1fr_1fr_1fr_10rem] gap-3 overflow-hidden rounded-lg border border-transparent border-t-border px-3 py-[3px] pb-[2px] first:border-t-transparent`,b.colors),children:[(0,K.jsx)(T,{as:`p`,variant:`body`,tone:`faint`,className:`truncate py-[0.6rem]`,children:t}),s===`same`?(0,K.jsx)(_vi,{href:`/datasets/${e}/items/${t}`,className:`col-span-2 gap-2`,tooltip:hvi.same.tooltip,children:(0,K.jsx)(vvi,{variant:`same`,version:r?.datasetVersion})}):(0,K.jsxs)(K.Fragment,{children:[n?.datasetVersion?(0,K.jsx)(_vi,{href:`/datasets/${e}/items/${t}`,className:`gap-2`,tooltip:c?hvi[c].tooltip:void 0,children:(0,K.jsx)(vvi,{variant:c,version:n.datasetVersion})}):(0,K.jsx)(`div`,{className:`flex items-center justify-center`,children:(0,K.jsx)(gvi,{red:o,tooltip:o?`Deleted in this version`:`Not present in this version`})}),r?.datasetVersion?(0,K.jsx)(_vi,{href:`/datasets/${e}/items/${t}`,className:`gap-2`,tooltip:l?hvi[l].tooltip:void 0,children:(0,K.jsx)(vvi,{variant:l,version:r.datasetVersion})}):(0,K.jsx)(`div`,{className:`flex items-center justify-center`,children:(0,K.jsx)(gvi,{red:!o,tooltip:o?`Not present in this version`:`Deleted in this version`})})]}),s===`changed`?(0,K.jsx)(_vi,{href:`/datasets/${e}/items/${t}/versions?version=${n?.datasetVersion}&compare=${r?.datasetVersion}`,children:`Compare`}):(0,K.jsx)(`div`,{children:(0,K.jsx)(gvi,{tooltip:`Comparing is available only for changed items`})})]},t)})})})}function Svi(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 Cvi({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)(wvi,{item:e,onClose:r,...a},e.id):t?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(m$.Header,{children:[(0,K.jsx)(m$.Heading,{children:`Dataset item`}),(0,K.jsx)(m$.HeaderActions,{children:(0,K.jsx)(m$.CloseButton,{icon:`x`,onClick:r,tooltip:`Close detail panel`})})]}),n]}):null;return i===`inline`?c?(0,K.jsx)(m$,{variant:`inline`,title:s,children:c}):null:(0,K.jsx)(m$,{open:!!o,onClose:r,title:s,children:c})}function wvi({datasetId:e,item:t,items:n,onItemChange:r,onClose:i}){let{navigate:a}=_l(),{updateItem:o,deleteItem:s}=zP(),[c,l]=(0,G.useState)(!1),[u,d]=(0,G.useState)(``),[f,p]=(0,G.useState)(``),[m,h]=(0,G.useState)(``),[g,_]=(0,G.useState)(``),[v,y]=(0,G.useState)(``),[b,x]=(0,G.useState)(``),[S,C]=(0,G.useState)(null),[w,T]=(0,G.useState)(!1);(0,G.useEffect)(()=>{t&&(d(JSON.stringify(t.input,null,2)),p(t.groundTruth?JSON.stringify(t.groundTruth,null,2):``),h(t.metadata?JSON.stringify(t.metadata,null,2):``),_(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):``),y(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):``),x(t.requestContext?JSON.stringify(t.requestContext,null,2):``),l(!1),T(!1),C(null))},[t?.id]);let E=n.findIndex(e=>e.id===t.id),D=E>0?()=>r(n[E-1].id):void 0,O=E>=0&&E<n.length-1?()=>r(n[E+1].id):void 0;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(m$.Header,{children:[(0,K.jsx)(m$.Heading,{children:`Dataset item`}),(0,K.jsxs)(m$.HeaderActions,{children:[!c&&(0,K.jsxs)(mD,{children:[(0,K.jsx)(mD.Trigger,{asChild:!0,children:(0,K.jsx)(X,{size:`icon-sm`,variant:`ghost`,tooltip:`Open actions menu`,"aria-label":`Open actions menu`,children:(0,K.jsx)(Ar,{})})}),(0,K.jsxs)(mD.Content,{align:`end`,className:`w-48`,children:[(0,K.jsxs)(mD.Item,{onSelect:()=>a(`/datasets/${e}/items/${t.id}/versions?version=${t.datasetVersion}`),children:[(0,K.jsx)(as,{}),`Item versions`]}),(0,K.jsxs)(mD.Item,{onSelect:()=>l(!0),children:[(0,K.jsx)(Ro,{}),`Edit`]}),(0,K.jsxs)(mD.Item,{onSelect:()=>T(!0),variant:`destructive`,children:[(0,K.jsx)(Sc,{}),`Delete item`]})]})]}),(0,K.jsx)(m$.NextPrevNav,{onPrevious:D,onNext:O,previousLabel:`Go to previous item`,nextLabel:`Go to next item`}),(0,K.jsx)(m$.CloseButton,{icon:`x`,onClick:i,tooltip:`Close detail panel`})]})]}),(0,K.jsx)(m$.Content,{children:c?(0,K.jsx)(Tgi,{inputValue:u,setInputValue:e=>{d(e),S?.field===`input`&&C(null)},groundTruthValue:f,setGroundTruthValue:e=>{p(e),S?.field===`groundTruth`&&C(null)},metadataValue:m,setMetadataValue:h,trajectoryValue:g,setTrajectoryValue:_,toolMocksValue:v,setToolMocksValue:y,requestContextValue:b,setRequestContextValue:x,validationErrors:S,onSave:async()=>{let n;try{n=JSON.parse(u)}catch{UC.error(`Input must be valid JSON`);return}let r;if(f.trim())try{r=JSON.parse(f)}catch{UC.error(`Ground Truth must be valid JSON`);return}let i;if(m.trim())try{i=JSON.parse(m)}catch{UC.error(`Metadata must be valid JSON`);return}let a=null;if(g.trim())try{a=JSON.parse(g)}catch{UC.error(`Expected Trajectory must be valid JSON`);return}let s;if(v.trim())try{let e=JSON.parse(v);if(!Array.isArray(e)){UC.error(`Tool Mocks must be a JSON array`);return}s=e}catch{UC.error(`Tool Mocks must be valid JSON`);return}else s=[];let c;if(b.trim())try{c=JSON.parse(b)}catch{UC.error(`Request Context must be valid JSON`);return}try{await o.mutateAsync({datasetId:e,itemId:t.id,input:n,groundTruth:r,metadata:i,expectedTrajectory:a,toolMocks:s,requestContext:c}),UC.success(`Item updated successfully`),l(!1),C(null)}catch(e){let t=Svi(e);t?C(t):UC.error(`Failed to update item: ${e instanceof Error?e.message:`Unknown error`}`)}},onCancel:()=>{d(JSON.stringify(t.input,null,2)),p(t.groundTruth?JSON.stringify(t.groundTruth,null,2):``),h(t.metadata?JSON.stringify(t.metadata,null,2):``),_(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):``),y(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):``),x(t.requestContext?JSON.stringify(t.requestContext,null,2):``),l(!1),C(null)},isSaving:o.isPending}):(0,K.jsx)(Sgi,{item:t})}),(0,K.jsx)(aP,{open:w,onOpenChange:T,children:(0,K.jsxs)(aP.Content,{children:[(0,K.jsxs)(aP.Header,{children:[(0,K.jsx)(aP.Title,{children:`Delete Item`}),(0,K.jsx)(aP.Description,{children:`Are you sure you want to delete this item? This action cannot be undone.`})]}),(0,K.jsxs)(aP.Footer,{children:[(0,K.jsx)(aP.Cancel,{children:`Cancel`}),(0,K.jsx)(aP.Action,{onClick:async()=>{try{await s.mutateAsync({datasetId:e,itemId:t.id}),UC.success(`Item deleted successfully`),T(!1),i()}catch(e){UC.error(`Failed to delete item: ${e instanceof Error?e.message:`Unknown error`}`)}},children:s.isPending?`Deleting...`:`Yes, delete`})]})]})})]})}function Tvi(){let{datasetId:e,items:t,isLoadingItems:n,currentItemId:r,openItem:i,close:a}=ugi(),o=fE();v3r(r,a);let s=(0,G.useMemo)(()=>r?t.find(e=>e.id===r):void 0,[t,r]),{data:c,isLoading:l}=oIt({datasetId:s?``:e,itemId:!s&&r?r:``,queryOptions:{enabled:!(s||!e)&&!!(!s&&r&&r)}}),u=(0,K.jsx)(Cvi,{datasetId:e,item:s??c??void 0,itemId:r,fallback:n||l?(0,K.jsx)(m$.LoadingData,{}):(0,K.jsxs)(m$.NoData,{children:[`No loaded item "`,r,`".`]}),items:t,onItemChange:i,onClose:a,variant:o?`drawer`:`inline`});return o?u:r?(0,K.jsx)(J8,{owner:`dataset-item`,children:u}):null}function Evi({crumbs:e,children:t}){return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:e}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Dataset`}),(0,K.jsx)(`div`,{}),(0,K.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:t})]})}function Dvi(){let{datasetId:e}=Ab(),t=kb(),[n,r]=Hb(),{activeVersion:i}=GP(n,r),a=[sF(`/datasets`),cF],o=[...a,WLt],[s,c]=(0,G.useState)(!1),[l,u]=(0,G.useState)(!1),[d,f]=(0,G.useState)(!1),[p,m]=(0,G.useState)(!1),[h,g]=(0,G.useState)(!1),{data:_,error:v,isLoading:y}=VP({datasetId:e,queryOptions:{enabled:!!e}}),{data:b=[],isLoading:x}=RP({datasetId:e,search:void 0,version:i,queryOptions:{enabled:!!e}});if(y)return null;if(v&&JP(v))return(0,K.jsx)(Evi,{crumbs:a,children:(0,K.jsx)(jU,{})});if(v&&YP(v))return(0,K.jsx)(Evi,{crumbs:a,children:(0,K.jsx)(AU,{resource:`datasets`})});if(v&&XP(v)||!y&&!v&&!_)return(0,K.jsx)(Evi,{crumbs:a,children:(0,K.jsx)(RC,{titleSlot:`Dataset not found`,descriptionSlot:`No dataset with id "${e}".`,actionSlot:(0,K.jsx)(X,{render:(0,K.jsx)(Vb,{to:`/datasets`}),icon:(0,K.jsx)(Rt,{}),children:`Back to datasets`})})});if(v)return(0,K.jsx)(Evi,{crumbs:a,children:(0,K.jsx)(RC,{tone:`error`,titleSlot:`Failed to load dataset`,descriptionSlot:v instanceof Error?v.message:`An unexpected error occurred. Please try again.`})});let S=e=>{t(`/experiments/${e}`)},C=()=>{t(`/datasets`)},w=b.length>0,T=(_?.version??0)>0,E=w||T,D=w||(_?.tags?.length??0)>0,O=(0,K.jsxs)(K.Fragment,{children:[w&&(0,K.jsx)(X,{variant:`ghost`,size:`sm`,onClick:()=>c(!0),icon:(0,K.jsx)(Uo,{}),children:`New experiment`}),E&&(0,K.jsx)(X,{variant:`ghost`,size:`sm`,render:(0,K.jsx)(Vb,{to:`/experiments?dataset=${e}`}),icon:(0,K.jsx)(wLt,{}),children:`Experiments`}),(0,K.jsx)(X,{variant:`ghost`,size:`sm`,onClick:()=>g(!0),icon:(0,K.jsx)(Cn,{}),children:`Schema`}),(0,K.jsxs)(mD,{children:[(0,K.jsx)(mD.Trigger,{asChild:!0,children:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,"aria-label":`Dataset actions menu`,children:(0,K.jsx)(Ar,{})})}),(0,K.jsxs)(mD.Content,{align:`end`,className:`w-48`,children:[(0,K.jsxs)(mD.Item,{onSelect:()=>void t(`/datasets/${e}/edit`),children:[(0,K.jsx)(Ro,{}),` Edit dataset`]}),(0,K.jsxs)(mD.Item,{onSelect:()=>m(!0),children:[(0,K.jsx)(xr,{}),` Duplicate dataset`]}),(0,K.jsxs)(mD.Item,{onSelect:()=>f(!0),variant:`destructive`,children:[(0,K.jsx)(Sc,{}),` Delete dataset`]})]})]})]});return(0,K.jsxs)(lgi,{datasetId:e,items:b,isLoadingItems:x,children:[(0,K.jsxs)(`div`,{className:`h-full`,children:[(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:o}),headerActions:O,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(`div`,{children:(0,K.jsx)(fgi,{datasetId:e,onAddItemClick:()=>u(!0),toolbarActionsSlot:D?(0,K.jsx)(mgi,{datasetId:e}):void 0})})]}),(0,K.jsx)(Tvi,{})]}),(0,K.jsx)(h_i,{initialDatasetId:e,initialDatasetVersion:i??void 0,open:s,onOpenChange:c,onSuccess:S},`${e}:${i??`latest`}`),(0,K.jsx)(Edr,{datasetId:e,open:l,onOpenChange:u}),_&&(0,K.jsx)(Cpi,{open:p,onOpenChange:m,sourceDatasetId:_.id,sourceDatasetName:_.name,sourceDatasetDescription:_.description,sourceDatasetTargetType:_.targetType}),_&&(0,K.jsx)(whi,{open:h,onOpenChange:g,dataset:_}),_&&(0,K.jsx)(Hpi,{open:d,onOpenChange:f,datasetId:_.id,datasetName:_.name,onSuccess:C})]})}function Ovi({children:e,className:t}){return(0,K.jsx)(`div`,{className:m(`grid content-start`,t),children:e})}function kvi({children:e,isLoading:t}){return(0,K.jsx)(T,{variant:`caption`,tone:`muted`,className:m(`mt-1 ml-1 flex max-w-140 flex-wrap gap-x-4 gap-y-1 first-of-type:mt-3`,{"w-[40rem] max-w-[80%] animate-pulse rounded-md bg-fill":t}),children:t?(0,K.jsx)(K.Fragment,{children:`\xA0`}):(0,K.jsx)(K.Fragment,{children:e})})}function Avi({children:e,title:t,description:n,icon:r,className:i,withMargins:a=!0}){let o=t===`loading`,s=n===`loading`;return e?(0,K.jsx)(`header`,{className:m(`grid w-full grid-cols-[1fr_auto] gap-8`,{"mt-6 mb-4":a},i),children:e}):(0,K.jsxs)(`header`,{className:m(`grid gap-1 py-3`,i),children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,tone:`ink`,className:m(`flex items-center gap-2`,`[&>svg]:size-6 [&>svg]:text-muted-foreground`,{"w-60 max-w-[50%] animate-pulse rounded-md bg-muted":o}),children:o?(0,K.jsx)(K.Fragment,{children:`\xA0`}):(0,K.jsxs)(K.Fragment,{children:[r&&r,` `,t]})}),n&&(0,K.jsx)(T,{variant:`caption`,tone:`muted`,className:m(`m-0`,{"w-[40rem] max-w-[80%] animate-pulse rounded-md bg-muted":s}),children:s?(0,K.jsx)(K.Fragment,{children:`\xA0`}):n})]})}function jvi({children:e,isLoading:t}){return(0,K.jsx)(T,{as:`h1`,variant:`heading`,tone:`ink`,className:m(`flex items-center gap-2`,`[&>svg]:size-[1.25em] [&>svg]:opacity-50`,t&&`w-60 max-w-[50%] animate-pulse rounded-md bg-fill`),children:t?(0,K.jsx)(K.Fragment,{children:`\xA0`}):e})}var H7=Object.assign(Avi,{Title:jvi,Description:kvi,Column:Ovi}),Mvi=[sF(`/datasets`),cF,{id:`dataset-edit`,label:`Edit dataset`}];function Nvi({children:e}){return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Mvi}),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 Pvi(){let{datasetId:e}=Ab(),t=kb(),{data:n,error:r,isLoading:i}=VP({datasetId:e,queryOptions:{enabled:!!e}}),a=()=>void t(`/datasets/${e}`);return i?null:r&&JP(r)?(0,K.jsx)(Nvi,{children:(0,K.jsx)(jU,{})}):r&&YP(r)?(0,K.jsx)(Nvi,{children:(0,K.jsx)(AU,{resource:`datasets`})}):r||!n?(0,K.jsx)(Nvi,{children:(0,K.jsx)(RC,{tone:`error`,titleSlot:`Failed to load dataset`,descriptionSlot:r instanceof Error?r.message:`An unexpected error occurred. Please try again.`})}):(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Mvi}),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)(H7,{className:`mb-6 p-0`,children:(0,K.jsxs)(H7.Column,{children:[(0,K.jsxs)(H7.Title,{children:[(0,K.jsx)(Tr,{}),` Edit dataset`]}),(0,K.jsx)(H7.Description,{children:n.name})]})}),(0,K.jsx)(dF,{className:`p-4`,children:(0,K.jsx)(Vpi,{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 Fvi(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 Ivi(e,t){return e.map(e=>{let n=typeof e.updatedAt==`string`?new Date(e.updatedAt):e.updatedAt;return{value:String(e.datasetVersion),label:(0,K.jsxs)(`span`,{className:`flex w-full items-center gap-2`,children:[(0,K.jsxs)(Gw,{children:[(0,K.jsx)(Gw.Item,{children:(0,K.jsxs)(`b`,{children:[`v. `,e.datasetVersion]})}),(0,K.jsx)(Gw.Item,{children:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:Fw(n,`date-time`)})})]}),e.isLatest?(0,K.jsx)(bw,{variant:`blue`,size:`xs`,className:`ml-auto`,children:`Latest`}):null]}),disabled:t?.has(e.datasetVersion)??!1}})}function Lvi(e){let t=Number(e);return e!=null&&Number.isFinite(t)&&t>0?t:null}function Rvi(){let{datasetId:e,itemId:t}=Ab(),[n,r]=Hb(),i=[sF(`/datasets`),cF,{id:`dataset-item`,label:RLt(t),to:e&&t?`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}`:void 0},{id:`dataset-item-versions`,label:`Item Version History`}],a=Lvi(n.get(`version`)),o=Lvi(n.get(`compare`)),s=n.get(`view`)===`diff`,{data:c,error:l}=VP({datasetId:e??``,queryOptions:{enabled:!!e}}),{data:u,isLoading:d}=CIt({datasetId:e??``,itemId:t??``,queryOptions:{enabled:!!e&&!!t}}),f=(a==null?void 0:u?.find(e=>e.datasetVersion===a))??u?.[0],p=f?.datasetVersion??null,m=o!=null&&o!==p?o:null,{data:h,isLoading:g}=wIt({datasetId:e??``,itemId:t??``,datasetVersion:m??0,latestVersion:c?.version,queryOptions:{enabled:!!e&&!!t&&(m??0)>0}}),_=(e,t)=>r(n=>{let r=new URLSearchParams(n);return t==null?r.delete(e):r.set(e,String(t)),r},{replace:!0});if(l&&JP(l))return(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:i}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Item Version History`}),(0,K.jsx)(jU,{variant:`fill`})]});if(l&&YP(l))return(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:i}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Item Version History`}),(0,K.jsx)(AU,{variant:`fill`,resource:`datasets`})]});if(!e||!t)return(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:i}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Item Version History`}),(0,K.jsx)(`div`,{className:`grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto`,children:(0,K.jsx)(`div`,{className:`py-5 text-center text-muted-foreground`,children:(0,K.jsx)(`p`,{children:`Item not found.`})})})]});let v=!!(f&&h),y=s&&v,b=f?Fvi(f,e):null,x=h?Fvi(h,e):null,S=(f?.datasetVersion??0)<(h?.datasetVersion??0);return(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:i}),headerActions:v&&(0,K.jsx)(X,{variant:`ghost`,size:`sm`,onClick:()=>_(`view`,s?null:`diff`),children:s?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(gr,{}),` Default view`]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(ji,{}),` Diff view`]})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Item Version History`}),(0,K.jsxs)(`div`,{className:`grid min-h-0 grid-cols-1 gap-4 md:grid-cols-2`,children:[(0,K.jsxs)(dF,{className:`grid min-h-0 grid-rows-[auto_1fr] overflow-hidden`,children:[(0,K.jsx)(fF,{children:(0,K.jsx)(zvi,{label:`Version`,value:p==null?``:String(p),options:Ivi(u??[],m==null?void 0:new Set([m])),onValueChange:e=>_(`version`,Number(e))})}),(0,K.jsx)(hF,{className:`grid content-start gap-5 overflow-y-auto`,children:d?(0,K.jsx)(T,{as:`p`,variant:`body`,tone:`muted`,children:`Loading...`}):b?(0,K.jsx)(Sgi,{item:b,diff:y&&x?{against:x,side:S?`a`:`b`}:void 0}):(0,K.jsx)(T,{as:`p`,variant:`body`,tone:`muted`,children:`Item data not available`})})]}),(0,K.jsxs)(dF,{className:`grid min-h-0 grid-rows-[auto_1fr] overflow-hidden`,children:[(0,K.jsx)(fF,{children:(0,K.jsx)(zvi,{label:`Compare version`,value:m==null?``:String(m),placeholder:`Select a version to compare`,options:Ivi(u??[],p==null?void 0:new Set([p])),onValueChange:e=>_(`compare`,Number(e))})}),(0,K.jsx)(hF,{className:`grid content-start gap-5 overflow-y-auto`,children:m==null?(0,K.jsx)(RC,{className:`h-full`,titleSlot:`No version selected`,descriptionSlot:`Pick a version above to compare it with the one on the left.`}):g?(0,K.jsx)(T,{as:`p`,variant:`body`,tone:`muted`,children:`Loading...`}):x?(0,K.jsx)(Sgi,{item:x,diff:y&&b?{against:b,side:S?`b`:`a`}:void 0}):(0,K.jsxs)(T,{as:`p`,variant:`body`,tone:`muted`,children:[`Version `,m,` not found`]})})]})]})]})}function zvi({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)(as,{className:`size-4 opacity-50`}),(0,K.jsxs)(WA,{value:t,onValueChange:i,children:[(0,K.jsx)(KA,{"aria-label":e,className:`w-full`,children:(0,K.jsx)(GA,{placeholder:r,className:`flex-1`})}),(0,K.jsx)(qA,{children:n.map(e=>(0,K.jsx)(JA,{value:e.value,disabled:e.disabled,children:e.label},e.value))})]})]})}var Bvi=[sF(`/datasets`),cF,{id:`dataset-versions`,label:`Versions`}];function Vvi(){let{datasetId:e}=Ab(),[t]=Hb(),n=t.get(`ids`)?.split(`,`).map(Number).filter(e=>!isNaN(e)&&e>0)??[],r=kb(),{data:i,error:a}=VP({datasetId:e??``,queryOptions:{enabled:!!e}}),o=RP({datasetId:e??``,search:void 0,version:n[0]??null,queryOptions:{enabled:!!e}}),s=RP({datasetId:e??``,search:void 0,version:n[1]??null,queryOptions:{enabled:!!e}}),c=(0,G.useMemo)(()=>o.data??[],[o.data]),l=(0,G.useMemo)(()=>s.data??[],[s.data]),u=(0,G.useMemo)(()=>{let e=new Map;for(let t of[...c,...l])e.has(t.id)||e.set(t.id,{id:t.id,createdAt:new Date(t.createdAt)});return[...e.values()].sort((e,t)=>t.createdAt.getTime()-e.createdAt.getTime())},[c,l]),d=(0,G.useMemo)(()=>new Map(c.map(e=>[e.id,e])),[c]),f=(0,G.useMemo)(()=>new Map(l.map(e=>[e.id,e])),[l]);return a&&JP(a)?(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:Bvi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Versions`}),(0,K.jsx)(jU,{variant:`fill`})]}):a&&YP(a)?(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:Bvi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Versions`}),(0,K.jsx)(AU,{variant:`fill`,resource:`datasets`})]}):!e||n.length<2?(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:Bvi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Versions`}),(0,K.jsx)(`div`,{className:`grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto`,children:(0,K.jsx)(`div`,{className:`py-5 text-center text-muted-foreground`,children:(0,K.jsx)(`p`,{children:`Select at least two versions to compare.`})})})]}):(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:Bvi}),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)(H7,{children:[(0,K.jsxs)(H7.Column,{children:[(0,K.jsxs)(H7.Title,{children:[(0,K.jsx)(vte,{}),` Compare Dataset Versions`]}),(0,K.jsx)(H7.Description,{children:(0,K.jsxs)(gQ,{children:[(0,K.jsx)(as,{}),` Comparing `,n.length,` versions of`,` `,i?.name||e?.slice(0,8)]})})]}),(0,K.jsx)(H7.Column,{children:(0,K.jsx)(X,{render:(0,K.jsx)(Vb,{to:`/datasets/${e}`}),icon:(0,K.jsx)(Rt,{}),children:`Back to dataset`})})]}),(0,K.jsx)(pvi,{children:(0,K.jsxs)(fvi,{children:[(0,K.jsx)(mvi,{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)(xvi,{datasetId:e,versionA:n[0],versionB:n[1],allItems:u,itemsAMap:d,itemsBMap:f})]})})]})})]})}var Hvi=100,Uvi=async(e,t,{page:n,experiments:r})=>{let i=await Promise.all(r.map(async r=>{try{let{results:i,pagination:a}=await e.listDatasetExperimentResults(r.datasetId,r.experimentId,{page:n,perPage:Hvi,status:t});return{experiment:r,results:i,hasMore:a.hasMore&&i.length>0}}catch{return{experiment:r,results:[],hasMore:!1}}})),a=i.filter(e=>e.hasMore).map(e=>e.experiment);return{items:i.flatMap(({experiment:e,results:n})=>n.filter(e=>e.status===t).map(t=>({id:t.id,input:t.input,output:t.output,error:t.error,itemId:t.itemId,experimentId:t.experimentId,datasetId:e.datasetId,traceId:t.traceId??void 0,scores:t.scores?Object.fromEntries(t.scores.map(e=>[e.scorerId,e.score??0])):{},tags:t.tags??[],targetType:t.targetType,createdAt:t.createdAt,startedAt:t.startedAt,completedAt:t.completedAt,status:t.status,groundTruth:t.groundTruth,toolMockReport:t.toolMockReport}))),next:a.length>0?{page:n+1,experiments:a}:void 0}},Wvi=(e,{experimentId:t,targetType:n,targetId:r,experiments:i,isLoadingExperiments:a=!1,queryOptions:o})=>{let s=Y(),{inView:c,setRef:l}=oP(),u=i!==void 0,{data:d,isLoading:f}=k_i({datasetId:void 0,target:{targetType:n,targetId:r},queryOptions:{enabled:!u}}),p=u?i:d?.experiments,m=u?a:f,h=t?p?.filter(e=>e.id===t):p,g=ky({queryKey:[`review-items`,e,`infinite`,t??`all`,u?`supplied`:`discovered`,u?void 0:n||`all`,u?void 0:r||`all`,h?.map(e=>[e.datasetId,e.id])],queryFn:async({pageParam:t})=>{let n=await Uvi(s,e,t);for(;n.items.length===0&&n.next;)n=await Uvi(s,e,n.next);return n},initialPageParam:{page:0,experiments:(h??[]).flatMap(e=>e.datasetId?[{experimentId:e.id,datasetId:e.datasetId}]:[])},getNextPageParam:e=>e.next,select:e=>e.pages.flatMap(e=>e.items),enabled:!!p,refetchOnWindowFocus:!1,...o});return(0,G.useEffect)(()=>{c&&g.hasNextPage&&!g.isFetching&&g.fetchNextPage({cancelRefetch:!1})},[c,g]),{...g,isLoading:g.isLoading||m,setEndOfListElement:l}},Gvi=(e={})=>Wvi(`needs-review`,e),Kvi=(e={})=>Wvi(`complete`,e);function qvi({queryOptions:e}={}){let t=Y();return Ey({queryKey:[`experiment-review-summary`],queryFn:()=>t.getExperimentReviewSummary(),...e})}var Jvi={baseline:`purple`,contender:`blue`},U7=e=>e===0?`Baseline`:`Contender ${e}`;function Yvi({open:e,onOpenChange:t,experimentId:n,experimentName:r,onSuccess:i}){let{deleteExperiment:a}=zP();return(0,K.jsx)(aP,{open:e,onOpenChange:t,children:(0,K.jsxs)(aP.Content,{children:[(0,K.jsxs)(aP.Header,{children:[(0,K.jsx)(aP.Title,{children:`Delete Experiment`}),(0,K.jsxs)(aP.Description,{children:[`Are you sure you want to delete "`,r||n,`"? This will permanently delete the experiment, all its results, and the traces it produced, including their spans and any scores, feedback, metrics and logs attached to those traces. This action cannot be undone.`]})]}),(0,K.jsxs)(aP.Footer,{children:[(0,K.jsx)(aP.Cancel,{children:`Cancel`}),(0,K.jsx)(X,{icon:(0,K.jsx)(Sc,{}),variant:`primary`,onClick:async()=>{try{await a.mutateAsync(n),UC.success(`Experiment deleted successfully`),t(!1),i?.()}catch(e){UC.error(`Failed to delete experiment: ${e instanceof Error?e.message:`Unknown error`}`)}},disabled:a.isPending,children:a.isPending?`Deleting...`:`Delete`})]})]})})}var Xvi=`minmax(9rem,1fr)`,Zvi=`minmax(8rem,16rem)`,Qvi=`auto auto auto auto auto auto auto auto`,$vi=`auto auto auto`,W7={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`},eyi={completed:`neutral`,running:`warning`,failed:`destructive`,pending:`neutral`},G7={completed:`Run completed`,running:`Run in progress`,failed:`Run failed`,pending:`Run queued`};function tyi(e){let t=hU(e.id)??e.id;return e.name||`Experiment #${t}`}var nyi=60;function ryi({experiment:e}){return(0,K.jsx)(`span`,{className:`block min-w-0 truncate text-left text-muted-foreground`,children:tyi(e)})}function iyi({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<=nyi?n:(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{asChild:!0,children:n}),(0,K.jsx)(CC,{children:t})]})}function ayi(){let{data:e}=PP(),{data:t}=sP(),{data:n}=eF(),{data:r}=qP();return{agents:e,workflows:t,scorers:n,processors:r}}var oyi={agent:tF,workflow:rP,scorer:iF,processor:rF},syi={agent:`Agent`,workflow:`Workflow`,scorer:`Scorer`,processor:`Processor`},cyi=`External (caller-run)`;function lyi(e,{agents:t,workflows:n,scorers:r,processors:i}){let{targetType:a,targetId:o}=e;if(!o)return cyi;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 uyi({experiment:e,datasetName:t,review:n,selectionRole:r,showUsage:i=!1,metrics:a}){let o=e.status??`pending`,s=e.succeededCount??0,c=e.failedCount??0,l=e.totalItems??0;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Z.Cell,{children:r?(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(bw,{variant:r.variant,className:`shrink-0`,children:r.label}),(0,K.jsx)(ryi,{experiment:e})]}):(0,K.jsx)(ryi,{experiment:e})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(iyi,{experiment:e})}),t!==void 0&&(0,K.jsx)(Z.TextCell,{children:t}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(myi,{experiment:e})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(bw,{variant:eyi[o]??`neutral`,indicator:`dot`,children:G7[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)(pyi,{value:dyi(e),format:xw}),i&&(0,K.jsx)(fyi,{metrics:a}),(0,K.jsx)(Z.Cell,{className:`text-center`,children:(0,K.jsx)(hyi,{review:n})}),(0,K.jsx)(Z.TextCell,{children:Fw(e.createdAt,`date`)??`—`})]})}function dyi(e){if(e.startedAt&&e.completedAt)return new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime()}function fyi({metrics:e}){let t=e?.avgDurationMs===void 0?void 0:Math.round(e.avgDurationMs);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(pyi,{value:t,format:xw}),(0,K.jsx)(pyi,{value:V7(e),format:M5}),(0,K.jsx)(pyi,{value:e?.estimatedCost,format:t=>z7(t,e?.costUnit)})]})}function pyi({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 myi({experiment:e}){let t=lyi(e,ayi()),n=e.targetId?e.targetType:null,r=n?oyi[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":syi[n],children:(0,K.jsx)(r,{})}),(0,K.jsx)(`span`,{className:n?`truncate`:`truncate text-placeholder`,children:t})]})}function hyi({review:e}){if(!e)return(0,K.jsx)(`span`,{className:`text-placeholder`,children:`—`});let t=e.needsReview+e.complete;return t===0?(0,K.jsx)(`span`,{className:`text-placeholder`,children:`—`}):e.needsReview>0?(0,K.jsxs)(bw,{size:`xs`,variant:`warning`,children:[e.needsReview,` pending`]}):(0,K.jsxs)(bw,{size:`xs`,variant:`success`,children:[e.complete,`/`,t,` reviewed`]})}var gyi=`${Xvi} ${Zvi} 1fr ${Qvi}`,_yi=`${gyi} auto`,vyi=`${gyi} ${$vi} auto`,yyi=[{label:W7.avgDuration,className:`text-center`},{label:W7.tokens,className:`text-center`},{label:W7.cost,className:`text-center`}],byi=e=>[{label:W7.experiment},{label:W7.description},{label:W7.dataset},{label:W7.target},{label:W7.status,sortKey:`status`},{label:W7.items,className:`text-center`},{label:W7.succeeded,className:`text-center`},{label:W7.failed,className:`text-center`},{label:W7.duration,className:`text-center`},...e?yyi:[],{label:W7.review,className:`text-center`},{label:W7.date,sortKey:`createdAt`}],xyi=e=>e.stopPropagation();function Syi({experiment:e,rowProps:t,onSelect:n,featured:r,onDelete:i,leadingCell:a,children:o}){let s=a?2:void 0,{paths:c,Link:l}=_l(),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:xyi,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)(Sc,{className:`size-4`})})})]})}function Cyi({experiments:e,datasets:t,reviewByExperiment:n,metricsByExperiment:r,isLoading:i,search:a=``,statusFilter:o=`all`,datasetFilter:s=`all`,selection:c,onSelectExperiment:l,selectedExperimentId:u,keyboardGlobal:d=!0,isFetchingNextPage:f,hasNextPage:p,setEndOfListElement:m,sort:h,onSortChange:g}){let _=(0,G.useMemo)(()=>{let e=new Map;return t?.forEach(t=>e.set(t.id,t.name)),e},[t]),v=(0,G.useMemo)(()=>h?e:[...e].sort((e,t)=>{let n=e.createdAt?new Date(e.createdAt).getTime():0;return(t.createdAt?new Date(t.createdAt).getTime():0)-n}),[e,h]),y=(0,G.useMemo)(()=>{let e=a.toLowerCase();return v.filter(t=>{let n=t.datasetId?_.get(t.datasetId)??``:``,r=!e||t.id.toLowerCase().includes(e)||(t.name??``).toLowerCase().includes(e)||n.toLowerCase().includes(e)||(t.targetId??``).toLowerCase().includes(e),i=o===`all`||t.status===o,a=s===`all`||t.datasetId===s;return r&&i&&a})},[v,a,_,o,s]),{containerRef:b,getRowProps:x}=_Q({count:y.length,global:d}),[S,C]=(0,G.useState)(null),w=r!==void 0,T=w?vyi:_yi;if(i)return(0,K.jsx)(NU,{columns:T});let E=(c?.selectedExperimentIds.length??0)===0||y.length===0?!1:y.every(e=>c?.selectedExperimentIds.includes(e.id))?!0:`indeterminate`,D=c?`auto ${T}`:T,O=byi(w).map(e=>e.sortKey&&g?(0,K.jsx)(Z.SortableTopCell,{className:e.className,sortKey:e.sortKey,sort:h?.key===e.sortKey?h.direction:void 0,onSortChange:g,children:e.label},e.label):(0,K.jsx)(Z.TopCell,{className:e.className,children:e.label},e.label));return(0,K.jsxs)(Z,{columns:D,scrollRef:b,children:[(0,K.jsx)(Z.Top,{hasLeadingCell:c!==void 0,children:c?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Z.TopSelectCell,{checked:E,onToggle:()=>c.onToggleAll(y.map(e=>e.id)),"aria-label":`Select all experiments`}),(0,K.jsxs)(Z.TopCells,{colStart:2,children:[O,(0,K.jsx)(Z.TopCell,{"aria-hidden":!0,children:null})]})]}):(0,K.jsxs)(K.Fragment,{children:[O,(0,K.jsx)(Z.TopCell,{"aria-hidden":!0,children:null})]})}),y.length===0&&!p?(0,K.jsx)(Z.NoMatch,{message:`No experiments match your filters`}):null,y.map((e,t)=>{let i=e.datasetId?_.get(e.datasetId)??hU(e.datasetId)??e.datasetId:`—`,a=c?.selectedExperimentIds.indexOf(e.id)??-1,o=a!==-1,s=!o&&c?.comparableDatasetId!==void 0&&e.datasetId!==c.comparableDatasetId,d=(0,K.jsx)(uyi,{experiment:e,datasetName:i,review:n?.get(e.id),showUsage:w,metrics:r?.get(e.id),selectionRole:o?{label:U7(a),variant:a===0?Jvi.baseline:Jvi.contender}:void 0});return(0,K.jsx)(Syi,{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)(Yvi,{open:!0,onOpenChange:e=>{e||C(null)},experimentId:S.id,experimentName:S.name??void 0})]})}var wyi=[{value:`all`,label:`All statuses`},{value:`completed`,label:`Completed`},{value:`running`,label:`Running`},{value:`failed`,label:`Failed`},{value:`pending`,label:`Pending`}];function Tyi(e){return[{value:`all`,label:`All datasets`},...(e??[]).map(e=>({value:e.id,label:e.name}))]}var Eyi=({onRunExperiment:e})=>(0,K.jsx)(RC,{titleSlot:`No Experiments yet`,descriptionSlot:(0,K.jsxs)(K.Fragment,{children:[`Run an experiment from a dataset to evaluate `,(0,K.jsx)(`br`,{}),`your agents and workflows.`]}),actionSlot:(0,K.jsxs)(`div`,{className:`flex flex-col items-center gap-2`,children:[e&&(0,K.jsx)(X,{variant:`primary`,onClick:e,icon:(0,K.jsx)(Uo,{}),children:`New experiment`}),(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/docs/evals/experiments`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(Br,{}),children:`Experiments documentation`})]}),variant:`fill`}),Dyi=e=>`${e} experiment${e===1?``:`s`}`;function Oyi({experimentIds:e,onDeleted:t}){let[n,r]=(0,G.useState)(!1),[i,a]=(0,G.useState)(!1),{deleteExperiment:o}=zP(),s=e.length;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(X,{size:`sm`,variant:`destructive-ghost`,disabled:s===0,icon:(0,K.jsx)(Sc,{}),onClick:()=>r(!0),children:`Delete`}),(0,K.jsx)(aP,{open:n,onOpenChange:r,children:(0,K.jsxs)(aP.Content,{children:[(0,K.jsxs)(aP.Header,{children:[(0,K.jsxs)(aP.Title,{children:[`Delete `,Dyi(s)]}),(0,K.jsxs)(aP.Description,{children:[s===1?`Its`:`Their`,` results and traces will be deleted too. This can't be undone.`]})]}),(0,K.jsxs)(aP.Footer,{children:[(0,K.jsx)(aP.Cancel,{children:`Cancel`}),(0,K.jsx)(X,{icon:(0,K.jsx)(Sc,{}),variant:`destructive`,onClick:async()=>{a(!0);let n=await Promise.allSettled(e.map(e=>o.mutateAsync(e)));a(!1);let i=n.filter(e=>e.status===`rejected`).length;i>0?UC.error(`Failed to delete ${i} of ${Dyi(s)}`):(UC.success(`Deleted ${Dyi(s)}`),r(!1),t())},disabled:i,children:i?`Deleting…`:s===1?`Delete experiment`:`Delete experiments`})]})]})})]})}function kyi({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)(Hc,{}),onClick:t,tooltip:a?void 0:`Clear selection`,className:`mr-2 tabular-nums`,children:[i,` selected`]}),(0,K.jsx)(Oyi,{experimentIds:e,onDeleted:t}),r?(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{render:(0,K.jsx)(`span`,{className:`cursor-not-allowed`,tabIndex:0}),children:(0,K.jsx)(X,{size:`sm`,disabled:!0,tabIndex:-1,icon:(0,K.jsx)(Ni,{}),children:`Compare`})}),(0,K.jsx)(CC,{children:r})]}):(0,K.jsx)(X,{size:`sm`,onClick:n,icon:(0,K.jsx)(Ni,{}),children:`Compare`})]})}function Ayi({dataset:e}){return(0,K.jsx)(T,{as:`p`,variant:`body-sm`,tone:`muted`,role:`note`,"aria-label":`Comparable experiments`,className:`min-w-0 truncate`,children:e?(0,K.jsxs)(K.Fragment,{children:[`Comparable experiments share dataset`,` `,(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`ink`,title:e.id,children:e.name})]}):`Select an experiment to pick the dataset to compare`})}var jyi=`search`,Myi=`status`,Nyi=`dataset`,K7=`all`,Pyi=[{id:`contains`,label:`contains`},{id:`is`,label:`is`}],Fyi=wyi.filter(e=>e.value!==K7),Iyi=({search:e,statusFilter:t,datasetFilter:n,targetType:r,targetId:i})=>{let a=[];return e&&a.push(w7(jyi,e,`contains`)),a.push(...Bfi({targetType:r,targetId:i})),t!==K7&&a.push(w7(Myi,t)),n!==K7&&a.push(w7(Nyi,n)),a},Lyi=e=>({...Vfi(e),search:T7(e,jyi),statusFilter:T7(e,Myi)||K7,datasetFilter:T7(e,Nyi)||K7});function Ryi({search:e,statusFilter:t,datasetFilter:n,targetType:r,targetId:i,datasetOptions:a,onChange:o}){let s=Hfi(r),c=(0,G.useMemo)(()=>[{id:jyi,label:`Search`,icon:_s,search:!0,operators:[`contains`]},...s,{id:Myi,label:`Status`,icon:Wn,color:_F(`orange`),operators:[`is`],strict:!0,suggestions:Fyi},{id:Nyi,label:`Dataset`,icon:Tr,color:_F(`blue`),operators:[`is`],strict:!0,suggestions:a.filter(e=>e.value!==K7)}],[s,a]),l=(0,G.useMemo)(()=>Iyi({search:e,statusFilter:t,datasetFilter:n,targetType:r,targetId:i}),[e,t,n,r,i]);return(0,K.jsxs)(p5,{fields:c,operators:Pyi,value:l,onValueChange:e=>o(Lyi(e)),createItemId:e=>e,"aria-label":`Experiments filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(p5.Chips,{}),(0,K.jsx)(p5.Input,{placeholder:`Filter experiments`})]})}function zyi({search:e,statusFilter:t,datasetFilter:n,datasetOptions:r,targetType:i,targetId:a,onFiltersChange:o,selection:s,comparableDataset:c}){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(jq,{children:(0,K.jsx)(jq.Start,{children:(0,K.jsx)(Ryi,{search:e,statusFilter:t,datasetFilter:n,datasetOptions:r,targetType:i,targetId:a,onChange:o})})}),(0,K.jsxs)(jq,{children:[(0,K.jsx)(jq.Start,{className:`self-end`,children:(0,K.jsx)(Ayi,{dataset:c})}),(0,K.jsx)(jq.End,{children:(0,K.jsx)(kyi,{...s})})]})]})}var Byi={present:!1,targetType:null,output:null,metadata:null,comment:null,error:null,startedAt:null,completedAt:null,scores:[]},Vyi=e=>e?e instanceof Date?e.toISOString():e:null,Hyi=e=>{let t=new Map;for(let n of e??[])t.set(n.itemId,n);return t},Uyi=(e,t,n,r)=>{if(!e)return Byi;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:Vyi(t?.startedAt),completedAt:Vyi(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}},Wyi=(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 q7(e){return!e.startedAt||!e.completedAt?null:new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime()}function Gyi(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 Kyi=(e,t)=>{let n=Gyi(e),r=Gyi(t);return n!=null&&r!=null?r-n:void 0},qyi=(e,t)=>{let n=q7(e),r=q7(t);return n!=null&&r!=null?r-n:null},Jyi=(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},Yyi=(e,t)=>{let n=V7(e.usage),r=V7(t.usage);return n!==void 0&&r!==void 0?r-n:void 0},Xyi=({comparison:e,experimentIds:t,resultsById:n,scoresById:r,usageById:i})=>{if(!e)return[];let a=new Map(t.map(e=>[e,Hyi(n?.[e])]));return e.items.map(e=>{let n=t.map(t=>Uyi(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:Wyi(o,e),durationDeltaMs:n===0?null:qyi(o,e),costDelta:n===0?void 0:Jyi(o,e),tokenDelta:n===0?void 0:Yyi(o,e),averageScoreDelta:n===0?void 0:Kyi(o,e)}))}})};function Zyi({datasetId:e,itemId:t,onClose:n}){let{data:r,isLoading:i}=oIt({datasetId:e,itemId:t??``,queryOptions:{enabled:!!e&&!!t}});return(0,K.jsx)(Cvi,{datasetId:e,item:r,itemId:t,fallback:i?(0,K.jsx)(m$.LoadingData,{}):(0,K.jsxs)(m$.NoData,{children:[`Dataset item "`,t,`" not found.`]}),items:r?[r]:[],onItemChange:()=>{},onClose:n})}function Qyi({label:e,value:t,expanded:n,onExpandedChange:r}){return t==null?null:(0,K.jsx)(I7,{title:e,framed:!0,expanded:n,onExpandedChange:r,children:(0,K.jsx)(F7,{value:t})})}function $yi({usage:e,showUsage:t,durationMs:n,costDelta:r,tokenDelta:i,durationDeltaMs:a,averageScore:o,scores:s}){let c=e?.costUnit,l=t?[{id:`cost`,icon:(0,K.jsx)(mr,{}),label:`Cost`,value:z7(e?.estimatedCost,c),rawValue:e?.estimatedCost,delta:r??null,formatDelta:$_i(c),higherIsBetter:!1}]:[],u=t?[{id:`tokens`,icon:(0,K.jsx)(Gi,{}),label:`Tokens`,value:B7(V7(e)),rawValue:V7(e),delta:i??null,formatDelta:B7,higherIsBetter:!1}]:[],d=n==null?[]:[{id:`duration`,icon:(0,K.jsx)(lr,{}),label:`Duration`,value:xw(n)??`-`,rawValue:n,delta:a??null,formatDelta:Y_i,higherIsBetter:!1}],f=o?[{id:`avg-score`,icon:(0,K.jsx)(Di,{}),label:`Avg score`,value:R7(o.value),rawValue:o.value,delta:o.delta??null}]:[];return[...l,...d,...f,...u,...s.map(e=>({id:`scorer:${e.scorerId}`,icon:(0,K.jsx)(iF,{}),label:e.label??(0,K.jsx)(ygi,{scorerId:e.scorerId}),value:e.reason?.trim()?(0,K.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[R7(e.value),(0,K.jsx)(tvi,{scorerId:e.scorerId,reason:e.reason})]}):R7(e.value),rawValue:e.value,delta:e.delta??null}))]}function ebi({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 tbi(e){return(0,G.useSyncExternalStore)(e.subscribe,e.read,()=>e.defaultValue)}var nbi={cost:`cost`,"total-cost":`cost`,duration:`duration`,"avg-duration":`duration`,"avg-score":`average`,tokens:`tokens`,"total-tokens":`tokens`,errors:`errors`};function rbi(e){return e.startsWith(`scorer:`)?e:nbi[e]}var ibi=[],abi=ebi({key:`mastra:experiments-compare:hidden-metrics`,defaultValue:ibi,parse:e=>Mp(q()).parse(e)});function obi(){let e=tbi(abi);return{isHidden:t=>e.includes(t),isMetricVisible:t=>{let n=rbi(t);return n===void 0||!e.includes(n)},toggle:t=>abi.write(e.includes(t)?e.filter(e=>e!==t):[...e,t]),reset:()=>abi.write(ibi)}}function sbi(e){return e==null?`-`:typeof e==`string`?e:JSON.stringify(e,null,2)}function cbi(e,t){return $yi({usage:e.usage,showUsage:t,durationMs:q7(e),costDelta:e.costDelta,tokenDelta:e.tokenDelta,durationDeltaMs:e.durationDeltaMs,averageScore:e.scores.length>0?{value:Gyi(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 lbi({column:e,isLoading:t,showUsage:n=!1,outputExpanded:r,onOutputExpandedChange:i,onShowTrace:a}){let{isMetricVisible:o}=obi();if(t)return(0,K.jsx)(`div`,{className:`flex h-32 items-center justify-center`,children:(0,K.jsx)(Qc,{})});if(!e.present)return(0,K.jsx)(T,{tone:`muted`,className:`py-5 text-center`,children:`Not present in this experiment`});let s=sbi(e.output),c=H_i(e),l=L7(e),u=q_i(e),d=J_i(e),f=cbi(e,n).filter(e=>o(e.id)),{traceId:p}=e,m=p&&a?(0,K.jsx)(X,{size:`icon-sm`,variant:`ghost`,tooltip:`View trace`,"aria-label":`View trace`,onClick:()=>a(p),children:(0,K.jsx)(oF,{})}):void 0,h=f.length>0,g=e=>(0,K.jsxs)(K.Fragment,{children:[!h&&m,(0,K.jsx)(jw,{content:e,variant:`ghost`})]});return(0,K.jsxs)(`div`,{className:xgi,children:[h&&(0,K.jsx)(I7,{title:`Metrics`,collapsible:!1,actions:m,children:(0,K.jsx)(bgi,{metrics:f})}),l?(0,K.jsx)(I7,{title:`Error`,tone:`negative`,framed:!0,actions:g(l),children:(0,K.jsx)(T,{tone:`muted`,className:`p-3 break-words`,children:l})}):(0,K.jsx)(I7,{title:`Output`,framed:!0,actions:g(s),expanded:r,onExpandedChange:i,children:d?(0,K.jsx)(T,{tone:`muted`,className:`p-3 break-words`,children:d}):(0,K.jsx)(F7,{value:c??e.output})}),u.length>0&&(0,K.jsx)(I7,{title:`Tool calls (${u.length})`,children:(0,K.jsx)(jri,{toolCalls:u})}),e.comment&&(0,K.jsx)(I7,{title:`Comment`,framed:!0,children:(0,K.jsx)(F7,{value:e.comment})}),e.metadata&&Object.keys(e.metadata).length>0&&(0,K.jsx)(I7,{title:`Metadata`,framed:!0,actions:(0,K.jsx)(jw,{content:sbi(e.metadata),variant:`ghost`}),children:(0,K.jsx)(F7,{value:e.metadata})})]})}function ubi({experiment:e,open:t,onOpenChange:n}){let[r,i]=(0,G.useState)(e.name??``),[a,o]=(0,G.useState)(e.description??``),{updateExperiment:s}=zP(),c=!!r.trim();return(0,K.jsx)(_E,{open:t,onOpenChange:n,pending:s.isPending,children:(0,K.jsxs)(vE,{children:[(0,K.jsx)(yE,{children:(0,K.jsx)(SE,{children:`Rename Experiment`})}),(0,K.jsxs)(uU,{onSubmit:async t=>{if(t.preventDefault(),c&&!s.isPending&&e.datasetId)try{await s.mutateAsync({datasetId:e.datasetId,experimentId:e.id,name:r.trim(),description:a.trim()}),UC.success(`Experiment renamed`),n(!1)}catch(e){UC.error(`Failed to rename experiment: ${e instanceof Error?e.message:`Unknown error`}`)}},children:[(0,K.jsxs)(xE,{children:[(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{required:!0,children:`Name`}),(0,K.jsx)(ZM,{required:!0,value:r,onChange:e=>i(e.target.value),placeholder:`Enter experiment name`,autoFocus:!0})]}),(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{children:`Description`}),(0,K.jsx)(ZM,{value:a,onChange:e=>o(e.target.value),placeholder:`Enter experiment description (optional)`})]})]}),(0,K.jsxs)(bE,{children:[(0,K.jsx)(wE,{children:`Cancel`}),(0,K.jsx)(gE,{type:`submit`,disabled:!c,children:s.isPending?`Saving...`:`Save`})]})]})]})})}function dbi({datasetId:e,version:t,differsFromBaseline:n}){let{Link:r,paths:i}=_l();return(0,K.jsxs)(`span`,{className:m(`flex min-w-0 items-center gap-2`,n&&`text-warning-foreground`),children:[n&&(0,K.jsx)(`span`,{className:`min-w-0 truncate`,children:`differs from baseline`}),(0,K.jsxs)(r,{href:`${i.datasetLink(e)}?version=${t}`,"aria-label":`Open dataset v${t}`,className:`shrink-0 hover:underline`,children:[`v`,t]})]})}function fbi({role:e,label:t,experiment:n,onSetBaseline:r}){let{Link:i}=_l(),[a,o]=(0,G.useState)(!1),s=n?hU(n.id)??n.id:null,c=!!n?.datasetId;return(0,K.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[n&&(0,K.jsxs)(mD,{children:[(0,K.jsx)(mD.Trigger,{render:(0,K.jsxs)(X,{size:`sm`,className:`max-w-full min-w-0`,children:[(0,K.jsx)(`span`,{className:`min-w-0 truncate`,children:n.name||s}),(0,K.jsx)(h,{"aria-hidden":!0})]})}),(0,K.jsxs)(mD.Content,{align:`start`,className:`min-w-48`,children:[(0,K.jsxs)(mD.Item,{render:(0,K.jsx)(i,{href:`/experiments/${n.id}`}),children:[(0,K.jsx)(ua,{}),` View experiment`]}),c&&(0,K.jsxs)(mD.Item,{onSelect:()=>o(!0),children:[(0,K.jsx)(Ro,{}),` Rename experiment`]})]})]}),n&&a&&(0,K.jsx)(ubi,{experiment:n,open:!0,onOpenChange:o}),(0,K.jsx)(`div`,{className:`ml-auto shrink-0`,children:r?(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{render:(0,K.jsx)(`button`,{type:`button`,"aria-label":`Set as baseline`,onClick:r,className:m(`cursor-pointer rounded-[7px] hover:brightness-110`,_)}),children:(0,K.jsx)(bw,{variant:Jvi[e],size:`md`,icon:(0,K.jsx)(qs,{}),children:t})}),(0,K.jsx)(CC,{children:`Set as baseline`})]}):(0,K.jsx)(bw,{variant:Jvi[e],size:`md`,icon:e===`baseline`?(0,K.jsx)(qs,{className:`fill-current`}):(0,K.jsx)(qs,{}),children:t})})]})}function pbi({role:e,experiment:t,summary:n,metrics:r,baselineMetrics:i,versionMismatch:a,showUsage:o=!1}){let{Link:s,paths:c}=_l(),{isMetricVisible:l}=obi(),u=t?.createdAt?new Date(t.createdAt):null,d=e===`contender`,f=(e,t)=>d?X_i(e,t):null,p=t?[...t.targetId?[{id:`target`,icon:t.targetType===`agent`?(0,K.jsx)(tF,{}):(0,K.jsx)(tc,{}),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)(as,{}),label:`Dataset version`,value:(0,K.jsx)(dbi,{datasetId:t.datasetId,version:t.datasetVersion,differsFromBaseline:a}),delta:null}]:[],...u?[{id:`created-at`,icon:(0,K.jsx)(Fn,{}),label:`Created`,value:Fw(u,`date`),delta:null}]:[]]:[],m=o?r:void 0,h=[...m?[{id:`total-cost`,icon:(0,K.jsx)(mr,{}),label:`Total cost`,value:z7(m.cost,m.costUnit),rawValue:m.cost,delta:m.costUnit===i?.costUnit?f(m.cost,i?.cost):null,formatDelta:$_i(m.costUnit),higherIsBetter:!1,emphasis:!0}]:[],...r?[{id:`avg-duration`,icon:(0,K.jsx)(lr,{}),label:`Avg duration`,value:xw(r.averageDurationMs)??`-`,rawValue:r.averageDurationMs,delta:f(r.averageDurationMs,i?.averageDurationMs),formatDelta:Y_i,higherIsBetter:!1,emphasis:!0}]:[],...r&&n&&n.length>0?[{id:`avg-score`,icon:(0,K.jsx)(Di,{}),label:`Avg score`,value:R7(r.averageScore),rawValue:r.averageScore,delta:f(r.averageScore,i?.averageScore),emphasis:!0}]:[],...m?[{id:`total-tokens`,icon:(0,K.jsx)(Gi,{}),label:`Total tokens`,value:B7(m.tokens),rawValue:m.tokens,delta:f(m.tokens,i?.tokens),formatDelta:B7,higherIsBetter:!1}]:[],...p,...r?[{id:`errors`,icon:(0,K.jsx)(Un,{}),label:`Errors`,value:String(r.errorCount),delta:f(r.errorCount,i?.errorCount),formatDelta:String,higherIsBetter:!1}]:[],...(n??[]).map(({scorerId:e,average:t,delta:n})=>({id:`scorer:${e}`,icon:(0,K.jsx)(iF,{}),label:(0,K.jsx)(ygi,{scorerId:e}),value:R7(t),rawValue:t,delta:d?n:null}))].filter(e=>l(e.id));return h.length===0?null:(0,K.jsx)(I7,{title:`Summary`,collapsible:!1,children:(0,K.jsx)(bgi,{metrics:h})})}function mbi(e){return(0,K.jsx)(msi,{...e,headerActionsSlot:e.traceId?(0,K.jsx)(zui,{traceId:e.traceId,spans:e.spans},e.traceId):void 0})}function hbi({traceId:e,onClose:t,withQueryTrace:n,withFeedback:r}){let{navigate:i}=_l(),[a,o]=(0,G.useState)(),{data:s,isLoading:c}=O_i({traceId:e,queryOptions:{enabled:!!e}}),l=s?.spans,u=l?.find(e=>!e.parentSpanId),{data:d}=S8({traceId:e,queryOptions:{enabled:r&&!!e}}),{data:f}=B$r({traceId:e,spanId:a,queryOptions:{enabled:r&&!!e&&!!a}}),{data:p}=$P({traceId:e,spanId:u?.spanId,page:0,queryOptions:{enabled:!!e&&!!u?.spanId}});return(0,K.jsx)(mbi,{size:`wide`,traceId:e,spans:l,isLoadingSpans:c,selectedSpanId:a??null,onClose:()=>{o(void 0),t()},onSpanSelect:o,showUnavailableFeaturesMsg:!1,traceHref:e?`/traces?traceId=${encodeURIComponent(e)}`:void 0,anchorSpanId:u?.spanId,withQueryTrace:n,withFeedback:r,onOpenScore:(e,t)=>i(kq(e,t)),feedbackTabBadge:r?d?.pagination?.total??void 0:void 0,feedbackTabSlot:r?({traceId:e})=>(0,K.jsx)(z5,{traceId:e}):void 0,scoresTabBadge:p?.pagination?.total??void 0,scoresTabSlot:({traceId:e,rootSpanId:t})=>t?(0,K.jsx)(TVr,{traceId:e,spanId:t,onScoreSelect:t=>i(kq(e,t))}):null,spanFeedbackTabBadge:r?f?.pagination?.total??void 0:void 0,spanFeedbackTabSlot:r?({traceId:e,spanId:t})=>e&&t?(0,K.jsx)(Sni,{traceId:e,spanId:t},`${e}:${t}`):null:void 0})}var J7=`min-w-0 px-4 py-3`,gbi=`grid grid-cols-[minmax(22rem,26rem)_repeat(var(--compare-cols),minmax(32rem,1fr))] divide-x divide-border border-border`,_bi=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,vbi=()=>!!window.getSelection()?.toString(),ybi=e=>e!=null,bbi=e=>e.length>0?e.reduce((e,t)=>e+t,0)/e.length:null,xbi=(e,t,n)=>bbi(e.map(e=>e.sides[t]?.scores.find(e=>e.scorerId===n)?.value??null).filter(ybi)),Sbi=(e,t)=>{let n=e.map(e=>e.sides[t]).filter(e=>e?.present);return{errorCount:n.filter(e=>e.error).length,averageScore:bbi(n.flatMap(e=>e.scores.map(e=>e.value)).filter(ybi)),averageDurationMs:bbi(n.map(q7).filter(ybi))}};function Cbi({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=i5(),u=e=>{c(void 0),o(e)},d=e=>{o(void 0),c(e)},{data:f,isLoading:p,error:h}=fIt({datasetId:e,experimentIds:i,baselineId:t,queryOptions:{enabled:!!e&&!!t&&n.length>0}}),{data:g,isLoading:_}=yIt({datasetId:e,experimentIds:i}),v=(0,G.useMemo)(()=>i.map(e=>({id:e,status:g[e]?.status})),[i,g]),{data:y,isLoading:b}=xIt({datasetId:e,experiments:v}),{data:x}=SIt({experiments:v}),{supportsMetrics:S,isLoading:C}=x7(),{data:w,isLoading:E}=E_i({experiments:v,supportsMetrics:S}),D=(0,G.useMemo)(()=>Xyi({comparison:f,experimentIds:i,resultsById:y,scoresById:x,usageById:w}),[f,i,y,x,w]),O=(0,G.useMemo)(()=>{let e=[...new Set(D.flatMap(e=>e.sides.flatMap(e=>e.scores.map(e=>e.scorerId))))].sort();return i.map((t,n)=>e.map(e=>{let t=xbi(D,n,e),r=xbi(D,0,e);return{scorerId:e,average:t,delta:n>0&&t!=null&&r!=null?t-r:null}}))},[D,i]),k=(0,G.useMemo)(()=>i.map((e,t)=>{let n=w[e]?.summary;return{...Sbi(D,t),cost:n?.estimatedCost,costUnit:n?.costUnit,tokens:V7(n)}}),[D,i,w]);if(p||_||C||E)return(0,K.jsx)(`div`,{className:`pointer-events-none fixed inset-0 flex items-center justify-center`,children:(0,K.jsx)(Qc,{})});if(h)return(0,K.jsx)(EA,{variant:`warning`,title:`Error loading comparison`,children:(0,K.jsx)(EA.Message,{children:h instanceof Error?h.message:`Unknown error`})});if(!f||f.items.length===0)return(0,K.jsx)(T,{as:`p`,variant:`body`,tone:`muted`,className:`py-5 text-center`,children:`No comparison data`});let A=g[t];return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{role:`table`,"aria-label":`Experiments comparison`,className:`grid min-w-[calc(22rem_+_var(--compare-cols)_*_32rem)]`,style:{"--compare-cols":i.length},children:[(0,K.jsxs)(`div`,{role:`row`,className:m(gbi,`sticky top-0 z-20 bg-background`),children:[(0,K.jsx)(`div`,{role:`columnheader`,"aria-label":`Items`,className:J7}),i.map((e,t)=>(0,K.jsx)(`div`,{role:`columnheader`,"aria-label":U7(t),className:m(J7,`border-b`),children:(0,K.jsx)(fbi,{role:t===0?`baseline`:`contender`,label:U7(t),experiment:g[e]??void 0,onSetBaseline:t>0&&r?()=>r(e):void 0})},e))]}),(0,K.jsxs)(`div`,{role:`row`,"aria-label":`Summary`,className:m(gbi,`border-b`),children:[(0,K.jsx)(`div`,{role:`cell`,"aria-label":`Items`,className:J7}),i.map((e,t)=>{let n=g[e]??void 0;return(0,K.jsx)(`div`,{role:`cell`,"aria-label":U7(t),className:J7,children:(0,K.jsx)(pbi,{role:t===0?`baseline`:`contender`,experiment:n,summary:O[t],metrics:b?void 0:k[t],baselineMetrics:b?void 0:k[0],versionMismatch:t>0&&n&&A?n?.datasetVersion!==A?.datasetVersion:void 0,showUsage:S})},e)})]}),D.map(e=>(0,K.jsx)(wbi,{row:e,isLoading:b,showUsage:S,onOpen:()=>u(e.itemId),onShowTrace:d},e.itemId))]}),(0,K.jsx)(Zyi,{datasetId:e,itemId:a,onClose:()=>o(void 0)}),(0,K.jsx)(hbi,{traceId:s,onClose:()=>c(void 0),withQueryTrace:l.enabled,withFeedback:l.enabled})]})}function wbi({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=>{_bi(e)||vbi()||r()},onKeyDown:e=>{e.target!==e.currentTarget||e.key!==`Enter`&&e.key!==` `||(e.preventDefault(),r())},className:m(gbi,`cursor-pointer border-b transition-colors duration-normal ease-out-custom hover:bg-fill-subtle`,U),children:[(0,K.jsxs)(`div`,{role:`cell`,className:m(J7,xgi),children:[(0,K.jsx)(Qyi,{label:`Input`,value:e.input,...s(`input`)}),(0,K.jsx)(Qyi,{label:`Ground truth`,value:e.groundTruth,...s(`groundTruth`)})]}),e.sides.map((e,r)=>(0,K.jsx)(`div`,{role:`cell`,"aria-label":U7(r),className:J7,children:(0,K.jsx)(lbi,{column:e,isLoading:t,showUsage:n,outputExpanded:c.expanded,onOutputExpandedChange:c.onExpandedChange,onShowTrace:i})},e.experimentId))]})}function Tbi(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 Y7=[sF(`/experiments`)],Ebi=[`createdAt`,`status`],Dbi=new Map;function Obi(){let[e,t]=(0,G.useState)(``),[n,r]=(0,G.useState)(`all`),[i,a]=(0,G.useState)(!1),[o,s]=(0,G.useState)([]),c=kb(),[l,u]=Hb(),{sort:d,onSortChange:f}=l7({searchParams:l,setSearchParams:u,allowedKeys:Ebi}),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}=Qfi(),_=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(D7,e.targetType),r(O7,e.targetType===h?e.targetId:``),n},{replace:!0})},{data:v,isLoading:y,error:b}=BP(),{data:x,isLoading:S,error:C,isFetchingNextPage:w,hasNextPage:T,setEndOfListElement:E}=L_i({datasetId:m===`all`?void 0:m,target:{targetType:h,targetId:g},orderBy:p}),{data:D}=qvi(),{supportsMetrics:O}=x7(),k=(0,G.useMemo)(()=>v?.datasets??[],[v?.datasets]),A=(0,G.useMemo)(()=>x??[],[x]),j=(0,G.useMemo)(()=>Tyi(k),[k]),{data:M}=dIt({datasetIds:(0,G.useMemo)(()=>A.flatMap(e=>e.datasetId?[e.datasetId]:[]),[A])}),N=(0,G.useMemo)(()=>{let e=new Map(k.map(e=>[e.id,e]));return M?.forEach(t=>e.set(t.id,t)),[...e.values()]},[k,M]),{data:P}=I_i({experiments:A,supportsMetrics:O}),F=O?P??Dbi:void 0,I=(0,G.useMemo)(()=>Tbi(D),[D]),L=y||S,R=C||b,z=e=>{let t=new Set(A.map(e=>e.id));s(n=>{let r=n.filter(e=>t.has(e));return r.includes(e)?r.filter(t=>t!==e):r.length>=10?[...r.slice(0,9),e]:[...r,e]})},B=e=>{let t=new Map(A.map(e=>[e.id,e.datasetId])),n=t.get(e[0]);s(r=>r.length>0?[]:e.filter(e=>t.get(e)===n).slice(0,10))},{selectedIds:V,selectedDatasetIds:H}=(0,G.useMemo)(()=>{let e=new Map(A.map(e=>[e.id,e.datasetId])),t=o.filter(t=>e.has(t));return{selectedIds:t,selectedDatasetIds:new Set(t.map(t=>e.get(t)))}},[A,o]),ee=A.find(e=>e.id===V[0])?.datasetId??void 0,te=ee?{id:ee,name:N.find(e=>e.id===ee)?.name??ee}:void 0,U=V.length<2?`Select at least two experiments to compare`:H.size===1?void 0:`Only experiments from the same dataset can be compared`,W=()=>{if(V.length<2||U)return;let[e,...t]=V,[n]=H;if(!n)return;let r=new URLSearchParams({dataset:n,baseline:e});for(let e of t)r.append(`contender`,e);c(`/experiments/compare?${r.toString()}`)};if(R&&JP(R))return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Y7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(jU,{variant:`fill`})]});if(C&&YP(C))return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Y7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(AU,{variant:`fill`,resource:`experiments`})]});if(b&&YP(b))return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Y7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(AU,{variant:`fill`,resource:`datasets`})]});if(R)return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Y7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load experiments`,descriptionSlot:R.message})]});let ne=(0,K.jsx)(h_i,{open:i,onOpenChange:a,onSuccess:e=>void c(`/experiments/${e}`)});return A.length===0&&!L&&m===`all`&&!h?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Y7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(Eyi,{onRunExperiment:()=>a(!0)}),ne]}):(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Y7}),headerActions:(0,K.jsx)(X,{variant:`primary`,size:`sm`,icon:(0,K.jsx)(Uo,{}),onClick:()=>a(!0),children:`New experiment`}),actionRow:(0,K.jsx)(zyi,{search:e,statusFilter:n,datasetFilter:m,datasetOptions:j,targetType:h,targetId:g,onFiltersChange:_,selection:{selectedIds:V,onClearSelection:()=>s([]),onCompare:W,compareDisabledReason:U},comparableDataset:te}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(Cyi,{experiments:A,datasets:N,reviewByExperiment:I,metricsByExperiment:F,isLoading:L,search:e,statusFilter:n,datasetFilter:m,isFetchingNextPage:w,hasNextPage:T,setEndOfListElement:E,sort:d,onSortChange:f,selection:{selectedExperimentIds:V,onToggleSelection:z,onToggleAll:B,comparableDatasetId:ee}}),ne]})}var kbi={baseline:`bg-badge-purple-indicator`,contender:`bg-badge-blue-indicator`};function Abi({experimentId:e,name:t,role:n,className:r,trailing:i}){let{Link:a,paths:o}=_l(),s=t||e.slice(0,8);return(0,K.jsxs)(X,{render:(0,K.jsx)(a,{href:o.experimentLink(e)}),variant:`ghost`,size:`sm`,className:m(`max-w-48 min-w-0`,r),"aria-label":`Open experiment ${s}`,children:[n&&(0,K.jsx)(`span`,{"aria-hidden":`true`,className:m(`size-1.5 shrink-0 rounded-full`,kbi[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 jbi(){let[e]=Hb(),t=e.get(`dataset`)??void 0,n=e.get(`baseline`)??void 0;return{datasetId:t,baselineId:n,contenderIds:(0,G.useMemo)(()=>[...new Set(e.getAll(`contender`))].filter(e=>e&&e!==n).slice(0,9),[e,n])}}function Mbi(){let{datasetId:e,baselineId:t,contenderIds:n}=jbi();return{datasetId:e,experimentIds:e&&t&&n.length>0&&t?[t,...n]:[]}}function Nbi(){let{experimentIds:e}=Mbi();return e.length>0?`Comparing ${e.length} experiments`:`Comparing`}function Pbi(){let{datasetId:e,experimentIds:t}=Mbi(),{data:n}=yIt({datasetId:e??``,experimentIds:t});return t.length===0?null:(0,K.jsxs)(yZ,{children:[(0,K.jsx)(bZ,{delay:0,closeDelay:100,render:(0,K.jsx)(X,{type:`button`,variant:`ghost`,size:`icon-sm`,"aria-label":`Show compared experiments`,children:(0,K.jsx)(h,{})})}),(0,K.jsx)(xZ,{side:`bottom`,align:`end`,sideOffset:4,showArrow:!1,className:`w-72 p-1.5`,children:(0,K.jsx)(`ul`,{"aria-label":`Compared experiments`,className:`grid gap-0.5`,children:t.map((e,t)=>(0,K.jsx)(`li`,{className:`grid`,children:(0,K.jsx)(Abi,{className:`w-full max-w-none justify-start`,experimentId:e,name:n[e]?.name,role:t===0?`baseline`:`contender`,trailing:t===0&&(0,K.jsx)(bw,{variant:`purple`,size:`sm`,icon:(0,K.jsx)(qs,{className:`fill-current`}),children:`Baseline`})})},e))})})]})}function Fbi({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)(Abi,{experimentId:t}),n<e.length-2&&`,`]})]},t))}function Ibi({datasetId:e,baselineId:t,contenderIds:n}){let[,r]=Hb(),i=(0,G.useMemo)(()=>[t,...n],[t,n]),{data:a,isLoading:o,error:s}=yIt({datasetId:e,experimentIds:i});return s&&JP(s)?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Compare`}),(0,K.jsx)(jU,{variant:`fill`})]}):s&&YP(s)?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Compare`}),(0,K.jsx)(AU,{variant:`fill`,resource:`experiments`})]}):s&&!XP(s)?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Compare`}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load experiments`,descriptionSlot:s.message})]}):!o&&(s||i.some(e=>!a[e]))?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Compare`}),(0,K.jsx)(`div`,{className:`grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto`,children:(0,K.jsxs)(`div`,{className:`py-5 text-center text-muted-foreground`,children:[(0,K.jsxs)(T,{as:`p`,children:[`Experiments must belong to the same dataset (`,e,`) to be compared.`]}),(0,K.jsxs)(T,{className:`mt-2 flex items-center justify-center gap-2`,children:[`One of`,(0,K.jsx)(Fbi,{experimentIds:i}),`was not found in it.`]})]})})]}):(0,K.jsx)(`div`,{className:`h-full overflow-auto`,children:(0,K.jsxs)(`div`,{className:`grid w-full content-start`,children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Experiments comparison`}),(0,K.jsx)(Cbi,{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 Lbi(){let{datasetId:e,baselineId:t,contenderIds:n}=jbi();return!e||!t||n.length===0?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Compare`}),(0,K.jsx)(`div`,{className:`grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto`,children:(0,K.jsxs)(`div`,{className:`py-5 text-center text-muted-foreground`,children:[(0,K.jsx)(T,{as:`p`,children:`Select two to ten experiments to compare.`}),(0,K.jsxs)(T,{className:`mt-2`,children:[`Use the URL format: /experiments/compare?dataset=`,`{datasetId}`,`&baseline=`,`{experimentId}`,`&contender=`,`{experimentId}`,`&contender=`,`{experimentId}`]})]})})]}):(0,K.jsx)(Ibi,{datasetId:e,baselineId:t,contenderIds:n})}function Rbi(){let{datasetId:e}=jbi(),{Link:t,paths:n}=_l(),{data:r,isLoading:i}=VP({datasetId:e??``,queryOptions:{enabled:!!e}});if(!e||i)return null;let a=r?.name||e;return(0,K.jsx)(t,{href:n.datasetLink(e),"aria-label":`Open dataset ${a}`,className:m(`flex max-w-64 min-w-0 rounded-[7px] hover:brightness-110`,_),children:(0,K.jsx)(bw,{size:`md`,icon:(0,K.jsx)(Tr,{}),className:`max-w-full min-w-0`,children:(0,K.jsx)(`span`,{className:`min-w-0 truncate`,children:a})})})}var zbi=[{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 Bbi({datasetId:e,baselineId:t,contenderIds:n}){let{data:r}=fIt({datasetId:e,experimentIds:(0,G.useMemo)(()=>[t,...n],[t,n]),baselineId:t}),{supportsMetrics:i}=x7(),{isHidden:a,toggle:o,reset:s}=obi(),c=(0,G.useMemo)(()=>[...new Set((r?.items??[]).flatMap(e=>Object.values(e.results).flatMap(e=>e?Object.keys(e.scores):[])))].sort(),[r]),l=zbi.filter(e=>i||!e.usage);return(0,K.jsxs)(mD,{children:[(0,K.jsx)(mD.Trigger,{render:(0,K.jsx)(X,{variant:`ghost`,size:`md`,icon:(0,K.jsx)(vr,{"aria-hidden":!0}),children:`Metrics`})}),(0,K.jsxs)(mD.Content,{align:`end`,className:`min-w-56`,children:[(0,K.jsx)(mD.Label,{children:`Run metrics`}),l.map(e=>(0,K.jsx)(mD.CheckboxItem,{checked:!a(e.key),onCheckedChange:()=>o(e.key),children:e.label},e.key)),c.length>0&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(mD.Separator,{}),(0,K.jsx)(mD.Label,{children:`Scorers`}),c.map(e=>{let t=`scorer:${e}`;return(0,K.jsx)(mD.CheckboxItem,{checked:!a(t),onCheckedChange:()=>o(t),children:e},t)})]}),(0,K.jsx)(mD.Separator,{}),(0,K.jsx)(mD.Item,{onSelect:s,children:`Show all metrics`})]})]})}function Vbi(){let{datasetId:e,baselineId:t,contenderIds:n}=jbi();return(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[e&&t&&n.length>0&&(0,K.jsx)(Bbi,{datasetId:e,baselineId:t,contenderIds:n}),(0,K.jsx)(Rbi,{})]})}var Hbi=[sF(`/experiments`),{id:`experiments-compare`,Component:Nbi,Switcher:Pbi}];function Ubi(){return(0,K.jsx)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:Hbi}),headerActions:(0,K.jsx)(Vbi,{}),children:(0,K.jsx)(Lbi,{})})}function Wbi(e){let{data:t}=WP({experimentId:e.id,experimentStatus:e.status,queryOptions:{enabled:!!e.id}});return(0,G.useMemo)(()=>{if(e.scorerIds?.length)return e.scorerIds;if(!t)return[];let n=new Set;for(let e of Object.values(t))for(let t of e)n.add(t.scorerId);return[...n].sort()},[e.scorerIds,t])}var Gbi=[`agent`,`workflow`,`scorer`];function Kbi({experiment:e}){let[t,n]=(0,G.useState)(!1),r=kb(),{paths:i}=_l(),a=Wbi(e),o=Gbi.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)(Ho,{}),children:`Rerun`}),t&&(0,K.jsx)(h_i,{open:!0,onOpenChange:n,initialDatasetId:e.datasetId,initialDatasetVersion:e.datasetVersion??void 0,initialTargetType:o,initialTargetId:e.targetId,initialScorerIds:a,initialName:e.name??void 0,initialDescription:e.description??void 0,onSuccess:e=>void r(i.experimentLink(e))},a.join(`,`))]})}function qbi({experiment:e,onDeleteClick:t}){let[n,r]=(0,G.useState)(!1),i=!!e.datasetId;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Kbi,{experiment:e}),(i||!!t)&&(0,K.jsxs)(mD,{children:[(0,K.jsx)(mD.Trigger,{asChild:!0,children:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,"aria-label":`Experiment actions menu`,children:(0,K.jsx)(Ar,{})})}),(0,K.jsxs)(mD.Content,{align:`end`,className:`w-48`,children:[i&&(0,K.jsxs)(mD.Item,{onSelect:()=>r(!0),children:[(0,K.jsx)(Ro,{}),` Rename experiment`]}),t&&(0,K.jsxs)(mD.Item,{onSelect:t,variant:`destructive`,children:[(0,K.jsx)(Sc,{}),` Delete experiment`]})]})]}),n&&(0,K.jsx)(ubi,{experiment:e,open:!0,onOpenChange:r})]})}function Jbi(e){let{data:t,isLoading:n}=b8({traceId:e,queryOptions:{enabled:!!e}}),r=t?.spans.find(e=>!e.parentSpanId)?.entityType===`agent`,{supportsMetrics:i,isLoading:a}=x7(),o=r&&i,s=L$r({traceIds:e?[e]:[],enabled:o,autoRefetch:!1}),c=o&&(s.isLoading||s.isPlaceholderData);return{usage:e?s.data?.get(e):void 0,isLoading:!!e&&(n||a||c)}}var Ybi=`__create_tag__`;function Xbi({selectedResults:e,vocabulary:t,onAddTag:n,disabled:r,variant:i}){let[a,o]=(0,G.useState)(``),s=(0,G.useMemo)(()=>[...t].sort(),[t]),c=(0,G.useMemo)(()=>{if(e.length===0)return new Set;let[t,...n]=e;return new Set((t.tags??[]).filter(e=>n.every(t=>(t.tags??[]).includes(e))))},[e]),l=(0,G.useMemo)(()=>{let e=s.map(e=>({label:e,value:e,end:c.has(e)?(0,K.jsx)(Bn,{"data-testid":`tag-applied`,className:`size-3.5`}):void 0})),t=a.trim();return t.length>0&&!s.includes(t)?[{label:`Create "${t}"`,value:Ybi},...e]:e},[s,c,a]);return(0,K.jsx)(TP,{"data-testid":`experiment-results-tag-picker`,options:l,value:void 0,onValueChange:e=>{let t=e===Ybi?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 Zbi(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function Qbi({report:e}){let{served:t,unconsumed:n,liveCalls:r,failure:i}=e,a=[...t.map(e=>({outcome:`served`,toolName:e.toolName,args:e.args})),...r.map(e=>({outcome:`live`,toolName:e.toolName,args:e.args})),...n.map(e=>({outcome:`unconsumed`,toolName:e.toolName,args:e.args}))];return(0,K.jsxs)(`div`,{className:`grid gap-2`,"data-testid":`tool-mock-report`,children:[(0,K.jsx)(m$.SectionHeading,{icon:(0,K.jsx)(Bc,{}),children:`Tool Mocks`}),i&&(0,K.jsx)(EA,{variant:`destructive`,title:`Mock mismatch`,children:(0,K.jsxs)(EA.Message,{children:[(0,K.jsx)(`span`,{className:`block`,children:`Tool "${i.toolName}" was called with arguments that did not match an available mock (${i.code}).`}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`mt-1 block`,children:[`Called with: `,(0,K.jsx)(uZ,{children:Zbi(i.args)})]}),n.length>0&&(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`mt-1 block`,children:[`Unconsumed mocks: `,(0,K.jsx)(uZ,{children:n.map(e=>Zbi(e.args)).join(`, `)})]})]})}),(0,K.jsx)(`div`,{className:`divide-y divide-border rounded border border-border`,children:a.map((e,t)=>(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-2 px-3 py-1.5`,children:[(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`min-w-0 truncate`,children:[(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`muted`,font:`mono`,children:e.toolName}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,font:`mono`,className:`ml-2`,children:Zbi(e.args)})]}),(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`shrink-0 rounded px-2 py-0.5 ${$bi(e.outcome)}`,children:e.outcome})]},`${e.outcome}-${e.toolName}-${t}`))})]})}function $bi(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 exi({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)(txi,{result:e,onClose:i,...o}):t?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(m$.Header,{children:[(0,K.jsxs)(m$.Heading,{children:[`Experiment item`,(0,K.jsx)(m$.CopyId,{id:t})]}),(0,K.jsx)(m$.HeaderActions,{children:(0,K.jsx)(m$.CloseButton,{icon:`x`,onClick:i})})]}),n]}):null;return a===`inline`?c?(0,K.jsx)(m$,{variant:`inline`,title:s,children:c}):null:(0,K.jsx)(m$,{open:!!(e??t),onClose:i,title:s,depth:1,children:c})}function txi({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=ixi(e.input),g=ixi(e.output),_=H_i(e),v=q_i(e),y=J_i(e),b=c&&e.status!==`needs-review`&&e.status!==`complete`,x=Array.isArray(e.tags)?e.tags:[],S=(0,G.useMemo)(()=>[e],[e]),C=!!l||x.length>0,{Link:w}=_l(),E=m&&e.traceId?e.traceId:void 0,{data:D}=S8({traceId:E,queryOptions:{enabled:!!E}}),{usage:O,isLoading:k}=Jbi(e.traceId),A=k&&(e.targetType==null||e.targetType===`agent`),j=$yi({usage:O,showUsage:!!O||A,durationMs:q7(e),scores:[]}).map(e=>A&&(e.id===`cost`||e.id===`tokens`)?{...e,value:(0,K.jsx)(dw,{"aria-hidden":!0,className:`h-4 w-14`})}:e),M=typeof e.error==`string`&&e.error?e.error:L7(e),N=[...j,{id:`item-id`,icon:(0,K.jsx)(ui,{}),label:`Item Id`,value:(0,K.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,K.jsx)(`span`,{className:`font-mono`,title:e.itemId,children:hU(e.itemId)}),(0,K.jsx)(jw,{content:e.itemId,tooltip:`Copy item ID to clipboard`,variant:`link`})]}),delta:null},...e.createdAt?[{id:`created`,icon:(0,K.jsx)(Fn,{}),label:`Created`,value:Fw(e.createdAt,`date-time`),delta:null}]:[],...e.status?[{id:`status`,icon:(0,K.jsx)(bee,{}),label:`Status`,value:(0,K.jsx)(Wti,{status:e.status}),delta:null}]:[],...C?[{id:`tags`,icon:(0,K.jsx)(Qs,{}),label:`Tags`,value:(0,K.jsx)(rxi,{tags:x,selectedResults:S,onTagsChange:l,tagVocabulary:u,isUpdatingTags:d}),delta:null}]:[],...$yi({showUsage:!1,durationMs:null,scores:(t??[]).map(e=>({scorerId:e.scorerId,value:e.score,reason:e.reason,label:o?(0,K.jsx)(nxi,{scorerId:e.scorerId,featured:s===e.id,onClick:()=>o(e.id)}):void 0}))})],P=(0,K.jsx)(m$.Content,{children:(0,K.jsxs)(`div`,{className:xgi,children:[(0,K.jsx)(bgi,{metrics:N}),(0,K.jsx)(I7,{title:`Input`,framed:!0,actions:(0,K.jsx)(jw,{content:h}),children:(0,K.jsx)(F7,{value:e.input})}),e.groundTruth!=null&&(0,K.jsx)(I7,{title:`Ground Truth`,framed:!0,actions:(0,K.jsx)(jw,{content:ixi(e.groundTruth)}),children:(0,K.jsx)(F7,{value:e.groundTruth})}),M?(0,K.jsx)(I7,{title:`Error`,tone:`negative`,framed:!0,actions:(0,K.jsx)(jw,{content:M}),children:(0,K.jsx)(T,{tone:`muted`,className:`p-3 break-words`,children:M})}):(0,K.jsx)(I7,{title:`Output`,framed:!0,actions:(0,K.jsx)(jw,{content:g}),children:y?(0,K.jsx)(T,{tone:`muted`,className:`p-3 break-words`,children:y}):(0,K.jsx)(F7,{value:_??e.output})}),v.length>0&&(0,K.jsx)(I7,{title:`Tool calls (${v.length})`,children:(0,K.jsx)(jri,{toolCalls:v})}),e.toolMockReport&&(0,K.jsx)(Qbi,{report:e.toolMockReport})]})});return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(m$.Header,{children:[b&&(0,K.jsx)(X,{size:`sm`,variant:`primary`,onClick:()=>c(e.id),icon:(0,K.jsx)(or,{}),children:`Request review`}),p&&e.status===`needs-review`&&(0,K.jsx)(X,{size:`sm`,variant:`primary`,onClick:p,icon:(0,K.jsx)(Wn,{}),children:`Mark as reviewed`}),(0,K.jsxs)(m$.HeaderActions,{children:[f&&(0,K.jsx)(X,{size:`icon-sm`,variant:`ghost`,render:(0,K.jsx)(w,{href:f}),tooltip:`See experiment`,"aria-label":`See experiment`,children:(0,K.jsx)(mi,{})}),e.traceId&&a&&(0,K.jsx)(X,{size:`icon-sm`,variant:`ghost`,onClick:a,tooltip:`See trace`,"aria-label":`See trace`,children:(0,K.jsx)(oF,{})}),(0,K.jsx)(m$.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:`Go to previous result`,nextLabel:`Go to next result`}),(0,K.jsx)(m$.CloseButton,{icon:`x`,onClick:i})]})]}),E?(0,K.jsxs)(CA,{defaultTab:`details`,className:`grid h-full min-h-0 grid-rows-[auto_1fr]`,children:[(0,K.jsx)(m$.Header,{children:(0,K.jsxs)(SA,{variant:`pill-ghost`,size:`sm`,children:[(0,K.jsx)(wA,{value:`details`,children:`Details`}),(0,K.jsxs)(wA,{value:`feedback`,children:[`Feedback`,D?.pagination?.total!=null&&(0,K.jsxs)(K.Fragment,{children:[` (`,D.pagination.total,`)`]})]})]})}),(0,K.jsx)(TA,{value:`details`,flush:!0,children:P}),(0,K.jsx)(TA,{value:`feedback`,flush:!0,children:(0,K.jsx)(m$.Content,{children:m({traceId:E})})})]}):P]})}function nxi({scorerId:e,featured:t,onClick:n}){return(0,K.jsx)(`button`,{type:`button`,"aria-pressed":t,onClick:n,className:m(`min-w-0 cursor-pointer truncate hover:text-foreground hover:underline`,t&&`text-foreground`),children:e})}function rxi({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)(wfi,{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)(Hc,{className:`size-3`})})]},t)),n&&(0,K.jsx)(Xbi,{selectedResults:t,vocabulary:r,onAddTag:t=>n([...e,t]),disabled:i,variant:`ghost`})]})}function ixi(e){return e==null?`-`:typeof e==`string`?e:JSON.stringify(e,null,2)}function axi(e){let t=e.scorer;return t?.hasJudge===!1||t?.hasJudge!==!0&&!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function oxi({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:i}){return(0,K.jsx)(m$,{open:!!e,onClose:r,title:e?`Score ${e.scorerId}`:`Score`,depth:2,children:e&&(0,K.jsx)(sxi,{score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:i})})}function sxi({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:i}){let a=axi(e),o=a?`Not applicable (code-based scorer)`:`Step not configured`;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(m$.Header,{children:[(0,K.jsx)(m$.CloseButton,{onClick:r,tooltip:`Close score panel`}),(0,K.jsxs)(m$.Heading,{children:[`Score`,(0,K.jsx)(m$.CopyId,{id:e.scorerId})]}),(0,K.jsxs)(m$.HeaderActions,{children:[i&&e.traceId&&(0,K.jsx)(X,{size:`icon-sm`,variant:`ghost`,onClick:i,tooltip:`See trace`,"aria-label":`See trace`,children:(0,K.jsx)(oF,{})}),(n||t)&&(0,K.jsx)(m$.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:`Go to previous score`,nextLabel:`Go to next score`})]})]}),(0,K.jsx)(m$.Content,{children:(0,K.jsxs)(`div`,{className:`grid gap-3`,children:[(0,K.jsx)(m$.CodeSection,{title:`Score: ${e.score}`,icon:(0,K.jsx)(Di,{}),codeStr:e.reason||o,simplified:!0}),!a&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(m$.CodeSection,{title:`Preprocess Prompt`,icon:(0,K.jsx)(qo,{}),codeStr:e.preprocessPrompt||o,simplified:!0}),(0,K.jsx)(m$.CodeSection,{title:`Analyze Prompt`,icon:(0,K.jsx)(qo,{}),codeStr:e.analyzePrompt||o,simplified:!0}),(0,K.jsx)(m$.CodeSection,{title:`Generate Score Prompt`,icon:(0,K.jsx)(qo,{}),codeStr:e.generateScorePrompt||o,simplified:!0}),(0,K.jsx)(m$.CodeSection,{title:`Generate Reason Prompt`,icon:(0,K.jsx)(qo,{}),codeStr:e.generateReasonPrompt||o,simplified:!0})]})]})})]})}function cxi(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 lxi({result:e,scores:t,state:n,withQueryTrace:r,withFeedback:i,...a}){let o=cxi(t,e?.id),{navigate:s}=_l(),{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}=O_i({traceId:c,queryOptions:{enabled:!!c}}),x=y?.spans,S=x?.find(e=>!e.parentSpanId),{data:C}=S8({traceId:c??void 0,queryOptions:{enabled:i&&!!c}}),{data:w}=B$r({traceId:c??void 0,spanId:u,queryOptions:{enabled:i&&!!c&&!!u}}),{data:T}=$P({traceId:c??void 0,spanId:S?.spanId,page:0,queryOptions:{enabled:!!c&&!!S?.spanId}});return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(exi,{...a,result:e,scores:t,onScoreClick:h,featuredScoreId:f,onShowTrace:e?.traceId?()=>g(e.traceId):void 0,feedbackTabSlot:i?({traceId:e})=>(0,K.jsx)(z5,{traceId:e},e):void 0}),(0,K.jsx)(oxi,{score:m??void 0,onNext:_(),onPrevious:v(),onClose:()=>p(null),onShowTrace:m?()=>g(m.traceId):void 0}),(0,K.jsx)(mbi,{size:`wide`,depth:2,traceId:c??void 0,spans:x,isLoadingSpans:b,selectedSpanId:u??null,onClose:()=>{l(null),d(void 0)},onSpanSelect:d,showUnavailableFeaturesMsg:!1,traceHref:c?`/traces?traceId=${encodeURIComponent(c)}`:void 0,anchorSpanId:S?.spanId,withQueryTrace:r,withFeedback:i,onOpenScore:(e,t)=>s(kq(e,t)),feedbackTabBadge:i?C?.pagination?.total??void 0:void 0,feedbackTabSlot:i?({traceId:e})=>(0,K.jsx)(z5,{traceId:e}):void 0,scoresTabBadge:T?.pagination?.total??void 0,scoresTabSlot:({traceId:e,rootSpanId:n})=>n?(0,K.jsx)(TVr,{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)(Sni,{traceId:e,spanId:t},`${e}:${t}`):null:void 0})]})}function uxi({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}=B_i(),p=(0,G.useMemo)(()=>r?s.find(e=>e.itemId===r):void 0,[s,r]),{data:m}=WP({experimentId:i,experimentStatus:o,queryOptions:{enabled:!!i}}),{updateExperimentResult:h}=zP(),g=(0,G.useCallback)(async e=>{try{await h.mutateAsync({datasetId:a,experimentId:i,resultId:e,status:`needs-review`}),UC(`Result flagged for review`)}catch{UC.error(`Failed to flag result for review`)}},[a,i,h]),_=(0,G.useCallback)(async e=>{try{await h.mutateAsync({datasetId:a,experimentId:i,resultId:e,status:`complete`}),UC(`Result marked as reviewed`)}catch{UC.error(`Failed to complete result`)}},[a,i,h]),v=p?m?.[p.itemId]:void 0,y=cxi(v,p?.id);return(0,K.jsx)(lxi,{variant:n,result:p,itemId:r,fallback:c||l?(0,K.jsx)(m$.LoadingData,{}):(0,K.jsxs)(m$.NoData,{children:[`No loaded result for item "`,r,`".`]}),scores:v,state:y,withQueryTrace:e,withFeedback:t,onPrevious:d,onNext:f,onClose:u,onComplete:p?()=>_(p.id):void 0,onFlagForReview:p?()=>void g(p.id):void 0})}function dxi(e){let{currentItemId:t,close:n}=B_i(),r=fE();return v3r(t,n),r?(0,K.jsx)(uxi,{...e}):t?(0,K.jsx)(J8,{owner:`experiment-item`,children:(0,K.jsx)(uxi,{...e,variant:`inline`})}):null}function fxi({children:e,className:t}){return(0,K.jsx)(`div`,{className:`@container`,children:(0,K.jsx)(`div`,{className:m(`grid gap-4 *:min-w-0! @xl:@max-4xl:grid-cols-2 @3xl:@max-4xl:has-[>:nth-child(3)]:grid-cols-3 @3xl:@max-4xl:has-[>:nth-child(4):last-child]:grid-cols-2 @4xl:grid-cols-[repeat(auto-fit,minmax(12rem,1fr))] @4xl:@max-6xl:has-[>:nth-child(5)]:grid-cols-3`,t),children:e})})}var pxi=[{label:`Agent`,entityType:`agent`},{label:`Workflow`,entityType:`workflow_run`},{label:`Scorer`,entityType:`scorer`},{label:`Ingest`,entityType:`rag_ingestion`},{label:`Classifier`,entityType:`classifier`}],X7=`rootEntityType`,Z7={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`},mxi=Object.keys(Z7),hxi=`mastra:metrics:saved-filters`;function gxi(e){let t=Axi(e);try{localStorage.setItem(hxi,t.toString())}catch{}}function _xi(){try{let e=localStorage.getItem(hxi);if(!e)return null;let t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function vxi(e){if(e.has(`rootEntityType`))return!0;for(let t of mxi)if(e.has(Z7[t]))return!0;return!1}var yxi=`hasAll`,bxi=[{id:`is`,label:`is`},{id:yxi,label:`has all of`,arity:`many`}],xxi={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`},Sxi={provider:fr,model:wr},Cxi=[`threadId`,`resourceId`,`userId`,`organizationId`,`runId`,`sessionId`,`requestId`,`experimentId`],wxi=e=>({id:e,label:xxi[e],icon:Sxi[e]??t0r(e),color:I8(e)}),Txi=(e,t)=>e.label.localeCompare(t.label);function Exi({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r}){let i=(e,t)=>({...wxi(e),operators:[`is`],strict:!0,suggestions:t}),a=e=>({...wxi(e),operators:[`is`]}),o=e=>e.map(e=>({value:e})),s=[i(`rootEntityType`,pxi.map(e=>({value:e.entityType,label:e.label}))),i(`entityName`,o(t)),{...i(`tags`,o(e)),operators:[yxi]},i(`serviceName`,o(n)),i(`environment`,o(r))],c=Cxi.map(a),l=[`provider`,`model`].map(e=>({...a(e),hidden:!0}));return[...s.toSorted(Txi),...c.toSorted(Txi),...l]}function Dxi(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:yxi,value:t}}let t=Array.isArray(e.value)?e.value[0]??``:e.value;return{id:e.fieldId,fieldId:e.fieldId,operatorId:`is`,value:Nxi(t)?``:t}})}function Oxi(e){return e.map(e=>({fieldId:e.fieldId,value:Array.isArray(e.value)?e.value.map(String):String(e.value)}))}function kxi(e){let t=[],n=new Map([[X7,`rootEntityType`]]);for(let e of mxi)n.set(Z7[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 Axi(e){let t=new URLSearchParams,n=e.getAll(X7);for(let e of n)t.append(X7,e);for(let n of mxi){let r=Z7[n],i=e.getAll(r);for(let e of i)t.append(r,e)}return t}function jxi(e,t){e.delete(X7);for(let t of mxi)e.delete(Z7[t]);for(let n of t){let t=n.fieldId===`rootEntityType`?X7:Z7[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 Mxi=`Any`;function Nxi(e){let t=e.trim();return t===``||t===Mxi}var Pxi=new Set(pxi.map(e=>e.entityType));function Fxi(e){let t=e.trim();return Pxi.has(t)?t:void 0}function Ixi(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=>!Nxi(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:Fxi(e);n&&(t.rootEntityType=n)}else t[e]=r[0]}else if(typeof n.value==`string`){if(Nxi(n.value))continue;let r=n.value.trim();if(e===`rootEntityType`){let e=Fxi(r);e&&(t.rootEntityType=e)}else t[e]=r}}return t}var Lxi={first:0,normal:1,last:2},Rxi=class extends Error{constructor(){super(`Skipped: nothing is waiting for this request any more`),this.name=`SkippedRequestError`}};function zxi(e){let t=0,n=[],r=()=>{t<e&&n.shift()?.start()};return{run(i,{priority:a=Lxi.normal,isWanted:o}={}){return new Promise((s,c)=>{let l=e=>{e&&o&&!o()?(c(new Rxi),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 Bxi=(0,G.createContext)(void 0);function Vxi(){let e=(0,G.use)(Bxi);if(!e)throw Error(`useAggregateLimiter must be used inside MetricsProvider or AggregateLimiterProvider`);return e}function Hxi(e,t){let n=Vxi(),r=dy();return({queryKey:i})=>n.run(e,{priority:t,isWanted:()=>(r.getQueryCache().find({queryKey:i,exact:!0})?.getObserversCount()??0)>0})}function Uxi({children:e}){let t=(0,G.use)(Bxi),[n]=(0,G.useState)(()=>t?void 0:zxi(3));return(0,K.jsx)(Bxi,{value:t??n,children:e})}var Wxi=864e5,Gxi={"24h":Wxi,"3d":2592e5,"7d":6048e5,"14d":12096e5,"30d":2592e6};function Kxi(e,t,n){if(e!==`custom`){let t=Gxi[e]??Wxi;return{start:new Date(n-t),end:new Date(n)}}return{start:t?.from??new Date(n-Wxi),end:t?.to??new Date(n)}}function qxi({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)(()=>Kxi(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 Jxi(e){let t=Y(),{filters:n,filterKey:r,queryOptions:i}=e;return Ey({queryKey:[`metrics`,`agent-runs-kpi`,r],queryFn:()=>t.getMetricAggregate({name:[`mastra_agent_duration_ms`],aggregation:`count`,filters:n,comparePeriod:`previous_period`}),...i})}new Intl.NumberFormat(`en-US`,{notation:`compact`,maximumSignificantDigits:3}),new Intl.NumberFormat(`en-US`),new Set(Intl.supportedValuesOf(`currency`));function Yxi(e){let t=Y(),{filters:n,filterKey:r,queryOptions:i}=e;return Ey({queryKey:[`metrics`,`token-usage-by-agent`,r],queryFn:async()=>{let e={groupBy:[`entityName`],aggregation:`sum`,orderDirection:`DESC`,filters:n},[r,i]=await Promise.all([t.getMetricBreakdown({...e,name:[`mastra_model_total_input_tokens`]}),t.getMetricBreakdown({...e,name:[`mastra_model_total_output_tokens`]})]),a=new Map,o=e=>c8(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 Xxi(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=c8(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 Zxi(e){let t=Y(),{filters:n,filterKey:r,queryOptions:i}=e;return Ey({queryKey:[`metrics`,`trace-volume`,r],queryFn:async()=>{let[e,r,i]=await Promise.all([Xxi(t,`mastra_agent_duration_ms`,n),Xxi(t,`mastra_workflow_duration_ms`,n),Xxi(t,`mastra_tool_duration_ms`,n)]);return{agentData:e,workflowData:r,toolData:i}},...i})}var Qxi=[{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`}],$xi=new Set(Qxi.map(e=>e.value));function eSi(e){return typeof e==`string`&&($xi.has(e)||e===`custom`)}var tSi=(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)(tSi)}function nSi(e,t){return e===`custom`?t?.from?t.to?`${Pw(t.from)} – ${Pw(t.to)}`:Pw(t.from)??``:`Custom range`:Qxi.find(t=>t.value===e)?.label??e}var rSi=36e5;function iSi(e,t){if(e!==`custom`)return`vs previous ${e}`;let n=t?.to?.getTime()??Date.now(),r=t?.from?.getTime()??n-24*rSi,i=Math.round((n-r)/rSi);return`vs previous ${i>24&&i%24==0?`${i/24}d`:`${i}h`}`}function aSi({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)(()=>Ixi(l),[l]),d=(0,G.useMemo)(()=>JSON.stringify(u),[u]),f=qxi({datePreset:t,customRange:a,dimensionalFilter:u,dimensionalFilterKey:d}),p=(0,G.useMemo)(()=>s??{},[s]),m=nSi(t,a),h=iSi(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)(tSi.Provider,{value:g,children:(0,K.jsx)(Uxi,{children:e})})}var oSi=[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`];function sSi(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 cSi(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 lSi=864e5;function uSi(){let{data:e}=r5(),t=e?.capabilities.traceRetentionDays;if(t===void 0)return;let n=new Date(Date.now()-t*lSi);return new Date(n.getFullYear(),n.getMonth(),n.getDate())}function dSi(){let{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=Q7(),i=uSi();return(0,K.jsx)(F5r,{preset:sSi(e),onPresetChange:e=>t(cSi(e)),dateFrom:n?.from,dateTo:n?.to,onDateRangeChange:(e,t)=>r({from:e,to:t}),presets:oSi,minDate:i})}var fSi=G.forwardRef(({label:e,children:t,...n},r)=>(0,K.jsx)(X,{ref:r,variant:`ghost`,size:`icon-sm`,tooltip:e,"aria-label":e,...n,children:t}));fSi.displayName=`MetricsCardAction`;function pSi({children:e,className:t}){return(0,K.jsx)(`div`,{className:m(`-my-1 flex shrink-0 items-center gap-1 self-start`,t),children:e})}function mSi({children:e,className:t}){return(0,K.jsx)(`div`,{className:m(`overflow-x-auto overflow-y-hidden [&_tbody>tr:last-child]:border-b-0`,t),children:e})}function hSi({className:e,...t}){return(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,className:m(`-my-1 shrink-0 cursor-grab active:cursor-grabbing`,e),...t,children:(0,K.jsx)(Vi,{})})}function gSi({message:e=`Failed to load data`,className:t}){return(0,K.jsx)(`div`,{className:m(`flex flex-col items-center justify-center gap-3`,t),children:(0,K.jsx)(T,{variant:`caption`,className:`text-destructive-foreground`,children:e})})}function _Si({label:e,value:t,change:n,isLoading:r=!1,className:i}){return(0,K.jsxs)(`div`,{className:m(`grid gap-1.5`,i),children:[(0,K.jsx)(`h3`,{className:`text-body-sm text-muted-foreground`,children:e}),(0,K.jsxs)(`span`,{className:`flex items-baseline gap-2`,children:[(0,K.jsx)(`span`,{className:m(`text-title text-foreground tabular-nums [text-box:trim-both_cap_alphabetic]`,r&&`relative min-w-24`),children:r?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`span`,{className:`invisible`,children:`0`}),(0,K.jsx)(dw,{className:`absolute inset-0`})]}):t}),!r&&n&&(0,K.jsxs)(`span`,{className:`text-body-sm text-muted-foreground tabular-nums [text-box:trim-both_cap_alphabetic]`,children:[n,` vs previous`]})]})]})}function vSi({className:e}){return(0,K.jsx)(`div`,{className:m(`flex items-center justify-center`,e),children:(0,K.jsx)(Qc,{size:`md`,variant:`pulse`,className:`text-placeholder`})})}function ySi({message:e=`No data yet`,className:t}){return(0,K.jsx)(`div`,{className:m(`flex h-full items-center justify-center`,t),children:(0,K.jsx)(T,{tone:`faint`,children:e})})}function bSi({children:e,className:t}){return(0,K.jsx)(dF,{className:m(`group/metrics-card grid min-h-72 min-w-80 flex-1 grid-rows-[auto_1fr] gap-4 px-4 py-3 2xl:min-w-120 md:min-w-88 lg:min-w-sm xl:min-w-104`,t),children:e})}function xSi({children:e,className:t,as:n=`h3`}){return(0,K.jsx)(n,{className:m(`text-subheading text-foreground`,t),children:e})}function SSi({title:e,value:t,onValueChange:n,options:r,className:i}){return(0,K.jsx)(`div`,{className:`flex min-w-0`,children:(0,K.jsxs)(mD,{modal:!1,children:[(0,K.jsxs)(mD.Trigger,{render:(0,K.jsx)(`button`,{type:`button`,className:m(`-mx-1.5 -my-0.5 flex items-center gap-1 self-start rounded-md px-1.5 py-0.5 text-left text-subheading text-foreground hover:bg-fill-subtle`,i)}),children:[e,(0,K.jsx)(h,{className:`size-3.5 text-muted-foreground`})]}),(0,K.jsx)(mD.Content,{align:`start`,children:(0,K.jsx)(mD.RadioOptions,{options:r,value:t,onValueChange:n,closeOnSelect:!0})})]})})}function CSi({children:e,className:t}){return(0,K.jsx)(`div`,{className:m(`flex min-h-6 min-w-0 flex-wrap items-center justify-between gap-x-4 gap-y-2 [&>*:first-child]:min-w-0 [&>*:last-child:not(:first-child)]:ml-auto`,t),children:e})}function wSi({children:e,className:t}){return(0,K.jsx)(`div`,{className:m(`flex items-start gap-4 [&>:first-child]:min-w-0 [&>:first-child]:flex-1`,t),children:e})}function TSi({value:e,isLoading:t=!1,className:n}){return(0,K.jsx)(`span`,{className:m(`order-last shrink-0 text-subheading text-foreground tabular-nums`,n),children:(0,K.jsx)(ESi,{value:e,isLoading:t})})}function ESi({value:e,isLoading:t}){return t?(0,K.jsx)(fw,{line:`text-body`,className:`h-4 w-14`}):typeof e==`string`?e:(0,K.jsx)(`span`,{className:`inline-flex items-center gap-3`,children:e.map(e=>(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,K.jsx)(`span`,{"aria-hidden":!0,className:`size-2 shrink-0 rounded-[2px]`,style:{backgroundColor:e.color}}),(0,K.jsxs)(`span`,{className:`sr-only`,children:[e.label,` `]}),e.value]},e.label))})}var $7=Object.assign(bSi,{Root:bSi,Kpi:_3,TopBar:wSi,Toolbar:CSi,Actions:pSi,Action:fSi,DragHandle:hSi,Title:xSi,TitleMenu:SSi,Total:TSi,Headline:_Si,Loading:vSi,Error:gSi,Content:mSi,NoData:ySi}),DSi=`pointer-events-none absolute opacity-0 pointer-coarse:pointer-events-auto pointer-coarse:static pointer-coarse:opacity-100 group-hover/metrics-card:pointer-events-auto group-hover/metrics-card:static group-hover/metrics-card:opacity-100 motion-safe:group-hover/metrics-card:transition-opacity group-focus-within/metrics-card:pointer-events-auto group-focus-within/metrics-card:static group-focus-within/metrics-card:opacity-100 motion-safe:group-focus-within/metrics-card:transition-opacity group-has-data-popup-open/metrics-card:pointer-events-auto group-has-data-popup-open/metrics-card:static group-has-data-popup-open/metrics-card:opacity-100`;function OSi({onClick:e}){return(0,K.jsx)($7.Action,{label:`View in traces`,className:DSi,onClick:e,children:(0,K.jsx)(oF,{})})}function kSi({onClick:e}){return(0,K.jsx)($7.Action,{label:`View errors in logs`,className:DSi,onClick:e,children:(0,K.jsx)(La,{})})}function e9({isEmpty:e=!1,emptyMessage:t=`No data in this range`,children:n}){return(0,K.jsxs)(`div`,{className:`relative flex min-h-0 flex-1 flex-col`,"data-chart-empty":e||void 0,children:[(0,K.jsx)(`div`,{className:m(`flex min-h-0 flex-1 flex-col`,e&&`invisible [&_.recharts-xAxis-tick-labels]:visible`),children:(0,K.jsx)(m7r.Provider,{value:e,children:n})}),e&&(0,K.jsx)(jSi,{message:t})]})}function ASi({className:e}){return(0,K.jsx)(`div`,{"aria-hidden":!0,className:m(`h-px bg-[linear-gradient(to_right,var(--border)_3px,transparent_3px)] bg-size-[6px_1px] opacity-50`,e)})}function jSi({message:e}){return(0,K.jsxs)(`div`,{className:`absolute inset-0 flex flex-col justify-between`,style:{paddingTop:b5.top,paddingBottom:22},children:[(0,K.jsx)(ASi,{}),(0,K.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,K.jsx)(ASi,{className:`flex-1`}),(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`muted`,className:`max-w-[70%] text-center font-[450] text-balance`,children:e}),(0,K.jsx)(ASi,{className:`flex-1`})]}),(0,K.jsx)(ASi,{})]})}function t9({variant:e=`default`,title:t,href:n,LinkComponent:r,titleMenu:i,dragHandle:a,onTitleChange:o,total:s,change:c,isLoading:l=!1,actions:u,toolbar:d,isUpdating:f=!1,bodyHeight:p=`fixed`,className:h,children:g}){let _=m(`transition-opacity duration-200`,f&&`opacity-50`),v=e===`compact`,y=e===`hero`,b=!y&&p===`fixed`;return(0,K.jsxs)($7,{className:m(`min-h-0! min-w-0! grid-cols-1`,`[&:has([data-slot=chart-skeleton])_[data-slot=chart-legend]]:invisible`,`[&:has([data-chart-empty])_[data-slot=chart-legend]]:invisible`,v&&`h-84`,h),children:[(0,K.jsxs)($7.TopBar,{children:[y?(0,K.jsx)($7.Headline,{label:t,value:typeof s==`string`?s:`—`,change:c,isLoading:l,className:_}):(0,K.jsx)(NSi,{title:t,href:n,LinkComponent:r,titleMenu:i,dragHandle:a,onTitleChange:o}),u&&(0,K.jsx)($7.Actions,{className:m(y&&`my-0 self-center`),children:u}),!y&&s!==void 0&&(0,K.jsx)($7.Total,{value:s,isLoading:l,className:_})]}),(0,K.jsxs)($7.Content,{className:m(`flex flex-col gap-4 overflow-visible`,v&&`min-h-0`),children:[d||b&&d!==void 0&&(0,K.jsx)(`div`,{"aria-hidden":!0,className:`min-h-6`}),(0,K.jsx)(`div`,{className:m(`relative flex min-h-0 min-w-0 flex-col`,MSi(e,p),_),children:g})]})]})}function MSi(e,t){if(e===`compact`)return`flex-1`;if(e!==`hero`)return t===`fit`?`min-h-60`:`min-h-60 flex-1`}function NSi({dragHandle:e,...t}){return e?(0,K.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1.5`,children:[(0,K.jsx)($7.DragHandle,{...e}),(0,K.jsx)(PSi,{...t})]}):(0,K.jsx)(PSi,{...t})}function PSi({title:e,href:t,LinkComponent:n,titleMenu:r,onTitleChange:i}){return r?(0,K.jsx)($7.TitleMenu,{title:e,...r}):t?(0,K.jsx)(`h3`,{className:`flex`,children:(0,K.jsx)(ISi,{href:t,LinkComponent:n,children:e})}):i?(0,K.jsx)(FSi,{title:e,onTitleChange:i}):(0,K.jsx)($7.Title,{children:e})}function FSi({title:e,onTitleChange:t}){return(0,K.jsx)(`h3`,{className:`flex min-w-0`,children:(0,K.jsx)(`input`,{"aria-label":`Widget title`,defaultValue:e,...YA,onBlur:n=>{let r=n.currentTarget.value.trim();n.currentTarget.value=r,r!==e&&t(r)},onKeyDown:t=>{t.key===`Escape`&&(t.currentTarget.value=e),(t.key===`Enter`||t.key===`Escape`)&&(t.preventDefault(),t.currentTarget.blur())},className:m(`-mx-1.5 -my-0.5 field-sizing-content min-w-12 truncate rounded-md bg-transparent px-1.5 py-0.5`,`text-body zoom-safe-text font-medium text-foreground`,`outline-1 -outline-offset-1 outline-transparent outline-dashed hover:outline-border-strong focus:outline-border-focus`)},e)})}function ISi({href:e,LinkComponent:t,children:n}){return(0,K.jsxs)(t??`a`,{href:e,className:m(`-mx-1.5 -my-0.5 inline-flex items-center gap-1.5 rounded-md px-1.5 py-0.5 text-subheading text-foreground hover:bg-fill-subtle`,`focus-visible:outline-1 focus-visible:-outline-offset-1 focus-visible:outline-border-focus focus-visible:outline-solid`),children:[n,(0,K.jsx)(za,{"aria-hidden":!0,className:`size-3.5 text-muted-foreground`})]})}function n9({error:e,onRetry:t}){return JP(e)?(0,K.jsx)(jU,{}):YP(e)?(0,K.jsx)(AU,{resource:`traces`}):(0,K.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3`,children:[(0,K.jsx)($7.Error,{message:`Couldn't load this data. Try again in a moment.`}),t&&(0,K.jsx)(X,{size:`sm`,icon:(0,K.jsx)(ss,{}),onClick:t,children:`Retry`})]})}function LSi({label:e,icon:t,isError:n=!1,...r}){return(0,K.jsxs)(_3,{busy:!n&&(r.isLoading||r.isUpdating),children:[(0,K.jsx)(_3.Label,{icon:(0,K.jsx)(t,{}),children:e}),n?(0,K.jsx)(RSi,{}):(0,K.jsx)(zSi,{...r})]})}function RSi(){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(_3.ValueRow,{className:`mt-1`,children:(0,K.jsx)(_3.Value,{children:`—`})}),(0,K.jsx)(_3.Footer,{detail:(0,K.jsx)(`span`,{className:`text-destructive-foreground`,children:`Couldn't load`})})]})}function zSi({value:e,change:t,lowerIsBetter:n,detail:r,previous:i,comparison:a,isLoading:o=!1,isUpdating:s=!1}){let c=m(`transition-opacity duration-200`,s&&`opacity-50`);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(_3.ValueRow,{className:m(`mt-1`,c),isLoading:o,children:[(0,K.jsx)(_3.Value,{children:e}),t!==void 0&&(0,K.jsx)(_3.Change,{changePct:t,comparison:a,lowerIsBetter:n,prevValue:i})]}),(0,K.jsx)(_3.Footer,{detail:r,prevValue:t===void 0?void 0:i,isLoading:o,className:c})]})}var BSi={2:`@3xl:grid-cols-2`,3:`@3xl:grid-cols-2 @7xl:grid-cols-3`},VSi={1:``,2:`@3xl:col-span-2`,full:`col-span-full`};function r9({children:e,columns:t=3,className:n}){return(0,K.jsx)(`div`,{className:m(`@container`,n),children:(0,K.jsx)(`div`,{className:m(`grid gap-4`,BSi[t]),children:e})})}function HSi({children:e,span:t=1,className:n}){return(0,K.jsx)(`div`,{className:m(`min-w-0 *:size-full *:min-w-0!`,VSi[t],n),children:e})}r9.Item=HSi;var USi=864e5;function i9(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 a9=e=>e===`1h`?1:24;function WSi(e,t){if(t>=24)return Math.floor(e/USi)*USi;let n=new Date(e),r=Math.floor(n.getHours()/t)*t;return new Date(n.getFullYear(),n.getMonth(),n.getDate(),r).getTime()}function GSi(e,t){if(t>=24)return WSi(e,t)+USi;let n=new Date(e);return WSi(new Date(n.getFullYear(),n.getMonth(),n.getDate(),n.getHours()+t).getTime(),t)}function KSi(e,t,n){let r=B9r(e,t),i=[];for(let a=WSi(e.getTime(),n);a<=t.getTime();a=GSi(a,n))i.push(U9r(a,n,r));return i}function qSi(e,t){let n=new Map(e.map((e,t)=>[e.ts,t]));return e=>n.get(WSi(new Date(e.timestamp).getTime(),t))}function o9(e,t){return{from:new Date(e),to:new Date(GSi(e,t))}}function s9(){let{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r,queryFilters:i}=Q7(),a=qxi({datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r});return i??a}var JSi={input:`mastra_model_total_input_tokens`,output:`mastra_model_total_output_tokens`,cacheRead:`mastra_model_input_cache_read_tokens`},YSi=`mastra_agent_duration_ms`;function XSi(){let e=Y(),{filters:t,filterKey:n,timestamp:r}=s9(),{interval:i,stepHours:a}=i9(r.start,r.end);return Ey({queryKey:[`metrics`,`activity`,n,i],placeholderData:vy,queryFn:async()=>{let n=n=>e.getMetricTimeSeries({name:[n],interval:i,aggregation:`sum`,filters:t}),[o,s,c,l]=await Promise.all([n(JSi.input),n(JSi.output),n(JSi.cacheRead),e.getMetricTimeSeries({name:[YSi],interval:i,aggregation:`count`,groupBy:[`status`],filters:t})]),u=KSi(r.start,r.end,a).map(e=>({...e,input:0,cacheRead:0,output:0,cost:0,completed:0,failed:0,failureRate:0})),d=qSi(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 ZSi=[{dataKey:`input`,label:`Input`,color:h5.green},{dataKey:`cacheRead`,label:`Cache read`,color:h5.violet},{dataKey:`output`,label:`Output`,color:h5.sky}],QSi=[{dataKey:`cost`,label:`Cost`,color:h5.green}],$Si={tokens:`Token usage`,cost:`Model cost`},eCi=[{value:`tokens`,label:$Si.tokens},{value:`cost`,label:$Si.cost}];function tCi({onViewTraces:e,onTimeRangeClick:t}){let[n,r]=(0,G.useState)(`tokens`),{data:i=[],isLoading:a,isError:o,isPlaceholderData:s}=XSi(),{timestamp:c}=s9(),{stepHours:l}=i9(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?ZSi:QSi,m={title:$Si[n],titleMenu:{value:n,onValueChange:r,options:eCi},actions:e&&(0,K.jsx)(OSi,{onClick:e}),toolbar:(0,K.jsx)($7.Toolbar,{children:(0,K.jsx)(w5,{series:p})})};return o?(0,K.jsx)(t9,{...m,children:(0,K.jsx)(n9,{})}):(0,K.jsx)(t9,{...m,total:f?_5(u):y5(d),isLoading:a,isUpdating:s,children:(0,K.jsx)(e9,{isEmpty:!a&&u===0&&d===0,children:(0,K.jsx)(j9r,{data:i,series:p,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:f?_5:y5,axisFormatter:f?d7r:f7r,onBucketClick:t&&(e=>t(o9(Number(e.ts),l))),isLoading:a,...m5})})})}var nCi=[{dataKey:`failureRate`,label:`Failed runs`,color:h5.error}],rCi=e=>`${Math.round(e*100)}%`;function iCi({onViewErrors:e,onTimeRangeClick:t,titleMenu:n}){let{data:r=[],isLoading:i,isError:a,isPlaceholderData:o}=XSi(),{timestamp:s}=s9(),{stepHours:c}=i9(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)(kSi,{onClick:e}),toolbar:(0,K.jsx)($7.Toolbar,{children:(0,K.jsx)(w5,{series:nCi})})};return a?(0,K.jsx)(t9,{...f,children:(0,K.jsx)(n9,{})}):(0,K.jsx)(t9,{...f,total:v5(l>0?u/l:0),isLoading:i,isUpdating:o,children:(0,K.jsx)(e9,{isEmpty:!i&&l===0,children:(0,K.jsx)(l9r,{lineStyle:`thin`,data:r,series:nCi,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:v5,axisFormatter:rCi,yDomain:d,onBucketClick:t&&(e=>t(o9(Number(e.ts),c))),isLoading:i,...m5})})})}var aCi=[{dataKey:`completed`,label:`Completed`,color:h5.green},{dataKey:`failed`,label:`Failed`,color:h5.error}],oCi=[{value:`runs`,label:`Agent runs`},{value:`failure`,label:`Failure rate`}];function sCi({onTimeRangeClick:e,onFailureTimeRangeClick:t,onViewErrors:n}){let[r,i]=(0,G.useState)(`runs`),a={value:r,onValueChange:i,options:oCi};return r===`failure`?(0,K.jsx)(iCi,{titleMenu:a,onViewErrors:n,onTimeRangeClick:t}):(0,K.jsx)(cCi,{titleMenu:a,onTimeRangeClick:e})}function cCi({onTimeRangeClick:e,titleMenu:t}){let{data:n=[],isLoading:r,isError:i,isPlaceholderData:a}=XSi(),{timestamp:o}=s9(),{stepHours:s}=i9(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)($7.Toolbar,{children:(0,K.jsx)(w5,{series:aCi})})};return i?(0,K.jsx)(t9,{...l,children:(0,K.jsx)(n9,{})}):(0,K.jsx)(t9,{...l,total:_5(c),isLoading:r,isUpdating:a,children:(0,K.jsx)(e9,{isEmpty:!r&&c===0,children:(0,K.jsx)(j9r,{data:n,series:aCi,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:_5,onBucketClick:e&&(t=>e(o9(Number(t.ts),s))),isLoading:r,...m5})})})}var lCi={.5:`p50`,.95:`p95`,.99:`p99`},uCi={agents:`mastra_agent_duration_ms`,workflows:`mastra_workflow_duration_ms`,tools:`mastra_tool_duration_ms`};function dCi(e){let t=Y(),{filters:n,filterKey:r,timestamp:i}=s9(),{interval:a}=i9(i.start,i.end),o=a9(a);return Ey({queryKey:[`metrics`,`latency-percentiles`,e,r,a],placeholderData:vy,queryFn:async()=>{let r=await t.getMetricPercentiles({name:uCi[e],percentiles:[.5,.95,.99],interval:a,filters:n}),s=KSi(i.start,i.end,o),c=qSi(s,o);for(let e of r.series){let t=lCi[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 fCi={agents:kh.AGENT,workflows:kh.WORKFLOW_RUN,tools:kh.TOOL},pCi=[{dataKey:`p50`,label:`P50`,color:h5.sky},{dataKey:`p95`,label:`P95`,color:h5.green,emphasis:!0},{dataKey:`p99`,label:`P99`,color:h5.violet}],mCi={agents:`Agent latency`,workflows:`Workflow latency`,tools:`Tool latency`},hCi=[{value:`agents`,label:mCi.agents},{value:`workflows`,label:mCi.workflows},{value:`tools`,label:mCi.tools}];function gCi({onViewTraces:e,onTimeRangeClick:t}){let[n,r]=(0,G.useState)(`agents`),{data:i=[],isLoading:a,isError:o,isPlaceholderData:s}=dCi(n),{timestamp:c}=s9(),l=a9(i9(c.start,c.end).interval),u=Math.max(0,...i.map(e=>e.p95??0)),d={title:mCi[n],titleMenu:{value:n,onValueChange:r,options:hCi},actions:e&&(0,K.jsx)(OSi,{onClick:()=>e(fCi[n])}),toolbar:(0,K.jsx)($7.Toolbar,{children:(0,K.jsx)(w5,{series:pCi})})};return o?(0,K.jsx)(t9,{...d,children:(0,K.jsx)(n9,{})}):(0,K.jsx)(t9,{...d,total:u7r(u),isLoading:a,isUpdating:s,children:(0,K.jsx)(e9,{isEmpty:!a&&u===0,children:(0,K.jsx)(l9r,{lineStyle:`thin`,data:i,series:pCi,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:u7r,axisFormatter:p7r,onBucketClick:t&&(e=>t(o9(Number(e.ts),l))),isLoading:a,...m5})})})}var _Ci=`-mx-2 flex w-[calc(100%+1rem)] items-center gap-3 rounded-md px-2 py-1 text-left`,c9=`shrink-0 text-right text-body-sm tabular-nums`;function vCi({row:e,columns:t,valueWidth:n,share:r,highlighted:i,dimmed:a,onHover:o,LinkComponent:s}){let c=m(_Ci,i&&`bg-fill-subtle`,(e.href||e.onClick)&&`hover:bg-fill-subtle`);return(0,K.jsx)(`li`,{children:(0,K.jsxs)(yCi,{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)(bCi,{row:e}),t.map((t,n)=>(0,K.jsx)(`span`,{className:m(c9,`text-muted-foreground`,t.width??`w-16`),children:e.cells?.[n]},t.label)),(0,K.jsx)(`span`,{className:m(c9,`w-12 text-muted-foreground`),children:r}),(0,K.jsx)(`span`,{className:m(c9,`text-foreground`,n),children:e.value})]})})}function yCi({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 bCi({row:e}){return typeof e.label==`string`?(0,K.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,title:e.title??e.label,children:(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`ink`,children:e.label})}):(0,K.jsx)(`span`,{className:`flex min-w-0 flex-1`,title:e.title,children:e.label})}var xCi=`var(--chart-share-1)`,SCi=[1,2,3,4,5].map(e=>`var(--chart-share-${e})`),CCi=[3,4,2,5,1].map(e=>`var(--chart-share-${e})`),wCi=[1,.7,.48,.32,.2,.14],TCi={color:`var(--chart-share-rest)`,alpha:1},ECi=50,DCi=`__rest`;function OCi(e,t,n){if(n===`hues`){let n=SCi.includes(e)?[e,...SCi.filter(t=>t!==e)]:[e,...CCi];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:wCi[n]??.1}))}var kCi=e=>e.reduce((e,t)=>e+Math.max(t.share,0),0);function ACi(e){return e.map(e=>Number.isFinite(e.share)&&e.share>0?e:{...e,share:0}).toSorted((e,t)=>t.share-e.share)}function jCi(e,{limit:t,other:n,color:r,palette:i}){if(e.length<=t+1){let t=MCi(e,r,i);return{shown:t,bar:t,rest:[]}}let a=e.slice(t),o=n?.(a),s={key:DCi,label:`Other (${a.length})`,share:kCi(a),value:o?.value,cells:o?.cells,paint:TCi,segment:DCi},c=MCi(e.slice(0,t),r,i);return{shown:[...c,s],bar:c,rest:a}}function MCi(e,t,n){let r=OCi(t,e.length,n);return e.map((e,t)=>({...e,paint:NCi(e)??r[t]??TCi,segment:e.key}))}var NCi=e=>e.color?{color:e.color,alpha:1}:void 0;function PCi(e,{count:t,color:n,palette:r}){let i=Math.min(t,e.length,ECi),a=MCi(e.slice(0,i),n,r),o=e.slice(i,t).map(e=>({...e,paint:TCi,segment:DCi}));return{shown:[...a,...o],bar:a,rest:e.slice(i)}}function FCi(e,t){let n=e.map(e=>({key:e.key,share:e.share,paint:e.paint})),r=t.length?[{key:DCi,share:kCi(t),paint:TCi}]:[],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 ICi(e,t){if(t!==void 0)return e.find(e=>e.key===t)?.segment??t}var LCi=(e,t)=>t!==void 0&&t!==e;function RCi(e,t){return t===void 0||t===e.key?!1:t!==`__rest`||e.segment!==`__rest`}var zCi=(e,t)=>{let n=e/(t||1);return n>0?n<.001?`<0.1%`:`${(n*100).toFixed(+(n<.1))}%`:`0%`};function BCi({shown:e,total:t,limit:n,pageSize:r,onMore:i,onLess:a}){if(t<=n)return null;let o=t-e,s=`flex items-center gap-1.5 rounded-md px-2 py-1 text-label text-muted-foreground transition-colors duration-150 hover:bg-fill-subtle hover:text-foreground`,c=new Intl.NumberFormat(`en`,{notation:`compact`,maximumFractionDigits:1});return(0,K.jsxs)(`li`,{className:`-mx-2 flex items-center gap-1`,children:[o>0&&(0,K.jsxs)(`button`,{type:`button`,onClick:i,className:s,children:[(0,K.jsx)(h,{className:`size-3.5 shrink-0`}),`Show `,Math.min(o,r),` more`]}),e>n&&(0,K.jsxs)(`button`,{type:`button`,onClick:a,className:s,children:[(0,K.jsx)(l,{className:`size-3.5 shrink-0`}),`Show top `,n]}),o>0&&(0,K.jsxs)(`span`,{className:`ml-auto pr-2 text-body-sm text-placeholder tabular-nums`,children:[c.format(e),` of `,c.format(t)]})]})}var VCi=[`w-32`,`w-24`,`w-36`,`w-20`,`w-28`];function HCi({className:e}){return(0,K.jsxs)(K.Fragment,{children:[``,(0,K.jsx)(dw,{className:m(`absolute top-1/2 h-3.5 -translate-y-1/2`,e)})]})}function UCi({rows:e,columns:t,valueWidth:n,header:r}){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`flex h-2`,children:(0,K.jsx)(dw,{className:`size-full rounded-full`})}),r,(0,K.jsx)(`ul`,{className:`grid min-w-0 grid-cols-1 gap-0.5`,"aria-busy":!0,children:Array.from({length:e},(e,r)=>(0,K.jsxs)(`li`,{className:_Ci,children:[(0,K.jsx)(dw,{className:`size-2 shrink-0 rounded-[2px]`}),(0,K.jsx)(`span`,{className:`min-w-0 flex-1`,children:(0,K.jsx)(T,{as:`span`,variant:`body-sm`,className:`relative`,children:(0,K.jsx)(HCi,{className:m(`left-0`,VCi[r%VCi.length])})})}),t.map(e=>(0,K.jsx)(`span`,{className:m(c9,`relative`,e.width??`w-16`),children:(0,K.jsx)(HCi,{className:`right-0 w-10`})},e.label)),(0,K.jsx)(`span`,{className:m(c9,`relative w-12`),children:(0,K.jsx)(HCi,{className:`right-0 w-9`})}),(0,K.jsx)(`span`,{className:m(c9,`relative`,n),children:(0,K.jsx)(HCi,{className:`right-0 w-12`})})]},r))})]})}function WCi({className:e,...t}){return(0,K.jsx)(`div`,{className:m(`grid grid-cols-1`,e),children:(0,K.jsx)(GCi,{...t})})}function GCi({rows:e,columns:t=[],valueLabel:n,valueWidth:r=`w-14`,palette:i=`shades`,color:a=xCi,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)(KCi,{columns:t,valueLabel:n,valueWidth:r});if(d)return(0,K.jsx)(UCi,{rows:s===`other`?o+1:o,columns:t,valueWidth:r,header:v});let y=ACi(e);if(y.length===0)return(0,K.jsx)(T,{variant:`body-sm`,tone:`muted`,className:`py-6 text-center`,children:u});let b=kCi(y),x=s===`more`,{shown:S,bar:C,rest:w}=x?PCi(y,{count:_,color:a,palette:i}):jCi(y,{limit:o,other:l,color:a,palette:i}),E=FCi(C,w),D=ICi(S,p),O=()=>m(void 0);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`flex h-2 gap-0.5`,onMouseLeave:O,children:E.map(e=>(0,K.jsx)(`span`,{"data-testid":`share-bar-segment`,onMouseEnter:()=>m(e.key),className:`h-full min-w-[3px] first:rounded-l-full last:rounded-r-full`,style:{flex:`${e.grow} 1 0`,backgroundColor:e.paint.color,opacity:e.paint.alpha*(LCi(e.key,D)?.3:1)}},e.key))}),v,(0,K.jsxs)(`ul`,{className:`grid min-w-0 grid-cols-1 gap-0.5`,onMouseLeave:O,children:[S.map(e=>(0,K.jsx)(vCi,{row:e,columns:t,valueWidth:r,share:zCi(e.share,b),highlighted:p===e.key,dimmed:RCi(e,p),onHover:()=>m(e.key),LinkComponent:f},e.key)),x&&(0,K.jsx)(BCi,{shown:Math.min(_,y.length),total:y.length,limit:o,pageSize:c,onMore:()=>g(e=>e+1),onLess:()=>g(0)})]})]})}function KCi({columns:e,valueLabel:t,valueWidth:n}){let r=[...e.map(e=>({label:e.label,width:e.width??`w-16`})),{label:`Share`,width:`w-12`},{label:t,width:n}];return(0,K.jsx)(`div`,{"aria-hidden":!0,className:`flex items-center justify-end gap-3 pt-3 pb-0.5 text-column text-placeholder`,children:r.map(e=>(0,K.jsx)(`span`,{className:m(`shrink-0 text-right whitespace-nowrap`,e.width),children:e.label},e.label))})}var qCi={agents:kh.AGENT,workflows:kh.WORKFLOW_RUN,tools:kh.TOOL},JCi=[{label:`Error rate`}],YCi={agents:`Agent runs`,workflows:`Workflow runs`,tools:`Tool calls`},XCi=[{value:`agents`,label:YCi.agents},{value:`workflows`,label:YCi.workflows},{value:`tools`,label:YCi.tools}],ZCi=(e,t)=>v5(t>0?e/t:0);function QCi({onViewTraces:e,onViewErrors:t,onEntityClick:n}){let[r,i]=(0,G.useState)(`agents`),a=qCi[r],o=Zxi({...s9(),queryOptions:{placeholderData:vy}}),s={agents:o.data?.agentData??[],workflows:o.data?.workflowData??[],tools:o.data?.toolData??[]}[r],c=s.map(e=>({key:e.name,label:e.name,share:e.completed+e.errors,value:_5(e.completed+e.errors),cells:[ZCi(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:YCi[r],titleMenu:{value:r,onValueChange:i,options:XCi},actions:(e||t)&&(0,K.jsxs)(K.Fragment,{children:[e&&(0,K.jsx)(OSi,{onClick:()=>e(a)}),t&&(0,K.jsx)(kSi,{onClick:()=>t(a)})]})};return o.isError?(0,K.jsx)(t9,{...d,children:(0,K.jsx)(n9,{})}):(0,K.jsx)(t9,{...d,total:_5(u),isLoading:o.isLoading,isUpdating:o.isPlaceholderData,children:(0,K.jsx)(e9,{children:(0,K.jsx)(WCi,{rows:c,columns:JCi,valueLabel:`Runs`,color:h5.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:_5(n),cells:[ZCi(t,n)]}},emptyState:`No runs in this range.`,isLoading:o.isLoading},r)})})}var $Ci=[`mastra_model_total_input_tokens`,`mastra_model_total_output_tokens`],ewi=100;function twi(e){let t=Y(),{filters:n,filterKey:r}=s9();return Ey({queryKey:[`metrics`,`token-spend`,e,r],placeholderData:vy,queryFn:async()=>{let{groups:r}=await t.getMetricBreakdown({name:$Ci,groupBy:[e],aggregation:`sum`,orderDirection:`DESC`,limit:ewi,filters:n});return r.map(t=>({key:String(t.dimensions[e]??`unknown`),tokens:t.value,cost:t.estimatedCost??0}))}})}var nwi={agents:`Usage by agent`,models:`Usage by model`,threads:`Usage by thread`},rwi=[{value:`agents`,label:nwi.agents},{value:`models`,label:nwi.models},{value:`threads`,label:nwi.threads}],iwi={placeholderData:vy},awi=[{label:`Tokens`}];function owi(e){let[t,n]=(0,G.useState)(`agents`);return t===`models`?(0,K.jsx)(cwi,{...e,onViewChange:n}):t===`threads`?(0,K.jsx)(lwi,{...e,onViewChange:n}):(0,K.jsx)(swi,{...e,onViewChange:n})}function swi(e){let{onAgentClick:t}=e,{data:n=[],isLoading:r,isPlaceholderData:i,isError:a}=Yxi({...s9(),queryOptions:iwi}),o=n.map(e=>({key:e.name,cost:e.cost??0,tokens:e.total,onClick:t&&(()=>t(e.name))}));return(0,K.jsx)(uwi,{view:`agents`,...e,rows:o,isLoading:r,isUpdating:i,isError:a})}function cwi(e){let{onModelClick:t}=e,{data:n=[],isLoading:r,isPlaceholderData:i,isError:a}=twi(`model`),o=n.map(e=>({...e,onClick:t&&(()=>t(e.key))}));return(0,K.jsx)(uwi,{view:`models`,...e,rows:o,isLoading:r,isUpdating:i,isError:a})}function lwi(e){let{onThreadClick:t}=e,{data:n=[],isLoading:r,isPlaceholderData:i,isError:a}=twi(`threadId`),o=n.map(e=>({...e,onClick:t&&(()=>t(e.key))}));return(0,K.jsx)(uwi,{view:`threads`,...e,rows:o,isLoading:r,isUpdating:i,isError:a})}function uwi({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:y5(e.cost),cells:[_5(e.tokens)],onClick:e.onClick})),l={title:nwi[e],titleMenu:{value:e,onValueChange:t,options:rwi},actions:n&&(0,K.jsx)(OSi,{onClick:n})};return o?(0,K.jsx)(t9,{...l,children:(0,K.jsx)(n9,{})}):(0,K.jsx)(t9,{...l,total:y5(r.reduce((e,t)=>e+t.cost,0)),isLoading:i,isUpdating:a,children:(0,K.jsx)(e9,{children:(0,K.jsx)(WCi,{rows:c,columns:awi,valueLabel:`Cost`,color:h5.green,other:e=>({value:y5(e.reduce((e,t)=>e+t.share,0)),cells:[_5(e.reduce((e,t)=>e+(s.get(t.key)??0),0))]}),emptyState:`No model usage in this range.`,isLoading:i})})})}var dwi=100;function fwi(){let e=Y(),{filters:t,filterKey:n,timestamp:r}=s9(),{interval:i}=i9(r.start,r.end),a=a9(i);return Ey({queryKey:[`metrics`,`scores`,n,i],placeholderData:vy,queryFn:async()=>{let n=await e.listScores({filters:t,pagination:{page:0,perPage:dwi}}),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=KSi(r.start,r.end,a),u=qSi(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 pwi=[h5.green,h5.sky,h5.violet,h5.teal,h5.indigo],mwi=e=>e.toFixed(2),hwi=e=>String(+e.toFixed(2));function gwi(e){return e.map(({scorerId:e,name:t},n)=>({dataKey:e,label:t,color:pwi[n%pwi.length]??h5.neutral}))}function _wi(){let{data:e,isLoading:t,isError:n,isPlaceholderData:r}=fwi(),i=e?.scorers??[],a={title:`Scores`};return n?(0,K.jsx)(t9,{...a,children:(0,K.jsx)(n9,{})}):(0,K.jsx)(t9,{...a,isUpdating:r,children:(0,K.jsx)(e9,{isEmpty:!t&&i.length===0,children:(0,K.jsx)(l9r,{lineStyle:`thin`,data:e?.buckets??[],series:gwi(i),height:`fill`,yDomain:[0,1],valueFormatter:mwi,axisFormatter:hwi,isLoading:t,...c7r})})})}var vwi=[`entityName`,`environment`,`threadId`,`resourceId`,`userId`,`organizationId`,`runId`,`sessionId`],ywi=[`provider`,`model`],bwi=[`serviceName`,`requestId`,`experimentId`],xwi=(e,t)=>({op:`eq`,left:{path:e},right:{literal:t}});function Swi(e){let t=bwi.filter(t=>e[t]!==void 0);if(t.length)return{supported:!1,unsupportedFields:t};let n=[];e.rootEntityType&&n.push(xwi(`entityType`,e.rootEntityType));for(let t of vwi){let r=e[t];r!==void 0&&n.push(xwi(t,r))}for(let t of e.tags??[])n.push({op:`includes`,path:`tags`,value:t});for(let t of ywi){let r=e[t];r!==void 0&&n.push({spans:{some:xwi(t,r)}})}return n.length===0?{supported:!0,where:void 0}:{supported:!0,where:n.length===1?n[0]:{op:`and`,args:n}}}var Cwi=({start:e,end:t})=>({from:e.toISOString(),to:t.toISOString()}),wwi=({start:e,end:t})=>i9(e,t).interval;function Twi(e,t){let n=a9(wwi(t)),r=KSi(t.start,t.end,n).map(e=>({...e,rows:[]})),i=qSi(r,n);for(let t of e)t.bucket&&r[i({timestamp:t.bucket,value:0})??-1]?.rows.push(t);return r}function Ewi({requiresRootSpanFields:e=!1}={}){let{data:t,isLoading:n}=r5(),{timestamp:r,dimensionalFilter:i}=s9();if(n)return{status:`loading`};let a=t?.capabilities;if(a?.traceAggregate!==!0||e&&a.traceQueryRootSpanFields!==!0)return{status:`unavailable`};let o=Swi(i);return o.supported?{status:`ready`,scope:{timeRange:Cwi(r),...o.where?{where:o.where}:{},interval:wwi(r),window:r}}:{status:`unsupported-filter`,unsupportedFields:o.unsupportedFields}}function l9(e,{priority:t,enabled:n}={}){let r=Y();return u$r({request:e,enabled:n,queryOptions:{queryFn:Hxi(()=>r.aggregateTraces(e),t),placeholderData:vy,staleTime:1/0}})}var Dwi=[{measure:`countDistinct.resourceId`,dataKey:`resources`,label:`Resources`,color:h5.sky},{measure:`countDistinct.threadId`,dataKey:`threads`,label:`Threads`,color:h5.green},{measure:`countDistinct.userId`,dataKey:`users`,label:`Users`,color:h5.violet},{measure:`countDistinct.sessionId`,dataKey:`sessions`,label:`Sessions`,color:h5.teal}],Owi=Dwi.map(e=>e.measure),kwi=`Resources and threads`;function Awi(e,t){return e?.measures[t.measure]??0}function jwi({scope:e,onTimeRangeClick:t}){let n=l9({timeRange:e.timeRange,where:e.where,interval:e.interval,measures:Owi,limit:10}),r=l9({timeRange:e.timeRange,where:e.where,measures:Owi}),i=r.data?.rows[0],a=Dwi.filter(e=>Awi(i,e)>0),o=a.map((e,t)=>({dataKey:e.dataKey,label:e.label,color:e.color,emphasis:t===0})),s=Twi(n.data?.rows??[],e.window).map(({rows:e,...t})=>({...t,...Object.fromEntries(a.map(t=>[t.dataKey,Awi(e[0],t)]))})),c=a9(e.interval===`1d`?`1d`:`1h`),l=n.error??r.error,u=n.isLoading||r.isLoading,d={title:kwi,total:l?void 0:a.length?a.map(e=>({label:e.label,value:_5(Awi(i,e)),color:e.color})):_5(0),isLoading:r.isLoading,toolbar:o.length>0&&(0,K.jsx)($7.Toolbar,{children:(0,K.jsx)(w5,{series:o})})};return l?(0,K.jsx)(t9,{...d,children:(0,K.jsx)(n9,{error:l,onRetry:()=>{n.error&&n.refetch(),r.error&&r.refetch()}})}):(0,K.jsx)(t9,{...d,isUpdating:n.isPlaceholderData||r.isPlaceholderData,children:(0,K.jsx)(e9,{isEmpty:!u&&a.length===0,children:(0,K.jsx)(l9r,{lineStyle:`thin`,data:s,series:o,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:_5,axisFormatter:d7r,onBucketClick:t&&(e=>t({window:o9(Number(e.ts),c)})),isLoading:u,...m5})})})}var Mwi={serviceName:`service`,requestId:`request ID`,experimentId:`experiment`};function Nwi({requiresRootSpanFields:e,children:t,...n}){let r=Ewi({requiresRootSpanFields:e});return r.status===`unavailable`?null:r.status===`ready`?t(r.scope):(0,K.jsx)(t9,{...n,toolbar:null,children:r.status===`loading`?(0,K.jsx)($7.Loading,{}):(0,K.jsx)($7.NoData,{message:`Not available with a ${r.unsupportedFields.map(e=>Mwi[e]??e).join(` or `)} filter.`})})}function Pwi(e){return(0,K.jsx)(Nwi,{title:kwi,children:t=>(0,K.jsx)(jwi,{scope:t,...e})})}function Fwi(){return Q7().scope}var Iwi=[`entityName`,`environment`,`serviceName`,`threadId`,`resourceId`,`userId`,`organizationId`,`runId`,`sessionId`,`requestId`,`experimentId`],Lwi=[`tags`,`provider`,`model`],Rwi=(e,t)=>({op:`eq`,left:{path:e},right:{literal:t}});function zwi(e){let t=Lwi.filter(t=>e[t]!==void 0);if(t.length)return{supported:!1,unsupportedFields:t};let n=[];e.rootEntityType&&n.push(Rwi(`entityType`,e.rootEntityType));for(let t of Iwi){let r=e[t];r!==void 0&&n.push(Rwi(t,r))}return n.length===0?{supported:!0,where:void 0}:{supported:!0,where:n.length===1?n[0]:{op:`and`,args:n}}}function Bwi(){let{data:e,isLoading:t}=r5(),{timestamp:n,dimensionalFilter:r}=s9();if(t)return{status:`loading`};if(e?.capabilities.spanAggregate!==!0)return{status:`unavailable`};let i=zwi(r);return i.supported?{status:`ready`,scope:{timeRange:Cwi(n),...i.where?{where:i.where}:{},interval:wwi(n),window:n}}:{status:`unsupported-filter`,unsupportedFields:i.unsupportedFields}}function Vwi(e,{priority:t,enabled:n}={}){let r=Y();return l$r({request:e,enabled:n,queryOptions:{queryFn:Hxi(()=>r.aggregateSpans(e),t),placeholderData:vy,staleTime:1/0}})}var Hwi=`Breakdown`,Uwi={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 Wwi({tab:e,tabs:t,onTabChange:n,isUpdating:r,children:i}){return(0,K.jsx)(t9,{title:Uwi[e],titleMenu:t.length>1?{value:e,onValueChange:n,options:t.map(e=>({value:e,label:Uwi[e]}))}:void 0,isUpdating:r,bodyHeight:`fit`,children:i})}var Gwi={agents:[`agent_run`],workflows:[`workflow_run`],tools:[`tool_call`,`mcp_tool_call`]},Kwi=e=>e in Gwi;function qwi(e){let t=Gwi[e];return t.length===1?{op:`eq`,left:{path:`spanType`},right:{literal:t[0]??``}}:{op:`in`,value:{path:`spanType`},set:[...t]}}var Jwi=e=>e!==`workflows`&&e!==`tools`,Ywi=e=>e!==`models`,Xwi=e=>e===`tools`||e===`models`;function u9(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 d9={trace:1e3,span:500};function Zwi({timeRange:e,where:t}){return{timeRange:e,...t?{where:t}:{},groupBy:[`projectId`],measures:[`count`,`errorRate`,`duration.p95`,`countDistinct.resourceId`,`countDistinct.threadId`],limit:d9.trace}}function Qwi({timeRange:e,where:t},n){return{timeRange:e,...t?{where:t}:{},groupBy:u9(`environments`,n),measures:[`count`,`errorRate`,`duration.p95`],limit:d9.trace}}function $wi(e){let t={op:`exists`,path:`threadId`};return e?{op:`and`,args:[t,e]}:t}function eTi({timeRange:e,where:t},n){return{timeRange:e,where:$wi(t),groupBy:n?[`projectId`,`threadId`]:[`resourceId`,`threadId`],measures:[`count`,`errorRate`,`duration.p95`],limit:d9.trace}}function tTi(e,t,n){return e===`projects`?Zwi(t):e===`environments`?Qwi(t,n):eTi(t,n)}function nTi({timeRange:e,where:t}){return{timeRange:e,where:$wi(t),groupBy:[`resourceId`,`threadId`],measures:[`count`],limit:d9.trace}}function rTi(e){let t=new Map;for(let n of e){let e=oTi(n,`resourceId`);e&&t.set(oTi(n,`threadId`),e)}return t}var iTi=e=>e===`agents`||e===`workflows`?`countDistinct.traceId`:`count`;function aTi(e,{timeRange:t,where:n},r){let i=qwi(e);return{timeRange:t,where:n?{op:`and`,args:[i,n]}:i,groupBy:u9(e,r),measures:[`count`,...iTi(e)===`count`?[]:[`countDistinct.traceId`],`errorCount`,`errorRate`,`duration.p95`],limit:d9.span}}var f9=(e,t)=>{let n=e.measures[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0},oTi=(e,t)=>{let n=e.dimensions?.[t];return n==null?``:String(n)},sTi=(e,t)=>t.map(t=>e.dimensions[t]==null?``:String(e.dimensions[t])).join(`|`);function cTi({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=iTi(e);for(let e of n){let n=l(t.map(t=>oTi(e,t)).join(`|`));n.count=f9(e,u)??0,n.errorRate=f9(e,`errorRate`),n.p95=f9(e,`duration.p95`),n.resources=f9(e,`countDistinct.resourceId`),n.threads=f9(e,`countDistinct.threadId`)}for(let e of i)l(sTi(e,t)).count=e.value;for(let e of r??[]){let n=l(sTi(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 lTi({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=iTi(e);for(let e of n){let n=o(t.map(t=>oTi(e,t)).join(`|`));n.count=f9(e,s)??0,n.errorRate=f9(e,`errorRate`),n.p95=f9(e,`duration.p95`)}for(let e of i)o(sTi(e,t)).count=e.value;for(let e of r){let n=o(sTi(e,t));n.tokens=e.value,n.cost=e.estimatedCost??void 0}return a}function uTi(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 dTi(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:fTi(n,a,i),isNew:!1}}function fTi(e,t,n){return e===`errorRate`?t:n>0?t/n:void 0}function pTi(e,t){if(e.delta!==void 0&&e.delta!==0)return e.delta>0==(t===`count`)?`good`:`bad`}var mTi=[`mastra_model_total_input_tokens`,`mastra_model_total_output_tokens`];function p9({groupBy:e,filters:t,window:n,measure:r=`tokens`,enabled:i=!0}){let a=Y(),{filters:o,filterKey:s}=s9();return Ey({queryKey:[`metrics`,`cost-breakdown`,r,e,t,s,n.start.toISOString(),n.end.toISOString()],staleTime:1/0,enabled:i,queryFn:()=>a.getMetricBreakdown({name:r===`tokens`?mTi:[`mastra_model_total_input_tokens`],groupBy:e,aggregation:r===`tokens`?`sum`:`count`,orderDirection:`DESC`,limit:1e3,filters:{...o,...t,timestamp:n}})})}function hTi({start:e,end:t}){return{start:new Date(2*e.getTime()-t.getTime()),end:new Date(e.getTime())}}var gTi=[`count`,`errorRate`,`p95`,`tokens`,`cost`],_Ti=e=>gTi.includes(e),vTi=e=>Xwi(e)?`Spans`:`Traces`,yTi=`A trace is one end-to-end request, with every step it took.`,bTi=`A span is one step inside a trace, such as a tool call or a model call. One trace can have many.`,xTi=e=>Xwi(e)?bTi:yTi,STi={errorRate:`Errors`,p95:`P95 latency`,tokens:`Tokens`,cost:`Cost`},CTi=e=>e.toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`}),wTi=({start:e,end:t})=>`${CTi(e)} – ${CTi(t)}`;function TTi(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: ${wTi(e)}`,previous:`Previous: ${wTi(hTi(e))}`}}var ETi=(e,t)=>t&&e!==`projects`,DTi=(e,t)=>t===`count`?vTi(e):STi[t];function OTi({tab:e,built:t,previous:n,truncated:r,groupBy:i,usage:a}){return e===`threads`?t.filter(e=>e.name!==``):!n||r?t:uTi(t,n,i,a)}function kTi(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 ATi=(e,t)=>e===`projects`?t.key:t.projectId;function jTi(e,t){let n=ATi(e,t),r=n?{projectId:n}:{};return Kwi(e)?{...r,span:{spanTypes:Gwi[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 MTi(e,t){return t&&t.toUpperCase()!==`USD`?`${_5(e)} ${t}`:y5(e)}function NTi(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}${v5(r)}`}function PTi(e){let t=hTi(e.window);return{...e,window:t,timeRange:Cwi(t)}}var FTi={good:`text-badge-green-foreground`,bad:`text-badge-red-foreground`};function ITi({trend:e,children:t}){return t===void 0?(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`—`}):(0,K.jsx)(`span`,{className:e?FTi[e]:`text-muted-foreground`,children:t})}function LTi({change:e,metric:t}){return e?(0,K.jsx)(ITi,{trend:pTi(e,t),children:NTi(e,t)}):(0,K.jsx)(ITi,{trend:void 0})}function RTi({window:e,label:t}){let{summary:n,current:r,previous:i}=TTi(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 zTi(){return(0,K.jsx)(`span`,{title:`No price for this model`,children:`Not priced`})}function BTi({row:e}){return e.cost===void 0?e.tokens?(0,K.jsx)(zTi,{}):`—`:MTi(e.cost,e.costUnit)}function m9({muted:e=!1,children:t}){return(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:e?`muted`:void 0,className:`tabular-nums`,children:t})}function VTi({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)(Uai,{parts:mPn(n.name,n.provider)}):t})]})}var HTi=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`})]}),UTi={agent:tF,workflow:rP,tool:aF},WTi={agents:`agent`,workflows:`workflow`,tools:`tool`};function GTi({entity:e}){let t=UTi[e];return(0,K.jsx)(gPn,{icon:(0,K.jsx)(t,{className:`size-3`})})}function KTi({provider:e}){return e?(0,K.jsx)(_Pn,{provider:e}):(0,K.jsx)(gPn,{icon:(0,K.jsx)(HTi,{className:`size-3`})})}function qTi({tab:e,row:t}){let n=WTi[e];return n?(0,K.jsx)(GTi,{entity:n}):e===`models`?(0,K.jsx)(KTi,{provider:t.provider}):null}function JTi({tab:e,row:t}){let{projectLabel:n}=Fwi();return(0,K.jsx)(VTi,{mark:(0,K.jsx)(qTi,{tab:e,row:t}),title:kTi(e,t,n),model:e===`models`&&t.name!==``?{name:t.name,provider:t.provider}:void 0})}function YTi({text:e}){return(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`muted`,className:`truncate`,title:e,children:e})}var XTi={asc:Qt,desc:Pt},ZTi=`focus-visible:outline-1 focus-visible:outline-solid focus-visible:outline-border-focus focus-visible:-outline-offset-1`,QTi=`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 $Ti({header:e,explained:t,sorted:n,className:r,...i}){let a=n&&XTi[n];return(0,K.jsxs)(`button`,{type:`button`,...i,className:m(`group/header flex items-center gap-1 rounded whitespace-nowrap hover:text-muted-foreground`,ZTi,r),children:[(0,K.jsx)(`span`,{className:m(t&&QTi),children:e}),a&&(0,K.jsx)(a,{"aria-hidden":!0,className:`size-3`})]})}function eEi({header:e,explained:t,className:n,...r}){return(0,K.jsx)(`span`,{tabIndex:t?0:void 0,...r,className:m(`group/header rounded whitespace-nowrap`,ZTi,n),children:(0,K.jsx)(`span`,{className:m(t&&QTi),children:e})})}function tEi({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)($Ti,{header:e,explained:a,sorted:n,onClick:r,"aria-describedby":o}):(0,K.jsx)(eEi,{header:e,explained:a,"aria-describedby":o});return a?(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{render:s}),(0,K.jsx)(CC,{id:i,keepMounted:!0,side:`top`,className:`max-w-72`,children:t})]}):s}var nEi=`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)]`,rEi=`pt-1.75 pb-2 text-body-sm`,iEi=m(`relative col-span-full grid grid-cols-subgrid items-center px-3`,rEi,nEi),aEi=[`w-32`,`w-24`,`w-36`,`w-20`,`w-28`],oEi=`a, button, input, select, textarea, label, [role="button"], [role="link"], [contenteditable]`;function sEi(e){if(!(e.target instanceof Element))return!1;let t=e.target.closest(oEi);return!!(t&&e.currentTarget.contains(t))}function cEi(e,t,n){return e.align===`end`?`right-0 w-10`:t>0?`left-0 w-16`:m(`left-0`,aEi[n%aEi.length])}function lEi({columns:e,rows:t,getRowKey:n,empty:r,pageSize:i,isLoading:a,...o}){return a?Array.from({length:i??5},(t,n)=>(0,K.jsx)(dEi,{columns:e,rowIndex:n},n)):t.length===0?i?r===void 0?(0,K.jsx)(uEi,{count:i}):(0,K.jsxs)(`div`,{role:`row`,className:`col-span-full grid *:col-start-1 *:row-start-1`,children:[(0,K.jsx)(uEi,{count:i}),(0,K.jsx)(`p`,{role:`cell`,className:`flex items-center justify-center px-3 py-4 text-center text-body-sm text-muted-foreground`,children:r})]}):r===void 0?null:(0,K.jsx)(`div`,{role:`row`,className:`col-span-full`,children:(0,K.jsx)(`p`,{role:`cell`,className:`py-8 text-center text-body-sm text-muted-foreground`,children:r})}):t.map(t=>(0,K.jsx)(fEi,{row:t,columns:e,...o},n(t)))}function uEi({count:e}){return e<=0?null:(0,K.jsx)(`div`,{"aria-hidden":!0,"data-slot":`metrics-table-filler`,className:`col-span-full`,children:Array.from({length:e},(e,t)=>(0,K.jsx)(`div`,{className:rEi,children:``},t))})}function dEi({columns:e,rowIndex:t}){return(0,K.jsx)(`div`,{role:`row`,"aria-busy":!0,className:iEi,children:e.map((e,n)=>(0,K.jsxs)(`div`,{role:`cell`,className:m(`relative flex min-w-0`,e.align===`end`&&`justify-end`),children:[``,(0,K.jsx)(dw,{className:m(`absolute top-1/2 h-3.5 -translate-y-1/2`,cEi(e,n,t))})]},e.id))})}function fEi({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=>{sEi(t)||n?.(e)}:void 0,onKeyDown:n?t=>{t.target===t.currentTarget&&(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),n?.(e))}:void 0,onMouseEnter:r?()=>r(e):void 0,onMouseLeave:r?()=>r(void 0):void 0,className:m(iEi,`rounded text-foreground transition-opacity duration-150`,n&&m(`cursor-pointer`,`focus-visible:outline-1 focus-visible:outline-solid focus-visible:outline-border-focus focus-visible:-outline-offset-1`),s&&`before:bg-fill-subtle`,c&&`opacity-40`),children:t.map(t=>(0,K.jsx)(`div`,{role:`cell`,className:m(`flex min-w-0 items-center`,t.align===`end`&&`justify-end text-right`),children:t.cell(e)},t.id))})}var pEi=`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)]`,mEi={asc:`ascending`,desc:`descending`};function hEi(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 gEi(e,t){return typeof e==`number`&&typeof t==`number`?e-t:String(e).localeCompare(String(t))}function _Ei(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*gEi(n,a)})}var vEi=e=>e.width??(e.align===`end`?`minmax(max-content,1fr)`:`max-content`);function yEi({columns:e,rows:t,getRowKey:n,sort:r,defaultSort:i,onSortChange:a,onRowClick:o,onRowHover:s,isRowDimmed:c,isRowActive:l,rowTitle:u,empty:d,pageSize:f,isLoading:p=!1,"aria-label":h,className:g}){let[_,v]=(0,G.useState)(i),[y,b]=(0,G.useState)(0),x=r??_,S=_Ei(t,e,x),C=f?Math.ceil(S.length/f):1,w=Math.min(y,Math.max(0,C-1)),T=f?S.slice(w*f,(w+1)*f):S,E={gridTemplateColumns:e.map(vEi).join(` `)},D=!p&&C>1,O=e=>{let t=hEi(x,e)??i;v(t),b(0),a?.(t)};return(0,K.jsxs)(`div`,{className:m(`grid min-w-0 gap-3`,g),children:[(0,K.jsxs)(lw,{orientation:`horizontal`,children:[(0,K.jsxs)(`div`,{role:`table`,"aria-label":h,className:`grid min-w-min gap-x-4`,style:E,children:[(0,K.jsx)(`div`,{role:`row`,className:m(`relative col-span-full grid grid-cols-subgrid items-end px-3 pb-1.5 text-label text-placeholder`,pEi),children:e.map(e=>{let t=x?.column===e.id?x.direction:void 0;return(0,K.jsx)(`div`,{role:`columnheader`,"aria-sort":t&&mEi[t],className:m(`flex min-w-0 items-center gap-1`,e.align===`end`&&`justify-end text-right`),children:(0,K.jsx)(tEi,{header:e.header,description:e.description,sorted:t,onSort:e.sortValue?()=>O(e):void 0})},e.id)})}),(0,K.jsx)(lEi,{columns:e,rows:T,getRowKey:n,onRowClick:o,onRowHover:s,isRowDimmed:c,isRowActive:l,rowTitle:u,empty:d,pageSize:f,isLoading:p})]}),f!==void 0&&!p&&T.length>0&&(0,K.jsx)(uEi,{count:f-T.length})]}),D&&(0,K.jsx)(Rdi,{page:w,pageCount:C,onPageChange:b})]})}var bEi=10,xEi={column:`count`,direction:`desc`},SEi={projects:`Project`,agents:`Agent`,workflows:`Workflow`,tools:`Tool`,models:`Model`,threads:`Thread`,environments:`Environment`},CEi={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 wEi({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=Fwi(),[p,m]=(0,G.useState)(xEi),[h,g]=(0,G.useState)(`count`),_=(e=xEi)=>{m(e),_Ti(e.column)&&g(e.column)},v=[r,i,a].filter(e=>e!==void 0);if(v.some(e=>e.isError))return(0,K.jsx)(Wwi,{...d,tab:e,children:(0,K.jsx)(n9,{onRetry:()=>v.forEach(e=>e.isError&&void e.refetch())})});let y=v.some(e=>e.isLoading),b=Ywi(e),x=i!==void 0,S=ETi(e,d.byProject),C=r?.data?.truncated===!0,w=y?[]:cTi({tab:e,groupBy:t,aggregateRows:r?.data?.rows,usageGroups:i?.data?.groups,spanGroups:a?.data?.groups,resources:o?.data?rTi(o.data.rows):void 0}),E=[s,c,l].every(e=>!e||!e.isLoading&&!e.isError)&&!y?lTi({tab:e,groupBy:t,aggregateRows:s?.data?.rows,usageGroups:c?.data?.groups,spanGroups:l?.data?.groups}):void 0,D=OTi({tab:e,built:w,previous:E,truncated:C,groupBy:t,usage:x}),O=vTi(e),k=e=>E?dTi(e,E.get(e.key),h):void 0,A=e=>e.projectId?f.projectLabel?.(e.projectId)??e.projectId:`—`,j={id:`name`,header:SEi[e],width:`minmax(12rem,3fr)`,cell:t=>(0,K.jsx)(JTi,{tab:e,row:t})},M={id:`project`,header:`Project`,width:`minmax(8rem,2fr)`,cell:e=>(0,K.jsx)(YTi,{text:A(e)})},N={id:`resource`,header:`Resource`,width:`minmax(6rem,1fr)`,cell:e=>(0,K.jsx)(YTi,{text:e.resource??`—`})},P=[{id:`errorRate`,header:`Errors`,align:`end`,sortValue:e=>e.errorRate,cell:e=>(0,K.jsx)(m9,{muted:!0,children:e.errorRate===void 0?`—`:v5(e.errorRate)})},{id:`p95`,header:`P95 latency`,align:`end`,sortValue:e=>e.p95,cell:e=>(0,K.jsx)(m9,{muted:!0,children:e.p95===void 0?`—`:u7r(e.p95)})}],F=[{id:`tokens`,header:`Tokens`,align:`end`,sortValue:e=>e.tokens,cell:e=>(0,K.jsx)(m9,{muted:!0,children:e.tokens===void 0?`—`:_5(e.tokens)})},{id:`cost`,header:`Cost`,align:`end`,sortValue:e=>e.cost,cell:e=>(0,K.jsx)(m9,{muted:!0,children:(0,K.jsx)(BTi,{row:e})})}],I={id:`count`,header:O,align:`end`,description:xTi(e),sortValue:e=>e.count,cell:e=>(0,K.jsx)(m9,{children:_5(e.count)})},L={id:`change`,header:`% Change`,align:`end`,description:(0,K.jsx)(RTi,{window:n,label:DTi(e,h)}),sortValue:e=>k(e)?.change,cell:e=>(0,K.jsx)(m9,{children:(0,K.jsx)(LTi,{change:k(e),metric:h})})},R=[j,...S?[M]:[],...e===`threads`?[N]:[],...b?P:[],...x?F:[],I,L];return(0,K.jsx)(Wwi,{...d,tab:e,isUpdating:r?.isPlaceholderData,children:(0,K.jsxs)(e9,{children:[(0,K.jsx)(yEi,{"aria-label":`${SEi[e]} breakdown`,columns:R,rows:D,getRowKey:e=>e.key,sort:p,defaultSort:xEi,onSortChange:_,onRowClick:d.onRowClick&&(t=>d.onRowClick?.(jTi(e,t))),pageSize:bEi,isLoading:y,empty:CEi[e]},e),!y&&C&&(0,K.jsxs)(T,{variant:`caption`,tone:`muted`,className:`pt-2`,children:[`Showing the `,_5(u),` busiest; sorting covers only these.`]})]})})}var TEi={entityType:`agent`};function EEi({tab:e,scope:t,...n}){let r=u9(e,n.byProject),i=Jwi(e),a=PTi(t),o=Vwi(aTi(e,t,n.byProject)),s=Vwi(aTi(e,a,n.byProject),{priority:Lxi.last}),c=p9({groupBy:r,filters:TEi,window:t.window,enabled:i}),l=p9({groupBy:r,filters:TEi,window:a.window,enabled:i});return(0,K.jsx)(wEi,{...n,tab:e,groupBy:r,window:t.window,aggregate:o,totals:i?c:void 0,previousAggregate:s,previousUsage:i?l:void 0,limit:d9.span})}function DEi(e){let t=u9(`models`,e.byProject),{timestamp:n}=s9(),r=hTi(n),i=p9({groupBy:t,window:n}),a=p9({groupBy:t,window:n,measure:`modelSpans`}),o=p9({groupBy:t,window:r}),s=p9({groupBy:t,window:r,measure:`modelSpans`});return(0,K.jsx)(wEi,{...e,tab:`models`,groupBy:t,window:n,totals:i,spans:a,previousUsage:o,previousSpans:s,limit:d9.trace})}function OEi({tab:e,scope:t,...n}){let r=u9(e,n.byProject),i=PTi(t),a=l9(tTi(e,t,n.byProject)),o=l9(tTi(e,i,n.byProject),{priority:Lxi.last}),s=l9(nTi(t),{enabled:e===`threads`&&n.byProject}),c=p9({groupBy:r,window:t.window}),l=n.byProject?s:a,u=p9({groupBy:r,window:i.window});return(0,K.jsx)(wEi,{...n,tab:e,groupBy:r,window:t.window,aggregate:a,totals:c,resources:e===`threads`?l:void 0,previousAggregate:o,previousUsage:u,limit:d9.trace})}var kEi={serviceName:`service`,requestId:`request ID`,experimentId:`experiment`,tags:`tags`,provider:`provider`,model:`model`};function AEi({tab:e,traceGate:t,spanGate:n,...r}){if(e===`models`)return(0,K.jsx)(DEi,{...r},e);let i=Kwi(e)?n:t;return i.status===`unsupported-filter`?(0,K.jsx)(Wwi,{...r,tab:e,children:(0,K.jsx)($7.NoData,{message:`Not available with a ${i.unsupportedFields.map(e=>kEi[e]??e).join(` or `)} filter.`})}):Kwi(e)?n.status===`ready`&&(0,K.jsx)(EEi,{...r,tab:e,scope:n.scope},e):t.status===`ready`&&(0,K.jsx)(OEi,{...r,tab:e,scope:t.scope},e)}function jEi({chosen:e,traceScope:t,spanGate:n,...r}){let i=l9(Zwi(t)).data?.rows.filter(e=>(e.measures.count??0)>0).length,a=e??MEi(i);return(0,K.jsx)(AEi,{...r,tab:a,traceGate:{status:`ready`,scope:t},spanGate:n})}function MEi(e){return e===void 0||e>=2?`projects`:`agents`}var NEi=[`projects`,`agents`,`workflows`,`tools`,`models`,`threads`,`environments`],PEi=NEi.filter(e=>e!==`projects`);function FEi({onRowClick:e}){let t=Fwi().projectLabel!==void 0,n=Ewi(),r=Bwi(),[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)(t9,{title:Hwi,bodyHeight:`fit`,children:(0,K.jsx)($7.Loading,{})});let o={tabs:t?NEi:PEi,onTabChange:a,onRowClick:e,byProject:t};return t&&n.status===`ready`?(0,K.jsx)(jEi,{...o,chosen:i,traceScope:n.scope,spanGate:r}):(0,K.jsx)(AEi,{...o,tab:i??`agents`,traceGate:n,spanGate:r})}function IEi({experiment:e,metrics:t}){let{data:n}=WP({experimentId:e.id,experimentStatus:e.status,queryOptions:{enabled:!!e.id}}),{data:r,isLoading:i}=E_i({experiments:(0,G.useMemo)(()=>[{id:e.id,status:e.status}],[e.id,e.status]),supportsMetrics:t?.isEnabled??!1}),a=e.status===`running`||e.status===`pending`||i,o=(0,G.useMemo)(()=>{if(!n)return;let e=Object.values(n).flat();return e.length===0?null:e.reduce((e,t)=>e+t.score,0)/e.length},[n]),s=e.startedAt??e.createdAt,c=!e.startedAt||!e.completedAt?`—`:xw(new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime())??`—`,l=r[e.id]?.summary,u=V7(l),d=l?.inputTokens===void 0&&l?.outputTokens===void 0?`input + output`:(0,K.jsxs)(Gw,{singleLine:!0,children:[(0,K.jsxs)(Gw.Item,{children:[B7(l.inputTokens??0),` in`]}),(0,K.jsxs)(Gw.Item,{children:[B7(l.outputTokens??0),` out`]})]}),f=t?.isEnabled?t.data?.avgAgentDurationMs:void 0,p=f==null?void 0:xw(Math.round(f)),m=p?`${p} avg per item`:s?`started ${Fw(new Date(s),`date-time`)}`:`not started`;return(0,K.jsxs)(fxi,{children:[t?.isEnabled&&(0,K.jsx)(LSi,{label:`Total cost`,icon:mr,value:l?.estimatedCost===void 0?`—`:z7(l.estimatedCost,l.costUnit),detail:`estimated`,isLoading:a}),(0,K.jsx)(LSi,{label:`Run duration`,icon:vc,value:c,detail:m}),t?.isEnabled&&(0,K.jsx)(LSi,{label:`Total tokens`,icon:Gi,value:u===void 0?`—`:B7(u),detail:d,isLoading:a}),(0,K.jsx)(LSi,{label:`Avg score`,icon:Di,value:o==null?`—`:o.toFixed(3),detail:o==null?`no scores`:`across all scorers`,isLoading:o===void 0})]})}function LEi({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)(Hc,{}),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)(Xbi,{selectedResults:n,vocabulary:r,onAddTag:e.addTagToSelected,disabled:o})]})]})}var REi=e=>Math.floor(Math.random()*e);function zEi({messages:e,intervalMs:t=3e3}){let n=e.length,[r,i]=(0,G.useState)(()=>REi(n));return(0,G.useEffect)(()=>{if(n<2)return;let e=setInterval(()=>i(e=>(e+1+REi(n-1))%n),t);return()=>clearInterval(e)},[n,t]),n===0?null:(0,K.jsx)(K.Fragment,{children:e[r%n]})}function BEi(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 VEi=[`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…`],HEi=`Waiting to start…`;function UEi({experiment:e}){let{status:t,totalItems:n,succeededCount:r,failedCount:i,startedAt:a}=e,o=BEi(),s=r+i,c=n===1?`item`:`items`,l=t===`pending`,u=a?Math.floor((o-new Date(a).getTime())/1e3)*1e3:void 0,d=!l&&u!==void 0?xw(u):void 0;return(0,K.jsx)(RC,{variant:`fill`,as:`h2`,iconSlot:(0,K.jsx)(Qc,{}),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?HEi:(0,K.jsx)(zEi,{messages:VEi})}),(0,K.jsxs)(Gw,{className:`justify-center tabular-nums`,children:[(0,K.jsxs)(Gw.Item,{children:[s,` / `,n,` `,c,` finished`]}),d&&(0,K.jsxs)(Gw.Item,{children:[d,` elapsed`]})]})]})})}var WEi={pending:{icon:(0,K.jsx)(lr,{className:`size-4 text-warning-foreground`}),label:G7.pending},running:{icon:(0,K.jsx)(Qc,{size:`sm`}),label:G7.running},completed:{icon:(0,K.jsx)(Kn,{className:`size-4 text-muted-foreground`}),label:G7.completed},failed:{icon:(0,K.jsx)(ir,{className:`size-4 text-destructive-foreground`}),label:G7.failed}};function GEi({status:e,className:t}){let n=WEi[e]??WEi.pending;return(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{render:(0,K.jsx)(`span`,{tabIndex:0,className:m(`flex shrink-0 items-center`,t),children:n.icon})}),(0,K.jsx)(CC,{children:n.label})]})}var KEi=()=>{let{experimentId:e}=Ab(),{data:t}=OIt({experimentId:e??``,queryOptions:{enabled:!!e,retryOnMount:!1}});return{experimentId:e,experiment:t}},qEi=()=>{let{experimentId:e,experiment:t}=KEi(),n=t?.datasetId??``,{data:r}=vIt({datasetId:n,experimentId:e??``,queryOptions:{enabled:!!(n&&e),retryOnMount:!1}});return r??t};function JEi(){let{experimentId:e,experiment:t}=KEi();if(!e)return null;let n=e.length>8?`${e.slice(0,8)}...`:e;return t?.name||n}function YEi(){let e=qEi();return e?.status?(0,K.jsx)(GEi,{status:e.status}):null}function XEi(){let e=qEi();if(!e||e.status===`running`||e.status===`pending`)return null;let{totalItems:t,failedCount:n}=e,r=`${t} ${t===1?`item`:`items`}`;return(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`tabular-nums`,children:(0,K.jsxs)(Gw,{children:[(0,K.jsx)(Gw.Item,{children:r}),n>0&&(0,K.jsxs)(Gw.Item,{children:[n,` errored`]})]})})}function ZEi({datasetId:e,experimentId:t}){let[n,r]=(0,G.useState)(!1),{updateExperimentResult:i}=zP();return{addTag:(0,G.useCallback)(async(a,o)=>{let s=o.filter(e=>!(e.tags??[]).includes(a));if(n||s.length===0)return;r(!0);let c=0;try{c=(await Promise.allSettled(s.map(n=>i.mutateAsync({datasetId:e,experimentId:t,resultId:n.id,tags:[...n.tags??[],a]})))).filter(e=>e.status===`fulfilled`).length}finally{r(!1)}c>0?UC(`Tag "${a}" added to ${c} result${c>1?`s`:``}`):UC.error(`Failed to add tag`)},[e,t,n,i]),isPending:n}}function QEi(e,t){let{data:n}=VP({datasetId:e,queryOptions:{enabled:!!e}});return(0,G.useMemo)(()=>[...new Set([...n?.tags??[],...t.flatMap(e=>e.tags??[])])].sort(),[n?.tags,t])}function $Ei({datasetId:e,experimentId:t,results:n}){let[r,i]=(0,G.useState)(new Set),[a,o]=(0,G.useState)(!1),{updateExperimentResult:s}=zP(),{addTag:c,isPending:l}=ZEi({datasetId:e,experimentId:t}),u=QEi(e,n),d=(0,G.useMemo)(()=>n.filter(e=>r.has(e.id)),[n,r]),f=(0,G.useCallback)(e=>{i(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),p=(0,G.useCallback)(()=>i(new Set),[]);return{selectedIds:r,selectedResults:d,toggleSelect:f,toggleSelectAll:(0,G.useCallback)(()=>{i(e=>n.length>0&&n.every(t=>e.has(t.id))?new Set:new Set(n.map(e=>e.id)))},[n]),clearSelection:p,flagSelectedForReview:(0,G.useCallback)(async()=>{if(a||r.size===0)return;o(!0);let n=new Set;try{for(let i of r)try{await s.mutateAsync({datasetId:e,experimentId:t,resultId:i,status:`needs-review`}),n.add(i)}catch{}}finally{o(!1)}n.size>0&&(i(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),UC(`${n.size} result${n.size>1?`s`:``} flagged for review`))},[e,t,a,r,s]),isFlagging:a,addTagToSelected:(0,G.useCallback)(e=>c(e,d),[c,d]),isTagging:l,tagVocabulary:u}}var eDi=[];function tDi({crumbs:e,children:t}){return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:e}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiment`}),(0,K.jsx)(`div`,{}),(0,K.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:t})]})}function nDi(){let{experimentId:e}=Ab(),t=[sF(`/experiments`),{id:`experiment`,Component:JEi,icon:YEi,Action:XEi}],n=kb(),[r,i]=(0,G.useState)(!1),a=i5(),{data:o,isLoading:s,error:c}=OIt({experimentId:e??``,queryOptions:{enabled:!!e}}),l=o?.datasetId??``,{data:u,isLoading:d,error:f}=vIt({datasetId:l,experimentId:e??``,queryOptions:{enabled:!!l&&!!e}}),p=u?.status===`completed`||u?.status===`failed`,{data:m,isLoading:h,setEndOfListElement:g,isFetchingNextPage:_,hasNextPage:v}=bIt({datasetId:l,experimentId:e??``,experimentStatus:u?.status,queryOptions:{enabled:!!l&&!!e&&p}}),{supportsMetrics:y}=x7(),b=D_i({experimentId:e,experimentStatus:u?.status,supportsMetrics:y,queryOptions:{enabled:!!e&&y&&p}}),x=$Ei({datasetId:l,experimentId:e??``,results:m??eDi}),S=c??f;if(!e||s||d)return null;if(S&&JP(S))return(0,K.jsx)(tDi,{crumbs:t,children:(0,K.jsx)(jU,{})});if(S&&YP(S))return(0,K.jsx)(tDi,{crumbs:t,children:(0,K.jsx)(AU,{resource:`datasets`})});let C=(0,K.jsx)(tDi,{crumbs:t,children:(0,K.jsx)(RC,{titleSlot:`Experiment not found`,descriptionSlot:`No experiment with id "${e}".`,actionSlot:(0,K.jsx)(X,{render:(0,K.jsx)(Vb,{to:`/experiments`}),icon:(0,K.jsx)(Rt,{}),children:`Back to experiments`})})});return S&&XP(S)?C:S?(0,K.jsx)(tDi,{crumbs:t,children:(0,K.jsx)(RC,{tone:`error`,titleSlot:`Failed to load experiment`,descriptionSlot:S instanceof Error?S.message:`An unexpected error occurred. Please try again.`})}):!l||!u?C:(0,K.jsx)(z_i,{experimentId:e,datasetId:l,experimentStatus:u.status,results:m??[],isLoadingResults:h,hasNextPage:v,children:(0,K.jsxs)(`div`,{className:`h-full`,children:[(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:t}),headerActions:(0,K.jsx)(qbi,{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)(IEi,{experiment:u,metrics:b}),(0,K.jsxs)(`div`,{className:`grid content-start gap-1`,children:[(0,K.jsx)(LEi,{selection:x}),(0,K.jsx)(cvi,{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)(UEi,{experiment:u})]}),(0,K.jsx)(dxi,{withQueryTrace:a.enabled,withFeedback:a.enabled}),(0,K.jsx)(Yvi,{open:r,onOpenChange:i,experimentId:e,experimentName:u.name??void 0,onSuccess:()=>n(`/experiments`)})]})})}function rDi({tag:e,onRename:t,onRemove:n}){let[r,i]=(0,G.useState)(!1),[a,o]=(0,G.useState)(e),s=(0,G.useRef)(null);(0,G.useEffect)(()=>{r&&(s.current?.focus(),s.current?.select())},[r]);let c=()=>{let n=a.trim();n&&n!==e&&t(n),i(!1)};return r?(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 rounded-md border border-border bg-card px-1`,children:[(0,K.jsx)(ZM,{variant:`unstyled`,ref:s,value:a,onChange:e=>o(e.target.value),onKeyDown:t=>{t.key===`Enter`&&(t.preventDefault(),c()),t.key===`Escape`&&(o(e),i(!1))},onBlur:c,className:`h-auto w-20 bg-transparent px-0 py-0.5 text-caption text-muted-foreground outline-hidden`}),(0,K.jsx)(`button`,{type:`button`,onMouseDown:e=>{e.preventDefault(),c()},className:m(ZC,`p-0.5`),children:(0,K.jsx)(Bn,{className:`h-3 w-3`})})]}):(0,K.jsxs)(`span`,{className:`group inline-flex items-center gap-0.5 rounded-md border border-border bg-card px-1.5 py-0.5 text-muted-foreground`,children:[(0,K.jsx)(T,{as:`span`,variant:`caption`,children:e}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>{o(e),i(!0)},className:m(ZC,`p-0.5 opacity-0 transition-opacity group-hover:opacity-100`),title:`Edit tag`,children:(0,K.jsx)(Ro,{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)(Hc,{className:`h-3 w-3`})})]})}function iDi({selectedCount:e,vocabulary:t,onApplyTag:n,onRemoveTag:r,onNewTag:i,size:a=`sm`}){let[o,s]=(0,G.useState)(!1),[c,l]=(0,G.useState)(``),u=t.filter(e=>e.toLowerCase().includes(c.toLowerCase())),d=c.trim()&&!t.includes(c.trim());return(0,K.jsxs)($M,{open:o,onOpenChange:s,children:[(0,K.jsx)(eN,{asChild:!0,children:(0,K.jsxs)(X,{size:a,icon:(0,K.jsx)(Qs,{}),children:[`Tag `,e,` items`]})}),(0,K.jsxs)(tN,{className:`w-56 p-2`,align:`end`,children:[(0,K.jsx)(ZM,{value:c,onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Enter`&&c.trim()&&(e.preventDefault(),d?i(c.trim()):n(c.trim()),l(``))},placeholder:`Search or create tag`,className:`mb-1 h-7 text-caption`,autoFocus:!0}),(0,K.jsxs)(`div`,{className:`max-h-40 space-y-0.5 overflow-y-auto`,children:[u.map(e=>(0,K.jsxs)(`div`,{className:`flex items-center justify-between rounded px-2 py-1 hover:bg-fill-subtle`,children:[(0,K.jsx)(`button`,{type:`button`,onClick:()=>n(e),className:`flex-1 text-left text-muted-foreground`,children:(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`block`,children:e})}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>r(e),className:`ml-2 text-placeholder hover:text-destructive-foreground`,children:(0,K.jsx)(Hc,{className:`h-3 w-3`})})]},e)),d&&(0,K.jsx)(`button`,{type:`button`,onClick:()=>{i(c.trim()),l(``)},className:`w-full rounded px-2 py-1 text-left text-info-indicator hover:bg-fill-subtle`,children:(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[`Create & apply "`,c.trim(),`"`]})})]})]})]})}var aDi=[{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`}],oDi=`__untagged__`,sDi=`all`,cDi=[{value:`review`,label:`Review queue`},{value:`completed`,label:`Completed`}];function lDi({datasetId:e,experimentId:t,experiments:n,isLoadingExperiments:r,targetType:i,targetId:a,featuredItemId:o,toolbarStart:s,renderFilters:c,toolbarEnd:l,onCreateScorer:u,breadcrumbs:d,withQueryTrace:f,withFeedback:p}){let h=Y(),{paths:g}=_l(),{data:_}=VP({datasetId:e??``,queryOptions:{enabled:!!e}}),v=Gvi({experimentId:t,targetType:i,targetId:a,experiments:n,isLoadingExperiments:r}),y=Kvi({experimentId:t,targetType:i,targetId:a,experiments:n,isLoadingExperiments:r}),{data:b,isLoading:x}=v,{data:S,isLoading:C}=y,{updateExperimentResult:w}=zP(),[E,D]=(0,G.useState)(o??null);(0,G.useEffect)(()=>{o!==void 0&&D(o)},[o]);let[O,k]=(0,G.useState)(null),[A,j]=(0,G.useState)(new Set),[M,N]=(0,G.useState)(!1),[P,F]=(0,G.useState)(!1),[I,L]=(0,G.useState)(!1),[R,z]=(0,G.useState)(``),[B,V]=(0,G.useState)(``),[H,ee]=(0,G.useState)(``),[te,U]=(0,G.useState)([]),[W,ne]=(0,G.useState)(!1),re=(0,G.useMemo)(()=>b??[],[b]),ie=(0,G.useMemo)(()=>{let e=new Set;if(_?.tags)for(let t of _.tags)e.add(t);for(let t of re)for(let n of t.tags)e.add(n);return[...e].sort()},[_,re]),ae=(0,G.useMemo)(()=>O?O===oDi?re.filter(e=>e.tags.length===0):re.filter(e=>e.tags.includes(O)):re,[re,O]),oe=(0,G.useMemo)(()=>{let e=new Map,t=0;for(let n of re){n.tags.length===0&&t++;for(let t of n.tags)e.set(t,(e.get(t)??0)+1)}let n=[...e.entries()].sort((e,t)=>t[1]-e[1]).map(([e])=>({value:e,label:e}));return[{value:sDi,label:`All tags`},...t>0?[{value:oDi,label:`Untagged`}]:[],...n]},[re]),se=!!O||M,ce=(0,G.useCallback)(()=>{k(null),N(!1),D(null)},[]),le=(0,G.useCallback)((e,t)=>{let n=re.find(t=>t.id===e);n?.experimentId&&n?.datasetId&&w.mutate({datasetId:n.datasetId,experimentId:n.experimentId,resultId:n.id,tags:t})},[re,w]),ue=(0,G.useCallback)(e=>{let t=re.find(t=>t.id===e);j(t=>{let n=new Set(t);return n.delete(e),n}),E===e&&D(null),t?.experimentId&&t?.datasetId&&w.mutate({datasetId:t.datasetId,experimentId:t.experimentId,resultId:t.id,status:null})},[re,w,E]),de=(0,G.useCallback)(e=>{let t=re.find(t=>t.id===e);j(t=>{let n=new Set(t);return n.delete(e),n}),E===e&&D(null),t?.experimentId&&t?.datasetId&&w.mutate({datasetId:t.datasetId,experimentId:t.experimentId,resultId:t.id,status:`complete`})},[re,w,E]),fe=(0,G.useMemo)(()=>{let e=M?S??[]:ae;return!M||!O?e:O===oDi?e.filter(e=>e.tags.length===0):e.filter(e=>e.tags.includes(O))},[M,S,ae,O]),pe=M?C:!1,me=(0,G.useMemo)(()=>new Set(fe.map(e=>e.id)),[fe]),he=(0,G.useMemo)(()=>[...A].filter(e=>me.has(e)).length,[A,me]),ge=fe.length>0&&he===fe.length,_e=(0,G.useCallback)(e=>{j(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),ve=(0,G.useCallback)(()=>{j(ge?new Set:new Set(fe.map(e=>e.id)))},[ge,fe]),ye=(0,G.useCallback)(e=>{for(let t of A){let n=re.find(e=>e.id===t);n&&!n.tags.includes(e)&&le(t,[...n.tags,e])}},[re,A,le]),be=(0,G.useCallback)(e=>{for(let t of A){let n=re.find(e=>e.id===t);n&&n.tags.includes(e)&&le(t,n.tags.filter(t=>t!==e))}},[re,A,le]),xe=(0,G.useCallback)(()=>{for(let e of A)de(e);j(new Set)},[A,de]),Se=(0,G.useCallback)(()=>{for(let e of A)ue(e);j(new Set)},[A,ue]),Ce=(0,G.useCallback)(()=>{z(``),L(!0)},[]),we=(0,G.useCallback)(async()=>{if(B&&H){F(!0),L(!1);try{let e=re.filter(e=>A.has(e.id));if(e.length===0){F(!1);return}let t=await h.clusterFailures({modelId:`${B}/${H}`,items:e.map(e=>({id:e.id,input:e.input,output:e.output??void 0,error:typeof e.error==`string`?e.error:e.error?String(e.error):void 0,scores:e.scores,existingTags:e.tags.length>0?e.tags:void 0})),availableTags:ie.length>0?ie:void 0,prompt:R||void 0});t.proposedTags&&t.proposedTags.length>0&&(U(t.proposedTags.map(e=>({...e,accepted:!0}))),ne(!0))}catch(e){console.error(`Analysis failed:`,e)}finally{F(!1)}}},[B,H,re,A,h,ie,R]),Te=(0,G.useCallback)(()=>{for(let e of te){if(!e.accepted)continue;let t=re.find(t=>t.id===e.itemId);if(t){let n=[...new Set([...t.tags,...e.tags])];le(t.id,n)}}ne(!1)},[te,re,le]),Ee=(0,G.useCallback)(e=>{D(t=>t===e?null:e)},[]),De=(0,G.useMemo)(()=>E?fe.find(e=>e.id===E)??null:null,[E,fe]),{data:Oe}=WP({experimentId:De?.experimentId??``,queryOptions:{enabled:!!De?.experimentId}}),ke=M?y:v,Ae=fe.length===0||!(!E||De);(0,G.useEffect)(()=>{Ae&&ke.hasNextPage&&!ke.isFetching&&ke.fetchNextPage({cancelRefetch:!1})},[Ae,ke]);let je=E?fe.findIndex(e=>e.id===E):-1,Me=je>0?()=>D(fe[je-1].id):void 0,Ne=je>=0&&je<fe.length-1?()=>D(fe[je+1].id):void 0,Pe=!M&&A.size>0,Fe=!!u&&!M&&ae.length>0,Ie=M?`completed`:`review`,Le=e=>{N(e===`completed`),D(null)},Re=(0,K.jsxs)(jq,{children:[(0,K.jsx)(jq.Start,{children:c?(0,K.jsxs)(K.Fragment,{children:[s,c({status:Ie,onStatusChange:Le,tag:O,onTagChange:k,tagOptions:oe.filter(e=>e.value!==sDi)})]}):(0,K.jsxs)(K.Fragment,{children:[s,(0,K.jsxs)(WA,{value:Ie,onValueChange:e=>Le(e===`completed`?`completed`:`review`),children:[(0,K.jsx)(KA,{"aria-label":`Status`,size:`md`,className:`whitespace-nowrap`,children:(0,K.jsx)(GA,{placeholder:`Select an option`})}),(0,K.jsx)(qA,{children:cDi.map(e=>(0,K.jsx)(JA,{value:e.value,children:e.label},e.value))})]}),oe.length>1&&(0,K.jsxs)(WA,{value:O??sDi,onValueChange:e=>k(e===sDi?null:e),children:[(0,K.jsx)(KA,{"aria-label":`Tags`,size:`md`,className:`whitespace-nowrap`,children:(0,K.jsx)(GA,{placeholder:`Select an option`})}),(0,K.jsx)(qA,{children:oe.map(e=>(0,K.jsx)(JA,{value:e.value,children:e.label},e.value))})]}),se&&(0,K.jsx)(X,{onClick:ce,size:`sm`,variant:`default`,icon:(0,K.jsx)(Hc,{}),children:`Reset`})]})}),(Pe||l||Fe)&&(0,K.jsxs)(jq.End,{children:[l,Fe&&(0,K.jsxs)(X,{size:`md`,onClick:()=>u?.(ae.map(e=>({input:e.input,output:e.output}))),children:[(0,K.jsx)(TC,{size:`xs`,children:(0,K.jsx)(Di,{})}),`Create scorer`]}),Pe&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(iDi,{size:`md`,selectedCount:A.size,vocabulary:ie,onApplyTag:ye,onRemoveTag:be,onNewTag:e=>ye(e)}),(0,K.jsx)(X,{variant:`primary`,onClick:xe,icon:(0,K.jsx)(Wn,{}),children:`Mark as reviewed`}),(0,K.jsxs)(mD,{children:[(0,K.jsx)(mD.Trigger,{asChild:!0,children:(0,K.jsx)(X,{size:`icon-md`,disabled:P,"aria-label":`More actions`,children:P?(0,K.jsx)(Qc,{className:`h-4 w-4`}):(0,K.jsx)(Mr,{})})}),(0,K.jsxs)(mD.Content,{align:`end`,children:[(0,K.jsxs)(mD.Item,{onSelect:Ce,children:[(0,K.jsx)(TC,{size:`xs`,children:(0,K.jsx)(Bs,{})}),`Analyze`]}),(0,K.jsx)(mD.Separator,{}),(0,K.jsxs)(mD.Item,{onSelect:Se,children:[(0,K.jsx)(TC,{size:`xs`,children:(0,K.jsx)(Sc,{})}),`Remove from queue`]})]})]})]})]})]});if(x)return(0,K.jsxs)(uw,{breadcrumbs:d,actionRow:Re,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(Qc,{fill:!0})]});let ze=(0,K.jsx)(lxi,{withQueryTrace:f,withFeedback:p,result:De??void 0,title:`Review item ${De?.id??``}`,scores:De?Oe?.[De.itemId]:void 0,experimentLink:De?.experimentId?g.experimentItemLink(De.experimentId,De.itemId):void 0,onComplete:M||!De?void 0:()=>de(De.id),onPrevious:Me,onNext:Ne,onClose:()=>D(null)});return(0,K.jsxs)(uw,{breadcrumbs:d,actionRow:Re,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(_E,{open:I,onOpenChange:L,children:(0,K.jsxs)(vE,{children:[(0,K.jsxs)(yE,{children:[(0,K.jsx)(SE,{children:`Analyze Items`}),(0,K.jsx)(CE,{children:`Use an LLM to automatically suggest tags for the selected items.`})]}),(0,K.jsxs)(xE,{children:[(0,K.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[(0,K.jsxs)(fA,{className:`gap-1`,children:[(0,K.jsx)(mA,{children:`Provider`}),(0,K.jsx)(LJ,{value:B,onValueChange:V})]}),(0,K.jsxs)(fA,{className:`gap-1`,children:[(0,K.jsx)(mA,{children:`Model`}),(0,K.jsx)(RJ,{llmId:B,value:H,onValueChange:ee})]})]}),(0,K.jsxs)(T,{variant:`meta`,tone:`muted`,children:[A.size,` item`,A.size===1?``:`s`,` will be analyzed`]}),(0,K.jsxs)(fA,{className:`gap-1`,children:[(0,K.jsx)(mA,{children:`Instructions (optional)`}),(0,K.jsx)(ZA,{className:`text-caption`,value:R,onChange:e=>z(e.target.value),placeholder:`E.g., Focus on safety issues and factual errors`,rows:3})]})]}),(0,K.jsxs)(bE,{children:[(0,K.jsx)(wE,{children:`Cancel`}),(0,K.jsx)(gE,{onConfirm:we,disabled:!B||!H||P,children:`Analyze`})]})]})}),(0,K.jsx)(_E,{open:W,onOpenChange:ne,children:(0,K.jsxs)(vE,{size:`lg`,children:[(0,K.jsxs)(yE,{children:[(0,K.jsx)(SE,{children:`Review Proposed Tags`}),(0,K.jsxs)(CE,{children:[te.filter(e=>e.accepted).length,` of `,te.length,` proposals selected`]})]}),(0,K.jsx)(xE,{children:te.map((e,t)=>{let n=re.find(t=>t.id===e.itemId);return(0,K.jsx)(`div`,{className:m(`rounded-lg border p-3`,!e.accepted&&`opacity-50`),children:(0,K.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,K.jsx)(XM,{checked:e.accepted,onCheckedChange:e=>U(n=>n.map((n,r)=>r===t?{...n,accepted:!!e}:n))}),(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsx)(T,{variant:`meta`,tone:`muted`,className:`block truncate`,children:n?typeof n.input==`string`?n.input.slice(0,100):JSON.stringify(n.input).slice(0,100):e.itemId}),(0,K.jsx)(`div`,{className:`mt-1.5 flex flex-wrap gap-1`,children:e.tags.map((e,n)=>(0,K.jsx)(rDi,{tag:e,onRename:e=>U(r=>r.map((r,i)=>i===t?{...r,tags:r.tags.map((t,r)=>r===n?e:t)}:r)),onRemove:()=>U(e=>e.map((e,r)=>r===t?{...e,tags:e.tags.filter((e,t)=>t!==n)}:e))},`${e}-${n}`))}),e.reason&&(0,K.jsx)(T,{variant:`meta`,tone:`muted`,className:`mt-1 block italic`,children:e.reason})]})]})},e.itemId)})}),(0,K.jsxs)(bE,{children:[(0,K.jsx)(wE,{children:`Cancel`}),(0,K.jsxs)(gE,{onConfirm:Te,disabled:te.filter(e=>e.accepted).length===0,children:[`Accept `,te.filter(e=>e.accepted).length,` proposals`]})]})]})}),(0,K.jsxs)(`div`,{className:`grid h-full min-h-0 w-full grid-cols-1 gap-4 overflow-hidden`,children:[(0,K.jsx)(`div`,{className:`min-h-0 w-full overflow-hidden`,children:pe||fe.length===0&&ke.hasNextPage?(0,K.jsx)(Qc,{fill:!0}):fe.length===0?(0,K.jsx)(RC,{titleSlot:M?`No completed reviews yet`:`No items to review`,descriptionSlot:M?`Items marked as complete will appear here for auditing.`:`When experiment results are flagged for review, they will appear here.`,variant:`fill`}):(0,K.jsx)(rvi,{results:fe,isLoading:!1,featuredResultId:E,onResultClick:Ee,columns:aDi,selectedIds:M?void 0:A,onToggleSelect:M?void 0:_e,onToggleSelectAll:M?void 0:ve,setEndOfListElement:ke.setEndOfListElement,hasNextPage:ke.hasNextPage,isFetchingNextPage:ke.isFetchingNextPage})}),ze]})]})}var uDi=`experiment`,dDi=`status`,fDi=[{value:`review`,label:`Review queue`},{value:`completed`,label:`Completed`}],pDi=[{id:`is`,label:`is`}],mDi=({targetType:e,targetId:t,experimentId:n,status:r,tag:i})=>{let a=Bfi({targetType:e,targetId:t});return n&&a.push(w7(uDi,n)),r!==`review`&&a.push(w7(dDi,r)),i&&a.push(w7(`tag`,i)),a},hDi=e=>({...Vfi(e),experimentId:T7(e,uDi),status:T7(e,`status`)===`completed`?`completed`:`review`,tag:T7(e,`tag`)||null});function gDi({targetType:e,targetId:t,experimentId:n,status:r,tag:i,experiments:a,tagOptions:o,onChange:s}){let c=Hfi(e),l=(0,G.useMemo)(()=>[...c,{id:uDi,label:`Experiment`,icon:mi,color:_F(`pink`),strict:!0,suggestions:a.map(e=>({value:e.id,label:tyi(e)}))},{id:dDi,label:`Status`,icon:Wn,color:_F(`orange`),strict:!0,suggestions:fDi},{id:`tag`,label:`Tag`,icon:Qs,color:_F(`pink`),strict:!0,hidden:o.length===0,suggestions:o}],[c,a,o]),u=(0,G.useMemo)(()=>mDi({targetType:e,targetId:t,experimentId:n,status:r,tag:i}),[e,t,n,r,i]);return(0,K.jsxs)(p5,{fields:l,operators:pDi,value:u,onValueChange:e=>s(hDi(e)),createItemId:e=>e,"aria-label":`Review queue filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(p5.Chips,{}),(0,K.jsx)(p5.Input,{placeholder:`Filter review queue`})]})}var _Di=[sF(`/experiments`),sF(`/experiments/review-queue`)],vDi=`experiment`,yDi=`review`;function bDi(){let[e,t]=Hb(),n=e.get(D7),r=Ifi(n)?n:``,i=r?e.get(`targetId`)??``:``,a=e.get(vDi),o=e.get(yDi),{Link:s,paths:c}=_l(),l=i5(),{data:u,error:d}=k_i({datasetId:void 0,target:{targetType:r,targetId:i}}),f=u?.experiments.find(e=>e.id===a),p=(e,n)=>{e.status!==n.status&&n.onStatusChange(e.status),e.tag!==n.tag&&n.onTagChange(e.tag),t(t=>{let n=new URLSearchParams(t),a=e.targetType!==r,o=a||e.targetId!==i?``:e.experimentId,s=a?``:e.targetId;return e.targetType?n.set(D7,e.targetType):n.delete(D7),s?n.set(O7,s):n.delete(O7),o?n.set(vDi,o):n.delete(vDi),n.delete(yDi),n},{replace:!0})};return d&&JP(d)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:_Di}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(jU,{variant:`fill`})]}):d&&YP(d)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:_Di}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(AU,{variant:`fill`,resource:`experiments`})]}):d?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:_Di}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load experiments`,descriptionSlot:d.message})]}):(0,K.jsx)(lDi,{withQueryTrace:l.enabled,withFeedback:l.enabled,breadcrumbs:(0,K.jsx)(EP,{crumbs:_Di}),datasetId:f?.datasetId??void 0,experimentId:a??void 0,targetType:r,targetId:i,featuredItemId:o,renderFilters:e=>(0,K.jsx)(gDi,{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 xDi({connection:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){let i=t?e.authorId:void 0;return(0,K.jsxs)(`li`,{className:`flex items-center justify-between gap-4 border-b py-2`,children:[(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-2`,children:[(0,K.jsx)(T,{as:`p`,variant:`caption`,font:`mono`,className:`wrap-anywhere`,children:e.connectionId}),(0,K.jsxs)(Gw,{children:[(0,K.jsx)(Gw.Item,{children:(0,K.jsx)(T,{as:`span`,variant:`caption`,children:e.label??`(no label)`})}),(0,K.jsx)(Gw.Item,{children:(0,K.jsx)(bw,{size:`xs`,emphasis:`subtle`,children:e.status})})]}),(e.scope||i)&&(0,K.jsxs)(`dl`,{className:`flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1`,children:[e.scope&&(0,K.jsxs)(`div`,{className:`flex min-w-0 items-baseline gap-1`,children:[(0,K.jsx)(`dt`,{children:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`faint`,children:`Scope`})}),(0,K.jsx)(`dd`,{className:`min-w-0`,children:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:e.scope})})]}),i&&(0,K.jsxs)(`div`,{className:`flex min-w-0 items-baseline gap-1`,children:[(0,K.jsx)(`dt`,{children:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`faint`,children:`Author`})}),(0,K.jsx)(`dd`,{className:`min-w-0 wrap-anywhere`,children:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:i})})]})]})]}),(0,K.jsx)(`button`,{type:`button`,className:`shrink-0 text-destructive-foreground underline disabled:opacity-50`,onClick:r,disabled:n,children:`Disconnect`})]})}function SDi({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return(0,K.jsx)(`ul`,{className:`space-y-1`,children:e.map(e=>(0,K.jsx)(xDi,{connection:e,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(e.connectionId)},e.connectionId))})}function CDi({groups:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return(0,K.jsx)(`div`,{className:`space-y-4`,children:e.map(([e,i])=>(0,K.jsxs)(`div`,{children:[(0,K.jsx)(T,{as:`h3`,variant:`subheading`,tone:`ink`,"data-testid":`integration-author-group-${e}`,children:e===`shared`?`Shared`:`Owned by ${e}`}),(0,K.jsx)(SDi,{connections:i,isAdmin:t,disconnectPending:n,onDisconnect:r})]},e))})}function wDi({providerId:e,toolkit:t,connections:n,groupedByAuthor:r,isAdmin:i,isLoading:a,error:o,disconnectPending:s,disconnectError:c,onDisconnect:l}){return(0,K.jsxs)(`div`,{className:`space-y-2 rounded border p-4`,children:[(0,K.jsx)(T,{as:`h2`,variant:`heading`,children:`Existing connections`}),!e||!t?(0,K.jsx)(`p`,{className:`text-muted-foreground`,children:`Pick a provider and toolkit to list connections.`}):a?(0,K.jsx)(`p`,{className:`text-muted-foreground`,children:`Loading…`}):o?(0,K.jsx)(`p`,{className:`text-destructive-foreground`,children:String(o)}):n.length===0?(0,K.jsx)(`p`,{className:`text-muted-foreground`,children:`No connections.`}):r?(0,K.jsx)(CDi,{groups:r,isAdmin:i,disconnectPending:s,onDisconnect:l}):(0,K.jsx)(SDi,{connections:n,isAdmin:i,disconnectPending:s,onDisconnect:l}),c?(0,K.jsx)(`p`,{className:`text-destructive-foreground`,children:String(c)}):null]})}function TDi({providers:e,toolkits:t,providerId:n,toolkit:r,label:i,providersLoading:a,providersError:o,toolkitsLoading:s,toolkitsError:c,authorizePending:l,authorizeError:u,authorizedConnection:d,onProviderChange:f,onToolkitChange:p,onLabelChange:m,onConnect:h}){return(0,K.jsxs)(`div`,{className:`space-y-4 rounded border p-4`,children:[(0,K.jsxs)(fA,{invalid:!!o,disabled:a,children:[(0,K.jsx)(mA,{children:`Provider`}),(0,K.jsxs)(WA,{value:n,onValueChange:f,children:[(0,K.jsx)(KA,{children:(0,K.jsx)(GA,{placeholder:a?`Loading providers…`:`Select provider`})}),(0,K.jsx)(qA,{children:e.map(e=>(0,K.jsx)(JA,{value:e.id,children:`${e.displayName??e.name} (${e.id})`},e.id))})]}),(0,K.jsx)(gA,{children:o?String(o):void 0})]}),(0,K.jsxs)(fA,{invalid:!!c,disabled:!n||s,children:[(0,K.jsx)(mA,{children:`Toolkit`}),(0,K.jsxs)(WA,{value:r,onValueChange:p,children:[(0,K.jsx)(KA,{children:(0,K.jsx)(GA,{placeholder:s?`Loading toolkits…`:`Select toolkit`})}),(0,K.jsx)(qA,{children:t.map(e=>(0,K.jsx)(JA,{value:e.slug,children:`${e.name} (${e.slug})`},e.slug))})]}),(0,K.jsx)(gA,{children:c?String(c):void 0})]}),(0,K.jsxs)(fA,{disabled:!n||!r,children:[(0,K.jsx)(mA,{children:`Label (optional)`}),(0,K.jsx)(ZM,{placeholder:`My personal Gmail`,value:i,onChange:e=>m(e.target.value)})]}),(0,K.jsx)(X,{type:`button`,variant:`primary`,onClick:h,disabled:!n||!r||l,children:l?`Authorizing…`:`Connect`}),u?(0,K.jsx)(`div`,{role:`alert`,children:(0,K.jsx)(EA,{variant:`destructive`,children:String(u)})}):null,d?(0,K.jsxs)(EA,{variant:`success`,children:[`Authorized: `,d.connectionId,` (status: `,d.status,`)`]}):null]})}var EDi=e=>e.authorId?.trim()||`shared`,DDi=(e,t)=>{if(!t||new Set(e.map(EDi)).size<=1)return null;let n=new Map;for(let t of e){let e=EDi(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},ODi=[`*`,`tool-providers:*`,`tool-providers:admin`];function kDi(){let{data:e}=My();return e?.permissions?.some(e=>ODi.includes(e))??!1}var ADi=[{id:`integrations`,label:`Integrations`}];function jDi(){let[e,t]=(0,G.useState)(``),[n,r]=(0,G.useState)(``),[i,a]=(0,G.useState)(``),o=HJ(),s=WJ({providerId:e||null,queryOptions:{enabled:!!e}}),c=Nzn({providerId:e||null,toolkit:n||null}),l=jzn(),u=Mzn(),d=kDi(),f=o.data?.providers??[],p=s.data?.data??[],m=(0,G.useMemo)(()=>c.data?.items??[],[c.data?.items]),h=(0,G.useMemo)(()=>DDi(m,d),[m,d]);return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:ADi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Integrations`}),(0,K.jsxs)(`div`,{className:`max-w-3xl space-y-6`,children:[(0,K.jsx)(T,{as:`p`,variant:`body`,tone:`muted`,children:`Minimal page to verify the ToolProvider backend. Pick a provider and toolkit, then connect.`}),(0,K.jsx)(TDi,{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)(wDi,{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 h9(e,t){return e.position===t.position?e.id===t.id?0:e.id<t.id?-1:1:e.position<t.position?-1:1}function MDi(e){return!e.deletedAt&&!e.mergedInto}function NDi(e){let t=new Map;for(let n of e)MDi(n)&&!t.has(n.id)&&t.set(n.id,{page:n,children:[]});let n=[],r=new Map;for(let e of t.values()){let i=e.page.parentId?t.get(e.page.parentId):void 0;i&&i!==e?(i.children.push(e),r.set(e,i)):n.push(e)}let i=new Set,a=e=>{if(!i.has(e)){i.add(e);for(let t of e.children)a(t)}};n.forEach(a);let o=[...t.values()].filter(e=>!i.has(e));o.sort((e,t)=>h9(e.page,t.page));for(let e of o){if(i.has(e))continue;let t=[],o=e;for(;o&&!t.includes(o);)t.push(o),o=r.get(o);let s=(o?t.slice(t.indexOf(o)):[e]).reduce((e,t)=>h9(t.page,e.page)<0?t:e),c=r.get(s);c&&c.children.splice(c.children.indexOf(s),1),n.push(s),a(s)}let s=e=>{e.sort((e,t)=>h9(e.page,t.page));for(let t of e)s(t.children)};return s(n),n}function PDi(e,t){let n=[],r=(e,i)=>{for(let a of e){let e=t.has(a.page.id);n.push({page:a.page,depth:i,hasChildren:a.children.length>0,expanded:e}),e&&r(a.children,i+1)}};return r(e,0),n}function FDi(e,t){let n=new Map(e.map(e=>[e.id,e])),r=[],i=new Set([t]),a=n.get(t)?.parentId??null;for(;a&&n.has(a)&&!i.has(a);)i.add(a),r.unshift(a),a=n.get(a)?.parentId??null;return r}function g9(e){return e.childCountCapped?`${e.childCount??0}+`:String(e.childCount??0)}function IDi(e,t){let n=new Set;return t&&!(e.get(t.id)?.length??0)&&!(t.childCount??0)&&t.parentId&&t.parentId!==t.id&&(e.get(t.parentId)??[]).filter(e=>e.id!==t.id&&!_9(e)).slice(0,8).forEach(e=>n.add(e.id)),n}var LDi=`more:`,RDi=`rest:`,zDi=`group:`;function _9(e){return e.id.startsWith(LDi)}function v9(e){return e.id.startsWith(RDi)}function y9(e){return e.id.startsWith(zDi)}function BDi(e){return e.filter(e=>!e.deletedAt&&!e.mergedInto)}function VDi(e,t,n=qDi){let r=BDi(e),i=new Map(r.map(e=>[e.id,e])),a=new Map,o=[];for(let e of r){let t=e.parentId&&e.parentId!==e.id?i.get(e.parentId):void 0;t?a.set(t.id,[...a.get(t.id)??[],e]):o.push(e)}for(let e of a.values())e.sort(h9);o.sort(h9);let s=t&&i.has(t)?t:o[0]?.id??null,c=s?i.get(s):void 0,l=new Map,u=new Map,d=new Map,f=[],p=(e,t,n,r)=>{if(l.has(e))return;l.set(e,n),d.set(e,t);let i=n===1?e:r;i&&u.set(e,i),f.push(e)};if(s)p(s,null,0,void 0);else for(let e of o)p(e.id,null,1,void 0);for(;f.length;){let e=f.shift(),t=l.get(e),n=i.get(e),r=n?.parentId&&i.has(n.parentId)?n.parentId:null;r&&p(r,e,t+1,u.get(e));for(let n of a.get(e)??[])p(n.id,e,t+1,u.get(e));if(e===s&&c&&o.includes(c))for(let n of o)n.id!==s&&p(n.id,e,t+1,n.id)}let m=new Map;for(let e=t?i.get(t)?.parentId:void 0;e&&!m.has(e);){let t=i.get(e);if(!t)break;m.set(t.id,t.isScope?`scope`:`ancestor`),e=t.parentId&&t.parentId!==t.id?t.parentId:void 0}for(let e of r)e.isScope&&!y9(e)&&!_9(e)&&l.has(e.id)&&m.set(e.id,`scope`);let h=IDi(a,c),g=new Map,_=new Set,v=0;for(let e of r){let t=l.get(e.id),r=t!==void 0&&(t<=1||h.has(e.id))&&!_9(e),i=t!==void 0&&m.has(e.id)&&!_9(e),a=t===void 0&&n.has(e.id)&&!_9(e);a&&_.add(e.id),g.set(e.id,r||a||i&&v++<10?`full`:`dot`)}return{depth:l,form:g,branch:u,via:d,level:m,linked:_,center:s}}var HDi=230,UDi=300,WDi=150,GDi=70,KDi=28,b9=16,qDi=new Set;function JDi(e,t,n,r,i){let a=Math.max(...e.map(e=>i(e)))/2,o=r.flatMap(e=>{let t=n.get(e);return t?[Math.atan2(t.y,t.x)]:[]}),s=new Map,c=[...e],l=a*2.5+b9,u=l+a;for(let e=0;c.length&&e<12;e++){let e=Math.asin(Math.min(1,(a+b9/2)/l)),t=2*Math.asin(Math.min(1,(a*2+b9)/(2*l))),n=o.length?[...o].sort((e,t)=>e-t):[-Math.PI],r=[];n.forEach((i,a)=>{let o=n[(a+1)%n.length],s=i+e,c=(a+1<n.length?o:o+2*Math.PI)-e;for(let e=s;e<=c+1e-9;e+=t)r.push(e)}),c.splice(0,Math.max(1,r.length)).forEach((e,t)=>{let n=r[t]??r[0]??0;s.set(e.id,{x:Math.cos(n)*l,y:Math.sin(n)*l})}),u=l+a,l+=a*2+b9}return{points:s,reach:u}}function YDi(e,t,n,r=qDi){let i=BDi(e),a=new Map(i.map(e=>[e.id,e])),o=new Map;for(let e of t.depth.keys()){if(!a.has(e)||e===t.center)continue;let n=t.via.get(e)??null;o.set(n,[...o.get(n)??[],e])}let s=new Map,c=e=>{let n=t.form.get(e)===`full`?4:1,r=(o.get(e)??[]).reduce((e,t)=>e+c(t),0),i=Math.max(n,r);return s.set(e,i),i},l=t.center?o.get(t.center)??[]:o.get(null)??[];l.forEach(c);let u=new Map;for(let[e,r]of t.depth){let i=a.get(e);i&&e!==t.center&&t.form.get(e)===`full`&&u.set(r,(u.get(r)??0)+n(i)+30)}let d=u.get(1)??0,f=Math.max(1,Math.ceil(d/(2*Math.PI*UDi))),p=[...t.depth].filter(([e,n])=>n===1&&e!==t.center&&t.form.get(e)===`full`&&a.has(e)).length,m=p?d/p:0,h=[0,Math.max(HDi,d/f/(2*Math.PI))],g=e=>{for(;h.length<=e;){let e=h.length,t=h[e-1],n=u.has(e-1)&&e>1?WDi:GDi,r=e===2?(f-1)*m:0;h.push(Math.max(t+n+r,(u.get(e)??0)/(2*Math.PI)))}return h[e]},_=0,v=new Map,y=(e,n,r,i)=>{let a=e.reduce((e,t)=>e+(s.get(t)??1),0)||1,c=e.filter(e=>t.form.get(e)!==`full`).length,l=i*g(n),u=Math.max(1,Math.floor(l/KDi)),d=r,p=0;for(let r of e){let e=(s.get(r)??1)/a*i,l=d+e/2,h=t.form.get(r)===`full`,b=h||c<=u?0:p%Math.ceil(c/u);h||p++;let x=g(n)+(h&&n===1?_++%f*m:b*KDi);v.set(r,{x:Math.cos(l)*x,y:Math.sin(l)*x}),y(o.get(r)??[],n+1,d,e),d+=e}},b=l.length?(s.get(l[0])??1)/l.reduce((e,t)=>e+(s.get(t)??1),0)*2*Math.PI:0,x=()=>{v.clear(),_=0,t.center&&v.set(t.center,{x:0,y:0}),y(l,1,-Math.PI/2-b/2,2*Math.PI)};x();let S=i.filter(e=>!v.has(e.id)).sort((e,t)=>e.id<t.id?-1:1),C=S.filter(e=>r.has(e.id)&&t.form.get(e.id)===`full`),w=S.filter(e=>r.has(e.id)&&t.form.get(e.id)!==`full`),T=0,E=t.center?a.get(t.center)?.parentId:void 0,D=l.some(e=>e!==E);if(C.length&&t.center&&D){let e=Math.max(...C.map(e=>n(e)))/2,t=0;for(let[e,r]of v){let i=a.get(e);i&&(t=Math.max(t,Math.hypot(r.x,r.y)+n(i)/2))}let r=Math.max(t+b9+e,C.length*(e*2+b9)/(2*Math.PI));C.forEach((e,t)=>{let n=Math.PI/2+t/C.length*2*Math.PI;v.set(e.id,{x:Math.cos(n)*r,y:Math.sin(n)*r})}),T=r+e}else if(C.length&&t.center){let e=JDi(C,t.center,v,l,n),r=Math.max(0,...l.filter(e=>t.form.get(e)===`full`).map(e=>n(a.get(e))));h.length=2,h[1]=Math.max(h[1],e.reach+b9+r/2),x();let i=JDi(C,t.center,v,l,n);for(let[e,t]of i.points)v.set(e,t)}let O=w,k=Math.min(175,Math.max(120,O.length*KDi/(2*Math.PI)));O.forEach((e,t)=>{let n=Math.PI/2+t/O.length*2*Math.PI;v.set(e.id,{x:Math.cos(n)*k,y:Math.sin(n)*k})});let A=S.filter(e=>!r.has(e.id));if(A.length){let e=Math.max(g(h.length),T)+GDi;A.forEach((t,n)=>{let r=-Math.PI/2+n/A.length*2*Math.PI;v.set(t.id,{x:Math.cos(r)*e,y:Math.sin(r)*e})})}return v}var XDi=[`var(--chart-blue)`,`var(--chart-green)`,`var(--chart-amber)`,`var(--chart-pink)`,`var(--chart-cyan)`,`var(--chart-orange)`,`var(--chart-purple)`,`var(--chart-red)`];function ZDi(e,t){let n=[];for(let r of e){let e=t.branch.get(r.id);e&&!n.includes(e)&&n.push(e)}return new Map(n.map((e,t)=>[e,XDi[t%XDi.length]]))}var QDi=.7,$Di=.7;function eOi(e){return e<=16?1:Math.max($Di,Math.sqrt(16/e))}var tOi={author:``};function nOi(e,t,n){return{id:e,scopeId:t.scopeId,parentId:t.id,isScope:!1,position:``,name:``,version:0,createdBy:tOi,updatedBy:tOi,createdAt:``,updatedAt:``,...n}}function rOi(e){if(!e.isScope||!e.address)return null;let t=e.address.indexOf(`:`);return t>0?e.address.slice(0,t):null}function iOi(e){let t=e.cap??48,n=BDi(e.pages),r=new Map(n.map(e=>[e.id,e])),i=new Map,a=[];for(let e of n){let t=e.parentId&&e.parentId!==e.id?e.parentId:null;t?i.set(t,[...i.get(t)??[],e]):a.push(e)}for(let e of i.values())e.sort(h9);a.sort(h9);let o=e.focusId?r.get(e.focusId):void 0,s=new Map,c=new Map,l=new Map,u=[],d=(e,t)=>{l.has(e.id)||(l.set(e.id,t),s.set(e.id,e),u.push(e.id))},f=o??a[0],p=IDi(i,f);if(f&&d(f,0),f&&!o)for(let e of a.slice(1,9))d(e,1);for(let e=o?.parentId?r.get(o.parentId):void 0,t=1;e;t++)l.has(e.id)||d(e,t),e=e.parentId&&e.parentId!==e.id?r.get(e.parentId):void 0;for(;u.length;){let n=u.shift(),a=s.get(n),o=l.get(n);if(o>=3||o===2&&!p.has(n))continue;let m=a.parentId?r.get(a.parentId):void 0;m&&d(m,o+1);let h=i.get(n)??[];if(!e.loadedParents.has(n)){let e=a.childCount??0,t=Math.min(e,8);for(let r=0;r<t;r++){let t=nOi(`${LDi}${n}:${r}`,a,{name:`${a.childCountCapped?`${e}+`:e} ${e===1?`page`:`pages`} under ${a.name}`});s.set(t.id,t),l.set(t.id,o+1)}if(!h.length)continue}let g=new Map;for(let e of h){let t=rOi(e);t&&g.set(t,[...g.get(t)??[],e])}let _=new Set;if(n!==f?.id)for(let[t,r]of g){let i=`${zDi}${n}:${t}`;if(r.length<3||e.openGroups.has(i))continue;for(let e of r)_.add(e.id);let c=nOi(i,a,{isScope:!0,address:`${t}:*`,displayLabel:`${t} scopes`,name:`${r.length} ${t} scopes`,childCount:r.length});s.set(c.id,c),l.set(c.id,o+1)}let v=h.filter(e=>!_.has(e.id)),y=0;for(let r of v)if(l.has(r.id))y++;else{if(y>=t+(e.revealed?.get(n)??0))break;d(r,o+1),y++}if(e.loadedParents.has(n)){let e=Math.max(a.childCount??h.length,h.length),t=Math.max(0,e-y-_.size);if(c.set(n,{hidden:t,drawn:y}),t>0&&n===f?.id){let r=nOi(`${RDi}${n}`,a,{name:`+${a.childCountCapped?`${e}+`:t} more`,childCount:t});s.set(r.id,r),l.set(r.id,o+1)}}}let m=o?[o.id,...o.parentId&&o.parentId!==o.id?[o.parentId]:[]]:a.map(e=>e.id),h=[...l].filter(([e,t])=>(t<=1||p.has(e))&&!m.includes(e)).map(([e])=>s.get(e)).filter(e=>(e.childCount??0)>0&&!y9(e)&&!_9(e)&&!v9(e));return m.push(...h.slice(0,24).map(e=>e.id)),{pages:[...s.values()],hiddenChildren:c,wanted:m,hub:f?.id??null}}var aOi={linear:{label:`Linear`,icon:e=>(0,K.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 100 100`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,...e,children:(0,K.jsx)(`path`,{d:`M1.22541 61.5228c-.2225-.9485.90748-1.5459 1.59638-.857L39.3342 97.1782c.6889.6889.0915 1.8189-.857 1.5964C20.0515 94.4522 5.54779 79.9485 1.22541 61.5228ZM.00189135 46.8891c-.01764375.2833.08887215.5599.28957165.7606L52.3503 99.7085c.2007.2007.4773.3075.7606.2896 2.3692-.1476 4.6938-.46 6.9624-.9259.7645-.157 1.0301-1.0963.4782-1.6481L2.57595 39.4485c-.55186-.5519-1.49117-.2863-1.648174.4782-.465915 2.2686-.77832 4.5932-.92588465 6.9624ZM4.21093 29.7054c-.16649.3738-.08169.8106.20765 1.1l64.77602 64.776c.2894.2894.7262.3742 1.1.2077 1.7861-.7956 3.5171-1.6927 5.1855-2.684.5521-.328.6373-1.0867.1832-1.5407L8.43566 24.3367c-.45409-.4541-1.21271-.3689-1.54074.1832-.99132 1.6684-1.88843 3.3994-2.68399 5.1855ZM12.6587 18.074c-.3701-.3701-.393-.9637-.0443-1.3541C21.7795 6.45931 35.1114 0 49.9519 0 77.5927 0 100 22.4073 100 50.0481c0 14.8405-6.4593 28.1724-16.7199 37.3375-.3903.3487-.984.3258-1.3542-.0443L12.6587 18.074Z`})})},notion:{label:`Notion`,icon:e=>(0,K.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,...e,children:(0,K.jsx)(`path`,{d:`M4.459 4.208c.746.606 1.026.56 2.428.466l13.215-.793c.28 0 .047-.28-.046-.326L17.86 1.968c-.42-.326-.981-.7-2.055-.607L3.01 2.295c-.466.046-.56.28-.374.466zm.793 3.08v13.904c0 .747.373 1.027 1.214.98l14.523-.84c.841-.046.935-.56.935-1.167V6.354c0-.606-.233-.933-.748-.887l-15.177.887c-.56.047-.747.327-.747.933zm14.337.745c.093.42 0 .84-.42.888l-.7.14v10.264c-.608.327-1.168.514-1.635.514-.748 0-.935-.234-1.495-.933l-4.577-7.186v6.952L12.21 19s0 .84-1.168.84l-3.222.186c-.093-.186 0-.653.327-.746l.84-.233V9.854L7.822 9.76c-.094-.42.14-1.026.793-1.073l3.456-.233 4.764 7.279v-6.44l-1.215-.139c-.093-.514.28-.887.747-.933zM1.936 1.035l13.31-.98c1.634-.14 2.055-.047 3.082.7l4.249 2.986c.7.513.934.653.934 1.213v16.378c0 1.026-.373 1.634-1.68 1.726l-15.458.934c-.98.047-1.448-.093-1.962-.747l-3.129-4.06c-.56-.747-.793-1.306-.793-1.96V2.667c0-.839.374-1.54 1.447-1.632z`})})},confluence:{label:`Confluence`,icon:e=>(0,K.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,...e,children:(0,K.jsx)(`path`,{d:`M.87 18.257c-.248.382-.53.875-.763 1.245a.764.764 0 0 0 .255 1.04l4.965 3.054a.764.764 0 0 0 1.058-.26c.199-.332.454-.763.733-1.221 1.967-3.247 3.945-2.853 7.508-1.146l4.957 2.337a.764.764 0 0 0 1.028-.382l2.364-5.346a.764.764 0 0 0-.382-1 599.851 599.851 0 0 1-4.965-2.361C10.911 10.97 5.224 11.185.87 18.257zM23.131 5.743c.249-.405.531-.875.764-1.25a.764.764 0 0 0-.256-1.034L18.675.404a.764.764 0 0 0-1.058.26c-.195.335-.451.763-.734 1.225-1.966 3.246-3.945 2.85-7.508 1.146L4.437.694a.764.764 0 0 0-1.027.382L1.046 6.422a.764.764 0 0 0 .382 1c1.039.49 3.105 1.467 4.965 2.361 6.698 3.246 12.392 3.029 16.738-4.04z`})})},zendesk:{label:`Zendesk`,icon:e=>(0,K.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,...e,children:(0,K.jsx)(`path`,{d:`M12.914 2.904V16.29L24 2.905H12.914zM0 2.906C0 5.966 2.483 8.45 5.543 8.45s5.542-2.484 5.543-5.544H0zm11.086 4.807L0 21.096h11.086V7.713zm7.37 7.84c-3.063 0-5.542 2.48-5.542 5.543H24c0-3.06-2.48-5.543-5.543-5.543z`})})},fireflies:{label:`Fireflies`},github:{label:`GitHub`,icon:pQ},slack:{label:`Slack`,icon:e=>(0,K.jsxs)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,...e,children:[(0,K.jsx)(`path`,{d:`M5.042 15.165a2.528 2.528 0 0 1-2.52 2.523A2.528 2.528 0 0 1 0 15.165a2.527 2.527 0 0 1 2.522-2.52h2.52v2.52zm1.271 0a2.527 2.527 0 0 1 2.521-2.52 2.527 2.527 0 0 1 2.521 2.52v6.313A2.528 2.528 0 0 1 8.834 24a2.528 2.528 0 0 1-2.521-2.522v-6.313z`,fill:`#E01E5A`}),(0,K.jsx)(`path`,{d:`M8.834 5.042a2.528 2.528 0 0 1-2.521-2.52A2.528 2.528 0 0 1 8.834 0a2.528 2.528 0 0 1 2.521 2.522v2.52H8.834zm0 1.271a2.527 2.527 0 0 1 2.521 2.521 2.527 2.527 0 0 1-2.521 2.521H2.522A2.528 2.528 0 0 1 0 8.834a2.528 2.528 0 0 1 2.522-2.521h6.312z`,fill:`#36C5F0`}),(0,K.jsx)(`path`,{d:`M18.956 8.834a2.528 2.528 0 0 1 2.522-2.521A2.528 2.528 0 0 1 24 8.834a2.528 2.528 0 0 1-2.522 2.521h-2.522V8.834zm-1.27 0a2.528 2.528 0 0 1-2.523 2.521 2.527 2.527 0 0 1-2.52-2.521V2.522A2.527 2.527 0 0 1 15.165 0a2.528 2.528 0 0 1 2.523 2.522v6.312z`,fill:`#2EB67D`}),(0,K.jsx)(`path`,{d:`M15.165 18.956a2.528 2.528 0 0 1 2.523 2.522A2.528 2.528 0 0 1 15.165 24a2.527 2.527 0 0 1-2.52-2.522v-2.522h2.52zm0-1.27a2.527 2.527 0 0 1-2.52-2.523 2.527 2.527 0 0 1 2.52-2.52h6.313A2.528 2.528 0 0 1 24 15.165a2.528 2.528 0 0 1-2.522 2.523h-6.313z`,fill:`#ECB22E`})]})},google:{label:`Google`,icon:MNn}};function oOi(e){if(!e.isScope||!e.address)return;let t=e.address.slice(0,e.address.indexOf(`:`));return Object.hasOwn(aOi,t)?aOi[t]:void 0}function x9(e){let t=oOi(e);return t&&e.name===e.address?t.label:e.name}function sOi(e,t){let n=[],r=new Set;for(let i=e.parentId?t.get(e.parentId):void 0;i&&!r.has(i.id);)r.add(i.id),n.unshift(i.isScope&&i.address?i.address:i.name),i=i.parentId?t.get(i.parentId):void 0;return n.join(` › `)}function cOi(e,t){if(e.isScope)return e.address;let n=[],r=new Set;for(let i=e;i&&!r.has(i.id);i=i.parentId?t.get(i.parentId):void 0){if(r.add(i.id),i.isScope)return i.address?`${i.address}#${n.reverse().join(`/`)}`:void 0;if(!i.key)return;n.push(i.key)}}function lOi(e){return e.normalize(`NFKC`).trim().replace(/\s+/g,` `).toLowerCase()}function uOi(e,t=new Map){let n=new Map,r=new Map,i=new Map,a=new Map;for(let t of e){if(t.deletedAt||t.mergedInto)continue;n.set(t.id,t),t.isScope&&t.address&&r.set(t.address,t),!t.isScope&&t.key&&t.parentId&&i.set(`${t.parentId}\u0000${t.key}`,t);let e=lOi(t.name);a.set(e,a.has(e)?null:t)}let o=e=>{let t=e.indexOf(`#`);if(t<=0)return;let n=r.get(e.slice(0,t));if(!n)return;let a=n;for(let r of e.slice(t+1).split(`/`))if(a=i.get(`${a.id}\u0000${r}`),!a||a.scopeId!==n.id)return;return a===n?void 0:a};return{resolve(e){let i=e.trim();if(!i)return;let s=t.get(i);return n.get(i)??(s&&!s.deletedAt&&!s.mergedInto?s:void 0)??o(i)??r.get(i)??a.get(lOi(i))??void 0}}}function dOi(e,t,n,r){let i=e.resolve(r);if(i)return n.includes(i.id)?i:void 0;let a=r.trim(),o=a.indexOf(`#`);if(o<=0)return;let s=a.slice(0,o),c=[...t.values()].find(e=>e.isScope&&e.address===s);if(!c)return;let l=a.slice(o+1).split(`/`),u=n.flatMap(e=>{let n=t.get(e);return n&&fOi(n,c,l,t)?[n]:[]});return u.length===1?u[0]:void 0}function fOi(e,t,n,r){if(e.isScope||e.deletedAt||e.mergedInto||e.scopeId!==t.id)return!1;let i=e;for(let e=n.length-1;e>=0;e--){if(i.key!==n[e])return!1;if(i.parentId===t.id)return e===0;let a=i.parentId?r.get(i.parentId):void 0;if(!a)return e>0;i=a}return!1}var pOi=/\[\[([^\]]+)\]\]/g,mOi=/^(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:^\1[ \t]*$|(?![\s\S]))/gm,hOi=/(`+)[\s\S]*?\1/g;function gOi(e){return[...e.replace(mOi,``).replace(hOi,``).matchAll(pOi)].map(e=>e[1]??``)}function _Oi(e){let t=uOi(e),n=[];for(let r of e){if(!r.body||r.deletedAt||r.mergedInto)continue;let e=new Map;for(let n of gOi(r.body)){let i=t.resolve(n);i&&i.id!==r.id&&e.set(i.id,(e.get(i.id)??0)+1)}for(let[t,i]of e)n.push({source:r.id,target:t,kind:`link`,count:i})}return n}var vOi=(0,G.createContext)(new Map),yOi=12,bOi=320;function xOi({point:e,pane:t}){let n=`clamp(0.5rem, ${e.x}px - 10rem, calc(100% - 20.5rem))`;if(t.height>0&&e.y>t.height/2)return{left:n,bottom:t.height-e.y+yOi,maxHeight:Math.min(bOi,e.y-yOi-8)};let r=t.height>0?t.height-e.y-yOi-8:bOi;return{left:n,top:e.y+yOi,maxHeight:Math.min(bOi,r)}}function SOi(e,t){let n=(0,G.useRef)(e);return t(n.current,e)||(n.current=e),n.current}var COi=/\[\[([^\]]+)\]\]/g;function wOi(e){let t=[],n=0;for(let r of e.matchAll(COi))r.index>n&&t.push({type:`text`,value:e.slice(n,r.index)}),t.push({type:`wikilink`,value:r[1]??``}),n=r.index+r[0].length;return n<e.length&&t.push({type:`text`,value:e.slice(n)}),t}function TOi({page:e,className:t}){let n=oOi(e)?.icon;return n?(0,K.jsx)(n,{"aria-hidden":!0,className:m(`shrink-0 text-foreground`,t)}):null}function S9({label:e,children:t}){return(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{render:t}),(0,K.jsx)(CC,{children:e})]})}var EOi={"scope-created":`Scope created`,"page-created":`Page created`,"page-updated":`Page edited`,"page-moved":`Page moved`,"page-merged":`Page merged`,"page-deleted":`Page deleted`,"note-added":`Note added`,"note-restamped":`Note restamped`,"note-removed":`Note removed`,"note-restored":`Note restored`,"pin-added":`Pinned`,"pin-removed":`Unpinned`};function DOi(e){return e.startsWith(`importer:`)?`Importer`:e}function OOi({author:e}){let t=e.includes(`:`)?e.slice(e.indexOf(`:`)+1):e,n=0;for(let t of e)n=n*31+t.charCodeAt(0)|0;let r=[`--chart-blue`,`--chart-purple`,`--chart-green`,`--chart-orange`,`--chart-pink`],i=r[Math.abs(n)%r.length];return(0,K.jsx)(`span`,{"aria-hidden":!0,className:`flex size-6 shrink-0 items-center justify-center rounded-full border border-border`,style:{background:`color-mix(in oklab, var(${i}) 28%, var(--card))`},children:(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`ink`,children:(t.trim()[0]??`?`).toUpperCase()})})}function kOi(e,t){if(e.isScope)return e.address??null;let n=t.find(t=>t.id===e.scopeId);if(!n?.address)return null;let r=[...t.slice(t.indexOf(n)+1).filter(e=>!e.isScope),e].map(e=>e.key);return r.some(e=>!e)?null:`${n.address}#${r.join(`/`)}`}var AOi=(0,G.createContext)(null);function jOi({node:e,...t}){let n=(0,G.useContext)(AOi),r=e?.properties[wZ];if(typeof r!=`string`||!n)return(0,K.jsx)(`span`,{...t});let i=n.index.resolve(r);return i?(0,K.jsx)(S9,{label:r,children:(0,K.jsx)(`button`,{type:`button`,"data-testid":`knowledge-body-link`,className:`rounded bg-badge-blue-subtle px-1 text-left font-medium wrap-anywhere text-badge-blue-foreground hover:underline`,onClick:()=>n.onPageClick(i),children:i.name})}):(0,K.jsx)(S9,{label:`No loaded page has this address`,children:(0,K.jsx)(`span`,{"data-testid":`knowledge-body-link-unresolved`,className:`rounded border border-dashed border-border px-1 wrap-anywhere text-muted-foreground`,children:r})})}var MOi=[c8n],NOi={span:jOi};function C9({label:e,count:t,children:n}){return(0,K.jsxs)(`section`,{"aria-label":e,className:`flex flex-col gap-2`,children:[(0,K.jsxs)(T,{as:`h3`,variant:`label`,tone:`ink`,className:`flex items-center gap-1.5`,children:[e,t?(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`muted`,className:`tabular-nums`,children:t}):null]}),n]})}function POi({page:e,onPageClick:t}){return(0,K.jsx)(`button`,{type:`button`,className:`text-left font-medium text-info-indicator hover:underline`,onClick:()=>t(e),children:e.name})}var FOi=new WeakMap;function IOi(e,t){let n=FOi.get(e);n||FOi.set(e,n=new WeakMap);let r=n.get(t);return r||n.set(t,r=uOi(e.values(),t)),r}function LOi({note:e,pagesById:t,onPageClick:n,highlighted:r,itemRef:i,showPage:a,compact:o}){let s=IOi(t,(0,G.useContext)(vOi)),c=n=>dOi(s,t,e.mentions,n),l=e=>{let n=t.get(e);return n?.address??n?.name??e},u=a?t.get(e.pageId):void 0;return(0,K.jsxs)(`li`,{ref:i,"data-highlighted":r||void 0,className:`flex gap-3 rounded-lg border border-border bg-card ${o?`p-2`:`p-3`}`,style:r?{borderColor:`var(--chart-blue)`,boxShadow:`0 0 0 1px var(--chart-blue)`}:void 0,children:[o?null:(0,K.jsx)(OOi,{author:e.provenance.author}),(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-1.5`,children:[(0,K.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-0.5`,children:[(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`ink`,children:DOi(e.provenance.author)}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:(0,K.jsx)(jA,{value:e.updatedAt})}),u?(0,K.jsxs)(T,{as:`span`,variant:`caption`,tone:`muted`,children:[`on `,(0,K.jsx)(POi,{page:u,onPageClick:n})]}):null]}),(0,K.jsx)(`p`,{className:`text-ui-md wrap-anywhere text-foreground`,children:wOi(e.text).map((e,t)=>{if(e.type===`text`)return(0,K.jsx)(`span`,{children:e.value},t);let r=c(e.value);return r?(0,K.jsx)(S9,{label:e.value,children:(0,K.jsx)(`button`,{type:`button`,"data-testid":`knowledge-note-link`,className:`rounded bg-badge-blue-subtle px-1 text-left font-medium wrap-anywhere text-badge-blue-foreground hover:underline`,onClick:()=>n(r),children:r.name})},t):(0,K.jsx)(`span`,{className:`font-medium wrap-anywhere`,children:e.value},t)})}),e.stampScopeIds.length>0?(0,K.jsx)(`div`,{className:`flex min-w-0 flex-wrap gap-1`,"aria-label":`Stamped to`,children:e.stampScopeIds.map(e=>(0,K.jsx)(bw,{variant:`neutral`,size:`xs`,title:l(e),children:(0,K.jsx)(`span`,{className:`truncate`,children:l(e)})},e))}):null]})]})}function ROi({page:e,notes:t,pin:n,pagesById:r,onPageClick:i,highlightMentionOf:a,ancestors:o=[],mentionedBy:s=[],notesMore:c,childPages:l,activity:u,compact:d=!1}){let f=(0,G.useRef)(null);(0,G.useEffect)(()=>{f.current?.scrollIntoView?.({block:`nearest`})},[a,t]);let p=!1,m=e.isScope?e:o.find(t=>t.id===e.scopeId)??r.get(e.scopeId),h=kOi(e,o),g=e.isScope?e.displayLabel??`Scope`:`Page`,_=(0,G.useMemo)(()=>new Map([...r,...[...o,e].map(e=>[e.id,e])]),[r,o,e]),v=(0,G.useContext)(vOi),y=(0,G.useMemo)(()=>uOi([...r.values(),...o,e],v),[r,o,e,v]),b=(0,G.useMemo)(()=>({index:y,onPageClick:i}),[y,i]);return(0,K.jsxs)(`article`,{"aria-label":e.name,className:`@container flex min-h-0 flex-1 flex-col overflow-y-auto overscroll-contain`,children:[(0,K.jsxs)(`header`,{className:d?`flex flex-col gap-3 border-b border-surface-rim px-4 pt-3 pb-4`:`flex flex-col gap-3 border-b border-border bg-fill-subtle px-6 pt-5 pb-4`,children:[(0,K.jsxs)(uP,{label:`Breadcrumb`,className:`ml-[-.9em] min-w-0`,listClassName:`overflow-hidden`,children:[o.map(e=>(0,K.jsx)(fP,{as:`button`,onClick:()=>i(e),children:x9(e)},e.id)),(0,K.jsx)(fP,{as:`span`,isCurrent:!0,children:x9(e)})]}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[d?null:(0,K.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(TOi,{page:e,className:`size-icon-lg`}),(0,K.jsx)(S9,{label:(e.isScope?e.address:h)??e.name,children:(0,K.jsx)(T,{as:`h2`,variant:`title`,className:`min-w-0 break-words`,"data-testid":`knowledge-page-title`,children:x9(e)})}),(0,K.jsxs)(bw,{variant:`neutral`,size:`sm`,className:`shrink-0 tabular-nums`,children:[`v`,e.version]})]}),e.description?(0,K.jsx)(T,{variant:`body`,tone:`muted`,children:e.description}):null,(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,K.jsx)(bw,{variant:e.isScope?`info`:`neutral`,size:`sm`,children:g}),n?(0,K.jsx)(bw,{variant:`warning`,size:`sm`,icon:(0,K.jsx)(Bo,{size:10,"aria-hidden":!0}),children:n.audience.length>0?`Pinned for ${n.audience.join(`, `)}`:`Pinned`}):null,(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,"data-testid":`knowledge-page-version`,children:(0,K.jsxs)(Gw,{children:[e.isScope?null:(0,K.jsxs)(Gw.Item,{children:[`In `,m?x9(m):e.scopeId]}),d?(0,K.jsxs)(Gw.Item,{children:[`v`,e.version]}):null,(0,K.jsxs)(Gw.Item,{children:[`Updated`,` `,(0,K.jsx)(jA,{value:e.updatedAt,label:`Updated by ${DOi(e.updatedBy.author)}`})]})]})})]})]})]}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-8 ${d?`p-4`:`p-6`} @4xl:flex-row`,children:[(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-8 @4xl:flex-1`,children:[e.body?(0,K.jsx)(`div`,{"data-testid":`knowledge-page-body`,className:`max-w-3xl`,children:(0,K.jsx)(AOi.Provider,{value:b,children:(0,K.jsx)(xX,{remarkPlugins:MOi,components:NOi,children:e.body})})}):(0,K.jsxs)(T,{variant:`body`,tone:`muted`,children:[`This `,e.isScope?`scope`:`page`,` has no body yet.`]}),t.length>0||c?(0,K.jsxs)(C9,{label:`Notes`,count:c?void 0:t.length,children:[(0,K.jsx)(`ul`,{className:`flex flex-col gap-2`,children:t.map(e=>{let t=!!a&&e.mentions.includes(a),n=t&&!p;return n&&(p=!0),(0,K.jsx)(LOi,{note:e,pagesById:_,onPageClick:i,highlighted:t,itemRef:n?e=>{f.current=e}:void 0},e.id)})}),c]}):null]}),(0,K.jsxs)(`aside`,{className:`flex min-w-0 flex-col divide-y divide-border border-t border-border *:py-6 *:last:pb-0 @4xl:w-72 @4xl:shrink-0 @4xl:border-t-0 @4xl:border-l @4xl:pl-8 @4xl:*:first:pt-0`,children:[l,s.length>0?(0,K.jsx)(C9,{label:`Mentioned in`,count:s.length,children:(0,K.jsx)(`ul`,{className:`flex flex-col gap-2`,children:s.map(e=>(0,K.jsx)(LOi,{note:e,pagesById:_,onPageClick:i,showPage:!0,compact:!0},e.id))})}):null,u&&u.length>0?(0,K.jsx)(C9,{label:`Activity`,children:(0,K.jsx)(`ol`,{className:`relative flex flex-col gap-3 border-l border-border pl-4`,children:u.map(e=>(0,K.jsxs)(`li`,{className:`relative flex flex-col`,children:[(0,K.jsx)(`span`,{"aria-hidden":!0,className:`absolute top-1.5 -left-5 size-2 rounded-full border border-border bg-card`}),(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`ink`,children:EOi[e.action]??e.action}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`min-w-0`,children:(0,K.jsxs)(Gw,{singleLine:!0,children:[(0,K.jsx)(Gw.Item,{className:`min-w-0`,children:(0,K.jsx)(S9,{label:e.provenance.author,children:(0,K.jsx)(`span`,{className:`truncate`,children:DOi(e.provenance.author)})})}),(0,K.jsx)(Gw.Item,{className:`shrink-0`,children:(0,K.jsx)(jA,{value:e.createdAt})})]})})]},e.id))})}):null]})]})]},e.id)}function zOi(e,t){return e.split(/(\s+|(?<=:))/).map(e=>e.length>t&&!/^\s+$/.test(e)?`${e.slice(0,t-1)}\u2026`:e).join(``)}function w9(){return typeof window<`u`&&!!window.matchMedia?.(`(prefers-reduced-motion: no-preference)`).matches}function BOi(e,t){let n=e.map(e=>e.id).join(`\0`),[r,i]=(0,G.useState)(n),[a,o]=(0,G.useState)([]),s=(0,G.useRef)(e);if((0,G.useEffect)(()=>{s.current=e}),r!==n&&(i(n),t)){let t=new Set(e.map(e=>e.id)),n=s.current.filter(e=>!t.has(e.id));o(e=>[...e.filter(e=>!t.has(e.node.id)),...n.filter(t=>!e.some(e=>e.node.id===t.id)).map(e=>({node:e,fading:!1}))])}let c=a.some(e=>!e.fading),l=(0,G.useRef)(void 0);return(0,G.useEffect)(()=>{if(!c)return;let e=requestAnimationFrame(()=>{o(e=>e.map(e=>({...e,fading:!0}))),clearTimeout(l.current),l.current=setTimeout(()=>o(e=>e.filter(e=>!e.fading)),750)});return()=>cancelAnimationFrame(e)},[c,a.length]),(0,G.useEffect)(()=>()=>clearTimeout(l.current),[]),!t||a.length===0?e:[...e,...a.map(({node:e,fading:t})=>({...e,selectable:!1,focusable:!1,style:{...e.style,opacity:+!t,pointerEvents:`none`}}))]}var VOi=.15,HOi={left:0,right:0};function UOi(e,t){return e-t.left-t.right>0?t:HOi}function WOi({bounds:e,width:t,height:n,ring:r,anchor:i,insets:a=HOi}){let o=UOi(t,a),s=r?VOi:QDi,c=t-o.left-o.right,l=JO(e,c,n,s,2,.1);if(i&&l.zoom<=s){let e=i.position.x+(i.width??0)/2,t=i.position.y+(i.height??0)/2;return{zoom:l.zoom,x:o.left+c/2-e*l.zoom,y:n/2-t*l.zoom}}return{...l,x:l.x+o.left}}var GOi=.05,KOi=3e3;function qOi({bounds:e,nodes:t,width:n,height:r,legend:i,insets:a=HOi}){let o=UOi(n,a),s=(t,i)=>{let a=JO(e,n-t-o.right,r-i,VOi,1,GOi);return{zoom:a.zoom,x:a.x+t,y:a.y+i}},c=s(o.left,0);if(!i||!t.some(e=>{let t=e.x*c.zoom+c.x,n=e.y*c.zoom+c.y;return t<i.right&&n<i.bottom}))return c;let l=s(i.right,0),u=s(o.left,i.bottom);return l.zoom>=u.zoom?l:u}var T9=e=>e?700:0;function JOi(e,t,n){if(t+48>n)return n/2-(e+t/2);if(e<24)return 24-e;let r=e+t-(n-24);return r>0?-r:0}function YOi(e){let t=+this._x.call(null,e),n=+this._y.call(null,e);return XOi(this.cover(t,n),t,n,e)}function XOi(e,t,n,r){if(isNaN(t)||isNaN(n))return e;var i,a=e._root,o={data:r},s=e._x0,c=e._y0,l=e._x1,u=e._y1,d,f,p,m,h,g,_,v;if(!a)return e._root=o,e;for(;a.length;)if((h=t>=(d=(s+l)/2))?s=d:l=d,(g=n>=(f=(c+u)/2))?c=f:u=f,i=a,!(a=a[_=g<<1|h]))return i[_]=o,e;if(p=+e._x.call(null,a.data),m=+e._y.call(null,a.data),t===p&&n===m)return o.next=a,i?i[_]=o:e._root=o,e;do i=i?i[_]=[,,,,]:e._root=[,,,,],(h=t>=(d=(s+l)/2))?s=d:l=d,(g=n>=(f=(c+u)/2))?c=f:u=f;while((_=g<<1|h)==(v=(m>=f)<<1|p>=d));return i[v]=a,i[_]=o,e}function ZOi(e){Array.isArray(e)||(e=Array.from(e));let t=e.length,n=new Float64Array(t),r=new Float64Array(t),i=1/0,a=i,o=-i,s=o;for(let c=0,l,u,d;c<t;++c)isNaN(u=+this._x.call(null,l=e[c]))||isNaN(d=+this._y.call(null,l))?n[c]=NaN:(n[c]=u,r[c]=d,u<i&&(i=u),u>o&&(o=u),d<a&&(a=d),d>s&&(s=d));if(i>o||a>s)return this;this.cover(i,a).cover(o,s);for(let i=0;i<t;++i)XOi(this,n[i],r[i],e[i]);return this}function QOi(e,t){if(isNaN(e=+e)||isNaN(t=+t))return this;var n=this._x0,r=this._y0,i=this._x1,a=this._y1;if(isNaN(n))i=(n=Math.floor(e))+1,a=(r=Math.floor(t))+1;else{for(var o=i-n||1,s=this._root,c,l;n>e||e>=i||r>t||t>=a;)switch(l=(t<r)<<1|e<n,c=[,,,,],c[l]=s,s=c,o*=2,l){case 0:i=n+o,a=r+o;break;case 1:n=i-o,a=r+o;break;case 2:i=n+o,r=a-o;break;case 3:n=i-o,r=a-o}this._root&&this._root.length&&(this._root=s)}return this._x0=n,this._y0=r,this._x1=i,this._y1=a,this}function $Oi(){var e=[];return this.visit(function(t){if(!t.length)do e.push(t.data);while(t=t.next)}),e}function eki(e){return arguments.length?this.cover(+e[0][0],+e[0][1]).cover(+e[1][0],+e[1][1]):isNaN(this._x0)?void 0:[[this._x0,this._y0],[this._x1,this._y1]]}function E9(e,t,n,r,i){this.node=e,this.x0=t,this.y0=n,this.x1=r,this.y1=i}function tki(e,t,n){var r,i=this._x0,a=this._y0,o,s,c,l,u=this._x1,d=this._y1,f=[],p=this._root,m,h;for(p&&f.push(new E9(p,i,a,u,d)),n==null?n=1/0:(i=e-n,a=t-n,u=e+n,d=t+n,n*=n);m=f.pop();)if(!(!(p=m.node)||(o=m.x0)>u||(s=m.y0)>d||(c=m.x1)<i||(l=m.y1)<a)){if(p.length){var g=(o+c)/2,_=(s+l)/2;f.push(new E9(p[3],g,_,c,l),new E9(p[2],o,_,g,l),new E9(p[1],g,s,c,_),new E9(p[0],o,s,g,_)),(h=(t>=_)<<1|e>=g)&&(m=f[f.length-1],f[f.length-1]=f[f.length-1-h],f[f.length-1-h]=m)}else{var v=e-+this._x.call(null,p.data),y=t-+this._y.call(null,p.data),b=v*v+y*y;if(b<n){var x=Math.sqrt(n=b);i=e-x,a=t-x,u=e+x,d=t+x,r=p.data}}}return r}function nki(e){if(isNaN(u=+this._x.call(null,e))||isNaN(d=+this._y.call(null,e)))return this;var t,n=this._root,r,i,a,o=this._x0,s=this._y0,c=this._x1,l=this._y1,u,d,f,p,m,h,g,_;if(!n)return this;if(n.length)for(;;){if((m=u>=(f=(o+c)/2))?o=f:c=f,(h=d>=(p=(s+l)/2))?s=p:l=p,t=n,!(n=n[g=h<<1|m]))return this;if(!n.length)break;(t[g+1&3]||t[g+2&3]||t[g+3&3])&&(r=t,_=g)}for(;n.data!==e;)if(i=n,!(n=n.next))return this;return(a=n.next)&&delete n.next,i?(a?i.next=a:delete i.next,this):t?(a?t[g]=a:delete t[g],(n=t[0]||t[1]||t[2]||t[3])&&n===(t[3]||t[2]||t[1]||t[0])&&!n.length&&(r?r[_]=n:this._root=n),this):(this._root=a,this)}function rki(e){for(var t=0,n=e.length;t<n;++t)this.remove(e[t]);return this}function iki(){return this._root}function aki(){var e=0;return this.visit(function(t){if(!t.length)do++e;while(t=t.next)}),e}function oki(e){var t=[],n,r=this._root,i,a,o,s,c;for(r&&t.push(new E9(r,this._x0,this._y0,this._x1,this._y1));n=t.pop();)if(!e(r=n.node,a=n.x0,o=n.y0,s=n.x1,c=n.y1)&&r.length){var l=(a+s)/2,u=(o+c)/2;(i=r[3])&&t.push(new E9(i,l,u,s,c)),(i=r[2])&&t.push(new E9(i,a,u,l,c)),(i=r[1])&&t.push(new E9(i,l,o,s,u)),(i=r[0])&&t.push(new E9(i,a,o,l,u))}return this}function ski(e){var t=[],n=[],r;for(this._root&&t.push(new E9(this._root,this._x0,this._y0,this._x1,this._y1));r=t.pop();){var i=r.node;if(i.length){var a,o=r.x0,s=r.y0,c=r.x1,l=r.y1,u=(o+c)/2,d=(s+l)/2;(a=i[0])&&t.push(new E9(a,o,s,u,d)),(a=i[1])&&t.push(new E9(a,u,s,c,d)),(a=i[2])&&t.push(new E9(a,o,d,u,l)),(a=i[3])&&t.push(new E9(a,u,d,c,l))}n.push(r)}for(;r=n.pop();)e(r.node,r.x0,r.y0,r.x1,r.y1);return this}function cki(e){return e[0]}function lki(e){return arguments.length?(this._x=e,this):this._x}function uki(e){return e[1]}function dki(e){return arguments.length?(this._y=e,this):this._y}function fki(e,t,n){var r=new pki(t??cki,n??uki,NaN,NaN,NaN,NaN);return e==null?r:r.addAll(e)}function pki(e,t,n,r,i,a){this._x=e,this._y=t,this._x0=n,this._y0=r,this._x1=i,this._y1=a,this._root=void 0}function mki(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}var D9=fki.prototype=pki.prototype;D9.copy=function(){var e=new pki(this._x,this._y,this._x0,this._y0,this._x1,this._y1),t=this._root,n,r;if(!t)return e;if(!t.length)return e._root=mki(t),e;for(n=[{source:t,target:e._root=[,,,,]}];t=n.pop();)for(var i=0;i<4;++i)(r=t.source[i])&&(r.length?n.push({source:r,target:t.target[i]=[,,,,]}):t.target[i]=mki(r));return e},D9.add=YOi,D9.addAll=ZOi,D9.cover=QOi,D9.data=$Oi,D9.extent=eki,D9.find=tki,D9.remove=nki,D9.removeAll=rki,D9.root=iki,D9.size=aki,D9.visit=oki,D9.visitAfter=ski,D9.x=lki,D9.y=dki;function hki(e,t){var n,r=1;e??=0,t??=0;function i(){var i,a=n.length,o,s=0,c=0;for(i=0;i<a;++i)o=n[i],s+=o.x,c+=o.y;for(s=(s/a-e)*r,c=(c/a-t)*r,i=0;i<a;++i)o=n[i],o.x-=s,o.y-=c}return i.initialize=function(e){n=e},i.x=function(t){return arguments.length?(e=+t,i):e},i.y=function(e){return arguments.length?(t=+e,i):t},i.strength=function(e){return arguments.length?(r=+e,i):r},i}function O9(e){return function(){return e}}function k9(e){return(e()-.5)*1e-6}function gki(e){return e.x+e.vx}function _ki(e){return e.y+e.vy}function vki(e){var t,n,r,i=1,a=1;typeof e!=`function`&&(e=O9(e==null?1:+e));function o(){for(var e,o=t.length,c,l,u,d,f,p,m=0;m<a;++m)for(c=fki(t,gki,_ki).visitAfter(s),e=0;e<o;++e)l=t[e],f=n[l.index],p=f*f,u=l.x+l.vx,d=l.y+l.vy,c.visit(h);function h(e,t,n,a,o){var s=e.data,c=e.r,m=f+c;if(s){if(s.index>l.index){var h=u-s.x-s.vx,g=d-s.y-s.vy,_=h*h+g*g;_<m*m&&(h===0&&(h=k9(r),_+=h*h),g===0&&(g=k9(r),_+=g*g),_=(m-(_=Math.sqrt(_)))/_*i,l.vx+=(h*=_)*(m=(c*=c)/(p+c)),l.vy+=(g*=_)*m,s.vx-=h*(m=1-m),s.vy-=g*m)}}else return t>u+m||a<u-m||n>d+m||o<d-m}}function s(e){if(e.data)return e.r=n[e.data.index];for(var t=e.r=0;t<4;++t)e[t]&&e[t].r>e.r&&(e.r=e[t].r)}function c(){if(t){var r,i=t.length,a;for(n=Array(i),r=0;r<i;++r)a=t[r],n[a.index]=+e(a,r,t)}}return o.initialize=function(e,n){t=e,r=n,c()},o.iterations=function(e){return arguments.length?(a=+e,o):a},o.strength=function(e){return arguments.length?(i=+e,o):i},o.radius=function(t){return arguments.length?(e=typeof t==`function`?t:O9(+t),c(),o):e},o}function yki(e){return e.index}function bki(e,t){var n=e.get(t);if(!n)throw Error(`node not found: `+t);return n}function xki(e){var t=yki,n=d,r,i=O9(30),a,o,s,c,l,u=1;e??=[];function d(e){return 1/Math.min(s[e.source.index],s[e.target.index])}function f(t){for(var n=0,i=e.length;n<u;++n)for(var o=0,s,d,f,p,m,h,g;o<i;++o)s=e[o],d=s.source,f=s.target,p=f.x+f.vx-d.x-d.vx||k9(l),m=f.y+f.vy-d.y-d.vy||k9(l),h=Math.sqrt(p*p+m*m),h=(h-a[o])/h*t*r[o],p*=h,m*=h,f.vx-=p*(g=c[o]),f.vy-=m*g,d.vx+=p*(g=1-g),d.vy+=m*g}function p(){if(o){var n,i=o.length,l=e.length,u=new Map(o.map((e,n)=>[t(e,n,o),e])),d;for(n=0,s=Array(i);n<l;++n)d=e[n],d.index=n,typeof d.source!=`object`&&(d.source=bki(u,d.source)),typeof d.target!=`object`&&(d.target=bki(u,d.target)),s[d.source.index]=(s[d.source.index]||0)+1,s[d.target.index]=(s[d.target.index]||0)+1;for(n=0,c=Array(l);n<l;++n)d=e[n],c[n]=s[d.source.index]/(s[d.source.index]+s[d.target.index]);r=Array(l),m(),a=Array(l),h()}}function m(){if(o)for(var t=0,i=e.length;t<i;++t)r[t]=+n(e[t],t,e)}function h(){if(o)for(var t=0,n=e.length;t<n;++t)a[t]=+i(e[t],t,e)}return f.initialize=function(e,t){o=e,l=t,p()},f.links=function(t){return arguments.length?(e=t,p(),f):e},f.id=function(e){return arguments.length?(t=e,f):t},f.iterations=function(e){return arguments.length?(u=+e,f):u},f.strength=function(e){return arguments.length?(n=typeof e==`function`?e:O9(+e),m(),f):n},f.distance=function(e){return arguments.length?(i=typeof e==`function`?e:O9(+e),h(),f):i},f}var Ski=1664525,Cki=1013904223,wki=4294967296;function Tki(){let e=1;return()=>(e=(Ski*e+Cki)%wki)/wki}function Eki(e){return e.x}function Dki(e){return e.y}var Oki=10,kki=Math.PI*(3-Math.sqrt(5));function Aki(e){var t,n=1,r=.001,i=1-r**(1/300),a=0,o=.6,s=new Map,c=Zst(d),l=gD(`tick`,`end`),u=Tki();e??=[];function d(){f(),l.call(`tick`,t),n<r&&(c.stop(),l.call(`end`,t))}function f(r){var c,l=e.length,u;r===void 0&&(r=1);for(var d=0;d<r;++d)for(n+=(a-n)*i,s.forEach(function(e){e(n)}),c=0;c<l;++c)u=e[c],u.fx==null?u.x+=u.vx*=o:(u.x=u.fx,u.vx=0),u.fy==null?u.y+=u.vy*=o:(u.y=u.fy,u.vy=0);return t}function p(){for(var t=0,n=e.length,r;t<n;++t){if(r=e[t],r.index=t,r.fx!=null&&(r.x=r.fx),r.fy!=null&&(r.y=r.fy),isNaN(r.x)||isNaN(r.y)){var i=Oki*Math.sqrt(.5+t),a=t*kki;r.x=i*Math.cos(a),r.y=i*Math.sin(a)}(isNaN(r.vx)||isNaN(r.vy))&&(r.vx=r.vy=0)}}function m(t){return t.initialize&&t.initialize(e,u),t}return p(),t={tick:f,restart:function(){return c.restart(d),t},stop:function(){return c.stop(),t},nodes:function(n){return arguments.length?(e=n,p(),s.forEach(m),t):e},alpha:function(e){return arguments.length?(n=+e,t):n},alphaMin:function(e){return arguments.length?(r=+e,t):r},alphaDecay:function(e){return arguments.length?(i=+e,t):+i},alphaTarget:function(e){return arguments.length?(a=+e,t):a},velocityDecay:function(e){return arguments.length?(o=1-e,t):1-o},randomSource:function(e){return arguments.length?(u=e,s.forEach(m),t):u},force:function(e,n){return arguments.length>1?(n==null?s.delete(e):s.set(e,m(n)),t):s.get(e)},find:function(t,n,r){var i=0,a=e.length,o,s,c,l,u;for(r==null?r=1/0:r*=r,i=0;i<a;++i)l=e[i],o=t-l.x,s=n-l.y,c=o*o+s*s,c<r&&(u=l,r=c);return u},on:function(e,n){return arguments.length>1?(l.on(e,n),t):l.on(e)}}}function jki(){var e,t,n,r,i=O9(-30),a,o=1,s=1/0,c=.81;function l(n){var i,a=e.length,o=fki(e,Eki,Dki).visitAfter(d);for(r=n,i=0;i<a;++i)t=e[i],o.visit(f)}function u(){if(e){var t,n=e.length,r;for(a=Array(n),t=0;t<n;++t)r=e[t],a[r.index]=+i(r,t,e)}}function d(e){var t=0,n,r,i=0,o,s,c;if(e.length){for(o=s=c=0;c<4;++c)(n=e[c])&&(r=Math.abs(n.value))&&(t+=n.value,i+=r,o+=r*n.x,s+=r*n.y);e.x=o/i,e.y=s/i}else{n=e,n.x=n.data.x,n.y=n.data.y;do t+=a[n.data.index];while(n=n.next)}e.value=t}function f(e,i,l,u){if(!e.value)return!0;var d=e.x-t.x,f=e.y-t.y,p=u-i,m=d*d+f*f;if(p*p/c<m)return m<s&&(d===0&&(d=k9(n),m+=d*d),f===0&&(f=k9(n),m+=f*f),m<o&&(m=Math.sqrt(o*m)),t.vx+=d*e.value*r/m,t.vy+=f*e.value*r/m),!0;if(!(e.length||m>=s)){(e.data!==t||e.next)&&(d===0&&(d=k9(n),m+=d*d),f===0&&(f=k9(n),m+=f*f),m<o&&(m=Math.sqrt(o*m)));do e.data!==t&&(p=a[e.data.index]*r/m,t.vx+=d*p,t.vy+=f*p);while(e=e.next)}}return l.initialize=function(t,r){e=t,n=r,u()},l.strength=function(e){return arguments.length?(i=typeof e==`function`?e:O9(+e),u(),l):i},l.distanceMin=function(e){return arguments.length?(o=e*e,l):Math.sqrt(o)},l.distanceMax=function(e){return arguments.length?(s=e*e,l):Math.sqrt(s)},l.theta=function(e){return arguments.length?(c=e*e,l):Math.sqrt(c)},l}function Mki(e){var t=O9(.1),n,r,i;typeof e!=`function`&&(e=O9(e==null?0:+e));function a(e){for(var t=0,a=n.length,o;t<a;++t)o=n[t],o.vx+=(i[t]-o.x)*r[t]*e}function o(){if(n){var a,o=n.length;for(r=Array(o),i=Array(o),a=0;a<o;++a)r[a]=isNaN(i[a]=+e(n[a],a,n))?0:+t(n[a],a,n)}}return a.initialize=function(e){n=e,o()},a.strength=function(e){return arguments.length?(t=typeof e==`function`?e:O9(+e),o(),a):t},a.x=function(t){return arguments.length?(e=typeof t==`function`?t:O9(+t),o(),a):e},a}function Nki(e){var t=O9(.1),n,r,i;typeof e!=`function`&&(e=O9(e==null?0:+e));function a(e){for(var t=0,a=n.length,o;t<a;++t)o=n[t],o.vy+=(i[t]-o.y)*r[t]*e}function o(){if(n){var a,o=n.length;for(r=Array(o),i=Array(o),a=0;a<o;++a)r[a]=isNaN(i[a]=+e(n[a],a,n))?0:+t(n[a],a,n)}}return a.initialize=function(e){n=e,o()},a.strength=function(e){return arguments.length?(t=typeof e==`function`?e:O9(+e),o(),a):t},a.y=function(t){return arguments.length?(e=typeof t==`function`?t:O9(+t),o(),a):e},a}var Pki=28,Fki=300;function Iki(e,t,n={}){let r=n.ticks??Fki,i=[...e].sort((e,t)=>e.id.localeCompare(t.id)).map((e,t)=>{let n=18*Math.sqrt(.5+t),r=t*2.399963229728653,i=e.initial??{x:n*Math.cos(r),y:n*Math.sin(r)};return{id:e.id,size:e.size,padding:e.padding??Pki,x:e.fixed?.x??i.x,y:e.fixed?.y??i.y,fx:e.fixed?.x??null,fy:e.fixed?.y??null}}),a=new Set(i.map(e=>e.id)),o=new Set(t.filter(e=>e.hug).map(e=>`${e.source}\u0000${e.target}`)),s=t.filter(e=>a.has(e.source)&&a.has(e.target)).map(e=>({source:e.source,target:e.target}));Aki(i).force(`link`,xki(s).id(e=>e.id).distance(e=>{let t=e.source,n=e.target;return(o.has(`${t.id}\u0000${n.id}`)?8:40)+(t.size+n.size)/2})).force(`charge`,jki().strength(e=>e.size<=24?-60:-700)).force(`collide`,vki().radius(e=>e.size/2+e.padding).strength(1).iterations(3)).force(`center`,hki(0,0)).force(`x`,Mki(0).strength(.06)).force(`y`,Nki(0).strength(.08)).stop().tick(r),Lki(i);let c=new Map;for(let e of i)c.set(e.id,{x:e.x??0,y:e.y??0});return c}function Lki(e){let t=[...e].sort((e,t)=>t.size-e.size);for(let e=0;e<600;e++){let e=!1;for(let n=0;n<t.length;n++)for(let r=n+1;r<t.length;r++){let i=t[n],a=t[r];if(!i||!a)continue;let o=i.size/2+a.size/2+Math.min(i.padding,a.padding),s=(a.x??0)-(i.x??0),c=(a.y??0)-(i.y??0),l=Math.hypot(s,c);if(l>=o)continue;l===0&&(s=1,c=0,l=1);let u=o-l+.5,d=s/l,f=c/l,p=i.fx!=null,m=a.fx!=null;if(p&&m)continue;let h=p?0:m?1:.5,g=1-h;i.x=(i.x??0)-d*u*h,i.y=(i.y??0)-f*u*h,a.x=(a.x??0)+d*u*g,a.y=(a.y??0)+f*u*g,e=!0}if(!e)break}}function Rki(e,t=[]){let n=new Set(e.filter(e=>!e.deletedAt&&!e.mergedInto).map(e=>e.id)),r=[];for(let t of e)n.has(t.id)&&t.parentId&&t.parentId!==t.id&&n.has(t.parentId)&&r.push({source:t.parentId,target:t.id,kind:`parent`});let i=new Map;for(let e of t){if(e.kind!==`mention`&&e.kind!==`link`||e.source===e.target||!n.has(e.source)||!n.has(e.target))continue;let t=`${e.kind}\u0000${e.source}\u0000${e.target}`,r=i.get(t),a=e.count??1;r?r.count=(r.count??1)+a:i.set(t,{source:e.source,target:e.target,kind:e.kind,count:a})}return[...r,...i.values()]}function zki(e){return`unplaced:${e}`}function Bki(e,t=[]){let n=new Set(e.filter(e=>!e.deletedAt&&!e.mergedInto).map(e=>e.id)),r=new Map,i=new Map;for(let e of t){if(!n.has(e.target))continue;let t=e.principalId&&n.has(e.principalId)?e.principalId:null;if(!t){if(e.principalId)continue;t=zki(e.principal),r.has(t)||r.set(t,Vki(t,e))}t!==e.target&&i.set(`${t}\u0000${e.target}`,{source:t,target:e.target,kind:`grant`,role:e.role})}return{placeholders:[...r.values()],edges:[...i.values()]}}function Vki(e,t){let n={author:``};return{id:e,scopeId:e,parentId:null,isScope:!0,address:t.principal,displayLabel:t.principalLabel,position:``,name:t.principal,version:0,createdBy:n,updatedBy:n,createdAt:``,updatedAt:``}}function Hki(e,t){let n=new Set([e]);for(let r of t)r.source===e&&n.add(r.target),r.target===e&&n.add(r.source);return n}function Uki(e,t,n){return{nodes:e.filter(e=>!e.deletedAt&&!e.mergedInto).map(e=>({id:e.id,type:`page`,position:{x:0,y:0},data:{page:e,size:e.isScope?124:108,selected:e.id===n}})),edges:t.map(e=>({id:`${e.kind}:${e.source}->${e.target}`,source:e.source,target:e.target,data:{kind:e.kind,count:e.count??1,...e.role?{role:e.role}:{}}}))}}var Wki=[`top`,`bottom`,`right`,`left`];function Gki(e,{dot:t,tip:n,gap:r}){let i=(t.left+t.right)/2,a=(t.top+t.bottom)/2;return e===`top`?{left:i-n.width/2,right:i+n.width/2,bottom:t.top-r,top:t.top-r-n.height}:e===`bottom`?{left:i-n.width/2,right:i+n.width/2,top:t.bottom+r,bottom:t.bottom+r+n.height}:e===`left`?{right:t.left-r,left:t.left-r-n.width,top:a-n.height/2,bottom:a+n.height/2}:{left:t.right+r,right:t.right+r+n.width,top:a-n.height/2,bottom:a+n.height/2}}function Kki(e,t){let n=Math.min(e.right,t.right)-Math.max(e.left,t.left),r=Math.min(e.bottom,t.bottom)-Math.max(e.top,t.top);return n>0&&r>0?n*r:0}function qki(e,t,n){let r=Math.max(4,Math.ceil(Math.hypot(n.x-t.x,n.y-t.y)/6));for(let i=0;i<=r;i++){let a=t.x+(n.x-t.x)*i/r,o=t.y+(n.y-t.y)*i/r;if(a>=e.left&&a<=e.right&&o>=e.top&&o<=e.bottom)return!0}return!1}function Jki(e){let t=e=>(e.right-e.left)*(e.bottom-e.top),n=`top`,r=1/0;for(let i of Wki){let a=Gki(i,e),o=(t(a)-Kki(a,e.bounds))*100;for(let t of e.obstacles)o+=Kki(a,t)*4;for(let t of e.lines)qki(a,t.from,t.to)&&(o+=2e3);o<r&&(n=i,r=o)}return n}var Yki={left:0,right:0},Xki={"--knowledge-color":`var(--chart-blue)`,background:`color-mix(in oklab, var(--chart-blue) 16%, var(--card))`},Zki={"--knowledge-color":`var(--border-strong)`},Qki=`var(--muted-foreground)`,$ki={"--knowledge-color":Qki,background:Qki},eAi={stroke:`var(--foreground)`,strokeOpacity:.45,strokeDasharray:`4 4`,strokeWidth:1.25},tAi=`var(--chart-cyan)`,nAi={stroke:tAi,strokeWidth:2.25},rAi={type:MO.ArrowClosed,color:tAi,width:14,height:14},iAi=`var(--chart-blue)`,aAi=`var(--muted-foreground)`,oAi={type:MO.Arrow,color:aAi,width:12,height:12,strokeWidth:1.5},sAi=`var(--chart-purple)`,cAi={stroke:sAi,strokeWidth:1.75,strokeDasharray:`8 3 2 3`},lAi={type:MO.ArrowClosed,color:sAi,width:13,height:13},A9=`var(--chart-green)`,uAi={stroke:A9,strokeWidth:1.25},dAi={type:MO.ArrowClosed,color:A9,width:12,height:12},fAi={out:{stroke:A9},in:{stroke:`var(--chart-orange)`,strokeDasharray:`6 3`}},pAi={out:dAi,in:{type:MO.ArrowClosed,color:`var(--chart-orange)`,width:12,height:12}},mAi={stroke:`var(--foreground)`,strokeOpacity:.2,strokeWidth:1},hAi={background:`var(--card)`,borderColor:`var(--chart-purple)`,borderStyle:`dashed`};function gAi(e){let t=e/2*(1-Math.SQRT1_2);return{badge:20,style:{width:20,height:20,top:t,right:t,transform:`translate(50%, -50%)`}}}var _Ai=150,vAi=4e3,yAi=3;function bAi(e){let{left:t,top:n,right:r,bottom:i}=e.getBoundingClientRect();return{left:t,top:n,right:r,bottom:i}}function xAi(e){let t=[];for(let n of e.querySelectorAll(`.react-flow__edge-path`)){if(typeof n.getTotalLength!=`function`||typeof n.getScreenCTM!=`function`)continue;let e=n.getScreenCTM();if(!e)continue;let r=n.getTotalLength(),i=n.getPointAtLength(0),a=n.getPointAtLength(r);t.push({from:{x:e.a*i.x+e.c*i.y+e.e,y:e.b*i.x+e.d*i.y+e.f},to:{x:e.a*a.x+e.c*a.y+e.e,y:e.b*a.x+e.d*a.y+e.f}})}return t}var SAi={top:{tip:`bottom-full left-1/2 mb-2`,transform:`translateX(-50%)`,origin:`bottom center`,tail:`top-full left-1/2 -translate-x-1/2 -translate-y-1/2 border-r border-b`},bottom:{tip:`top-full left-1/2 mt-2`,transform:`translateX(-50%)`,origin:`top center`,tail:`bottom-full left-1/2 -translate-x-1/2 translate-y-1/2 border-l border-t`},right:{tip:`left-full top-1/2 ml-2`,transform:`translateY(-50%)`,origin:`center left`,tail:`right-full top-1/2 translate-x-1/2 -translate-y-1/2 border-l border-b`},left:{tip:`right-full top-1/2 mr-2`,transform:`translateY(-50%)`,origin:`center right`,tail:`left-full top-1/2 -translate-x-1/2 -translate-y-1/2 border-r border-t`}};function CAi({level:e}){return(0,K.jsx)(e===`scope`?na:Xt,{"aria-hidden":!0,"data-testid":`knowledge-level-icon-${e}`,className:`mr-1 inline-block size-3 align-text-bottom`})}function wAi({data:e}){let{page:t,size:n,color:r,path:i,ref:a,links:o,notShown:s}=e,[c,l]=(0,G.useState)(!1),u=(0,G.useRef)(null),d=(0,G.useRef)(null),[f,p]=(0,G.useState)(`top`),m=uk(e=>e.transform[2]),h=Math.min(Math.max(1/m,1),yAi),g=_9(t),_=y9(t),v=g?`Hover or click to load them`:_?`Click to show them`:null,y=!v&&t.childCount?`${g9(t)} ${t.childCount===1?`child`:`children`}`:null,b=t.isScope?t.displayLabel??`Scope`:`Page`,x=o&&(o.in>0||o.out>0)?_Z(o,s):null,S=[t.name,v??i,y,x].filter(Boolean).join(`, `);(0,G.useLayoutEffect)(()=>{let e=u.current,t=d.current,n=e?.closest(`.knowledge-graph`);if(!c||!e||!t||!n)return;let r=bAi(e),i=bAi(t),a=t.offsetWidth*h,o=t.offsetHeight*h;if(!a||!o)return;let s=[...n.querySelectorAll(`[data-testid="knowledge-page-node"], [data-testid="knowledge-page-dot"]`),...(n.parentElement??n).querySelectorAll(`[aria-label="Legend"], [data-testid="knowledge-graph-back"], [data-knowledge-graph-zoom]`)].map(bAi).filter(e=>e.right>e.left&&(e.left!==i.left||e.top!==i.top)&&(e.left!==r.left||e.top!==r.top));p(Jki({dot:r,tip:{width:a,height:o},gap:8,bounds:bAi(n),obstacles:s,lines:xAi(n)}))},[c,h]);let C=SAi[f];return(0,K.jsxs)(`div`,{ref:u,"data-testid":`knowledge-page-dot`,"data-page-id":t.id,"data-page-type":g?`stand-in`:_?`group`:t.isScope?`scope`:`page`,"aria-label":S,className:`relative cursor-pointer transition-opacity`,style:{width:n,height:n,opacity:g?.5:void 0},onPointerEnter:()=>l(!0),onPointerLeave:()=>l(!1),children:[(0,K.jsx)(`span`,{"aria-hidden":!0,"data-testid":`knowledge-dot-hit-area`,className:`absolute rounded-full`,style:{inset:-8}}),(0,K.jsx)(`div`,{className:`size-full rounded-full border`,style:{background:g?`transparent`:r??`var(--muted-foreground)`,borderColor:r??`var(--muted-foreground)`,borderStyle:g?`dashed`:`solid`},children:e.showCount&&!g&&!_&&o&&o.in+o.out>0?(0,K.jsx)(T,{as:`span`,variant:`meta`,"data-testid":`knowledge-dot-count`,className:`flex size-full items-center justify-center`,style:{color:`var(--background)`},children:o.in+o.out}):null}),c?(0,K.jsxs)(`div`,{role:`tooltip`,ref:d,"data-side":f,className:`pointer-events-none absolute ${C.tip} flex w-max max-w-72 flex-col rounded-md border border-border bg-card px-2 py-1 shadow-overlay`,style:{transform:`${C.transform} scale(${h})`,transformOrigin:C.origin},children:[(0,K.jsx)(`span`,{"data-testid":`knowledge-tooltip-tail`,"aria-hidden":!0,className:`absolute size-2 rotate-45 border-border bg-card ${C.tail}`}),v?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`ink`,children:t.name}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:(0,K.jsxs)(Gw,{children:[_&&(0,K.jsx)(Gw.Item,{children:i}),(0,K.jsx)(Gw.Item,{children:v})]})})]}):(0,K.jsx)(M6n,{name:t.name,kind:b,pageRef:a,path:i,childCount:t.childCount?g9(t):void 0,links:o,notShown:s})]}):null,(0,K.jsx)(yk,{type:`target`,position:NO.Top,className:`!invisible`}),(0,K.jsx)(yk,{type:`source`,position:NO.Bottom,className:`!invisible`})]})}var TAi=96,EAi=.74;function DAi({data:e}){if(e.form===`dot`)return(0,K.jsx)(wAi,{data:e});let{page:t,size:n,selected:r,pinned:i,badge:a}=e,o=y9(t),s=t.isScope?t.displayLabel??`Scope`:`Page`,c=kAi(t),l=v9(t),u=n<TAi,d=Math.max(4,Math.floor(n*EAi/(u?6.5:7.5))),f=OAi(e,s);return(0,K.jsxs)(`div`,{"data-testid":`knowledge-page-node`,"data-page-id":t.id,"data-page-type":c?`placeholder`:l?`rest`:o?`group`:t.isScope?`scope`:`page`,className:`relative transition-opacity ${c?`cursor-default`:`cursor-pointer`}`,style:{width:n,height:n},"aria-label":f,children:[(0,K.jsx)(S9,{label:f,children:(0,K.jsxs)(`div`,{className:`knowledge-circle flex size-full flex-col items-center justify-center gap-0.5 overflow-hidden rounded-full border-2 text-center shadow-raised ${l?`hover:border-foreground`:``}`,"data-selected":r||void 0,"data-far":e.far||void 0,style:{...c||l?hAi:e.far?$ki:t.isScope?Xki:Zki,paddingInline:.26/2*n},children:[e.far?null:(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:t.isScope?void 0:`muted`,className:`pointer-events-none inline-flex max-w-full items-center justify-center gap-1 whitespace-nowrap uppercase`,style:t.isScope?{color:`var(--chart-blue)`}:void 0,"data-testid":t.isScope?`knowledge-scope-caption`:`knowledge-page-caption`,children:[e.level?(0,K.jsx)(CAi,{level:e.level}):null,(0,K.jsx)(`span`,{className:`truncate`,children:l?`More`:e.isParent?`Parent`:s})]}),(0,K.jsx)(T,{as:`span`,variant:u?`meta`:`label`,tone:`ink`,className:`pointer-events-none max-w-full overflow-hidden [overflow-wrap:normal] ${u?`line-clamp-2`:`line-clamp-3`}`,style:e.far?{color:`var(--background)`}:void 0,"data-testid":`knowledge-circle-name`,children:(0,K.jsx)(AAi,{text:zOi(x9(t),d)})})]})}),i?(0,K.jsx)(jAi,{size:n}):null,e.hiddenLinks&&(e.hiddenLinks.in>0||e.hiddenLinks.out>0)?(0,K.jsx)(S9,{label:_Z(e.hiddenLinks),children:(0,K.jsxs)(`span`,{"data-testid":`knowledge-hidden-links`,"aria-label":_Z(e.hiddenLinks),className:`absolute bottom-full left-1/2 -mb-1 flex -translate-x-1/2 gap-1 rounded-full border border-border bg-card px-1.5 shadow-raised`,children:[e.hiddenLinks.in>0?(0,K.jsxs)(T,{as:`span`,variant:`meta`,style:{color:`var(--chart-orange)`},children:[`→`,e.hiddenLinks.in]}):null,e.hiddenLinks.out>0?(0,K.jsxs)(T,{as:`span`,variant:`meta`,style:{color:A9},children:[e.hiddenLinks.out,`→`]}):null]})}):null,a?(0,K.jsx)(S9,{label:`${a} children, not all drawn`,children:(0,K.jsx)(`span`,{"data-testid":`knowledge-child-count-badge`,"aria-label":`${a} children, not all drawn`,className:`absolute top-full left-1/2 -mt-1 -translate-x-1/2 rounded-full border border-border bg-card px-1.5 shadow-raised`,children:(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`ink`,children:a})})}):null,(0,K.jsx)(yk,{type:`target`,position:NO.Top,className:`!invisible`}),(0,K.jsx)(yk,{type:`source`,position:NO.Bottom,className:`!invisible`})]})}function OAi(e,t){let{page:n,links:r,notShown:i}=e;if(kAi(n))return`${t}: ${n.address}. Nothing written to it yet.`;if(v9(n))return`Show ${Math.min(12,n.childCount??12)} more of ${n.childCount??`the rest`}`;if(y9(n))return`${n.name}: click to show them`;if(n.isScope&&n.address){let e=x9(n);return e===n.address?`${t}: ${e}`:`${t}: ${e} (${n.address})`}return r&&r.in+r.out>0?`${n.name}: ${_Z(r,i)}`:n.name}function kAi(e){return e.id.startsWith(`unplaced:`)}function AAi({text:e}){let t=e.split(`:`);return(0,K.jsx)(K.Fragment,{children:t.map((e,n)=>(0,K.jsxs)(G.Fragment,{children:[e,n<t.length-1?(0,K.jsxs)(K.Fragment,{children:[`:`,(0,K.jsx)(`wbr`,{})]}):null]},n))})}function jAi({size:e}){let{badge:t,style:n}=gAi(e);return(0,K.jsx)(`span`,{"data-testid":`knowledge-pin-badge`,className:`absolute flex items-center justify-center rounded-full bg-badge-amber-strong text-badge-amber-foreground shadow-raised`,style:n,"aria-label":`Pinned`,children:(0,K.jsx)(Bo,{size:Math.round(t*.6),"aria-hidden":!0})})}function MAi(e,t,n=3){let r=t.x-e.x,i=t.y-e.y,a=Math.hypot(r,i)||1,o=r/a,s=i/a;return{x1:e.x+o*(e.r+n),y1:e.y+s*(e.r+n),x2:t.x-o*(t.r+n),y2:t.y-s*(t.r+n)}}function NAi({id:e,data:t,style:n,markerEnd:r}){if(!t)return null;let{x1:i,y1:a,x2:o,y2:s}=MAi(t.from,t.to),c=t.kind===`mention`,l=`M ${i} ${a} L ${o} ${s}`;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(xk,{id:e,path:l,style:n,markerEnd:r,interactionWidth:c?20:0}),t.kind===`grant`&&t.role?(0,K.jsx)(`path`,{d:l,fill:`none`,stroke:`transparent`,strokeWidth:14,"data-testid":`knowledge-grant-edge`,"data-role":t.role,"aria-label":`Grants ${t.role}`,children:(0,K.jsx)(`title`,{children:`Grants ${t.role}`})}):null]})}var PAi={rim:(0,G.memo)(NAi)},FAi={page:(0,G.memo)(DAi)};function IAi(e){if(e.length===0)return null;let t=1/0,n=1/0,r=-1/0,i=-1/0;for(let a of e)t=Math.min(t,a.position.x),n=Math.min(n,a.position.y),r=Math.max(r,a.position.x+(a.width??0)),i=Math.max(i,a.position.y+(a.height??0));return{x:t,y:n,width:r-t,height:i-n}}var LAi=`knowledge-circle inline-block size-3 shrink-0 rounded-full border-2`;function RAi({drawn:e,counts:t,dots:n,linkEnds:r,focused:i,levels:a,branches:o,collapsible:s}){let[c,l]=(0,G.useState)(!s),[u,d]=(0,G.useState)(!1),f=c||u;return(0,K.jsxs)(`div`,{className:`absolute top-3 left-3 z-10 flex translate-x-(--knowledge-pane-left) flex-col items-start gap-1.5 transition-transform duration-slow ease-out-custom motion-reduce:transition-none`,onPointerEnter:s?()=>d(!0):void 0,onPointerLeave:s?()=>d(!1):void 0,children:[s?(0,K.jsx)(X,{size:`sm`,icon:(0,K.jsx)(Xi,{}),"aria-expanded":f,className:`shadow-overlay`,onFocus:()=>d(!0),onBlur:()=>d(!1),onClick:()=>{l(e=>!e),d(!1)},children:`Legend`}):null,(0,K.jsxs)(`ul`,{"aria-label":`Legend`,hidden:s&&!f,className:`pointer-events-none flex flex-col gap-1 rounded-lg px-2.5 py-2 ${s?`bg-card shadow-overlay`:`rounded-md border border-border bg-card/90 shadow-raised`}`,children:[(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`span`,{className:LAi,style:{...Xki},"aria-hidden":!0}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Scope`})]}),a.includes(`scope`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-level-scope`,children:[(0,K.jsx)(na,{"aria-hidden":!0,className:`size-3 shrink-0 text-muted-foreground`}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Scope, above its pages`})]}):null,a.includes(`ancestor`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-level-ancestor`,children:[(0,K.jsx)(Xt,{"aria-hidden":!0,className:`size-3 shrink-0 text-muted-foreground`}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Page above the focus`})]}):null,(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`span`,{className:LAi,style:{...Zki},"aria-hidden":!0}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Page`})]}),i?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-focused`,children:[(0,K.jsx)(`span`,{className:LAi,style:{...Zki,borderWidth:3},"aria-hidden":!0}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Focused page`})]}):null,n||r?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-dot`,children:[(0,K.jsx)(`span`,{className:`inline-block size-2 shrink-0 rounded-full bg-muted-foreground`,"aria-hidden":!0}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Page in another branch`})]}):null,o.slice(0,WAi).map(e=>(0,K.jsxs)(`li`,{className:`flex items-center gap-2 pl-0.5`,"data-testid":`knowledge-legend-branch`,children:[(0,K.jsx)(`span`,{className:`inline-block size-2 shrink-0 rounded-full`,style:{background:e.color},"aria-hidden":!0}),(0,K.jsx)(S9,{label:e.name,children:(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`pointer-events-auto max-w-40 truncate`,children:o.length>1?`Under ${e.name}`:e.scope?`Under parent scope`:`Under parent page`})})]},e.id)),o.length>WAi?(0,K.jsx)(`li`,{className:`pl-0.5`,children:(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,children:[`+`,o.length-WAi,` more branches`]})}):null,e.has(`out`)||e.has(`in`)?(0,K.jsxs)(K.Fragment,{children:[e.has(`out`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-out`,children:[(0,K.jsxs)(`svg`,{width:`16`,height:`8`,"aria-hidden":!0,className:`shrink-0`,children:[(0,K.jsx)(`line`,{x1:`0`,y1:`4`,x2:`12`,y2:`4`,stroke:A9,strokeWidth:`1.5`}),(0,K.jsx)(`polygon`,{points:`11,1 16,4 11,7`,fill:A9})]}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Links out of the selected page`})]}):null,e.has(`in`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-in`,children:[(0,K.jsxs)(`svg`,{width:`16`,height:`8`,"aria-hidden":!0,className:`shrink-0`,children:[(0,K.jsx)(`line`,{x1:`0`,y1:`4`,x2:`12`,y2:`4`,stroke:`var(--chart-orange)`,strokeWidth:`1.5`,strokeDasharray:`3 2`}),(0,K.jsx)(`polygon`,{points:`11,1 16,4 11,7`,fill:`var(--chart-orange)`})]}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Links into it`})]}):null]}):null,e.has(`mention`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-mention`,children:[(0,K.jsx)(`svg`,{width:`12`,height:`4`,"aria-hidden":!0,className:`shrink-0`,children:(0,K.jsx)(`line`,{x1:`0`,y1:`2`,x2:`12`,y2:`2`,stroke:iAi,strokeWidth:`2`})}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Mentioned in notes`})]}):null,e.has(`link`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,children:[(0,K.jsxs)(`svg`,{width:`16`,height:`8`,"aria-hidden":!0,className:`shrink-0`,"data-testid":`knowledge-legend-link`,children:[(0,K.jsx)(`line`,{x1:`0`,y1:`4`,x2:`12`,y2:`4`,...uAi}),(0,K.jsx)(`polygon`,{points:`11,1 16,4 11,7`,fill:A9})]}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Linked in page body`})]}):null,e.has(`dot-parent`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-dot-parent`,children:[(0,K.jsx)(`svg`,{width:`16`,height:`4`,"aria-hidden":!0,className:`shrink-0`,children:(0,K.jsx)(`line`,{x1:`0`,y1:`2`,x2:`16`,y2:`2`,...mAi,strokeOpacity:.5})}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Child page (dot)`})]}):null,e.has(`up`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-up`,children:[(0,K.jsxs)(`svg`,{width:`16`,height:`8`,"aria-hidden":!0,className:`shrink-0`,children:[(0,K.jsx)(`line`,{x1:`0`,y1:`4`,x2:`12`,y2:`4`,...nAi}),(0,K.jsx)(`polygon`,{points:`9,1 15,4 9,7`,fill:tAi})]}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Parent of the focused page`})]}):null,e.has(`parent`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,children:[(0,K.jsxs)(`svg`,{width:`16`,height:`8`,"aria-hidden":!0,className:`shrink-0`,"data-testid":`knowledge-legend-parent-arrow`,children:[(0,K.jsx)(`line`,{x1:`0`,y1:`4`,x2:`14`,y2:`4`,...eAi,strokeDasharray:`3 2`}),(0,K.jsx)(`polyline`,{points:`10,1 14,4 10,7`,fill:`none`,stroke:aAi,strokeWidth:`1.25`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Parent → child`})]}):null,t?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-link-counts`,children:[(0,K.jsx)(T,{as:`span`,variant:`meta`,style:{color:`var(--chart-orange)`},children:`→4`}),(0,K.jsx)(T,{as:`span`,variant:`meta`,style:{color:A9},children:`14→`}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Links in, links out (not drawn)`})]}):null,e.has(`grant`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,children:[(0,K.jsxs)(`svg`,{width:`16`,height:`8`,"aria-hidden":!0,className:`shrink-0`,"data-testid":`knowledge-legend-grant`,children:[(0,K.jsx)(`line`,{x1:`0`,y1:`4`,x2:`12`,y2:`4`,...cAi,strokeDasharray:`4 2 1 2`,strokeWidth:`1.5`}),(0,K.jsx)(`polygon`,{points:`11,1 16,4 11,7`,fill:sAi})]}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Grants access (hover for role)`})]}):null,(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`span`,{className:`flex size-3 shrink-0 items-center justify-center rounded-full bg-badge-amber-strong text-badge-amber-foreground`,"aria-hidden":!0,children:(0,K.jsx)(Bo,{size:8})}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Pinned`})]})]})]})}var zAi=4,BAi=`knowledge-neighbour`;function VAi(e){let t=(0,G.useRef)(new Map);return(0,G.useMemo)(()=>{let n=new Map,r=e.map(e=>{let r=JSON.stringify(e),i=t.current.get(e.id),a=i&&i.sig===r?i:{sig:r,edge:e};return n.set(e.id,a),a.edge});return t.current=n,r},[e])}var HAi=1.2,UAi=.8,WAi=4,GAi=40;function KAi(e){let{settled:t=!0}=e,n=(0,G.useRef)(e),[r,i]=(0,G.useState)(!1),a=!t&&!r;a||(n.current=e);let o=a?{...e,pages:n.current.pages,edges:n.current.edges,pinnedIds:n.current.pinnedIds,grants:n.current.grants,selectedPageId:n.current.selectedPageId,centerId:n.current.centerId,hiddenLinks:n.current.hiddenLinks,knownLinks:n.current.knownLinks,nearIds:n.current.nearIds}:e,[s,c]=(0,G.useState)(!1);return(0,G.useEffect)(()=>{if(t){c(!1),i(!1);return}let e=setTimeout(()=>c(!0),_Ai),n=setTimeout(()=>i(!0),vAi);return()=>{clearTimeout(e),clearTimeout(n)}},[t,e.selectedPageId]),(0,K.jsxs)(Sk,{children:[(0,K.jsx)(qAi,{...o}),s&&a?(0,K.jsx)(`p`,{role:`status`,"data-testid":`knowledge-graph-loading`,className:`text-ui-sm pointer-events-none absolute bottom-3 left-1/2 z-10 -translate-x-1/2 rounded border border-border bg-card px-3 py-1 text-muted-foreground shadow-overlay`,children:`Loading pages…`}):null]})}function qAi({pages:e,edges:t,pinnedIds:n=[],grants:r,selectedPageId:i,centerId:a,hiddenLinks:o,knownLinks:s,nearIds:c,exactLinkCounts:l,fetchedLinks:u,onHover:d,showCounts:f,onPreview:p,onSelect:m,onOpen:h,onClearSelection:g,onMentionSelect:_,insets:v=Yki,collapsibleLegend:y}){let{graphPages:b,allEdges:x}=(0,G.useMemo)(()=>{let n=Bki(e,r);return{graphPages:n.placeholders.length?[...e,...n.placeholders]:e,allEdges:[...Rki(e,t),...n.edges]}},[e,t,r]),S=s??t,C=(0,G.useMemo)(()=>{let e=new Map,t=new Set;for(let n of S){if(n.kind!==`mention`&&n.kind!==`link`||n.source===n.target||t.has(`${n.source}\u0000${n.target}`))continue;t.add(`${n.source}\u0000${n.target}`);let r=e.get(n.source)??{in:0,out:0};r.out++,e.set(n.source,r);let i=e.get(n.target)??{in:0,out:0};i.in++,e.set(n.target,i)}for(let[t,n]of l??[])e.set(t,n);return e},[S,l]),w=(0,G.useMemo)(()=>{let e=new Map,t=(t,n)=>{let r=e.get(t);r?r.push(n):e.set(t,[n])};for(let e of[...S,...u??[]])(e.kind===`mention`||e.kind===`link`)&&(t(e.source,e),e.target!==e.source&&t(e.target,e));return e},[S,u]),E=(0,G.useMemo)(()=>{let e=VDi(b,i??a??null,c),t=ZDi(b,e),n=Uki(b,x);for(let t of n.nodes)if(e.form.get(t.id)===`dot`){let e=C.get(t.id),n=f&&!_9(t.data.page)&&!!e&&e.in+e.out>0;t.data.size=n?28:20}else t.id===e.center?t.data.size=Math.round(t.data.size*HAi):t.data.size=Math.round(108*(e.linked.has(t.id)?UAi:1));let r=n.nodes.filter(t=>e.depth.get(t.id)===1&&e.form.get(t.id)===`full`),o=eOi(r.length);if(o<1)for(let e of r)e.data.size=Math.round(e.data.size*o);let s=new Map(n.nodes.map(e=>[e.id,e.data.size])),l=YDi(b,e,e=>s.get(e.id)??20,c),u=Iki(n.nodes.map(t=>({id:t.id,size:t.data.size,padding:e.form.get(t.id)===`dot`?4:24,initial:l.get(t.id)})),[],{ticks:0});return{nodes:n.nodes,edges:n.edges,positions:u,shape:e,colors:t}},[b,x,i,a,C,f,c]),D=(0,G.useMemo)(()=>new Map(b.map(e=>[e.id,e])),[b]),O=(0,G.useMemo)(()=>{let e=E.shape.center?D.get(E.shape.center)?.parentId:void 0;return e&&E.positions.has(e)?e:null},[E,D]),k=(0,G.useMemo)(()=>{let e=new Set;for(let[t,n]of E.shape.level)E.shape.form.get(t)===`full`&&e.add(n);return[...e]},[E]),A=(0,G.useMemo)(()=>{let e=new Map;for(let t of E.nodes){if(E.shape.form.get(t.id)!==`dot`||_9(t.data.page))continue;let n=E.shape.branch.get(t.id),r=n?E.colors.get(n):void 0,i=n?D.get(n):void 0;n&&r&&i&&!e.has(n)&&e.set(n,{id:n,name:i.displayLabel??x9(i),color:r,scope:!!i.isScope})}return[...e.values()]},[E,D]),j=(0,G.useMemo)(()=>new Set(n),[n]),M=(0,G.useMemo)(()=>{let e=new Map;for(let t of b)t.parentId&&!_9(t)&&!v9(t)&&e.set(t.parentId,(e.get(t.parentId)??0)+1);return new Set(b.filter(t=>!y9(t)&&!v9(t)&&(t.childCountCapped||(t.childCount??0)>(e.get(t.id)??0))).map(e=>e.id))},[b]),[N,P]=(0,G.useState)(null);(0,G.useEffect)(()=>d?.(N),[N,d]);let F=(0,G.useMemo)(()=>{if(!N)return[];let e=new Set(E.nodes.map(e=>e.id)),t=new Set(E.edges.map(e=>e.id)),n=[];for(let r of w.get(N)??[]){let i=`${r.kind}:${r.source}->${r.target}`;if(!t.has(i)&&e.has(r.source)&&e.has(r.target)&&(t.add(i),n.push({id:i,source:r.source,target:r.target,data:{kind:r.kind,count:r.count??1}}),n.length>=GAi))break}return n},[N,w,E]),I=(0,G.useMemo)(()=>{let e=N?C.get(N):void 0;if(!N||!e)return 0;let t=new Set;for(let e of[...E.edges,...F]){let n=e.data?.kind;n!==`mention`&&n!==`link`||e.source!==N&&e.target!==N||t.add(`${e.source}\u0000${e.target}`)}return Math.max(0,e.in+e.out-t.size)},[N,C,E,F]),L=N&&E.positions.has(N)?N:i??null,R=(0,G.useMemo)(()=>L&&E.positions.has(L)?Hki(L,[...x,...F.map(e=>({kind:e.data?.kind??`link`,source:e.source,target:e.target}))]):null,[L,E,x,F]),z=(0,G.useMemo)(()=>E.nodes.map(e=>{let t=E.positions.get(e.id)??{x:0,y:0};return{...e,width:e.data.size,height:e.data.size,handles:[{type:`target`,position:NO.Top,x:e.data.size/2,y:0,width:1,height:1},{type:`source`,position:NO.Bottom,x:e.data.size/2,y:e.data.size,width:1,height:1}],position:{x:t.x-e.data.size/2,y:t.y-e.data.size/2},data:{...e.data,selected:e.id===i,pinned:j.has(e.id),form:E.shape.form.get(e.id)??`full`,color:E.colors.get(E.shape.branch.get(e.id)??``),badge:M.has(e.id)?g9(e.data.page):void 0,path:sOi(e.data.page,D),hiddenLinks:E.shape.form.get(e.id)===`full`?o?.get(e.id):void 0,ref:cOi(e.data.page,D),links:C.get(e.id),showCount:f,level:E.shape.form.get(e.id)===`full`?E.shape.level.get(e.id):void 0,isParent:e.id===O,far:E.shape.linked.has(e.id)||void 0}}}),[E,i,j,M,D,o,C,f,O]),{flowEdges:B,drawnEdgeStyles:V}=(0,G.useMemo)(()=>{let e=new Set,t=new Map(E.nodes.map(e=>[e.id,e.data.size])),n=e=>({...E.positions.get(e)??{x:0,y:0},r:(t.get(e)??0)/2});return{flowEdges:[...E.edges,...F].map(t=>{let r=t.data?.kind===`mention`,i=t.data?.kind===`grant`,a=t.data?.kind===`link`,o=E.shape.form.get(t.target)===`dot`,s=(r||a)&&L?t.source===L?`out`:t.target===L?`in`:void 0:void 0,c=!r&&!i&&!a&&t.source===O&&t.target===E.shape.center;return e.add(s??(c?`up`:r?`mention`:i?`grant`:a?`link`:o?`dot-parent`:`parent`)),{...t,type:`rim`,data:{kind:t.data?.kind??`parent`,count:t.data?.count??1,...t.data?.role?{role:t.data.role}:{},from:n(t.source),to:n(t.target)},...s===`in`?{zIndex:1}:{},...r&&_?{className:`cursor-pointer`}:{},style:s?{...fAi[s],strokeWidth:r?2:1.5}:r?{stroke:iAi,strokeWidth:Math.min(1.5+(t.data?.count??1)*.5,4)}:c?nAi:i?cAi:a?uAi:o?mAi:eAi,markerEnd:s?pAi[s]:c?rAi:r?{type:MO.ArrowClosed,color:iAi,width:14,height:14}:i?lAi:a?dAi:o?void 0:oAi}}),drawnEdgeStyles:e}},[E,F,_,L,O]),H=VAi(B),ee=(0,G.useMemo)(()=>z.map(e=>{let t=R?.has(e.id),n=e.id===N&&I>0;return!t&&!n?e:{...e,...t?{className:BAi}:{},...n?{data:{...e.data,notShown:I}}:{}}}),[z,R,N,I]),te=(0,G.useMemo)(()=>R?H.map(e=>R.has(e.source)&&R.has(e.target)?{...e,className:[e.className,BAi].filter(Boolean).join(` `)}:e):H,[H,R]),U=(0,G.useMemo)(()=>new Map(e.map(e=>[e.id,e])),[e]),W=_k(),ne=(0,G.useRef)(null),re=z.length>0,ie=BOi(ee,w9()),ae=E.shape.linked,oe={"--knowledge-pane-left":`${v.left}px`},se=(0,G.useRef)({nodes:z,selectedPageId:i,centerId:a,reactFlow:W,linkedIds:ae,insets:v});se.current={nodes:z,selectedPageId:i,centerId:a,reactFlow:W,linkedIds:ae,insets:v};let ce=(0,G.useRef)(!1),le=()=>{let e=ne.current,t=e?.clientWidth??0,n=e?.clientHeight??0;if(t===0||n===0)return ce.current=!0,null;ce.current=!1;let{nodes:r,reactFlow:i}=se.current,a=IAi(r);return a?{container:e,width:t,height:n,current:r,flow:i,bounds:a}:null},ue=(0,G.useCallback)(e=>{let t=le();if(!t)return;let{selectedPageId:n,centerId:r,linkedIds:i,insets:a}=se.current,o=t.current.find(e=>e.id===(n??r)),s=!!n&&t.current.some(e=>i.has(e.id)),c=WOi({bounds:t.bounds,width:t.width,height:t.height,ring:s,anchor:o,insets:a});t.flow.setViewport(c,e?{duration:e}:void 0)},[]),de=(0,G.useCallback)(()=>{let e=le();if(!e)return;let t=e.container?.getBoundingClientRect(),n=e.container?.querySelector(`[aria-label="Legend"]`)?.getBoundingClientRect(),r=qOi({bounds:e.bounds,nodes:e.current.map(e=>({x:e.position.x,y:e.position.y,width:e.width??0,height:e.height??0})),width:e.width,height:e.height,legend:t&&n?{right:n.right-t.left+8,bottom:n.bottom-t.top+8}:void 0,insets:se.current.insets});e.flow.setViewport(r)},[]),fe=(0,G.useCallback)(e=>{let t=ne.current,n=t?.clientWidth??0,r=t?.clientHeight??0,{nodes:i,selectedPageId:a,centerId:o,reactFlow:s,insets:c}=se.current,l=i.find(e=>e.id===(a??o));if(!l||n===0||r===0)return;let u=UOi(n,c),d=s.getViewport(),f=JOi(l.position.x*d.zoom+d.x-u.left,(l.width??0)*d.zoom,n-u.left-u.right),p=JOi(l.position.y*d.zoom+d.y,(l.height??0)*d.zoom,r);(f!==0||p!==0)&&s.setViewport({zoom:d.zoom,x:d.x+f,y:d.y+p},e?{duration:e}:void 0)},[]);(0,G.useEffect)(()=>{let e=ne.current;if(!e||typeof ResizeObserver>`u`)return;let t={width:e.clientWidth,height:e.clientHeight},n,r=!1,i=new ResizeObserver(([e])=>{if(!e)return;let{width:i,height:a}=e.contentRect,o=i!==t.width||a!==t.height;(t.width===0||t.height===0)&&(r=!0),t={width:i,height:a},(o||ce.current)&&i!==0&&a!==0&&(n!==void 0&&cancelAnimationFrame(n),n=requestAnimationFrame(()=>{n=void 0,r||ce.current?(r=!1,de()):fe()}))});return i.observe(e),()=>{i.disconnect(),n!==void 0&&cancelAnimationFrame(n)}},[re,de,fe]);let pe=(0,G.useRef)(null),me=!!i&&U.has(i),he=(0,G.useRef)(!1);(0,G.useEffect)(()=>{he.current&&fe(T9(w9()))},[v.left,v.right,fe]);let ge=(0,G.useRef)(0),_e=(0,G.useRef)(null),ve=(0,G.useRef)(``),ye=(0,G.useCallback)(()=>{ge.current=0},[]);(0,G.useEffect)(()=>{if(!he.current||((i??null)!==_e.current&&(ge.current=0),Date.now()>=ge.current))return;let e=z.map(e=>`${e.id}@${e.position.x},${e.position.y}`).join(`|`);e!==ve.current&&(ve.current=e,de())},[z,i,de]),(0,G.useEffect)(()=>{if(!he.current||!me||!i)return;let e=pe.current===i;pe.current=null,e||fe(T9(w9()))},[i,me,fe]);let be=e=>{if(_9(e)||y9(e)||v9(e))return m(e);if(e.id===i&&h)return h(e);pe.current=e.id,m(e)},xe=(0,G.useRef)(null),Se=e=>{if(e.key!==`Enter`&&e.key!==` `)return;let t=e.target.closest(`.react-flow__node`)?.dataset.id,n=t?U.get(t):void 0;n&&(e.preventDefault(),be(n))},Ce=(0,G.useRef)({activate:be,onPreview:p,onMentionSelect:_,onClearSelection:g,laidOut:E,pagesById:U});Ce.current={activate:be,onPreview:p,onMentionSelect:_,onClearSelection:g,laidOut:E,pagesById:U};let we=(0,G.useCallback)((e,t)=>{P(t.id),Ce.current.laidOut.shape.form.get(t.id)===`dot`&&Ce.current.onPreview?.(t.data.page)},[]),Te=(0,G.useCallback)(()=>P(null),[]),Ee=(0,G.useCallback)((e,t)=>{kAi(t.data.page)||Ce.current.activate(t.data.page)},[]),De=(0,G.useCallback)((e,t)=>{let{onMentionSelect:n,pagesById:r}=Ce.current;if(t.data?.kind!==`mention`||!n)return;let i=r.get(t.source),a=r.get(t.target);if(!i||!a)return;let o=ne.current?.getBoundingClientRect();n({source:i,target:a,point:{x:e.clientX-(o?.left??0),y:e.clientY-(o?.top??0)},pane:{width:o?.width??0,height:o?.height??0}})},[]),Oe=(0,G.useCallback)(e=>{let t=xe.current;xe.current=null,t&&Math.hypot(e.clientX-t.x,e.clientY-t.y)>zAi||Ce.current.onClearSelection?.()},[]);return re?(0,K.jsxs)(`div`,{ref:ne,style:oe,className:`knowledge-graph relative size-full`,"data-emphasis":R?`on`:void 0,"data-testid":`knowledge-page-graph`,onKeyDown:Se,onWheelCapture:ye,onPointerDownCapture:e=>{ye(),xe.current={x:e.clientX,y:e.clientY}},children:[(0,K.jsx)(RAi,{collapsible:y,branches:A,levels:k,focused:!!i&&E.positions.has(i),dots:[...E.shape.form.values()].includes(`dot`),linkEnds:E.shape.linked.size>0,drawn:V,counts:[...o??[]].some(([e,t])=>E.shape.form.get(e)===`full`&&(t.in>0||t.out>0))}),(0,K.jsx)(Wmt,{nodes:ie,edges:te,nodeTypes:FAi,edgeTypes:PAi,onInit:()=>{he.current=!0,ge.current=Date.now()+KOi,_e.current=se.current.selectedPageId??null,ve.current=se.current.nodes.map(e=>`${e.id}@${e.position.x},${e.position.y}`).join(`|`),de()},minZoom:.1,proOptions:{hideAttribution:!0},nodesConnectable:!1,nodesDraggable:!1,onPaneClick:Oe,onNodeMouseEnter:we,onNodeMouseLeave:Te,onNodeClick:Ee,onEdgeClick:De,children:(0,K.jsx)(rht,{variant:Ck.Dots,gap:26,size:1.4,color:`var(--border-strong)`})}),(0,K.jsx)(`div`,{className:`absolute bottom-3 left-3 z-10 translate-x-(--knowledge-tree-drawer-inset,0px) transition-transform duration-slow ease-out-custom motion-reduce:transition-none`,children:(0,K.jsxs)(fU,{size:`sm`,"aria-label":`Zoom`,"data-knowledge-graph-zoom":!0,className:`rounded-full shadow-overlay`,children:[(0,K.jsx)(X,{size:`icon-sm`,tooltip:`Zoom out`,"aria-label":`Zoom out`,onClick:()=>void W.zoomOut({duration:T9(w9())}),children:(0,K.jsx)(oo,{})}),(0,K.jsx)(X,{size:`icon-sm`,tooltip:`Zoom in`,"aria-label":`Zoom in`,onClick:()=>void W.zoomIn({duration:T9(w9())}),children:(0,K.jsx)(Uo,{})}),(0,K.jsx)(X,{size:`icon-sm`,tooltip:`Fit view`,"aria-label":`Fit view`,onClick:()=>ue(T9(w9())),children:(0,K.jsx)(Va,{})})]})})]}):(0,K.jsx)(`div`,{className:`flex h-full items-center justify-center p-6`,children:(0,K.jsx)(T,{variant:`body`,tone:`muted`,children:`No pages yet.`})})}function JAi(e){let t;for(let n=e;n;n=n.parentElement){let{overflowY:e}=getComputedStyle(n);if(e===`auto`||e===`scroll`||e===`overlay`){if(n.scrollHeight>n.clientHeight)return n.getBoundingClientRect();t??=n}}return(t??e)?.getBoundingClientRect()}var YAi=1/3,XAi=.1,ZAi=.7;function QAi({pages:e,pinnedIds:t,selectedPageId:n,onSelect:r,initiallyExpanded:i,mayHaveChildren:a,onExpandedChange:o,loadMore:s,"aria-label":c=`Knowledge pages`}){let l=(0,G.useMemo)(()=>NDi(e),[e]),u=(0,G.useMemo)(()=>new Set(t),[t]),[d,f]=(0,G.useState)(()=>new Set(i??l.map(e=>e.page.id))),[p,h]=(0,G.useState)(null),g=(0,G.useRef)(new Map),_=(0,G.useRef)(null);(0,G.useEffect)(()=>{if(!n){_.current=null;return}let t=FDi(e,n),r=[n,...t].join(`/`);_.current!==r&&(_.current=r,f(e=>t.every(t=>e.has(t))?e:new Set([...e,...t])))},[e,n]),(0,G.useEffect)(()=>{o?.(d)},[d,o]);let v=(0,G.useMemo)(()=>PDi(l,d).map(e=>!e.hasChildren&&a?.(e.page)?{...e,hasChildren:!0}:e),[l,d,a]),b=(0,G.useRef)(null),x=(0,G.useRef)(null),S=(0,G.useRef)(!1);(0,G.useEffect)(()=>{if(!n){x.current=null;return}let e=g.current.get(n);if(!e)return;let t=x.current!==n;if(t)x.current=n,S.current=!1;else if(S.current)return;let r=JAi(b.current),i=e.getBoundingClientRect();if((t||r)&&!(!t&&r&&r.height===0&&i.top>=r.top&&i.bottom<=r.bottom)){if(r&&r.height>0){if(i.top>=r.top+r.height*XAi&&i.bottom<=r.top+r.height*ZAi)return;e.style.scrollMarginTop=`${r.height*YAi}px`}e.scrollIntoView?.({block:`start`,behavior:t&&w9()?`smooth`:`auto`}),e.style.scrollMarginTop=``}},[v,n]);let C=p&&v.some(e=>e.page.id===p)?p:v.find(e=>e.page.id===n)?.page.id??v[0]?.page.id,w=(e,t)=>f(n=>{if(n.has(e)===t)return n;let r=new Set(n);return t?r.add(e):r.delete(e),r}),T=e=>{e&&(h(e),g.current.get(e)?.focus())},E=(e,t)=>{let n=v[t];if(n){switch(e.key){case`ArrowDown`:T(v[t+1]?.page.id);break;case`ArrowUp`:T(v[t-1]?.page.id);break;case`ArrowRight`:n.hasChildren&&!n.expanded?w(n.page.id,!0):n.expanded&&T(v[t+1]?.page.id);break;case`ArrowLeft`:n.expanded?w(n.page.id,!1):T(v.slice(0,t).findLast(e=>e.depth<n.depth)?.page.id);break;case`Enter`:case` `:r(n.page);break;default:return}e.preventDefault()}};if(v.length===0)return(0,K.jsx)(`p`,{className:`px-3 py-2 text-body text-muted-foreground`,children:`No pages yet.`});let D=[];return(0,K.jsx)(`div`,{ref:b,role:`tree`,"aria-label":c,className:`min-h-0 overflow-y-auto py-1`,onWheel:()=>S.current=!0,onTouchMove:()=>S.current=!0,onPointerDown:()=>S.current=!0,onKeyDown:()=>S.current=!0,children:v.map((e,t)=>{let i=e.page.id===n;D[e.depth]=e.page.id;let a=v[t+1]?.depth??-1,o=[];for(let t=e.depth-1;t>=a;t--){let e=t<0?``:D[t];e!==void 0&&o.push({parentId:e,depth:t+1})}return e.expanded&&v[t+1]?.depth!==e.depth+1&&o.unshift({parentId:e.page.id,depth:e.depth+1}),(0,K.jsxs)(G.Fragment,{children:[(0,K.jsxs)(`div`,{ref:t=>{t?g.current.set(e.page.id,t):g.current.delete(e.page.id)},role:`treeitem`,"aria-level":e.depth+1,"aria-selected":i,"aria-expanded":e.hasChildren?e.expanded:void 0,tabIndex:e.page.id===C?0:-1,onFocus:()=>h(e.page.id),onKeyDown:e=>E(e,t),onClick:()=>{r(e.page),e.hasChildren&&w(e.page.id,!0)},className:m(`flex h-8 cursor-pointer items-center gap-2 rounded-md pr-2 text-body-sm text-foreground outline-none focus-visible:bg-fill-subtle`,i?`bg-fill-hover`:`hover:bg-fill-subtle`),style:{paddingLeft:`${e.depth*12+4}px`},children:[e.hasChildren?(0,K.jsx)(`button`,{type:`button`,tabIndex:-1,"aria-label":e.expanded?`Collapse ${e.page.name}`:`Expand ${e.page.name}`,className:`flex size-3 shrink-0 items-center justify-center text-muted-foreground hover:text-foreground`,onClick:t=>{t.stopPropagation(),w(e.page.id,!e.expanded)},children:(0,K.jsx)(y,{direction:`right`,open:e.expanded,className:`size-3`})}):(0,K.jsx)(`span`,{className:`size-3 shrink-0`,"aria-hidden":!0}),(0,K.jsx)(`span`,{className:`flex shrink-0 items-center text-muted-foreground [&>svg]:size-3.5`,"aria-hidden":!0,children:e.page.isScope&&x9(e.page)!==e.page.name?(0,K.jsx)(TOi,{page:e.page}):e.hasChildren?(0,K.jsx)(Ci,{}):(0,K.jsx)(oi,{})}),(0,K.jsx)(`span`,{className:m(`min-w-0 flex-1 truncate`,e.page.isScope&&`font-medium`),children:x9(e.page)}),e.page.childCount?(0,K.jsx)(`span`,{"data-testid":`knowledge-tree-count`,"aria-label":`${g9(e.page)} below`,className:`shrink-0 text-caption text-placeholder tabular-nums`,children:g9(e.page)}):null,u.has(e.page.id)?(0,K.jsx)(Bo,{size:12,className:`shrink-0 text-badge-amber-indicator`,"aria-label":`Pinned`}):null,e.page.isScope&&e.page.address&&e.page.address!==e.page.name?(0,K.jsx)(`span`,{"data-testid":`knowledge-tree-address`,className:`max-w-1/2 min-w-0 truncate text-caption text-muted-foreground`,children:e.page.address}):null]}),o.map(({parentId:e,depth:t})=>{let n=s?.get(e);return n?(0,K.jsx)(`button`,{type:`button`,className:`flex h-8 w-full items-center text-left text-caption text-muted-foreground hover:text-foreground`,style:{paddingLeft:`${t*12+42}px`},onClick:n,children:`Load more`},`more-${e}`):null})]},e.page.id)})})}var $Ai=/^[0-9A-Z]{26}$/,eji=6e4,tji=e=>Date.now()-Date.parse(e.createdAt)<eji,nji=2,rji=40;function iji(e){return`${e.kind}\u0000${e.source}\u0000${e.target}`}function aji(e,t,n,r){let i=new Map;for(let t of e)t.source!==t.target&&!i.has(iji(t))&&i.set(iji(t),t);let a=new Map;for(let e of i.values())a.set(`${e.source}\u0000${e.target}`,e);let o=new Set,s={in:0,out:0};if(r)for(let[e,n]of i)t.has(n.source)&&t.has(n.target)&&o.add(e);else if(n){let e=new Set,r=new Set,a=0,c=0;for(let[l,u]of i){if(!t.has(u.source)||!t.has(u.target))continue;let i=u.source===n?`out`:u.target===n?`in`:null;if(!i)continue;let d=`${u.source}\u0000${u.target}`;!e.has(d)&&!r.has(d)&&((i===`out`?c:a)>=20?(r.add(d),s[i]++):(e.add(d),i===`out`?c++:a++)),e.has(d)&&o.add(l)}}let c=new Set([...o].map(e=>{let t=i.get(e);return`${t.source}\u0000${t.target}`})),l=new Map,u=(e,n)=>{if(!t.has(e))return;let r=l.get(e)??{in:0,out:0};r[n]++,l.set(e,r)};for(let[e,t]of a)c.has(e)||(u(t.source,`out`),u(t.target,`in`));return{edges:[...i.values()].filter(e=>o.has(iji(e))),hidden:l,more:s}}function oji(e,t){return t?`page`:e===`tree`?`tree`:`graph`}var sji=296,cji=44;function lji(e,t){return e?t?sji:cji:0}var uji=392,dji=()=>[],fji=[],pji=()=>[],mji=()=>({isPending:!1,isError:!1,error:null}),hji=150;function gji(e,t){let n=new Map,r=new Set;for(let e of t){if(e.kind===`parent`||r.has(`${e.source}\u0000${e.target}`))continue;r.add(`${e.source}\u0000${e.target}`);let t=n.get(e.source)??{in:0,out:0};t.out++,n.set(e.source,t);let i=n.get(e.target)??{in:0,out:0};i.in++,n.set(e.target,i)}let i=new Map;for(let[t,r]of e){let e=n.get(t)??{in:0,out:0};i.set(t,{in:Math.max(0,r.in-e.in),out:Math.max(0,r.out-e.out)})}return i}var _ji=()=>({isPending:!1,isError:!1,error:null});function vji(e){return!!e&&typeof e==`object`&&`status`in e&&e.status===404}function yji(e,t){if(t.length===0)return e;let n=new Map(e);for(let e of t)n.set(e.id,e);return n}function bji(e,t){if(!t)return e;let n=new Map(e.map(e=>[e.id,e])),r=new Map([[t,!0]]),i=e=>{let t=r.get(e.id);if(t!==void 0)return t;let a=e.parentId?n.get(e.parentId):void 0;r.set(e.id,!1);let o=!!a&&a.id!==e.id&&i(a);return r.set(e.id,o),o};return e.filter(i)}var xji=[`w-32`,`w-24`,`w-40`,`w-28`,`w-36`,`w-20`];function Sji({label:e,rows:t}){return(0,K.jsx)(`div`,{role:`status`,"aria-label":e,className:`flex flex-col`,children:xji.slice(0,t).map((e,t)=>(0,K.jsxs)(`div`,{className:`flex h-8 items-center gap-2 px-1`,style:{paddingLeft:`${t%3*12+4}px`},children:[(0,K.jsx)(dw,{className:`size-3.5 shrink-0`}),(0,K.jsx)(fw,{className:e})]},e))})}function Cji(){return(0,K.jsx)(`div`,{role:`status`,"aria-label":`Loading notes`,className:`flex flex-col gap-2`,children:[0,1].map(e=>(0,K.jsxs)(`div`,{className:`flex flex-col gap-2 rounded-lg border border-border p-3`,children:[(0,K.jsx)(fw,{className:`w-24`}),(0,K.jsx)(fw,{className:`w-full`}),(0,K.jsx)(fw,{className:`w-2/3`})]},e))})}function wji({compact:e}){return(0,K.jsxs)(`div`,{role:`status`,"aria-label":`Loading page`,className:`flex flex-col`,children:[(0,K.jsxs)(`div`,{className:`flex flex-col gap-2 border-b border-border ${e?`px-4 pt-3 pb-4`:`bg-fill-subtle px-6 pt-5 pb-4`}`,children:[(0,K.jsx)(fw,{line:`text-caption`,className:`w-28`}),e?null:(0,K.jsx)(fw,{line:`text-title`,className:`h-5 w-56`}),(0,K.jsx)(fw,{className:`w-72 max-w-full`}),(0,K.jsx)(fw,{line:`text-caption`,className:`w-40`})]}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-3 ${e?`p-4`:`p-6`}`,children:[(0,K.jsx)(fw,{className:`w-full max-w-3xl`}),(0,K.jsx)(fw,{className:`w-5/6 max-w-2xl`}),(0,K.jsx)(fw,{className:`w-2/3 max-w-xl`})]})]})}function Tji({onClick:e,label:t=`Load more`}){return(0,K.jsx)(`button`,{type:`button`,className:`self-start text-caption text-muted-foreground hover:text-foreground`,onClick:e,children:t})}function Eji({source:e,pageId:t,cursor:n,pagesById:r,onPageClick:i}){let a=e.usePage(t,n),[o,s]=(0,G.useState)(!1),c=(0,G.useMemo)(()=>yji(r,a.data?.related??[]),[a.data,r]);if(a.isPending)return(0,K.jsx)(Cji,{});if(!a.data)return null;let l=a.data.notesNextCursor;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`ul`,{className:`flex flex-col gap-3`,children:a.data.notes.map(e=>(0,K.jsx)(LOi,{note:e,pagesById:c,onPageClick:i},e.id))}),l?o?(0,K.jsx)(Eji,{source:e,pageId:t,cursor:l,pagesById:r,onPageClick:i}):(0,K.jsx)(Tji,{label:`Load more notes`,onClick:()=>s(!0)}):null]})}function Dji({useTreeLevels:e,parentId:t,onOpen:n}){let[r,i]=(0,G.useState)([]),a=e((0,G.useMemo)(()=>[{parentId:t},...r.map(e=>({parentId:t,cursor:e}))],[t,r])),o=a.flatMap(e=>e.data?.pages??[]),s=a[a.length-1];if(a[0]?.isPending)return(0,K.jsx)(C9,{label:`Pages`,children:(0,K.jsx)(Sji,{label:`Loading pages`,rows:3})});let c=s?.data?.nextCursor;return o.length===0&&!c?null:(0,K.jsxs)(C9,{label:`Pages`,children:[(0,K.jsx)(`div`,{className:`rounded-xl p-1 ${Wb}`,children:(0,K.jsx)(t8,{className:`rounded-lg bg-background p-1`,onSelect:n,children:(0,K.jsx)(Oji,{pages:o,useTreeLevels:e,onOpen:n})})}),c?(0,K.jsx)(Tji,{onClick:()=>i(e=>[...e,c])}):null]})}function Oji({pages:e,useTreeLevels:t,onOpen:n}){return e.map(e=>e.childCount===0?(0,K.jsxs)(t8.File,{id:e.id,children:[(0,K.jsx)(t8.Icon,{className:`text-muted-foreground`,children:(0,K.jsx)(oi,{})}),(0,K.jsx)(kji,{page:e})]},e.id):(0,K.jsx)(Aji,{page:e,useTreeLevels:t,onOpen:n},e.id))}function kji({page:e}){return e.description?(0,K.jsx)(S9,{label:e.description,children:(0,K.jsx)(t8.Label,{children:e.name})}):(0,K.jsx)(t8.Label,{children:e.name})}function Aji({page:e,useTreeLevels:t,onOpen:n}){let[r,i]=(0,G.useState)(!1);return(0,K.jsxs)(t8.Folder,{id:e.id,open:r,onOpenChange:i,children:[(0,K.jsxs)(t8.FolderTrigger,{actions:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`Open ${e.name}`,"aria-label":`Open ${e.name}`,onClick:()=>n(e.id),children:(0,K.jsx)(Ht,{})}),children:[(0,K.jsx)(t8.Icon,{className:`text-muted-foreground`,children:(0,K.jsx)(Ci,{})}),(0,K.jsx)(kji,{page:e}),e.childCount?(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`ml-auto pl-2 tabular-nums`,children:e.childCount}):null]}),(0,K.jsx)(t8.FolderContent,{children:r?(0,K.jsx)(jji,{parentId:e.id,useTreeLevels:t,onOpen:n}):null})]})}function jji({parentId:e,useTreeLevels:t,onOpen:n}){let[r,i]=(0,G.useState)([]),a=t([{parentId:e},...r.map(t=>({parentId:e,cursor:t}))]),o=a.flatMap(e=>e.data?.pages??[]),s=a[a.length-1]?.data?.nextCursor;return a[0]?.isPending?(0,K.jsx)(`li`,{role:`none`,className:`pl-6`,children:(0,K.jsx)(Sji,{label:`Loading pages`,rows:2})}):a[0]?.isError?(0,K.jsx)(Mji,{children:`Couldn’t load the pages under this one.`}):o.length===0&&!s?(0,K.jsx)(Mji,{children:`No pages under this one.`}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Oji,{pages:o,useTreeLevels:t,onOpen:n}),s?(0,K.jsx)(`li`,{role:`none`,className:`pl-9`,children:(0,K.jsx)(Tji,{onClick:()=>i(e=>[...e,s])})}):null]})}function Mji({children:e}){return(0,K.jsx)(`li`,{role:`none`,className:`flex h-8 items-center pl-9 text-caption text-muted-foreground`,children:e})}function Nji({source:e,mention:t,pagesById:n,onOpen:r,onClose:i}){let a=e.usePage(t.source.id),o=(a.data?.notes??[]).filter(e=>e.mentions.includes(t.target.id));return(0,G.useEffect)(()=>{let e=e=>{e.key===`Escape`&&i()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[i]),(0,K.jsxs)(`div`,{role:`dialog`,"aria-label":`${t.source.name} mentions ${t.target.name}`,"data-testid":`knowledge-mention-popup`,className:`absolute z-20 flex w-80 max-w-[calc(100%-1rem)] flex-col gap-2 overflow-hidden rounded-lg border border-border bg-card p-3 shadow-overlay`,style:xOi(t),children:[(0,K.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,K.jsxs)(T,{as:`h3`,variant:`card-title`,className:`min-w-0 flex-1`,children:[(0,K.jsx)(`button`,{type:`button`,className:`hover:underline`,onClick:()=>r(t.source.id),children:t.source.name}),(0,K.jsxs)(T,{as:`span`,variant:`card-title`,tone:`muted`,children:[` `,`mentions`,` `]}),(0,K.jsx)(`button`,{type:`button`,className:`hover:underline`,onClick:()=>r(t.target.id),children:t.target.name})]}),(0,K.jsx)(`button`,{type:`button`,"aria-label":`Close`,className:`rounded p-0.5 text-muted-foreground hover:bg-fill hover:text-foreground`,onClick:i,children:(0,K.jsx)(Hc,{size:14,"aria-hidden":!0})})]}),(0,K.jsx)(`div`,{className:`min-h-0 overflow-y-auto`,children:a.isPending?(0,K.jsx)(Cji,{}):o.length===0?(0,K.jsxs)(T,{variant:`caption`,tone:`muted`,children:[`The notes that make this mention aren't in the first page of notes. Open `,t.source.name,` to read them all.`]}):(0,K.jsx)(`ul`,{className:`flex flex-col gap-2`,children:o.map(e=>(0,K.jsx)(LOi,{note:e,pagesById:yji(n,a.data?[...a.data.related,...a.data.ancestors,a.data.page]:[]),onPageClick:e=>r(e.id),compact:!0},e.id))})})]})}function Pji({source:e,pageId:t,pagesById:n,onSelect:r,highlightMentionOf:i,compact:a}){let o=e.usePage(t),s=(e.useActivity??_ji)(t),[c,l]=(0,G.useState)(null),u=(0,G.useMemo)(()=>o.data?yji(n,[...o.data.ancestors,...o.data.related]):n,[o.data,n]);if(o.isPending)return(0,K.jsx)(wji,{compact:a});if(o.isError||!o.data){let e=vji(o.error);return(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:e?`Page not found`:`Failed to load the page`,descriptionSlot:e?`It may have been deleted or merged.`:o.error?.message??``})}let d=e=>r(e.id),f=o.data.notesNextCursor;return(0,K.jsx)(ROi,{compact:a,page:o.data.page,notes:o.data.notes,pin:o.data.pin??void 0,pagesById:u,onPageClick:d,highlightMentionOf:i,ancestors:o.data.ancestors,mentionedBy:o.data.mentionedBy,activity:s.data?.events,childPages:e.useTreeLevels?(0,K.jsx)(Dji,{useTreeLevels:e.useTreeLevels,parentId:t,onOpen:r},t):void 0,notesMore:f?c?.pageId===t?(0,K.jsx)(Eji,{source:e,pageId:t,cursor:f,pagesById:u,onPageClick:d}):(0,K.jsx)(Tji,{label:`Load more notes`,onClick:()=>l({pageId:t})}):void 0})}function Fji({source:e,onSelect:t}){let[n,r]=(0,G.useState)(``),i=e.useSearch(n),a=n.trim().length>=nji?i.data?.results??[]:[],o=new Set,s=a.map(e=>e.page).filter(e=>!o.has(e.id)&&(o.add(e.id),!0)).slice(0,10);return(0,K.jsxs)(`div`,{className:`relative w-64 min-w-0`,children:[(0,K.jsx)(RU,{label:`Search knowledge`,placeholder:`Search pages and notes`,size:`sm`,value:n,onValueChange:r}),s.length>0?(0,K.jsx)(`div`,{className:`absolute z-20 mt-1 w-full overflow-hidden rounded-xl ${Gb}`,children:(0,K.jsx)(lw,{maxHeight:`18rem`,children:(0,K.jsx)(`ul`,{role:`listbox`,"aria-label":`Search results`,className:`p-1`,children:s.map(e=>(0,K.jsx)(`li`,{role:`option`,"aria-selected":!1,children:(0,K.jsx)(`button`,{type:`button`,className:m(BE,`whitespace-normal`),onClick:()=>{t(e.id),r(``)},children:(0,K.jsx)(`div`,{className:`line-clamp-2`,children:e.name})})},e.id))})})}):null]})}function Iji(e,t){let n=(e,t)=>e.size===t.size&&[...e].every(e=>t.has(e));return e.pages.length===t.pages.length&&e.pages.every((e,n)=>e===t.pages[n])&&n(e.loaded,t.loaded)&&n(e.failed,t.failed)&&e.nextCursor.size===t.nextCursor.size&&[...e.nextCursor].every(([e,n])=>t.nextCursor.get(e)===n)}function Lji(e,t,n,r){let[i,a]=(0,G.useState)(()=>new Set),[o,s]=(0,G.useState)(()=>new Map),c=(0,G.useMemo)(()=>{let e=[{parentId:null}];for(let t of i){e.push({parentId:t});for(let n of o.get(t)??[])e.push({parentId:t,cursor:n})}for(let t of r)i.has(t)||e.push({parentId:t});return e},[i,o,r]),l=(e.useTreeLevels??dji)(c),{pages:u,loaded:d,failed:f,nextCursor:p}=SOi((0,G.useMemo)(()=>{let e=new Set,t=new Map,r=new Set,i=new Map;l.forEach((n,a)=>{let o=c[a];if(!o)return;let s=o.parentId??``;if(n.isError&&e.add(s),n.data){r.add(s);for(let e of n.data.pages)t.set(e.id,e);n.data.nextCursor?i.set(s,n.data.nextCursor):i.delete(s)}});for(let e of[...n?.ancestors??[],...n?[n.page]:[]])t.has(e.id)||t.set(e.id,e);return{pages:[...t.values()],loaded:r,failed:e,nextCursor:i}},[l,c,n]),Iji),m=(0,G.useMemo)(()=>t.truncated?null:new Set(t.pages.map(e=>e.parentId).filter(e=>e!==null)),[t]);return{pages:u,loaded:d,failed:f,mayHaveChildren:(0,G.useCallback)(e=>!d.has(e.id)&&(e.childCountCapped||(e.childCount===void 0?!tji(e)&&(!m||m.has(e.id)):e.childCount>0)),[d,m]),loadMore:(0,G.useMemo)(()=>{let e=new Map;for(let[t,n]of p)e.set(t,()=>s(e=>new Map(e).set(t,[...e.get(t)??[],n])));return e},[p]),onExpandedChange:(0,G.useCallback)(e=>a(new Set(e)),[]),rootsPending:l[0]?.isPending??!1}}function Rji({graph:e,source:t,selectedPageId:n,onSelect:r,view:i,onViewChange:a,toolbarEnd:o,flush:s=!1}){let c=fE(1024),l=!c&&i===`tree`?`graph`:i,u=t.usePage(n),d=!!t.useTreeLevels,[f,p]=(0,G.useState)([]),[m,h]=(0,G.useState)([]),[g,_]=(0,G.useState)(()=>new Set),[v,y]=(0,G.useState)(()=>new Map),[b,x]=(0,G.useState)(!1),[S,C]=(0,G.useState)(!0),w=Lji(t,e,u.data,f),E=(0,G.useMemo)(()=>d?iOi({pages:[...new Map([...e.pages,...w.pages].map(e=>[e.id,e])).values()],loadedParents:w.loaded,rootKey:``,focusId:n,openGroups:g,revealed:v}):{pages:e.pages,hiddenChildren:new Map,wanted:[],hub:null},[d,w.pages,w.loaded,n,g,v,e.pages]),D=!d||E.wanted.every(e=>w.loaded.has(e)||w.failed.has(e));(0,G.useEffect)(()=>{if(!d||l===`page`)return;let e=[...new Set([...E.wanted,...m])];p(t=>t.length===e.length&&t.every((t,n)=>t===e[n])?t:e)},[d,l,E.wanted,m]);let O=(t.usePageLinks??mji)(l===`graph`?n:null).data,k=(0,G.useMemo)(()=>{let e=u.data;if(!e||e.page.id!==n)return null;let t=new Map([...w.pages,...e.ancestors,...e.related].map(e=>[e.id,e])),r=uOi(t.values()),i=e.page.id,a=e.notes.flatMap(e=>e.mentions).filter(e=>e&&e!==i),o=gOi(e.page.body??``).map(e=>e.trim()).filter(e=>e&&e!==i),s=[...a,...o],c=new Set(a),l=new Set(o.filter(e=>!e.includes(`:`)&&!$Ai.test(e)&&!c.has(e))),d=(O?.edges??[]).filter(e=>e.toPageId===i),f=[...new Set([...(e.mentionedBy??[]).map(e=>e.pageId),...d.filter(e=>e.kind===`note`).map(e=>e.fromPageId)])].filter(e=>e!==i),p=[...new Set(d.filter(e=>e.kind===`body`).map(e=>e.fromPageId))].filter(e=>e!==i),m=[...new Set([...f,...p])],h=e=>t.get(e)??r.resolve(e),g=e=>[...new Set(e.filter(e=>!h(e)&&!l.has(e)))],_=e=>new Set(e.flatMap(e=>h(e)?.id??[])).size,v=e=>Math.max(0,rji-_(e)),y=g(s),b=g(m);return{detail:e,known:t,mentions:a,refs:o,into:m,noteInto:f,bodyInto:p,lookup:h,fetchKeys:[...y.slice(0,v(s)),...b.slice(0,v(m))],unfetched:{out:Math.max(0,y.length-v(s)),in:Math.max(0,b.length-v(m))}}},[u.data,n,w.pages,O]),A=k?.fetchKeys??fji,j=(t.useLinkedPages??pji)(A),M=A.map((e,t)=>`${e}=${j[t]?.data?.page?.id??``}`).join(`|`),N=(0,G.useMemo)(()=>{let e=new Map;return A.forEach((t,n)=>{let r=j[n]?.data?.page;r&&e.set(t,r)}),e},[M]),P=(0,G.useMemo)(()=>{if(!k)return{edges:[],pages:[],unfetched:{in:0,out:0}};let{detail:e,lookup:t,mentions:n,refs:r,noteInto:i,bodyInto:a}=k,o=e=>t(e)??N.get(e),s=e.page.id,c=[],l=new Map,u=(e,t,n)=>{let r=o(e);!r||r.id===s?(!r&&t===`mention`&&n===`out`&&c.push({source:s,target:e,kind:t}),!r&&n===`in`&&c.push({source:e,target:s,kind:t})):(l.set(r.id,r),c.push(n===`out`?{source:s,target:r.id,kind:t}:{source:r.id,target:s,kind:t}))};for(let e of n)u(e,`mention`,`out`);for(let e of r)u(e,`link`,`out`);for(let e of i)u(e,`mention`,`in`);for(let e of a)u(e,`link`,`in`);return{edges:c.filter(e=>e.source!==e.target),pages:[...l.values()],unfetched:k.unfetched}},[k,N]),F=(0,G.useMemo)(()=>new Set(P.pages.map(e=>e.id)),[P.pages]),I=(0,G.useMemo)(()=>{let e=new Set(E.pages.map(e=>e.id)),t=P.pages.filter(t=>!e.has(t.id));return{...E,pages:t.length?[...E.pages,...t]:E.pages}},[E,P.pages]),L=(0,G.useMemo)(()=>new Map(I.pages.map(e=>[e.id,e])),[I.pages]),R=e=>h(t=>t.includes(e)?t:[...t,e].slice(-8)),[z,B]=(0,G.useState)(null),V=(0,G.useMemo)(()=>{let t=new Set;return[...e.edges.filter(e=>e.kind===`mention`),..._Oi(I.pages),...P.edges].filter(e=>{let n=`${e.kind}:${e.source}>${e.target}`;return!t.has(n)&&(t.add(n),!0)})},[e.edges,I.pages,P.edges]),H=(0,G.useMemo)(()=>aji(V,L,n,b),[V,L,n,b]),ee=H.edges,te=(0,G.useMemo)(()=>I.pages.filter(e=>!_9(e)&&!v9(e)&&!y9(e)).map(e=>e.id).sort(),[I.pages]),U=(t.useLinkCounts??mji)(l===`graph`?te:[]),W=(0,G.useMemo)(()=>U.data?new Map(Object.entries(U.data)):void 0,[U.data]),ne=(0,G.useMemo)(()=>W?gji(W,ee):H.hidden,[W,ee,H.hidden]),[re,ie]=(0,G.useState)(null),ae=(0,G.useRef)(void 0),oe=(0,G.useCallback)(e=>{clearTimeout(ae.current),e?ae.current=setTimeout(()=>ie(e),hji):ie(null)},[]);(0,G.useEffect)(()=>()=>clearTimeout(ae.current),[]);let se=(t.usePageLinks??mji)(re),ce=(0,G.useMemo)(()=>re&&se.data?se.data.edges.map(e=>({source:e.fromPageId,target:e.toPageId,kind:e.kind===`body`?`link`:`mention`,count:e.count})):[],[re,se.data]),[le,ue]=(0,G.useState)(null),[de,fe]=(0,G.useState)(null),pe=(0,G.useCallback)(()=>ue(null),[]),me=!c||l===`graph`,he=!c,[ge,_e]=(0,G.useState)(!0),[ve,ye]=(0,G.useState)(),be=(0,G.useRef)(null),xe=(0,G.useRef)(null),Se=(0,G.useRef)(null),Ce=(0,G.useRef)(!1),we=de&&de.source===n?de.target:void 0,Te=l===`page`&&!!n,[Ee,De]=(0,G.useState)([]),Oe=(0,G.useRef)(n),ke=(0,G.useRef)(null);(0,G.useEffect)(()=>{let e=Oe.current;Oe.current=n;let t=ke.current;ke.current=null,t&&t===n||e&&n&&e!==n&&De(t=>[...t.filter(e=>e!==n),e].slice(-50))},[n]);let Ae=Ee.length?Ee[Ee.length-1]:void 0,je=()=>{Ae&&(ke.current=Ae,De(e=>e.slice(0,-1)),r(Ae))},Me=e=>{r(e),a(`page`)},Ne=e=>{r(e),i!==`graph`&&a(`graph`)},Pe=e=>{e.isScope&&B(e.id),l===`graph`&&(d||L.has(e.id))&&e.id!==n?Ne(e.id):Me(e.id)},Fe=e=>{z&&!bji([...w.pages,...I.pages],z).some(t=>t.id===e)&&B(null)},Ie=e=>{Fe(e),Me(e)},Le=e=>{l===`graph`&&(d||L.has(e))&&e!==n?(Fe(e),Ne(e)):Ie(e)},Re=z?w.pages.find(e=>e.id===z)??L.get(z):void 0,ze=bji(t.useTreeLevels?w.pages:e.pages,Re?z:null),Be=(0,G.useMemo)(()=>bji(I.pages,Re?z:null),[I.pages,Re,z]),Ve=l===`graph`?L.get(n??I.hub??``):void 0;Ve&&I.hiddenChildren.get(Ve.id);let He=[{value:`tree`,label:`Tree`,icon:(0,K.jsx)(Sa,{}),narrowOnly:!0},{value:`graph`,label:`Graph`,icon:(0,K.jsx)(_o,{}),narrowOnly:!1},{value:`page`,label:`Page`,icon:(0,K.jsx)(oi,{}),narrowOnly:!1}],Ue=oji(l,Te),We=he&&!Te&&n&&!vji(u.error)&&n?n:void 0;We&&We!==ve&&ye(We);let Ge=We??ve,Ke={left:lji(he,ge),right:We?uji:0},qe={"--knowledge-tree-inset":`${Ke.left}px`,"--knowledge-tree-drawer-inset":`${he&&ge?sji:0}px`,"--knowledge-drawer-inset":`${Ke.right}px`},Je=()=>be.current?.querySelector(`[role="tab"][aria-selected="true"]`)?.focus(),Ye=e=>{e&&Ce.current&&(Ce.current=!1,Je())},Xe=e=>{(0,Zc.flushSync)(()=>_e(e)),(e?Se:xe).current?.focus()},Ze=he&&!ge,Qe=he?(0,K.jsxs)(m$.Header,{children:[(0,K.jsx)(m$.Heading,{children:`Pages`}),(0,K.jsx)(m$.HeaderActions,{children:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`Hide pages`,"aria-label":`Hide pages`,ref:Se,onClick:()=>Xe(!1),children:(0,K.jsx)(Zee,{})})})]}):null,$e=(0,K.jsxs)(K.Fragment,{children:[Re?(0,K.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-surface-rim bg-fill-subtle px-3 py-2`,"data-testid":`knowledge-scope-focus`,children:[(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,K.jsx)(T,{as:`span`,variant:`eyebrow`,tone:`muted`,className:`uppercase`,children:Re.displayLabel??`Scope`}),(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5`,children:[(0,K.jsx)(TOi,{page:Re,className:`size-3.5`}),(0,K.jsx)(S9,{label:Re.address??Re.name,children:(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`ink`,className:`truncate`,children:x9(Re)})})]})]}),(0,K.jsx)(X,{variant:`ghost`,size:`sm`,onClick:()=>B(null),children:`All scopes`})]}):null,(0,K.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:t.useTreeLevels&&w.rootsPending?(0,K.jsx)(`div`,{className:`p-2`,children:(0,K.jsx)(Sji,{label:`Loading pages`,rows:6})}):(0,K.jsx)(QAi,{pages:ze,pinnedIds:e.pinnedIds,selectedPageId:n,onSelect:Pe,initiallyExpanded:Re?[Re.id]:void 0,...t.useTreeLevels?{mayHaveChildren:w.mayHaveChildren,onExpandedChange:w.onExpandedChange,loadMore:w.loadMore}:{}},Re?Re.id:`all`)})]}),et=Ge?L.get(Ge)??w.pages.find(e=>e.id===Ge):void 0;return(0,K.jsx)(vOi.Provider,{value:N,children:(0,K.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col ${s?``:`gap-2`}`,children:[(0,K.jsxs)(jq,{className:s?`shrink-0 border-b border-surface-rim px-3 py-2`:void 0,children:[(0,K.jsxs)(jq.Start,{children:[(0,K.jsx)(CA,{ref:be,value:Ue,defaultTab:Ue,onValueChange:e=>a(e),"aria-label":`View`,children:(0,K.jsx)(SA,{variant:`pill-ghost`,size:`sm`,children:He.map(e=>(0,K.jsxs)(wA,{value:e.value,disabled:e.value===`page`&&!n,className:e.narrowOnly?`lg:hidden`:void 0,children:[(0,K.jsx)(TC,{size:`xs`,children:e.icon}),(0,K.jsx)(T,{variant:`caption`,className:`text-inherit`,children:e.label})]},e.value))})}),(0,K.jsx)(Fji,{source:t,onSelect:Le})]}),o?(0,K.jsx)(jq.End,{children:o}):null]}),!d&&e.truncated&&!Te?(0,K.jsxs)(T,{variant:`caption`,tone:`muted`,className:s?`px-3 pt-2`:void 0,children:[`The graph shows the first `,e.pages.length,` pages. Open the tree or search to reach the rest.`]}):null,n&&!Te&&vji(u.error)?(0,K.jsx)(T,{role:`alert`,variant:`caption`,className:`text-destructive-foreground ${s?`px-3 pt-2`:``}`,children:`Page not found. The linked page may have been deleted or merged.`}):null,(0,K.jsxs)(`div`,{style:qe,className:`relative flex min-h-0 flex-1 flex-col gap-3 lg:flex-row`,children:[he?(0,K.jsx)(`div`,{inert:Ze,"aria-hidden":Ze||void 0,"data-state":Ze?`closed`:`open`,className:`absolute inset-y-2 left-2 z-10 flex w-72 transition duration-slow ease-out-custom motion-reduce:transition-none ${Ze?`pointer-events-none -translate-x-4 opacity-0`:`translate-x-0 opacity-100`}`,children:(0,K.jsxs)(m$,{variant:`inline`,title:`Pages`,className:`shadow-overlay`,children:[Qe,$e]})}):(0,K.jsx)(`aside`,{"aria-label":`Pages`,className:`min-h-0 w-full flex-1 flex-col overflow-hidden rounded-lg border border-border bg-card lg:w-72 lg:flex-none lg:shrink-0 ${l===`tree`?`flex`:`hidden`}`,children:$e}),he?(0,K.jsx)(X,{tooltip:`Show pages`,"aria-label":`Show pages`,size:`icon-sm`,inert:!Ze,"aria-hidden":!Ze||void 0,className:`absolute top-3 left-3 z-10 shadow-overlay transition-opacity duration-slow ease-out-custom motion-reduce:transition-none ${Ze?`opacity-100`:`pointer-events-none opacity-0`}`,ref:xe,onClick:()=>Xe(!0),children:(0,K.jsx)(Qee,{})}):null,Te?(0,K.jsx)(`section`,{ref:Ye,"aria-label":`Selected page`,className:`flex min-h-0 min-w-0 flex-1 flex-col ${he?`bg-background p-2 pl-[calc(var(--knowledge-tree-inset)+0.5rem)] transition-[padding] duration-slow ease-out-custom motion-reduce:transition-none ${s?``:`rounded-xl border border-border`}`:`overflow-hidden rounded-lg border border-border bg-card`}`,children:(0,K.jsx)(`div`,{className:he?`flex min-h-0 flex-1 flex-col overflow-hidden rounded-studio-frame ${Kb}`:`contents`,children:(0,K.jsx)(Pji,{source:t,pageId:n,pagesById:L,onSelect:Ie,highlightMentionOf:we})})}):(0,K.jsxs)(`div`,{className:`relative min-h-0 min-w-0 flex-1 overflow-hidden bg-background lg:block lg:h-full ${s?``:`rounded-xl border border-border`} ${l===`graph`?`block`:`hidden`}`,"data-testid":`knowledge-graph-container`,children:[me?(0,K.jsx)(`div`,{className:`absolute top-3 right-3 z-10 -translate-x-(--knowledge-drawer-inset) transition-transform duration-slow ease-out-custom motion-reduce:transition-none`,children:(0,K.jsxs)(fU,{orientation:`vertical`,size:`sm`,"aria-label":`Graph options`,className:`rounded-xl shadow-overlay`,children:[(0,K.jsx)(X,{"data-testid":`knowledge-graph-back`,"aria-label":`Back`,tooltip:Ae?`Back to the previous page`:`Nothing to go back to yet`,tooltipPosition:`left`,size:`icon-sm`,disabled:!Ae,onClick:je,children:(0,K.jsx)(Rt,{})}),(0,K.jsx)(X,{"aria-label":`All links`,"aria-pressed":b,"data-testid":`knowledge-graph-all-links`,tooltip:b?`Show only the selected page’s links`:`Show every link between pages`,tooltipPosition:`left`,size:`icon-sm`,className:b?`[--control-icon:var(--foreground)]`:void 0,onClick:()=>x(e=>!e),children:(0,K.jsx)(ua,{})}),(0,K.jsx)(X,{"aria-label":`Link counts`,"aria-pressed":S,"data-testid":`knowledge-graph-dot-counts`,tooltip:S?`Hide link counts`:`Show link counts on each dot`,tooltipPosition:`left`,size:`icon-sm`,className:S?`[--control-icon:var(--foreground)]`:void 0,onClick:()=>C(e=>!e),children:(0,K.jsx)(Gi,{})})]})}):null,me?(0,K.jsx)(KAi,{pages:Be,edges:ee,pinnedIds:e.pinnedIds,grants:e.grants,selectedPageId:n,centerId:I.hub,hiddenLinks:ne,knownLinks:V,fetchedLinks:ce,exactLinkCounts:W,onHover:oe,nearIds:F,settled:D,insets:Ke,collapsibleLegend:he,showCounts:S,onPreview:e=>{_9(e)&&e.parentId&&R(e.parentId)},onSelect:e=>{if(_9(e))return e.parentId?R(e.parentId):void 0;if(v9(e)){let t=e.parentId;return t?(y(e=>new Map(e).set(t,(e.get(t)??0)+12)),w.loadMore.get(t)?.()):void 0}if(y9(e))return _(t=>new Set(t).add(e.id));Ne(e.id)},onOpen:e=>Me(e.id),onClearSelection:()=>{ue(null),n&&r(null)},onMentionSelect:ue}):null,he?(0,K.jsx)(`div`,{inert:!We,"aria-hidden":!We||void 0,"data-state":We?`open`:`closed`,onTransitionEnd:e=>{!We&&e.target===e.currentTarget&&ye(void 0)},className:`absolute inset-y-2 right-2 z-10 flex w-96 transition duration-slow ease-out-custom motion-reduce:transition-none ${We?`translate-x-0 opacity-100`:`pointer-events-none translate-x-4 opacity-0`}`,children:Ge?(0,K.jsxs)(m$,{variant:`inline`,title:`Page details`,className:`shadow-overlay`,children:[(0,K.jsxs)(m$.Header,{children:[(0,K.jsx)(m$.Heading,{className:`min-w-0 flex-1 shrink`,children:(0,K.jsx)(`span`,{className:`truncate`,children:et?.name??`Page`})}),(0,K.jsxs)(m$.HeaderActions,{children:[(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`Open page`,"aria-label":`Open page`,onClick:()=>{Ce.current=!0,Me(Ge)},children:(0,K.jsx)(Ste,{})}),(0,K.jsx)(m$.CloseButton,{icon:`x`,label:`Close page details`,tooltip:`Close`,onClick:()=>{Je(),r(null)}})]})]}),(0,K.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden`,children:(0,K.jsx)(Pji,{source:t,pageId:Ge,pagesById:L,onSelect:Le,highlightMentionOf:we,compact:!0})})]}):null}):null,le&&me?(0,K.jsx)(Nji,{source:t,mention:le,pagesById:L,onClose:pe,onOpen:e=>{fe(e===le.source.id?{source:le.source.id,target:le.target.id}:null),ue(null),Ie(e)}}):null]})]})]})})}var zji=2,Bji=5e3,Vji=6e4,Hji=5e3,Uji=150,j9=e=>e?Vji:Bji,Wji=e=>e instanceof Ym&&(e.status>=400&&e.status<500||e.status===501);function Gji(e,t){return new Promise(n=>{let r=setTimeout(n,e);t.addEventListener(`abort`,()=>(clearTimeout(r),n()),{once:!0})})}function Kji(e){return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)}var qji=()=>document.visibilityState!==`hidden`;function Jji(e){let t=Y(),n=dy(),[r,i]=(0,G.useState)(!1),a=(0,G.useSyncExternalStore)(Kji,qji,()=>!0),o=(0,G.useRef)(!1);return(0,G.useEffect)(()=>{if(!e||!a)return;let r=new AbortController,s,c=()=>{clearTimeout(s),s=setTimeout(()=>void n.invalidateQueries({queryKey:[`knowledge`,e]}),Uji)};return(async()=>{for(;!r.signal.aborted;){try{let n=(await t.getKnowledge(e).events({signal:r.signal})).getReader();for(o.current&&c(),o.current=!0,i(!0);!(await n.read()).done;)c()}catch(e){if(Wji(e)){i(!1);return}}if(r.signal.aborted)return;i(!1),await Gji(Hji,r.signal)}})(),()=>{r.abort(),clearTimeout(s),i(!1)}},[t,n,e,a]),r}function Yji(){let e=Y();return Ey({queryKey:[`knowledge`,`instances`],queryFn:async()=>(await e.listKnowledge()).instances})}function Xji(e,t){let n=Y();return Ey({queryKey:[`knowledge`,e,`graph`],queryFn:e?async()=>n.getKnowledge(e).graph():yy,refetchInterval:j9(t)})}function Zji(e,t,n,r){let i=Y();return Ey({queryKey:[`knowledge`,e,`page`,n,r??null],queryFn:e&&n?async()=>i.getKnowledge(e).page(n,{noteCursor:r}):yy,refetchInterval:!r&&j9(t)})}function Qji(e,t){let n=Y();return Ty({queries:t.map(t=>({queryKey:[`knowledge`,e,`page`,t,null],queryFn:e?async()=>n.getKnowledge(e).page(t):yy,retry:(e,t)=>!(t&&`status`in t&&t.status===404)&&e<2,staleTime:3e4}))})}function $ji(e,t,n){let r=Y();return Ty({queries:n.map(n=>({queryKey:[`knowledge`,e,`tree`,n.parentId,n.cursor??null],queryFn:e?async()=>r.getKnowledge(e).tree({parentId:n.parentId??void 0,cursor:n.cursor}):yy,refetchInterval:!n.cursor&&j9(t)}))})}var eMi=200,tMi=(e,t)=>!Wji(t)&&e<2;function nMi(e,t,n){let r=Y();return Ey({queryKey:[`knowledge`,e,`link-counts`,n],queryFn:e&&n.length?async()=>{let t=r.getKnowledge(e),i=[];for(let e=0;e<n.length;e+=eMi)i.push(n.slice(e,e+eMi));let a=await Promise.all(i.map(e=>t.linkCounts(e)));return Object.assign({},...a.map(e=>e.counts))}:yy,placeholderData:vy,retry:tMi,refetchInterval:j9(t)})}function rMi(e,t){let n=Y();return Ey({queryKey:[`knowledge`,e,`page-links`,t],queryFn:e&&t?async()=>n.getKnowledge(e).pageLinks(t):yy,staleTime:3e4,retry:tMi})}function iMi(e,t,n){let r=Y();return Ey({queryKey:[`knowledge`,e,`activity`,n],queryFn:e?async()=>r.getKnowledge(e).activity({pageId:n}):yy,refetchInterval:j9(t)})}function aMi(e,t){let n=Y(),r=t.trim();return Ey({queryKey:[`knowledge`,e,`search`,r],queryFn:e&&r.length>=zji?async()=>n.getKnowledge(e).search(r):yy,placeholderData:vy})}var oMi=[sF(`/knowledge`)];function M9({children:e}){return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:oMi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Knowledge`}),e]})}function sMi({knowledgeKey:e,live:t,graph:n}){let[r,i]=Hb(),a=r.get(`page`),o=r.get(`view`),s=o===`graph`||o===`page`||o===`tree`?o:a?`page`:`tree`,c=(0,G.useMemo)(()=>({usePage:(n,r)=>Zji(e,t,n,r),useSearch:t=>aMi(e,t),useTreeLevels:n=>$ji(e,t,n),useLinkCounts:n=>nMi(e,t,n),usePageLinks:t=>rMi(e,t),useLinkedPages:t=>Qji(e,t),useActivity:n=>iMi(e,t,n)}),[e,t]),l=Zji(e,t,a).data?.page.id;(0,G.useEffect)(()=>{l&&a&&l!==a&&i(e=>{let t=new URLSearchParams(e);return t.set(`page`,l),t},{replace:!0})},[l,a,i]);let u=(0,G.useRef)(null);(0,G.useEffect)(()=>{u.current=null},[r]);let d=(e,t)=>{let n=new URLSearchParams(u.current??r);t===null?n.delete(e):n.set(e,t),u.current=n,i(n)};return(0,K.jsx)(Rji,{graph:n,source:c,selectedPageId:a,onSelect:e=>d(`page`,e),view:s,onViewChange:e=>d(`view`,e)})}function cMi(){let[e,t]=Hb(),n=Yji(),r=e.get(`instance`)??n.data?.[0]?.key,i=Jji(r),a=Xji(r,i),o=n.error??a.error;return o&&JP(o)?(0,K.jsx)(M9,{children:(0,K.jsx)(jU,{variant:`fill`})}):o&&YP(o)?(0,K.jsx)(M9,{children:(0,K.jsx)(AU,{variant:`fill`,resource:`knowledge`})}):n.error&&!n.data&&XP(n.error)?(0,K.jsx)(M9,{children:(0,K.jsx)(RC,{variant:`fill`,titleSlot:`Knowledge browsing is not enabled`,descriptionSlot:`This server does not register the Knowledge routes. Add KNOWLEDGE_ROUTES from @mastra/server/server-adapter to server.apiRoutes, then reload.`})}):n.error&&!n.data?(0,K.jsx)(M9,{children:(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load Knowledge`,descriptionSlot:n.error.message})}):n.data&&n.data.length===0?(0,K.jsx)(M9,{children:(0,K.jsx)(RC,{variant:`fill`,titleSlot:`No Knowledge instances`,descriptionSlot:`Register one on your Mastra instance with the knowledge option to browse it here.`})}):(0,K.jsx)(M9,{children:(0,K.jsxs)(`div`,{className:`flex h-full min-h-0 flex-1 flex-col gap-3`,children:[n.data&&n.data.length>1?(0,K.jsx)(`select`,{"aria-label":`Knowledge instance`,className:`text-ui-md h-8 w-fit rounded border border-border bg-card px-2`,value:r,onChange:e=>t(new URLSearchParams({instance:e.target.value})),children:n.data.map(e=>(0,K.jsx)(`option`,{value:e.key,children:e.key},e.key))}):null,!r||a.isPending?(0,K.jsx)(`p`,{className:`text-ui-md p-4 text-muted-foreground`,children:`Loading knowledge…`}):a.data?a.data.pages.length===0?(0,K.jsx)(RC,{variant:`fill`,titleSlot:`No pages yet`,descriptionSlot:`Agents add pages and notes to Knowledge as they run. They will appear here.`}):(0,K.jsx)(sMi,{knowledgeKey:r,live:i,graph:a.data}):(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load Knowledge`,descriptionSlot:a.error?.message})]})})}function lMi({title:e,description:t,errorBanner:n,children:r}){return(0,K.jsxs)(`div`,{"data-testid":`login-page`,className:`w-full max-w-sm space-y-6 p-6`,children:[(0,K.jsxs)(`div`,{className:`flex flex-col items-center space-y-2`,children:[(0,K.jsx)(EQ,{className:`h-10 w-10`}),(0,K.jsx)(T,{as:`h1`,variant:`heading`,tone:`ink`,children:e})]}),t,n,r]})}function uMi({redirectUri:e,onSuccess:t,initialMode:n=`signin`,errorMessage:r}){let{data:i,isLoading:a}=jy(),{mutate:o,isPending:s,error:c}=eHe(),{mutate:l,isPending:u,error:d}=nHe(),{mutate:f,isPending:p}=rHe(),[m,h]=(0,G.useState)(n),[g,_]=(0,G.useState)(``),[v,y]=(0,G.useState)(``),[b,x]=(0,G.useState)(``);if(a)return(0,K.jsx)(`div`,{className:`text-muted-foreground`,children:`Loading...`});if(!i?.enabled||!i?.login)return(0,K.jsx)(`div`,{className:`text-muted-foreground`,children:`Authentication is not configured`});let{login:S}=i,C=S.type===`sso`||S.type===`both`,w=S.type===`credentials`||S.type===`both`,E=S.sso,D=S.signUpEnabled!==!1,O=m===`signin`||!D,k=O?s:u,A=O?c:d,j=()=>{t?t():e?window.location.href=e:window.location.href=DQ(`/`)},M=e=>{e.preventDefault(),O?o({email:v,password:b},{onSuccess:j}):l({email:v,password:b,name:g||void 0},{onSuccess:j})},N=()=>{f({redirectUri:e},{onSuccess:e=>{window.location.href=e.url}})},P=()=>{h(O?`signup`:`signin`)},F=S.description?(0,K.jsxs)(`div`,{className:`flex items-start gap-2.5 rounded-md border border-border bg-sidebar p-3`,children:[(0,K.jsx)(ja,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}),(0,K.jsx)(T,{tone:`muted`,children:S.description})]}):null;return(0,K.jsxs)(lMi,{title:O?`Sign in to Mastra Studio`:`Create your account`,description:F,errorBanner:r?(0,K.jsx)(`div`,{role:`alert`,children:(0,K.jsx)(EA,{variant:`destructive`,children:r})}):null,children:[w&&(0,K.jsxs)(uU,{onSubmit:M,children:[!O&&(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{children:`Name`}),(0,K.jsx)(ZM,{name:`name`,type:`text`,autoComplete:`name`,value:g,onChange:e=>_(e.target.value),placeholder:`Your name`,variant:`default`,size:`lg`})]}),(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{required:!0,children:`Email`}),(0,K.jsx)(ZM,{name:`email`,type:`email`,autoComplete:`email`,value:v,onChange:e=>y(e.target.value),placeholder:`you@example.com`,required:!0,variant:`default`,size:`lg`}),(0,K.jsx)(gA,{})]}),(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{required:!0,children:`Password`}),(0,K.jsx)(ZM,{name:`password`,type:`password`,autoComplete:O?`current-password`:`new-password`,value:b,onChange:e=>x(e.target.value),placeholder:O?`Enter your password`:`Create a password`,required:!0,variant:`default`,size:`lg`}),(0,K.jsx)(gA,{})]}),A?(0,K.jsx)(`div`,{role:`alert`,children:(0,K.jsx)(EA,{variant:`destructive`,children:A.message})}):null,(0,K.jsx)(X,{icon:(0,K.jsx)(Na,{}),type:`submit`,disabled:k,className:`w-full`,size:`lg`,children:k?O?`Signing in...`:`Creating account...`:O?`Sign in`:`Create account`}),D&&(0,K.jsxs)(`div`,{className:`text-center`,children:[(0,K.jsx)(T,{as:`span`,variant:`body`,tone:`muted`,children:O?`Don't have an account? `:`Already have an account? `}),(0,K.jsx)(`button`,{type:`button`,onClick:P,className:`text-foreground hover:underline`,children:(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:O?`Sign up`:`Sign in`})})]})]}),C&&w&&(0,K.jsxs)(`div`,{className:`relative`,children:[(0,K.jsx)(`div`,{className:`absolute inset-0 flex items-center`,children:(0,K.jsx)(`div`,{className:`w-full border-t border-border`})}),(0,K.jsx)(`div`,{className:`relative flex justify-center`,children:(0,K.jsx)(T,{as:`span`,variant:`body`,tone:`muted`,className:`bg-sidebar px-2`,children:`or continue with`})})]}),C&&E&&(0,K.jsxs)(X,{onClick:N,disabled:p,className:`w-full`,size:`lg`,children:[E.icon&&(0,K.jsx)(`span`,{className:`mr-2`,children:E.icon}),p?`Redirecting...`:E.text||`Sign in`]})]})}function dMi(){let[e]=Hb(),t=kb(),n=e.get(`redirect`)||`/`,r=e.get(`mode`)===`signup`?`signup`:`signin`,i=e.get(`error_description`)||e.get(`error`)||null;return(0,K.jsx)(uMi,{redirectUri:n,onSuccess:()=>{n.startsWith(`http`)?window.location.href=n:t(n,{replace:!0})},initialMode:r,errorMessage:i})}function fMi({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)(Hc,{}),children:`Clear`}),a&&(0,K.jsxs)(mD,{children:[(0,K.jsx)(mD.Trigger,{asChild:!0,children:(0,K.jsx)(X,{disabled:e,size:`icon-md`,"aria-label":`More filter actions`,children:(0,K.jsx)(Ar,{})})}),(0,K.jsxs)(mD.Content,{align:`end`,children:[n&&(0,K.jsxs)(mD.Item,{onSelect:()=>n(),children:[(0,K.jsx)(Hc,{}),`Remove all filters`]}),n&&(r||i)&&(0,K.jsx)(mD.Separator,{}),r&&(0,K.jsxs)(mD.Item,{onSelect:()=>r(),children:[(0,K.jsx)(fs,{}),`Save filters for next time`]}),i&&(0,K.jsxs)(mD.Item,{onSelect:()=>i(),children:[(0,K.jsx)(Sc,{}),`Remove saved filters`]})]})]})]})}var pMi=m(BE,`min-w-0`);function mMi({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:pMi,onClick:r,children:[(0,K.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:n}),t&&(0,K.jsx)(`span`,{className:HE,children:(0,K.jsx)(Bn,{})})]})}function hMi({field:e,tokens:t,onChange:n}){let[r,i]=(0,G.useState)(``),a=`max-h-[80dvh] overflow-auto p-1`,o=(0,G.useMemo)(()=>{let t=r.trim().toLowerCase();return t?e.options.filter(e=>e.label.toLowerCase().includes(t)):e.options},[e.options,r]),s=(0,G.useMemo)(()=>t.find(t=>t.fieldId===e.id),[t,e.id]),c=typeof s?.value==`string`?s.value:e.multi?void 0:e.defaultValue,l=(0,G.useMemo)(()=>{let e=s?.value;return Array.isArray(e)?e:typeof e==`string`?[e]:[]},[s]);return(0,K.jsxs)(K.Fragment,{children:[e.searchable!==!1&&(0,K.jsxs)(`div`,{className:KE.container,children:[(0,K.jsx)(_s,{className:KE.icon}),(0,K.jsx)(`input`,{type:`text`,value:r,onChange:e=>i(e.target.value),placeholder:`Search ${e.label.toLowerCase()}`,className:KE.input,...YA,onKeyDown:e=>{if(e.key!==`ArrowDown`)return;let t=e.currentTarget.closest(`[data-pick-multi-panel]`)?.querySelector(`[data-pick-multi-item]:not([disabled])`);t&&(e.preventDefault(),e.stopPropagation(),t.focus())}})]}),e.isLoading?(0,K.jsxs)(`div`,{className:m(pnt,`m-1`),children:[(0,K.jsx)(Qc,{size:`sm`,className:`size-3 text-muted-foreground`}),`Loading options…`]}):o.length===0?(0,K.jsx)(`div`,{className:m(pnt,`m-1`),children:e.emptyText??`No option found.`}):e.multi?(0,K.jsx)(`div`,{className:a,children:(0,K.jsx)(K.Fragment,{children:o.map(t=>{let r=l.includes(t.value);return(0,K.jsx)(mMi,{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)(mMi,{role:`radio`,checked:c===t.value,label:t.label,onClick:()=>n(e.id,t.value)},t.value)),!e.omitAnyOption&&(0,K.jsx)(mMi,{role:`radio`,checked:c===`Any`,label:`Any`,onClick:()=>n(e.id,`Any`)})]})})]})}function gMi(e){return Array.isArray(e)?e.length===0?`Any`:e.join(`, `):e}var _Mi=`This filter is set by the current context and cannot be removed here.`;function vMi(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:gMi(t)}function yMi({field:e,value:t,tooltipContent:n}){let r=vMi(e,t),i=`${e.label} filter is locked by context`;return(0,K.jsx)(bC,{delayDuration:150,children:(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{asChild:!0,children:(0,K.jsxs)(fU,{"data-locked-field-id":e.id,"data-property-filter-pill":`locked`,tabIndex:0,"aria-label":i,children:[(0,K.jsx)(pU,{children:e.label}),(0,K.jsx)(pU,{children:`is`}),(0,K.jsx)(pU,{children:r}),(0,K.jsx)(pU,{children:(0,K.jsx)(ja,{})})]})}),(0,K.jsx)(CC,{children:n})]})})}function bMi({field:e,value:t,onChange:n,onRemove:r,disabled:i,autoFocus:a}){let[o,s]=(0,G.useState)(t),c=(0,G.useRef)(null);return(0,G.useEffect)(()=>{o.trim()!==t&&s(t)},[t]),(0,G.useEffect)(()=>{a&&c.current?.focus()},[a]),(0,K.jsxs)(fU,{children:[(0,K.jsx)(pU,{children:e.label}),(0,K.jsx)(pU,{children:`is`}),(0,K.jsx)(ZM,{ref:c,disabled:i,value:o,placeholder:e.placeholder??`Enter ${e.label}`,onChange:e=>{let r=e.target.value;s(r),r.trim()!==t&&n(r)},onKeyDown:e=>{if(e.key===`Enter`){e.preventDefault();let r=o.trim();r!==t&&n(r)}else e.key===`Escape`&&(e.preventDefault(),s(t),e.currentTarget.blur())}}),(0,K.jsx)(X,{size:`icon-md`,type:`button`,disabled:i,"aria-label":`Remove ${e.label} filter`,onMouseDown:e=>e.preventDefault(),onClick:r,children:(0,K.jsx)(Hc,{})})]})}function xMi({field:e,token:t,tokens:n,onChange:r,onRemove:i,disabled:a}){let[o,s]=(0,G.useState)(!1);return(0,K.jsxs)(fU,{children:[(0,K.jsx)(pU,{children:e.label}),(0,K.jsx)(pU,{children:`is`}),(0,K.jsxs)($M,{open:o,onOpenChange:s,children:[(0,K.jsx)(eN,{asChild:!0,children:(0,K.jsx)(X,{type:`button`,disabled:a,children:gMi(t.value)})}),(0,K.jsx)(tN,{align:`start`,sideOffset:4,className:`w-64 p-0`,"data-pick-multi-panel":!0,children:(0,K.jsx)(hMi,{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)(Hc,{})})]})}function SMi({fields:e,tokens:t,onTokensChange:n,disabled:r,autoFocusFieldId:i,lockedFieldIds:a,lockedTooltipContent:o=_Mi}){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)(yMi,{field:u,value:n.value,tooltipContent:o},`${n.fieldId}-${a}`):u.kind===`text`&&!Array.isArray(n.value)?(0,K.jsx)(bMi,{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)(xMi,{field:u,token:n,tokens:t,disabled:r,onChange:(e,t)=>c(a,{fieldId:e,value:t}),onRemove:()=>l(a)},`${n.fieldId}-${a}`):(0,K.jsxs)(fU,{children:[(0,K.jsx)(pU,{children:u.label}),(0,K.jsx)(pU,{children:`is`}),(0,K.jsx)(pU,{children:gMi(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)(Hc,{})})]},`${n.fieldId}-${a}`):null})})}var CMi=(0,G.forwardRef)((e,t)=>(0,K.jsx)(`button`,{type:`button`,role:`menuitem`,"data-filter-item":``,ref:t,...e}));CMi.displayName=`FilterMenuButton`;function wMi({fields:e,tokens:t,onTokensChange:n,label:r=`Add filter`,disabled:i,size:a,onStartTextFilter:o,hiddenFieldIds:s}){let c=(0,G.useMemo)(()=>{if(!s||s.length===0)return e;let t=new Set(s);return e.filter(e=>!t.has(e.id))},[e,s]),[l,u]=(0,G.useState)(!1),[d,f]=(0,G.useState)(),[p,h]=(0,G.useState)([]),[g,_]=(0,G.useState)(),[v,y]=(0,G.useState)(),b=(0,G.useRef)(!1),x=(0,G.useCallback)(e=>{y(t=>t===e?void 0:e)},[]),S=(0,G.useCallback)(()=>y(void 0),[]);(0,G.useEffect)(()=>{l||y(void 0)},[l]);let C=(0,G.useMemo)(()=>c.find(e=>e.id===d),[c,d]),w=(0,G.useMemo)(()=>{let n=new Set;for(let r of t){let t=e.find(e=>e.id===r.fieldId);t&&t.kind!==`pick-multi`&&n.add(r.fieldId)}return n},[t,e]),E=(0,G.useCallback)(()=>{f(void 0),h([]),_(void 0)},[]);(0,G.useEffect)(()=>{l||E()},[l,E]);let D=(0,G.useCallback)((e,r)=>{let i=t.findIndex(t=>t.fieldId===e);if(Array.isArray(r)&&r.length===0){if(i===-1)return;n(t.filter((e,t)=>t!==i));return}if(i===-1){n([...t,{fieldId:e,value:r}]);return}let a=[...t];a[i]={fieldId:e,value:r},n(a)},[n,t]),O=(0,G.useCallback)(()=>{C?w.has(C.id)?_(`Remove the existing ${C.label} filter before adding another.`):p.length===0?_(`Choose at least one ${C.label.toLowerCase()} value.`):(n([...t,{fieldId:C.id,value:p}]),u(!1)):_(`Choose a property first.`)},[p,n,C,w,t]);return(0,K.jsxs)($M,{open:l,onOpenChange:u,children:[(0,K.jsx)(eN,{asChild:!0,children:(0,K.jsx)(X,{size:a,disabled:i,icon:(0,K.jsx)(ga,{}),children:r})}),(0,K.jsx)(tN,{align:`start`,sideOffset:4,className:m(`w-64`,C?`p-3`:`p-1`),initialFocus:!1,finalFocus:()=>!b.current||(b.current=!1,!1),children:(0,K.jsxs)(`div`,{className:m(`grid`,C&&`gap-3`),children:[C&&(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`button`,{type:`button`,"aria-label":`Back to properties`,className:m(`text-muted-foreground hover:text-foreground`,`transition-[color] duration-fast ease-out-custom motion-reduce:transition-none`),onClick:E,children:(0,K.jsx)(Rt,{className:`size-4`})}),(0,K.jsx)(Ti,{className:`size-4 shrink-0 text-muted-foreground`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:`${C.label} is`})]}),!C&&(0,K.jsx)(`div`,{role:`menu`,className:`max-h-[80dvh] overflow-auto`,onKeyDown:e=>{if(e.key!==`ArrowDown`&&e.key!==`ArrowUp`&&e.key!==`Home`&&e.key!==`End`)return;let t=Array.from(e.currentTarget.querySelectorAll(`[data-filter-item]:not([disabled])`));if(t.length===0)return;e.preventDefault();let n=document.activeElement,r=t.findIndex(e=>e===n),i;i=e.key===`Home`?0:e.key===`End`?t.length-1:e.key===`ArrowDown`?r<0?0:(r+1)%t.length:r<=0?t.length-1:r-1,t[i]?.focus()},children:(0,K.jsx)(K.Fragment,{children:c.length>0?c.map(e=>{let r=w.has(e.id);return e.kind===`pick-multi`?(0,K.jsx)(TMi,{field:e,tokens:t,onChange:D,open:v===e.id,onToggle:x,onClose:S},e.id):(0,K.jsxs)(CMi,{className:m(BE,`group`),disabled:r,onClick:()=>{_(void 0),e.kind===`text`?(n([...t,{fieldId:e.id,value:``}]),o?.(e.id),b.current=!0,u(!1)):f(e.id)},children:[(0,K.jsx)(`span`,{className:`truncate`,children:e.label}),r?(0,K.jsx)(`span`,{className:`ml-auto text-muted-foreground`,children:`In use`}):(0,K.jsx)(`span`,{className:m(VE,`text-muted-foreground opacity-0 group-hover:opacity-100 group-focus:opacity-100`),children:(0,K.jsx)(Uo,{})})]},e.id)}):(0,K.jsx)(`div`,{className:`flex h-control-md items-center gap-2 px-2 py-0.5 text-menu text-muted-foreground box-content`,children:`No matching property.`})})}),C&&(0,K.jsxs)(fA,{invalid:!!g,children:[(0,K.jsx)(TP,{multiple:!0,options:C.options??[],value:p,onValueChange:e=>{h(e),_(void 0)},placeholder:C.placeholder??`Choose ${C.label}`,searchPlaceholder:`Search ${C.label.toLowerCase()}`,emptyText:C.emptyText??`No option found.`,size:`md`,"aria-label":C.label}),(0,K.jsx)(gA,{children:g})]}),C&&(0,K.jsxs)(`div`,{className:`flex items-center justify-end gap-2`,children:[(0,K.jsx)(X,{icon:(0,K.jsx)(Hc,{}),variant:`ghost`,size:`md`,onClick:()=>u(!1),children:`Cancel`}),(0,K.jsx)(X,{icon:(0,K.jsx)(ga,{}),size:`md`,onClick:O,children:`Add filter`})]})]})})]})}function TMi({field:e,tokens:t,onChange:n,open:r,onToggle:i,onClose:a}){let o=(0,G.useRef)(null);return(0,K.jsxs)($M,{open:r,onOpenChange:t=>{t?i(e.id):a()},children:[(0,K.jsx)(eN,{asChild:!0,children:(0,K.jsxs)(CMi,{className:BE,onKeyDown:t=>{(t.key===`ArrowRight`||t.key===`ArrowLeft`)&&(r||i(e.id),t.preventDefault(),requestAnimationFrame(()=>{(o.current?.querySelector(`input, button, [tabindex]:not([tabindex="-1"])`))?.focus()}))},children:[r&&(0,K.jsx)(c,{className:`text-muted-foreground`}),(0,K.jsx)(`span`,{className:`truncate`,children:e.label}),!r&&(0,K.jsx)(`span`,{className:m(VE,`text-muted-foreground`),children:(0,K.jsx)(c,{})})]})}),(0,K.jsx)(tN,{ref:o,side:`right`,align:`start`,sideOffset:4,className:`w-64 p-0`,initialFocus:!1,onKeyDown:e=>{if(e.key!==`ArrowDown`&&e.key!==`ArrowUp`&&e.key!==`Home`&&e.key!==`End`)return;let t=Array.from(e.currentTarget.querySelectorAll(`[data-pick-multi-item]:not([disabled])`));if(t.length===0)return;e.preventDefault(),e.stopPropagation();let n=document.activeElement,r=t.findIndex(e=>e===n),i;i=e.key===`Home`?0:e.key===`End`?t.length-1:e.key===`ArrowDown`?r<0?0:(r+1)%t.length:r<=0?t.length-1:r-1,t[i]?.focus()},"data-pick-multi-panel":!0,children:(0,K.jsx)(hMi,{field:e,tokens:t,onChange:n})})]})}function EMi({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:i,onNext:a,depth:o}){let s=e?Iw(e.timestamp)??``:``;return(0,K.jsx)(m$,{open:!!e,onClose:t,title:e?`Log ${s}`:`Log`,depth:o,children:e&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(m$.Header,{children:[(0,K.jsx)(m$.CloseButton,{onClick:t}),(0,K.jsx)(m$.Heading,{children:`Log`}),(0,K.jsx)(m$.Metadata,{children:(0,K.jsx)(m$.Meta,{tooltip:s,children:s})}),(0,K.jsx)(m$.HeaderActions,{children:(0,K.jsx)(m$.NextPrevNav,{onPrevious:i,onNext:a,previousLabel:`Go to previous log`,nextLabel:`Go to next log`})})]}),(0,K.jsx)(m$.Content,{children:(0,K.jsxs)(`div`,{className:`grid gap-6 p-2`,children:[(0,K.jsxs)(y3,{children:[e.entityType&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(y3.Key,{children:`Entity Type`}),(0,K.jsx)(y3.Value,{children:e.entityType})]}),e.entityName&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(y3.Key,{children:`Entity Name`}),(0,K.jsx)(y3.Value,{children:e.entityName})]}),e.serviceName&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(y3.Key,{children:`Service`}),(0,K.jsx)(y3.Value,{children:e.serviceName})]}),e.environment&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(y3.Key,{children:`Environment`}),(0,K.jsx)(y3.Value,{children:e.environment})]}),e.source&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(y3.Key,{children:`Source`}),(0,K.jsx)(y3.Value,{children:e.source})]}),e.metadata&&Object.entries(e.metadata).map(([e,t])=>(0,K.jsxs)(G.Fragment,{children:[(0,K.jsx)(y3.Key,{children:e}),(0,K.jsx)(y3.Value,{children:String(t)})]},e))]}),(0,K.jsx)(m$.CodeSection,{title:`Message`,codeStr:e.message,simplified:!0}),(e.traceId||e.spanId)&&(0,K.jsxs)(`div`,{className:`grid gap-2`,children:[e.traceId&&(0,K.jsxs)(fU,{className:`w-full min-w-0`,children:[(0,K.jsxs)(X,{className:`min-w-0 flex-1 justify-between overflow-hidden`,icon:(0,K.jsx)(Ht,{}),onClick:()=>e.traceId&&n?.(e.traceId),children:[(0,K.jsx)(`span`,{children:`Trace`}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,tone:`faint`,className:`ml-auto min-w-0 truncate`,children:[`# `,e.traceId]})]}),(0,K.jsx)(jw,{content:e.traceId,tooltip:`Copy trace ID to clipboard`})]}),e.spanId&&(0,K.jsxs)(fU,{className:`w-full min-w-0`,children:[(0,K.jsxs)(X,{className:`min-w-0 flex-1 justify-between overflow-hidden`,disabled:!e.traceId||!r,onClick:()=>e.traceId&&e.spanId&&r?.(e.traceId,e.spanId),icon:(0,K.jsx)(Ht,{}),children:[(0,K.jsx)(`span`,{children:`Span`}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,tone:`faint`,className:`ml-auto min-w-0 truncate`,children:[`# `,e.spanId]})]}),(0,K.jsx)(jw,{content:e.spanId,tooltip:`Copy span ID to clipboard`})]})]}),e.data&&Object.keys(e.data).length>0&&(0,K.jsx)(m$.CodeSection,{title:`Data`,codeStr:JSON.stringify(e.data,null,2)})]})})]})})}function DMi({error:e,resource:t,errorTitle:n}){if(JP(e))return(0,K.jsx)(jU,{});if(YP(e))return(0,K.jsx)(AU,{resource:t});if(QP(e))return(0,K.jsx)(RC,{titleSlot:`Observability storage is not available`,descriptionSlot:`The observability storage domain is disabled or not configured. Enable it in your storage configuration to view logs in Studio.`});if(ZP(e,`logs`))return(0,K.jsx)(RC,{titleSlot:`Logs are not available with your current storage`,descriptionSlot:`The configured observability storage provider does not support listing logs. Switch to a storage provider with logs support to view runtime logs in Studio.`});let r=e instanceof Error?e.message:void 0;return(0,K.jsx)(RC,{tone:`error`,titleSlot:n,descriptionSlot:r??`Unknown error`})}var OMi={debug:`neutral`,info:`info`,warn:`warning`,error:`destructive`,fatal:`destructive`};function kMi({level:e}){return(0,K.jsx)(_U,{children:(0,K.jsx)(bw,{variant:OMi[e],children:e})})}function AMi({entityType:e,className:t}){let n=m(`size-3.5 shrink-0 text-placeholder`,t);switch(e.toLowerCase()){case`agent`:return(0,K.jsx)(tF,{className:n,"aria-hidden":!0});case`workflow`:case`workflow_run`:return(0,K.jsx)(rP,{className:n,"aria-hidden":!0});case`tool`:return(0,K.jsx)(aF,{className:n,"aria-hidden":!0});default:return null}}function jMi({entityType:e,entityName:t}){return(0,K.jsxs)(_U,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(AMi,{entityType:e??``}),t?(0,K.jsx)(T,{as:`span`,variant:`body-sm`,className:`min-w-0 truncate`,children:t}):`-`]})}function MMi({message:e}){return(0,K.jsx)(_U,{className:`min-w-0 truncate font-mono text-body-sm text-muted-foreground`,children:e})}function NMi({data:e}){if(!e||Object.keys(e).length===0)return(0,K.jsx)(_U,{children:null});let t=Object.entries(e).map(([e,t])=>{if(typeof t==`string`)return`${e}: ${t}`;try{return`${e}: ${JSON.stringify(t)}`}catch{return`${e}: <unserializable>`}}).join(`, `);return(0,K.jsx)(bU,{font:`mono`,children:t})}var N9=Object.assign(wU,{Top:kU,TopCell:EU,SortableTopCell:OU,TopCellWithTooltip:DU,TopCellSmart:Pyn,RowWrapper:kyn,RowButton:TU,RowLink:Dyn,Spacer:Byn,NoMatch:SU,DateCell:Yvn,TimeCell:Zvn,LevelCell:kMi,EntityCell:jMi,MessageCell:MMi,DataCell:NMi,NextPageLoading:xU}),PMi=`6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)`,FMi=36,IMi=8;function LMi({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=Ati({count:e.length,getScrollElement:()=>u.current,estimateSize:()=>FMi,overscan:IMi}),{getRowProps:f}=_Q({count:e.length,containerRef:u,onNavigate:e=>d.scrollToIndex(e),global:!0}),p=(0,G.useRef)(t);if((0,G.useEffect)(()=>{p.current&&!t&&u.current?.dispatchEvent(new Event(`scroll`)),p.current=t},[t]),t)return(0,K.jsx)(NU,{columns:PMi,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)(N9,{columns:PMi,scrollRef:u,className:`min-w-0`,fit:`container`,children:[(0,K.jsxs)(N9.Top,{children:[l?(0,K.jsx)(N9.SortableTopCell,{sortKey:`timestamp`,sort:c,onSortChange:l,children:`Date`}):(0,K.jsx)(N9.TopCell,{children:`Date`}),(0,K.jsx)(N9.TopCell,{children:`Time`}),(0,K.jsx)(N9.TopCell,{children:`Level`}),(0,K.jsx)(N9.TopCell,{children:`Entity`}),(0,K.jsx)(N9.TopCell,{children:`Message`}),(0,K.jsx)(N9.TopCell,{children:`Data`})]}),e.length===0?(0,K.jsx)(N9.NoMatch,{message:`No logs match your search`}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(N9.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)(N9.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)(N9.DateCell,{timestamp:n.timestamp}),(0,K.jsx)(N9.TimeCell,{timestamp:n.timestamp}),(0,K.jsx)(N9.LevelCell,{level:n.level}),(0,K.jsx)(N9.EntityCell,{entityType:n.entityType,entityName:n.entityName}),(0,K.jsx)(N9.MessageCell,{message:n.message}),(0,K.jsx)(N9.DataCell,{data:n.data})]},r)}),(0,K.jsx)(N9.Spacer,{height:_})]}),(0,K.jsx)(N9.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:i})]})}function RMi({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=>zMi(e,a));return l?(0,K.jsxs)(`div`,{className:m(`grid grid-cols-[1fr_auto] items-start gap-3`),children:[(0,K.jsx)(SMi,{fields:a,tokens:o,onTokensChange:s,disabled:i,autoFocusFieldId:c}),l&&(0,K.jsx)(fMi,{disabled:i,onClear:u?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]}):null}function zMi(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 BMi={"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`},VMi=`Pick a wider range or lower the logging level. Verbose entries (debug, info) may be filtered out.`;function HMi({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!==`all`&&e!==`custom`?{title:`No logs for ${BMi[e]}`,description:VMi}:t&&n?{title:`No logs between ${Fw(t,`date-time`)} and ${Fw(n,`date-time`)}`,description:VMi}:t?{title:`No logs since ${Fw(t,`date-time`)}`,description:VMi}:{title:`No logs yet`,description:`Logs will appear here once agents, workflows, or tools are executed.`}}var UMi=({datePreset:e,dateFrom:t,dateTo:n}={})=>{let{title:r,description:i}=HMi({datePreset:e,dateFrom:t,dateTo:n});return(0,K.jsx)(RC,{titleSlot:r,descriptionSlot:i,actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/en/docs/observability/logging`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(Br,{}),children:`Logging documentation`}),variant:`fill`})},WMi=`Filters setting for Logs saved`,GMi=`Filters setting for Logs cleared up`;function KMi(e,t,n){let{storageKey:r,messages:i,skipHydration:a}=n??{},[o,s]=(0,G.useState)(()=>gci(r)!==null),c=(0,G.useCallback)(()=>{mci(e,r),s(!0);let t=i?.saved??WMi;t!==!1&&UC.success(t)},[e,r,i?.saved]),l=(0,G.useCallback)(()=>{hci(r),s(!1);let e=i?.cleared??GMi;e!==!1&&UC.success(e)},[r,i?.cleared]),u=(0,G.useRef)(!1);return(0,G.useEffect)(()=>{if(a||u.current||(u.current=!0,_ci(e)))return;let n=gci(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 qMi(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 JMi(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,qMi(`${e}${n.message??``}${n.data?JSON.stringify(n.data):``}`))}return t}function YMi(e,t,n,r){let i=(0,G.useMemo)(()=>JMi(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 XMi=`logId`,ZMi=`traceId`,QMi=`spanId`,P9=864e5,$Mi={"last-24h":P9,"last-3d":3*P9,"last-7d":7*P9,"last-14d":14*P9,"last-30d":30*P9};function eNi(e){e.delete(XMi),e.delete(ZMi),e.delete(QMi)}function tNi(e,t,n){let{onRemoveAll:r}=n??{},i=(0,G.useMemo)(()=>{let t=e.get(f7);return t&&dci.has(t)?t:cci},[e]),a=e.get(p7),o=e.get(m7),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=$Mi[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(XMi),d=e.get(ZMi),f=e.get(QMi),p=(0,G.useMemo)(()=>oci.find(t=>t.entityType===e.get(d7)),[e]),m=(0,G.useMemo)(()=>yci(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`?XMi:t===`traceId`?ZMi:QMi;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 xci(n,e),eNi(n),n},{replace:!0})},[t]),_=g,v=(0,G.useCallback)((e,n)=>{if(l.current!==`custom`)return;let r=n===`from`?p7:m7;t(t=>{let n=new URLSearchParams(t);return e?n.set(r,e.toISOString()):n.delete(r),eNi(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(f7),n.delete(p7),n.delete(m7)):e===`custom`?n.set(f7,`custom`):(n.set(f7,e),n.delete(p7),n.delete(m7)),eNi(n),n},{replace:!0})},[t]),b=(0,G.useCallback)(()=>{t(e=>{let t=new URLSearchParams(e);t.delete(d7);for(let e of g7)t.delete(h7[e]);return t.delete(f7),t.delete(p7),t.delete(m7),eNi(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 nNi=20,rNi=1e4,iNi={field:`timestamp`,direction:`DESC`};function aNi(e,t,n){if(e?.pagination?.hasMore)return n+1}function oNi(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 sNi(e){return ZP(e.state.error,`logs`)||QP(e.state.error)?!1:rNi}var cNi=({filters:e,orderBy:t=iNi,queryOptions:n}={})=>{let r=Y(),{inView:i,setRef:a}=oP(),{hasNextPage:o,isFetchingNextPage:s,fetchNextPage:c,data:l,isLoading:u,isError:d,error:f}=ky({queryKey:[`logs`,e,t],queryFn:({pageParam:n})=>r.listLogsVNext({pagination:{page:n,perPage:nNi},filters:e,orderBy:t}),initialPageParam:0,getNextPageParam:aNi,select:oNi,retry:!1,refetchInterval:sNi,...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}},lNi=[sF(`/logs`)];function uNi(){let[e,t]=Hb(),n=kb(),r=tNi(e,t),i=i5(),{sort:a,onSortChange:o}=l7({searchParams:e,setSearchParams:t,allowedKeys:lci,defaultSort:uci}),s=(0,G.useMemo)(()=>({field:`timestamp`,direction:a?.direction===`asc`?`ASC`:`DESC`}),[a?.direction]),c=KMi(e,t),[l,u]=(0,G.useState)(),{data:d=[],isPending:f}=i$r(),{data:p=[],isPending:m}=_8({entityType:r.selectedEntityOption?.entityType,rootOnly:!0}),{data:h=[],isPending:g}=v8(),{data:_=[],isPending:v}=n$r(),y=(0,G.useMemo)(()=>vci({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}=cNi({filters:(0,G.useMemo)(()=>Sci({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}=YMi(b,r.featuredLogId,r.handleFeaturedChange,r.featuredTraceId),{data:j,isLoading:M}=b8({traceId:r.featuredTraceId??null,queryOptions:{enabled:!!r.featuredTraceId}}),N=(0,G.useCallback)(()=>r.applyFilterTokens(Cci(y,r.filterTokens)),[y,r]),P=(0,G.useCallback)(()=>r.handleFeaturedChange({logId:null}),[r]),F=(0,G.useCallback)(e=>r.handleFeaturedChange({traceId:e,spanId:null}),[r]),I=(0,G.useCallback)((e,t)=>r.handleFeaturedChange({traceId:e,spanId:t}),[r]),L=(0,G.useCallback)(()=>r.handleFeaturedChange({traceId:null,spanId:null}),[r]),R=(0,G.useCallback)(e=>r.handleFeaturedChange({spanId:e??null}),[r]),z=(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(jq,{children:(0,K.jsxs)(jq.Start,{children:[(0,K.jsx)(Ybn,{preset:r.datePreset,onPresetChange:r.handleDatePresetChange,dateFrom:r.selectedDateFrom,dateTo:r.selectedDateTo,onDateChange:r.handleDateChange,disabled:x,presets:[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`]}),(0,K.jsx)(wMi,{fields:y,tokens:r.filterTokens,onTokensChange:r.handleFilterTokensChange,disabled:x,onStartTextFilter:u,size:`sm`})]})}),(0,K.jsx)(RMi,{isLoading:x,filterFields:y,filterTokens:r.filterTokens,onFilterTokensChange:r.handleFilterTokensChange,onClear:N,onRemoveAll:r.handleRemoveAll,onSave:c.handleSave,onRemoveSaved:c.hasSavedFilters?c.handleRemoveSaved:void 0,autoFocusFilterFieldId:l})]});if(S)return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:lNi}),actionRow:z,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Logs`}),(0,K.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:(0,K.jsx)(DMi,{error:S,resource:`logs`,errorTitle:`Failed to load logs`})})]});let B=!!r.selectedEntityOption||r.filterTokens.length>0;return b.length===0&&!x&&!B?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:lNi}),actionRow:z,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Logs`}),(0,K.jsx)(UMi,{datePreset:r.datePreset,dateFrom:r.selectedDateFrom,dateTo:r.selectedDateTo})]}):(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:lNi}),actionRow:z,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Logs`}),(0,K.jsx)(LMi,{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)(EMi,{log:D??void 0,onClose:P,onTraceClick:F,onSpanClick:I,onPrevious:k,onNext:A}),(0,K.jsx)(mbi,{depth:2,traceId:D?r.featuredTraceId??void 0:void 0,spans:j?.spans,isLoadingSpans:M,selectedSpanId:r.featuredSpanId??null,onSpanSelect:R,onClose:L,withQueryTrace:i.enabled,withFeedback:i.enabled,onOpenScore:(e,t)=>n(kq(e,t))})]})}var dNi={name:e=>e.name||e.id};function fNi({server:e,rowProps:t}){let{paths:n,Link:r}=_l(),i=Y().options.baseUrl,a=e.transports?.includes(`sse`)??!0?`sse`:`mcp`,o=i?`${i}/api/mcp/${e.id}/${a}`:``,{data:s}=HIt({selectedServer:e}),c=Object.values(s||{}),l=c.length,u=c.filter(e=>e.toolType===`agent`).length,d=c.filter(e=>e.toolType===`workflow`).length,f=fY(e.name,50);return(0,K.jsxs)(Z.RowLink,{to:n.mcpServerLink(e.id),LinkComponent:r,...t,children:[(0,K.jsx)(Z.NameCell,{children:f}),(0,K.jsx)(Z.DescriptionCell,{children:o}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:u||``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:l||``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:d||``})]})}function pNi({mcpServers:e,isLoading:t,search:n=``,sort:r,onSortChange:i}){let a=(0,G.useMemo)(()=>{let t=n.toLowerCase();return yQ(e.filter(e=>e.name?.toLowerCase().includes(t)||e.id?.toLowerCase().includes(t)),r,dNi)},[e,n,r]),{containerRef:o,getRowProps:s}=_Q({count:a.length,global:!0});return t?(0,K.jsx)(NU,{columns:`auto 1fr auto auto auto`}):(0,K.jsxs)(Z,{columns:`auto 1fr auto auto auto`,scrollRef:o,children:[(0,K.jsxs)(Z.Top,{children:[i?(0,K.jsx)(Z.SortableTopCell,{sortKey:`name`,sort:r?.key===`name`?r.direction:void 0,onSortChange:i,children:`Name`}):(0,K.jsx)(Z.TopCell,{children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`URL`}),(0,K.jsx)(Z.TopCellSmart,{long:`Agents`,short:(0,K.jsx)(tF,{}),tooltip:`Agent tools`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Tools`,short:(0,K.jsx)(aF,{}),tooltip:`Tools`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Workflows`,short:(0,K.jsx)(rP,{}),tooltip:`Workflow tools`,className:`text-center`})]}),a.length===0&&n?(0,K.jsx)(Z.NoMatch,{message:`No MCP Servers match your search`}):null,a.map((e,t)=>(0,K.jsx)(fNi,{server:e,rowProps:s(t)},e.id))]})}var mNi=()=>(0,K.jsx)(RC,{titleSlot:`No MCP Servers yet`,descriptionSlot:(0,K.jsxs)(K.Fragment,{children:[`MCP servers are not configured yet. `,(0,K.jsx)(`br`,{}),`More information in the documentation.`]}),actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/docs/tools-mcp/mcp-overview`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(Br,{}),children:`MCP documentation`}),variant:`fill`}),F9=[sF(`/mcps`)],hNi=()=>{let{data:e=[],isLoading:t,error:n}=KP(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)();return n&&JP(n)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:F9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsx)(jU,{variant:`fill`})]}):n&&YP(n)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:F9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsx)(AU,{variant:`fill`,resource:`MCP servers`})]}):n?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:F9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load MCP servers`,descriptionSlot:n.message})]}):e.length===0&&!t?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:F9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsx)(mNi,{})]}):(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:F9}),actionRow:(0,K.jsx)(jq,{children:(0,K.jsx)(jq.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(zU,{onSearch:i,label:`Filter MCP servers`,placeholder:`Filter by name`})})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsx)(pNi,{mcpServers:e,isLoading:t,search:r,sort:a,onSortChange:(e,t)=>o({key:t,direction:e})})]})};function gNi(){let[e,t]=Hb();return{eventName:e.get(`event`)??void 0,close:()=>t(e=>{let t=new URLSearchParams(e);return t.delete(`event`),t},{replace:!0})}}var _Ni=e=>`?${new URLSearchParams({event:e}).toString()}`;function vNi(e,{enabled:t=!0}={}){let n=Y();return Ey({queryKey:[`mcp-server-events`,e],queryFn:()=>n.getMcpServerEvents(e),enabled:t})}function yNi(e,t){let n=Y();return Oy({mutationFn:r=>n.emitMcpServerEvent(e,t,r)})}function bNi(e){if(e instanceof Ym&&typeof e.body==`object`&&e.body!==null){let t=`error`in e.body?e.body.error:void 0;if(typeof t==`string`&&t)return t}return`The event request failed.`}var xNi={push:`blue`,poll:`neutral`,webhook:`purple`};function SNi({delivery:e}){return(0,K.jsx)(`span`,{className:`flex flex-wrap items-center gap-1`,children:e.map(e=>(0,K.jsx)(bw,{size:`xs`,variant:xNi[e],emphasis:`subtle`,children:e},e))})}var CNi=0,wNi=()=>`feed-${CNi++}`;function TNi(e,t){return[...t,...e].slice(0,200)}function ENi(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:TNi(e.items,[{kind:`gap`,key:wNi()}])};case`occurrences`:{let n=[...t.occurrences].reverse().map(e=>({kind:`occurrence`,key:wNi(),occurrence:e}));return{...e,items:TNi(e.items,n)}}case`warning`:return{...e,warning:t.message};case`error`:return{...e,status:`error`,error:t.message}}}var DNi={status:`idle`,items:[]};function ONi(e,t){let n=Y(),[r,i]=(0,G.useReducer)(ENi,DNi),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:bNi(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:bNi(e)})}};return{...r,start:l,stop:c,pollOnce:u}}function I9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function kNi(e){return e.map(e=>JSON.stringify(e)).join(` | `)}function ANi(e){return e.map(L9).join(` | `)}function L9(e){return I9(e)?Array.isArray(e.enum)?kNi(e.enum):`const`in e?JSON.stringify(e.const):Array.isArray(e.anyOf)?ANi(e.anyOf):Array.isArray(e.oneOf)?ANi(e.oneOf):Array.isArray(e.type)?e.type.join(` | `):e.type===`array`?`${L9(e.items)}[]`:NNi(e)?`Record<string, ${L9(e.additionalProperties)}>`:typeof e.type==`string`?e.type:`unknown`:`unknown`}function jNi(e,t,n,{defaultsAreOptional:r=!1}){let i=I9(t)?t:{},a=`default`in i;return{name:e,type:L9(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 MNi(e,t={}){if(!I9(e)||!I9(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])=>jNi(e,r,n,t))}function NNi(e){return I9(e)&&e.type===`object`&&!I9(e.properties)&&I9(e.additionalProperties)}function PNi(e){return I9(e)&&(e.type===`object`||I9(e.properties))}var FNi=[`type`,`properties`,`items`,`enum`,`const`,`anyOf`,`oneOf`,`allOf`,`$ref`];function INi(e){return!I9(e)||!FNi.some(t=>t in e)}function R9(e){return I9(e)?Kk(e):J({})}function LNi({inputSchema:e,onChange:t}){return INi(e)?(0,K.jsx)(T,{tone:`muted`,children:`This event takes no arguments.`}):(0,K.jsx)(nP,{schema:R9(e),onValuesChange:e=>t(e??{})})}function RNi({occurrence:e}){return(0,K.jsx)(dF,{children:(0,K.jsxs)(Hw,{children:[(0,K.jsxs)(Uw,{className:`flex w-full cursor-pointer items-center gap-2 px-3 py-2 text-left`,children:[(0,K.jsx)(y,{direction:`right`,className:`size-4 shrink-0`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,className:`min-w-0 flex-1 truncate`,children:e.eventId}),e.eventId.startsWith(`mastra-test-`)&&(0,K.jsx)(bw,{size:`xs`,variant:`amber`,emphasis:`subtle`,children:`test`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,tone:`muted`,className:`shrink-0`,children:e.timestamp})]}),(0,K.jsx)(Ww,{children:(0,K.jsx)(FT,{value:JSON.stringify(e.data,null,2),language:`json`,editable:!1,lineNumbers:!1,showCopyButton:!1,variant:`embedded`,"aria-label":`Event ${e.eventId} data`,className:`px-3 pb-3`})})]})})}var zNi=`Gap: events may have been skipped`;function BNi({items:e}){return e.length===0?(0,K.jsx)(RC,{iconSlot:(0,K.jsx)(Go,{}),titleSlot:`No events yet`,descriptionSlot:`Start listening or poll to see occurrences here.`}):(0,K.jsx)(`ol`,{"aria-label":`Occurrences`,className:`grid grid-cols-1 gap-2`,children:e.map(e=>(0,K.jsx)(`li`,{children:e.kind===`gap`?(0,K.jsx)(EA,{variant:`warning`,children:zNi}):(0,K.jsx)(RNi,{occurrence:e.occurrence})},e.key))})}var VNi={idle:`Not listening`,connecting:`Connecting…`,polling:`Polling…`,polled:`Polled`,stopped:`Stopped`,error:`Failed`};function HNi({status:e,canStream:t}){if(e===`live`)return(0,K.jsx)(bw,{variant:`green`,indicator:`pulse`,size:`sm`,children:`Listening`});let n=e===`idle`&&!t?`Not polled yet`:VNi[e];return(0,K.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(e===`connecting`||e===`polling`)&&(0,K.jsx)(Qc,{size:`sm`}),(0,K.jsx)(T,{as:`span`,tone:`muted`,children:n})]})}function UNi({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)(HNi,{status:e,canStream:t}),n&&(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1`,children:[(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:`Cursor`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,className:`min-w-0 truncate`,children:n}),(0,K.jsx)(jw,{tooltip:`Copy cursor`,content:n})]})]})}function WNi({serverId:e,event:t,onEmitted:n}){let{mutateAsync:r,isPending:i,isSuccess:a,error:o}=yNi(e,t.name);return(0,K.jsxs)(`section`,{"aria-label":`Send test event`,className:`grid grid-cols-1 gap-3`,children:[(0,K.jsx)(T,{as:`h3`,variant:`subheading`,children:`Send test event`}),(0,K.jsx)(nP,{schema:R9(t.payloadSchema),onSubmit:async e=>{try{await r(e??{}),n?.()}catch{}},isSubmitLoading:i,submitButtonLabel:`Send test event`}),a&&!o&&(0,K.jsx)(T,{tone:`muted`,children:`Test event sent.`}),o&&(0,K.jsx)(EA,{variant:`destructive`,children:bNi(o)})]})}function GNi({serverId:e,event:t,testEmit:n,canEmit:r}){let[i,a]=(0,G.useState)({}),o=ONi(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)(LNi,{inputSchema:t.inputSchema,onChange:a}),(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,K.jsx)(UNi,{status:o.status,canStream:s,cursor:o.cursor}),s&&c&&(0,K.jsx)(X,{onClick:o.stop,children:`Stop`}),s&&!c&&(0,K.jsx)(X,{variant:`primary`,onClick:()=>void o.start(i),children:`Start`}),!s&&(0,K.jsx)(X,{variant:`primary`,disabled:o.status===`polling`,onClick:()=>void o.pollOnce(i),children:`Poll once`})]}),o.error&&(0,K.jsx)(EA,{variant:`destructive`,children:o.error}),o.warning&&(0,K.jsx)(EA,{variant:`warning`,children:o.warning}),n&&t.emittable&&r&&(0,K.jsx)(WNi,{serverId:e,event:t,onEmitted:s?void 0:()=>void o.pollOnce(i)}),(0,K.jsx)(BNi,{items:o.items})]})}function KNi({description:e}){let t=U$({collapsedHeight:140});return(0,K.jsx)(H$,{state:t,expandLabel:`Read more`,children:(0,K.jsx)(xX,{children:e})})}function qNi({description:e,overview:t,playground:n,canRun:r}){return(0,K.jsx)(K.Fragment,{children:(0,K.jsxs)(CA,{defaultTab:`overview`,className:`grid flex-1 grid-rows-[auto_1fr] gap-4 overflow-visible`,children:[(0,K.jsxs)(SA,{variant:`pill`,size:`sm`,children:[(0,K.jsx)(wA,{value:`overview`,children:`Overview`}),(0,K.jsx)(wA,{value:`playground`,disabled:!r,disabledTooltip:`You don't have permission to execute tools.`,children:`Playground`})]}),(0,K.jsxs)(TA,{value:`overview`,flush:!0,className:`content-start gap-6`,children:[e&&(0,K.jsx)(dF,{className:`p-4`,children:(0,K.jsx)(KNi,{description:e})}),t]}),(0,K.jsx)(TA,{value:`playground`,flush:!0,keepMounted:!0,className:`h-full`,children:r&&n})]})})}function JNi(e){return(0,K.jsx)(OHr,{className:`min-h-control-md`,...e})}function YNi(){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 XNi({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 ZNi({field:e}){let t=!!e.description||e.defaultValue!==void 0;return(0,K.jsx)(v$,{label:(0,K.jsxs)(T,{as:`span`,variant:`body-sm`,font:`mono`,tone:`ink`,children:[e.name,e.required&&(0,K.jsx)(YNi,{})]}),description:t&&(0,K.jsx)(XNi,{field:e}),children:(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,tone:`muted`,children:e.type})})}function QNi({message:e}){return(0,K.jsx)(v$,{label:(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`muted`,children:e})})}function $Ni({schema:e,emptyMessage:t,defaultsAreOptional:n}){if(INi(e))return(0,K.jsx)(QNi,{message:t});if(!PNi(e)||NNi(e))return(0,K.jsx)(v$,{label:`Type`,children:(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,tone:`muted`,children:L9(e)})});let r=MNi(e,{defaultsAreOptional:n});return r.length===0?(0,K.jsx)(QNi,{message:t}):r.map(e=>(0,K.jsx)(ZNi,{field:e},e.name))}function z9({title:e,...t}){return(0,K.jsxs)(D3,{children:[(0,K.jsx)(JNi,{children:(0,K.jsx)(O3,{children:e})}),(0,K.jsx)(g$,{children:(0,K.jsx)($Ni,{...t})})]})}function ePi({serverId:e,eventName:t}){let{canExecute:n,canEdit:r}=KC(),{data:i,isLoading:a}=vNi(e),o=i?.events.find(e=>e.name===t);return a?(0,K.jsx)(m$.LoadingData,{}):!i||!o?(0,K.jsxs)(m$.NoData,{children:[`This server has no event "`,t,`".`]}):(0,K.jsx)(qNi,{description:o.description,overview:(0,K.jsxs)(`div`,{className:`grid grid-cols-1 gap-6`,children:[(0,K.jsx)(SNi,{delivery:o.delivery}),(0,K.jsx)(z9,{title:`Arguments`,schema:o.inputSchema,emptyMessage:`This event takes no arguments.`,defaultsAreOptional:!0}),(0,K.jsx)(z9,{title:`Payload`,schema:o.payloadSchema,emptyMessage:`No payload schema defined.`})]}),canRun:n(`mcp`),playground:(0,K.jsx)(GNi,{serverId:e,event:o,testEmit:i.testEmit,canEmit:r(`mcp`)})})}function tPi({serverId:e}){let{eventName:t,close:n}=gNi();return(0,K.jsxs)(m$,{open:t!==void 0,onClose:n,title:t??``,children:[(0,K.jsxs)(m$.Header,{children:[(0,K.jsxs)(m$.Heading,{children:[(0,K.jsx)(TC,{size:`sm`,className:`text-muted-foreground`,children:(0,K.jsx)(Go,{})}),(0,K.jsx)(`span`,{className:`truncate`,children:t})]}),(0,K.jsx)(m$.HeaderActions,{children:(0,K.jsx)(m$.CloseButton,{icon:`x`,tooltip:`Close event`,onClick:n})})]}),(0,K.jsx)(m$.Content,{className:`flex flex-col gap-4 px-3`,children:t&&(0,K.jsx)(ePi,{serverId:e,eventName:t},t)})]})}var nPi=new Set([`completed`,`failed`,`cancelled`]),rPi={working:`working`,input_required:`input required`,completed:`completed`,failed:`failed`,cancelled:`cancelled`},iPi=e=>nPi.has(e.status),aPi=2e3,B9=e=>[`mcp-server-tasks`,e],oPi=e=>!!e?.some(e=>!iPi(e));function sPi(e,t={}){let n=Y();return ky({queryKey:[...B9(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=>oPi(e.tasks))?aPi:!1})}function cPi(e,{enabled:t=!0}={}){let n=Y();return Ey({queryKey:[...B9(e),`surfaces`],queryFn:()=>n.getMcpServerTasks(e,{limit:1}),select:e=>e.surfaces,enabled:t})}function lPi(e,t){let n=Y();return Ey({queryKey:[...B9(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&&!iPi(e.state.data)?aPi:!1})}function uPi(e){let t=Y();return Oy({mutationFn:n=>t.findMcpServerTask(e,n)})}function dPi(e){let t=Y(),n=dy();return Oy({mutationFn:n=>t.cancelMcpServerTask(e,n),onSettled:()=>n.invalidateQueries({queryKey:B9(e)})})}function fPi(e){let t=Y(),n=dy();return Oy({mutationFn:({taskKey:n,inputResponses:r})=>t.answerMcpServerTaskInput(e,n,r),onSettled:()=>n.invalidateQueries({queryKey:B9(e)})})}function pPi(){let[e,t]=Hb();return{taskKey:e.get(`task`)??void 0,open:e=>t(t=>{let n=new URLSearchParams(t);return n.set(`task`,e),n},{replace:!0}),close:()=>t(e=>{let t=new URLSearchParams(e);return t.delete(`task`),t},{replace:!0})}}var mPi=(e,t=``)=>{let n=new URLSearchParams(t);return n.set(`task`,e),`?${n.toString()}`},hPi=e=>`${e.slice(0,8)}…`,gPi=new Set([`working`,`input_required`,`completed`,`failed`,`cancelled`]);function _Pi(){let[e,t]=Hb(),n=e.get(`status`),r=e.get(`surface`),i=e.get(`client`);return{filters:{...n&&gPi.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 vPi=e=>`${e.slice(0,8)}…`,yPi={working:{variant:`info`,indicator:`pulse`},input_required:{variant:`warning`,indicator:`dot`},completed:{variant:`success`},failed:{variant:`destructive`},cancelled:{variant:`neutral`}};function bPi({status:e}){let{variant:t,indicator:n}=yPi[e];return(0,K.jsx)(bw,{size:`sm`,variant:t,emphasis:`subtle`,indicator:n,children:rPi[e]})}function xPi({serverId:e}){let{taskKey:t,close:n}=pPi(),{data:r,isSuccess:i}=lPi(e,t);return(0,K.jsxs)(m$,{open:t!==void 0,onClose:n,title:r?.surface??`Task`,children:[(0,K.jsxs)(m$.Header,{children:[(0,K.jsxs)(m$.Heading,{children:[(0,K.jsx)(TC,{size:`sm`,className:`text-muted-foreground`,children:(0,K.jsx)(ma,{})}),(0,K.jsx)(`span`,{className:`truncate`,children:r?`${r.surface} task`:`Task`})]}),(0,K.jsx)(m$.HeaderActions,{children:(0,K.jsx)(m$.CloseButton,{icon:`x`,tooltip:`Close task`,onClick:n})})]}),(0,K.jsx)(m$.Content,{className:`flex flex-col gap-4 px-3`,children:r?(0,K.jsx)(SPi,{serverId:e,task:r},r.taskKey):i&&(0,K.jsx)(T,{tone:`muted`,children:`This task is no longer listed.`})})]})}function SPi({serverId:e,task:t}){let n=dPi(e),{canEdit:r,isLoading:i}=KC(),a=!i&&r(`mcp`),o=Object.entries(t.inputRequests??{});return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(y3,{children:[(0,K.jsx)(y3.Key,{children:`Status`}),(0,K.jsx)(y3.Value,{children:(0,K.jsx)(bPi,{status:t.status})}),t.statusMessage&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(y3.Key,{children:`Message`}),(0,K.jsx)(y3.Value,{children:t.statusMessage})]}),(0,K.jsx)(y3.Key,{children:`Created`}),(0,K.jsx)(y3.Value,{children:(0,K.jsx)(jA,{value:t.createdAt})}),(0,K.jsx)(y3.Key,{children:`Updated`}),(0,K.jsx)(y3.Value,{children:(0,K.jsx)(jA,{value:t.lastUpdatedAt})}),(0,K.jsx)(y3.Key,{children:`Expires`}),(0,K.jsx)(y3.Value,{children:t.expiresAt?(0,K.jsx)(jA,{value:t.expiresAt}):`never`}),(0,K.jsx)(y3.Key,{children:`Task key`}),(0,K.jsx)(y3.ValueWithCopyBtn,{copyValue:t.taskKey,copyTooltip:`Copy task key`,children:hPi(t.taskKey)}),t.clientLabel&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(y3.Key,{children:`Client`}),(0,K.jsx)(y3.ValueWithCopyBtn,{copyValue:t.clientLabel,copyTooltip:`Copy client`,children:t.clientLabel})]}),(0,K.jsx)(y3.Key,{children:`Client key`}),(0,K.jsx)(y3.ValueWithCopyBtn,{copyValue:t.principalKey,copyTooltip:`Copy client key`,children:hPi(t.principalKey)})]}),(0,K.jsx)(T,{tone:`muted`,variant:`caption`,children:`Keys are hashes: the task id and the client's credentials stay with the client that started the task.`}),o.map(([n,r])=>(0,K.jsx)(wPi,{serverId:e,taskKey:t.taskKey,inputKey:n,request:r,canAnswer:a},n)),!iPi(t)&&!i&&!a&&(0,K.jsx)(T,{tone:`muted`,variant:`caption`,children:`Cancelling or answering a task needs the mcp:write permission.`}),!iPi(t)&&a&&(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,K.jsx)(X,{variant:`destructive-ghost`,className:`self-start`,disabled:n.isPending,onClick:()=>n.mutate(t.taskKey),children:`Cancel task`}),n.error&&(0,K.jsx)(EA,{variant:`destructive`,children:EPi(n.error)})]}),t.result&&(0,K.jsx)(TPi,{label:`Result`,value:t.result}),t.error&&(0,K.jsx)(TPi,{label:`Error`,value:t.error})]})}var CPi=J({message:q().optional(),requestedSchema:Rp(q(),Ap())});function wPi({serverId:e,taskKey:t,inputKey:n,request:r,canAnswer:i}){let a=fPi(e),o=r.method===`elicitation/create`?CPi.safeParse(r.params):void 0,s=e=>a.mutate({taskKey:t,inputResponses:{[n]:e}});return(0,K.jsxs)(`section`,{"aria-label":`Input request ${n}`,className:`flex flex-col gap-3`,children:[(0,K.jsx)(T,{as:`h3`,variant:`subheading`,children:`Input requested`}),o?.success&&!i?(0,K.jsxs)(K.Fragment,{children:[o.data.message&&(0,K.jsx)(T,{children:o.data.message}),(0,K.jsx)(TPi,{label:`Request`,value:r})]}):o?.success?(0,K.jsxs)(K.Fragment,{children:[o.data.message&&(0,K.jsx)(T,{children:o.data.message}),(0,K.jsx)(nP,{schema:R9(o.data.requestedSchema),onSubmit:e=>s({action:`accept`,content:e??{}}),isSubmitLoading:a.isPending,submitButtonLabel:`Accept`,submitButtonVariant:`primary`,submitActions:(0,K.jsx)(X,{type:`button`,disabled:a.isPending,onClick:()=>s({action:`decline`}),children:`Decline`})})]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(T,{tone:`muted`,children:[`Studio can't answer a `,r.method,` request; the client that started the task has to.`]}),(0,K.jsx)(TPi,{label:`Request`,value:r})]}),a.error&&(0,K.jsx)(EA,{variant:`destructive`,children:EPi(a.error)})]})}function TPi({label:e,value:t}){return(0,K.jsxs)(`section`,{className:`flex flex-col gap-2`,children:[(0,K.jsx)(T,{as:`h3`,variant:`subheading`,children:e}),(0,K.jsx)(FT,{value:JSON.stringify(t,null,2),language:`json`,editable:!1,lineNumbers:!1,"aria-label":`Task ${e.toLowerCase()}`})]})}function EPi(e){let t=bNi(e);return t===`Task not found`?`The task is no longer waiting for this; the list has been refreshed.`:t}function DPi(e){if(!I9(e))return;if(I9(e.ui)&&typeof e.ui.resourceUri==`string`)return e.ui.resourceUri;let t=e[`ui/resourceUri`];return typeof t==`string`?t:void 0}function OPi(e){return I9(e)&&e.status===`suspended`}function kPi(e){return e<1e3?`${Math.round(e)} ms`:`${(e/1e3).toFixed(2)} s`}function APi(e){return e===void 0?`undefined`:JSON.stringify(e,null,2)}function jPi(e){return e.status===`error`?e.error:APi(e.output)}function MPi({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:NPi(n),durationMs:r}}}function NPi(e){return e instanceof Error?JSON.stringify({error:e.message},null,2):JSON.stringify({error:String(e)},null,2)}function PPi({zodInputSchema:e,isRunning:t,onRun:n,requestContextEntityType:r,requestContextEntityId:i}){let a=!ZN(e),[o,s]=(0,G.useState)({view:`form`,value:void 0}),c=(0,G.useRef)(void 0),[l,u]=(0,G.useState)([]);function d(t){if(t===o.view)return;if(u([]),o.view===`form`)return s({view:`json`,value:JSON.stringify(c.current??{},null,2)});let n=Kjt(o.value);if(!n.ok)return u([n.error]);let r=qjt(e,n.value);if(r)return u([r]);c.current=n.value,s({view:`form`,value:n.value})}function f(t){let r=Jjt(e,t);r.ok?n(r.value):u(r.errors)}let p={isSubmitLoading:t,submitButtonLabel:`Run`,submitButtonIcon:(0,K.jsx)(Ho,{}),submitButtonVariant:`primary`};return(0,K.jsxs)(D3,{children:[(0,K.jsx)(JNi,{action:(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(QLt,{entityType:r,entityId:i}),(0,K.jsx)(CA,{defaultTab:`form`,value:o.view,onValueChange:d,children:(0,K.jsxs)(SA,{size:`md`,children:[(0,K.jsxs)(wA,{value:`form`,disabled:t,children:[(0,K.jsx)(TC,{size:`sm`,children:(0,K.jsx)(Yo,{})}),`Form`]}),(0,K.jsxs)(wA,{value:`json`,disabled:t,children:[(0,K.jsx)(TC,{size:`sm`,children:(0,K.jsx)(Cn,{})}),`JSON`]})]})})]}),children:(0,K.jsx)(O3,{children:`Request`})}),(0,K.jsx)(g$,{children:(0,K.jsx)(`div`,{className:`p-4`,children:o.view===`json`?(0,K.jsxs)(`div`,{className:`grid gap-4`,children:[(0,K.jsxs)(fA,{invalid:l.length>0,children:[(0,K.jsx)(FT,{variant:`embedded`,language:`json`,value:o.value,onChange:e=>{s({view:`json`,value:e}),u([])},editable:!t,"aria-label":`Request JSON`}),l.length>0&&(0,K.jsx)(gA,{children:l.map(e=>(0,K.jsx)(`span`,{className:`block`,children:e},e))})]}),(0,K.jsx)(NA,{...p,onSubmit:()=>f(o.value)})]}):(0,K.jsx)(nP,{...p,schema:e,defaultValues:o.value,onValuesChange:e=>{c.current=e},onSubmit:n,className:`gap-0`,children:!a&&(0,K.jsx)(T,{variant:`body-sm`,tone:`muted`,className:`pb-4`,children:`This tool takes no input. Run it as is.`})})})})]})}function FPi({isRunning:e,lastRun:t}){return e?(0,K.jsx)(RC,{iconSlot:(0,K.jsx)(Qc,{}),titleSlot:`Running…`,descriptionSlot:`Waiting for the tool to respond.`}):t?t.status===`error`?(0,K.jsx)(Dw,{code:jPi(t),className:`overflow-x-auto p-4 text-caption whitespace-pre`}):(0,K.jsx)(FT,{value:jPi(t),language:`json`,editable:!1,lineNumbers:!1,showCopyButton:!1,variant:`embedded`,"aria-label":`Tool response`,className:`p-4`}):(0,K.jsx)(RC,{iconSlot:(0,K.jsx)(ys,{}),titleSlot:`No response yet`,descriptionSlot:`Run the tool to see its output here.`})}function IPi({run:e}){return(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[e.status===`success`?(0,K.jsx)(bw,{variant:`success`,emphasis:`subtle`,indicator:`dot`,children:`Success`}):(0,K.jsx)(bw,{variant:`destructive`,emphasis:`subtle`,indicator:`dot`,children:`Error`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,tone:`muted`,children:kPi(e.durationMs)}),(0,K.jsx)(jw,{content:jPi(e),copyMessage:`Response copied`,tooltip:`Copy response`,size:`icon-sm`})]})}function LPi({isRunning:e,lastRun:t}){return(0,K.jsxs)(D3,{className:`h-full`,children:[(0,K.jsx)(JNi,{action:!e&&t&&(0,K.jsx)(IPi,{run:t}),children:(0,K.jsx)(O3,{children:`Response`})}),(0,K.jsx)(g$,{className:m(`grid min-h-48 flex-1`,e||!t?`content-center`:`content-start`),children:(0,K.jsx)(FPi,{isRunning:e,lastRun:t})})]})}function RPi({zodInputSchema:e,execution:t,requestContextEntityType:n,requestContextEntityId:r}){let[i]=mw(n,r),[a,o]=(0,G.useState)(),s=async e=>{let n=performance.now();await t.execute(e,i).catch(()=>void 0),o(performance.now()-n)},c=t.status===`pending`;return(0,K.jsxs)(`div`,{className:`grid h-full grid-rows-[auto_1fr] gap-6`,children:[(0,K.jsx)(PPi,{zodInputSchema:e,isRunning:c,onRun:s,requestContextEntityType:n,requestContextEntityId:r}),(0,K.jsx)(LPi,{isRunning:c,lastRun:MPi(t,a)})]})}function zPi({serverId:e,tool:t}){let n=Uvr(e),{mutateAsync:r,status:i,data:a,error:o}=VIt({serverId:e,toolId:t.name}),{data:s}=RIt({serverId:e,appResourceUri:DPi(t._meta)}),c=R9(t.inputSchema),l={execute:(e,t)=>r({data:e,requestContext:t}),status:i,output:a,error:o};return(0,K.jsxs)(`div`,{className:`grid content-start gap-6`,children:[s&&(0,K.jsx)(RRr,{html:s,toolName:t.name,onToolCall:n}),OPi(a)&&(0,K.jsxs)(EA,{variant:`warning`,children:[`This tool asked for more input, which Studio cannot provide. The suspend payload below shows what it needs. Call it from an MCP client with an `,(0,K.jsx)(uZ,{children:`inputRequests`}),` handler to finish the request.`]}),(0,K.jsx)(RPi,{zodInputSchema:c,execution:l,requestContextEntityType:`mcp-tool`,requestContextEntityId:`${e}:${t.name}`})]})}var BPi=(0,G.createContext)(void 0),VPi=BPi.Provider;function HPi(){let e=(0,G.useContext)(BPi);if(e===void 0)throw Error(`useOpenToolId must be used inside ToolDrawer`);return e}function UPi({inputSchema:e,outputSchema:t,requestContextSchema:n,footer:r}){return(0,K.jsxs)(`div`,{className:`grid gap-6`,children:[(0,K.jsx)(z9,{title:`Input`,schema:e,emptyMessage:`This tool takes no input.`,defaultsAreOptional:!0}),(0,K.jsx)(z9,{title:`Output`,schema:t,emptyMessage:`No output schema defined.`}),n!==void 0&&(0,K.jsx)(z9,{title:`Request context`,schema:n,emptyMessage:`No request context fields.`,defaultsAreOptional:!0}),r]})}function WPi({serverId:e}){let t=HPi(),{canExecute:n}=KC(),{data:r,isLoading:i}=BIt({serverId:e,toolId:t});return i?(0,K.jsx)(m$.LoadingData,{}):r?(0,K.jsx)(qNi,{description:r.description,overview:(0,K.jsx)(UPi,{inputSchema:r.inputSchema}),canRun:n(`tools`),playground:(0,K.jsx)(zPi,{serverId:e,tool:r})}):(0,K.jsxs)(m$.NoData,{children:[`This server has no tool "`,t,`".`]})}var GPi=`auto 1fr auto`;function KPi({server:e}){let{data:t,isLoading:n,isError:r}=vNi(e.id),i=t?.events??[],{Link:a}=_l(),{containerRef:o,getRowProps:s}=_Q({count:i.length});return(0,K.jsxs)(`section`,{className:`flex flex-col gap-3`,children:[(0,K.jsx)(T,{as:`h2`,variant:`heading`,children:`Events`}),n&&(0,K.jsx)(NU,{columns:GPi}),r&&(0,K.jsx)(EA,{variant:`destructive`,children:`Could not load this server's events.`}),t&&(0,K.jsxs)(Z,{columns:GPi,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}${_Ni(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)(SNi,{delivery:t.delivery})})]},t.name))]})]})}var qPi=`minmax(0,1fr) auto auto auto auto auto auto auto`,JPi={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.`},YPi=[{id:`is`,label:`is`}],XPi=Object.entries(rPi).map(([e,t])=>({value:e,label:t})),ZPi=e=>e.stopPropagation(),QPi=e=>e.clientLabel??vPi(e.principalKey),$Pi=e=>[`status`,`surface`,`client`].flatMap(t=>{let n=e[t];return n?[{id:t,fieldId:t,operatorId:`is`,value:n}]:[]}),eFi=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 tFi({server:e}){let{filters:t,setFilters:n}=_Pi(),{data:r,isLoading:i,isError:a,hasNextPage:o,fetchNextPage:s,isFetchingNextPage:c}=sPi(e.id,t),{data:l=[]}=cPi(e.id),u=(0,G.useMemo)(()=>r?.pages.flatMap(e=>e.tasks)??[],[r]),d=r?.pages[0]?.unavailable,{containerRef:f,getRowProps:p}=_Q({count:u.length}),m=$Pi(t).length>0,h=(0,G.useMemo)(()=>{let e=new Map(u.map(e=>[e.principalKey,QPi(e)]));return t.client&&!e.has(t.client)&&e.set(t.client,vPi(t.client)),[...e]},[u,t.client]),g=(0,G.useMemo)(()=>[{id:`status`,label:`Status`,icon:Wn,color:_F(`orange`),operators:[`is`],strict:!0,suggestions:XPi},{id:`surface`,label:`Surface`,icon:Bc,color:_F(`blue`),operators:[`is`],strict:!0,suggestions:l.map(e=>({value:e.name}))},{id:`client`,label:`Client`,icon:Mc,color:_F(`purple`),operators:[`is`],suggestions:h.map(([e,t])=>({value:e,label:t}))}],[l,h]);return(0,K.jsxs)(`section`,{"aria-label":`Tasks`,className:`flex flex-col gap-3`,children:[(0,K.jsx)(T,{as:`h2`,variant:`heading`,children:`Tasks`}),a&&(0,K.jsx)(EA,{variant:`destructive`,children:`Could not load this server's tasks.`}),d&&(0,K.jsx)(EA,{variant:`info`,children:JPi[d]}),!d&&(0,K.jsxs)(jq,{children:[(0,K.jsx)(jq.Start,{children:(0,K.jsxs)(p5,{fields:g,operators:YPi,value:$Pi(t),onValueChange:e=>n(eFi(e)),createItemId:e=>e,"aria-label":`Task filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(p5.Chips,{}),(0,K.jsx)(p5.Input,{placeholder:`Filter tasks`})]})}),(0,K.jsx)(jq.End,{children:(0,K.jsx)(rFi,{serverId:e.id})})]}),i&&(0,K.jsx)(NU,{columns:qPi}),r&&!d&&(0,K.jsxs)(Z,{columns:qPi,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)(nFi,{serverId:e.id,task:r,rowProps:p(i),onFilterClient:()=>n({...t,client:r.principalKey})},r.taskKey))]}),o&&(0,K.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,K.jsx)(X,{variant:`default`,size:`sm`,onClick:()=>s(),disabled:c,children:c?`Loading…`:`Load more`}),(0,K.jsxs)(T,{variant:`caption`,tone:`muted`,children:[`Showing the `,u.length,` most recent `,m?`matching `:``,`tasks.`]})]})]})}function nFi({serverId:e,task:t,rowProps:n,onFilterClient:r}){let{Link:i}=_l(),[a]=Hb(),o=(0,G.useRef)(null);return(0,K.jsxs)(Z.RowWrapper,{...n,onSelectRow:()=>o.current?.click(),children:[(0,K.jsxs)(Z.RowLink,{ref:o,colEnd:-2,to:`/mcps/${e}${mPi(t.taskKey,a)}`,LinkComponent:i,tabIndex:-1,onClick:ZPi,"aria-label":`${t.surface} task ${hPi(t.taskKey)}`,children:[(0,K.jsx)(Z.NameCell,{children:t.surface}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(bPi,{status:t.status})}),(0,K.jsx)(Z.CreatedCell,{timestamp:t.createdAt,preset:`day-time-seconds`}),(0,K.jsx)(Z.Cell,{className:`text-muted-foreground`,children:(0,K.jsx)(jA,{value:t.lastUpdatedAt})}),(0,K.jsx)(Z.Cell,{className:`text-muted-foreground`,children:t.expiresAt?(0,K.jsx)(jA,{value:t.expiresAt}):`never`}),(0,K.jsx)(Z.TextCell,{children:Object.keys(t.inputRequests??{}).length||`—`}),(0,K.jsx)(Z.TextCell,{font:`mono`,className:`text-muted-foreground`,children:hPi(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 ${QPi(t)}`,onClick:e=>{e.stopPropagation(),r()},children:QPi(t)})})]})}function rFi({serverId:e}){let[t,n]=(0,G.useState)(``),r=uPi(e),{open:i}=pPi();return(0,K.jsxs)(`form`,{onSubmit:e=>{e.preventDefault();let a=t.trim();a&&r.mutate(a,{onSuccess:({task:e})=>{n(``),i(e.taskKey)}})},className:`flex items-center gap-2`,"aria-label":`Find a task by MCP task id`,children:[(0,K.jsx)(ZM,{size:`sm`,value:t,onChange:e=>{n(e.target.value),r.reset()},placeholder:`MCP task id`,"aria-label":`MCP task id`,"aria-invalid":r.isError||void 0,className:`w-56 font-mono`}),(0,K.jsx)(X,{type:`submit`,size:`sm`,variant:`default`,disabled:!t.trim()||r.isPending,children:`Find`}),r.isError&&(0,K.jsx)(T,{variant:`caption`,role:`status`,className:`text-destructive-foreground`,children:`No task with that id.`})]})}var iFi={agent:tF,workflow:rP,tool:aF},aFi=`auto minmax(0, 1fr) auto`,oFi=`auto minmax(0, 1fr) auto auto`,sFi={tool:`Tool`,agent:`Agent`,workflow:`Workflow`};function cFi(e){return e in iFi}function lFi({type:e}){let t=cFi(e)?e:`tool`,n=iFi[t],r=sFi[t];return(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{asChild:!0,children:(0,K.jsx)(`span`,{"aria-label":t,className:`inline-flex text-muted-foreground [&>svg]:size-4`,children:(0,K.jsx)(n,{})})}),(0,K.jsx)(CC,{children:r})]})}var uFi=J({ui:J({resourceUri:q().optional()}).optional(),"ui/resourceUri":q().optional()});function dFi(e){let t=uFi.safeParse(e);return t.success?!!(t.data.ui?.resourceUri?.startsWith(`ui://`)||t.data[`ui/resourceUri`]?.startsWith(`ui://`)):!1}function fFi({surface:e}){return e?(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{asChild:!0,children:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,K.jsx)(bw,{size:`xs`,variant:e.mode===`always`?`info`:`neutral`,emphasis:`subtle`,children:e.mode}),e.required&&(0,K.jsx)(bw,{size:`xs`,variant:`warning`,emphasis:`subtle`,children:`required`}),e.recover&&(0,K.jsx)(bw,{size:`xs`,variant:`neutral`,emphasis:`subtle`,children:`recover`})]})}),(0,K.jsxs)(CC,{children:[e.mode===`always`?`Always runs as a task`:`Runs as a task when the client asks for one`,e.required?`; clients without task support are refused`:``,e.recover?`; resumed after a server restart`:``]})]}):null}function pFi({server:e}){let[t,n]=(0,G.useState)(``),{data:r={},isLoading:i}=HIt({selectedServer:e}),{Link:a,paths:o}=_l(),{data:s}=cPi(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?oFi:aFi,d=(0,G.useMemo)(()=>{let e=t.toLowerCase();return Object.values(r).filter(t=>t.name.toLowerCase().includes(e)||t.description?.toLowerCase().includes(e))},[r,t]),{containerRef:f,getRowProps:p}=_Q({count:d.length});return(0,K.jsxs)(`section`,{className:`flex flex-col gap-3`,children:[(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,K.jsx)(T,{as:`h2`,variant:`heading`,children:`Available tools`}),(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(zU,{onSearch:n,label:`Filter tools`,placeholder:`Filter by name`,shortcutDisabled:!0})})]}),i?(0,K.jsx)(NU,{columns:u}):(0,K.jsxs)(Z,{columns:u,fit:`container`,scrollRef:f,children:[(0,K.jsxs)(Z.Top,{children:[(0,K.jsx)(Z.TopCell,{children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`Description`}),(0,K.jsx)(Z.TopCell,{className:`justify-center text-center`,children:`Type`}),l&&(0,K.jsx)(Z.TopCell,{children:`Task`})]}),d.length===0&&t?(0,K.jsx)(Z.NoMatch,{message:`No tools match your search`}):null,d.map((t,n)=>(0,K.jsxs)(Z.RowLink,{to:o.mcpServerToolLink(e.id,t.name),LinkComponent:a,...p(n),children:[(0,K.jsx)(Z.NameCell,{children:(0,K.jsxs)(`span`,{className:`flex items-center gap-2`,children:[t.name,dFi(t._meta)&&(0,K.jsx)(bw,{size:`xs`,children:`App`})]})}),(0,K.jsx)(Z.DescriptionCell,{children:t.description}),(0,K.jsx)(Z.TextCell,{className:`justify-center text-center`,children:(0,K.jsx)(lFi,{type:t.toolType??`tool`})}),l&&(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(fFi,{surface:c.get(t.name)})})]},t.name))]})]})}var mFi=({isLoading:e,server:t})=>{let[{sseUrl:n,httpStreamUrl:r},i]=(0,G.useState)({sseUrl:``,httpStreamUrl:``});if((0,G.useEffect)(()=>{if(!t)return;let e=window.MASTRA_SERVER_HOST,n=window.MASTRA_SERVER_PORT,r=null;e&&n&&(r=`http://${e}:${n}`);let a=r||`http://localhost:4111`,o=`${a}/api/mcp/${t.id}/sse`,s=`${a}/api/mcp/${t.id}/mcp`;i({sseUrl:o,httpStreamUrl:s})},[t]),e)return null;if(!t)return(0,K.jsx)(T,{as:`h1`,variant:`heading`,tone:`muted`,className:`py-20 text-center`,children:`Server not found`});let a=t.transports?.includes(`sse`)??!0,o=`npx -y mcp-remote ${a?n:r}`,s=[{value:`http`,label:`HTTP`,description:`Use for stateless HTTP transport with streamable responses.`,content:r,tooltip:`Copy HTTP Stream URL`},...a?[{value:`sse`,label:`SSE`,description:`Use for real-time communication via SSE.`,content:n,tooltip:`Copy SSE URL`}]:[],{value:`cli`,label:`CLI`,description:`Use for local command-line access via npx and mcp-remote.`,content:o,tooltip:`Copy command line config`}];return(0,K.jsxs)(`div`,{className:`flex flex-col gap-6 pt-4`,children:[(0,K.jsx)(dF,{children:(0,K.jsxs)(CA,{defaultTab:`http`,children:[(0,K.jsxs)(fF,{className:`flex-row items-center justify-between gap-3 space-y-0 border-b border-border`,children:[(0,K.jsx)(pF,{className:`shrink-0`,children:`Connect`}),(0,K.jsx)(`div`,{className:`min-w-0`,children:(0,K.jsx)(SA,{variant:`pill-ghost`,size:`sm`,children:s.map(e=>(0,K.jsx)(wA,{value:e.value,children:e.label},e.value))})})]}),s.map(e=>(0,K.jsx)(TA,{value:e.value,flush:!0,children:(0,K.jsxs)(hF,{className:`flex flex-col gap-3`,children:[(0,K.jsx)(T,{tone:`muted`,children:e.description}),(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-3 rounded-lg bg-muted py-2 pr-2 pl-3`,children:[(0,K.jsx)(T,{as:`span`,font:`mono`,className:`min-w-0 break-all`,children:e.content}),(0,K.jsx)(jw,{tooltip:e.tooltip,content:e.content})]})]})},e.value))]})}),(0,K.jsx)(pFi,{server:t}),t.tasks_capability&&(0,K.jsx)(tFi,{server:t}),t.events_capability&&(0,K.jsx)(KPi,{server:t})]})};function hFi(){let[e,t]=Hb();return{toolId:e.get(`tool`)??void 0,close:()=>t(e=>{let t=new URLSearchParams(e);return t.delete(`tool`),t},{replace:!0})}}function gFi({children:e}){let{toolId:t,close:n}=hFi();return(0,K.jsxs)(m$,{open:t!==void 0,onClose:n,title:t??``,children:[(0,K.jsxs)(m$.Header,{children:[(0,K.jsxs)(m$.Heading,{children:[(0,K.jsx)(TC,{size:`sm`,className:`text-muted-foreground`,children:(0,K.jsx)(aF,{})}),(0,K.jsx)(`span`,{className:`truncate`,children:t})]}),(0,K.jsx)(m$.HeaderActions,{children:(0,K.jsx)(m$.CloseButton,{icon:`x`,tooltip:`Close tool`,onClick:n})})]}),(0,K.jsx)(m$.Content,{className:`flex flex-col gap-4 px-3`,children:t&&(0,K.jsx)(VPi,{value:t,children:e},t)})]})}var _Fi=()=>{let{serverId:e}=Ab(),t=[sF(`/mcps`),HLt],{data:n=[],isLoading:r}=KP(),i=n.find(t=>t.id===e),a=i?.transports?.includes(`sse`)??!0,o=r||i?(0,K.jsxs)(Nq,{children:[(0,K.jsx)(Nq.Title,{isLoading:r,children:i?.name}),i&&(0,K.jsx)(Nq.Meta,{beside:!0,children:(0,K.jsxs)(bw,{size:`sm`,children:[`v`,i.version_detail.version]})}),i&&(0,K.jsx)(Nq.Description,{children:a?`This MCP server can be accessed through multiple transport methods. Choose the one that best fits your use case.`:`This MCP server speaks Streamable HTTP only (protocol 2026-07-28).`})]}):void 0;return(0,K.jsxs)(uw,{variant:`narrow`,breadcrumbs:(0,K.jsx)(EP,{crumbs:t}),header:o,children:[(0,K.jsx)(mFi,{isLoading:r,server:i}),e&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(gFi,{children:(0,K.jsx)(WPi,{serverId:e})}),(0,K.jsx)(tPi,{serverId:e}),(0,K.jsx)(xPi,{serverId:e})]})]})};function vFi(){let{data:e,isLoading:t}=r5();if(t)return`loading`;let n=e?.capabilities;return n?.traceAggregate===!0&&n.spanAggregate===!0?`unified`:`legacy`}var V9=[sF(`/metrics`)],yFi=e=>e.fieldId===N5r;function bFi({fields:e}){let{filterTokens:t,setFilterTokens:n}=Q7(),r=[f5,...Dxi(t)];return(0,K.jsxs)(p5,{fields:[P5r,...e],operators:bxi,value:r,onValueChange:e=>n(Oxi(e.filter(e=>!yFi(e)))),createItemId:e=>e,"aria-label":`Metrics filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(p5.Chips,{renderChip:e=>yFi(e)?(0,K.jsx)(dSi,{}):(0,K.jsx)(p5.Chip,{item:e})}),(0,K.jsx)(p5.Input,{placeholder:`Filter metrics`})]})}function xFi({children:e,filterFields:t}){return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:V9}),actionRow:(0,K.jsx)(jq,{children:(0,K.jsx)(jq.Start,{children:(0,K.jsx)(bFi,{fields:t})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),e]})}function SFi({error:e}){return JP(e)?(0,K.jsx)(jU,{}):YP(e)?(0,K.jsx)(AU,{resource:`metrics`}):(0,K.jsx)(RC,{tone:`error`,titleSlot:`Failed to load storage capabilities`,descriptionSlot:e.message})}var CFi=Exi({availableTags:[],availableEntityNames:[],availableServiceNames:[],availableEnvironments:[]});function wFi({children:e}){let{supportsMetrics:t,isLoading:n,error:r}=x7();return n?(0,K.jsx)(xFi,{filterFields:CFi,children:(0,K.jsxs)(`div`,{className:`flex h-full items-center justify-center gap-2`,children:[(0,K.jsx)(Qc,{"aria-label":`Loading storage capabilities`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:`Loading storage capabilities`})]})}):r?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:V9}),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)(SFi,{error:r})})]}):t?e:(0,K.jsx)(xFi,{filterFields:CFi,children:(0,K.jsx)(RC,{titleSlot:`Metrics are not available with your current storage`,descriptionSlot:`Metrics require ClickHouse, DuckDB, Postgres v-next, Spanner, or in-memory storage for observability. Other relational databases (LibSQL, MSSQL) and document stores (MongoDB) do not support metrics collection. To enable metrics on an existing project, switch the observability storage in the Mastra configuration.`,actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/docs/observability/metrics/overview`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(Br,{}),children:`Metrics documentation`}),variant:`fill`})})}function TFi(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 EFi(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=TFi(i);s&&e.set(t,s)}function H9(e,t,n){typeof n==`string`&&n.length>0&&e.set(t,n)}function DFi(e,t,n){if(Array.isArray(n)&&n.length!==0)for(let r of n)r&&e.append(t,r)}function OFi({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 kFi({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:i=`/traces`}){let a=new URLSearchParams;a.set(T8,`branches`),EFi(a,E8,D8,O8,e,t,r.window);let o=r.rootEntityType??n.rootEntityType;o&&a.set(S1r,o),r.status&&a.set(C1r,r.status),H9(a,k8.entityName,r.entityName??n.entityName),H9(a,k8.threadId,r.threadId??n.threadId),H9(a,k8.resourceId,r.resourceId??n.resourceId),H9(a,k8.runId,n.runId),H9(a,k8.sessionId,r.sessionId??n.sessionId),H9(a,k8.requestId,n.requestId),H9(a,k8.userId,r.userId??n.userId),H9(a,k8.organizationId,n.organizationId),H9(a,k8.experimentId,n.experimentId),H9(a,k8.serviceName,n.serviceName),H9(a,k8.environment,r.environment??n.environment),DFi(a,k8.tags,n.tags),r.span&&a.append(z8,JSON.stringify(OFi(r.span)));let s=a.toString();return s?`${i}?${s}`:i}function AFi({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:i=`/logs`}){let a=new URLSearchParams;EFi(a,f7,p7,m7,e,t,r.window);let o=r.rootEntityType??n.rootEntityType;o&&a.set(d7,o),H9(a,h7.entityName,r.entityName??n.entityName),H9(a,h7.threadId,r.threadId??n.threadId),H9(a,h7.resourceId,r.resourceId??n.resourceId),H9(a,h7.runId,n.runId),H9(a,h7.sessionId,n.sessionId),H9(a,h7.requestId,n.requestId),H9(a,h7.userId,n.userId),H9(a,h7.organizationId,n.organizationId),H9(a,h7.experimentId,n.experimentId),H9(a,h7.serviceName,n.serviceName),H9(a,h7.environment,n.environment),DFi(a,h7.tags,n.tags),r.status===`error`&&a.append(h7.level,`error`);let s=a.toString();return s?`${i}?${s}`:i}function jFi(){let{datePreset:e,customRange:t,dimensionalFilter:n}=Q7(),r=kb(),i={preset:e,customRange:t,dashboardFilter:n};return{openTraces:(e={})=>{r(kFi({...i,scope:e}))},openLogs:(e={})=>{r(AFi({...i,scope:e}))}}}var MFi=`period`,NFi=`dateFrom`,PFi=`dateTo`;function FFi(){let[e,t]=Hb(),n=e.get(MFi),r=eSi(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(NFi)),i=t(e.get(PFi));if(n||i)return{from:n,to:i}},[r,e.toString()]),a=(0,G.useMemo)(()=>kxi(e),[e.toString()]),o=(0,G.useCallback)(e=>{t(t=>{let n=new URLSearchParams(t);return e===`24h`?n.delete(MFi):n.set(MFi,e),e!==`custom`&&(n.delete(NFi),n.delete(PFi)),n},{replace:!0})},[t]),s=(0,G.useCallback)(e=>{t(t=>{let n=new URLSearchParams(t);return e?.from?n.set(NFi,e.from.toISOString()):n.delete(NFi),e?.to?n.set(PFi,e.to.toISOString()):n.delete(PFi),n},{replace:!0})},[t]),c=(0,G.useCallback)(e=>{t(t=>{let n=new URLSearchParams(t);return jxi(n,e),gxi(n),n},{replace:!0})},[t]),l=(0,G.useRef)(!1);return(0,G.useEffect)(()=>{if(l.current||(l.current=!0,vxi(e)))return;let n=_xi();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)(aSi,{preset:r,filterTokens:a,onPresetChange:o,onFilterTokensChange:c,customRange:i,onCustomRangeChange:s,children:(0,K.jsx)(wFi,{children:(0,K.jsx)(IFi,{})})})}function IFi(){let{error:e}=Jxi(s9()),{isInMemory:t}=x7(),{data:n}=i$r(),{data:r}=_8(),{data:i}=n$r(),{data:a}=v8(),o=Exi({availableTags:n??[],availableEntityNames:r??[],availableServiceNames:i??[],availableEnvironments:a??[]});return e&&JP(e)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:V9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),(0,K.jsx)(jU,{variant:`fill`})]}):e&&YP(e)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:V9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),(0,K.jsx)(AU,{variant:`fill`,resource:`metrics`})]}):e?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:V9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load metrics`,descriptionSlot:e.message})]}):(0,K.jsx)(xFi,{filterFields:o,children:(0,K.jsxs)(`div`,{className:`grid content-start gap-4`,children:[t&&(0,K.jsx)(EA,{variant:`info`,title:`Metrics are not persisted`,children:(0,K.jsx)(EA.Message,{children:`This project uses in-memory storage for observability. Metrics will be lost on every server restart. For persistent metrics, switch the observability storage to ClickHouse, DuckDB, Postgres v-next, or Spanner.`})}),(0,K.jsx)(LFi,{})]})})}function LFi(){let{openTraces:e,openLogs:t}=jFi(),n=kh.AGENT,r=vFi(),i=(0,K.jsx)(sCi,{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)(gCi,{onViewTraces:t=>e({rootEntityType:t}),onTimeRangeClick:t=>e({window:t})}),o=(0,K.jsx)(owi,{onViewTraces:()=>e(),onAgentClick:t=>e({rootEntityType:n,entityName:t}),onModelClick:t=>e({model:t}),onThreadClick:t=>e({threadId:t})}),s=(0,K.jsx)(tCi,{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)(r9,{columns:2,children:[(0,K.jsx)(r9.Item,{children:s}),(0,K.jsx)(r9.Item,{children:i}),(0,K.jsx)(r9.Item,{children:a}),(0,K.jsx)(r9.Item,{children:(0,K.jsx)(Pwi,{onTimeRangeClick:e})})]}),(0,K.jsx)(FEi,{onRowClick:e})]}):(0,K.jsxs)(`div`,{className:`grid content-start gap-4 pb-6`,children:[s,(0,K.jsxs)(r9,{columns:2,children:[(0,K.jsx)(r9.Item,{children:i}),(0,K.jsx)(r9.Item,{children:a})]}),(0,K.jsxs)(r9,{columns:2,children:[(0,K.jsx)(r9.Item,{children:(0,K.jsx)(QCi,{onViewTraces:t=>e({rootEntityType:t}),onViewErrors:e=>t({rootEntityType:e,status:`error`}),onEntityClick:(t,n)=>e({rootEntityType:t,entityName:n})})}),(0,K.jsx)(r9.Item,{children:o})]}),(0,K.jsx)(_wi,{})]})}function RFi(){let{isCmsAvailable:e}=q3(),{paths:t}=_l();return e?(0,K.jsx)(Arr,{href:t.cmsPromptBlockCreateLink(),tooltip:`Create a prompt`,children:`New prompt`}):null}var U9=[sF(`/prompts`)],zFi=50,BFi=[`updatedAt`];function VFi(){let[e,t]=(0,G.useState)(``),[n,r]=(0,G.useState)(0),[i,a]=Hb(),{sort:o,onSortChange:s}=l7({searchParams:i,setSearchParams:a,allowedKeys:BFi}),{data:c,isLoading:l,error:u,isPlaceholderData:d}=IJr({page:n,perPage:zFi,orderBy:(0,G.useMemo)(()=>o?{field:o.key,direction:o.direction===`asc`?`ASC`:`DESC`}:void 0,[o])}),f=c?.promptBlocks??[],p=c?.hasMore??!1,m=(0,G.useCallback)(()=>{d||r(e=>e+1)},[d]),h=(0,G.useCallback)(()=>{d||r(e=>Math.max(0,e-1))},[d]),g=(0,G.useCallback)(e=>{t(e),r(0)},[]),_=(0,G.useCallback)((e,t)=>{s(e,t),r(0)},[s]);return u&&JP(u)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:U9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(jU,{variant:`fill`})]}):u&&YP(u)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:U9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(AU,{variant:`fill`,resource:`prompt blocks`})]}):u?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:U9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load prompt blocks`,descriptionSlot:u.message})]}):f.length===0&&!l&&n===0?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:U9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(CYr,{})]}):(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:U9}),headerActions:(0,K.jsx)(RFi,{}),actionRow:(0,K.jsx)(jq,{children:(0,K.jsx)(jq.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(zU,{onSearch:g,label:`Filter prompts`,placeholder:`Filter by name or description`})})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(SYr,{promptBlocks:f,isLoading:l,search:e,currentPage:n,hasMore:p,onNextPage:m,onPrevPage:h,updatedSort:o?.direction,onSortChange:_})]})}var HFi=[sF(`/resources`)],UFi=[{title:`Mastra APIs`,description:`Explore and test the available REST API endpoints with the interactive Swagger UI.`,icon:Pee,href:`/swagger-ui`,external:!1},{title:`Documentation`,description:`Read the official Mastra documentation for guides, references, and tutorials.`,icon:pn,href:`https://mastra.ai/en/docs`,external:!0},{title:`Github`,description:`Browse the source code, report issues, and contribute to the Mastra project.`,icon:Br,href:`https://github.com/mastra-ai/mastra`,external:!0},{title:`Community`,description:`Join the Mastra Discord community for help, discussion, and collaboration.`,icon:$a,href:`https://discord.gg/mastra-ai`,external:!0},{title:`Share with your team`,description:`Running Mastra Studio locally? Deploy to the cloud so your team can collaborate.`,icon:dr,href:`https://mastra.ai/cloud`,external:!0},{title:`Talk to our Sales team`,description:`Get a custom demo, discuss on-prem deployments, and how we can help you accelerate getting agents into production.`,icon:An,href:`https://mastra.ai/contact?ref=studio`,external:!0}];function WFi(){return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:HFi}),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:UFi.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:m(`h-5 w-5 text-muted-foreground group-hover:text-info-indicator`,f)}),(0,K.jsx)(T,{as:`span`,variant:`subheading`,tone:`ink`,children:e.title}),e.external&&(0,K.jsx)(Br,{className:`ml-auto h-3.5 w-3.5 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100`})]}),(0,K.jsx)(T,{variant:`caption`,tone:`muted`,children:e.description})]},e.href))})})]})}function GFi(){let{isCmsAvailable:e}=q3(),{paths:t}=_l();return e?(0,K.jsx)(Arr,{href:t.cmsScorersCreateLink(),tooltip:`Create a scorer`,children:`New scorer`}):null}var W9=[sF(`/scorers`)];function KFi(){let{data:e={},isLoading:t,error:n}=eF(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)(`all`),[s,c]=(0,G.useState)();if(n&&JP(n))return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Scorers`}),(0,K.jsx)(jU,{variant:`fill`})]});if(n&&YP(n))return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Scorers`}),(0,K.jsx)(AU,{variant:`fill`,resource:`scorers`})]});if(n)return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Scorers`}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load scorers`,descriptionSlot:n.message})]});if(Object.keys(e).length===0&&!t)return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:W9}),headerActions:(0,K.jsx)(GFi,{}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Scorers`}),(0,K.jsx)(JVr,{})]});let l=a!==`all`||r!==``;return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:W9}),headerActions:(0,K.jsx)(GFi,{}),actionRow:(0,K.jsx)(XVr,{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)(qVr,{scorers:e,isLoading:t,search:r,sourceFilter:a,sort:s,onSortChange:(e,t)=>c({key:t,direction:e})})]})}var qFi=[`input`,`entity`],JFi={input:`Input`,entity:`Entity`};function YFi(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 XFi(){let[e,t]=(0,G.useState)(new Set),n=(0,G.useMemo)(()=>new Set(qFi.filter(t=>!e.has(t))),[e]);return{visibleColumns:n,columns:(0,G.useMemo)(()=>YFi(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 ZFi({visibleColumns:e,toggleColumn:t}){return(0,K.jsxs)(mD,{children:[(0,K.jsx)(mD.Trigger,{asChild:!0,children:(0,K.jsx)(X,{icon:(0,K.jsx)(vr,{}),children:`Columns`})}),(0,K.jsxs)(mD.Content,{align:`end`,children:[(0,K.jsx)(mD.Label,{children:`Toggle columns`}),qFi.map(n=>(0,K.jsx)(mD.CheckboxItem,{checked:e.has(n),onClick:()=>t(n),children:JFi[n]},n))]})]})}var QFi=[sF(`/scorers`),BLt],$Fi=[`date`,`score`];function eIi(){let{scorerId:e}=Ab(),[t,n]=Hb(),r=t.get(`scoreId`)??void 0,[i,a]=(0,G.useState)(r),[o,s]=(0,G.useState)(!1),c=kb(),[l,u]=(0,G.useState)({value:`all`,label:`All Entities`,type:`ALL`}),{scorer:d,error:f}=uLt(e),p=XFi(),{data:m={},isLoading:h,error:g}=PP(),{isLoading:_,error:v}=sP({}),{sort:y,onSortChange:b}=l7({searchParams:t,setSearchParams:n,allowedKeys:$Fi}),{data:x=[],isLoading:S,error:C,isFetchingNextPage:w,hasNextPage:T,setEndOfListElement:E}=lLt({scorerId:e,entityId:l?.value===`all`?void 0:l?.value,entityType:l?.type===`ALL`?void 0:l?.type}),D=(0,G.useMemo)(()=>yQ(x,y,{date:e=>e.createdAt,score:e=>typeof e.score==`number`?e.score:void 0}),[x,y]),O=(0,G.useMemo)(()=>d?.agentIds?.filter(e=>m[e]).map(e=>({value:e,label:m[e].name,type:`AGENT`}))||[],[d?.agentIds,m]),k=(0,G.useMemo)(()=>d?.workflowIds?.map(e=>({value:e,label:e,type:`WORKFLOW`}))||[],[d?.workflowIds]),A=(0,G.useMemo)(()=>[{value:`all`,label:`All Entities`,type:`ALL`},...O,...k],[O,k]),j=t.get(`entity`)??`all`,M=A.find(e=>e.value===j);M&&M.value!==l?.value&&u(M),(0,G.useEffect)(()=>{if(f){let e=f instanceof Error?f.message:`Failed to load scorer`;UC.error(`Error loading scorer: ${e}`)}},[f]),(0,G.useEffect)(()=>{if(g){let e=g instanceof Error?g.message:`Failed to load agents`;UC.error(`Error loading agents: ${e}`)}},[g]),(0,G.useEffect)(()=>{if(v){let e=v instanceof Error?v.message:`Failed to load workflows`;UC.error(`Error loading workflows: ${e}`)}},[v]);let N=e=>{e?.value&&n(t=>{let n=new URLSearchParams(t);return n.set(`entity`,e.value),n})};(0,G.useEffect)(()=>{let e=t.get(`scoreId`)??void 0;e!==i&&(e?D.find(t=>t.id===e)&&a(e):a(void 0))},[t,D]);let P=(0,G.useCallback)(e=>{a(e||void 0),n(t=>{let n=new URLSearchParams(t);return e?n.set(`scoreId`,e):n.delete(`scoreId`),n})},[n]);if(!d)return null;let F=JP(f)||JP(g)||JP(v),I=f&&YP(f),L=!F&&!I&&(f||g||v),R=!S&&D.length===0,z=l?.value!==`all`,B=d?.source===`stored`,V=e?(0,K.jsx)(h_i,{open:o,onOpenChange:s,initialScorerIds:[e],onSuccess:e=>void c(`/experiments/${e}`)}):null,H=B?(0,K.jsxs)(mD,{children:[(0,K.jsx)(mD.Trigger,{asChild:!0,children:(0,K.jsx)(X,{size:`icon-lg`,"aria-label":`Scorer actions menu`,children:(0,K.jsx)(Ar,{})})}),(0,K.jsx)(mD.Content,{align:`end`,className:`w-48`,children:(0,K.jsxs)(mD.Item,{onSelect:()=>void c(`/cms/scorers/${e}/edit`),children:[(0,K.jsx)(Ro,{}),` Edit scorer`]})})]}):null;if(F||I||L||R&&!z){let t=(f instanceof Error?f.message:void 0)??(g instanceof Error?g.message:void 0)??(v instanceof Error?v.message:void 0)??`An unexpected error occurred`;return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:QFi}),actionRow:!(F||I||L)&&H?(0,K.jsx)(jq,{children:(0,K.jsx)(jq.End,{children:H})}):void 0,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:F?(0,K.jsx)(jU,{}):I?(0,K.jsx)(AU,{resource:`scorers`}):L?(0,K.jsx)(RC,{tone:`error`,titleSlot:`Failed to load scorer`,descriptionSlot:t}):(0,K.jsx)(UVr,{onRunExperiment:()=>s(!0)})}),V]})}return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:QFi}),actionRow:(0,K.jsxs)(jq,{children:[(0,K.jsx)(jq.Start,{children:(0,K.jsx)(WVr,{selectedEntity:l,entityOptions:A,onEntityChange:N,onReset:()=>{n(e=>{let t=new URLSearchParams(e);return t.set(`entity`,`all`),t})},isLoading:S||h||_})}),(0,K.jsxs)(jq.End,{children:[(0,K.jsx)(ZFi,{visibleColumns:p.visibleColumns,toggleColumn:p.toggleColumn}),(0,K.jsx)(X,{variant:`primary`,onClick:()=>s(!0),icon:(0,K.jsx)(Uo,{}),children:`New experiment`}),H]})]}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(HVr,{scores:D,isLoading:S,selectedScoreId:i,isFetchingNextPage:w,hasNextPage:T,setEndOfListElement:E,onScoreClick:P,errorMsg:C?.message,columnsState:p,sort:y,onSortChange:b}),V]})}var tIi=[{value:`system`,label:`System`,icon:(0,K.jsx)(co,{})},{value:`light`,label:`Light`,icon:(0,K.jsx)(Tte,{})},{value:`dark`,label:`Dark`,icon:(0,K.jsx)(uo,{})}];function nIi(e,t){if(e.some(e=>e.value===t))return t;let[n]=e;return n?n.value:`system`}var rIi=({value:e,onChange:t,options:n=tIi,size:r=`md`,"aria-label":i=`Theme`,...a})=>{let{theme:o,setTheme:s}=B(),c=e??o,l=t??s,u=nIi(n,c);return(0,K.jsx)(ddr,{...a,"aria-label":i,iconOnly:!0,size:r===`xs`?`sm`:r,value:u,onValueChange:l,children:n.map(e=>(0,K.jsx)(fdr,{value:e.value,"aria-label":e.label,children:e.icon},e.value))})},iIi=[sF(`/settings`)],aIi=()=>{let{baseUrl:e,headers:t,apiPrefix:n}=YC();return(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:iIi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Settings`}),(0,K.jsx)(AHr,{children:(0,K.jsxs)(`div`,{className:`mx-auto flex max-w-4xl flex-col gap-8`,children:[(0,K.jsxs)(D3,{children:[(0,K.jsxs)(OHr,{children:[(0,K.jsx)(O3,{children:`General`}),(0,K.jsx)(kHr,{children:`Stored in this browser.`})]}),(0,K.jsx)(g$,{children:(0,K.jsx)(v$,{label:`Theme`,description:`Customize the appearance of the studio.`,children:(0,K.jsx)(rIi,{})})})]}),(0,K.jsxs)(D3,{children:[(0,K.jsxs)(OHr,{children:[(0,K.jsx)(O3,{children:`Mastra Connection`}),(0,K.jsx)(kHr,{children:`Configure the Mastra instance URL, API prefix, and request headers used by the studio.`})]}),(0,K.jsx)(NHr,{variant:`factory`,initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})]})]})})]})};function oIi(){let[e]=Hb(),t=kb(),n=e.get(`redirect`)||`/`;return(0,K.jsx)(uMi,{redirectUri:n,onSuccess:()=>{n.startsWith(`http`)?window.location.href=n:t(n,{replace:!0})},initialMode:`signup`})}function sIi({current:e,features:t}){let n=E6r(),r=D6r(),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 cIi=[`traces`,`spans`],lIi={traces:{icon:(0,K.jsx)(oF,{}),label:`Traces`},spans:{icon:(0,K.jsx)(zn,{}),label:`Spans`},threads:{icon:(0,K.jsx)(to,{}),label:`Threads`}};function uIi({current:e,views:t=cIi,onViewChange:n}){return(0,K.jsx)(`nav`,{"aria-label":`Observability views`,children:(0,K.jsx)(CA,{value:e,defaultTab:e,onValueChange:n,children:(0,K.jsx)(SA,{variant:`pill-ghost`,children:t.map(e=>(0,K.jsxs)(wA,{value:e,children:[(0,K.jsx)(TC,{size:`xs`,children:lIi[e].icon}),(0,K.jsx)(T,{variant:`caption`,className:`text-inherit`,children:lIi[e].label})]},e))})})})}function dIi(){return(0,K.jsxs)(`div`,{role:`status`,"aria-label":`Loading views`,className:`flex min-h-control-md items-center gap-0.5`,children:[(0,K.jsx)(dw,{className:`h-control-md w-20 rounded-full`}),(0,K.jsx)(dw,{className:`h-control-md w-20 rounded-full`})]})}function fIi({current:e,features:t,onViewChange:n,breadcrumbs:r,children:i}){let{views:a,isLoading:o,showSwitch:s}=sIi({current:e,features:t}),[c,l]=(0,G.useState)(null),u=Vsi(),d;return o?d=(0,K.jsx)(dIi,{}):s&&(d=(0,K.jsx)(uIi,{current:e,views:a,onViewChange:n})),(0,K.jsx)(uw,{breadcrumbs:r({current:e,isLoading:o,showSwitch:s}),actionRow:(d||u)&&(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center justify-between gap-3`,children:[d,(0,K.jsx)(`div`,{ref:l,className:`flex min-w-0 grow justify-end`})]}),children:(0,K.jsx)(Xli.Provider,{value:c??void 0,children:i})})}function pIi({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)(Qc,{"aria-label":`Loading storage capabilities`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:`Loading storage capabilities`})]}):(0,K.jsx)(RC,{variant:`fill`,titleSlot:r,descriptionSlot:i})]})}var mIi={refetchInterval:({state:e})=>osi(e.error),refetchOnWindowFocus:!1};function hIi(e){let[t,n]=(0,G.useState)(()=>new URLSearchParams);return e||{searchParams:t,setSearchParams:e=>n(t=>typeof e==`function`?e(t):e)}}function gIi(e,{sortFields:t,defaultDatePreset:n=Jsi}={}){let{searchParams:r,setSearchParams:i}=hIi(e),a=JSON.stringify(eci(r,n)),o=JSON.stringify(nci(r)),{datePreset:s,dateFrom:c,dateTo:l}=(0,G.useMemo)(()=>eci(r,n),[a]),{tokens:u,groups:d}=(0,G.useMemo)(()=>nci(r),[o]),f=ici(r,t??Ksi),p=(0,G.useMemo)(()=>({field:f.field,direction:f.direction}),[f.field,f.direction]),m=c?.getTime(),h=l?.getTime(),g=(0,G.useMemo)(()=>{let e=new Date,t=c8r(s,m===void 0?void 0:new Date(m),h===void 0?void 0:new Date(h),e);return f1r(t.dateFrom,t.dateTo,e)},[s,m,h]),_=(0,G.useRef)(null);(0,G.useLayoutEffect)(()=>{_.current=null},[r]);let v=e=>{let t=_.current??r,n=new URLSearchParams(t);e(n),n.toString()!==t.toString()&&(_.current=n,i(n,{replace:!0}))},y=e=>v(t=>tci(t,e(eci(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=jsi(b.current,n,e,t),{datePreset:`custom`,dateFrom:e,dateTo:t})),E=e=>y(t=>{let n=Msi(b.current,t);return b.current=void 0,n??{datePreset:e}}),D=(e,t)=>v(n=>rci(n,{tokens:e,groups:t})),O=e=>v(t=>aci(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 _Ii(e){return[`observability-list-head`,...e]}function vIi(e){let t=hy([e]),[n,r]=(0,G.useState)();return{anchorTo:n?.selectionHash===t?n.to:void 0,reanchor:()=>r({selectionHash:t,to:new Date().toISOString()})}}var yIi=()=>({rows:[],watermark:void 0});function bIi({queryKey:e,fetchHead:t,getId:n,getEndedAt:r,enabled:i,since:a,limit:o=50,maxRows:s=500,interval:c=nsi,onOverflow:l}){let u=dy(),d=_Ii(e),{data:f}=Ey({queryKey:d,queryFn:async()=>{let e=u.getQueryData(d)??yIi(),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?.(),yIi();let m=c.length>0?Math.max(e.watermark??-1/0,...c):e.watermark;return{rows:[...f.values()],watermark:m}},initialData:yIi,staleTime:1/0,enabled:i,refetchInterval:e=>!isi(e.state.error)&&c,refetchOnWindowFocus:!1,refetchOnReconnect:!1,retry:!1});return{headRows:f.rows}}function xIi(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 SIi(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),xIi(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 CIi={traces:`Traces`,spans:`Spans`,threads:`Threads`};function wIi({current:e,isLoading:t,showSwitch:n}){if(!(t||n||e===`traces`))return CIi[e]}function TIi(e){let t=e.get(`traceId`),n=e.get(`spanId`);return t&&n?{traceId:t,spanId:n}:void 0}function EIi(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 DIi({traceId:e,spanId:t}){return new URLSearchParams({traceId:e,spanId:t})}function OIi(e){return e.get(`threadId`)??void 0}function kIi(e,t){let n=new URLSearchParams(e);return t?n.set(`threadId`,t):n.delete(`threadId`),n}var AIi=e=>`${e.traceId}:${e.spanId}`;function jIi(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 MIi({query:e,rolling:t,autoRefetch:n=!0,limit:r,enabled:i=!0}){let a=Y(),{anchorTo:o,reanchor:s}=vIi(e),c=(0,G.useMemo)(()=>o?{...e,timeRange:{...e.timeRange,to:o}}:e,[e,o]),l=D$r({query:c,limit:r,enabled:i,queryOptions:mIi}),{headRows:u}=bIi({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:AIi,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&&SIi(f,u,{getId:AIi,compare:jIi(d),hasNextPage:l.hasNextPage}),[f,u,d,l.hasNextPage]);return{...l,spans:p}}function NIi(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 PIi({timeRange:e,where:t,onZoom:n}){let r=k6r(),i=(0,G.useMemo)(()=>({timeRange:e,...t?{where:t}:{},interval:Q9r(e).interval,measures:[...W9r],limit:1}),[e,t]),a=!r.enabled||$9r(e),{data:o,isLoading:s,isError:c,isPlaceholderData:l}=l$r({request:i,enabled:!a,queryOptions:{placeholderData:vy}}),u=(0,G.useMemo)(()=>iei(o?.rows??[],e),[o,e]);return a?null:(0,K.jsx)(z9r,{label:`Spans over time`,resourceLabel:`Spans`,buckets:u,isLoading:s,isError:c,isUpdating:l,onZoom:n&&(t=>n(aei(u,t,e)))})}var FIi=[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`],IIi=[];function LIi({timeRange:e}){let t=Y(),{data:n}=r5(),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=IIi}=_8(),{data:l=IIi}=v8();return(0,G.useMemo)(()=>[P5r,...zci({withContextFields:r,withTimeToFirstChunk:i,withTimeToFirstToken:a,withOutcomeFields:o,withModelFields:s,entityNames:c,environments:l,valueSuggestions:n=>K$r(t,e,`spans`,n)})],[r,i,a,o,s,c,l,t,e])}function RIi({tokens:e,groups:t,onFiltersChange:n}){let r=(0,G.useMemo)(()=>u0r(e),[e]),i=(0,G.useMemo)(()=>{let e=p0r([],t);return{...e,nodes:[f5,...r,...e.nodes]}},[r,t]),a=(0,G.useCallback)(e=>{let t=h0r({...e,nodes:e.nodes.filter(e=>s8(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(s8);a({...i,nodes:[...n,o,...s]})},[r,i,a])}}var zIi=e=>e;function BIi({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=LIi({timeRange:i}),{filterBarValue:h,onFilterBarChange:g}=RIi({tokens:a,groups:o,onFiltersChange:d});return(0,K.jsxs)(p5,{fields:m,operators:R1r,value:h,onValueChange:g,createItemId:zIi,describeSuggestionsError:f,maxDepth:3,"aria-label":`Span filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(p5.Chips,{renderChip:i=>i.fieldId===`timeRange`?(0,K.jsx)(p5.TimeRange,{preset:e,onPresetChange:s,dateFrom:t,dateTo:n,minDate:r,onDateChange:c,onDateRangeChange:l,disabled:p,presets:FIi,defaultPreset:a5.datePreset,onReset:u&&(()=>u(a5.datePreset))}):(0,K.jsx)(p5.Chip,{item:i})}),(0,K.jsx)(p5.Input,{placeholder:`Filter spans`})]})}function VIi({selection:e,onSelectionChange:t,renderPanel:n,urlState:r}){let i=gIi(r,{sortFields:qsi}),{timeRange:a,tokens:o,groups:s}=i,c=Dsi({scope:`spans`}),{data:l,isLoading:u}=r5(),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:Y3r(c.preferences,{withTimeToFirstChunk:f,withTimeToFirstToken:p}),[c.preferences,u,f,p]),_=(0,G.useMemo)(()=>{let e=[`startedAt`];return f&&l?.capabilities.traceQueryTimeToFirstChunkSort&&$8(g,`timeToFirstChunk`)&&e.push(`timeToFirstChunkMs`),p&&l?.capabilities.traceQueryTimeToFirstTokenSort&&$8(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)(()=>Hci(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}=MIi({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(NIi),[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)(y6r,{toolbar:(0,K.jsxs)(K.Fragment,{children:[r&&(0,K.jsx)(rui,{page:`spans`,...r,columns:c}),(0,K.jsxs)(jq,{children:[(0,K.jsx)(jq.Start,{children:(0,K.jsx)(BIi,{datePreset:i.datePreset,dateFrom:i.dateFrom,dateTo:i.dateTo,timeRange:a,tokens:o,groups:s,onDatePresetChange:i.onDatePresetChange,onDateChange:i.onDateChange,onDateRangeChange:i.onDateRangeChange,onDateReset:i.onDateReset,onFiltersChange:i.onFiltersChange,disabled:E})}),(0,K.jsx)(jq.End,{children:(0,K.jsx)(I6r,{scope:`spans`,value:c.preferences,onChange:c.setPreferences})})]})]}),chart:(0,K.jsx)(PIi,{timeRange:a,where:x,onZoom:({from:e,to:t})=>i.onZoom(e,t)}),error:D?(0,K.jsx)(Z8,{error:O,resource:`spans`,errorTitle:`Failed to load spans`}):void 0,empty:M?(0,K.jsx)(D3r,{resource:`spans`,datePreset:i.datePreset,dateFrom:i.dateFrom,dateTo:i.dateTo}):void 0,children:(0,K.jsx)(Bti,{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 HIi({selection:e,spans:t,onSelect:n,onClose:r,onShowTrace:i}){let{data:a,isLoading:o}=y8({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)(iai,{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 UIi({selection:e,spans:t,onSelect:n,onClose:r,onShowTrace:i}){let a=fE();v3r(e?`${e.traceId}:${e.spanId}`:void 0,r);let o=e?(0,K.jsx)(HIi,{selection:e,spans:t,onSelect:n,onClose:r,onShowTrace:i}):null;return a?(0,K.jsx)(m$,{open:!!e,onClose:r,title:`Span details`,children:o}):o?(0,K.jsx)(J8,{owner:`span-detail`,children:(0,K.jsx)(m$,{variant:`inline`,title:`Span details`,children:o})}):null}function WIi(){let{enabled:e,isLoading:t}=E6r(),n=kb(),[r,i]=Hb();return(0,K.jsx)(pIi,{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)(VIi,{urlState:{searchParams:r,setSearchParams:i},selection:TIi(r),onSelectionChange:e=>i(t=>EIi(t,e),{replace:!0}),renderPanel:e=>(0,K.jsx)(UIi,{...e,onShowTrace:e=>n(`/traces?${DIi(e)}`)})})})}async function GIi(){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 KIi({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 qIi({repoOrSlug:e,owner:t}){let{templates:n}=await GIi(),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 KIi({repo:e,owner:t});if(r)return r;throw Error(`Template ${e} not found`)}return r}async function JIi({repo:e,owner:t,branch:n}){let r=`https://raw.githubusercontent.com/${t}/${e}/${n}/.env.example`,i=await fetch(r);return i.ok?(await i.text()).split(`
|
|
724
|
-
`).reduce((e,t)=>{if(!t||t.startsWith(`#`))return e;let[n,r]=t.split(`=`);return n&&(e[n]=r?.split(``)?.every(e=>e===`*`)?``:r?.replaceAll(`"`,``)),e},{}):{}}var YIi=({queryOptions:e}={})=>Ey({queryKey:[`mastra-templates`],queryFn:GIi,...e}),XIi=({repoOrSlug:e,owner:t,queryOptions:n})=>Ey({queryKey:[`template-repo`,e,t],queryFn:()=>qIi({repoOrSlug:e,owner:t}),...n}),ZIi=({repo:e,owner:t,branch:n,queryOptions:r})=>Ey({queryKey:[`template-repo-env-vars`,e,t,n],queryFn:()=>JIi({repo:e,owner:t,branch:n}),...r}),QIi=({queryOptions:e}={})=>{let t=Y();return Ey({queryKey:[`agent-builder-workflow`],queryFn:async()=>await t.getAgentBuilderAction(`merge-template`).details(),...e})},$Ii=({queryOptions:e}={})=>{let t=Y();return Oy({mutationFn:async({runId:e})=>await t.getAgentBuilderAction(`merge-template`).createRun({runId:e}),...e})},eLi=({queryOptions:e}={})=>{let t=Y();return Oy({mutationFn:async({runId:e})=>await t.getAgentBuilderAction(`merge-template`).runById(e),...e})},tLi=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)},nLi=(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=tLi(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=tLi(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}},rLi=(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)}},iLi=(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}=nLi(a,s,e);s=c,r(c),(a.runId||i||t)&&rLi(a.runId||i||t,c)}}catch(t){console.error(`💥 [processStream] Error processing template installation stream:`,t);let{newState:n}=nLi({type:`error`,payload:{error:t instanceof Error?t.message:`Unknown error`}},s,e);r(n)}finally{a(!1),o.releaseLock()}}}},aLi=({workflowInfo:e,queryOptions:t}={})=>{let n=Y(),{streamResult:r,isStreaming:i,processStream:a}=iLi(e);return{streamInstall:Oy({mutationFn:async({inputData:e,selectedModel:t,runId:r})=>{for(let i=1;i<=3;i++)try{let i=n.getAgentBuilderAction(`merge-template`),o=new Ll;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}},oLi=({workflowInfo:e,queryOptions:t}={})=>{let n=Y(),{streamResult:r,isStreaming:i,processStream:a}=iLi(e);return{observeInstall:Oy({mutationFn:async({runId:e})=>{let t=2e3;for(let r=1;r<=3;r++)try{let t=await n.getAgentBuilderAction(`merge-template`).observeStream({runId:e});await a(t,e);return}catch(e){console.error(`💥 [observeInstall] Attempt ${r} failed:`,e);let n=e?.message?.includes(`Failed to fetch`)||e?.message?.includes(`NetworkError`)||e?.message?.includes(`network error`)||e?.message?.includes(`fetch`)||e?.code===`NETWORK_ERROR`||e?.name===`TypeError`;if(console.warn(`ObserveStream attempt ${r}/3 failed:`,e),n&&r<3){console.info(`🔄 ObserveStream network error detected (likely hot reload), retrying in ${t}ms... (attempt ${r+1}/3)`),await new Promise(e=>setTimeout(e,t));continue}throw console.error(`❌ [observeInstall] Non-network error or max retries reached, throwing:`,e),e}},...t?.observeInstall}),streamResult:r,isStreaming:i}};function sLi(e){return e.replace(/\/$/,``).split(`/`).pop()}function cLi({templates:e,linkComponent:t,className:n,isLoading:r}){let i=t||`a`;return r?(0,K.jsx)(`div`,{className:m(`grid gap-y-4`,n),children:Array.from({length:5}).map((e,t)=>(0,K.jsx)(`div`,{className:`h-16 animate-pulse rounded-lg bg-card`},t))}):(0,K.jsx)(`div`,{className:m(`grid gap-y-4`,n),children:e.map(e=>{let t=e?.agents||e?.tools||e?.networks||e?.workflows||e?.mcp;return(0,K.jsxs)(`article`,{className:m(Wb,`state-layer grid w-full grid-cols-[1fr_auto] overflow-hidden rounded-lg`),children:[(0,K.jsxs)(i,{to:`/templates/${e.slug}`,className:m(`group grid`,{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":e.imageURL}),children:[e.imageURL&&(0,K.jsx)(`div`,{className:`overflow-hidden`,children:(0,K.jsx)(`div`,{className:`thumb transition-scale h-full w-full bg-cover duration-150`,style:{backgroundImage:`url(${e.imageURL})`}})}),(0,K.jsxs)(`div`,{className:m(`grid w-full gap-0.5 px-4 py-3`,`[&_svg]:h-[1em] [&_svg]:w-[1em] [&_svg]:text-muted-foreground`),children:[(0,K.jsx)(T,{as:`h2`,tone:`ink`,children:e.title}),(0,K.jsx)(T,{className:m(QC,f),children:e.description}),(0,K.jsxs)(`div`,{className:`mt-3 hidden flex-wrap items-center gap-x-8 gap-y-4 text-muted-foreground 2xl:flex`,children:[t&&(0,K.jsxs)(`ul`,{className:m(`text-muted-foreground`,`m-0 flex list-none gap-4 p-0`,`[&>li]:flex [&>li]:items-center [&>li]:gap-0.5`),children:[e?.agents&&e.agents.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(tF,{}),` `,e.agents.length]})}),e?.tools&&e.tools.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(aF,{}),` `,e.tools.length]})}),e?.networks&&e.networks.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(_o,{}),` `,e.networks.length]})}),e?.workflows&&e.workflows.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(Rc,{}),` `,e.workflows.length]})}),e?.mcp&&e.mcp.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(nF,{}),` `,e.mcp.length]})})]}),(0,K.jsx)(`div`,{className:`flex items-center gap-4`,children:e.supportedProviders.map(e=>(0,K.jsx)(T,{tone:`muted`,as:`span`,variant:`body`,children:e},e))})]})]})]}),(0,K.jsx)(`a`,{href:e.githubUrl,className:m(`group ml-auto hidden items-center gap-2 pr-4`,`lg:flex`),target:`_blank`,rel:`noopener noreferrer`,children:(0,K.jsx)(T,{as:`span`,variant:`body`,children:(0,K.jsxs)(`span`,{className:m(`flex items-center gap-2 rounded bg-sidebar px-2 py-1`,mKe,QC,f),children:[(0,K.jsx)(pQ,{}),` `,sLi(e.githubUrl)]})})})]},e.slug)})})}function lLi({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:i,onProviderChange:a,searchTerm:o,onSearchChange:s,onReset:c,className:l,isLoading:u}){return u?(0,K.jsxs)(`div`,{className:m(`flex h-[6.5rem] items-center gap-5`,`[&>div]:h-8 [&>div]:w-48 [&>div]:animate-pulse [&>div]:bg-card`,l),children:[(0,K.jsx)(`div`,{}),` `,(0,K.jsx)(`div`,{}),` `,(0,K.jsx)(`div`,{})]}):(0,K.jsxs)(`div`,{className:m(`sticky top-0 mx-auto flex flex-wrap gap-1.5 bg-background py-5`,l),children:[(0,K.jsx)(RU,{label:`Search templates`,placeholder:`Search templates`,size:`sm`,value:o,onValueChange:s}),(0,K.jsxs)(WA,{value:t,onValueChange:i,children:[(0,K.jsx)(KA,{"aria-label":`Filter by tag`,size:`sm`,className:`w-auto`,children:(0,K.jsx)(GA,{placeholder:`Select an option`})}),(0,K.jsx)(qA,{children:e.map(e=>(0,K.jsx)(JA,{value:e.value,children:e.label},e.value))})]}),(0,K.jsxs)(WA,{value:r,onValueChange:a,children:[(0,K.jsx)(KA,{"aria-label":`Filter by provider`,size:`sm`,className:`w-auto`,children:(0,K.jsx)(GA,{placeholder:`Select an option`})}),(0,K.jsx)(qA,{children:n.map(e=>(0,K.jsx)(JA,{value:e.value,children:e.label},e.value))})]}),c&&(0,K.jsx)(x3,{onClick:c})]})}var uLi=[{id:`templates`,label:`Templates`}];function dLi(){let{data:e,isLoading:t}=YIi(),{templates:n,tags:r,providers:i}=e??{templates:[],tags:[],providers:[]},[a,o]=(0,G.useState)(`all`),[s,c]=(0,G.useState)(`all`),[l,u]=(0,G.useState)(``),d=[{value:`all`,label:`Any tag`}];(r||[]).forEach(e=>{d.push({value:e,label:e})});let f=[{value:`all`,label:`Any provider`}];(i||[]).forEach(e=>{f.push({value:e,label:e})});let p=(e,t)=>{t===`tag`?o(e):t===`provider`&&c(e)},h=e=>{u(e)},g=()=>{o(`all`),c(`all`),u(``)},_=n.filter(e=>!(l&&!e.title.toLowerCase().includes(l)&&!e.description.toLowerCase().includes(l)||a!==`all`&&!e.tags.includes(a)||s!==`all`&&!e.supportedProviders.includes(s))),v=l||a!==`all`||s!==`all`;return(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:uLi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Templates`}),(0,K.jsx)($C,{children:(0,K.jsxs)(B1e,{children:[(0,K.jsx)(TC,{children:(0,K.jsx)(Do,{})}),`Templates`]})}),(0,K.jsxs)(`div`,{className:m(`z-10 h-full w-full overflow-y-auto px-5 pb-12`),children:[(0,K.jsx)(lLi,{selectedTag:a,onTagChange:e=>p(e,`tag`),tagOptions:d,selectedProvider:s,onProviderChange:e=>p(e,`provider`),providerOptions:f,searchTerm:l,onSearchChange:h,onReset:v?g:void 0,className:`max-w-[80rem]`,isLoading:t}),(0,K.jsx)(cLi,{templates:_,linkComponent:Vb,className:`mx-auto max-w-[80rem]`,isLoading:t})]})]})}function fLi({children:e,className:t}){return(0,K.jsx)(`div`,{className:m(`transition-height mt-12 rounded-lg border border-border px-4 py-5 lg:min-h-[25rem] lg:px-12`,t),children:e})}function pLi({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)(wc,{className:`text-warning-foreground`}),title:`Template Installed with Warnings`}:{icon:(0,K.jsx)(Gr,{}),title:`Template Installation Failed`};return(0,K.jsxs)(fLi,{className:`mb-5 content-center space-y-4 text-muted-foreground`,children:[(0,K.jsxs)(`div`,{className:`grid content-center items-center justify-items-center gap-4 [&>svg]:h-8 [&>svg]:w-8`,children:[o,(0,K.jsxs)(`div`,{className:`space-y-2 text-center`,children:[(0,K.jsx)(T,{variant:`subheading`,tone:`ink`,children:s}),(0,K.jsx)(T,{tone:`muted`,children:a()})]})]}),t&&t.length>0&&(0,K.jsxs)(`details`,{children:[(0,K.jsx)(`summary`,{className:m(`text-muted-foreground hover:text-foreground`,`cursor-pointer text-center select-none`),children:(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[`Show Validation Issues (`,t.length,`)`]})}),(0,K.jsx)(`div`,{className:`mt-4 max-h-60 space-y-2 overflow-auto rounded bg-muted p-3 text-left`,children:t.map((e,t)=>(0,K.jsxs)(`div`,{className:`border-l-2 border-destructive-indicator pl-2`,children:[(0,K.jsx)(T,{as:`p`,variant:`column`,className:`text-destructive-foreground`,children:e.type===`typescript`?`🔴 TypeScript Error`:`⚠️ Lint Error`}),(0,K.jsx)(Dw,{className:`mt-1 text-caption wrap-break-word whitespace-pre-wrap text-muted-foreground`,code:e.message})]},t))})]}),n&&!i&&(0,K.jsxs)(`details`,{children:[(0,K.jsx)(`summary`,{className:m(`text-muted-foreground hover:text-foreground`,`cursor-pointer text-center select-none`),children:(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`block`,children:`Show Details`})}),(0,K.jsx)(`div`,{className:`mt-4 max-h-60 overflow-auto rounded bg-muted p-3 text-left`,children:(0,K.jsx)(Dw,{className:`text-caption wrap-break-word whitespace-pre-wrap`,code:n})})]})]})}function mLi({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:i,handleInstallTemplate:a,handleVariableChange:o,isLoadingEnvVars:s,isInstalling:c,defaultModelProvider:l,defaultModelId:u,onModelUpdate:d}){return(0,K.jsx)(fLi,{children:(0,K.jsxs)(`div`,{className:`mx-auto my-4 grid max-w-[40rem] gap-5 p-4 lg:p-5`,children:[(0,K.jsxs)(T,{as:`h2`,variant:`heading`,tone:`muted`,className:m(`flex items-center gap-2`,`[&_svg]:h-[1.2em] [&_svg]:opacity-70 [&>svg]:w-[1.2em]`),children:[`Install Template `,(0,K.jsx)(To,{})]}),(0,K.jsxs)(fA,{orientation:`horizontal`,children:[(0,K.jsx)(mA,{children:`Template AI Model Provider`}),(0,K.jsx)(Oyt,{className:`flex-1`,children:(0,K.jsxs)(WA,{name:`template-provider`,value:t,onValueChange:n,children:[(0,K.jsx)(KA,{size:`md`,children:(0,K.jsx)(GA,{placeholder:`Select`})}),(0,K.jsx)(qA,{children:e.map(e=>(0,K.jsx)(JA,{value:e.value,children:e.label},e.value))})]})})]}),t&&Object.entries(r||{}).length>0&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h3`,tone:`muted`,children:`Set required Environmental Variables`}),(0,K.jsx)(`div`,{className:`grid grid-cols-[1fr_1fr] items-start gap-4`,children:s?(0,K.jsxs)(`div`,{className:m(`text-muted-foreground`,`col-span-2 flex items-center justify-center gap-4`,`[&_svg]:h-[1.1em] [&_svg]:w-[1.1em] [&_svg]:opacity-50`,`animate-in duration-300 fade-in`),children:[(0,K.jsx)(Qc,{}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[` `,`Loading variables...`]})]}):Object.entries(r).map(([e,t])=>(0,K.jsxs)(G.Fragment,{children:[(0,K.jsxs)(fA,{className:`w-full`,children:[(0,K.jsx)(mA,{className:`sr-only`,children:`Key`}),(0,K.jsx)(ZM,{name:`env-${e}`,value:e,disabled:!0,className:`w-full`})]}),(0,K.jsxs)(fA,{invalid:i.includes(e),className:`w-full`,children:[(0,K.jsx)(mA,{className:`sr-only`,children:`Value`}),(0,K.jsx)(ZM,{name:e,value:t,onChange:o,autoComplete:`off`,className:`w-full`}),(0,K.jsx)(gA,{children:i.includes(e)?`Value is required.`:void 0})]})]},e))}),(0,K.jsxs)(`div`,{className:`relative mt-3.5 border-t border-border pt-12`,children:[(0,K.jsx)(`div`,{className:`absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full bg-background`,children:(0,K.jsx)(T,{tone:`muted`,as:`span`,variant:`caption`,className:`block`,children:`And`})}),(0,K.jsx)(T,{as:`h3`,tone:`muted`,children:`Set AI Model for Template Installation`}),(0,K.jsx)(T,{tone:`muted`,className:`mt-2 mb-5`,children:`This model will be used by the workflow to process and install the template`}),(0,K.jsx)(Z4r,{defaultProvider:l||``,defaultModel:u||``,updateModel:d||(()=>Promise.resolve({message:`Updated`})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:`Provider`})]})]}),t&&!s&&(0,K.jsx)(X,{className:m(`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)(Qc,{className:`h-4 w-4`}),` Installing...`]}):(0,K.jsxs)(K.Fragment,{children:[`Install `,(0,K.jsx)(Ht,{})]})})]})})}function hLi({title:e,description:t,githubUrl:n,isLoading:r,infoData:i,templateSlug:a}){let o=a?`feat/install-template-${a}`:`feat/install-template-[slug]`;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`mt-5 grid items-center`,children:(0,K.jsxs)(`div`,{className:m(`flex items-center gap-3`,`[&>svg]:h-[1.2em] [&>svg]:w-[1.2em] [&>svg]:opacity-50`,{"[&>svg]:opacity-20":r}),children:[(0,K.jsx)(Do,{}),(0,K.jsx)(`h2`,{className:m({"flex min-w-[50%] rounded-lg bg-muted":r}),children:(0,K.jsx)(T,{as:`span`,variant:`title`,className:`block`,children:r?(0,K.jsx)(K.Fragment,{children:`\xA0`}):e})})]})}),(0,K.jsxs)(`div`,{className:`grid gap-x-24 lg:grid-cols-[1fr_1fr]`,children:[(0,K.jsxs)(`div`,{className:`grid`,children:[(0,K.jsx)(T,{tone:`muted`,className:m(`mt-2 mb-4`,{"rounded-lg bg-muted":r}),children:r?(0,K.jsx)(K.Fragment,{children:`\xA0`}):t}),!r&&a&&(0,K.jsxs)(`div`,{className:m(`mb-4 rounded-lg border border-border bg-background p-4`,`flex items-start gap-3`),children:[(0,K.jsx)(`div`,{className:`mt-0.5 shrink-0`,children:(0,K.jsx)(Xi,{className:`h-[1.1em] w-[1.1em] text-info-indicator`})}),(0,K.jsxs)(`div`,{className:`flex-1 space-y-2`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(ki,{className:`h-[1em] w-[1em] text-muted-foreground`}),(0,K.jsx)(T,{as:`span`,variant:`subheading`,tone:`ink`,children:`A new Git branch will be created`})]}),(0,K.jsxs)(`div`,{className:`space-y-1`,children:[(0,K.jsxs)(T,{tone:`muted`,as:`p`,variant:`caption`,children:[(0,K.jsx)(T,{as:`span`,variant:`column`,children:`Branch name:`}),` `,(0,K.jsx)(uZ,{children:o})]}),(0,K.jsx)(T,{tone:`muted`,as:`p`,variant:`caption`,children:`This ensures safe installation with easy rollback if needed. Your main branch remains unchanged.`})]})]})]}),n&&(0,K.jsxs)(`a`,{href:n,target:`_blank`,rel:`noopener noreferrer`,className:m(`text-muted-foreground hover:text-foreground`,`mt-auto flex items-center gap-2`),children:[(0,K.jsx)(pQ,{}),(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:n?.split(`/`)?.pop()})]})]}),i&&(0,K.jsx)(t3r,{data:i,labelsAreHidden:!0,isLoading:r})]})]})}function gLi(e){switch(e){case`running`:return(0,K.jsx)(Qc,{size:`sm`,"aria-hidden":!0});case`success`:return(0,K.jsx)(Bn,{"aria-hidden":!0});case`failed`:return(0,K.jsx)(Hc,{"aria-hidden":!0});default:return null}}function _Li(){return(0,K.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`text-placeholder`,"aria-hidden":!0,children:(0,K.jsx)(`circle`,{cx:`12`,cy:`12`,r:`8.5`,pathLength:`48`,fill:`none`,stroke:`currentcolor`,strokeWidth:`2.8`,strokeLinecap:`round`,strokeDasharray:`3 3`})})}function vLi({status:e,variant:t}){return t===`plain`?(0,K.jsx)(`span`,{className:m(`flex size-4 items-center justify-center self-center [&>svg]:size-4`,b.colors,{"[&>svg]:text-success-indicator":e===`success`,"[&>svg]:text-destructive-foreground":e===`failed`}),children:e===`pending`?(0,K.jsx)(_Li,{}):gLi(e)}):(0,K.jsx)(`span`,{className:m(`flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none`,b.colors,b.transform,{"[&>svg]:text-success-indicator":e===`success`,"[&>svg]:text-destructive-foreground":e===`failed`,"border border-dashed border-placeholder":e===`pending`,"[&>svg]:size-4":e!==`running`,"bg-success-subtle":e===`success`,"bg-destructive-subtle":e===`failed`,"scale-110":e===`success`||e===`failed`}),children:gLi(e)})}function yLi({step:e,isActive:t,position:n,variant:r=`default`}){let i=t||e.status===`success`?`ink`:`muted`;return(0,K.jsxs)(`div`,{className:m(`grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none`,b.colors,{"border border-transparent":r==="default","border-dashed border-placeholder bg-card":t&&r==="default"}),children:[(0,K.jsxs)(`div`,{className:`grid min-w-0 grid-cols-[auto_1fr] gap-2`,children:[(0,K.jsxs)(T,{as:`span`,tone:i,className:m(`flex min-w-6 justify-end`,b.colors),children:[n,`.`]}),(0,K.jsxs)(`div`,{className:`min-w-0`,children:[(0,K.jsx)(T,{as:`h4`,tone:i,className:b.colors,children:e.title}),e.description&&(0,K.jsx)(T,{tone:`faint`,className:m(`-mt-0.5`,{truncate:r===`plain`}),children:e.description})]})]}),(0,K.jsx)(vLi,{status:e.status,variant:r})]})}function bLi({currentStep:e,steps:t=[],className:n}){return(0,K.jsx)(`div`,{className:m(n),children:t.map((t,n)=>(0,K.jsx)(yLi,{step:t,isActive:e?.id===t.id,position:n+1},t.id))})}function xLi({steps:e}){let t=e.length,n=e.filter(e=>e.status===`success`).length;return(0,K.jsxs)(`div`,{className:`flex w-full flex-col content-center justify-center gap-4`,children:[(0,K.jsx)(`div`,{className:`grid w-full grid-cols-[0_repeat(9,1fr)]`,children:e.map((t,n)=>(0,K.jsx)(`div`,{className:m(`relative flex h-8 items-center justify-end`,b.colors,{"bg-success-subtle":t.status===`success`&&e?.[n-1]?.status===`success`}),children:(0,K.jsx)(`div`,{className:m(`absolute right-0 z-10 flex size-8 translate-x-1/2 items-center justify-center self-center rounded-full bg-fill text-column text-muted-foreground motion-reduce:transition-none`,b.colors,b.transform,{"border border-dashed border-placeholder":t.status===`pending`,"scale-110 bg-success-subtle text-success-subtle-foreground":t.status===`success`,"scale-110 bg-destructive-subtle text-destructive-subtle-foreground":t.status===`failed`}),children:t.status===`running`?(0,K.jsx)(Qc,{}):n+1})},t.id))}),(0,K.jsxs)(`div`,{className:m(`text-center text-caption text-muted-foreground`,b.colors),children:[n,` of `,t,` steps completed`]})]})}var SLi=(0,G.createContext)(3);function CLi({title:e,description:t,action:n,done:r,className:i,children:a}){let o=(0,G.useContext)(SLi);return(0,K.jsxs)(`li`,{className:m(`group/step grid grid-cols-[1.5rem_minmax(0,1fr)] gap-x-4 [counter-increment:ds-step]`,i),children:[(0,K.jsxs)(`div`,{className:`flex flex-col items-center`,children:[(0,K.jsx)(`span`,{className:m(`flex size-6 shrink-0 items-center justify-center rounded-full`,b.colors,r?`bg-success-indicator/18 text-success-indicator`:`bg-fill text-foreground`),children:r?(0,K.jsx)(Bn,{className:`size-3.5`,"aria-label":`Done`}):(0,K.jsx)(T,{as:`span`,variant:`column`,className:`before:content-[counter(ds-step)]`,"aria-hidden":!0})}),(0,K.jsx)(`span`,{"aria-hidden":!0,className:`w-px flex-1 bg-border group-last/step:hidden`})]}),(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-3 pb-8 group-last/step:pb-0`,children:[(0,K.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,K.jsxs)(`div`,{className:`flex min-h-6 flex-wrap items-center justify-between gap-x-6 gap-y-2`,children:[(0,K.jsx)(T,{as:o===2?`h2`:`h3`,variant:`label`,className:`text-pretty`,children:e}),n==null?null:(0,K.jsx)(`div`,{className:`flex shrink-0 items-center gap-2`,children:n})]}),t==null?null:(0,K.jsx)(T,{as:`p`,variant:`body-sm`,tone:`muted`,className:`max-w-[70ch] text-pretty`,children:t})]}),a]})]})}function wLi({headingLevel:e=3,className:t,children:n}){return(0,K.jsx)(SLi.Provider,{value:e,children:(0,K.jsx)(`ol`,{className:m(`flex flex-col [counter-reset:ds-step]`,t),children:n})})}Object.assign(wLi,{Step:CLi});function TLi({name:e,streamResult:t,runId:n,workflowInfo:r}){let i=t?.phase||`initializing`,a=t?.payload?.workflowState,o=t?.payload?.currentStep,s=t?.error,c=a?.steps||{},l=Object.keys(c).length>0,u=e=>e===`input`||e.endsWith(`.input`)||e.startsWith(`Mapping_`)&&/[0-9a-f]{8}/.test(e)||/[0-9a-f]{8,}/.test(e)?!1:!r?.allSteps||e in r.allSteps,d=Object.entries(c).filter(([e,t])=>u(e)),f=d.length,p=()=>{switch(i){case`initializing`:return`Preparing template installation...`;case`processing`:return`Installing ${e} template`;case`completed`:return`Template installation completed!`;case`error`:return`Template installation failed`;default:return`Installing template...`}},h=d.map(([e,t])=>({id:e,status:t?.status,description:t?.description,title:e.charAt(0).toUpperCase()+e.slice(1).replace(/-/g,` `),isActive:o?.id===e}));return(0,K.jsxs)(fLi,{className:`mb-5 content-center space-y-6 text-muted-foreground`,children:[(0,K.jsxs)(`div`,{className:`text-center`,children:[(0,K.jsx)(T,{as:`h3`,variant:`heading`,tone:`ink`,children:p()}),(t?.runId||n)&&(0,K.jsxs)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`mt-2`,children:[`Run ID: `,t?.runId??n]})]}),l&&f>0&&![`error`].includes(i)&&(0,K.jsx)(`div`,{className:`mx-auto w-full max-w-[30rem] px-4`,children:(0,K.jsx)(xLi,{steps:h})}),s&&i===`error`&&(0,K.jsxs)(`div`,{className:m(`text-foreground`,`flex items-center gap-3 rounded-lg bg-destructive-subtle p-4`,`[&>svg]:h-6 [&>svg]:w-6 [&>svg]:text-destructive-foreground [&>svg]:opacity-70`),children:[(0,K.jsx)(So,{}),(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:s||`Something went wrong`})]}),l&&(0,K.jsx)(bLi,{steps:h,currentStep:o,className:`pb-4`}),!l&&i===`initializing`&&(0,K.jsxs)(`div`,{className:m(`text-muted-foreground`,`grid justify-items-center gap-4 text-center`),children:[(0,K.jsx)(Qc,{}),(0,K.jsx)(T,{as:`p`,variant:`body`,children:`This may take some time...`})]})]})}function ELi({name:e,installedEntities:t}){return(0,K.jsxs)(fLi,{className:m(`grid content-center items-center justify-items-center gap-4`,`[&>svg]:h-8 [&>svg]:w-8`),children:[(0,K.jsx)(To,{}),(0,K.jsx)(T,{as:`h2`,variant:`heading`,children:`Done!`}),(0,K.jsxs)(T,{tone:`muted`,className:`text-center`,children:[`The `,(0,K.jsx)(`b`,{className:`text-muted-foreground`,children:e}),` template has been successfully installed.`,t&&t.length>0&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`br`,{}),` Installed entities are listed below.`]})]}),t&&t.length>0&&(0,K.jsx)(t3r,{data:t})]})}function DLi(){let{templateSlug:e}=Ab(),t=[{id:`templates`,label:`Templates`,to:`/templates`},{id:`template`,label:LLt(e)}],[n,r]=Hb(),[i,a]=(0,G.useState)(``),[o,s]=(0,G.useState)(``),[c,l]=(0,G.useState)(``),[u,d]=(0,G.useState)({}),[f,p]=(0,G.useState)([]),[h,g]=(0,G.useState)(null),[_,v]=(0,G.useState)(!1),[y,b]=(0,G.useState)(``),[x,S]=(0,G.useState)(!1),[C,w]=(0,G.useState)(!1),[T,E]=(0,G.useState)([]),{data:D,isLoading:O}=XIi({repoOrSlug:e,owner:`mastra-ai`}),k=`1.83.0-alpha.10`.includes(`beta`)??!1?`beta`:`main`,{data:A,isLoading:j}=ZIi({repo:D?.githubUrl?new URL(D.githubUrl).pathname.split(`/`)[2]:`template-${e}`,owner:`mastra-ai`,branch:k}),{data:M,isLoading:N}=QIi(),{mutateAsync:P,isPending:F}=$Ii(),{mutateAsync:I}=eLi(),{streamInstall:L,streamResult:R,isStreaming:z}=aLi({workflowInfo:M}),{observeInstall:B,streamResult:V,isStreaming:H}=oLi({workflowInfo:M});(0,G.useEffect)(()=>{let e=n.get(`runId`);!e||_||h||z||H||(console.info(`🔄 Checking completed run after hot reload:`,{runId:e}),b(e),I({runId:e}).then(e=>{let t=e.snapshot;if(t?.status===`success`&&t?.result?.success)v(!0);else if(t?.result?.success===!1){if(t?.result?.validationResults&&!t?.result?.validationResults?.valid&&t?.result?.validationResults?.remainingErrors>0){let{remainingErrors:e,errors:n}=t.result.validationResults,r=`Template installation completed but ${e} validation issue${e>1?`s`:``} remain unresolved.`;g(r),E(n||[])}else{let e=t?.result?.message||t?.result?.error||`Template installation failed`;g(typeof e==`string`?e:String(e))}}}).catch(e=>{console.error(`❌ Failed to fetch run details:`,e),g(`Failed to retrieve installation status after reload`)}))},[n,_,h,z,H,I]),(0,G.useEffect)(()=>{let e=n.get(`runId`),t=n.get(`resume`),i=n.get(`provider`);if(e&&t===`true`&&i&&!z&&!H&&!x&&!C&&M){b(e),S(!0);try{I({runId:e}).then(t=>{if(t.snapshot?.status===`running`)return B.mutateAsync({runId:e})}).then(()=>{r(e=>{let t=new URLSearchParams(e);return t.delete(`resume`),t})}).catch(e=>{console.error(`❌ Failed to resume template installation:`,e),e.message?.includes(`404`)||e.message?.includes(`not found`)?g(`Template installation run not found. It may have expired or been completed.`):g(`Failed to resume template installation. Please try again.`)})}catch(e){console.error(`❌ Auto-resume failed with error:`,e),g(`Failed to resume template installation. Please refresh and try again.`)}}},[n,e,z,H,x,C,M,I,B,r]);let ee=[{value:`openai`,label:`OpenAI`},{value:`anthropic`,label:`Anthropic`},{value:`groq`,label:`Groq`},{value:`google`,label:`Google`}],te=[{key:`tools`,label:`Tools`,value:D?.tools?.length?D.tools.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(aF,{})},{key:`agents`,label:`Agents`,value:D?.agents?.length?D.agents.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(tF,{})},{key:`workflows`,label:`Workflows`,value:D?.workflows?.length?D.workflows.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(Rc,{})},{key:`providers`,label:`Providers`,value:D?.supportedProviders?.length?D.supportedProviders.join(`, `):`n/a`,icon:(0,K.jsx)(Dn,{})},{key:`tags`,label:`Tags`,value:D?.tags?.length?D.tags.join(`, `):`n/a`,icon:(0,K.jsx)(Qs,{})}],U=[{...te[0]},{...te[1]},{...te[2]}].filter(e=>e.value!==`n/a`);return(0,G.useEffect)(()=>{A&&d(A)},[A]),(0,G.useEffect)(()=>{let e=R||V;e?.phase===`error`&&e?.error&&g(typeof e.error==`string`?e.error:String(e.error))},[R?.phase,R?.error,V?.phase,V?.error]),(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(`div`,{className:m(`h-full w-full overflow-y-scroll lg:px-12`),children:(0,K.jsxs)(`div`,{className:`mx-auto grid w-full max-w-[80rem] gap-y-4 p-4`,children:[(0,K.jsx)(hLi,{isLoading:O,title:D?.title,description:D?.longDescription,imageURL:D?.imageURL,githubUrl:D?.githubUrl,infoData:te,templateSlug:e}),D&&(0,K.jsxs)(K.Fragment,{children:[(z||H)&&(0,K.jsx)(TLi,{name:D.title,streamResult:H?V:R,runId:y,workflowInfo:M}),_&&(0,K.jsx)(ELi,{name:D.title,installedEntities:U,linkComponent:Vb}),h&&(0,K.jsx)(pLi,{errorMsg:h,validationErrors:T.length>0?T:R?.validationResults?.errors||V?.validationResults?.errors}),!z&&!H&&!_&&!h&&(0,K.jsx)(mLi,{providerOptions:ee,selectedProvider:i,onProviderChange:e=>{a(e)},variables:u,setVariables:d,errors:f,setErrors:p,handleInstallTemplate:async()=>{let e=Object.entries(u).reduce((e,[t,n])=>(n===``&&e.push(t),e),[]);if(e.length>0)p(e);else if(D){g(null),v(!1),b(``),w(!0);try{let e={repo:D.githubUrl||`https://github.com/mastra-ai/template-${D.slug}`,ref:k,slug:D.slug,variables:u},{runId:t}=await P({});b(t),r(e=>{let n=new URLSearchParams(e);return n.set(`runId`,t),n.set(`resume`,`true`),n.set(`provider`,i||`openai`),n}),await L.mutateAsync({inputData:e,selectedModel:{provider:o,modelId:c},runId:t})}catch(e){w(!1),g(e?.message||`Template installation failed`),console.error(`Template installation failed`,e)}}},handleVariableChange:e=>{let{name:t,value:n}=e.target;n.trim()===``?p(e=>[...e,t]):p(e=>e.filter(e=>e!==t)),d(e=>({...e,[t]:n}))},isLoadingEnvVars:j||N,isInstalling:F,defaultModelProvider:o,defaultModelId:c,onModelUpdate:async e=>(s(e.provider),l(e.modelId),{message:`Model updated successfully`})})]})]})})]})}var OLi=e=>e.threadId;function kLi(e,t){return`traces`in e?{traces:{...e.traces,to:t}}:{threads:{...e.threads,to:t}}}var ALi=e=>`traces`in e?e.traces:e.threads;function jLi(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 MLi({query:e,rolling:t,autoRefetch:n=!0,limit:r,enabled:i=!0}){let a=Y(),{anchorTo:o,reanchor:s}=vIi(e),c=(0,G.useMemo)(()=>o?{...e,timeRange:kLi(e.timeRange,o)}:e,[e,o]),l=k$r({query:c,limit:r,enabled:i,queryOptions:mIi}),{headRows:u}=bIi({queryKey:[`threads`,e],fetchHead:async t=>(await a.queryTraceThreads({...e,timeRange:kLi(e.timeRange,t),orderBy:[{field:`endedAt`,direction:`desc`}],page:{limit:50}})).threads,getId:OLi,getEndedAt:e=>e.endedAt,since:Date.parse(ALi(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&&SIi(f,u,{getId:OLi,compare:jLi(d),hasNextPage:l.hasNextPage}),[f,u,d,l.hasNextPage]);return{...l,threads:p}}function NLi(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 PLi=[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`],FLi=[];function ILi(){let{data:e}=r5(),t=e?.capabilities.traceQueryTimeToFirstChunk??!1,n=e?.capabilities.traceQueryTimeToFirstToken??!1,{data:r=FLi}=_8(),{data:i=FLi}=v8();return(0,G.useMemo)(()=>[P5r,...tli({withTimeToFirstChunk:t,withTimeToFirstToken:n,entityNames:r,environments:i})],[t,n,r,i])}function LLi({tokens:e,groups:t,onFiltersChange:n}){let r=(0,G.useMemo)(()=>u0r(e),[e]),i=(0,G.useMemo)(()=>{let e=p0r([],t);return{...e,nodes:[f5,...r,...e.nodes]}},[r,t]),a=(0,G.useCallback)(e=>{let t=h0r({...e,nodes:e.nodes.filter(e=>s8(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(s8);a({...i,nodes:[...n,o,...s]})},[r,i,a])}}var RLi=e=>e;function zLi({datePreset:e,dateFrom:t,dateTo:n,minDate:r,tokens:i,groups:a,onDatePresetChange:o,onDateChange:s,onDateRangeChange:c,onFiltersChange:l,disabled:u}){let d=ILi(),{filterBarValue:f,onFilterBarChange:p}=LLi({tokens:i,groups:a,onFiltersChange:l});return(0,K.jsxs)(p5,{fields:d,operators:R1r,value:f,onValueChange:p,createItemId:RLi,maxDepth:3,"aria-label":`Thread filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(p5.Chips,{renderChip:i=>i.fieldId===`timeRange`?(0,K.jsx)(p5.TimeRange,{preset:e,onPresetChange:o,dateFrom:t,dateTo:n,minDate:r,onDateChange:s,onDateRangeChange:c,disabled:u,presets:PLi,defaultPreset:a5.datePreset}):(0,K.jsx)(p5.Chip,{item:i})}),(0,K.jsx)(p5.Input,{placeholder:`Filter threads`})]})}function BLi({selectedThreadId:e,onSelectedThreadChange:t,onOpenScore:n,urlState:r}){let i=gIi(r),{timeRange:a,tokens:o,groups:s,sort:c}=i,l=i5().enabled,u=N6r().enabled,d=Dsi({scope:`threads`}),{data:f,isLoading:p}=r5(),m=f?.capabilities.traceQueryTimeToFirstChunk??!1,h=f?.capabilities.traceQueryTimeToFirstToken??!1,g=(0,G.useMemo)(()=>p?d.preferences:Y3r(d.preferences,{withTimeToFirstChunk:m,withTimeToFirstToken:h}),[d.preferences,p,m,h]),{threads:_,hasNextPage:v,isFetchingNextPage:y,setEndOfListElement:b,isLoading:x,isError:S,error:C}=MLi({query:(0,G.useMemo)(()=>{let e=ili(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(NLi),[_]),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)(y6r,{toolbar:(0,K.jsxs)(K.Fragment,{children:[r&&(0,K.jsx)(rui,{page:`threads`,...r,columns:d}),(0,K.jsxs)(jq,{children:[(0,K.jsx)(jq.Start,{children:(0,K.jsx)(zLi,{datePreset:i.datePreset,dateFrom:i.dateFrom,dateTo:i.dateTo,tokens:o,groups:s,onDatePresetChange:i.onDatePresetChange,onDateChange:i.onDateChange,onDateRangeChange:i.onDateRangeChange,onFiltersChange:i.onFiltersChange,disabled:x})}),(0,K.jsx)(jq.End,{children:(0,K.jsx)(I6r,{scope:`threads`,value:d.preferences,onChange:d.setPreferences})})]})]}),error:S?(0,K.jsx)(Z8,{error:C,resource:`threads`,errorTitle:`Failed to load threads`}):void 0,empty:D?(0,K.jsx)(D3r,{resource:`threads`,datePreset:i.datePreset,dateFrom:i.dateFrom,dateTo:i.dateTo}):void 0,children:(0,K.jsx)(Bti,{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)(fsi,{open:!!e,threadId:e??``,depth:1,closeLabel:`Close`,withQueryTrace:l,withFeedback:u,onOpenScore:n,onClose:()=>t(void 0)})]})}function VLi(){let{enabled:e,isLoading:t}=D6r(),n=kb(),[r,i]=Hb();return(0,K.jsx)(pIi,{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)(BLi,{urlState:{searchParams:r,setSearchParams:i},selectedThreadId:OIi(r),onSelectedThreadChange:e=>i(t=>kIi(t,e),{replace:!0}),onOpenScore:(e,t)=>n(kq(e,t))})})}var HLi=()=>(0,K.jsx)(RC,{titleSlot:`No Workflows yet`,descriptionSlot:(0,K.jsxs)(K.Fragment,{children:[`Mastra workflows are not configured yet. `,(0,K.jsx)(`br`,{}),`More information in the documentation.`]}),actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/docs/workflows/overview`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(Br,{}),children:`Workflows documentation`}),variant:`fill`});function ULi(e,t,n){return yQ(e,t,{name:e=>e.name,running:e=>n[e.id]?.running??0,suspended:e=>n[e.id]?.suspended??0,steps:e=>Object.keys(e.steps??{}).length})}function WLi(e){return Object.keys(e.steps??{}).filter(t=>e.allSteps?.[t]?.isWorkflow)}function GLi(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 KLi(e,t,n){let r=GLi(t),i=[],a=(e,o,s,c,l,u)=>{let d=WLi(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 qLi=`auto 24rem minmax(0, 1fr) auto auto auto`;function JLi({guides:e,isLastChild:t}){return(0,K.jsxs)(`span`,{"aria-hidden":!0,className:`-my-6 flex shrink-0 self-stretch`,children:[e.map((e,t)=>(0,K.jsx)(`span`,{className:m(`w-6`,e&&`border-l border-border`)},t)),(0,K.jsxs)(`span`,{className:`relative w-6`,children:[(0,K.jsx)(`span`,{className:m(`absolute top-0 left-0 border-l border-border`,t?`h-1/2`:`h-full`)}),(0,K.jsx)(`span`,{className:`absolute top-1/2 left-0 w-3.5 border-b border-border`})]})]})}function YLi({row:e,isExpanded:t,onToggle:n}){let r=e.kind===`workflow`&&e.nestedIds.length>0,i=e.kind===`workflow`?e.workflow.name:e.stepId;return(0,K.jsx)(`div`,{className:`flex items-center pl-5`,children:r?(0,K.jsx)(`button`,{type:`button`,"aria-expanded":t,"aria-label":`${t?`Collapse`:`Expand`} nested workflows of ${i}`,className:m(ZC,`relative grid size-5 shrink-0 place-items-center before:absolute before:-inset-1.5 before:content-['']`),onClick:e=>{e.stopPropagation(),n()},children:(0,K.jsx)(y,{direction:`right`,className:`size-4`})}):(0,K.jsx)(`span`,{className:`size-5 shrink-0`,"aria-hidden":!0})})}var XLi=e=>e.stopPropagation();function ZLi({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 QLi({row:e,isExpanded:t,onToggle:n,runCount:r,rowProps:i}){let{paths:a,Link:o}=_l(),s=(0,G.useRef)(null),{workflow:c,nestedIds:l}=e,u=fY(c.name,50),d=fY(c.description??``,200),f=Object.keys(c.steps??{}).length,p=r?.running??0,m=r?.suspended??0,h=l.length>0;return(0,K.jsxs)(Z.RowWrapper,{...i,onSelectRow:()=>s.current?.click(),children:[(0,K.jsx)(YLi,{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:XLi,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)(JLi,{guides:e.guides,isLastChild:e.isLastChild}):null,(0,K.jsx)(`span`,{className:`truncate`,children:u}),c.origin===`dynamic`?(0,K.jsx)(bw,{size:`xs`,variant:`blue`,title:`Registered via the dynamic-workflows API`,children:`Dynamic`}):null,h?(0,K.jsxs)(T,{as:`span`,variant:`body-sm`,tone:`muted`,title:`Nested workflows: ${l.join(`, `)}`,className:`inline-flex shrink-0 items-center gap-1`,children:[(0,K.jsx)(Rc,{"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)(Po,{"aria-hidden":!0,className:`size-3.5`}),m]}):``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:f||``})]})]})}function $Li({workflows:e,isLoading:t,search:n=``,sort:r,onSortChange:i,requestContext:a}){let[o,s]=(0,G.useState)(new Set),c=xMt({requestContext:a}),l=(0,G.useMemo)(()=>Object.entries(e).map(([e,t])=>({...t,id:e})),[e]),u=(0,G.useMemo)(()=>{let e=n.toLowerCase();return l.filter(t=>t.name?.toLowerCase().includes(e)||t.description?.toLowerCase().includes(e))},[l,n]),d=(0,G.useMemo)(()=>ULi(u,r,c),[u,r,c]),f=(0,G.useMemo)(()=>KLi(d,e,o),[d,e,o]),p=(0,G.useMemo)(()=>{let e=new Map;for(let t of f)t.kind===`workflow`&&e.set(t.pathKey,e.size);return e},[f]),{containerRef:h,getRowProps:g}=_Q({count:p.size,global:!0}),v=e=>{s(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})};return t?(0,K.jsx)(NU,{columns:qLi,fit:`container`}):(0,K.jsxs)(Z,{columns:qLi,fit:`container`,scrollRef:h,children:[(0,K.jsxs)(Z.Top,{children:[(0,K.jsx)(Z.TopCell,{children:(0,K.jsx)(`span`,{className:`sr-only`,children:`Expand`})}),(0,K.jsx)(ZLi,{sortKey:`name`,sort:r,onSortChange:i,children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`Description`}),(0,K.jsx)(ZLi,{sortKey:`running`,sort:r,onSortChange:i,children:`Running`}),(0,K.jsx)(ZLi,{sortKey:`suspended`,sort:r,onSortChange:i,children:`Pending input`}),(0,K.jsx)(ZLi,{sortKey:`steps`,sort:r,onSortChange:i,children:`Number of steps`})]}),f.length===0&&n?(0,K.jsx)(Z.NoMatch,{message:`No Workflows match your search`}):null,f.map(e=>{let t=o.has(e.pathKey),n=()=>v(e.pathKey);return e.kind===`unregistered`?(0,K.jsxs)(Z.RowStatic,{className:`gap-0 px-0`,children:[(0,K.jsx)(YLi,{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)(JLi,{guides:e.guides,isLastChild:e.isLastChild}),(0,K.jsx)(`span`,{className:`truncate`,children:fY(e.stepId,50)}),(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{render:(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`muted`}),role:`note`,tabIndex:0,className:m(`shrink-0 rounded-sm`,_),children:`not registered`}),(0,K.jsx)(CC,{className:`max-w-72`,children:`Runs as a step of its parent workflow. Add it to the workflows of your Mastra instance to open, run, and inspect it on its own page.`})]})]})}),(0,K.jsx)(Z.DescriptionCell,{children:fY(e.description??``,200)}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:``})]})]},`workflow-${e.pathKey}`):(0,K.jsx)(QLi,{row:e,isExpanded:t,onToggle:n,runCount:c[e.workflow.id],rowProps:g(p.get(e.pathKey)??-1)},`workflow-${e.pathKey}`)})]})}var G9=[sF(`/workflows`)];function eRi(){let{data:e,isLoading:t,error:n}=sP(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)();return n&&JP(n)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:G9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(jU,{variant:`fill`})]}):n&&YP(n)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:G9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(AU,{variant:`fill`,resource:`workflows`})]}):n?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:G9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load workflows`,descriptionSlot:n.message})]}):Object.keys(e||{}).length===0&&!t?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:G9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(HLi,{})]}):(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:G9}),actionRow:(0,K.jsxs)(jq,{children:[(0,K.jsx)(jq.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(zU,{onSearch:i,label:`Filter workflows`,placeholder:`Filter by name or description`})})}),(0,K.jsx)(jq.End,{children:(0,K.jsx)(X,{render:(0,K.jsx)(Vb,{to:`/workflows/schedules`}),variant:`primary`,icon:(0,K.jsx)(Nn,{}),children:`Schedules`})})]}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)($Li,{workflows:e||{},isLoading:t,search:r,sort:a,onSortChange:(e,t)=>o({key:t,direction:e})})]})}var tRi={active:`bg-success-indicator`,paused:`bg-info-indicator`,completed:`bg-muted-foreground`},nRi={active:`text-success-indicator`,paused:`text-info-indicator`,completed:`text-muted-foreground`},rRi=({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 ${tRi[e]}`,"aria-hidden":!0}),(0,K.jsx)(T,{as:`span`,variant:`caption`,className:nRi[e],children:e})]});function iRi({status:e}){let{icon:t,color:n}=aRi(e);return(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 whitespace-nowrap ${n}`,children:[(0,K.jsx)(`span`,{className:`inline-flex shrink-0 items-center`,"aria-hidden":!0,children:t}),(0,K.jsx)(T,{as:`span`,variant:`caption`,children:e})]})}function aRi(e){switch(e){case`success`:return{icon:(0,K.jsx)(Bn,{size:14}),color:`text-success-indicator`};case`failed`:return{icon:(0,K.jsx)(Hc,{size:14}),color:`text-destructive-foreground`};case`running`:return{icon:(0,K.jsx)(Qc,{}),color:`text-muted-foreground`};case`suspended`:return{icon:(0,K.jsx)(Zn,{size:14}),color:`text-info-indicator`};case`canceled`:return{icon:(0,K.jsx)(tr,{size:14}),color:`text-muted-foreground`};case`pending`:case`waiting`:return{icon:(0,K.jsx)(lr,{size:14}),color:`text-muted-foreground`};default:return{icon:null,color:`text-muted-foreground`}}}var oRi=`auto auto auto auto 1fr`,sRi=3e4,cRi=3e5;function lRi({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:i,setEndOfListElement:a}){let{Link:o,paths:s}=_l(),c=e=>!!(n&&e.runId&&e.outcome!==`failed`),l=e.filter(c).length,{containerRef:u,getRowProps:d}=_Q({count:l}),f=-1;return t?(0,K.jsx)(NU,{columns:oRi}):e.length===0?(0,K.jsx)(T,{variant:`body`,tone:`muted`,className:`p-4`,children:`No trigger history yet.`}):(0,K.jsxs)(Z,{columns:oRi,className:`min-w-0`,scrollRef:u,children:[(0,K.jsxs)(Z.Top,{children:[(0,K.jsx)(Z.TopCell,{children:`Run`}),(0,K.jsx)(Z.TopCell,{children:`Status`}),(0,K.jsx)(Z.TopCell,{children:`Started`}),(0,K.jsx)(Z.TopCell,{children:`Duration`}),(0,K.jsx)(Z.TopCell,{children:` `})]}),e.map(e=>{let t=e.actualFireAt-e.scheduledFireAt,r=xw(t,{signed:!0}),i=e.outcome===`failed`,a=i?e.error:e.run?.error,l=Math.abs(t),u=!i&&l>sRi&&l<=cRi,p=`${e.scheduleId}-${e.runId}-${e.actualFireAt}`,m=c(e);m&&(f+=1);let h=(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,tone:m?`ink`:`muted`,className:`whitespace-nowrap`,children:e.runId}),g=(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Z.Cell,{children:h}),(0,K.jsx)(Z.Cell,{children:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[i?(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`inline-flex items-center gap-1.5 whitespace-nowrap text-destructive-foreground`,children:[(0,K.jsx)(wc,{size:14}),`publish failed`]}):e.run?(0,K.jsx)(iRi,{status:e.run.status}):(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`inline-flex items-center gap-1.5 whitespace-nowrap`,children:`pending`}),a?(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{asChild:!0,children:(0,K.jsx)(`span`,{className:`inline-flex text-destructive-foreground`,children:(0,K.jsx)(wc,{size:14})})}),(0,K.jsx)(CC,{children:a})]}):null]})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-2 whitespace-nowrap`,children:[e.actualFireAt?(0,K.jsx)(jA,{value:e.actualFireAt}):`—`,u?(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{asChild:!0,children:(0,K.jsx)(`span`,{className:`inline-flex text-info-indicator`,children:(0,K.jsx)(wc,{size:14})})}),(0,K.jsxs)(CC,{children:[`Published `,r,` after the scheduled fire time`]})]}):null]})}),(0,K.jsx)(Z.Cell,{children:e.run?(0,K.jsx)(T,{as:`span`,variant:`body-sm`,font:`mono`,children:xw(e.run.durationMs)||`—`}):(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`—`})}),(0,K.jsx)(Z.Cell,{children:` `})]});return m?(0,K.jsx)(Z.RowLink,{to:s.workflowRunLink(n,e.runId),LinkComponent:o,...d(f),children:g},p):(0,K.jsx)(Z.RowStatic,{children:g},p)}),(0,K.jsx)(Z.NextPageLoading,{isLoading:i,hasMore:r,setEndOfListElement:a})]})}var uRi={id:`workflow-schedules`,label:`Schedules`,icon:Nn,to:`/workflows/schedules`};function dRi({label:e,children:t}){return(0,K.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,K.jsx)(T,{variant:`meta`,tone:`muted`,className:`uppercase`,children:e}),(0,K.jsx)(`div`,{children:(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:t})})]})}function fRi(){let{scheduleId:e}=Ab(),t=[sF(`/workflows`),uRi,{id:`schedule`,label:LLt(e),icon:Nn}],{paths:n}=_l(),{data:r,error:i}=tRt({scheduleId:e,queryOptions:{enabled:!!e}}),{data:a,isLoading:o,error:s,hasNextPage:c,isFetchingNextPage:l,setEndOfListElement:u}=rRt({scheduleId:e,queryOptions:{enabled:!!e}}),d=iRt({scheduleId:e});if(i&&JP(i))return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(jU,{variant:`fill`})]});if(i&&YP(i))return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(AU,{variant:`fill`,resource:`schedules`})]});if(i)return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load schedule`,descriptionSlot:i.message})]});let f=r?.workflowId,p=r?.agentId;return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:t}),actionRow:(0,K.jsx)(jq,{children:(0,K.jsxs)(jq.End,{children:[(0,K.jsx)(X,{render:(0,K.jsx)(Vb,{to:n.schedulesLink()}),variant:`ghost`,icon:(0,K.jsx)(Rt,{}),children:`Back to schedules`}),f?(0,K.jsx)(X,{icon:(0,K.jsx)(rP,{}),render:(0,K.jsx)(Vb,{to:n.workflowLink(f)}),variant:`ghost`,children:`Open workflow`}):null,r&&r.status!==`completed`?(0,K.jsx)(X,{onClick:()=>{let e=r.status===`active`?`pause`:`resume`;d.mutate(e,{onSuccess:()=>UC.success(e===`pause`?`Schedule paused`:`Schedule resumed`),onError:e=>UC.error(e.message)})},disabled:d.isPending,"data-testid":`schedule-toggle-button`,children:r.status===`active`?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Po,{}),`Pause`]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Ho,{}),`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)(dRi,{label:p?`Agent`:`Workflow`,children:f?(0,K.jsx)(Vb,{to:n.workflowLink(f),className:`text-foreground hover:underline`,children:f}):p?(0,K.jsx)(Vb,{to:n.agentLink(p),className:`text-foreground hover:underline`,children:p}):`—`}),(0,K.jsxs)(dRi,{label:r.cron?`Cron`:`Runs at`,children:[(0,K.jsx)(T,{as:`span`,variant:`body`,font:`mono`,children:r.cron??(r.runAt?new Date(r.runAt).toLocaleString():`—`)}),r.endAt?(0,K.jsxs)(`span`,{className:`ml-2 text-caption text-muted-foreground`,children:[`until `,new Date(r.endAt).toLocaleString()]}):null,r.timezone?(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`ml-2`,children:r.timezone}):null]}),(0,K.jsx)(dRi,{label:`Status`,children:(0,K.jsx)(rRi,{status:r.status})}),(0,K.jsx)(dRi,{label:`Next fire`,children:r.nextFireAt?(0,K.jsx)(jA,{value:r.nextFireAt}):`—`})]}),(0,K.jsxs)(`div`,{className:`overflow-y-auto`,"data-testid":`schedule-triggers-panel`,children:[(0,K.jsx)(T,{variant:`body`,className:`mb-3`,children:`Trigger history`}),s?(0,K.jsx)(RC,{tone:`error`,titleSlot:`Failed to load trigger history`,descriptionSlot:s.message}):(0,K.jsx)(lRi,{triggers:a??[],isLoading:o,workflowId:f,hasNextPage:c,isFetchingNextPage:l,setEndOfListElement:u})]})]}):null]})}var pRi={target:e=>e.workflowId??e.agentId??``,status:e=>e.status,nextFireAt:e=>e.nextFireAt,lastFireAt:e=>e.lastFireAt},mRi=`minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto`;function hRi({schedules:e,isLoading:t,search:n=``,sort:r,onSortChange:i}){let{paths:a,Link:o}=_l(),s=(0,G.useMemo)(()=>{let t=n.toLowerCase();return yQ(t?e.filter(e=>e.id.toLowerCase().includes(t)||(e.workflowId??e.agentId??``).toLowerCase().includes(t)):e,r,pRi)},[e,n,r]),{containerRef:c,getRowProps:l}=_Q({count:s.length,global:!0});if(t)return(0,K.jsx)(NU,{columns:mRi});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:mRi,className:`min-w-0`,scrollRef:c,children:[(0,K.jsxs)(Z.Top,{children:[u(`target`,`Target`),(0,K.jsx)(Z.TopCell,{children:`Schedule ID`}),(0,K.jsx)(Z.TopCell,{children:`Cron`}),u(`status`,`Status`),u(`nextFireAt`,`Next fire`),u(`lastFireAt`,`Last run`)]}),s.length===0&&n?(0,K.jsx)(Z.NoMatch,{message:`No schedules match your search`}):null,s.length===0&&!n?(0,K.jsx)(Z.NoMatch,{message:`No schedules configured`}):null,s.map((e,t)=>(0,K.jsxs)(Z.RowLink,{to:a.scheduleLink(e.id),LinkComponent:o,...l(t),children:[(0,K.jsx)(Z.NameCell,{children:e.workflowId??e.agentId}),(0,K.jsx)(Z.Cell,{className:`min-w-0`,children:(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`muted`,font:`mono`,className:`block truncate`,title:e.id,children:e.id})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-2 whitespace-nowrap`,children:[(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,children:e.cron??(e.runAt?`once @ ${new Date(e.runAt).toLocaleString()}`:`—`)}),e.timezone?(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:e.timezone}):null]})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(rRi,{status:e.status})}),(0,K.jsx)(Z.Cell,{children:e.nextFireAt?(0,K.jsx)(jA,{value:e.nextFireAt}):`—`}),(0,K.jsx)(Z.Cell,{children:e.lastRun?(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-2 whitespace-nowrap`,children:[(0,K.jsx)(iRi,{status:e.lastRun.status}),e.lastFireAt?(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:(0,K.jsx)(jA,{value:e.lastFireAt})}):null]}):e.lastFireAt?(0,K.jsx)(jA,{value:e.lastFireAt}):(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`Never`})})]},e.id))]})}function gRi({workflowId:e}={}){let{data:t,isLoading:n,error:r}=uF(e?{workflowId:e}:{}),[i,a]=(0,G.useState)(``),[o,s]=(0,G.useState)();return r?(0,K.jsx)(RC,{tone:`error`,titleSlot:`Failed to load schedules`,descriptionSlot:r.message}):(0,K.jsxs)(`div`,{className:`grid h-full grid-rows-[auto_1fr] gap-4 overflow-hidden`,children:[(0,K.jsx)(`div`,{className:`max-w-120`,children:(0,K.jsx)(zU,{onSearch:a,label:`Filter schedules`,placeholder:`Filter by id or workflow`})}),(0,K.jsx)(`div`,{className:`overflow-y-auto`,children:(0,K.jsx)(hRi,{schedules:t??[],isLoading:n,search:i,sort:o,onSortChange:(e,t)=>s({key:t,direction:e})})})]})}var _Ri=[sF(`/workflows`),uRi];function vRi(){let[e]=Hb(),t=e.get(`workflowId`)??void 0,{error:n}=uF(t?{workflowId:t}:{});return n&&JP(n)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:_Ri}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(jU,{variant:`fill`})]}):n&&YP(n)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:_Ri}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(AU,{variant:`fill`,resource:`schedules`})]}):(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:_Ri}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(`div`,{className:`h-full`,children:(0,K.jsx)(gRi,{workflowId:t})})]})}var yRi={"--belt-hue":`var(--warning-indicator)`};function bRi(e){let t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function xRi(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 SRi({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:(0,K.jsxs)(`section`,{className:m(FMt,`pointer-events-auto relative isolate`),"data-testid":`workflow-suspended-steps`,"aria-label":`Step suspended`,children:[(0,K.jsxs)(`div`,{className:`max-h-[calc(100cqh-64px)] overflow-y-auto overscroll-contain rounded-[inherit]`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-3 border-b border-border bg-background px-5 py-4`,children:[(0,K.jsxs)(T,{as:`h2`,variant:`column`,tone:`ink`,className:`flex items-center gap-2`,children:[(0,K.jsx)(TC,{children:(0,K.jsx)(Zn,{})}),`Step suspended`]}),(0,K.jsx)(bw,{variant:`orange`,emphasis:`subtle`,children:`Needs input`})]}),e.map(e=>{let n=t.allSteps[e.stepId];if(!n||n.isWorkflow)return null;let i=n?.resumeSchema?Kk(lA(n.resumeSchema)):Rp(q(),kp());return(0,K.jsx)(CRi,{step:e,stepSchema:i,description:n.description,onResume:r},`${e.runId}-${e.stepId}`)})]}),(0,K.jsx)(c4e,{status:`ready`,label:`Needs input`,className:`before:hidden`,style:yRi})]})}function CRi({step:e,stepSchema:t,description:n,onResume:r}){let[i,a]=(0,G.useState)(!1),[o,s]=(0,G.useState)(!1);return(0,K.jsxs)(`div`,{className:`space-y-5 p-5 [&+&]:border-t [&+&]:border-border`,children:[(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(T,{as:`p`,variant:`subheading`,tone:`ink`,className:`break-words`,children:e.stepId}),n&&(0,K.jsx)(T,{as:`p`,variant:`caption`,tone:`muted`,children:n})]}),e.suspendPayload!==void 0&&(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsxs)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`flex items-center gap-2`,children:[(0,K.jsx)(TC,{children:(0,K.jsx)(po,{})}),`The step is asking`]}),(0,K.jsxs)(Hw,{open:i,onOpenChange:a,children:[(0,K.jsxs)(Uw,{className:m(`bg-card hover:bg-card active:bg-card shadow-raised [--field:var(--field-on-surface)] [--field-disabled:var(--field-on-surface)] [--field-rim:var(--field-rim-on-surface)]`,`flex w-full items-center justify-between gap-2 rounded-lg px-3 py-2.5`),children:[(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(TC,{children:(0,K.jsx)(y,{direction:`right`,className:`text-muted-foreground`})}),(0,K.jsx)(T,{as:`span`,variant:`body`,tone:`ink`,className:`truncate`,children:xRi(e.suspendPayload,e.stepId)})]}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`shrink-0`,children:bRi(e.suspendPayload)})]}),(0,K.jsx)(Ww,{children:(0,K.jsx)(`div`,{"data-testid":`suspended-payload`,className:`pt-2`,children:(0,K.jsx)(FT,{value:JSON.stringify(e.suspendPayload,null,2),editable:!1,className:`w-full overflow-x-auto p-2`,showCopyButton:!1})})})]})]}),(0,K.jsxs)(`div`,{className:`space-y-3`,children:[(0,K.jsxs)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`flex items-center gap-2`,children:[(0,K.jsx)(TC,{children:(0,K.jsx)(ho,{})}),`Your response`]}),(0,K.jsx)(`div`,{className:`-mx-5`,children:(0,K.jsx)(Zjt,{schema:t,isSubmitLoading:o,submitButtonLabel:`Resume`,submitButtonVariant:`primary`,submitButtonIcon:(0,K.jsx)(Ho,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:async t=>{s(!0);try{await r({stepId:e.stepId.split(`.`),runId:e.runId,resumeData:t})}catch(e){UC.error(e instanceof Error?e.message:`Error resuming workflow`)}finally{s(!1)}}})})]})]})}function wRi({hidden:e,requestContext:t,canResume:n}){let{result:r,workflow:i,runId:a,isStreamingWorkflow:o}=(0,G.useContext)(gw),s=Yvt(r,a),c=eyt(t),l=r?.status===`suspended`&&s.length>0&&!o;return!i||!l||!n?null:(0,K.jsx)(`div`,{hidden:e,"data-testid":`workflow-suspended-overlay`,className:`pointer-events-none absolute top-12 right-2 z-30 w-95 max-w-[calc(100%-16px)] animate-in duration-300 fade-in-0 slide-in-from-top-2 motion-reduce:animate-none`,children:(0,K.jsx)(SRi,{suspendedSteps:s,workflow:i,isStreaming:o,onResume:c})},a)}var TRi={success:{label:`Completed`,icon:Bn},failed:{label:`Failed`,icon:ir},suspended:{label:`Needs input`,icon:Po},waiting:{label:`Waiting`,icon:vc},paused:{label:`Paused`,icon:Po},skipped:{label:`Skipped`,icon:Ps},running:{label:`Running`,icon:Da},canceled:{label:`Canceled`,icon:tr}},ERi={label:`Status unavailable`,icon:Cee};function DRi({row:e,isSelected:t,isHovered:n,onSelectStep:r,onHoverStep:i,onOpenInput:a,onOpenOutput:o}){let s=Object.hasOwn(TRi,e.status)?TRi[e.status]:ERi,c=s.icon,l=Rbt(e.status),u=e.stepId.slice(0,e.stepId.lastIndexOf(`.`)),d=e.isNestedEntry?e.stepId.slice(e.stepId.lastIndexOf(`.`)+1):e.stepId;return(0,K.jsxs)(`div`,{"data-testid":`workflow-timeline-row`,"data-workflow-step-key":e.stepId,onMouseEnter:()=>!e.isNestedEntry&&i(e.stepId),onMouseLeave:()=>!e.isNestedEntry&&i(null),className:m(`grid grid-cols-[minmax(130px,1fr)_minmax(64px,1fr)_56px_64px] items-center gap-3 rounded-md px-2 py-1`,`@max-[540px]/workflow-timeline:grid-cols-[minmax(0,1fr)_48px_64px] @max-[540px]/workflow-timeline:gap-x-1.5 @max-[540px]/workflow-timeline:gap-y-1 @max-[540px]/workflow-timeline:py-2`,(t||n)&&`bg-fill-subtle`),children:[(0,K.jsxs)(`button`,{type:`button`,"aria-disabled":e.isNestedEntry,"aria-pressed":t,onClick:()=>{e.isNestedEntry||r(e.stepId)},title:e.stepId,className:m(`text-foreground`,`flex min-h-9 min-w-0 cursor-pointer items-center gap-2.5 text-left focus-visible:rounded-sm aria-disabled:cursor-default`,_),children:[(0,K.jsx)(`span`,{"aria-label":s.label,className:m(`grid size-6 flex-none place-items-center rounded-md border border-border bg-background`,zbt[l]),children:(0,K.jsx)(c,{"aria-hidden":!0,className:m(`size-3.5`,e.status===`running`&&`motion-safe:animate-spin`)})}),(0,K.jsxs)(`span`,{className:`min-w-0`,children:[(0,K.jsx)(T,{as:`span`,variant:`meta`,className:`block truncate`,children:d}),e.isNestedEntry&&(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`flex min-w-0 items-center gap-1`,children:[(0,K.jsx)(Cr,{"aria-hidden":!0,className:`size-3 shrink-0`}),(0,K.jsx)(`span`,{className:`truncate`,children:u})]})]})]}),(0,K.jsx)(`div`,{className:`relative h-5 min-w-0 overflow-hidden rounded-sm bg-muted @max-[540px]/workflow-timeline:col-span-full @max-[540px]/workflow-timeline:row-start-2 @max-[540px]/workflow-timeline:ml-[34px]`,"aria-hidden":!0,children:e.timing&&(0,K.jsx)(`div`,{"data-testid":`workflow-timeline-bar`,"data-offset":e.timing.offsetPct,"data-width":e.timing.widthPct,className:m(`absolute top-0 h-full min-w-0.5 rounded-sm`,Bbt[l]),style:{left:`${e.timing.offsetPct}%`,width:`${e.timing.widthPct}%`}})}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`text-right whitespace-nowrap`,title:e.timing&&e.spansSuspension?`Includes time spent suspended waiting for input`:void 0,children:e.timing?(0,K.jsx)(T,{as:`span`,variant:`meta`,font:`mono`,children:xw(e.timing.durationMs)}):(0,K.jsx)(`span`,{"aria-label":`Timing unavailable`,children:`—`})}),(0,K.jsxs)(`div`,{className:`flex items-center`,children:[(0,K.jsx)(X,{type:`button`,variant:`ghost`,size:`icon-sm`,tooltip:`View step input`,disabled:e.step.input===void 0,onClick:t=>a(e,t.currentTarget),children:(0,K.jsx)(Mt,{})}),(0,K.jsx)(X,{type:`button`,variant:`ghost`,size:`icon-sm`,tooltip:`View step output`,disabled:e.step.output===void 0,onClick:t=>o(e,t.currentTarget),children:(0,K.jsx)(Kt,{})})]})]})}var ORi=e=>e.includes(`.`),kRi=e=>e===`input`||e.endsWith(`.input`),ARi=1;function jRi(e,t){let n=Ubt(e),r=n?.isLive?Math.max(t,n.start):n?.end;return{span:n&&r!==void 0?{start:n.start,end:r}:void 0,isLive:n?.isLive??!1,spansSuspension:n?.spansSuspension??!1}}function MRi(e,t){let n=Object.entries(e).filter(([e])=>!kRi(e)).map(([e,n])=>({stepId:e,step:n,...jRi(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,ARi),100-t)}}return{stepId:e,step:t,status:OA(t)?`suspended`:t.status,timing:s,spansSuspension:a,isRunning:r,isNestedEntry:ORi(e)}})}function NRi(){let{steps:e}=z$(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:i}=hw(),[a,o]=(0,G.useState)(()=>Date.now()),[s,c]=(0,G.useState)(!0),[l,u]=(0,G.useState)(!1),{showData:d}=lP(),f=(0,G.useRef)(null),p=MRi(e,a),h=p.some(e=>e.isRunning);return H1e(f,{enabled:h&&!s}),(0,G.useEffect)(()=>{if(!h||s)return;let e=setInterval(()=>o(Date.now()),100);return()=>clearInterval(e)},[h,s]),p.length===0?null:(0,K.jsx)(`div`,{"data-testid":`workflow-timeline`,className:`relative z-20 shrink-0 px-2 pb-2`,children:(0,K.jsxs)(Hw,{open:!s,onOpenChange:e=>c(!e),className:m(Wb,`@container/workflow-timeline pointer-events-auto overflow-hidden rounded-xl`),children:[(0,K.jsxs)(`div`,{className:`flex items-center`,children:[(0,K.jsxs)(Uw,{className:`flex min-h-11 min-w-0 flex-1 items-center gap-2 px-3.5 py-2.5 text-caption text-foreground hover:bg-fill-subtle`,"aria-label":s?`Expand timeline`:`Collapse timeline`,children:[(0,K.jsx)(`span`,{children:(0,K.jsx)(zn,{"aria-hidden":!0,className:`size-4 text-muted-foreground`})}),(0,K.jsx)(`span`,{children:`Timeline`}),(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,children:[p.length,` events`]}),(0,K.jsx)(`span`,{className:`ml-auto`,children:(0,K.jsx)(y,{direction:`right`,className:`size-4`})})]}),!s&&(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:l?`Restore timeline height`:`Enlarge timeline`,"aria-pressed":l,onClick:()=>u(!l),className:`mr-2 shrink-0`,children:l?(0,K.jsx)(lee,{}):(0,K.jsx)(hee,{})})]}),(0,K.jsx)(Ww,{children:(0,K.jsx)(`div`,{ref:f,"data-testid":`workflow-timeline-list`,className:m(`overflow-auto overscroll-contain px-1.5 pb-1.5`,l?`max-h-[min(720px,calc(100dvh-112px))]`:`max-h-[min(320px,40dvh)]`),children:p.map(e=>(0,K.jsx)(DRi,{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 PRi=({workflowId:e,workflow:t,isLoading:n})=>{let[r]=mw(`workflow`,e),{canExecute:i,isLoading:a}=KC(),{stepDetail:o}=lP(),s=fE(),c=o?.type===`data`,l=(0,K.jsxs)(`div`,{className:`[container-type:size] relative h-full min-h-0`,children:[(0,K.jsx)(Mmr,{workflowId:e,workflow:t,isLoading:n,requestContext:r}),(0,K.jsx)(wRi,{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)(V$,{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)(NRi,{})})]});return s&&o&&!c?(0,K.jsx)(`div`,{className:`h-full min-h-0 overflow-hidden`,children:(0,K.jsx)(V$,{requestContext:r})}):(0,K.jsxs)(`div`,{className:`relative h-full min-h-0`,children:[l,(0,K.jsxs)(F6,{className:`pointer-events-none absolute inset-0 z-30 min-h-0 w-full min-w-0 p-2`,children:[(0,K.jsx)(P6,{id:`workflow-graph`,className:`pointer-events-none min-w-0`}),o&&!c&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(I6,{className:`pointer-events-auto`}),(0,K.jsx)(P6,{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)(V$,{requestContext:r})})})]})]})]})},FRi=()=>{let{workflowId:e}=Ab(),{data:t,isLoading:n,error:r}=cP({workflowId:e,requestContext:mw(`workflow`,e)[0],queryOptions:{enabled:!!e}});return r&&JP(r)?(0,K.jsx)(jU,{variant:`fill`}):r&&YP(r)?(0,K.jsx)(AU,{variant:`fill`,resource:`workflows`}):(0,K.jsx)(PRi,{workflowId:e,workflow:t??void 0,isLoading:n})};function IRi(){let{workflowId:e}=Ab(),{error:t}=uF(e?{workflowId:e}:{});if(!e)return null;let n;return n=t&&JP(t)?(0,K.jsx)(jU,{variant:`fill`}):t&&YP(t)?(0,K.jsx)(AU,{variant:`fill`,resource:`schedules`}):(0,K.jsx)(`div`,{className:`h-full`,children:(0,K.jsx)(gRi,{workflowId:e})}),(0,K.jsxs)(uw,{children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),n]})}function LRi(){let{workflowId:e}=Ab();return e?(0,K.jsx)(Uui,{scopedEntityId:e,scopedEntityType:kh.WORKFLOW_RUN}):null}var RRi=(0,G.createContext)(null);function K9(){let e=(0,G.useContext)(RRi);if(!e)throw Error(`Workspace components must be rendered inside <Workspace.Root>`);return e}var zRi=e=>e?.status;function BRi(e,t){return JP(e)?`Your session has expired. Sign in again to continue.`:YP(e)?`You don't have permission to access this.`:XP(e)?`This path no longer exists.`:zRi(e)===501?`This workspace does not support this operation.`:t}function VRi({error:e,fallback:t,className:n}){return(0,K.jsx)(EA,{variant:`destructive`,className:n,children:(0,K.jsx)(EA.Message,{children:BRi(e,t)})})}var HRi=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;function URi(e){let t=HRi.exec(e);return t?{frontmatter:t[1]??``,body:e.slice(t[0].length)}:{frontmatter:null,body:e}}function WRi({content:e}){let{frontmatter:t,body:n}=URi(e);return(0,K.jsxs)(K.Fragment,{children:[t!==null&&(0,K.jsx)(`div`,{"data-testid":`workspace-frontmatter`,className:`border-b border-border`,children:(0,K.jsx)(pY,{code:t,lang:`yaml`,overflow:`wrap`,className:`rounded-none border-0 bg-transparent [&_pre]:p-4`})}),(0,K.jsx)(`div`,{className:`p-4`,children:(0,K.jsx)(xX,{children:n})})]})}function GRi(){let{activeFilePath:e}=K9();return e?(0,K.jsx)(T,{as:`span`,variant:`body-sm`,font:`mono`,tone:`muted`,className:`truncate`,"data-testid":`workspace-file-path`,children:e}):null}function KRi({path:e,content:t,mimeType:n}){return oVn(e,n)?(0,K.jsx)(`div`,{className:`flex justify-center p-4`,children:(0,K.jsx)(`img`,{src:`data:${n||`image/png`};base64,${t}`,alt:e.split(`/`).pop(),className:`max-w-full object-contain`})}):sVn(e,n)?(0,K.jsx)(`div`,{className:`flex justify-center p-4`,children:(0,K.jsx)(`video`,{controls:!0,"aria-label":e.split(`/`).pop(),className:`max-w-full`,children:(0,K.jsx)(`source`,{src:`data:${lVn(e,n)};base64,${t}`,type:lVn(e,n)})})}):uVn(e)?(0,K.jsx)(WRi,{content:t}):(0,K.jsx)(pY,{code:t,lang:U2e(e),overflow:`scroll`,className:`rounded-none border-0 bg-transparent [&_pre]:p-4`})}function qRi({renderPreview:e}){let{workspaceId:t,activeFilePath:n}=K9(),{data:r,isLoading:i,error:a}=TVn({workspaceId:t,path:n,queryOptions:{enabled:!!n}});if(!n)return null;if(i)return(0,K.jsxs)(`div`,{"aria-busy":`true`,className:`flex flex-col gap-2 p-4`,children:[(0,K.jsx)(dw,{className:`h-4 w-1/2`}),(0,K.jsx)(dw,{className:`h-4 w-5/6`}),(0,K.jsx)(dw,{className:`h-4 w-2/3`})]});if(!r)return(0,K.jsx)(VRi,{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)(KRi,{...o})}var JRi=(e,t)=>e===`.`?t:`${e}/${t}`,YRi=e=>e.split(`/`).slice(0,-1).map((e,t,n)=>n.slice(0,t+1).join(`/`)),XRi=e=>{let t=e.lastIndexOf(`/`);return t===-1?`.`:e.slice(0,t)};function ZRi({labeled:e=!1}={}){let{workspaceId:t,onCreateDirectory:n,isReadOnly:r}=K9(),i=dy(),[a,o]=(0,G.useState)(!1),[s,c]=(0,G.useState)(``),[l,u]=(0,G.useState)(!1);if(!n||r(`.`))return null;let d=s.trim().replace(/^\.?\/+|\/+$/g,``),f=async()=>{if(d){u(!0);try{await n(d),await i.invalidateQueries({queryKey:[`workspace`,t,`fs`,`list`,XRi(d)]}),o(!1),c(``)}catch{}finally{u(!1)}}};return(0,K.jsxs)(K.Fragment,{children:[e?(0,K.jsx)(X,{variant:`ghost`,icon:(0,K.jsx)(xi,{}),onClick:()=>o(!0),children:`New folder`}):(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`New folder`,onClick:()=>o(!0),children:(0,K.jsx)(xi,{})}),(0,K.jsx)(_E,{open:a,onOpenChange:o,pending:l,children:(0,K.jsx)(vE,{size:`sm`,children:(0,K.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),f()},children:[(0,K.jsx)(yE,{children:(0,K.jsx)(SE,{children:`New folder`})}),(0,K.jsx)(xE,{children:(0,K.jsx)(ZM,{autoFocus:!0,"aria-label":`Folder path`,placeholder:`docs/guides`,value:s,onChange:e=>c(e.target.value)})}),(0,K.jsxs)(bE,{children:[(0,K.jsx)(wE,{children:`Cancel`}),(0,K.jsx)(X,{type:`submit`,variant:`primary`,disabled:!d||l,children:`Create`})]})]})})})]})}function QRi(e){return`${e.topSource}/${e.name}`}function $Ri(e){let t=mVn(e.topSource,e.name);return t?`${t.owner}/${t.repo}/${e.name}`:null}function ezi({open:e,onOpenChange:t,workspaceId:n,onInstall:r,isInstalling:i,installedSkillIds:a=[],installedSkillNames:o=[],writableMounts:s,installedSkillPaths:c}){let[l,u]=(0,G.useState)(``),[d,f]=(0,G.useState)(null),[p,h]=(0,G.useState)(),g=s?.some(e=>e.path===p)?p:s?.[0]?.path,{data:_,isLoading:v}=fVn({workspaceId:n,queryOptions:{enabled:!!n}}),y=dVn({workspaceId:n}),b=(0,G.useMemo)(()=>d?.topSource?mVn(d.topSource,d.name):null,[d]),x=(0,G.useMemo)(()=>!b||!d?null:`https://skills.sh/${b.owner}/${b.repo}/${d.name}`,[b,d]),{data:S,isLoading:C}=pVn({workspaceId:n,owner:b?.owner,repo:b?.repo,skillPath:d?.name,queryOptions:{enabled:!!n&&!!b&&!!d}}),w=Tw(e=>{e.trim().length>=2&&y.mutate(e)},300),E=(0,G.useCallback)(e=>{u(e),w(e)},[w]),D=(0,G.useMemo)(()=>l.trim().length>=2?y.data?.skills??[]:_?.skills??[],[l,y.data,_]),O=y.isPending,k=l.trim().length>=2,A=(0,G.useMemo)(()=>{if(!d)return!1;let e=$Ri(d);return!!(e&&a.includes(e)||o.includes(d.name))},[d,a,o]),j=(0,G.useCallback)(()=>{d&&b&&r({repository:`${b.owner}/${b.repo}`,skillName:d.name,mount:s&&s.length>1?g:void 0})},[d,b,r,s,g]),M=(0,G.useCallback)(e=>{e||(u(``),f(null),h(void 0)),t(e)},[t]);return(0,K.jsx)(_E,{open:e,onOpenChange:M,pending:i,children:(0,K.jsxs)(vE,{size:`xl`,className:`h-[80vh]`,children:[(0,K.jsxs)(yE,{children:[(0,K.jsx)(SE,{children:`Add Skill`}),(0,K.jsx)(CE,{children:`Search and install skills from the community registry`})]}),(0,K.jsxs)(xE,{layout:`fill`,children:[(0,K.jsx)(RU,{label:`Search skills`,placeholder:`Search skills`,value:l,onValueChange:E}),(0,K.jsxs)(`div`,{className:`flex min-h-0 flex-1 gap-4`,children:[(0,K.jsxs)(`div`,{className:`flex min-h-0 w-1/2 flex-col`,children:[(0,K.jsx)(T,{as:`p`,variant:`eyebrow`,tone:`muted`,className:`mb-2`,children:k?`Search Results`:`Popular Skills`}),(0,K.jsx)(lw,{className:`flex-1 rounded-lg border border-border`,children:(0,K.jsx)(cw,{className:!v&&!O&&D.length===0?`flex flex-col [&>div]:flex [&>div]:flex-1 [&>div]:flex-col`:void 0,children:v||O?(0,K.jsx)(`div`,{className:`flex items-center justify-center py-5`,children:(0,K.jsx)(Da,{className:`size-6 animate-spin text-muted-foreground`})}):D.length===0?(0,K.jsxs)(`div`,{className:`flex flex-1 flex-col items-center-safe justify-center-safe py-5 text-muted-foreground`,children:[(0,K.jsx)(tr,{className:`mb-2 size-8`}),(0,K.jsx)(T,{children:k?`No skills found`:`No skills available`})]}):(0,K.jsx)(`div`,{className:`space-y-1 p-2`,children:D.map(e=>{let t=QRi(e),n=$Ri(e),r=n&&a.includes(n)||o.includes(e.name),i=d?QRi(d):null;return(0,K.jsx)(`button`,{onClick:()=>f(e),className:m(`w-full rounded-md px-3 py-2 text-left`,`hover:bg-fill-subtle`,i===t&&`border border-border-strong bg-fill-hover`),children:(0,K.jsxs)(`div`,{className:`flex items-start justify-between gap-2`,children:[(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(T,{as:`span`,variant:`subheading`,tone:`ink`,className:`truncate`,children:e.name}),r&&(0,K.jsxs)(T,{as:`span`,variant:`meta`,className:`inline-flex items-center gap-1 rounded bg-info-subtle px-1.5 py-0.5 text-info-subtle-foreground`,children:[(0,K.jsx)(Bn,{className:`size-2.5`}),`Installed`]})]}),(0,K.jsx)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`truncate`,children:e.topSource})]}),(0,K.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 text-muted-foreground`,children:[(0,K.jsx)(Dr,{className:`size-3`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,children:e.installs.toLocaleString()})]})]})},t)})})})})]}),(0,K.jsxs)(`div`,{className:`flex min-h-0 w-1/2 flex-col`,children:[(0,K.jsx)(T,{as:`p`,variant:`eyebrow`,tone:`muted`,className:`mb-2`,children:`Preview`}),(0,K.jsx)(`div`,{className:`flex flex-1 flex-col overflow-hidden rounded-lg border border-border`,children:d?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`border-b border-border bg-card p-4`,children:(0,K.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,K.jsx)(`div`,{className:`rounded-lg bg-muted p-2`,children:(0,K.jsx)(mQ,{className:`size-5 text-muted-foreground`})}),(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsx)(T,{as:`h3`,variant:`subheading`,tone:`ink`,className:`truncate`,children:d.name}),(0,K.jsxs)(`div`,{className:`mt-1 flex items-center gap-3 text-muted-foreground`,children:[(0,K.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(pQ,{className:`size-3`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`block`,children:d.topSource})]}),(0,K.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(Dr,{className:`size-3`}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[d.installs.toLocaleString(),` installs`]})]})]})]}),b&&(0,K.jsx)(`a`,{href:`https://github.com/${b.owner}/${b.repo}`,target:`_blank`,rel:`noopener noreferrer`,className:m(`text-muted-foreground hover:text-foreground`,`transition-[color] duration-fast ease-out-custom motion-reduce:transition-none`),title:`View on GitHub`,children:(0,K.jsx)(Br,{className:`size-4`})})]})}),C?(0,K.jsx)(`div`,{className:`flex flex-1 items-center justify-center`,children:(0,K.jsx)(Da,{className:`size-6 animate-spin text-muted-foreground`})}):S?(0,K.jsx)(lw,{className:`flex-1`,children:(0,K.jsx)(`div`,{className:`p-4`,children:(0,K.jsx)(xX,{children:S})})}):(0,K.jsxs)(`div`,{className:`flex flex-1 flex-col items-center justify-center text-muted-foreground`,children:[(0,K.jsx)(Do,{className:`mb-2 size-8`}),(0,K.jsx)(T,{children:`Preview unavailable`}),x&&(0,K.jsxs)(`a`,{href:x,target:`_blank`,rel:`noopener noreferrer`,className:`mt-2 flex items-center gap-1 text-info-indicator hover:underline`,children:[(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[`View on skills.sh`,` `]}),(0,K.jsx)(Br,{className:`size-3`})]})]})]}):(0,K.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center text-muted-foreground`,children:[(0,K.jsx)(Do,{className:`mb-2 size-8`}),(0,K.jsx)(T,{children:`Select a skill to preview`})]})})]})]}),d&&s&&s.length>1&&(0,K.jsxs)(fA,{orientation:`horizontal`,className:m(`bg-card hover:bg-card active:bg-card shadow-raised [--field:var(--field-on-surface)] [--field-disabled:var(--field-on-surface)] [--field-rim:var(--field-rim-on-surface)]`,`gap-3 rounded-lg p-3`),children:[(0,K.jsx)(Ci,{className:`size-4 shrink-0 text-muted-foreground`}),(0,K.jsx)(mA,{className:`whitespace-nowrap`,children:`Install to`}),(0,K.jsxs)(WA,{value:g,onValueChange:h,children:[(0,K.jsx)(KA,{className:`flex-1`,children:(0,K.jsx)(GA,{})}),(0,K.jsx)(qA,{children:s.map(e=>{let t=e.displayName??e.name??e.provider??`unknown`;return(0,K.jsxs)(JA,{value:e.path,children:[t,` (`,e.path,`)`]},e.path)})})]})]})]}),d&&(0,K.jsxs)(bE,{children:[A&&s&&s.length>1&&(()=>{let e=c?.[d.name];if(!e)return null;let t=s.find(t=>e.startsWith(t.path+`/`)||e===t.path);return t?(0,K.jsxs)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`mr-auto`,children:[`Installed at `,t.path]}):null})(),(0,K.jsx)(wE,{children:`Cancel`}),(0,K.jsx)(gE,{onConfirm:j,disabled:!b||A,"data-testid":`install-skill-button`,children:i?`Installing...`:A?`Already installed`:`Install`})]})]})})}function tzi({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)(Pc,{}),`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)(Pc,{})}),(0,K.jsx)(ezi,{...c,open:r,onOpenChange:i,workspaceId:t,onInstall:e=>void l(e),isInstalling:a})]})}function nzi({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(YRi(t??``))),[v,y]=(0,G.useState)(t);if(t!==v){y(t);let e=YRi(t??``).filter(e=>!g.has(e));e.length>0&&_(new Set([...g,...e]))}let b=a?.join(`
|
|
724
|
+
`).reduce((e,t)=>{if(!t||t.startsWith(`#`))return e;let[n,r]=t.split(`=`);return n&&(e[n]=r?.split(``)?.every(e=>e===`*`)?``:r?.replaceAll(`"`,``)),e},{}):{}}var YIi=({queryOptions:e}={})=>Ey({queryKey:[`mastra-templates`],queryFn:GIi,...e}),XIi=({repoOrSlug:e,owner:t,queryOptions:n})=>Ey({queryKey:[`template-repo`,e,t],queryFn:()=>qIi({repoOrSlug:e,owner:t}),...n}),ZIi=({repo:e,owner:t,branch:n,queryOptions:r})=>Ey({queryKey:[`template-repo-env-vars`,e,t,n],queryFn:()=>JIi({repo:e,owner:t,branch:n}),...r}),QIi=({queryOptions:e}={})=>{let t=Y();return Ey({queryKey:[`agent-builder-workflow`],queryFn:async()=>await t.getAgentBuilderAction(`merge-template`).details(),...e})},$Ii=({queryOptions:e}={})=>{let t=Y();return Oy({mutationFn:async({runId:e})=>await t.getAgentBuilderAction(`merge-template`).createRun({runId:e}),...e})},eLi=({queryOptions:e}={})=>{let t=Y();return Oy({mutationFn:async({runId:e})=>await t.getAgentBuilderAction(`merge-template`).runById(e),...e})},tLi=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)},nLi=(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=tLi(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=tLi(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}},rLi=(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)}},iLi=(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}=nLi(a,s,e);s=c,r(c),(a.runId||i||t)&&rLi(a.runId||i||t,c)}}catch(t){console.error(`💥 [processStream] Error processing template installation stream:`,t);let{newState:n}=nLi({type:`error`,payload:{error:t instanceof Error?t.message:`Unknown error`}},s,e);r(n)}finally{a(!1),o.releaseLock()}}}},aLi=({workflowInfo:e,queryOptions:t}={})=>{let n=Y(),{streamResult:r,isStreaming:i,processStream:a}=iLi(e);return{streamInstall:Oy({mutationFn:async({inputData:e,selectedModel:t,runId:r})=>{for(let i=1;i<=3;i++)try{let i=n.getAgentBuilderAction(`merge-template`),o=new Ll;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}},oLi=({workflowInfo:e,queryOptions:t}={})=>{let n=Y(),{streamResult:r,isStreaming:i,processStream:a}=iLi(e);return{observeInstall:Oy({mutationFn:async({runId:e})=>{let t=2e3;for(let r=1;r<=3;r++)try{let t=await n.getAgentBuilderAction(`merge-template`).observeStream({runId:e});await a(t,e);return}catch(e){console.error(`💥 [observeInstall] Attempt ${r} failed:`,e);let n=e?.message?.includes(`Failed to fetch`)||e?.message?.includes(`NetworkError`)||e?.message?.includes(`network error`)||e?.message?.includes(`fetch`)||e?.code===`NETWORK_ERROR`||e?.name===`TypeError`;if(console.warn(`ObserveStream attempt ${r}/3 failed:`,e),n&&r<3){console.info(`🔄 ObserveStream network error detected (likely hot reload), retrying in ${t}ms... (attempt ${r+1}/3)`),await new Promise(e=>setTimeout(e,t));continue}throw console.error(`❌ [observeInstall] Non-network error or max retries reached, throwing:`,e),e}},...t?.observeInstall}),streamResult:r,isStreaming:i}};function sLi(e){return e.replace(/\/$/,``).split(`/`).pop()}function cLi({templates:e,linkComponent:t,className:n,isLoading:r}){let i=t||`a`;return r?(0,K.jsx)(`div`,{className:m(`grid gap-y-4`,n),children:Array.from({length:5}).map((e,t)=>(0,K.jsx)(`div`,{className:`h-16 animate-pulse rounded-lg bg-card`},t))}):(0,K.jsx)(`div`,{className:m(`grid gap-y-4`,n),children:e.map(e=>{let t=e?.agents||e?.tools||e?.networks||e?.workflows||e?.mcp;return(0,K.jsxs)(`article`,{className:m(Wb,`state-layer grid w-full grid-cols-[1fr_auto] overflow-hidden rounded-lg`),children:[(0,K.jsxs)(i,{to:`/templates/${e.slug}`,className:m(`group grid`,{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":e.imageURL}),children:[e.imageURL&&(0,K.jsx)(`div`,{className:`overflow-hidden`,children:(0,K.jsx)(`div`,{className:`thumb transition-scale h-full w-full bg-cover duration-150`,style:{backgroundImage:`url(${e.imageURL})`}})}),(0,K.jsxs)(`div`,{className:m(`grid w-full gap-0.5 px-4 py-3`,`[&_svg]:h-[1em] [&_svg]:w-[1em] [&_svg]:text-muted-foreground`),children:[(0,K.jsx)(T,{as:`h2`,tone:`ink`,children:e.title}),(0,K.jsx)(T,{className:m(QC,f),children:e.description}),(0,K.jsxs)(`div`,{className:`mt-3 hidden flex-wrap items-center gap-x-8 gap-y-4 text-muted-foreground 2xl:flex`,children:[t&&(0,K.jsxs)(`ul`,{className:m(`text-muted-foreground`,`m-0 flex list-none gap-4 p-0`,`[&>li]:flex [&>li]:items-center [&>li]:gap-0.5`),children:[e?.agents&&e.agents.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(tF,{}),` `,e.agents.length]})}),e?.tools&&e.tools.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(aF,{}),` `,e.tools.length]})}),e?.networks&&e.networks.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(_o,{}),` `,e.networks.length]})}),e?.workflows&&e.workflows.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(Rc,{}),` `,e.workflows.length]})}),e?.mcp&&e.mcp.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(nF,{}),` `,e.mcp.length]})})]}),(0,K.jsx)(`div`,{className:`flex items-center gap-4`,children:e.supportedProviders.map(e=>(0,K.jsx)(T,{tone:`muted`,as:`span`,variant:`body`,children:e},e))})]})]})]}),(0,K.jsx)(`a`,{href:e.githubUrl,className:m(`group ml-auto hidden items-center gap-2 pr-4`,`lg:flex`),target:`_blank`,rel:`noopener noreferrer`,children:(0,K.jsx)(T,{as:`span`,variant:`body`,children:(0,K.jsxs)(`span`,{className:m(`flex items-center gap-2 rounded bg-sidebar px-2 py-1`,mKe,QC,f),children:[(0,K.jsx)(pQ,{}),` `,sLi(e.githubUrl)]})})})]},e.slug)})})}function lLi({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:i,onProviderChange:a,searchTerm:o,onSearchChange:s,onReset:c,className:l,isLoading:u}){return u?(0,K.jsxs)(`div`,{className:m(`flex h-[6.5rem] items-center gap-5`,`[&>div]:h-8 [&>div]:w-48 [&>div]:animate-pulse [&>div]:bg-card`,l),children:[(0,K.jsx)(`div`,{}),` `,(0,K.jsx)(`div`,{}),` `,(0,K.jsx)(`div`,{})]}):(0,K.jsxs)(`div`,{className:m(`sticky top-0 mx-auto flex flex-wrap gap-1.5 bg-background py-5`,l),children:[(0,K.jsx)(RU,{label:`Search templates`,placeholder:`Search templates`,size:`sm`,value:o,onValueChange:s}),(0,K.jsxs)(WA,{value:t,onValueChange:i,children:[(0,K.jsx)(KA,{"aria-label":`Filter by tag`,size:`sm`,className:`w-auto`,children:(0,K.jsx)(GA,{placeholder:`Select an option`})}),(0,K.jsx)(qA,{children:e.map(e=>(0,K.jsx)(JA,{value:e.value,children:e.label},e.value))})]}),(0,K.jsxs)(WA,{value:r,onValueChange:a,children:[(0,K.jsx)(KA,{"aria-label":`Filter by provider`,size:`sm`,className:`w-auto`,children:(0,K.jsx)(GA,{placeholder:`Select an option`})}),(0,K.jsx)(qA,{children:n.map(e=>(0,K.jsx)(JA,{value:e.value,children:e.label},e.value))})]}),c&&(0,K.jsx)(x3,{onClick:c})]})}var uLi=[{id:`templates`,label:`Templates`}];function dLi(){let{data:e,isLoading:t}=YIi(),{templates:n,tags:r,providers:i}=e??{templates:[],tags:[],providers:[]},[a,o]=(0,G.useState)(`all`),[s,c]=(0,G.useState)(`all`),[l,u]=(0,G.useState)(``),d=[{value:`all`,label:`Any tag`}];(r||[]).forEach(e=>{d.push({value:e,label:e})});let f=[{value:`all`,label:`Any provider`}];(i||[]).forEach(e=>{f.push({value:e,label:e})});let p=(e,t)=>{t===`tag`?o(e):t===`provider`&&c(e)},h=e=>{u(e)},g=()=>{o(`all`),c(`all`),u(``)},_=n.filter(e=>!(l&&!e.title.toLowerCase().includes(l)&&!e.description.toLowerCase().includes(l)||a!==`all`&&!e.tags.includes(a)||s!==`all`&&!e.supportedProviders.includes(s))),v=l||a!==`all`||s!==`all`;return(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:uLi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Templates`}),(0,K.jsx)($C,{children:(0,K.jsxs)(B1e,{children:[(0,K.jsx)(TC,{children:(0,K.jsx)(Do,{})}),`Templates`]})}),(0,K.jsxs)(`div`,{className:m(`z-10 h-full w-full overflow-y-auto px-5 pb-12`),children:[(0,K.jsx)(lLi,{selectedTag:a,onTagChange:e=>p(e,`tag`),tagOptions:d,selectedProvider:s,onProviderChange:e=>p(e,`provider`),providerOptions:f,searchTerm:l,onSearchChange:h,onReset:v?g:void 0,className:`max-w-[80rem]`,isLoading:t}),(0,K.jsx)(cLi,{templates:_,linkComponent:Vb,className:`mx-auto max-w-[80rem]`,isLoading:t})]})]})}function fLi({children:e,className:t}){return(0,K.jsx)(`div`,{className:m(`transition-height mt-12 rounded-lg border border-border px-4 py-5 lg:min-h-[25rem] lg:px-12`,t),children:e})}function pLi({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)(wc,{className:`text-warning-foreground`}),title:`Template Installed with Warnings`}:{icon:(0,K.jsx)(Gr,{}),title:`Template Installation Failed`};return(0,K.jsxs)(fLi,{className:`mb-5 content-center space-y-4 text-muted-foreground`,children:[(0,K.jsxs)(`div`,{className:`grid content-center items-center justify-items-center gap-4 [&>svg]:h-8 [&>svg]:w-8`,children:[o,(0,K.jsxs)(`div`,{className:`space-y-2 text-center`,children:[(0,K.jsx)(T,{variant:`subheading`,tone:`ink`,children:s}),(0,K.jsx)(T,{tone:`muted`,children:a()})]})]}),t&&t.length>0&&(0,K.jsxs)(`details`,{children:[(0,K.jsx)(`summary`,{className:m(`text-muted-foreground hover:text-foreground`,`cursor-pointer text-center select-none`),children:(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[`Show Validation Issues (`,t.length,`)`]})}),(0,K.jsx)(`div`,{className:`mt-4 max-h-60 space-y-2 overflow-auto rounded bg-muted p-3 text-left`,children:t.map((e,t)=>(0,K.jsxs)(`div`,{className:`border-l-2 border-destructive-indicator pl-2`,children:[(0,K.jsx)(T,{as:`p`,variant:`column`,className:`text-destructive-foreground`,children:e.type===`typescript`?`🔴 TypeScript Error`:`⚠️ Lint Error`}),(0,K.jsx)(Dw,{className:`mt-1 text-caption wrap-break-word whitespace-pre-wrap text-muted-foreground`,code:e.message})]},t))})]}),n&&!i&&(0,K.jsxs)(`details`,{children:[(0,K.jsx)(`summary`,{className:m(`text-muted-foreground hover:text-foreground`,`cursor-pointer text-center select-none`),children:(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`block`,children:`Show Details`})}),(0,K.jsx)(`div`,{className:`mt-4 max-h-60 overflow-auto rounded bg-muted p-3 text-left`,children:(0,K.jsx)(Dw,{className:`text-caption wrap-break-word whitespace-pre-wrap`,code:n})})]})]})}function mLi({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:i,handleInstallTemplate:a,handleVariableChange:o,isLoadingEnvVars:s,isInstalling:c,defaultModelProvider:l,defaultModelId:u,onModelUpdate:d}){return(0,K.jsx)(fLi,{children:(0,K.jsxs)(`div`,{className:`mx-auto my-4 grid max-w-[40rem] gap-5 p-4 lg:p-5`,children:[(0,K.jsxs)(T,{as:`h2`,variant:`heading`,tone:`muted`,className:m(`flex items-center gap-2`,`[&_svg]:h-[1.2em] [&_svg]:opacity-70 [&>svg]:w-[1.2em]`),children:[`Install Template `,(0,K.jsx)(To,{})]}),(0,K.jsxs)(fA,{orientation:`horizontal`,children:[(0,K.jsx)(mA,{children:`Template AI Model Provider`}),(0,K.jsx)(Oyt,{className:`flex-1`,children:(0,K.jsxs)(WA,{name:`template-provider`,value:t,onValueChange:n,children:[(0,K.jsx)(KA,{size:`md`,children:(0,K.jsx)(GA,{placeholder:`Select`})}),(0,K.jsx)(qA,{children:e.map(e=>(0,K.jsx)(JA,{value:e.value,children:e.label},e.value))})]})})]}),t&&Object.entries(r||{}).length>0&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h3`,tone:`muted`,children:`Set required Environmental Variables`}),(0,K.jsx)(`div`,{className:`grid grid-cols-[1fr_1fr] items-start gap-4`,children:s?(0,K.jsxs)(`div`,{className:m(`text-muted-foreground`,`col-span-2 flex items-center justify-center gap-4`,`[&_svg]:h-[1.1em] [&_svg]:w-[1.1em] [&_svg]:opacity-50`,`animate-in duration-300 fade-in`),children:[(0,K.jsx)(Qc,{}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[` `,`Loading variables...`]})]}):Object.entries(r).map(([e,t])=>(0,K.jsxs)(G.Fragment,{children:[(0,K.jsxs)(fA,{className:`w-full`,children:[(0,K.jsx)(mA,{className:`sr-only`,children:`Key`}),(0,K.jsx)(ZM,{name:`env-${e}`,value:e,disabled:!0,className:`w-full`})]}),(0,K.jsxs)(fA,{invalid:i.includes(e),className:`w-full`,children:[(0,K.jsx)(mA,{className:`sr-only`,children:`Value`}),(0,K.jsx)(ZM,{name:e,value:t,onChange:o,autoComplete:`off`,className:`w-full`}),(0,K.jsx)(gA,{children:i.includes(e)?`Value is required.`:void 0})]})]},e))}),(0,K.jsxs)(`div`,{className:`relative mt-3.5 border-t border-border pt-12`,children:[(0,K.jsx)(`div`,{className:`absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full bg-background`,children:(0,K.jsx)(T,{tone:`muted`,as:`span`,variant:`caption`,className:`block`,children:`And`})}),(0,K.jsx)(T,{as:`h3`,tone:`muted`,children:`Set AI Model for Template Installation`}),(0,K.jsx)(T,{tone:`muted`,className:`mt-2 mb-5`,children:`This model will be used by the workflow to process and install the template`}),(0,K.jsx)(Z4r,{defaultProvider:l||``,defaultModel:u||``,updateModel:d||(()=>Promise.resolve({message:`Updated`})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:`Provider`})]})]}),t&&!s&&(0,K.jsx)(X,{className:m(`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)(Qc,{className:`h-4 w-4`}),` Installing...`]}):(0,K.jsxs)(K.Fragment,{children:[`Install `,(0,K.jsx)(Ht,{})]})})]})})}function hLi({title:e,description:t,githubUrl:n,isLoading:r,infoData:i,templateSlug:a}){let o=a?`feat/install-template-${a}`:`feat/install-template-[slug]`;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`mt-5 grid items-center`,children:(0,K.jsxs)(`div`,{className:m(`flex items-center gap-3`,`[&>svg]:h-[1.2em] [&>svg]:w-[1.2em] [&>svg]:opacity-50`,{"[&>svg]:opacity-20":r}),children:[(0,K.jsx)(Do,{}),(0,K.jsx)(`h2`,{className:m({"flex min-w-[50%] rounded-lg bg-muted":r}),children:(0,K.jsx)(T,{as:`span`,variant:`title`,className:`block`,children:r?(0,K.jsx)(K.Fragment,{children:`\xA0`}):e})})]})}),(0,K.jsxs)(`div`,{className:`grid gap-x-24 lg:grid-cols-[1fr_1fr]`,children:[(0,K.jsxs)(`div`,{className:`grid`,children:[(0,K.jsx)(T,{tone:`muted`,className:m(`mt-2 mb-4`,{"rounded-lg bg-muted":r}),children:r?(0,K.jsx)(K.Fragment,{children:`\xA0`}):t}),!r&&a&&(0,K.jsxs)(`div`,{className:m(`mb-4 rounded-lg border border-border bg-background p-4`,`flex items-start gap-3`),children:[(0,K.jsx)(`div`,{className:`mt-0.5 shrink-0`,children:(0,K.jsx)(Xi,{className:`h-[1.1em] w-[1.1em] text-info-indicator`})}),(0,K.jsxs)(`div`,{className:`flex-1 space-y-2`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(ki,{className:`h-[1em] w-[1em] text-muted-foreground`}),(0,K.jsx)(T,{as:`span`,variant:`subheading`,tone:`ink`,children:`A new Git branch will be created`})]}),(0,K.jsxs)(`div`,{className:`space-y-1`,children:[(0,K.jsxs)(T,{tone:`muted`,as:`p`,variant:`caption`,children:[(0,K.jsx)(T,{as:`span`,variant:`column`,children:`Branch name:`}),` `,(0,K.jsx)(uZ,{children:o})]}),(0,K.jsx)(T,{tone:`muted`,as:`p`,variant:`caption`,children:`This ensures safe installation with easy rollback if needed. Your main branch remains unchanged.`})]})]})]}),n&&(0,K.jsxs)(`a`,{href:n,target:`_blank`,rel:`noopener noreferrer`,className:m(`text-muted-foreground hover:text-foreground`,`mt-auto flex items-center gap-2`),children:[(0,K.jsx)(pQ,{}),(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:n?.split(`/`)?.pop()})]})]}),i&&(0,K.jsx)(t3r,{data:i,labelsAreHidden:!0,isLoading:r})]})]})}function gLi(e){switch(e){case`running`:return(0,K.jsx)(Qc,{size:`sm`,"aria-hidden":!0});case`success`:return(0,K.jsx)(Bn,{"aria-hidden":!0});case`failed`:return(0,K.jsx)(Hc,{"aria-hidden":!0});default:return null}}function _Li(){return(0,K.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`text-placeholder`,"aria-hidden":!0,children:(0,K.jsx)(`circle`,{cx:`12`,cy:`12`,r:`8.5`,pathLength:`48`,fill:`none`,stroke:`currentcolor`,strokeWidth:`2.8`,strokeLinecap:`round`,strokeDasharray:`3 3`})})}function vLi({status:e,variant:t}){return t===`plain`?(0,K.jsx)(`span`,{className:m(`flex size-4 items-center justify-center self-center [&>svg]:size-4`,b.colors,{"[&>svg]:text-success-indicator":e===`success`,"[&>svg]:text-destructive-foreground":e===`failed`}),children:e===`pending`?(0,K.jsx)(_Li,{}):gLi(e)}):(0,K.jsx)(`span`,{className:m(`flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none`,b.colors,b.transform,{"[&>svg]:text-success-indicator":e===`success`,"[&>svg]:text-destructive-foreground":e===`failed`,"border border-dashed border-placeholder":e===`pending`,"[&>svg]:size-4":e!==`running`,"bg-success-subtle":e===`success`,"bg-destructive-subtle":e===`failed`,"scale-110":e===`success`||e===`failed`}),children:gLi(e)})}function yLi({step:e,isActive:t,position:n,variant:r=`default`}){let i=t||e.status===`success`?`ink`:`muted`;return(0,K.jsxs)(`div`,{className:m(`grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none`,b.colors,{"border border-transparent":r==="default","border-dashed border-placeholder bg-card":t&&r==="default"}),children:[(0,K.jsxs)(`div`,{className:`grid min-w-0 grid-cols-[auto_1fr] gap-2`,children:[(0,K.jsxs)(T,{as:`span`,tone:i,className:m(`flex min-w-6 justify-end`,b.colors),children:[n,`.`]}),(0,K.jsxs)(`div`,{className:`min-w-0`,children:[(0,K.jsx)(T,{as:`h4`,tone:i,className:b.colors,children:e.title}),e.description&&(0,K.jsx)(T,{tone:`faint`,className:m(`-mt-0.5`,{truncate:r===`plain`}),children:e.description})]})]}),(0,K.jsx)(vLi,{status:e.status,variant:r})]})}function bLi({currentStep:e,steps:t=[],className:n}){return(0,K.jsx)(`div`,{className:m(n),children:t.map((t,n)=>(0,K.jsx)(yLi,{step:t,isActive:e?.id===t.id,position:n+1},t.id))})}function xLi({steps:e}){let t=e.length,n=e.filter(e=>e.status===`success`).length;return(0,K.jsxs)(`div`,{className:`flex w-full flex-col content-center justify-center gap-4`,children:[(0,K.jsx)(`div`,{className:`grid w-full grid-cols-[0_repeat(9,1fr)]`,children:e.map((t,n)=>(0,K.jsx)(`div`,{className:m(`relative flex h-8 items-center justify-end`,b.colors,{"bg-success-subtle":t.status===`success`&&e?.[n-1]?.status===`success`}),children:(0,K.jsx)(`div`,{className:m(`absolute right-0 z-10 flex size-8 translate-x-1/2 items-center justify-center self-center rounded-full bg-fill text-column text-muted-foreground motion-reduce:transition-none`,b.colors,b.transform,{"border border-dashed border-placeholder":t.status===`pending`,"scale-110 bg-success-subtle text-success-subtle-foreground":t.status===`success`,"scale-110 bg-destructive-subtle text-destructive-subtle-foreground":t.status===`failed`}),children:t.status===`running`?(0,K.jsx)(Qc,{}):n+1})},t.id))}),(0,K.jsxs)(`div`,{className:m(`text-center text-caption text-muted-foreground`,b.colors),children:[n,` of `,t,` steps completed`]})]})}var SLi=(0,G.createContext)(3);function CLi({title:e,description:t,action:n,done:r,className:i,children:a}){let o=(0,G.useContext)(SLi);return(0,K.jsxs)(`li`,{className:m(`group/step grid grid-cols-[1.5rem_minmax(0,1fr)] gap-x-4 [counter-increment:ds-step]`,i),children:[(0,K.jsxs)(`div`,{className:`flex flex-col items-center`,children:[(0,K.jsx)(`span`,{className:m(`flex size-6 shrink-0 items-center justify-center rounded-full`,b.colors,r?`bg-success-indicator/18 text-success-indicator`:`bg-fill text-foreground`),children:r?(0,K.jsx)(Bn,{className:`size-3.5`,"aria-label":`Done`}):(0,K.jsx)(T,{as:`span`,variant:`column`,className:`before:content-[counter(ds-step)]`,"aria-hidden":!0})}),(0,K.jsx)(`span`,{"aria-hidden":!0,className:`w-px flex-1 bg-border group-last/step:hidden`})]}),(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-3 pb-8 group-last/step:pb-0`,children:[(0,K.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,K.jsxs)(`div`,{className:`flex min-h-6 flex-wrap items-center justify-between gap-x-6 gap-y-2`,children:[(0,K.jsx)(T,{as:o===2?`h2`:`h3`,variant:`label`,className:`text-pretty`,children:e}),n==null?null:(0,K.jsx)(`div`,{className:`flex shrink-0 items-center gap-2`,children:n})]}),t==null?null:(0,K.jsx)(T,{as:`p`,variant:`body-sm`,tone:`muted`,className:`max-w-[70ch] text-pretty`,children:t})]}),a]})]})}function wLi({headingLevel:e=3,className:t,children:n}){return(0,K.jsx)(SLi.Provider,{value:e,children:(0,K.jsx)(`ol`,{className:m(`flex flex-col [counter-reset:ds-step]`,t),children:n})})}Object.assign(wLi,{Step:CLi});function TLi({name:e,streamResult:t,runId:n,workflowInfo:r}){let i=t?.phase||`initializing`,a=t?.payload?.workflowState,o=t?.payload?.currentStep,s=t?.error,c=a?.steps||{},l=Object.keys(c).length>0,u=e=>e===`input`||e.endsWith(`.input`)||e.startsWith(`Mapping_`)&&/[0-9a-f]{8}/.test(e)||/[0-9a-f]{8,}/.test(e)?!1:!r?.allSteps||e in r.allSteps,d=Object.entries(c).filter(([e,t])=>u(e)),f=d.length,p=()=>{switch(i){case`initializing`:return`Preparing template installation...`;case`processing`:return`Installing ${e} template`;case`completed`:return`Template installation completed!`;case`error`:return`Template installation failed`;default:return`Installing template...`}},h=d.map(([e,t])=>({id:e,status:t?.status,description:t?.description,title:e.charAt(0).toUpperCase()+e.slice(1).replace(/-/g,` `),isActive:o?.id===e}));return(0,K.jsxs)(fLi,{className:`mb-5 content-center space-y-6 text-muted-foreground`,children:[(0,K.jsxs)(`div`,{className:`text-center`,children:[(0,K.jsx)(T,{as:`h3`,variant:`heading`,tone:`ink`,children:p()}),(t?.runId||n)&&(0,K.jsxs)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`mt-2`,children:[`Run ID: `,t?.runId??n]})]}),l&&f>0&&![`error`].includes(i)&&(0,K.jsx)(`div`,{className:`mx-auto w-full max-w-[30rem] px-4`,children:(0,K.jsx)(xLi,{steps:h})}),s&&i===`error`&&(0,K.jsxs)(`div`,{className:m(`text-foreground`,`flex items-center gap-3 rounded-lg bg-destructive-subtle p-4`,`[&>svg]:h-6 [&>svg]:w-6 [&>svg]:text-destructive-foreground [&>svg]:opacity-70`),children:[(0,K.jsx)(So,{}),(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:s||`Something went wrong`})]}),l&&(0,K.jsx)(bLi,{steps:h,currentStep:o,className:`pb-4`}),!l&&i===`initializing`&&(0,K.jsxs)(`div`,{className:m(`text-muted-foreground`,`grid justify-items-center gap-4 text-center`),children:[(0,K.jsx)(Qc,{}),(0,K.jsx)(T,{as:`p`,variant:`body`,children:`This may take some time...`})]})]})}function ELi({name:e,installedEntities:t}){return(0,K.jsxs)(fLi,{className:m(`grid content-center items-center justify-items-center gap-4`,`[&>svg]:h-8 [&>svg]:w-8`),children:[(0,K.jsx)(To,{}),(0,K.jsx)(T,{as:`h2`,variant:`heading`,children:`Done!`}),(0,K.jsxs)(T,{tone:`muted`,className:`text-center`,children:[`The `,(0,K.jsx)(`b`,{className:`text-muted-foreground`,children:e}),` template has been successfully installed.`,t&&t.length>0&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`br`,{}),` Installed entities are listed below.`]})]}),t&&t.length>0&&(0,K.jsx)(t3r,{data:t})]})}function DLi(){let{templateSlug:e}=Ab(),t=[{id:`templates`,label:`Templates`,to:`/templates`},{id:`template`,label:LLt(e)}],[n,r]=Hb(),[i,a]=(0,G.useState)(``),[o,s]=(0,G.useState)(``),[c,l]=(0,G.useState)(``),[u,d]=(0,G.useState)({}),[f,p]=(0,G.useState)([]),[h,g]=(0,G.useState)(null),[_,v]=(0,G.useState)(!1),[y,b]=(0,G.useState)(``),[x,S]=(0,G.useState)(!1),[C,w]=(0,G.useState)(!1),[T,E]=(0,G.useState)([]),{data:D,isLoading:O}=XIi({repoOrSlug:e,owner:`mastra-ai`}),k=`1.83.0-alpha.11`.includes(`beta`)??!1?`beta`:`main`,{data:A,isLoading:j}=ZIi({repo:D?.githubUrl?new URL(D.githubUrl).pathname.split(`/`)[2]:`template-${e}`,owner:`mastra-ai`,branch:k}),{data:M,isLoading:N}=QIi(),{mutateAsync:P,isPending:F}=$Ii(),{mutateAsync:I}=eLi(),{streamInstall:L,streamResult:R,isStreaming:z}=aLi({workflowInfo:M}),{observeInstall:B,streamResult:V,isStreaming:H}=oLi({workflowInfo:M});(0,G.useEffect)(()=>{let e=n.get(`runId`);!e||_||h||z||H||(console.info(`🔄 Checking completed run after hot reload:`,{runId:e}),b(e),I({runId:e}).then(e=>{let t=e.snapshot;if(t?.status===`success`&&t?.result?.success)v(!0);else if(t?.result?.success===!1){if(t?.result?.validationResults&&!t?.result?.validationResults?.valid&&t?.result?.validationResults?.remainingErrors>0){let{remainingErrors:e,errors:n}=t.result.validationResults,r=`Template installation completed but ${e} validation issue${e>1?`s`:``} remain unresolved.`;g(r),E(n||[])}else{let e=t?.result?.message||t?.result?.error||`Template installation failed`;g(typeof e==`string`?e:String(e))}}}).catch(e=>{console.error(`❌ Failed to fetch run details:`,e),g(`Failed to retrieve installation status after reload`)}))},[n,_,h,z,H,I]),(0,G.useEffect)(()=>{let e=n.get(`runId`),t=n.get(`resume`),i=n.get(`provider`);if(e&&t===`true`&&i&&!z&&!H&&!x&&!C&&M){b(e),S(!0);try{I({runId:e}).then(t=>{if(t.snapshot?.status===`running`)return B.mutateAsync({runId:e})}).then(()=>{r(e=>{let t=new URLSearchParams(e);return t.delete(`resume`),t})}).catch(e=>{console.error(`❌ Failed to resume template installation:`,e),e.message?.includes(`404`)||e.message?.includes(`not found`)?g(`Template installation run not found. It may have expired or been completed.`):g(`Failed to resume template installation. Please try again.`)})}catch(e){console.error(`❌ Auto-resume failed with error:`,e),g(`Failed to resume template installation. Please refresh and try again.`)}}},[n,e,z,H,x,C,M,I,B,r]);let ee=[{value:`openai`,label:`OpenAI`},{value:`anthropic`,label:`Anthropic`},{value:`groq`,label:`Groq`},{value:`google`,label:`Google`}],te=[{key:`tools`,label:`Tools`,value:D?.tools?.length?D.tools.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(aF,{})},{key:`agents`,label:`Agents`,value:D?.agents?.length?D.agents.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(tF,{})},{key:`workflows`,label:`Workflows`,value:D?.workflows?.length?D.workflows.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(Rc,{})},{key:`providers`,label:`Providers`,value:D?.supportedProviders?.length?D.supportedProviders.join(`, `):`n/a`,icon:(0,K.jsx)(Dn,{})},{key:`tags`,label:`Tags`,value:D?.tags?.length?D.tags.join(`, `):`n/a`,icon:(0,K.jsx)(Qs,{})}],U=[{...te[0]},{...te[1]},{...te[2]}].filter(e=>e.value!==`n/a`);return(0,G.useEffect)(()=>{A&&d(A)},[A]),(0,G.useEffect)(()=>{let e=R||V;e?.phase===`error`&&e?.error&&g(typeof e.error==`string`?e.error:String(e.error))},[R?.phase,R?.error,V?.phase,V?.error]),(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(`div`,{className:m(`h-full w-full overflow-y-scroll lg:px-12`),children:(0,K.jsxs)(`div`,{className:`mx-auto grid w-full max-w-[80rem] gap-y-4 p-4`,children:[(0,K.jsx)(hLi,{isLoading:O,title:D?.title,description:D?.longDescription,imageURL:D?.imageURL,githubUrl:D?.githubUrl,infoData:te,templateSlug:e}),D&&(0,K.jsxs)(K.Fragment,{children:[(z||H)&&(0,K.jsx)(TLi,{name:D.title,streamResult:H?V:R,runId:y,workflowInfo:M}),_&&(0,K.jsx)(ELi,{name:D.title,installedEntities:U,linkComponent:Vb}),h&&(0,K.jsx)(pLi,{errorMsg:h,validationErrors:T.length>0?T:R?.validationResults?.errors||V?.validationResults?.errors}),!z&&!H&&!_&&!h&&(0,K.jsx)(mLi,{providerOptions:ee,selectedProvider:i,onProviderChange:e=>{a(e)},variables:u,setVariables:d,errors:f,setErrors:p,handleInstallTemplate:async()=>{let e=Object.entries(u).reduce((e,[t,n])=>(n===``&&e.push(t),e),[]);if(e.length>0)p(e);else if(D){g(null),v(!1),b(``),w(!0);try{let e={repo:D.githubUrl||`https://github.com/mastra-ai/template-${D.slug}`,ref:k,slug:D.slug,variables:u},{runId:t}=await P({});b(t),r(e=>{let n=new URLSearchParams(e);return n.set(`runId`,t),n.set(`resume`,`true`),n.set(`provider`,i||`openai`),n}),await L.mutateAsync({inputData:e,selectedModel:{provider:o,modelId:c},runId:t})}catch(e){w(!1),g(e?.message||`Template installation failed`),console.error(`Template installation failed`,e)}}},handleVariableChange:e=>{let{name:t,value:n}=e.target;n.trim()===``?p(e=>[...e,t]):p(e=>e.filter(e=>e!==t)),d(e=>({...e,[t]:n}))},isLoadingEnvVars:j||N,isInstalling:F,defaultModelProvider:o,defaultModelId:c,onModelUpdate:async e=>(s(e.provider),l(e.modelId),{message:`Model updated successfully`})})]})]})})]})}var OLi=e=>e.threadId;function kLi(e,t){return`traces`in e?{traces:{...e.traces,to:t}}:{threads:{...e.threads,to:t}}}var ALi=e=>`traces`in e?e.traces:e.threads;function jLi(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 MLi({query:e,rolling:t,autoRefetch:n=!0,limit:r,enabled:i=!0}){let a=Y(),{anchorTo:o,reanchor:s}=vIi(e),c=(0,G.useMemo)(()=>o?{...e,timeRange:kLi(e.timeRange,o)}:e,[e,o]),l=k$r({query:c,limit:r,enabled:i,queryOptions:mIi}),{headRows:u}=bIi({queryKey:[`threads`,e],fetchHead:async t=>(await a.queryTraceThreads({...e,timeRange:kLi(e.timeRange,t),orderBy:[{field:`endedAt`,direction:`desc`}],page:{limit:50}})).threads,getId:OLi,getEndedAt:e=>e.endedAt,since:Date.parse(ALi(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&&SIi(f,u,{getId:OLi,compare:jLi(d),hasNextPage:l.hasNextPage}),[f,u,d,l.hasNextPage]);return{...l,threads:p}}function NLi(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 PLi=[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`],FLi=[];function ILi(){let{data:e}=r5(),t=e?.capabilities.traceQueryTimeToFirstChunk??!1,n=e?.capabilities.traceQueryTimeToFirstToken??!1,{data:r=FLi}=_8(),{data:i=FLi}=v8();return(0,G.useMemo)(()=>[P5r,...tli({withTimeToFirstChunk:t,withTimeToFirstToken:n,entityNames:r,environments:i})],[t,n,r,i])}function LLi({tokens:e,groups:t,onFiltersChange:n}){let r=(0,G.useMemo)(()=>u0r(e),[e]),i=(0,G.useMemo)(()=>{let e=p0r([],t);return{...e,nodes:[f5,...r,...e.nodes]}},[r,t]),a=(0,G.useCallback)(e=>{let t=h0r({...e,nodes:e.nodes.filter(e=>s8(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(s8);a({...i,nodes:[...n,o,...s]})},[r,i,a])}}var RLi=e=>e;function zLi({datePreset:e,dateFrom:t,dateTo:n,minDate:r,tokens:i,groups:a,onDatePresetChange:o,onDateChange:s,onDateRangeChange:c,onFiltersChange:l,disabled:u}){let d=ILi(),{filterBarValue:f,onFilterBarChange:p}=LLi({tokens:i,groups:a,onFiltersChange:l});return(0,K.jsxs)(p5,{fields:d,operators:R1r,value:f,onValueChange:p,createItemId:RLi,maxDepth:3,"aria-label":`Thread filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(p5.Chips,{renderChip:i=>i.fieldId===`timeRange`?(0,K.jsx)(p5.TimeRange,{preset:e,onPresetChange:o,dateFrom:t,dateTo:n,minDate:r,onDateChange:s,onDateRangeChange:c,disabled:u,presets:PLi,defaultPreset:a5.datePreset}):(0,K.jsx)(p5.Chip,{item:i})}),(0,K.jsx)(p5.Input,{placeholder:`Filter threads`})]})}function BLi({selectedThreadId:e,onSelectedThreadChange:t,onOpenScore:n,urlState:r}){let i=gIi(r),{timeRange:a,tokens:o,groups:s,sort:c}=i,l=i5().enabled,u=N6r().enabled,d=Dsi({scope:`threads`}),{data:f,isLoading:p}=r5(),m=f?.capabilities.traceQueryTimeToFirstChunk??!1,h=f?.capabilities.traceQueryTimeToFirstToken??!1,g=(0,G.useMemo)(()=>p?d.preferences:Y3r(d.preferences,{withTimeToFirstChunk:m,withTimeToFirstToken:h}),[d.preferences,p,m,h]),{threads:_,hasNextPage:v,isFetchingNextPage:y,setEndOfListElement:b,isLoading:x,isError:S,error:C}=MLi({query:(0,G.useMemo)(()=>{let e=ili(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(NLi),[_]),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)(y6r,{toolbar:(0,K.jsxs)(K.Fragment,{children:[r&&(0,K.jsx)(rui,{page:`threads`,...r,columns:d}),(0,K.jsxs)(jq,{children:[(0,K.jsx)(jq.Start,{children:(0,K.jsx)(zLi,{datePreset:i.datePreset,dateFrom:i.dateFrom,dateTo:i.dateTo,tokens:o,groups:s,onDatePresetChange:i.onDatePresetChange,onDateChange:i.onDateChange,onDateRangeChange:i.onDateRangeChange,onFiltersChange:i.onFiltersChange,disabled:x})}),(0,K.jsx)(jq.End,{children:(0,K.jsx)(I6r,{scope:`threads`,value:d.preferences,onChange:d.setPreferences})})]})]}),error:S?(0,K.jsx)(Z8,{error:C,resource:`threads`,errorTitle:`Failed to load threads`}):void 0,empty:D?(0,K.jsx)(D3r,{resource:`threads`,datePreset:i.datePreset,dateFrom:i.dateFrom,dateTo:i.dateTo}):void 0,children:(0,K.jsx)(Bti,{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)(fsi,{open:!!e,threadId:e??``,depth:1,closeLabel:`Close`,withQueryTrace:l,withFeedback:u,onOpenScore:n,onClose:()=>t(void 0)})]})}function VLi(){let{enabled:e,isLoading:t}=D6r(),n=kb(),[r,i]=Hb();return(0,K.jsx)(pIi,{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)(BLi,{urlState:{searchParams:r,setSearchParams:i},selectedThreadId:OIi(r),onSelectedThreadChange:e=>i(t=>kIi(t,e),{replace:!0}),onOpenScore:(e,t)=>n(kq(e,t))})})}var HLi=()=>(0,K.jsx)(RC,{titleSlot:`No Workflows yet`,descriptionSlot:(0,K.jsxs)(K.Fragment,{children:[`Mastra workflows are not configured yet. `,(0,K.jsx)(`br`,{}),`More information in the documentation.`]}),actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/docs/workflows/overview`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(Br,{}),children:`Workflows documentation`}),variant:`fill`});function ULi(e,t,n){return yQ(e,t,{name:e=>e.name,running:e=>n[e.id]?.running??0,suspended:e=>n[e.id]?.suspended??0,steps:e=>Object.keys(e.steps??{}).length})}function WLi(e){return Object.keys(e.steps??{}).filter(t=>e.allSteps?.[t]?.isWorkflow)}function GLi(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 KLi(e,t,n){let r=GLi(t),i=[],a=(e,o,s,c,l,u)=>{let d=WLi(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 qLi=`auto 24rem minmax(0, 1fr) auto auto auto`;function JLi({guides:e,isLastChild:t}){return(0,K.jsxs)(`span`,{"aria-hidden":!0,className:`-my-6 flex shrink-0 self-stretch`,children:[e.map((e,t)=>(0,K.jsx)(`span`,{className:m(`w-6`,e&&`border-l border-border`)},t)),(0,K.jsxs)(`span`,{className:`relative w-6`,children:[(0,K.jsx)(`span`,{className:m(`absolute top-0 left-0 border-l border-border`,t?`h-1/2`:`h-full`)}),(0,K.jsx)(`span`,{className:`absolute top-1/2 left-0 w-3.5 border-b border-border`})]})]})}function YLi({row:e,isExpanded:t,onToggle:n}){let r=e.kind===`workflow`&&e.nestedIds.length>0,i=e.kind===`workflow`?e.workflow.name:e.stepId;return(0,K.jsx)(`div`,{className:`flex items-center pl-5`,children:r?(0,K.jsx)(`button`,{type:`button`,"aria-expanded":t,"aria-label":`${t?`Collapse`:`Expand`} nested workflows of ${i}`,className:m(ZC,`relative grid size-5 shrink-0 place-items-center before:absolute before:-inset-1.5 before:content-['']`),onClick:e=>{e.stopPropagation(),n()},children:(0,K.jsx)(y,{direction:`right`,className:`size-4`})}):(0,K.jsx)(`span`,{className:`size-5 shrink-0`,"aria-hidden":!0})})}var XLi=e=>e.stopPropagation();function ZLi({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 QLi({row:e,isExpanded:t,onToggle:n,runCount:r,rowProps:i}){let{paths:a,Link:o}=_l(),s=(0,G.useRef)(null),{workflow:c,nestedIds:l}=e,u=fY(c.name,50),d=fY(c.description??``,200),f=Object.keys(c.steps??{}).length,p=r?.running??0,m=r?.suspended??0,h=l.length>0;return(0,K.jsxs)(Z.RowWrapper,{...i,onSelectRow:()=>s.current?.click(),children:[(0,K.jsx)(YLi,{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:XLi,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)(JLi,{guides:e.guides,isLastChild:e.isLastChild}):null,(0,K.jsx)(`span`,{className:`truncate`,children:u}),c.origin===`dynamic`?(0,K.jsx)(bw,{size:`xs`,variant:`blue`,title:`Registered via the dynamic-workflows API`,children:`Dynamic`}):null,h?(0,K.jsxs)(T,{as:`span`,variant:`body-sm`,tone:`muted`,title:`Nested workflows: ${l.join(`, `)}`,className:`inline-flex shrink-0 items-center gap-1`,children:[(0,K.jsx)(Rc,{"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)(Po,{"aria-hidden":!0,className:`size-3.5`}),m]}):``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:f||``})]})]})}function $Li({workflows:e,isLoading:t,search:n=``,sort:r,onSortChange:i,requestContext:a}){let[o,s]=(0,G.useState)(new Set),c=xMt({requestContext:a}),l=(0,G.useMemo)(()=>Object.entries(e).map(([e,t])=>({...t,id:e})),[e]),u=(0,G.useMemo)(()=>{let e=n.toLowerCase();return l.filter(t=>t.name?.toLowerCase().includes(e)||t.description?.toLowerCase().includes(e))},[l,n]),d=(0,G.useMemo)(()=>ULi(u,r,c),[u,r,c]),f=(0,G.useMemo)(()=>KLi(d,e,o),[d,e,o]),p=(0,G.useMemo)(()=>{let e=new Map;for(let t of f)t.kind===`workflow`&&e.set(t.pathKey,e.size);return e},[f]),{containerRef:h,getRowProps:g}=_Q({count:p.size,global:!0}),v=e=>{s(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})};return t?(0,K.jsx)(NU,{columns:qLi,fit:`container`}):(0,K.jsxs)(Z,{columns:qLi,fit:`container`,scrollRef:h,children:[(0,K.jsxs)(Z.Top,{children:[(0,K.jsx)(Z.TopCell,{children:(0,K.jsx)(`span`,{className:`sr-only`,children:`Expand`})}),(0,K.jsx)(ZLi,{sortKey:`name`,sort:r,onSortChange:i,children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`Description`}),(0,K.jsx)(ZLi,{sortKey:`running`,sort:r,onSortChange:i,children:`Running`}),(0,K.jsx)(ZLi,{sortKey:`suspended`,sort:r,onSortChange:i,children:`Pending input`}),(0,K.jsx)(ZLi,{sortKey:`steps`,sort:r,onSortChange:i,children:`Number of steps`})]}),f.length===0&&n?(0,K.jsx)(Z.NoMatch,{message:`No Workflows match your search`}):null,f.map(e=>{let t=o.has(e.pathKey),n=()=>v(e.pathKey);return e.kind===`unregistered`?(0,K.jsxs)(Z.RowStatic,{className:`gap-0 px-0`,children:[(0,K.jsx)(YLi,{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)(JLi,{guides:e.guides,isLastChild:e.isLastChild}),(0,K.jsx)(`span`,{className:`truncate`,children:fY(e.stepId,50)}),(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{render:(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`muted`}),role:`note`,tabIndex:0,className:m(`shrink-0 rounded-sm`,_),children:`not registered`}),(0,K.jsx)(CC,{className:`max-w-72`,children:`Runs as a step of its parent workflow. Add it to the workflows of your Mastra instance to open, run, and inspect it on its own page.`})]})]})}),(0,K.jsx)(Z.DescriptionCell,{children:fY(e.description??``,200)}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:``})]})]},`workflow-${e.pathKey}`):(0,K.jsx)(QLi,{row:e,isExpanded:t,onToggle:n,runCount:c[e.workflow.id],rowProps:g(p.get(e.pathKey)??-1)},`workflow-${e.pathKey}`)})]})}var G9=[sF(`/workflows`)];function eRi(){let{data:e,isLoading:t,error:n}=sP(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)();return n&&JP(n)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:G9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(jU,{variant:`fill`})]}):n&&YP(n)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:G9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(AU,{variant:`fill`,resource:`workflows`})]}):n?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:G9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load workflows`,descriptionSlot:n.message})]}):Object.keys(e||{}).length===0&&!t?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:G9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(HLi,{})]}):(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:G9}),actionRow:(0,K.jsxs)(jq,{children:[(0,K.jsx)(jq.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(zU,{onSearch:i,label:`Filter workflows`,placeholder:`Filter by name or description`})})}),(0,K.jsx)(jq.End,{children:(0,K.jsx)(X,{render:(0,K.jsx)(Vb,{to:`/workflows/schedules`}),variant:`primary`,icon:(0,K.jsx)(Nn,{}),children:`Schedules`})})]}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)($Li,{workflows:e||{},isLoading:t,search:r,sort:a,onSortChange:(e,t)=>o({key:t,direction:e})})]})}var tRi={active:`bg-success-indicator`,paused:`bg-info-indicator`,completed:`bg-muted-foreground`},nRi={active:`text-success-indicator`,paused:`text-info-indicator`,completed:`text-muted-foreground`},rRi=({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 ${tRi[e]}`,"aria-hidden":!0}),(0,K.jsx)(T,{as:`span`,variant:`caption`,className:nRi[e],children:e})]});function iRi({status:e}){let{icon:t,color:n}=aRi(e);return(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 whitespace-nowrap ${n}`,children:[(0,K.jsx)(`span`,{className:`inline-flex shrink-0 items-center`,"aria-hidden":!0,children:t}),(0,K.jsx)(T,{as:`span`,variant:`caption`,children:e})]})}function aRi(e){switch(e){case`success`:return{icon:(0,K.jsx)(Bn,{size:14}),color:`text-success-indicator`};case`failed`:return{icon:(0,K.jsx)(Hc,{size:14}),color:`text-destructive-foreground`};case`running`:return{icon:(0,K.jsx)(Qc,{}),color:`text-muted-foreground`};case`suspended`:return{icon:(0,K.jsx)(Zn,{size:14}),color:`text-info-indicator`};case`canceled`:return{icon:(0,K.jsx)(tr,{size:14}),color:`text-muted-foreground`};case`pending`:case`waiting`:return{icon:(0,K.jsx)(lr,{size:14}),color:`text-muted-foreground`};default:return{icon:null,color:`text-muted-foreground`}}}var oRi=`auto auto auto auto 1fr`,sRi=3e4,cRi=3e5;function lRi({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:i,setEndOfListElement:a}){let{Link:o,paths:s}=_l(),c=e=>!!(n&&e.runId&&e.outcome!==`failed`),l=e.filter(c).length,{containerRef:u,getRowProps:d}=_Q({count:l}),f=-1;return t?(0,K.jsx)(NU,{columns:oRi}):e.length===0?(0,K.jsx)(T,{variant:`body`,tone:`muted`,className:`p-4`,children:`No trigger history yet.`}):(0,K.jsxs)(Z,{columns:oRi,className:`min-w-0`,scrollRef:u,children:[(0,K.jsxs)(Z.Top,{children:[(0,K.jsx)(Z.TopCell,{children:`Run`}),(0,K.jsx)(Z.TopCell,{children:`Status`}),(0,K.jsx)(Z.TopCell,{children:`Started`}),(0,K.jsx)(Z.TopCell,{children:`Duration`}),(0,K.jsx)(Z.TopCell,{children:` `})]}),e.map(e=>{let t=e.actualFireAt-e.scheduledFireAt,r=xw(t,{signed:!0}),i=e.outcome===`failed`,a=i?e.error:e.run?.error,l=Math.abs(t),u=!i&&l>sRi&&l<=cRi,p=`${e.scheduleId}-${e.runId}-${e.actualFireAt}`,m=c(e);m&&(f+=1);let h=(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,tone:m?`ink`:`muted`,className:`whitespace-nowrap`,children:e.runId}),g=(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Z.Cell,{children:h}),(0,K.jsx)(Z.Cell,{children:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[i?(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`inline-flex items-center gap-1.5 whitespace-nowrap text-destructive-foreground`,children:[(0,K.jsx)(wc,{size:14}),`publish failed`]}):e.run?(0,K.jsx)(iRi,{status:e.run.status}):(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`inline-flex items-center gap-1.5 whitespace-nowrap`,children:`pending`}),a?(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{asChild:!0,children:(0,K.jsx)(`span`,{className:`inline-flex text-destructive-foreground`,children:(0,K.jsx)(wc,{size:14})})}),(0,K.jsx)(CC,{children:a})]}):null]})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-2 whitespace-nowrap`,children:[e.actualFireAt?(0,K.jsx)(jA,{value:e.actualFireAt}):`—`,u?(0,K.jsxs)(xC,{children:[(0,K.jsx)(SC,{asChild:!0,children:(0,K.jsx)(`span`,{className:`inline-flex text-info-indicator`,children:(0,K.jsx)(wc,{size:14})})}),(0,K.jsxs)(CC,{children:[`Published `,r,` after the scheduled fire time`]})]}):null]})}),(0,K.jsx)(Z.Cell,{children:e.run?(0,K.jsx)(T,{as:`span`,variant:`body-sm`,font:`mono`,children:xw(e.run.durationMs)||`—`}):(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`—`})}),(0,K.jsx)(Z.Cell,{children:` `})]});return m?(0,K.jsx)(Z.RowLink,{to:s.workflowRunLink(n,e.runId),LinkComponent:o,...d(f),children:g},p):(0,K.jsx)(Z.RowStatic,{children:g},p)}),(0,K.jsx)(Z.NextPageLoading,{isLoading:i,hasMore:r,setEndOfListElement:a})]})}var uRi={id:`workflow-schedules`,label:`Schedules`,icon:Nn,to:`/workflows/schedules`};function dRi({label:e,children:t}){return(0,K.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,K.jsx)(T,{variant:`meta`,tone:`muted`,className:`uppercase`,children:e}),(0,K.jsx)(`div`,{children:(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:t})})]})}function fRi(){let{scheduleId:e}=Ab(),t=[sF(`/workflows`),uRi,{id:`schedule`,label:LLt(e),icon:Nn}],{paths:n}=_l(),{data:r,error:i}=tRt({scheduleId:e,queryOptions:{enabled:!!e}}),{data:a,isLoading:o,error:s,hasNextPage:c,isFetchingNextPage:l,setEndOfListElement:u}=rRt({scheduleId:e,queryOptions:{enabled:!!e}}),d=iRt({scheduleId:e});if(i&&JP(i))return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(jU,{variant:`fill`})]});if(i&&YP(i))return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(AU,{variant:`fill`,resource:`schedules`})]});if(i)return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load schedule`,descriptionSlot:i.message})]});let f=r?.workflowId,p=r?.agentId;return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:t}),actionRow:(0,K.jsx)(jq,{children:(0,K.jsxs)(jq.End,{children:[(0,K.jsx)(X,{render:(0,K.jsx)(Vb,{to:n.schedulesLink()}),variant:`ghost`,icon:(0,K.jsx)(Rt,{}),children:`Back to schedules`}),f?(0,K.jsx)(X,{icon:(0,K.jsx)(rP,{}),render:(0,K.jsx)(Vb,{to:n.workflowLink(f)}),variant:`ghost`,children:`Open workflow`}):null,r&&r.status!==`completed`?(0,K.jsx)(X,{onClick:()=>{let e=r.status===`active`?`pause`:`resume`;d.mutate(e,{onSuccess:()=>UC.success(e===`pause`?`Schedule paused`:`Schedule resumed`),onError:e=>UC.error(e.message)})},disabled:d.isPending,"data-testid":`schedule-toggle-button`,children:r.status===`active`?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Po,{}),`Pause`]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Ho,{}),`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)(dRi,{label:p?`Agent`:`Workflow`,children:f?(0,K.jsx)(Vb,{to:n.workflowLink(f),className:`text-foreground hover:underline`,children:f}):p?(0,K.jsx)(Vb,{to:n.agentLink(p),className:`text-foreground hover:underline`,children:p}):`—`}),(0,K.jsxs)(dRi,{label:r.cron?`Cron`:`Runs at`,children:[(0,K.jsx)(T,{as:`span`,variant:`body`,font:`mono`,children:r.cron??(r.runAt?new Date(r.runAt).toLocaleString():`—`)}),r.endAt?(0,K.jsxs)(`span`,{className:`ml-2 text-caption text-muted-foreground`,children:[`until `,new Date(r.endAt).toLocaleString()]}):null,r.timezone?(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`ml-2`,children:r.timezone}):null]}),(0,K.jsx)(dRi,{label:`Status`,children:(0,K.jsx)(rRi,{status:r.status})}),(0,K.jsx)(dRi,{label:`Next fire`,children:r.nextFireAt?(0,K.jsx)(jA,{value:r.nextFireAt}):`—`})]}),(0,K.jsxs)(`div`,{className:`overflow-y-auto`,"data-testid":`schedule-triggers-panel`,children:[(0,K.jsx)(T,{variant:`body`,className:`mb-3`,children:`Trigger history`}),s?(0,K.jsx)(RC,{tone:`error`,titleSlot:`Failed to load trigger history`,descriptionSlot:s.message}):(0,K.jsx)(lRi,{triggers:a??[],isLoading:o,workflowId:f,hasNextPage:c,isFetchingNextPage:l,setEndOfListElement:u})]})]}):null]})}var pRi={target:e=>e.workflowId??e.agentId??``,status:e=>e.status,nextFireAt:e=>e.nextFireAt,lastFireAt:e=>e.lastFireAt},mRi=`minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto`;function hRi({schedules:e,isLoading:t,search:n=``,sort:r,onSortChange:i}){let{paths:a,Link:o}=_l(),s=(0,G.useMemo)(()=>{let t=n.toLowerCase();return yQ(t?e.filter(e=>e.id.toLowerCase().includes(t)||(e.workflowId??e.agentId??``).toLowerCase().includes(t)):e,r,pRi)},[e,n,r]),{containerRef:c,getRowProps:l}=_Q({count:s.length,global:!0});if(t)return(0,K.jsx)(NU,{columns:mRi});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:mRi,className:`min-w-0`,scrollRef:c,children:[(0,K.jsxs)(Z.Top,{children:[u(`target`,`Target`),(0,K.jsx)(Z.TopCell,{children:`Schedule ID`}),(0,K.jsx)(Z.TopCell,{children:`Cron`}),u(`status`,`Status`),u(`nextFireAt`,`Next fire`),u(`lastFireAt`,`Last run`)]}),s.length===0&&n?(0,K.jsx)(Z.NoMatch,{message:`No schedules match your search`}):null,s.length===0&&!n?(0,K.jsx)(Z.NoMatch,{message:`No schedules configured`}):null,s.map((e,t)=>(0,K.jsxs)(Z.RowLink,{to:a.scheduleLink(e.id),LinkComponent:o,...l(t),children:[(0,K.jsx)(Z.NameCell,{children:e.workflowId??e.agentId}),(0,K.jsx)(Z.Cell,{className:`min-w-0`,children:(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`muted`,font:`mono`,className:`block truncate`,title:e.id,children:e.id})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-2 whitespace-nowrap`,children:[(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,children:e.cron??(e.runAt?`once @ ${new Date(e.runAt).toLocaleString()}`:`—`)}),e.timezone?(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:e.timezone}):null]})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(rRi,{status:e.status})}),(0,K.jsx)(Z.Cell,{children:e.nextFireAt?(0,K.jsx)(jA,{value:e.nextFireAt}):`—`}),(0,K.jsx)(Z.Cell,{children:e.lastRun?(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-2 whitespace-nowrap`,children:[(0,K.jsx)(iRi,{status:e.lastRun.status}),e.lastFireAt?(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:(0,K.jsx)(jA,{value:e.lastFireAt})}):null]}):e.lastFireAt?(0,K.jsx)(jA,{value:e.lastFireAt}):(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`Never`})})]},e.id))]})}function gRi({workflowId:e}={}){let{data:t,isLoading:n,error:r}=uF(e?{workflowId:e}:{}),[i,a]=(0,G.useState)(``),[o,s]=(0,G.useState)();return r?(0,K.jsx)(RC,{tone:`error`,titleSlot:`Failed to load schedules`,descriptionSlot:r.message}):(0,K.jsxs)(`div`,{className:`grid h-full grid-rows-[auto_1fr] gap-4 overflow-hidden`,children:[(0,K.jsx)(`div`,{className:`max-w-120`,children:(0,K.jsx)(zU,{onSearch:a,label:`Filter schedules`,placeholder:`Filter by id or workflow`})}),(0,K.jsx)(`div`,{className:`overflow-y-auto`,children:(0,K.jsx)(hRi,{schedules:t??[],isLoading:n,search:i,sort:o,onSortChange:(e,t)=>s({key:t,direction:e})})})]})}var _Ri=[sF(`/workflows`),uRi];function vRi(){let[e]=Hb(),t=e.get(`workflowId`)??void 0,{error:n}=uF(t?{workflowId:t}:{});return n&&JP(n)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:_Ri}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(jU,{variant:`fill`})]}):n&&YP(n)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:_Ri}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(AU,{variant:`fill`,resource:`schedules`})]}):(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:_Ri}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(`div`,{className:`h-full`,children:(0,K.jsx)(gRi,{workflowId:t})})]})}var yRi={"--belt-hue":`var(--warning-indicator)`};function bRi(e){let t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function xRi(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 SRi({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:(0,K.jsxs)(`section`,{className:m(FMt,`pointer-events-auto relative isolate`),"data-testid":`workflow-suspended-steps`,"aria-label":`Step suspended`,children:[(0,K.jsxs)(`div`,{className:`max-h-[calc(100cqh-64px)] overflow-y-auto overscroll-contain rounded-[inherit]`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-3 border-b border-border bg-background px-5 py-4`,children:[(0,K.jsxs)(T,{as:`h2`,variant:`column`,tone:`ink`,className:`flex items-center gap-2`,children:[(0,K.jsx)(TC,{children:(0,K.jsx)(Zn,{})}),`Step suspended`]}),(0,K.jsx)(bw,{variant:`orange`,emphasis:`subtle`,children:`Needs input`})]}),e.map(e=>{let n=t.allSteps[e.stepId];if(!n||n.isWorkflow)return null;let i=n?.resumeSchema?Kk(lA(n.resumeSchema)):Rp(q(),kp());return(0,K.jsx)(CRi,{step:e,stepSchema:i,description:n.description,onResume:r},`${e.runId}-${e.stepId}`)})]}),(0,K.jsx)(c4e,{status:`ready`,label:`Needs input`,className:`before:hidden`,style:yRi})]})}function CRi({step:e,stepSchema:t,description:n,onResume:r}){let[i,a]=(0,G.useState)(!1),[o,s]=(0,G.useState)(!1);return(0,K.jsxs)(`div`,{className:`space-y-5 p-5 [&+&]:border-t [&+&]:border-border`,children:[(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(T,{as:`p`,variant:`subheading`,tone:`ink`,className:`break-words`,children:e.stepId}),n&&(0,K.jsx)(T,{as:`p`,variant:`caption`,tone:`muted`,children:n})]}),e.suspendPayload!==void 0&&(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsxs)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`flex items-center gap-2`,children:[(0,K.jsx)(TC,{children:(0,K.jsx)(po,{})}),`The step is asking`]}),(0,K.jsxs)(Hw,{open:i,onOpenChange:a,children:[(0,K.jsxs)(Uw,{className:m(`bg-card hover:bg-card active:bg-card shadow-raised [--field:var(--field-on-surface)] [--field-disabled:var(--field-on-surface)] [--field-rim:var(--field-rim-on-surface)]`,`flex w-full items-center justify-between gap-2 rounded-lg px-3 py-2.5`),children:[(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(TC,{children:(0,K.jsx)(y,{direction:`right`,className:`text-muted-foreground`})}),(0,K.jsx)(T,{as:`span`,variant:`body`,tone:`ink`,className:`truncate`,children:xRi(e.suspendPayload,e.stepId)})]}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`shrink-0`,children:bRi(e.suspendPayload)})]}),(0,K.jsx)(Ww,{children:(0,K.jsx)(`div`,{"data-testid":`suspended-payload`,className:`pt-2`,children:(0,K.jsx)(FT,{value:JSON.stringify(e.suspendPayload,null,2),editable:!1,className:`w-full overflow-x-auto p-2`,showCopyButton:!1})})})]})]}),(0,K.jsxs)(`div`,{className:`space-y-3`,children:[(0,K.jsxs)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`flex items-center gap-2`,children:[(0,K.jsx)(TC,{children:(0,K.jsx)(ho,{})}),`Your response`]}),(0,K.jsx)(`div`,{className:`-mx-5`,children:(0,K.jsx)(Zjt,{schema:t,isSubmitLoading:o,submitButtonLabel:`Resume`,submitButtonVariant:`primary`,submitButtonIcon:(0,K.jsx)(Ho,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:async t=>{s(!0);try{await r({stepId:e.stepId.split(`.`),runId:e.runId,resumeData:t})}catch(e){UC.error(e instanceof Error?e.message:`Error resuming workflow`)}finally{s(!1)}}})})]})]})}function wRi({hidden:e,requestContext:t,canResume:n}){let{result:r,workflow:i,runId:a,isStreamingWorkflow:o}=(0,G.useContext)(gw),s=Yvt(r,a),c=eyt(t),l=r?.status===`suspended`&&s.length>0&&!o;return!i||!l||!n?null:(0,K.jsx)(`div`,{hidden:e,"data-testid":`workflow-suspended-overlay`,className:`pointer-events-none absolute top-12 right-2 z-30 w-95 max-w-[calc(100%-16px)] animate-in duration-300 fade-in-0 slide-in-from-top-2 motion-reduce:animate-none`,children:(0,K.jsx)(SRi,{suspendedSteps:s,workflow:i,isStreaming:o,onResume:c})},a)}var TRi={success:{label:`Completed`,icon:Bn},failed:{label:`Failed`,icon:ir},suspended:{label:`Needs input`,icon:Po},waiting:{label:`Waiting`,icon:vc},paused:{label:`Paused`,icon:Po},skipped:{label:`Skipped`,icon:Ps},running:{label:`Running`,icon:Da},canceled:{label:`Canceled`,icon:tr}},ERi={label:`Status unavailable`,icon:Cee};function DRi({row:e,isSelected:t,isHovered:n,onSelectStep:r,onHoverStep:i,onOpenInput:a,onOpenOutput:o}){let s=Object.hasOwn(TRi,e.status)?TRi[e.status]:ERi,c=s.icon,l=Rbt(e.status),u=e.stepId.slice(0,e.stepId.lastIndexOf(`.`)),d=e.isNestedEntry?e.stepId.slice(e.stepId.lastIndexOf(`.`)+1):e.stepId;return(0,K.jsxs)(`div`,{"data-testid":`workflow-timeline-row`,"data-workflow-step-key":e.stepId,onMouseEnter:()=>!e.isNestedEntry&&i(e.stepId),onMouseLeave:()=>!e.isNestedEntry&&i(null),className:m(`grid grid-cols-[minmax(130px,1fr)_minmax(64px,1fr)_56px_64px] items-center gap-3 rounded-md px-2 py-1`,`@max-[540px]/workflow-timeline:grid-cols-[minmax(0,1fr)_48px_64px] @max-[540px]/workflow-timeline:gap-x-1.5 @max-[540px]/workflow-timeline:gap-y-1 @max-[540px]/workflow-timeline:py-2`,(t||n)&&`bg-fill-subtle`),children:[(0,K.jsxs)(`button`,{type:`button`,"aria-disabled":e.isNestedEntry,"aria-pressed":t,onClick:()=>{e.isNestedEntry||r(e.stepId)},title:e.stepId,className:m(`text-foreground`,`flex min-h-9 min-w-0 cursor-pointer items-center gap-2.5 text-left focus-visible:rounded-sm aria-disabled:cursor-default`,_),children:[(0,K.jsx)(`span`,{"aria-label":s.label,className:m(`grid size-6 flex-none place-items-center rounded-md border border-border bg-background`,zbt[l]),children:(0,K.jsx)(c,{"aria-hidden":!0,className:m(`size-3.5`,e.status===`running`&&`motion-safe:animate-spin`)})}),(0,K.jsxs)(`span`,{className:`min-w-0`,children:[(0,K.jsx)(T,{as:`span`,variant:`meta`,className:`block truncate`,children:d}),e.isNestedEntry&&(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`flex min-w-0 items-center gap-1`,children:[(0,K.jsx)(Cr,{"aria-hidden":!0,className:`size-3 shrink-0`}),(0,K.jsx)(`span`,{className:`truncate`,children:u})]})]})]}),(0,K.jsx)(`div`,{className:`relative h-5 min-w-0 overflow-hidden rounded-sm bg-muted @max-[540px]/workflow-timeline:col-span-full @max-[540px]/workflow-timeline:row-start-2 @max-[540px]/workflow-timeline:ml-[34px]`,"aria-hidden":!0,children:e.timing&&(0,K.jsx)(`div`,{"data-testid":`workflow-timeline-bar`,"data-offset":e.timing.offsetPct,"data-width":e.timing.widthPct,className:m(`absolute top-0 h-full min-w-0.5 rounded-sm`,Bbt[l]),style:{left:`${e.timing.offsetPct}%`,width:`${e.timing.widthPct}%`}})}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`text-right whitespace-nowrap`,title:e.timing&&e.spansSuspension?`Includes time spent suspended waiting for input`:void 0,children:e.timing?(0,K.jsx)(T,{as:`span`,variant:`meta`,font:`mono`,children:xw(e.timing.durationMs)}):(0,K.jsx)(`span`,{"aria-label":`Timing unavailable`,children:`—`})}),(0,K.jsxs)(`div`,{className:`flex items-center`,children:[(0,K.jsx)(X,{type:`button`,variant:`ghost`,size:`icon-sm`,tooltip:`View step input`,disabled:e.step.input===void 0,onClick:t=>a(e,t.currentTarget),children:(0,K.jsx)(Mt,{})}),(0,K.jsx)(X,{type:`button`,variant:`ghost`,size:`icon-sm`,tooltip:`View step output`,disabled:e.step.output===void 0,onClick:t=>o(e,t.currentTarget),children:(0,K.jsx)(Kt,{})})]})]})}var ORi=e=>e.includes(`.`),kRi=e=>e===`input`||e.endsWith(`.input`),ARi=1;function jRi(e,t){let n=Ubt(e),r=n?.isLive?Math.max(t,n.start):n?.end;return{span:n&&r!==void 0?{start:n.start,end:r}:void 0,isLive:n?.isLive??!1,spansSuspension:n?.spansSuspension??!1}}function MRi(e,t){let n=Object.entries(e).filter(([e])=>!kRi(e)).map(([e,n])=>({stepId:e,step:n,...jRi(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,ARi),100-t)}}return{stepId:e,step:t,status:OA(t)?`suspended`:t.status,timing:s,spansSuspension:a,isRunning:r,isNestedEntry:ORi(e)}})}function NRi(){let{steps:e}=z$(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:i}=hw(),[a,o]=(0,G.useState)(()=>Date.now()),[s,c]=(0,G.useState)(!0),[l,u]=(0,G.useState)(!1),{showData:d}=lP(),f=(0,G.useRef)(null),p=MRi(e,a),h=p.some(e=>e.isRunning);return H1e(f,{enabled:h&&!s}),(0,G.useEffect)(()=>{if(!h||s)return;let e=setInterval(()=>o(Date.now()),100);return()=>clearInterval(e)},[h,s]),p.length===0?null:(0,K.jsx)(`div`,{"data-testid":`workflow-timeline`,className:`relative z-20 shrink-0 px-2 pb-2`,children:(0,K.jsxs)(Hw,{open:!s,onOpenChange:e=>c(!e),className:m(Wb,`@container/workflow-timeline pointer-events-auto overflow-hidden rounded-xl`),children:[(0,K.jsxs)(`div`,{className:`flex items-center`,children:[(0,K.jsxs)(Uw,{className:`flex min-h-11 min-w-0 flex-1 items-center gap-2 px-3.5 py-2.5 text-caption text-foreground hover:bg-fill-subtle`,"aria-label":s?`Expand timeline`:`Collapse timeline`,children:[(0,K.jsx)(`span`,{children:(0,K.jsx)(zn,{"aria-hidden":!0,className:`size-4 text-muted-foreground`})}),(0,K.jsx)(`span`,{children:`Timeline`}),(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,children:[p.length,` events`]}),(0,K.jsx)(`span`,{className:`ml-auto`,children:(0,K.jsx)(y,{direction:`right`,className:`size-4`})})]}),!s&&(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:l?`Restore timeline height`:`Enlarge timeline`,"aria-pressed":l,onClick:()=>u(!l),className:`mr-2 shrink-0`,children:l?(0,K.jsx)(lee,{}):(0,K.jsx)(hee,{})})]}),(0,K.jsx)(Ww,{children:(0,K.jsx)(`div`,{ref:f,"data-testid":`workflow-timeline-list`,className:m(`overflow-auto overscroll-contain px-1.5 pb-1.5`,l?`max-h-[min(720px,calc(100dvh-112px))]`:`max-h-[min(320px,40dvh)]`),children:p.map(e=>(0,K.jsx)(DRi,{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 PRi=({workflowId:e,workflow:t,isLoading:n})=>{let[r]=mw(`workflow`,e),{canExecute:i,isLoading:a}=KC(),{stepDetail:o}=lP(),s=fE(),c=o?.type===`data`,l=(0,K.jsxs)(`div`,{className:`[container-type:size] relative h-full min-h-0`,children:[(0,K.jsx)(Mmr,{workflowId:e,workflow:t,isLoading:n,requestContext:r}),(0,K.jsx)(wRi,{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)(V$,{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)(NRi,{})})]});return s&&o&&!c?(0,K.jsx)(`div`,{className:`h-full min-h-0 overflow-hidden`,children:(0,K.jsx)(V$,{requestContext:r})}):(0,K.jsxs)(`div`,{className:`relative h-full min-h-0`,children:[l,(0,K.jsxs)(F6,{className:`pointer-events-none absolute inset-0 z-30 min-h-0 w-full min-w-0 p-2`,children:[(0,K.jsx)(P6,{id:`workflow-graph`,className:`pointer-events-none min-w-0`}),o&&!c&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(I6,{className:`pointer-events-auto`}),(0,K.jsx)(P6,{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)(V$,{requestContext:r})})})]})]})]})},FRi=()=>{let{workflowId:e}=Ab(),{data:t,isLoading:n,error:r}=cP({workflowId:e,requestContext:mw(`workflow`,e)[0],queryOptions:{enabled:!!e}});return r&&JP(r)?(0,K.jsx)(jU,{variant:`fill`}):r&&YP(r)?(0,K.jsx)(AU,{variant:`fill`,resource:`workflows`}):(0,K.jsx)(PRi,{workflowId:e,workflow:t??void 0,isLoading:n})};function IRi(){let{workflowId:e}=Ab(),{error:t}=uF(e?{workflowId:e}:{});if(!e)return null;let n;return n=t&&JP(t)?(0,K.jsx)(jU,{variant:`fill`}):t&&YP(t)?(0,K.jsx)(AU,{variant:`fill`,resource:`schedules`}):(0,K.jsx)(`div`,{className:`h-full`,children:(0,K.jsx)(gRi,{workflowId:e})}),(0,K.jsxs)(uw,{children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),n]})}function LRi(){let{workflowId:e}=Ab();return e?(0,K.jsx)(Uui,{scopedEntityId:e,scopedEntityType:kh.WORKFLOW_RUN}):null}var RRi=(0,G.createContext)(null);function K9(){let e=(0,G.useContext)(RRi);if(!e)throw Error(`Workspace components must be rendered inside <Workspace.Root>`);return e}var zRi=e=>e?.status;function BRi(e,t){return JP(e)?`Your session has expired. Sign in again to continue.`:YP(e)?`You don't have permission to access this.`:XP(e)?`This path no longer exists.`:zRi(e)===501?`This workspace does not support this operation.`:t}function VRi({error:e,fallback:t,className:n}){return(0,K.jsx)(EA,{variant:`destructive`,className:n,children:(0,K.jsx)(EA.Message,{children:BRi(e,t)})})}var HRi=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;function URi(e){let t=HRi.exec(e);return t?{frontmatter:t[1]??``,body:e.slice(t[0].length)}:{frontmatter:null,body:e}}function WRi({content:e}){let{frontmatter:t,body:n}=URi(e);return(0,K.jsxs)(K.Fragment,{children:[t!==null&&(0,K.jsx)(`div`,{"data-testid":`workspace-frontmatter`,className:`border-b border-border`,children:(0,K.jsx)(pY,{code:t,lang:`yaml`,overflow:`wrap`,className:`rounded-none border-0 bg-transparent [&_pre]:p-4`})}),(0,K.jsx)(`div`,{className:`p-4`,children:(0,K.jsx)(xX,{children:n})})]})}function GRi(){let{activeFilePath:e}=K9();return e?(0,K.jsx)(T,{as:`span`,variant:`body-sm`,font:`mono`,tone:`muted`,className:`truncate`,"data-testid":`workspace-file-path`,children:e}):null}function KRi({path:e,content:t,mimeType:n}){return oVn(e,n)?(0,K.jsx)(`div`,{className:`flex justify-center p-4`,children:(0,K.jsx)(`img`,{src:`data:${n||`image/png`};base64,${t}`,alt:e.split(`/`).pop(),className:`max-w-full object-contain`})}):sVn(e,n)?(0,K.jsx)(`div`,{className:`flex justify-center p-4`,children:(0,K.jsx)(`video`,{controls:!0,"aria-label":e.split(`/`).pop(),className:`max-w-full`,children:(0,K.jsx)(`source`,{src:`data:${lVn(e,n)};base64,${t}`,type:lVn(e,n)})})}):uVn(e)?(0,K.jsx)(WRi,{content:t}):(0,K.jsx)(pY,{code:t,lang:U2e(e),overflow:`scroll`,className:`rounded-none border-0 bg-transparent [&_pre]:p-4`})}function qRi({renderPreview:e}){let{workspaceId:t,activeFilePath:n}=K9(),{data:r,isLoading:i,error:a}=TVn({workspaceId:t,path:n,queryOptions:{enabled:!!n}});if(!n)return null;if(i)return(0,K.jsxs)(`div`,{"aria-busy":`true`,className:`flex flex-col gap-2 p-4`,children:[(0,K.jsx)(dw,{className:`h-4 w-1/2`}),(0,K.jsx)(dw,{className:`h-4 w-5/6`}),(0,K.jsx)(dw,{className:`h-4 w-2/3`})]});if(!r)return(0,K.jsx)(VRi,{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)(KRi,{...o})}var JRi=(e,t)=>e===`.`?t:`${e}/${t}`,YRi=e=>e.split(`/`).slice(0,-1).map((e,t,n)=>n.slice(0,t+1).join(`/`)),XRi=e=>{let t=e.lastIndexOf(`/`);return t===-1?`.`:e.slice(0,t)};function ZRi({labeled:e=!1}={}){let{workspaceId:t,onCreateDirectory:n,isReadOnly:r}=K9(),i=dy(),[a,o]=(0,G.useState)(!1),[s,c]=(0,G.useState)(``),[l,u]=(0,G.useState)(!1);if(!n||r(`.`))return null;let d=s.trim().replace(/^\.?\/+|\/+$/g,``),f=async()=>{if(d){u(!0);try{await n(d),await i.invalidateQueries({queryKey:[`workspace`,t,`fs`,`list`,XRi(d)]}),o(!1),c(``)}catch{}finally{u(!1)}}};return(0,K.jsxs)(K.Fragment,{children:[e?(0,K.jsx)(X,{variant:`ghost`,icon:(0,K.jsx)(xi,{}),onClick:()=>o(!0),children:`New folder`}):(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`New folder`,onClick:()=>o(!0),children:(0,K.jsx)(xi,{})}),(0,K.jsx)(_E,{open:a,onOpenChange:o,pending:l,children:(0,K.jsx)(vE,{size:`sm`,children:(0,K.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),f()},children:[(0,K.jsx)(yE,{children:(0,K.jsx)(SE,{children:`New folder`})}),(0,K.jsx)(xE,{children:(0,K.jsx)(ZM,{autoFocus:!0,"aria-label":`Folder path`,placeholder:`docs/guides`,value:s,onChange:e=>c(e.target.value)})}),(0,K.jsxs)(bE,{children:[(0,K.jsx)(wE,{children:`Cancel`}),(0,K.jsx)(X,{type:`submit`,variant:`primary`,disabled:!d||l,children:`Create`})]})]})})})]})}function QRi(e){return`${e.topSource}/${e.name}`}function $Ri(e){let t=mVn(e.topSource,e.name);return t?`${t.owner}/${t.repo}/${e.name}`:null}function ezi({open:e,onOpenChange:t,workspaceId:n,onInstall:r,isInstalling:i,installedSkillIds:a=[],installedSkillNames:o=[],writableMounts:s,installedSkillPaths:c}){let[l,u]=(0,G.useState)(``),[d,f]=(0,G.useState)(null),[p,h]=(0,G.useState)(),g=s?.some(e=>e.path===p)?p:s?.[0]?.path,{data:_,isLoading:v}=fVn({workspaceId:n,queryOptions:{enabled:!!n}}),y=dVn({workspaceId:n}),b=(0,G.useMemo)(()=>d?.topSource?mVn(d.topSource,d.name):null,[d]),x=(0,G.useMemo)(()=>!b||!d?null:`https://skills.sh/${b.owner}/${b.repo}/${d.name}`,[b,d]),{data:S,isLoading:C}=pVn({workspaceId:n,owner:b?.owner,repo:b?.repo,skillPath:d?.name,queryOptions:{enabled:!!n&&!!b&&!!d}}),w=Tw(e=>{e.trim().length>=2&&y.mutate(e)},300),E=(0,G.useCallback)(e=>{u(e),w(e)},[w]),D=(0,G.useMemo)(()=>l.trim().length>=2?y.data?.skills??[]:_?.skills??[],[l,y.data,_]),O=y.isPending,k=l.trim().length>=2,A=(0,G.useMemo)(()=>{if(!d)return!1;let e=$Ri(d);return!!(e&&a.includes(e)||o.includes(d.name))},[d,a,o]),j=(0,G.useCallback)(()=>{d&&b&&r({repository:`${b.owner}/${b.repo}`,skillName:d.name,mount:s&&s.length>1?g:void 0})},[d,b,r,s,g]),M=(0,G.useCallback)(e=>{e||(u(``),f(null),h(void 0)),t(e)},[t]);return(0,K.jsx)(_E,{open:e,onOpenChange:M,pending:i,children:(0,K.jsxs)(vE,{size:`xl`,className:`h-[80vh]`,children:[(0,K.jsxs)(yE,{children:[(0,K.jsx)(SE,{children:`Add Skill`}),(0,K.jsx)(CE,{children:`Search and install skills from the community registry`})]}),(0,K.jsxs)(xE,{layout:`fill`,children:[(0,K.jsx)(RU,{label:`Search skills`,placeholder:`Search skills`,value:l,onValueChange:E}),(0,K.jsxs)(`div`,{className:`flex min-h-0 flex-1 gap-4`,children:[(0,K.jsxs)(`div`,{className:`flex min-h-0 w-1/2 flex-col`,children:[(0,K.jsx)(T,{as:`p`,variant:`eyebrow`,tone:`muted`,className:`mb-2`,children:k?`Search Results`:`Popular Skills`}),(0,K.jsx)(lw,{className:`flex-1 rounded-lg border border-border`,children:(0,K.jsx)(cw,{className:!v&&!O&&D.length===0?`flex flex-col [&>div]:flex [&>div]:flex-1 [&>div]:flex-col`:void 0,children:v||O?(0,K.jsx)(`div`,{className:`flex items-center justify-center py-5`,children:(0,K.jsx)(Da,{className:`size-6 animate-spin text-muted-foreground`})}):D.length===0?(0,K.jsxs)(`div`,{className:`flex flex-1 flex-col items-center-safe justify-center-safe py-5 text-muted-foreground`,children:[(0,K.jsx)(tr,{className:`mb-2 size-8`}),(0,K.jsx)(T,{children:k?`No skills found`:`No skills available`})]}):(0,K.jsx)(`div`,{className:`space-y-1 p-2`,children:D.map(e=>{let t=QRi(e),n=$Ri(e),r=n&&a.includes(n)||o.includes(e.name),i=d?QRi(d):null;return(0,K.jsx)(`button`,{onClick:()=>f(e),className:m(`w-full rounded-md px-3 py-2 text-left`,`hover:bg-fill-subtle`,i===t&&`border border-border-strong bg-fill-hover`),children:(0,K.jsxs)(`div`,{className:`flex items-start justify-between gap-2`,children:[(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(T,{as:`span`,variant:`subheading`,tone:`ink`,className:`truncate`,children:e.name}),r&&(0,K.jsxs)(T,{as:`span`,variant:`meta`,className:`inline-flex items-center gap-1 rounded bg-info-subtle px-1.5 py-0.5 text-info-subtle-foreground`,children:[(0,K.jsx)(Bn,{className:`size-2.5`}),`Installed`]})]}),(0,K.jsx)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`truncate`,children:e.topSource})]}),(0,K.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 text-muted-foreground`,children:[(0,K.jsx)(Dr,{className:`size-3`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,children:e.installs.toLocaleString()})]})]})},t)})})})})]}),(0,K.jsxs)(`div`,{className:`flex min-h-0 w-1/2 flex-col`,children:[(0,K.jsx)(T,{as:`p`,variant:`eyebrow`,tone:`muted`,className:`mb-2`,children:`Preview`}),(0,K.jsx)(`div`,{className:`flex flex-1 flex-col overflow-hidden rounded-lg border border-border`,children:d?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`border-b border-border bg-card p-4`,children:(0,K.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,K.jsx)(`div`,{className:`rounded-lg bg-muted p-2`,children:(0,K.jsx)(mQ,{className:`size-5 text-muted-foreground`})}),(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsx)(T,{as:`h3`,variant:`subheading`,tone:`ink`,className:`truncate`,children:d.name}),(0,K.jsxs)(`div`,{className:`mt-1 flex items-center gap-3 text-muted-foreground`,children:[(0,K.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(pQ,{className:`size-3`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`block`,children:d.topSource})]}),(0,K.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(Dr,{className:`size-3`}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[d.installs.toLocaleString(),` installs`]})]})]})]}),b&&(0,K.jsx)(`a`,{href:`https://github.com/${b.owner}/${b.repo}`,target:`_blank`,rel:`noopener noreferrer`,className:m(`text-muted-foreground hover:text-foreground`,`transition-[color] duration-fast ease-out-custom motion-reduce:transition-none`),title:`View on GitHub`,children:(0,K.jsx)(Br,{className:`size-4`})})]})}),C?(0,K.jsx)(`div`,{className:`flex flex-1 items-center justify-center`,children:(0,K.jsx)(Da,{className:`size-6 animate-spin text-muted-foreground`})}):S?(0,K.jsx)(lw,{className:`flex-1`,children:(0,K.jsx)(`div`,{className:`p-4`,children:(0,K.jsx)(xX,{children:S})})}):(0,K.jsxs)(`div`,{className:`flex flex-1 flex-col items-center justify-center text-muted-foreground`,children:[(0,K.jsx)(Do,{className:`mb-2 size-8`}),(0,K.jsx)(T,{children:`Preview unavailable`}),x&&(0,K.jsxs)(`a`,{href:x,target:`_blank`,rel:`noopener noreferrer`,className:`mt-2 flex items-center gap-1 text-info-indicator hover:underline`,children:[(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[`View on skills.sh`,` `]}),(0,K.jsx)(Br,{className:`size-3`})]})]})]}):(0,K.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center text-muted-foreground`,children:[(0,K.jsx)(Do,{className:`mb-2 size-8`}),(0,K.jsx)(T,{children:`Select a skill to preview`})]})})]})]}),d&&s&&s.length>1&&(0,K.jsxs)(fA,{orientation:`horizontal`,className:m(`bg-card hover:bg-card active:bg-card shadow-raised [--field:var(--field-on-surface)] [--field-disabled:var(--field-on-surface)] [--field-rim:var(--field-rim-on-surface)]`,`gap-3 rounded-lg p-3`),children:[(0,K.jsx)(Ci,{className:`size-4 shrink-0 text-muted-foreground`}),(0,K.jsx)(mA,{className:`whitespace-nowrap`,children:`Install to`}),(0,K.jsxs)(WA,{value:g,onValueChange:h,children:[(0,K.jsx)(KA,{className:`flex-1`,children:(0,K.jsx)(GA,{})}),(0,K.jsx)(qA,{children:s.map(e=>{let t=e.displayName??e.name??e.provider??`unknown`;return(0,K.jsxs)(JA,{value:e.path,children:[t,` (`,e.path,`)`]},e.path)})})]})]})]}),d&&(0,K.jsxs)(bE,{children:[A&&s&&s.length>1&&(()=>{let e=c?.[d.name];if(!e)return null;let t=s.find(t=>e.startsWith(t.path+`/`)||e===t.path);return t?(0,K.jsxs)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`mr-auto`,children:[`Installed at `,t.path]}):null})(),(0,K.jsx)(wE,{children:`Cancel`}),(0,K.jsx)(gE,{onConfirm:j,disabled:!b||A,"data-testid":`install-skill-button`,children:i?`Installing...`:A?`Already installed`:`Install`})]})]})})}function tzi({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)(Pc,{}),`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)(Pc,{})}),(0,K.jsx)(ezi,{...c,open:r,onOpenChange:i,workspaceId:t,onInstall:e=>void l(e),isInstalling:a})]})}function nzi({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(YRi(t??``))),[v,y]=(0,G.useState)(t);if(t!==v){y(t);let e=YRi(t??``).filter(e=>!g.has(e));e.length>0&&_(new Set([...g,...e]))}let b=a?.join(`
|
|
725
725
|
`)??``,x=(0,G.useMemo)(()=>({workspaceId:e,activeFilePath:t,setActiveFilePath:i,isSearching:f,setSearching:e=>{p(e),e||h(``)},query:m,setQuery:h,onDelete:n,onCreateDirectory:r,isReadOnly:e=>(b?b.split(`
|
|
726
726
|
`):[]).some(t=>t===`.`||e===t||e.startsWith(`${t}/`)),searchFiles:o,searchSkills:s,fileCount:c,skillCount:l,addSkill:u,openFolders:g,setFolderOpen:(e,t)=>_(n=>{if(n.has(e)===t)return n;let r=new Set(n);return t?r.add(e):r.delete(e),r})}),[e,t,f,m,n,r,i,b,o,s,c,l,u,g]);return(0,K.jsx)(RRi.Provider,{value:x,children:d})}var rzi=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`})}),izi=e=>(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,...e,children:(0,K.jsx)(`path`,{d:`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 azi(){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)(izi,{})})}function ozi(){let{isSearching:e}=K9();return e?(0,K.jsx)(lzi,{}):(0,K.jsx)(czi,{})}var szi=(e,t)=>`${e} ${t}${e===1?``:`s`}`;function czi(){let{fileCount:e,skillCount:t}=K9();return(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`muted`,className:`block min-w-0`,children:(0,K.jsxs)(Gw,{singleLine:!0,children:[(0,K.jsx)(Gw.Item,{children:e===void 0?`Files`:szi(e,`File`)}),t===void 0?null:(0,K.jsx)(Gw.Item,{children:szi(t,`Skill`)})]})})}function lzi(){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)(ZM,{type:`search`,size:`sm`,autoFocus:!0,"aria-label":`Search query`,placeholder:`Search files and skills`,value:n,onChange:e=>{let n=e.target.value;r(n),i(()=>t(n))},onKeyDown:t=>{t.key===`Escape`&&e(!1)}}),(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`Close search`,onClick:()=>e(!1),children:(0,K.jsx)(Hc,{})})]})}function uzi(){let{workspaceId:e,query:t,activeFilePath:n,setActiveFilePath:r,searchFiles:i,searchSkills:a}=K9(),{data:o,isLoading:s,isError:c,error:l}=kVn({workspaceId:e,query:t,files:i,skills:a,queryOptions:{enabled:t.trim().length>0&&(i||a)}});return t.trim()?s?(0,K.jsxs)(`div`,{"aria-busy":`true`,className:`flex flex-col gap-2 p-2`,children:[(0,K.jsx)(dw,{className:`h-4 w-3/4`}),(0,K.jsx)(dw,{className:`h-4 w-2/3`})]}):c?(0,K.jsx)(VRi,{error:l,fallback:`Search failed.`,className:`m-2`}):o?.length?(0,K.jsx)(`ul`,{"aria-label":`Search results`,className:`flex flex-col py-1`,children:o.map(e=>(0,K.jsx)(`li`,{children:(0,K.jsxs)(`button`,{type:`button`,title:e.path,onClick:()=>r(e.path),className:m(`text-foreground`,`flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left hover:bg-fill-subtle`,n===e.path&&`bg-fill`),children:[(0,K.jsx)(TC,{size:`sm`,children:e.kind===`skill`?(0,K.jsx)(mQ,{}):(0,K.jsx)(rzi,{})}),(0,K.jsx)(T,{as:`span`,variant:`body-sm`,className:`truncate`,children:e.label})]})},e.path))}):(0,K.jsx)(RC,{titleSlot:`No results`}):(0,K.jsx)(RC,{titleSlot:`Search files and skills`,descriptionSlot:`Type to find matching content.`})}function dzi({mount:e}){switch(e.icon||e.provider){case`aws-s3`:case`s3`:return(0,K.jsx)(DNn,{className:`text-foreground`});case`google-cloud`:case`google-cloud-storage`:case`gcs`:return(0,K.jsx)(MNn,{});case`azure-blob`:case`azure`:return(0,K.jsx)(ANn,{className:`text-badge-blue-indicator`});case`cloudflare`:case`cloudflare-r2`:case`r2`:return(0,K.jsx)(fr,{className:`text-badge-orange-indicator`});case`neon`:return(0,K.jsx)(fr,{className:`text-badge-green-indicator`});case`minio`:return(0,K.jsx)(Ui,{className:`text-badge-red-indicator`});case`database`:return(0,K.jsx)(Tr,{className:`text-badge-green-indicator`});case`local`:case`folder`:return(0,K.jsx)(Ci,{className:`text-badge-amber-indicator`});case`hard-drive`:return(0,K.jsx)(Ui,{className:`text-muted-foreground`});default:return(0,K.jsx)(fr,{className:`text-muted-foreground`})}}var fzi=e=>(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,...e,children:(0,K.jsx)(`path`,{d:`M1.5 8.5V8C1.5 7.60218 1.65804 7.22064 1.93934 6.93934C2.22064 6.65804 2.60218 6.5 3 6.5H13C13.3978 6.5 13.7794 6.65804 14.0607 6.93934C14.342 7.22064 14.5 7.60218 14.5 8V8.5M8.70667 4.20667L7.29333 2.79333C7.20048 2.70037 7.09022 2.62661 6.96886 2.57628C6.84749 2.52595 6.71739 2.50003 6.586 2.5H3C2.60218 2.5 2.22064 2.65804 1.93934 2.93934C1.65804 3.22064 1.5 3.60218 1.5 4V12C1.5 12.3978 1.65804 12.7794 1.93934 13.0607C2.22064 13.342 2.60218 13.5 3 13.5H13C13.3978 13.5 13.7794 13.342 14.0607 13.0607C14.342 12.7794 14.5 12.3978 14.5 12V6C14.5 5.60218 14.342 5.22064 14.0607 4.93934C13.7794 4.65804 13.3978 4.5 13 4.5H9.414C9.14887 4.49977 8.89402 4.39426 8.70667 4.20667Z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`})}),pzi=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`})}),mzi=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 hzi(){let{workspaceId:e,activeFilePath:t,setActiveFilePath:n}=K9(),{data:r,isLoading:i,error:a}=aY({workspaceId:e,path:`.`}),[o,s]=(0,G.useState)(null);return i?(0,K.jsx)(Czi,{}):r?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(t8,{"aria-label":`Workspace files`,selectedId:t,onSelect:n,className:`py-1`,children:(0,K.jsx)(gzi,{entries:r,parent:`.`,onRequestDelete:s})}),(0,K.jsx)(Szi,{entry:o,onClose:()=>s(null)})]}):(0,K.jsx)(VRi,{error:a,fallback:`Could not load files.`,className:`m-2`})}function gzi({entries:e,parent:t,onRequestDelete:n}){return e.map(e=>{let r=JRi(t,e.name);return e.type===`directory`?(0,K.jsx)(yzi,{name:e.name,path:r,mount:e.mount,onRequestDelete:n},e.name):(0,K.jsx)(xzi,{name:e.name,size:e.size,path:r,onRequestDelete:n},e.name)})}function _zi({children:e}){return(0,K.jsx)(`span`,{className:`ml-auto flex shrink-0 items-center gap-1 opacity-0 group-focus-within:opacity-100 group-hover:opacity-100`,children:e})}function vzi({name:e,onClick:t}){return(0,K.jsx)(X,{variant:`destructive-ghost`,size:`icon-sm`,tooltip:`Delete ${e}`,onClick:e=>{e.stopPropagation(),t()},onKeyDown:e=>e.stopPropagation(),children:(0,K.jsx)(pzi,{})})}function yzi({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}=aY({workspaceId:i,path:t,queryOptions:{enabled:u}}),[f,p]=(0,G.useState)(!1),m=a&&!s(t),h=o&&!s(t);return(0,K.jsxs)(t8.Folder,{id:t,open:u,onOpenChange:e=>l(t,e),children:[(0,K.jsxs)(t8.FolderTrigger,{actions:m||h?(0,K.jsxs)(_zi,{children:[h?(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`New folder in ${e}`,onClick:e=>{e.stopPropagation(),l(t,!0),p(!0)},onKeyDown:e=>e.stopPropagation(),children:(0,K.jsx)(xi,{})}):null,m?(0,K.jsx)(vzi,{name:e,onClick:()=>r({path:t,type:`directory`})}):null]}):void 0,children:[(0,K.jsx)(t8.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)(dzi,{mount:n})}):(0,K.jsx)(fzi,{})}),(0,K.jsx)(t8.Label,{children:e}),n?.status===`error`?(0,K.jsx)(`span`,{role:`img`,"aria-label":`Mount error: ${n.error??`unavailable`}`,title:n.error,className:`flex shrink-0`,children:(0,K.jsx)(Un,{className:`size-3 text-destructive-foreground`})}):null,n&&s(t)?(0,K.jsx)(`span`,{role:`img`,"aria-label":`Read-only`,title:`Read-only`,className:`flex shrink-0`,children:(0,K.jsx)(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)(Qc,{size:`sm`,"aria-label":`Loading ${e}`,className:`size-3 text-muted-foreground`})}):null]}),(0,K.jsx)(t8.FolderContent,{children:u?(0,K.jsx)(bzi,{path:t,creating:f,onCreated:()=>p(!1),onRequestDelete:r}):null})]})}function bzi({path:e,creating:t,onCreated:n,onRequestDelete:r}){let{workspaceId:i,onCreateDirectory:a}=K9(),o=dy(),{data:s,isLoading:c,error:l}=aY({workspaceId:i,path:e}),u=async t=>{try{await a?.(JRi(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)(t8.Input,{type:`folder`,placeholder:`Folder name`,onSubmit:e=>void u(e),onCancel:n}):null,c?null:s?(0,K.jsx)(gzi,{entries:s,parent:e,onRequestDelete:r}):(0,K.jsx)(VRi,{error:l,fallback:`Could not load folder.`,className:`my-1 mr-1`})]})}function xzi({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)(t8.File,{ref:l,id:n,children:[(0,K.jsx)(t8.Icon,{children:(0,K.jsx)(rzi,{})}),(0,K.jsx)(t8.Label,{children:e}),(0,K.jsxs)(_zi,{children:[t===void 0?null:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`faint`,font:`mono`,children:mzi(t)}),s?(0,K.jsx)(vzi,{name:e,onClick:()=>r({path:n,type:`file`})}):null]})]})}function Szi({entry:e,onClose:t}){let{workspaceId:n,activeFilePath:r,setActiveFilePath:i,onDelete:a}=K9(),o=dy(),[s,c]=(0,G.useState)(!1),l=e?.path.split(`/`).pop(),u=async()=>{if(e&&a){c(!0);try{await a(e)}catch{return}finally{c(!1)}(r===e.path||r?.startsWith(`${e.path}/`))&&i(void 0),o.removeQueries({queryKey:[`workspace`,n,`fs`,`list`,e.path]}),await o.invalidateQueries({queryKey:[`workspace`,n,`fs`,`list`,XRi(e.path)]}),t()}},d=null;return e&&(d=e.type===`directory`?`This permanently deletes the folder "${l}" and everything inside it.`:`This permanently deletes "${l}".`),(0,K.jsx)(aP,{open:e!==null,onOpenChange:e=>{!e&&!s&&t()},children:(0,K.jsxs)(aP.Content,{children:[(0,K.jsxs)(aP.Header,{children:[(0,K.jsxs)(aP.Title,{children:[`Delete `,e?.type===`directory`?`folder`:`file`,`?`]}),(0,K.jsxs)(aP.Description,{children:[d,` This action cannot be undone.`]})]}),(0,K.jsxs)(aP.Footer,{children:[(0,K.jsx)(aP.Cancel,{disabled:s,children:`Cancel`}),(0,K.jsx)(X,{variant:`destructive`,disabled:s,onClick:()=>void u(),children:s?`Deleting…`:`Delete`})]})]})})}function Czi(){return(0,K.jsxs)(`div`,{"data-testid":`workspace-tree-skeleton`,"aria-busy":`true`,className:`flex flex-col gap-2 py-2 pl-[18px]`,children:[(0,K.jsx)(dw,{className:`h-4 w-3/4`}),(0,K.jsx)(dw,{className:`h-4 w-1/2`}),(0,K.jsx)(dw,{className:`h-4 w-2/3`})]})}function wzi({children:e,...t}){return(0,K.jsx)(nzi,{...t,children:(0,K.jsx)(Tzi,{children:e})})}function Tzi({children:e}){let{workspaceId:t}=K9(),{data:n,error:r}=aY({workspaceId:t,path:`.`});return(n?n.length===0:XP(r))?(0,K.jsx)(RC,{variant:`fill`,titleSlot:`This workspace is empty`,descriptionSlot:`Files written by your agents will show up here.`,actionSlot:(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:[(0,K.jsx)(ZRi,{labeled:!0}),(0,K.jsx)(tzi,{labeled:!0})]})}):(0,K.jsx)(`div`,{className:`size-full overflow-hidden`,children:(0,K.jsx)(F6,{className:`size-full min-h-0 min-w-0`,orientation:`horizontal`,children:e})})}function Ezi({children:e}){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(hJr,{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)(I6,{className:`w-px bg-border`})]})}function Dzi({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 Ozi(){let{isSearching:e}=K9();return(0,K.jsx)(lw,{className:`min-h-0 flex-1 px-2 py-1`,children:e?(0,K.jsx)(uzi,{}):(0,K.jsx)(hzi,{})})}function kzi({children:e}){return(0,K.jsx)(P6,{id:`workspace-active-file`,className:`flex min-w-0 flex-col`,minSize:30,children:e})}function Azi({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 jzi({renderPreview:e}){let{activeFilePath:t}=K9();return t?(0,K.jsx)(lw,{className:`min-h-0 flex-1`,children:(0,K.jsx)(qRi,{renderPreview:e})}):(0,K.jsx)(RC,{variant:`fill`,titleSlot:`Select a file`})}var q9={Root:wzi,Aside:Ezi,AsideHeader:Dzi,Search:ozi,SearchToggle:azi,CreateDirectory:ZRi,Tree:Ozi,ActiveFile:kzi,ActiveFileHeader:Azi,FilePath:GRi,ActiveFileContent:jzi};function Mzi({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)(tzi,{}),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 Nzi=()=>(0,K.jsx)(RC,{titleSlot:`No Workspaces yet`,descriptionSlot:(0,K.jsxs)(K.Fragment,{children:[`Add a workspace to your Mastra configuration to `,(0,K.jsx)(`br`,{}),`manage files, skills, and enable semantic search.`]}),actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/en/docs/workspace/overview`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(Br,{}),children:`Workspaces documentation`}),variant:`fill`}),Pzi=()=>(0,K.jsx)(RC,{titleSlot:`Workspace Not Configured`,descriptionSlot:(0,K.jsxs)(K.Fragment,{children:[`No workspace is configured. Add a workspace to your `,(0,K.jsx)(`br`,{}),`Mastra configuration to manage files, skills, and enable semantic search.`]}),actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/en/docs/workspace/overview`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(Br,{}),children:`Workspaces documentation`}),variant:`fill`}),Fzi=()=>(0,K.jsx)(RC,{titleSlot:`Workspace Not Supported`,descriptionSlot:(0,K.jsxs)(K.Fragment,{children:[`The workspace feature requires a newer version of `,(0,K.jsx)(`code`,{className:`text-foreground`,children:`@mastra/core`}),`.`,(0,K.jsx)(`br`,{}),`Please upgrade your dependencies to enable workspace functionality.`]}),actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/en/docs/workspace/overview`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(Br,{}),children:`Workspaces documentation`}),variant:`fill`}),Izi=`.agents/skills`,Lzi=e=>e.replace(/^\.?\/+|\/+$/g,``);function Rzi({workspaceId:e,showInitWarning:t,skills:n}){let{data:r}=aY({workspaceId:e,path:Izi,queryOptions:{enabled:!!n}}),i=n&&r?r.filter(e=>e.type===`directory`&&!n.some(t=>t.name===e.name||Lzi(t.path)===`${Izi}/${e.name}`)):[];return!t&&i.length===0?null:(0,K.jsxs)(`div`,{className:`flex shrink-0 flex-col gap-2 border-b border-border p-3`,children:[t&&(0,K.jsx)(EA,{variant:`warning`,children:(0,K.jsxs)(EA.Message,{children:[`File search requires `,(0,K.jsx)(`code`,{children:`workspace.init()`}),` to index files from your configured`,` `,(0,K.jsx)(`code`,{children:`autoIndexPaths`}),`.`]})}),i.length>0&&(0,K.jsx)(EA,{variant:`warning`,title:`Skills installed but not discovered`,children:(0,K.jsxs)(EA.Message,{children:[i.map(e=>e.name).join(`, `),` `,i.length===1?`is`:`are`,` in`,` `,(0,K.jsx)(`code`,{children:Izi}),` but not discovered. Add this path to your workspace skills configuration to see `,i.length===1?`it`:`them`,`.`]})})]})}var J9=[sF(`/workspaces`)],zzi=e=>YP(e)?`you don't have permission to modify this workspace`:e instanceof Error?e.message:`Unknown error`;function Bzi(){let{workspaceId:e}=Ab(),[t,n]=Hb(),r=kb(),i=dy(),a=t.get(`file`),{data:o,error:s,isLoading:c}=bVn(),l=o?.workspaces??[],u=e??l[0]?.id,{data:d,isLoading:f,error:p}=yVn({workspaceId:u,queryOptions:{enabled:!!u}}),m=JP(s)||JP(p),h=YP(s)||YP(p),g=tVn(s)||tVn(p),_=u?l.find(e=>e.id===u):void 0,v=e=>{let r=new URLSearchParams(t);for(let[t,n]of Object.entries(e))n===null?r.delete(t):r.set(t,n);n(r)},y=e=>{r(`/workspaces/${e}`)},b=e=>{v({file:e??null})},x=a??void 0,S=SVn(),C=CVn(),w=d?.isWorkspaceConfigured??!1,T=d?.capabilities?.hasDynamicFilesystem??!1,E=(d?.capabilities?.hasFilesystem??!1)&&!T,D=d?.capabilities?.hasSkills??!1,{data:O,refetch:k}=AVn({workspaceId:u,queryOptions:{enabled:!!u&&E}}),A=hVn(),j=gVn(),M=_Vn(),N=e=>{let t=/^\.agents\/skills\/([^/]+)$/.exec(e);if(t)return re.find(t=>t.path?.replace(/^\.?\/+|\/+$/g,``)===e)?.name??t[1]},P=async()=>{if(u)try{let e=await j.mutateAsync({workspaceId:u}),t=e.updated.filter(e=>!e.success);t.length>0?UC.error(`Failed to update ${t.map(e=>e.skillName).join(`, `)}`):UC.success(`${e.updated.length} skill(s) updated`),i.invalidateQueries({queryKey:[`workspace`,u,`fs`]})}catch(e){UC.error(`Failed to update skills: ${e instanceof Error?e.message:`Unknown error`}`)}},F=async({path:e,type:t})=>{if(!u)return;let n=t===`directory`?N(e):void 0;if(n)try{if(!(await M.mutateAsync({workspaceId:u,skillName:n})).success)throw Error(`Failed to remove skill "${n}"`);UC.success(`Skill "${n}" removed`),k()}catch(e){throw UC.error(e instanceof Error?e.message:`Failed to remove skill`),e}else try{await S.mutateAsync({path:e,recursive:!0,force:!0,workspaceId:u})}catch(t){throw UC.error(`Failed to delete ${e}: ${zzi(t)}`),t}},I=_?.safety?.readOnly??!1,{canEdit:L,canDelete:R,canExecute:z,isLoading:B}=KC(),V=!B&&L(`workspaces`)&&!I,H=!B&&R(`workspaces`)&&!I,ee=!B&&z(`workspaces`),te=E&&D&&V,U=d?.mounts,W=U?.filter(e=>!e.readOnly).map(e=>({path:e.path,displayName:e.displayName,icon:e.icon,provider:e.provider,name:e.name})),ne=async e=>{if(u)try{let t=await A.mutateAsync({...e,workspaceId:u});if(!t.success)throw Error(`Unknown error`);i.invalidateQueries({queryKey:[`workspace`,u,`fs`]}),k(),UC.success(`Skill "${t.skillName}" installed successfully (${t.filesWritten} files)`)}catch(e){throw UC.error(`Failed to install skill: ${e instanceof Error?e.message:`Unknown error`}`),e}},re=O?.skills??[],ie=O?.isSkillsConfigured??!1,ae=ee&&E&&!!(d?.capabilities?.canBM25||d?.capabilities?.canVector),oe=ee&&D&&ie&&re.length>0,se=I?[`.`]:(U??[]).filter(e=>e.readOnly).map(e=>e.path.replace(/^\/+|\/+$/g,``)||`.`);if(c)return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:J9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(Qc,{fill:!0})]});if(m)return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:J9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(jU,{variant:`fill`})]});if(h)return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:J9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(AU,{variant:`fill`,resource:`workspaces`})]});if(g)return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:J9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(Fzi,{})]});let ce=s||p;if(ce)return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:J9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load workspace`,descriptionSlot:ce.message})]});if(!c&&l.length===0)return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:J9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(Nzi,{})]});if(!f&&!c&&!w)return(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:J9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(Pzi,{})]});let le=l.map(e=>({value:e.id,label:e.name,description:e.source===`agent`?`Agent: ${e.agentName}`:`Global workspace`,end:(0,K.jsxs)(`span`,{className:`flex shrink-0 gap-1`,children:[e.safety?.readOnly&&(0,K.jsx)(bw,{size:`xs`,variant:`warning`,children:`Read-only`}),e.capabilities.hasFilesystem&&(0,K.jsx)(bw,{size:`xs`,children:`FS`}),e.capabilities.hasSandbox&&(0,K.jsx)(bw,{size:`xs`,children:`Sandbox`}),e.capabilities.hasSkills&&(0,K.jsx)(bw,{size:`xs`,children:`Skills`})]})}));return(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:J9}),headerActions:(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(TP,{"aria-label":`Workspace`,variant:`ghost`,className:`w-auto`,options:le,value:_?.id,onValueChange:y,placeholder:`Select workspace`,searchPlaceholder:`Search workspaces`,emptyText:`No workspaces found.`}),I&&(0,K.jsx)(bw,{size:`xs`,variant:`warning`,children:`Read-only`})]}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsxs)(`div`,{className:`flex min-h-0 flex-col`,children:[E&&u&&(0,K.jsx)(Rzi,{workspaceId:u,showInitWarning:ae&&!f&&d?.status!==`ready`,skills:D&&O?re:void 0}),E&&u&&(0,K.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,K.jsx)(Mzi,{workspaceId:u,activeFilePath:x,onActiveFileChange:b,readOnlyPaths:se,skillCount:D&&O?re.length:void 0,searchFiles:ae,searchSkills:oe,onCreateDirectory:V?async e=>{try{await C.mutateAsync({path:e,recursive:!0,workspaceId:u})}catch(t){throw UC.error(`Failed to create ${e}: ${zzi(t)}`),t}}:void 0,asideActions:te&&re.some(e=>e.path?.includes(`.agents/skills/`))?(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`Update skills`,disabled:j.isPending,onClick:()=>void P(),children:(0,K.jsx)(Qo,{className:j.isPending?`animate-spin`:void 0})}):void 0,addSkill:te?{onInstall:ne,installedSkillIds:re.filter(e=>e.skillsShSource).map(e=>`${e.skillsShSource.owner}/${e.skillsShSource.repo}/${e.name}`),installedSkillNames:re.filter(e=>!e.skillsShSource).map(e=>e.name),writableMounts:W,installedSkillPaths:Object.fromEntries(re.filter(e=>e.path).map(e=>[e.name,e.path]))}:void 0,onDelete:H?F:void 0},u)}),T&&!f&&(0,K.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,K.jsx)(RC,{variant:`fill`,titleSlot:`Filesystem resolved per request`,descriptionSlot:`This workspace creates its filesystem when an agent runs, so its files can't be browsed here.`})}),!E&&!T&&!f&&(0,K.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,K.jsx)(RC,{variant:`fill`,titleSlot:`No filesystem or skills configured`,descriptionSlot:`Add a filesystem or skills to this workspace to browse its files here.`})})]})]})}function Vzi({children:e,className:t,edgeToEdge:n,mobileHeader:r,ref:i,sidebar:a,...o}){let s=n!==void 0;return(0,K.jsxs)(`div`,{ref:i,"data-slot":`app-shell`,className:m(`h-full min-h-0`,a&&`lg:grid lg:grid-cols-[auto_minmax(0,1fr)] lg:grid-rows-[1fr]`,t),...o,children:[a,(0,K.jsxs)(`div`,{"data-slot":`app-shell-content`,className:`flex h-full min-h-0 min-w-0 flex-col`,children:[r,(0,K.jsx)(`div`,{"data-slot":`app-shell-body`,className:m(`flex min-h-0 flex-1 flex-col`,s&&`transition-[padding] duration-(--resize-dur) ease-(--resize-ease) motion-reduce:transition-none!`,s&&`in-data-[sidebar-gesture=active]:transition-none!`,!n&&`lg:py-2 lg:pr-2`,!n&&(a?`lg:pl-0`:`lg:pl-2`)),children:e})]})]})}function Hzi({children:e,className:t,edgeToEdge:n}){let r=n!==void 0;return(0,K.jsx)(`div`,{"data-slot":`main-card`,className:m(`relative min-h-0 flex-1 overflow-hidden`,r&&`transition-[border-radius,padding,box-shadow] duration-(--resize-dur) ease-(--resize-ease) motion-reduce:transition-none!`,r&&`in-data-[sidebar-gesture=active]:transition-none!`,!n&&`lg:rounded-studio-frame lg:p-px lg:shadow-raised`,fKe,t),children:e})}function Uzi(){return(0,K.jsxs)(`div`,{className:`h-screen bg-sidebar`,children:[(0,K.jsx)(t1e,{position:`bottom-right`}),(0,K.jsx)(M,{defaultTheme:`system`,children:(0,K.jsx)(bC,{delayDuration:0,children:(0,K.jsx)(Vzi,{children:(0,K.jsx)(Hzi,{className:`flex items-center justify-center overflow-y-auto`,children:(0,K.jsx)(Lb,{})})})})})]})}function Wzi(){let{data:e,isLoading:t}=jy(),{isLoading:n,canAccessAgentBuilder:r}=qC();return t||n||!e||e.enabled&&!Ay(e)?{isVisible:!1}:{isVisible:r}}function Gzi(){let{isImpersonating:e,impersonatedRole:t,stopImpersonation:n}=l1e();return!e||!t?null:(0,K.jsxs)(`div`,{className:`mx-3 mb-2 flex items-center gap-2 rounded-md border border-info-edge bg-info-subtle px-3 py-1.5`,children:[(0,K.jsx)(Hr,{className:`h-3.5 w-3.5 shrink-0 text-info-subtle-foreground`}),(0,K.jsxs)(T,{variant:`meta`,className:`truncate text-info-subtle-foreground`,children:[`Previewing `,(0,K.jsx)(`span`,{className:`font-medium capitalize`,children:t.name}),` experience`]}),(0,K.jsx)(`button`,{type:`button`,onClick:n,className:`ml-auto shrink-0 rounded p-0.5 text-info-subtle-foreground hover:bg-info-edge`,title:`Exit role preview`,children:(0,K.jsx)(Hc,{className:`h-3 w-3`})})]})}function Kzi({children:e,contentClassName:t,commandClassName:n,showOverlay:r=!0,overlayClassName:i,...a}){return(0,K.jsx)(CRn,{size:`xl`,showOverlay:r,overlayClassName:m(`bg-sidebar/40 backdrop-blur-none`,i),contentClassName:m(`command-palette-popup overflow-visible bg-transparent shadow-none`,t),commandClassName:m(`command-palette-shell gap-2 overflow-visible rounded-none bg-transparent text-muted-foreground shadow-none backdrop-blur-none`,`[&_[data-slot=command-input-wrapper]_svg]:text-muted-foreground`,`**:[[cmdk-input]]:h-full **:[[cmdk-input]]:text-body`,`**:[[cmdk-group-heading]]:px-2 **:[[cmdk-group-heading]]:pt-2 **:[[cmdk-group-heading]]:pb-1 **:[[cmdk-group]]:p-0`,`**:[[cmdk-item]]:px-2 **:[[cmdk-item]]:py-1.5`,n),...a,children:e})}function qzi({wrapperClassName:e,...t}){return(0,K.jsx)(kJ,{wrapperClassName:m(`command-palette-surface command-palette-surface-input`,LQe,`h-11 shrink-0 rounded-xl border-0 px-3 pr-11`,e),...t})}function Jzi({children:e,className:t,...n}){return(0,K.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,K.jsx)(`div`,{className:m(`grid h-full min-h-0 grid-rows-[auto_minmax(0,1fr)] gap-2 md:grid-cols-[13rem_minmax(0,1fr)] md:grid-rows-none`,t),...n,children:e})})}function Yzi({children:e,className:t,...n}){return(0,K.jsx)(`aside`,{className:m(`command-palette-surface command-palette-surface-rail flex max-h-[min(14rem,32dvh)] min-h-0 flex-col overflow-hidden rounded-xl p-2 md:h-full md:max-h-none`,Gb,t),...n,children:(0,K.jsx)(lw,{className:`-m-1 min-h-0 flex-1 p-1`,children:(0,K.jsx)(cw,{className:`pr-1`,children:(0,K.jsx)(`div`,{className:`flex flex-col gap-1`,children:e})})})})}function Xzi({icon:e,label:t,count:n,active:r,onSelect:i}){return(0,K.jsxs)(`button`,{type:`button`,className:m(ZC,`flex h-9 w-full cursor-pointer items-center gap-2 rounded-lg border border-transparent px-2.5 text-left text-body-sm hover:border-border hover:bg-fill-subtle data-[active=true]:border-border data-[active=true]:bg-fill-hover data-[active=true]:text-foreground`,`transition-[color,transform] duration-fast ease-out-custom active:scale-[0.99] motion-reduce:transition-none`),"data-active":r,"aria-pressed":r,onClick:i,children:[(0,K.jsx)(`span`,{className:`flex size-4 shrink-0 items-center justify-center [&>svg]:size-4`,children:e}),(0,K.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:t}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`rounded-md border border-border bg-muted/70 px-1.5 py-0.5 leading-none`,children:n})]})}function Zzi({children:e,footer:t,...n}){return(0,K.jsxs)(`div`,{role:`region`,className:m(`command-palette-surface command-palette-surface-results command-palette-results-panel relative flex min-h-0 min-w-0 flex-col overflow-hidden rounded-xl`,Gb),...n,children:[(0,K.jsx)(AJ,{scrollArea:!0,scrollAreaClassName:`min-h-0 flex-1 rounded-none`,scrollAreaViewportClassName:`command-palette-scroll-viewport`,className:`command-palette-list max-h-none rounded-none border-none bg-transparent shadow-none`,children:e}),t]})}function Y9({icon:e,title:t,subtitle:n,path:r,badge:i,shortcut:a,className:o,...s}){return(0,K.jsxs)(NJ,{className:m(`group h-auto items-start gap-3 rounded-lg border border-transparent px-3 py-2.5 data-[selected=true]:border-border`,o),...s,children:[(0,K.jsx)(`span`,{className:m(`mt-0.5 flex size-4 max-w-4 min-w-4 shrink-0 basis-4 items-center justify-center text-muted-foreground group-data-[selected=true]:text-foreground [&>svg]:!size-4 [&>svg]:shrink-0`),children:e}),(0,K.jsxs)(`span`,{className:`flex min-w-0 flex-1 flex-col gap-1`,children:[(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`ink`,className:`truncate`,children:t}),i&&(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`shrink-0 rounded-md border border-border bg-muted/60 px-1.5 py-0.5 leading-none uppercase`,children:i})]}),(n||r)&&(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`flex min-w-0 items-center gap-2`,children:[n&&(0,K.jsx)(`span`,{className:`min-w-0 truncate`,children:n}),r&&(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,font:`mono`,className:`max-w-52 truncate rounded-md border border-border bg-muted/70 px-1.5 py-0.5 leading-none`,children:r})]})]}),a&&(0,K.jsx)(TRn,{children:a})]})}function Qzi({label:e}){return(0,K.jsxs)(`div`,{className:`command-palette-footer pointer-events-none absolute inset-x-0 bottom-0 z-20 flex items-end justify-between gap-3 px-3 pt-3 pb-2 text-meta text-muted-foreground`,children:[(0,K.jsx)(`span`,{className:`truncate`,children:e}),(0,K.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1.5`,children:[(0,K.jsx)(PC,{size:`sm`,children:`↑`}),(0,K.jsx)(PC,{size:`sm`,children:`↓`}),(0,K.jsx)(PC,{size:`sm`,children:`↵`}),(0,K.jsx)(PC,{size:`sm`,children:`Esc`})]})]})}var $zi=!1,eBi=new Set,tBi=()=>{eBi.forEach(e=>e())},nBi=e=>(eBi.add(e),()=>eBi.delete(e)),rBi=()=>$zi,iBi=e=>{let t=typeof e==`function`?e($zi):e;t!==$zi&&($zi=t,tBi())},aBi=({enableShortcut:e=!0}={})=>{let t=(0,G.useSyncExternalStore)(nBi,rBi,rBi),n=(0,G.useCallback)(e=>{iBi(e)},[]),r=(0,G.useCallback)(()=>{iBi(e=>!e)},[]);return(0,G.useEffect)(()=>{if(!e)return;let t=e=>{e.key===`k`&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),r())};return document.addEventListener(`keydown`,t),()=>document.removeEventListener(`keydown`,t)},[e,r]),{open:t,setOpen:n,toggle:r}};function oBi(e,t){return[e.name,e.url,t,`path route navigate`].filter(Boolean).join(` `)}function sBi(e){return!e||e===`Studio`?`Path`:e}function cBi(e){return`/traces?entity=${encodeURIComponent(e)}`}var lBi=({scopeOptions:e,activeScope:t,onScopeChange:n})=>(0,K.jsx)(Yzi,{"aria-label":`Search categories`,children:e.map(e=>(0,K.jsx)(Xzi,{icon:e.icon,label:e.label,count:e.count,active:t===e.id,onSelect:()=>n(e.id)},e.id))}),uBi=({sidebar:e,activeScope:t,closeCommand:n})=>!e||t!==`all`&&t!==`settings`?null:(0,K.jsx)(MJ,{heading:`Commands`,children:(0,K.jsx)(Y9,{value:`toggle sidebar collapse expand layout panel`,onSelect:()=>{e.toggleSidebar(),n()},icon:(0,K.jsx)($ee,{}),title:`Toggle sidebar`,subtitle:`Studio layout`})}),dBi=({sections:e,handleSelect:t})=>(0,K.jsx)(K.Fragment,{children:e.map(e=>(0,K.jsx)(MJ,{heading:e.title,children:e.items.map(n=>{let r=n.Icon;return(0,K.jsx)(Y9,{value:oBi(n,e.title),onSelect:()=>t(n.url),icon:(0,K.jsx)(r,{}),title:n.name,subtitle:`Studio path`,path:n.url,badge:sBi(e.title)},n.url)})},e.key))}),fBi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(MJ,{heading:`Agents`,children:t.map(([e,t])=>(0,K.jsx)(Y9,{value:`${t.name} ${e} chat agent conversation thread ${n.agentLink(e)}`,onSelect:()=>r(n.agentLink(e)),icon:(0,K.jsx)(tF,{}),title:t.name,subtitle:`Agent chat`,path:n.agentLink(e),badge:`Agent`},e))}),pBi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(MJ,{heading:`Workflows`,children:t.map(([e,t])=>(0,K.jsx)(Y9,{value:`${t.name} ${e} graph workflow view ${n.workflowLink(e)}`,onSelect:()=>r(n.workflowLink(e)),icon:(0,K.jsx)(rP,{}),title:t.name,subtitle:`Workflow graph`,path:n.workflowLink(e),badge:`Workflow`},e))}),mBi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(MJ,{heading:`Tools`,children:t.map(([e,t])=>(0,K.jsx)(Y9,{value:`tool ${t.id} ${e} ${n.toolLink(e)}`,onSelect:()=>r(n.toolLink(e)),icon:(0,K.jsx)(aF,{}),title:t.id,subtitle:`Tool definition`,path:n.toolLink(e),badge:`Tool`},e))}),hBi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(MJ,{heading:`Processors`,children:t.map(e=>{let t=e.name||e.id,i=e.isWorkflow?n.workflowLink(e.id)+`/graph`:n.processorLink(e.id);return(0,K.jsx)(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)})}),gBi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(MJ,{heading:`MCP Servers`,children:t.map(e=>(0,K.jsx)(Y9,{value:`mcp server ${e.name} ${e.id} ${n.mcpServerLink(e.id)}`,onSelect:()=>r(n.mcpServerLink(e.id)),icon:(0,K.jsx)(nF,{}),title:e.name,subtitle:`MCP server`,path:n.mcpServerLink(e.id),badge:`MCP`},e.id))}),_Bi=({visible:e,agentEntries:t,workflowEntries:n,handleSelect:r})=>e?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(MJ,{heading:`Observability`,children:[(0,K.jsx)(Y9,{value:`observability traces telemetry signals /traces`,onSelect:()=>r(`/traces`),icon:(0,K.jsx)(Hr,{}),title:`Traces`,subtitle:`Runtime traces`,path:`/traces`,badge:`Signal`}),(0,K.jsx)(Y9,{value:`metrics usage latency performance tokens /metrics`,onSelect:()=>r(`/metrics`),icon:(0,K.jsx)(Di,{}),title:`Metrics`,subtitle:`Runtime metrics`,path:`/metrics`,badge:`Signal`}),(0,K.jsx)(Y9,{value:`logs events runtime /logs`,onSelect:()=>r(`/logs`),icon:(0,K.jsx)(Hr,{}),title:`Logs`,subtitle:`Runtime logs`,path:`/logs`,badge:`Signal`})]}),t.length>0&&(0,K.jsx)(MJ,{heading:`Agent Traces`,children:t.map(([e,t])=>{let n=cBi(e);return(0,K.jsx)(Y9,{value:`${t.name} ${e} traces agent observability telemetry`,onSelect:()=>r(n),icon:(0,K.jsx)(Hr,{}),title:t.name,subtitle:`Agent traces`,path:n,badge:`Trace`},e)})}),n.length>0&&(0,K.jsx)(MJ,{heading:`Workflow Traces`,children:n.map(([e,t])=>{let n=cBi(t.name);return(0,K.jsx)(Y9,{value:`${t.name} ${e} traces workflow observability telemetry`,onSelect:()=>r(n),icon:(0,K.jsx)(Hr,{}),title:t.name,subtitle:`Workflow traces`,path:n,badge:`Trace`},e)})})]}):null,vBi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(MJ,{heading:`Scorers`,children:t.map(([e,t])=>{let i=t.scorer?.config?.name||t.scorer?.config?.id||e;return(0,K.jsx)(Y9,{value:`scorer score evaluation ${i} ${e} ${n.scorerLink(e)}`,onSelect:()=>r(n.scorerLink(e)),icon:(0,K.jsx)(Di,{}),title:i,subtitle:`Evaluation scorer`,path:n.scorerLink(e),badge:`Scorer`},e)})}),yBi=()=>{let{open:e,setOpen:t}=aBi(),{navigate:n,paths:r}=_l(),{isMastraPlatform:i}=X8(),a=A3(),[o,s]=G.useState(`all`),{data:c={}}=PP(),{data:l={}}=sP(),{data:u={}}=BJ(),{data:d={}}=qP(),{data:f=[]}=KP(),{data:p={}}=eF(),{isCmsAvailable:m,isLoading:h}=q3(),{hasPermission:g,hasAnyPermission:_,isLoading:v}=KC(),y=e=>{t(e),e||s(`all`)},b=()=>y(!1),x=e=>{n(e),b()},S=G.useCallback(e=>{if(e.hidden||e.url===`/prompts`&&!m&&!h||i&&!e.isOnMastraPlatform)return!1;let t=y1e(e.url);return v&&t&&t!==`public`?!1:b1e(t,g,_)},[_,g,m,h,i,v]),C=Object.entries(c),w=Object.entries(l),T=Object.entries(u),E=Object.values(d).filter(e=>e.phases&&e.phases.length>0),D=Object.entries(p),O=G.useMemo(()=>{let e=[];for(let t of NLt){let n=t.items.filter(S);n.length>0&&e.push({key:t.key,title:t.title,items:n})}let t=[...PLt.filter(S),...i?[]:[{name:`Templates`,url:`/templates`,Icon:Do,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)(_s,{}),count:P},{id:`paths`,label:`Paths`,icon:(0,K.jsx)(ls,{}),count:k},{id:`agents`,label:`Agents`,icon:(0,K.jsx)(tF,{}),count:C.length},{id:`workflows`,label:`Workflows`,icon:(0,K.jsx)(rP,{}),count:w.length},{id:`tooling`,label:`Tooling`,icon:(0,K.jsx)(na,{}),count:A},{id:`evaluation`,label:`Evaluation`,icon:(0,K.jsx)(Di,{}),count:j},{id:`observability`,label:`Intelligence`,icon:(0,K.jsx)(Hr,{}),count:M},{id:`settings`,label:`Studio`,icon:(0,K.jsx)(Rs,{}),count:N}],I=o===`all`||o===`paths`,L=o===`all`||o===`agents`,R=o===`all`||o===`workflows`,z=o===`all`||o===`tooling`,B=o===`all`||o===`evaluation`,V=o===`all`||o===`observability`,H=o===`settings`,ee=G.useMemo(()=>{let e=[];for(let t of O)H?t.key===`studio`&&e.push(t):(o===`evaluation`&&t.key===`evaluation`||o===`observability`&&t.key===`observability`||I&&(o===`all`||t.key!==`studio`))&&e.push(t);return e},[o,O,I,H]);return(0,K.jsxs)(Kzi,{open:e,onOpenChange:y,title:`Mastra Studio Search`,description:`Search Studio routes and runtime entities`,children:[(0,K.jsx)(qzi,{placeholder:`Search Studio, agents, workflows, tools, paths`}),(0,K.jsxs)(Jzi,{children:[(0,K.jsx)(lBi,{scopeOptions:F,activeScope:o,onScopeChange:s}),(0,K.jsxs)(Zzi,{"aria-label":`Search results`,footer:(0,K.jsx)(Qzi,{label:`Studio search`}),children:[(0,K.jsx)(jJ,{children:`No matching results.`}),(0,K.jsx)(uBi,{sidebar:a,activeScope:o,closeCommand:b}),(0,K.jsx)(dBi,{sections:ee,handleSelect:x}),(0,K.jsx)(fBi,{visible:L,entries:C,paths:r,handleSelect:x}),(0,K.jsx)(pBi,{visible:R,entries:w,paths:r,handleSelect:x}),(0,K.jsx)(mBi,{visible:z,entries:T,paths:r,handleSelect:x}),(0,K.jsx)(hBi,{visible:z,entries:E,paths:r,handleSelect:x}),(0,K.jsx)(gBi,{visible:z,entries:f,paths:r,handleSelect:x}),(0,K.jsx)(_Bi,{visible:V,agentEntries:C,workflowEntries:w,handleSelect:x}),(0,K.jsx)(vBi,{visible:B,entries:D,paths:r,handleSelect:x})]})]})]})};function bBi(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 xBi(e){let{Icon:t}=e;return{name:e.name,url:e.url,icon:(0,K.jsx)(t,{})}}function SBi(){let{state:e,isMobile:t,setOpenMobile:n}=j3(),{setOpen:r}=aBi({enableShortcut:!1}),i=f8r(`K`),a=Ob().pathname,{isMastraPlatform:o}=X8(),{data:s}=jy(),{isCmsAvailable:c,isLoading:l}=q3(),{hasPermission:u,hasAnyPermission:d,isLoading:f}=KC(),{data:p}=fgr(),m=p!==void 0&&p.status!==`not-mounted`,h=s&&Ay(s),g=new Set([`/prompts`]),{isVisible:_}=Wzi(),v=a===`/agent-builder`||a.startsWith(`/agent-builder/`),y=()=>{t&&n(!1),r(!0)},b=e=>{if(e.hidden||e.url===`/connections`&&!m||g.has(e.url)&&!c&&!l||o&&!e.isOnMastraPlatform)return!1;if(f){let t=y1e(e.url);if(t&&t!==`public`)return!1}return!!b1e(y1e(e.url),u,d)},{data:x}=KP(),{data:S}=bVn(),C=PLt.filter(b),w=NLt.map(e=>{let t=e.items.filter(b),n=e=>({...xBi(e),isActive:bBi(e,a,t)});return{key:e.key,title:e.title,href:e.href,isHeaderActive:!(!e.href||a!==e.href||t.some(e=>bBi(e,a,t))),links:t.filter(e=>!e.foldable).map(n),moreLinks:t.filter(e=>e.foldable).map(e=>({...n(e),defaultVisible:e.url===`/mcps`&&!!x?.length||e.url===`/workspaces`&&!!S?.workspaces.length}))}});return(0,K.jsxs)(F3,{"aria-label":`Sidebar`,children:[(0,K.jsxs)(F3.Header,{collapsedLogo:(0,K.jsx)(EQ,{className:`size-6`}),actions:h&&(0,K.jsx)(Tir,{}),children:[(0,K.jsx)(F3.Brand,{logo:(0,K.jsx)(EQ,{className:`size-6`}),title:`Mastra Studio`}),!t&&(0,K.jsx)(F3.SearchTrigger,{"aria-label":`Search and navigate`,shortcut:i,onClick:y}),(0,K.jsx)(F3.Trigger,{})]}),_&&(0,K.jsx)(F3.NavList,{className:`mb-1`,children:(0,K.jsx)(F3.NavLink,{state:e,link:{name:`Agent Builder`,url:`/agent-builder`,icon:(0,K.jsx)(Bc,{})},isActive:v})}),(0,K.jsx)(Gzi,{}),(0,K.jsx)(F3.Nav,{children:(0,K.jsx)(F3.Sections,{sections:w,visibilityStorageKey:`mastra:studio:sidebar-visibility`})}),(0,K.jsx)(F3.Footer,{children:(0,K.jsxs)(F3.NavList,{children:[C.map(t=>(0,K.jsx)(F3.NavLink,{state:e,link:xBi(t),isActive:bBi(t,a)},t.name)),(0,K.jsx)(XWr,{state:e})]})})]})}var CBi=()=>{let{baseUrl:e,headers:t,apiPrefix:n,setConfig:r}=YC(),[i,a]=(0,G.useState)(()=>Object.entries(t).map(([e,t])=>({name:e,value:t})));return(0,K.jsx)(bC,{delayDuration:0,children:(0,K.jsxs)(uU,{onSubmit:t=>{t.preventDefault();let a=new FormData(t.currentTarget),o={};for(let e=0;e<i.length;e++){let t=a.get(`headers.${e}.name`),n=a.get(`headers.${e}.value`);typeof t==`string`&&typeof n==`string`&&(o[t]=n)}r({headers:o,baseUrl:e,apiPrefix:n}),UC.success(`Headers saved`)},className:`w-full max-w-md gap-6 text-left`,children:[(0,K.jsx)(jHr,{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)(fs,{}),`Save headers`]})]})})};function wBi({children:e,loginUrl:t=`/login`,signupUrl:n=`/signup`}){let{data:r,isLoading:i}=jy();if(i||!r?.enabled||Ay(r))return(0,K.jsx)(K.Fragment,{children:e});let a=typeof window<`u`?window.location.href:void 0;return r.login?(0,K.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,K.jsxs)(`div`,{className:`flex flex-col items-center space-y-6 text-center`,children:[(0,K.jsx)(EQ,{className:`h-16 w-16 opacity-50`}),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(T,{as:`h2`,variant:`heading`,tone:`ink`,children:`Sign in to continue`}),(0,K.jsx)(`p`,{className:`max-w-sm text-muted-foreground`,children:`You need to sign in to access this page.`})]}),r.login.description&&(0,K.jsxs)(`div`,{className:`flex items-start gap-2.5 rounded-md border border-border bg-background p-3 text-left`,children:[(0,K.jsx)(ja,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}),(0,K.jsx)(T,{tone:`muted`,className:`max-w-sm`,children:r.login.description})]}),(0,K.jsx)(Sir,{config:r.login,redirectUri:a,loginUrl:t}),(r.login.type===`credentials`||r.login.type===`both`)&&r.login.signUpEnabled!==!1&&(0,K.jsxs)(`div`,{children:[(0,K.jsx)(T,{as:`span`,variant:`body`,tone:`muted`,children:`Don't have an account? `}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>{let e=new URL(DQ(n),window.location.origin);a&&e.searchParams.set(`redirect`,a),window.location.href=e.toString()},className:`text-foreground hover:underline`,children:(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:`Sign up`})})]})]})}):(0,K.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,K.jsxs)(`div`,{className:`flex flex-col items-center space-y-6 text-center`,children:[(0,K.jsx)(EQ,{className:`h-16 w-16 opacity-50`}),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(T,{as:`h2`,variant:`heading`,tone:`ink`,children:`Authentication Required`}),(0,K.jsx)(`p`,{className:`max-w-sm text-muted-foreground`,children:`Add the authorization header that Studio needs to reach your Mastra server.`})]}),(0,K.jsx)(CBi,{})]})})}var TBi=`experimental-ui:`,EBi=`current`,DBi=G.createContext(null);function OBi(e,t){let n=window.localStorage.getItem(TBi+e);return n&&t.has(n)?n:EBi}function kBi({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]=OBi(r.key,e)}i(t)},[e,n]);let a=G.useCallback(e=>r[e]??EBi,[r]),o=G.useCallback((e,t)=>{window.localStorage.setItem(TBi+e,t),i(n=>({...n,[e]:t}))},[]),s=G.useMemo(()=>({experiments:e,getVariant:a,setVariant:o}),[e,a,o]);return(0,K.jsx)(DBi.Provider,{value:s,children:t})}var ABi=[{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`}]}],jBi=()=>({experimentalUIEnabled:typeof window<`u`&&window.MASTRA_EXPERIMENTAL_UI===`true`}),MBi=()=>{let{toggleSidebar:e}=j3();return FC({"[":e},{repeat:!1}),null};function NBi(){let{setOpenMobile:e}=j3(),{setOpen:t}=aBi({enableShortcut:!1});return(0,K.jsxs)(`header`,{className:`sticky top-0 z-20 flex h-12 shrink-0 items-center justify-between gap-3 border-b border-border bg-sidebar px-3 lg:hidden`,children:[(0,K.jsxs)(`div`,{className:`flex min-w-0 items-center gap-3`,children:[(0,K.jsx)(F3.MobileTrigger,{}),(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(EQ,{className:`size-[1.5rem] shrink-0`}),(0,K.jsx)(T,{variant:`body-sm`,font:`display`,as:`span`,className:`whitespace-nowrap`,children:`Mastra Studio`})]})]}),(0,K.jsx)(X,{type:`button`,variant:`ghost`,size:`icon-md`,tooltip:`Search`,"aria-label":`Search and navigate`,onClick:()=>{e(!1),t(!0)},className:`shrink-0`,children:(0,K.jsx)(_s,{})})]})}var PBi={"studio-frame":100,"route-side-panel":0},FBi={overflow:`visible`};function IBi({children:e,className:t}){let n=fE(),{hasPanel:r,panelHandle:i,onPanelResize:a}=Y8(),{defaultLayout:o,onLayoutChange:s}=iJr({id:`studio-frame-layout-v1`,storage:localStorage});return(0,K.jsx)(`div`,{className:`relative flex min-h-0 flex-1`,children:(0,K.jsxs)(F6,{className:`min-h-0 flex-1`,style:FBi,orientation:`horizontal`,defaultLayout:o??PBi,onLayoutChange:s,children:[(0,K.jsx)(P6,{id:`studio-frame`,className:m(`min-w-0`,t),style:FBi,children:e}),r&&!n&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(I6,{className:`w-2`}),(0,K.jsx)(hJr,{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)(h3r,{className:`h-full min-h-0`})})]})]})})}function LBi({children:e}){let{data:t,isFetched:n}=jy(),{pathname:r}=Ob(),i=!(n&&t?.enabled&&!Ay(t));return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(yBi,{}),(0,K.jsx)(Vzi,{sidebar:i?(0,K.jsx)(SBi,{}):void 0,mobileHeader:i?(0,K.jsx)(NBi,{}):void 0,children:(0,K.jsx)(IBi,{className:`flex min-h-0 flex-1 flex-col`,children:(0,K.jsx)(Hzi,{children:(0,K.jsx)(wBi,{children:(0,K.jsx)(R1e,{resetKeys:[r],children:e})})})})})]})}var RBi=({children:e})=>{let{experimentalUIEnabled:t}=jBi(),{Link:n}=_l();return(0,K.jsxs)(`div`,{className:`h-screen bg-sidebar`,children:[(0,K.jsx)(t1e,{position:`bottom-right`}),(0,K.jsx)(M,{defaultTheme:`system`,children:(0,K.jsx)(bC,{delayDuration:0,children:(0,K.jsx)(kBi,{experiments:t?ABi:[],children:(0,K.jsxs)(F3.Provider,{LinkComponent:n,children:[(0,K.jsx)(MBi,{}),(0,K.jsx)(m3r,{children:(0,K.jsx)(LBi,{children:e})})]})})})})]})},zBi=({children:e})=>(0,K.jsxs)(`div`,{className:`h-screen bg-sidebar`,children:[(0,K.jsx)(t1e,{position:`bottom-right`}),(0,K.jsx)(M,{defaultTheme:`system`,children:(0,K.jsx)(bC,{delayDuration:0,children:(0,K.jsx)(`div`,{className:`h-full overflow-y-auto`,children:(0,K.jsx)(wBi,{children:e})})})})]}),BBi={name:`Agents`,url:`/agent-builder/agents`,icon:(0,K.jsx)(tF,{})},VBi={name:`Skills`,url:`/agent-builder/skills`,icon:(0,K.jsx)(sn,{className:`size-5`})},HBi={name:`Favorites`,url:`/agent-builder/favorite`,icon:(0,K.jsx)(qs,{className:`size-5`})},UBi={name:`Library`,url:`/agent-builder/library`,icon:(0,K.jsx)(oa,{className:`size-5`})},WBi={name:`Infra`,url:`/agent-builder/infrastructure`,icon:(0,K.jsx)(yte,{className:`size-5`})};function GBi(){let{Link:e}=_l(),{pathname:t}=Ob(),n=Iq(),{canManageSkills:r,canUseFavorites:i}=qC(),{hasPermission:a}=KC(),o=a(`infrastructure:read`),s=(0,G.useMemo)(()=>{let e=[BBi];return n.skills&&r&&e.push(VBi),i&&e.push(HBi),e.push(UBi),o&&e.push(WBi),e},[n.skills,r,i,o]);return(0,K.jsx)(`nav`,{"aria-label":`Primary`,className:`fixed inset-x-0 bottom-0 z-40 border-t border-border bg-sidebar/95 pb-[env(safe-area-inset-bottom)] backdrop-blur-sm md:hidden`,children:(0,K.jsx)(`ul`,{className:`grid`,style:{gridTemplateColumns:`repeat(${s.length}, minmax(0, 1fr))`},children:s.map(n=>{let r=t.startsWith(n.url);return(0,K.jsx)(`li`,{children:(0,K.jsxs)(e,{href:n.url,"aria-current":r?`page`:void 0,className:m(r?`text-foreground`:`text-muted-foreground`,`relative flex flex-col items-center justify-center gap-1 py-2`,f,r?`before:absolute before:inset-x-0 before:-top-px before:h-0.5 before:bg-current`:`hover:text-foreground`),children:[(0,K.jsx)(`span`,{className:`flex size-6 items-center justify-center`,"aria-hidden":`true`,children:(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`block`,children:n.icon})}),(0,K.jsx)(T,{as:`span`,variant:`caption`,children:n.name})]})},n.name)})})})}var KBi={name:`My agents`,url:`/agent-builder/agents`,icon:(0,K.jsx)(tF,{})},qBi={name:`Favorites`,url:`/agent-builder/favorite`,icon:(0,K.jsx)(qs,{})},JBi={name:`Library`,url:`/agent-builder/library`,icon:(0,K.jsx)(oa,{})},YBi={name:`Skills`,url:`/agent-builder/skills`,icon:(0,K.jsx)(sn,{className:`h-4 w-4`})},XBi={name:`Infrastructure`,url:`/agent-builder/infrastructure`,icon:(0,K.jsx)(yte,{className:`h-4 w-4`})};function ZBi({forceExpanded:e=!1}={}){let{Link:t}=_l(),{state:n,isMobile:r}=j3(),{pathname:i}=Ob(),a=Iq(),{canManageSkills:o,canUseFavorites:s}=qC(),{hasPermission:c}=KC(),l=c(`infrastructure:read`),u=e?`default`:n,{data:d}=jy(),f=d&&Ay(d),p=[KBi];a.skills&&o&&p.push(YBi),s&&p.push(qBi),p.push(JBi);let m=(0,K.jsx)(t,{href:`/agents`,"aria-label":`Back to Mastra Studio`,children:(0,K.jsx)(EQ,{className:`size-6`})});return(0,K.jsxs)(F3,{className:`h-full`,mobileMode:`drawer`,children:[!e&&(0,K.jsxs)(F3.Header,{collapsedLogo:m,actions:f&&(0,K.jsx)(Tir,{}),children:[(0,K.jsx)(t,{href:`/agents`,"aria-label":`Back to Mastra Studio`,className:`min-w-0 flex-1`,children:(0,K.jsx)(F3.Brand,{logo:(0,K.jsx)(EQ,{className:`size-6`}),title:`Mastra Studio`})}),!r&&(0,K.jsx)(F3.Trigger,{})]}),(0,K.jsx)(Gzi,{}),(0,K.jsx)(F3.Nav,{children:(0,K.jsx)(F3.NavSection,{children:(0,K.jsx)(F3.NavList,{children:p.map(e=>{let n=i.startsWith(e.url);return(0,K.jsx)(F3.NavLink,{LinkComponent:t,state:u,link:e,isActive:n},e.name)})})})}),!e&&(0,K.jsx)(F3.Footer,{children:l&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(F3.NavSeparator,{}),(0,K.jsx)(F3.NavSection,{children:(0,K.jsx)(F3.NavList,{children:(0,K.jsx)(F3.NavLink,{LinkComponent:t,state:u,link:XBi,isActive:i.startsWith(XBi.url)})})})]})})]})}var X9=()=>(0,K.jsx)(`div`,{className:`h-screen bg-sidebar`,children:(0,K.jsxs)(VUr,{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)(ZBi,{})}),(0,K.jsx)(`div`,{className:`flex h-full min-h-0 flex-col`,children:(0,K.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto bg-transparent pb-[calc(3.5rem+env(safe-area-inset-bottom))] md:pb-0`,children:(0,K.jsx)(Lb,{})})})]}),(0,K.jsx)(GBi,{})]})}),QBi=()=>(0,K.jsx)(`div`,{className:`grid h-screen grid-cols-[minmax(0,1fr)] grid-rows-1 bg-sidebar`,children:(0,K.jsx)(Lb,{})});function $Bi({agentId:e,children:t,disabled:n=!1}){let r=fE(),i=(0,K.jsx)(xQ,{children:(0,K.jsx)(y3r,{agentId:e})},e);return n?t:(0,K.jsxs)(nE,{side:`right`,children:[t,r?(0,K.jsxs)(aE,{children:[(0,K.jsx)(oE,{}),(0,K.jsx)(sE,{children:(0,K.jsxs)(cE,{className:`w-[calc(100vw-2.5rem)] max-w-md`,children:[(0,K.jsx)(uE,{className:`sr-only`,children:`Config`}),(0,K.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:i})]})})]}):(0,K.jsx)(J8,{owner:`agent-detail`,children:i})]})}var eVi=()=>{let{toggle:e}=Y8();return FC({"]":e}),null};function tVi(){let e=fE(),{isCollapsed:t,toggle:n}=Y8();return e?(0,K.jsx)(rE,{asChild:!0,children:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,type:`button`,"aria-label":`Config`,tooltip:`Show config panel`,"data-testid":`agent-overview-panel-toggle`,children:(0,K.jsx)(Z3,{side:`right`})})}):(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,type:`button`,"aria-label":`Config`,"aria-pressed":!t,tooltip:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[t?`Show config panel`:`Hide config panel`,(0,K.jsx)(PC,{size:`xs`,children:`]`})]}),"data-testid":`agent-overview-panel-toggle`,onClick:n,children:(0,K.jsx)(Z3,{side:`right`})})}function nVi({agentId:e,showConfig:t=!0}){let{data:n}=NP({agentId:e,requestContext:mw(`agent`,e)[0],queryOptions:{enabled:!!e}}),{canCreateAgent:r}=wNn(),{Link:i,paths:a}=_l(),{handleCopy:o,isCopied:s}=Aw({text:`${window.location.origin}${DQ(`/agents/${encodeURIComponent(e)}/session`)}`,copyMessage:`Session URL copied to clipboard!`}),c=a.cmsAgentEditLink(e),l=r&&n?.source===`stored`&&!!c;return(0,K.jsxs)(K.Fragment,{children:[l&&(0,K.jsx)(X,{variant:`ghost`,size:`sm`,render:(0,K.jsx)(i,{href:c}),icon:(0,K.jsx)(Ro,{}),children:`Edit`}),(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,type:`button`,"aria-label":`Copy session URL`,onClick:o,tooltip:`Copy session URL to share with your team`,"data-testid":`agent-entity-header-share`,children:s?(0,K.jsx)(Bn,{}):(0,K.jsx)(fa,{})}),t&&(0,K.jsx)(tVi,{})]})}function rVi(e){if(e)try{return lA(e)}catch{return}}function iVi(e){let t=rVi(e.inputSchema);return{inputSchema:t,outputSchema:rVi(e.outputSchema),requestContextSchema:rVi(e.requestContextSchema),zodInputSchema:R9(t)}}function aVi(e,t){let{data:n={},isLoading:r,isError:i}=PP(),a=Object.entries(n).filter(([,t])=>Object.values(t.tools??{}).some(t=>t.id===e)).map(([e,t])=>({id:e,name:t.name||e}));return{agents:[...a.filter(e=>e.id===t),...a.filter(e=>e.id!==t)],isLoading:r,isError:i}}function oVi({agent:e,isCurrent:t}){let{Link:n,paths:r}=_l(),i=(0,K.jsx)(Z.NameCell,{children:(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(TC,{size:`sm`,className:`shrink-0 text-muted-foreground`,children:(0,K.jsx)(tF,{})}),e.name]})});return t?(0,K.jsxs)(Z.RowStatic,{children:[i,(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(bw,{variant:`neutral`,emphasis:`subtle`,children:`Current`})})]}):(0,K.jsxs)(Z.RowLink,{to:r.agentLink(e.id),LinkComponent:n,children:[i,(0,K.jsx)(`span`,{})]})}function sVi({isLoading:e,isError:t,isEmpty:n}){if(e)return`Loading agents…`;if(t)return`Couldn't load the agents that use this tool.`;if(n)return`No agents use this tool yet.`}function cVi({toolId:e,currentAgentId:t}){let{agents:n,isLoading:r,isError:i}=aVi(e,t),a=sVi({isLoading:r,isError:i,isEmpty:n.length===0});return a?(0,K.jsx)(g$,{children:(0,K.jsx)(QNi,{message:a})}):(0,K.jsx)(Z,{columns:`minmax(0,1fr) auto`,fit:`container`,children:n.map(e=>(0,K.jsx)(oVi,{agent:e,isCurrent:e.id===t},e.id))})}function lVi(e){return(0,K.jsxs)(D3,{children:[(0,K.jsx)(JNi,{children:(0,K.jsx)(O3,{children:`Used by`})}),(0,K.jsx)(cVi,{...e})]})}function uVi({tool:e,execution:t,currentAgentId:n,requestContextEntityType:r,requestContextEntityId:i}){let{canExecute:a}=KC(),{inputSchema:o,outputSchema:s,requestContextSchema:c,zodInputSchema:l}=iVi(e);return(0,K.jsx)(qNi,{description:e.description,overview:(0,K.jsx)(UPi,{inputSchema:o,outputSchema:s,requestContextSchema:c,footer:(0,K.jsx)(lVi,{toolId:e.id,currentAgentId:n})}),canRun:a(`tools`),playground:(0,K.jsx)(RPi,{zodInputSchema:l,execution:t,requestContextEntityType:r,requestContextEntityId:i})})}function dVi({agentId:e}){let t=HPi(),[n]=mw(`agent`,e),{data:r,isLoading:i}=NP({agentId:e,requestContext:n}),{mutateAsync:a,status:o,data:s,error:c}=nIt(),l=Object.values(r?.tools??{}).find(e=>e.id===t),u={execute:(n,r)=>a({agentId:e,toolId:t,input:n,playgroundRequestContext:r}),status:o,output:s,error:c};return i?(0,K.jsx)(m$.LoadingData,{}):l?(0,K.jsx)(uVi,{tool:l,execution:u,currentAgentId:e,requestContextEntityType:`agent-tool`,requestContextEntityId:`${e}:${l.id}`}):(0,K.jsxs)(m$.NoData,{children:[`This agent has no tool "`,t,`".`]})}var fVi=[sF(`/agents`),zLt],pVi=({agentId:e})=>{let t=kb();return FC({"g$+t":()=>t(`/agents/${e}/traces`)}),null},mVi=k8.threadId;function hVi(e,t,n){if(e===`chat`){let e=Vy(`/agents/:agentId/threads/:threadId`,t)?.params.threadId;return e===`new`?void 0:e}if(e===`traces`){let e=new URLSearchParams(n),t=e.get(j8(mVi));return t&&t!==`is`?void 0:e.get(mVi)||void 0}}var gVi=({children:e})=>{let{agentId:t}=Ab(),n=Ob(),{isCmsAvailable:r}=q3(),{hasObservability:i}=kFt(),a=qc.has(`datasets`),o=r&&a,s=i&&a,{data:c}=NP({agentId:t,requestContext:mw(`agent`,t)[0],queryOptions:{enabled:!!t}}),l=Lq(c?.provider??``),u=c?.modelId??``,d=n.pathname.includes(`/threads`)?`chat`:n.pathname.includes(`/editor`)?`versions`:n.pathname.includes(`/traces`)?`traces`:`none`,f=hVi(d,n.pathname,n.search);return(0,K.jsx)(Far,{defaultProvider:l,defaultModel:u,children:(0,K.jsxs)(Lte,{children:[(0,K.jsx)(pVi,{agentId:t}),(0,K.jsx)(eVi,{}),(0,K.jsx)(gFi,{children:(0,K.jsx)(dVi,{agentId:t})}),(0,K.jsx)($Bi,{agentId:t,disabled:d===`versions`,children:(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:fVi}),headerActions:(0,K.jsx)(nVi,{agentId:t,showConfig:d!==`versions`}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:t}),(0,K.jsxs)(`div`,{className:`grid h-full min-h-0 grid-cols-[minmax(0,1fr)] grid-rows-[auto_minmax(0,1fr)]`,children:[(0,K.jsx)(O0r,{agentId:t,activeTab:d,threadId:f,showPlayground:o,showObservability:s}),e]})]})})]})},`${t}:${l}/${u}`)};function _Vi(e,t){let n=e.page,r=new Map([...e.ancestors,n].map(e=>[e.id,e]));return{name:n.name,kind:n.isScope?n.displayLabel??`Scope`:`Page`,pageRef:cOi(n,r),childCount:t?.pages.length?`${t.pages.length}${t.nextCursor?`+`:``}`:void 0}}function vVi(e,t){let n=e.split(`#`)[0]?.split(`:`)[0];return!!(n&&e.includes(`:`)&&t?.pages.some(e=>e.isScope&&e.address?.split(`:`)[0]===n))}function yVi(e){let t=Y(),n=Yji().data?.[0]?.key,r=e.pageId??e.pageRef,i=Ey({queryKey:[`knowledge`,n,`tree`,null,null],queryFn:n?async()=>t.getKnowledge(n).tree({}):yy,staleTime:3e4}),a=e.pageId!==void 0||e.pageRef!==void 0&&vVi(e.pageRef,i.data),{data:o}=Ey({queryKey:[`knowledge`,n,`page`,r,null],queryFn:n&&r&&a?async()=>t.getKnowledge(n).page(r):yy,retry:!1,staleTime:3e4}),s=o?.page.id,c=Ey({queryKey:[`knowledge`,n,`tree`,s??null,null],queryFn:n&&s?async()=>t.getKnowledge(n).tree({parentId:s}):yy,staleTime:3e4});return o?_Vi(o,c.data):void 0}function bVi({children:e}){return(0,K.jsx)(X6n,{pageHref:hZ,refHref:hZ,usePagePreview:yVi,children:e})}var xVi=()=>{let e=kb();return FC({"g$+a":()=>e(`/agents`),"g$+p":()=>e(`/prompts`),"g$+w":()=>e(`/workflows`),"g$+c":()=>e(`/processors`),"g$+m":()=>e(`/mcps`),"g$+o":()=>e(`/tools`),"g$+k":()=>e(`/workspaces`),"g$+s":()=>e(`/scorers`),"g$+d":()=>e(`/datasets`),"g$+x":()=>e(`/experiments`),"g$+q":()=>e(`/experiments/review-queue`),"g$+n":()=>e(`/metrics`),"g$+t":()=>e(`/traces`),"g$+l":()=>e(`/logs`),"g$+,":()=>e(`/settings`),"g$+h":()=>e(`/resources`)}),null},SVi=sF(`/traces`);function CVi(e){return e.startsWith(`/spans`)?`spans`:e.startsWith(`/threads`)?`threads`:`traces`}function wVi({children:e}){let{pathname:t}=Ob(),n=kb();return(0,K.jsx)(fIi,{current:CVi(t),features:oui,onViewChange:e=>n(`/${e}`),breadcrumbs:e=>{let t=wIi(e);return(0,K.jsx)(EP,{crumbs:t?[SVi,{id:e.current,label:t}]:[SVi]})},children:e})}var TVi=()=>(0,K.jsx)(RC,{titleSlot:`No Processors yet`,descriptionSlot:`Configure processors. Add input or output processors to your agents to transform messages.`,actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/docs/agents/processors`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(Br,{}),children:`Processors documentation`}),variant:`fill`}),EVi=[`input`,`inputStep`,`outputStep`,`outputStream`,`outputResult`],DVi={name:e=>e.name||e.id,agents:e=>e.agentIds?.length??0};function OVi({processors:e,isLoading:t,search:n=``,sort:r,onSortChange:i}){let{paths:a,Link:o}=_l(),s=(0,G.useMemo)(()=>Object.values(e??{}).filter(e=>e.phases&&e.phases.length>0),[e]),c=(0,G.useMemo)(()=>{let e=n.toLowerCase();return yQ(s.filter(t=>t.id.toLowerCase().includes(e)||(t.name||``).toLowerCase().includes(e)),r,DVi)},[s,n,r]),{containerRef:l,getRowProps:u}=_Q({count:c.length,global:!0});if(t)return(0,K.jsx)(NU,{columns:`auto 1fr auto auto auto auto auto auto`});let d=e=>r?.key===e?r.direction:void 0;return(0,K.jsxs)(Z,{columns:`auto 1fr auto auto auto auto auto auto`,scrollRef:l,children:[(0,K.jsxs)(Z.Top,{children:[i?(0,K.jsx)(Z.SortableTopCell,{sortKey:`name`,sort:d(`name`),onSortChange:i,children:`Name`}):(0,K.jsx)(Z.TopCell,{children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`Description`}),(0,K.jsx)(Z.TopCellSmart,{long:`Input`,short:`Input`,tooltip:`Contains input phase`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Input Step`,short:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Qr,{}),` Step`]}),tooltip:`Contains input step phase`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Output Step`,short:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(ei,{}),` Step`]}),tooltip:`Contains output step phase`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Output Stream`,short:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(ei,{}),` Stream`]}),tooltip:`Contains output stream phase`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Output Result`,short:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(ei,{}),` Result`]}),tooltip:`Contains output result phase`,className:`text-center`}),i?(0,K.jsx)(Z.SortableTopCell,{sortKey:`agents`,sort:d(`agents`),onSortChange:i,align:`end`,children:`Used by`}):(0,K.jsx)(Z.TopCellSmart,{short:`Used by`,long:`Used by Agents`,className:`text-center`})]}),c.length===0&&n?(0,K.jsx)(Z.NoMatch,{message:`No Processors match your search`}):null,c.map((e,t)=>{let n=fY(e.name||e.id,50),r=fY(e.description??``,200),i=e.agentIds?.length??0,s=new Set(e.phases||[]),c=e.isWorkflow?a.workflowLink(e.id)+`/graph`:a.processorLink(e.id);return(0,K.jsxs)(Z.RowLink,{to:c,LinkComponent:o,...u(t),children:[(0,K.jsx)(Z.NameCell,{children:n}),(0,K.jsx)(Z.DescriptionCell,{children:r}),EVi.map(e=>(0,K.jsx)(Z.TextCell,{className:`text-center`,children:s.has(e)&&(0,K.jsx)(Bn,{className:`mx-auto size-4`})},e)),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:i||``})]},e.id)})]})}var Z9=[sF(`/processors`)];function kVi(){let{data:e={},isLoading:t,error:n}=qP(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)();return n&&JP(n)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Z9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Processors`}),(0,K.jsx)(jU,{variant:`fill`})]}):n&&YP(n)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Z9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Processors`}),(0,K.jsx)(AU,{variant:`fill`,resource:`processors`})]}):n?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Z9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Processors`}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load processors`,descriptionSlot:n.message})]}):Object.keys(e).length===0&&!t?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Z9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Processors`}),(0,K.jsx)(TVi,{})]}):(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Z9}),actionRow:(0,K.jsx)(jq,{children:(0,K.jsx)(jq.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(zU,{onSearch:i,label:`Filter processors`,placeholder:`Filter by name`})})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Processors`}),(0,K.jsx)(OVi,{processors:e,isLoading:t,search:r,sort:a,onSortChange:(e,t)=>o({key:t,direction:e})})]})}var AVi={input:`Input - Process input messages before LLM (once at start)`,inputStep:`Input Step - Process at each agentic loop step`,outputStream:`Output Stream - Process streaming chunks`,outputResult:`Output Result - Process complete output after streaming`,outputStep:`Output Step - Process after each LLM response (before tools)`,toolResult:`Tool Result - Process tool output before it is added to the message list`,llmRequest:`LLM Request - Transform the provider prompt before each LLM call`};function jVi({processorId:e}){let{data:t,isLoading:n,error:r}=YIt({processorId:e,queryOptions:{enabled:!!e}});return(0,G.useEffect)(()=>{if(r){let e=r instanceof Error?r.message:`Failed to load processor`;UC.error(`Error loading processor: ${e}`)}},[r]),n?(0,K.jsxs)(`div`,{className:`p-4`,children:[(0,K.jsx)(dw,{className:`mb-4 h-8 w-48`}),(0,K.jsx)(dw,{className:`h-32 w-full`})]}):r?null:t?(0,K.jsx)(MVi,{processor:t}):(0,K.jsx)(`div`,{className:`px-4 py-8 text-center`,children:(0,K.jsx)(T,{variant:`heading`,tone:`muted`,children:`Processor not found`})})}function MVi({processor:e}){let t=PT(),[n,r]=(0,G.useState)(e.phases[0]||`input`),[i,a]=(0,G.useState)(e.configurations[0]?.agentId||``),[o,s]=(0,G.useState)(`Hello, this is a test message.`),[c,l]=(0,G.useState)(null),[u,d]=(0,G.useState)(),f=XIt(),p=async()=>{d(void 0),l(null);let t=n===`outputStep`||n===`outputResult`?`assistant`:`user`,r=[{id:crypto.randomUUID(),role:t,createdAt:new Date,content:{format:2,parts:[{type:`text`,text:o}]}}];try{let t=await f.mutateAsync({processorId:e.id,phase:n,messages:r,agentId:i||void 0});l(t),!t.success&&t.error&&d(t.error)}catch(e){d(e.message||`An error occurred`)}},m=c?JSON.stringify(c,null,2):`{}`;return(0,K.jsxs)(`div`,{className:`relative grid h-full min-w-min grid-cols-[auto_1fr] overflow-x-auto overflow-y-auto`,children:[(0,K.jsxs)(`div`,{className:`w-[22rem] overflow-y-auto border-r border-border`,children:[(0,K.jsx)(NVi,{processor:e}),(0,K.jsxs)(`div`,{className:`space-y-5 p-5`,children:[(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{children:`Phase`}),(0,K.jsxs)(WA,{value:n,onValueChange:t=>{let n=e.phases.find(e=>e===t);n&&r(n)},children:[(0,K.jsx)(KA,{className:`w-full`,children:(0,K.jsx)(GA,{placeholder:`Select phase`})}),(0,K.jsx)(qA,{children:e.phases.map(e=>(0,K.jsx)(JA,{value:e,children:e},e))})]})]}),(0,K.jsx)(T,{variant:`meta`,tone:`muted`,children:AVi[n]})]}),e.configurations.length>1&&(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{children:`Agent Configuration`}),(0,K.jsxs)(WA,{value:i,onValueChange:a,children:[(0,K.jsx)(KA,{className:`w-full`,children:(0,K.jsx)(GA,{placeholder:`Select agent`})}),(0,K.jsx)(qA,{children:e.configurations.map(e=>(0,K.jsxs)(JA,{value:e.agentId,children:[e.agentName,` (`,e.type,`)`]},e.agentId))})]})]}),(0,K.jsxs)(fA,{children:[(0,K.jsx)(mA,{children:`Test Message`}),(0,K.jsx)(ZA,{value:o,onChange:e=>s(e.target.value),placeholder:`Enter a test message`,rows:4})]}),(0,K.jsx)(X,{icon:(0,K.jsx)(Ho,{}),onClick:p,disabled:f.isPending||n===`outputStream`||n===`llmRequest`,className:`w-full`,children:f.isPending?`Running...`:`Run processor`}),n===`outputStream`&&(0,K.jsx)(T,{variant:`meta`,className:`text-warning-foreground`,children:`Output Stream phase cannot be executed directly. Use streaming instead.`}),n===`llmRequest`&&(0,K.jsx)(T,{variant:`meta`,className:`text-warning-foreground`,children:`LLM Request phase cannot be executed directly. It runs on the provider prompt during an agent call.`}),c&&(0,K.jsxs)(`div`,{className:`space-y-2 border-t border-border pt-4`,children:[(0,K.jsx)(T,{variant:`caption`,tone:`muted`,children:`Status`}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(bw,{variant:c.success?`success`:`destructive`,children:c.success?`Success`:`Failed`}),c.tripwire?.triggered&&(0,K.jsx)(bw,{variant:`info`,children:`Tripwire Triggered`})]}),c.tripwire?.triggered&&c.tripwire.reason&&(0,K.jsxs)(`div`,{className:`mt-2 rounded-md border border-warning-edge bg-warning-subtle p-3`,children:[(0,K.jsx)(T,{variant:`column`,className:`text-warning-subtle-foreground`,children:`Tripwire Reason`}),(0,K.jsx)(T,{variant:`caption`,tone:`muted`,className:`mt-1`,children:c.tripwire.reason})]})]})]})]}),(0,K.jsx)(`div`,{className:`absolute top-4 right-4 z-10`,children:(0,K.jsx)(jw,{content:m,tooltip:`Copy JSON result to clipboard`})}),(0,K.jsx)(`div`,{className:`relative h-full overflow-x-auto overflow-y-auto p-5`,children:(0,K.jsx)(MT,{value:u||m,editable:!0,theme:t,extensions:[mt,NT],basicSetup:{foldGutter:!1}})})]})}function NVi({processor:e}){return(0,K.jsxs)(`div`,{className:`border-b border-border px-5 pt-5 pb-4`,children:[(0,K.jsx)(T,{variant:`heading`,tone:`faint`,className:`mb-2`,children:e.name||e.id}),e.name&&e.name!==e.id&&(0,K.jsx)(T,{variant:`caption`,tone:`muted`,className:`mb-3`,children:e.id}),(0,K.jsx)(`div`,{className:`mt-3 flex flex-wrap gap-1`,children:e.phases.map(e=>(0,K.jsx)(bw,{children:e},e))}),(0,K.jsx)(`div`,{className:`mt-3`,children:(0,K.jsxs)(T,{variant:`meta`,tone:`muted`,children:[`Attached to `,e.configurations.length,` agent`,e.configurations.length===1?``:`s`]})})]})}var Q9=[sF(`/processors`),VLt];function PVi(){let{processorId:e}=Ab(),{data:t,isLoading:n,error:r}=YIt({processorId:e,queryOptions:{enabled:!!e}});return r&&JP(r)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(jU,{variant:`fill`})]}):r&&YP(r)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(AU,{variant:`fill`,resource:`processors`})]}):!n&&t?.isWorkflow?(0,K.jsx)(Ib,{to:`/workflows/${e}/graph`,replace:!0}):n?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:Q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(dw,{className:`mb-4 h-8 w-48`}),(0,K.jsx)(dw,{className:`h-32 w-full`})]}):(0,K.jsxs)(uw,{variant:`fit`,breadcrumbs:(0,K.jsx)(EP,{crumbs:Q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(`div`,{className:`h-full w-full overflow-y-hidden`,children:(0,K.jsx)(jVi,{processorId:e})})]})}function FVi(){let e=HPi(),{data:t,isLoading:n}=mzn({toolId:e}),{mutateAsync:r,status:i,data:a,error:o}=hzn(),s={execute:(t,n)=>r({toolId:e,input:t,requestContext:n}),status:i,output:a,error:o};return n?(0,K.jsx)(m$.LoadingData,{}):t?(0,K.jsx)(uVi,{tool:t,execution:s,requestContextEntityType:`tool`,requestContextEntityId:t.id}):(0,K.jsxs)(m$.NoData,{children:[`Tool "`,e,`" not found.`]})}var IVi=()=>(0,K.jsx)(RC,{titleSlot:`No Tools yet`,descriptionSlot:(0,K.jsxs)(K.Fragment,{children:[`Mastra tools are not configured yet. `,(0,K.jsx)(`br`,{}),`More information in the documentation.`]}),actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/docs/agents/using-tools-and-mcp`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(Br,{}),children:`Tools documentation`}),variant:`fill`}),LVi=(e,t)=>{let n=new Map,r=Object.keys(t);for(let e of r){let r=t[e],i=r.tools,a=Object.keys(i);for(let t of a){let a=i[t];n.has(a.id)||n.set(a.id,{...a,agents:[]}),n.get(a.id).agents.push({...r,id:e})}}for(let[t,r]of Object.entries(e))n.has(r.id)||n.set(r.id,{...r,agents:[]});return Array.from(n.values())},RVi={name:e=>e.id,agents:e=>e.agents.length};function zVi({tools:e,agents:t,isLoading:n,search:r=``,sort:i,onSortChange:a,selectedToolId:o}){let{paths:s,Link:c}=_l(),l=(0,G.useMemo)(()=>LVi(e,t),[e,t]),u=(0,G.useMemo)(()=>yQ(l.filter(e=>e.id.toLowerCase().includes(r.toLowerCase())),i,RVi),[l,r,i]),{containerRef:d,getRowProps:f}=_Q({count:u.length,global:!0});if(n)return(0,K.jsx)(NU,{columns:`auto 1fr auto`});let p=e=>i?.key===e?i.direction:void 0;return(0,K.jsxs)(Z,{columns:`auto 1fr auto`,scrollRef:d,children:[(0,K.jsxs)(Z.Top,{children:[a?(0,K.jsx)(Z.SortableTopCell,{sortKey:`name`,sort:p(`name`),onSortChange:a,children:`Name`}):(0,K.jsx)(Z.TopCell,{children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`Description`}),a?(0,K.jsx)(Z.SortableTopCell,{sortKey:`agents`,sort:p(`agents`),onSortChange:a,align:`end`,children:`Agents`}):(0,K.jsx)(Z.TopCellSmart,{long:`Agents`,short:(0,K.jsx)(tF,{}),tooltip:`Attached agents`,className:`text-center`})]}),u.length===0&&r?(0,K.jsx)(Z.NoMatch,{message:`No Tools match your search`}):null,u.map((e,t)=>{let n=fY(e.id,50),r=fY(e.description??``,200),i=e.agents.length;return(0,K.jsxs)(Z.RowLink,{to:s.toolLink(e.id),LinkComponent:c,featured:e.id===o,...f(t),children:[(0,K.jsx)(Z.NameCell,{children:n}),(0,K.jsx)(Z.DescriptionCell,{children:r}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:i||``})]},e.id)})]})}var $9=[sF(`/tools`)];function BVi(){let{data:e={},isLoading:t,error:n}=PP(),{data:r={},isLoading:i,error:a}=BJ(),[o,s]=(0,G.useState)(``),[c,l]=(0,G.useState)(),{toolId:u}=hFi(),d=t||i,f=a||n;return f&&JP(f)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:$9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Tools`}),(0,K.jsx)(jU,{variant:`fill`})]}):f&&YP(f)?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:$9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Tools`}),(0,K.jsx)(AU,{variant:`fill`,resource:`tools`})]}):f?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:$9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Tools`}),(0,K.jsx)(RC,{tone:`error`,variant:`fill`,titleSlot:`Failed to load tools`,descriptionSlot:f.message})]}):Object.keys(r).length===0&&!d?(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:$9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Tools`}),(0,K.jsx)(IVi,{})]}):(0,K.jsxs)(uw,{breadcrumbs:(0,K.jsx)(EP,{crumbs:$9}),actionRow:(0,K.jsx)(jq,{children:(0,K.jsx)(jq.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(zU,{onSearch:s,label:`Filter tools`,placeholder:`Filter by name`})})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Tools`}),(0,K.jsx)(zVi,{tools:r,agents:e,isLoading:d,search:o,sort:c,onSortChange:(e,t)=>l({key:t,direction:e}),selectedToolId:u}),(0,K.jsx)(gFi,{children:(0,K.jsx)(FVi,{})})]})}var VVi=()=>{let e=kb();return(0,K.jsx)(gl,{Link:JC,navigate:t=>e(t),paths:LMn,children:(0,K.jsxs)(Ite,{children:[(0,K.jsx)(xVi,{}),(0,K.jsx)(bVi,{children:(0,K.jsx)(RBi,{children:(0,K.jsx)(S1e,{children:(0,K.jsx)(Lb,{})})})})]})})},HVi=()=>{let e=kb();return(0,K.jsx)(gl,{Link:JC,navigate:t=>e(t),paths:LMn,children:(0,K.jsx)(zBi,{children:(0,K.jsx)(Lb,{})})})},UVi=!!window.MASTRA_CLOUD_API_ENDPOINT,WVi=qc.has(`datasets`),GVi=[{index:!0,element:(0,K.jsx)(Qui,{})},{path:`instruction-blocks`,element:(0,K.jsx)($ui,{})},{path:`tools`,element:(0,K.jsx)(rdi,{})},{path:`agents`,element:(0,K.jsx)(Gui,{})},{path:`scorers`,element:(0,K.jsx)(tdi,{})},{path:`workflows`,element:(0,K.jsx)(adi,{})},{path:`skills`,element:(0,K.jsx)(ndi,{})},{path:`memory`,element:(0,K.jsx)(edi,{})},{path:`variables`,element:(0,K.jsx)(idi,{})}],KVi=[{element:(0,K.jsx)(Uzi,{}),children:[{path:`/login`,element:(0,K.jsx)(dMi,{})},{path:`/signup`,element:(0,K.jsx)(oIi,{})}]},{path:`/agent-builder`,element:(0,K.jsx)(p1e,{paths:LMn}),children:[{index:!0,element:(0,K.jsx)(BMn,{})},{path:`agents`,element:(0,K.jsx)(X9,{}),children:[{index:!0,element:(0,K.jsx)(pzn,{})}]},{path:`agents`,element:(0,K.jsx)(QBi,{}),children:[{path:`create`,element:(0,K.jsx)(Tzn,{})},{path:`:id`,loader:({params:e})=>qy(`/agent-builder/agents/${e.id}/view`)},{path:`:id/edit`,element:(0,K.jsx)(atr,{})},{path:`:id/view`,element:(0,K.jsx)(mnr,{})}]},{path:`skills`,element:(0,K.jsx)(X9,{}),children:[{index:!0,element:(0,K.jsx)(Unr,{})}]},{path:`skills`,element:(0,K.jsx)(QBi,{}),children:[{path:`create`,element:(0,K.jsx)(qnr,{})},{path:`:id`,loader:({params:e})=>qy(`/agent-builder/skills/${e.id}/edit`)},{path:`:id/edit`,element:(0,K.jsx)(yrr,{})},{path:`:id/view`,element:(0,K.jsx)(Drr,{})}]},{path:`infrastructure`,element:(0,K.jsx)(X9,{}),children:[{index:!0,element:(0,K.jsx)(Mnr,{})}]},{path:`favorite`,element:(0,K.jsx)(X9,{}),children:[{index:!0,element:(0,K.jsx)(Enr,{})}]},{path:`library`,element:(0,K.jsx)(X9,{}),children:[{index:!0,element:(0,K.jsx)(Nnr,{})}]}]},{element:(0,K.jsx)(HVi,{}),children:[{path:`/agents/:agentId/session`,element:(0,K.jsx)(f2r,{})},{path:`/agents/:agentId/session/:threadId`,element:(0,K.jsx)(f2r,{})}]},{element:(0,K.jsx)(VVi,{}),children:[...UVi?[]:[{path:`/settings`,element:(0,K.jsx)(aIi,{})},{path:`/templates`,element:(0,K.jsx)(dLi,{})},{path:`/templates/:templateSlug`,element:(0,K.jsx)(DLi,{})}],{path:`/logs`,element:(0,K.jsx)(uNi,{})},{path:`/scorers`,element:(0,K.jsx)(KFi,{})},{path:`/scorers/:scorerId`,element:(0,K.jsx)(eIi,{})},{path:`/metrics`,element:(0,K.jsx)(FFi,{})},{path:`/intelligence`,element:(0,K.jsx)(Ibn,{})},{path:`/intelligence/entities/:entityType/:entityId`,element:(0,K.jsx)(axn,{})},{element:(0,K.jsx)(wVi,{children:(0,K.jsx)(Lb,{})}),children:[{path:`/traces`,element:(0,K.jsx)(Uui,{})},{path:`/spans`,element:(0,K.jsx)(WIi,{})},{path:`/threads`,element:(0,K.jsx)(VLi,{})}]},{path:`/traces/:traceId`,loader:({params:e,request:t})=>{let n=new URL(t.url).searchParams;return n.set(`traceId`,e.traceId??``),qy(`/traces?${n.toString()}`)}},{path:`/observability`,loader:({request:e})=>qy(`/traces${new URL(e.url).search}`)},{path:`/resources`,element:(0,K.jsx)(WFi,{})},{path:`/agents`,element:(0,K.jsx)(sir,{})},{path:`/cms/agents/create`,element:(0,K.jsx)(qui,{}),children:GVi},{path:`/cms/agents/:agentId/edit`,element:(0,K.jsx)(Zui,{}),children:GVi},{path:`/cms/scorers/create`,element:(0,K.jsx)(mdi,{})},{path:`/cms/scorers/:scorerId/edit`,element:(0,K.jsx)(vdi,{})},{path:`/prompts`,element:(0,K.jsx)(VFi,{})},{path:`/cms/prompts/create`,element:(0,K.jsx)(sdi,{})},{path:`/cms/prompts/:promptBlockId/edit`,element:(0,K.jsx)(fdi,{})},{path:`/agents/:agentId`,element:(0,K.jsx)(gVi,{children:(0,K.jsx)(Lb,{})}),children:[{index:!0,loader:NMn},{path:`chat`,loader:PMn},{path:`chat/:threadId`,loader:PMn},{path:`threads`,loader:MMn},{path:`threads/:threadId`,element:(0,K.jsx)(W4r,{})},{path:`overview`,loader:IMn},{path:`settings`,loader:IMn},...WVi?[{path:`editor`,element:(0,K.jsx)(w3r,{})}]:[],{path:`traces`,element:(0,K.jsx)(Wui,{})},{path:`channels`,loader:({params:e})=>qy(`/agents/${e.agentId}/threads/new`)}]},{path:`/tools`,element:(0,K.jsx)(BVi,{})},{path:`/integrations`,element:(0,K.jsx)(jDi,{})},{path:`/connections`,element:(0,K.jsx)(yfi,{})},{path:`/processors`,element:(0,K.jsx)(kVi,{})},{path:`/processors/:processorId`,element:(0,K.jsx)(PVi,{})},{path:`/mcps`,element:(0,K.jsx)(hNi,{})},{path:`/mcps/:serverId`,element:(0,K.jsx)(_Fi,{})},{path:`/workspaces`,element:(0,K.jsx)(Bzi,{})},{path:`/workspaces/:workspaceId`,element:(0,K.jsx)(Bzi,{})},{path:`/workspaces/:workspaceId/skills/:skillName`,loader:({params:e,request:t})=>qy(Aq(e.workspaceId,new URL(t.url).searchParams.get(`path`)))},{path:`/workflows`,element:(0,K.jsx)(eRi,{})},{path:`/workflows/schedules`,element:(0,K.jsx)(vRi,{})},{path:`/workflows/schedules/:scheduleId`,element:(0,K.jsx)(fRi,{})},{path:`/workflows/:workflowId`,element:(0,K.jsx)(sRt,{children:(0,K.jsx)(Lb,{})}),children:[{index:!0,loader:({params:e})=>qy(`/workflows/${e.workflowId}/graph`)},{path:`graph`,element:(0,K.jsx)(FRi,{})},{path:`graph/:runId`,element:(0,K.jsx)(FRi,{})},{path:`traces`,element:(0,K.jsx)(LRi,{})},{path:`schedules`,element:(0,K.jsx)(IRi,{})}]},{path:`/knowledge`,element:(0,K.jsx)(cMi,{})},...WVi?[{path:`/datasets`,element:(0,K.jsx)(epi,{})},{path:`/datasets/:datasetId`,element:(0,K.jsx)(Dvi,{}),children:[{path:`items/:itemId`,element:null}]},{path:`/datasets/:datasetId/edit`,element:(0,K.jsx)(Pvi,{})},{path:`/datasets/:datasetId/items/:itemId/versions`,element:(0,K.jsx)(Rvi,{})},{path:`/experiments`,element:(0,K.jsx)(Obi,{})},{path:`/experiments/compare`,element:(0,K.jsx)(Ubi,{})},{path:`/experiments/review-queue`,element:(0,K.jsx)(bDi,{})},{path:`/experiments/:experimentId`,element:(0,K.jsx)(nDi,{}),children:[{path:`items/:itemId`,element:null}]},{path:`/datasets/:datasetId/versions`,element:(0,K.jsx)(Vvi,{})}]:[],{index:!0,element:(0,K.jsx)(RMn,{})}]}];function qVi(){let e=window.MASTRA_STUDIO_BASE_PATH||``,{baseUrl:t,headers:n,apiPrefix:r,isLoading:i}=YC(),a=(0,G.useMemo)(()=>t?HVe(t,r):void 0,[t,r]),o=(0,G.useMemo)(()=>({...n,"x-mastra-client-type":`studio`}),[n]),s=(0,G.useMemo)(()=>QGe(KVi,{basename:e}),[e]);return i?(0,K.jsx)(`div`,{className:`flex h-screen w-full items-center justify-center`,children:(0,K.jsx)(Qc,{})}):t?(0,K.jsx)(TBe,{baseUrl:t,headers:o,apiPrefix:r,customFetch:a,children:(0,K.jsx)(c1e,{children:(0,K.jsx)(jMn,{children:(0,K.jsx)(P1e,{baseUrl:t,children:(0,K.jsx)(FGe,{router:s})})})})}):(0,K.jsx)(ZWr,{})}function JVi(){let e=window.MASTRA_SERVER_PROTOCOL||`http`,t=window.MASTRA_SERVER_HOST||`localhost`,n=window.MASTRA_SERVER_PORT||4111,r=window.MASTRA_API_PREFIX||`/api`,i=window.MASTRA_CLOUD_API_ENDPOINT||``,a=window.MASTRA_AUTO_DETECT_URL===`true`,o=i||(a?window.location.origin:`${e}://${t}:${n}`);return(0,K.jsx)(Dbn,{children:(0,K.jsx)(N1e,{endpoint:o,defaultApiPrefix:r,children:(0,K.jsx)(qVi,{})})})}function YVi(){(0,Mte.createRoot)(document.getElementById(`root`)).render((0,K.jsx)(G.StrictMode,{children:(0,K.jsx)(JVi,{})}))}export{YVi as startStudio};
|