@mastra/deployer-cloud 1.85.1-alpha.0 → 1.86.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -818,6 +818,6 @@ container holding the app. Specify either width or maxWidth, and either height o
|
|
|
818
818
|
]`,Ehi=[{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 Dhi(){let{isCopied:e,handleCopy:t}=lC({text:Thi,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:Ehi.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)(nX,{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)(JS,{variant:`success`,size:`xs`,children:`required`}):(0,K.jsx)(JS,{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)(sC,{}):(0,K.jsx)(cC,{}),variant:`ghost`,size:`sm`,onClick:t,children:e?`Copied`:`Copy`})]}),(0,K.jsx)(mw,{variant:`embedded`,language:`json`,editable:!1,lineNumbers:!1,showCopyButton:!1,value:Thi,className:`p-3`})]}),(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:whi,target:`_blank`,rel:`noopener noreferrer`}),className:`self-start`,icon:(0,K.jsx)(qN,{}),children:`Datasets documentation`})]})}var Ohi=10,khi=`[
|
|
819
819
|
{ "input": "…", "groundTruth": "…" }
|
|
820
820
|
]`,Ahi=`flex min-h-0 flex-1 flex-col py-0`;function jhi({tab:e,onTabChange:t,file:n,onFileSelect:r,onReplace:i,pastedText:a,onPastedTextChange:o,validation:s,isImporting:c}){return(0,K.jsxs)(uk,{value:e,defaultTab:`upload`,onValueChange:t,className:`flex h-full flex-col gap-3`,children:[(0,K.jsxs)(lk,{variant:`pill`,children:[(0,K.jsx)(dk,{value:`upload`,children:`Upload file`}),(0,K.jsx)(dk,{value:`paste`,children:`Paste JSON`})]}),(0,K.jsx)(fk,{value:`upload`,className:Ahi,children:n?(0,K.jsx)(Fhi,{file:n,validation:s,onReplace:i,isImporting:c}):(0,K.jsx)(Mhi,{onFileSelect:r,disabled:c})}),(0,K.jsx)(fk,{value:`paste`,className:Ahi,children:(0,K.jsx)(mw,{"aria-label":`JSON items`,language:`json`,lineNumbers:!1,showCopyButton:!1,placeholder:khi,value:a,onChange:o,editable:!c,className:`min-h-50 flex-1`})})]})}function Mhi({onFileSelect:e,disabled:t}){let[n,r]=(0,G.useState)(!1),i=(0,G.useCallback)(t=>{let n=t.target.files?.[0];n&&e(n),t.target.value=``},[e]),a=(0,G.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),r(!0)},[]),o=(0,G.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),r(!1)},[]),s=(0,G.useCallback)(n=>{if(n.preventDefault(),n.stopPropagation(),r(!1),t)return;let i=n.dataTransfer.files?.[0];i&&e(i)},[t,e]);return(0,K.jsxs)(`div`,{"data-testid":`json-dropzone`,onDragOver:a,onDragLeave:o,onDrop:s,className:c(`relative flex flex-1 flex-col items-center justify-center gap-3 rounded-lg border border-dashed border-border bg-card px-4 py-6 text-center`,`hover:border-success-edge hover:bg-success-subtle`,n&&`border-success-edge bg-success-subtle`,t&&`cursor-wait opacity-60`),children:[(0,K.jsx)(`input`,{type:`file`,accept:`.json,application/json`,"aria-label":`Choose a JSON file`,onChange:i,disabled:t,className:`absolute inset-0 cursor-pointer opacity-0`}),(0,K.jsx)(`div`,{className:`flex size-9 items-center justify-center rounded-md border border-border bg-background text-muted-foreground`,children:(0,K.jsx)(lhi,{className:`size-icon-md`})}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,K.jsx)(T,{tone:`ink`,children:`Drop a JSON file here`}),(0,K.jsxs)(T,{variant:`caption`,tone:`muted`,children:[`or `,(0,K.jsx)(`span`,{className:`underline`,children:`choose a file`}),` from your computer`]})]}),(0,K.jsxs)(T,{variant:`meta`,tone:`muted`,children:[`.json files containing an array of items, up to `,Bfi]})]})}function Nhi(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`}function Phi(e){return typeof e==`string`?e:JSON.stringify(e)??``}function Fhi({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,Ohi);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)(hk,{className:`size-icon-md shrink-0 text-muted-foreground`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`ink`,font:`mono`,className:`min-w-0 flex-1 truncate`,children:e.name}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`shrink-0`,children:Nhi(e.size)}),(0,K.jsx)(X,{icon:(0,K.jsx)(hS,{}),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:Phi(e.input)}),e.hasInput?e.hasGroundTruth?null:(0,K.jsx)(JS,{variant:`warning`,size:`xs`,children:`no groundTruth`}):(0,K.jsx)(JS,{variant:`destructive`,size:`xs`,children:`no input`})]},e.index)),a>Ohi&&(0,K.jsxs)(T,{as:`p`,variant:`meta`,tone:`muted`,className:`border-t border-border px-3 py-1.5`,children:[`+ `,a-Ohi,` more`]})]})}var Ihi=e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsText(e)});function Lhi({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}=bN(),x=a===`upload`?l:p,S=(0,G.useMemo)(()=>a===`upload`&&d?{status:`error`,kind:`parse`,message:d}:Ufi(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 ${Bfi}`);else try{let n=await Ihi(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}),Qx.success(`Imported ${S.total} item${S.total===1?``:`s`}`),i?.(),r(!1),E()}catch(e){Qx.error(e instanceof Error?e.message:`Failed to import items`)}finally{g(!1)}}},[S,b,e,i,r,E]);return(0,K.jsx)(Xw,{open:n,onOpenChange:D,pending:h,children:(0,K.jsxs)(Zw,{size:`xl`,children:[(0,K.jsxs)(Qw,{children:[(0,K.jsx)(tT,{children:`Import into dataset`}),(0,K.jsxs)(nT,{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)(eT,{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)(jhi,{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)(Dhi,{})})]})}),(0,K.jsxs)($w,{children:[(0,K.jsx)(Rhi,{validation:S}),(0,K.jsx)(rT,{children:`Cancel`}),(0,K.jsxs)(Yw,{onConfirm:O,disabled:S.status!==`ready`,children:[h&&(0,K.jsx)(It,{}),S.status===`ready`?`Import ${S.total} item${S.total===1?``:`s`}`:`Import`]})]})]})})}function Rhi({validation:e}){let t=c(`size-1.5 shrink-0 rounded-full`,e.status===`idle`&&`bg-muted-foreground`,e.status===`ready`&&`bg-success-indicator`,e.status===`error`&&`bg-destructive-indicator`),n;switch(e.status){case`idle`:n=`No items yet`;break;case`ready`:n=(0,K.jsxs)(wC,{singleLine:!0,children:[(0,K.jsxs)(wC.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)(wC.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 ${Bfi}`;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)(nX,{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 zhi(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 Bhi({active:e,onPrevious:t,onNext:n,onClose:r}){(0,G.useEffect)(()=>{if(!e)return;let i=e=>{e.defaultPrevented||zhi(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 Vhi=(0,G.createContext)(null);function Hhi({datasetId:e,items:t,isLoadingItems:n,children:r}){let i=Tv(),a=PRe(`/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]);Bhi({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)(Vhi.Provider,{value:d,children:r})}function Uhi(){let e=(0,G.useContext)(Vhi);if(!e)throw Error(`useDatasetItemPanel must be used within a DatasetItemPanelProvider`);return e}var Whi=[`createdAt`];function Ghi({datasetId:e,onAddItemClick:t,onNavigateToDataset:n,toolbarActionsSlot:r}){let[i,a]=Mv(),{activeVersion:o}=wN(i,a),{sort:s,onSortChange:c}=r7({searchParams:i,setSearchParams:a,allowedKeys:Whi}),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]=rC(O,300),{data:j}=SN({datasetId:e,queryOptions:{enabled:!!e}}),{data:M=[],isLoading:N,setEndOfListElement:P,isFetchingNextPage:F,hasNextPage:I}=yN({datasetId:e,search:A||void 0,version:o,orderBy:l,queryOptions:{enabled:!!e}}),{deleteItems:L}=bN(),{currentItemId:R,openItem:z,close:B}=Uhi();return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`grid h-full overflow-auto`,children:(0,K.jsx)(Chi,{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)(mhi,{datasetId:e,open:u,onOpenChange:d}),(0,K.jsx)(Lhi,{datasetId:e,datasetName:j?.name,open:f,onOpenChange:p}),(0,K.jsx)(Qfi,{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)($fi,{open:v,onOpenChange:e=>{y(e),e||(x([]),D(e=>e+1))},items:b,currentDatasetId:e}),(0,K.jsx)(WM,{open:S,onOpenChange:C,children:(0,K.jsxs)(WM.Content,{children:[(0,K.jsxs)(WM.Header,{children:[(0,K.jsx)(WM.Title,{children:`Delete Items`}),(0,K.jsxs)(WM.Description,{children:[`Are you sure you want to delete `,w.length,` item`,w.length===1?``:`s`,`? This action cannot be undone.`]})]}),(0,K.jsxs)(WM.Footer,{children:[(0,K.jsx)(WM.Cancel,{children:`Cancel`}),(0,K.jsx)(WM.Action,{onClick:async()=>{await L.mutateAsync({datasetId:e,itemIds:w}),Qx.success(`Deleted ${w.length} items`),C(!1),T([]),D(e=>e+1)},children:L.isPending?`Deleting...`:`Delete`})]})]})})]})}var Khi=`__create_tag__`;function qhi({datasetId:e}){let{data:t}=SN({datasetId:e,queryOptions:{enabled:!!e}}),{data:n}=xN(),{updateDataset:r}=bN(),[i,a]=(0,G.useState)(``),o=(0,G.useMemo)(()=>Array.isArray(t?.tags)?t.tags:[],[t?.tags]),s=(0,G.useMemo)(()=>$di(n?.datasets??[]),[n?.datasets]),c=(0,G.useMemo)(()=>{let e=s.map(e=>({label:e,value:e,end:o.includes(e)?(0,K.jsx)(sC,{"data-testid":`tag-applied`,className:`size-icon-sm`}):void 0})),t=i.trim();return t.length>0&&!s.includes(t)&&!o.includes(t)?[{label:`Create "${t}"`,value:Khi},...e]:e},[s,o,i]),l=t=>{r.mutate({datasetId:e,tags:t},{onError:()=>Qx.error(`Failed to update tags`)})},u=e=>{let t=e===Khi?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)(tfi,{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)(hw,{className:`size-icon-xs`})})]},e)),(0,K.jsx)(lN,{options:c,value:void 0,onValueChange:u,onInputValueChange:a,placeholder:`Add tag`,searchPlaceholder:`Search or create tag`,emptyText:`Type to create a tag`,variant:`ghost`,size:`sm`,className:`w-auto min-w-0`,disabled:r.isPending})]})}var F7=e=>JSON.stringify(e??null,null,2),Jhi=e=>e==null||e===``||typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0,Yhi=[{key:`input`,title:`Input`,icon:(0,K.jsx)(H4,{}),value:e=>F7(e.input),payload:e=>e.input},{key:`groundTruth`,title:`Ground Truth`,icon:(0,K.jsx)(U4,{}),value:e=>Jhi(e.groundTruth)?void 0:F7(e.groundTruth),payload:e=>Jhi(e.groundTruth)?null:e.groundTruth},{key:`expectedTrajectory`,title:`Expected Trajectory`,icon:(0,K.jsx)(Qmn,{}),value:e=>e.expectedTrajectory==null?void 0:F7(e.expectedTrajectory)},{key:`toolMocks`,title:`Tool Mocks`,icon:(0,K.jsx)(US,{}),value:e=>e.toolMocks?.length?F7(e.toolMocks):void 0},{key:`requestContext`,title:`Request Context`,icon:(0,K.jsx)(HS,{}),value:e=>e.requestContext==null?void 0:F7(e.requestContext)},{key:`metadata`,title:`Metadata`,icon:(0,K.jsx)(vX,{}),value:e=>F7(e.metadata)}],Xhi=e=>e.toFixed(2);function Zhi({delta:e,format:t=Xhi,higherIsBetter:n=!0,baseline:r}){let i=e===0?`text-muted-foreground`:(n?e>0:e<0)?`text-success-indicator`:`text-destructive-foreground`,a=e>0?`+`:e<0?`-`:``,o=`${a}${t(Math.abs(e))}`,s=r!==void 0&&r!==0&&Number.isFinite(r),l=(0,K.jsxs)(K.Fragment,{children:[a,s?`${(Math.abs(e)/Math.abs(r)*100).toFixed(1)}%`:t(Math.abs(e)),(0,K.jsx)(`span`,{"aria-hidden":!0,className:`inline-flex size-icon-sm shrink-0 [&>svg]:size-icon-sm`,children:e>0?(0,K.jsx)(R4,{}):e<0?(0,K.jsx)(PLr,{}):null})]}),u=c(`inline-flex items-center gap-1 tabular-nums`,i);return s?(0,K.jsxs)(_x,{children:[(0,K.jsx)(vx,{render:(0,K.jsx)(`span`,{tabIndex:0,className:u}),children:l}),(0,K.jsx)(yx,{children:o})]}):(0,K.jsx)(`span`,{className:u,children:l})}function Qhi({scorerId:e}){let{Link:t,paths:n}=sn();return(0,K.jsx)(t,{href:n.scorerLink(e),"aria-label":`Open ${e}`,className:`min-w-0 truncate hover:text-foreground hover:underline`,children:e})}function $hi({metrics:e}){if(e.length===0)return null;let t=e.some(e=>e.delta!=null);return(0,K.jsx)(`dl`,{className:c(`grid auto-rows-[minmax(1.5rem,auto)] items-center gap-x-4 gap-y-1`,t?`grid-cols-[minmax(0,1fr)_auto_auto]`:`grid-cols-[minmax(0,1fr)_auto]`),children:e.map(({id:e,icon:n,label:r,value:i,delta:a,formatDelta:o,rawValue:s,higherIsBetter:l,emphasis:u})=>(0,K.jsxs)(G.Fragment,{children:[(0,K.jsxs)(`dt`,{className:`flex min-w-0 items-center gap-1.5 text-body-sm text-muted-foreground [&>svg]:size-icon-sm [&>svg]:shrink-0`,children:[n,r]}),(0,K.jsx)(`dd`,{className:c(`flex min-w-0 justify-end text-right text-foreground tabular-nums`,u?`text-heading font-semibold`:`text-body-sm`),children:i}),t&&(0,K.jsx)(`dd`,{className:`flex justify-end text-body-sm`,children:a!=null&&(0,K.jsx)(Zhi,{delta:a,format:o,higherIsBetter:l,baseline:s==null?void 0:s-a})})]},e))})}function I7({value:e}){return(0,K.jsx)(`div`,{className:`min-w-0 p-3 text-foreground`,children:typeof e==`string`?(0,K.jsx)(pY,{children:e}):(0,K.jsx)(mw,{value:JSON.stringify(e??null,null,2),language:`json`,editable:!1,lineNumbers:!1,showCopyButton:!1,variant:`embedded`,"aria-label":`JSON payload`})})}var egi=`grid content-start gap-5`;function L7({title:e,actions:t,tone:n=`default`,collapsible:r=!0,framed:i=!1,expanded:a,onExpandedChange:o,children:s}){let l=qQ({collapsedHeight:160}),u=a===void 0||!o?l:{...l,isExpanded:a,setExpanded:o,toggleExpanded:()=>o(!a)},d=r?(0,K.jsx)(KQ,{state:u,expandLabel:`Expand`,children:s}):s;return(0,K.jsxs)(`section`,{className:`grid min-w-0 gap-2`,children:[(0,K.jsxs)(`div`,{className:`flex h-7 items-center justify-between gap-2`,children:[(0,K.jsx)(dQ.SectionHeading,{className:c(n===`negative`&&`text-destructive-foreground`),children:e}),(0,K.jsx)(`div`,{className:`ml-auto flex items-center gap-1`,children:t})]}),(0,K.jsxs)(`div`,{role:`region`,"aria-label":e,className:`min-w-0`,children:[i?n===`negative`?(0,K.jsx)(`div`,{className:`min-w-0 overflow-hidden rounded-lg border border-destructive-edge bg-destructive-subtle`,children:d}):(0,K.jsx)(JN,{className:`min-w-0 overflow-hidden`,children:d}):d,r&&u.isExpanded&&u.isClipped&&(0,K.jsx)(`div`,{className:`flex justify-center pt-1`,children:(0,K.jsx)(X,{size:`sm`,variant:`ghost`,icon:(0,K.jsx)(lZ,{}),onClick:()=>u.setExpanded(!1),children:`Collapse`})})]})]})}function tgi({item:e,diff:t}){return(0,K.jsxs)(`div`,{className:egi,children:[(0,K.jsx)($hi,{metrics:ngi(e)}),Yhi.map(n=>{if(n.payload&&!t){let t=n.payload(e);return t==null?null:(0,K.jsx)(L7,{title:n.title,framed:!0,actions:(0,K.jsx)(uC,{content:typeof t==`string`?t:JSON.stringify(t,null,2)}),children:(0,K.jsx)(I7,{value:t})},n.key)}let r=n.value(e),i=t?n.value(t.against):void 0;return r===void 0&&i===void 0?null:r===void 0?(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,K.jsx)(dQ.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)(dQ.CodeSection,{title:n.title,icon:n.icon,codeStr:r,diff:t?{against:i??``,side:t.side}:void 0},n.key)})]})}function ngi(e){let t=e.updatedAt&&new Date(e.updatedAt).getTime()!==new Date(e.createdAt).getTime(),n=[{id:`item-id`,icon:(0,K.jsx)(W6,{}),label:`Item Id`,value:(0,K.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,K.jsx)(`span`,{className:`font-mono`,title:e.id,children:ZV(e.id)}),(0,K.jsx)(uC,{content:e.id,tooltip:`Copy item ID to clipboard`,variant:`link`})]}),delta:null},{id:`created`,icon:(0,K.jsx)(qj,{}),label:`Created`,value:mC(e.createdAt,`date-time`),delta:null}];return t&&n.push({id:`updated`,icon:(0,K.jsx)(VS,{}),label:`Updated`,value:mC(e.updatedAt,`date-time`),delta:null}),n}function rgi({field:e,errors:t}){return t.length===0?null:(0,K.jsx)(rk,{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 igi({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)(XV,{className:`size-icon-lg`}),` Edit Item`]})}),(0,K.jsxs)(`div`,{className:`space-y-6`,children:[(0,K.jsxs)($O,{invalid:f?.field===`input`,children:[(0,K.jsx)(tk,{required:!0,children:`Input (JSON)`}),(0,K.jsx)(mw,{value:e,onChange:t,showCopyButton:!1,className:`min-h-[120px]`}),f?.field===`input`&&(0,K.jsx)(rgi,{field:`input`,errors:f.errors})]}),(0,K.jsxs)($O,{invalid:f?.field===`groundTruth`,children:[(0,K.jsx)(tk,{children:`Ground Truth (JSON, optional)`}),(0,K.jsx)(mw,{value:n,onChange:r,showCopyButton:!1,className:`min-h-[100px]`}),f?.field===`groundTruth`&&(0,K.jsx)(rgi,{field:`groundTruth`,errors:f.errors})]}),(0,K.jsxs)($O,{children:[(0,K.jsx)(tk,{children:`Expected Trajectory (JSON, optional)`}),(0,K.jsx)(mw,{value:o,onChange:s,showCopyButton:!1,className:`min-h-[80px]`})]}),(0,K.jsxs)($O,{invalid:f?.field===`toolMocks`,children:[(0,K.jsx)(tk,{children:`Tool Mocks (JSON array, optional)`}),(0,K.jsxs)(nk,{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)(mw,{value:c,onChange:l,showCopyButton:!1,className:`min-h-[100px]`}),f?.field===`toolMocks`&&(0,K.jsx)(rgi,{field:`toolMocks`,errors:f.errors})]}),(0,K.jsxs)($O,{children:[(0,K.jsx)(tk,{children:`Request Context (JSON, optional)`}),(0,K.jsx)(mw,{value:u,onChange:d,showCopyButton:!1,className:`min-h-[80px]`})]}),(0,K.jsxs)($O,{children:[(0,K.jsx)(tk,{children:`Metadata (JSON, optional)`}),(0,K.jsx)(mw,{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)(sC,{}),variant:`primary`,onClick:p,disabled:h,children:h?`Saving...`:`Save changes`}),(0,K.jsx)(X,{icon:(0,K.jsx)(hw,{}),onClick:m,disabled:h,children:`Cancel`})]})]})]})}function agi(){return(0,K.jsxs)(SC,{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 ogi({provider:e,modelId:t,canReset:n,onProviderChange:r,onModelIdChange:i,onReset:a,container:o}){let s=iS(),{isLoading:c}=Sq(),[l,u]=(0,G.useState)(!1);return s.active&&s.pickerVisible===!1?(0,K.jsxs)(ik,{className:`gap-2`,children:[(0,K.jsx)(ak,{children:`Model`}),(0,K.jsx)(`div`,{children:(0,K.jsx)(JS,{icon:(0,K.jsx)(hH,{}),children:`Locked by admin`})})]}):(0,K.jsxs)(ik,{className:`gap-2`,children:[(0,K.jsx)(ak,{children:`Model`}),c?(0,K.jsx)(NS,{className:`h-control-md w-60 rounded-full`}):(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsxs)(GV,{className:`min-w-0`,children:[(0,K.jsx)(wq,{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)(Tq,{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)(fS,{})})]})]})}var sgi=(e,t)=>`${e}:${t}`,cgi=(e,t)=>e?.value===t?.value;function lgi({datasets:e,datasetId:t,version:n,onDatasetChange:r,container:i}){let{total:a}=yN({datasetId:t,search:void 0,version:n,queryOptions:{enabled:!!t}}),o=e.find(e=>e.value===t)??null;return(0,K.jsxs)($O,{children:[(0,K.jsx)(tk,{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)(iN,{items:e,value:o,onValueChange:e=>e&&r(e.value),isItemEqualToValue:cgi,autoHighlight:!0,children:[(0,K.jsx)(gkt,{placeholder:`Select a dataset`,children:a!==void 0&&(0,K.jsxs)(wC,{children:[(0,K.jsxs)(wC.Item,{children:[a,` `,a===1?`item`:`items`]}),(0,K.jsx)(wC.Item,{children:n===void 0?`latest`:`v${n}`})]})}),(0,K.jsxs)(aN,{container:i,children:[(0,K.jsx)(cN,{children:`No datasets found`}),(0,K.jsx)(oN,{children:e=>(0,K.jsx)(sN,{value:e,children:e.label},e.value)})]})]})]})}function ugi(e,t){return t!==void 0||(e??1)>1}function dgi({datasetId:e,version:t,onVersionChange:n,container:r}){let{data:i}=SN({datasetId:e,queryOptions:{enabled:!!e}});return ugi(i?.version,t)?(0,K.jsxs)($O,{children:[(0,K.jsx)(tk,{children:`Dataset version`}),(0,K.jsx)(fjt,{datasetId:e,value:t??null,onValueChange:e=>n(e??void 0),container:r})]}):null}function fgi({description:e,onDescriptionChange:t,disabled:n}){return(0,K.jsxs)($O,{children:[(0,K.jsx)(tk,{children:`Description`}),(0,K.jsx)(Vk,{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)($O,{children:[(0,K.jsx)(tk,{children:`Experiment name`}),(0,K.jsx)(Hj,{value:e,placeholder:t,onChange:e=>n(e.target.value),disabled:r})]})}function mgi(e){try{return NO(e)}catch(e){console.error(`Failed to parse requestContextSchema:`,e);return}}function hgi({requestContextSchema:e,onChange:t}){let[n]=(0,G.useState)(()=>mgi(e));return n?(0,K.jsxs)(ik,{children:[(0,K.jsx)(ak,{children:`Request context`}),(0,K.jsx)(HM,{schema:n,onValuesChange:t,className:`[&_button[type=submit]]:hidden`})]}):(0,K.jsx)(`div`,{role:`alert`,children:(0,K.jsx)(gk,{variant:`destructive`,children:`Failed to parse request context schema`})})}function ggi({schema:e,raw:t,onRawChange:n,onValuesChange:r}){return e?(0,K.jsx)(hgi,{requestContextSchema:e,onChange:r}):(0,K.jsxs)($O,{children:[(0,K.jsx)(tk,{children:`Request context (JSON)`}),(0,K.jsx)(mw,{value:t,onChange:n,showCopyButton:!1,"aria-label":`Request context JSON`,className:`min-h-[120px]`})]})}function _gi({onRun:e,canRun:t,isRunning:n}){return(0,K.jsx)(Yw,{onConfirm:e,disabled:!t,children:(0,K.jsx)(vgi,{isRunning:n})})}function vgi({isRunning:e}){return e?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(It,{className:`h-4 w-4`}),`Starting…`]}):`Run experiment`}function ygi({scorer:e}){let t=(0,K.jsx)(sN,{value:e,children:e.label});return e.description?(0,K.jsxs)(_x,{children:[(0,K.jsx)(vx,{render:t}),(0,K.jsx)(yx,{side:`right`,className:`max-w-64`,children:e.description})]}):t}function bgi(){let{data:e}=NN();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 xgi(e,t){return e.map(e=>t.find(t=>t.value===e)??{value:e,label:e})}function Sgi({scorerIds:e,usesDefaultScorers:t,onScorerIdsChange:n,container:r}){let i=bgi();return(0,K.jsxs)($O,{children:[(0,K.jsx)(tk,{info:`Grade each output automatically. Outputs are saved either way, so you can always review them yourself.`,children:`Scorers`}),(0,K.jsxs)(iN,{multiple:!0,items:i,value:xgi(e,i),onValueChange:e=>n(e.map(e=>e.value)),isItemEqualToValue:cgi,autoHighlight:!0,children:[(0,K.jsx)(Ckt,{children:(0,K.jsx)(fkt,{children:e=>(0,K.jsxs)(K.Fragment,{children:[e.map(e=>(0,K.jsx)(wkt,{children:e.label},e.value)),(0,K.jsx)(Tkt,{placeholder:e.length===0?`No scoring, read the outputs yourself`:void 0})]})})}),(0,K.jsxs)(aN,{container:r,children:[(0,K.jsx)(cN,{children:`No scorers registered`}),(0,K.jsx)(oN,{children:e=>(0,K.jsx)(ygi,{scorer:e},e.value)})]})]}),t&&(0,K.jsx)(nk,{children:`The dataset's default scorers.`})]})}var Cgi=[{type:`agent`,label:`Agents`},{type:`workflow`,label:`Workflows`},{type:`scorer`,label:`Scorers`}];function wgi(e){return Cgi.map(t=>({value:t.label,items:e.filter(e=>e.type===t.type)})).filter(e=>e.items.length>0)}function Tgi({options:e,isLoading:t,target:n,onTargetValueChange:r,container:i,className:a}){return(0,K.jsxs)($O,{className:a,children:[(0,K.jsx)(tk,{required:!0,info:`What runs on each item: an agent, a workflow, or a scorer you want to test.`,children:`Target`}),(0,K.jsxs)(iN,{items:wgi(e),value:n??null,onValueChange:e=>r(e?.value??``),isItemEqualToValue:cgi,disabled:t,autoHighlight:!0,children:[(0,K.jsx)(gkt,{placeholder:`Pick an agent, workflow or scorer`}),(0,K.jsxs)(aN,{container:i,children:[(0,K.jsx)(cN,{children:`Nothing to run`}),(0,K.jsx)(oN,{children:(e,t)=>(0,K.jsxs)(ykt,{items:e.items,children:[t>0?(0,K.jsx)(Skt,{}):null,(0,K.jsx)(bkt,{children:e.value}),(0,K.jsx)(xkt,{children:e=>(0,K.jsx)(sN,{value:e,children:e.label},e.value)})]},e.value)})]})]})]})}var Egi=(e,t)=>e.provider===t?.provider&&e.modelId===t?.modelId;function Dgi(e){let[t,n]=(0,G.useState)(null),r=t??e??{provider:``,modelId:``},i=t?.provider&&t.modelId&&!Egi(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&&!Egi(t,e),agentModel:i}}function Ogi(e,t){return e||(t[0]?.value??``)}function kgi({initialDatasetId:e,initialDatasetVersion:t}){let{data:n}=xN(),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:Ogi(i,r),version:o,setVersion:s,selectDataset:e=>{a(e),s(void 0)}}}function Agi({initialName:e,targetLabel:t}){let[n,r]=(0,G.useState)(e??``),[i]=(0,G.useState)(nui),a=rui(t??`experiment`,i);return{name:n,setName:r,defaultName:a,runName:n.trim()||a}}var jgi=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Mgi(e){if(jgi(e)&&Object.keys(e).length!==0)return e}function Ngi(e){try{return{ok:!0,value:JSON.parse(e)}}catch{return{ok:!1}}}function Pgi(e){if(!e.trim())return{ok:!0};let t=Ngi(e);return t.ok?jgi(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 Fgi(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 Igi(e){let{data:t}=SN({datasetId:e,queryOptions:{enabled:!!e}}),[n,r]=(0,G.useState)(``),[i,a]=(0,G.useState)({}),o=Mgi(t?.requestContextSchema);return{schema:o,raw:n,setRaw:r,setValues:a,resetValues:()=>a({}),resolve:()=>o?Fgi(i):Pgi(n)}}function Lgi({datasetId:e,initialScorerIds:t}){let{data:n}=SN({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 Rgi=(e,t,n,r)=>({value:sgi(e,t),label:n,type:e,id:t,defaultModel:r});function zgi(e,t){if(e&&t)return{provider:wK(e),modelId:t}}function Bgi(){let{data:e,isLoading:t}=gN(),{data:n,isLoading:r}=KM({}),{data:i,isLoading:a}=NN();return{options:[...Object.entries(e??{}).map(([e,t])=>Rgi(`agent`,e,t.name||e,zgi(t.provider,t.modelId))),...Object.entries(n??{}).map(([e,t])=>Rgi(`workflow`,e,t.name||e)),...Object.entries(i??{}).map(([e,t])=>Rgi(`scorer`,e,t.scorer?.config?.name||e))],isLoading:t||r||a}}function Vgi({initialTargetType:e,initialTargetId:t}){return!e||!t?``:sgi(e,t)}function Hgi(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 Ugi(e){let{options:t,isLoading:n}=Bgi(),[r,i]=(0,G.useState)(()=>Vgi(e));return{options:t,isLoading:n,target:Hgi(t,r,e),setTargetValue:i}}var Wgi=e=>(e.metaKey||e.ctrlKey)&&e.key===`Enter`,Ggi=e=>e.trim()||void 0,Kgi=e=>e.length>0?e:void 0;function qgi({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=Ugi({initialTargetType:s,initialTargetId:c}),p=kgi({initialDatasetId:i,initialDatasetVersion:a}),m=Lgi({datasetId:p.datasetId,initialScorerIds:o}),h=Igi(p.datasetId),{target:g}=f,_=Dgi(g?.defaultModel),v=g?.type===`agent`,y=v?_.agentModel:void 0,b=Agi({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}=bN(),{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)qx.error(e.message);else try{let n=await T.mutateAsync({datasetId:E,name:b.runName,description:Ggi(x),targetType:g.type,targetId:g.id,agentModel:y,scorerIds:Kgi(m.scorerIds),version:p.version,requestContext:e.requestContext});qx.success(`Experiment started`),t(!1),r?.(n.experimentId)}catch(e){qx.error(e instanceof Error?e.message:`Failed to start experiment`)}};return(0,K.jsx)(Xw,{open:e,onOpenChange:t,onOpenChangeComplete:n,pending:D,children:(0,K.jsxs)(Zw,{ref:d,size:`lg`,onKeyDown:e=>{Wgi(e)&&k&&(e.preventDefault(),M())},children:[(0,K.jsxs)(Qw,{children:[(0,K.jsx)(tT,{children:`New experiment`}),(0,K.jsx)(nT,{children:`Run every item in a dataset through an agent, workflow or scorer.`})]}),(0,K.jsx)(eT,{children:(0,K.jsxs)(xC,{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)(Tgi,{options:f.options,isLoading:f.isLoading,target:g,onTargetValueChange:A,container:d,className:`min-w-0 flex-1`}),v&&(0,K.jsx)(ogi,{provider:_.provider,modelId:_.modelId,canReset:_.canReset,onProviderChange:_.setProvider,onModelIdChange:_.setModelId,onReset:_.reset,container:d})]}),(0,K.jsx)(lgi,{datasets:p.datasets,datasetId:E,version:p.version,onDatasetChange:j,container:d}),(0,K.jsx)(Sgi,{scorerIds:m.scorerIds,usesDefaultScorers:m.usesDefaultScorers,onScorerIdsChange:m.setScorerIds,container:d})]}),(0,K.jsx)(`div`,{className:`mt-6`,children:(0,K.jsx)(agi,{})}),(0,K.jsxs)(CC,{className:`space-y-6 pt-4`,children:[E&&(0,K.jsx)(dgi,{datasetId:E,version:p.version,onVersionChange:p.setVersion,container:d}),(0,K.jsx)(fgi,{description:x,onDescriptionChange:S,disabled:D}),(0,K.jsx)(ggi,{schema:h.schema,raw:h.raw,onRawChange:h.setRaw,onValuesChange:h.setValues},O)]})]})}),(0,K.jsxs)($w,{children:[(0,K.jsx)(rT,{children:`Cancel`}),(0,K.jsx)(_gi,{onRun:M,canRun:k,isRunning:D})]})]})})}function Jgi({open:e,onOpenChange:t,onSuccess:n,...r}){let[i,a]=(0,G.useState)(0);return(0,K.jsx)(qgi,{open:e,onOpenChange:t,onOpenChangeComplete:e=>{e||a(e=>e+1)},onSuccess:n,...r},`${i}:${JSON.stringify(r)}`)}var Ygi=`mastra_model_total_input_tokens`,Xgi=`mastra_model_total_output_tokens`,Zgi=()=>({estimatedCost:0,costUnits:new Set,hasUnknownCostUnit:!1});function Qgi(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 $gi(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 e_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 t_i=2e3;function n_i(e){let t=Zgi(),n=new Map;for(let r of e.groups){let e=Qgi(r);if(!e)continue;$gi(t,e,r);let i=r.dimensions.traceId;i&&$gi(K6(n,i,Zgi),e,r)}let r={};for(let[e,t]of n)r[e]=e_i(t);return{summary:e_i(t),traces:r}}var r_i=5,i_i=e=>!e||Object.keys(e.traces).length===0&&e.summary.inputTokens===void 0&&e.summary.outputTokens===void 0,a_i=({experiments:e,supportsMetrics:t})=>{let n=Y(),r=RAt(e.map(e=>e.id));return x_({queries:e.map(({id:e,status:r})=>{let i=r!==`running`&&r!==`pending`;return{queryKey:[`experiment-item-usage`,e,i],queryFn:async()=>n_i(await n.getMetricBreakdown({name:[Ygi,Xgi],aggregation:`sum`,groupBy:[`traceId`,`name`],filters:{experimentId:e}})),enabled:t&&i,refetchInterval:e=>i_i(e.state.data)&&e.state.dataUpdateCount<r_i?t_i:!1}}),combine:r})},o_i=({experimentId:e,experimentStatus:t,supportsMetrics:n,queryOptions:r})=>{let i=Y(),a=!!e&&n,o=S_({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}},s_i=({traceId:e,queryOptions:t})=>{let n=Y();return S_({queryKey:[`experiment-trace-light`,e],queryFn:async()=>{if(!e)throw Error(`Trace ID is required`);return n.getTraceLight(e)},...t})};function c_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),S_({queryKey:e?[`dataset-experiments`,e,i]:[`experiments`,i],queryFn:()=>e?r.listDatasetExperiments(e,i):r.listExperiments(i),...n})}var l_i=`mastra_agent_duration_ms`,u_i=500,d_i=5e3;function f_i(e){let t=[];for(let n=0;n<e.length;n+=u_i)t.push(e.slice(n,n+u_i));return t}function p_i(e){return e.flatMap(e=>e.status===`fulfilled`?[e.value]:[])}function m_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=Qgi(e);t&&r.has(t)&&n&&$gi(K6(i,t,Zgi),n,e)}let a=new Map;for(let[e,t]of i)a.set(e,e_i(t));for(let e of n.flatMap(e=>e.groups)){let t=e.dimensions.experimentId;t&&r.has(t)&&(K6(a,t,()=>({})).avgDurationMs=e.value)}return a}var h_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 S_({queryKey:[`experiments-list-metrics`,r],enabled:t&&r.length>0,queryFn:async()=>{let e=f_i(r),[t,i]=await Promise.all([Promise.allSettled(e.map(e=>n.getMetricBreakdown({name:[Ygi,Xgi],aggregation:`sum`,groupBy:[`experimentId`,`name`],filters:{experimentIds:e},limit:e.length*2}))),Promise.allSettled(e.map(e=>n.getMetricBreakdown({name:[l_i],aggregation:`avg`,groupBy:[`experimentId`],filters:{experimentIds:e},limit:e.length})))]);return m_i(r,p_i(t),p_i(i))},placeholderData:m_,refetchInterval:i?d_i:!1})};function g_i({datasetId:e,target:t,orderBy:n,queryOptions:r}){let i=Y(),{inView:a,setRef:o}=GM(),s=t?.targetType||void 0,c=t?.targetId||void 0,l=T_({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 __i=(0,G.createContext)(null);function v_i({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:i,hasNextPage:a,children:o}){let s=Tv(),c=PRe(`/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]);Bhi({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)(__i.Provider,{value:m,children:o})}function y_i(){let e=(0,G.useContext)(__i);if(!e)throw Error(`useExperimentItemPanel must be used within an ExperimentItemPanelProvider`);return e}function b_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 x_i(e){if(e.targetType===`agent`)return b_i(e.output,`text`)}function S_i(e){if(e.targetType)return x_i(e);let{output:t}=e;if(t!=null&&t!==``)return typeof t==`string`?t:JSON.stringify(t)}function C_i(e){let t=[];return e.some(e=>S_i(e))&&t.push({name:`output`,label:`Output`,size:`20rem`}),e.some(e=>R7(e))&&t.push({name:`error`,label:`Error`,size:`20rem`}),t}function R7(e){let t=b_i(e.error,`message`);if(t)return t;if(e.targetType===`agent`&&e.output&&typeof e.output==`object`)return b_i(e.output.error,`message`)}function w_i(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function T_i(e){return Array.isArray(e)?e.flatMap(e=>w_i(e)&&w_i(e.payload)?[e.payload]:[]):[]}function E_i(e){if(e.targetType!==`agent`||!w_i(e.output))return[];let t=new Map(T_i(e.output.toolResults).map(e=>[e.toolCallId,e]));return T_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 D_i(e){if(x_i(e)||R7(e))return;let t=E_i(e).length;if(t!==0)return`No final text response after ${t} tool ${t===1?`call`:`calls`}`}var z7=e=>e==null?`-`:e.toFixed(2),O_i=e=>QS(e)??`-`,k_i=(e,t)=>e!=null&&t!=null?e-t:null,A_i=new Set(Intl.supportedValuesOf(`currency`)),j_i={minimumFractionDigits:3,maximumFractionDigits:3},B7=(e,t)=>{if(e===void 0)return`-`;let n=(t??`usd`).toUpperCase();return A_i.has(n)?new Intl.NumberFormat(`en-US`,{style:`currency`,currency:n,...j_i}).format(e):`${new Intl.NumberFormat(`en-US`,j_i).format(e)} ${t}`},M_i=e=>t=>B7(t,e),N_i=new Intl.NumberFormat(`en-US`),V7=e=>e===void 0?`-`:N_i.format(e),H7=e=>{if(e?.inputTokens!==void 0||e?.outputTokens!==void 0)return(e.inputTokens??0)+(e.outputTokens??0)};function P_i({scorerId:e,reason:t,nested:n=!1}){let r=`text-muted-foreground hover:text-foreground [&>svg]:size-icon-sm`;return(0,K.jsxs)(mX,{children:[(0,K.jsx)(hX,{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)(Ux,{})}),(0,K.jsx)(gX,{side:`left`,align:`start`,className:`max-h-80 max-w-100 overflow-y-auto`,onClick:e=>e.stopPropagation(),children:(0,K.jsx)(pY,{children:t})})]})}var F_i=new Set([`itemId`,`id`,`status`,`input`,`output`,`error`,`tags`,`scores`,`cost`,`tokens`,`duration`]);function I_i({results:e,isLoading:t,featuredResultId:n,onResultClick:r,columns:i,scoresByItemId:a,scorerIds:o,setEndOfListElement:s,isFetchingNextPage:c,hasNextPage:l,emptyMessage:u=`No results yet`,selectedIds:d,onToggleSelect:f,onToggleSelectAll:p}){let{Link:m,paths:h}=sn(),g=!!(d&&f),_=i.filter(e=>F_i.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}=OZ({count:e.length}),P=e=>o?.includes(e.name)?(0,K.jsx)(Z.TopCell,{children:(0,K.jsxs)(m,{href:h.scorerLink(e.name),className:`flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-icon-sm [&>svg]:shrink-0`,children:[(0,K.jsx)(BN,{}),(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)(yH,{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)(fli,{status:e.status}):(0,K.jsx)(`span`,{className:`text-placeholder`,children:`—`})}),S&&(0,K.jsx)(Z.TextCell,{font:`mono`,children:B_i(z_i(e.input),200)}),C&&(0,K.jsx)(Z.Cell,{className:`truncate font-mono`,"data-testid":`result-output-${e.id}`,children:S_i(e)??``}),w&&(0,K.jsx)(Z.Cell,{className:`truncate text-destructive-foreground`,"data-testid":`result-error-${e.id}`,children:R7(e)??``}),T&&(0,K.jsx)(Z.Cell,{className:`flex items-center gap-1 overflow-hidden`,"data-testid":`result-tags-${e.id}`,children:e.tags?.map(e=>(0,K.jsx)(tfi,{value:e,className:`shrink-0`},e))}),E&&(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(L_i,{scores:e.scores})}),D&&(0,K.jsx)(Z.Cell,{className:`text-muted-foreground tabular-nums`,"data-testid":`result-cost-${e.id}`,children:B7(e.usage?.estimatedCost,e.usage?.costUnit)}),O&&(0,K.jsx)(Z.Cell,{className:`text-muted-foreground tabular-nums`,"data-testid":`result-tokens-${e.id}`,children:V7(H7(e.usage))}),k&&(0,K.jsx)(Z.Cell,{className:`text-muted-foreground tabular-nums`,"data-testid":`result-duration-${e.id}`,children:QS(R_i(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)(P_i,{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 L_i({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)(xx,{size:`xs`,className:`text-muted-foreground`,children:(0,K.jsx)(G4,{})}),(0,K.jsx)(T,{variant:`meta`,tone:`muted`,font:`mono`,children:t[0].toFixed(2)}),t.length>1&&(0,K.jsxs)(JS,{children:[`+`,t.length-1]})]})}function R_i({startedAt:e,completedAt:t}){if(e&&t)return new Date(t).getTime()-new Date(e).getTime()}function z_i(e){return e==null?`-`:typeof e==`string`?e:JSON.stringify(e,null,2)}function B_i(e,t){return e.length<=t?e:e.slice(0,t-1)+`...`}function V_i({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}=y_i(),m=(0,G.useMemo)(()=>d?n.find(e=>e.itemId===d)?.id??null:null,[n,d]),{data:h}=CN({experimentId:e,experimentStatus:t,queryOptions:{enabled:!!e}}),{data:g}=a_i({experiments:(0,G.useMemo)(()=>[{id:e,status:t}],[e,t]),supportsMetrics:u}),_=g[e]?.traces,v=(0,G.useMemo)(()=>_?n.map(e=>({...e,usage:e.traceId?_[e.traceId]:void 0})):n,[n,_]),y=(0,G.useMemo)(()=>{if(!h)return[];let e=new Set;for(let t of Object.values(h))for(let n of t)e.add(n.scorerId);return[...e].sort()},[h]),b=(0,G.useCallback)(e=>{let t=n.find(t=>t.id===e);t&&(t.itemId===d?p():f(t.itemId))},[n,d,p,f]),x=(0,G.useMemo)(()=>[{name:`itemId`,label:`Item ID`,size:`7rem`},{name:`input`,label:`Input`,size:`20rem`},...C_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)(I_i,{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 H_i({children:e,className:t}){return(0,K.jsx)(`div`,{className:c(`grid content-start gap-4 overflow-y-auto`,t),children:e})}function U_i({children:e,className:t}){return(0,K.jsx)(`div`,{className:`flex w-full overflow-y-auto`,children:(0,K.jsx)(`div`,{className:c(`grid w-full content-start gap-4 overflow-y-auto`,t),children:e})})}function W_i({children:e,className:t}){return(0,K.jsx)(`div`,{className:c(`flex w-full flex-wrap items-center justify-between gap-3 gap-x-4`,t),children:e})}var G_i=Object.assign(U_i,{Content:H_i,Toolbar:W_i});function K_i({children:e,className:t}){return(0,K.jsx)(`div`,{className:c(`grid size-full grid-cols-1 overflow-y-auto`,t),children:e})}function q_i({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){let{data:i}=sjt({datasetId:e,queryOptions:{enabled:!!e}}),a=(i??[]).map(e=>{let t=`v${e.version}`,n=mC(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)(wC,{children:[(0,K.jsx)(wC.Item,{children:t}),n&&(0,K.jsx)(wC.Item,{children:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:n})}),r&&(0,K.jsx)(wC.Item,{children:r})]})}});return(0,K.jsxs)(G_i.Toolbar,{className:`grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4`,children:[(0,K.jsx)(`div`,{}),(0,K.jsxs)(Pk,{items:a,value:t??``,onValueChange:e=>r?.(e,n??``),children:[(0,K.jsx)(Ik,{"aria-label":`Version A`,size:`md`,children:(0,K.jsx)(Fk,{placeholder:`Select version`})}),(0,K.jsx)(Lk,{children:a.map(e=>(0,K.jsx)(Rk,{value:e.value,label:e.label,children:e.content},e.value))})]}),(0,K.jsxs)(Pk,{items:a,value:n??``,onValueChange:e=>r?.(t??``,e),children:[(0,K.jsx)(Ik,{"aria-label":`Version B`,size:`md`,children:(0,K.jsx)(Fk,{placeholder:`Select an option`})}),(0,K.jsx)(Lk,{children:a.map(e=>(0,K.jsx)(Rk,{value:e.value,label:e.label,children:e.content},e.value))})]}),(0,K.jsx)(`div`,{})]})}var J_i={added:{badgeVariant:`info`,borderColor:`border-info-edge`,icon:(0,K.jsx)(Ix,{}),tooltip:`Added in this version`},changed:{badgeVariant:`warning`,borderColor:`border-warning-edge`,icon:(0,K.jsx)(XV,{}),tooltip:`Changed in this version`},same:{badgeVariant:`success`,borderColor:`border-success-edge`,icon:(0,K.jsx)(BRr,{}),tooltip:`Same in both versions`}};function Y_i({red:e=!1,tooltip:t}){return(0,K.jsxs)(_x,{children:[(0,K.jsx)(vx,{render:(0,K.jsx)(`span`,{}),role:`img`,tabIndex:0,"aria-label":t,className:c(`rounded`,p),children:(0,K.jsx)(Bx,{className:c(`size-icon-lg text-muted-foreground/40`,{"text-destructive-foreground":e})})}),(0,K.jsx)(yx,{children:t})]})}function X_i({href:e,tooltip:t,className:n,children:r}){let{Link:i}=sn(),a=(0,K.jsx)(i,{href:e,className:c(`flex w-full items-center justify-center gap-4 rounded-lg px-3 py-2 text-left hover:bg-fill-subtle`,u.colors,p,n),children:r});return t===void 0?a:(0,K.jsxs)(_x,{children:[(0,K.jsx)(vx,{render:a}),(0,K.jsx)(yx,{children:t})]})}function Z_i({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}=J_i[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)(JS,{variant:n,size:`xs`,icon:r})})]})}function Q_i(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?`same`:e&&t&&e.datasetVersion!==t.datasetVersion?`changed`:e?`added`:`removed`}function $_i({otherVersionExists:e,status:t,isNewer:n}){if(!e&&n)return`added`;if(t===`changed`&&n)return`changed`}function evi({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=Q_i(n,r),l=$_i({otherVersionExists:r!==void 0,status:s,isNewer:o}),d=$_i({otherVersionExists:n!==void 0,status:s,isNewer:!o});return(0,K.jsxs)(`li`,{className:c(`text-foreground`,`grid grid-cols-[1fr_1fr_1fr_10rem] gap-3 overflow-hidden rounded-lg border border-transparent border-t-border px-3 py-[3px] pb-[2px] first:border-t-transparent`,u.colors),children:[(0,K.jsx)(T,{as:`p`,variant:`body`,tone:`faint`,className:`truncate py-[0.6rem]`,children:t}),s===`same`?(0,K.jsx)(X_i,{href:`/datasets/${e}/items/${t}`,className:`col-span-2 gap-2`,tooltip:J_i.same.tooltip,children:(0,K.jsx)(Z_i,{variant:`same`,version:r?.datasetVersion})}):(0,K.jsxs)(K.Fragment,{children:[n?.datasetVersion?(0,K.jsx)(X_i,{href:`/datasets/${e}/items/${t}`,className:`gap-2`,tooltip:l?J_i[l].tooltip:void 0,children:(0,K.jsx)(Z_i,{variant:l,version:n.datasetVersion})}):(0,K.jsx)(`div`,{className:`flex items-center justify-center`,children:(0,K.jsx)(Y_i,{red:o,tooltip:o?`Deleted in this version`:`Not present in this version`})}),r?.datasetVersion?(0,K.jsx)(X_i,{href:`/datasets/${e}/items/${t}`,className:`gap-2`,tooltip:d?J_i[d].tooltip:void 0,children:(0,K.jsx)(Z_i,{variant:d,version:r.datasetVersion})}):(0,K.jsx)(`div`,{className:`flex items-center justify-center`,children:(0,K.jsx)(Y_i,{red:!o,tooltip:o?`Not present in this version`:`Deleted in this version`})})]}),s===`changed`?(0,K.jsx)(X_i,{href:`/datasets/${e}/items/${t}/versions?version=${n?.datasetVersion}&compare=${r?.datasetVersion}`,children:`Compare`}):(0,K.jsx)(`div`,{children:(0,K.jsx)(Y_i,{tooltip:`Comparing is available only for changed items`})})]},t)})})})}var tvi=U(`IconHistory`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M3 5V9H7`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M3.51172 15C4.74723 18.4956 8.08094 21 11.9996 21C16.9702 21 20.9996 16.9706 20.9996 12C20.9996 7.02944 16.9702 3 11.9996 3C8.27045 3 5.07102 5.26806 3.70551 8.5`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M12 8V12L15 15`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}));function nvi(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 rvi({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)(ivi,{item:e,onClose:r,...a},e.id):t?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(dQ.Header,{children:[(0,K.jsx)(dQ.Heading,{children:`Dataset item`}),(0,K.jsx)(dQ.HeaderActions,{children:(0,K.jsx)(dQ.CloseButton,{icon:`x`,onClick:r,tooltip:`Close detail panel`})})]}),n]}):null;return i===`inline`?c?(0,K.jsx)(dQ,{variant:`inline`,title:s,children:c}):null:(0,K.jsx)(dQ,{open:!!o,onClose:r,title:s,children:c})}function ivi({datasetId:e,item:t,items:n,onItemChange:r,onClose:i}){let{navigate:a}=sn(),{updateItem:o,deleteItem:s}=bN(),[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)(dQ.Header,{children:[(0,K.jsx)(dQ.Heading,{children:`Dataset item`}),(0,K.jsxs)(dQ.HeaderActions,{children:[!c&&(0,K.jsxs)(ZT,{children:[(0,K.jsx)(ZT.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)(QT,{})})}),(0,K.jsxs)(ZT.Content,{align:`end`,className:`w-48`,children:[(0,K.jsxs)(ZT.Item,{onSelect:()=>a(`/datasets/${e}/items/${t.id}/versions?version=${t.datasetVersion}`),children:[(0,K.jsx)(tvi,{}),`Item versions`]}),(0,K.jsxs)(ZT.Item,{onSelect:()=>l(!0),children:[(0,K.jsx)(XV,{}),`Edit`]}),(0,K.jsxs)(ZT.Item,{onSelect:()=>T(!0),variant:`destructive`,children:[(0,K.jsx)(Bj,{}),`Delete item`]})]})]}),(0,K.jsx)(dQ.NextPrevNav,{onPrevious:D,onNext:O,previousLabel:`Go to previous item`,nextLabel:`Go to next item`}),(0,K.jsx)(dQ.CloseButton,{icon:`x`,onClick:i,tooltip:`Close detail panel`})]})]}),(0,K.jsx)(dQ.Content,{children:c?(0,K.jsx)(igi,{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{Qx.error(`Input must be valid JSON`);return}let r;if(f.trim())try{r=JSON.parse(f)}catch{Qx.error(`Ground Truth must be valid JSON`);return}let i;if(m.trim())try{i=JSON.parse(m)}catch{Qx.error(`Metadata must be valid JSON`);return}let a=null;if(g.trim())try{a=JSON.parse(g)}catch{Qx.error(`Expected Trajectory must be valid JSON`);return}let s;if(v.trim())try{let e=JSON.parse(v);if(!Array.isArray(e)){Qx.error(`Tool Mocks must be a JSON array`);return}s=e}catch{Qx.error(`Tool Mocks must be valid JSON`);return}else s=[];let c;if(b.trim())try{c=JSON.parse(b)}catch{Qx.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}),Qx.success(`Item updated successfully`),l(!1),C(null)}catch(e){let t=nvi(e);t?C(t):Qx.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)(tgi,{item:t})}),(0,K.jsx)(WM,{open:w,onOpenChange:T,children:(0,K.jsxs)(WM.Content,{children:[(0,K.jsxs)(WM.Header,{children:[(0,K.jsx)(WM.Title,{children:`Delete Item`}),(0,K.jsx)(WM.Description,{children:`Are you sure you want to delete this item? This action cannot be undone.`})]}),(0,K.jsxs)(WM.Footer,{children:[(0,K.jsx)(WM.Cancel,{children:`Cancel`}),(0,K.jsx)(WM.Action,{onClick:async()=>{try{await s.mutateAsync({datasetId:e,itemId:t.id}),Qx.success(`Item deleted successfully`),T(!1),i()}catch(e){Qx.error(`Failed to delete item: ${e instanceof Error?e.message:`Unknown error`}`)}},children:s.isPending?`Deleting...`:`Yes, delete`})]})]})})]})}function avi(){let{datasetId:e,items:t,isLoadingItems:n,currentItemId:r,openItem:i,close:a}=Uhi(),o=Gw();y2r(r,a);let s=(0,G.useMemo)(()=>r?t.find(e=>e.id===r):void 0,[t,r]),{data:c,isLoading:l}=zAt({datasetId:s?``:e,itemId:!s&&r?r:``,queryOptions:{enabled:!(s||!e)&&!!(!s&&r&&r)}}),u=(0,K.jsx)(rvi,{datasetId:e,item:s??c??void 0,itemId:r,fallback:n||l?(0,K.jsx)(dQ.LoadingData,{}):(0,K.jsxs)(dQ.NoData,{children:[`No loaded item "`,r,`".`]}),items:t,onItemChange:i,onClose:a,variant:o?`drawer`:`inline`});return o?u:r?(0,K.jsx)(B8,{owner:`dataset-item`,children:u}):null}function ovi({crumbs:e,children:t}){return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{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 svi(){let{datasetId:e}=Ev(),t=Tv(),[n,r]=Mv(),{activeVersion:i}=wN(n,r),a=[KN(`/datasets`),kMt],o=[...a,AMt],[s,c]=(0,G.useState)(!1),[l,u]=(0,G.useState)(!1),[d,f]=(0,G.useState)(!1),[p,m]=(0,G.useState)(!1),[h,g]=(0,G.useState)(!1),{data:_,error:v,isLoading:y}=SN({datasetId:e,queryOptions:{enabled:!!e}}),{data:b=[],isLoading:x}=yN({datasetId:e,search:void 0,version:i,queryOptions:{enabled:!!e}});if(y)return null;if(v&&DN(v))return(0,K.jsx)(ovi,{crumbs:a,children:(0,K.jsx)(_H,{})});if(v&&ON(v))return(0,K.jsx)(ovi,{crumbs:a,children:(0,K.jsx)(gH,{resource:`datasets`})});if(v&&kN(v)||!y&&!v&&!_)return(0,K.jsx)(ovi,{crumbs:a,children:(0,K.jsx)(Hx,{titleSlot:`Dataset not found`,descriptionSlot:`No dataset with id "${e}".`,actionSlot:(0,K.jsx)(X,{render:(0,K.jsx)(jv,{to:`/datasets`}),icon:(0,K.jsx)(tS,{}),children:`Back to datasets`})})});if(v)return(0,K.jsx)(ovi,{crumbs:a,children:(0,K.jsx)(Hx,{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)(Ix,{}),children:`New experiment`}),E&&(0,K.jsx)(X,{variant:`ghost`,size:`sm`,render:(0,K.jsx)(jv,{to:`/experiments?dataset=${e}`}),icon:(0,K.jsx)(sMt,{}),children:`Experiments`}),(0,K.jsx)(X,{variant:`ghost`,size:`sm`,onClick:()=>g(!0),icon:(0,K.jsx)(HS,{}),children:`Schema`}),(0,K.jsxs)(ZT,{children:[(0,K.jsx)(ZT.Trigger,{asChild:!0,children:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,"aria-label":`Dataset actions menu`,children:(0,K.jsx)(QT,{})})}),(0,K.jsxs)(ZT.Content,{align:`end`,className:`w-48`,children:[(0,K.jsxs)(ZT.Item,{onSelect:()=>void t(`/datasets/${e}/edit`),children:[(0,K.jsx)(XV,{}),` Edit dataset`]}),(0,K.jsxs)(ZT.Item,{onSelect:()=>m(!0),children:[(0,K.jsx)(cC,{}),` Duplicate dataset`]}),(0,K.jsxs)(ZT.Item,{onSelect:()=>f(!0),variant:`destructive`,children:[(0,K.jsx)(Bj,{}),` Delete dataset`]})]})]})]});return(0,K.jsxs)(Hhi,{datasetId:e,items:b,isLoadingItems:x,children:[(0,K.jsxs)(`div`,{className:`h-full`,children:[(0,K.jsxs)(MS,{variant:`fit`,breadcrumbs:(0,K.jsx)(uN,{crumbs:o}),headerActions:O,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(`div`,{children:(0,K.jsx)(Ghi,{datasetId:e,onAddItemClick:()=>u(!0),toolbarActionsSlot:D?(0,K.jsx)(qhi,{datasetId:e}):void 0})})]}),(0,K.jsx)(avi,{})]}),(0,K.jsx)(Jgi,{initialDatasetId:e,initialDatasetVersion:i??void 0,open:s,onOpenChange:c,onSuccess:S},`${e}:${i??`latest`}`),(0,K.jsx)(ror,{datasetId:e,open:l,onOpenChange:u}),_&&(0,K.jsx)(epi,{open:p,onOpenChange:m,sourceDatasetId:_.id,sourceDatasetName:_.name,sourceDatasetDescription:_.description,sourceDatasetTargetType:_.targetType}),_&&(0,K.jsx)(thi,{open:h,onOpenChange:g,dataset:_}),_&&(0,K.jsx)(ypi,{open:d,onOpenChange:f,datasetId:_.id,datasetName:_.name,onSuccess:C})]})}function cvi({children:e,className:t}){return(0,K.jsx)(`div`,{className:c(`grid content-start`,t),children:e})}function lvi({children:e,isLoading:t}){return(0,K.jsx)(T,{variant:`caption`,tone:`muted`,className:c(`mt-1 ml-1 flex max-w-140 flex-wrap gap-x-4 gap-y-1 first-of-type:mt-3`,{"w-[40rem] max-w-[80%] animate-pulse rounded-md bg-fill":t}),children:t?(0,K.jsx)(K.Fragment,{children:`\xA0`}):(0,K.jsx)(K.Fragment,{children:e})})}function uvi({children:e,title:t,description:n,icon:r,className:i,withMargins:a=!0}){let o=t===`loading`,s=n===`loading`;return e?(0,K.jsx)(`header`,{className:c(`grid w-full grid-cols-[1fr_auto] gap-8`,{"mt-6 mb-4":a},i),children:e}):(0,K.jsxs)(`header`,{className:c(`grid gap-1 py-3`,i),children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,tone:`ink`,className:c(`flex items-center gap-2`,`[&>svg]:size-6 [&>svg]:text-muted-foreground`,{"w-60 max-w-[50%] animate-pulse rounded-md bg-muted":o}),children:o?(0,K.jsx)(K.Fragment,{children:`\xA0`}):(0,K.jsxs)(K.Fragment,{children:[r&&r,` `,t]})}),n&&(0,K.jsx)(T,{variant:`caption`,tone:`muted`,className:c(`m-0`,{"w-[40rem] max-w-[80%] animate-pulse rounded-md bg-muted":s}),children:s?(0,K.jsx)(K.Fragment,{children:`\xA0`}):n})]})}function dvi({children:e,isLoading:t}){return(0,K.jsx)(T,{as:`h1`,variant:`heading`,tone:`ink`,className:c(`flex items-center gap-2`,`[&>svg]:size-[1.25em] [&>svg]:opacity-50`,t&&`w-60 max-w-[50%] animate-pulse rounded-md bg-fill`),children:t?(0,K.jsx)(K.Fragment,{children:`\xA0`}):e})}var U7=Object.assign(uvi,{Title:dvi,Description:lvi,Column:cvi}),fvi=[KN(`/datasets`),kMt,{id:`dataset-edit`,label:`Edit dataset`}];function pvi({children:e}){return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:fvi}),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 mvi(){let{datasetId:e}=Ev(),t=Tv(),{data:n,error:r,isLoading:i}=SN({datasetId:e,queryOptions:{enabled:!!e}}),a=()=>void t(`/datasets/${e}`);return i?null:r&&DN(r)?(0,K.jsx)(pvi,{children:(0,K.jsx)(_H,{})}):r&&ON(r)?(0,K.jsx)(pvi,{children:(0,K.jsx)(gH,{resource:`datasets`})}):r||!n?(0,K.jsx)(pvi,{children:(0,K.jsx)(Hx,{tone:`error`,titleSlot:`Failed to load dataset`,descriptionSlot:r instanceof Error?r.message:`An unexpected error occurred. Please try again.`})}):(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:fvi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Edit dataset`}),(0,K.jsx)(`div`,{}),(0,K.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:(0,K.jsxs)(`div`,{className:`w-full max-w-2xl overflow-y-auto px-4 py-5`,children:[(0,K.jsx)(U7,{className:`mb-6 p-0`,children:(0,K.jsxs)(U7.Column,{children:[(0,K.jsxs)(U7.Title,{children:[(0,K.jsx)(iT,{}),` Edit dataset`]}),(0,K.jsx)(U7.Description,{children:n.name})]})}),(0,K.jsx)(JN,{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})})]})})]})}var hvi=U(`IconChanges`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M20 18V6C20 4.89543 19.1046 4 18 4H6C4.89543 4 4 4.89543 4 6V18C4 19.1046 4.89543 20 6 20H18C19.1046 20 20 19.1046 20 18Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M9.5 10H14.5M12 7.5V12.5`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M9.5 16L14.5 16`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}));function gvi(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 _vi(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)(wC,{children:[(0,K.jsx)(wC.Item,{children:(0,K.jsxs)(`b`,{children:[`v. `,e.datasetVersion]})}),(0,K.jsx)(wC.Item,{children:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:mC(n,`date-time`)})})]}),e.isLatest?(0,K.jsx)(JS,{variant:`blue`,size:`xs`,className:`ml-auto`,children:`Latest`}):null]}),disabled:t?.has(e.datasetVersion)??!1}})}function vvi(e){let t=Number(e);return e!=null&&Number.isFinite(t)&&t>0?t:null}function yvi(){let{datasetId:e,itemId:t}=Ev(),[n,r]=Mv(),i=[KN(`/datasets`),kMt,{id:`dataset-item`,label:CMt(t),to:e&&t?`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}`:void 0},{id:`dataset-item-versions`,label:`Item Version History`}],a=vvi(n.get(`version`)),o=vvi(n.get(`compare`)),s=n.get(`view`)===`diff`,{data:c,error:l}=SN({datasetId:e??``,queryOptions:{enabled:!!e}}),{data:u,isLoading:d}=ijt({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}=ajt({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&&DN(l))return(0,K.jsxs)(MS,{variant:`fit`,breadcrumbs:(0,K.jsx)(uN,{crumbs:i}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Item Version History`}),(0,K.jsx)(_H,{variant:`fill`})]});if(l&&ON(l))return(0,K.jsxs)(MS,{variant:`fit`,breadcrumbs:(0,K.jsx)(uN,{crumbs:i}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Item Version History`}),(0,K.jsx)(gH,{variant:`fill`,resource:`datasets`})]});if(!e||!t)return(0,K.jsxs)(MS,{variant:`fit`,breadcrumbs:(0,K.jsx)(uN,{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?gvi(f,e):null,x=h?gvi(h,e):null,S=(f?.datasetVersion??0)<(h?.datasetVersion??0);return(0,K.jsxs)(MS,{variant:`fit`,breadcrumbs:(0,K.jsx)(uN,{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)(y3r,{}),` Default view`]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(hvi,{}),` 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)(JN,{className:`grid min-h-0 grid-rows-[auto_1fr] overflow-hidden`,children:[(0,K.jsx)(YN,{children:(0,K.jsx)(bvi,{label:`Version`,value:p==null?``:String(p),options:_vi(u??[],m==null?void 0:new Set([m])),onValueChange:e=>_(`version`,Number(e))})}),(0,K.jsx)(QN,{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)(tgi,{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)(JN,{className:`grid min-h-0 grid-rows-[auto_1fr] overflow-hidden`,children:[(0,K.jsx)(YN,{children:(0,K.jsx)(bvi,{label:`Compare version`,value:m==null?``:String(m),placeholder:`Select a version to compare`,options:_vi(u??[],p==null?void 0:new Set([p])),onValueChange:e=>_(`compare`,Number(e))})}),(0,K.jsx)(QN,{className:`grid content-start gap-5 overflow-y-auto`,children:m==null?(0,K.jsx)(Hx,{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)(tgi,{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 bvi({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)(tvi,{className:`size-icon-md opacity-50`}),(0,K.jsxs)(Pk,{value:t,onValueChange:i,children:[(0,K.jsx)(Ik,{"aria-label":e,className:`w-full`,children:(0,K.jsx)(Fk,{placeholder:r,className:`flex-1`})}),(0,K.jsx)(Lk,{children:n.map(e=>(0,K.jsx)(Rk,{value:e.value,disabled:e.disabled,children:e.label},e.value))})]})]})}var xvi=U(`IconLaw`,()=>(0,K.jsx)(`path`,{d:`M12 3V20M12 20H7M12 20H17M3 6H7.52786C7.83835 6 8.14458 5.92771 8.42229 5.78885L9.57771 5.21115C9.85542 5.07229 10.1616 5 10.4721 5H13.5279C13.8384 5 14.1446 5.07229 14.4223 5.21115L15.5777 5.78885C15.8554 5.92771 16.1616 6 16.4721 6H21M5.5 6L3.02044 13.4387C2.71808 14.3458 3.08919 15.3834 4.00531 15.657C5.01171 15.9577 5.98829 15.9577 6.99469 15.657C7.91081 15.3834 8.28192 14.3457 7.97956 13.4387L5.5 6ZM18.5 6L16.0204 13.4387C15.7181 14.3458 16.0892 15.3834 17.0053 15.657C18.0117 15.9577 18.9883 15.9577 19.9947 15.657C20.9108 15.3834 21.2819 14.3457 20.9796 13.4387L18.5 6Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})),Svi=[KN(`/datasets`),kMt,{id:`dataset-versions`,label:`Versions`}];function Cvi(){let{datasetId:e}=Ev(),[t]=Mv(),n=t.get(`ids`)?.split(`,`).map(Number).filter(e=>!isNaN(e)&&e>0)??[],r=Tv(),{data:i,error:a}=SN({datasetId:e??``,queryOptions:{enabled:!!e}}),o=yN({datasetId:e??``,search:void 0,version:n[0]??null,queryOptions:{enabled:!!e}}),s=yN({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&&DN(a)?(0,K.jsxs)(MS,{variant:`fit`,breadcrumbs:(0,K.jsx)(uN,{crumbs:Svi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Versions`}),(0,K.jsx)(_H,{variant:`fill`})]}):a&&ON(a)?(0,K.jsxs)(MS,{variant:`fit`,breadcrumbs:(0,K.jsx)(uN,{crumbs:Svi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Versions`}),(0,K.jsx)(gH,{variant:`fill`,resource:`datasets`})]}):!e||n.length<2?(0,K.jsxs)(MS,{variant:`fit`,breadcrumbs:(0,K.jsx)(uN,{crumbs:Svi}),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)(MS,{variant:`fit`,breadcrumbs:(0,K.jsx)(uN,{crumbs:Svi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Versions`}),(0,K.jsx)(`div`,{className:`h-full overflow-hidden px-[3vw] pb-4`,children:(0,K.jsxs)(`div`,{className:`mx-auto grid h-full max-w-[140rem] grid-rows-[auto_1fr] gap-4`,children:[(0,K.jsxs)(U7,{children:[(0,K.jsxs)(U7.Column,{children:[(0,K.jsxs)(U7.Title,{children:[(0,K.jsx)(xvi,{}),` Compare Dataset Versions`]}),(0,K.jsx)(U7.Description,{children:(0,K.jsxs)(EZ,{children:[(0,K.jsx)(tvi,{}),` Comparing `,n.length,` versions of`,` `,i?.name||e?.slice(0,8)]})})]}),(0,K.jsx)(U7.Column,{children:(0,K.jsx)(X,{render:(0,K.jsx)(jv,{to:`/datasets/${e}`}),icon:(0,K.jsx)(tS,{}),children:`Back to dataset`})})]}),(0,K.jsx)(K_i,{children:(0,K.jsxs)(G_i,{children:[(0,K.jsx)(q_i,{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)(evi,{datasetId:e,versionA:n[0],versionB:n[1],allItems:u,itemsAMap:d,itemsBMap:f})]})})]})})]})}var wvi=100,Tvi=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:wvi,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}},Evi=(e,{experimentId:t,targetType:n,targetId:r,experiments:i,isLoadingExperiments:a=!1,queryOptions:o})=>{let s=Y(),{inView:c,setRef:l}=GM(),u=i!==void 0,{data:d,isLoading:f}=c_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=T_({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 Tvi(s,e,t);for(;n.items.length===0&&n.next;)n=await Tvi(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}},Dvi=(e={})=>Evi(`needs-review`,e),Ovi=(e={})=>Evi(`complete`,e);function kvi({queryOptions:e}={}){let t=Y();return S_({queryKey:[`experiment-review-summary`],queryFn:()=>t.getExperimentReviewSummary(),...e})}var Avi={baseline:`purple`,contender:`blue`},W7=e=>e===0?`Baseline`:`Contender ${e}`;function jvi({open:e,onOpenChange:t,experimentId:n,experimentName:r,onSuccess:i}){let{deleteExperiment:a}=bN();return(0,K.jsx)(WM,{open:e,onOpenChange:t,children:(0,K.jsxs)(WM.Content,{children:[(0,K.jsxs)(WM.Header,{children:[(0,K.jsx)(WM.Title,{children:`Delete Experiment`}),(0,K.jsxs)(WM.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)(WM.Footer,{children:[(0,K.jsx)(WM.Cancel,{children:`Cancel`}),(0,K.jsx)(X,{icon:(0,K.jsx)(Bj,{}),variant:`primary`,onClick:async()=>{try{await a.mutateAsync(n),Qx.success(`Experiment deleted successfully`),t(!1),i?.()}catch(e){Qx.error(`Failed to delete experiment: ${e instanceof Error?e.message:`Unknown error`}`)}},disabled:a.isPending,children:a.isPending?`Deleting...`:`Delete`})]})]})})}var Mvi=`minmax(9rem,1fr)`,Nvi=`minmax(8rem,16rem)`,Pvi=`auto auto auto auto auto auto auto auto`,Fvi=`auto auto auto`,G7={experiment:`Experiment`,description:`Description`,dataset:`Dataset`,target:`Target`,status:`Status`,items:`Items`,succeeded:`Processed`,failed:`Errored`,duration:`Duration`,avgDuration:`Avg duration`,tokens:`Tokens`,cost:`Cost`,review:`Review`,date:`Date`},Ivi={completed:`neutral`,running:`warning`,failed:`destructive`,pending:`neutral`},K7={completed:`Run completed`,running:`Run in progress`,failed:`Run failed`,pending:`Run queued`};function Lvi(e){let t=ZV(e.id)??e.id;return e.name||`Experiment #${t}`}var Rvi=60;function zvi({experiment:e}){return(0,K.jsx)(`span`,{className:`block min-w-0 truncate text-left text-muted-foreground`,children:Lvi(e)})}function Bvi({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<=Rvi?n:(0,K.jsxs)(_x,{children:[(0,K.jsx)(vx,{asChild:!0,children:n}),(0,K.jsx)(yx,{children:t})]})}function Vvi(){let{data:e}=gN(),{data:t}=KM(),{data:n}=NN(),{data:r}=EN();return{agents:e,workflows:t,scorers:n,processors:r}}var Hvi={agent:PN,workflow:GS,scorer:BN,processor:zN},Uvi={agent:`Agent`,workflow:`Workflow`,scorer:`Scorer`,processor:`Processor`},Wvi=`External (caller-run)`;function Gvi(e,{agents:t,workflows:n,scorers:r,processors:i}){let{targetType:a,targetId:o}=e;if(!o)return Wvi;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 Kvi({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)(JS,{variant:r.variant,className:`shrink-0`,children:r.label}),(0,K.jsx)(zvi,{experiment:e})]}):(0,K.jsx)(zvi,{experiment:e})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(Bvi,{experiment:e})}),t!==void 0&&(0,K.jsx)(Z.TextCell,{children:t}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(Xvi,{experiment:e})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(JS,{variant:Ivi[o]??`neutral`,indicator:`dot`,children:K7[o]??o})}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:l}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:s}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:(0,K.jsx)(`span`,{className:c>0?`text-destructive-foreground`:``,children:c})}),(0,K.jsx)(Yvi,{value:qvi(e),format:QS}),i&&(0,K.jsx)(Jvi,{metrics:a}),(0,K.jsx)(Z.Cell,{className:`text-center`,children:(0,K.jsx)(Zvi,{review:n})}),(0,K.jsx)(Z.TextCell,{children:mC(e.createdAt,`date`)??`—`})]})}function qvi(e){if(e.startedAt&&e.completedAt)return new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime()}function Jvi({metrics:e}){let t=e?.avgDurationMs===void 0?void 0:Math.round(e.avgDurationMs);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Yvi,{value:t,format:QS}),(0,K.jsx)(Yvi,{value:H7(e),format:T5}),(0,K.jsx)(Yvi,{value:e?.estimatedCost,format:t=>B7(t,e?.costUnit)})]})}function Yvi({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 Xvi({experiment:e}){let t=Gvi(e,Vvi()),n=e.targetId?e.targetType:null,r=n?Hvi[n]:null;return(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5 [&_svg]:size-icon-sm [&_svg]:shrink-0`,children:[r&&(0,K.jsx)(`span`,{className:`flex text-muted-foreground`,role:`img`,"aria-label":Uvi[n],children:(0,K.jsx)(r,{})}),(0,K.jsx)(`span`,{className:n?`truncate`:`truncate text-placeholder`,children:t})]})}function Zvi({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)(JS,{size:`xs`,variant:`warning`,children:[e.needsReview,` pending`]}):(0,K.jsxs)(JS,{size:`xs`,variant:`success`,children:[e.complete,`/`,t,` reviewed`]})}var Qvi=`${Mvi} ${Nvi} 1fr ${Pvi}`,$vi=`${Qvi} auto`,eyi=`${Qvi} ${Fvi} auto`,tyi=[{label:G7.avgDuration,className:`text-center`},{label:G7.tokens,className:`text-center`},{label:G7.cost,className:`text-center`}],nyi=e=>[{label:G7.experiment},{label:G7.description},{label:G7.dataset},{label:G7.target},{label:G7.status,sortKey:`status`},{label:G7.items,className:`text-center`},{label:G7.succeeded,className:`text-center`},{label:G7.failed,className:`text-center`},{label:G7.duration,className:`text-center`},...e?tyi:[],{label:G7.review,className:`text-center`},{label:G7.date,sortKey:`createdAt`}],ryi=e=>e.stopPropagation();function iyi({experiment:e,rowProps:t,onSelect:n,featured:r,onDelete:i,leadingCell:a,children:o}){let s=a?2:void 0,{paths:c,Link:l}=sn(),u=(0,G.useRef)(null);return(0,K.jsxs)(Z.RowWrapper,{...t,onSelectRow:n??(()=>u.current?.click()),children:[a,n?(0,K.jsx)(Z.RowButton,{colStart:s,colEnd:-2,featured:r,tabIndex:-1,onClick:e=>{e.stopPropagation(),n()},children:o}):(0,K.jsx)(Z.RowLink,{ref:u,colStart:s,colEnd:-2,featured:r,to:c.experimentLink(e.id),LinkComponent:l,tabIndex:-1,onClick:ryi,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)(Bj,{})})})]})}function ayi({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}=OZ({count:y.length,global:d}),[S,C]=(0,G.useState)(null),w=r!==void 0,T=w?eyi:$vi;if(i)return(0,K.jsx)(yH,{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=nyi(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)??ZV(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)(Kvi,{experiment:e,datasetName:i,review:n?.get(e.id),showUsage:w,metrics:r?.get(e.id),selectionRole:o?{label:W7(a),variant:a===0?Avi.baseline:Avi.contender}:void 0});return(0,K.jsx)(iyi,{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)(jvi,{open:!0,onOpenChange:e=>{e||C(null)},experimentId:S.id,experimentName:S.name??void 0})]})}var oyi=[{value:`all`,label:`All statuses`},{value:`completed`,label:`Completed`},{value:`running`,label:`Running`},{value:`failed`,label:`Failed`},{value:`pending`,label:`Pending`}];function syi(e){return[{value:`all`,label:`All datasets`},...(e??[]).map(e=>({value:e.id,label:e.name}))]}var cyi=({onRunExperiment:e})=>(0,K.jsx)(Hx,{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)(Ix,{}),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)(qN,{}),children:`Experiments documentation`})]}),variant:`fill`}),lyi=e=>`${e} experiment${e===1?``:`s`}`;function uyi({experimentIds:e,onDeleted:t}){let[n,r]=(0,G.useState)(!1),[i,a]=(0,G.useState)(!1),{deleteExperiment:o}=bN(),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)(Bj,{}),onClick:()=>r(!0),children:`Delete`}),(0,K.jsx)(WM,{open:n,onOpenChange:r,children:(0,K.jsxs)(WM.Content,{children:[(0,K.jsxs)(WM.Header,{children:[(0,K.jsxs)(WM.Title,{children:[`Delete `,lyi(s)]}),(0,K.jsxs)(WM.Description,{children:[s===1?`Its`:`Their`,` results and traces will be deleted too. This can't be undone.`]})]}),(0,K.jsxs)(WM.Footer,{children:[(0,K.jsx)(WM.Cancel,{children:`Cancel`}),(0,K.jsx)(X,{icon:(0,K.jsx)(Bj,{}),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?Qx.error(`Failed to delete ${i} of ${lyi(s)}`):(Qx.success(`Deleted ${lyi(s)}`),r(!1),t())},disabled:i,children:i?`Deleting…`:s===1?`Delete experiment`:`Delete experiments`})]})]})})]})}function dyi({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)(hw,{}),onClick:t,tooltip:a?void 0:`Clear selection`,className:`mr-2 tabular-nums`,children:[i,` selected`]}),(0,K.jsx)(uyi,{experimentIds:e,onDeleted:t}),r?(0,K.jsxs)(_x,{children:[(0,K.jsx)(vx,{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)(hvi,{}),children:`Compare`})}),(0,K.jsx)(yx,{children:r})]}):(0,K.jsx)(X,{size:`sm`,onClick:n,icon:(0,K.jsx)(hvi,{}),children:`Compare`})]})}function fyi({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 pyi=`search`,myi=`status`,hyi=`dataset`,q7=`all`,gyi=[{id:`contains`,label:`contains`},{id:`is`,label:`is`}],_yi=oyi.filter(e=>e.value!==q7),vyi=({search:e,statusFilter:t,datasetFilter:n,targetType:r,targetId:i})=>{let a=[];return e&&a.push(T7(pyi,e,`contains`)),a.push(..._fi({targetType:r,targetId:i})),t!==q7&&a.push(T7(myi,t)),n!==q7&&a.push(T7(hyi,n)),a},yyi=e=>({...vfi(e),search:E7(e,pyi),statusFilter:E7(e,myi)||q7,datasetFilter:E7(e,hyi)||q7});function byi({search:e,statusFilter:t,datasetFilter:n,targetType:r,targetId:i,datasetOptions:a,onChange:o}){let s=yfi(r),c=(0,G.useMemo)(()=>[{id:pyi,label:`Search`,icon:QM,search:!0,operators:[`contains`]},...s,{id:myi,label:`Status`,icon:bX,color:$N(`orange`),operators:[`is`],strict:!0,suggestions:_yi},{id:hyi,label:`Dataset`,icon:iT,color:$N(`blue`),operators:[`is`],strict:!0,suggestions:a.filter(e=>e.value!==q7)}],[s,a]),l=(0,G.useMemo)(()=>vyi({search:e,statusFilter:t,datasetFilter:n,targetType:r,targetId:i}),[e,t,n,r,i]);return(0,K.jsxs)(c5,{fields:c,operators:gyi,value:l,onValueChange:e=>o(yyi(e)),createItemId:e=>e,"aria-label":`Experiments filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(c5.Chips,{}),(0,K.jsx)(c5.Input,{placeholder:`Filter experiments`})]})}function xyi({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)(_K,{children:(0,K.jsx)(_K.Start,{children:(0,K.jsx)(byi,{search:e,statusFilter:t,datasetFilter:n,datasetOptions:r,targetType:i,targetId:a,onChange:o})})}),(0,K.jsxs)(_K,{children:[(0,K.jsx)(_K.Start,{className:`self-end`,children:(0,K.jsx)(fyi,{dataset:c})}),(0,K.jsx)(_K.End,{children:(0,K.jsx)(dyi,{...s})})]})]})}var Syi={present:!1,targetType:null,output:null,metadata:null,comment:null,error:null,startedAt:null,completedAt:null,scores:[]},Cyi=e=>e?e instanceof Date?e.toISOString():e:null,wyi=e=>{let t=new Map;for(let n of e??[])t.set(n.itemId,n);return t},Tyi=(e,t,n,r)=>{if(!e)return Syi;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:Cyi(t?.startedAt),completedAt:Cyi(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}},Eyi=(e,t)=>{let n={};for(let r of new Set([...e.scores,...t.scores].map(e=>e.scorerId))){let i=e.scores.find(e=>e.scorerId===r)?.value??null,a=t.scores.find(e=>e.scorerId===r)?.value??null;n[r]=i!=null&&a!=null?a-i:null}return n};function J7(e){return!e.startedAt||!e.completedAt?null:new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime()}function Dyi(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 Oyi=(e,t)=>{let n=Dyi(e),r=Dyi(t);return n!=null&&r!=null?r-n:void 0},kyi=(e,t)=>{let n=J7(e),r=J7(t);return n!=null&&r!=null?r-n:null},Ayi=(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},jyi=(e,t)=>{let n=H7(e.usage),r=H7(t.usage);return n!==void 0&&r!==void 0?r-n:void 0},Myi=({comparison:e,experimentIds:t,resultsById:n,scoresById:r,usageById:i})=>{if(!e)return[];let a=new Map(t.map(e=>[e,wyi(n?.[e])]));return e.items.map(e=>{let n=t.map(t=>Tyi(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:Eyi(o,e),durationDeltaMs:n===0?null:kyi(o,e),costDelta:n===0?void 0:Ayi(o,e),tokenDelta:n===0?void 0:jyi(o,e),averageScoreDelta:n===0?void 0:Oyi(o,e)}))}})};function Nyi({datasetId:e,itemId:t,onClose:n}){let{data:r,isLoading:i}=zAt({datasetId:e,itemId:t??``,queryOptions:{enabled:!!e&&!!t}});return(0,K.jsx)(rvi,{datasetId:e,item:r,itemId:t,fallback:i?(0,K.jsx)(dQ.LoadingData,{}):(0,K.jsxs)(dQ.NoData,{children:[`Dataset item "`,t,`" not found.`]}),items:r?[r]:[],onItemChange:()=>{},onClose:n})}function Pyi({label:e,value:t,expanded:n,onExpandedChange:r}){return t==null?null:(0,K.jsx)(L7,{title:e,framed:!0,expanded:n,onExpandedChange:r,children:(0,K.jsx)(I7,{value:t})})}var Fyi=U(`IconCoins`,()=>(0,K.jsx)(`path`,{d:`M9 16C5.68629 16 3 13.3137 3 10C3 6.68629 5.68629 4 9 4C11.4597 4 13.5737 5.48012 14.5 7.59829M21 14C21 17.3137 18.3137 20 15 20C12.3841 20 10.1591 18.3259 9.33811 15.9906C9.11911 15.3677 9 14.6978 9 14C9 10.7998 11.5055 8.1847 14.6619 8.00937C14.7738 8.00315 14.8865 8 15 8C18.3137 8 21 10.6863 21 14Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`square`}));function Iyi({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)(Fyi,{}),label:`Cost`,value:B7(e?.estimatedCost,c),rawValue:e?.estimatedCost,delta:r??null,formatDelta:M_i(c),higherIsBetter:!1}]:[],u=t?[{id:`tokens`,icon:(0,K.jsx)(Z4,{}),label:`Tokens`,value:V7(H7(e)),rawValue:H7(e),delta:i??null,formatDelta:V7,higherIsBetter:!1}]:[],d=n==null?[]:[{id:`duration`,icon:(0,K.jsx)(YS,{}),label:`Duration`,value:QS(n)??`-`,rawValue:n,delta:a??null,formatDelta:O_i,higherIsBetter:!1}],f=o?[{id:`avg-score`,icon:(0,K.jsx)(G4,{}),label:`Avg score`,value:z7(o.value),rawValue:o.value,delta:o.delta??null}]:[];return[...l,...d,...f,...u,...s.map(e=>({id:`scorer:${e.scorerId}`,icon:(0,K.jsx)(BN,{}),label:e.label??(0,K.jsx)(Qhi,{scorerId:e.scorerId}),value:e.reason?.trim()?(0,K.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[z7(e.value),(0,K.jsx)(P_i,{scorerId:e.scorerId,reason:e.reason})]}):z7(e.value),rawValue:e.value,delta:e.delta??null}))]}function Lyi({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 Ryi(e){return(0,G.useSyncExternalStore)(e.subscribe,e.read,()=>e.defaultValue)}var zyi={cost:`cost`,"total-cost":`cost`,duration:`duration`,"avg-duration":`duration`,"avg-score":`average`,tokens:`tokens`,"total-tokens":`tokens`,errors:`errors`};function Byi(e){return e.startsWith(`scorer:`)?e:zyi[e]}var Vyi=[],Hyi=Lyi({key:`mastra:experiments-compare:hidden-metrics`,defaultValue:Vyi,parse:e=>yd(q()).parse(e)});function Uyi(){let e=Ryi(Hyi);return{isHidden:t=>e.includes(t),isMetricVisible:t=>{let n=Byi(t);return n===void 0||!e.includes(n)},toggle:t=>Hyi.write(e.includes(t)?e.filter(e=>e!==t):[...e,t]),reset:()=>Hyi.write(Vyi)}}function Wyi(e){return e==null?`-`:typeof e==`string`?e:JSON.stringify(e,null,2)}function Gyi(e,t){return Iyi({usage:e.usage,showUsage:t,durationMs:J7(e),costDelta:e.costDelta,tokenDelta:e.tokenDelta,durationDeltaMs:e.durationDeltaMs,averageScore:e.scores.length>0?{value:Dyi(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 Kyi({column:e,isLoading:t,showUsage:n=!1,outputExpanded:r,onOutputExpandedChange:i,onShowTrace:a}){let{isMetricVisible:o}=Uyi();if(t)return(0,K.jsx)(`div`,{className:`flex h-32 items-center justify-center`,children:(0,K.jsx)(It,{})});if(!e.present)return(0,K.jsx)(T,{tone:`muted`,className:`py-5 text-center`,children:`Not present in this experiment`});let s=Wyi(e.output),c=x_i(e),l=R7(e),u=E_i(e),d=D_i(e),f=Gyi(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)(WN,{})}):void 0,h=f.length>0,g=e=>(0,K.jsxs)(K.Fragment,{children:[!h&&m,(0,K.jsx)(uC,{content:e,variant:`ghost`})]});return(0,K.jsxs)(`div`,{className:egi,children:[h&&(0,K.jsx)(L7,{title:`Metrics`,collapsible:!1,actions:m,children:(0,K.jsx)($hi,{metrics:f})}),l?(0,K.jsx)(L7,{title:`Error`,tone:`negative`,framed:!0,actions:g(l),children:(0,K.jsx)(T,{tone:`muted`,className:`p-3 break-words`,children:l})}):(0,K.jsx)(L7,{title:`Output`,framed:!0,actions:g(s),expanded:r,onExpandedChange:i,children:d?(0,K.jsx)(T,{tone:`muted`,className:`p-3 break-words`,children:d}):(0,K.jsx)(I7,{value:c??e.output})}),u.length>0&&(0,K.jsx)(L7,{title:`Tool calls (${u.length})`,children:(0,K.jsx)(Zni,{toolCalls:u})}),e.comment&&(0,K.jsx)(L7,{title:`Comment`,framed:!0,children:(0,K.jsx)(I7,{value:e.comment})}),e.metadata&&Object.keys(e.metadata).length>0&&(0,K.jsx)(L7,{title:`Metadata`,framed:!0,actions:(0,K.jsx)(uC,{content:Wyi(e.metadata),variant:`ghost`}),children:(0,K.jsx)(I7,{value:e.metadata})})]})}var qyi=U(`IconTarget`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M17 12C17 14.7614 14.7614 17 12 17C9.23858 17 7 14.7614 7 12C7 9.23858 9.23858 7 12 7C14.7614 7 17 9.23858 17 12Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M13 12C13 12.5523 12.5523 13 12 13C11.4477 13 11 12.5523 11 12C11 11.4477 11.4477 11 12 11C12.5523 11 13 11.4477 13 12Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinejoin:`round`})]}));function Jyi({experiment:e,open:t,onOpenChange:n}){let[r,i]=(0,G.useState)(e.name??``),[a,o]=(0,G.useState)(e.description??``),{updateExperiment:s}=bN(),c=!!r.trim();return(0,K.jsx)(Xw,{open:t,onOpenChange:n,pending:s.isPending,children:(0,K.jsxs)(Zw,{children:[(0,K.jsx)(Qw,{children:(0,K.jsx)(tT,{children:`Rename Experiment`})}),(0,K.jsxs)(UV,{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()}),Qx.success(`Experiment renamed`),n(!1)}catch(e){Qx.error(`Failed to rename experiment: ${e instanceof Error?e.message:`Unknown error`}`)}},children:[(0,K.jsxs)(eT,{children:[(0,K.jsxs)($O,{children:[(0,K.jsx)(tk,{required:!0,children:`Name`}),(0,K.jsx)(Hj,{required:!0,value:r,onChange:e=>i(e.target.value),placeholder:`Enter experiment name`,autoFocus:!0})]}),(0,K.jsxs)($O,{children:[(0,K.jsx)(tk,{children:`Description`}),(0,K.jsx)(Hj,{value:a,onChange:e=>o(e.target.value),placeholder:`Enter experiment description (optional)`})]})]}),(0,K.jsxs)($w,{children:[(0,K.jsx)(rT,{children:`Cancel`}),(0,K.jsx)(Yw,{type:`submit`,disabled:!c,children:s.isPending?`Saving...`:`Save`})]})]})]})})}function Yyi({datasetId:e,version:t,differsFromBaseline:n}){let{Link:r,paths:i}=sn();return(0,K.jsxs)(`span`,{className:c(`flex min-w-0 items-center gap-2`,n&&`text-warning-foreground`),children:[n&&(0,K.jsx)(`span`,{className:`min-w-0 truncate`,children:`differs from baseline`}),(0,K.jsxs)(r,{href:`${i.datasetLink(e)}?version=${t}`,"aria-label":`Open dataset v${t}`,className:`shrink-0 hover:underline`,children:[`v`,t]})]})}function Xyi({role:e,label:t,experiment:n,onSetBaseline:r}){let{Link:i}=sn(),[a,o]=(0,G.useState)(!1),s=n?ZV(n.id)??n.id:null,l=!!n?.datasetId;return(0,K.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[n&&(0,K.jsxs)(ZT,{children:[(0,K.jsx)(ZT.Trigger,{render:(0,K.jsxs)(X,{size:`sm`,className:`max-w-full min-w-0`,children:[(0,K.jsx)(`span`,{className:`min-w-0 truncate`,children:n.name||s}),(0,K.jsx)(_,{"aria-hidden":!0})]})}),(0,K.jsxs)(ZT.Content,{align:`start`,className:`min-w-48`,children:[(0,K.jsxs)(ZT.Item,{render:(0,K.jsx)(i,{href:`/experiments/${n.id}`}),children:[(0,K.jsx)(YX,{}),` View experiment`]}),l&&(0,K.jsxs)(ZT.Item,{onSelect:()=>o(!0),children:[(0,K.jsx)(XV,{}),` Rename experiment`]})]})]}),n&&a&&(0,K.jsx)(Jyi,{experiment:n,open:!0,onOpenChange:o}),(0,K.jsx)(`div`,{className:`ml-auto shrink-0`,children:r?(0,K.jsxs)(_x,{children:[(0,K.jsx)(vx,{render:(0,K.jsx)(`button`,{type:`button`,"aria-label":`Set as baseline`,onClick:r,className:c(`cursor-pointer rounded-[7px] hover:brightness-110`,p)}),children:(0,K.jsx)(JS,{variant:Avi[e],size:`md`,icon:(0,K.jsx)(SK,{}),children:t})}),(0,K.jsx)(yx,{children:`Set as baseline`})]}):(0,K.jsx)(JS,{variant:Avi[e],size:`md`,icon:e===`baseline`?(0,K.jsx)(SK,{className:`fill-current`}):(0,K.jsx)(SK,{}),children:t})})]})}function Zyi({role:e,experiment:t,summary:n,metrics:r,baselineMetrics:i,versionMismatch:a,showUsage:o=!1}){let{Link:s,paths:c}=sn(),{isMetricVisible:l}=Uyi(),u=t?.createdAt?new Date(t.createdAt):null,d=e===`contender`,f=(e,t)=>d?k_i(e,t):null,p=t?[...t.targetId?[{id:`target`,icon:t.targetType===`agent`?(0,K.jsx)(PN,{}):(0,K.jsx)(qyi,{}),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)(tvi,{}),label:`Dataset version`,value:(0,K.jsx)(Yyi,{datasetId:t.datasetId,version:t.datasetVersion,differsFromBaseline:a}),delta:null}]:[],...u?[{id:`created-at`,icon:(0,K.jsx)(qj,{}),label:`Created`,value:mC(u,`date`),delta:null}]:[]]:[],m=o?r:void 0,h=[...m?[{id:`total-cost`,icon:(0,K.jsx)(Fyi,{}),label:`Total cost`,value:B7(m.cost,m.costUnit),rawValue:m.cost,delta:m.costUnit===i?.costUnit?f(m.cost,i?.cost):null,formatDelta:M_i(m.costUnit),higherIsBetter:!1,emphasis:!0}]:[],...r?[{id:`avg-duration`,icon:(0,K.jsx)(YS,{}),label:`Avg duration`,value:QS(r.averageDurationMs)??`-`,rawValue:r.averageDurationMs,delta:f(r.averageDurationMs,i?.averageDurationMs),formatDelta:O_i,higherIsBetter:!1,emphasis:!0}]:[],...r&&n&&n.length>0?[{id:`avg-score`,icon:(0,K.jsx)(G4,{}),label:`Avg score`,value:z7(r.averageScore),rawValue:r.averageScore,delta:f(r.averageScore,i?.averageScore),emphasis:!0}]:[],...m?[{id:`total-tokens`,icon:(0,K.jsx)(Z4,{}),label:`Total tokens`,value:V7(m.tokens),rawValue:m.tokens,delta:f(m.tokens,i?.tokens),formatDelta:V7,higherIsBetter:!1}]:[],...p,...r?[{id:`errors`,icon:(0,K.jsx)(Wx,{}),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)(BN,{}),label:(0,K.jsx)(Qhi,{scorerId:e}),value:z7(t),rawValue:t,delta:d?n:null}))].filter(e=>l(e.id));return h.length===0?null:(0,K.jsx)(L7,{title:`Summary`,collapsible:!1,children:(0,K.jsx)($hi,{metrics:h})})}function Qyi({traceHref:e,selectedSpanId:t,showPartialThread:n,showUnavailableFeaturesMsg:r,...i}){let{traceId:a,spans:o,anchorSpanId:s}=i,{navigate:c}=sn(),l=qli(),u=(0,G.useMemo)(()=>({...l,onOpenTrace:e?()=>c(e):void 0}),[l,e,c]),d=r8({traceId:a,spanId:t??``,queryOptions:{enabled:!!a&&!!t}}),f=i8({traceId:a,passive:!0,queryOptions:{enabled:!!a}}),p=Kjt(),m=Yjt(),h=eui(),g=Ati(F5(o,s),s),_=!!(a&&n&&g),v=UXr({threadId:_?g:void 0,queryOptions:{enabled:_}});return(0,K.jsx)(Xii,{...i,selectedSpanId:t,showPartialThread:n,navigation:u,fullTrace:{spans:f.data?.spans,isLoading:f.isLoading,error:f.error??void 0},selectedSpan:{span:d.data?.span,isLoading:d.isLoading},threadHasOtherTraces:v,scorers:p.data,isLoadingScorers:p.isLoading,onTriggerScorer:m.mutateAsync,onDownload:h.download,isDownloading:h.isPending,renderMessages:e=>(0,K.jsx)(cli,{...e}),spanInput:(0,K.jsx)(y7,{}),spanOutput:(0,K.jsx)(uli,{})})}function $yi(e){return(0,K.jsx)(Qyi,{...e,headerActionsSlot:e.traceId?(0,K.jsx)(dui,{traceId:e.traceId,spans:e.spans},e.traceId):void 0})}function ebi({traceId:e,onClose:t,withFeedback:n}){let{navigate:r}=sn(),[i,a]=(0,G.useState)(),{data:o,isLoading:s}=s_i({traceId:e,queryOptions:{enabled:!!e}}),c=o?.spans,l=c?.find(e=>!e.parentSpanId),{data:u}=s8({traceId:e,queryOptions:{enabled:n&&!!e}}),{data:d}=o8({traceId:e,spanId:i,queryOptions:{enabled:n&&!!e&&!!i}}),{data:f}=MN({traceId:e,spanId:l?.spanId,page:0,queryOptions:{enabled:!!e&&!!l?.spanId}});return(0,K.jsx)($yi,{size:`wide`,traceId:e,spans:c,isLoadingSpans:s,selectedSpanId:i??null,onClose:()=>{a(void 0),t()},onSpanSelect:a,showUnavailableFeaturesMsg:!1,traceHref:e?`/traces?traceId=${encodeURIComponent(e)}`:void 0,anchorSpanId:l?.spanId,feedbackTabBadge:n?u?.pagination?.total??void 0:void 0,feedbackTabSlot:n?({traceId:e})=>(0,K.jsx)(x7,{traceId:e}):void 0,scoresTabBadge:f?.pagination?.total??void 0,scoresTabSlot:({traceId:e,rootSpanId:t})=>t?(0,K.jsx)(oRr,{traceId:e,spanId:t,onScoreSelect:t=>r(qDn(e,t))}):null,spanFeedbackTabBadge:n?d?.pagination?.total??void 0:void 0,spanFeedbackTabSlot:n?({traceId:e,spanId:t})=>e&&t?(0,K.jsx)(Gli,{traceId:e,spanId:t},`${e}:${t}`):null:void 0})}var Y7=`min-w-0 px-4 py-3`,tbi=`grid grid-cols-[minmax(22rem,26rem)_repeat(var(--compare-cols),minmax(32rem,1fr))] divide-x divide-border border-border`,nbi=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,rbi=()=>!!window.getSelection()?.toString(),ibi=e=>e!=null,abi=e=>e.length>0?e.reduce((e,t)=>e+t,0)/e.length:null,obi=(e,t,n)=>abi(e.map(e=>e.sides[t]?.scores.find(e=>e.scorerId===n)?.value??null).filter(ibi)),sbi=(e,t)=>{let n=e.map(e=>e.sides[t]).filter(e=>e?.present);return{errorCount:n.filter(e=>e.error).length,averageScore:abi(n.flatMap(e=>e.scores.map(e=>e.value)).filter(ibi)),averageDurationMs:abi(n.map(J7).filter(ibi))}};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,l]=(0,G.useState)(),u=h7(),d=e=>{l(void 0),o(e)},f=e=>{o(void 0),l(e)},{data:p,isLoading:m,error:h}=GAt({datasetId:e,experimentIds:i,baselineId:t,queryOptions:{enabled:!!e&&!!t&&n.length>0}}),{data:g,isLoading:_}=ejt({datasetId:e,experimentIds:i}),v=(0,G.useMemo)(()=>i.map(e=>({id:e,status:g[e]?.status})),[i,g]),{data:y,isLoading:b}=njt({datasetId:e,experiments:v}),{data:x}=rjt({experiments:v}),{supportsMetrics:S,isLoading:C}=S7(),{data:w,isLoading:E}=a_i({experiments:v,supportsMetrics:S}),D=(0,G.useMemo)(()=>Myi({comparison:p,experimentIds:i,resultsById:y,scoresById:x,usageById:w}),[p,i,y,x,w]),O=(0,G.useMemo)(()=>{let e=[...new Set(D.flatMap(e=>e.sides.flatMap(e=>e.scores.map(e=>e.scorerId))))].sort();return i.map((t,n)=>e.map(e=>{let t=obi(D,n,e),r=obi(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:H7(n)}}),[D,i,w]);if(m||_||C||E)return(0,K.jsx)(`div`,{className:`pointer-events-none fixed inset-0 flex items-center justify-center`,children:(0,K.jsx)(It,{})});if(h)return(0,K.jsx)(gk,{variant:`warning`,title:`Error loading comparison`,children:(0,K.jsx)(gk.Message,{children:h instanceof Error?h.message:`Unknown error`})});if(!p||p.items.length===0)return(0,K.jsx)(T,{as:`p`,variant:`body`,tone:`muted`,className:`py-5 text-center`,children:`No comparison data`});let A=g[t];return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{role:`table`,"aria-label":`Experiments comparison`,className:`grid min-w-[calc(22rem_+_var(--compare-cols)_*_32rem)]`,style:{"--compare-cols":i.length},children:[(0,K.jsxs)(`div`,{role:`row`,className:c(tbi,`sticky top-0 z-20 bg-background`),children:[(0,K.jsx)(`div`,{role:`columnheader`,"aria-label":`Items`,className:Y7}),i.map((e,t)=>(0,K.jsx)(`div`,{role:`columnheader`,"aria-label":W7(t),className:c(Y7,`border-b`),children:(0,K.jsx)(Xyi,{role:t===0?`baseline`:`contender`,label:W7(t),experiment:g[e]??void 0,onSetBaseline:t>0&&r?()=>r(e):void 0})},e))]}),(0,K.jsxs)(`div`,{role:`row`,"aria-label":`Summary`,className:c(tbi,`border-b`),children:[(0,K.jsx)(`div`,{role:`cell`,"aria-label":`Items`,className:Y7}),i.map((e,t)=>{let n=g[e]??void 0;return(0,K.jsx)(`div`,{role:`cell`,"aria-label":W7(t),className:Y7,children:(0,K.jsx)(Zyi,{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)(lbi,{row:e,isLoading:b,showUsage:S,onOpen:()=>d(e.itemId),onShowTrace:f},e.itemId))]}),(0,K.jsx)(Nyi,{datasetId:e,itemId:a,onClose:()=>o(void 0)}),(0,K.jsx)(ebi,{traceId:s,onClose:()=>l(void 0),withFeedback:u.enabled})]})}function lbi({row:e,isLoading:t,showUsage:n,onOpen:r,onShowTrace:i}){let[a,o]=(0,G.useState)({input:!1,groundTruth:!1,output:!1}),s=e=>({expanded:a[e],onExpandedChange:t=>o(n=>({...n,[e]:t}))}),l=s(`output`);return(0,K.jsxs)(`div`,{role:`row`,"aria-label":e.itemId,tabIndex:0,onClick:e=>{nbi(e)||rbi()||r()},onKeyDown:e=>{e.target!==e.currentTarget||e.key!==`Enter`&&e.key!==` `||(e.preventDefault(),r())},className:c(tbi,`cursor-pointer border-b transition-colors duration-normal ease-out-custom hover:bg-fill-subtle`,m),children:[(0,K.jsxs)(`div`,{role:`cell`,className:c(Y7,egi),children:[(0,K.jsx)(Pyi,{label:`Input`,value:e.input,...s(`input`)}),(0,K.jsx)(Pyi,{label:`Ground truth`,value:e.groundTruth,...s(`groundTruth`)})]}),e.sides.map((e,r)=>(0,K.jsx)(`div`,{role:`cell`,"aria-label":W7(r),className:Y7,children:(0,K.jsx)(Kyi,{column:e,isLoading:t,showUsage:n,outputExpanded:l.expanded,onOutputExpandedChange:l.onExpandedChange,onShowTrace:i})},e.experimentId))]})}function ubi(e){let t=new Map;if(!e?.counts)return t;for(let n of e.counts)t.set(n.experimentId,{needsReview:n.needsReview,complete:n.complete,total:n.total});return t}var X7=[KN(`/experiments`)],dbi=[`createdAt`,`status`],fbi=new Map;function pbi(){let[e,t]=(0,G.useState)(``),[n,r]=(0,G.useState)(`all`),[i,a]=(0,G.useState)(!1),[o,s]=(0,G.useState)([]),c=Tv(),[l,u]=Mv(),{sort:d,onSortChange:f}=r7({searchParams:l,setSearchParams:u,allowedKeys:dbi}),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}=kfi(),_=e=>{t(e.search),r(e.statusFilter),u(t=>{let n=new URLSearchParams(t),r=(e,t)=>{t?n.set(e,t):n.delete(e)};return r(`dataset`,e.datasetFilter===`all`?``:e.datasetFilter),r(O7,e.targetType),r(k7,e.targetType===h?e.targetId:``),n},{replace:!0})},{data:v,isLoading:y,error:b}=xN(),{data:x,isLoading:S,error:C,isFetchingNextPage:w,hasNextPage:T,setEndOfListElement:E}=g_i({datasetId:m===`all`?void 0:m,target:{targetType:h,targetId:g},orderBy:p}),{data:D}=kvi(),{supportsMetrics:O}=S7(),k=(0,G.useMemo)(()=>v?.datasets??[],[v?.datasets]),A=(0,G.useMemo)(()=>x??[],[x]),j=(0,G.useMemo)(()=>syi(k),[k]),{data:M}=WAt({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}=h_i({experiments:A,supportsMetrics:O}),F=O?P??fbi:void 0,I=(0,G.useMemo)(()=>ubi(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&&DN(R))return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:X7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(_H,{variant:`fill`})]});if(C&&ON(C))return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:X7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(gH,{variant:`fill`,resource:`experiments`})]});if(b&&ON(b))return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:X7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(gH,{variant:`fill`,resource:`datasets`})]});if(R)return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:X7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(Hx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load experiments`,descriptionSlot:R.message})]});let ne=(0,K.jsx)(Jgi,{open:i,onOpenChange:a,onSuccess:e=>void c(`/experiments/${e}`)});return A.length===0&&!L&&m===`all`&&!h?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:X7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(cyi,{onRunExperiment:()=>a(!0)}),ne]}):(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:X7}),headerActions:(0,K.jsx)(X,{variant:`primary`,size:`sm`,icon:(0,K.jsx)(Ix,{}),onClick:()=>a(!0),children:`New experiment`}),actionRow:(0,K.jsx)(xyi,{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)(ayi,{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 mbi={baseline:`bg-badge-purple-indicator`,contender:`bg-badge-blue-indicator`};function hbi({experimentId:e,name:t,role:n,className:r,trailing:i}){let{Link:a,paths:o}=sn(),s=t||e.slice(0,8);return(0,K.jsxs)(X,{render:(0,K.jsx)(a,{href:o.experimentLink(e)}),variant:`ghost`,size:`sm`,className:c(`max-w-48 min-w-0`,r),"aria-label":`Open experiment ${s}`,children:[n&&(0,K.jsx)(`span`,{"aria-hidden":`true`,className:c(`size-1.5 shrink-0 rounded-full`,mbi[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 gbi(){let[e]=Mv(),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 _bi(){let{datasetId:e,baselineId:t,contenderIds:n}=gbi();return{datasetId:e,experimentIds:e&&t&&n.length>0&&t?[t,...n]:[]}}function vbi(){let{experimentIds:e}=_bi();return e.length>0?`Comparing ${e.length} experiments`:`Comparing`}function ybi(){let{datasetId:e,experimentIds:t}=_bi(),{data:n}=ejt({datasetId:e??``,experimentIds:t});return t.length===0?null:(0,K.jsxs)(mX,{children:[(0,K.jsx)(hX,{delay:0,closeDelay:100,render:(0,K.jsx)(X,{type:`button`,variant:`ghost`,size:`icon-sm`,"aria-label":`Show compared experiments`,children:(0,K.jsx)(_,{})})}),(0,K.jsx)(gX,{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)(hbi,{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)(JS,{variant:`purple`,size:`sm`,icon:(0,K.jsx)(SK,{className:`fill-current`}),children:`Baseline`})})},e))})})]})}function bbi({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)(hbi,{experimentId:t}),n<e.length-2&&`,`]})]},t))}function xbi({datasetId:e,baselineId:t,contenderIds:n}){let[,r]=Mv(),i=(0,G.useMemo)(()=>[t,...n],[t,n]),{data:a,isLoading:o,error:s}=ejt({datasetId:e,experimentIds:i});return s&&DN(s)?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Compare`}),(0,K.jsx)(_H,{variant:`fill`})]}):s&&ON(s)?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Compare`}),(0,K.jsx)(gH,{variant:`fill`,resource:`experiments`})]}):s&&!kN(s)?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Compare`}),(0,K.jsx)(Hx,{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)(bbi,{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 Sbi(){let{datasetId:e,baselineId:t,contenderIds:n}=gbi();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)(xbi,{datasetId:e,baselineId:t,contenderIds:n})}function Cbi(){let{datasetId:e}=gbi(),{Link:t,paths:n}=sn(),{data:r,isLoading:i}=SN({datasetId:e??``,queryOptions:{enabled:!!e}});if(!e||i)return null;let a=r?.name||e;return(0,K.jsx)(t,{href:n.datasetLink(e),"aria-label":`Open dataset ${a}`,className:c(`flex max-w-64 min-w-0 rounded-[7px] hover:brightness-110`,p),children:(0,K.jsx)(JS,{size:`md`,icon:(0,K.jsx)(iT,{}),className:`max-w-full min-w-0`,children:(0,K.jsx)(`span`,{className:`min-w-0 truncate`,children:a})})})}var wbi=[{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 Tbi({datasetId:e,baselineId:t,contenderIds:n}){let{data:r}=GAt({datasetId:e,experimentIds:(0,G.useMemo)(()=>[t,...n],[t,n]),baselineId:t}),{supportsMetrics:i}=S7(),{isHidden:a,toggle:o,reset:s}=Uyi(),c=(0,G.useMemo)(()=>[...new Set((r?.items??[]).flatMap(e=>Object.values(e.results).flatMap(e=>e?Object.keys(e.scores):[])))].sort(),[r]),l=wbi.filter(e=>i||!e.usage);return(0,K.jsxs)(ZT,{children:[(0,K.jsx)(ZT.Trigger,{render:(0,K.jsx)(X,{variant:`ghost`,size:`md`,icon:(0,K.jsx)(y3r,{"aria-hidden":!0}),children:`Metrics`})}),(0,K.jsxs)(ZT.Content,{align:`end`,className:`min-w-56`,children:[(0,K.jsx)(ZT.Label,{children:`Run metrics`}),l.map(e=>(0,K.jsx)(ZT.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)(ZT.Separator,{}),(0,K.jsx)(ZT.Label,{children:`Scorers`}),c.map(e=>{let t=`scorer:${e}`;return(0,K.jsx)(ZT.CheckboxItem,{checked:!a(t),onCheckedChange:()=>o(t),children:e},t)})]}),(0,K.jsx)(ZT.Separator,{}),(0,K.jsx)(ZT.Item,{onSelect:s,children:`Show all metrics`})]})]})}function Ebi(){let{datasetId:e,baselineId:t,contenderIds:n}=gbi();return(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[e&&t&&n.length>0&&(0,K.jsx)(Tbi,{datasetId:e,baselineId:t,contenderIds:n}),(0,K.jsx)(Cbi,{})]})}var Dbi=[KN(`/experiments`),{id:`experiments-compare`,Component:vbi,Switcher:ybi}];function Obi(){return(0,K.jsx)(MS,{variant:`fit`,breadcrumbs:(0,K.jsx)(uN,{crumbs:Dbi}),headerActions:(0,K.jsx)(Ebi,{}),children:(0,K.jsx)(Sbi,{})})}function kbi(e){let{data:t}=CN({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 Abi=[`agent`,`workflow`,`scorer`];function jbi({experiment:e}){let[t,n]=(0,G.useState)(!1),r=Tv(),{paths:i}=sn(),a=kbi(e),o=Abi.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)(xT,{}),children:`Rerun`}),t&&(0,K.jsx)(Jgi,{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 Mbi({experiment:e,onDeleteClick:t}){let[n,r]=(0,G.useState)(!1),i=!!e.datasetId;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(jbi,{experiment:e}),(i||!!t)&&(0,K.jsxs)(ZT,{children:[(0,K.jsx)(ZT.Trigger,{asChild:!0,children:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,"aria-label":`Experiment actions menu`,children:(0,K.jsx)(QT,{})})}),(0,K.jsxs)(ZT.Content,{align:`end`,className:`w-48`,children:[i&&(0,K.jsxs)(ZT.Item,{onSelect:()=>r(!0),children:[(0,K.jsx)(XV,{}),` Rename experiment`]}),t&&(0,K.jsxs)(ZT.Item,{onSelect:t,variant:`destructive`,children:[(0,K.jsx)(Bj,{}),` Delete experiment`]})]})]}),n&&(0,K.jsx)(Jyi,{experiment:e,open:!0,onOpenChange:r})]})}var Nbi=U(`CircleDotIcon`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z`,stroke:`currentColor`,strokeWidth:`2`}),(0,K.jsx)(`circle`,{cx:`12`,cy:`12`,r:`2.5`,fill:`currentColor`})]}));function Pbi(e){let{data:t,isLoading:n}=i8({traceId:e,queryOptions:{enabled:!!e}}),r=t?.spans.find(e=>!e.parentSpanId)?.entityType===`agent`,{supportsMetrics:i,isLoading:a}=S7(),o=r&&i,s=xZr({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 Fbi=`__create_tag__`;function Ibi({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)(sC,{"data-testid":`tag-applied`,className:`size-icon-sm`}):void 0})),t=a.trim();return t.length>0&&!s.includes(t)?[{label:`Create "${t}"`,value:Fbi},...e]:e},[s,c,a]);return(0,K.jsx)(lN,{"data-testid":`experiment-results-tag-picker`,options:l,value:void 0,onValueChange:e=>{let t=e===Fbi?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 Lbi(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function Rbi({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)(dQ.SectionHeading,{icon:(0,K.jsx)(US,{}),children:`Tool Mocks`}),i&&(0,K.jsx)(gk,{variant:`destructive`,title:`Mock mismatch`,children:(0,K.jsxs)(gk.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)(nX,{children:Lbi(i.args)})]}),n.length>0&&(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`mt-1 block`,children:[`Unconsumed mocks: `,(0,K.jsx)(nX,{children:n.map(e=>Lbi(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:Lbi(e.args)})]}),(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`shrink-0 rounded px-2 py-0.5 ${zbi(e.outcome)}`,children:e.outcome})]},`${e.outcome}-${e.toolName}-${t}`))})]})}function zbi(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 Bbi({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)(Vbi,{result:e,onClose:i,...o}):t?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(dQ.Header,{children:[(0,K.jsxs)(dQ.Heading,{children:[`Experiment item`,(0,K.jsx)(dQ.CopyId,{id:t})]}),(0,K.jsx)(dQ.HeaderActions,{children:(0,K.jsx)(dQ.CloseButton,{icon:`x`,onClick:i})})]}),n]}):null;return a===`inline`?c?(0,K.jsx)(dQ,{variant:`inline`,title:s,children:c}):null:(0,K.jsx)(dQ,{open:!!(e??t),onClose:i,title:s,depth:1,children:c})}function Vbi({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=Wbi(e.input),g=Wbi(e.output),_=x_i(e),v=E_i(e),y=D_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}=sn(),E=m&&e.traceId?e.traceId:void 0,{data:D}=s8({traceId:E,queryOptions:{enabled:!!E}}),{usage:O,isLoading:k}=Pbi(e.traceId),A=k&&(e.targetType==null||e.targetType===`agent`),j=Iyi({usage:O,showUsage:!!O||A,durationMs:J7(e),scores:[]}).map(e=>A&&(e.id===`cost`||e.id===`tokens`)?{...e,value:(0,K.jsx)(NS,{"aria-hidden":!0,className:`h-4 w-14`})}:e),M=typeof e.error==`string`&&e.error?e.error:R7(e),N=[...j,{id:`item-id`,icon:(0,K.jsx)(W6,{}),label:`Item Id`,value:(0,K.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,K.jsx)(`span`,{className:`font-mono`,title:e.itemId,children:ZV(e.itemId)}),(0,K.jsx)(uC,{content:e.itemId,tooltip:`Copy item ID to clipboard`,variant:`link`})]}),delta:null},...e.createdAt?[{id:`created`,icon:(0,K.jsx)(qj,{}),label:`Created`,value:mC(e.createdAt,`date-time`),delta:null}]:[],...e.status?[{id:`status`,icon:(0,K.jsx)(Nbi,{}),label:`Status`,value:(0,K.jsx)(fli,{status:e.status}),delta:null}]:[],...C?[{id:`tags`,icon:(0,K.jsx)(vX,{}),label:`Tags`,value:(0,K.jsx)(Ubi,{tags:x,selectedResults:S,onTagsChange:l,tagVocabulary:u,isUpdatingTags:d}),delta:null}]:[],...Iyi({showUsage:!1,durationMs:null,scores:(t??[]).map(e=>({scorerId:e.scorerId,value:e.score,reason:e.reason,label:o?(0,K.jsx)(Hbi,{scorerId:e.scorerId,featured:s===e.id,onClick:()=>o(e.id)}):void 0}))})],P=(0,K.jsx)(dQ.Content,{children:(0,K.jsxs)(`div`,{className:egi,children:[(0,K.jsx)($hi,{metrics:N}),(0,K.jsx)(L7,{title:`Input`,framed:!0,actions:(0,K.jsx)(uC,{content:h}),children:(0,K.jsx)(I7,{value:e.input})}),e.groundTruth!=null&&(0,K.jsx)(L7,{title:`Ground Truth`,framed:!0,actions:(0,K.jsx)(uC,{content:Wbi(e.groundTruth)}),children:(0,K.jsx)(I7,{value:e.groundTruth})}),M?(0,K.jsx)(L7,{title:`Error`,tone:`negative`,framed:!0,actions:(0,K.jsx)(uC,{content:M}),children:(0,K.jsx)(T,{tone:`muted`,className:`p-3 break-words`,children:M})}):(0,K.jsx)(L7,{title:`Output`,framed:!0,actions:(0,K.jsx)(uC,{content:g}),children:y?(0,K.jsx)(T,{tone:`muted`,className:`p-3 break-words`,children:y}):(0,K.jsx)(I7,{value:_??e.output})}),v.length>0&&(0,K.jsx)(L7,{title:`Tool calls (${v.length})`,children:(0,K.jsx)(Zni,{toolCalls:v})}),e.toolMockReport&&(0,K.jsx)(Rbi,{report:e.toolMockReport})]})});return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(dQ.Header,{children:[b&&(0,K.jsx)(X,{size:`sm`,variant:`primary`,onClick:()=>c(e.id),icon:(0,K.jsx)(FN,{}),children:`Request review`}),p&&e.status===`needs-review`&&(0,K.jsx)(X,{size:`sm`,variant:`primary`,onClick:p,icon:(0,K.jsx)(bX,{}),children:`Mark as reviewed`}),(0,K.jsxs)(dQ.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)(LN,{})}),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)(WN,{})}),(0,K.jsx)(dQ.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:`Go to previous result`,nextLabel:`Go to next result`}),(0,K.jsx)(dQ.CloseButton,{icon:`x`,onClick:i})]})]}),E?(0,K.jsxs)(uk,{defaultTab:`details`,className:`grid h-full min-h-0 grid-rows-[auto_1fr]`,children:[(0,K.jsx)(dQ.Header,{children:(0,K.jsxs)(lk,{variant:`pill-ghost`,size:`sm`,children:[(0,K.jsx)(dk,{value:`details`,children:`Details`}),(0,K.jsxs)(dk,{value:`feedback`,children:[`Feedback`,D?.pagination?.total!=null&&(0,K.jsxs)(K.Fragment,{children:[` (`,D.pagination.total,`)`]})]})]})}),(0,K.jsx)(fk,{value:`details`,flush:!0,children:P}),(0,K.jsx)(fk,{value:`feedback`,flush:!0,children:(0,K.jsx)(dQ.Content,{children:m({traceId:E})})})]}):P]})}function Hbi({scorerId:e,featured:t,onClick:n}){return(0,K.jsx)(`button`,{type:`button`,"aria-pressed":t,onClick:n,className:c(`min-w-0 cursor-pointer truncate hover:text-foreground hover:underline`,t&&`text-foreground`),children:e})}function Ubi({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)(tfi,{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)(hw,{className:`size-icon-xs`})})]},t)),n&&(0,K.jsx)(Ibi,{selectedResults:t,vocabulary:r,onAddTag:t=>n([...e,t]),disabled:i,variant:`ghost`})]})}function Wbi(e){return e==null?`-`:typeof e==`string`?e:JSON.stringify(e,null,2)}function Gbi(e){let t=e.scorer;return t?.hasJudge===!1||t?.hasJudge!==!0&&!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function Kbi({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:i}){return(0,K.jsx)(dQ,{open:!!e,onClose:r,title:e?`Score ${e.scorerId}`:`Score`,depth:2,children:e&&(0,K.jsx)(qbi,{score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:i})})}function qbi({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:i}){let a=Gbi(e),o=a?`Not applicable (code-based scorer)`:`Step not configured`;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(dQ.Header,{children:[(0,K.jsx)(dQ.CloseButton,{onClick:r,tooltip:`Close score panel`}),(0,K.jsxs)(dQ.Heading,{children:[`Score`,(0,K.jsx)(dQ.CopyId,{id:e.scorerId})]}),(0,K.jsxs)(dQ.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)(WN,{})}),(n||t)&&(0,K.jsx)(dQ.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:`Go to previous score`,nextLabel:`Go to next score`})]})]}),(0,K.jsx)(dQ.Content,{children:(0,K.jsxs)(`div`,{className:`grid gap-3`,children:[(0,K.jsx)(dQ.CodeSection,{title:`Score: ${e.score}`,icon:(0,K.jsx)(G4,{}),codeStr:e.reason||o,simplified:!0}),!a&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(dQ.CodeSection,{title:`Preprocess Prompt`,icon:(0,K.jsx)(K4,{}),codeStr:e.preprocessPrompt||o,simplified:!0}),(0,K.jsx)(dQ.CodeSection,{title:`Analyze Prompt`,icon:(0,K.jsx)(K4,{}),codeStr:e.analyzePrompt||o,simplified:!0}),(0,K.jsx)(dQ.CodeSection,{title:`Generate Score Prompt`,icon:(0,K.jsx)(K4,{}),codeStr:e.generateScorePrompt||o,simplified:!0}),(0,K.jsx)(dQ.CodeSection,{title:`Generate Reason Prompt`,icon:(0,K.jsx)(K4,{}),codeStr:e.generateReasonPrompt||o,simplified:!0})]})]})})]})}function Jbi(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 Ybi({result:e,scores:t,state:n,withFeedback:r,...i}){let a=Jbi(t,e?.id),{featuredTraceId:o,setFeaturedTraceId:s,featuredSpanId:c,setFeaturedSpanId:l,featuredScoreId:u,setFeaturedScoreId:d,featuredScore:f}=n??a,p=e=>{d(t=>e===t?null:e),s(null),l(void 0)},m=e=>{e&&(s(e),l(void 0),d(null))},h=()=>{if(!u||!t)return;let e=t.findIndex(e=>e.id===u);if(e>=0&&e<t.length-1)return()=>d(t[e+1].id)},g=()=>{if(!u||!t)return;let e=t.findIndex(e=>e.id===u);if(e>0)return()=>d(t[e-1].id)},{data:_,isLoading:v}=s_i({traceId:o,queryOptions:{enabled:!!o}}),y=_?.spans,b=y?.find(e=>!e.parentSpanId),{data:x}=s8({traceId:o??void 0,queryOptions:{enabled:r&&!!o}}),{data:S}=o8({traceId:o??void 0,spanId:c,queryOptions:{enabled:r&&!!o&&!!c}}),{data:C}=MN({traceId:o??void 0,spanId:b?.spanId,page:0,queryOptions:{enabled:!!o&&!!b?.spanId}});return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Bbi,{...i,result:e,scores:t,onScoreClick:p,featuredScoreId:u,onShowTrace:e?.traceId?()=>m(e.traceId):void 0,feedbackTabSlot:r?({traceId:e})=>(0,K.jsx)(x7,{traceId:e},e):void 0}),(0,K.jsx)(Kbi,{score:f??void 0,onNext:h(),onPrevious:g(),onClose:()=>d(null),onShowTrace:f?()=>m(f.traceId):void 0}),(0,K.jsx)($yi,{size:`wide`,depth:2,traceId:o??void 0,spans:y,isLoadingSpans:v,selectedSpanId:c??null,onClose:()=>{s(null),l(void 0)},onSpanSelect:l,showUnavailableFeaturesMsg:!1,traceHref:o?`/traces?traceId=${encodeURIComponent(o)}`:void 0,anchorSpanId:b?.spanId,feedbackTabBadge:r?x?.pagination?.total??void 0:void 0,feedbackTabSlot:r?({traceId:e})=>(0,K.jsx)(x7,{traceId:e}):void 0,scoresTabBadge:C?.pagination?.total??void 0,scoresTabSlot:({traceId:e,rootSpanId:n})=>n?(0,K.jsx)(oRr,{traceId:e,spanId:n,onScoreSelect:e=>{t?.some(t=>t.id===e)&&(s(null),l(void 0),d(e))}}):null,spanFeedbackTabBadge:r?S?.pagination?.total??void 0:void 0,spanFeedbackTabSlot:r?({traceId:e,spanId:t})=>e&&t?(0,K.jsx)(Gli,{traceId:e,spanId:t},`${e}:${t}`):null:void 0})]})}function Xbi({withFeedback:e,variant:t}){let{currentItemId:n,experimentId:r,datasetId:i,experimentStatus:a,results:o,isLoadingResults:s,hasNextPage:c,close:l,goToPreviousItem:u,goToNextItem:d}=y_i(),f=(0,G.useMemo)(()=>n?o.find(e=>e.itemId===n):void 0,[o,n]),{data:p}=CN({experimentId:r,experimentStatus:a,queryOptions:{enabled:!!r}}),{updateExperimentResult:m}=bN(),h=(0,G.useCallback)(async e=>{try{await m.mutateAsync({datasetId:i,experimentId:r,resultId:e,status:`needs-review`}),Qx(`Result flagged for review`)}catch{Qx.error(`Failed to flag result for review`)}},[i,r,m]),g=(0,G.useCallback)(async e=>{try{await m.mutateAsync({datasetId:i,experimentId:r,resultId:e,status:`complete`}),Qx(`Result marked as reviewed`)}catch{Qx.error(`Failed to complete result`)}},[i,r,m]),_=f?p?.[f.itemId]:void 0,v=Jbi(_,f?.id);return(0,K.jsx)(Ybi,{variant:t,result:f,itemId:n,fallback:s||c?(0,K.jsx)(dQ.LoadingData,{}):(0,K.jsxs)(dQ.NoData,{children:[`No loaded result for item "`,n,`".`]}),scores:_,state:v,withFeedback:e,onPrevious:u,onNext:d,onClose:l,onComplete:f?()=>g(f.id):void 0,onFlagForReview:f?()=>void h(f.id):void 0})}function Zbi(e){let{currentItemId:t,close:n}=y_i(),r=Gw();return y2r(t,n),r?(0,K.jsx)(Xbi,{...e}):t?(0,K.jsx)(B8,{owner:`experiment-item`,children:(0,K.jsx)(Xbi,{...e,variant:`inline`})}):null}function Qbi({children:e,className:t}){return(0,K.jsx)(`div`,{className:`@container`,children:(0,K.jsx)(`div`,{className:c(`grid gap-4 *:min-w-0! @xl:@max-4xl:grid-cols-2 @3xl:@max-4xl:has-[>:nth-child(3)]:grid-cols-3 @3xl:@max-4xl:has-[>:nth-child(4):last-child]:grid-cols-2 @4xl:grid-cols-[repeat(auto-fit,minmax(12rem,1fr))] @4xl:@max-6xl:has-[>:nth-child(5)]:grid-cols-3`,t),children:e})})}var $bi=[{label:`Agent`,entityType:`agent`},{label:`Workflow`,entityType:`workflow_run`},{label:`Scorer`,entityType:`scorer`},{label:`Ingest`,entityType:`rag_ingestion`},{label:`Classifier`,entityType:`classifier`}],Z7=`rootEntityType`,Q7={tags:`filterTags`,entityName:`filterEntityName`,runId:`filterRunId`,threadId:`filterThreadId`,sessionId:`filterSessionId`,requestId:`filterRequestId`,resourceId:`filterResourceId`,userId:`filterUserId`,organizationId:`filterOrganizationId`,serviceName:`filterServiceName`,environment:`filterEnvironment`,experimentId:`filterExperimentId`,provider:`filterProvider`,model:`filterModel`},exi=Object.keys(Q7),txi=`mastra:metrics:saved-filters`;function nxi(e){let t=gxi(e);try{localStorage.setItem(txi,t.toString())}catch{}}function rxi(){try{let e=localStorage.getItem(txi);if(!e)return null;let t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function ixi(e){if(e.has(`rootEntityType`))return!0;for(let t of exi)if(e.has(Q7[t]))return!0;return!1}var axi=`hasAll`,oxi=[{id:`is`,label:`is`},{id:axi,label:`has all of`,arity:`many`}],sxi={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`},cxi={provider:U6,model:oP},lxi=[`threadId`,`resourceId`,`userId`,`organizationId`,`runId`,`sessionId`,`requestId`,`experimentId`],uxi=e=>({id:e,label:sxi[e],icon:cxi[e]??e$r(e),color:O8(e)}),dxi=(e,t)=>e.label.localeCompare(t.label);function fxi({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r}){let i=(e,t)=>({...uxi(e),operators:[`is`],strict:!0,suggestions:t}),a=e=>({...uxi(e),operators:[`is`]}),o=e=>e.map(e=>({value:e})),s=[i(`rootEntityType`,$bi.map(e=>({value:e.entityType,label:e.label}))),i(`entityName`,o(t)),{...i(`tags`,o(e)),operators:[axi]},i(`serviceName`,o(n)),i(`environment`,o(r))],c=lxi.map(a),l=[`provider`,`model`].map(e=>({...a(e),hidden:!0}));return[...s.toSorted(dxi),...c.toSorted(dxi),...l]}function pxi(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:axi,value:t}}let t=Array.isArray(e.value)?e.value[0]??``:e.value;return{id:e.fieldId,fieldId:e.fieldId,operatorId:`is`,value:yxi(t)?``:t}})}function mxi(e){return e.map(e=>({fieldId:e.fieldId,value:Array.isArray(e.value)?e.value.map(String):String(e.value)}))}function hxi(e){let t=[],n=new Map([[Z7,`rootEntityType`]]);for(let e of exi)n.set(Q7[e],e);let r=new Set;for(let[i]of e.entries()){let a=n.get(i);if(!a||r.has(a))continue;if(r.add(a),a===`tags`){let n=e.getAll(i);if(n.length===0)continue;t.push({fieldId:a,value:n.filter(Boolean)});continue}if(a===`rootEntityType`||a===`entityName`||a===`serviceName`||a===`environment`||a===`provider`||a===`model`){let n=e.getAll(i);if(n.length>1){t.push({fieldId:a,value:n});continue}}let o=e.get(i);o!==null&&t.push({fieldId:a,value:o})}return t}function gxi(e){let t=new URLSearchParams,n=e.getAll(Z7);for(let e of n)t.append(Z7,e);for(let n of exi){let r=Q7[n],i=e.getAll(r);for(let e of i)t.append(r,e)}return t}function _xi(e,t){e.delete(Z7);for(let t of exi)e.delete(Q7[t]);for(let n of t){let t=n.fieldId===`rootEntityType`?Z7:Q7[n.fieldId];if(t){if(Array.isArray(n.value)){let r=n.value.filter(e=>typeof e==`string`&&e!==``);if(r.length===0){n.fieldId===`tags`&&e.append(t,``);continue}for(let n of r)e.append(t,n)}else typeof n.value==`string`&&e.set(t,n.value.trim())}}}var vxi=`Any`;function yxi(e){let t=e.trim();return t===``||t===vxi}var bxi=new Set($bi.map(e=>e.entityType));function xxi(e){let t=e.trim();return bxi.has(t)?t:void 0}function Sxi(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=>!yxi(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:xxi(e);n&&(t.rootEntityType=n)}else t[e]=r[0]}else if(typeof n.value==`string`){if(yxi(n.value))continue;let r=n.value.trim();if(e===`rootEntityType`){let e=xxi(r);e&&(t.rootEntityType=e)}else t[e]=r}}return t}var Cxi={first:0,normal:1,last:2},wxi=class extends Error{constructor(){super(`Skipped: nothing is waiting for this request any more`),this.name=`SkippedRequestError`}};function Txi(e){let t=0,n=[],r=()=>{t<e&&n.shift()?.start()};return{run(i,{priority:a=Cxi.normal,isWanted:o}={}){return new Promise((s,c)=>{let l=e=>{e&&o&&!o()?(c(new wxi),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 Exi=(0,G.createContext)(void 0);function Dxi(){let e=(0,G.use)(Exi);if(!e)throw Error(`useAggregateLimiter must be used inside MetricsProvider or AggregateLimiterProvider`);return e}function Oxi(e,t){let n=Dxi(),r=s_();return({queryKey:i})=>n.run(e,{priority:t,isWanted:()=>(r.getQueryCache().find({queryKey:i,exact:!0})?.getObserversCount()??0)>0})}function kxi({children:e}){let t=(0,G.use)(Exi),[n]=(0,G.useState)(()=>t?void 0:Txi(3));return(0,K.jsx)(Exi,{value:t??n,children:e})}var Axi=864e5,jxi={"24h":Axi,"3d":2592e5,"7d":6048e5,"14d":12096e5,"30d":2592e6};function Mxi(e,t,n){if(e!==`custom`){let t=jxi[e]??Axi;return{start:new Date(n-t),end:new Date(n)}}return{start:t?.from??new Date(n-Axi),end:t?.to??new Date(n)}}function Nxi({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)(()=>Mxi(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 Pxi(e){let t=Y(),{filters:n,filterKey:r,queryOptions:i}=e;return S_({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 Fxi(e){let t=Y(),{filters:n,filterKey:r,queryOptions:i}=e;return S_({queryKey:[`metrics`,`token-usage-by-agent`,r],queryFn:async()=>{let e={groupBy:[`entityName`],aggregation:`sum`,orderDirection:`DESC`,filters:n},[r,i]=await Promise.all([t.getMetricBreakdown({...e,name:[`mastra_model_total_input_tokens`]}),t.getMetricBreakdown({...e,name:[`mastra_model_total_output_tokens`]})]),a=new Map,o=e=>K6(a,e,()=>({input:0,output:0,cost:null,costUnit:null})),s=(e,t)=>{t.estimatedCost!=null&&(e.cost=(e.cost??0)+t.estimatedCost,t.costUnit&&(e.costUnit=t.costUnit))};for(let e of r.groups){let t=o(e.dimensions.entityName??`unknown`);t.input=e.value,s(t,e)}for(let e of i.groups){let t=o(e.dimensions.entityName??`unknown`);t.output=e.value,s(t,e)}return Array.from(a.entries()).map(([e,t])=>({name:e,input:t.input,output:t.output,total:t.input+t.output,cost:t.cost,costUnit:t.costUnit})).sort((e,t)=>t.total-e.total)},...i})}async function Ixi(e,t,n){let r=await e.getMetricBreakdown({name:[t],groupBy:[`entityName`,`status`],aggregation:`count`,orderDirection:`DESC`,filters:n}),i=new Map;for(let e of r.groups){let t=e.dimensions.entityName??`unknown`,n=e.dimensions.status??`ok`,r=K6(i,t,()=>({completed:0,errors:0}));n===`error`?r.errors+=e.value:r.completed+=e.value}return Array.from(i.entries()).map(([e,t])=>({name:e,...t})).sort((e,t)=>t.completed+t.errors-(e.completed+e.errors))}function Lxi(e){let t=Y(),{filters:n,filterKey:r,queryOptions:i}=e;return S_({queryKey:[`metrics`,`trace-volume`,r],queryFn:async()=>{let[e,r,i]=await Promise.all([Ixi(t,`mastra_agent_duration_ms`,n),Ixi(t,`mastra_workflow_duration_ms`,n),Ixi(t,`mastra_tool_duration_ms`,n)]);return{agentData:e,workflowData:r,toolData:i}},...i})}var Rxi=[{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`}],zxi=new Set(Rxi.map(e=>e.value));function Bxi(e){return typeof e==`string`&&(zxi.has(e)||e===`custom`)}var Vxi=(0,G.createContext)({datePreset:`24h`,setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:`Last 24 hours`,comparisonLabel:`vs previous 24h`,filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:`{}`,queryFilters:void 0,scope:{}});function $7(){return(0,G.useContext)(Vxi)}function Hxi(e,t){return e===`custom`?t?.from?t.to?`${pC(t.from)} – ${pC(t.to)}`:pC(t.from)??``:`Custom range`:Rxi.find(t=>t.value===e)?.label??e}var Uxi=36e5;function Wxi(e,t){if(e!==`custom`)return`vs previous ${e}`;let n=t?.to?.getTime()??Date.now(),r=t?.from?.getTime()??n-24*Uxi,i=Math.round((n-r)/Uxi);return`vs previous ${i>24&&i%24==0?`${i/24}d`:`${i}h`}`}function Gxi({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)(()=>Sxi(l),[l]),d=(0,G.useMemo)(()=>JSON.stringify(u),[u]),f=Nxi({datePreset:t,customRange:a,dimensionalFilter:u,dimensionalFilterKey:d}),p=(0,G.useMemo)(()=>s??{},[s]),m=Hxi(t,a),h=Wxi(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)(Vxi.Provider,{value:g,children:(0,K.jsx)(kxi,{children:e})})}var Kxi=[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`];function qxi(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 Jxi(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 Yxi=864e5;function Xxi(){let{data:e}=m7(),t=e?.capabilities.traceRetentionDays;if(t===void 0)return;let n=new Date(Date.now()-t*Yxi);return new Date(n.getFullYear(),n.getMonth(),n.getDate())}function Zxi(){let{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=$7(),i=Xxi();return(0,K.jsx)(t8r,{preset:qxi(e),onPresetChange:e=>t(Jxi(e)),dateFrom:n?.from,dateTo:n?.to,onDateRangeChange:(e,t)=>r({from:e,to:t}),presets:Kxi,minDate:i})}var Qxi=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}));Qxi.displayName=`MetricsCardAction`;function $xi({children:e,className:t}){return(0,K.jsx)(`div`,{className:c(`-my-1 flex shrink-0 items-center gap-1 self-start`,t),children:e})}function eSi({children:e,className:t}){return(0,K.jsx)(`div`,{className:c(`overflow-x-auto overflow-y-hidden [&_tbody>tr:last-child]:border-b-0`,t),children:e})}function tSi({className:e,...t}){return(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,className:c(`-my-1 shrink-0 cursor-grab active:cursor-grabbing`,e),...t,children:(0,K.jsx)(dP,{})})}function nSi({message:e=`Failed to load data`,className:t}){return(0,K.jsx)(`div`,{className:c(`flex flex-col items-center justify-center gap-3`,t),children:(0,K.jsx)(T,{variant:`caption`,className:`text-destructive-foreground`,children:e})})}function rSi({label:e,value:t,change:n,isLoading:r=!1,className:i}){return(0,K.jsxs)(`div`,{className:c(`grid gap-1.5`,i),children:[(0,K.jsx)(`h3`,{className:`text-body-sm text-muted-foreground`,children:e}),(0,K.jsxs)(`span`,{className:`flex items-baseline gap-2`,children:[(0,K.jsx)(`span`,{className:c(`text-title text-foreground tabular-nums [text-box:trim-both_cap_alphabetic]`,r&&`relative min-w-24`),children:r?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`span`,{className:`invisible`,children:`0`}),(0,K.jsx)(NS,{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 iSi({className:e}){return(0,K.jsx)(`div`,{className:c(`flex items-center justify-center`,e),children:(0,K.jsx)(It,{size:`md`,variant:`pulse`,className:`text-placeholder`})})}function aSi({message:e=`No data yet`,className:t}){return(0,K.jsx)(`div`,{className:c(`flex h-full items-center justify-center`,t),children:(0,K.jsx)(T,{tone:`faint`,children:e})})}function oSi({children:e,className:t}){return(0,K.jsx)(JN,{className:c(`group/metrics-card grid min-h-72 min-w-80 flex-1 grid-rows-[auto_1fr] gap-4 px-4 py-3 2xl:min-w-120 md:min-w-88 lg:min-w-sm xl:min-w-104`,t),children:e})}function sSi({children:e,className:t,as:n=`h3`}){return(0,K.jsx)(n,{className:c(`text-subheading text-foreground`,t),children:e})}function cSi({title:e,value:t,onValueChange:n,options:r,className:i}){return(0,K.jsx)(`div`,{className:`flex min-w-0`,children:(0,K.jsxs)(ZT,{modal:!1,children:[(0,K.jsxs)(ZT.Trigger,{render:(0,K.jsx)(`button`,{type:`button`,className:c(`-mx-1.5 -my-0.5 flex items-center gap-1 self-start rounded-md px-1.5 py-0.5 text-left text-subheading text-foreground hover:bg-fill-subtle`,i)}),children:[e,(0,K.jsx)(_,{className:`size-icon-sm text-muted-foreground`})]}),(0,K.jsx)(ZT.Content,{align:`start`,children:(0,K.jsx)(ZT.RadioOptions,{options:r,value:t,onValueChange:n,closeOnSelect:!0})})]})})}function lSi({children:e,className:t}){return(0,K.jsx)(`div`,{className:c(`flex min-h-6 min-w-0 flex-wrap items-center justify-between gap-x-4 gap-y-2 [&>*:first-child]:min-w-0 [&>*:last-child:not(:first-child)]:ml-auto`,t),children:e})}function uSi({children:e,className:t}){return(0,K.jsx)(`div`,{className:c(`flex items-start gap-4 [&>:first-child]:min-w-0 [&>:first-child]:flex-1`,t),children:e})}function dSi({value:e,isLoading:t=!1,className:n}){return(0,K.jsx)(`span`,{className:c(`order-last shrink-0 text-subheading text-foreground tabular-nums`,n),children:(0,K.jsx)(fSi,{value:e,isLoading:t})})}function fSi({value:e,isLoading:t}){return t?(0,K.jsx)(PS,{line:`text-body`,className:`h-4 w-14`}):typeof e==`string`?e:(0,K.jsx)(`span`,{className:`inline-flex items-center gap-3`,children:e.map(e=>(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,K.jsx)(`span`,{"aria-hidden":!0,className:`size-2 shrink-0 rounded-[2px]`,style:{backgroundColor:e.color}}),(0,K.jsxs)(`span`,{className:`sr-only`,children:[e.label,` `]}),e.value]},e.label))})}var e9=Object.assign(oSi,{Root:oSi,Kpi:z4,TopBar:uSi,Toolbar:lSi,Actions:$xi,Action:Qxi,DragHandle:tSi,Title:sSi,TitleMenu:cSi,Total:dSi,Headline:rSi,Loading:iSi,Error:nSi,Content:eSi,NoData:aSi}),pSi=`pointer-events-none absolute opacity-0 pointer-coarse:pointer-events-auto pointer-coarse:static pointer-coarse:opacity-100 group-hover/metrics-card:pointer-events-auto group-hover/metrics-card:static group-hover/metrics-card:opacity-100 motion-safe:group-hover/metrics-card:transition-opacity group-focus-within/metrics-card:pointer-events-auto group-focus-within/metrics-card:static group-focus-within/metrics-card:opacity-100 motion-safe:group-focus-within/metrics-card:transition-opacity group-has-data-popup-open/metrics-card:pointer-events-auto group-has-data-popup-open/metrics-card:static group-has-data-popup-open/metrics-card:opacity-100`;function mSi({onClick:e}){return(0,K.jsx)(e9.Action,{label:`View in traces`,className:pSi,onClick:e,children:(0,K.jsx)(WN,{})})}function hSi({onClick:e}){return(0,K.jsx)(e9.Action,{label:`View errors in logs`,className:pSi,onClick:e,children:(0,K.jsx)(cMt,{})})}function t9({isEmpty:e=!1,emptyMessage:t=`No data in this range`,children:n}){return(0,K.jsxs)(`div`,{className:`relative flex min-h-0 flex-1 flex-col`,"data-chart-empty":e||void 0,children:[(0,K.jsx)(`div`,{className:c(`flex min-h-0 flex-1 flex-col`,e&&`invisible [&_.recharts-xAxis-tick-labels]:visible`),children:(0,K.jsx)(N8r.Provider,{value:e,children:n})}),e&&(0,K.jsx)(_Si,{message:t})]})}function gSi({className:e}){return(0,K.jsx)(`div`,{"aria-hidden":!0,className:c(`h-px bg-[linear-gradient(to_right,var(--border)_3px,transparent_3px)] bg-size-[6px_1px] opacity-50`,e)})}function _Si({message:e}){return(0,K.jsxs)(`div`,{className:`absolute inset-0 flex flex-col justify-between`,style:{paddingTop:h5.top,paddingBottom:22},children:[(0,K.jsx)(gSi,{}),(0,K.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,K.jsx)(gSi,{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)(gSi,{className:`flex-1`})]}),(0,K.jsx)(gSi,{})]})}function n9({variant:e=`default`,title:t,href:n,LinkComponent:r,titleMenu:i,dragHandle:a,onTitleChange:o,total:s,change:l,isLoading:u=!1,actions:d,toolbar:f,isUpdating:p=!1,bodyHeight:m=`fixed`,className:h,children:g}){let _=c(`transition-opacity duration-200`,p&&`opacity-50`),v=e===`compact`,y=e===`hero`,b=!y&&m===`fixed`;return(0,K.jsxs)(e9,{className:c(`min-h-0! min-w-0! grid-cols-1`,`[&:has([data-slot=chart-skeleton])_[data-slot=chart-legend]]:invisible`,`[&:has([data-chart-empty])_[data-slot=chart-legend]]:invisible`,v&&`h-84`,h),children:[(0,K.jsxs)(e9.TopBar,{children:[y?(0,K.jsx)(e9.Headline,{label:t,value:typeof s==`string`?s:`—`,change:l,isLoading:u,className:_}):(0,K.jsx)(ySi,{title:t,href:n,LinkComponent:r,titleMenu:i,dragHandle:a,onTitleChange:o}),d&&(0,K.jsx)(e9.Actions,{className:c(y&&`my-0 self-center`),children:d}),!y&&s!==void 0&&(0,K.jsx)(e9.Total,{value:s,isLoading:u,className:_})]}),(0,K.jsxs)(e9.Content,{className:c(`flex flex-col gap-4 overflow-visible`,v&&`min-h-0`),children:[f||b&&f!==void 0&&(0,K.jsx)(`div`,{"aria-hidden":!0,className:`min-h-6`}),(0,K.jsx)(`div`,{className:c(`relative flex min-h-0 min-w-0 flex-col`,vSi(e,m),_),children:g})]})]})}function vSi(e,t){if(e===`compact`)return`flex-1`;if(e!==`hero`)return t===`fit`?`min-h-60`:`min-h-60 flex-1`}function ySi({dragHandle:e,...t}){return e?(0,K.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1.5`,children:[(0,K.jsx)(e9.DragHandle,{...e}),(0,K.jsx)(bSi,{...t})]}):(0,K.jsx)(bSi,{...t})}function bSi({title:e,href:t,LinkComponent:n,titleMenu:r,onTitleChange:i}){return r?(0,K.jsx)(e9.TitleMenu,{title:e,...r}):t?(0,K.jsx)(`h3`,{className:`flex`,children:(0,K.jsx)(SSi,{href:t,LinkComponent:n,children:e})}):i?(0,K.jsx)(xSi,{title:e,onTitleChange:i}):(0,K.jsx)(e9.Title,{children:e})}function xSi({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,...zk,onBlur:n=>{let r=n.currentTarget.value.trim();n.currentTarget.value=r,r!==e&&t(r)},onKeyDown:t=>{t.key===`Escape`&&(t.currentTarget.value=e),(t.key===`Enter`||t.key===`Escape`)&&(t.preventDefault(),t.currentTarget.blur())},className:c(`-mx-1.5 -my-0.5 field-sizing-content min-w-12 truncate rounded-md bg-transparent px-1.5 py-0.5`,`text-body zoom-safe-text font-medium text-foreground`,`outline-1 -outline-offset-1 outline-transparent outline-dashed hover:outline-border-strong focus:outline-border-focus`)},e)})}function SSi({href:e,LinkComponent:t,children:n}){return(0,K.jsxs)(t??`a`,{href:e,className:c(`-mx-1.5 -my-0.5 inline-flex items-center gap-1.5 rounded-md px-1.5 py-0.5 text-subheading text-foreground hover:bg-fill-subtle`,`focus-visible:outline-1 focus-visible:-outline-offset-1 focus-visible:outline-border-focus focus-visible:outline-solid`),children:[n,(0,K.jsx)(aZ,{"aria-hidden":!0,className:`size-icon-sm text-muted-foreground`})]})}function r9({error:e,onRetry:t}){return DN(e)?(0,K.jsx)(_H,{}):ON(e)?(0,K.jsx)(gH,{resource:`traces`}):(0,K.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3`,children:[(0,K.jsx)(e9.Error,{message:`Couldn't load this data. Try again in a moment.`}),t&&(0,K.jsx)(X,{size:`sm`,icon:(0,K.jsx)(fS,{}),onClick:t,children:`Retry`})]})}function CSi({label:e,icon:t,isError:n=!1,...r}){return(0,K.jsxs)(z4,{busy:!n&&(r.isLoading||r.isUpdating),children:[(0,K.jsx)(z4.Label,{icon:t&&(0,K.jsx)(t,{}),children:e}),n?(0,K.jsx)(wSi,{}):(0,K.jsx)(TSi,{...r})]})}function wSi(){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(z4.ValueRow,{className:`mt-1`,children:(0,K.jsx)(z4.Value,{children:`—`})}),(0,K.jsx)(z4.Footer,{detail:(0,K.jsx)(`span`,{className:`text-destructive-foreground`,children:`Couldn't load`})})]})}function TSi({value:e,change:t,lowerIsBetter:n,detail:r,previous:i,comparison:a,isLoading:o=!1,isUpdating:s=!1}){let l=c(`transition-opacity duration-200`,s&&`opacity-50`);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(z4.ValueRow,{className:c(`mt-1`,l),isLoading:o,children:[(0,K.jsx)(z4.Value,{children:e}),t!==void 0&&(0,K.jsx)(z4.Change,{changePct:t,comparison:a,lowerIsBetter:n,prevValue:i})]}),(0,K.jsx)(z4.Footer,{detail:r,prevValue:t===void 0?void 0:i,isLoading:o,className:l})]})}var ESi={2:`@3xl:grid-cols-2`,3:`@3xl:grid-cols-2 @7xl:grid-cols-3`},DSi={1:``,2:`@3xl:col-span-2`,full:`col-span-full`};function i9({children:e,columns:t=3,className:n}){return(0,K.jsx)(`div`,{className:c(`@container`,n),children:(0,K.jsx)(`div`,{className:c(`grid gap-4`,ESi[t]),children:e})})}function OSi({children:e,span:t=1,className:n}){return(0,K.jsx)(`div`,{className:c(`min-w-0 *:size-full *:min-w-0!`,DSi[t],n),children:e})}i9.Item=OSi;var kSi=864e5;function a9(e,t){let n=t.getTime()-e.getTime();return n<=9e7?{interval:`1h`,stepHours:1}:n<=2628e5?{interval:`1h`,stepHours:3}:n<=6084e5?{interval:`1h`,stepHours:6}:n<=12132e5?{interval:`1h`,stepHours:12}:{interval:`1d`,stepHours:24}}var o9=e=>e===`1h`?1:24;function ASi(e,t){if(t>=24)return Math.floor(e/kSi)*kSi;let n=new Date(e),r=Math.floor(n.getHours()/t)*t;return new Date(n.getFullYear(),n.getMonth(),n.getDate(),r).getTime()}function jSi(e,t){if(t>=24)return ASi(e,t)+kSi;let n=new Date(e);return ASi(new Date(n.getFullYear(),n.getMonth(),n.getDate(),n.getHours()+t).getTime(),t)}function MSi(e,t,n){let r=A4r(e,t),i=[];for(let a=ASi(e.getTime(),n);a<=t.getTime();a=jSi(a,n))i.push(N4r(a,n,r));return i}function NSi(e,t){let n=new Map(e.map((e,t)=>[e.ts,t]));return e=>n.get(ASi(new Date(e.timestamp).getTime(),t))}function s9(e,t){return{from:new Date(e),to:new Date(jSi(e,t))}}function c9(){let{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r,queryFilters:i}=$7(),a=Nxi({datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r});return i??a}var PSi={input:`mastra_model_total_input_tokens`,output:`mastra_model_total_output_tokens`,cacheRead:`mastra_model_input_cache_read_tokens`},FSi=`mastra_agent_duration_ms`;function ISi(){let e=Y(),{filters:t,filterKey:n,timestamp:r}=c9(),{interval:i,stepHours:a}=a9(r.start,r.end);return S_({queryKey:[`metrics`,`activity`,n,i],placeholderData:m_,queryFn:async()=>{let n=n=>e.getMetricTimeSeries({name:[n],interval:i,aggregation:`sum`,filters:t}),[o,s,c,l]=await Promise.all([n(PSi.input),n(PSi.output),n(PSi.cacheRead),e.getMetricTimeSeries({name:[FSi],interval:i,aggregation:`count`,groupBy:[`status`],filters:t})]),u=MSi(r.start,r.end,a).map(e=>({...e,input:0,cacheRead:0,output:0,cost:0,completed:0,failed:0,failureRate:0})),d=NSi(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 LSi=[{dataKey:`input`,label:`Input`,color:u5.green},{dataKey:`cacheRead`,label:`Cache read`,color:u5.violet},{dataKey:`output`,label:`Output`,color:u5.sky}],RSi=[{dataKey:`cost`,label:`Cost`,color:u5.green}],zSi={tokens:`Token usage`,cost:`Model cost`},BSi=[{value:`tokens`,label:zSi.tokens},{value:`cost`,label:zSi.cost}];function VSi({onViewTraces:e,onTimeRangeClick:t}){let[n,r]=(0,G.useState)(`tokens`),{data:i=[],isLoading:a,isError:o,isPlaceholderData:s}=ISi(),{timestamp:c}=c9(),{stepHours:l}=a9(c.start,c.end),u=i.reduce((e,t)=>e+t.input+t.cacheRead+t.output,0),d=i.reduce((e,t)=>e+t.cost,0),f=n===`tokens`,p=f?LSi:RSi,m={title:zSi[n],titleMenu:{value:n,onValueChange:r,options:BSi},actions:e&&(0,K.jsx)(mSi,{onClick:e}),toolbar:(0,K.jsx)(e9.Toolbar,{children:(0,K.jsx)(y5,{series:p})})};return o?(0,K.jsx)(n9,{...m,children:(0,K.jsx)(r9,{})}):(0,K.jsx)(n9,{...m,total:f?f5(u):m5(d),isLoading:a,isUpdating:s,children:(0,K.jsx)(t9,{isEmpty:!a&&u===0&&d===0,children:(0,K.jsx)(Z5r,{data:i,series:p,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:f?f5:m5,axisFormatter:f?A8r:j8r,onBucketClick:t&&(e=>t(s9(Number(e.ts),l))),isLoading:a,...l5})})})}var HSi=[{dataKey:`failureRate`,label:`Failed runs`,color:u5.error}],USi=e=>`${Math.round(e*100)}%`;function WSi({onViewErrors:e,onTimeRangeClick:t,titleMenu:n}){let{data:r=[],isLoading:i,isError:a,isPlaceholderData:o}=ISi(),{timestamp:s}=c9(),{stepHours:c}=a9(s.start,s.end),l=r.reduce((e,t)=>e+t.completed+t.failed,0),u=r.reduce((e,t)=>e+t.failed,0),d=u===0?[0,1]:void 0,f={title:`Failure rate`,titleMenu:n,actions:e&&(0,K.jsx)(hSi,{onClick:e}),toolbar:(0,K.jsx)(e9.Toolbar,{children:(0,K.jsx)(y5,{series:HSi})})};return a?(0,K.jsx)(n9,{...f,children:(0,K.jsx)(r9,{})}):(0,K.jsx)(n9,{...f,total:p5(l>0?u/l:0),isLoading:i,isUpdating:o,children:(0,K.jsx)(t9,{isEmpty:!i&&l===0,children:(0,K.jsx)(k5r,{lineStyle:`thin`,data:r,series:HSi,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:p5,axisFormatter:USi,yDomain:d,onBucketClick:t&&(e=>t(s9(Number(e.ts),c))),isLoading:i,...l5})})})}var GSi=[{dataKey:`completed`,label:`Completed`,color:u5.green},{dataKey:`failed`,label:`Failed`,color:u5.error}],KSi=[{value:`runs`,label:`Agent runs`},{value:`failure`,label:`Failure rate`}];function qSi({onTimeRangeClick:e,onFailureTimeRangeClick:t,onViewErrors:n}){let[r,i]=(0,G.useState)(`runs`),a={value:r,onValueChange:i,options:KSi};return r===`failure`?(0,K.jsx)(WSi,{titleMenu:a,onViewErrors:n,onTimeRangeClick:t}):(0,K.jsx)(JSi,{titleMenu:a,onTimeRangeClick:e})}function JSi({onTimeRangeClick:e,titleMenu:t}){let{data:n=[],isLoading:r,isError:i,isPlaceholderData:a}=ISi(),{timestamp:o}=c9(),{stepHours:s}=a9(o.start,o.end),c=n.reduce((e,t)=>e+t.completed+t.failed,0),l={title:`Agent runs`,titleMenu:t,toolbar:(0,K.jsx)(e9.Toolbar,{children:(0,K.jsx)(y5,{series:GSi})})};return i?(0,K.jsx)(n9,{...l,children:(0,K.jsx)(r9,{})}):(0,K.jsx)(n9,{...l,total:f5(c),isLoading:r,isUpdating:a,children:(0,K.jsx)(t9,{isEmpty:!r&&c===0,children:(0,K.jsx)(Z5r,{data:n,series:GSi,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:f5,onBucketClick:e&&(t=>e(s9(Number(t.ts),s))),isLoading:r,...l5})})})}var YSi={.5:`p50`,.95:`p95`,.99:`p99`},XSi={agents:`mastra_agent_duration_ms`,workflows:`mastra_workflow_duration_ms`,tools:`mastra_tool_duration_ms`};function ZSi(e){let t=Y(),{filters:n,filterKey:r,timestamp:i}=c9(),{interval:a}=a9(i.start,i.end),o=o9(a);return S_({queryKey:[`metrics`,`latency-percentiles`,e,r,a],placeholderData:m_,queryFn:async()=>{let r=await t.getMetricPercentiles({name:XSi[e],percentiles:[.5,.95,.99],interval:a,filters:n}),s=MSi(i.start,i.end,o),c=NSi(s,o);for(let e of r.series){let t=YSi[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 QSi={agents:wp.AGENT,workflows:wp.WORKFLOW_RUN,tools:wp.TOOL},$Si=[{dataKey:`p50`,label:`P50`,color:u5.sky},{dataKey:`p95`,label:`P95`,color:u5.green,emphasis:!0},{dataKey:`p99`,label:`P99`,color:u5.violet}],eCi={agents:`Agent latency`,workflows:`Workflow latency`,tools:`Tool latency`},tCi=[{value:`agents`,label:eCi.agents},{value:`workflows`,label:eCi.workflows},{value:`tools`,label:eCi.tools}];function nCi({onViewTraces:e,onTimeRangeClick:t}){let[n,r]=(0,G.useState)(`agents`),{data:i=[],isLoading:a,isError:o,isPlaceholderData:s}=ZSi(n),{timestamp:c}=c9(),l=o9(a9(c.start,c.end).interval),u=Math.max(0,...i.map(e=>e.p95??0)),d={title:eCi[n],titleMenu:{value:n,onValueChange:r,options:tCi},actions:e&&(0,K.jsx)(mSi,{onClick:()=>e(QSi[n])}),toolbar:(0,K.jsx)(e9.Toolbar,{children:(0,K.jsx)(y5,{series:$Si})})};return o?(0,K.jsx)(n9,{...d,children:(0,K.jsx)(r9,{})}):(0,K.jsx)(n9,{...d,total:k8r(u),isLoading:a,isUpdating:s,children:(0,K.jsx)(t9,{isEmpty:!a&&u===0,children:(0,K.jsx)(k5r,{lineStyle:`thin`,data:i,series:$Si,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:k8r,axisFormatter:M8r,onBucketClick:t&&(e=>t(s9(Number(e.ts),l))),isLoading:a,...l5})})})}var rCi=`-mx-2 flex w-[calc(100%+1rem)] items-center gap-3 rounded-md px-2 py-1 text-left`,l9=`shrink-0 text-right text-body-sm tabular-nums`;function iCi({row:e,columns:t,valueWidth:n,share:r,highlighted:i,dimmed:a,onHover:o,LinkComponent:s}){let l=c(rCi,i&&`bg-fill-subtle`,(e.href||e.onClick)&&`hover:bg-fill-subtle`);return(0,K.jsx)(`li`,{children:(0,K.jsxs)(aCi,{row:e,LinkComponent:s,className:l,style:{opacity:a?.5:1},onMouseEnter:o,children:[(0,K.jsx)(`span`,{className:`size-2 shrink-0 rounded-[2px]`,style:{backgroundColor:e.paint.color,opacity:e.paint.alpha}}),(0,K.jsx)(oCi,{row:e}),t.map((t,n)=>(0,K.jsx)(`span`,{className:c(l9,`text-muted-foreground`,t.width??`w-16`),children:e.cells?.[n]},t.label)),(0,K.jsx)(`span`,{className:c(l9,`w-12 text-muted-foreground`),children:r}),(0,K.jsx)(`span`,{className:c(l9,`text-foreground`,n),children:e.value})]})})}function aCi({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 oCi({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 sCi=`var(--chart-share-1)`,cCi=[1,2,3,4,5].map(e=>`var(--chart-share-${e})`),lCi=[3,4,2,5,1].map(e=>`var(--chart-share-${e})`),uCi=[1,.7,.48,.32,.2,.14],dCi={color:`var(--chart-share-rest)`,alpha:1},fCi=50,pCi=`__rest`;function mCi(e,t,n){if(n===`hues`){let n=cCi.includes(e)?[e,...cCi.filter(t=>t!==e)]:[e,...lCi];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:uCi[n]??.1}))}var hCi=e=>e.reduce((e,t)=>e+Math.max(t.share,0),0);function gCi(e){return e.map(e=>Number.isFinite(e.share)&&e.share>0?e:{...e,share:0}).toSorted((e,t)=>t.share-e.share)}function _Ci(e,{limit:t,other:n,color:r,palette:i}){if(e.length<=t+1){let t=vCi(e,r,i);return{shown:t,bar:t,rest:[]}}let a=e.slice(t),o=n?.(a),s={key:pCi,label:`Other (${a.length})`,share:hCi(a),value:o?.value,cells:o?.cells,paint:dCi,segment:pCi},c=vCi(e.slice(0,t),r,i);return{shown:[...c,s],bar:c,rest:a}}function vCi(e,t,n){let r=mCi(t,e.length,n);return e.map((e,t)=>({...e,paint:yCi(e)??r[t]??dCi,segment:e.key}))}var yCi=e=>e.color?{color:e.color,alpha:1}:void 0;function bCi(e,{count:t,color:n,palette:r}){let i=Math.min(t,e.length,fCi),a=vCi(e.slice(0,i),n,r),o=e.slice(i,t).map(e=>({...e,paint:dCi,segment:pCi}));return{shown:[...a,...o],bar:a,rest:e.slice(i)}}function xCi(e,t){let n=e.map(e=>({key:e.key,share:e.share,paint:e.paint})),r=t.length?[{key:pCi,share:hCi(t),paint:dCi}]:[],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 SCi(e,t){if(t!==void 0)return e.find(e=>e.key===t)?.segment??t}var CCi=(e,t)=>t!==void 0&&t!==e;function wCi(e,t){return t===void 0||t===e.key?!1:t!==`__rest`||e.segment!==`__rest`}var TCi=(e,t)=>{let n=e/(t||1);return n>0?n<.001?`<0.1%`:`${(n*100).toFixed(+(n<.1))}%`:`0%`};function ECi({shown:e,total:t,limit:n,pageSize:r,onMore:i,onLess:a}){if(t<=n)return null;let o=t-e,s=`flex items-center gap-1.5 rounded-md px-2 py-1 text-label text-muted-foreground transition-colors duration-150 hover:bg-fill-subtle hover:text-foreground`,c=new Intl.NumberFormat(`en`,{notation:`compact`,maximumFractionDigits:1});return(0,K.jsxs)(`li`,{className:`-mx-2 flex items-center gap-1`,children:[o>0&&(0,K.jsxs)(`button`,{type:`button`,onClick:i,className:s,children:[(0,K.jsx)(_,{className:`size-icon-sm shrink-0`}),`Show `,Math.min(o,r),` more`]}),e>n&&(0,K.jsxs)(`button`,{type:`button`,onClick:a,className:s,children:[(0,K.jsx)(d,{className:`size-icon-sm shrink-0`}),`Show top `,n]}),o>0&&(0,K.jsxs)(`span`,{className:`ml-auto pr-2 text-body-sm text-placeholder tabular-nums`,children:[c.format(e),` of `,c.format(t)]})]})}var DCi=[`w-32`,`w-24`,`w-36`,`w-20`,`w-28`];function OCi({className:e}){return(0,K.jsxs)(K.Fragment,{children:[``,(0,K.jsx)(NS,{className:c(`absolute top-1/2 h-3.5 -translate-y-1/2`,e)})]})}function kCi({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)(NS,{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:rCi,children:[(0,K.jsx)(NS,{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)(OCi,{className:c(`left-0`,DCi[r%DCi.length])})})}),t.map(e=>(0,K.jsx)(`span`,{className:c(l9,`relative`,e.width??`w-16`),children:(0,K.jsx)(OCi,{className:`right-0 w-10`})},e.label)),(0,K.jsx)(`span`,{className:c(l9,`relative w-12`),children:(0,K.jsx)(OCi,{className:`right-0 w-9`})}),(0,K.jsx)(`span`,{className:c(l9,`relative`,n),children:(0,K.jsx)(OCi,{className:`right-0 w-12`})})]},r))})]})}function ACi({className:e,...t}){return(0,K.jsx)(`div`,{className:c(`grid grid-cols-1`,e),children:(0,K.jsx)(jCi,{...t})})}function jCi({rows:e,columns:t=[],valueLabel:n,valueWidth:r=`w-14`,palette:i=`shades`,color:a=sCi,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)(MCi,{columns:t,valueLabel:n,valueWidth:r});if(d)return(0,K.jsx)(kCi,{rows:s===`other`?o+1:o,columns:t,valueWidth:r,header:v});let y=gCi(e);if(y.length===0)return(0,K.jsx)(T,{variant:`body-sm`,tone:`muted`,className:`py-6 text-center`,children:u});let b=hCi(y),x=s===`more`,{shown:S,bar:C,rest:w}=x?bCi(y,{count:_,color:a,palette:i}):_Ci(y,{limit:o,other:l,color:a,palette:i}),E=xCi(C,w),D=SCi(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*(CCi(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)(iCi,{row:e,columns:t,valueWidth:r,share:TCi(e.share,b),highlighted:p===e.key,dimmed:wCi(e,p),onHover:()=>m(e.key),LinkComponent:f},e.key)),x&&(0,K.jsx)(ECi,{shown:Math.min(_,y.length),total:y.length,limit:o,pageSize:c,onMore:()=>g(e=>e+1),onLess:()=>g(0)})]})]})}function MCi({columns:e,valueLabel:t,valueWidth:n}){let r=[...e.map(e=>({label:e.label,width:e.width??`w-16`})),{label:`Share`,width:`w-12`},{label:t,width:n}];return(0,K.jsx)(`div`,{"aria-hidden":!0,className:`flex items-center justify-end gap-3 pt-3 pb-0.5 text-column text-placeholder`,children:r.map(e=>(0,K.jsx)(`span`,{className:c(`shrink-0 text-right whitespace-nowrap`,e.width),children:e.label},e.label))})}var NCi={agents:wp.AGENT,workflows:wp.WORKFLOW_RUN,tools:wp.TOOL},PCi=[{label:`Error rate`}],FCi={agents:`Agent runs`,workflows:`Workflow runs`,tools:`Tool calls`},ICi=[{value:`agents`,label:FCi.agents},{value:`workflows`,label:FCi.workflows},{value:`tools`,label:FCi.tools}],LCi=(e,t)=>p5(t>0?e/t:0);function RCi({onViewTraces:e,onViewErrors:t,onEntityClick:n}){let[r,i]=(0,G.useState)(`agents`),a=NCi[r],o=Lxi({...c9(),queryOptions:{placeholderData:m_}}),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:f5(e.completed+e.errors),cells:[LCi(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:FCi[r],titleMenu:{value:r,onValueChange:i,options:ICi},actions:(e||t)&&(0,K.jsxs)(K.Fragment,{children:[e&&(0,K.jsx)(mSi,{onClick:()=>e(a)}),t&&(0,K.jsx)(hSi,{onClick:()=>t(a)})]})};return o.isError?(0,K.jsx)(n9,{...d,children:(0,K.jsx)(r9,{})}):(0,K.jsx)(n9,{...d,total:f5(u),isLoading:o.isLoading,isUpdating:o.isPlaceholderData,children:(0,K.jsx)(t9,{children:(0,K.jsx)(ACi,{rows:c,columns:PCi,valueLabel:`Runs`,color:u5.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:f5(n),cells:[LCi(t,n)]}},emptyState:`No runs in this range.`,isLoading:o.isLoading},r)})})}var zCi=[`mastra_model_total_input_tokens`,`mastra_model_total_output_tokens`],BCi=100;function VCi(e){let t=Y(),{filters:n,filterKey:r}=c9();return S_({queryKey:[`metrics`,`token-spend`,e,r],placeholderData:m_,queryFn:async()=>{let{groups:r}=await t.getMetricBreakdown({name:zCi,groupBy:[e],aggregation:`sum`,orderDirection:`DESC`,limit:BCi,filters:n});return r.map(t=>({key:String(t.dimensions[e]??`unknown`),tokens:t.value,cost:t.estimatedCost??0}))}})}var HCi={agents:`Usage by agent`,models:`Usage by model`,threads:`Usage by thread`},UCi=[{value:`agents`,label:HCi.agents},{value:`models`,label:HCi.models},{value:`threads`,label:HCi.threads}],WCi={placeholderData:m_},GCi=[{label:`Tokens`}];function KCi(e){let[t,n]=(0,G.useState)(`agents`);return t===`models`?(0,K.jsx)(JCi,{...e,onViewChange:n}):t===`threads`?(0,K.jsx)(YCi,{...e,onViewChange:n}):(0,K.jsx)(qCi,{...e,onViewChange:n})}function qCi(e){let{onAgentClick:t}=e,{data:n=[],isLoading:r,isPlaceholderData:i,isError:a}=Fxi({...c9(),queryOptions:WCi}),o=n.map(e=>({key:e.name,cost:e.cost??0,tokens:e.total,onClick:t&&(()=>t(e.name))}));return(0,K.jsx)(XCi,{view:`agents`,...e,rows:o,isLoading:r,isUpdating:i,isError:a})}function JCi(e){let{onModelClick:t}=e,{data:n=[],isLoading:r,isPlaceholderData:i,isError:a}=VCi(`model`),o=n.map(e=>({...e,onClick:t&&(()=>t(e.key))}));return(0,K.jsx)(XCi,{view:`models`,...e,rows:o,isLoading:r,isUpdating:i,isError:a})}function YCi(e){let{onThreadClick:t}=e,{data:n=[],isLoading:r,isPlaceholderData:i,isError:a}=VCi(`threadId`),o=n.map(e=>({...e,onClick:t&&(()=>t(e.key))}));return(0,K.jsx)(XCi,{view:`threads`,...e,rows:o,isLoading:r,isUpdating:i,isError:a})}function XCi({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:m5(e.cost),cells:[f5(e.tokens)],onClick:e.onClick})),l={title:HCi[e],titleMenu:{value:e,onValueChange:t,options:UCi},actions:n&&(0,K.jsx)(mSi,{onClick:n})};return o?(0,K.jsx)(n9,{...l,children:(0,K.jsx)(r9,{})}):(0,K.jsx)(n9,{...l,total:m5(r.reduce((e,t)=>e+t.cost,0)),isLoading:i,isUpdating:a,children:(0,K.jsx)(t9,{children:(0,K.jsx)(ACi,{rows:c,columns:GCi,valueLabel:`Cost`,color:u5.green,other:e=>({value:m5(e.reduce((e,t)=>e+t.share,0)),cells:[f5(e.reduce((e,t)=>e+(s.get(t.key)??0),0))]}),emptyState:`No model usage in this range.`,isLoading:i})})})}var ZCi=100;function QCi(){let e=Y(),{filters:t,filterKey:n,timestamp:r}=c9(),{interval:i}=a9(r.start,r.end),a=o9(i);return S_({queryKey:[`metrics`,`scores`,n,i],placeholderData:m_,queryFn:async()=>{let n=await e.listScores({filters:t,pagination:{page:0,perPage:ZCi}}),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=MSi(r.start,r.end,a),u=NSi(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 $Ci=[u5.green,u5.sky,u5.violet,u5.teal,u5.indigo],ewi=e=>e.toFixed(2),twi=e=>String(+e.toFixed(2));function nwi(e){return e.map(({scorerId:e,name:t},n)=>({dataKey:e,label:t,color:$Ci[n%$Ci.length]??u5.neutral}))}function rwi(){let{data:e,isLoading:t,isError:n,isPlaceholderData:r}=QCi(),i=e?.scorers??[],a={title:`Scores`};return n?(0,K.jsx)(n9,{...a,children:(0,K.jsx)(r9,{})}):(0,K.jsx)(n9,{...a,isUpdating:r,children:(0,K.jsx)(t9,{isEmpty:!t&&i.length===0,children:(0,K.jsx)(k5r,{lineStyle:`thin`,data:e?.buckets??[],series:nwi(i),height:`fill`,yDomain:[0,1],valueFormatter:ewi,axisFormatter:twi,isLoading:t,...D8r})})})}var iwi=[`entityName`,`environment`,`threadId`,`resourceId`,`userId`,`organizationId`,`runId`,`sessionId`],awi=[`provider`,`model`],owi=[`serviceName`,`requestId`,`experimentId`],swi=(e,t)=>({op:`eq`,left:{path:e},right:{literal:t}});function cwi(e){let t=owi.filter(t=>e[t]!==void 0);if(t.length)return{supported:!1,unsupportedFields:t};let n=[];e.rootEntityType&&n.push(swi(`entityType`,e.rootEntityType));for(let t of iwi){let r=e[t];r!==void 0&&n.push(swi(t,r))}for(let t of e.tags??[])n.push({op:`includes`,path:`tags`,value:t});for(let t of awi){let r=e[t];r!==void 0&&n.push({spans:{some:swi(t,r)}})}return n.length===0?{supported:!0,where:void 0}:{supported:!0,where:n.length===1?n[0]:{op:`and`,args:n}}}var lwi=({start:e,end:t})=>({from:e.toISOString(),to:t.toISOString()}),uwi=({start:e,end:t})=>a9(e,t).interval;function dwi(e,t){let n=o9(uwi(t)),r=MSi(t.start,t.end,n).map(e=>({...e,rows:[]})),i=NSi(r,n);for(let t of e)t.bucket&&r[i({timestamp:t.bucket,value:0})??-1]?.rows.push(t);return r}function fwi({requiresRootSpanFields:e=!1}={}){let{data:t,isLoading:n}=m7(),{timestamp:r,dimensionalFilter:i}=c9();if(n)return{status:`loading`};let a=t?.capabilities;if(a?.traceAggregate!==!0||e&&a.traceQueryRootSpanFields!==!0)return{status:`unavailable`};let o=cwi(i);return o.supported?{status:`ready`,scope:{timeRange:lwi(r),...o.where?{where:o.where}:{},interval:uwi(r),window:r}}:{status:`unsupported-filter`,unsupportedFields:o.unsupportedFields}}function u9(e,{priority:t,enabled:n}={}){let r=Y();return JXr({request:e,enabled:n,queryOptions:{queryFn:Oxi(()=>r.aggregateTraces(e),t),placeholderData:m_,staleTime:1/0}})}var pwi=[{measure:`countDistinct.resourceId`,dataKey:`resources`,label:`Resources`,color:u5.sky},{measure:`countDistinct.threadId`,dataKey:`threads`,label:`Threads`,color:u5.green},{measure:`countDistinct.userId`,dataKey:`users`,label:`Users`,color:u5.violet},{measure:`countDistinct.sessionId`,dataKey:`sessions`,label:`Sessions`,color:u5.teal}],mwi=pwi.map(e=>e.measure),hwi=`Resources and threads`;function gwi(e,t){return e?.measures[t.measure]??0}function _wi({scope:e,onTimeRangeClick:t}){let n=u9({timeRange:e.timeRange,where:e.where,interval:e.interval,measures:mwi,limit:10}),r=u9({timeRange:e.timeRange,where:e.where,measures:mwi}),i=r.data?.rows[0],a=pwi.filter(e=>gwi(i,e)>0),o=a.map((e,t)=>({dataKey:e.dataKey,label:e.label,color:e.color,emphasis:t===0})),s=dwi(n.data?.rows??[],e.window).map(({rows:e,...t})=>({...t,...Object.fromEntries(a.map(t=>[t.dataKey,gwi(e[0],t)]))})),c=o9(e.interval===`1d`?`1d`:`1h`),l=n.error??r.error,u=n.isLoading||r.isLoading,d={title:hwi,total:l?void 0:a.length?a.map(e=>({label:e.label,value:f5(gwi(i,e)),color:e.color})):f5(0),isLoading:r.isLoading,toolbar:o.length>0&&(0,K.jsx)(e9.Toolbar,{children:(0,K.jsx)(y5,{series:o})})};return l?(0,K.jsx)(n9,{...d,children:(0,K.jsx)(r9,{error:l,onRetry:()=>{n.error&&n.refetch(),r.error&&r.refetch()}})}):(0,K.jsx)(n9,{...d,isUpdating:n.isPlaceholderData||r.isPlaceholderData,children:(0,K.jsx)(t9,{isEmpty:!u&&a.length===0,children:(0,K.jsx)(k5r,{lineStyle:`thin`,data:s,series:o,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:f5,axisFormatter:A8r,onBucketClick:t&&(e=>t({window:s9(Number(e.ts),c)})),isLoading:u,...l5})})})}var vwi={serviceName:`service`,requestId:`request ID`,experimentId:`experiment`};function ywi({requiresRootSpanFields:e,children:t,...n}){let r=fwi({requiresRootSpanFields:e});return r.status===`unavailable`?null:r.status===`ready`?t(r.scope):(0,K.jsx)(n9,{...n,toolbar:null,children:r.status===`loading`?(0,K.jsx)(e9.Loading,{}):(0,K.jsx)(e9.NoData,{message:`Not available with a ${r.unsupportedFields.map(e=>vwi[e]??e).join(` or `)} filter.`})})}function bwi(e){return(0,K.jsx)(ywi,{title:hwi,children:t=>(0,K.jsx)(_wi,{scope:t,...e})})}function xwi(){return $7().scope}var Swi=[`entityName`,`environment`,`serviceName`,`threadId`,`resourceId`,`userId`,`organizationId`,`runId`,`sessionId`,`requestId`,`experimentId`],Cwi=[`tags`,`provider`,`model`],wwi=(e,t)=>({op:`eq`,left:{path:e},right:{literal:t}});function Twi(e){let t=Cwi.filter(t=>e[t]!==void 0);if(t.length)return{supported:!1,unsupportedFields:t};let n=[];e.rootEntityType&&n.push(wwi(`entityType`,e.rootEntityType));for(let t of Swi){let r=e[t];r!==void 0&&n.push(wwi(t,r))}return n.length===0?{supported:!0,where:void 0}:{supported:!0,where:n.length===1?n[0]:{op:`and`,args:n}}}function Ewi(){let{data:e,isLoading:t}=m7(),{timestamp:n,dimensionalFilter:r}=c9();if(t)return{status:`loading`};if(e?.capabilities.spanAggregate!==!0)return{status:`unavailable`};let i=Twi(r);return i.supported?{status:`ready`,scope:{timeRange:lwi(n),...i.where?{where:i.where}:{},interval:uwi(n),window:n}}:{status:`unsupported-filter`,unsupportedFields:i.unsupportedFields}}function Dwi(e,{priority:t,enabled:n}={}){let r=Y();return qXr({request:e,enabled:n,queryOptions:{queryFn:Oxi(()=>r.aggregateSpans(e),t),placeholderData:m_,staleTime:1/0}})}var Owi=`Breakdown`,kwi={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 Awi({tab:e,tabs:t,onTabChange:n,isUpdating:r,children:i}){return(0,K.jsx)(n9,{title:kwi[e],titleMenu:t.length>1?{value:e,onValueChange:n,options:t.map(e=>({value:e,label:kwi[e]}))}:void 0,isUpdating:r,bodyHeight:`fit`,children:i})}var jwi={agents:[`agent_run`],workflows:[`workflow_run`],tools:[`tool_call`,`mcp_tool_call`]},Mwi=e=>e in jwi;function Nwi(e){let t=jwi[e];return t.length===1?{op:`eq`,left:{path:`spanType`},right:{literal:t[0]??``}}:{op:`in`,value:{path:`spanType`},set:[...t]}}var Pwi=e=>e!==`workflows`&&e!==`tools`,Fwi=e=>e!==`models`,Iwi=e=>e===`tools`||e===`models`;function d9(e,t){if(e===`projects`)return[`projectId`];let n=(...e)=>t?[`projectId`,...e]:e;return e===`environments`?n(`environment`):e===`threads`?n(`threadId`):e===`models`?n(`provider`,`model`):n(`entityName`)}var f9={trace:1e3,span:500};function Lwi({timeRange:e,where:t}){return{timeRange:e,...t?{where:t}:{},groupBy:[`projectId`],measures:[`count`,`errorRate`,`duration.p95`,`countDistinct.resourceId`,`countDistinct.threadId`],limit:f9.trace}}function Rwi({timeRange:e,where:t},n){return{timeRange:e,...t?{where:t}:{},groupBy:d9(`environments`,n),measures:[`count`,`errorRate`,`duration.p95`],limit:f9.trace}}function zwi(e){let t={op:`exists`,path:`threadId`};return e?{op:`and`,args:[t,e]}:t}function Bwi({timeRange:e,where:t},n){return{timeRange:e,where:zwi(t),groupBy:n?[`projectId`,`threadId`]:[`resourceId`,`threadId`],measures:[`count`,`errorRate`,`duration.p95`],limit:f9.trace}}function Vwi(e,t,n){return e===`projects`?Lwi(t):e===`environments`?Rwi(t,n):Bwi(t,n)}function Hwi({timeRange:e,where:t}){return{timeRange:e,where:zwi(t),groupBy:[`resourceId`,`threadId`],measures:[`count`],limit:f9.trace}}function Uwi(e){let t=new Map;for(let n of e){let e=Kwi(n,`resourceId`);e&&t.set(Kwi(n,`threadId`),e)}return t}var Wwi=e=>e===`agents`||e===`workflows`?`countDistinct.traceId`:`count`;function Gwi(e,{timeRange:t,where:n},r){let i=Nwi(e);return{timeRange:t,where:n?{op:`and`,args:[i,n]}:i,groupBy:d9(e,r),measures:[`count`,...Wwi(e)===`count`?[]:[`countDistinct.traceId`],`errorCount`,`errorRate`,`duration.p95`],limit:f9.span}}var p9=(e,t)=>{let n=e.measures[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0},Kwi=(e,t)=>{let n=e.dimensions?.[t];return n==null?``:String(n)},qwi=(e,t)=>t.map(t=>e.dimensions[t]==null?``:String(e.dimensions[t])).join(`|`);function Jwi({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=Wwi(e);for(let e of n){let n=l(t.map(t=>Kwi(e,t)).join(`|`));n.count=p9(e,u)??0,n.errorRate=p9(e,`errorRate`),n.p95=p9(e,`duration.p95`),n.resources=p9(e,`countDistinct.resourceId`),n.threads=p9(e,`countDistinct.threadId`)}for(let e of i)l(qwi(e,t)).count=e.value;for(let e of r??[]){let n=l(qwi(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 Ywi({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=Wwi(e);for(let e of n){let n=o(t.map(t=>Kwi(e,t)).join(`|`));n.count=p9(e,s)??0,n.errorRate=p9(e,`errorRate`),n.p95=p9(e,`duration.p95`)}for(let e of i)o(qwi(e,t)).count=e.value;for(let e of r){let n=o(qwi(e,t));n.tokens=e.value,n.cost=e.estimatedCost??void 0}return a}function Xwi(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 Zwi(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:Qwi(n,a,i),isNew:!1}}function Qwi(e,t,n){return e===`errorRate`?t:n>0?t/n:void 0}function $wi(e,t){if(e.delta!==void 0&&e.delta!==0)return e.delta>0==(t===`count`)?`good`:`bad`}var eTi=[`mastra_model_total_input_tokens`,`mastra_model_total_output_tokens`];function m9({groupBy:e,filters:t,window:n,measure:r=`tokens`,enabled:i=!0}){let a=Y(),{filters:o,filterKey:s}=c9();return S_({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`?eTi:[`mastra_model_total_input_tokens`],groupBy:e,aggregation:r===`tokens`?`sum`:`count`,orderDirection:`DESC`,limit:1e3,filters:{...o,...t,timestamp:n}})})}function tTi({start:e,end:t}){return{start:new Date(2*e.getTime()-t.getTime()),end:new Date(e.getTime())}}var nTi=[`count`,`errorRate`,`p95`,`tokens`,`cost`],rTi=e=>nTi.includes(e),iTi=e=>Iwi(e)?`Spans`:`Traces`,aTi=`A trace is one end-to-end request, with every step it took.`,oTi=`A span is one step inside a trace, such as a tool call or a model call. One trace can have many.`,sTi=e=>Iwi(e)?oTi:aTi,cTi={errorRate:`Errors`,p95:`P95 latency`,tokens:`Tokens`,cost:`Cost`},lTi=e=>e.toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`}),uTi=({start:e,end:t})=>`${lTi(e)} – ${lTi(t)}`;function dTi(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: ${uTi(e)}`,previous:`Previous: ${uTi(tTi(e))}`}}var fTi=(e,t)=>t&&e!==`projects`,pTi=(e,t)=>t===`count`?iTi(e):cTi[t];function mTi({tab:e,built:t,previous:n,truncated:r,groupBy:i,usage:a}){return e===`threads`?t.filter(e=>e.name!==``):!n||r?t:Xwi(t,n,i,a)}function hTi(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 gTi=(e,t)=>e===`projects`?t.key:t.projectId;function _Ti(e,t){let n=gTi(e,t),r=n?{projectId:n}:{};return Mwi(e)?{...r,span:{spanTypes:jwi[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 vTi(e,t){return t&&t.toUpperCase()!==`USD`?`${f5(e)} ${t}`:m5(e)}function yTi(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}${p5(r)}`}function bTi(e){let t=tTi(e.window);return{...e,window:t,timeRange:lwi(t)}}var xTi={good:`text-badge-green-foreground`,bad:`text-badge-red-foreground`};function STi({trend:e,children:t}){return t===void 0?(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`—`}):(0,K.jsx)(`span`,{className:e?xTi[e]:`text-muted-foreground`,children:t})}function CTi({change:e,metric:t}){return e?(0,K.jsx)(STi,{trend:$wi(e,t),children:yTi(e,t)}):(0,K.jsx)(STi,{trend:void 0})}function wTi({window:e,label:t}){let{summary:n,current:r,previous:i}=dTi(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 TTi(){return(0,K.jsx)(`span`,{title:`No price for this model`,children:`Not priced`})}function ETi({row:e}){return e.cost===void 0?e.tokens?(0,K.jsx)(TTi,{}):`—`:vTi(e.cost,e.costUnit)}function h9({muted:e=!1,children:t}){return(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:e?`muted`:void 0,className:`tabular-nums`,children:t})}function DTi({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)(rti,{parts:wkn(n.name,n.provider)}):t})]})}var OTi=e=>(0,K.jsxs)(`svg`,{width:`19.125`,height:`18`,viewBox:`-1.0625 -1 19.125 18`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,...e,children:[(0,K.jsx)(`path`,{d:`M4.31445 3.16083C3.78402 3.16083 3.27531 3.37154 2.90024 3.74661C2.52517 4.12169 2.31445 4.63039 2.31445 5.16083V5.66083C2.31445 6.19126 2.52517 6.69997 2.90024 7.07504C3.27531 7.45011 3.78402 7.66083 4.31445 7.66083C4.84489 7.66083 5.35359 7.45011 5.72867 7.07504C6.10374 6.69997 6.31445 6.19126 6.31445 5.66083V5.16083C6.31445 4.63039 6.10374 4.12169 5.72867 3.74661C5.35359 3.37154 4.84489 3.16083 4.31445 3.16083Z`,fill:`currentColor`}),(0,K.jsx)(`path`,{d:`M6.76666 9.50235C6.57678 9.28532 6.30244 9.16083 6.01407 9.16083H4.50201C4.10791 9.16078 3.71766 9.23838 3.35356 9.38921C3.11733 9.48706 2.8951 9.6145 2.69205 9.76806C2.48056 9.928 2.38001 10.1888 2.38001 10.454V13.0642C2.38001 13.6165 2.82773 14.0642 3.38001 14.0642H8.55436C9.4135 14.0642 9.87269 13.0523 9.30695 12.4057L6.76666 9.50235Z`,fill:`currentColor`}),(0,K.jsx)(`path`,{fillRule:`evenodd`,clipRule:`evenodd`,d:`M12.0686 2.26107C12.0686 2.17635 11.9999 2.10767 11.9152 2.10767H10.9948C10.91 2.10767 10.8414 2.17635 10.8414 2.26107V3.85184C10.8414 3.95606 10.7397 4.02994 10.6406 3.99773L9.12775 3.50619C9.04718 3.48001 8.96063 3.52411 8.93445 3.60468L8.65003 4.48004C8.62385 4.56062 8.66795 4.64716 8.74852 4.67334L10.2611 5.1648C10.3602 5.19701 10.399 5.31655 10.3378 5.40086L9.40289 6.68765C9.35309 6.75619 9.36829 6.85212 9.43683 6.90192L10.1815 7.44292C10.25 7.49272 10.3459 7.47752 10.3957 7.40898L11.3309 6.12181C11.3922 6.03749 11.5179 6.03749 11.5791 6.12181L12.5143 7.40904C12.5641 7.47758 12.6601 7.49278 12.7286 7.44298L13.4732 6.90198C13.5418 6.85218 13.557 6.75625 13.5072 6.68771L12.5723 5.40091C12.511 5.3166 12.5499 5.19705 12.649 5.16485L14.1615 4.67338C14.2421 4.6472 14.2862 4.56066 14.26 4.48009L13.9756 3.60473C13.9494 3.52415 13.8629 3.48006 13.7823 3.50624L12.2694 3.99782C12.1703 4.03003 12.0686 3.95615 12.0686 3.85193V2.26107Z`,fill:`currentColor`})]}),kTi={agent:PN,workflow:GS,tool:HN},ATi={agents:`agent`,workflows:`workflow`,tools:`tool`};function jTi({entity:e}){let t=kTi[e];return(0,K.jsx)(Ekn,{icon:(0,K.jsx)(t,{className:`size-3`})})}function MTi({provider:e}){return e?(0,K.jsx)(Dkn,{provider:e}):(0,K.jsx)(Ekn,{icon:(0,K.jsx)(OTi,{className:`size-icon-xs`})})}function NTi({tab:e,row:t}){let n=ATi[e];return n?(0,K.jsx)(jTi,{entity:n}):e===`models`?(0,K.jsx)(MTi,{provider:t.provider}):null}function PTi({tab:e,row:t}){let{projectLabel:n}=xwi();return(0,K.jsx)(DTi,{mark:(0,K.jsx)(NTi,{tab:e,row:t}),title:hTi(e,t,n),model:e===`models`&&t.name!==``?{name:t.name,provider:t.provider}:void 0})}function FTi({text:e}){return(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`muted`,className:`truncate`,title:e,children:e})}var ITi={asc:eH,desc:$V},LTi=`focus-visible:outline-1 focus-visible:outline-solid focus-visible:outline-border-focus focus-visible:-outline-offset-1`,RTi=`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 zTi({header:e,explained:t,sorted:n,className:r,...i}){let a=n&&ITi[n];return(0,K.jsxs)(`button`,{type:`button`,...i,className:c(`group/header flex items-center gap-1 rounded whitespace-nowrap hover:text-muted-foreground`,LTi,r),children:[(0,K.jsx)(`span`,{className:c(t&&RTi),children:e}),a&&(0,K.jsx)(a,{"aria-hidden":!0,className:`size-3`})]})}function BTi({header:e,explained:t,className:n,...r}){return(0,K.jsx)(`span`,{tabIndex:t?0:void 0,...r,className:c(`group/header rounded whitespace-nowrap`,LTi,n),children:(0,K.jsx)(`span`,{className:c(t&&RTi),children:e})})}function VTi({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)(zTi,{header:e,explained:a,sorted:n,onClick:r,"aria-describedby":o}):(0,K.jsx)(BTi,{header:e,explained:a,"aria-describedby":o});return a?(0,K.jsxs)(_x,{children:[(0,K.jsx)(vx,{render:s}),(0,K.jsx)(yx,{id:i,keepMounted:!0,side:`top`,className:`max-w-72`,children:t})]}):s}var HTi=`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)]`,UTi=`pt-1.75 pb-2 text-body-sm`,WTi=c(`relative col-span-full grid grid-cols-subgrid items-center px-3`,UTi,HTi),GTi=[`w-32`,`w-24`,`w-36`,`w-20`,`w-28`],KTi=`a, button, input, select, textarea, label, [role="button"], [role="link"], [contenteditable]`;function qTi(e){if(!(e.target instanceof Element))return!1;let t=e.target.closest(KTi);return!!(t&&e.currentTarget.contains(t))}function JTi(e,t,n){return e.align===`end`?`right-0 w-10`:t>0?`left-0 w-16`:c(`left-0`,GTi[n%GTi.length])}function YTi({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)(ZTi,{columns:e,rowIndex:n},n)):t.length===0?i?r===void 0?(0,K.jsx)(XTi,{count:i}):(0,K.jsxs)(`div`,{role:`row`,className:`col-span-full grid *:col-start-1 *:row-start-1`,children:[(0,K.jsx)(XTi,{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)(QTi,{row:t,columns:e,...o},n(t)))}function XTi({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:UTi,children:``},t))})}function ZTi({columns:e,rowIndex:t}){return(0,K.jsx)(`div`,{role:`row`,"aria-busy":!0,className:WTi,children:e.map((e,n)=>(0,K.jsxs)(`div`,{role:`cell`,className:c(`relative flex min-w-0`,e.align===`end`&&`justify-end`),children:[``,(0,K.jsx)(NS,{className:c(`absolute top-1/2 h-3.5 -translate-y-1/2`,JTi(e,n,t))})]},e.id))})}function QTi({row:e,columns:t,onRowClick:n,onRowHover:r,isRowDimmed:i,isRowActive:a,rowTitle:o}){let s=a?.(e)??!1,l=i?.(e)??!1;return(0,K.jsx)(`div`,{role:`row`,"aria-current":s||void 0,tabIndex:n?0:void 0,title:o?.(e),onClick:n?t=>{qTi(t)||n?.(e)}:void 0,onKeyDown:n?t=>{t.target===t.currentTarget&&(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),n?.(e))}:void 0,onMouseEnter:r?()=>r(e):void 0,onMouseLeave:r?()=>r(void 0):void 0,className:c(WTi,`rounded text-foreground transition-opacity duration-150`,n&&c(`cursor-pointer`,`focus-visible:outline-1 focus-visible:outline-solid focus-visible:outline-border-focus focus-visible:-outline-offset-1`),s&&`before:bg-fill-subtle`,l&&`opacity-40`),children:t.map(t=>(0,K.jsx)(`div`,{role:`cell`,className:c(`flex min-w-0 items-center`,t.align===`end`&&`justify-end text-right`),children:t.cell(e)},t.id))})}var $Ti=`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)]`,eEi={asc:`ascending`,desc:`descending`};function tEi(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 nEi(e,t){return typeof e==`number`&&typeof t==`number`?e-t:String(e).localeCompare(String(t))}function rEi(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*nEi(n,a)})}var iEi=e=>e.width??(e.align===`end`?`minmax(max-content,1fr)`:`max-content`);function aEi({columns:e,rows:t,getRowKey:n,sort:r,defaultSort:i,onSortChange:a,onRowClick:o,onRowHover:s,isRowDimmed:l,isRowActive:u,rowTitle:d,empty:f,pageSize:p,isLoading:m=!1,"aria-label":h,className:g}){let[_,v]=(0,G.useState)(i),[y,b]=(0,G.useState)(0),x=r??_,S=rEi(t,e,x),C=p?Math.ceil(S.length/p):1,w=Math.min(y,Math.max(0,C-1)),T=p?S.slice(w*p,(w+1)*p):S,E={gridTemplateColumns:e.map(iEi).join(` `)},D=!m&&C>1,O=e=>{let t=tEi(x,e)??i;v(t),b(0),a?.(t)};return(0,K.jsxs)(`div`,{className:c(`grid min-w-0 gap-3`,g),children:[(0,K.jsxs)(jS,{orientation:`horizontal`,children:[(0,K.jsxs)(`div`,{role:`table`,"aria-label":h,className:`grid min-w-min gap-x-4`,style:E,children:[(0,K.jsx)(`div`,{role:`row`,className:c(`relative col-span-full grid grid-cols-subgrid items-end px-3 pb-1.5 text-label text-placeholder`,$Ti),children:e.map(e=>{let t=x?.column===e.id?x.direction:void 0;return(0,K.jsx)(`div`,{role:`columnheader`,"aria-sort":t&&eEi[t],className:c(`flex min-w-0 items-center gap-1`,e.align===`end`&&`justify-end text-right`),children:(0,K.jsx)(VTi,{header:e.header,description:e.description,sorted:t,onSort:e.sortValue?()=>O(e):void 0})},e.id)})}),(0,K.jsx)(YTi,{columns:e,rows:T,getRowKey:n,onRowClick:o,onRowHover:s,isRowDimmed:l,isRowActive:u,rowTitle:d,empty:f,pageSize:p,isLoading:m})]}),p!==void 0&&!m&&T.length>0&&(0,K.jsx)(XTi,{count:p-T.length})]}),D&&(0,K.jsx)(hdi,{page:w,pageCount:C,onPageChange:b})]})}var oEi=10,sEi={column:`count`,direction:`desc`},cEi={projects:`Project`,agents:`Agent`,workflows:`Workflow`,tools:`Tool`,models:`Model`,threads:`Thread`,environments:`Environment`},lEi={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 uEi({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=xwi(),[p,m]=(0,G.useState)(sEi),[h,g]=(0,G.useState)(`count`),_=(e=sEi)=>{m(e),rTi(e.column)&&g(e.column)},v=[r,i,a].filter(e=>e!==void 0);if(v.some(e=>e.isError))return(0,K.jsx)(Awi,{...d,tab:e,children:(0,K.jsx)(r9,{onRetry:()=>v.forEach(e=>e.isError&&void e.refetch())})});let y=v.some(e=>e.isLoading),b=Fwi(e),x=i!==void 0,S=fTi(e,d.byProject),C=r?.data?.truncated===!0,w=y?[]:Jwi({tab:e,groupBy:t,aggregateRows:r?.data?.rows,usageGroups:i?.data?.groups,spanGroups:a?.data?.groups,resources:o?.data?Uwi(o.data.rows):void 0}),E=[s,c,l].every(e=>!e||!e.isLoading&&!e.isError)&&!y?Ywi({tab:e,groupBy:t,aggregateRows:s?.data?.rows,usageGroups:c?.data?.groups,spanGroups:l?.data?.groups}):void 0,D=mTi({tab:e,built:w,previous:E,truncated:C,groupBy:t,usage:x}),O=iTi(e),k=e=>E?Zwi(e,E.get(e.key),h):void 0,A=e=>e.projectId?f.projectLabel?.(e.projectId)??e.projectId:`—`,j={id:`name`,header:cEi[e],width:`minmax(12rem,3fr)`,cell:t=>(0,K.jsx)(PTi,{tab:e,row:t})},M={id:`project`,header:`Project`,width:`minmax(8rem,2fr)`,cell:e=>(0,K.jsx)(FTi,{text:A(e)})},N={id:`resource`,header:`Resource`,width:`minmax(6rem,1fr)`,cell:e=>(0,K.jsx)(FTi,{text:e.resource??`—`})},P=[{id:`errorRate`,header:`Errors`,align:`end`,sortValue:e=>e.errorRate,cell:e=>(0,K.jsx)(h9,{muted:!0,children:e.errorRate===void 0?`—`:p5(e.errorRate)})},{id:`p95`,header:`P95 latency`,align:`end`,sortValue:e=>e.p95,cell:e=>(0,K.jsx)(h9,{muted:!0,children:e.p95===void 0?`—`:k8r(e.p95)})}],F=[{id:`tokens`,header:`Tokens`,align:`end`,sortValue:e=>e.tokens,cell:e=>(0,K.jsx)(h9,{muted:!0,children:e.tokens===void 0?`—`:f5(e.tokens)})},{id:`cost`,header:`Cost`,align:`end`,sortValue:e=>e.cost,cell:e=>(0,K.jsx)(h9,{muted:!0,children:(0,K.jsx)(ETi,{row:e})})}],I={id:`count`,header:O,align:`end`,description:sTi(e),sortValue:e=>e.count,cell:e=>(0,K.jsx)(h9,{children:f5(e.count)})},L={id:`change`,header:`% Change`,align:`end`,description:(0,K.jsx)(wTi,{window:n,label:pTi(e,h)}),sortValue:e=>k(e)?.change,cell:e=>(0,K.jsx)(h9,{children:(0,K.jsx)(CTi,{change:k(e),metric:h})})},R=[j,...S?[M]:[],...e===`threads`?[N]:[],...b?P:[],...x?F:[],I,L];return(0,K.jsx)(Awi,{...d,tab:e,isUpdating:r?.isPlaceholderData,children:(0,K.jsxs)(t9,{children:[(0,K.jsx)(aEi,{"aria-label":`${cEi[e]} breakdown`,columns:R,rows:D,getRowKey:e=>e.key,sort:p,defaultSort:sEi,onSortChange:_,onRowClick:d.onRowClick&&(t=>d.onRowClick?.(_Ti(e,t))),pageSize:oEi,isLoading:y,empty:lEi[e]},e),!y&&C&&(0,K.jsxs)(T,{variant:`caption`,tone:`muted`,className:`pt-2`,children:[`Showing the `,f5(u),` busiest; sorting covers only these.`]})]})})}var dEi={entityType:`agent`};function fEi({tab:e,scope:t,...n}){let r=d9(e,n.byProject),i=Pwi(e),a=bTi(t),o=Dwi(Gwi(e,t,n.byProject)),s=Dwi(Gwi(e,a,n.byProject),{priority:Cxi.last}),c=m9({groupBy:r,filters:dEi,window:t.window,enabled:i}),l=m9({groupBy:r,filters:dEi,window:a.window,enabled:i});return(0,K.jsx)(uEi,{...n,tab:e,groupBy:r,window:t.window,aggregate:o,totals:i?c:void 0,previousAggregate:s,previousUsage:i?l:void 0,limit:f9.span})}function pEi(e){let t=d9(`models`,e.byProject),{timestamp:n}=c9(),r=tTi(n),i=m9({groupBy:t,window:n}),a=m9({groupBy:t,window:n,measure:`modelSpans`}),o=m9({groupBy:t,window:r}),s=m9({groupBy:t,window:r,measure:`modelSpans`});return(0,K.jsx)(uEi,{...e,tab:`models`,groupBy:t,window:n,totals:i,spans:a,previousUsage:o,previousSpans:s,limit:f9.trace})}function mEi({tab:e,scope:t,...n}){let r=d9(e,n.byProject),i=bTi(t),a=u9(Vwi(e,t,n.byProject)),o=u9(Vwi(e,i,n.byProject),{priority:Cxi.last}),s=u9(Hwi(t),{enabled:e===`threads`&&n.byProject}),c=m9({groupBy:r,window:t.window}),l=n.byProject?s:a,u=m9({groupBy:r,window:i.window});return(0,K.jsx)(uEi,{...n,tab:e,groupBy:r,window:t.window,aggregate:a,totals:c,resources:e===`threads`?l:void 0,previousAggregate:o,previousUsage:u,limit:f9.trace})}var hEi={serviceName:`service`,requestId:`request ID`,experimentId:`experiment`,tags:`tags`,provider:`provider`,model:`model`};function gEi({tab:e,traceGate:t,spanGate:n,...r}){if(e===`models`)return(0,K.jsx)(pEi,{...r},e);let i=Mwi(e)?n:t;return i.status===`unsupported-filter`?(0,K.jsx)(Awi,{...r,tab:e,children:(0,K.jsx)(e9.NoData,{message:`Not available with a ${i.unsupportedFields.map(e=>hEi[e]??e).join(` or `)} filter.`})}):Mwi(e)?n.status===`ready`&&(0,K.jsx)(fEi,{...r,tab:e,scope:n.scope},e):t.status===`ready`&&(0,K.jsx)(mEi,{...r,tab:e,scope:t.scope},e)}function _Ei({chosen:e,traceScope:t,spanGate:n,...r}){let i=u9(Lwi(t)).data?.rows.filter(e=>(e.measures.count??0)>0).length,a=e??vEi(i);return(0,K.jsx)(gEi,{...r,tab:a,traceGate:{status:`ready`,scope:t},spanGate:n})}function vEi(e){return e===void 0||e>=2?`projects`:`agents`}var yEi=[`projects`,`agents`,`workflows`,`tools`,`models`,`threads`,`environments`],bEi=yEi.filter(e=>e!==`projects`);function xEi({onRowClick:e}){let t=xwi().projectLabel!==void 0,n=fwi(),r=Ewi(),[i,a]=(0,G.useState)();if(n.status===`unavailable`||r.status===`unavailable`)return null;if(n.status===`loading`||r.status===`loading`)return(0,K.jsx)(n9,{title:Owi,bodyHeight:`fit`,children:(0,K.jsx)(e9.Loading,{})});let o={tabs:t?yEi:bEi,onTabChange:a,onRowClick:e,byProject:t};return t&&n.status===`ready`?(0,K.jsx)(_Ei,{...o,chosen:i,traceScope:n.scope,spanGate:r}):(0,K.jsx)(gEi,{...o,tab:i??`agents`,traceGate:n,spanGate:r})}function SEi({experiment:e,metrics:t}){let{data:n}=CN({experimentId:e.id,experimentStatus:e.status,queryOptions:{enabled:!!e.id}}),{data:r,isLoading:i}=a_i({experiments:(0,G.useMemo)(()=>[{id:e.id,status:e.status}],[e.id,e.status]),supportsMetrics:t?.isEnabled??!1}),a=e.status===`running`||e.status===`pending`||i,o=(0,G.useMemo)(()=>{if(!n)return;let e=Object.values(n).flat();return e.length===0?null:e.reduce((e,t)=>e+t.score,0)/e.length},[n]),s=e.startedAt??e.createdAt,c=!e.startedAt||!e.completedAt?`—`:QS(new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime())??`—`,l=r[e.id]?.summary,u=H7(l),d=l?.inputTokens===void 0&&l?.outputTokens===void 0?`input + output`:(0,K.jsxs)(wC,{singleLine:!0,children:[(0,K.jsxs)(wC.Item,{children:[V7(l.inputTokens??0),` in`]}),(0,K.jsxs)(wC.Item,{children:[V7(l.outputTokens??0),` out`]})]}),f=t?.isEnabled?t.data?.avgAgentDurationMs:void 0,p=f==null?void 0:QS(Math.round(f)),m=p?`${p} avg per item`:s?`started ${mC(new Date(s),`date-time`)}`:`not started`;return(0,K.jsxs)(Qbi,{children:[t?.isEnabled&&(0,K.jsx)(CSi,{label:`Total cost`,icon:Fyi,value:l?.estimatedCost===void 0?`—`:B7(l.estimatedCost,l.costUnit),detail:`estimated`,isLoading:a}),(0,K.jsx)(CSi,{label:`Run duration`,icon:WS,value:c,detail:m}),t?.isEnabled&&(0,K.jsx)(CSi,{label:`Total tokens`,icon:Z4,value:u===void 0?`—`:V7(u),detail:d,isLoading:a}),(0,K.jsx)(CSi,{label:`Avg score`,icon:G4,value:o==null?`—`:o.toFixed(3),detail:o==null?`no scores`:`across all scorers`,isLoading:o===void 0})]})}function CEi({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)(hw,{}),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)(FN,{}),children:`Request review`}),(0,K.jsx)(Ibi,{selectedResults:n,vocabulary:r,onAddTag:e.addTagToSelected,disabled:o})]})]})}var wEi=e=>Math.floor(Math.random()*e);function TEi({messages:e,intervalMs:t=3e3}){let n=e.length,[r,i]=(0,G.useState)(()=>wEi(n));return(0,G.useEffect)(()=>{if(n<2)return;let e=setInterval(()=>i(e=>(e+1+wEi(n-1))%n),t);return()=>clearInterval(e)},[n,t]),n===0?null:(0,K.jsx)(K.Fragment,{children:e[r%n]})}function EEi(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 DEi=[`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…`],OEi=`Waiting to start…`;function kEi({experiment:e}){let{status:t,totalItems:n,succeededCount:r,failedCount:i,startedAt:a}=e,o=EEi(),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?QS(u):void 0;return(0,K.jsx)(Hx,{variant:`fill`,as:`h2`,iconSlot:(0,K.jsx)(It,{}),titleSlot:l?`Experiment queued`:`Experiment in progress`,descriptionSlot:(0,K.jsxs)(`span`,{className:`flex flex-col items-center gap-1`,children:[(0,K.jsx)(`span`,{children:l?OEi:(0,K.jsx)(TEi,{messages:DEi})}),(0,K.jsxs)(wC,{className:`justify-center tabular-nums`,children:[(0,K.jsxs)(wC.Item,{children:[s,` / `,n,` `,c,` finished`]}),d&&(0,K.jsxs)(wC.Item,{children:[d,` elapsed`]})]})]})})}var AEi={pending:{icon:(0,K.jsx)(YS,{className:`size-icon-md text-warning-foreground`}),label:K7.pending},running:{icon:(0,K.jsx)(It,{size:`sm`}),label:K7.running},completed:{icon:(0,K.jsx)(bX,{className:`size-icon-md text-muted-foreground`}),label:K7.completed},failed:{icon:(0,K.jsx)(Vx,{className:`size-icon-md text-destructive-foreground`}),label:K7.failed}};function jEi({status:e,className:t}){let n=AEi[e]??AEi.pending;return(0,K.jsxs)(_x,{children:[(0,K.jsx)(vx,{render:(0,K.jsx)(`span`,{tabIndex:0,className:c(`flex shrink-0 items-center`,t),children:n.icon})}),(0,K.jsx)(yx,{children:n.label})]})}var MEi=()=>{let{experimentId:e}=Ev(),{data:t}=ljt({experimentId:e??``,queryOptions:{enabled:!!e,retryOnMount:!1}});return{experimentId:e,experiment:t}},NEi=()=>{let{experimentId:e,experiment:t}=MEi(),n=t?.datasetId??``,{data:r}=$At({datasetId:n,experimentId:e??``,queryOptions:{enabled:!!(n&&e),retryOnMount:!1}});return r??t};function PEi(){let{experimentId:e,experiment:t}=MEi();if(!e)return null;let n=e.length>8?`${e.slice(0,8)}...`:e;return t?.name||n}function FEi(){let e=NEi();return e?.status?(0,K.jsx)(jEi,{status:e.status}):null}function IEi(){let e=NEi();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)(wC,{children:[(0,K.jsx)(wC.Item,{children:r}),n>0&&(0,K.jsxs)(wC.Item,{children:[n,` errored`]})]})})}function LEi({datasetId:e,experimentId:t}){let[n,r]=(0,G.useState)(!1),{updateExperimentResult:i}=bN();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?Qx(`Tag "${a}" added to ${c} result${c>1?`s`:``}`):Qx.error(`Failed to add tag`)},[e,t,n,i]),isPending:n}}function REi(e,t){let{data:n}=SN({datasetId:e,queryOptions:{enabled:!!e}});return(0,G.useMemo)(()=>[...new Set([...n?.tags??[],...t.flatMap(e=>e.tags??[])])].sort(),[n?.tags,t])}function zEi({datasetId:e,experimentId:t,results:n}){let[r,i]=(0,G.useState)(new Set),[a,o]=(0,G.useState)(!1),{updateExperimentResult:s}=bN(),{addTag:c,isPending:l}=LEi({datasetId:e,experimentId:t}),u=REi(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}),Qx(`${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 BEi=[];function VEi({crumbs:e,children:t}){return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{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 HEi(){let{experimentId:e}=Ev(),t=[KN(`/experiments`),{id:`experiment`,Component:PEi,icon:FEi,Action:IEi}],n=Tv(),[r,i]=(0,G.useState)(!1),a=h7(),{data:o,isLoading:s,error:c}=ljt({experimentId:e??``,queryOptions:{enabled:!!e}}),l=o?.datasetId??``,{data:u,isLoading:d,error:f}=$At({datasetId:l,experimentId:e??``,queryOptions:{enabled:!!l&&!!e}}),p=u?.status===`completed`||u?.status===`failed`,{data:m,isLoading:h,setEndOfListElement:g,isFetchingNextPage:_,hasNextPage:v}=tjt({datasetId:l,experimentId:e??``,experimentStatus:u?.status,queryOptions:{enabled:!!l&&!!e&&p}}),{supportsMetrics:y}=S7(),b=o_i({experimentId:e,experimentStatus:u?.status,supportsMetrics:y,queryOptions:{enabled:!!e&&y&&p}}),x=zEi({datasetId:l,experimentId:e??``,results:m??BEi}),S=c??f;if(!e||s||d)return null;if(S&&DN(S))return(0,K.jsx)(VEi,{crumbs:t,children:(0,K.jsx)(_H,{})});if(S&&ON(S))return(0,K.jsx)(VEi,{crumbs:t,children:(0,K.jsx)(gH,{resource:`datasets`})});let C=(0,K.jsx)(VEi,{crumbs:t,children:(0,K.jsx)(Hx,{titleSlot:`Experiment not found`,descriptionSlot:`No experiment with id "${e}".`,actionSlot:(0,K.jsx)(X,{render:(0,K.jsx)(jv,{to:`/experiments`}),icon:(0,K.jsx)(tS,{}),children:`Back to experiments`})})});return S&&kN(S)?C:S?(0,K.jsx)(VEi,{crumbs:t,children:(0,K.jsx)(Hx,{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)(v_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)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:t}),headerActions:(0,K.jsx)(Mbi,{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)(SEi,{experiment:u,metrics:b}),(0,K.jsxs)(`div`,{className:`grid content-start gap-1`,children:[(0,K.jsx)(CEi,{selection:x}),(0,K.jsx)(V_i,{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)(kEi,{experiment:u})]}),(0,K.jsx)(Zbi,{withFeedback:a.enabled}),(0,K.jsx)(jvi,{open:r,onOpenChange:i,experimentId:e,experimentName:u.name??void 0,onSuccess:()=>n(`/experiments`)})]})})}function UEi({tag:e,onRename:t,onRemove:n}){let[r,i]=(0,G.useState)(!1),[a,o]=(0,G.useState)(e),s=(0,G.useRef)(null);(0,G.useEffect)(()=>{r&&(s.current?.focus(),s.current?.select())},[r]);let l=()=>{let n=a.trim();n&&n!==e&&t(n),i(!1)};return r?(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 rounded-md border border-border bg-card px-1`,children:[(0,K.jsx)(Hj,{variant:`unstyled`,ref:s,value:a,onChange:e=>o(e.target.value),onKeyDown:t=>{t.key===`Enter`&&(t.preventDefault(),l()),t.key===`Escape`&&(o(e),i(!1))},onBlur:l,className:`h-auto w-20 bg-transparent px-0 py-0.5 text-caption text-muted-foreground outline-hidden`}),(0,K.jsx)(`button`,{type:`button`,onMouseDown:e=>{e.preventDefault(),l()},className:c(gS,`p-0.5`),children:(0,K.jsx)(sC,{className:`size-icon-xs`})})]}):(0,K.jsxs)(`span`,{className:`group inline-flex items-center gap-0.5 rounded-md border border-border bg-card px-1.5 py-0.5 text-muted-foreground`,children:[(0,K.jsx)(T,{as:`span`,variant:`caption`,children:e}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>{o(e),i(!0)},className:c(gS,`p-0.5 opacity-0 transition-opacity group-hover:opacity-100`),title:`Edit tag`,children:(0,K.jsx)(XV,{className:`size-icon-xs`})}),(0,K.jsx)(`button`,{type:`button`,onClick:n,className:`p-0.5 text-placeholder opacity-0 transition-opacity group-hover:opacity-100 hover:text-destructive-foreground`,title:`Remove tag`,children:(0,K.jsx)(hw,{className:`size-icon-xs`})})]})}function WEi({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)(Wj,{open:o,onOpenChange:s,children:[(0,K.jsx)(Gj,{asChild:!0,children:(0,K.jsxs)(X,{size:a,icon:(0,K.jsx)(vX,{}),children:[`Tag `,e,` items`]})}),(0,K.jsxs)(Kj,{className:`w-56 p-2`,align:`end`,children:[(0,K.jsx)(Hj,{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)(hw,{className:`size-icon-xs`})})]},e)),d&&(0,K.jsx)(`button`,{type:`button`,onClick:()=>{i(c.trim()),l(``)},className:`w-full rounded px-2 py-1 text-left text-info-indicator hover:bg-fill-subtle`,children:(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[`Create & apply "`,c.trim(),`"`]})})]})]})]})}var GEi=[{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`}],KEi=`__untagged__`,qEi=`all`,JEi=[{value:`review`,label:`Review queue`},{value:`completed`,label:`Completed`}];function YEi({datasetId:e,experimentId:t,experiments:n,isLoadingExperiments:r,targetType:i,targetId:a,featuredItemId:o,toolbarStart:s,renderFilters:l,toolbarEnd:u,onCreateScorer:d,breadcrumbs:f,withFeedback:p}){let m=Y(),{paths:h}=sn(),{data:g}=SN({datasetId:e??``,queryOptions:{enabled:!!e}}),_=Dvi({experimentId:t,targetType:i,targetId:a,experiments:n,isLoadingExperiments:r}),v=Ovi({experimentId:t,targetType:i,targetId:a,experiments:n,isLoadingExperiments:r}),{data:y,isLoading:b}=_,{data:x,isLoading:S}=v,{updateExperimentResult:C}=bN(),[w,E]=(0,G.useState)(o??null);(0,G.useEffect)(()=>{o!==void 0&&E(o)},[o]);let[D,O]=(0,G.useState)(null),[k,A]=(0,G.useState)(new Set),[j,M]=(0,G.useState)(!1),[N,P]=(0,G.useState)(!1),[F,I]=(0,G.useState)(!1),[L,R]=(0,G.useState)(``),[z,B]=(0,G.useState)(``),[V,H]=(0,G.useState)(``),[ee,te]=(0,G.useState)([]),[U,W]=(0,G.useState)(!1),ne=(0,G.useMemo)(()=>y??[],[y]),re=(0,G.useMemo)(()=>{let e=new Set;if(g?.tags)for(let t of g.tags)e.add(t);for(let t of ne)for(let n of t.tags)e.add(n);return[...e].sort()},[g,ne]),ie=(0,G.useMemo)(()=>D?D===KEi?ne.filter(e=>e.tags.length===0):ne.filter(e=>e.tags.includes(D)):ne,[ne,D]),ae=(0,G.useMemo)(()=>{let e=new Map,t=0;for(let n of ne){n.tags.length===0&&t++;for(let t of n.tags)e.set(t,(e.get(t)??0)+1)}let n=[...e.entries()].sort((e,t)=>t[1]-e[1]).map(([e])=>({value:e,label:e}));return[{value:qEi,label:`All tags`},...t>0?[{value:KEi,label:`Untagged`}]:[],...n]},[ne]),oe=!!D||j,se=(0,G.useCallback)(()=>{O(null),M(!1),E(null)},[]),ce=(0,G.useCallback)((e,t)=>{let n=ne.find(t=>t.id===e);n?.experimentId&&n?.datasetId&&C.mutate({datasetId:n.datasetId,experimentId:n.experimentId,resultId:n.id,tags:t})},[ne,C]),le=(0,G.useCallback)(e=>{let t=ne.find(t=>t.id===e);A(t=>{let n=new Set(t);return n.delete(e),n}),w===e&&E(null),t?.experimentId&&t?.datasetId&&C.mutate({datasetId:t.datasetId,experimentId:t.experimentId,resultId:t.id,status:null})},[ne,C,w]),ue=(0,G.useCallback)(e=>{let t=ne.find(t=>t.id===e);A(t=>{let n=new Set(t);return n.delete(e),n}),w===e&&E(null),t?.experimentId&&t?.datasetId&&C.mutate({datasetId:t.datasetId,experimentId:t.experimentId,resultId:t.id,status:`complete`})},[ne,C,w]),de=(0,G.useMemo)(()=>{let e=j?x??[]:ie;return!j||!D?e:D===KEi?e.filter(e=>e.tags.length===0):e.filter(e=>e.tags.includes(D))},[j,x,ie,D]),fe=j?S:!1,pe=(0,G.useMemo)(()=>new Set(de.map(e=>e.id)),[de]),me=(0,G.useMemo)(()=>[...k].filter(e=>pe.has(e)).length,[k,pe]),he=de.length>0&&me===de.length,ge=(0,G.useCallback)(e=>{A(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),_e=(0,G.useCallback)(()=>{A(he?new Set:new Set(de.map(e=>e.id)))},[he,de]),ve=(0,G.useCallback)(e=>{for(let t of k){let n=ne.find(e=>e.id===t);n&&!n.tags.includes(e)&&ce(t,[...n.tags,e])}},[ne,k,ce]),ye=(0,G.useCallback)(e=>{for(let t of k){let n=ne.find(e=>e.id===t);n&&n.tags.includes(e)&&ce(t,n.tags.filter(t=>t!==e))}},[ne,k,ce]),be=(0,G.useCallback)(()=>{for(let e of k)ue(e);A(new Set)},[k,ue]),xe=(0,G.useCallback)(()=>{for(let e of k)le(e);A(new Set)},[k,le]),Se=(0,G.useCallback)(()=>{R(``),I(!0)},[]),Ce=(0,G.useCallback)(async()=>{if(z&&V){P(!0),I(!1);try{let e=ne.filter(e=>k.has(e.id));if(e.length===0){P(!1);return}let t=await m.clusterFailures({modelId:`${z}/${V}`,items:e.map(e=>({id:e.id,input:e.input,output:e.output??void 0,error:typeof e.error==`string`?e.error:e.error?String(e.error):void 0,scores:e.scores,existingTags:e.tags.length>0?e.tags:void 0})),availableTags:re.length>0?re:void 0,prompt:L||void 0});t.proposedTags&&t.proposedTags.length>0&&(te(t.proposedTags.map(e=>({...e,accepted:!0}))),W(!0))}catch(e){console.error(`Analysis failed:`,e)}finally{P(!1)}}},[z,V,ne,k,m,re,L]),we=(0,G.useCallback)(()=>{for(let e of ee){if(!e.accepted)continue;let t=ne.find(t=>t.id===e.itemId);if(t){let n=[...new Set([...t.tags,...e.tags])];ce(t.id,n)}}W(!1)},[ee,ne,ce]),Te=(0,G.useCallback)(e=>{E(t=>t===e?null:e)},[]),Ee=(0,G.useMemo)(()=>w?de.find(e=>e.id===w)??null:null,[w,de]),{data:De}=CN({experimentId:Ee?.experimentId??``,queryOptions:{enabled:!!Ee?.experimentId}}),Oe=j?v:_,ke=de.length===0||!(!w||Ee);(0,G.useEffect)(()=>{ke&&Oe.hasNextPage&&!Oe.isFetching&&Oe.fetchNextPage({cancelRefetch:!1})},[ke,Oe]);let Ae=w?de.findIndex(e=>e.id===w):-1,je=Ae>0?()=>E(de[Ae-1].id):void 0,Me=Ae>=0&&Ae<de.length-1?()=>E(de[Ae+1].id):void 0,Ne=!j&&k.size>0,Pe=!!d&&!j&&ie.length>0,Fe=j?`completed`:`review`,Ie=e=>{M(e===`completed`),E(null)},Le=(0,K.jsxs)(_K,{children:[(0,K.jsx)(_K.Start,{children:l?(0,K.jsxs)(K.Fragment,{children:[s,l({status:Fe,onStatusChange:Ie,tag:D,onTagChange:O,tagOptions:ae.filter(e=>e.value!==qEi)})]}):(0,K.jsxs)(K.Fragment,{children:[s,(0,K.jsxs)(Pk,{value:Fe,onValueChange:e=>Ie(e===`completed`?`completed`:`review`),children:[(0,K.jsx)(Ik,{"aria-label":`Status`,size:`md`,className:`whitespace-nowrap`,children:(0,K.jsx)(Fk,{placeholder:`Select an option`})}),(0,K.jsx)(Lk,{children:JEi.map(e=>(0,K.jsx)(Rk,{value:e.value,children:e.label},e.value))})]}),ae.length>1&&(0,K.jsxs)(Pk,{value:D??qEi,onValueChange:e=>O(e===qEi?null:e),children:[(0,K.jsx)(Ik,{"aria-label":`Tags`,size:`md`,className:`whitespace-nowrap`,children:(0,K.jsx)(Fk,{placeholder:`Select an option`})}),(0,K.jsx)(Lk,{children:ae.map(e=>(0,K.jsx)(Rk,{value:e.value,children:e.label},e.value))})]}),oe&&(0,K.jsx)(X,{onClick:se,size:`sm`,variant:`default`,icon:(0,K.jsx)(hw,{}),children:`Reset`})]})}),(Ne||u||Pe)&&(0,K.jsxs)(_K.End,{children:[u,Pe&&(0,K.jsxs)(X,{size:`md`,onClick:()=>d?.(ie.map(e=>({input:e.input,output:e.output}))),children:[(0,K.jsx)(xx,{size:`xs`,children:(0,K.jsx)(G4,{})}),`Create scorer`]}),Ne&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(WEi,{size:`md`,selectedCount:k.size,vocabulary:re,onApplyTag:ve,onRemoveTag:ye,onNewTag:e=>ve(e)}),(0,K.jsx)(X,{variant:`primary`,onClick:be,icon:(0,K.jsx)(bX,{}),children:`Mark as reviewed`}),(0,K.jsxs)(ZT,{children:[(0,K.jsx)(ZT.Trigger,{asChild:!0,children:(0,K.jsx)(X,{size:`icon-md`,disabled:N,"aria-label":`More actions`,children:N?(0,K.jsx)(It,{className:`h-4 w-4`}):(0,K.jsx)(tQ,{})})}),(0,K.jsxs)(ZT.Content,{align:`end`,children:[(0,K.jsxs)(ZT.Item,{onSelect:Se,children:[(0,K.jsx)(xx,{size:`xs`,children:(0,K.jsx)(xZ,{})}),`Analyze`]}),(0,K.jsx)(ZT.Separator,{}),(0,K.jsxs)(ZT.Item,{onSelect:xe,children:[(0,K.jsx)(xx,{size:`xs`,children:(0,K.jsx)(Bj,{})}),`Remove from queue`]})]})]})]})]})]});if(b)return(0,K.jsxs)(MS,{breadcrumbs:f,actionRow:Le,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(It,{fill:!0})]});let Re=(0,K.jsx)(Ybi,{withFeedback:p,result:Ee??void 0,title:`Review item ${Ee?.id??``}`,scores:Ee?De?.[Ee.itemId]:void 0,experimentLink:Ee?.experimentId?h.experimentItemLink(Ee.experimentId,Ee.itemId):void 0,onComplete:j||!Ee?void 0:()=>ue(Ee.id),onPrevious:je,onNext:Me,onClose:()=>E(null)});return(0,K.jsxs)(MS,{breadcrumbs:f,actionRow:Le,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(Xw,{open:F,onOpenChange:I,children:(0,K.jsxs)(Zw,{children:[(0,K.jsxs)(Qw,{children:[(0,K.jsx)(tT,{children:`Analyze Items`}),(0,K.jsx)(nT,{children:`Use an LLM to automatically suggest tags for the selected items.`})]}),(0,K.jsxs)(eT,{children:[(0,K.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[(0,K.jsxs)($O,{className:`gap-1`,children:[(0,K.jsx)(tk,{children:`Provider`}),(0,K.jsx)(wq,{value:z,onValueChange:B})]}),(0,K.jsxs)($O,{className:`gap-1`,children:[(0,K.jsx)(tk,{children:`Model`}),(0,K.jsx)(Tq,{llmId:z,value:V,onValueChange:H})]})]}),(0,K.jsxs)(T,{variant:`meta`,tone:`muted`,children:[k.size,` item`,k.size===1?``:`s`,` will be analyzed`]}),(0,K.jsxs)($O,{className:`gap-1`,children:[(0,K.jsx)(tk,{children:`Instructions (optional)`}),(0,K.jsx)(Vk,{className:`text-caption`,value:L,onChange:e=>R(e.target.value),placeholder:`E.g., Focus on safety issues and factual errors`,rows:3})]})]}),(0,K.jsxs)($w,{children:[(0,K.jsx)(rT,{children:`Cancel`}),(0,K.jsx)(Yw,{onConfirm:Ce,disabled:!z||!V||N,children:`Analyze`})]})]})}),(0,K.jsx)(Xw,{open:U,onOpenChange:W,children:(0,K.jsxs)(Zw,{size:`lg`,children:[(0,K.jsxs)(Qw,{children:[(0,K.jsx)(tT,{children:`Review Proposed Tags`}),(0,K.jsxs)(nT,{children:[ee.filter(e=>e.accepted).length,` of `,ee.length,` proposals selected`]})]}),(0,K.jsx)(eT,{children:ee.map((e,t)=>{let n=ne.find(t=>t.id===e.itemId);return(0,K.jsx)(`div`,{className:c(`rounded-lg border p-3`,!e.accepted&&`opacity-50`),children:(0,K.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,K.jsx)(Vj,{checked:e.accepted,onCheckedChange:e=>te(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)(UEi,{tag:e,onRename:e=>te(r=>r.map((r,i)=>i===t?{...r,tags:r.tags.map((t,r)=>r===n?e:t)}:r)),onRemove:()=>te(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)($w,{children:[(0,K.jsx)(rT,{children:`Cancel`}),(0,K.jsxs)(Yw,{onConfirm:we,disabled:ee.filter(e=>e.accepted).length===0,children:[`Accept `,ee.filter(e=>e.accepted).length,` proposals`]})]})]})}),(0,K.jsxs)(`div`,{className:`grid h-full min-h-0 w-full grid-cols-1 gap-4 overflow-hidden`,children:[(0,K.jsx)(`div`,{className:`min-h-0 w-full overflow-hidden`,children:fe||de.length===0&&Oe.hasNextPage?(0,K.jsx)(It,{fill:!0}):de.length===0?(0,K.jsx)(Hx,{titleSlot:j?`No completed reviews yet`:`No items to review`,descriptionSlot:j?`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)(I_i,{results:de,isLoading:!1,featuredResultId:w,onResultClick:Te,columns:GEi,selectedIds:j?void 0:k,onToggleSelect:j?void 0:ge,onToggleSelectAll:j?void 0:_e,setEndOfListElement:Oe.setEndOfListElement,hasNextPage:Oe.hasNextPage,isFetchingNextPage:Oe.isFetchingNextPage})}),Re]})]})}var XEi=`experiment`,ZEi=`status`,QEi=[{value:`review`,label:`Review queue`},{value:`completed`,label:`Completed`}],$Ei=[{id:`is`,label:`is`}],eDi=({targetType:e,targetId:t,experimentId:n,status:r,tag:i})=>{let a=_fi({targetType:e,targetId:t});return n&&a.push(T7(XEi,n)),r!==`review`&&a.push(T7(ZEi,r)),i&&a.push(T7(`tag`,i)),a},tDi=e=>({...vfi(e),experimentId:E7(e,XEi),status:E7(e,`status`)===`completed`?`completed`:`review`,tag:E7(e,`tag`)||null});function nDi({targetType:e,targetId:t,experimentId:n,status:r,tag:i,experiments:a,tagOptions:o,onChange:s}){let c=yfi(e),l=(0,G.useMemo)(()=>[...c,{id:XEi,label:`Experiment`,icon:LN,color:$N(`pink`),strict:!0,suggestions:a.map(e=>({value:e.id,label:Lvi(e)}))},{id:ZEi,label:`Status`,icon:bX,color:$N(`orange`),strict:!0,suggestions:QEi},{id:`tag`,label:`Tag`,icon:vX,color:$N(`pink`),strict:!0,hidden:o.length===0,suggestions:o}],[c,a,o]),u=(0,G.useMemo)(()=>eDi({targetType:e,targetId:t,experimentId:n,status:r,tag:i}),[e,t,n,r,i]);return(0,K.jsxs)(c5,{fields:l,operators:$Ei,value:u,onValueChange:e=>s(tDi(e)),createItemId:e=>e,"aria-label":`Review queue filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(c5.Chips,{}),(0,K.jsx)(c5.Input,{placeholder:`Filter review queue`})]})}var rDi=[KN(`/experiments`),KN(`/experiments/review-queue`)],iDi=`experiment`,aDi=`review`;function oDi(){let[e,t]=Mv(),n=e.get(O7),r=pfi(n)?n:``,i=r?e.get(`targetId`)??``:``,a=e.get(iDi),o=e.get(aDi),{Link:s,paths:c}=sn(),l=h7(),{data:u,error:d}=c_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(O7,e.targetType):n.delete(O7),s?n.set(k7,s):n.delete(k7),o?n.set(iDi,o):n.delete(iDi),n.delete(aDi),n},{replace:!0})};return d&&DN(d)?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:rDi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(_H,{variant:`fill`})]}):d&&ON(d)?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:rDi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(gH,{variant:`fill`,resource:`experiments`})]}):d?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:rDi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(Hx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load experiments`,descriptionSlot:d.message})]}):(0,K.jsx)(YEi,{withFeedback:l.enabled,breadcrumbs:(0,K.jsx)(uN,{crumbs:rDi}),datasetId:f?.datasetId??void 0,experimentId:a??void 0,targetType:r,targetId:i,featuredItemId:o,renderFilters:e=>(0,K.jsx)(nDi,{targetType:r,targetId:i,experimentId:a??``,status:e.status,tag:e.tag,experiments:u?.experiments??[],tagOptions:e.tagOptions,onChange:t=>p(t,e)}),toolbarEnd:a?(0,K.jsx)(X,{render:(0,K.jsx)(s,{href:c.experimentLink(a)}),icon:(0,K.jsx)(R4,{}),children:`See experiment`}):void 0})}function sDi({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)(wC,{children:[(0,K.jsx)(wC.Item,{children:(0,K.jsx)(T,{as:`span`,variant:`caption`,children:e.label??`(no label)`})}),(0,K.jsx)(wC.Item,{children:(0,K.jsx)(JS,{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 cDi({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return(0,K.jsx)(`ul`,{className:`space-y-1`,children:e.map(e=>(0,K.jsx)(sDi,{connection:e,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(e.connectionId)},e.connectionId))})}function lDi({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)(cDi,{connections:i,isAdmin:t,disconnectPending:n,onDisconnect:r})]},e))})}function uDi({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)(lDi,{groups:r,isAdmin:i,disconnectPending:s,onDisconnect:l}):(0,K.jsx)(cDi,{connections:n,isAdmin:i,disconnectPending:s,onDisconnect:l}),c?(0,K.jsx)(`p`,{className:`text-destructive-foreground`,children:String(c)}):null]})}function dDi({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)($O,{invalid:!!o,disabled:a,children:[(0,K.jsx)(tk,{children:`Provider`}),(0,K.jsxs)(Pk,{value:n,onValueChange:f,children:[(0,K.jsx)(Ik,{children:(0,K.jsx)(Fk,{placeholder:a?`Loading providers…`:`Select provider`})}),(0,K.jsx)(Lk,{children:e.map(e=>(0,K.jsx)(Rk,{value:e.id,children:`${e.displayName??e.name} (${e.id})`},e.id))})]}),(0,K.jsx)(rk,{children:o?String(o):void 0})]}),(0,K.jsxs)($O,{invalid:!!c,disabled:!n||s,children:[(0,K.jsx)(tk,{children:`Toolkit`}),(0,K.jsxs)(Pk,{value:r,onValueChange:p,children:[(0,K.jsx)(Ik,{children:(0,K.jsx)(Fk,{placeholder:s?`Loading toolkits…`:`Select toolkit`})}),(0,K.jsx)(Lk,{children:t.map(e=>(0,K.jsx)(Rk,{value:e.slug,children:`${e.name} (${e.slug})`},e.slug))})]}),(0,K.jsx)(rk,{children:c?String(c):void 0})]}),(0,K.jsxs)($O,{disabled:!n||!r,children:[(0,K.jsx)(tk,{children:`Label (optional)`}),(0,K.jsx)(Hj,{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)(gk,{variant:`destructive`,children:String(u)})}):null,d?(0,K.jsxs)(gk,{variant:`success`,children:[`Authorized: `,d.connectionId,` (status: `,d.status,`)`]}):null]})}var fDi=e=>e.authorId?.trim()||`shared`,pDi=(e,t)=>{if(!t||new Set(e.map(fDi)).size<=1)return null;let n=new Map;for(let t of e){let e=fDi(t);n.set(e,[...n.get(e)??[],t])}let r=Array.from(n.entries());return r.sort(([e],[t])=>e===`shared`?1:t===`shared`?-1:e.localeCompare(t)),r},mDi=[`*`,`tool-providers:*`,`tool-providers:admin`];function hDi(){let{data:e}=O_();return e?.permissions?.some(e=>mDi.includes(e))??!1}var gDi=[{id:`integrations`,label:`Integrations`}];function _Di(){let[e,t]=(0,G.useState)(``),[n,r]=(0,G.useState)(``),[i,a]=(0,G.useState)(``),o=Mq(),s=Pq({providerId:e||null,queryOptions:{enabled:!!e}}),c=WPn({providerId:e||null,toolkit:n||null}),l=HPn(),u=UPn(),d=hDi(),f=o.data?.providers??[],p=s.data?.data??[],m=(0,G.useMemo)(()=>c.data?.items??[],[c.data?.items]),h=(0,G.useMemo)(()=>pDi(m,d),[m,d]);return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:gDi}),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)(dDi,{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)(uDi,{providerId:e,toolkit:n,connections:m,groupedByAuthor:h,isAdmin:d,isLoading:c.isLoading,error:c.error,disconnectPending:u.isPending,disconnectError:u.error,onDisconnect:t=>{u.mutate({providerId:e,connectionId:t})}})]})]})}function g9(e,t){return e.position===t.position?e.id===t.id?0:e.id<t.id?-1:1:e.position<t.position?-1:1}function vDi(e){return!e.deletedAt&&!e.mergedInto}function yDi(e){let t=new Map;for(let n of e)vDi(n)&&!t.has(n.id)&&t.set(n.id,{page:n,children:[]});let n=[],r=new Map;for(let e of t.values()){let i=e.page.parentId?t.get(e.page.parentId):void 0;i&&i!==e?(i.children.push(e),r.set(e,i)):n.push(e)}let i=new Set,a=e=>{if(!i.has(e)){i.add(e);for(let t of e.children)a(t)}};n.forEach(a);let o=[...t.values()].filter(e=>!i.has(e));o.sort((e,t)=>g9(e.page,t.page));for(let e of o){if(i.has(e))continue;let t=[],o=e;for(;o&&!t.includes(o);)t.push(o),o=r.get(o);let s=(o?t.slice(t.indexOf(o)):[e]).reduce((e,t)=>g9(t.page,e.page)<0?t:e),c=r.get(s);c&&c.children.splice(c.children.indexOf(s),1),n.push(s),a(s)}let s=e=>{e.sort((e,t)=>g9(e.page,t.page));for(let t of e)s(t.children)};return s(n),n}function bDi(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 xDi(e,t){let n=new Map(e.map(e=>[e.id,e])),r=[],i=new Set([t]),a=n.get(t)?.parentId??null;for(;a&&n.has(a)&&!i.has(a);)i.add(a),r.unshift(a),a=n.get(a)?.parentId??null;return r}function _9(e){return e.childCountCapped?`${e.childCount??0}+`:String(e.childCount??0)}function SDi(e,t){let n=new Set;return t&&!(e.get(t.id)?.length??0)&&!(t.childCount??0)&&t.parentId&&t.parentId!==t.id&&(e.get(t.parentId)??[]).filter(e=>e.id!==t.id&&!v9(e)).slice(0,8).forEach(e=>n.add(e.id)),n}var CDi=`more:`,wDi=`rest:`,TDi=`group:`;function v9(e){return e.id.startsWith(CDi)}function y9(e){return e.id.startsWith(wDi)}function b9(e){return e.id.startsWith(TDi)}function EDi(e){return e.filter(e=>!e.deletedAt&&!e.mergedInto)}function DDi(e,t,n=NDi){let r=EDi(e),i=new Map(r.map(e=>[e.id,e])),a=new Map,o=[];for(let e of r){let t=e.parentId&&e.parentId!==e.id?i.get(e.parentId):void 0;t?a.set(t.id,[...a.get(t.id)??[],e]):o.push(e)}for(let e of a.values())e.sort(g9);o.sort(g9);let s=t&&i.has(t)?t:o[0]?.id??null,c=s?i.get(s):void 0,l=new Map,u=new Map,d=new Map,f=[],p=(e,t,n,r)=>{if(l.has(e))return;l.set(e,n),d.set(e,t);let i=n===1?e:r;i&&u.set(e,i),f.push(e)};if(s)p(s,null,0,void 0);else for(let e of o)p(e.id,null,1,void 0);for(;f.length;){let e=f.shift(),t=l.get(e),n=i.get(e),r=n?.parentId&&i.has(n.parentId)?n.parentId:null;r&&p(r,e,t+1,u.get(e));for(let n of a.get(e)??[])p(n.id,e,t+1,u.get(e));if(e===s&&c&&o.includes(c))for(let n of o)n.id!==s&&p(n.id,e,t+1,n.id)}let m=new Map;for(let e=t?i.get(t)?.parentId:void 0;e&&!m.has(e);){let t=i.get(e);if(!t)break;m.set(t.id,t.isScope?`scope`:`ancestor`),e=t.parentId&&t.parentId!==t.id?t.parentId:void 0}for(let e of r)e.isScope&&!b9(e)&&!v9(e)&&l.has(e.id)&&m.set(e.id,`scope`);let h=SDi(a,c),g=new Map,_=new Set,v=0;for(let e of r){let t=l.get(e.id),r=t!==void 0&&(t<=1||h.has(e.id))&&!v9(e),i=t!==void 0&&m.has(e.id)&&!v9(e),a=t===void 0&&n.has(e.id)&&!v9(e);a&&_.add(e.id),g.set(e.id,r||a||i&&v++<10?`full`:`dot`)}return{depth:l,form:g,branch:u,via:d,level:m,linked:_,center:s}}var ODi=230,kDi=300,ADi=150,jDi=70,MDi=28,x9=16,NDi=new Set;function PDi(e,t,n,r,i){let a=Math.max(...e.map(e=>i(e)))/2,o=r.flatMap(e=>{let t=n.get(e);return t?[Math.atan2(t.y,t.x)]:[]}),s=new Map,c=[...e],l=a*2.5+x9,u=l+a;for(let e=0;c.length&&e<12;e++){let e=Math.asin(Math.min(1,(a+x9/2)/l)),t=2*Math.asin(Math.min(1,(a*2+x9)/(2*l))),n=o.length?[...o].sort((e,t)=>e-t):[-Math.PI],r=[];n.forEach((i,a)=>{let o=n[(a+1)%n.length],s=i+e,c=(a+1<n.length?o:o+2*Math.PI)-e;for(let e=s;e<=c+1e-9;e+=t)r.push(e)}),c.splice(0,Math.max(1,r.length)).forEach((e,t)=>{let n=r[t]??r[0]??0;s.set(e.id,{x:Math.cos(n)*l,y:Math.sin(n)*l})}),u=l+a,l+=a*2+x9}return{points:s,reach:u}}function FDi(e,t,n,r=NDi){let i=EDi(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*kDi))),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(ODi,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?ADi:jDi,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/MDi)),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*MDi);v.set(r,{x:Math.cos(l)*x,y:Math.sin(l)*x}),y(o.get(r)??[],n+1,d,e),d+=e}},b=l.length?(s.get(l[0])??1)/l.reduce((e,t)=>e+(s.get(t)??1),0)*2*Math.PI:0,x=()=>{v.clear(),_=0,t.center&&v.set(t.center,{x:0,y:0}),y(l,1,-Math.PI/2-b/2,2*Math.PI)};x();let S=i.filter(e=>!v.has(e.id)).sort((e,t)=>e.id<t.id?-1:1),C=S.filter(e=>r.has(e.id)&&t.form.get(e.id)===`full`),w=S.filter(e=>r.has(e.id)&&t.form.get(e.id)!==`full`),T=0,E=t.center?a.get(t.center)?.parentId:void 0,D=l.some(e=>e!==E);if(C.length&&t.center&&D){let e=Math.max(...C.map(e=>n(e)))/2,t=0;for(let[e,r]of v){let i=a.get(e);i&&(t=Math.max(t,Math.hypot(r.x,r.y)+n(i)/2))}let r=Math.max(t+x9+e,C.length*(e*2+x9)/(2*Math.PI));C.forEach((e,t)=>{let n=Math.PI/2+t/C.length*2*Math.PI;v.set(e.id,{x:Math.cos(n)*r,y:Math.sin(n)*r})}),T=r+e}else if(C.length&&t.center){let e=PDi(C,t.center,v,l,n),r=Math.max(0,...l.filter(e=>t.form.get(e)===`full`).map(e=>n(a.get(e))));h.length=2,h[1]=Math.max(h[1],e.reach+x9+r/2),x();let i=PDi(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*MDi/(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)+jDi;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 IDi=[`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 LDi(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,IDi[t%IDi.length]]))}var RDi=.7,zDi=.7;function BDi(e){return e<=16?1:Math.max(zDi,Math.sqrt(16/e))}var VDi={author:``};function HDi(e,t,n){return{id:e,scopeId:t.scopeId,parentId:t.id,isScope:!1,position:``,name:``,version:0,createdBy:VDi,updatedBy:VDi,createdAt:``,updatedAt:``,...n}}function UDi(e){if(!e.isScope||!e.address)return null;let t=e.address.indexOf(`:`);return t>0?e.address.slice(0,t):null}function WDi(e){let t=e.cap??48,n=EDi(e.pages),r=new Map(n.map(e=>[e.id,e])),i=new Map,a=[];for(let e of n){let t=e.parentId&&e.parentId!==e.id?e.parentId:null;t?i.set(t,[...i.get(t)??[],e]):a.push(e)}for(let e of i.values())e.sort(g9);a.sort(g9);let o=e.focusId?r.get(e.focusId):void 0,s=new Map,c=new Map,l=new Map,u=[],d=(e,t)=>{l.has(e.id)||(l.set(e.id,t),s.set(e.id,e),u.push(e.id))},f=o??a[0],p=SDi(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=HDi(`${CDi}${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=UDi(e);t&&g.set(t,[...g.get(t)??[],e])}let _=new Set;if(n!==f?.id)for(let[t,r]of g){let i=`${TDi}${n}:${t}`;if(r.length<3||e.openGroups.has(i))continue;for(let e of r)_.add(e.id);let c=HDi(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=HDi(`${wDi}${n}`,a,{name:`+${a.childCountCapped?`${e}+`:t} more`,childCount:t});s.set(r.id,r),l.set(r.id,o+1)}}}let m=o?[o.id,...o.parentId&&o.parentId!==o.id?[o.parentId]:[]]:a.map(e=>e.id),h=[...l].filter(([e,t])=>(t<=1||p.has(e))&&!m.includes(e)).map(([e])=>s.get(e)).filter(e=>(e.childCount??0)>0&&!b9(e)&&!v9(e)&&!y9(e));return m.push(...h.slice(0,24).map(e=>e.id)),{pages:[...s.values()],hiddenChildren:c,wanted:m,hub:f?.id??null}}var GDi={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:CZ},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:HOn}};function KDi(e){return!e.isScope&&e.parentId===e.scopeId?e.key:void 0}function qDi(e){let t=e.isScope&&e.address?e.address.slice(0,e.address.indexOf(`:`)):KDi(e);return t&&Object.hasOwn(GDi,t)?GDi[t]:void 0}var JDi=new Map([[`org`,`Organization`],[`project`,`Project`],[`user`,`User`],[`agent`,`Agent`],[`team`,`Team`]]);function S9(e){let t=KDi(e);if(t&&e.name===t)return qDi(e)?.label??e.name;if(!e.isScope||!e.address)return e.name;let n=e.address.includes(`/`)?e.address.slice(e.address.lastIndexOf(`/`)+1):void 0;if(e.name!==e.address&&e.name!==n)return e.name;let r=qDi(e);if(r)return r.label;if(e.displayLabel?.trim())return e.displayLabel;if(n&&e.name===n)return e.name;let i=e.address.slice(0,e.address.indexOf(`:`)),a=i.replace(/[-_]+/g,` `);return JDi.get(i)??(a?a.charAt(0).toUpperCase()+a.slice(1):e.name)}function YDi(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 XDi(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 ZDi(e){return e.normalize(`NFKC`).trim().replace(/\s+/g,` `).toLowerCase()}function QDi(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=ZDi(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(ZDi(i))??void 0}}}function $Di(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&&eOi(n,c,l,t)?[n]:[]});return u.length===1?u[0]:void 0}function eOi(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 tOi=/\[\[([^\]]+)\]\]/g,nOi=/^(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:^\1[ \t]*$|(?![\s\S]))/gm,rOi=/(`+)[\s\S]*?\1/g;function iOi(e){return[...e.replace(nOi,``).replace(rOi,``).matchAll(tOi)].map(e=>e[1]??``)}function aOi(e){let t=QDi(e),n=[];for(let r of e){if(!r.body||r.deletedAt||r.mergedInto)continue;let e=new Map;for(let n of iOi(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 oOi=(0,G.createContext)(new Map),sOi=12,cOi=320;function lOi({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+sOi,maxHeight:Math.min(cOi,e.y-sOi-8)};let r=t.height>0?t.height-e.y-sOi-8:cOi;return{left:n,top:e.y+sOi,maxHeight:Math.min(cOi,r)}}function uOi(e,t){let n=(0,G.useRef)(e);return t(n.current,e)||(n.current=e),n.current}var dOi=/^(#{1,3})[ \t]+(.+?)[ \t#]*$/gm,fOi=/^(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:^\1[ \t]*$|(?![\s\S]))/gm;function pOi(e){return[...e.replace(fOi,``).matchAll(dOi)].map(([,e,t])=>({depth:e?.length??1,text:(t??``).replace(/\[\[([^\]]+)\]\]/g,`$1`).replace(/[*_`]/g,``)}))}var mOi=/\[\[([^\]]+)\]\]/g;function hOi(e){let t=[],n=0;for(let r of e.matchAll(mOi))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 gOi({page:e,className:t}){let n=qDi(e)?.icon;return n?(0,K.jsx)(n,{"aria-hidden":!0,className:c(`shrink-0 text-foreground`,t)}):null}function C9({label:e,children:t}){return(0,K.jsxs)(_x,{children:[(0,K.jsx)(vx,{render:t}),(0,K.jsx)(yx,{children:e})]})}var _Oi={"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 vOi(e){return e.startsWith(`importer:`)?`Importer`:e}function yOi({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 bOi(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 xOi=(0,G.createContext)(null);function SOi({node:e,...t}){let n=(0,G.useContext)(xOi),r=e?.properties[yX];if(typeof r!=`string`||!n)return(0,K.jsx)(`span`,{...t});let i=n.index.resolve(r);return i?(0,K.jsx)(C9,{label:r,children:(0,K.jsx)(`button`,{type:`button`,"data-testid":`knowledge-body-link`,className:`rounded bg-badge-blue-subtle px-1 text-left font-medium wrap-anywhere text-badge-blue-foreground hover:underline`,onClick:()=>n.onPageClick(i),children:i.name})}):(0,K.jsx)(C9,{label:`No loaded page has this address`,children:(0,K.jsx)(`span`,{"data-testid":`knowledge-body-link-unresolved`,className:`rounded border border-dashed border-border px-1 wrap-anywhere text-muted-foreground`,children:r})})}var COi=[S0n];function wOi(e,t){let n=new Map;for(let r of e.body?iOi(e.body):[]){let i=t.resolve(r);i&&i.id!==e.id&&n.set(i.id,{page:i,count:(n.get(i.id)?.count??0)+1})}return[...n.values()]}function TOi({label:e,value:t}){return(0,K.jsxs)(`div`,{className:`flex flex-col gap-0.5 px-3 py-2`,children:[(0,K.jsx)(`dt`,{children:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:e})}),(0,K.jsx)(`dd`,{children:(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`ink`,children:t})})]})}var EOi={span:SOi};function w9({label:e,count:t,className:n,children:r}){return(0,K.jsxs)(`section`,{"aria-label":e,className:n?`flex flex-col gap-2 ${n}`:`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]}),r]})}function DOi({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 OOi=new WeakMap;function kOi(e,t){let n=OOi.get(e);n||OOi.set(e,n=new WeakMap);let r=n.get(t);return r||n.set(t,r=QDi(e.values(),t)),r}function AOi({note:e,pagesById:t,onPageClick:n,highlighted:r,itemRef:i,showPage:a,compact:o}){let s=kOi(t,(0,G.useContext)(oOi)),c=n=>$Di(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)(yOi,{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:vOi(e.provenance.author)}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:(0,K.jsx)(xk,{value:e.updatedAt})}),u?(0,K.jsxs)(T,{as:`span`,variant:`caption`,tone:`muted`,children:[`on `,(0,K.jsx)(DOi,{page:u,onPageClick:n})]}):null]}),(0,K.jsx)(`p`,{className:`text-body wrap-anywhere text-foreground`,children:hOi(e.text).map((e,t)=>{if(e.type===`text`)return(0,K.jsx)(`span`,{children:e.value},t);let r=c(e.value);return r?(0,K.jsx)(C9,{label:e.value,children:(0,K.jsx)(`button`,{type:`button`,"data-testid":`knowledge-note-link`,className:`rounded bg-badge-blue-subtle px-1 text-left font-medium wrap-anywhere text-badge-blue-foreground hover:underline`,onClick:()=>n(r),children:r.name})},t):(0,K.jsx)(`span`,{className:`font-medium wrap-anywhere`,children:e.value},t)})}),e.stampScopeIds.length>0?(0,K.jsx)(`div`,{className:`flex min-w-0 flex-wrap gap-1`,"aria-label":`Stamped to`,children:e.stampScopeIds.map(e=>(0,K.jsx)(JS,{variant:`neutral`,size:`xs`,title:l(e),children:(0,K.jsx)(`span`,{className:`truncate`,children:l(e)})},e))}):null]})]})}function jOi({page:e,notes:t,pin:n,pagesById:r,onPageClick:i,highlightMentionOf:a,ancestors:o=[],mentionedBy:s=[],notesMore:c,childPages:l,activity:u,links:d,onOpenPage:f,compact:p=!1}){let m=(0,G.useRef)(null);(0,G.useEffect)(()=>{m.current?.scrollIntoView?.({block:`nearest`})},[a,t]);let h=!1,g=e.isScope?e:o.find(t=>t.id===e.scopeId)??r.get(e.scopeId),_=bOi(e,o),v=e.isScope?e.displayLabel??`Scope`:`Page`,y=(0,G.useMemo)(()=>new Map([...r,...[...o,e].map(e=>[e.id,e])]),[r,o,e]),b=(0,G.useContext)(oOi),x=(0,G.useMemo)(()=>QDi([...r.values(),...o,e],b),[r,o,e,b]),S=(0,G.useMemo)(()=>({index:x,onPageClick:i}),[x,i]),C=(0,G.useRef)(null),w=(0,G.useMemo)(()=>e.body?pOi(e.body):[],[e.body]),E=(0,G.useMemo)(()=>wOi(e,x),[e,x]),D=d?.out??E,O=d?.in??[],k=d?d.in.length:s.length,A=(0,K.jsx)(xOi.Provider,{value:S,children:(0,K.jsx)(pY,{remarkPlugins:COi,components:EOi,children:e.body??``})}),j=(0,K.jsxs)(T,{variant:`body`,tone:`muted`,children:[`This `,e.isScope?`scope`:`page`,` has no body yet.`]}),M=e=>(0,K.jsx)(`ul`,{className:`flex flex-col gap-2`,children:e.map(e=>{let t=!!a&&e.mentions.includes(a),n=t&&!h;return n&&(h=!0),(0,K.jsx)(AOi,{note:e,pagesById:y,onPageClick:i,highlighted:t,compact:p,itemRef:n?e=>{m.current=e}:void 0},e.id)})}),N=a?t.filter(e=>e.mentions.includes(a)):[],P=t.reduce((e,t)=>!e||t.updatedAt>e.updatedAt?t:e,void 0),F=N.length>0?N:P?[P]:[],I=D.length>0||O.length>0||s.length>0?(0,K.jsx)(w9,{label:`Connections`,count:D.length+Math.max(O.length,s.length),children:(0,K.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[D.length>0?(0,K.jsxs)(`section`,{"aria-label":`Links to`,className:`flex flex-col gap-1.5`,children:[(0,K.jsx)(T,{as:`h4`,variant:`caption`,tone:`muted`,children:`Links to`}),(0,K.jsx)(`ul`,{className:`flex flex-col gap-1`,children:D.map(({page:e,count:t})=>(0,K.jsxs)(`li`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(QV,{"aria-hidden":!0,className:`size-icon-xs shrink-0 text-muted-foreground`}),(0,K.jsx)(`button`,{type:`button`,className:`min-w-0 truncate text-left text-body-sm text-foreground hover:underline`,onClick:()=>i(e),children:S9(e)}),t>1?(0,K.jsxs)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`tabular-nums`,children:[`×`,t]}):null]},e.id))})]}):null,O.length>0?(0,K.jsxs)(`section`,{"aria-label":`Linked from`,className:`flex flex-col gap-1.5`,children:[(0,K.jsx)(T,{as:`h4`,variant:`caption`,tone:`muted`,children:`Linked from`}),(0,K.jsx)(`ul`,{className:`flex flex-col gap-1`,children:O.map(({page:e,count:t})=>(0,K.jsxs)(`li`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(tS,{"aria-hidden":!0,className:`size-icon-xs shrink-0 text-muted-foreground`}),(0,K.jsx)(`button`,{type:`button`,className:`min-w-0 truncate text-left text-body-sm text-foreground hover:underline`,onClick:()=>i(e),children:S9(e)}),t>1?(0,K.jsxs)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`tabular-nums`,children:[`×`,t]}):null]},e.id))})]}):null,s.length>0?(0,K.jsxs)(`section`,{"aria-label":`Mentioned in`,className:`flex flex-col gap-1.5`,children:[(0,K.jsx)(T,{as:`h4`,variant:`caption`,tone:`muted`,children:`Mentioned in`}),(0,K.jsx)(`ul`,{className:`flex flex-col gap-2`,children:s.map(e=>(0,K.jsx)(AOi,{note:e,pagesById:y,onPageClick:i,showPage:!0,compact:!0},e.id))})]}):null]})}):null;return(0,K.jsxs)(`article`,{"aria-label":e.name,className:`@container flex min-h-0 flex-1 flex-col overflow-y-auto overscroll-contain`,children:[(0,K.jsxs)(`header`,{className:p?`flex flex-col gap-3 border-b border-surface-rim px-4 pt-3 pb-4`:`flex flex-col gap-3 border-b border-border bg-fill-subtle px-6 pt-5 pb-4`,children:[(0,K.jsxs)(BDt,{label:`Breadcrumb`,className:`ml-[-.9em] min-w-0`,listClassName:`overflow-hidden`,children:[o.map(e=>(0,K.jsx)(XM,{as:`button`,onClick:()=>i(e),children:S9(e)},e.id)),(0,K.jsx)(XM,{as:`span`,isCurrent:!0,children:S9(e)})]}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[p?null:(0,K.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(gOi,{page:e,className:`size-icon-lg`}),(0,K.jsx)(C9,{label:(e.isScope?e.address:_)??e.name,children:(0,K.jsx)(T,{as:`h2`,variant:`title`,className:`min-w-0 break-words`,"data-testid":`knowledge-page-title`,children:S9(e)})}),(0,K.jsxs)(JS,{variant:`neutral`,size:`sm`,className:`shrink-0 tabular-nums`,children:[`v`,e.version]})]}),e.description?(0,K.jsx)(T,{variant:`body`,tone:`muted`,className:`wrap-anywhere ${p?`line-clamp-3`:`line-clamp-6`}`,children:e.description}):null,(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,K.jsx)(JS,{variant:e.isScope?`info`:`neutral`,size:`sm`,children:v}),n?(0,K.jsx)(JS,{variant:`warning`,size:`sm`,icon:(0,K.jsx)(xX,{"aria-hidden":!0}),children:n.audience.length>0?`Pinned for ${n.audience.join(`, `)}`:`Pinned`}):null,p?(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,"data-testid":`knowledge-page-version`,children:(0,K.jsxs)(wC,{children:[e.isScope||!g?null:(0,K.jsxs)(wC.Item,{children:[`In `,S9(g)]}),(0,K.jsxs)(wC.Item,{children:[`v`,e.version]}),(0,K.jsxs)(wC.Item,{children:[`Updated`,` `,(0,K.jsx)(xk,{value:e.updatedAt,label:`Updated by ${vOi(e.updatedBy.author)}`})]})]})}):null]})]})]}),p?(0,K.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-6 p-4`,children:[(0,K.jsxs)(`dl`,{"aria-label":`Links and notes`,className:`grid grid-cols-3 divide-x divide-border rounded-lg border border-border`,children:[(0,K.jsx)(TOi,{label:`Links in`,value:k}),(0,K.jsx)(TOi,{label:`Links out`,value:D.length}),(0,K.jsx)(TOi,{label:`Notes`,value:c?`${t.length}+`:t.length})]}),(0,K.jsx)(w9,{label:`Preview`,className:`min-h-48 flex-1`,children:e.body?(0,K.jsx)(jS,{className:`min-h-0`,children:(0,K.jsx)(`div`,{"data-testid":`knowledge-page-body`,children:A})}):j}),I,F.length>0?(0,K.jsxs)(w9,{label:a?`Notes that mention it`:`Latest note`,children:[M(F),f&&t.length>F.length?(0,K.jsxs)(X,{variant:`ghost`,size:`sm`,className:`self-start`,onClick:f,children:[`All `,c?``:`${t.length} `,`notes`]}):null]}):null]}):(0,K.jsxs)(`div`,{className:`flex flex-col gap-8 p-6 @3xl:flex-row`,children:[(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-8 @3xl:flex-1`,children:[e.body?(0,K.jsx)(`div`,{ref:C,"data-testid":`knowledge-page-body`,className:`max-w-3xl`,children:A}):j,t.length>0||c?(0,K.jsxs)(w9,{label:`Notes`,count:c?void 0:t.length,children:[M(t),c]}):null]}),(0,K.jsxs)(`aside`,{className:`flex min-w-0 flex-col divide-y divide-border border-t border-border *:py-6 *:last:pb-0 @3xl:w-72 @3xl:shrink-0 @3xl:border-t-0 @3xl:border-l @3xl:pl-8 @3xl:*:first:pt-0`,children:[w.length>1?(0,K.jsx)(w9,{label:`On this page`,children:(0,K.jsx)(`ol`,{className:`flex flex-col gap-1.5 border-l border-border`,children:w.map((e,t)=>(0,K.jsx)(`li`,{className:e.depth>2?`pl-6`:`pl-3`,children:(0,K.jsx)(`button`,{type:`button`,className:`text-left text-body-sm text-muted-foreground hover:text-foreground`,onClick:()=>{(C.current?.querySelectorAll(`h1, h2, h3`))?.[t]?.scrollIntoView({block:`start`,behavior:`smooth`})},children:(0,K.jsx)(`span`,{className:`line-clamp-2 wrap-anywhere`,children:e.text})})},t))})}):null,(0,K.jsx)(w9,{label:`Details`,children:(0,K.jsxs)(V4,{children:[e.isScope?null:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(V4.Key,{children:`Scope`}),(0,K.jsx)(V4.Value,{children:g?S9(g):e.scopeId})]}),(0,K.jsx)(V4.Key,{children:`Updated`}),(0,K.jsx)(V4.Value,{children:(0,K.jsx)(xk,{value:e.updatedAt})}),(0,K.jsx)(V4.Key,{children:`By`}),(0,K.jsx)(V4.Value,{children:vOi(e.updatedBy.author)}),(0,K.jsx)(V4.Key,{children:`Created`}),(0,K.jsx)(V4.Value,{children:(0,K.jsx)(xk,{value:e.createdAt})}),(0,K.jsx)(V4.Key,{children:`Version`}),(0,K.jsxs)(V4.Value,{children:[`v`,e.version]})]})}),I,l,u&&u.length>0?(0,K.jsx)(w9,{label:`Activity`,children:(0,K.jsx)(`ol`,{className:`relative flex flex-col gap-3 border-l border-border pl-4`,children:u.map(e=>(0,K.jsxs)(`li`,{className:`relative flex flex-col`,children:[(0,K.jsx)(`span`,{"aria-hidden":!0,className:`absolute top-1.5 -left-5 size-2 rounded-full border border-border bg-card`}),(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`ink`,children:_Oi[e.action]??e.action}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`min-w-0`,children:(0,K.jsxs)(wC,{singleLine:!0,children:[(0,K.jsx)(wC.Item,{className:`min-w-0`,children:(0,K.jsx)(C9,{label:e.provenance.author,children:(0,K.jsx)(`span`,{className:`truncate`,children:vOi(e.provenance.author)})})}),(0,K.jsx)(wC.Item,{className:`shrink-0`,children:(0,K.jsx)(xk,{value:e.createdAt})})]})})]},e.id))})}):null]})]})]},e.id)}function MOi(e,t){return e.split(/(\s+|(?<=:))/).map(e=>e.length>t&&!/^\s+$/.test(e)?`${e.slice(0,t-1)}\u2026`:e).join(``)}function T9(){return typeof window<`u`&&!!window.matchMedia?.(`(prefers-reduced-motion: no-preference)`).matches}function NOi(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 POi=.15,FOi={left:0,right:0};function IOi(e,t){return e-t.left-t.right>0?t:FOi}function LOi({bounds:e,width:t,height:n,ring:r,anchor:i,insets:a=FOi}){let o=IOi(t,a),s=r?POi:RDi,c=t-o.left-o.right,l=FD(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 ROi=.05,zOi=3e3;function BOi({bounds:e,nodes:t,width:n,height:r,legend:i,insets:a=FOi}){let o=IOi(n,a),s=(t,i)=>{let a=FD(e,n-t-o.right,r-i,POi,1,ROi);return{zoom:a.zoom,x:a.x+t,y:a.y+i}},c=s(o.left,0);if(!i||!t.some(e=>{let t=e.x*c.zoom+c.x,n=e.y*c.zoom+c.y;return t<i.right&&n<i.bottom}))return c;let l=s(i.right,0),u=s(o.left,i.bottom);return l.zoom>=u.zoom?l:u}var E9=e=>e?700:0;function VOi(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 HOi(e){let t=+this._x.call(null,e),n=+this._y.call(null,e);return UOi(this.cover(t,n),t,n,e)}function UOi(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 WOi(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)UOi(this,n[i],r[i],e[i]);return this}function GOi(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 KOi(){var e=[];return this.visit(function(t){if(!t.length)do e.push(t.data);while(t=t.next)}),e}function qOi(e){return arguments.length?this.cover(+e[0][0],+e[0][1]).cover(+e[1][0],+e[1][1]):isNaN(this._x0)?void 0:[[this._x0,this._y0],[this._x1,this._y1]]}function D9(e,t,n,r,i){this.node=e,this.x0=t,this.y0=n,this.x1=r,this.y1=i}function JOi(e,t,n){var r,i=this._x0,a=this._y0,o,s,c,l,u=this._x1,d=this._y1,f=[],p=this._root,m,h;for(p&&f.push(new D9(p,i,a,u,d)),n==null?n=1/0:(i=e-n,a=t-n,u=e+n,d=t+n,n*=n);m=f.pop();)if(!(!(p=m.node)||(o=m.x0)>u||(s=m.y0)>d||(c=m.x1)<i||(l=m.y1)<a)){if(p.length){var g=(o+c)/2,_=(s+l)/2;f.push(new D9(p[3],g,_,c,l),new D9(p[2],o,_,g,l),new D9(p[1],g,s,c,_),new D9(p[0],o,s,g,_)),(h=(t>=_)<<1|e>=g)&&(m=f[f.length-1],f[f.length-1]=f[f.length-1-h],f[f.length-1-h]=m)}else{var v=e-+this._x.call(null,p.data),y=t-+this._y.call(null,p.data),b=v*v+y*y;if(b<n){var x=Math.sqrt(n=b);i=e-x,a=t-x,u=e+x,d=t+x,r=p.data}}}return r}function YOi(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 XOi(e){for(var t=0,n=e.length;t<n;++t)this.remove(e[t]);return this}function ZOi(){return this._root}function QOi(){var e=0;return this.visit(function(t){if(!t.length)do++e;while(t=t.next)}),e}function $Oi(e){var t=[],n,r=this._root,i,a,o,s,c;for(r&&t.push(new D9(r,this._x0,this._y0,this._x1,this._y1));n=t.pop();)if(!e(r=n.node,a=n.x0,o=n.y0,s=n.x1,c=n.y1)&&r.length){var l=(a+s)/2,u=(o+c)/2;(i=r[3])&&t.push(new D9(i,l,u,s,c)),(i=r[2])&&t.push(new D9(i,a,u,l,c)),(i=r[1])&&t.push(new D9(i,l,o,s,u)),(i=r[0])&&t.push(new D9(i,a,o,l,u))}return this}function eki(e){var t=[],n=[],r;for(this._root&&t.push(new D9(this._root,this._x0,this._y0,this._x1,this._y1));r=t.pop();){var i=r.node;if(i.length){var a,o=r.x0,s=r.y0,c=r.x1,l=r.y1,u=(o+c)/2,d=(s+l)/2;(a=i[0])&&t.push(new D9(a,o,s,u,d)),(a=i[1])&&t.push(new D9(a,u,s,c,d)),(a=i[2])&&t.push(new D9(a,o,d,u,l)),(a=i[3])&&t.push(new D9(a,u,d,c,l))}n.push(r)}for(;r=n.pop();)e(r.node,r.x0,r.y0,r.x1,r.y1);return this}function tki(e){return e[0]}function nki(e){return arguments.length?(this._x=e,this):this._x}function rki(e){return e[1]}function iki(e){return arguments.length?(this._y=e,this):this._y}function aki(e,t,n){var r=new oki(t??tki,n??rki,NaN,NaN,NaN,NaN);return e==null?r:r.addAll(e)}function oki(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 ski(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}var O9=aki.prototype=oki.prototype;O9.copy=function(){var e=new oki(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=ski(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]=ski(r));return e},O9.add=HOi,O9.addAll=WOi,O9.cover=GOi,O9.data=KOi,O9.extent=qOi,O9.find=JOi,O9.remove=YOi,O9.removeAll=XOi,O9.root=ZOi,O9.size=QOi,O9.visit=$Oi,O9.visitAfter=eki,O9.x=nki,O9.y=iki;function cki(e,t){var n,r=1;e??=0,t??=0;function i(){var i,a=n.length,o,s=0,c=0;for(i=0;i<a;++i)o=n[i],s+=o.x,c+=o.y;for(s=(s/a-e)*r,c=(c/a-t)*r,i=0;i<a;++i)o=n[i],o.x-=s,o.y-=c}return i.initialize=function(e){n=e},i.x=function(t){return arguments.length?(e=+t,i):e},i.y=function(e){return arguments.length?(t=+e,i):t},i.strength=function(e){return arguments.length?(r=+e,i):r},i}function k9(e){return function(){return e}}function A9(e){return(e()-.5)*1e-6}function lki(e){return e.x+e.vx}function uki(e){return e.y+e.vy}function dki(e){var t,n,r,i=1,a=1;typeof e!=`function`&&(e=k9(e==null?1:+e));function o(){for(var e,o=t.length,c,l,u,d,f,p,m=0;m<a;++m)for(c=aki(t,lki,uki).visitAfter(s),e=0;e<o;++e)l=t[e],f=n[l.index],p=f*f,u=l.x+l.vx,d=l.y+l.vy,c.visit(h);function h(e,t,n,a,o){var s=e.data,c=e.r,m=f+c;if(s){if(s.index>l.index){var h=u-s.x-s.vx,g=d-s.y-s.vy,_=h*h+g*g;_<m*m&&(h===0&&(h=A9(r),_+=h*h),g===0&&(g=A9(r),_+=g*g),_=(m-(_=Math.sqrt(_)))/_*i,l.vx+=(h*=_)*(m=(c*=c)/(p+c)),l.vy+=(g*=_)*m,s.vx-=h*(m=1-m),s.vy-=g*m)}}else return t>u+m||a<u-m||n>d+m||o<d-m}}function s(e){if(e.data)return e.r=n[e.data.index];for(var t=e.r=0;t<4;++t)e[t]&&e[t].r>e.r&&(e.r=e[t].r)}function c(){if(t){var r,i=t.length,a;for(n=Array(i),r=0;r<i;++r)a=t[r],n[a.index]=+e(a,r,t)}}return o.initialize=function(e,n){t=e,r=n,c()},o.iterations=function(e){return arguments.length?(a=+e,o):a},o.strength=function(e){return arguments.length?(i=+e,o):i},o.radius=function(t){return arguments.length?(e=typeof t==`function`?t:k9(+t),c(),o):e},o}function fki(e){return e.index}function pki(e,t){var n=e.get(t);if(!n)throw Error(`node not found: `+t);return n}function mki(e){var t=fki,n=d,r,i=k9(30),a,o,s,c,l,u=1;e??=[];function d(e){return 1/Math.min(s[e.source.index],s[e.target.index])}function f(t){for(var n=0,i=e.length;n<u;++n)for(var o=0,s,d,f,p,m,h,g;o<i;++o)s=e[o],d=s.source,f=s.target,p=f.x+f.vx-d.x-d.vx||A9(l),m=f.y+f.vy-d.y-d.vy||A9(l),h=Math.sqrt(p*p+m*m),h=(h-a[o])/h*t*r[o],p*=h,m*=h,f.vx-=p*(g=c[o]),f.vy-=m*g,d.vx+=p*(g=1-g),d.vy+=m*g}function p(){if(o){var n,i=o.length,l=e.length,u=new Map(o.map((e,n)=>[t(e,n,o),e])),d;for(n=0,s=Array(i);n<l;++n)d=e[n],d.index=n,typeof d.source!=`object`&&(d.source=pki(u,d.source)),typeof d.target!=`object`&&(d.target=pki(u,d.target)),s[d.source.index]=(s[d.source.index]||0)+1,s[d.target.index]=(s[d.target.index]||0)+1;for(n=0,c=Array(l);n<l;++n)d=e[n],c[n]=s[d.source.index]/(s[d.source.index]+s[d.target.index]);r=Array(l),m(),a=Array(l),h()}}function m(){if(o)for(var t=0,i=e.length;t<i;++t)r[t]=+n(e[t],t,e)}function h(){if(o)for(var t=0,n=e.length;t<n;++t)a[t]=+i(e[t],t,e)}return f.initialize=function(e,t){o=e,l=t,p()},f.links=function(t){return arguments.length?(e=t,p(),f):e},f.id=function(e){return arguments.length?(t=e,f):t},f.iterations=function(e){return arguments.length?(u=+e,f):u},f.strength=function(e){return arguments.length?(n=typeof e==`function`?e:k9(+e),m(),f):n},f.distance=function(e){return arguments.length?(i=typeof e==`function`?e:k9(+e),h(),f):i},f}var hki=1664525,gki=1013904223,_ki=4294967296;function vki(){let e=1;return()=>(e=(hki*e+gki)%_ki)/_ki}function yki(e){return e.x}function bki(e){return e.y}var xki=10,Ski=Math.PI*(3-Math.sqrt(5));function Cki(e){var t,n=1,r=.001,i=1-r**(1/300),a=0,o=.6,s=new Map,c=gnt(d),l=rE(`tick`,`end`),u=vki();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=xki*Math.sqrt(.5+t),a=t*Ski;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 wki(){var e,t,n,r,i=k9(-30),a,o=1,s=1/0,c=.81;function l(n){var i,a=e.length,o=aki(e,yki,bki).visitAfter(d);for(r=n,i=0;i<a;++i)t=e[i],o.visit(f)}function u(){if(e){var t,n=e.length,r;for(a=Array(n),t=0;t<n;++t)r=e[t],a[r.index]=+i(r,t,e)}}function d(e){var t=0,n,r,i=0,o,s,c;if(e.length){for(o=s=c=0;c<4;++c)(n=e[c])&&(r=Math.abs(n.value))&&(t+=n.value,i+=r,o+=r*n.x,s+=r*n.y);e.x=o/i,e.y=s/i}else{n=e,n.x=n.data.x,n.y=n.data.y;do t+=a[n.data.index];while(n=n.next)}e.value=t}function f(e,i,l,u){if(!e.value)return!0;var d=e.x-t.x,f=e.y-t.y,p=u-i,m=d*d+f*f;if(p*p/c<m)return m<s&&(d===0&&(d=A9(n),m+=d*d),f===0&&(f=A9(n),m+=f*f),m<o&&(m=Math.sqrt(o*m)),t.vx+=d*e.value*r/m,t.vy+=f*e.value*r/m),!0;if(!(e.length||m>=s)){(e.data!==t||e.next)&&(d===0&&(d=A9(n),m+=d*d),f===0&&(f=A9(n),m+=f*f),m<o&&(m=Math.sqrt(o*m)));do e.data!==t&&(p=a[e.data.index]*r/m,t.vx+=d*p,t.vy+=f*p);while(e=e.next)}}return l.initialize=function(t,r){e=t,n=r,u()},l.strength=function(e){return arguments.length?(i=typeof e==`function`?e:k9(+e),u(),l):i},l.distanceMin=function(e){return arguments.length?(o=e*e,l):Math.sqrt(o)},l.distanceMax=function(e){return arguments.length?(s=e*e,l):Math.sqrt(s)},l.theta=function(e){return arguments.length?(c=e*e,l):Math.sqrt(c)},l}function Tki(e){var t=k9(.1),n,r,i;typeof e!=`function`&&(e=k9(e==null?0:+e));function a(e){for(var t=0,a=n.length,o;t<a;++t)o=n[t],o.vx+=(i[t]-o.x)*r[t]*e}function o(){if(n){var a,o=n.length;for(r=Array(o),i=Array(o),a=0;a<o;++a)r[a]=isNaN(i[a]=+e(n[a],a,n))?0:+t(n[a],a,n)}}return a.initialize=function(e){n=e,o()},a.strength=function(e){return arguments.length?(t=typeof e==`function`?e:k9(+e),o(),a):t},a.x=function(t){return arguments.length?(e=typeof t==`function`?t:k9(+t),o(),a):e},a}function Eki(e){var t=k9(.1),n,r,i;typeof e!=`function`&&(e=k9(e==null?0:+e));function a(e){for(var t=0,a=n.length,o;t<a;++t)o=n[t],o.vy+=(i[t]-o.y)*r[t]*e}function o(){if(n){var a,o=n.length;for(r=Array(o),i=Array(o),a=0;a<o;++a)r[a]=isNaN(i[a]=+e(n[a],a,n))?0:+t(n[a],a,n)}}return a.initialize=function(e){n=e,o()},a.strength=function(e){return arguments.length?(t=typeof e==`function`?e:k9(+e),o(),a):t},a.y=function(t){return arguments.length?(e=typeof t==`function`?t:k9(+t),o(),a):e},a}var Dki=28,Oki=300;function kki(e,t,n={}){let r=n.ticks??Oki,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??Dki,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}));Cki(i).force(`link`,mki(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`,wki().strength(e=>e.size<=24?-60:-700)).force(`collide`,dki().radius(e=>e.size/2+e.padding).strength(1).iterations(3)).force(`center`,cki(0,0)).force(`x`,Tki(0).strength(.06)).force(`y`,Eki(0).strength(.08)).stop().tick(r),Aki(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 Aki(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 jki(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 Mki(e){return`unplaced:${e}`}function Nki(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=Mki(e.principal),r.has(t)||r.set(t,Pki(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 Pki(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 Fki(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 Iki(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 Lki=[`top`,`bottom`,`right`,`left`];function Rki(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 zki(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 Bki(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 Vki(e){let t=e=>(e.right-e.left)*(e.bottom-e.top),n=`top`,r=1/0;for(let i of Lki){let a=Rki(i,e),o=(t(a)-zki(a,e.bounds))*100;for(let t of e.obstacles)o+=zki(a,t)*4;for(let t of e.lines)Bki(a,t.from,t.to)&&(o+=2e3);o<r&&(n=i,r=o)}return n}var Hki=U(`IconArrowWallUp`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M16.25 10.9998L12.7071 7.45696C12.3166 7.06643 11.6834 7.06643 11.2929 7.45695L7.75 10.9998`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M12 21V7.75`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M19 3H5`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]})),Uki={left:0,right:0},Wki={"--knowledge-color":`var(--chart-blue)`,background:`color-mix(in oklab, var(--chart-blue) 16%, var(--card))`},Gki={"--knowledge-color":`var(--border-strong)`},Kki=`var(--muted-foreground)`,qki={"--knowledge-color":Kki,background:Kki},Jki={stroke:`var(--foreground)`,strokeOpacity:.45,strokeDasharray:`4 4`,strokeWidth:1.25},Yki=`var(--chart-cyan)`,Xki={stroke:Yki,strokeWidth:2.25},Zki={type:yD.ArrowClosed,color:Yki,width:14,height:14},Qki=`var(--chart-blue)`,$ki=`var(--muted-foreground)`,eAi={type:yD.Arrow,color:$ki,width:12,height:12,strokeWidth:1.5},tAi=`var(--chart-purple)`,nAi={stroke:tAi,strokeWidth:1.75,strokeDasharray:`8 3 2 3`},rAi={type:yD.ArrowClosed,color:tAi,width:13,height:13},j9=`var(--chart-green)`,iAi={stroke:j9,strokeWidth:1.25},aAi={type:yD.ArrowClosed,color:j9,width:12,height:12},oAi={out:{stroke:j9},in:{stroke:`var(--chart-orange)`,strokeDasharray:`6 3`}},sAi={out:aAi,in:{type:yD.ArrowClosed,color:`var(--chart-orange)`,width:12,height:12}},cAi={stroke:`var(--foreground)`,strokeOpacity:.2,strokeWidth:1},lAi={background:`var(--card)`,borderColor:`var(--chart-purple)`,borderStyle:`dashed`};function uAi(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 dAi=150,fAi=4e3,pAi=3;function mAi(e){let{left:t,top:n,right:r,bottom:i}=e.getBoundingClientRect();return{left:t,top:n,right:r,bottom:i}}function hAi(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 gAi={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 _Ai({level:e}){return(0,K.jsx)(e===`scope`?XS:Hki,{"aria-hidden":!0,"data-testid":`knowledge-level-icon-${e}`,className:`mr-1 inline-block size-3 align-text-bottom`})}function vAi({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=ZD(e=>e.transform[2]),h=Math.min(Math.max(1/m,1),pAi),g=v9(t),_=b9(t),v=g?`Hover or click to load them`:_?`Click to show them`:null,y=!v&&t.childCount?`${_9(t)} ${t.childCount===1?`child`:`children`}`:null,b=t.isScope?t.displayLabel??`Scope`:`Page`,x=o&&(o.in>0||o.out>0)?fX(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=mAi(e),i=mAi(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(mAi).filter(e=>e.right>e.left&&(e.left!==i.left||e.top!==i.top)&&(e.left!==r.left||e.top!==r.top));p(Vki({dot:r,tip:{width:a,height:o},gap:8,bounds:mAi(n),obstacles:s,lines:hAi(n)}))},[c,h]);let C=gAi[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)(wC,{children:[_&&(0,K.jsx)(wC.Item,{children:i}),(0,K.jsx)(wC.Item,{children:v})]})})]}):(0,K.jsx)(J1n,{name:t.name,kind:b,pageRef:a,path:i,childCount:t.childCount?_9(t):void 0,links:o,notShown:s})]}):null,(0,K.jsx)(oO,{type:`target`,position:bD.Top,className:`!invisible`}),(0,K.jsx)(oO,{type:`source`,position:bD.Bottom,className:`!invisible`})]})}var yAi=96,bAi=.74;function xAi({data:e}){if(e.form===`dot`)return(0,K.jsx)(vAi,{data:e});let{page:t,size:n,selected:r,pinned:i,badge:a}=e,o=b9(t),s=t.isScope?t.displayLabel??`Scope`:`Page`,c=CAi(t),l=y9(t),u=n<yAi,d=Math.max(4,Math.floor(n*bAi/(u?6.5:7.5))),f=SAi(e,s);return(0,K.jsxs)(`div`,{"data-testid":`knowledge-page-node`,"data-page-id":t.id,"data-page-type":c?`placeholder`:l?`rest`:o?`group`:t.isScope?`scope`:`page`,className:`relative transition-opacity ${c?`cursor-default`:`cursor-pointer`}`,style:{width:n,height:n},"aria-label":f,children:[(0,K.jsx)(C9,{label:f,children:(0,K.jsxs)(`div`,{className:`knowledge-circle flex size-full flex-col items-center justify-center gap-0.5 overflow-hidden rounded-full border-2 text-center shadow-raised ${l?`hover:border-foreground`:``}`,"data-selected":r||void 0,"data-far":e.far||void 0,style:{...c||l?lAi:e.far?qki:t.isScope?Wki:Gki,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)(_Ai,{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)(wAi,{text:MOi(S9(t),d)})})]})}),i?(0,K.jsx)(TAi,{size:n}):null,e.hiddenLinks&&(e.hiddenLinks.in>0||e.hiddenLinks.out>0)?(0,K.jsx)(C9,{label:fX(e.hiddenLinks),children:(0,K.jsxs)(`span`,{"data-testid":`knowledge-hidden-links`,"aria-label":fX(e.hiddenLinks),className:`absolute bottom-full left-1/2 -mb-1 flex -translate-x-1/2 gap-1 rounded-full border border-border bg-card px-1.5 shadow-raised`,children:[e.hiddenLinks.in>0?(0,K.jsxs)(T,{as:`span`,variant:`meta`,style:{color:`var(--chart-orange)`},children:[`→`,e.hiddenLinks.in]}):null,e.hiddenLinks.out>0?(0,K.jsxs)(T,{as:`span`,variant:`meta`,style:{color:j9},children:[e.hiddenLinks.out,`→`]}):null]})}):null,a?(0,K.jsx)(C9,{label:`${a} children, not all drawn`,children:(0,K.jsx)(`span`,{"data-testid":`knowledge-child-count-badge`,"aria-label":`${a} children, not all drawn`,className:`absolute top-full left-1/2 -mt-1 -translate-x-1/2 rounded-full border border-border bg-card px-1.5 shadow-raised`,children:(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`ink`,children:a})})}):null,(0,K.jsx)(oO,{type:`target`,position:bD.Top,className:`!invisible`}),(0,K.jsx)(oO,{type:`source`,position:bD.Bottom,className:`!invisible`})]})}function SAi(e,t){let{page:n,links:r,notShown:i}=e;if(CAi(n))return`${t}: ${n.address}. Nothing written to it yet.`;if(y9(n))return`Show ${Math.min(12,n.childCount??12)} more of ${n.childCount??`the rest`}`;if(b9(n))return`${n.name}: click to show them`;if(n.isScope&&n.address){let e=S9(n);return e===n.address?`${t}: ${e}`:`${t}: ${e} (${n.address})`}return r&&r.in+r.out>0?`${n.name}: ${fX(r,i)}`:n.name}function CAi(e){return e.id.startsWith(`unplaced:`)}function wAi({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 TAi({size:e}){let{badge:t,style:n}=uAi(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)(xX,{size:Math.round(t*.6),"aria-hidden":!0})})}function EAi(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 DAi({id:e,data:t,style:n,markerEnd:r}){if(!t)return null;let{x1:i,y1:a,x2:o,y2:s}=EAi(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)(cO,{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 OAi={rim:(0,G.memo)(DAi)},kAi={page:(0,G.memo)(xAi)};function AAi(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 jAi=`knowledge-circle inline-block size-3 shrink-0 rounded-full border-2`;function MAi({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)(Ux,{}),"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:jAi,style:{...Wki},"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)(XS,{"aria-hidden":!0,className:`size-icon-xs shrink-0 text-muted-foreground`}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Scope, above its pages`})]}):null,a.includes(`ancestor`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-level-ancestor`,children:[(0,K.jsx)(Hki,{"aria-hidden":!0,className:`size-icon-xs shrink-0 text-muted-foreground`}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Page above the focus`})]}):null,(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`span`,{className:jAi,style:{...Gki},"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:jAi,style:{...Gki,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,RAi).map(e=>(0,K.jsxs)(`li`,{className:`flex items-center gap-2 pl-0.5`,"data-testid":`knowledge-legend-branch`,children:[(0,K.jsx)(`span`,{className:`inline-block size-2 shrink-0 rounded-full`,style:{background:e.color},"aria-hidden":!0}),(0,K.jsx)(C9,{label:e.name,children:(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`pointer-events-auto max-w-40 truncate`,children:o.length>1?`Under ${e.name}`:e.scope?`Under parent scope`:`Under parent page`})})]},e.id)),o.length>RAi?(0,K.jsx)(`li`,{className:`pl-0.5`,children:(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,children:[`+`,o.length-RAi,` more branches`]})}):null,e.has(`out`)||e.has(`in`)?(0,K.jsxs)(K.Fragment,{children:[e.has(`out`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-out`,children:[(0,K.jsxs)(`svg`,{width:`16`,height:`8`,"aria-hidden":!0,className:`shrink-0`,children:[(0,K.jsx)(`line`,{x1:`0`,y1:`4`,x2:`12`,y2:`4`,stroke:j9,strokeWidth:`1.5`}),(0,K.jsx)(`polygon`,{points:`11,1 16,4 11,7`,fill:j9})]}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Links out of the selected page`})]}):null,e.has(`in`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-in`,children:[(0,K.jsxs)(`svg`,{width:`16`,height:`8`,"aria-hidden":!0,className:`shrink-0`,children:[(0,K.jsx)(`line`,{x1:`0`,y1:`4`,x2:`12`,y2:`4`,stroke:`var(--chart-orange)`,strokeWidth:`1.5`,strokeDasharray:`3 2`}),(0,K.jsx)(`polygon`,{points:`11,1 16,4 11,7`,fill:`var(--chart-orange)`})]}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Links into it`})]}):null]}):null,e.has(`mention`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-mention`,children:[(0,K.jsx)(`svg`,{width:`12`,height:`4`,"aria-hidden":!0,className:`shrink-0`,children:(0,K.jsx)(`line`,{x1:`0`,y1:`2`,x2:`12`,y2:`2`,stroke:Qki,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`,...iAi}),(0,K.jsx)(`polygon`,{points:`11,1 16,4 11,7`,fill:j9})]}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Linked in page body`})]}):null,e.has(`dot-parent`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-dot-parent`,children:[(0,K.jsx)(`svg`,{width:`16`,height:`4`,"aria-hidden":!0,className:`shrink-0`,children:(0,K.jsx)(`line`,{x1:`0`,y1:`2`,x2:`16`,y2:`2`,...cAi,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`,...Xki}),(0,K.jsx)(`polygon`,{points:`9,1 15,4 9,7`,fill:Yki})]}),(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`,...Jki,strokeDasharray:`3 2`}),(0,K.jsx)(`polyline`,{points:`10,1 14,4 10,7`,fill:`none`,stroke:$ki,strokeWidth:`1.25`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Parent → child`})]}):null,t?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-link-counts`,children:[(0,K.jsx)(T,{as:`span`,variant:`meta`,style:{color:`var(--chart-orange)`},children:`→4`}),(0,K.jsx)(T,{as:`span`,variant:`meta`,style:{color:j9},children:`14→`}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Links in, links out (not drawn)`})]}):null,e.has(`grant`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,children:[(0,K.jsxs)(`svg`,{width:`16`,height:`8`,"aria-hidden":!0,className:`shrink-0`,"data-testid":`knowledge-legend-grant`,children:[(0,K.jsx)(`line`,{x1:`0`,y1:`4`,x2:`12`,y2:`4`,...nAi,strokeDasharray:`4 2 1 2`,strokeWidth:`1.5`}),(0,K.jsx)(`polygon`,{points:`11,1 16,4 11,7`,fill:tAi})]}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Grants access (hover for role)`})]}):null,(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`span`,{className:`flex size-3 shrink-0 items-center justify-center rounded-full bg-badge-amber-strong text-badge-amber-foreground [&>svg]:size-2`,"aria-hidden":!0,children:(0,K.jsx)(xX,{})}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Pinned`})]})]})]})}var NAi=4,PAi=`knowledge-neighbour`;function FAi(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 IAi=1.2,LAi=.8,RAi=4,zAi=40;function BAi(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),dAi),n=setTimeout(()=>i(!0),fAi);return()=>{clearTimeout(e),clearTimeout(n)}},[t,e.selectedPageId]),(0,K.jsxs)(lO,{children:[(0,K.jsx)(VAi,{...o}),s&&a?(0,K.jsx)(`p`,{role:`status`,"data-testid":`knowledge-graph-loading`,className:`pointer-events-none absolute bottom-3 left-1/2 z-10 -translate-x-1/2 rounded border border-border bg-card px-3 py-1 text-body-sm text-muted-foreground shadow-overlay`,children:`Loading pages…`}):null]})}function VAi({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=Uki,collapsibleLegend:y}){let{graphPages:b,allEdges:x}=(0,G.useMemo)(()=>{let n=Nki(e,r);return{graphPages:n.placeholders.length?[...e,...n.placeholders]:e,allEdges:[...jki(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=DDi(b,i??a??null,c),t=LDi(b,e),n=Iki(b,x);for(let t of n.nodes)if(e.form.get(t.id)===`dot`){let e=C.get(t.id),n=f&&!v9(t.data.page)&&!!e&&e.in+e.out>0;t.data.size=n?28:20}else t.id===e.center?t.data.size=Math.round(t.data.size*IAi):t.data.size=Math.round(108*(e.linked.has(t.id)?LAi:1));let r=n.nodes.filter(t=>e.depth.get(t.id)===1&&e.form.get(t.id)===`full`),o=BDi(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=FDi(b,e,e=>s.get(e.id)??20,c),u=kki(n.nodes.map(t=>({id:t.id,size:t.data.size,padding:e.form.get(t.id)===`dot`?4:24,initial:l.get(t.id)})),[],{ticks:0});return{nodes:n.nodes,edges:n.edges,positions:u,shape:e,colors:t}},[b,x,i,a,C,f,c]),D=(0,G.useMemo)(()=>new Map(b.map(e=>[e.id,e])),[b]),O=(0,G.useMemo)(()=>{let e=E.shape.center?D.get(E.shape.center)?.parentId:void 0;return e&&E.positions.has(e)?e:null},[E,D]),k=(0,G.useMemo)(()=>{let e=new Set;for(let[t,n]of E.shape.level)E.shape.form.get(t)===`full`&&e.add(n);return[...e]},[E]),A=(0,G.useMemo)(()=>{let e=new Map;for(let t of E.nodes){if(E.shape.form.get(t.id)!==`dot`||v9(t.data.page))continue;let n=E.shape.branch.get(t.id),r=n?E.colors.get(n):void 0,i=n?D.get(n):void 0;n&&r&&i&&!e.has(n)&&e.set(n,{id:n,name:i.displayLabel??S9(i),color:r,scope:!!i.isScope})}return[...e.values()]},[E,D]),j=(0,G.useMemo)(()=>new Set(n),[n]),M=(0,G.useMemo)(()=>{let e=new Map;for(let t of b)t.parentId&&!v9(t)&&!y9(t)&&e.set(t.parentId,(e.get(t.parentId)??0)+1);return new Set(b.filter(t=>!b9(t)&&!y9(t)&&(t.childCountCapped||(t.childCount??0)>(e.get(t.id)??0))).map(e=>e.id))},[b]),[N,P]=(0,G.useState)(null);(0,G.useEffect)(()=>d?.(N),[N,d]);let F=(0,G.useMemo)(()=>{if(!N)return[];let e=new Set(E.nodes.map(e=>e.id)),t=new Set(E.edges.map(e=>e.id)),n=[];for(let r of w.get(N)??[]){let i=`${r.kind}:${r.source}->${r.target}`;if(!t.has(i)&&e.has(r.source)&&e.has(r.target)&&(t.add(i),n.push({id:i,source:r.source,target:r.target,data:{kind:r.kind,count:r.count??1}}),n.length>=zAi))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)?Fki(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:bD.Top,x:e.data.size/2,y:0,width:1,height:1},{type:`source`,position:bD.Bottom,x:e.data.size/2,y:e.data.size,width:1,height:1}],position:{x:t.x-e.data.size/2,y:t.y-e.data.size/2},data:{...e.data,selected:e.id===i,pinned:j.has(e.id),form:E.shape.form.get(e.id)??`full`,color:E.colors.get(E.shape.branch.get(e.id)??``),badge:M.has(e.id)?_9(e.data.page):void 0,path:YDi(e.data.page,D),hiddenLinks:E.shape.form.get(e.id)===`full`?o?.get(e.id):void 0,ref:XDi(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?{...oAi[s],strokeWidth:r?2:1.5}:r?{stroke:Qki,strokeWidth:Math.min(1.5+(t.data?.count??1)*.5,4)}:c?Xki:i?nAi:a?iAi:o?cAi:Jki,markerEnd:s?sAi[s]:c?Zki:r?{type:yD.ArrowClosed,color:Qki,width:14,height:14}:i?rAi:a?aAi:o?void 0:eAi}}),drawnEdgeStyles:e}},[E,F,_,L,O]),H=FAi(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:PAi}:{},...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,PAi].filter(Boolean).join(` `)}:e):H,[H,R]),U=(0,G.useMemo)(()=>new Map(e.map(e=>[e.id,e])),[e]),W=iO(),ne=(0,G.useRef)(null),re=z.length>0,ie=NOi(ee,T9()),ae=E.shape.linked,oe={"--knowledge-pane-left":`${v.left}px`},se=(0,G.useRef)({nodes:z,selectedPageId:i,centerId:a,reactFlow:W,linkedIds:ae,insets:v});se.current={nodes:z,selectedPageId:i,centerId:a,reactFlow:W,linkedIds:ae,insets:v};let ce=(0,G.useRef)(!1),le=()=>{let e=ne.current,t=e?.clientWidth??0,n=e?.clientHeight??0;if(t===0||n===0)return ce.current=!0,null;ce.current=!1;let{nodes:r,reactFlow:i}=se.current,a=AAi(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=LOi({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=BOi({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=IOi(n,c),d=s.getViewport(),f=VOi(l.position.x*d.zoom+d.x-u.left,(l.width??0)*d.zoom,n-u.left-u.right),p=VOi(l.position.y*d.zoom+d.y,(l.height??0)*d.zoom,r);(f!==0||p!==0)&&s.setViewport({zoom:d.zoom,x:d.x+f,y:d.y+p},e?{duration:e}:void 0)},[]);(0,G.useEffect)(()=>{let e=ne.current;if(!e||typeof ResizeObserver>`u`)return;let t={width:e.clientWidth,height:e.clientHeight},n,r=!1,i=new ResizeObserver(([e])=>{if(!e)return;let{width:i,height:a}=e.contentRect,o=i!==t.width||a!==t.height;(t.width===0||t.height===0)&&(r=!0),t={width:i,height:a},(o||ce.current)&&i!==0&&a!==0&&(n!==void 0&&cancelAnimationFrame(n),n=requestAnimationFrame(()=>{n=void 0,r||ce.current?(r=!1,de()):fe()}))});return i.observe(e),()=>{i.disconnect(),n!==void 0&&cancelAnimationFrame(n)}},[re,de,fe]);let pe=(0,G.useRef)(null),me=!!i&&U.has(i),he=(0,G.useRef)(!1);(0,G.useEffect)(()=>{he.current&&fe(E9(T9()))},[v.left,v.right,fe]);let ge=(0,G.useRef)(0),_e=(0,G.useRef)(null),ve=(0,G.useRef)(``),ye=(0,G.useCallback)(()=>{ge.current=0},[]);(0,G.useEffect)(()=>{if(!he.current||((i??null)!==_e.current&&(ge.current=0),Date.now()>=ge.current))return;let e=z.map(e=>`${e.id}@${e.position.x},${e.position.y}`).join(`|`);e!==ve.current&&(ve.current=e,de())},[z,i,de]),(0,G.useEffect)(()=>{if(!he.current||!me||!i)return;let e=pe.current===i;pe.current=null,e||fe(E9(T9()))},[i,me,fe]);let be=e=>{if(v9(e)||b9(e)||y9(e))return m(e);if(e.id===i&&h)return h(e);pe.current=e.id,m(e)},xe=(0,G.useRef)(null),Se=e=>{if(e.key!==`Enter`&&e.key!==` `)return;let t=e.target.closest(`.react-flow__node`)?.dataset.id,n=t?U.get(t):void 0;n&&(e.preventDefault(),be(n))},Ce=(0,G.useRef)({activate:be,onPreview:p,onMentionSelect:_,onClearSelection:g,laidOut:E,pagesById:U});Ce.current={activate:be,onPreview:p,onMentionSelect:_,onClearSelection:g,laidOut:E,pagesById:U};let we=(0,G.useCallback)((e,t)=>{P(t.id),Ce.current.laidOut.shape.form.get(t.id)===`dot`&&Ce.current.onPreview?.(t.data.page)},[]),Te=(0,G.useCallback)(()=>P(null),[]),Ee=(0,G.useCallback)((e,t)=>{CAi(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)>NAi||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)(MAi,{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)(llt,{nodes:ie,edges:te,nodeTypes:kAi,edgeTypes:OAi,onInit:()=>{he.current=!0,ge.current=Date.now()+zOi,_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)(Slt,{variant:uO.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)(GV,{size:`sm`,"aria-label":`Zoom`,"data-knowledge-graph-zoom":!0,className:`rounded-full shadow-overlay`,children:[(0,K.jsx)(X,{size:`icon-sm`,tooltip:`Zoom out`,"aria-label":`Zoom out`,onClick:()=>void W.zoomOut({duration:E9(T9())}),children:(0,K.jsx)($6e,{})}),(0,K.jsx)(X,{size:`icon-sm`,tooltip:`Zoom in`,"aria-label":`Zoom in`,onClick:()=>void W.zoomIn({duration:E9(T9())}),children:(0,K.jsx)(Ix,{})}),(0,K.jsx)(X,{size:`icon-sm`,tooltip:`Fit view`,"aria-label":`Fit view`,onClick:()=>ue(E9(T9())),children:(0,K.jsx)(Q6e,{})})]})})]}):(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 HAi(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 UAi=1/3,WAi=.1,GAi=.7;function KAi({pages:e,pinnedIds:t,selectedPageId:n,onSelect:r,initiallyExpanded:i,mayHaveChildren:a,onExpandedChange:o,loadMore:s,"aria-label":l=`Knowledge pages`}){let u=(0,G.useMemo)(()=>yDi(e),[e]),d=(0,G.useMemo)(()=>new Set(t),[t]),[f,p]=(0,G.useState)(()=>new Set(i??u.map(e=>e.page.id))),[m,h]=(0,G.useState)(null),g=(0,G.useRef)(new Map),_=(0,G.useRef)(null);(0,G.useEffect)(()=>{if(!n){_.current=null;return}let t=xDi(e,n),r=[n,...t].join(`/`);_.current!==r&&(_.current=r,p(e=>t.every(t=>e.has(t))?e:new Set([...e,...t])))},[e,n]),(0,G.useEffect)(()=>{o?.(f)},[f,o]);let v=(0,G.useMemo)(()=>bDi(u,f).map(e=>!e.hasChildren&&a?.(e.page)?{...e,hasChildren:!0}:e),[u,f,a]),b=(0,G.useRef)(null),x=(0,G.useRef)(null),S=(0,G.useRef)(!1);(0,G.useEffect)(()=>{if(!n){x.current=null;return}let e=g.current.get(n);if(!e)return;let t=x.current!==n;if(t)x.current=n,S.current=!1;else if(S.current)return;let r=HAi(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*WAi&&i.bottom<=r.top+r.height*GAi)return;e.style.scrollMarginTop=`${r.height*UAi}px`}e.scrollIntoView?.({block:`start`,behavior:t&&T9()?`smooth`:`auto`}),e.style.scrollMarginTop=``}},[v,n]);let C=m&&v.some(e=>e.page.id===m)?m:v.find(e=>e.page.id===n)?.page.id??v[0]?.page.id,w=(e,t)=>p(n=>{if(n.has(e)===t)return n;let r=new Set(n);return t?r.add(e):r.delete(e),r}),T=e=>{e&&(h(e),g.current.get(e)?.focus())},E=(e,t)=>{let n=v[t];if(n){switch(e.key){case`ArrowDown`:T(v[t+1]?.page.id);break;case`ArrowUp`:T(v[t-1]?.page.id);break;case`ArrowRight`:n.hasChildren&&!n.expanded?w(n.page.id,!0):n.expanded&&T(v[t+1]?.page.id);break;case`ArrowLeft`:n.expanded?w(n.page.id,!1):T(v.slice(0,t).findLast(e=>e.depth<n.depth)?.page.id);break;case`Enter`:case` `:r(n.page);break;default:return}e.preventDefault()}};if(v.length===0)return(0,K.jsx)(`p`,{className:`px-3 py-2 text-body text-muted-foreground`,children:`No pages yet.`});let D=[];return(0,K.jsx)(`div`,{ref:b,role:`tree`,"aria-label":l,className:`min-h-0 overflow-y-auto py-1`,onWheel:()=>S.current=!0,onTouchMove:()=>S.current=!0,onPointerDown:()=>S.current=!0,onKeyDown:()=>S.current=!0,children:v.map((e,t)=>{let i=e.page.id===n;D[e.depth]=e.page.id;let a=v[t+1]?.depth??-1,o=[];for(let t=e.depth-1;t>=a;t--){let e=t<0?``:D[t];e!==void 0&&o.push({parentId:e,depth:t+1})}return e.expanded&&v[t+1]?.depth!==e.depth+1&&o.unshift({parentId:e.page.id,depth:e.depth+1}),(0,K.jsxs)(G.Fragment,{children:[(0,K.jsxs)(`div`,{ref:t=>{t?g.current.set(e.page.id,t):g.current.delete(e.page.id)},role:`treeitem`,"aria-level":e.depth+1,"aria-selected":i,"aria-expanded":e.hasChildren?e.expanded:void 0,tabIndex:e.page.id===C?0:-1,onFocus:()=>h(e.page.id),onKeyDown:e=>E(e,t),onClick:()=>{r(e.page),e.hasChildren&&w(e.page.id,!0)},className:c(`flex h-8 cursor-pointer items-center gap-2 rounded-md pr-2 text-body-sm text-foreground outline-none focus-visible:bg-fill-subtle`,i?`bg-fill-hover`:`hover:bg-fill-subtle`),style:{paddingLeft:`${e.depth*12+4}px`},children:[e.hasChildren?(0,K.jsx)(`button`,{type:`button`,tabIndex:-1,"aria-label":e.expanded?`Collapse ${S9(e.page)}`:`Expand ${S9(e.page)}`,className:`flex size-3 shrink-0 items-center justify-center text-muted-foreground hover:text-foreground`,onClick:t=>{t.stopPropagation(),w(e.page.id,!e.expanded)},children:(0,K.jsx)(y,{direction:`right`,open:e.expanded,className:`size-3`})}):(0,K.jsx)(`span`,{className:`size-3 shrink-0`,"aria-hidden":!0}),(0,K.jsx)(`span`,{className:`flex shrink-0 items-center text-muted-foreground [&>svg]:size-icon-sm`,"aria-hidden":!0,children:qDi(e.page)?.icon?(0,K.jsx)(gOi,{page:e.page}):e.page.isScope||e.hasChildren?(0,K.jsx)(GN,{}):(0,K.jsx)(hk,{})}),(0,K.jsx)(`span`,{className:c(`min-w-0 flex-1 truncate`,e.page.isScope&&`font-medium`),children:S9(e.page)}),e.page.childCount?(0,K.jsx)(`span`,{"data-testid":`knowledge-tree-count`,"aria-label":`${_9(e.page)} below`,className:`shrink-0 text-caption text-placeholder tabular-nums`,children:_9(e.page)}):null,d.has(e.page.id)?(0,K.jsx)(xX,{className:`size-icon-xs shrink-0 text-badge-amber-indicator`,"aria-label":`Pinned`}):null,e.page.isScope&&e.page.address&&e.page.address!==S9(e.page)?(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 qAi=U(`IconSidebarLeftArrow`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M4 6C4 4.89543 4.89543 4 6 4H18C19.1046 4 20 4.89543 20 6V18C20 19.1046 19.1046 20 18 20H6C4.89543 20 4 19.1046 4 18V6Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M9 4V20`,stroke:`currentColor`,strokeWidth:`2`}),(0,K.jsx)(`path`,{d:`M15.5 10L13.5 12L15.5 14`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]})),JAi=U(`IconSidebarWideLeftArrow`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M15 10L13 12L15 14`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M3 7C3 5.89543 3.89543 5 5 5H19C20.1046 5 21 5.89543 21 7V17C21 18.1046 20.1046 19 19 19H5C3.89543 19 3 18.1046 3 17V7Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M8 5V12V19`,stroke:`currentColor`,strokeWidth:`2`})]})),YAi=/^[0-9A-Z]{26}$/,XAi=6e4,ZAi=e=>Date.now()-Date.parse(e.createdAt)<XAi,QAi=2,$Ai=40;function eji(e){return`${e.kind}\u0000${e.source}\u0000${e.target}`}function tji(e,t,n,r){let i=new Map;for(let t of e)t.source!==t.target&&!i.has(eji(t))&&i.set(eji(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(eji(e))),hidden:l,more:s}}function nji(e,t){return t?`page`:e===`tree`?`tree`:`graph`}var rji=296,iji=44;function aji(e,t){return e?t?rji:iji:0}var oji=392,sji=()=>[],cji=[],lji=()=>[],uji=()=>({isPending:!1,isError:!1,error:null}),dji=150;function fji(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 pji=()=>({isPending:!1,isError:!1,error:null});function mji(e){return!!e&&typeof e==`object`&&`status`in e&&e.status===404}function hji(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 gji(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 _ji=[`w-32`,`w-24`,`w-40`,`w-28`,`w-36`,`w-20`];function vji({label:e,rows:t}){return(0,K.jsx)(`div`,{role:`status`,"aria-label":e,className:`flex flex-col`,children:_ji.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)(NS,{className:`size-3.5 shrink-0`}),(0,K.jsx)(PS,{className:e})]},e))})}function yji(){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)(PS,{className:`w-24`}),(0,K.jsx)(PS,{className:`w-full`}),(0,K.jsx)(PS,{className:`w-2/3`})]},e))})}function bji({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)(PS,{line:`text-caption`,className:`w-28`}),e?null:(0,K.jsx)(PS,{line:`text-title`,className:`h-5 w-56`}),(0,K.jsx)(PS,{className:`w-72 max-w-full`}),(0,K.jsx)(PS,{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)(PS,{className:`w-full max-w-3xl`}),(0,K.jsx)(PS,{className:`w-5/6 max-w-2xl`}),(0,K.jsx)(PS,{className:`w-2/3 max-w-xl`})]})]})}function xji({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 Sji({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)(()=>hji(r,a.data?.related??[]),[a.data,r]);if(a.isPending)return(0,K.jsx)(yji,{});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)(AOi,{note:e,pagesById:c,onPageClick:i},e.id))}),l?o?(0,K.jsx)(Sji,{source:e,pageId:t,cursor:l,pagesById:r,onPageClick:i}):(0,K.jsx)(xji,{label:`Load more notes`,onClick:()=>s(!0)}):null]})}function Cji({useTreeLevels:e,parentId:t,onOpen:n}){let[r,i]=(0,G.useState)([]),a=e((0,G.useMemo)(()=>[{parentId:t},...r.map(e=>({parentId:t,cursor:e}))],[t,r])),o=a.flatMap(e=>e.data?.pages??[]),s=a[a.length-1];if(a[0]?.isPending)return(0,K.jsx)(w9,{label:`Pages`,children:(0,K.jsx)(vji,{label:`Loading pages`,rows:3})});let c=s?.data?.nextCursor;return o.length===0&&!c?null:(0,K.jsxs)(w9,{label:`Pages`,children:[(0,K.jsx)(`div`,{className:`rounded-xl p-1 ${Pv}`,children:(0,K.jsx)(N6,{className:`rounded-lg bg-background p-1`,onSelect:n,children:(0,K.jsx)(wji,{pages:o,useTreeLevels:e,onOpen:n})})}),c?(0,K.jsx)(xji,{onClick:()=>i(e=>[...e,c])}):null]})}function wji({pages:e,useTreeLevels:t,onOpen:n}){return e.map(e=>e.childCount===0?(0,K.jsxs)(N6.File,{id:e.id,children:[(0,K.jsx)(N6.Icon,{className:`text-muted-foreground`,children:(0,K.jsx)(hk,{})}),(0,K.jsx)(Tji,{page:e})]},e.id):(0,K.jsx)(Eji,{page:e,useTreeLevels:t,onOpen:n},e.id))}function Tji({page:e}){return e.description?(0,K.jsx)(C9,{label:e.description,children:(0,K.jsx)(N6.Label,{children:e.name})}):(0,K.jsx)(N6.Label,{children:e.name})}function Eji({page:e,useTreeLevels:t,onOpen:n}){let[r,i]=(0,G.useState)(!1);return(0,K.jsxs)(N6.Folder,{id:e.id,open:r,onOpenChange:i,children:[(0,K.jsxs)(N6.FolderTrigger,{actions:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`Open ${e.name}`,"aria-label":`Open ${e.name}`,onClick:()=>n(e.id),children:(0,K.jsx)(QV,{})}),children:[(0,K.jsx)(N6.Icon,{className:`text-muted-foreground`,children:(0,K.jsx)(GN,{})}),(0,K.jsx)(Tji,{page:e}),e.childCount?(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`ml-auto pl-2 tabular-nums`,children:e.childCount}):null]}),(0,K.jsx)(N6.FolderContent,{children:r?(0,K.jsx)(Dji,{parentId:e.id,useTreeLevels:t,onOpen:n}):null})]})}function Dji({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)(vji,{label:`Loading pages`,rows:2})}):a[0]?.isError?(0,K.jsx)(Oji,{children:`Couldn’t load the pages under this one.`}):o.length===0&&!s?(0,K.jsx)(Oji,{children:`No pages under this one.`}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(wji,{pages:o,useTreeLevels:t,onOpen:n}),s?(0,K.jsx)(`li`,{role:`none`,className:`pl-9`,children:(0,K.jsx)(xji,{onClick:()=>i(e=>[...e,s])})}):null]})}function Oji({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 kji({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:lOi(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)(hw,{className:`size-icon-sm`,"aria-hidden":!0})})]}),(0,K.jsx)(`div`,{className:`min-h-0 overflow-y-auto`,children:a.isPending?(0,K.jsx)(yji,{}):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)(AOi,{note:e,pagesById:hji(n,a.data?[...a.data.related,...a.data.ancestors,a.data.page]:[]),onPageClick:e=>r(e.id),compact:!0},e.id))})})]})}function Aji({source:e,pageId:t,pagesById:n,onSelect:r,highlightMentionOf:i,compact:a,onOpenPage:o}){let s=e.usePage(t),c=(e.useActivity??pji)(t),l=(e.usePageLinks??uji)(t).data,u=(0,G.useMemo)(()=>l?Pji(t,l):void 0,[t,l]),[d,f]=(0,G.useState)(null),p=(0,G.useMemo)(()=>s.data?hji(n,[...s.data.ancestors,...s.data.related]):n,[s.data,n]);if(s.isPending)return(0,K.jsx)(bji,{compact:a});if(s.isError||!s.data){let e=mji(s.error);return(0,K.jsx)(Hx,{tone:`error`,variant:`fill`,titleSlot:e?`Page not found`:`Failed to load the page`,descriptionSlot:e?`It may have been deleted or merged.`:s.error?.message??``})}let m=e=>r(e.id),h=s.data.notesNextCursor;return(0,K.jsx)(jOi,{compact:a,onOpenPage:o,page:s.data.page,notes:s.data.notes,pin:s.data.pin??void 0,pagesById:p,onPageClick:m,highlightMentionOf:i,ancestors:s.data.ancestors,mentionedBy:s.data.mentionedBy,links:u,activity:c.data?.events,childPages:e.useTreeLevels?(0,K.jsx)(Cji,{useTreeLevels:e.useTreeLevels,parentId:t,onOpen:r},t):void 0,notesMore:h?d?.pageId===t?(0,K.jsx)(Sji,{source:e,pageId:t,cursor:h,pagesById:p,onPageClick:m}):(0,K.jsx)(xji,{label:`Load more notes`,onClick:()=>f({pageId:t})}):void 0})}var jji=30;function Mji(e,t){let n=t.trim()?e.toLowerCase().indexOf(t.trim().toLowerCase()):-1;if(n<=jji)return e;let r=e.lastIndexOf(` `,n-jji)+1;return`…${e.slice(r)}`}function Nji({text:e,query:t}){let n=t.trim().toLowerCase(),r=n?e.toLowerCase().indexOf(n):-1;return r<0?(0,K.jsx)(K.Fragment,{children:e}):(0,K.jsxs)(K.Fragment,{children:[e.slice(0,r),(0,K.jsx)(`mark`,{className:`rounded-sm bg-badge-blue-subtle text-foreground`,children:e.slice(r,r+n.length)}),e.slice(r+n.length)]})}function Pji(e,{edges:t,pages:n}){let r=new Map(n.map(e=>[e.id,e])),i=(n,i)=>{let a=new Map;for(let r of t)r[n]===e&&r[i]!==e&&a.set(r[i],(a.get(r[i])??0)+r.count);return[...a].flatMap(([e,t])=>{let n=r.get(e);return n?[{page:n,count:t}]:[]})};return{out:i(`fromPageId`,`toPageId`),in:i(`toPageId`,`fromPageId`)}}function Fji({source:e,onSelect:t}){let[n,r]=(0,G.useState)(``),i=e.useSearch(n),a=n.trim().length>=QAi?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)(wH,{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 ${Fv}`,children:(0,K.jsx)(jS,{maxHeight:`18rem`,children:(0,K.jsx)(`ul`,{role:`listbox`,"aria-label":`Search results`,className:`p-1`,children:s.map(e=>(0,K.jsx)(`li`,{role:`option`,"aria-selected":!1,children:(0,K.jsx)(`button`,{type:`button`,className:c(CT,`whitespace-normal`),onClick:()=>{t(e.id),r(``)},children:(0,K.jsxs)(`span`,{className:`flex min-w-0 flex-col gap-0.5`,children:[(0,K.jsx)(`span`,{className:`line-clamp-2 wrap-anywhere`,children:(0,K.jsx)(Nji,{text:e.name,query:n})}),e.description?(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`line-clamp-1 wrap-anywhere`,children:(0,K.jsx)(Nji,{text:Mji(e.description,n),query:n})}):null]})})},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??sji)(c),{pages:u,loaded:d,failed:f,nextCursor:p}=uOi((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?!ZAi(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=Gw(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?WDi({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??uji)(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=QDi(t.values()),i=e.page.id,a=e.notes.flatMap(e=>e.mentions).filter(e=>e&&e!==i),o=iOi(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(`:`)&&!YAi.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,$Ai-_(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??cji,j=(t.useLinkedPages??lji)(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`),...aOi(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)(()=>tji(V,L,n,b),[V,L,n,b]),ee=H.edges,te=(0,G.useMemo)(()=>I.pages.filter(e=>!v9(e)&&!y9(e)&&!b9(e)).map(e=>e.id).sort(),[I.pages]),U=(t.useLinkCounts??uji)(l===`graph`?te:[]),W=(0,G.useMemo)(()=>U.data?new Map(Object.entries(U.data)):void 0,[U.data]),ne=(0,G.useMemo)(()=>W?fji(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),dji):ie(null)},[]);(0,G.useEffect)(()=>()=>clearTimeout(ae.current),[]);let se=(t.usePageLinks??uji)(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&&!gji([...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=gji(t.useTreeLevels?w.pages:e.pages,Re?z:null),Be=(0,G.useMemo)(()=>gji(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)(UN,{}),narrowOnly:!0},{value:`graph`,label:`Graph`,icon:(0,K.jsx)(T7e,{}),narrowOnly:!1},{value:`page`,label:`Page`,icon:(0,K.jsx)(hk,{}),narrowOnly:!1}],Ue=nji(l,Te),We=he&&Te,Ge=he&&!Te&&n&&!mji(u.error)&&n?n:void 0;Ge&&Ge!==ve&&ye(Ge);let Ke=Ge??ve,qe={left:aji(he,ge),right:Ge?oji:0},Je={"--knowledge-tree-inset":`${qe.left}px`,"--knowledge-tree-drawer-inset":`${he&&ge?rji:0}px`,"--knowledge-drawer-inset":`${qe.right}px`},Ye=()=>be.current?.querySelector(`[role="tab"][aria-selected="true"]`)?.focus(),Xe=e=>{e&&Ce.current&&(Ce.current=!1,Ye())},Ze=e=>{(0,Pt.flushSync)(()=>_e(e)),(e?Se:xe).current?.focus()},Qe=he&&!ge,$e=he?(0,K.jsxs)(dQ.Header,{children:[(0,K.jsx)(dQ.Heading,{children:`Pages`}),(0,K.jsx)(dQ.HeaderActions,{children:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`Hide pages`,"aria-label":`Hide pages`,ref:Se,onClick:()=>Ze(!1),children:(0,K.jsx)(JAi,{})})})]}):null,et=(0,K.jsxs)(K.Fragment,{children:[Re?(0,K.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-surface-rim bg-fill-subtle px-3 py-2`,"data-testid":`knowledge-scope-focus`,children:[(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,K.jsx)(T,{as:`span`,variant:`eyebrow`,tone:`muted`,className:`uppercase`,children:Re.displayLabel??`Scope`}),(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5`,children:[(0,K.jsx)(gOi,{page:Re,className:`size-3.5`}),(0,K.jsx)(C9,{label:Re.address??Re.name,children:(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`ink`,className:`truncate`,children:S9(Re)})})]})]}),(0,K.jsx)(X,{variant:`ghost`,size:`sm`,onClick:()=>B(null),children:`All scopes`})]}):null,(0,K.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:t.useTreeLevels&&w.rootsPending?(0,K.jsx)(`div`,{className:`p-2`,children:(0,K.jsx)(vji,{label:`Loading pages`,rows:6})}):(0,K.jsx)(KAi,{pages:ze,pinnedIds:e.pinnedIds,selectedPageId:n,onSelect:Pe,initiallyExpanded:Re?[Re.id]:void 0,...t.useTreeLevels?{mayHaveChildren:w.mayHaveChildren,onExpandedChange:w.onExpandedChange,loadMore:w.loadMore}:{}},Re?Re.id:`all`)})]}),tt=Ke?L.get(Ke)??w.pages.find(e=>e.id===Ke):void 0;return(0,K.jsx)(oOi.Provider,{value:N,children:(0,K.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col ${s?``:`gap-2`}`,children:[(0,K.jsxs)(_K,{className:s?`shrink-0 border-b border-surface-rim px-3 py-2`:void 0,children:[(0,K.jsxs)(_K.Start,{children:[(0,K.jsx)(uk,{ref:be,value:Ue,defaultTab:Ue,onValueChange:e=>a(e),"aria-label":`View`,children:(0,K.jsx)(lk,{variant:`pill-ghost`,size:`sm`,children:He.map(e=>(0,K.jsxs)(dk,{value:e.value,disabled:e.value===`page`&&!n,className:e.narrowOnly?`lg:hidden`:void 0,children:[(0,K.jsx)(xx,{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)(_K.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&&mji(u.error)?(0,K.jsx)(T,{role:`alert`,variant:`caption`,className:`text-destructive-foreground ${s?`px-3 pt-2`:``}`,children:`Page not found. The linked page may have been deleted or merged.`}):null,(0,K.jsxs)(`div`,{style:Je,className:`relative flex min-h-0 flex-1 flex-col gap-3 lg:flex-row`,children:[he?(0,K.jsx)(`div`,{inert:Qe,"aria-hidden":Qe||void 0,"data-state":Qe?`closed`:`open`,className:`absolute inset-y-2 left-2 z-10 flex w-72 transition duration-slow ease-out-custom motion-reduce:transition-none ${Qe?`pointer-events-none -translate-x-4 opacity-0`:`translate-x-0 opacity-100`}`,children:(0,K.jsxs)(dQ,{variant:`inline`,title:`Pages`,className:`shadow-overlay`,children:[$e,et]})}):(0,K.jsx)(`aside`,{"aria-label":`Pages`,className:`min-h-0 w-full flex-1 flex-col overflow-hidden rounded-lg border border-border bg-card lg:w-72 lg:flex-none lg:shrink-0 ${l===`tree`?`flex`:`hidden`}`,children:et}),he?(0,K.jsx)(X,{tooltip:`Show pages`,"aria-label":`Show pages`,size:`icon-sm`,inert:!Qe,"aria-hidden":!Qe||void 0,className:`absolute top-3 left-3 z-10 shadow-overlay transition-opacity duration-slow ease-out-custom motion-reduce:transition-none ${Qe?`opacity-100`:`pointer-events-none opacity-0`}`,ref:xe,onClick:()=>Ze(!0),children:(0,K.jsx)(qAi,{})}):null,Te&&!he?(0,K.jsx)(`section`,{ref:Xe,"aria-label":`Selected page`,className:`flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-lg border border-border bg-card`,children:(0,K.jsx)(Aji,{source:t,pageId:n,pagesById:L,onSelect:Ie,highlightMentionOf:we})}):(0,K.jsxs)(`div`,{className:`relative min-h-0 min-w-0 flex-1 overflow-hidden bg-sidebar lg:block lg:h-full ${s?``:`rounded-xl border border-border`} ${l===`graph`||We?`block`:`hidden`}`,"data-testid":`knowledge-graph-container`,children:[me&&!We?(0,K.jsx)(`div`,{className:`absolute top-3 right-3 z-10 -translate-x-(--knowledge-drawer-inset) transition-transform duration-slow ease-out-custom motion-reduce:transition-none`,children:(0,K.jsxs)(GV,{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)(tS,{})}),(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)(YX,{})}),(0,K.jsx)(X,{"aria-label":`Link counts`,"aria-pressed":S,"data-testid":`knowledge-graph-dot-counts`,tooltip:S?`Hide link counts`:`Show link counts on each dot`,tooltipPosition:`left`,size:`icon-sm`,className:S?`[--control-icon:var(--foreground)]`:void 0,onClick:()=>C(e=>!e),children:(0,K.jsx)(Z4,{})})]})}):null,me&&!We?(0,K.jsx)(BAi,{pages:Be,edges:ee,pinnedIds:e.pinnedIds,grants:e.grants,selectedPageId:n,centerId:I.hub,hiddenLinks:ne,knownLinks:V,fetchedLinks:ce,exactLinkCounts:W,onHover:oe,nearIds:F,settled:D,insets:qe,collapsibleLegend:he,showCounts:S,onPreview:e=>{v9(e)&&e.parentId&&R(e.parentId)},onSelect:e=>{if(v9(e))return e.parentId?R(e.parentId):void 0;if(y9(e)){let t=e.parentId;return t?(y(e=>new Map(e).set(t,(e.get(t)??0)+12)),w.loadMore.get(t)?.()):void 0}if(b9(e))return _(t=>new Set(t).add(e.id));Ne(e.id)},onOpen:e=>Me(e.id),onClearSelection:()=>{ue(null),n&&r(null)},onMentionSelect:ue}):null,he?(0,K.jsx)(`div`,{inert:!Ge,"aria-hidden":!Ge||void 0,"data-state":Ge?`open`:`closed`,onTransitionEnd:e=>{!Ge&&e.target===e.currentTarget&&ye(void 0)},className:`absolute inset-y-2 right-2 z-10 flex w-96 transition duration-slow ease-out-custom motion-reduce:transition-none ${Ge?`translate-x-0 opacity-100`:`pointer-events-none translate-x-4 opacity-0`}`,children:Ke?(0,K.jsxs)(dQ,{variant:`inline`,title:`Page details`,className:`shadow-overlay`,children:[(0,K.jsxs)(dQ.Header,{children:[(0,K.jsx)(dQ.Heading,{className:`min-w-0 flex-1 shrink`,children:(0,K.jsx)(`span`,{className:`truncate`,children:tt?.name??`Page`})}),(0,K.jsxs)(dQ.HeaderActions,{children:[(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`Open page`,"aria-label":`Open page`,onClick:()=>{Ce.current=!0,Me(Ke)},children:(0,K.jsx)(qN,{})}),(0,K.jsx)(dQ.CloseButton,{icon:`x`,label:`Close page details`,tooltip:`Close`,onClick:()=>{Ye(),r(null)}})]})]}),(0,K.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden`,children:(0,K.jsx)(Aji,{source:t,pageId:Ke,pagesById:L,onSelect:Le,highlightMentionOf:we,compact:!0,onOpenPage:()=>{Ce.current=!0,Me(Ke)}})})]}):null}):null,We?(0,K.jsx)(`section`,{ref:Xe,"aria-label":`Selected page`,className:`absolute inset-y-2 right-2 left-[calc(var(--knowledge-tree-inset)+0.5rem)] z-20 flex transition-[left] duration-slow ease-out-custom motion-reduce:transition-none`,children:(0,K.jsxs)(dQ,{variant:`inline`,title:`Page`,className:`shadow-overlay`,children:[(0,K.jsxs)(dQ.Header,{children:[(0,K.jsx)(dQ.Heading,{children:`Page`}),(0,K.jsx)(dQ.HeaderActions,{children:(0,K.jsx)(dQ.CloseButton,{icon:`x`,label:`Close page`,tooltip:`Close`,onClick:()=>{Ye(),a(`graph`)}})})]}),(0,K.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden`,children:(0,K.jsx)(Aji,{source:t,pageId:n,pagesById:L,onSelect:Ie,highlightMentionOf:we})})]})}):null,le&&me?(0,K.jsx)(kji,{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,M9=e=>e?Vji:Bji,Wji=e=>e instanceof Wf&&(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=s_(),[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 S_({queryKey:[`knowledge`,`instances`],queryFn:async()=>(await e.listKnowledge()).instances})}function Xji(e,t){let n=Y();return S_({queryKey:[`knowledge`,e,`graph`],queryFn:e?async()=>n.getKnowledge(e).graph():h_,refetchInterval:M9(t)})}function Zji(e,t,n,r){let i=Y();return S_({queryKey:[`knowledge`,e,`page`,n,r??null],queryFn:e&&n?async()=>i.getKnowledge(e).page(n,{noteCursor:r}):h_,refetchInterval:!r&&M9(t)})}function Qji(e,t){let n=Y();return x_({queries:t.map(t=>({queryKey:[`knowledge`,e,`page`,t,null],queryFn:e?async()=>n.getKnowledge(e).page(t):h_,retry:(e,t)=>!(t&&`status`in t&&t.status===404)&&e<2,staleTime:3e4}))})}function $ji(e,t,n){let r=Y();return x_({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}):h_,refetchInterval:!n.cursor&&M9(t)}))})}var eMi=200,tMi=(e,t)=>!Wji(t)&&e<2;function nMi(e,t,n){let r=Y();return S_({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))}:h_,placeholderData:m_,retry:tMi,refetchInterval:M9(t)})}function rMi(e,t){let n=Y();return S_({queryKey:[`knowledge`,e,`page-links`,t],queryFn:e&&t?async()=>n.getKnowledge(e).pageLinks(t):h_,staleTime:3e4,retry:tMi})}function iMi(e,t,n){let r=Y();return S_({queryKey:[`knowledge`,e,`activity`,n],queryFn:e?async()=>r.getKnowledge(e).activity({pageId:n}):h_,refetchInterval:M9(t)})}function aMi(e,t){let n=Y(),r=t.trim();return S_({queryKey:[`knowledge`,e,`search`,r],queryFn:e&&r.length>=zji?async()=>n.getKnowledge(e).search(r):h_,placeholderData:m_})}var oMi=[KN(`/knowledge`)];function N9({children:e}){return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:oMi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Knowledge`}),e]})}function sMi({knowledgeKey:e,live:t,graph:n}){let[r,i]=Mv(),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]=Mv(),n=Yji(),r=e.get(`instance`)??n.data?.[0]?.key,i=Jji(r),a=Xji(r,i),o=n.error??a.error;return o&&DN(o)?(0,K.jsx)(N9,{children:(0,K.jsx)(_H,{variant:`fill`})}):o&&ON(o)?(0,K.jsx)(N9,{children:(0,K.jsx)(gH,{variant:`fill`,resource:`knowledge`})}):n.error&&!n.data&&kN(n.error)?(0,K.jsx)(N9,{children:(0,K.jsx)(Hx,{variant:`fill`,titleSlot:`Knowledge browsing is not enabled`,descriptionSlot:`This server does not register the Knowledge routes. Add KNOWLEDGE_ROUTES from @mastra/server/server-adapter to server.apiRoutes, then reload.`})}):n.error&&!n.data?(0,K.jsx)(N9,{children:(0,K.jsx)(Hx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load Knowledge`,descriptionSlot:n.error.message})}):n.data&&n.data.length===0?(0,K.jsx)(N9,{children:(0,K.jsx)(Hx,{variant:`fill`,titleSlot:`No Knowledge instances`,descriptionSlot:`Register one on your Mastra instance with the knowledge option to browse it here.`})}):(0,K.jsx)(N9,{children:(0,K.jsxs)(`div`,{className:`flex h-full min-h-0 flex-1 flex-col gap-3`,children:[n.data&&n.data.length>1?(0,K.jsx)(`select`,{"aria-label":`Knowledge instance`,className:`text-ui-md h-8 w-fit rounded border border-border bg-card px-2`,value:r,onChange:e=>t(new URLSearchParams({instance:e.target.value})),children:n.data.map(e=>(0,K.jsx)(`option`,{value:e.key,children:e.key},e.key))}):null,!r||a.isPending?(0,K.jsx)(`p`,{className:`text-ui-md p-4 text-muted-foreground`,children:`Loading knowledge…`}):a.data?a.data.pages.length===0?(0,K.jsx)(Hx,{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)(Hx,{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)(LZ,{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}=D_(),{mutate:o,isPending:s,error:c}=HFe(),{mutate:l,isPending:u,error:d}=WFe(),{mutate:f,isPending:p}=GFe(),[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=RZ(`/`)},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)(hH,{className:`mt-0.5 size-icon-md shrink-0 text-muted-foreground`}),(0,K.jsx)(T,{tone:`muted`,children:S.description})]}):null;return(0,K.jsxs)(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)(gk,{variant:`destructive`,children:r})}):null,children:[w&&(0,K.jsxs)(UV,{onSubmit:M,children:[!O&&(0,K.jsxs)($O,{children:[(0,K.jsx)(tk,{children:`Name`}),(0,K.jsx)(Hj,{name:`name`,type:`text`,autoComplete:`name`,value:g,onChange:e=>_(e.target.value),placeholder:`Your name`,variant:`default`,size:`lg`})]}),(0,K.jsxs)($O,{children:[(0,K.jsx)(tk,{required:!0,children:`Email`}),(0,K.jsx)(Hj,{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)(rk,{})]}),(0,K.jsxs)($O,{children:[(0,K.jsx)(tk,{required:!0,children:`Password`}),(0,K.jsx)(Hj,{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)(rk,{})]}),A?(0,K.jsx)(`div`,{role:`alert`,children:(0,K.jsx)(gk,{variant:`destructive`,children:A.message})}):null,(0,K.jsx)(X,{icon:(0,K.jsx)(Ymn,{}),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]=Mv(),t=Tv(),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)(hw,{}),children:`Clear`}),a&&(0,K.jsxs)(ZT,{children:[(0,K.jsx)(ZT.Trigger,{asChild:!0,children:(0,K.jsx)(X,{disabled:e,size:`icon-md`,"aria-label":`More filter actions`,children:(0,K.jsx)(QT,{})})}),(0,K.jsxs)(ZT.Content,{align:`end`,children:[n&&(0,K.jsxs)(ZT.Item,{onSelect:()=>n(),children:[(0,K.jsx)(hw,{}),`Remove all filters`]}),n&&(r||i)&&(0,K.jsx)(ZT.Separator,{}),r&&(0,K.jsxs)(ZT.Item,{onSelect:()=>r(),children:[(0,K.jsx)(W4,{}),`Save filters for next time`]}),i&&(0,K.jsxs)(ZT.Item,{onSelect:()=>i(),children:[(0,K.jsx)(Bj,{}),`Remove saved filters`]})]})]})]})}var pMi=c(CT,`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:TT,children:(0,K.jsx)(sC,{})})]})}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]),l=typeof s?.value==`string`?s.value:e.multi?void 0:e.defaultValue,u=(0,G.useMemo)(()=>{let e=s?.value;return Array.isArray(e)?e:typeof e==`string`?[e]:[]},[s]);return(0,K.jsxs)(K.Fragment,{children:[e.searchable!==!1&&(0,K.jsxs)(`div`,{className:kT.container,children:[(0,K.jsx)(QM,{className:kT.icon}),(0,K.jsx)(`input`,{type:`text`,value:r,onChange:e=>i(e.target.value),placeholder:`Search ${e.label.toLowerCase()}`,className:kT.input,...zk,onKeyDown:e=>{if(e.key!==`ArrowDown`)return;let t=e.currentTarget.closest(`[data-pick-multi-panel]`)?.querySelector(`[data-pick-multi-item]:not([disabled])`);t&&(e.preventDefault(),e.stopPropagation(),t.focus())}})]}),e.isLoading?(0,K.jsxs)(`div`,{className:c(a8e,`m-1`),children:[(0,K.jsx)(It,{size:`sm`,className:`size-3 text-muted-foreground`}),`Loading options…`]}):o.length===0?(0,K.jsx)(`div`,{className:c(a8e,`m-1`),children:e.emptyText??`No option found.`}):e.multi?(0,K.jsx)(`div`,{className:a,children:(0,K.jsx)(K.Fragment,{children:o.map(t=>{let r=u.includes(t.value);return(0,K.jsx)(mMi,{role:`checkbox`,checked:r,label:t.label,onClick:()=>n(e.id,r?u.filter(e=>e!==t.value):[...u,t.value])},t.value)})})}):(0,K.jsx)(`div`,{role:`radiogroup`,className:a,children:(0,K.jsxs)(K.Fragment,{children:[o.map(t=>(0,K.jsx)(mMi,{role:`radio`,checked:l===t.value,label:t.label,onClick:()=>n(e.id,t.value)},t.value)),!e.omitAnyOption&&(0,K.jsx)(mMi,{role:`radio`,checked:l===`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)(gx,{delayDuration:150,children:(0,K.jsxs)(_x,{children:[(0,K.jsx)(vx,{asChild:!0,children:(0,K.jsxs)(GV,{"data-locked-field-id":e.id,"data-property-filter-pill":`locked`,tabIndex:0,"aria-label":i,children:[(0,K.jsx)(KV,{children:e.label}),(0,K.jsx)(KV,{children:`is`}),(0,K.jsx)(KV,{children:r}),(0,K.jsx)(KV,{children:(0,K.jsx)(hH,{})})]})}),(0,K.jsx)(yx,{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)(GV,{children:[(0,K.jsx)(KV,{children:e.label}),(0,K.jsx)(KV,{children:`is`}),(0,K.jsx)(Hj,{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)(hw,{})})]})}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)(GV,{children:[(0,K.jsx)(KV,{children:e.label}),(0,K.jsx)(KV,{children:`is`}),(0,K.jsxs)(Wj,{open:o,onOpenChange:s,children:[(0,K.jsx)(Gj,{asChild:!0,children:(0,K.jsx)(X,{type:`button`,disabled:a,children:gMi(t.value)})}),(0,K.jsx)(Kj,{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)(hw,{})})]})}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)(GV,{children:[(0,K.jsx)(KV,{children:u.label}),(0,K.jsx)(KV,{children:`is`}),(0,K.jsx)(KV,{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)(hw,{})})]},`${n.fieldId}-${a}`):null})})}var CMi=U(`IconFilter1`,()=>(0,K.jsx)(`path`,{d:`M18 4H6C4.89543 4 4 4.89543 4 6V7.17157C4 7.70201 4.21071 8.21071 4.58579 8.58579L9.41421 13.4142C9.78929 13.7893 10 14.298 10 14.8284V20.057C10 20.7552 10.6974 21.2385 11.3511 20.9933L13.3511 20.2433C13.7414 20.097 14 19.7238 14 19.307V14.8284C14 14.298 14.2107 13.7893 14.5858 13.4142L19.4142 8.58579C19.7893 8.21071 20 7.70201 20 7.17157V6C20 4.89543 19.1046 4 18 4Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinejoin:`round`})),wMi=(0,G.forwardRef)((e,t)=>(0,K.jsx)(`button`,{type:`button`,role:`menuitem`,"data-filter-item":``,ref:t,...e}));wMi.displayName=`FilterMenuButton`;function TMi({fields:e,tokens:t,onTokensChange:n,label:r=`Add filter`,disabled:i,size:a,onStartTextFilter:o,hiddenFieldIds:s}){let l=(0,G.useMemo)(()=>{if(!s||s.length===0)return e;let t=new Set(s);return e.filter(e=>!t.has(e.id))},[e,s]),[u,d]=(0,G.useState)(!1),[f,p]=(0,G.useState)(),[m,h]=(0,G.useState)([]),[g,_]=(0,G.useState)(),[v,y]=(0,G.useState)(),b=(0,G.useRef)(!1),x=(0,G.useCallback)(e=>{y(t=>t===e?void 0:e)},[]),S=(0,G.useCallback)(()=>y(void 0),[]);(0,G.useEffect)(()=>{u||y(void 0)},[u]);let C=(0,G.useMemo)(()=>l.find(e=>e.id===f),[l,f]),w=(0,G.useMemo)(()=>{let n=new Set;for(let r of t){let t=e.find(e=>e.id===r.fieldId);t&&t.kind!==`pick-multi`&&n.add(r.fieldId)}return n},[t,e]),E=(0,G.useCallback)(()=>{p(void 0),h([]),_(void 0)},[]);(0,G.useEffect)(()=>{u||E()},[u,E]);let D=(0,G.useCallback)((e,r)=>{let i=t.findIndex(t=>t.fieldId===e);if(Array.isArray(r)&&r.length===0){if(i===-1)return;n(t.filter((e,t)=>t!==i));return}if(i===-1){n([...t,{fieldId:e,value:r}]);return}let a=[...t];a[i]={fieldId:e,value:r},n(a)},[n,t]),O=(0,G.useCallback)(()=>{C?w.has(C.id)?_(`Remove the existing ${C.label} filter before adding another.`):m.length===0?_(`Choose at least one ${C.label.toLowerCase()} value.`):(n([...t,{fieldId:C.id,value:m}]),d(!1)):_(`Choose a property first.`)},[m,n,C,w,t]);return(0,K.jsxs)(Wj,{open:u,onOpenChange:d,children:[(0,K.jsx)(Gj,{asChild:!0,children:(0,K.jsx)(X,{size:a,disabled:i,icon:(0,K.jsx)(DZ,{}),children:r})}),(0,K.jsx)(Kj,{align:`start`,sideOffset:4,className:c(`w-64`,C?`p-3`:`p-1`),initialFocus:!1,finalFocus:()=>!b.current||(b.current=!1,!1),children:(0,K.jsxs)(`div`,{className:c(`grid`,C&&`gap-3`),children:[C&&(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`button`,{type:`button`,"aria-label":`Back to properties`,className:c(`text-muted-foreground hover:text-foreground`,`transition-[color] duration-fast ease-out-custom motion-reduce:transition-none`),onClick:E,children:(0,K.jsx)(tS,{className:`size-icon-md`})}),(0,K.jsx)(CMi,{className:`size-icon-md shrink-0 text-muted-foreground`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:`${C.label} is`})]}),!C&&(0,K.jsx)(`div`,{role:`menu`,className:`max-h-[80dvh] overflow-auto`,onKeyDown:e=>{if(e.key!==`ArrowDown`&&e.key!==`ArrowUp`&&e.key!==`Home`&&e.key!==`End`)return;let t=Array.from(e.currentTarget.querySelectorAll(`[data-filter-item]:not([disabled])`));if(t.length===0)return;e.preventDefault();let n=document.activeElement,r=t.findIndex(e=>e===n),i;i=e.key===`Home`?0:e.key===`End`?t.length-1:e.key===`ArrowDown`?r<0?0:(r+1)%t.length:r<=0?t.length-1:r-1,t[i]?.focus()},children:(0,K.jsx)(K.Fragment,{children:l.length>0?l.map(e=>{let r=w.has(e.id);return e.kind===`pick-multi`?(0,K.jsx)(EMi,{field:e,tokens:t,onChange:D,open:v===e.id,onToggle:x,onClose:S},e.id):(0,K.jsxs)(wMi,{className:c(CT,`group`),disabled:r,onClick:()=>{_(void 0),e.kind===`text`?(n([...t,{fieldId:e.id,value:``}]),o?.(e.id),b.current=!0,d(!1)):p(e.id)},children:[(0,K.jsx)(`span`,{className:`truncate`,children:e.label}),r?(0,K.jsx)(`span`,{className:`ml-auto text-muted-foreground`,children:`In use`}):(0,K.jsx)(`span`,{className:c(wT,`text-muted-foreground opacity-0 group-hover:opacity-100 group-focus:opacity-100`),children:(0,K.jsx)(Ix,{})})]},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)($O,{invalid:!!g,children:[(0,K.jsx)(lN,{multiple:!0,options:C.options??[],value:m,onValueChange:e=>{h(e),_(void 0)},placeholder:C.placeholder??`Choose ${C.label}`,searchPlaceholder:`Search ${C.label.toLowerCase()}`,emptyText:C.emptyText??`No option found.`,size:`md`,"aria-label":C.label}),(0,K.jsx)(rk,{children:g})]}),C&&(0,K.jsxs)(`div`,{className:`flex items-center justify-end gap-2`,children:[(0,K.jsx)(X,{icon:(0,K.jsx)(hw,{}),variant:`ghost`,size:`md`,onClick:()=>d(!1),children:`Cancel`}),(0,K.jsx)(X,{icon:(0,K.jsx)(DZ,{}),size:`md`,onClick:O,children:`Add filter`})]})]})})]})}function EMi({field:e,tokens:t,onChange:n,open:r,onToggle:i,onClose:a}){let o=(0,G.useRef)(null);return(0,K.jsxs)(Wj,{open:r,onOpenChange:t=>{t?i(e.id):a()},children:[(0,K.jsx)(Gj,{asChild:!0,children:(0,K.jsxs)(wMi,{className:CT,onKeyDown:t=>{(t.key===`ArrowRight`||t.key===`ArrowLeft`)&&(r||i(e.id),t.preventDefault(),requestAnimationFrame(()=>{(o.current?.querySelector(`input, button, [tabindex]:not([tabindex="-1"])`))?.focus()}))},children:[r&&(0,K.jsx)(f,{className:`text-muted-foreground`}),(0,K.jsx)(`span`,{className:`truncate`,children:e.label}),!r&&(0,K.jsx)(`span`,{className:c(wT,`text-muted-foreground`),children:(0,K.jsx)(f,{})})]})}),(0,K.jsx)(Kj,{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 DMi({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:i,onNext:a,depth:o,actions:s}){let c=e?hC(e.timestamp)??``:``;return(0,K.jsx)(dQ,{open:!!e,onClose:t,title:e?`Log ${c}`:`Log`,depth:o,children:e&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(dQ.Header,{children:[(0,K.jsx)(dQ.CloseButton,{onClick:t}),(0,K.jsx)(dQ.Heading,{children:`Log`}),(0,K.jsx)(dQ.Metadata,{children:(0,K.jsx)(dQ.Meta,{tooltip:c,children:c})}),(0,K.jsxs)(dQ.HeaderActions,{children:[s,(0,K.jsx)(dQ.NextPrevNav,{onPrevious:i,onNext:a,previousLabel:`Go to previous log`,nextLabel:`Go to next log`})]})]}),(0,K.jsx)(dQ.Content,{children:(0,K.jsxs)(`div`,{className:`grid gap-6 p-2`,children:[(0,K.jsxs)(V4,{children:[e.entityType&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(V4.Key,{children:`Entity Type`}),(0,K.jsx)(V4.Value,{children:e.entityType})]}),e.entityName&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(V4.Key,{children:`Entity Name`}),(0,K.jsx)(V4.Value,{children:e.entityName})]}),e.serviceName&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(V4.Key,{children:`Service`}),(0,K.jsx)(V4.Value,{children:e.serviceName})]}),e.environment&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(V4.Key,{children:`Environment`}),(0,K.jsx)(V4.Value,{children:e.environment})]}),e.source&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(V4.Key,{children:`Source`}),(0,K.jsx)(V4.Value,{children:e.source})]}),e.metadata&&Object.entries(e.metadata).map(([e,t])=>(0,K.jsxs)(G.Fragment,{children:[(0,K.jsx)(V4.Key,{children:e}),(0,K.jsx)(V4.Value,{children:String(t)})]},e))]}),(0,K.jsx)(dQ.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)(GV,{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)(QV,{}),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)(uC,{content:e.traceId,tooltip:`Copy trace ID to clipboard`})]}),e.spanId&&(0,K.jsxs)(GV,{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)(QV,{}),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)(uC,{content:e.spanId,tooltip:`Copy span ID to clipboard`})]})]}),e.data&&Object.keys(e.data).length>0&&(0,K.jsx)(dQ.CodeSection,{title:`Data`,codeStr:JSON.stringify(e.data,null,2)})]})})]})})}function OMi({error:e,resource:t,errorTitle:n}){if(DN(e))return(0,K.jsx)(_H,{});if(ON(e))return(0,K.jsx)(gH,{resource:t});if(jN(e))return(0,K.jsx)(Hx,{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(AN(e,`logs`))return(0,K.jsx)(Hx,{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)(Hx,{tone:`error`,titleSlot:n,descriptionSlot:r??`Unknown error`})}var kMi={debug:`neutral`,info:`info`,warn:`warning`,error:`destructive`,fatal:`destructive`};function AMi({level:e}){return(0,K.jsx)(nH,{children:(0,K.jsx)(JS,{variant:kMi[e],children:e})})}function jMi({entityType:e,className:t}){let n=c(`size-3.5 shrink-0 text-placeholder`,t);switch(e.toLowerCase()){case`agent`:return(0,K.jsx)(PN,{className:n,"aria-hidden":!0});case`workflow`:case`workflow_run`:return(0,K.jsx)(GS,{className:n,"aria-hidden":!0});case`tool`:return(0,K.jsx)(HN,{className:n,"aria-hidden":!0});default:return null}}function MMi({entityType:e,entityName:t}){return(0,K.jsxs)(nH,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(jMi,{entityType:e??``}),t?(0,K.jsx)(T,{as:`span`,variant:`body-sm`,className:`min-w-0 truncate`,children:t}):`-`]})}function NMi({message:e}){return(0,K.jsx)(nH,{className:`min-w-0 truncate font-mono text-body-sm text-muted-foreground`,children:e})}function PMi({data:e}){if(!e||Object.keys(e).length===0)return(0,K.jsx)(nH,{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)(aH,{font:`mono`,children:t})}var P9=Object.assign(lH,{Top:mH,TopCell:dH,SortableTopCell:pH,TopCellWithTooltip:fH,TopCellSmart:Lmn,RowWrapper:Mmn,RowButton:uH,RowLink:Amn,Spacer:Umn,NoMatch:sH,DateCell:Qpn,TimeCell:emn,LevelCell:AMi,EntityCell:MMi,MessageCell:NMi,DataCell:PMi,NextPageLoading:oH}),FMi=`6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)`,IMi=36,LMi=8;function RMi({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=O9r({count:e.length,getScrollElement:()=>u.current,estimateSize:()=>IMi,overscan:LMi}),{getRowProps:f}=OZ({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)(yH,{columns:FMi,fit:`container`});let m=d.getVirtualItems(),h=d.getTotalSize(),g=m[0]?.start??0,_=m.length>0?Math.max(0,h-(m[m.length-1]?.end??0)):0;return(0,K.jsxs)(P9,{columns:FMi,scrollRef:u,className:`min-w-0`,fit:`container`,children:[(0,K.jsxs)(P9.Top,{children:[l?(0,K.jsx)(P9.SortableTopCell,{sortKey:`timestamp`,sort:c,onSortChange:l,children:`Date`}):(0,K.jsx)(P9.TopCell,{children:`Date`}),(0,K.jsx)(P9.TopCell,{children:`Time`}),(0,K.jsx)(P9.TopCell,{children:`Level`}),(0,K.jsx)(P9.TopCell,{children:`Entity`}),(0,K.jsx)(P9.TopCell,{children:`Message`}),(0,K.jsx)(P9.TopCell,{children:`Data`})]}),e.length===0?(0,K.jsx)(P9.NoMatch,{message:`No logs match your search`}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(P9.Spacer,{height:g}),m.map(t=>{let n=e[t.index];if(!n)return null;let r=a.get(n);if(!r)return null;let i=r===o;return(0,K.jsxs)(P9.RowButton,{ref:d.measureElement,"data-index":t.index,...f(t.index),onClick:()=>s(n),featured:i,variant:n.level===`error`||n.level===`fatal`?`error`:`default`,children:[(0,K.jsx)(P9.DateCell,{timestamp:n.timestamp}),(0,K.jsx)(P9.TimeCell,{timestamp:n.timestamp}),(0,K.jsx)(P9.LevelCell,{level:n.level}),(0,K.jsx)(P9.EntityCell,{entityType:n.entityType,entityName:n.entityName}),(0,K.jsx)(P9.MessageCell,{message:n.message}),(0,K.jsx)(P9.DataCell,{data:n.data})]},r)}),(0,K.jsx)(P9.Spacer,{height:_})]}),(0,K.jsx)(P9.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:i})]})}function zMi({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:i,filterFields:a,filterTokens:o,onFilterTokensChange:s,autoFocusFilterFieldId:l}){let u=o.length>0,d=o.some(e=>BMi(e,a));return u?(0,K.jsxs)(`div`,{className:c(`grid grid-cols-[1fr_auto] items-start gap-3`),children:[(0,K.jsx)(SMi,{fields:a,tokens:o,onTokensChange:s,disabled:i,autoFocusFieldId:l}),u&&(0,K.jsx)(fMi,{disabled:i,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]}):null}function BMi(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 VMi={"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`},HMi=`Pick a wider range or lower the logging level. Verbose entries (debug, info) may be filtered out.`;function UMi({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!==`all`&&e!==`custom`?{title:`No logs for ${VMi[e]}`,description:HMi}:t&&n?{title:`No logs between ${mC(t,`date-time`)} and ${mC(n,`date-time`)}`,description:HMi}:t?{title:`No logs since ${mC(t,`date-time`)}`,description:HMi}:{title:`No logs yet`,description:`Logs will appear here once agents, workflows, or tools are executed.`}}var WMi=({datePreset:e,dateFrom:t,dateTo:n}={})=>{let{title:r,description:i}=UMi({datePreset:e,dateFrom:t,dateTo:n});return(0,K.jsx)(Hx,{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)(qN,{}),children:`Logging documentation`}),variant:`fill`})},GMi=`Filters setting for Logs saved`,KMi=`Filters setting for Logs cleared up`;function qMi(e,t,n){let{storageKey:r,messages:i,skipHydration:a}=n??{},[o,s]=(0,G.useState)(()=>Vai(r)!==null),c=(0,G.useCallback)(()=>{zai(e,r),s(!0);let t=i?.saved??GMi;t!==!1&&Qx.success(t)},[e,r,i?.saved]),l=(0,G.useCallback)(()=>{Bai(r),s(!1);let e=i?.cleared??KMi;e!==!1&&Qx.success(e)},[r,i?.cleared]),u=(0,G.useRef)(!1);return(0,G.useEffect)(()=>{if(a||u.current||(u.current=!0,Hai(e)))return;let n=Vai(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 JMi(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 YMi(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,JMi(`${e}${n.message??``}${n.data?JSON.stringify(n.data):``}`))}return t}function XMi(e,t,n,r){let i=(0,G.useMemo)(()=>YMi(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 ZMi=`logId`,QMi=`traceId`,$Mi=`spanId`,F9=864e5,eNi={"last-24h":F9,"last-3d":3*F9,"last-7d":7*F9,"last-14d":14*F9,"last-30d":30*F9};function tNi(e){e.delete(ZMi),e.delete(QMi),e.delete($Mi)}function nNi(e,t,n){let{onRemoveAll:r}=n??{},i=(0,G.useMemo)(()=>{let t=e.get(o7);return t&&Iai.has(t)?t:Nai},[e]),a=e.get(s7),o=e.get(c7),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=eNi[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(ZMi),d=e.get(QMi),f=e.get($Mi),p=(0,G.useMemo)(()=>jai.find(t=>t.entityType===e.get(a7)),[e]),m=(0,G.useMemo)(()=>Wai(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`?ZMi:t===`traceId`?QMi:$Mi;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 Kai(n,e),tNi(n),n},{replace:!0})},[t]),_=g,v=(0,G.useCallback)((e,n)=>{if(l.current!==`custom`)return;let r=n===`from`?s7:c7;t(t=>{let n=new URLSearchParams(t);return e?n.set(r,e.toISOString()):n.delete(r),tNi(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(o7),n.delete(s7),n.delete(c7)):e===`custom`?n.set(o7,`custom`):(n.set(o7,e),n.delete(s7),n.delete(c7)),tNi(n),n},{replace:!0})},[t]),b=(0,G.useCallback)(()=>{t(e=>{let t=new URLSearchParams(e);t.delete(a7);for(let e of u7)t.delete(l7[e]);return t.delete(o7),t.delete(s7),t.delete(c7),tNi(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 rNi=20,iNi=1e4,aNi={field:`timestamp`,direction:`DESC`};function oNi(e,t,n){if(e?.pagination?.hasMore)return n+1}function sNi(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 cNi(e){return AN(e.state.error,`logs`)||jN(e.state.error)?!1:iNi}var lNi=({filters:e,orderBy:t=aNi,queryOptions:n}={})=>{let r=Y(),{inView:i,setRef:a}=GM(),{hasNextPage:o,isFetchingNextPage:s,fetchNextPage:c,data:l,isLoading:u,isError:d,error:f}=T_({queryKey:[`logs`,e,t],queryFn:({pageParam:n})=>r.listLogsVNext({pagination:{page:n,perPage:rNi},filters:e,orderBy:t}),initialPageParam:0,getNextPageParam:oNi,select:sNi,retry:!1,refetchInterval:cNi,...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}},uNi=[KN(`/logs`)];function dNi(){let[e,t]=Mv(),n=nNi(e,t),{sort:r,onSortChange:i}=r7({searchParams:e,setSearchParams:t,allowedKeys:Pai,defaultSort:Fai}),a=(0,G.useMemo)(()=>({field:`timestamp`,direction:r?.direction===`asc`?`ASC`:`DESC`}),[r?.direction]),o=qMi(e,t),[s,c]=(0,G.useState)(),{data:l=[],isPending:u}=HXr(),{data:d=[],isPending:f}=t8({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:p=[],isPending:m}=n8(),{data:h=[],isPending:g}=BXr(),_=(0,G.useMemo)(()=>Uai({availableTags:l,availableRootEntityNames:d,availableServiceNames:h,availableEnvironments:p,loading:{tags:u,entityNames:f,serviceNames:g,environments:m}}),[l,d,h,p,u,f,g,m]),{data:v=[],isLoading:y,error:b,isFetchingNextPage:x,hasNextPage:S,setEndOfListElement:C}=lNi({filters:(0,G.useMemo)(()=>qai({rootEntityType:n.selectedEntityOption?.entityType,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,tokens:n.filterTokens}),[n.filterTokens,n.selectedDateFrom,n.selectedDateTo,n.selectedEntityOption]),orderBy:a}),{logIdMap:w,featuredLog:T,handleLogClick:E,handlePreviousLog:D,handleNextLog:O}=XMi(v,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:k,isLoading:A}=i8({traceId:n.featuredTraceId??null,queryOptions:{enabled:!!n.featuredTraceId}}),j=(0,G.useCallback)(()=>n.applyFilterTokens(Jai(_,n.filterTokens)),[_,n]),M=(0,G.useCallback)(()=>n.handleFeaturedChange({logId:null}),[n]),N=(0,G.useCallback)(e=>n.handleFeaturedChange({traceId:e,spanId:null}),[n]),P=(0,G.useCallback)((e,t)=>n.handleFeaturedChange({traceId:e,spanId:t}),[n]),F=(0,G.useCallback)(()=>n.handleFeaturedChange({traceId:null,spanId:null}),[n]),I=(0,G.useCallback)(e=>n.handleFeaturedChange({spanId:e??null}),[n]),L=(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(_K,{children:(0,K.jsxs)(_K.Start,{children:[(0,K.jsx)(agn,{preset:n.datePreset,onPresetChange:n.handleDatePresetChange,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,onDateChange:n.handleDateChange,disabled:y,presets:[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`]}),(0,K.jsx)(TMi,{fields:_,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:y,onStartTextFilter:c,size:`sm`})]})}),(0,K.jsx)(zMi,{isLoading:y,filterFields:_,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:j,onRemoveAll:n.handleRemoveAll,onSave:o.handleSave,onRemoveSaved:o.hasSavedFilters?o.handleRemoveSaved:void 0,autoFocusFilterFieldId:s})]});if(b)return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:uNi}),actionRow:L,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)(OMi,{error:b,resource:`logs`,errorTitle:`Failed to load logs`})})]});let R=!!n.selectedEntityOption||n.filterTokens.length>0;return v.length===0&&!y&&!R?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:uNi}),actionRow:L,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Logs`}),(0,K.jsx)(WMi,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})]}):(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:uNi}),actionRow:L,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Logs`}),(0,K.jsx)(RMi,{logs:v,isLoading:y,isFetchingNextPage:x,hasNextPage:S,setEndOfListElement:C,logIdMap:w,featuredLogId:n.featuredLogId,onLogClick:E,timestampSort:r?.direction,onSortChange:i}),(0,K.jsx)(DMi,{log:T??void 0,onClose:M,onTraceClick:N,onSpanClick:P,onPrevious:D,onNext:O}),(0,K.jsx)($yi,{depth:2,traceId:T?n.featuredTraceId??void 0:void 0,spans:k?.spans,isLoadingSpans:A,selectedSpanId:n.featuredSpanId??null,onSpanSelect:I,onClose:F})]})}function fNi(){let e=Y();return S_({queryKey:[`builtin-mcp-server`],queryFn:()=>e.getBuiltinMcpServer(),retry:!1})}var pNi=`<your-token>`;function mNi(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function hNi(e,{protectedServer:t}){let n=mNi(e),r=`Authorization: Bearer ${pNi}`,i=t?{headers:{Authorization:`Bearer ${pNi}`}}:{};return[{value:`claude-code`,label:`Claude Code`,lang:`bash`,code:`claude mcp add --transport http mastra ${n}${t?` --header "${r}"`:``}`},{value:`cursor`,label:`Cursor`,lang:`json`,code:JSON.stringify({mcpServers:{mastra:{url:e,...i}}},null,2)},{value:`vscode`,label:`VS Code`,lang:`json`,code:JSON.stringify({servers:{mastra:{type:`http`,url:e,...i}}},null,2)},{value:`inspector`,label:`MCP Inspector`,lang:`bash`,code:`npx @modelcontextprotocol/inspector --cli ${n} --transport http${t?` --header "${r}"`:``} --method tools/list`}]}var gNi=`https://mastra.ai/docs/server/mcp`;function _Ni(){let{data:e,error:t}=fNi();return e?(0,K.jsx)(vNi,{descriptor:e}):!t||DN(t)||ON(t)||kN(t)?null:(0,K.jsx)(yNi,{children:(0,K.jsx)(gk,{variant:`destructive`,children:`Couldn't load the built-in MCP server. Try reloading the page.`})})}function vNi({descriptor:e}){return(0,K.jsx)(yNi,{status:(0,K.jsx)(bNi,{descriptor:e}),children:e.enabled?e.mcpPackageInstalled?(0,K.jsx)(wNi,{descriptor:e}):(0,K.jsx)(CNi,{}):(0,K.jsx)(SNi,{descriptor:e})})}function yNi({status:e,children:t}){return(0,K.jsxs)(JN,{role:`region`,"aria-label":`Mastra (built-in) MCP server`,children:[(0,K.jsxs)(YN,{className:`flex-row flex-wrap items-center gap-3 space-y-0 border-b border-border`,children:[(0,K.jsx)(XN,{className:`shrink-0`,children:`Mastra (built-in)`}),e]}),(0,K.jsx)(QN,{className:`flex flex-col gap-4`,children:t})]})}function bNi({descriptor:e}){let{label:t,variant:n}=xNi(e);return(0,K.jsx)(JS,{variant:n,emphasis:`subtle`,indicator:`dot`,children:t})}function xNi(e){if(!e.enabled)return{label:`Disabled`,variant:`neutral`};if(!e.mcpPackageInstalled)return{label:`Not installed`,variant:`warning`};let{auth:t}=e;return t.type===`protected`?{label:`Protected by ${t.provider??`server auth`}`,variant:`success`}:t.devOnly?{label:`Open in dev only`,variant:`info`}:{label:`Open to anyone`,variant:`warning`}}function SNi({descriptor:e}){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{tone:`muted`,children:e.disabledReason===`config`?(0,K.jsxs)(K.Fragment,{children:[`The built-in MCP server is turned off because `,(0,K.jsx)(nX,{children:`server.mcp.enabled`}),` is`,` `,(0,K.jsx)(nX,{children:`false`}),`.`]}):(0,K.jsxs)(K.Fragment,{children:[`The built-in MCP server only runs under `,(0,K.jsx)(nX,{children:`mastra dev`}),` unless the server has auth. Configure `,(0,K.jsx)(nX,{children:`server.auth`}),`, or set `,(0,K.jsx)(nX,{children:`server.mcp.enabled`}),` to`,` `,(0,K.jsx)(nX,{children:`true`}),`.`]})}),(0,K.jsx)(ENi,{})]})}function CNi(){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(T,{tone:`muted`,children:[`The built-in MCP server is enabled, but it needs the `,(0,K.jsx)(nX,{children:`@mastra/mcp`}),` package. Install it and restart the server.`]}),(0,K.jsx)(aJ,{code:`npm install @mastra/mcp`,lang:`bash`,copyTooltip:`Copy install command`}),(0,K.jsx)(ENi,{})]})}function wNi({descriptor:e}){let t=`${(Y().options.baseUrl||window.location.origin).replace(/\/$/,``)}${e.path}`,n=hNi(t,{protectedServer:e.auth.type===`protected`}),[r,i]=(0,G.useState)(n[0].value),a=n.find(e=>e.value===r)??n[0];return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`muted`,children:`Endpoint`}),(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-3 rounded-lg bg-muted py-2 pr-2 pl-3`,children:[(0,K.jsx)(T,{as:`span`,font:`mono`,className:`min-w-0 break-all`,children:t}),(0,K.jsx)(uC,{tooltip:`Copy MCP endpoint URL`,content:t})]})]}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`muted`,children:`Toolsets`}),(0,K.jsxs)(`ul`,{className:`flex flex-wrap gap-2`,"aria-label":`Toolsets`,children:[e.toolsets.map(e=>(0,K.jsx)(`li`,{children:(0,K.jsx)(JS,{variant:`neutral`,emphasis:`subtle`,children:TNi(e)})},e)),e.readOnly&&(0,K.jsx)(`li`,{children:(0,K.jsx)(JS,{variant:`info`,emphasis:`subtle`,children:`Read-only`})})]})]}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`muted`,children:`Connect a client`}),(0,K.jsx)(aJ,{code:a.code,lang:a.lang,options:n.map(({value:e,label:t})=>({value:e,label:t})),value:r,onValueChange:i,selector:`tabs`,copyTooltip:`Copy snippet`}),(0,K.jsx)(T,{variant:`body-sm`,tone:`muted`,children:`Tools are listed per caller, so connect a client to see the tools your token can use.`})]})]})}function TNi(e){let t=e.replaceAll(`_`,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function ENi(){return(0,K.jsx)(`div`,{children:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:gNi,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(qN,{}),children:`MCP server docs`})})}var DNi={name:e=>e.name||e.id};function ONi({server:e,rowProps:t}){let{paths:n,Link:r}=sn(),i=Y().options.baseUrl,a=e.transports?.includes(`sse`)??!0?`sse`:`mcp`,o=i?`${i}/api/mcp/${e.id}/${a}`:``,{data:s}=Cjt({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=rJ(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 kNi({mcpServers:e,isLoading:t,search:n=``,sort:r,onSortChange:i}){let a=(0,G.useMemo)(()=>{let t=n.toLowerCase();return AZ(e.filter(e=>e.name?.toLowerCase().includes(t)||e.id?.toLowerCase().includes(t)),r,DNi)},[e,n,r]),{containerRef:o,getRowProps:s}=OZ({count:a.length,global:!0});return t?(0,K.jsx)(yH,{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)(PN,{}),tooltip:`Agent tools`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Tools`,short:(0,K.jsx)(HN,{}),tooltip:`Tools`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Workflows`,short:(0,K.jsx)(GS,{}),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)(ONi,{server:e,rowProps:s(t)},e.id))]})}var ANi=()=>(0,K.jsx)(Hx,{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)(qN,{}),children:`MCP documentation`}),variant:`fill`}),I9=[KN(`/mcps`)],jNi=()=>{let{data:e=[],isLoading:t,error:n}=TN(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)();return n&&DN(n)?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:I9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsx)(_H,{variant:`fill`})]}):n&&ON(n)?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:I9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsx)(gH,{variant:`fill`,resource:`MCP servers`})]}):n?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:I9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsx)(Hx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load MCP servers`,descriptionSlot:n.message})]}):e.length===0&&!t?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:I9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-6`,children:[(0,K.jsx)(_Ni,{}),(0,K.jsx)(ANi,{})]})]}):(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:I9}),actionRow:(0,K.jsx)(_K,{children:(0,K.jsx)(_K.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(wH,{...TH,onValueChange:i,label:`Search MCP servers`,placeholder:`Search by name`})})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-6`,children:[(0,K.jsx)(_Ni,{}),(0,K.jsx)(kNi,{mcpServers:e,isLoading:t,search:r,sort:a,onSortChange:(e,t)=>o({key:t,direction:e})})]})]})};function MNi(){let[e,t]=Mv();return{eventName:e.get(`event`)??void 0,close:()=>t(e=>{let t=new URLSearchParams(e);return t.delete(`event`),t},{replace:!0})}}var NNi=e=>`?${new URLSearchParams({event:e}).toString()}`;function PNi(e,{enabled:t=!0}={}){let n=Y();return S_({queryKey:[`mcp-server-events`,e],queryFn:()=>n.getMcpServerEvents(e),enabled:t})}function FNi(e,t){let n=Y();return w_({mutationFn:r=>n.emitMcpServerEvent(e,t,r)})}function INi(e){if(e instanceof Wf&&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 LNi={push:`blue`,poll:`neutral`,webhook:`purple`};function RNi({delivery:e}){return(0,K.jsx)(`span`,{className:`flex flex-wrap items-center gap-1`,children:e.map(e=>(0,K.jsx)(JS,{size:`xs`,variant:LNi[e],emphasis:`subtle`,children:e},e))})}var zNi=0,BNi=()=>`feed-${zNi++}`;function VNi(e,t){return[...t,...e].slice(0,200)}function HNi(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:VNi(e.items,[{kind:`gap`,key:BNi()}])};case`occurrences`:{let n=[...t.occurrences].reverse().map(e=>({kind:`occurrence`,key:BNi(),occurrence:e}));return{...e,items:VNi(e.items,n)}}case`warning`:return{...e,warning:t.message};case`error`:return{...e,status:`error`,error:t.message}}}var UNi={status:`idle`,items:[]};function WNi(e,t){let n=Y(),[r,i]=(0,G.useReducer)(HNi,UNi),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:INi(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:INi(e)})}};return{...r,start:l,stop:c,pollOnce:u}}function L9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function GNi(e){return e.map(e=>JSON.stringify(e)).join(` | `)}function KNi(e){return e.map(R9).join(` | `)}function R9(e){return L9(e)?Array.isArray(e.enum)?GNi(e.enum):`const`in e?JSON.stringify(e.const):Array.isArray(e.anyOf)?KNi(e.anyOf):Array.isArray(e.oneOf)?KNi(e.oneOf):Array.isArray(e.type)?e.type.join(` | `):e.type===`array`?`${R9(e.items)}[]`:YNi(e)?`Record<string, ${R9(e.additionalProperties)}>`:typeof e.type==`string`?e.type:`unknown`:`unknown`}function qNi(e,t,n,{defaultsAreOptional:r=!1}){let i=L9(t)?t:{},a=`default`in i;return{name:e,type:R9(i),required:n.has(e)&&!(r&&a),description:typeof i.description==`string`?i.description:void 0,defaultValue:a?JSON.stringify(i.default):void 0}}function JNi(e,t={}){if(!L9(e)||!L9(e.properties))return[];let n=new Set(Array.isArray(e.required)?e.required.filter(e=>typeof e==`string`):[]);return Object.entries(e.properties).map(([e,r])=>qNi(e,r,n,t))}function YNi(e){return L9(e)&&e.type===`object`&&!L9(e.properties)&&L9(e.additionalProperties)}function XNi(e){return L9(e)&&(e.type===`object`||L9(e.properties))}var ZNi=[`type`,`properties`,`items`,`enum`,`const`,`anyOf`,`oneOf`,`allOf`,`$ref`];function QNi(e){return!L9(e)||!ZNi.some(t=>t in e)}function z9(e){return L9(e)?NO(e):J({})}function $Ni({inputSchema:e,onChange:t}){return QNi(e)?(0,K.jsx)(T,{tone:`muted`,children:`This event takes no arguments.`}):(0,K.jsx)(HM,{schema:z9(e),onValuesChange:e=>t(e??{})})}function ePi({occurrence:e}){return(0,K.jsx)(JN,{children:(0,K.jsxs)(xC,{children:[(0,K.jsxs)(SC,{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)(JS,{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)(CC,{children:(0,K.jsx)(mw,{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 tPi=`Gap: events may have been skipped`;function nPi({items:e}){return e.length===0?(0,K.jsx)(Hx,{iconSlot:(0,K.jsx)(G6,{}),titleSlot:`No events yet`,descriptionSlot:`Start listening or poll to see occurrences here.`}):(0,K.jsx)(`ol`,{"aria-label":`Occurrences`,className:`grid grid-cols-1 gap-2`,children:e.map(e=>(0,K.jsx)(`li`,{children:e.kind===`gap`?(0,K.jsx)(gk,{variant:`warning`,children:tPi}):(0,K.jsx)(ePi,{occurrence:e.occurrence})},e.key))})}var rPi={idle:`Not listening`,connecting:`Connecting…`,polling:`Polling…`,polled:`Polled`,stopped:`Stopped`,error:`Failed`};function iPi({status:e,canStream:t}){if(e===`live`)return(0,K.jsx)(JS,{variant:`green`,indicator:`pulse`,size:`sm`,children:`Listening`});let n=e===`idle`&&!t?`Not polled yet`:rPi[e];return(0,K.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(e===`connecting`||e===`polling`)&&(0,K.jsx)(It,{size:`sm`}),(0,K.jsx)(T,{as:`span`,tone:`muted`,children:n})]})}function aPi({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)(iPi,{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)(uC,{tooltip:`Copy cursor`,content:n})]})]})}function oPi({serverId:e,event:t,onEmitted:n}){let{mutateAsync:r,isPending:i,isSuccess:a,error:o}=FNi(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)(HM,{schema:z9(t.payloadSchema),onSubmit:async e=>{try{await r(e??{}),n?.()}catch{}},isSubmitLoading:i,submitButtonLabel:`Send test event`}),a&&!o&&(0,K.jsx)(T,{tone:`muted`,children:`Test event sent.`}),o&&(0,K.jsx)(gk,{variant:`destructive`,children:INi(o)})]})}function sPi({serverId:e,event:t,testEmit:n,canEmit:r}){let[i,a]=(0,G.useState)({}),o=WNi(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)($Ni,{inputSchema:t.inputSchema,onChange:a}),(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,K.jsx)(aPi,{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)(gk,{variant:`destructive`,children:o.error}),o.warning&&(0,K.jsx)(gk,{variant:`warning`,children:o.warning}),n&&t.emittable&&r&&(0,K.jsx)(oPi,{serverId:e,event:t,onEmitted:s?void 0:()=>void o.pollOnce(i)}),(0,K.jsx)(nPi,{items:o.items})]})}function cPi({description:e}){let t=qQ({collapsedHeight:140});return(0,K.jsx)(KQ,{state:t,expandLabel:`Read more`,children:(0,K.jsx)(pY,{children:e})})}function lPi({description:e,overview:t,playground:n,canRun:r}){return(0,K.jsx)(K.Fragment,{children:(0,K.jsxs)(uk,{defaultTab:`overview`,className:`grid flex-1 grid-rows-[auto_1fr] gap-4 overflow-visible`,children:[(0,K.jsxs)(lk,{variant:`pill`,size:`sm`,children:[(0,K.jsx)(dk,{value:`overview`,children:`Overview`}),(0,K.jsx)(dk,{value:`playground`,disabled:!r,disabledTooltip:`You don't have permission to execute tools.`,children:`Playground`})]}),(0,K.jsxs)(fk,{value:`overview`,flush:!0,className:`content-start gap-6`,children:[e&&(0,K.jsx)(JN,{className:`p-4`,children:(0,K.jsx)(cPi,{description:e})}),t]}),(0,K.jsx)(fk,{value:`playground`,flush:!0,keepMounted:!0,className:`h-full`,children:r&&n})]})})}function uPi(e){return(0,K.jsx)(Q5n,{className:`min-h-control-md`,...e})}function dPi(){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 fPi({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 pPi({field:e}){let t=!!e.description||e.defaultValue!==void 0;return(0,K.jsx)(gZ,{title:(0,K.jsxs)(T,{as:`span`,variant:`body-sm`,font:`mono`,tone:`ink`,children:[e.name,e.required&&(0,K.jsx)(dPi,{})]}),description:t?(0,K.jsx)(`span`,{className:`whitespace-normal`,children:(0,K.jsx)(fPi,{field:e})}):void 0,children:(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,tone:`muted`,children:e.type})})}function mPi({message:e}){return(0,K.jsx)(hZ,{children:e})}function hPi({schema:e,emptyMessage:t,defaultsAreOptional:n}){if(QNi(e))return(0,K.jsx)(mPi,{message:t});if(!XNi(e)||YNi(e))return(0,K.jsx)(gZ,{title:`Type`,children:(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,tone:`muted`,children:R9(e)})});let r=JNi(e,{defaultsAreOptional:n});return r.length===0?(0,K.jsx)(mPi,{message:t}):r.map(e=>(0,K.jsx)(pPi,{field:e},e.name))}function B9({title:e,...t}){return(0,K.jsxs)(pZ,{children:[(0,K.jsx)(uPi,{children:(0,K.jsx)(mZ,{children:e})}),(0,K.jsx)(fZ,{children:(0,K.jsx)(hPi,{...t})})]})}function gPi({serverId:e,eventName:t}){let{canExecute:n,canEdit:r}=oS(),{data:i,isLoading:a}=PNi(e),o=i?.events.find(e=>e.name===t);return a?(0,K.jsx)(dQ.LoadingData,{}):!i||!o?(0,K.jsxs)(dQ.NoData,{children:[`This server has no event "`,t,`".`]}):(0,K.jsx)(lPi,{description:o.description,overview:(0,K.jsxs)(`div`,{className:`grid grid-cols-1 gap-6`,children:[(0,K.jsx)(RNi,{delivery:o.delivery}),(0,K.jsx)(B9,{title:`Arguments`,schema:o.inputSchema,emptyMessage:`This event takes no arguments.`,defaultsAreOptional:!0}),(0,K.jsx)(B9,{title:`Payload`,schema:o.payloadSchema,emptyMessage:`No payload schema defined.`})]}),canRun:n(`mcp`),playground:(0,K.jsx)(sPi,{serverId:e,event:o,testEmit:i.testEmit,canEmit:r(`mcp`)})})}function _Pi({serverId:e}){let{eventName:t,close:n}=MNi();return(0,K.jsxs)(dQ,{open:t!==void 0,onClose:n,title:t??``,children:[(0,K.jsxs)(dQ.Header,{children:[(0,K.jsxs)(dQ.Heading,{children:[(0,K.jsx)(xx,{size:`sm`,className:`text-muted-foreground`,children:(0,K.jsx)(G6,{})}),(0,K.jsx)(`span`,{className:`truncate`,children:t})]}),(0,K.jsx)(dQ.HeaderActions,{children:(0,K.jsx)(dQ.CloseButton,{icon:`x`,tooltip:`Close event`,onClick:n})})]}),(0,K.jsx)(dQ.Content,{className:`flex flex-col gap-4 px-3`,children:t&&(0,K.jsx)(gPi,{serverId:e,eventName:t},t)})]})}var vPi=new Set([`completed`,`failed`,`cancelled`]),yPi={working:`working`,input_required:`input required`,completed:`completed`,failed:`failed`,cancelled:`cancelled`},bPi=e=>vPi.has(e.status),xPi=2e3,V9=e=>[`mcp-server-tasks`,e],SPi=e=>!!e?.some(e=>!bPi(e));function CPi(e,t={}){let n=Y();return T_({queryKey:[...V9(e),`list`,t],queryFn:({pageParam:r})=>n.getMcpServerTasks(e,{...t,cursor:r}),initialPageParam:void 0,getNextPageParam:e=>e.nextCursor,refetchInterval:e=>e.state.data?.pages.some(e=>SPi(e.tasks))?xPi:!1})}function wPi(e,{enabled:t=!0}={}){let n=Y();return S_({queryKey:[...V9(e),`surfaces`],queryFn:()=>n.getMcpServerTasks(e,{limit:1}),select:e=>e.surfaces,enabled:t})}function TPi(e,t){let n=Y();return S_({queryKey:[...V9(e),`task`,t],queryFn:async()=>(await n.getMcpServerTasks(e,{key:t,limit:1})).tasks[0]??null,enabled:t!==void 0,refetchInterval:e=>e.state.data&&!bPi(e.state.data)?xPi:!1})}function EPi(e){let t=Y();return w_({mutationFn:n=>t.findMcpServerTask(e,n)})}function DPi(e){let t=Y(),n=s_();return w_({mutationFn:n=>t.cancelMcpServerTask(e,n),onSettled:()=>n.invalidateQueries({queryKey:V9(e)})})}function OPi(e){let t=Y(),n=s_();return w_({mutationFn:({taskKey:n,inputResponses:r})=>t.answerMcpServerTaskInput(e,n,r),onSettled:()=>n.invalidateQueries({queryKey:V9(e)})})}function kPi(){let[e,t]=Mv();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 APi=(e,t=``)=>{let n=new URLSearchParams(t);return n.set(`task`,e),`?${n.toString()}`},jPi=e=>`${e.slice(0,8)}…`,MPi=new Set([`working`,`input_required`,`completed`,`failed`,`cancelled`]);function NPi(){let[e,t]=Mv(),n=e.get(`status`),r=e.get(`surface`),i=e.get(`client`);return{filters:{...n&&MPi.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 PPi=e=>`${e.slice(0,8)}…`,FPi={working:{variant:`info`,indicator:`pulse`},input_required:{variant:`warning`,indicator:`dot`},completed:{variant:`success`},failed:{variant:`destructive`},cancelled:{variant:`neutral`}};function IPi({status:e}){let{variant:t,indicator:n}=FPi[e];return(0,K.jsx)(JS,{size:`sm`,variant:t,emphasis:`subtle`,indicator:n,children:yPi[e]})}function LPi({serverId:e}){let{taskKey:t,close:n}=kPi(),{data:r,isSuccess:i}=TPi(e,t);return(0,K.jsxs)(dQ,{open:t!==void 0,onClose:n,title:r?.surface??`Task`,children:[(0,K.jsxs)(dQ.Header,{children:[(0,K.jsxs)(dQ.Heading,{children:[(0,K.jsx)(xx,{size:`sm`,className:`text-muted-foreground`,children:(0,K.jsx)(F8n,{})}),(0,K.jsx)(`span`,{className:`truncate`,children:r?`${r.surface} task`:`Task`})]}),(0,K.jsx)(dQ.HeaderActions,{children:(0,K.jsx)(dQ.CloseButton,{icon:`x`,tooltip:`Close task`,onClick:n})})]}),(0,K.jsx)(dQ.Content,{className:`flex flex-col gap-4 px-3`,children:r?(0,K.jsx)(RPi,{serverId:e,task:r},r.taskKey):i&&(0,K.jsx)(T,{tone:`muted`,children:`This task is no longer listed.`})})]})}function RPi({serverId:e,task:t}){let n=DPi(e),{canEdit:r,isLoading:i}=oS(),a=!i&&r(`mcp`),o=Object.entries(t.inputRequests??{});return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(V4,{children:[(0,K.jsx)(V4.Key,{children:`Status`}),(0,K.jsx)(V4.Value,{children:(0,K.jsx)(IPi,{status:t.status})}),t.statusMessage&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(V4.Key,{children:`Message`}),(0,K.jsx)(V4.Value,{children:t.statusMessage})]}),(0,K.jsx)(V4.Key,{children:`Created`}),(0,K.jsx)(V4.Value,{children:(0,K.jsx)(xk,{value:t.createdAt})}),(0,K.jsx)(V4.Key,{children:`Updated`}),(0,K.jsx)(V4.Value,{children:(0,K.jsx)(xk,{value:t.lastUpdatedAt})}),(0,K.jsx)(V4.Key,{children:`Expires`}),(0,K.jsx)(V4.Value,{children:t.expiresAt?(0,K.jsx)(xk,{value:t.expiresAt}):`never`}),(0,K.jsx)(V4.Key,{children:`Task key`}),(0,K.jsx)(V4.ValueWithCopyBtn,{copyValue:t.taskKey,copyTooltip:`Copy task key`,children:jPi(t.taskKey)}),t.clientLabel&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(V4.Key,{children:`Client`}),(0,K.jsx)(V4.ValueWithCopyBtn,{copyValue:t.clientLabel,copyTooltip:`Copy client`,children:t.clientLabel})]}),(0,K.jsx)(V4.Key,{children:`Client key`}),(0,K.jsx)(V4.ValueWithCopyBtn,{copyValue:t.principalKey,copyTooltip:`Copy client key`,children:jPi(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)(BPi,{serverId:e,taskKey:t.taskKey,inputKey:n,request:r,canAnswer:a},n)),!bPi(t)&&!i&&!a&&(0,K.jsx)(T,{tone:`muted`,variant:`caption`,children:`Cancelling or answering a task needs the mcp:write permission.`}),!bPi(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)(gk,{variant:`destructive`,children:HPi(n.error)})]}),t.result&&(0,K.jsx)(VPi,{label:`Result`,value:t.result}),t.error&&(0,K.jsx)(VPi,{label:`Error`,value:t.error})]})}var zPi=J({message:q().optional(),requestedSchema:kd(q(),md())});function BPi({serverId:e,taskKey:t,inputKey:n,request:r,canAnswer:i}){let a=OPi(e),o=r.method===`elicitation/create`?zPi.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)(VPi,{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)(HM,{schema:z9(o.data.requestedSchema),onSubmit:e=>s({action:`accept`,content:e??{}}),isSubmitLoading:a.isPending,submitButtonLabel:`Accept`,submitButtonVariant:`primary`,submitActions:(0,K.jsx)(X,{type:`button`,disabled:a.isPending,onClick:()=>s({action:`decline`}),children:`Decline`})})]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(T,{tone:`muted`,children:[`Studio can't answer a `,r.method,` request; the client that started the task has to.`]}),(0,K.jsx)(VPi,{label:`Request`,value:r})]}),a.error&&(0,K.jsx)(gk,{variant:`destructive`,children:HPi(a.error)})]})}function VPi({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)(mw,{value:JSON.stringify(t,null,2),language:`json`,editable:!1,lineNumbers:!1,"aria-label":`Task ${e.toLowerCase()}`})]})}function HPi(e){let t=INi(e);return t===`Task not found`?`The task is no longer waiting for this; the list has been refreshed.`:t}function UPi(e){if(!L9(e))return;if(L9(e.ui)&&typeof e.ui.resourceUri==`string`)return e.ui.resourceUri;let t=e[`ui/resourceUri`];return typeof t==`string`?t:void 0}function WPi(e){return L9(e)&&e.status===`suspended`}function GPi(e){return e<1e3?`${Math.round(e)} ms`:`${(e/1e3).toFixed(2)} s`}function KPi(e){return e===void 0?`undefined`:JSON.stringify(e,null,2)}function qPi(e){return e.status===`error`?e.error:KPi(e.output)}function JPi({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:YPi(n),durationMs:r}}}function YPi(e){return e instanceof Error?JSON.stringify({error:e.message},null,2):JSON.stringify({error:String(e)},null,2)}function XPi({zodInputSchema:e,isRunning:t,onRun:n,requestContextEntityType:r,requestContextEntityId:i}){let a=!aEt(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=bEt(o.value);if(!n.ok)return u([n.error]);let r=xEt(e,n.value);if(r)return u([r]);c.current=n.value,s({view:`form`,value:n.value})}function f(t){let r=SEt(e,t);r.ok?n(r.value):u(r.errors)}let p={isSubmitLoading:t,submitButtonLabel:`Run`,submitButtonIcon:(0,K.jsx)(xT,{}),submitButtonVariant:`primary`};return(0,K.jsxs)(pZ,{children:[(0,K.jsx)(uPi,{action:(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(zMt,{entityType:r,entityId:i}),(0,K.jsx)(uk,{defaultTab:`form`,value:o.view,onValueChange:d,children:(0,K.jsxs)(lk,{size:`md`,children:[(0,K.jsxs)(dk,{value:`form`,disabled:t,children:[(0,K.jsx)(xx,{size:`sm`,children:(0,K.jsx)(Igt,{})}),`Form`]}),(0,K.jsxs)(dk,{value:`json`,disabled:t,children:[(0,K.jsx)(xx,{size:`sm`,children:(0,K.jsx)(HS,{})}),`JSON`]})]})})]}),children:(0,K.jsx)(mZ,{children:`Request`})}),(0,K.jsx)(fZ,{children:(0,K.jsx)(`div`,{className:`p-4`,children:o.view===`json`?(0,K.jsxs)(`div`,{className:`grid gap-4`,children:[(0,K.jsxs)($O,{invalid:l.length>0,children:[(0,K.jsx)(mw,{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)(rk,{children:l.map(e=>(0,K.jsx)(`span`,{className:`block`,children:e},e))})]}),(0,K.jsx)(Ck,{...p,onSubmit:()=>f(o.value)})]}):(0,K.jsx)(HM,{...p,schema:e,defaultValues:o.value,onValuesChange:e=>{c.current=e},onSubmit:n,className:`gap-0`,children:!a&&(0,K.jsx)(T,{variant:`body-sm`,tone:`muted`,className:`pb-4`,children:`This tool takes no input. Run it as is.`})})})})]})}var ZPi=U(`IconSend`,()=>(0,K.jsx)(`path`,{d:`M13.1282 21.1524C13.3813 22.1224 14.7454 22.1581 15.0489 21.2027L20.1669 5.09042C20.4124 4.31745 19.6841 3.58908 18.9111 3.83461L2.79884 8.95262C1.84336 9.25613 1.8791 10.6203 2.84916 10.8733L10.4343 12.852C10.7846 12.9434 11.0581 13.217 11.1495 13.5672L13.1282 21.1524Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}));function QPi({isRunning:e,lastRun:t}){return e?(0,K.jsx)(Hx,{iconSlot:(0,K.jsx)(It,{}),titleSlot:`Running…`,descriptionSlot:`Waiting for the tool to respond.`}):t?t.status===`error`?(0,K.jsx)(iC,{code:qPi(t),className:`overflow-x-auto p-4 text-caption whitespace-pre`}):(0,K.jsx)(mw,{value:qPi(t),language:`json`,editable:!1,lineNumbers:!1,showCopyButton:!1,variant:`embedded`,"aria-label":`Tool response`,className:`p-4`}):(0,K.jsx)(Hx,{iconSlot:(0,K.jsx)(ZPi,{}),titleSlot:`No response yet`,descriptionSlot:`Run the tool to see its output here.`})}function $Pi({run:e}){return(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[e.status===`success`?(0,K.jsx)(JS,{variant:`success`,emphasis:`subtle`,indicator:`dot`,children:`Success`}):(0,K.jsx)(JS,{variant:`destructive`,emphasis:`subtle`,indicator:`dot`,children:`Error`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,tone:`muted`,children:GPi(e.durationMs)}),(0,K.jsx)(uC,{content:qPi(e),copyMessage:`Response copied`,tooltip:`Copy response`,size:`icon-sm`})]})}function eFi({isRunning:e,lastRun:t}){return(0,K.jsxs)(pZ,{className:`h-full`,children:[(0,K.jsx)(uPi,{action:!e&&t&&(0,K.jsx)($Pi,{run:t}),children:(0,K.jsx)(mZ,{children:`Response`})}),(0,K.jsx)(fZ,{className:c(`grid min-h-48 flex-1`,e||!t?`content-center`:`content-start`),children:(0,K.jsx)(QPi,{isRunning:e,lastRun:t})})]})}function tFi({zodInputSchema:e,execution:t,requestContextEntityType:n,requestContextEntityId:r}){let[i]=IS(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)(XPi,{zodInputSchema:e,isRunning:c,onRun:s,requestContextEntityType:n,requestContextEntityId:r}),(0,K.jsx)(eFi,{isRunning:c,lastRun:JPi(t,a)})]})}function nFi({serverId:e,tool:t}){let n=nmr(e),{mutateAsync:r,status:i,data:a,error:o}=Sjt({serverId:e,toolId:t.name}),{data:s}=yjt({serverId:e,appResourceUri:UPi(t._meta)}),c=z9(t.inputSchema),l={execute:(e,t)=>r({data:e,requestContext:t}),status:i,output:a,error:o};return(0,K.jsxs)(`div`,{className:`grid content-start gap-6`,children:[s&&(0,K.jsx)(aPr,{html:s,toolName:t.name,onToolCall:n}),WPi(a)&&(0,K.jsxs)(gk,{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)(nX,{children:`inputRequests`}),` handler to finish the request.`]}),(0,K.jsx)(tFi,{zodInputSchema:c,execution:l,requestContextEntityType:`mcp-tool`,requestContextEntityId:`${e}:${t.name}`})]})}var rFi=(0,G.createContext)(void 0),iFi=rFi.Provider;function aFi(){let e=(0,G.useContext)(rFi);if(e===void 0)throw Error(`useOpenToolId must be used inside ToolDrawer`);return e}function oFi({inputSchema:e,outputSchema:t,requestContextSchema:n,footer:r}){return(0,K.jsxs)(`div`,{className:`grid gap-6`,children:[(0,K.jsx)(B9,{title:`Input`,schema:e,emptyMessage:`This tool takes no input.`,defaultsAreOptional:!0}),(0,K.jsx)(B9,{title:`Output`,schema:t,emptyMessage:`No output schema defined.`}),n!==void 0&&(0,K.jsx)(B9,{title:`Request context`,schema:n,emptyMessage:`No request context fields.`,defaultsAreOptional:!0}),r]})}function sFi({serverId:e}){let t=aFi(),{canExecute:n}=oS(),{data:r,isLoading:i}=xjt({serverId:e,toolId:t});return i?(0,K.jsx)(dQ.LoadingData,{}):r?(0,K.jsx)(lPi,{description:r.description,overview:(0,K.jsx)(oFi,{inputSchema:r.inputSchema}),canRun:n(`tools`),playground:(0,K.jsx)(nFi,{serverId:e,tool:r})}):(0,K.jsxs)(dQ.NoData,{children:[`This server has no tool "`,t,`".`]})}var cFi=`auto 1fr auto`;function lFi({server:e}){let{data:t,isLoading:n,isError:r}=PNi(e.id),i=t?.events??[],{Link:a}=sn(),{containerRef:o,getRowProps:s}=OZ({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)(yH,{columns:cFi}),r&&(0,K.jsx)(gk,{variant:`destructive`,children:`Could not load this server's events.`}),t&&(0,K.jsxs)(Z,{columns:cFi,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}${NNi(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)(RNi,{delivery:t.delivery})})]},t.name))]})]})}var uFi=`minmax(0,1fr) auto auto auto auto auto auto auto`,dFi={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.`},fFi=[{id:`is`,label:`is`}],pFi=Object.entries(yPi).map(([e,t])=>({value:e,label:t})),mFi=e=>e.stopPropagation(),hFi=e=>e.clientLabel??PPi(e.principalKey),gFi=e=>[`status`,`surface`,`client`].flatMap(t=>{let n=e[t];return n?[{id:t,fieldId:t,operatorId:`is`,value:n}]:[]}),_Fi=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 vFi({server:e}){let{filters:t,setFilters:n}=NPi(),{data:r,isLoading:i,isError:a,hasNextPage:o,fetchNextPage:s,isFetchingNextPage:c}=CPi(e.id,t),{data:l=[]}=wPi(e.id),u=(0,G.useMemo)(()=>r?.pages.flatMap(e=>e.tasks)??[],[r]),d=r?.pages[0]?.unavailable,{containerRef:f,getRowProps:p}=OZ({count:u.length}),m=gFi(t).length>0,h=(0,G.useMemo)(()=>{let e=new Map(u.map(e=>[e.principalKey,hFi(e)]));return t.client&&!e.has(t.client)&&e.set(t.client,PPi(t.client)),[...e]},[u,t.client]),g=(0,G.useMemo)(()=>[{id:`status`,label:`Status`,icon:bX,color:$N(`orange`),operators:[`is`],strict:!0,suggestions:pFi},{id:`surface`,label:`Surface`,icon:US,color:$N(`blue`),operators:[`is`],strict:!0,suggestions:l.map(e=>({value:e.name}))},{id:`client`,label:`Client`,icon:vXr,color:$N(`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)(gk,{variant:`destructive`,children:`Could not load this server's tasks.`}),d&&(0,K.jsx)(gk,{variant:`info`,children:dFi[d]}),!d&&(0,K.jsxs)(_K,{children:[(0,K.jsx)(_K.Start,{children:(0,K.jsxs)(c5,{fields:g,operators:fFi,value:gFi(t),onValueChange:e=>n(_Fi(e)),createItemId:e=>e,"aria-label":`Task filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(c5.Chips,{}),(0,K.jsx)(c5.Input,{placeholder:`Filter tasks`})]})}),(0,K.jsx)(_K.End,{children:(0,K.jsx)(bFi,{serverId:e.id})})]}),i&&(0,K.jsx)(yH,{columns:uFi}),r&&!d&&(0,K.jsxs)(Z,{columns:uFi,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)(yFi,{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 yFi({serverId:e,task:t,rowProps:n,onFilterClient:r}){let{Link:i}=sn(),[a]=Mv(),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}${APi(t.taskKey,a)}`,LinkComponent:i,tabIndex:-1,onClick:mFi,"aria-label":`${t.surface} task ${jPi(t.taskKey)}`,children:[(0,K.jsx)(Z.NameCell,{children:t.surface}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(IPi,{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)(xk,{value:t.lastUpdatedAt})}),(0,K.jsx)(Z.Cell,{className:`text-muted-foreground`,children:t.expiresAt?(0,K.jsx)(xk,{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:jPi(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 ${hFi(t)}`,onClick:e=>{e.stopPropagation(),r()},children:hFi(t)})})]})}function bFi({serverId:e}){let[t,n]=(0,G.useState)(``),r=EPi(e),{open:i}=kPi();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)(Hj,{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 xFi={agent:PN,workflow:GS,tool:HN},SFi=`auto minmax(0, 1fr) auto`,CFi=`auto minmax(0, 1fr) auto auto`,wFi={tool:`Tool`,agent:`Agent`,workflow:`Workflow`};function TFi(e){return e in xFi}function EFi({type:e}){let t=TFi(e)?e:`tool`,n=xFi[t],r=wFi[t];return(0,K.jsxs)(_x,{children:[(0,K.jsx)(vx,{asChild:!0,children:(0,K.jsx)(`span`,{"aria-label":t,className:`inline-flex text-muted-foreground [&>svg]:size-icon-md`,children:(0,K.jsx)(n,{})})}),(0,K.jsx)(yx,{children:r})]})}var DFi=J({ui:J({resourceUri:q().optional()}).optional(),"ui/resourceUri":q().optional()});function OFi(e){let t=DFi.safeParse(e);return t.success?!!(t.data.ui?.resourceUri?.startsWith(`ui://`)||t.data[`ui/resourceUri`]?.startsWith(`ui://`)):!1}function kFi({surface:e}){return e?(0,K.jsxs)(_x,{children:[(0,K.jsx)(vx,{asChild:!0,children:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,K.jsx)(JS,{size:`xs`,variant:e.mode===`always`?`info`:`neutral`,emphasis:`subtle`,children:e.mode}),e.required&&(0,K.jsx)(JS,{size:`xs`,variant:`warning`,emphasis:`subtle`,children:`required`}),e.recover&&(0,K.jsx)(JS,{size:`xs`,variant:`neutral`,emphasis:`subtle`,children:`recover`})]})}),(0,K.jsxs)(yx,{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 AFi({server:e}){let[t,n]=(0,G.useState)(``),{data:r={},isLoading:i}=Cjt({selectedServer:e}),{Link:a,paths:o}=sn(),{data:s}=wPi(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?CFi:SFi,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}=OZ({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)(wH,{size:`sm`,debounceMs:300,className:`max-w-120`,onValueChange:n,label:`Search tools`,placeholder:`Search by name`})})]}),i?(0,K.jsx)(yH,{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,OFi(t._meta)&&(0,K.jsx)(JS,{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)(EFi,{type:t.toolType??`tool`})}),l&&(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(kFi,{surface:c.get(t.name)})})]},t.name))]})]})}var jFi=({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)(JN,{children:(0,K.jsxs)(uk,{defaultTab:`http`,children:[(0,K.jsxs)(YN,{className:`flex-row items-center justify-between gap-3 space-y-0 border-b border-border`,children:[(0,K.jsx)(XN,{className:`shrink-0`,children:`Connect`}),(0,K.jsx)(`div`,{className:`min-w-0`,children:(0,K.jsx)(lk,{variant:`pill-ghost`,size:`sm`,children:s.map(e=>(0,K.jsx)(dk,{value:e.value,children:e.label},e.value))})})]}),s.map(e=>(0,K.jsx)(fk,{value:e.value,flush:!0,children:(0,K.jsxs)(QN,{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)(uC,{tooltip:e.tooltip,content:e.content})]})]})},e.value))]})}),(0,K.jsx)(AFi,{server:t}),t.tasks_capability&&(0,K.jsx)(vFi,{server:t}),t.events_capability&&(0,K.jsx)(lFi,{server:t})]})};function MFi(){let[e,t]=Mv();return{toolId:e.get(`tool`)??void 0,close:()=>t(e=>{let t=new URLSearchParams(e);return t.delete(`tool`),t},{replace:!0})}}function NFi({children:e}){let{toolId:t,close:n}=MFi();return(0,K.jsxs)(dQ,{open:t!==void 0,onClose:n,title:t??``,children:[(0,K.jsxs)(dQ.Header,{children:[(0,K.jsxs)(dQ.Heading,{children:[(0,K.jsx)(xx,{size:`sm`,className:`text-muted-foreground`,children:(0,K.jsx)(HN,{})}),(0,K.jsx)(`span`,{className:`truncate`,children:t})]}),(0,K.jsx)(dQ.HeaderActions,{children:(0,K.jsx)(dQ.CloseButton,{icon:`x`,tooltip:`Close tool`,onClick:n})})]}),(0,K.jsx)(dQ.Content,{className:`flex flex-col gap-4 px-3`,children:t&&(0,K.jsx)(iFi,{value:t,children:e},t)})]})}var PFi=()=>{let{serverId:e}=Ev(),t=[KN(`/mcps`),DMt],{data:n=[],isLoading:r}=TN(),i=n.find(t=>t.id===e),a=i?.transports?.includes(`sse`)??!0,o=r||i?(0,K.jsxs)(yK,{children:[(0,K.jsx)(yK.Title,{isLoading:r,children:i?.name}),i&&(0,K.jsx)(yK.Meta,{beside:!0,children:(0,K.jsxs)(JS,{size:`sm`,children:[`v`,i.version_detail.version]})}),i&&(0,K.jsx)(yK.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)(MS,{variant:`narrow`,breadcrumbs:(0,K.jsx)(uN,{crumbs:t}),header:o,children:[(0,K.jsx)(jFi,{isLoading:r,server:i}),e&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(NFi,{children:(0,K.jsx)(sFi,{serverId:e})}),(0,K.jsx)(_Pi,{serverId:e}),(0,K.jsx)(LPi,{serverId:e})]})]})};function FFi(){let{data:e,isLoading:t}=m7();if(t)return`loading`;let n=e?.capabilities;return n?.traceAggregate===!0&&n.spanAggregate===!0?`unified`:`legacy`}var H9=[KN(`/metrics`)],IFi=e=>e.fieldId===$6r;function LFi({fields:e}){let{filterTokens:t,setFilterTokens:n}=$7(),r=[s5,...pxi(t)];return(0,K.jsxs)(c5,{fields:[e8r,...e],operators:oxi,value:r,onValueChange:e=>n(mxi(e.filter(e=>!IFi(e)))),createItemId:e=>e,"aria-label":`Metrics filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(c5.Chips,{renderChip:e=>IFi(e)?(0,K.jsx)(Zxi,{}):(0,K.jsx)(c5.Chip,{item:e})}),(0,K.jsx)(c5.Input,{placeholder:`Filter metrics`})]})}function RFi({children:e,filterFields:t}){return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:H9}),actionRow:(0,K.jsx)(_K,{children:(0,K.jsx)(_K.Start,{children:(0,K.jsx)(LFi,{fields:t})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),e]})}function zFi({error:e}){return DN(e)?(0,K.jsx)(_H,{}):ON(e)?(0,K.jsx)(gH,{resource:`metrics`}):(0,K.jsx)(Hx,{tone:`error`,titleSlot:`Failed to load storage capabilities`,descriptionSlot:e.message})}var BFi=fxi({availableTags:[],availableEntityNames:[],availableServiceNames:[],availableEnvironments:[]});function VFi({children:e}){let{supportsMetrics:t,isLoading:n,error:r}=S7();return n?(0,K.jsx)(RFi,{filterFields:BFi,children:(0,K.jsxs)(`div`,{className:`flex h-full items-center justify-center gap-2`,children:[(0,K.jsx)(It,{"aria-label":`Loading storage capabilities`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:`Loading storage capabilities`})]})}):r?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:H9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),(0,K.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:(0,K.jsx)(zFi,{error:r})})]}):t?e:(0,K.jsx)(RFi,{filterFields:BFi,children:(0,K.jsx)(Hx,{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)(qN,{}),children:`Metrics documentation`}),variant:`fill`})})}function HFi(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 UFi(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=HFi(i);s&&e.set(t,s)}function U9(e,t,n){typeof n==`string`&&n.length>0&&e.set(t,n)}function WFi(e,t,n){if(Array.isArray(n)&&n.length!==0)for(let r of n)r&&e.append(t,r)}function GFi({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(_8,`branches`),UFi(a,v8,y8,b8,e,t,r.window);let o=r.rootEntityType??n.rootEntityType;if(o&&a.set(h8,o),r.status&&a.set(g8,r.status),U9(a,x8.entityName,r.entityName??n.entityName),U9(a,x8.threadId,r.threadId??n.threadId),U9(a,x8.resourceId,r.resourceId??n.resourceId),U9(a,x8.runId,n.runId),U9(a,x8.sessionId,r.sessionId??n.sessionId),U9(a,x8.requestId,n.requestId),U9(a,x8.userId,r.userId??n.userId),U9(a,x8.organizationId,n.organizationId),U9(a,x8.experimentId,n.experimentId),U9(a,x8.serviceName,n.serviceName),U9(a,x8.environment,r.environment??n.environment),WFi(a,x8.tags,n.tags),r.span&&a.append(j8,JSON.stringify(GFi(r.span))),r.model){let e={id:`metrics-model`,logic:`and`,nodes:[{id:`model`,fieldId:`spans.model`,value:r.model}]};a.append(j8,JSON.stringify(e))}let s=a.toString();return s?`${i}?${s}`:i}function qFi({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:i=`/logs`}){let a=new URLSearchParams;UFi(a,o7,s7,c7,e,t,r.window);let o=r.rootEntityType??n.rootEntityType;o&&a.set(a7,o),U9(a,l7.entityName,r.entityName??n.entityName),U9(a,l7.threadId,r.threadId??n.threadId),U9(a,l7.resourceId,r.resourceId??n.resourceId),U9(a,l7.runId,n.runId),U9(a,l7.sessionId,n.sessionId),U9(a,l7.requestId,n.requestId),U9(a,l7.userId,n.userId),U9(a,l7.organizationId,n.organizationId),U9(a,l7.experimentId,n.experimentId),U9(a,l7.serviceName,n.serviceName),U9(a,l7.environment,n.environment),WFi(a,l7.tags,n.tags),r.status===`error`&&a.append(l7.level,`error`);let s=a.toString();return s?`${i}?${s}`:i}function JFi(){let{datePreset:e,customRange:t,dimensionalFilter:n}=$7(),r=Tv(),i={preset:e,customRange:t,dashboardFilter:n};return{openTraces:(e={})=>{r(KFi({...i,scope:e}))},openLogs:(e={})=>{r(qFi({...i,scope:e}))}}}var YFi=`period`,XFi=`dateFrom`,ZFi=`dateTo`;function QFi(){let[e,t]=Mv(),n=e.get(YFi),r=Bxi(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(XFi)),i=t(e.get(ZFi));if(n||i)return{from:n,to:i}},[r,e.toString()]),a=(0,G.useMemo)(()=>hxi(e),[e.toString()]),o=(0,G.useCallback)(e=>{t(t=>{let n=new URLSearchParams(t);return e===`24h`?n.delete(YFi):n.set(YFi,e),e!==`custom`&&(n.delete(XFi),n.delete(ZFi)),n},{replace:!0})},[t]),s=(0,G.useCallback)(e=>{t(t=>{let n=new URLSearchParams(t);return e?.from?n.set(XFi,e.from.toISOString()):n.delete(XFi),e?.to?n.set(ZFi,e.to.toISOString()):n.delete(ZFi),n},{replace:!0})},[t]),c=(0,G.useCallback)(e=>{t(t=>{let n=new URLSearchParams(t);return _xi(n,e),nxi(n),n},{replace:!0})},[t]),l=(0,G.useRef)(!1);return(0,G.useEffect)(()=>{if(l.current||(l.current=!0,ixi(e)))return;let n=rxi();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)(Gxi,{preset:r,filterTokens:a,onPresetChange:o,onFilterTokensChange:c,customRange:i,onCustomRangeChange:s,children:(0,K.jsx)(VFi,{children:(0,K.jsx)($Fi,{})})})}function $Fi(){let{error:e}=Pxi(c9()),{isInMemory:t}=S7(),{data:n}=HXr(),{data:r}=t8(),{data:i}=BXr(),{data:a}=n8(),o=fxi({availableTags:n??[],availableEntityNames:r??[],availableServiceNames:i??[],availableEnvironments:a??[]});return e&&DN(e)?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:H9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),(0,K.jsx)(_H,{variant:`fill`})]}):e&&ON(e)?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:H9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),(0,K.jsx)(gH,{variant:`fill`,resource:`metrics`})]}):e?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:H9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),(0,K.jsx)(Hx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load metrics`,descriptionSlot:e.message})]}):(0,K.jsx)(RFi,{filterFields:o,children:(0,K.jsxs)(`div`,{className:`grid content-start gap-4`,children:[t&&(0,K.jsx)(gk,{variant:`info`,title:`Metrics are not persisted`,children:(0,K.jsx)(gk.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)(eIi,{})]})})}function eIi(){let{openTraces:e,openLogs:t}=JFi(),n=wp.AGENT,r=FFi(),i=(0,K.jsx)(qSi,{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)(nCi,{onViewTraces:t=>e({rootEntityType:t}),onTimeRangeClick:t=>e({window:t})}),o=(0,K.jsx)(KCi,{onViewTraces:()=>e(),onAgentClick:t=>e({rootEntityType:n,entityName:t}),onModelClick:t=>e({model:t}),onThreadClick:t=>e({threadId:t})}),s=(0,K.jsx)(VSi,{onViewTraces:()=>e(),onTimeRangeClick:t=>e({window:t})});return r===`unified`?(0,K.jsxs)(`div`,{className:`grid content-start gap-4 pb-6`,children:[(0,K.jsxs)(i9,{columns:2,children:[(0,K.jsx)(i9.Item,{children:s}),(0,K.jsx)(i9.Item,{children:i}),(0,K.jsx)(i9.Item,{children:a}),(0,K.jsx)(i9.Item,{children:(0,K.jsx)(bwi,{onTimeRangeClick:e})})]}),(0,K.jsx)(xEi,{onRowClick:e})]}):(0,K.jsxs)(`div`,{className:`grid content-start gap-4 pb-6`,children:[s,(0,K.jsxs)(i9,{columns:2,children:[(0,K.jsx)(i9.Item,{children:i}),(0,K.jsx)(i9.Item,{children:a})]}),(0,K.jsxs)(i9,{columns:2,children:[(0,K.jsx)(i9.Item,{children:(0,K.jsx)(RCi,{onViewTraces:t=>e({rootEntityType:t}),onViewErrors:e=>t({rootEntityType:e,status:`error`}),onEntityClick:(t,n)=>e({rootEntityType:t,entityName:n})})}),(0,K.jsx)(i9.Item,{children:o})]}),(0,K.jsx)(rwi,{})]})}function tIi(){let{isCmsAvailable:e}=w3(),{paths:t}=sn();return e?(0,K.jsx)(v9n,{href:t.cmsPromptBlockCreateLink(),tooltip:`Create a prompt`,children:`New prompt`}):null}var W9=[KN(`/prompts`)],nIi=50,rIi=[`updatedAt`];function iIi(){let[e,t]=(0,G.useState)(``),[n,r]=(0,G.useState)(0),[i,a]=Mv(),{sort:o,onSortChange:s}=r7({searchParams:i,setSearchParams:a,allowedKeys:rIi}),{data:c,isLoading:l,error:u,isPlaceholderData:d}=tKr({page:n,perPage:nIi,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&&DN(u)?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(_H,{variant:`fill`})]}):u&&ON(u)?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(gH,{variant:`fill`,resource:`prompt blocks`})]}):u?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(Hx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load prompt blocks`,descriptionSlot:u.message})]}):f.length===0&&!l&&n===0?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(HKr,{})]}):(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:W9}),headerActions:(0,K.jsx)(tIi,{}),actionRow:(0,K.jsx)(_K,{children:(0,K.jsx)(_K.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(wH,{...TH,onValueChange:g,label:`Search prompts`,placeholder:`Search by name or description`})})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(VKr,{promptBlocks:f,isLoading:l,search:e,currentPage:n,hasMore:p,onNextPage:m,onPrevPage:h,updatedSort:o?.direction,onSortChange:_})]})}var aIi=U(`IconEarth`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M13.725 16.8649C14.4822 16.8649 15.1643 16.4076 15.4518 15.7071C15.7636 14.9477 15.5426 14.0737 14.9073 13.5537L13.5144 12.4136C13.1981 12.1547 12.8101 11.999 12.4026 11.9673L11.8411 11.9237C11.3675 11.8868 10.9057 12.0832 10.6037 12.4498C10.2249 12.9095 10.1641 13.5534 10.45 14.0759L11.4075 15.8252C11.7584 16.4663 12.431 16.8649 13.1619 16.8649H13.725Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M4.17188 8.07009L6.08243 9.75205C6.85862 10.4354 8.04586 10.3426 8.70645 9.54695C8.9552 9.24735 9.29283 9.03467 9.67046 8.93967L11.8146 8.40028C12.5298 8.22035 13.088 7.66138 13.2669 6.94588L14.1264 3.50879`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]})),oIi=[KN(`/resources`)],sIi=[{title:`Mastra APIs`,description:`Explore and test the available REST API endpoints with the interactive Swagger UI.`,icon:aIi,href:`/swagger-ui`,external:!1},{title:`Documentation`,description:`Read the official Mastra documentation for guides, references, and tutorials.`,icon:iMt,href:`https://mastra.ai/en/docs`,external:!0},{title:`Github`,description:`Browse the source code, report issues, and contribute to the Mastra project.`,icon:qN,href:`https://github.com/mastra-ai/mastra`,external:!0},{title:`Community`,description:`Join the Mastra Discord community for help, discussion, and collaboration.`,icon:JQ,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:Jnr,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:u2n,href:`https://mastra.ai/contact?ref=studio`,external:!0}];function cIi(){return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:oIi}),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:sIi.map(e=>(0,K.jsxs)(`a`,{href:e.href,...e.external?{target:`_blank`,rel:`noreferrer`}:{},className:`group flex flex-col gap-3 rounded-lg border border-border bg-background state-layer p-5 hover:border-border-strong`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[(0,K.jsx)(e.icon,{className:c(`h-5 w-5 text-muted-foreground group-hover:text-info-indicator`,A)}),(0,K.jsx)(T,{as:`span`,variant:`subheading`,tone:`ink`,children:e.title}),e.external&&(0,K.jsx)(qN,{className:`ml-auto size-icon-sm text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100`})]}),(0,K.jsx)(T,{variant:`caption`,tone:`muted`,children:e.description})]},e.href))})})]})}function lIi(){let{isCmsAvailable:e}=w3(),{paths:t}=sn();return e?(0,K.jsx)(v9n,{href:t.cmsScorersCreateLink(),tooltip:`Create a scorer`,children:`New scorer`}):null}var G9=[KN(`/scorers`)];function uIi(){let{data:e={},isLoading:t,error:n}=NN(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)(`all`),[s,c]=(0,G.useState)();if(n&&DN(n))return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:G9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Scorers`}),(0,K.jsx)(_H,{variant:`fill`})]});if(n&&ON(n))return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:G9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Scorers`}),(0,K.jsx)(gH,{variant:`fill`,resource:`scorers`})]});if(n)return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:G9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Scorers`}),(0,K.jsx)(Hx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load scorers`,descriptionSlot:n.message})]});if(Object.keys(e).length===0&&!t)return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:G9}),headerActions:(0,K.jsx)(lIi,{}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Scorers`}),(0,K.jsx)(kRr,{})]});let l=a!==`all`||r!==``;return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:G9}),headerActions:(0,K.jsx)(lIi,{}),actionRow:(0,K.jsx)(jRr,{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)(ORr,{scorers:e,isLoading:t,search:r,sourceFilter:a,sort:s,onSortChange:(e,t)=>c({key:t,direction:e})})]})}var dIi=[`input`,`entity`],fIi={input:`Input`,entity:`Entity`};function pIi(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 mIi(){let[e,t]=(0,G.useState)(new Set),n=(0,G.useMemo)(()=>new Set(dIi.filter(t=>!e.has(t))),[e]);return{visibleColumns:n,columns:(0,G.useMemo)(()=>pIi(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 hIi({visibleColumns:e,toggleColumn:t}){return(0,K.jsxs)(ZT,{children:[(0,K.jsx)(ZT.Trigger,{asChild:!0,children:(0,K.jsx)(X,{icon:(0,K.jsx)(y3r,{}),children:`Columns`})}),(0,K.jsxs)(ZT.Content,{align:`end`,children:[(0,K.jsx)(ZT.Label,{children:`Toggle columns`}),dIi.map(n=>(0,K.jsx)(ZT.CheckboxItem,{checked:e.has(n),onClick:()=>t(n),children:fIi[n]},n))]})]})}var gIi=[KN(`/scorers`),TMt],_Ii=[`date`,`score`];function vIi(){let{scorerId:e}=Ev(),[t,n]=Mv(),r=t.get(`scoreId`)??void 0,[i,a]=(0,G.useState)(r),[o,s]=(0,G.useState)(!1),c=Tv(),[l,u]=(0,G.useState)({value:`all`,label:`All Entities`,type:`ALL`}),{scorer:d,error:f}=Gjt(e),p=mIi(),{data:m={},isLoading:h,error:g}=gN(),{isLoading:_,error:v}=KM({}),{sort:y,onSortChange:b}=r7({searchParams:t,setSearchParams:n,allowedKeys:_Ii}),{data:x=[],isLoading:S,error:C,isFetchingNextPage:w,hasNextPage:T,setEndOfListElement:E}=Wjt({scorerId:e,entityId:l?.value===`all`?void 0:l?.value,entityType:l?.type===`ALL`?void 0:l?.type}),D=(0,G.useMemo)(()=>AZ(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`;Qx.error(`Error loading scorer: ${e}`)}},[f]),(0,G.useEffect)(()=>{if(g){let e=g instanceof Error?g.message:`Failed to load agents`;Qx.error(`Error loading agents: ${e}`)}},[g]),(0,G.useEffect)(()=>{if(v){let e=v instanceof Error?v.message:`Failed to load workflows`;Qx.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=DN(f)||DN(g)||DN(v),I=f&&ON(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)(Jgi,{open:o,onOpenChange:s,initialScorerIds:[e],onSuccess:e=>void c(`/experiments/${e}`)}):null,H=B?(0,K.jsxs)(ZT,{children:[(0,K.jsx)(ZT.Trigger,{asChild:!0,children:(0,K.jsx)(X,{size:`icon-lg`,"aria-label":`Scorer actions menu`,children:(0,K.jsx)(QT,{})})}),(0,K.jsx)(ZT.Content,{align:`end`,className:`w-48`,children:(0,K.jsxs)(ZT.Item,{onSelect:()=>void c(`/cms/scorers/${e}/edit`),children:[(0,K.jsx)(XV,{}),` 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)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:gIi}),actionRow:!(F||I||L)&&H?(0,K.jsx)(_K,{children:(0,K.jsx)(_K.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)(_H,{}):I?(0,K.jsx)(gH,{resource:`scorers`}):L?(0,K.jsx)(Hx,{tone:`error`,titleSlot:`Failed to load scorer`,descriptionSlot:t}):(0,K.jsx)(wRr,{onRunExperiment:()=>s(!0)})}),V]})}return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:gIi}),actionRow:(0,K.jsxs)(_K,{children:[(0,K.jsx)(_K.Start,{children:(0,K.jsx)(TRr,{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)(_K.End,{children:[(0,K.jsx)(hIi,{visibleColumns:p.visibleColumns,toggleColumn:p.toggleColumn}),(0,K.jsx)(X,{variant:`primary`,onClick:()=>s(!0),icon:(0,K.jsx)(Ix,{}),children:`New experiment`}),H]})]}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(CRr,{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 yIi=U(`IconMoon`,()=>(0,K.jsx)(`path`,{d:`M20.9638 12.7674C19.8361 13.5447 18.4693 13.9998 16.9961 13.9998C13.1301 13.9998 9.99609 10.8657 9.99609 6.99975C9.99609 5.52667 10.4511 4.15987 11.2283 3.03223C6.61911 3.42277 3 7.28768 3 11.9979C3 16.9674 7.0286 20.996 11.9981 20.996C16.7084 20.996 20.5734 17.3767 20.9638 12.7674Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})),bIi=U(`IconSun`,()=>(0,K.jsx)(`path`,{d:`M12 3V2M12 22V21M18.3598 5.64005L19.0698 4.93005M4.93016 19.07L5.64016 18.36M21 12H22M2 12H3M18.3598 18.36L19.0698 19.07M4.93016 4.93005L5.64016 5.64005M15.5355 8.46447C17.4882 10.4171 17.4882 13.5829 15.5355 15.5355C13.5829 17.4882 10.4171 17.4882 8.46447 15.5355C6.51185 13.5829 6.51185 10.4171 8.46447 8.46447C10.4171 6.51185 13.5829 6.51185 15.5355 8.46447Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})),xIi=[{value:`system`,label:`System`,icon:(0,K.jsx)(I8n,{})},{value:`light`,label:`Light`,icon:(0,K.jsx)(bIi,{})},{value:`dark`,label:`Dark`,icon:(0,K.jsx)(yIi,{})}];function SIi(e,t){if(e.some(e=>e.value===t))return t;let[n]=e;return n?n.value:`system`}var CIi=({value:e,onChange:t,options:n=xIi,size:r=`md`,"aria-label":i=`Theme`,...a})=>{let{theme:o,setTheme:s}=B(),c=e??o,l=t??s,u=SIi(n,c);return(0,K.jsx)(Har,{...a,"aria-label":i,iconOnly:!0,size:r===`xs`?`sm`:r,value:u,onValueChange:l,children:n.map(e=>(0,K.jsx)(Uar,{value:e.value,"aria-label":e.label,children:e.icon},e.value))})};function wIi(e){return Object.fromEntries(e.filter(e=>e.name.trim()).map(e=>[e.name.trim(),e.value]))}function TIi(e,t){return e.baseUrl.trim()===t.baseUrl.trim()&&e.apiPrefix.trim()===(t.apiPrefix??``).trim()&&JSON.stringify(wIi(e.headers))===JSON.stringify(t.headers)}function EIi({initialConfig:e}){let{setConfig:t}=pS(),n=(0,G.useRef)(0),r=()=>({baseUrl:e.baseUrl,apiPrefix:e.apiPrefix??``,headers:Object.entries(e.headers).map(([e,t])=>({id:n.current++,name:e,value:t}))}),[i,a]=(0,G.useState)(r),[o,s]=(0,G.useState)(),c=!TIi(i,e),l=(0,K.jsx)(X,{type:`button`,size:`sm`,icon:(0,K.jsx)(Ix,{}),onClick:()=>a(e=>({...e,headers:[...e.headers,{id:n.current++,name:``,value:``}]})),children:`Add header`}),u=(e,t)=>a(n=>({...n,headers:n.headers.map(n=>n.id===e?{...n,...t}:n)}));function d(e){e.preventDefault(),i.baseUrl.trim()?(t({baseUrl:i.baseUrl.trim(),apiPrefix:i.apiPrefix.trim()||void 0,headers:wIi(i.headers)}),Qx.success(`Connection saved`)):s(`Enter the server URL`)}function f(){a(r()),s(void 0)}return(0,K.jsx)(`form`,{onSubmit:d,onReset:f,noValidate:!0,children:(0,K.jsxs)(fZ,{children:[(0,K.jsx)(dZ,{label:`Mastra instance URL`,description:`The server this studio talks to.`,errorMsg:o,children:(0,K.jsx)(Hj,{name:`url`,value:i.baseUrl,placeholder:`http://localhost:4111`,spellCheck:!1,onChange:e=>{a(t=>({...t,baseUrl:e.target.value})),s(void 0)}})}),(0,K.jsx)(dZ,{label:`API prefix`,description:`Path in front of every API route.`,children:(0,K.jsx)(Hj,{name:`apiPrefix`,value:i.apiPrefix,placeholder:`/api (default)`,spellCheck:!1,onChange:e=>a(t=>({...t,apiPrefix:e.target.value}))})}),i.headers.length===0?(0,K.jsx)(hZ,{action:l,children:`No request headers`}):(0,K.jsx)(n7n,{action:l,children:i.headers.length===1?`1 request header`:`${i.headers.length} request headers`}),i.headers.map(e=>(0,K.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(Hj,{"aria-label":`Header name`,value:e.name,placeholder:`Authorization`,spellCheck:!1,onChange:t=>u(e.id,{name:t.target.value})}),(0,K.jsx)(Hj,{"aria-label":e.name?`Value of ${e.name}`:`Header value`,value:e.value,placeholder:`Bearer <token>`,spellCheck:!1,onChange:t=>u(e.id,{value:t.target.value})}),(0,K.jsx)(X,{type:`button`,size:`icon-md`,variant:`ghost`,"aria-label":e.name?`Remove ${e.name}`:`Remove header`,tooltip:`Remove header`,onClick:()=>a(t=>({...t,headers:t.headers.filter(t=>t.id!==e.id)})),children:(0,K.jsx)(Bj,{})})]},e.id)),c?(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,K.jsx)(`span`,{className:`text-body-sm text-muted-foreground`,children:`Unsaved changes`}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(X,{type:`reset`,size:`sm`,variant:`ghost`,children:`Discard`}),(0,K.jsx)(X,{type:`submit`,size:`sm`,variant:`primary`,children:`Save changes`})]})]}):null]})})}function DIi(){let{baseUrl:e,apiPrefix:t,headers:n}=pS(),r=JSON.stringify([e,t??``,n]);return(0,K.jsxs)(pZ,{children:[(0,K.jsx)(mZ,{info:`The Mastra instance the studio talks to, the path in front of its API routes, and the headers sent with every request.`,children:`Mastra connection`}),(0,K.jsx)(EIi,{initialConfig:{baseUrl:e,apiPrefix:t,headers:n}},r)]})}var OIi=()=>(0,K.jsx)(MS,{children:(0,K.jsxs)(e7n,{title:`Settings`,children:[(0,K.jsxs)(pZ,{children:[(0,K.jsx)(mZ,{info:`Stored in this browser.`,children:`General`}),(0,K.jsx)(fZ,{children:(0,K.jsx)(dZ,{label:`Theme`,description:`Color scheme for the interface.`,children:(0,K.jsx)(CIi,{})})})]}),(0,K.jsx)(DIi,{})]})});function kIi(){let[e]=Mv(),t=Tv(),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`})}var AIi=[`traces`,`spans`],jIi={traces:{icon:(0,K.jsx)(WN,{}),label:`Traces`},spans:{icon:(0,K.jsx)(VV,{}),label:`Spans`},threads:{icon:(0,K.jsx)(Oq,{}),label:`Threads`}};function MIi({current:e,views:t=AIi,onViewChange:n}){return(0,K.jsx)(`nav`,{"aria-label":`Observability views`,children:(0,K.jsx)(uk,{value:e,defaultTab:e,onValueChange:n,children:(0,K.jsx)(lk,{variant:`pill-ghost`,children:t.map(e=>(0,K.jsxs)(dk,{value:e,children:[(0,K.jsx)(xx,{size:`xs`,children:jIi[e].icon}),(0,K.jsx)(T,{variant:`caption`,className:`text-inherit`,children:jIi[e].label})]},e))})})})}function NIi(){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)(NS,{className:`h-control-md w-20 rounded-full`}),(0,K.jsx)(NS,{className:`h-control-md w-20 rounded-full`})]})}function PIi({current:e,views:{views:t,isLoading:n,showSwitch:r},onViewChange:i,breadcrumbs:a,children:o}){let[s,c]=(0,G.useState)(null),l=fai(),u;return n?u=(0,K.jsx)(NIi,{}):r&&(u=(0,K.jsx)(MIi,{current:e,views:t,onViewChange:i})),(0,K.jsx)(MS,{breadcrumbs:a({current:e,isLoading:n,showSwitch:r}),actionRow:(u||l)&&(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center justify-between gap-3`,children:[u,(0,K.jsx)(`div`,{ref:c,className:`flex min-w-0 grow justify-end`})]}),children:(0,K.jsx)(xsi.Provider,{value:s??void 0,children:o})})}function FIi({isLoading:e,enabled:t,heading:n,title:r,description:i,children:a}){return t?a:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:n}),e?(0,K.jsxs)(`div`,{className:`flex h-full items-center justify-center gap-2`,children:[(0,K.jsx)(It,{"aria-label":`Loading storage capabilities`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:`Loading storage capabilities`})]}):(0,K.jsx)(Hx,{variant:`fill`,titleSlot:r,descriptionSlot:i})]})}function IIi({current:e,features:t}){let n=Ysi(),r=Xsi(),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 LIi={refetchInterval:({state:e})=>Usi(e.error),refetchOnWindowFocus:!1};function RIi(e){let[t,n]=(0,G.useState)(()=>new URLSearchParams);return e||{searchParams:t,setSearchParams:e=>n(t=>typeof e==`function`?e(t):e)}}function zIi(e,{sortFields:t,withTokenSearch:n=!1,defaultDatePreset:r=yai}={}){let{searchParams:i,setSearchParams:a}=RIi(e),o=JSON.stringify(Tai(i,r)),s=JSON.stringify(Dai(i)),{datePreset:c,dateFrom:l,dateTo:u}=(0,G.useMemo)(()=>Tai(i,r),[o]),{tokens:d,groups:f}=(0,G.useMemo)(()=>{let e=Dai(i);return n?e:{...e,tokens:e.tokens.filter(e=>e.operatorId!==`hasAllTokens`)}},[s,n]),p=kai(i,t??_ai),m=(0,G.useMemo)(()=>({field:p.field,direction:p.direction}),[p.field,p.direction]),h=l?.getTime(),g=u?.getTime(),_=(0,G.useMemo)(()=>{let e=new Date,t=k4r(c,h===void 0?void 0:new Date(h),g===void 0?void 0:new Date(g),e);return d8(t.dateFrom,t.dateTo,e)},[c,h,g]),v=(0,G.useRef)(null);(0,G.useLayoutEffect)(()=>{v.current=null},[i]);let y=e=>{let t=v.current??i,n=new URLSearchParams(t);e(n),n.toString()!==t.toString()&&(v.current=n,a(n,{replace:!0}))},b=e=>y(t=>Eai(t,e(Tai(t,r)),r)),x=(0,G.useRef)(void 0),S=e=>{x.current=void 0,b(e)},C=e=>S(t=>e===`custom`?{...t,datePreset:e}:{datePreset:e}),w=(e,t)=>S(n=>n.datePreset===`custom`?t===`from`?{...n,dateFrom:e}:{...n,dateTo:e}:n),T=(e,t)=>S(n=>n.datePreset===`custom`?{...n,dateFrom:e,dateTo:t}:n),E=(e,t)=>b(n=>(x.current=rai(x.current,n,e,t),{datePreset:`custom`,dateFrom:e,dateTo:t})),D=e=>b(t=>{let n=iai(x.current,t);return x.current=void 0,n??{datePreset:e}}),O=(e,t)=>y(n=>Oai(n,{tokens:e,groups:t})),k=e=>y(t=>Aai(t,e)),A=d.length>0||f.length>0;return{datePreset:c,dateFrom:l,dateTo:u,timeRange:_,rolling:u===void 0,tokens:d,groups:f,sort:m,setSort:k,onDatePresetChange:C,onDateChange:w,onDateRangeChange:T,onZoom:E,onDateReset:D,onFiltersChange:O,contentFiltersApplied:A,filtersApplied:A||c!==r}}function BIi(e){return[`observability-list-head`,...e]}function VIi(e,t,n=!1){if(n)return{from:e.from,to:t};let r=Date.parse(e.to)-Date.parse(e.from);return{from:new Date(Date.parse(t)-r).toISOString(),to:t}}function HIi(e,t=!1){let n=d_([e]),[r,i]=(0,G.useState)();return{anchorWindow:r?.selectionHash===n?r.window:void 0,reanchor:e=>i({selectionHash:n,window:VIi(e,new Date().toISOString(),t)})}}var UIi=()=>({rows:[],watermark:void 0});function WIi({queryKey:e,fetchHead:t,getId:n,getEndedAt:r,enabled:i,since:a,limit:o=50,maxRows:s=500,interval:c=zsi,onOverflow:l}){let u=s_(),d=BIi(e),{data:f}=S_({queryKey:d,queryFn:async()=>{let e=u.getQueryData(d)??UIi(),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?.(),UIi();let m=c.length>0?Math.max(e.watermark??-1/0,...c):e.watermark;return{rows:[...f.values()],watermark:m}},initialData:UIi,staleTime:1/0,enabled:i,refetchInterval:e=>!Vsi(e.state.error)&&c,refetchOnWindowFocus:!1,refetchOnReconnect:!1,retry:!1});return{headRows:f.rows}}function GIi(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 KIi(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),GIi(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 qIi={traces:`Traces`,spans:`Spans`,threads:`Threads`};function JIi({current:e,isLoading:t,showSwitch:n}){if(!(t||n||e===`traces`))return qIi[e]}function YIi(e){let t=e.get(`traceId`),n=e.get(`spanId`);return t&&n?{traceId:t,spanId:n}:void 0}function XIi(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 ZIi({traceId:e,spanId:t}){return new URLSearchParams({traceId:e,spanId:t})}function QIi(e){return e.get(`threadId`)??void 0}function $Ii(e,t){let n=new URLSearchParams(e);return t?n.set(`threadId`,t):n.delete(`threadId`),n}var eLi=e=>`${e.traceId}:${e.spanId}`;function tLi(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 nLi({query:e,rolling:t,fixedStart:n=!1,autoRefetch:r=!0,limit:i,enabled:a=!0}){let o=Y(),{anchorWindow:s,reanchor:c}=HIi(e,n),l=(0,G.useMemo)(()=>s?{...e,timeRange:{...e.timeRange,...s}}:e,[e,s]),u=dZr({query:l,limit:i,enabled:a,queryOptions:LIi}),{headRows:d}=WIi({queryKey:[`spans`,e],fetchHead:async t=>(await o.querySpans({...e,timeRange:{...e.timeRange,...VIi(e.timeRange,t,n)},orderBy:[{field:`endedAt`,direction:`desc`}],page:{limit:50}})).spans,getId:eLi,getEndedAt:e=>e.endedAt,since:Date.parse(l.timeRange.to),enabled:a&&t&&r&&u.spans!==void 0&&!u.isFetching&&!u.isError,onOverflow:()=>c(e.timeRange)}),{orderBy:f}=e,p=u.spans,m=(0,G.useMemo)(()=>p&&KIi(p,d,{getId:eLi,compare:tLi(f),hasNextPage:u.hasNextPage}),[p,d,f,u.hasNextPage]);return{...u,spans:m}}function rLi(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 iLi({timeRange:e,where:t,onZoom:n}){let r=Zsi(),i=(0,G.useMemo)(()=>({timeRange:e,...t?{where:t}:{},interval:H4r(e).interval,measures:[...P4r],limit:1}),[e,t]),a=!r.enabled||U4r(e),{data:o,isLoading:s,isError:c,isPlaceholderData:l}=qXr({request:i,enabled:!a,queryOptions:{placeholderData:m_}}),u=(0,G.useMemo)(()=>J4r(o?.rows??[],e),[o,e]);return a?null:(0,K.jsx)(a7r,{label:`Spans over time`,resourceLabel:`Spans`,buckets:u,isLoading:s,isError:c,isUpdating:l,onZoom:n&&(t=>n(Y4r(u,t,e)))})}var aLi=[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`],oLi=[];function sLi({timeRange:e,withTokenSearch:t=!1}){let n=Y(),{data:r}=m7(),i=r?.capabilities.spanQueryContextFields??!1,a=r?.capabilities.traceQueryTimeToFirstChunk??!1,o=r?.capabilities.traceQueryTimeToFirstToken??!1,s=r?.capabilities.spanQueryOutcomeFields??!1,c=r?.capabilities.spanQueryModelFields??!1,{data:l=oLi}=t8(),{data:u=oLi}=n8();return(0,G.useMemo)(()=>[e8r,...V6(uoi({withContextFields:i,withTimeToFirstChunk:a,withTimeToFirstToken:o,withOutcomeFields:s,withModelFields:c,entityNames:l,environments:u,valueSuggestions:t=>QZr(n,e,`spans`,t)}),t)],[t,i,a,o,s,c,l,u,n,e])}function cLi({tokens:e,groups:t,onFiltersChange:n}){let r=(0,G.useMemo)(()=>l$r(e),[e]),i=(0,G.useMemo)(()=>{let e=f$r([],t);return{...e,nodes:[s5,...r,...e.nodes]}},[r,t]),a=(0,G.useCallback)(e=>{let t=m$r({...e,nodes:e.nodes.filter(e=>H6(e)||e.fieldId!==`timeRange`)});n(t.tokens,t.groups)},[n]);return{filterBarValue:i,onFilterBarChange:a,onFilterByField:(0,G.useCallback)((e,t)=>{let n=r.filter(t=>t.fieldId!==e),o={id:`${e}:${t}`,fieldId:e,operatorId:`is`,value:t},s=i.nodes.filter(H6);a({...i,nodes:[...n,o,...s]})},[r,i,a])}}var lLi=e=>e;function uLi({withTokenSearch:e=!1,datePreset:t,dateFrom:n,dateTo:r,minDate:i,timeRange:a,tokens:o,groups:s,onDatePresetChange:c,onDateChange:l,onDateRangeChange:u,onDateReset:d,onFiltersChange:f,describeSuggestionsError:p,disabled:m}){let h=sLi({timeRange:a,withTokenSearch:e}),{filterBarValue:g,onFilterBarChange:_}=cLi({tokens:o,groups:s,onFiltersChange:f});return(0,K.jsxs)(c5,{fields:h,operators:LQr,value:g,onValueChange:_,createItemId:lLi,describeSuggestionsError:p,maxDepth:3,"aria-label":`Span filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(c5.Chips,{renderChip:e=>e.fieldId===`timeRange`?(0,K.jsx)(c5.TimeRange,{preset:t,onPresetChange:c,dateFrom:n,dateTo:r,minDate:i,onDateChange:l,onDateRangeChange:u,disabled:m,presets:aLi,defaultPreset:K8.datePreset,onReset:d&&(()=>d(K8.datePreset))}):(0,K.jsx)(c5.Chip,{item:e})}),(0,K.jsx)(c5.Input,{placeholder:`Filter spans`})]})}var dLi={supported:!1,isLoading:!1};function fLi(e){let t=h7(),n=Ysi(),r=Xsi();return e===`spans`?n:e===`threads`?r:t}var pLi=(0,G.memo)(function({scope:e,value:t,onChange:n,discoveryTimeRange:r,metricsSupport:i=dLi,queryEnabled:a=!0}){let o=W8[e],s=fLi(e),c=Qsi(),{data:l}=m7(),[u]=(0,G.useState)(()=>d8(void 0,void 0,new Date)),d=s.enabled&&a,f=d&&(l?.capabilities.traceQueryTimeToFirstChunk??!1),p=d&&(l?.capabilities.traceQueryTimeToFirstToken??!1),m=(0,G.useMemo)(()=>{if(f&&p)return o;let e=o.standardColumns.filter(e=>(f||e!==`timeToFirstChunk`)&&(p||e!==`timeToFirstToken`));return{...o,standardColumns:e}},[o,f,p]),{fields:h}=$Zr({timeRange:r??u,queryOptions:{enabled:o.metadata&&d&&c.enabled}}),g=(0,G.useMemo)(()=>{let e=new Set;for(let t of h){let n=t.path.replace(/^metadata\./,``).split(`.`)[0];n&&e.add(n)}return[...e].sort()},[h]),_=i.isLoading?Z4r:i.supported?void 0:Q4r;return(0,K.jsx)(S3r,{preferences:t,catalog:m,availableMetadataKeys:g,usageDisabledReason:_,withQueryTrace:d,disabled:s.isLoading,onToggleColumn:e=>n(Z2r(t,e)),onAddCustomColumn:e=>n(Q2r(t,e)),onRemoveCustomColumn:e=>n($2r(t,e)),onAddMetadataColumn:e=>n(e4r(t,e)),onRemoveMetadataColumn:e=>n(t4r(t,e)),onReset:()=>n(o.defaults)})});function mLi({selection:e,onSelectionChange:t,renderPanel:n,urlState:r}){let{data:i,isLoading:a}=m7(),o=!!(i?.capabilities.spanQueryTokenSearch&&i.capabilities.spanAggregateTokenSearch),s=zIi(r,{sortFields:vai,withTokenSearch:o}),{timeRange:c,tokens:l,groups:u}=s,d=Psi({scope:`spans`}),f=i?.capabilities.spanQueryContextFields??!1,p=i?.capabilities.traceQueryTimeToFirstChunk??!1,m=i?.capabilities.traceQueryTimeToFirstToken??!1,h=i?.capabilities.spanQueryOutcomeFields??!1,g=i?.capabilities.spanQueryModelFields??!1,_=(0,G.useMemo)(()=>a?d.preferences:X2r(d.preferences,{withTimeToFirstChunk:p,withTimeToFirstToken:m}),[d.preferences,a,p,m]),v=(0,G.useMemo)(()=>{let e=[`startedAt`];return p&&i?.capabilities.traceQueryTimeToFirstChunkSort&&G8(_,`timeToFirstChunk`)&&e.push(`timeToFirstChunkMs`),m&&i?.capabilities.traceQueryTimeToFirstTokenSort&&G8(_,`timeToFirstToken`)&&e.push(`timeToFirstTokenMs`),e},[i,p,m,_]),y=v.includes(s.sort.field)?s.sort:{field:`startedAt`,direction:`desc`},{field:b,direction:x}=y,S=(0,G.useMemo)(()=>poi(l,u,{withTokenSearch:o,withContextFields:f,withOutcomeFields:h,withModelFields:g,withTimeToFirstChunk:p,withTimeToFirstToken:m}),[l,u,o,f,h,g,p,m]),{spans:C,hasNextPage:w,isFetchingNextPage:T,setEndOfListElement:E,isLoading:D,isError:O,error:k}=nLi({query:(0,G.useMemo)(()=>({timeRange:c,orderBy:[{field:b,direction:x}],where:S}),[c,b,x,S]),enabled:!a,rolling:s.rolling,fixedStart:s.datePreset===`custom`}),A=(0,G.useMemo)(()=>(C??[]).map(rLi),[C]),j=(0,G.useMemo)(()=>A.flatMap(e=>e.spanId?[{traceId:e.traceId,spanId:e.spanId}]:[]),[A]),M=n=>{n.spanId&&t(e?.traceId===n.traceId&&e.spanId===n.spanId?void 0:{traceId:n.traceId,spanId:n.spanId})},N=!D&&!O&&A.length===0&&!s.contentFiltersApplied&&!e;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Spans`}),(0,K.jsx)(g3r,{toolbar:(0,K.jsxs)(K.Fragment,{children:[r&&(0,K.jsx)(ksi,{page:`spans`,...r,columns:d}),(0,K.jsxs)(_K,{children:[(0,K.jsx)(_K.Start,{children:(0,K.jsx)(uLi,{withTokenSearch:o,datePreset:s.datePreset,dateFrom:s.dateFrom,dateTo:s.dateTo,timeRange:c,tokens:l,groups:u,onDatePresetChange:s.onDatePresetChange,onDateChange:s.onDateChange,onDateRangeChange:s.onDateRangeChange,onDateReset:s.onDateReset,onFiltersChange:s.onFiltersChange,disabled:D})}),(0,K.jsx)(_K.End,{children:(0,K.jsx)(pLi,{scope:`spans`,value:d.preferences,onChange:d.setPreferences})})]})]}),chart:(0,K.jsx)(iLi,{timeRange:c,where:S,onZoom:({from:e,to:t})=>s.onZoom(e,t)}),error:O?(0,K.jsx)(U8,{error:k,resource:`spans`,errorTitle:`Failed to load spans`}):void 0,empty:N?(0,K.jsx)(O2r,{resource:`spans`,datePreset:s.datePreset,dateFrom:s.dateFrom,dateTo:s.dateTo}):void 0,children:(0,K.jsx)(R9r,{listId:`all-spans`,traces:A,columnPreferences:_,isLoading:D,isFetchingNextPage:T,hasNextPage:w,setEndOfListElement:E,filtersApplied:s.filtersApplied,resource:`spans`,isBranchesMode:!0,sort:y,sortableFields:v,onSortChange:s.setSort,featuredTraceId:e?.traceId,featuredSpanId:e?.spanId,onTraceClick:M})}),n({selection:e,spans:j,onSelect:t,onClose:()=>t(void 0)})]})}function hLi({selection:e,spans:t,onSelect:n,onClose:r,onShowTrace:i}){let{data:a,isLoading:o}=r8({traceId:e.traceId,spanId:e.spanId}),s=qli(),c=t.findIndex(t=>t.traceId===e.traceId&&t.spanId===e.spanId),l=c>0?t[c-1]:void 0,u=c>=0&&c<t.length-1?t[c+1]:void 0;return(0,K.jsx)(qii,{traceId:e.traceId,spanId:e.spanId,span:a?.span,isLoading:o,input:(0,K.jsx)(y7,{}),output:(0,K.jsx)(uli,{}),navigation:s,onPrevious:l?()=>n(l):void 0,onNext:u?()=>n(u):void 0,onClose:r,onShowTrace:i})}function gLi({selection:e,spans:t,onSelect:n,onClose:r,onShowTrace:i}){let a=Gw();y2r(e?`${e.traceId}:${e.spanId}`:void 0,r);let o=e?(0,K.jsx)(hLi,{selection:e,spans:t,onSelect:n,onClose:r,onShowTrace:i}):null;return a?(0,K.jsx)(dQ,{open:!!e,onClose:r,title:`Span details`,children:o}):o?(0,K.jsx)(B8,{owner:`span-detail`,children:(0,K.jsx)(dQ,{variant:`inline`,title:`Span details`,children:o})}):null}function _Li(){let{enabled:e,isLoading:t}=Ysi(),n=Tv(),[r,i]=Mv();return(0,K.jsx)(FIi,{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)(mLi,{urlState:{searchParams:r,setSearchParams:i},selection:YIi(r),onSelectionChange:e=>i(t=>XIi(t,e),{replace:!0}),renderPanel:e=>(0,K.jsx)(gLi,{...e,onShowTrace:e=>n(`/traces?${ZIi(e)}`)})})})}async function vLi(){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 yLi({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 bLi({repoOrSlug:e,owner:t}){let{templates:n}=await vLi(),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 yLi({repo:e,owner:t});if(r)return r;throw Error(`Template ${e} not found`)}return r}async function xLi({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(`
|
|
821
|
-
`).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 SLi=({queryOptions:e}={})=>S_({queryKey:[`mastra-templates`],queryFn:vLi,...e}),CLi=({repoOrSlug:e,owner:t,queryOptions:n})=>S_({queryKey:[`template-repo`,e,t],queryFn:()=>bLi({repoOrSlug:e,owner:t}),...n}),wLi=({repo:e,owner:t,branch:n,queryOptions:r})=>S_({queryKey:[`template-repo-env-vars`,e,t,n],queryFn:()=>xLi({repo:e,owner:t,branch:n}),...r}),TLi=({queryOptions:e}={})=>{let t=Y();return S_({queryKey:[`agent-builder-workflow`],queryFn:async()=>await t.getAgentBuilderAction(`merge-template`).details(),...e})},ELi=({queryOptions:e}={})=>{let t=Y();return w_({mutationFn:async({runId:e})=>await t.getAgentBuilderAction(`merge-template`).createRun({runId:e}),...e})},DLi=({queryOptions:e}={})=>{let t=Y();return w_({mutationFn:async({runId:e})=>await t.getAgentBuilderAction(`merge-template`).runById(e),...e})},OLi=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)},kLi=(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=OLi(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=OLi(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}},ALi=(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)}},jLi=(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}=kLi(a,s,e);s=c,r(c),(a.runId||i||t)&&ALi(a.runId||i||t,c)}}catch(t){console.error(`💥 [processStream] Error processing template installation stream:`,t);let{newState:n}=kLi({type:`error`,payload:{error:t instanceof Error?t.message:`Unknown error`}},s,e);r(n)}finally{a(!1),o.releaseLock()}}}},MLi=({workflowInfo:e,queryOptions:t}={})=>{let n=Y(),{streamResult:r,isStreaming:i,processStream:a}=jLi(e);return{streamInstall:w_({mutationFn:async({inputData:e,selectedModel:t,runId:r})=>{for(let i=1;i<=3;i++)try{let i=n.getAgentBuilderAction(`merge-template`),o=new On;o.set(`selectedModel`,t);let s=await i.stream({inputData:e,requestContext:o},r);await a(s,r);return}catch(e){console.error(`💥 [streamInstall] Attempt ${i} failed:`,e);let t=e?.message?.includes(`Failed to fetch`)||e?.message?.includes(`NetworkError`)||e?.message?.includes(`network error`)||e?.message?.includes(`fetch`)||e?.code===`NETWORK_ERROR`||e?.name===`TypeError`;if(console.warn(`Stream attempt ${i}/3 failed:`,e),t){let e=r?`Network error during template installation (likely hot reload). Please refresh the page to resume from where you left off using runId: ${r}`:`Network error during template installation (likely hot reload). Please try again.`;throw console.error(`🔌 Stream network error:`,e),Error(e)}throw console.error(`❌ [streamInstall] Non-network error or max retries reached, throwing:`,e),e}},...t?.streamInstall}),streamResult:r,isStreaming:i}},NLi=({workflowInfo:e,queryOptions:t}={})=>{let n=Y(),{streamResult:r,isStreaming:i,processStream:a}=jLi(e);return{observeInstall:w_({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 PLi(e){return e.replace(/\/$/,``).split(`/`).pop()}function FLi({templates:e,linkComponent:t,className:n,isLoading:r}){let i=t||`a`;return r?(0,K.jsx)(`div`,{className:c(`grid gap-y-4`,n),children:Array.from({length:5}).map((e,t)=>(0,K.jsx)(`div`,{className:`h-16 animate-pulse rounded-lg bg-card`},t))}):(0,K.jsx)(`div`,{className:c(`grid gap-y-4`,n),children:e.map(e=>{let t=e?.agents||e?.tools||e?.networks||e?.workflows||e?.mcp;return(0,K.jsxs)(`article`,{className:c(Pv,`grid w-full grid-cols-[1fr_auto] overflow-hidden rounded-lg state-layer`),children:[(0,K.jsxs)(i,{to:`/templates/${e.slug}`,className:c(`group grid`,{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":e.imageURL}),children:[e.imageURL&&(0,K.jsx)(`div`,{className:`overflow-hidden`,children:(0,K.jsx)(`div`,{className:`thumb transition-scale h-full w-full bg-cover duration-150`,style:{backgroundImage:`url(${e.imageURL})`}})}),(0,K.jsxs)(`div`,{className:c(`grid w-full gap-0.5 px-4 py-3`,`[&_svg]:h-[1em] [&_svg]:w-[1em] [&_svg]:text-muted-foreground`),children:[(0,K.jsx)(T,{as:`h2`,tone:`ink`,children:e.title}),(0,K.jsx)(T,{className:c(_S,A),children:e.description}),(0,K.jsxs)(`div`,{className:`mt-3 hidden flex-wrap items-center gap-x-8 gap-y-4 text-muted-foreground 2xl:flex`,children:[t&&(0,K.jsxs)(`ul`,{className:c(`text-muted-foreground`,`m-0 flex list-none gap-4 p-0`,`[&>li]:flex [&>li]:items-center [&>li]:gap-0.5`),children:[e?.agents&&e.agents.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(PN,{}),` `,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)(HN,{}),` `,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)(T7e,{}),` `,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)(GS,{}),` `,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)(RN,{}),` `,e.mcp.length]})})]}),(0,K.jsx)(`div`,{className:`flex items-center gap-4`,children:e.supportedProviders.map(e=>(0,K.jsx)(T,{tone:`muted`,as:`span`,variant:`body`,children:e},e))})]})]})]}),(0,K.jsx)(`a`,{href:e.githubUrl,className:c(`group ml-auto hidden items-center gap-2 pr-4`,`lg:flex`),target:`_blank`,rel:`noopener noreferrer`,children:(0,K.jsx)(T,{as:`span`,variant:`body`,children:(0,K.jsxs)(`span`,{className:c(`flex items-center gap-2 rounded bg-sidebar px-2 py-1`,lBe,_S,A),children:[(0,K.jsx)(CZ,{}),` `,PLi(e.githubUrl)]})})})]},e.slug)})})}function ILi({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:i,onProviderChange:a,searchTerm:o,onSearchChange:s,onReset:l,className:u,isLoading:d}){return d?(0,K.jsxs)(`div`,{className:c(`flex h-[6.5rem] items-center gap-5`,`[&>div]:h-8 [&>div]:w-48 [&>div]:animate-pulse [&>div]:bg-card`,u),children:[(0,K.jsx)(`div`,{}),` `,(0,K.jsx)(`div`,{}),` `,(0,K.jsx)(`div`,{})]}):(0,K.jsxs)(`div`,{className:c(`sticky top-0 mx-auto flex flex-wrap gap-1.5 bg-background py-5`,u),children:[(0,K.jsx)(wH,{label:`Search templates`,placeholder:`Search templates`,size:`sm`,value:o,onValueChange:s}),(0,K.jsxs)(Pk,{value:t,onValueChange:i,children:[(0,K.jsx)(Ik,{"aria-label":`Search by tag`,size:`sm`,className:`w-auto`,children:(0,K.jsx)(Fk,{placeholder:`Select an option`})}),(0,K.jsx)(Lk,{children:e.map(e=>(0,K.jsx)(Rk,{value:e.value,children:e.label},e.value))})]}),(0,K.jsxs)(Pk,{value:r,onValueChange:a,children:[(0,K.jsx)(Ik,{"aria-label":`Search by provider`,size:`sm`,className:`w-auto`,children:(0,K.jsx)(Fk,{placeholder:`Select an option`})}),(0,K.jsx)(Lk,{children:n.map(e=>(0,K.jsx)(Rk,{value:e.value,children:e.label},e.value))})]}),l&&(0,K.jsx)(J4,{onClick:l})]})}var LLi=[{id:`templates`,label:`Templates`}];function RLi(){let{data:e,isLoading:t}=SLi(),{templates:n,tags:r,providers:i}=e??{templates:[],tags:[],providers:[]},[a,o]=(0,G.useState)(`all`),[s,l]=(0,G.useState)(`all`),[u,d]=(0,G.useState)(``),f=[{value:`all`,label:`Any tag`}];(r||[]).forEach(e=>{f.push({value:e,label:e})});let p=[{value:`all`,label:`Any provider`}];(i||[]).forEach(e=>{p.push({value:e,label:e})});let m=(e,t)=>{t===`tag`?o(e):t===`provider`&&l(e)},h=e=>{d(e)},g=()=>{o(`all`),l(`all`),d(``)},_=n.filter(e=>!(u&&!e.title.toLowerCase().includes(u)&&!e.description.toLowerCase().includes(u)||a!==`all`&&!e.tags.includes(a)||s!==`all`&&!e.supportedProviders.includes(s))),v=u||a!==`all`||s!==`all`;return(0,K.jsxs)(MS,{variant:`fit`,breadcrumbs:(0,K.jsx)(uN,{crumbs:LLi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Templates`}),(0,K.jsx)(vS,{children:(0,K.jsxs)(xJe,{children:[(0,K.jsx)(xx,{children:(0,K.jsx)(SZ,{})}),`Templates`]})}),(0,K.jsxs)(`div`,{className:c(`z-10 h-full w-full overflow-y-auto px-5 pb-12`),children:[(0,K.jsx)(ILi,{selectedTag:a,onTagChange:e=>m(e,`tag`),tagOptions:f,selectedProvider:s,onProviderChange:e=>m(e,`provider`),providerOptions:p,searchTerm:u,onSearchChange:h,onReset:v?g:void 0,className:`max-w-[80rem]`,isLoading:t}),(0,K.jsx)(FLi,{templates:_,linkComponent:jv,className:`mx-auto max-w-[80rem]`,isLoading:t})]})]})}var zLi=U(`IconEmojiSad`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`circle`,{cx:`12`,cy:`12`,r:`9`,stroke:`currentColor`,strokeWidth:`2`}),(0,K.jsx)(`path`,{d:`M10.75 9.9C10.75 11.0046 10.0784 11.75 9.25 11.75C8.42157 11.75 7.75 11.0046 7.75 9.9C7.75 8.79543 8.42157 8 9.25 8C10.0784 8 10.75 8.79543 10.75 9.9Z`,fill:`currentColor`}),(0,K.jsx)(`path`,{d:`M16.25 9.9C16.25 11.0046 15.5784 11.75 14.75 11.75C13.9216 11.75 13.25 11.0046 13.25 9.9C13.25 8.79543 13.9216 8 14.75 8C15.5784 8 16.25 8.79543 16.25 9.9Z`,fill:`currentColor`}),(0,K.jsx)(`path`,{d:`M7.89328 15.4758C7.7698 15.623 7.69925 15.8109 7.70417 16.0051C7.70903 16.1992 7.78791 16.3827 7.92489 16.5166C8.06187 16.6504 8.24712 16.7251 8.44131 16.7254C8.63557 16.7259 8.82181 16.651 8.9661 16.5242C9.05273 16.4499 9.14033 16.3801 9.23093 16.313C10.042 15.7109 11.0211 15.4001 12.0034 15.4C12.9856 15.3986 13.964 15.7081 14.7725 16.3111C14.8628 16.3783 14.9501 16.4481 15.0364 16.5226C15.1803 16.6498 15.3663 16.7253 15.5606 16.7254C15.7548 16.7256 15.9403 16.6515 16.0776 16.5181C16.215 16.3846 16.2944 16.2014 16.2999 16.0073C16.3054 15.8131 16.2354 15.625 16.1124 15.4774C16.0126 15.3603 15.909 15.2487 15.799 15.1403C14.816 14.1611 13.4082 13.5927 12.002 13.6C10.5957 13.595 9.19111 14.1644 8.20718 15.1399C8.09708 15.2479 7.99334 15.3591 7.89328 15.4758Z`,fill:`currentColor`})]}));function BLi({children:e,className:t}){return(0,K.jsx)(`div`,{className:c(`transition-height mt-12 rounded-lg border border-border px-4 py-5 lg:min-h-[25rem] lg:px-12`,t),children:e})}function VLi({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)(Gx,{className:`text-warning-foreground`}),title:`Template Installed with Warnings`}:{icon:(0,K.jsx)(zLi,{}),title:`Template Installation Failed`};return(0,K.jsxs)(BLi,{className:`mb-5 content-center space-y-4 text-muted-foreground`,children:[(0,K.jsxs)(`div`,{className:`grid content-center items-center justify-items-center gap-4 [&>svg]:h-8 [&>svg]:w-8`,children:[o,(0,K.jsxs)(`div`,{className:`space-y-2 text-center`,children:[(0,K.jsx)(T,{variant:`subheading`,tone:`ink`,children:s}),(0,K.jsx)(T,{tone:`muted`,children:a()})]})]}),t&&t.length>0&&(0,K.jsxs)(`details`,{children:[(0,K.jsx)(`summary`,{className:c(`text-muted-foreground hover:text-foreground`,`cursor-pointer text-center select-none`),children:(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[`Show Validation Issues (`,t.length,`)`]})}),(0,K.jsx)(`div`,{className:`mt-4 max-h-60 space-y-2 overflow-auto rounded bg-muted p-3 text-left`,children:t.map((e,t)=>(0,K.jsxs)(`div`,{className:`border-l-2 border-destructive-indicator pl-2`,children:[(0,K.jsx)(T,{as:`p`,variant:`column`,className:`text-destructive-foreground`,children:e.type===`typescript`?`🔴 TypeScript Error`:`⚠️ Lint Error`}),(0,K.jsx)(iC,{className:`mt-1 text-caption wrap-break-word whitespace-pre-wrap text-muted-foreground`,code:e.message})]},t))})]}),n&&!i&&(0,K.jsxs)(`details`,{children:[(0,K.jsx)(`summary`,{className:c(`text-muted-foreground hover:text-foreground`,`cursor-pointer text-center select-none`),children:(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`block`,children:`Show Details`})}),(0,K.jsx)(`div`,{className:`mt-4 max-h-60 overflow-auto rounded bg-muted p-3 text-left`,children:(0,K.jsx)(iC,{className:`text-caption wrap-break-word whitespace-pre-wrap`,code:n})})]})]})}function HLi({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:i,handleInstallTemplate:a,handleVariableChange:o,isLoadingEnvVars:s,isInstalling:l,defaultModelProvider:u,defaultModelId:d,onModelUpdate:f}){return(0,K.jsx)(BLi,{children:(0,K.jsxs)(`div`,{className:`mx-auto my-4 grid max-w-[40rem] gap-5 p-4 lg:p-5`,children:[(0,K.jsxs)(T,{as:`h2`,variant:`heading`,tone:`muted`,className:c(`flex items-center gap-2`,`[&_svg]:h-[1.2em] [&_svg]:opacity-70 [&>svg]:w-[1.2em]`),children:[`Install Template `,(0,K.jsx)(SZ,{})]}),(0,K.jsxs)($O,{orientation:`horizontal`,children:[(0,K.jsx)(tk,{children:`Template AI Model Provider`}),(0,K.jsx)(Jpt,{className:`flex-1`,children:(0,K.jsxs)(Pk,{name:`template-provider`,value:t,onValueChange:n,children:[(0,K.jsx)(Ik,{size:`md`,children:(0,K.jsx)(Fk,{placeholder:`Select`})}),(0,K.jsx)(Lk,{children:e.map(e=>(0,K.jsx)(Rk,{value:e.value,children:e.label},e.value))})]})})]}),t&&Object.entries(r||{}).length>0&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h3`,tone:`muted`,children:`Set required Environmental Variables`}),(0,K.jsx)(`div`,{className:`grid grid-cols-[1fr_1fr] items-start gap-4`,children:s?(0,K.jsxs)(`div`,{className:c(`text-muted-foreground`,`col-span-2 flex items-center justify-center gap-4`,`[&_svg]:h-[1.1em] [&_svg]:w-[1.1em] [&_svg]:opacity-50`,`animate-in duration-300 fade-in`),children:[(0,K.jsx)(It,{}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[` `,`Loading variables...`]})]}):Object.entries(r).map(([e,t])=>(0,K.jsxs)(G.Fragment,{children:[(0,K.jsxs)($O,{className:`w-full`,children:[(0,K.jsx)(tk,{className:`sr-only`,children:`Key`}),(0,K.jsx)(Hj,{name:`env-${e}`,value:e,disabled:!0,className:`w-full`})]}),(0,K.jsxs)($O,{invalid:i.includes(e),className:`w-full`,children:[(0,K.jsx)(tk,{className:`sr-only`,children:`Value`}),(0,K.jsx)(Hj,{name:e,value:t,onChange:o,autoComplete:`off`,className:`w-full`}),(0,K.jsx)(rk,{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)(e2r,{defaultProvider:u||``,defaultModel:d||``,updateModel:f||(()=>Promise.resolve({message:`Updated`})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:`Provider`})]})]}),t&&!s&&(0,K.jsx)(X,{className:c(`mt-4 flex min-h-10 w-full items-center justify-center gap-2 rounded-lg bg-card state-layer text-foreground`,`[&_svg]:h-[1.1em] [&_svg]:text-foreground [&>svg]:w-[1.1em]`),onClick:a,disabled:!t||!u||!d||i.length>0||l,children:l?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(It,{className:`h-4 w-4`}),` Installing...`]}):(0,K.jsxs)(K.Fragment,{children:[`Install `,(0,K.jsx)(QV,{})]})})]})})}function ULi({title:e,description:t,githubUrl:n,isLoading:r,infoData:i,templateSlug:a}){let o=a?`feat/install-template-${a}`:`feat/install-template-[slug]`;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`mt-5 grid items-center`,children:(0,K.jsxs)(`div`,{className:c(`flex items-center gap-3`,`[&>svg]:h-[1.2em] [&>svg]:w-[1.2em] [&>svg]:opacity-50`,{"[&>svg]:opacity-20":r}),children:[(0,K.jsx)(SZ,{}),(0,K.jsx)(`h2`,{className:c({"flex min-w-[50%] rounded-lg bg-muted":r}),children:(0,K.jsx)(T,{as:`span`,variant:`title`,className:`block`,children:r?(0,K.jsx)(K.Fragment,{children:`\xA0`}):e})})]})}),(0,K.jsxs)(`div`,{className:`grid gap-x-24 lg:grid-cols-[1fr_1fr]`,children:[(0,K.jsxs)(`div`,{className:`grid`,children:[(0,K.jsx)(T,{tone:`muted`,className:c(`mt-2 mb-4`,{"rounded-lg bg-muted":r}),children:r?(0,K.jsx)(K.Fragment,{children:`\xA0`}):t}),!r&&a&&(0,K.jsxs)(`div`,{className:c(`mb-4 rounded-lg border border-border bg-background p-4`,`flex items-start gap-3`),children:[(0,K.jsx)(`div`,{className:`mt-0.5 shrink-0`,children:(0,K.jsx)(Ux,{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)(BS,{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)(nX,{children:o})]}),(0,K.jsx)(T,{tone:`muted`,as:`p`,variant:`caption`,children:`This ensures safe installation with easy rollback if needed. Your main branch remains unchanged.`})]})]})]}),n&&(0,K.jsxs)(`a`,{href:n,target:`_blank`,rel:`noopener noreferrer`,className:c(`text-muted-foreground hover:text-foreground`,`mt-auto flex items-center gap-2`),children:[(0,K.jsx)(CZ,{}),(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:n?.split(`/`)?.pop()})]})]}),i&&(0,K.jsx)(i2r,{data:i,labelsAreHidden:!0,isLoading:r})]})]})}function WLi(e){switch(e){case`running`:return(0,K.jsx)(It,{size:`sm`,"aria-hidden":!0});case`success`:return(0,K.jsx)(sC,{"aria-hidden":!0});case`failed`:return(0,K.jsx)(hw,{"aria-hidden":!0});default:return null}}function GLi(){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 KLi({status:e,variant:t}){return t===`plain`?(0,K.jsx)(`span`,{className:c(`flex size-icon-md items-center justify-center self-center [&>svg]:size-icon-md`,u.colors,{"[&>svg]:text-success-indicator":e===`success`,"[&>svg]:text-destructive-foreground":e===`failed`}),children:e===`pending`?(0,K.jsx)(GLi,{}):WLi(e)}):(0,K.jsx)(`span`,{className:c(`flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none`,u.colors,u.transform,{"[&>svg]:text-success-indicator":e===`success`,"[&>svg]:text-destructive-foreground":e===`failed`,"border border-dashed border-placeholder":e===`pending`,"[&>svg]:size-icon-md":e!==`running`,"bg-success-subtle":e===`success`,"bg-destructive-subtle":e===`failed`,"scale-110":e===`success`||e===`failed`}),children:WLi(e)})}function qLi({step:e,isActive:t,position:n,variant:r=`default`}){let i=t||e.status===`success`?`ink`:`muted`;return(0,K.jsxs)(`div`,{className:c(`grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none`,u.colors,{"border border-transparent":r==="default","border-dashed border-placeholder bg-card":t&&r==="default"}),children:[(0,K.jsxs)(`div`,{className:`grid min-w-0 grid-cols-[auto_1fr] gap-2`,children:[(0,K.jsxs)(T,{as:`span`,tone:i,className:c(`flex min-w-6 justify-end`,u.colors),children:[n,`.`]}),(0,K.jsxs)(`div`,{className:`min-w-0`,children:[(0,K.jsx)(T,{as:`h4`,tone:i,className:u.colors,children:e.title}),e.description&&(0,K.jsx)(T,{tone:`faint`,className:c(`-mt-0.5`,{truncate:r===`plain`}),children:e.description})]})]}),(0,K.jsx)(KLi,{status:e.status,variant:r})]})}function JLi({currentStep:e,steps:t=[],className:n}){return(0,K.jsx)(`div`,{className:c(n),children:t.map((t,n)=>(0,K.jsx)(qLi,{step:t,isActive:e?.id===t.id,position:n+1},t.id))})}function YLi({steps:e}){let t=e.length,n=e.filter(e=>e.status===`success`).length;return(0,K.jsxs)(`div`,{className:`flex w-full flex-col content-center justify-center gap-4`,children:[(0,K.jsx)(`div`,{className:`grid w-full grid-cols-[0_repeat(9,1fr)]`,children:e.map((t,n)=>(0,K.jsx)(`div`,{className:c(`relative flex h-8 items-center justify-end`,u.colors,{"bg-success-subtle":t.status===`success`&&e?.[n-1]?.status===`success`}),children:(0,K.jsx)(`div`,{className:c(`absolute right-0 z-10 flex size-8 translate-x-1/2 items-center justify-center self-center rounded-full bg-fill text-column text-muted-foreground motion-reduce:transition-none`,u.colors,u.transform,{"border border-dashed border-placeholder":t.status===`pending`,"scale-110 bg-success-subtle text-success-subtle-foreground":t.status===`success`,"scale-110 bg-destructive-subtle text-destructive-subtle-foreground":t.status===`failed`}),children:t.status===`running`?(0,K.jsx)(It,{}):n+1})},t.id))}),(0,K.jsxs)(`div`,{className:c(`text-center text-caption text-muted-foreground`,u.colors),children:[n,` of `,t,` steps completed`]})]})}var XLi=(0,G.createContext)(3);function ZLi({title:e,description:t,action:n,done:r,className:i,children:a}){let o=(0,G.useContext)(XLi);return(0,K.jsxs)(`li`,{className:c(`group/step grid grid-cols-[1.5rem_minmax(0,1fr)] gap-x-4 [counter-increment:ds-step]`,i),children:[(0,K.jsxs)(`div`,{className:`flex flex-col items-center`,children:[(0,K.jsx)(`span`,{className:c(`flex size-6 shrink-0 items-center justify-center rounded-full`,u.colors,r?`bg-success-indicator/18 text-success-indicator`:`bg-fill text-foreground`),children:r?(0,K.jsx)(sC,{className:`size-icon-sm`,"aria-label":`Done`}):(0,K.jsx)(T,{as:`span`,variant:`column`,className:`before:content-[counter(ds-step)]`,"aria-hidden":!0})}),(0,K.jsx)(`span`,{"aria-hidden":!0,className:`w-px flex-1 bg-border group-last/step:hidden`})]}),(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-3 pb-8 group-last/step:pb-0`,children:[(0,K.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,K.jsxs)(`div`,{className:`flex min-h-6 flex-wrap items-center justify-between gap-x-6 gap-y-2`,children:[(0,K.jsx)(T,{as:o===2?`h2`:`h3`,variant:`label`,className:`text-pretty`,children:e}),n==null?null:(0,K.jsx)(`div`,{className:`flex shrink-0 items-center gap-2`,children:n})]}),t==null?null:(0,K.jsx)(T,{as:`p`,variant:`body-sm`,tone:`muted`,className:`max-w-[70ch] text-pretty`,children:t})]}),a]})]})}function QLi({headingLevel:e=3,className:t,children:n}){return(0,K.jsx)(XLi.Provider,{value:e,children:(0,K.jsx)(`ol`,{className:c(`flex flex-col [counter-reset:ds-step]`,t),children:n})})}Object.assign(QLi,{Step:ZLi});function $Li({name:e,streamResult:t,runId:n,workflowInfo:r}){let i=t?.phase||`initializing`,a=t?.payload?.workflowState,o=t?.payload?.currentStep,s=t?.error,l=a?.steps||{},u=Object.keys(l).length>0,d=e=>e===`input`||e.endsWith(`.input`)||e.startsWith(`Mapping_`)&&/[0-9a-f]{8}/.test(e)||/[0-9a-f]{8,}/.test(e)?!1:!r?.allSteps||e in r.allSteps,f=Object.entries(l).filter(([e,t])=>d(e)),p=f.length,m=()=>{switch(i){case`initializing`:return`Preparing template installation...`;case`processing`:return`Installing ${e} template`;case`completed`:return`Template installation completed!`;case`error`:return`Template installation failed`;default:return`Installing template...`}},h=f.map(([e,t])=>({id:e,status:t?.status,description:t?.description,title:e.charAt(0).toUpperCase()+e.slice(1).replace(/-/g,` `),isActive:o?.id===e}));return(0,K.jsxs)(BLi,{className:`mb-5 content-center space-y-6 text-muted-foreground`,children:[(0,K.jsxs)(`div`,{className:`text-center`,children:[(0,K.jsx)(T,{as:`h3`,variant:`heading`,tone:`ink`,children:m()}),(t?.runId||n)&&(0,K.jsxs)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`mt-2`,children:[`Run ID: `,t?.runId??n]})]}),u&&p>0&&![`error`].includes(i)&&(0,K.jsx)(`div`,{className:`mx-auto w-full max-w-[30rem] px-4`,children:(0,K.jsx)(YLi,{steps:h})}),s&&i===`error`&&(0,K.jsxs)(`div`,{className:c(`text-foreground`,`flex items-center gap-3 rounded-lg bg-destructive-subtle p-4`,`[&>svg]:h-6 [&>svg]:w-6 [&>svg]:text-destructive-foreground [&>svg]:opacity-70`),children:[(0,K.jsx)(Vx,{}),(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:s||`Something went wrong`})]}),u&&(0,K.jsx)(JLi,{steps:h,currentStep:o,className:`pb-4`}),!u&&i===`initializing`&&(0,K.jsxs)(`div`,{className:c(`text-muted-foreground`,`grid justify-items-center gap-4 text-center`),children:[(0,K.jsx)(It,{}),(0,K.jsx)(T,{as:`p`,variant:`body`,children:`This may take some time...`})]})]})}function eRi({name:e,installedEntities:t}){return(0,K.jsxs)(BLi,{className:c(`grid content-center items-center justify-items-center gap-4`,`[&>svg]:h-8 [&>svg]:w-8`),children:[(0,K.jsx)(SZ,{}),(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)(i2r,{data:t})]})}function tRi(){let{templateSlug:e}=Ev(),t=[{id:`templates`,label:`Templates`,to:`/templates`},{id:`template`,label:SMt(e)}],[n,r]=Mv(),[i,a]=(0,G.useState)(``),[o,s]=(0,G.useState)(``),[l,u]=(0,G.useState)(``),[d,f]=(0,G.useState)({}),[p,m]=(0,G.useState)([]),[h,g]=(0,G.useState)(null),[_,v]=(0,G.useState)(!1),[y,b]=(0,G.useState)(``),[x,S]=(0,G.useState)(!1),[C,w]=(0,G.useState)(!1),[T,E]=(0,G.useState)([]),{data:D,isLoading:O}=CLi({repoOrSlug:e,owner:`mastra-ai`}),k=`1.85.1-alpha.0`.includes(`beta`)??!1?`beta`:`main`,{data:A,isLoading:j}=wLi({repo:D?.githubUrl?new URL(D.githubUrl).pathname.split(`/`)[2]:`template-${e}`,owner:`mastra-ai`,branch:k}),{data:M,isLoading:N}=TLi(),{mutateAsync:P,isPending:F}=ELi(),{mutateAsync:I}=DLi(),{streamInstall:L,streamResult:R,isStreaming:z}=MLi({workflowInfo:M}),{observeInstall:B,streamResult:V,isStreaming:H}=NLi({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)(HN,{})},{key:`agents`,label:`Agents`,value:D?.agents?.length?D.agents.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(PN,{})},{key:`workflows`,label:`Workflows`,value:D?.workflows?.length?D.workflows.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(GS,{})},{key:`providers`,label:`Providers`,value:D?.supportedProviders?.length?D.supportedProviders.join(`, `):`n/a`,icon:(0,K.jsx)(k3,{})},{key:`tags`,label:`Tags`,value:D?.tags?.length?D.tags.join(`, `):`n/a`,icon:(0,K.jsx)(vX,{})}],U=[{...te[0]},{...te[1]},{...te[2]}].filter(e=>e.value!==`n/a`);return(0,G.useEffect)(()=>{A&&f(A)},[A]),(0,G.useEffect)(()=>{let e=R||V;e?.phase===`error`&&e?.error&&g(typeof e.error==`string`?e.error:String(e.error))},[R?.phase,R?.error,V?.phase,V?.error]),(0,K.jsxs)(MS,{variant:`fit`,breadcrumbs:(0,K.jsx)(uN,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(`div`,{className:c(`h-full w-full overflow-y-scroll lg:px-12`),children:(0,K.jsxs)(`div`,{className:`mx-auto grid w-full max-w-[80rem] gap-y-4 p-4`,children:[(0,K.jsx)(ULi,{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)($Li,{name:D.title,streamResult:H?V:R,runId:y,workflowInfo:M}),_&&(0,K.jsx)(eRi,{name:D.title,installedEntities:U,linkComponent:jv}),h&&(0,K.jsx)(VLi,{errorMsg:h,validationErrors:T.length>0?T:R?.validationResults?.errors||V?.validationResults?.errors}),!z&&!H&&!_&&!h&&(0,K.jsx)(HLi,{providerOptions:ee,selectedProvider:i,onProviderChange:e=>{a(e)},variables:d,setVariables:f,errors:p,setErrors:m,handleInstallTemplate:async()=>{let e=Object.entries(d).reduce((e,[t,n])=>(n===``&&e.push(t),e),[]);if(e.length>0)m(e);else if(D){g(null),v(!1),b(``),w(!0);try{let e={repo:D.githubUrl||`https://github.com/mastra-ai/template-${D.slug}`,ref:k,slug:D.slug,variables:d},{runId:t}=await P({});b(t),r(e=>{let n=new URLSearchParams(e);return n.set(`runId`,t),n.set(`resume`,`true`),n.set(`provider`,i||`openai`),n}),await L.mutateAsync({inputData:e,selectedModel:{provider:o,modelId:l},runId:t})}catch(e){w(!1),g(e?.message||`Template installation failed`),console.error(`Template installation failed`,e)}}},handleVariableChange:e=>{let{name:t,value:n}=e.target;n.trim()===``?m(e=>[...e,t]):m(e=>e.filter(e=>e!==t)),f(e=>({...e,[t]:n}))},isLoadingEnvVars:j||N,isInstalling:F,defaultModelProvider:o,defaultModelId:l,onModelUpdate:async e=>(s(e.provider),u(e.modelId),{message:`Model updated successfully`})})]})]})})]})}var nRi=e=>e.threadId,rRi=e=>`traces`in e?e.traces:e.threads;function iRi(e,t){return`traces`in e?{traces:{...e.traces,...t}}:{threads:{...e.threads,...t}}}function aRi(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 oRi({query:e,rolling:t,fixedStart:n=!1,autoRefetch:r=!0,limit:i,enabled:a=!0}){let o=Y(),{anchorWindow:s,reanchor:c}=HIi(e,n),l=(0,G.useMemo)(()=>s?{...e,timeRange:iRi(e.timeRange,s)}:e,[e,s]),u=pZr({query:l,limit:i,enabled:a,queryOptions:LIi}),{headRows:d}=WIi({queryKey:[`threads`,e],fetchHead:async t=>(await o.queryTraceThreads({...e,timeRange:iRi(e.timeRange,VIi(rRi(e.timeRange),t,n)),orderBy:[{field:`endedAt`,direction:`desc`}],page:{limit:50}})).threads,getId:nRi,getEndedAt:e=>e.endedAt,since:Date.parse(rRi(l.timeRange).to),enabled:a&&t&&r&&u.threads!==void 0&&!u.isFetching&&!u.isError,onOverflow:()=>c(rRi(e.timeRange))}),{orderBy:f}=e,p=u.threads,m=(0,G.useMemo)(()=>p&&KIi(p,d,{getId:nRi,compare:aRi(f),hasNextPage:u.hasNextPage}),[p,d,f,u.hasNextPage]);return{...u,threads:m}}function sRi(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 cRi=[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`],lRi=[];function uRi(){let{data:e}=m7(),t=e?.capabilities.traceQueryTimeToFirstChunk??!1,n=e?.capabilities.traceQueryTimeToFirstToken??!1,{data:r=lRi}=t8(),{data:i=lRi}=n8();return(0,G.useMemo)(()=>[e8r,...Eoi({withTimeToFirstChunk:t,withTimeToFirstToken:n,entityNames:r,environments:i})],[t,n,r,i])}function dRi({tokens:e,groups:t,onFiltersChange:n}){let r=(0,G.useMemo)(()=>l$r(e),[e]),i=(0,G.useMemo)(()=>{let e=f$r([],t);return{...e,nodes:[s5,...r,...e.nodes]}},[r,t]),a=(0,G.useCallback)(e=>{let t=m$r({...e,nodes:e.nodes.filter(e=>H6(e)||e.fieldId!==`timeRange`)});n(t.tokens,t.groups)},[n]);return{filterBarValue:i,onFilterBarChange:a,onFilterByField:(0,G.useCallback)((e,t)=>{let n=r.filter(t=>t.fieldId!==e),o={id:`${e}:${t}`,fieldId:e,operatorId:`is`,value:t},s=i.nodes.filter(H6);a({...i,nodes:[...n,o,...s]})},[r,i,a])}}var fRi=e=>e;function pRi({datePreset:e,dateFrom:t,dateTo:n,minDate:r,tokens:i,groups:a,onDatePresetChange:o,onDateChange:s,onDateRangeChange:c,onFiltersChange:l,disabled:u}){let d=uRi(),{filterBarValue:f,onFilterBarChange:p}=dRi({tokens:i,groups:a,onFiltersChange:l});return(0,K.jsxs)(c5,{fields:d,operators:LQr,value:f,onValueChange:p,createItemId:fRi,maxDepth:3,"aria-label":`Thread filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(c5.Chips,{renderChip:i=>i.fieldId===`timeRange`?(0,K.jsx)(c5.TimeRange,{preset:e,onPresetChange:o,dateFrom:t,dateTo:n,minDate:r,onDateChange:s,onDateRangeChange:c,disabled:u,presets:cRi,defaultPreset:K8.datePreset}):(0,K.jsx)(c5.Chip,{item:i})}),(0,K.jsx)(c5.Input,{placeholder:`Filter threads`})]})}function mRi({selectedThreadId:e,onSelectedThreadChange:t,onOpenScore:n,urlState:r}){let i=zIi(r),{timeRange:a,tokens:o,groups:s,sort:c}=i,l=h7().enabled,u=$si().enabled,d=Psi({scope:`threads`}),{data:f,isLoading:p}=m7(),m=f?.capabilities.traceQueryTimeToFirstChunk??!1,h=f?.capabilities.traceQueryTimeToFirstToken??!1,g=(0,G.useMemo)(()=>p?d.preferences:X2r(d.preferences,{withTimeToFirstChunk:m,withTimeToFirstToken:h}),[d.preferences,p,m,h]),{threads:_,hasNextPage:v,isFetchingNextPage:y,setEndOfListElement:b,isLoading:x,isError:S,error:C}=oRi({query:(0,G.useMemo)(()=>{let e=koi(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,fixedStart:i.datePreset===`custom`}),w=(0,G.useMemo)(()=>(_??[]).map(sRi),[_]),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)(g3r,{toolbar:(0,K.jsxs)(K.Fragment,{children:[r&&(0,K.jsx)(ksi,{page:`threads`,...r,columns:d}),(0,K.jsxs)(_K,{children:[(0,K.jsx)(_K.Start,{children:(0,K.jsx)(pRi,{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)(_K.End,{children:(0,K.jsx)(pLi,{scope:`threads`,value:d.preferences,onChange:d.setPreferences})})]})]}),error:S?(0,K.jsx)(U8,{error:C,resource:`threads`,errorTitle:`Failed to load threads`}):void 0,empty:D?(0,K.jsx)(O2r,{resource:`threads`,datePreset:i.datePreset,dateFrom:i.dateFrom,dateTo:i.dateTo}):void 0,children:(0,K.jsx)(R9r,{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)($li,{open:!!e,threadId:e??``,depth:1,closeLabel:`Close`,withQueryTrace:l,withFeedback:u,onOpenScore:n,onClose:()=>t(void 0)})]})}function hRi(){let{enabled:e,isLoading:t}=Xsi(),n=Tv(),[r,i]=Mv();return(0,K.jsx)(FIi,{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)(mRi,{urlState:{searchParams:r,setSearchParams:i},selectedThreadId:QIi(r),onSelectedThreadChange:e=>i(t=>$Ii(t,e),{replace:!0}),onOpenScore:(e,t)=>n(qDn(e,t))})})}var gRi=()=>(0,K.jsx)(Hx,{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)(qN,{}),children:`Workflows documentation`}),variant:`fill`});function _Ri(e,t,n){return AZ(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 vRi(e){return Object.keys(e.steps??{}).filter(t=>e.allSteps?.[t]?.isWorkflow)}function yRi(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 bRi(e,t,n){let r=yRi(t),i=[],a=(e,o,s,c,l,u)=>{let d=vRi(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 xRi=`auto 24rem minmax(0, 1fr) auto auto auto`;function SRi({guides:e,isLastChild:t}){return(0,K.jsxs)(`span`,{"aria-hidden":!0,className:`-my-6 flex shrink-0 self-stretch`,children:[e.map((e,t)=>(0,K.jsx)(`span`,{className:c(`w-6`,e&&`border-l border-border`)},t)),(0,K.jsxs)(`span`,{className:`relative w-6`,children:[(0,K.jsx)(`span`,{className:c(`absolute top-0 left-0 border-l border-border`,t?`h-1/2`:`h-full`)}),(0,K.jsx)(`span`,{className:`absolute top-1/2 left-0 w-3.5 border-b border-border`})]})]})}function CRi({row:e,isExpanded:t,onToggle:n}){let r=e.kind===`workflow`&&e.nestedIds.length>0,i=e.kind===`workflow`?e.workflow.name:e.stepId;return(0,K.jsx)(`div`,{className:`flex items-center pl-5`,children:r?(0,K.jsx)(`button`,{type:`button`,"aria-expanded":t,"aria-label":`${t?`Collapse`:`Expand`} nested workflows of ${i}`,className:c(gS,`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 wRi=e=>e.stopPropagation();function TRi({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 ERi({row:e,isExpanded:t,onToggle:n,runCount:r,rowProps:i}){let{paths:a,Link:o}=sn(),s=(0,G.useRef)(null),{workflow:c,nestedIds:l}=e,u=rJ(c.name,50),d=rJ(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)(CRi,{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:wRi,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)(SRi,{guides:e.guides,isLastChild:e.isLastChild}):null,(0,K.jsx)(`span`,{className:`truncate`,children:u}),c.origin===`dynamic`?(0,K.jsx)(JS,{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)(GS,{"aria-hidden":!0,className:`size-icon-sm`}),l.length]}):null]})}),(0,K.jsx)(Z.DescriptionCell,{children:d}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:p>0?(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-info-indicator`,"aria-label":`${p} run${p===1?``:`s`} in progress`,children:[(0,K.jsx)(`span`,{"aria-hidden":!0,className:`size-2 rounded-full bg-info-indicator motion-safe:animate-pulse`}),p]}):``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:m>0?(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-warning-foreground`,"aria-label":`${m} run${m===1?``:`s`} awaiting input`,children:[(0,K.jsx)(bT,{"aria-hidden":!0,className:`size-icon-sm`}),m]}):``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:f||``})]})]})}function DRi({workflows:e,isLoading:t,search:n=``,sort:r,onSortChange:i,requestContext:a}){let[o,s]=(0,G.useState)(new Set),l=YEt({requestContext:a}),u=(0,G.useMemo)(()=>Object.entries(e).map(([e,t])=>({...t,id:e})),[e]),d=(0,G.useMemo)(()=>{let e=n.toLowerCase();return u.filter(t=>t.name?.toLowerCase().includes(e)||t.description?.toLowerCase().includes(e))},[u,n]),f=(0,G.useMemo)(()=>_Ri(d,r,l),[d,r,l]),m=(0,G.useMemo)(()=>bRi(f,e,o),[f,e,o]),h=(0,G.useMemo)(()=>{let e=new Map;for(let t of m)t.kind===`workflow`&&e.set(t.pathKey,e.size);return e},[m]),{containerRef:g,getRowProps:_}=OZ({count:h.size,global:!0}),v=e=>{s(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})};return t?(0,K.jsx)(yH,{columns:xRi,fit:`container`}):(0,K.jsxs)(Z,{columns:xRi,fit:`container`,scrollRef:g,children:[(0,K.jsxs)(Z.Top,{children:[(0,K.jsx)(Z.TopCell,{children:(0,K.jsx)(`span`,{className:`sr-only`,children:`Expand`})}),(0,K.jsx)(TRi,{sortKey:`name`,sort:r,onSortChange:i,children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`Description`}),(0,K.jsx)(TRi,{sortKey:`running`,sort:r,onSortChange:i,children:`Running`}),(0,K.jsx)(TRi,{sortKey:`suspended`,sort:r,onSortChange:i,children:`Pending input`}),(0,K.jsx)(TRi,{sortKey:`steps`,sort:r,onSortChange:i,children:`Number of steps`})]}),m.length===0&&n?(0,K.jsx)(Z.NoMatch,{message:`No Workflows match your search`}):null,m.map(e=>{let t=o.has(e.pathKey),n=()=>v(e.pathKey);return e.kind===`unregistered`?(0,K.jsxs)(Z.RowStatic,{className:`gap-0 px-0`,children:[(0,K.jsx)(CRi,{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)(SRi,{guides:e.guides,isLastChild:e.isLastChild}),(0,K.jsx)(`span`,{className:`truncate`,children:rJ(e.stepId,50)}),(0,K.jsxs)(_x,{children:[(0,K.jsx)(vx,{render:(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`muted`}),role:`note`,tabIndex:0,className:c(`shrink-0 rounded-sm`,p),children:`not registered`}),(0,K.jsx)(yx,{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:rJ(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)(ERi,{row:e,isExpanded:t,onToggle:n,runCount:l[e.workflow.id],rowProps:_(h.get(e.pathKey)??-1)},`workflow-${e.pathKey}`)})]})}var K9=[KN(`/workflows`)];function ORi(){let{data:e,isLoading:t,error:n}=KM(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)();return n&&DN(n)?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:K9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(_H,{variant:`fill`})]}):n&&ON(n)?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:K9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(gH,{variant:`fill`,resource:`workflows`})]}):n?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:K9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(Hx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load workflows`,descriptionSlot:n.message})]}):Object.keys(e||{}).length===0&&!t?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:K9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(gRi,{})]}):(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:K9}),actionRow:(0,K.jsxs)(_K,{children:[(0,K.jsx)(_K.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(wH,{...TH,onValueChange:i,label:`Search workflows`,placeholder:`Search by name or description`})})}),(0,K.jsx)(_K.End,{children:(0,K.jsx)(X,{render:(0,K.jsx)(jv,{to:`/workflows/schedules`}),variant:`primary`,icon:(0,K.jsx)(VS,{}),children:`Schedules`})})]}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(DRi,{workflows:e||{},isLoading:t,search:r,sort:a,onSortChange:(e,t)=>o({key:t,direction:e})})]})}var kRi={active:`bg-success-indicator`,paused:`bg-info-indicator`,completed:`bg-muted-foreground`},ARi={active:`text-success-indicator`,paused:`text-info-indicator`,completed:`text-muted-foreground`},jRi=({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 ${kRi[e]}`,"aria-hidden":!0}),(0,K.jsx)(T,{as:`span`,variant:`caption`,className:ARi[e],children:e})]});function MRi({status:e}){let{icon:t,color:n}=NRi(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 NRi(e){switch(e){case`success`:return{icon:(0,K.jsx)(sC,{className:`size-icon-sm`}),color:`text-success-indicator`};case`failed`:return{icon:(0,K.jsx)(hw,{className:`size-icon-sm`}),color:`text-destructive-foreground`};case`running`:return{icon:(0,K.jsx)(It,{}),color:`text-muted-foreground`};case`suspended`:return{icon:(0,K.jsx)(bT,{className:`size-icon-sm`}),color:`text-info-indicator`};case`canceled`:return{icon:(0,K.jsx)(Bx,{className:`size-icon-sm`}),color:`text-muted-foreground`};case`pending`:case`waiting`:return{icon:(0,K.jsx)(YS,{className:`size-icon-sm`}),color:`text-muted-foreground`};default:return{icon:null,color:`text-muted-foreground`}}}var PRi=`auto auto auto auto 1fr`,FRi=3e4,IRi=3e5;function LRi({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:i,setEndOfListElement:a}){let{Link:o,paths:s}=sn(),c=e=>!!(n&&e.runId&&e.outcome!==`failed`),l=e.filter(c).length,{containerRef:u,getRowProps:d}=OZ({count:l}),f=-1;return t?(0,K.jsx)(yH,{columns:PRi}):e.length===0?(0,K.jsx)(T,{variant:`body`,tone:`muted`,className:`p-4`,children:`No trigger history yet.`}):(0,K.jsxs)(Z,{columns:PRi,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=QS(t,{signed:!0}),i=e.outcome===`failed`,a=i?e.error:e.run?.error,l=Math.abs(t),u=!i&&l>FRi&&l<=IRi,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)(Gx,{className:`size-icon-sm`}),`publish failed`]}):e.run?(0,K.jsx)(MRi,{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)(_x,{children:[(0,K.jsx)(vx,{asChild:!0,children:(0,K.jsx)(`span`,{className:`inline-flex text-destructive-foreground`,children:(0,K.jsx)(Gx,{className:`size-icon-sm`})})}),(0,K.jsx)(yx,{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)(xk,{value:e.actualFireAt}):`—`,u?(0,K.jsxs)(_x,{children:[(0,K.jsx)(vx,{asChild:!0,children:(0,K.jsx)(`span`,{className:`inline-flex text-info-indicator`,children:(0,K.jsx)(Gx,{className:`size-icon-sm`})})}),(0,K.jsxs)(yx,{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:QS(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 RRi={id:`workflow-schedules`,label:`Schedules`,icon:VS,to:`/workflows/schedules`};function zRi({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 BRi(){let{scheduleId:e}=Ev(),t=[KN(`/workflows`),RRi,{id:`schedule`,label:SMt(e),icon:VS}],{paths:n}=sn(),{data:r,error:i}=UMt({scheduleId:e,queryOptions:{enabled:!!e}}),{data:a,isLoading:o,error:s,hasNextPage:c,isFetchingNextPage:l,setEndOfListElement:u}=KMt({scheduleId:e,queryOptions:{enabled:!!e}}),d=qMt({scheduleId:e});if(i&&DN(i))return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(_H,{variant:`fill`})]});if(i&&ON(i))return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(gH,{variant:`fill`,resource:`schedules`})]});if(i)return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(Hx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load schedule`,descriptionSlot:i.message})]});let f=r?.workflowId,p=r?.agentId;return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:t}),actionRow:(0,K.jsx)(_K,{children:(0,K.jsxs)(_K.End,{children:[(0,K.jsx)(X,{render:(0,K.jsx)(jv,{to:n.schedulesLink()}),variant:`ghost`,icon:(0,K.jsx)(tS,{}),children:`Back to schedules`}),f?(0,K.jsx)(X,{icon:(0,K.jsx)(GS,{}),render:(0,K.jsx)(jv,{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:()=>Qx.success(e===`pause`?`Schedule paused`:`Schedule resumed`),onError:e=>Qx.error(e.message)})},disabled:d.isPending,"data-testid":`schedule-toggle-button`,children:r.status===`active`?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(bT,{}),`Pause`]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(xT,{}),`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)(zRi,{label:p?`Agent`:`Workflow`,children:f?(0,K.jsx)(jv,{to:n.workflowLink(f),className:`text-foreground hover:underline`,children:f}):p?(0,K.jsx)(jv,{to:n.agentLink(p),className:`text-foreground hover:underline`,children:p}):`—`}),(0,K.jsxs)(zRi,{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)(zRi,{label:`Status`,children:(0,K.jsx)(jRi,{status:r.status})}),(0,K.jsx)(zRi,{label:`Next fire`,children:r.nextFireAt?(0,K.jsx)(xk,{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)(Hx,{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 VRi={target:e=>e.workflowId??e.agentId??``,status:e=>e.status,nextFireAt:e=>e.nextFireAt,lastFireAt:e=>e.lastFireAt},HRi=`minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto`;function URi({schedules:e,isLoading:t,search:n=``,sort:r,onSortChange:i}){let{paths:a,Link:o}=sn(),s=(0,G.useMemo)(()=>{let t=n.toLowerCase();return AZ(t?e.filter(e=>e.id.toLowerCase().includes(t)||(e.workflowId??e.agentId??``).toLowerCase().includes(t)):e,r,VRi)},[e,n,r]),{containerRef:c,getRowProps:l}=OZ({count:s.length,global:!0});if(t)return(0,K.jsx)(yH,{columns:HRi});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:HRi,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)(jRi,{status:e.status})}),(0,K.jsx)(Z.Cell,{children:e.nextFireAt?(0,K.jsx)(xk,{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)(MRi,{status:e.lastRun.status}),e.lastFireAt?(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:(0,K.jsx)(xk,{value:e.lastFireAt})}):null]}):e.lastFireAt?(0,K.jsx)(xk,{value:e.lastFireAt}):(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`Never`})})]},e.id))]})}function WRi({workflowId:e}={}){let{data:t,isLoading:n,error:r}=WMt(e?{workflowId:e}:{}),[i,a]=(0,G.useState)(``),[o,s]=(0,G.useState)();return r?(0,K.jsx)(Hx,{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)(wH,{...TH,onValueChange:a,label:`Search schedules`,placeholder:`Search by id or workflow`})}),(0,K.jsx)(`div`,{className:`overflow-y-auto`,children:(0,K.jsx)(URi,{schedules:t??[],isLoading:n,search:i,sort:o,onSortChange:(e,t)=>s({key:t,direction:e})})})]})}var GRi=[KN(`/workflows`),RRi];function KRi(){let[e]=Mv(),t=e.get(`workflowId`)??void 0,{error:n}=WMt(t?{workflowId:t}:{});return n&&DN(n)?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:GRi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(_H,{variant:`fill`})]}):n&&ON(n)?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:GRi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(gH,{variant:`fill`,resource:`schedules`})]}):(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:GRi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(`div`,{className:`h-full`,children:(0,K.jsx)(WRi,{workflowId:t})})]})}var qRi=U(`IconArrowDownLeft`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M6 9V18H15`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M17.75 6.25L7 17`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),3),JRi={"--belt-hue":`var(--warning-indicator)`};function YRi(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 ZRi({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:(0,K.jsxs)(`section`,{className:c(lDt,`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)(xx,{children:(0,K.jsx)(bT,{})}),`Step suspended`]}),(0,K.jsx)(JS,{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?NO(XO(n.resumeSchema)):kd(q(),pd());return(0,K.jsx)(QRi,{step:e,stepSchema:i,description:n.description,onResume:r},`${e.runId}-${e.stepId}`)})]}),(0,K.jsx)(YXe,{status:`ready`,label:`Needs input`,className:`before:hidden`,style:JRi})]})}function QRi({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)(xx,{children:(0,K.jsx)(qRi,{})}),`The step is asking`]}),(0,K.jsxs)(xC,{open:i,onOpenChange:a,children:[(0,K.jsxs)(SC,{className:c(`bg-card hover:bg-card active:bg-card shadow-raised [--field:var(--field-on-surface)] [--field-disabled:var(--field-on-surface)] [--field-rim:var(--field-rim-on-surface)]`,`flex w-full items-center justify-between gap-2 rounded-lg px-3 py-2.5`),children:[(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(xx,{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:YRi(e.suspendPayload)})]}),(0,K.jsx)(CC,{children:(0,K.jsx)(`div`,{"data-testid":`suspended-payload`,className:`pt-2`,children:(0,K.jsx)(mw,{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)(xx,{children:(0,K.jsx)(R4,{})}),`Your response`]}),(0,K.jsx)(`div`,{className:`-mx-5`,children:(0,K.jsx)(TEt,{schema:t,isSubmitLoading:o,submitButtonLabel:`Resume`,submitButtonVariant:`primary`,submitButtonIcon:(0,K.jsx)(xT,{}),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){Qx.error(e instanceof Error?e.message:`Error resuming workflow`)}finally{s(!1)}}})})]})]})}function $Ri({hidden:e,requestContext:t,canResume:n}){let{result:r,workflow:i,runId:a,isStreamingWorkflow:o}=(0,G.useContext)(RS),s=mpt(r,a),c=ypt(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)(ZRi,{suspendedSteps:s,workflow:i,isStreaming:o,onResume:c})},a)}var ezi=U(`IconSkip`,()=>(0,K.jsx)(`path`,{d:`M19 5V19M6.52732 5.16646L15.5625 11.1835C16.1458 11.5719 16.1458 12.4281 15.5625 12.8165L6.52732 18.8335C5.87447 19.2683 5 18.8008 5 18.017V5.98298C5 5.1992 5.87447 4.7317 6.52732 5.16646Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})),tzi={success:{label:`Completed`,icon:sC},failed:{label:`Failed`,icon:Vx},suspended:{label:`Needs input`,icon:bT},waiting:{label:`Waiting`,icon:WS},paused:{label:`Paused`,icon:bT},skipped:{label:`Skipped`,icon:ezi},running:{label:`Running`,icon:yT},canceled:{label:`Canceled`,icon:Bx}},nzi={label:`Status unavailable`,icon:kq};function rzi({row:e,isSelected:t,isHovered:n,onSelectStep:r,onHoverStep:i,onOpenInput:a,onOpenOutput:o}){let s=Object.hasOwn(tzi,e.status)?tzi[e.status]:nzi,l=s.icon,u=iht(e.status),d=e.stepId.slice(0,e.stepId.lastIndexOf(`.`)),f=e.isNestedEntry?e.stepId.slice(e.stepId.lastIndexOf(`.`)+1):e.stepId;return(0,K.jsxs)(`div`,{"data-testid":`workflow-timeline-row`,"data-workflow-step-key":e.stepId,onMouseEnter:()=>!e.isNestedEntry&&i(e.stepId),onMouseLeave:()=>!e.isNestedEntry&&i(null),className:c(`grid grid-cols-[minmax(130px,1fr)_minmax(64px,1fr)_56px_64px] items-center gap-3 rounded-md px-2 py-1`,`@max-[540px]/workflow-timeline:grid-cols-[minmax(0,1fr)_48px_64px] @max-[540px]/workflow-timeline:gap-x-1.5 @max-[540px]/workflow-timeline:gap-y-1 @max-[540px]/workflow-timeline:py-2`,(t||n)&&`bg-fill-subtle`),children:[(0,K.jsxs)(`button`,{type:`button`,"aria-disabled":e.isNestedEntry,"aria-pressed":t,onClick:()=>{e.isNestedEntry||r(e.stepId)},title:e.stepId,className:c(`text-foreground`,`flex min-h-9 min-w-0 cursor-pointer items-center gap-2.5 text-left focus-visible:rounded-sm aria-disabled:cursor-default`,p),children:[(0,K.jsx)(`span`,{"aria-label":s.label,className:c(`grid size-6 flex-none place-items-center rounded-md border border-border bg-background`,aht[u]),children:(0,K.jsx)(l,{"aria-hidden":!0,className:c(`size-3.5`,e.status===`running`&&`motion-safe:animate-spin`)})}),(0,K.jsxs)(`span`,{className:`min-w-0`,children:[(0,K.jsx)(T,{as:`span`,variant:`meta`,className:`block truncate`,children:f}),e.isNestedEntry&&(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`flex min-w-0 items-center gap-1`,children:[(0,K.jsx)(hXe,{"aria-hidden":!0,className:`size-icon-xs shrink-0`}),(0,K.jsx)(`span`,{className:`truncate`,children:d})]})]})]}),(0,K.jsx)(`div`,{className:`relative h-5 min-w-0 overflow-hidden rounded-sm bg-muted @max-[540px]/workflow-timeline:col-span-full @max-[540px]/workflow-timeline:row-start-2 @max-[540px]/workflow-timeline:ml-[34px]`,"aria-hidden":!0,children:e.timing&&(0,K.jsx)(`div`,{"data-testid":`workflow-timeline-bar`,"data-offset":e.timing.offsetPct,"data-width":e.timing.widthPct,className:c(`absolute top-0 h-full min-w-0.5 rounded-sm`,oht[u]),style:{left:`${e.timing.offsetPct}%`,width:`${e.timing.widthPct}%`}})}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`text-right whitespace-nowrap`,title:e.timing&&e.spansSuspension?`Includes time spent suspended waiting for input`:void 0,children:e.timing?(0,K.jsx)(T,{as:`span`,variant:`meta`,font:`mono`,children:QS(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)(mk,{})}),(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)(pk,{})})]})]})}var izi=e=>e.includes(`.`),azi=e=>e===`input`||e.endsWith(`.input`),ozi=1;function szi(e,t){let n=lht(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 czi(e,t){let n=Object.entries(e).filter(([e])=>!azi(e)).map(([e,n])=>({stepId:e,step:n,...szi(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,ozi),100-t)}}return{stepId:e,step:t,status:vk(t)?`suspended`:t.status,timing:s,spansSuspension:a,isRunning:r,isNestedEntry:izi(e)}})}var lzi=U(`IconChevronGrabberVertical`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M8 8.99985L11.2929 5.70696C11.6834 5.31643 12.3166 5.31643 12.7071 5.70696L16 8.99985`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M8 15L11.2929 18.2929C11.6834 18.6834 12.3166 18.6834 12.7071 18.2929L16 15`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]})),uzi=U(`IconChevronGrabberVerticalToward`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M8 18.75L12 14.75L16 18.75`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M8 5.25L12 9.25L16 5.25`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}));function dzi(){let{steps:e}=UQ(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:i}=LS(),[a,o]=(0,G.useState)(()=>Date.now()),[s,l]=(0,G.useState)(!0),[u,d]=(0,G.useState)(!1),{showData:f}=JM(),p=(0,G.useRef)(null),m=czi(e,a),h=m.some(e=>e.isRunning);return CJe(p,{enabled:h&&!s}),(0,G.useEffect)(()=>{if(!h||s)return;let e=setInterval(()=>o(Date.now()),100);return()=>clearInterval(e)},[h,s]),m.length===0?null:(0,K.jsx)(`div`,{"data-testid":`workflow-timeline`,className:`relative z-20 shrink-0 px-2 pb-2`,children:(0,K.jsxs)(xC,{open:!s,onOpenChange:e=>l(!e),className:c(Pv,`@container/workflow-timeline pointer-events-auto overflow-hidden rounded-xl`),children:[(0,K.jsxs)(`div`,{className:`flex items-center`,children:[(0,K.jsxs)(SC,{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)(VV,{"aria-hidden":!0,className:`size-icon-md text-muted-foreground`})}),(0,K.jsx)(`span`,{children:`Timeline`}),(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,children:[m.length,` events`]}),(0,K.jsx)(`span`,{className:`ml-auto`,children:(0,K.jsx)(y,{direction:`right`,className:`size-4`})})]}),!s&&(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:u?`Restore timeline height`:`Enlarge timeline`,"aria-pressed":u,onClick:()=>d(!u),className:`mr-2 shrink-0`,children:u?(0,K.jsx)(uzi,{}):(0,K.jsx)(lzi,{})})]}),(0,K.jsx)(CC,{children:(0,K.jsx)(`div`,{ref:p,"data-testid":`workflow-timeline-list`,className:c(`overflow-auto overscroll-contain px-1.5 pb-1.5`,u?`max-h-[min(720px,calc(100dvh-112px))]`:`max-h-[min(320px,40dvh)]`),children:m.map(e=>(0,K.jsx)(rzi,{row:e,isSelected:t===e.stepId,isHovered:n===e.stepId,onSelectStep:r,onHoverStep:i,onOpenInput:(e,t)=>f({type:`step-input`,stepId:e.stepId},t),onOpenOutput:(e,t)=>f({type:`step-output`,stepId:e.stepId},t)},e.stepId))})})]})})}var fzi=({workflowId:e,workflow:t,isLoading:n})=>{let[r]=IS(`workflow`,e),{canExecute:i,isLoading:a}=oS(),{stepDetail:o}=JM(),s=Gw(),c=o?.type===`data`,l=(0,K.jsxs)(`div`,{className:`[container-type:size] relative h-full min-h-0`,children:[(0,K.jsx)(zlr,{workflowId:e,workflow:t,isLoading:n,requestContext:r}),(0,K.jsx)($Ri,{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)(GQ,{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)(dzi,{})})]});return s&&o&&!c?(0,K.jsx)(`div`,{className:`h-full min-h-0 overflow-hidden`,children:(0,K.jsx)(GQ,{requestContext:r})}):(0,K.jsxs)(`div`,{className:`relative h-full min-h-0`,children:[l,(0,K.jsxs)(p6,{className:`pointer-events-none absolute inset-0 z-30 min-h-0 w-full min-w-0 p-2`,children:[(0,K.jsx)(f6,{id:`workflow-graph`,className:`pointer-events-none min-w-0`}),o&&!c&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(m6,{className:`pointer-events-auto`}),(0,K.jsx)(f6,{id:`workflow-step-detail`,minSize:300,maxSize:`60%`,defaultSize:420,className:`min-w-0`,children:(0,K.jsx)(`div`,{className:`pointer-events-auto h-full min-h-0 overflow-hidden rounded-studio-panel border border-border bg-background`,children:(0,K.jsx)(GQ,{requestContext:r})})})]})]})]})},pzi=()=>{let{workflowId:e}=Ev(),{data:t,isLoading:n,error:r}=qM({workflowId:e,requestContext:IS(`workflow`,e)[0],queryOptions:{enabled:!!e}});return r&&DN(r)?(0,K.jsx)(_H,{variant:`fill`}):r&&ON(r)?(0,K.jsx)(gH,{variant:`fill`,resource:`workflows`}):(0,K.jsx)(fzi,{workflowId:e,workflow:t??void 0,isLoading:n})};function mzi(){let{workflowId:e}=Ev(),{error:t}=WMt(e?{workflowId:e}:{});if(!e)return null;let n;return n=t&&DN(t)?(0,K.jsx)(_H,{variant:`fill`}):t&&ON(t)?(0,K.jsx)(gH,{variant:`fill`,resource:`schedules`}):(0,K.jsx)(`div`,{className:`h-full`,children:(0,K.jsx)(WRi,{workflowId:e})}),(0,K.jsxs)(MS,{children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),n]})}function hzi(){let{workflowId:e}=Ev();return e?(0,K.jsx)(yui,{scopedEntityId:e,scopedEntityType:wp.WORKFLOW_RUN}):null}var gzi=(0,G.createContext)(null);function q9(){let e=(0,G.useContext)(gzi);if(!e)throw Error(`Workspace components must be rendered inside <Workspace.Root>`);return e}var _zi=e=>e?.status;function vzi(e,t){return DN(e)?`Your session has expired. Sign in again to continue.`:ON(e)?`You don't have permission to access this.`:kN(e)?`This path no longer exists.`:_zi(e)===501?`This workspace does not support this operation.`:t}function yzi({error:e,fallback:t,className:n}){return(0,K.jsx)(gk,{variant:`destructive`,className:n,children:(0,K.jsx)(gk.Message,{children:vzi(e,t)})})}var bzi=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;function xzi(e){let t=bzi.exec(e);return t?{frontmatter:t[1]??``,body:e.slice(t[0].length)}:{frontmatter:null,body:e}}function Szi({content:e}){let{frontmatter:t,body:n}=xzi(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)(aJ,{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)(pY,{children:n})})]})}function Czi(){let{activeFilePath:e}=q9();return e?(0,K.jsx)(T,{as:`span`,variant:`body-sm`,font:`mono`,tone:`muted`,className:`truncate`,"data-testid":`workspace-file-path`,children:e}):null}function wzi({path:e,content:t,mimeType:n}){return vIn(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`})}):yIn(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:${xIn(e,n)};base64,${t}`,type:xIn(e,n)})})}):SIn(e)?(0,K.jsx)(Szi,{content:t}):(0,K.jsx)(aJ,{code:t,lang:AXe(e),overflow:`scroll`,className:`rounded-none border-0 bg-transparent [&_pre]:p-4`})}function Tzi({renderPreview:e}){let{workspaceId:t,activeFilePath:n}=q9(),{data:r,isLoading:i,error:a}=LIn({workspaceId:t,path:n,queryOptions:{enabled:!!n}});if(!n)return null;if(i)return(0,K.jsxs)(`div`,{"aria-busy":`true`,className:`flex flex-col gap-2 p-4`,children:[(0,K.jsx)(NS,{className:`h-4 w-1/2`}),(0,K.jsx)(NS,{className:`h-4 w-5/6`}),(0,K.jsx)(NS,{className:`h-4 w-2/3`})]});if(!r)return(0,K.jsx)(yzi,{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)(wzi,{...o})}var Ezi=(e,t)=>e===`.`?t:`${e}/${t}`,Dzi=e=>e.split(`/`).slice(0,-1).map((e,t,n)=>n.slice(0,t+1).join(`/`)),Ozi=e=>{let t=e.lastIndexOf(`/`);return t===-1?`.`:e.slice(0,t)};function kzi({labeled:e=!1}={}){let{workspaceId:t,onCreateDirectory:n,isReadOnly:r}=q9(),i=s_(),[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`,Ozi(d)]}),o(!1),c(``)}catch{}finally{u(!1)}}};return(0,K.jsxs)(K.Fragment,{children:[e?(0,K.jsx)(X,{variant:`ghost`,icon:(0,K.jsx)(P6,{}),onClick:()=>o(!0),children:`New folder`}):(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`New folder`,onClick:()=>o(!0),children:(0,K.jsx)(P6,{})}),(0,K.jsx)(Xw,{open:a,onOpenChange:o,pending:l,children:(0,K.jsx)(Zw,{size:`sm`,children:(0,K.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),f()},children:[(0,K.jsx)(Qw,{children:(0,K.jsx)(tT,{children:`New folder`})}),(0,K.jsx)(eT,{children:(0,K.jsx)(Hj,{autoFocus:!0,"aria-label":`Folder path`,placeholder:`docs/guides`,value:s,onChange:e=>c(e.target.value)})}),(0,K.jsxs)($w,{children:[(0,K.jsx)(rT,{children:`Cancel`}),(0,K.jsx)(X,{type:`submit`,variant:`primary`,disabled:!d||l,children:`Create`})]})]})})})]})}function Azi(e){return`${e.topSource}/${e.name}`}function jzi(e){let t=EIn(e.topSource,e.name);return t?`${t.owner}/${t.repo}/${e.name}`:null}function Mzi({open:e,onOpenChange:t,workspaceId:n,onInstall:r,isInstalling:i,installedSkillIds:a=[],installedSkillNames:o=[],writableMounts:s,installedSkillPaths:l}){let[u,d]=(0,G.useState)(``),[f,p]=(0,G.useState)(null),[m,h]=(0,G.useState)(),g=s?.some(e=>e.path===m)?m:s?.[0]?.path,{data:_,isLoading:v}=wIn({workspaceId:n,queryOptions:{enabled:!!n}}),y=CIn({workspaceId:n}),b=(0,G.useMemo)(()=>f?.topSource?EIn(f.topSource,f.name):null,[f]),x=(0,G.useMemo)(()=>!b||!f?null:`https://skills.sh/${b.owner}/${b.repo}/${f.name}`,[b,f]),{data:S,isLoading:C}=TIn({workspaceId:n,owner:b?.owner,repo:b?.repo,skillPath:f?.name,queryOptions:{enabled:!!n&&!!b&&!!f}}),w=nC(e=>{e.trim().length>=2&&y.mutate(e)},300),E=(0,G.useCallback)(e=>{d(e),w(e)},[w]),D=(0,G.useMemo)(()=>u.trim().length>=2?y.data?.skills??[]:_?.skills??[],[u,y.data,_]),O=y.isPending,k=u.trim().length>=2,A=(0,G.useMemo)(()=>{if(!f)return!1;let e=jzi(f);return!!(e&&a.includes(e)||o.includes(f.name))},[f,a,o]),j=(0,G.useCallback)(()=>{f&&b&&r({repository:`${b.owner}/${b.repo}`,skillName:f.name,mount:s&&s.length>1?g:void 0})},[f,b,r,s,g]),M=(0,G.useCallback)(e=>{e||(d(``),p(null),h(void 0)),t(e)},[t]);return(0,K.jsx)(Xw,{open:e,onOpenChange:M,pending:i,children:(0,K.jsxs)(Zw,{size:`xl`,className:`h-[80vh]`,children:[(0,K.jsxs)(Qw,{children:[(0,K.jsx)(tT,{children:`Add Skill`}),(0,K.jsx)(nT,{children:`Search and install skills from the community registry`})]}),(0,K.jsxs)(eT,{layout:`fill`,children:[(0,K.jsx)(wH,{label:`Search skills`,placeholder:`Search skills`,value:u,onValueChange:E}),(0,K.jsxs)(`div`,{className:`flex min-h-0 flex-1 gap-4`,children:[(0,K.jsxs)(`div`,{className:`flex min-h-0 w-1/2 flex-col`,children:[(0,K.jsx)(T,{as:`p`,variant:`eyebrow`,tone:`muted`,className:`mb-2`,children:k?`Search Results`:`Popular Skills`}),(0,K.jsx)(jS,{className:`flex-1 rounded-lg border border-border`,children:(0,K.jsx)(AS,{className:!v&&!O&&D.length===0?`flex flex-col [&>div]:flex [&>div]:flex-1 [&>div]:flex-col`:void 0,children:v||O?(0,K.jsx)(`div`,{className:`flex items-center justify-center py-5`,children:(0,K.jsx)(It,{className:`text-muted-foreground`})}):D.length===0?(0,K.jsx)(Hx,{className:`flex-1`,titleSlot:k?`No skills found`:`No skills available`}):(0,K.jsx)(`div`,{className:`space-y-1 p-2`,children:D.map(e=>{let t=Azi(e),n=jzi(e),r=n&&a.includes(n)||o.includes(e.name),i=f?Azi(f):null;return(0,K.jsx)(`button`,{onClick:()=>p(e),className:c(`w-full rounded-md px-3 py-2 text-left`,`hover:bg-fill-subtle`,i===t&&`border border-border-strong bg-fill-hover`),children:(0,K.jsxs)(`div`,{className:`flex items-start justify-between gap-2`,children:[(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(T,{as:`span`,variant:`subheading`,tone:`ink`,className:`truncate`,children:e.name}),r&&(0,K.jsxs)(T,{as:`span`,variant:`meta`,className:`inline-flex items-center gap-1 rounded bg-info-subtle px-1.5 py-0.5 text-info-subtle-foreground`,children:[(0,K.jsx)(sC,{className:`size-icon-xs`}),`Installed`]})]}),(0,K.jsx)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`truncate`,children:e.topSource})]}),(0,K.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 text-muted-foreground`,children:[(0,K.jsx)(iJ,{className:`size-icon-xs`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,children:e.installs.toLocaleString()})]})]})},t)})})})})]}),(0,K.jsxs)(`div`,{className:`flex min-h-0 w-1/2 flex-col`,children:[(0,K.jsx)(T,{as:`p`,variant:`eyebrow`,tone:`muted`,className:`mb-2`,children:`Preview`}),(0,K.jsx)(`div`,{className:`flex flex-1 flex-col overflow-hidden rounded-lg border border-border`,children:f?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`border-b border-border bg-card p-4`,children:(0,K.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,K.jsx)(`div`,{className:`rounded-lg bg-muted p-2`,children:(0,K.jsx)(wZ,{className:`size-icon-lg text-muted-foreground`})}),(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsx)(T,{as:`h3`,variant:`subheading`,tone:`ink`,className:`truncate`,children:f.name}),(0,K.jsxs)(`div`,{className:`mt-1 flex items-center gap-3 text-muted-foreground`,children:[(0,K.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(CZ,{className:`size-icon-xs`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`block`,children:f.topSource})]}),(0,K.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(iJ,{className:`size-icon-xs`}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[f.installs.toLocaleString(),` installs`]})]})]})]}),b&&(0,K.jsx)(`a`,{href:`https://github.com/${b.owner}/${b.repo}`,target:`_blank`,rel:`noopener noreferrer`,className:c(`text-muted-foreground hover:text-foreground`,`transition-[color] duration-fast ease-out-custom motion-reduce:transition-none`),title:`View on GitHub`,children:(0,K.jsx)(qN,{className:`size-icon-md`})})]})}),C?(0,K.jsx)(`div`,{className:`flex flex-1 items-center justify-center`,children:(0,K.jsx)(It,{className:`text-muted-foreground`})}):S?(0,K.jsx)(jS,{className:`flex-1`,children:(0,K.jsx)(`div`,{className:`p-4`,children:(0,K.jsx)(pY,{children:S})})}):(0,K.jsx)(Hx,{className:`flex-1`,iconSlot:(0,K.jsx)(SZ,{}),titleSlot:`Preview unavailable`,actionSlot:x&&(0,K.jsxs)(`a`,{href:x,target:`_blank`,rel:`noopener noreferrer`,className:`flex items-center gap-1 text-info-indicator hover:underline`,children:[(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[`View on skills.sh`,` `]}),(0,K.jsx)(qN,{className:`size-icon-xs`})]})})]}):(0,K.jsx)(Hx,{variant:`fill`,iconSlot:(0,K.jsx)(SZ,{}),titleSlot:`Select a skill to preview`})})]})]}),f&&s&&s.length>1&&(0,K.jsxs)($O,{orientation:`horizontal`,className:c(`bg-card hover:bg-card active:bg-card shadow-raised [--field:var(--field-on-surface)] [--field-disabled:var(--field-on-surface)] [--field-rim:var(--field-rim-on-surface)]`,`gap-3 rounded-lg p-3`),children:[(0,K.jsx)(GN,{className:`size-icon-md shrink-0 text-muted-foreground`}),(0,K.jsx)(tk,{className:`whitespace-nowrap`,children:`Install to`}),(0,K.jsxs)(Pk,{value:g,onValueChange:h,children:[(0,K.jsx)(Ik,{className:`flex-1`,children:(0,K.jsx)(Fk,{})}),(0,K.jsx)(Lk,{children:s.map(e=>{let t=e.displayName??e.name??e.provider??`unknown`;return(0,K.jsxs)(Rk,{value:e.path,children:[t,` (`,e.path,`)`]},e.path)})})]})]})]}),f&&(0,K.jsxs)($w,{children:[A&&s&&s.length>1&&(()=>{let e=l?.[f.name];if(!e)return null;let t=s.find(t=>e.startsWith(t.path+`/`)||e===t.path);return t?(0,K.jsxs)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`mr-auto`,children:[`Installed at `,t.path]}):null})(),(0,K.jsx)(rT,{children:`Cancel`}),(0,K.jsx)(Yw,{onConfirm:j,disabled:!b||A,"data-testid":`install-skill-button`,children:i?`Installing...`:A?`Already installed`:`Install`})]})]})})}function Nzi({labeled:e=!1}){let{workspaceId:t,addSkill:n}=q9(),[r,i]=(0,G.useState)(!1),[a,o]=(0,G.useState)(!1);if(!n)return null;let{onInstall:s,...c}=n,l=async e=>{o(!0);try{await s(e),i(!1)}catch{}finally{o(!1)}};return(0,K.jsxs)(K.Fragment,{children:[e?(0,K.jsxs)(X,{variant:`ghost`,onClick:()=>i(!0),children:[(0,K.jsx)(x7n,{}),`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)(x7n,{})}),(0,K.jsx)(Mzi,{...c,open:r,onOpenChange:i,workspaceId:t,onInstall:e=>void l(e),isInstalling:a})]})}function Pzi({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(Dzi(t??``))),[v,y]=(0,G.useState)(t);if(t!==v){y(t);let e=Dzi(t??``).filter(e=>!g.has(e));e.length>0&&_(new Set([...g,...e]))}let b=a?.join(`
|
|
821
|
+
`).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 SLi=({queryOptions:e}={})=>S_({queryKey:[`mastra-templates`],queryFn:vLi,...e}),CLi=({repoOrSlug:e,owner:t,queryOptions:n})=>S_({queryKey:[`template-repo`,e,t],queryFn:()=>bLi({repoOrSlug:e,owner:t}),...n}),wLi=({repo:e,owner:t,branch:n,queryOptions:r})=>S_({queryKey:[`template-repo-env-vars`,e,t,n],queryFn:()=>xLi({repo:e,owner:t,branch:n}),...r}),TLi=({queryOptions:e}={})=>{let t=Y();return S_({queryKey:[`agent-builder-workflow`],queryFn:async()=>await t.getAgentBuilderAction(`merge-template`).details(),...e})},ELi=({queryOptions:e}={})=>{let t=Y();return w_({mutationFn:async({runId:e})=>await t.getAgentBuilderAction(`merge-template`).createRun({runId:e}),...e})},DLi=({queryOptions:e}={})=>{let t=Y();return w_({mutationFn:async({runId:e})=>await t.getAgentBuilderAction(`merge-template`).runById(e),...e})},OLi=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)},kLi=(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=OLi(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=OLi(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}},ALi=(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)}},jLi=(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}=kLi(a,s,e);s=c,r(c),(a.runId||i||t)&&ALi(a.runId||i||t,c)}}catch(t){console.error(`💥 [processStream] Error processing template installation stream:`,t);let{newState:n}=kLi({type:`error`,payload:{error:t instanceof Error?t.message:`Unknown error`}},s,e);r(n)}finally{a(!1),o.releaseLock()}}}},MLi=({workflowInfo:e,queryOptions:t}={})=>{let n=Y(),{streamResult:r,isStreaming:i,processStream:a}=jLi(e);return{streamInstall:w_({mutationFn:async({inputData:e,selectedModel:t,runId:r})=>{for(let i=1;i<=3;i++)try{let i=n.getAgentBuilderAction(`merge-template`),o=new On;o.set(`selectedModel`,t);let s=await i.stream({inputData:e,requestContext:o},r);await a(s,r);return}catch(e){console.error(`💥 [streamInstall] Attempt ${i} failed:`,e);let t=e?.message?.includes(`Failed to fetch`)||e?.message?.includes(`NetworkError`)||e?.message?.includes(`network error`)||e?.message?.includes(`fetch`)||e?.code===`NETWORK_ERROR`||e?.name===`TypeError`;if(console.warn(`Stream attempt ${i}/3 failed:`,e),t){let e=r?`Network error during template installation (likely hot reload). Please refresh the page to resume from where you left off using runId: ${r}`:`Network error during template installation (likely hot reload). Please try again.`;throw console.error(`🔌 Stream network error:`,e),Error(e)}throw console.error(`❌ [streamInstall] Non-network error or max retries reached, throwing:`,e),e}},...t?.streamInstall}),streamResult:r,isStreaming:i}},NLi=({workflowInfo:e,queryOptions:t}={})=>{let n=Y(),{streamResult:r,isStreaming:i,processStream:a}=jLi(e);return{observeInstall:w_({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 PLi(e){return e.replace(/\/$/,``).split(`/`).pop()}function FLi({templates:e,linkComponent:t,className:n,isLoading:r}){let i=t||`a`;return r?(0,K.jsx)(`div`,{className:c(`grid gap-y-4`,n),children:Array.from({length:5}).map((e,t)=>(0,K.jsx)(`div`,{className:`h-16 animate-pulse rounded-lg bg-card`},t))}):(0,K.jsx)(`div`,{className:c(`grid gap-y-4`,n),children:e.map(e=>{let t=e?.agents||e?.tools||e?.networks||e?.workflows||e?.mcp;return(0,K.jsxs)(`article`,{className:c(Pv,`grid w-full grid-cols-[1fr_auto] overflow-hidden rounded-lg state-layer`),children:[(0,K.jsxs)(i,{to:`/templates/${e.slug}`,className:c(`group grid`,{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":e.imageURL}),children:[e.imageURL&&(0,K.jsx)(`div`,{className:`overflow-hidden`,children:(0,K.jsx)(`div`,{className:`thumb transition-scale h-full w-full bg-cover duration-150`,style:{backgroundImage:`url(${e.imageURL})`}})}),(0,K.jsxs)(`div`,{className:c(`grid w-full gap-0.5 px-4 py-3`,`[&_svg]:h-[1em] [&_svg]:w-[1em] [&_svg]:text-muted-foreground`),children:[(0,K.jsx)(T,{as:`h2`,tone:`ink`,children:e.title}),(0,K.jsx)(T,{className:c(_S,A),children:e.description}),(0,K.jsxs)(`div`,{className:`mt-3 hidden flex-wrap items-center gap-x-8 gap-y-4 text-muted-foreground 2xl:flex`,children:[t&&(0,K.jsxs)(`ul`,{className:c(`text-muted-foreground`,`m-0 flex list-none gap-4 p-0`,`[&>li]:flex [&>li]:items-center [&>li]:gap-0.5`),children:[e?.agents&&e.agents.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(PN,{}),` `,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)(HN,{}),` `,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)(T7e,{}),` `,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)(GS,{}),` `,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)(RN,{}),` `,e.mcp.length]})})]}),(0,K.jsx)(`div`,{className:`flex items-center gap-4`,children:e.supportedProviders.map(e=>(0,K.jsx)(T,{tone:`muted`,as:`span`,variant:`body`,children:e},e))})]})]})]}),(0,K.jsx)(`a`,{href:e.githubUrl,className:c(`group ml-auto hidden items-center gap-2 pr-4`,`lg:flex`),target:`_blank`,rel:`noopener noreferrer`,children:(0,K.jsx)(T,{as:`span`,variant:`body`,children:(0,K.jsxs)(`span`,{className:c(`flex items-center gap-2 rounded bg-sidebar px-2 py-1`,lBe,_S,A),children:[(0,K.jsx)(CZ,{}),` `,PLi(e.githubUrl)]})})})]},e.slug)})})}function ILi({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:i,onProviderChange:a,searchTerm:o,onSearchChange:s,onReset:l,className:u,isLoading:d}){return d?(0,K.jsxs)(`div`,{className:c(`flex h-[6.5rem] items-center gap-5`,`[&>div]:h-8 [&>div]:w-48 [&>div]:animate-pulse [&>div]:bg-card`,u),children:[(0,K.jsx)(`div`,{}),` `,(0,K.jsx)(`div`,{}),` `,(0,K.jsx)(`div`,{})]}):(0,K.jsxs)(`div`,{className:c(`sticky top-0 mx-auto flex flex-wrap gap-1.5 bg-background py-5`,u),children:[(0,K.jsx)(wH,{label:`Search templates`,placeholder:`Search templates`,size:`sm`,value:o,onValueChange:s}),(0,K.jsxs)(Pk,{value:t,onValueChange:i,children:[(0,K.jsx)(Ik,{"aria-label":`Search by tag`,size:`sm`,className:`w-auto`,children:(0,K.jsx)(Fk,{placeholder:`Select an option`})}),(0,K.jsx)(Lk,{children:e.map(e=>(0,K.jsx)(Rk,{value:e.value,children:e.label},e.value))})]}),(0,K.jsxs)(Pk,{value:r,onValueChange:a,children:[(0,K.jsx)(Ik,{"aria-label":`Search by provider`,size:`sm`,className:`w-auto`,children:(0,K.jsx)(Fk,{placeholder:`Select an option`})}),(0,K.jsx)(Lk,{children:n.map(e=>(0,K.jsx)(Rk,{value:e.value,children:e.label},e.value))})]}),l&&(0,K.jsx)(J4,{onClick:l})]})}var LLi=[{id:`templates`,label:`Templates`}];function RLi(){let{data:e,isLoading:t}=SLi(),{templates:n,tags:r,providers:i}=e??{templates:[],tags:[],providers:[]},[a,o]=(0,G.useState)(`all`),[s,l]=(0,G.useState)(`all`),[u,d]=(0,G.useState)(``),f=[{value:`all`,label:`Any tag`}];(r||[]).forEach(e=>{f.push({value:e,label:e})});let p=[{value:`all`,label:`Any provider`}];(i||[]).forEach(e=>{p.push({value:e,label:e})});let m=(e,t)=>{t===`tag`?o(e):t===`provider`&&l(e)},h=e=>{d(e)},g=()=>{o(`all`),l(`all`),d(``)},_=n.filter(e=>!(u&&!e.title.toLowerCase().includes(u)&&!e.description.toLowerCase().includes(u)||a!==`all`&&!e.tags.includes(a)||s!==`all`&&!e.supportedProviders.includes(s))),v=u||a!==`all`||s!==`all`;return(0,K.jsxs)(MS,{variant:`fit`,breadcrumbs:(0,K.jsx)(uN,{crumbs:LLi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Templates`}),(0,K.jsx)(vS,{children:(0,K.jsxs)(xJe,{children:[(0,K.jsx)(xx,{children:(0,K.jsx)(SZ,{})}),`Templates`]})}),(0,K.jsxs)(`div`,{className:c(`z-10 h-full w-full overflow-y-auto px-5 pb-12`),children:[(0,K.jsx)(ILi,{selectedTag:a,onTagChange:e=>m(e,`tag`),tagOptions:f,selectedProvider:s,onProviderChange:e=>m(e,`provider`),providerOptions:p,searchTerm:u,onSearchChange:h,onReset:v?g:void 0,className:`max-w-[80rem]`,isLoading:t}),(0,K.jsx)(FLi,{templates:_,linkComponent:jv,className:`mx-auto max-w-[80rem]`,isLoading:t})]})]})}var zLi=U(`IconEmojiSad`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`circle`,{cx:`12`,cy:`12`,r:`9`,stroke:`currentColor`,strokeWidth:`2`}),(0,K.jsx)(`path`,{d:`M10.75 9.9C10.75 11.0046 10.0784 11.75 9.25 11.75C8.42157 11.75 7.75 11.0046 7.75 9.9C7.75 8.79543 8.42157 8 9.25 8C10.0784 8 10.75 8.79543 10.75 9.9Z`,fill:`currentColor`}),(0,K.jsx)(`path`,{d:`M16.25 9.9C16.25 11.0046 15.5784 11.75 14.75 11.75C13.9216 11.75 13.25 11.0046 13.25 9.9C13.25 8.79543 13.9216 8 14.75 8C15.5784 8 16.25 8.79543 16.25 9.9Z`,fill:`currentColor`}),(0,K.jsx)(`path`,{d:`M7.89328 15.4758C7.7698 15.623 7.69925 15.8109 7.70417 16.0051C7.70903 16.1992 7.78791 16.3827 7.92489 16.5166C8.06187 16.6504 8.24712 16.7251 8.44131 16.7254C8.63557 16.7259 8.82181 16.651 8.9661 16.5242C9.05273 16.4499 9.14033 16.3801 9.23093 16.313C10.042 15.7109 11.0211 15.4001 12.0034 15.4C12.9856 15.3986 13.964 15.7081 14.7725 16.3111C14.8628 16.3783 14.9501 16.4481 15.0364 16.5226C15.1803 16.6498 15.3663 16.7253 15.5606 16.7254C15.7548 16.7256 15.9403 16.6515 16.0776 16.5181C16.215 16.3846 16.2944 16.2014 16.2999 16.0073C16.3054 15.8131 16.2354 15.625 16.1124 15.4774C16.0126 15.3603 15.909 15.2487 15.799 15.1403C14.816 14.1611 13.4082 13.5927 12.002 13.6C10.5957 13.595 9.19111 14.1644 8.20718 15.1399C8.09708 15.2479 7.99334 15.3591 7.89328 15.4758Z`,fill:`currentColor`})]}));function BLi({children:e,className:t}){return(0,K.jsx)(`div`,{className:c(`transition-height mt-12 rounded-lg border border-border px-4 py-5 lg:min-h-[25rem] lg:px-12`,t),children:e})}function VLi({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)(Gx,{className:`text-warning-foreground`}),title:`Template Installed with Warnings`}:{icon:(0,K.jsx)(zLi,{}),title:`Template Installation Failed`};return(0,K.jsxs)(BLi,{className:`mb-5 content-center space-y-4 text-muted-foreground`,children:[(0,K.jsxs)(`div`,{className:`grid content-center items-center justify-items-center gap-4 [&>svg]:h-8 [&>svg]:w-8`,children:[o,(0,K.jsxs)(`div`,{className:`space-y-2 text-center`,children:[(0,K.jsx)(T,{variant:`subheading`,tone:`ink`,children:s}),(0,K.jsx)(T,{tone:`muted`,children:a()})]})]}),t&&t.length>0&&(0,K.jsxs)(`details`,{children:[(0,K.jsx)(`summary`,{className:c(`text-muted-foreground hover:text-foreground`,`cursor-pointer text-center select-none`),children:(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[`Show Validation Issues (`,t.length,`)`]})}),(0,K.jsx)(`div`,{className:`mt-4 max-h-60 space-y-2 overflow-auto rounded bg-muted p-3 text-left`,children:t.map((e,t)=>(0,K.jsxs)(`div`,{className:`border-l-2 border-destructive-indicator pl-2`,children:[(0,K.jsx)(T,{as:`p`,variant:`column`,className:`text-destructive-foreground`,children:e.type===`typescript`?`🔴 TypeScript Error`:`⚠️ Lint Error`}),(0,K.jsx)(iC,{className:`mt-1 text-caption wrap-break-word whitespace-pre-wrap text-muted-foreground`,code:e.message})]},t))})]}),n&&!i&&(0,K.jsxs)(`details`,{children:[(0,K.jsx)(`summary`,{className:c(`text-muted-foreground hover:text-foreground`,`cursor-pointer text-center select-none`),children:(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`block`,children:`Show Details`})}),(0,K.jsx)(`div`,{className:`mt-4 max-h-60 overflow-auto rounded bg-muted p-3 text-left`,children:(0,K.jsx)(iC,{className:`text-caption wrap-break-word whitespace-pre-wrap`,code:n})})]})]})}function HLi({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:i,handleInstallTemplate:a,handleVariableChange:o,isLoadingEnvVars:s,isInstalling:l,defaultModelProvider:u,defaultModelId:d,onModelUpdate:f}){return(0,K.jsx)(BLi,{children:(0,K.jsxs)(`div`,{className:`mx-auto my-4 grid max-w-[40rem] gap-5 p-4 lg:p-5`,children:[(0,K.jsxs)(T,{as:`h2`,variant:`heading`,tone:`muted`,className:c(`flex items-center gap-2`,`[&_svg]:h-[1.2em] [&_svg]:opacity-70 [&>svg]:w-[1.2em]`),children:[`Install Template `,(0,K.jsx)(SZ,{})]}),(0,K.jsxs)($O,{orientation:`horizontal`,children:[(0,K.jsx)(tk,{children:`Template AI Model Provider`}),(0,K.jsx)(Jpt,{className:`flex-1`,children:(0,K.jsxs)(Pk,{name:`template-provider`,value:t,onValueChange:n,children:[(0,K.jsx)(Ik,{size:`md`,children:(0,K.jsx)(Fk,{placeholder:`Select`})}),(0,K.jsx)(Lk,{children:e.map(e=>(0,K.jsx)(Rk,{value:e.value,children:e.label},e.value))})]})})]}),t&&Object.entries(r||{}).length>0&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h3`,tone:`muted`,children:`Set required Environmental Variables`}),(0,K.jsx)(`div`,{className:`grid grid-cols-[1fr_1fr] items-start gap-4`,children:s?(0,K.jsxs)(`div`,{className:c(`text-muted-foreground`,`col-span-2 flex items-center justify-center gap-4`,`[&_svg]:h-[1.1em] [&_svg]:w-[1.1em] [&_svg]:opacity-50`,`animate-in duration-300 fade-in`),children:[(0,K.jsx)(It,{}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[` `,`Loading variables...`]})]}):Object.entries(r).map(([e,t])=>(0,K.jsxs)(G.Fragment,{children:[(0,K.jsxs)($O,{className:`w-full`,children:[(0,K.jsx)(tk,{className:`sr-only`,children:`Key`}),(0,K.jsx)(Hj,{name:`env-${e}`,value:e,disabled:!0,className:`w-full`})]}),(0,K.jsxs)($O,{invalid:i.includes(e),className:`w-full`,children:[(0,K.jsx)(tk,{className:`sr-only`,children:`Value`}),(0,K.jsx)(Hj,{name:e,value:t,onChange:o,autoComplete:`off`,className:`w-full`}),(0,K.jsx)(rk,{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)(e2r,{defaultProvider:u||``,defaultModel:d||``,updateModel:f||(()=>Promise.resolve({message:`Updated`})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:`Provider`})]})]}),t&&!s&&(0,K.jsx)(X,{className:c(`mt-4 flex min-h-10 w-full items-center justify-center gap-2 rounded-lg bg-card state-layer text-foreground`,`[&_svg]:h-[1.1em] [&_svg]:text-foreground [&>svg]:w-[1.1em]`),onClick:a,disabled:!t||!u||!d||i.length>0||l,children:l?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(It,{className:`h-4 w-4`}),` Installing...`]}):(0,K.jsxs)(K.Fragment,{children:[`Install `,(0,K.jsx)(QV,{})]})})]})})}function ULi({title:e,description:t,githubUrl:n,isLoading:r,infoData:i,templateSlug:a}){let o=a?`feat/install-template-${a}`:`feat/install-template-[slug]`;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`mt-5 grid items-center`,children:(0,K.jsxs)(`div`,{className:c(`flex items-center gap-3`,`[&>svg]:h-[1.2em] [&>svg]:w-[1.2em] [&>svg]:opacity-50`,{"[&>svg]:opacity-20":r}),children:[(0,K.jsx)(SZ,{}),(0,K.jsx)(`h2`,{className:c({"flex min-w-[50%] rounded-lg bg-muted":r}),children:(0,K.jsx)(T,{as:`span`,variant:`title`,className:`block`,children:r?(0,K.jsx)(K.Fragment,{children:`\xA0`}):e})})]})}),(0,K.jsxs)(`div`,{className:`grid gap-x-24 lg:grid-cols-[1fr_1fr]`,children:[(0,K.jsxs)(`div`,{className:`grid`,children:[(0,K.jsx)(T,{tone:`muted`,className:c(`mt-2 mb-4`,{"rounded-lg bg-muted":r}),children:r?(0,K.jsx)(K.Fragment,{children:`\xA0`}):t}),!r&&a&&(0,K.jsxs)(`div`,{className:c(`mb-4 rounded-lg border border-border bg-background p-4`,`flex items-start gap-3`),children:[(0,K.jsx)(`div`,{className:`mt-0.5 shrink-0`,children:(0,K.jsx)(Ux,{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)(BS,{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)(nX,{children:o})]}),(0,K.jsx)(T,{tone:`muted`,as:`p`,variant:`caption`,children:`This ensures safe installation with easy rollback if needed. Your main branch remains unchanged.`})]})]})]}),n&&(0,K.jsxs)(`a`,{href:n,target:`_blank`,rel:`noopener noreferrer`,className:c(`text-muted-foreground hover:text-foreground`,`mt-auto flex items-center gap-2`),children:[(0,K.jsx)(CZ,{}),(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:n?.split(`/`)?.pop()})]})]}),i&&(0,K.jsx)(i2r,{data:i,labelsAreHidden:!0,isLoading:r})]})]})}function WLi(e){switch(e){case`running`:return(0,K.jsx)(It,{size:`sm`,"aria-hidden":!0});case`success`:return(0,K.jsx)(sC,{"aria-hidden":!0});case`failed`:return(0,K.jsx)(hw,{"aria-hidden":!0});default:return null}}function GLi(){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 KLi({status:e,variant:t}){return t===`plain`?(0,K.jsx)(`span`,{className:c(`flex size-icon-md items-center justify-center self-center [&>svg]:size-icon-md`,u.colors,{"[&>svg]:text-success-indicator":e===`success`,"[&>svg]:text-destructive-foreground":e===`failed`}),children:e===`pending`?(0,K.jsx)(GLi,{}):WLi(e)}):(0,K.jsx)(`span`,{className:c(`flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none`,u.colors,u.transform,{"[&>svg]:text-success-indicator":e===`success`,"[&>svg]:text-destructive-foreground":e===`failed`,"border border-dashed border-placeholder":e===`pending`,"[&>svg]:size-icon-md":e!==`running`,"bg-success-subtle":e===`success`,"bg-destructive-subtle":e===`failed`,"scale-110":e===`success`||e===`failed`}),children:WLi(e)})}function qLi({step:e,isActive:t,position:n,variant:r=`default`}){let i=t||e.status===`success`?`ink`:`muted`;return(0,K.jsxs)(`div`,{className:c(`grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none`,u.colors,{"border border-transparent":r==="default","border-dashed border-placeholder bg-card":t&&r==="default"}),children:[(0,K.jsxs)(`div`,{className:`grid min-w-0 grid-cols-[auto_1fr] gap-2`,children:[(0,K.jsxs)(T,{as:`span`,tone:i,className:c(`flex min-w-6 justify-end`,u.colors),children:[n,`.`]}),(0,K.jsxs)(`div`,{className:`min-w-0`,children:[(0,K.jsx)(T,{as:`h4`,tone:i,className:u.colors,children:e.title}),e.description&&(0,K.jsx)(T,{tone:`faint`,className:c(`-mt-0.5`,{truncate:r===`plain`}),children:e.description})]})]}),(0,K.jsx)(KLi,{status:e.status,variant:r})]})}function JLi({currentStep:e,steps:t=[],className:n}){return(0,K.jsx)(`div`,{className:c(n),children:t.map((t,n)=>(0,K.jsx)(qLi,{step:t,isActive:e?.id===t.id,position:n+1},t.id))})}function YLi({steps:e}){let t=e.length,n=e.filter(e=>e.status===`success`).length;return(0,K.jsxs)(`div`,{className:`flex w-full flex-col content-center justify-center gap-4`,children:[(0,K.jsx)(`div`,{className:`grid w-full grid-cols-[0_repeat(9,1fr)]`,children:e.map((t,n)=>(0,K.jsx)(`div`,{className:c(`relative flex h-8 items-center justify-end`,u.colors,{"bg-success-subtle":t.status===`success`&&e?.[n-1]?.status===`success`}),children:(0,K.jsx)(`div`,{className:c(`absolute right-0 z-10 flex size-8 translate-x-1/2 items-center justify-center self-center rounded-full bg-fill text-column text-muted-foreground motion-reduce:transition-none`,u.colors,u.transform,{"border border-dashed border-placeholder":t.status===`pending`,"scale-110 bg-success-subtle text-success-subtle-foreground":t.status===`success`,"scale-110 bg-destructive-subtle text-destructive-subtle-foreground":t.status===`failed`}),children:t.status===`running`?(0,K.jsx)(It,{}):n+1})},t.id))}),(0,K.jsxs)(`div`,{className:c(`text-center text-caption text-muted-foreground`,u.colors),children:[n,` of `,t,` steps completed`]})]})}var XLi=(0,G.createContext)(3);function ZLi({title:e,description:t,action:n,done:r,className:i,children:a}){let o=(0,G.useContext)(XLi);return(0,K.jsxs)(`li`,{className:c(`group/step grid grid-cols-[1.5rem_minmax(0,1fr)] gap-x-4 [counter-increment:ds-step]`,i),children:[(0,K.jsxs)(`div`,{className:`flex flex-col items-center`,children:[(0,K.jsx)(`span`,{className:c(`flex size-6 shrink-0 items-center justify-center rounded-full`,u.colors,r?`bg-success-indicator/18 text-success-indicator`:`bg-fill text-foreground`),children:r?(0,K.jsx)(sC,{className:`size-icon-sm`,"aria-label":`Done`}):(0,K.jsx)(T,{as:`span`,variant:`column`,className:`before:content-[counter(ds-step)]`,"aria-hidden":!0})}),(0,K.jsx)(`span`,{"aria-hidden":!0,className:`w-px flex-1 bg-border group-last/step:hidden`})]}),(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-3 pb-8 group-last/step:pb-0`,children:[(0,K.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,K.jsxs)(`div`,{className:`flex min-h-6 flex-wrap items-center justify-between gap-x-6 gap-y-2`,children:[(0,K.jsx)(T,{as:o===2?`h2`:`h3`,variant:`label`,className:`text-pretty`,children:e}),n==null?null:(0,K.jsx)(`div`,{className:`flex shrink-0 items-center gap-2`,children:n})]}),t==null?null:(0,K.jsx)(T,{as:`p`,variant:`body-sm`,tone:`muted`,className:`max-w-[70ch] text-pretty`,children:t})]}),a]})]})}function QLi({headingLevel:e=3,className:t,children:n}){return(0,K.jsx)(XLi.Provider,{value:e,children:(0,K.jsx)(`ol`,{className:c(`flex flex-col [counter-reset:ds-step]`,t),children:n})})}Object.assign(QLi,{Step:ZLi});function $Li({name:e,streamResult:t,runId:n,workflowInfo:r}){let i=t?.phase||`initializing`,a=t?.payload?.workflowState,o=t?.payload?.currentStep,s=t?.error,l=a?.steps||{},u=Object.keys(l).length>0,d=e=>e===`input`||e.endsWith(`.input`)||e.startsWith(`Mapping_`)&&/[0-9a-f]{8}/.test(e)||/[0-9a-f]{8,}/.test(e)?!1:!r?.allSteps||e in r.allSteps,f=Object.entries(l).filter(([e,t])=>d(e)),p=f.length,m=()=>{switch(i){case`initializing`:return`Preparing template installation...`;case`processing`:return`Installing ${e} template`;case`completed`:return`Template installation completed!`;case`error`:return`Template installation failed`;default:return`Installing template...`}},h=f.map(([e,t])=>({id:e,status:t?.status,description:t?.description,title:e.charAt(0).toUpperCase()+e.slice(1).replace(/-/g,` `),isActive:o?.id===e}));return(0,K.jsxs)(BLi,{className:`mb-5 content-center space-y-6 text-muted-foreground`,children:[(0,K.jsxs)(`div`,{className:`text-center`,children:[(0,K.jsx)(T,{as:`h3`,variant:`heading`,tone:`ink`,children:m()}),(t?.runId||n)&&(0,K.jsxs)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`mt-2`,children:[`Run ID: `,t?.runId??n]})]}),u&&p>0&&![`error`].includes(i)&&(0,K.jsx)(`div`,{className:`mx-auto w-full max-w-[30rem] px-4`,children:(0,K.jsx)(YLi,{steps:h})}),s&&i===`error`&&(0,K.jsxs)(`div`,{className:c(`text-foreground`,`flex items-center gap-3 rounded-lg bg-destructive-subtle p-4`,`[&>svg]:h-6 [&>svg]:w-6 [&>svg]:text-destructive-foreground [&>svg]:opacity-70`),children:[(0,K.jsx)(Vx,{}),(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:s||`Something went wrong`})]}),u&&(0,K.jsx)(JLi,{steps:h,currentStep:o,className:`pb-4`}),!u&&i===`initializing`&&(0,K.jsxs)(`div`,{className:c(`text-muted-foreground`,`grid justify-items-center gap-4 text-center`),children:[(0,K.jsx)(It,{}),(0,K.jsx)(T,{as:`p`,variant:`body`,children:`This may take some time...`})]})]})}function eRi({name:e,installedEntities:t}){return(0,K.jsxs)(BLi,{className:c(`grid content-center items-center justify-items-center gap-4`,`[&>svg]:h-8 [&>svg]:w-8`),children:[(0,K.jsx)(SZ,{}),(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)(i2r,{data:t})]})}function tRi(){let{templateSlug:e}=Ev(),t=[{id:`templates`,label:`Templates`,to:`/templates`},{id:`template`,label:SMt(e)}],[n,r]=Mv(),[i,a]=(0,G.useState)(``),[o,s]=(0,G.useState)(``),[l,u]=(0,G.useState)(``),[d,f]=(0,G.useState)({}),[p,m]=(0,G.useState)([]),[h,g]=(0,G.useState)(null),[_,v]=(0,G.useState)(!1),[y,b]=(0,G.useState)(``),[x,S]=(0,G.useState)(!1),[C,w]=(0,G.useState)(!1),[T,E]=(0,G.useState)([]),{data:D,isLoading:O}=CLi({repoOrSlug:e,owner:`mastra-ai`}),k=`1.86.0-alpha.1`.includes(`beta`)??!1?`beta`:`main`,{data:A,isLoading:j}=wLi({repo:D?.githubUrl?new URL(D.githubUrl).pathname.split(`/`)[2]:`template-${e}`,owner:`mastra-ai`,branch:k}),{data:M,isLoading:N}=TLi(),{mutateAsync:P,isPending:F}=ELi(),{mutateAsync:I}=DLi(),{streamInstall:L,streamResult:R,isStreaming:z}=MLi({workflowInfo:M}),{observeInstall:B,streamResult:V,isStreaming:H}=NLi({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)(HN,{})},{key:`agents`,label:`Agents`,value:D?.agents?.length?D.agents.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(PN,{})},{key:`workflows`,label:`Workflows`,value:D?.workflows?.length?D.workflows.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(GS,{})},{key:`providers`,label:`Providers`,value:D?.supportedProviders?.length?D.supportedProviders.join(`, `):`n/a`,icon:(0,K.jsx)(k3,{})},{key:`tags`,label:`Tags`,value:D?.tags?.length?D.tags.join(`, `):`n/a`,icon:(0,K.jsx)(vX,{})}],U=[{...te[0]},{...te[1]},{...te[2]}].filter(e=>e.value!==`n/a`);return(0,G.useEffect)(()=>{A&&f(A)},[A]),(0,G.useEffect)(()=>{let e=R||V;e?.phase===`error`&&e?.error&&g(typeof e.error==`string`?e.error:String(e.error))},[R?.phase,R?.error,V?.phase,V?.error]),(0,K.jsxs)(MS,{variant:`fit`,breadcrumbs:(0,K.jsx)(uN,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(`div`,{className:c(`h-full w-full overflow-y-scroll lg:px-12`),children:(0,K.jsxs)(`div`,{className:`mx-auto grid w-full max-w-[80rem] gap-y-4 p-4`,children:[(0,K.jsx)(ULi,{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)($Li,{name:D.title,streamResult:H?V:R,runId:y,workflowInfo:M}),_&&(0,K.jsx)(eRi,{name:D.title,installedEntities:U,linkComponent:jv}),h&&(0,K.jsx)(VLi,{errorMsg:h,validationErrors:T.length>0?T:R?.validationResults?.errors||V?.validationResults?.errors}),!z&&!H&&!_&&!h&&(0,K.jsx)(HLi,{providerOptions:ee,selectedProvider:i,onProviderChange:e=>{a(e)},variables:d,setVariables:f,errors:p,setErrors:m,handleInstallTemplate:async()=>{let e=Object.entries(d).reduce((e,[t,n])=>(n===``&&e.push(t),e),[]);if(e.length>0)m(e);else if(D){g(null),v(!1),b(``),w(!0);try{let e={repo:D.githubUrl||`https://github.com/mastra-ai/template-${D.slug}`,ref:k,slug:D.slug,variables:d},{runId:t}=await P({});b(t),r(e=>{let n=new URLSearchParams(e);return n.set(`runId`,t),n.set(`resume`,`true`),n.set(`provider`,i||`openai`),n}),await L.mutateAsync({inputData:e,selectedModel:{provider:o,modelId:l},runId:t})}catch(e){w(!1),g(e?.message||`Template installation failed`),console.error(`Template installation failed`,e)}}},handleVariableChange:e=>{let{name:t,value:n}=e.target;n.trim()===``?m(e=>[...e,t]):m(e=>e.filter(e=>e!==t)),f(e=>({...e,[t]:n}))},isLoadingEnvVars:j||N,isInstalling:F,defaultModelProvider:o,defaultModelId:l,onModelUpdate:async e=>(s(e.provider),u(e.modelId),{message:`Model updated successfully`})})]})]})})]})}var nRi=e=>e.threadId,rRi=e=>`traces`in e?e.traces:e.threads;function iRi(e,t){return`traces`in e?{traces:{...e.traces,...t}}:{threads:{...e.threads,...t}}}function aRi(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 oRi({query:e,rolling:t,fixedStart:n=!1,autoRefetch:r=!0,limit:i,enabled:a=!0}){let o=Y(),{anchorWindow:s,reanchor:c}=HIi(e,n),l=(0,G.useMemo)(()=>s?{...e,timeRange:iRi(e.timeRange,s)}:e,[e,s]),u=pZr({query:l,limit:i,enabled:a,queryOptions:LIi}),{headRows:d}=WIi({queryKey:[`threads`,e],fetchHead:async t=>(await o.queryTraceThreads({...e,timeRange:iRi(e.timeRange,VIi(rRi(e.timeRange),t,n)),orderBy:[{field:`endedAt`,direction:`desc`}],page:{limit:50}})).threads,getId:nRi,getEndedAt:e=>e.endedAt,since:Date.parse(rRi(l.timeRange).to),enabled:a&&t&&r&&u.threads!==void 0&&!u.isFetching&&!u.isError,onOverflow:()=>c(rRi(e.timeRange))}),{orderBy:f}=e,p=u.threads,m=(0,G.useMemo)(()=>p&&KIi(p,d,{getId:nRi,compare:aRi(f),hasNextPage:u.hasNextPage}),[p,d,f,u.hasNextPage]);return{...u,threads:m}}function sRi(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 cRi=[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`],lRi=[];function uRi(){let{data:e}=m7(),t=e?.capabilities.traceQueryTimeToFirstChunk??!1,n=e?.capabilities.traceQueryTimeToFirstToken??!1,{data:r=lRi}=t8(),{data:i=lRi}=n8();return(0,G.useMemo)(()=>[e8r,...Eoi({withTimeToFirstChunk:t,withTimeToFirstToken:n,entityNames:r,environments:i})],[t,n,r,i])}function dRi({tokens:e,groups:t,onFiltersChange:n}){let r=(0,G.useMemo)(()=>l$r(e),[e]),i=(0,G.useMemo)(()=>{let e=f$r([],t);return{...e,nodes:[s5,...r,...e.nodes]}},[r,t]),a=(0,G.useCallback)(e=>{let t=m$r({...e,nodes:e.nodes.filter(e=>H6(e)||e.fieldId!==`timeRange`)});n(t.tokens,t.groups)},[n]);return{filterBarValue:i,onFilterBarChange:a,onFilterByField:(0,G.useCallback)((e,t)=>{let n=r.filter(t=>t.fieldId!==e),o={id:`${e}:${t}`,fieldId:e,operatorId:`is`,value:t},s=i.nodes.filter(H6);a({...i,nodes:[...n,o,...s]})},[r,i,a])}}var fRi=e=>e;function pRi({datePreset:e,dateFrom:t,dateTo:n,minDate:r,tokens:i,groups:a,onDatePresetChange:o,onDateChange:s,onDateRangeChange:c,onFiltersChange:l,disabled:u}){let d=uRi(),{filterBarValue:f,onFilterBarChange:p}=dRi({tokens:i,groups:a,onFiltersChange:l});return(0,K.jsxs)(c5,{fields:d,operators:LQr,value:f,onValueChange:p,createItemId:fRi,maxDepth:3,"aria-label":`Thread filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(c5.Chips,{renderChip:i=>i.fieldId===`timeRange`?(0,K.jsx)(c5.TimeRange,{preset:e,onPresetChange:o,dateFrom:t,dateTo:n,minDate:r,onDateChange:s,onDateRangeChange:c,disabled:u,presets:cRi,defaultPreset:K8.datePreset}):(0,K.jsx)(c5.Chip,{item:i})}),(0,K.jsx)(c5.Input,{placeholder:`Filter threads`})]})}function mRi({selectedThreadId:e,onSelectedThreadChange:t,onOpenScore:n,urlState:r}){let i=zIi(r),{timeRange:a,tokens:o,groups:s,sort:c}=i,l=h7().enabled,u=$si().enabled,d=Psi({scope:`threads`}),{data:f,isLoading:p}=m7(),m=f?.capabilities.traceQueryTimeToFirstChunk??!1,h=f?.capabilities.traceQueryTimeToFirstToken??!1,g=(0,G.useMemo)(()=>p?d.preferences:X2r(d.preferences,{withTimeToFirstChunk:m,withTimeToFirstToken:h}),[d.preferences,p,m,h]),{threads:_,hasNextPage:v,isFetchingNextPage:y,setEndOfListElement:b,isLoading:x,isError:S,error:C}=oRi({query:(0,G.useMemo)(()=>{let e=koi(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,fixedStart:i.datePreset===`custom`}),w=(0,G.useMemo)(()=>(_??[]).map(sRi),[_]),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)(g3r,{toolbar:(0,K.jsxs)(K.Fragment,{children:[r&&(0,K.jsx)(ksi,{page:`threads`,...r,columns:d}),(0,K.jsxs)(_K,{children:[(0,K.jsx)(_K.Start,{children:(0,K.jsx)(pRi,{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)(_K.End,{children:(0,K.jsx)(pLi,{scope:`threads`,value:d.preferences,onChange:d.setPreferences})})]})]}),error:S?(0,K.jsx)(U8,{error:C,resource:`threads`,errorTitle:`Failed to load threads`}):void 0,empty:D?(0,K.jsx)(O2r,{resource:`threads`,datePreset:i.datePreset,dateFrom:i.dateFrom,dateTo:i.dateTo}):void 0,children:(0,K.jsx)(R9r,{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)($li,{open:!!e,threadId:e??``,depth:1,closeLabel:`Close`,withQueryTrace:l,withFeedback:u,onOpenScore:n,onClose:()=>t(void 0)})]})}function hRi(){let{enabled:e,isLoading:t}=Xsi(),n=Tv(),[r,i]=Mv();return(0,K.jsx)(FIi,{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)(mRi,{urlState:{searchParams:r,setSearchParams:i},selectedThreadId:QIi(r),onSelectedThreadChange:e=>i(t=>$Ii(t,e),{replace:!0}),onOpenScore:(e,t)=>n(qDn(e,t))})})}var gRi=()=>(0,K.jsx)(Hx,{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)(qN,{}),children:`Workflows documentation`}),variant:`fill`});function _Ri(e,t,n){return AZ(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 vRi(e){return Object.keys(e.steps??{}).filter(t=>e.allSteps?.[t]?.isWorkflow)}function yRi(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 bRi(e,t,n){let r=yRi(t),i=[],a=(e,o,s,c,l,u)=>{let d=vRi(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 xRi=`auto 24rem minmax(0, 1fr) auto auto auto`;function SRi({guides:e,isLastChild:t}){return(0,K.jsxs)(`span`,{"aria-hidden":!0,className:`-my-6 flex shrink-0 self-stretch`,children:[e.map((e,t)=>(0,K.jsx)(`span`,{className:c(`w-6`,e&&`border-l border-border`)},t)),(0,K.jsxs)(`span`,{className:`relative w-6`,children:[(0,K.jsx)(`span`,{className:c(`absolute top-0 left-0 border-l border-border`,t?`h-1/2`:`h-full`)}),(0,K.jsx)(`span`,{className:`absolute top-1/2 left-0 w-3.5 border-b border-border`})]})]})}function CRi({row:e,isExpanded:t,onToggle:n}){let r=e.kind===`workflow`&&e.nestedIds.length>0,i=e.kind===`workflow`?e.workflow.name:e.stepId;return(0,K.jsx)(`div`,{className:`flex items-center pl-5`,children:r?(0,K.jsx)(`button`,{type:`button`,"aria-expanded":t,"aria-label":`${t?`Collapse`:`Expand`} nested workflows of ${i}`,className:c(gS,`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 wRi=e=>e.stopPropagation();function TRi({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 ERi({row:e,isExpanded:t,onToggle:n,runCount:r,rowProps:i}){let{paths:a,Link:o}=sn(),s=(0,G.useRef)(null),{workflow:c,nestedIds:l}=e,u=rJ(c.name,50),d=rJ(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)(CRi,{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:wRi,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)(SRi,{guides:e.guides,isLastChild:e.isLastChild}):null,(0,K.jsx)(`span`,{className:`truncate`,children:u}),c.origin===`dynamic`?(0,K.jsx)(JS,{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)(GS,{"aria-hidden":!0,className:`size-icon-sm`}),l.length]}):null]})}),(0,K.jsx)(Z.DescriptionCell,{children:d}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:p>0?(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-info-indicator`,"aria-label":`${p} run${p===1?``:`s`} in progress`,children:[(0,K.jsx)(`span`,{"aria-hidden":!0,className:`size-2 rounded-full bg-info-indicator motion-safe:animate-pulse`}),p]}):``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:m>0?(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-warning-foreground`,"aria-label":`${m} run${m===1?``:`s`} awaiting input`,children:[(0,K.jsx)(bT,{"aria-hidden":!0,className:`size-icon-sm`}),m]}):``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:f||``})]})]})}function DRi({workflows:e,isLoading:t,search:n=``,sort:r,onSortChange:i,requestContext:a}){let[o,s]=(0,G.useState)(new Set),l=YEt({requestContext:a}),u=(0,G.useMemo)(()=>Object.entries(e).map(([e,t])=>({...t,id:e})),[e]),d=(0,G.useMemo)(()=>{let e=n.toLowerCase();return u.filter(t=>t.name?.toLowerCase().includes(e)||t.description?.toLowerCase().includes(e))},[u,n]),f=(0,G.useMemo)(()=>_Ri(d,r,l),[d,r,l]),m=(0,G.useMemo)(()=>bRi(f,e,o),[f,e,o]),h=(0,G.useMemo)(()=>{let e=new Map;for(let t of m)t.kind===`workflow`&&e.set(t.pathKey,e.size);return e},[m]),{containerRef:g,getRowProps:_}=OZ({count:h.size,global:!0}),v=e=>{s(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})};return t?(0,K.jsx)(yH,{columns:xRi,fit:`container`}):(0,K.jsxs)(Z,{columns:xRi,fit:`container`,scrollRef:g,children:[(0,K.jsxs)(Z.Top,{children:[(0,K.jsx)(Z.TopCell,{children:(0,K.jsx)(`span`,{className:`sr-only`,children:`Expand`})}),(0,K.jsx)(TRi,{sortKey:`name`,sort:r,onSortChange:i,children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`Description`}),(0,K.jsx)(TRi,{sortKey:`running`,sort:r,onSortChange:i,children:`Running`}),(0,K.jsx)(TRi,{sortKey:`suspended`,sort:r,onSortChange:i,children:`Pending input`}),(0,K.jsx)(TRi,{sortKey:`steps`,sort:r,onSortChange:i,children:`Number of steps`})]}),m.length===0&&n?(0,K.jsx)(Z.NoMatch,{message:`No Workflows match your search`}):null,m.map(e=>{let t=o.has(e.pathKey),n=()=>v(e.pathKey);return e.kind===`unregistered`?(0,K.jsxs)(Z.RowStatic,{className:`gap-0 px-0`,children:[(0,K.jsx)(CRi,{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)(SRi,{guides:e.guides,isLastChild:e.isLastChild}),(0,K.jsx)(`span`,{className:`truncate`,children:rJ(e.stepId,50)}),(0,K.jsxs)(_x,{children:[(0,K.jsx)(vx,{render:(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`muted`}),role:`note`,tabIndex:0,className:c(`shrink-0 rounded-sm`,p),children:`not registered`}),(0,K.jsx)(yx,{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:rJ(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)(ERi,{row:e,isExpanded:t,onToggle:n,runCount:l[e.workflow.id],rowProps:_(h.get(e.pathKey)??-1)},`workflow-${e.pathKey}`)})]})}var K9=[KN(`/workflows`)];function ORi(){let{data:e,isLoading:t,error:n}=KM(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)();return n&&DN(n)?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:K9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(_H,{variant:`fill`})]}):n&&ON(n)?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:K9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(gH,{variant:`fill`,resource:`workflows`})]}):n?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:K9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(Hx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load workflows`,descriptionSlot:n.message})]}):Object.keys(e||{}).length===0&&!t?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:K9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(gRi,{})]}):(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:K9}),actionRow:(0,K.jsxs)(_K,{children:[(0,K.jsx)(_K.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(wH,{...TH,onValueChange:i,label:`Search workflows`,placeholder:`Search by name or description`})})}),(0,K.jsx)(_K.End,{children:(0,K.jsx)(X,{render:(0,K.jsx)(jv,{to:`/workflows/schedules`}),variant:`primary`,icon:(0,K.jsx)(VS,{}),children:`Schedules`})})]}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(DRi,{workflows:e||{},isLoading:t,search:r,sort:a,onSortChange:(e,t)=>o({key:t,direction:e})})]})}var kRi={active:`bg-success-indicator`,paused:`bg-info-indicator`,completed:`bg-muted-foreground`},ARi={active:`text-success-indicator`,paused:`text-info-indicator`,completed:`text-muted-foreground`},jRi=({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 ${kRi[e]}`,"aria-hidden":!0}),(0,K.jsx)(T,{as:`span`,variant:`caption`,className:ARi[e],children:e})]});function MRi({status:e}){let{icon:t,color:n}=NRi(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 NRi(e){switch(e){case`success`:return{icon:(0,K.jsx)(sC,{className:`size-icon-sm`}),color:`text-success-indicator`};case`failed`:return{icon:(0,K.jsx)(hw,{className:`size-icon-sm`}),color:`text-destructive-foreground`};case`running`:return{icon:(0,K.jsx)(It,{}),color:`text-muted-foreground`};case`suspended`:return{icon:(0,K.jsx)(bT,{className:`size-icon-sm`}),color:`text-info-indicator`};case`canceled`:return{icon:(0,K.jsx)(Bx,{className:`size-icon-sm`}),color:`text-muted-foreground`};case`pending`:case`waiting`:return{icon:(0,K.jsx)(YS,{className:`size-icon-sm`}),color:`text-muted-foreground`};default:return{icon:null,color:`text-muted-foreground`}}}var PRi=`auto auto auto auto 1fr`,FRi=3e4,IRi=3e5;function LRi({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:i,setEndOfListElement:a}){let{Link:o,paths:s}=sn(),c=e=>!!(n&&e.runId&&e.outcome!==`failed`),l=e.filter(c).length,{containerRef:u,getRowProps:d}=OZ({count:l}),f=-1;return t?(0,K.jsx)(yH,{columns:PRi}):e.length===0?(0,K.jsx)(T,{variant:`body`,tone:`muted`,className:`p-4`,children:`No trigger history yet.`}):(0,K.jsxs)(Z,{columns:PRi,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=QS(t,{signed:!0}),i=e.outcome===`failed`,a=i?e.error:e.run?.error,l=Math.abs(t),u=!i&&l>FRi&&l<=IRi,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)(Gx,{className:`size-icon-sm`}),`publish failed`]}):e.run?(0,K.jsx)(MRi,{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)(_x,{children:[(0,K.jsx)(vx,{asChild:!0,children:(0,K.jsx)(`span`,{className:`inline-flex text-destructive-foreground`,children:(0,K.jsx)(Gx,{className:`size-icon-sm`})})}),(0,K.jsx)(yx,{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)(xk,{value:e.actualFireAt}):`—`,u?(0,K.jsxs)(_x,{children:[(0,K.jsx)(vx,{asChild:!0,children:(0,K.jsx)(`span`,{className:`inline-flex text-info-indicator`,children:(0,K.jsx)(Gx,{className:`size-icon-sm`})})}),(0,K.jsxs)(yx,{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:QS(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 RRi={id:`workflow-schedules`,label:`Schedules`,icon:VS,to:`/workflows/schedules`};function zRi({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 BRi(){let{scheduleId:e}=Ev(),t=[KN(`/workflows`),RRi,{id:`schedule`,label:SMt(e),icon:VS}],{paths:n}=sn(),{data:r,error:i}=UMt({scheduleId:e,queryOptions:{enabled:!!e}}),{data:a,isLoading:o,error:s,hasNextPage:c,isFetchingNextPage:l,setEndOfListElement:u}=KMt({scheduleId:e,queryOptions:{enabled:!!e}}),d=qMt({scheduleId:e});if(i&&DN(i))return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(_H,{variant:`fill`})]});if(i&&ON(i))return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(gH,{variant:`fill`,resource:`schedules`})]});if(i)return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(Hx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load schedule`,descriptionSlot:i.message})]});let f=r?.workflowId,p=r?.agentId;return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:t}),actionRow:(0,K.jsx)(_K,{children:(0,K.jsxs)(_K.End,{children:[(0,K.jsx)(X,{render:(0,K.jsx)(jv,{to:n.schedulesLink()}),variant:`ghost`,icon:(0,K.jsx)(tS,{}),children:`Back to schedules`}),f?(0,K.jsx)(X,{icon:(0,K.jsx)(GS,{}),render:(0,K.jsx)(jv,{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:()=>Qx.success(e===`pause`?`Schedule paused`:`Schedule resumed`),onError:e=>Qx.error(e.message)})},disabled:d.isPending,"data-testid":`schedule-toggle-button`,children:r.status===`active`?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(bT,{}),`Pause`]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(xT,{}),`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)(zRi,{label:p?`Agent`:`Workflow`,children:f?(0,K.jsx)(jv,{to:n.workflowLink(f),className:`text-foreground hover:underline`,children:f}):p?(0,K.jsx)(jv,{to:n.agentLink(p),className:`text-foreground hover:underline`,children:p}):`—`}),(0,K.jsxs)(zRi,{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)(zRi,{label:`Status`,children:(0,K.jsx)(jRi,{status:r.status})}),(0,K.jsx)(zRi,{label:`Next fire`,children:r.nextFireAt?(0,K.jsx)(xk,{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)(Hx,{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 VRi={target:e=>e.workflowId??e.agentId??``,status:e=>e.status,nextFireAt:e=>e.nextFireAt,lastFireAt:e=>e.lastFireAt},HRi=`minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto`;function URi({schedules:e,isLoading:t,search:n=``,sort:r,onSortChange:i}){let{paths:a,Link:o}=sn(),s=(0,G.useMemo)(()=>{let t=n.toLowerCase();return AZ(t?e.filter(e=>e.id.toLowerCase().includes(t)||(e.workflowId??e.agentId??``).toLowerCase().includes(t)):e,r,VRi)},[e,n,r]),{containerRef:c,getRowProps:l}=OZ({count:s.length,global:!0});if(t)return(0,K.jsx)(yH,{columns:HRi});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:HRi,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)(jRi,{status:e.status})}),(0,K.jsx)(Z.Cell,{children:e.nextFireAt?(0,K.jsx)(xk,{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)(MRi,{status:e.lastRun.status}),e.lastFireAt?(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:(0,K.jsx)(xk,{value:e.lastFireAt})}):null]}):e.lastFireAt?(0,K.jsx)(xk,{value:e.lastFireAt}):(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`Never`})})]},e.id))]})}function WRi({workflowId:e}={}){let{data:t,isLoading:n,error:r}=WMt(e?{workflowId:e}:{}),[i,a]=(0,G.useState)(``),[o,s]=(0,G.useState)();return r?(0,K.jsx)(Hx,{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)(wH,{...TH,onValueChange:a,label:`Search schedules`,placeholder:`Search by id or workflow`})}),(0,K.jsx)(`div`,{className:`overflow-y-auto`,children:(0,K.jsx)(URi,{schedules:t??[],isLoading:n,search:i,sort:o,onSortChange:(e,t)=>s({key:t,direction:e})})})]})}var GRi=[KN(`/workflows`),RRi];function KRi(){let[e]=Mv(),t=e.get(`workflowId`)??void 0,{error:n}=WMt(t?{workflowId:t}:{});return n&&DN(n)?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:GRi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(_H,{variant:`fill`})]}):n&&ON(n)?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:GRi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(gH,{variant:`fill`,resource:`schedules`})]}):(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:GRi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(`div`,{className:`h-full`,children:(0,K.jsx)(WRi,{workflowId:t})})]})}var qRi=U(`IconArrowDownLeft`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M6 9V18H15`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M17.75 6.25L7 17`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),3),JRi={"--belt-hue":`var(--warning-indicator)`};function YRi(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 ZRi({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:(0,K.jsxs)(`section`,{className:c(lDt,`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)(xx,{children:(0,K.jsx)(bT,{})}),`Step suspended`]}),(0,K.jsx)(JS,{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?NO(XO(n.resumeSchema)):kd(q(),pd());return(0,K.jsx)(QRi,{step:e,stepSchema:i,description:n.description,onResume:r},`${e.runId}-${e.stepId}`)})]}),(0,K.jsx)(YXe,{status:`ready`,label:`Needs input`,className:`before:hidden`,style:JRi})]})}function QRi({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)(xx,{children:(0,K.jsx)(qRi,{})}),`The step is asking`]}),(0,K.jsxs)(xC,{open:i,onOpenChange:a,children:[(0,K.jsxs)(SC,{className:c(`bg-card hover:bg-card active:bg-card shadow-raised [--field:var(--field-on-surface)] [--field-disabled:var(--field-on-surface)] [--field-rim:var(--field-rim-on-surface)]`,`flex w-full items-center justify-between gap-2 rounded-lg px-3 py-2.5`),children:[(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(xx,{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:YRi(e.suspendPayload)})]}),(0,K.jsx)(CC,{children:(0,K.jsx)(`div`,{"data-testid":`suspended-payload`,className:`pt-2`,children:(0,K.jsx)(mw,{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)(xx,{children:(0,K.jsx)(R4,{})}),`Your response`]}),(0,K.jsx)(`div`,{className:`-mx-5`,children:(0,K.jsx)(TEt,{schema:t,isSubmitLoading:o,submitButtonLabel:`Resume`,submitButtonVariant:`primary`,submitButtonIcon:(0,K.jsx)(xT,{}),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){Qx.error(e instanceof Error?e.message:`Error resuming workflow`)}finally{s(!1)}}})})]})]})}function $Ri({hidden:e,requestContext:t,canResume:n}){let{result:r,workflow:i,runId:a,isStreamingWorkflow:o}=(0,G.useContext)(RS),s=mpt(r,a),c=ypt(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)(ZRi,{suspendedSteps:s,workflow:i,isStreaming:o,onResume:c})},a)}var ezi=U(`IconSkip`,()=>(0,K.jsx)(`path`,{d:`M19 5V19M6.52732 5.16646L15.5625 11.1835C16.1458 11.5719 16.1458 12.4281 15.5625 12.8165L6.52732 18.8335C5.87447 19.2683 5 18.8008 5 18.017V5.98298C5 5.1992 5.87447 4.7317 6.52732 5.16646Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})),tzi={success:{label:`Completed`,icon:sC},failed:{label:`Failed`,icon:Vx},suspended:{label:`Needs input`,icon:bT},waiting:{label:`Waiting`,icon:WS},paused:{label:`Paused`,icon:bT},skipped:{label:`Skipped`,icon:ezi},running:{label:`Running`,icon:yT},canceled:{label:`Canceled`,icon:Bx}},nzi={label:`Status unavailable`,icon:kq};function rzi({row:e,isSelected:t,isHovered:n,onSelectStep:r,onHoverStep:i,onOpenInput:a,onOpenOutput:o}){let s=Object.hasOwn(tzi,e.status)?tzi[e.status]:nzi,l=s.icon,u=iht(e.status),d=e.stepId.slice(0,e.stepId.lastIndexOf(`.`)),f=e.isNestedEntry?e.stepId.slice(e.stepId.lastIndexOf(`.`)+1):e.stepId;return(0,K.jsxs)(`div`,{"data-testid":`workflow-timeline-row`,"data-workflow-step-key":e.stepId,onMouseEnter:()=>!e.isNestedEntry&&i(e.stepId),onMouseLeave:()=>!e.isNestedEntry&&i(null),className:c(`grid grid-cols-[minmax(130px,1fr)_minmax(64px,1fr)_56px_64px] items-center gap-3 rounded-md px-2 py-1`,`@max-[540px]/workflow-timeline:grid-cols-[minmax(0,1fr)_48px_64px] @max-[540px]/workflow-timeline:gap-x-1.5 @max-[540px]/workflow-timeline:gap-y-1 @max-[540px]/workflow-timeline:py-2`,(t||n)&&`bg-fill-subtle`),children:[(0,K.jsxs)(`button`,{type:`button`,"aria-disabled":e.isNestedEntry,"aria-pressed":t,onClick:()=>{e.isNestedEntry||r(e.stepId)},title:e.stepId,className:c(`text-foreground`,`flex min-h-9 min-w-0 cursor-pointer items-center gap-2.5 text-left focus-visible:rounded-sm aria-disabled:cursor-default`,p),children:[(0,K.jsx)(`span`,{"aria-label":s.label,className:c(`grid size-6 flex-none place-items-center rounded-md border border-border bg-background`,aht[u]),children:(0,K.jsx)(l,{"aria-hidden":!0,className:c(`size-3.5`,e.status===`running`&&`motion-safe:animate-spin`)})}),(0,K.jsxs)(`span`,{className:`min-w-0`,children:[(0,K.jsx)(T,{as:`span`,variant:`meta`,className:`block truncate`,children:f}),e.isNestedEntry&&(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`flex min-w-0 items-center gap-1`,children:[(0,K.jsx)(hXe,{"aria-hidden":!0,className:`size-icon-xs shrink-0`}),(0,K.jsx)(`span`,{className:`truncate`,children:d})]})]})]}),(0,K.jsx)(`div`,{className:`relative h-5 min-w-0 overflow-hidden rounded-sm bg-muted @max-[540px]/workflow-timeline:col-span-full @max-[540px]/workflow-timeline:row-start-2 @max-[540px]/workflow-timeline:ml-[34px]`,"aria-hidden":!0,children:e.timing&&(0,K.jsx)(`div`,{"data-testid":`workflow-timeline-bar`,"data-offset":e.timing.offsetPct,"data-width":e.timing.widthPct,className:c(`absolute top-0 h-full min-w-0.5 rounded-sm`,oht[u]),style:{left:`${e.timing.offsetPct}%`,width:`${e.timing.widthPct}%`}})}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`text-right whitespace-nowrap`,title:e.timing&&e.spansSuspension?`Includes time spent suspended waiting for input`:void 0,children:e.timing?(0,K.jsx)(T,{as:`span`,variant:`meta`,font:`mono`,children:QS(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)(mk,{})}),(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)(pk,{})})]})]})}var izi=e=>e.includes(`.`),azi=e=>e===`input`||e.endsWith(`.input`),ozi=1;function szi(e,t){let n=lht(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 czi(e,t){let n=Object.entries(e).filter(([e])=>!azi(e)).map(([e,n])=>({stepId:e,step:n,...szi(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,ozi),100-t)}}return{stepId:e,step:t,status:vk(t)?`suspended`:t.status,timing:s,spansSuspension:a,isRunning:r,isNestedEntry:izi(e)}})}var lzi=U(`IconChevronGrabberVertical`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M8 8.99985L11.2929 5.70696C11.6834 5.31643 12.3166 5.31643 12.7071 5.70696L16 8.99985`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M8 15L11.2929 18.2929C11.6834 18.6834 12.3166 18.6834 12.7071 18.2929L16 15`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]})),uzi=U(`IconChevronGrabberVerticalToward`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M8 18.75L12 14.75L16 18.75`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M8 5.25L12 9.25L16 5.25`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}));function dzi(){let{steps:e}=UQ(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:i}=LS(),[a,o]=(0,G.useState)(()=>Date.now()),[s,l]=(0,G.useState)(!0),[u,d]=(0,G.useState)(!1),{showData:f}=JM(),p=(0,G.useRef)(null),m=czi(e,a),h=m.some(e=>e.isRunning);return CJe(p,{enabled:h&&!s}),(0,G.useEffect)(()=>{if(!h||s)return;let e=setInterval(()=>o(Date.now()),100);return()=>clearInterval(e)},[h,s]),m.length===0?null:(0,K.jsx)(`div`,{"data-testid":`workflow-timeline`,className:`relative z-20 shrink-0 px-2 pb-2`,children:(0,K.jsxs)(xC,{open:!s,onOpenChange:e=>l(!e),className:c(Pv,`@container/workflow-timeline pointer-events-auto overflow-hidden rounded-xl`),children:[(0,K.jsxs)(`div`,{className:`flex items-center`,children:[(0,K.jsxs)(SC,{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)(VV,{"aria-hidden":!0,className:`size-icon-md text-muted-foreground`})}),(0,K.jsx)(`span`,{children:`Timeline`}),(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,children:[m.length,` events`]}),(0,K.jsx)(`span`,{className:`ml-auto`,children:(0,K.jsx)(y,{direction:`right`,className:`size-4`})})]}),!s&&(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:u?`Restore timeline height`:`Enlarge timeline`,"aria-pressed":u,onClick:()=>d(!u),className:`mr-2 shrink-0`,children:u?(0,K.jsx)(uzi,{}):(0,K.jsx)(lzi,{})})]}),(0,K.jsx)(CC,{children:(0,K.jsx)(`div`,{ref:p,"data-testid":`workflow-timeline-list`,className:c(`overflow-auto overscroll-contain px-1.5 pb-1.5`,u?`max-h-[min(720px,calc(100dvh-112px))]`:`max-h-[min(320px,40dvh)]`),children:m.map(e=>(0,K.jsx)(rzi,{row:e,isSelected:t===e.stepId,isHovered:n===e.stepId,onSelectStep:r,onHoverStep:i,onOpenInput:(e,t)=>f({type:`step-input`,stepId:e.stepId},t),onOpenOutput:(e,t)=>f({type:`step-output`,stepId:e.stepId},t)},e.stepId))})})]})})}var fzi=({workflowId:e,workflow:t,isLoading:n})=>{let[r]=IS(`workflow`,e),{canExecute:i,isLoading:a}=oS(),{stepDetail:o}=JM(),s=Gw(),c=o?.type===`data`,l=(0,K.jsxs)(`div`,{className:`[container-type:size] relative h-full min-h-0`,children:[(0,K.jsx)(zlr,{workflowId:e,workflow:t,isLoading:n,requestContext:r}),(0,K.jsx)($Ri,{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)(GQ,{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)(dzi,{})})]});return s&&o&&!c?(0,K.jsx)(`div`,{className:`h-full min-h-0 overflow-hidden`,children:(0,K.jsx)(GQ,{requestContext:r})}):(0,K.jsxs)(`div`,{className:`relative h-full min-h-0`,children:[l,(0,K.jsxs)(p6,{className:`pointer-events-none absolute inset-0 z-30 min-h-0 w-full min-w-0 p-2`,children:[(0,K.jsx)(f6,{id:`workflow-graph`,className:`pointer-events-none min-w-0`}),o&&!c&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(m6,{className:`pointer-events-auto`}),(0,K.jsx)(f6,{id:`workflow-step-detail`,minSize:300,maxSize:`60%`,defaultSize:420,className:`min-w-0`,children:(0,K.jsx)(`div`,{className:`pointer-events-auto h-full min-h-0 overflow-hidden rounded-studio-panel border border-border bg-background`,children:(0,K.jsx)(GQ,{requestContext:r})})})]})]})]})},pzi=()=>{let{workflowId:e}=Ev(),{data:t,isLoading:n,error:r}=qM({workflowId:e,requestContext:IS(`workflow`,e)[0],queryOptions:{enabled:!!e}});return r&&DN(r)?(0,K.jsx)(_H,{variant:`fill`}):r&&ON(r)?(0,K.jsx)(gH,{variant:`fill`,resource:`workflows`}):(0,K.jsx)(fzi,{workflowId:e,workflow:t??void 0,isLoading:n})};function mzi(){let{workflowId:e}=Ev(),{error:t}=WMt(e?{workflowId:e}:{});if(!e)return null;let n;return n=t&&DN(t)?(0,K.jsx)(_H,{variant:`fill`}):t&&ON(t)?(0,K.jsx)(gH,{variant:`fill`,resource:`schedules`}):(0,K.jsx)(`div`,{className:`h-full`,children:(0,K.jsx)(WRi,{workflowId:e})}),(0,K.jsxs)(MS,{children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),n]})}function hzi(){let{workflowId:e}=Ev();return e?(0,K.jsx)(yui,{scopedEntityId:e,scopedEntityType:wp.WORKFLOW_RUN}):null}var gzi=(0,G.createContext)(null);function q9(){let e=(0,G.useContext)(gzi);if(!e)throw Error(`Workspace components must be rendered inside <Workspace.Root>`);return e}var _zi=e=>e?.status;function vzi(e,t){return DN(e)?`Your session has expired. Sign in again to continue.`:ON(e)?`You don't have permission to access this.`:kN(e)?`This path no longer exists.`:_zi(e)===501?`This workspace does not support this operation.`:t}function yzi({error:e,fallback:t,className:n}){return(0,K.jsx)(gk,{variant:`destructive`,className:n,children:(0,K.jsx)(gk.Message,{children:vzi(e,t)})})}var bzi=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;function xzi(e){let t=bzi.exec(e);return t?{frontmatter:t[1]??``,body:e.slice(t[0].length)}:{frontmatter:null,body:e}}function Szi({content:e}){let{frontmatter:t,body:n}=xzi(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)(aJ,{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)(pY,{children:n})})]})}function Czi(){let{activeFilePath:e}=q9();return e?(0,K.jsx)(T,{as:`span`,variant:`body-sm`,font:`mono`,tone:`muted`,className:`truncate`,"data-testid":`workspace-file-path`,children:e}):null}function wzi({path:e,content:t,mimeType:n}){return vIn(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`})}):yIn(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:${xIn(e,n)};base64,${t}`,type:xIn(e,n)})})}):SIn(e)?(0,K.jsx)(Szi,{content:t}):(0,K.jsx)(aJ,{code:t,lang:AXe(e),overflow:`scroll`,className:`rounded-none border-0 bg-transparent [&_pre]:p-4`})}function Tzi({renderPreview:e}){let{workspaceId:t,activeFilePath:n}=q9(),{data:r,isLoading:i,error:a}=LIn({workspaceId:t,path:n,queryOptions:{enabled:!!n}});if(!n)return null;if(i)return(0,K.jsxs)(`div`,{"aria-busy":`true`,className:`flex flex-col gap-2 p-4`,children:[(0,K.jsx)(NS,{className:`h-4 w-1/2`}),(0,K.jsx)(NS,{className:`h-4 w-5/6`}),(0,K.jsx)(NS,{className:`h-4 w-2/3`})]});if(!r)return(0,K.jsx)(yzi,{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)(wzi,{...o})}var Ezi=(e,t)=>e===`.`?t:`${e}/${t}`,Dzi=e=>e.split(`/`).slice(0,-1).map((e,t,n)=>n.slice(0,t+1).join(`/`)),Ozi=e=>{let t=e.lastIndexOf(`/`);return t===-1?`.`:e.slice(0,t)};function kzi({labeled:e=!1}={}){let{workspaceId:t,onCreateDirectory:n,isReadOnly:r}=q9(),i=s_(),[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`,Ozi(d)]}),o(!1),c(``)}catch{}finally{u(!1)}}};return(0,K.jsxs)(K.Fragment,{children:[e?(0,K.jsx)(X,{variant:`ghost`,icon:(0,K.jsx)(P6,{}),onClick:()=>o(!0),children:`New folder`}):(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`New folder`,onClick:()=>o(!0),children:(0,K.jsx)(P6,{})}),(0,K.jsx)(Xw,{open:a,onOpenChange:o,pending:l,children:(0,K.jsx)(Zw,{size:`sm`,children:(0,K.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),f()},children:[(0,K.jsx)(Qw,{children:(0,K.jsx)(tT,{children:`New folder`})}),(0,K.jsx)(eT,{children:(0,K.jsx)(Hj,{autoFocus:!0,"aria-label":`Folder path`,placeholder:`docs/guides`,value:s,onChange:e=>c(e.target.value)})}),(0,K.jsxs)($w,{children:[(0,K.jsx)(rT,{children:`Cancel`}),(0,K.jsx)(X,{type:`submit`,variant:`primary`,disabled:!d||l,children:`Create`})]})]})})})]})}function Azi(e){return`${e.topSource}/${e.name}`}function jzi(e){let t=EIn(e.topSource,e.name);return t?`${t.owner}/${t.repo}/${e.name}`:null}function Mzi({open:e,onOpenChange:t,workspaceId:n,onInstall:r,isInstalling:i,installedSkillIds:a=[],installedSkillNames:o=[],writableMounts:s,installedSkillPaths:l}){let[u,d]=(0,G.useState)(``),[f,p]=(0,G.useState)(null),[m,h]=(0,G.useState)(),g=s?.some(e=>e.path===m)?m:s?.[0]?.path,{data:_,isLoading:v}=wIn({workspaceId:n,queryOptions:{enabled:!!n}}),y=CIn({workspaceId:n}),b=(0,G.useMemo)(()=>f?.topSource?EIn(f.topSource,f.name):null,[f]),x=(0,G.useMemo)(()=>!b||!f?null:`https://skills.sh/${b.owner}/${b.repo}/${f.name}`,[b,f]),{data:S,isLoading:C}=TIn({workspaceId:n,owner:b?.owner,repo:b?.repo,skillPath:f?.name,queryOptions:{enabled:!!n&&!!b&&!!f}}),w=nC(e=>{e.trim().length>=2&&y.mutate(e)},300),E=(0,G.useCallback)(e=>{d(e),w(e)},[w]),D=(0,G.useMemo)(()=>u.trim().length>=2?y.data?.skills??[]:_?.skills??[],[u,y.data,_]),O=y.isPending,k=u.trim().length>=2,A=(0,G.useMemo)(()=>{if(!f)return!1;let e=jzi(f);return!!(e&&a.includes(e)||o.includes(f.name))},[f,a,o]),j=(0,G.useCallback)(()=>{f&&b&&r({repository:`${b.owner}/${b.repo}`,skillName:f.name,mount:s&&s.length>1?g:void 0})},[f,b,r,s,g]),M=(0,G.useCallback)(e=>{e||(d(``),p(null),h(void 0)),t(e)},[t]);return(0,K.jsx)(Xw,{open:e,onOpenChange:M,pending:i,children:(0,K.jsxs)(Zw,{size:`xl`,className:`h-[80vh]`,children:[(0,K.jsxs)(Qw,{children:[(0,K.jsx)(tT,{children:`Add Skill`}),(0,K.jsx)(nT,{children:`Search and install skills from the community registry`})]}),(0,K.jsxs)(eT,{layout:`fill`,children:[(0,K.jsx)(wH,{label:`Search skills`,placeholder:`Search skills`,value:u,onValueChange:E}),(0,K.jsxs)(`div`,{className:`flex min-h-0 flex-1 gap-4`,children:[(0,K.jsxs)(`div`,{className:`flex min-h-0 w-1/2 flex-col`,children:[(0,K.jsx)(T,{as:`p`,variant:`eyebrow`,tone:`muted`,className:`mb-2`,children:k?`Search Results`:`Popular Skills`}),(0,K.jsx)(jS,{className:`flex-1 rounded-lg border border-border`,children:(0,K.jsx)(AS,{className:!v&&!O&&D.length===0?`flex flex-col [&>div]:flex [&>div]:flex-1 [&>div]:flex-col`:void 0,children:v||O?(0,K.jsx)(`div`,{className:`flex items-center justify-center py-5`,children:(0,K.jsx)(It,{className:`text-muted-foreground`})}):D.length===0?(0,K.jsx)(Hx,{className:`flex-1`,titleSlot:k?`No skills found`:`No skills available`}):(0,K.jsx)(`div`,{className:`space-y-1 p-2`,children:D.map(e=>{let t=Azi(e),n=jzi(e),r=n&&a.includes(n)||o.includes(e.name),i=f?Azi(f):null;return(0,K.jsx)(`button`,{onClick:()=>p(e),className:c(`w-full rounded-md px-3 py-2 text-left`,`hover:bg-fill-subtle`,i===t&&`border border-border-strong bg-fill-hover`),children:(0,K.jsxs)(`div`,{className:`flex items-start justify-between gap-2`,children:[(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(T,{as:`span`,variant:`subheading`,tone:`ink`,className:`truncate`,children:e.name}),r&&(0,K.jsxs)(T,{as:`span`,variant:`meta`,className:`inline-flex items-center gap-1 rounded bg-info-subtle px-1.5 py-0.5 text-info-subtle-foreground`,children:[(0,K.jsx)(sC,{className:`size-icon-xs`}),`Installed`]})]}),(0,K.jsx)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`truncate`,children:e.topSource})]}),(0,K.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 text-muted-foreground`,children:[(0,K.jsx)(iJ,{className:`size-icon-xs`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,children:e.installs.toLocaleString()})]})]})},t)})})})})]}),(0,K.jsxs)(`div`,{className:`flex min-h-0 w-1/2 flex-col`,children:[(0,K.jsx)(T,{as:`p`,variant:`eyebrow`,tone:`muted`,className:`mb-2`,children:`Preview`}),(0,K.jsx)(`div`,{className:`flex flex-1 flex-col overflow-hidden rounded-lg border border-border`,children:f?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`border-b border-border bg-card p-4`,children:(0,K.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,K.jsx)(`div`,{className:`rounded-lg bg-muted p-2`,children:(0,K.jsx)(wZ,{className:`size-icon-lg text-muted-foreground`})}),(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsx)(T,{as:`h3`,variant:`subheading`,tone:`ink`,className:`truncate`,children:f.name}),(0,K.jsxs)(`div`,{className:`mt-1 flex items-center gap-3 text-muted-foreground`,children:[(0,K.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(CZ,{className:`size-icon-xs`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`block`,children:f.topSource})]}),(0,K.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(iJ,{className:`size-icon-xs`}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[f.installs.toLocaleString(),` installs`]})]})]})]}),b&&(0,K.jsx)(`a`,{href:`https://github.com/${b.owner}/${b.repo}`,target:`_blank`,rel:`noopener noreferrer`,className:c(`text-muted-foreground hover:text-foreground`,`transition-[color] duration-fast ease-out-custom motion-reduce:transition-none`),title:`View on GitHub`,children:(0,K.jsx)(qN,{className:`size-icon-md`})})]})}),C?(0,K.jsx)(`div`,{className:`flex flex-1 items-center justify-center`,children:(0,K.jsx)(It,{className:`text-muted-foreground`})}):S?(0,K.jsx)(jS,{className:`flex-1`,children:(0,K.jsx)(`div`,{className:`p-4`,children:(0,K.jsx)(pY,{children:S})})}):(0,K.jsx)(Hx,{className:`flex-1`,iconSlot:(0,K.jsx)(SZ,{}),titleSlot:`Preview unavailable`,actionSlot:x&&(0,K.jsxs)(`a`,{href:x,target:`_blank`,rel:`noopener noreferrer`,className:`flex items-center gap-1 text-info-indicator hover:underline`,children:[(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[`View on skills.sh`,` `]}),(0,K.jsx)(qN,{className:`size-icon-xs`})]})})]}):(0,K.jsx)(Hx,{variant:`fill`,iconSlot:(0,K.jsx)(SZ,{}),titleSlot:`Select a skill to preview`})})]})]}),f&&s&&s.length>1&&(0,K.jsxs)($O,{orientation:`horizontal`,className:c(`bg-card hover:bg-card active:bg-card shadow-raised [--field:var(--field-on-surface)] [--field-disabled:var(--field-on-surface)] [--field-rim:var(--field-rim-on-surface)]`,`gap-3 rounded-lg p-3`),children:[(0,K.jsx)(GN,{className:`size-icon-md shrink-0 text-muted-foreground`}),(0,K.jsx)(tk,{className:`whitespace-nowrap`,children:`Install to`}),(0,K.jsxs)(Pk,{value:g,onValueChange:h,children:[(0,K.jsx)(Ik,{className:`flex-1`,children:(0,K.jsx)(Fk,{})}),(0,K.jsx)(Lk,{children:s.map(e=>{let t=e.displayName??e.name??e.provider??`unknown`;return(0,K.jsxs)(Rk,{value:e.path,children:[t,` (`,e.path,`)`]},e.path)})})]})]})]}),f&&(0,K.jsxs)($w,{children:[A&&s&&s.length>1&&(()=>{let e=l?.[f.name];if(!e)return null;let t=s.find(t=>e.startsWith(t.path+`/`)||e===t.path);return t?(0,K.jsxs)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`mr-auto`,children:[`Installed at `,t.path]}):null})(),(0,K.jsx)(rT,{children:`Cancel`}),(0,K.jsx)(Yw,{onConfirm:j,disabled:!b||A,"data-testid":`install-skill-button`,children:i?`Installing...`:A?`Already installed`:`Install`})]})]})})}function Nzi({labeled:e=!1}){let{workspaceId:t,addSkill:n}=q9(),[r,i]=(0,G.useState)(!1),[a,o]=(0,G.useState)(!1);if(!n)return null;let{onInstall:s,...c}=n,l=async e=>{o(!0);try{await s(e),i(!1)}catch{}finally{o(!1)}};return(0,K.jsxs)(K.Fragment,{children:[e?(0,K.jsxs)(X,{variant:`ghost`,onClick:()=>i(!0),children:[(0,K.jsx)(x7n,{}),`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)(x7n,{})}),(0,K.jsx)(Mzi,{...c,open:r,onOpenChange:i,workspaceId:t,onInstall:e=>void l(e),isInstalling:a})]})}function Pzi({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(Dzi(t??``))),[v,y]=(0,G.useState)(t);if(t!==v){y(t);let e=Dzi(t??``).filter(e=>!g.has(e));e.length>0&&_(new Set([...g,...e]))}let b=a?.join(`
|
|
822
822
|
`)??``,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(`
|
|
823
823
|
`):[]).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)(gzi.Provider,{value:x,children:d})}var Fzi=e=>(0,K.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`-1 -1 18 18`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,...e,children:(0,K.jsx)(`path`,{d:`M9 1.5H4C3.44772 1.5 3 1.94772 3 2.5V13.5C3 14.0523 3.44772 14.5 4 14.5H12C12.5523 14.5 13 14.0523 13 13.5V5.5M9 1.5L13 5.5M9 1.5V5.5H13`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`})}),Izi=e=>(0,K.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`-1 -1 18 18`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,...e,children:(0,K.jsx)(`path`,{d:`M7.25 12.5C10.1495 12.5 12.5 10.1495 12.5 7.25C12.5 4.35051 10.1495 2 7.25 2C4.35051 2 2 4.35051 2 7.25C2 10.1495 4.35051 12.5 7.25 12.5ZM11 11L14 14`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`})});function Lzi(){let{isSearching:e,setSearching:t,searchFiles:n,searchSkills:r}=q9();return!n&&!r?null:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`Search files and skills`,"aria-pressed":e,onClick:()=>t(!e),children:(0,K.jsx)(Izi,{})})}function Rzi(){let{isSearching:e}=q9();return e?(0,K.jsx)(Vzi,{}):(0,K.jsx)(Bzi,{})}var zzi=(e,t)=>`${e} ${t}${e===1?``:`s`}`;function Bzi(){let{fileCount:e,skillCount:t}=q9();return(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`muted`,className:`block min-w-0`,children:(0,K.jsxs)(wC,{singleLine:!0,children:[(0,K.jsx)(wC.Item,{children:e===void 0?`Files`:zzi(e,`File`)}),t===void 0?null:(0,K.jsx)(wC.Item,{children:zzi(t,`Skill`)})]})})}function Vzi(){let{setSearching:e,setQuery:t}=q9(),[n,r]=(0,G.useState)(``),[,i]=(0,G.useTransition)();return(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(Hj,{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)(hw,{})})]})}function Hzi(){let{workspaceId:e,query:t,activeFilePath:n,setActiveFilePath:r,searchFiles:i,searchSkills:a}=q9(),{data:o,isLoading:s,isError:l,error:u}=VIn({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)(NS,{className:`h-4 w-3/4`}),(0,K.jsx)(NS,{className:`h-4 w-2/3`})]}):l?(0,K.jsx)(yzi,{error:u,fallback:`Search failed.`,className:`m-2`}):o?.length?(0,K.jsx)(`ul`,{"aria-label":`Search results`,className:`flex flex-col py-1`,children:o.map(e=>(0,K.jsx)(`li`,{children:(0,K.jsxs)(`button`,{type:`button`,title:e.path,onClick:()=>r(e.path),className:c(`text-foreground`,`flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left hover:bg-fill-subtle`,n===e.path&&`bg-fill`),children:[(0,K.jsx)(xx,{size:`sm`,children:e.kind===`skill`?(0,K.jsx)(wZ,{}):(0,K.jsx)(Fzi,{})}),(0,K.jsx)(T,{as:`span`,variant:`body-sm`,className:`truncate`,children:e.label})]})},e.path))}):(0,K.jsx)(Hx,{titleSlot:`No results`}):(0,K.jsx)(Hx,{titleSlot:`Search files and skills`,descriptionSlot:`Type to find matching content.`})}function Uzi({mount:e}){switch(e.icon||e.provider){case`aws-s3`:case`s3`:return(0,K.jsx)(LOn,{className:`text-foreground`});case`google-cloud`:case`google-cloud-storage`:case`gcs`:return(0,K.jsx)(HOn,{});case`azure-blob`:case`azure`:return(0,K.jsx)(BOn,{className:`text-badge-blue-indicator`});case`cloudflare`:case`cloudflare-r2`:case`r2`:return(0,K.jsx)(U6,{className:`text-badge-orange-indicator`});case`neon`:return(0,K.jsx)(U6,{className:`text-badge-green-indicator`});case`minio`:return(0,K.jsx)(tcr,{className:`text-badge-red-indicator`});case`database`:return(0,K.jsx)(iT,{className:`text-badge-green-indicator`});case`local`:case`folder`:return(0,K.jsx)(GN,{className:`text-badge-amber-indicator`});case`hard-drive`:return(0,K.jsx)(tcr,{className:`text-muted-foreground`});default:return(0,K.jsx)(U6,{className:`text-muted-foreground`})}}var Wzi=e=>(0,K.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`-1 -1 18 18`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,...e,children:(0,K.jsx)(`path`,{d:`M1.5 8.5V8C1.5 7.60218 1.65804 7.22064 1.93934 6.93934C2.22064 6.65804 2.60218 6.5 3 6.5H13C13.3978 6.5 13.7794 6.65804 14.0607 6.93934C14.342 7.22064 14.5 7.60218 14.5 8V8.5M8.70667 4.20667L7.29333 2.79333C7.20048 2.70037 7.09022 2.62661 6.96886 2.57628C6.84749 2.52595 6.71739 2.50003 6.586 2.5H3C2.60218 2.5 2.22064 2.65804 1.93934 2.93934C1.65804 3.22064 1.5 3.60218 1.5 4V12C1.5 12.3978 1.65804 12.7794 1.93934 13.0607C2.22064 13.342 2.60218 13.5 3 13.5H13C13.3978 13.5 13.7794 13.342 14.0607 13.0607C14.342 12.7794 14.5 12.3978 14.5 12V6C14.5 5.60218 14.342 5.22064 14.0607 4.93934C13.7794 4.65804 13.3978 4.5 13 4.5H9.414C9.14887 4.49977 8.89402 4.39426 8.70667 4.20667Z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`})}),Gzi=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 Kzi(){let{workspaceId:e,activeFilePath:t,setActiveFilePath:n}=q9(),{data:r,isLoading:i,error:a}=Xq({workspaceId:e,path:`.`}),[o,s]=(0,G.useState)(null);return i?(0,K.jsx)(eBi,{}):r?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(N6,{"aria-label":`Workspace files`,selectedId:t,onSelect:n,className:`py-1`,children:(0,K.jsx)(qzi,{entries:r,parent:`.`,onRequestDelete:s})}),(0,K.jsx)($zi,{entry:o,onClose:()=>s(null)})]}):(0,K.jsx)(yzi,{error:a,fallback:`Could not load files.`,className:`m-2`})}function qzi({entries:e,parent:t,onRequestDelete:n}){return e.map(e=>{let r=Ezi(t,e.name);return e.type===`directory`?(0,K.jsx)(Xzi,{name:e.name,path:r,mount:e.mount,onRequestDelete:n},e.name):(0,K.jsx)(Qzi,{name:e.name,size:e.size,path:r,onRequestDelete:n},e.name)})}function Jzi({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 Yzi({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)(Bj,{})})}function Xzi({name:e,path:t,mount:n,onRequestDelete:r}){let{workspaceId:i,onDelete:a,onCreateDirectory:o,isReadOnly:s,openFolders:c,setFolderOpen:l}=q9(),u=c.has(t),{isLoading:d}=Xq({workspaceId:i,path:t,queryOptions:{enabled:u}}),[f,p]=(0,G.useState)(!1),m=a&&!s(t),h=o&&!s(t);return(0,K.jsxs)(N6.Folder,{id:t,open:u,onOpenChange:e=>l(t,e),children:[(0,K.jsxs)(N6.FolderTrigger,{actions:m||h?(0,K.jsxs)(Jzi,{children:[h?(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`New folder in ${e}`,onClick:e=>{e.stopPropagation(),l(t,!0),p(!0)},onKeyDown:e=>e.stopPropagation(),children:(0,K.jsx)(P6,{})}):null,m?(0,K.jsx)(Yzi,{name:e,onClick:()=>r({path:t,type:`directory`})}):null]}):void 0,children:[(0,K.jsx)(N6.Icon,{children:n?(0,K.jsx)(`span`,{role:`img`,"aria-label":`Mount: ${n.displayName??n.provider}`,title:[n.displayName??n.provider,n.description].filter(Boolean).join(`: `),className:`flex`,children:(0,K.jsx)(Uzi,{mount:n})}):(0,K.jsx)(Wzi,{})}),(0,K.jsx)(N6.Label,{children:e}),n?.status===`error`?(0,K.jsx)(`span`,{role:`img`,"aria-label":`Mount error: ${n.error??`unavailable`}`,title:n.error,className:`flex shrink-0`,children:(0,K.jsx)(Wx,{className:`size-icon-xs text-destructive-foreground`})}):null,n&&s(t)?(0,K.jsx)(`span`,{role:`img`,"aria-label":`Read-only`,title:`Read-only`,className:`flex shrink-0`,children:(0,K.jsx)(hH,{className:`size-icon-xs text-muted-foreground`})}):null,u&&d?(0,K.jsx)(`span`,{className:`flex shrink-0 animate-in delay-200 fill-mode-backwards fade-in`,children:(0,K.jsx)(It,{size:`sm`,"aria-label":`Loading ${e}`,className:`size-3 text-muted-foreground`})}):null]}),(0,K.jsx)(N6.FolderContent,{children:u?(0,K.jsx)(Zzi,{path:t,creating:f,onCreated:()=>p(!1),onRequestDelete:r}):null})]})}function Zzi({path:e,creating:t,onCreated:n,onRequestDelete:r}){let{workspaceId:i,onCreateDirectory:a}=q9(),o=s_(),{data:s,isLoading:c,error:l}=Xq({workspaceId:i,path:e}),u=async t=>{try{await a?.(Ezi(e,t.replace(/^\/+|\/+$/g,``)))}catch{return}n(),await o.invalidateQueries({queryKey:[`workspace`,i,`fs`,`list`,e]})};return(0,K.jsxs)(K.Fragment,{children:[t?(0,K.jsx)(N6.Input,{type:`folder`,placeholder:`Folder name`,onSubmit:e=>void u(e),onCancel:n}):null,c?null:s?(0,K.jsx)(qzi,{entries:s,parent:e,onRequestDelete:r}):(0,K.jsx)(yzi,{error:l,fallback:`Could not load folder.`,className:`my-1 mr-1`})]})}function Qzi({name:e,size:t,path:n,onRequestDelete:r}){let{onDelete:i,isReadOnly:a,activeFilePath:o}=q9(),s=i&&!a(n),c=n===o,l=(0,G.useRef)(null);return(0,G.useEffect)(()=>{c&&l.current?.scrollIntoView?.({block:`nearest`})},[c]),(0,K.jsxs)(N6.File,{ref:l,id:n,children:[(0,K.jsx)(N6.Icon,{children:(0,K.jsx)(Fzi,{})}),(0,K.jsx)(N6.Label,{children:e}),(0,K.jsxs)(Jzi,{children:[t===void 0?null:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`faint`,font:`mono`,children:Gzi(t)}),s?(0,K.jsx)(Yzi,{name:e,onClick:()=>r({path:n,type:`file`})}):null]})]})}function $zi({entry:e,onClose:t}){let{workspaceId:n,activeFilePath:r,setActiveFilePath:i,onDelete:a}=q9(),o=s_(),[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`,Ozi(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)(WM,{open:e!==null,onOpenChange:e=>{!e&&!s&&t()},children:(0,K.jsxs)(WM.Content,{children:[(0,K.jsxs)(WM.Header,{children:[(0,K.jsxs)(WM.Title,{children:[`Delete `,e?.type===`directory`?`folder`:`file`,`?`]}),(0,K.jsxs)(WM.Description,{children:[d,` This action cannot be undone.`]})]}),(0,K.jsxs)(WM.Footer,{children:[(0,K.jsx)(WM.Cancel,{disabled:s,children:`Cancel`}),(0,K.jsx)(X,{variant:`destructive`,disabled:s,onClick:()=>void u(),children:s?`Deleting…`:`Delete`})]})]})})}function eBi(){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)(NS,{className:`h-4 w-3/4`}),(0,K.jsx)(NS,{className:`h-4 w-1/2`}),(0,K.jsx)(NS,{className:`h-4 w-2/3`})]})}function tBi({children:e,...t}){return(0,K.jsx)(Pzi,{...t,children:(0,K.jsx)(nBi,{children:e})})}function nBi({children:e}){let{workspaceId:t}=q9(),{data:n,error:r}=Xq({workspaceId:t,path:`.`});return(n?n.length===0:kN(r))?(0,K.jsx)(Hx,{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)(kzi,{labeled:!0}),(0,K.jsx)(Nzi,{labeled:!0})]})}):(0,K.jsx)(`div`,{className:`size-full overflow-hidden`,children:(0,K.jsx)(p6,{className:`size-full min-h-0 min-w-0`,orientation:`horizontal`,children:e})})}function rBi({children:e}){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(jGr,{direction:`left`,id:`workspace-aside`,minSize:200,maxSize:`50%`,defaultSize:`25%`,collapsible:!1,className:`min-w-0`,children:(0,K.jsx)(`div`,{className:`flex h-full min-h-0 flex-col`,children:e})}),(0,K.jsx)(m6,{className:`w-px bg-border`})]})}function iBi({children:e,actions:t}){let{isSearching:n}=q9();return(0,K.jsxs)(`div`,{className:`flex h-11 shrink-0 items-center gap-2 border-b border-border px-3`,children:[(0,K.jsx)(`div`,{className:`min-w-0 flex-1`,children:e}),t&&!n?(0,K.jsx)(`div`,{className:`flex shrink-0 items-center gap-1`,children:t}):null]})}function aBi(){let{isSearching:e}=q9();return(0,K.jsx)(jS,{className:`min-h-0 flex-1 px-2 py-1`,children:e?(0,K.jsx)(Hzi,{}):(0,K.jsx)(Kzi,{})})}function oBi({children:e}){return(0,K.jsx)(f6,{id:`workspace-active-file`,className:`flex min-w-0 flex-col`,minSize:30,children:e})}function sBi({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 cBi({renderPreview:e}){let{activeFilePath:t}=q9();return t?(0,K.jsx)(jS,{className:`min-h-0 flex-1`,children:(0,K.jsx)(Tzi,{renderPreview:e})}):(0,K.jsx)(Hx,{variant:`fill`,titleSlot:`Select a file`})}var J9={Root:tBi,Aside:rBi,AsideHeader:iBi,Search:Rzi,SearchToggle:Lzi,CreateDirectory:kzi,Tree:aBi,ActiveFile:oBi,ActiveFileHeader:sBi,FilePath:Czi,ActiveFileContent:cBi};function lBi({asideActions:e,renderPreview:t,...n}){return(0,K.jsxs)(J9.Root,{...n,children:[(0,K.jsxs)(J9.Aside,{children:[(0,K.jsx)(J9.AsideHeader,{actions:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(J9.SearchToggle,{}),(0,K.jsx)(J9.CreateDirectory,{}),(0,K.jsx)(Nzi,{}),e]}),children:(0,K.jsx)(J9.Search,{})}),(0,K.jsx)(J9.Tree,{})]}),(0,K.jsxs)(J9.ActiveFile,{children:[(0,K.jsx)(J9.ActiveFileHeader,{children:(0,K.jsx)(J9.FilePath,{})}),(0,K.jsx)(J9.ActiveFileContent,{renderPreview:t})]})]})}var uBi=()=>(0,K.jsx)(Hx,{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)(qN,{}),children:`Workspaces documentation`}),variant:`fill`}),dBi=()=>(0,K.jsx)(Hx,{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)(qN,{}),children:`Workspaces documentation`}),variant:`fill`}),fBi=()=>(0,K.jsx)(Hx,{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)(qN,{}),children:`Workspaces documentation`}),variant:`fill`}),pBi=`.agents/skills`,mBi=e=>e.replace(/^\.?\/+|\/+$/g,``);function hBi({workspaceId:e,showInitWarning:t,skills:n}){let{data:r}=Xq({workspaceId:e,path:pBi,queryOptions:{enabled:!!n}}),i=n&&r?r.filter(e=>e.type===`directory`&&!n.some(t=>t.name===e.name||mBi(t.path)===`${pBi}/${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)(gk,{variant:`warning`,children:(0,K.jsxs)(gk.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)(gk,{variant:`warning`,title:`Skills installed but not discovered`,children:(0,K.jsxs)(gk.Message,{children:[i.map(e=>e.name).join(`, `),` `,i.length===1?`is`:`are`,` in`,` `,(0,K.jsx)(`code`,{children:pBi}),` but not discovered. Add this path to your workspace skills configuration to see `,i.length===1?`it`:`them`,`.`]})})]})}var Y9=[KN(`/workspaces`)],gBi=e=>ON(e)?`you don't have permission to modify this workspace`:e instanceof Error?e.message:`Unknown error`;function _Bi(){let{workspaceId:e}=Ev(),[t,n]=Mv(),r=Tv(),i=s_(),a=t.get(`file`),{data:o,error:s,isLoading:c}=MIn(),l=o?.workspaces??[],u=e??l[0]?.id,{data:d,isLoading:f,error:p}=jIn({workspaceId:u,queryOptions:{enabled:!!u}}),m=DN(s)||DN(p),h=ON(s)||ON(p),g=pIn(s)||pIn(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=PIn(),C=FIn(),w=d?.isWorkspaceConfigured??!1,T=d?.capabilities?.hasDynamicFilesystem??!1,E=(d?.capabilities?.hasFilesystem??!1)&&!T,D=d?.capabilities?.hasSkills??!1,{data:O,refetch:k}=HIn({workspaceId:u,queryOptions:{enabled:!!u&&E}}),A=DIn(),j=OIn(),M=kIn(),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?Qx.error(`Failed to update ${t.map(e=>e.skillName).join(`, `)}`):Qx.success(`${e.updated.length} skill(s) updated`),i.invalidateQueries({queryKey:[`workspace`,u,`fs`]})}catch(e){Qx.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}"`);Qx.success(`Skill "${n}" removed`),k()}catch(e){throw Qx.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 Qx.error(`Failed to delete ${e}: ${gBi(t)}`),t}},I=_?.safety?.readOnly??!1,{canEdit:L,canDelete:R,canExecute:z,isLoading:B}=oS(),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(),Qx.success(`Skill "${t.skillName}" installed successfully (${t.filesWritten} files)`)}catch(e){throw Qx.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)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:Y9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(It,{fill:!0})]});if(m)return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:Y9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(_H,{variant:`fill`})]});if(h)return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:Y9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(gH,{variant:`fill`,resource:`workspaces`})]});if(g)return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:Y9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(fBi,{})]});let ce=s||p;if(ce)return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:Y9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(Hx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load workspace`,descriptionSlot:ce.message})]});if(!c&&l.length===0)return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:Y9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(uBi,{})]});if(!f&&!c&&!w)return(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:Y9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(dBi,{})]});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)(JS,{size:`xs`,variant:`warning`,children:`Read-only`}),e.capabilities.hasFilesystem&&(0,K.jsx)(JS,{size:`xs`,children:`FS`}),e.capabilities.hasSandbox&&(0,K.jsx)(JS,{size:`xs`,children:`Sandbox`}),e.capabilities.hasSkills&&(0,K.jsx)(JS,{size:`xs`,children:`Skills`})]})}));return(0,K.jsxs)(MS,{variant:`fit`,breadcrumbs:(0,K.jsx)(uN,{crumbs:Y9}),headerActions:(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(lN,{"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)(JS,{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)(hBi,{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)(lBi,{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 Qx.error(`Failed to create ${e}: ${gBi(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)(hS,{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)(Hx,{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)(Hx,{variant:`fill`,titleSlot:`No filesystem or skills configured`,descriptionSlot:`Add a filesystem or skills to this workspace to browse its files here.`})})]})]})}function vBi({children:e,className:t,edgeToEdge:n,mobileHeader:r,ref:i,sidebar:a,...o}){let s=n!==void 0;return(0,K.jsxs)(`div`,{ref:i,"data-slot":`app-shell`,className:c(`h-full min-h-0`,a&&`lg:grid lg:grid-cols-[auto_minmax(0,1fr)] lg:grid-rows-[1fr]`,t),...o,children:[a,(0,K.jsxs)(`div`,{"data-slot":`app-shell-content`,className:`flex h-full min-h-0 min-w-0 flex-col`,"data-sidebar-reveal-layer":`page`,children:[r,(0,K.jsx)(`div`,{"data-slot":`app-shell-body`,className:c(`flex min-h-0 flex-1 flex-col`,s&&`transition-[padding] duration-(--resize-dur) ease-(--resize-ease) motion-reduce:transition-none!`,s&&`in-data-[sidebar-gesture=active]:transition-none!`,!n&&`lg:py-2 lg:pr-2`,!n&&(a?`lg:pl-0`:`lg:pl-2`)),children:e})]})]})}function yBi({children:e,className:t,edgeToEdge:n}){let r=n!==void 0;return(0,K.jsx)(`div`,{"data-slot":`main-card`,className:c(`relative min-h-0 flex-1 overflow-hidden`,r&&`transition-[border-radius,padding,box-shadow] duration-(--resize-dur) ease-(--resize-ease) motion-reduce:transition-none!`,r&&`in-data-[sidebar-gesture=active]:transition-none!`,!n&&`lg:rounded-studio-frame lg:p-px lg:shadow-raised`,sBe,t),children:e})}function bBi(){return(0,K.jsxs)(`div`,{className:`h-screen bg-sidebar`,children:[(0,K.jsx)($x,{position:`bottom-right`}),(0,K.jsx)(M,{defaultTheme:`system`,children:(0,K.jsx)(gx,{delayDuration:0,children:(0,K.jsx)(vBi,{children:(0,K.jsx)(yBi,{className:`flex items-center justify-center overflow-y-auto`,children:(0,K.jsx)(Av,{})})})})})]})}function xBi(){let{data:e,isLoading:t}=D_(),{isLoading:n,canAccessAgentBuilder:r}=sS();return t||n||!e||e.enabled&&!E_(e)?{isVisible:!1}:{isVisible:r}}function SBi(){let{isImpersonating:e,impersonatedRole:t,stopImpersonation:n}=aS();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)(nS,{className:`size-icon-sm shrink-0 text-info-subtle-foreground`}),(0,K.jsxs)(T,{variant:`meta`,className:`truncate text-info-subtle-foreground`,children:[`Previewing `,(0,K.jsx)(`span`,{className:`font-medium capitalize`,children:t.name}),` experience`]}),(0,K.jsx)(`button`,{type:`button`,onClick:n,className:`ml-auto shrink-0 rounded p-0.5 text-info-subtle-foreground hover:bg-info-edge`,title:`Exit role preview`,children:(0,K.jsx)(hw,{className:`size-icon-xs`})})]})}function CBi({children:e,contentClassName:t,commandClassName:n,showOverlay:r=!0,overlayClassName:i,...a}){return(0,K.jsx)(NNn,{size:`xl`,showOverlay:r,overlayClassName:c(`bg-sidebar/40 backdrop-blur-none`,i),contentClassName:c(`command-palette-popup overflow-visible bg-transparent shadow-none`,t),commandClassName:c(`command-palette-shell gap-2 overflow-visible rounded-none bg-transparent text-muted-foreground shadow-none backdrop-blur-none`,`[&_[data-slot=command-input-wrapper]_svg]:text-muted-foreground`,`**:[[cmdk-input]]:h-full **:[[cmdk-input]]:text-body`,`**:[[cmdk-group-heading]]:px-2 **:[[cmdk-group-heading]]:pt-2 **:[[cmdk-group-heading]]:pb-1 **:[[cmdk-group]]:p-0`,`**:[[cmdk-item]]:px-2 **:[[cmdk-item]]:py-1.5`,n),...a,children:e})}function wBi({wrapperClassName:e,...t}){return(0,K.jsx)(gq,{wrapperClassName:c(`command-palette-surface command-palette-surface-input`,Dx,`h-11 shrink-0 rounded-xl border-0 px-3 pr-11`,e),...t})}function TBi({children:e,className:t,...n}){return(0,K.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,K.jsx)(`div`,{className:c(`grid h-full min-h-0 grid-rows-[auto_minmax(0,1fr)] gap-2 md:grid-cols-[13rem_minmax(0,1fr)] md:grid-rows-none`,t),...n,children:e})})}function EBi({children:e,className:t,...n}){return(0,K.jsx)(`aside`,{className:c(`command-palette-surface command-palette-surface-rail flex max-h-[min(14rem,32dvh)] min-h-0 flex-col overflow-hidden rounded-xl p-2 md:h-full md:max-h-none`,Fv,t),...n,children:(0,K.jsx)(jS,{className:`-m-1 min-h-0 flex-1 p-1`,children:(0,K.jsx)(AS,{className:`pr-1`,children:(0,K.jsx)(`div`,{className:`flex flex-col gap-1`,children:e})})})})}function DBi({icon:e,label:t,count:n,active:r,onSelect:i}){return(0,K.jsxs)(`button`,{type:`button`,className:c(gS,`flex h-9 w-full cursor-pointer items-center gap-2 rounded-lg border border-transparent px-2.5 text-left text-body-sm hover:border-border hover:bg-fill-subtle data-[active=true]:border-border data-[active=true]:bg-fill-hover data-[active=true]:text-foreground`,`transition-[color,transform] duration-fast ease-out-custom active:scale-[0.99] motion-reduce:transition-none`),"data-active":r,"aria-pressed":r,onClick:i,children:[(0,K.jsx)(`span`,{className:`flex size-icon-md shrink-0 items-center justify-center [&>svg]:size-icon-md`,children:e}),(0,K.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:t}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`rounded-md border border-border bg-muted/70 px-1.5 py-0.5 leading-none`,children:n})]})}function OBi({children:e,footer:t,...n}){return(0,K.jsxs)(`div`,{role:`region`,className:c(`command-palette-surface command-palette-surface-results command-palette-results-panel relative flex min-h-0 min-w-0 flex-col overflow-hidden rounded-xl`,Fv),...n,children:[(0,K.jsx)(_q,{scrollArea:!0,scrollAreaClassName:`min-h-0 flex-1 rounded-none`,scrollAreaViewportClassName:`command-palette-scroll-viewport`,className:`command-palette-list max-h-none rounded-none border-none bg-transparent shadow-none`,children:e}),t]})}function X9({icon:e,title:t,subtitle:n,path:r,badge:i,shortcut:a,className:o,...s}){return(0,K.jsxs)(bq,{className:c(`group h-auto items-start gap-3 rounded-lg border border-transparent px-3 py-2.5 data-[selected=true]:border-border`,o),...s,children:[(0,K.jsx)(`span`,{className:c(`mt-0.5 flex size-4 max-w-4 min-w-4 shrink-0 basis-4 items-center justify-center text-muted-foreground group-data-[selected=true]:text-foreground [&>svg]:!size-4 [&>svg]:shrink-0`),children:e}),(0,K.jsxs)(`span`,{className:`flex min-w-0 flex-1 flex-col gap-1`,children:[(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`ink`,className:`truncate`,children:t}),i&&(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`shrink-0 rounded-md border border-border bg-muted/60 px-1.5 py-0.5 leading-none uppercase`,children:i})]}),(n||r)&&(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`flex min-w-0 items-center gap-2`,children:[n&&(0,K.jsx)(`span`,{className:`min-w-0 truncate`,children:n}),r&&(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,font:`mono`,className:`max-w-52 truncate rounded-md border border-border bg-muted/70 px-1.5 py-0.5 leading-none`,children:r})]})]}),a&&(0,K.jsx)(FNn,{children:a})]})}function kBi({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)(Fx,{size:`sm`,children:`↑`}),(0,K.jsx)(Fx,{size:`sm`,children:`↓`}),(0,K.jsx)(Fx,{size:`sm`,children:`↵`}),(0,K.jsx)(Fx,{size:`sm`,children:`Esc`})]})]})}var ABi=!1,jBi=new Set,MBi=()=>{jBi.forEach(e=>e())},NBi=e=>(jBi.add(e),()=>jBi.delete(e)),PBi=()=>ABi,FBi=e=>{let t=typeof e==`function`?e(ABi):e;t!==ABi&&(ABi=t,MBi())},IBi=({enableShortcut:e=!0}={})=>{let t=(0,G.useSyncExternalStore)(NBi,PBi,PBi),n=(0,G.useCallback)(e=>{FBi(e)},[]),r=(0,G.useCallback)(()=>{FBi(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 LBi(e,t){return[e.name,e.url,t,`path route navigate`].filter(Boolean).join(` `)}function RBi(e){return!e||e===`Studio`?`Path`:e}function zBi(e){return`/traces?entity=${encodeURIComponent(e)}`}var BBi=({scopeOptions:e,activeScope:t,onScopeChange:n})=>(0,K.jsx)(EBi,{"aria-label":`Search categories`,children:e.map(e=>(0,K.jsx)(DBi,{icon:e.icon,label:e.label,count:e.count,active:t===e.id,onSelect:()=>n(e.id)},e.id))}),VBi=({sidebar:e,activeScope:t,closeCommand:n})=>!e||t!==`all`&&t!==`settings`?null:(0,K.jsx)(yq,{heading:`Commands`,children:(0,K.jsx)(X9,{value:`toggle sidebar collapse expand layout panel`,onSelect:()=>{e.toggleSidebar(),n()},icon:(0,K.jsx)(xzr,{}),title:`Toggle sidebar`,subtitle:`Studio layout`})}),HBi=({sections:e,handleSelect:t})=>(0,K.jsx)(K.Fragment,{children:e.map(e=>(0,K.jsx)(yq,{heading:e.title,children:e.items.map(n=>{let r=n.Icon;return(0,K.jsx)(X9,{value:LBi(n,e.title),onSelect:()=>t(n.url),icon:(0,K.jsx)(r,{}),title:n.name,subtitle:`Studio path`,path:n.url,badge:RBi(e.title)},n.url)})},e.key))}),UBi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(yq,{heading:`Agents`,children:t.map(([e,t])=>(0,K.jsx)(X9,{value:`${t.name} ${e} chat agent conversation thread ${n.agentLink(e)}`,onSelect:()=>r(n.agentLink(e)),icon:(0,K.jsx)(PN,{}),title:t.name,subtitle:`Agent chat`,path:n.agentLink(e),badge:`Agent`},e))}),WBi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(yq,{heading:`Workflows`,children:t.map(([e,t])=>(0,K.jsx)(X9,{value:`${t.name} ${e} graph workflow view ${n.workflowLink(e)}`,onSelect:()=>r(n.workflowLink(e)),icon:(0,K.jsx)(GS,{}),title:t.name,subtitle:`Workflow graph`,path:n.workflowLink(e),badge:`Workflow`},e))}),GBi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(yq,{heading:`Tools`,children:t.map(([e,t])=>(0,K.jsx)(X9,{value:`tool ${t.id} ${e} ${n.toolLink(e)}`,onSelect:()=>r(n.toolLink(e)),icon:(0,K.jsx)(HN,{}),title:t.id,subtitle:`Tool definition`,path:n.toolLink(e),badge:`Tool`},e))}),KBi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(yq,{heading:`Processors`,children:t.map(e=>{let t=e.name||e.id,i=e.isWorkflow?n.workflowLink(e.id)+`/graph`:n.processorLink(e.id);return(0,K.jsx)(X9,{value:`processor ${t} ${e.id} ${i}`,onSelect:()=>r(i),icon:(0,K.jsx)(oP,{}),title:t,subtitle:e.isWorkflow?`Workflow processor`:`Processor`,path:i,badge:`Processor`},e.id)})}),qBi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(yq,{heading:`MCP Servers`,children:t.map(e=>(0,K.jsx)(X9,{value:`mcp server ${e.name} ${e.id} ${n.mcpServerLink(e.id)}`,onSelect:()=>r(n.mcpServerLink(e.id)),icon:(0,K.jsx)(RN,{}),title:e.name,subtitle:`MCP server`,path:n.mcpServerLink(e.id),badge:`MCP`},e.id))}),JBi=({visible:e,agentEntries:t,workflowEntries:n,handleSelect:r})=>e?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(yq,{heading:`Observability`,children:[(0,K.jsx)(X9,{value:`observability traces telemetry signals /traces`,onSelect:()=>r(`/traces`),icon:(0,K.jsx)(nS,{}),title:`Traces`,subtitle:`Runtime traces`,path:`/traces`,badge:`Signal`}),(0,K.jsx)(X9,{value:`metrics usage latency performance tokens /metrics`,onSelect:()=>r(`/metrics`),icon:(0,K.jsx)(G4,{}),title:`Metrics`,subtitle:`Runtime metrics`,path:`/metrics`,badge:`Signal`}),(0,K.jsx)(X9,{value:`logs events runtime /logs`,onSelect:()=>r(`/logs`),icon:(0,K.jsx)(nS,{}),title:`Logs`,subtitle:`Runtime logs`,path:`/logs`,badge:`Signal`})]}),t.length>0&&(0,K.jsx)(yq,{heading:`Agent Traces`,children:t.map(([e,t])=>{let n=zBi(e);return(0,K.jsx)(X9,{value:`${t.name} ${e} traces agent observability telemetry`,onSelect:()=>r(n),icon:(0,K.jsx)(nS,{}),title:t.name,subtitle:`Agent traces`,path:n,badge:`Trace`},e)})}),n.length>0&&(0,K.jsx)(yq,{heading:`Workflow Traces`,children:n.map(([e,t])=>{let n=zBi(t.name);return(0,K.jsx)(X9,{value:`${t.name} ${e} traces workflow observability telemetry`,onSelect:()=>r(n),icon:(0,K.jsx)(nS,{}),title:t.name,subtitle:`Workflow traces`,path:n,badge:`Trace`},e)})})]}):null,YBi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(yq,{heading:`Scorers`,children:t.map(([e,t])=>{let i=t.scorer?.config?.name||t.scorer?.config?.id||e;return(0,K.jsx)(X9,{value:`scorer score evaluation ${i} ${e} ${n.scorerLink(e)}`,onSelect:()=>r(n.scorerLink(e)),icon:(0,K.jsx)(G4,{}),title:i,subtitle:`Evaluation scorer`,path:n.scorerLink(e),badge:`Scorer`},e)})}),XBi=()=>{let{open:e,setOpen:t}=IBi(),{navigate:n,paths:r}=sn(),{isMastraPlatform:i}=H8(),a=n3(),[o,s]=G.useState(`all`),{data:c={}}=gN(),{data:l={}}=KM(),{data:u={}}=Dq(),{data:d={}}=EN(),{data:f=[]}=TN(),{data:p={}}=NN(),{isCmsAvailable:m,isLoading:h}=w3(),{hasPermission:g,hasAnyPermission:_,isLoading:v}=oS(),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=uS(e.url);return v&&t&&t!==`public`?!1:dS(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 vMt){let n=t.items.filter(S);n.length>0&&e.push({key:t.key,title:t.title,items:n})}let t=[...yMt.filter(S),...i?[]:[{name:`Templates`,url:`/templates`,Icon:SZ,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)(QM,{}),count:P},{id:`paths`,label:`Paths`,icon:(0,K.jsx)(Qmn,{}),count:k},{id:`agents`,label:`Agents`,icon:(0,K.jsx)(PN,{}),count:C.length},{id:`workflows`,label:`Workflows`,icon:(0,K.jsx)(GS,{}),count:w.length},{id:`tooling`,label:`Tooling`,icon:(0,K.jsx)(Csi,{}),count:A},{id:`evaluation`,label:`Evaluation`,icon:(0,K.jsx)(G4,{}),count:j},{id:`observability`,label:`Intelligence`,icon:(0,K.jsx)(nS,{}),count:M},{id:`settings`,label:`Studio`,icon:(0,K.jsx)(jq,{}),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)(CBi,{open:e,onOpenChange:y,title:`Mastra Studio Search`,description:`Search Studio routes and runtime entities`,children:[(0,K.jsx)(wBi,{placeholder:`Search Studio, agents, workflows, tools, paths`}),(0,K.jsxs)(TBi,{children:[(0,K.jsx)(BBi,{scopeOptions:F,activeScope:o,onScopeChange:s}),(0,K.jsxs)(OBi,{"aria-label":`Search results`,footer:(0,K.jsx)(kBi,{label:`Studio search`}),children:[(0,K.jsx)(vq,{children:`No matching results.`}),(0,K.jsx)(VBi,{sidebar:a,activeScope:o,closeCommand:b}),(0,K.jsx)(HBi,{sections:ee,handleSelect:x}),(0,K.jsx)(UBi,{visible:L,entries:C,paths:r,handleSelect:x}),(0,K.jsx)(WBi,{visible:R,entries:w,paths:r,handleSelect:x}),(0,K.jsx)(GBi,{visible:z,entries:T,paths:r,handleSelect:x}),(0,K.jsx)(KBi,{visible:z,entries:E,paths:r,handleSelect:x}),(0,K.jsx)(qBi,{visible:z,entries:f,paths:r,handleSelect:x}),(0,K.jsx)(JBi,{visible:V,agentEntries:C,workflowEntries:w,handleSelect:x}),(0,K.jsx)(YBi,{visible:B,entries:D,paths:r,handleSelect:x})]})]})]})};function ZBi(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 QBi(e){let{Icon:t}=e;return{name:e.name,url:e.url,icon:(0,K.jsx)(t,{})}}function $Bi(){let{state:e,isMobile:t,setOpenMobile:n}=r3(),{setOpen:r}=IBi({enableShortcut:!1}),i=M3r(`K`),a=wv().pathname,{isMastraPlatform:o}=H8(),{data:s}=D_(),{isCmsAvailable:c,isLoading:l}=w3(),{hasPermission:u,hasAnyPermission:d,isLoading:f}=oS(),{data:p}=Tdr(),m=p!==void 0&&p.status!==`not-mounted`,h=s&&E_(s),g=new Set([`/prompts`]),{isVisible:_}=xBi(),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=uS(e.url);if(t&&t!==`public`)return!1}return!!dS(uS(e.url),u,d)},{data:x}=TN(),{data:S}=MIn(),C=yMt.filter(b),w=vMt.map(e=>{let t=e.items.filter(b),n=e=>({...QBi(e),isActive:ZBi(e,a,t)});return{key:e.key,title:e.title,href:e.href,isHeaderActive:!(!e.href||a!==e.href||t.some(e=>ZBi(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)(LZ,{className:`size-6`}),actions:h&&(0,K.jsx)(mer,{}),children:[(0,K.jsx)(f3.Brand,{logo:(0,K.jsx)(LZ,{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)(US,{})},isActive:v})}),(0,K.jsx)(SBi,{}),(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:QBi(t),isActive:ZBi(t,a)},t.name)),(0,K.jsx)(cHr,{state:e})]})})]})}var eVi=()=>{let{baseUrl:e,headers:t,apiPrefix:n,setConfig:r}=pS(),[i,a]=(0,G.useState)(()=>Object.entries(t).map(([e,t])=>({name:e,value:t})));return(0,K.jsx)(gx,{delayDuration:0,children:(0,K.jsxs)(UV,{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}),Qx.success(`Headers saved`)},className:`w-full max-w-md gap-6 text-left`,children:[(0,K.jsx)(_zr,{headers:i,onAddHeader:e=>{a(t=>[...t,e])},onRemoveHeader:e=>{a(t=>t.filter((t,n)=>n!==e))}}),(0,K.jsxs)(X,{type:`submit`,className:`ml-auto`,children:[(0,K.jsx)(W4,{}),`Save headers`]})]})})};function tVi({children:e,loginUrl:t=`/login`,signupUrl:n=`/signup`}){let{data:r,isLoading:i}=D_();if(i||!r?.enabled||E_(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)(LZ,{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)(hH,{className:`mt-0.5 size-icon-md shrink-0 text-muted-foreground`}),(0,K.jsx)(T,{tone:`muted`,className:`max-w-sm`,children:r.login.description})]}),(0,K.jsx)(uer,{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(RZ(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)(LZ,{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)(eVi,{})]})})}var nVi=`experimental-ui:`,rVi=`current`,iVi=G.createContext(null);function aVi(e,t){let n=window.localStorage.getItem(nVi+e);return n&&t.has(n)?n:rVi}function oVi({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]=aVi(r.key,e)}i(t)},[e,n]);let a=G.useCallback(e=>r[e]??rVi,[r]),o=G.useCallback((e,t)=>{window.localStorage.setItem(nVi+e,t),i(n=>({...n,[e]:t}))},[]),s=G.useMemo(()=>({experiments:e,getVariant:a,setVariant:o}),[e,a,o]);return(0,K.jsx)(iVi.Provider,{value:s,children:t})}var sVi=[{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`}]}],cVi=()=>({experimentalUIEnabled:typeof window<`u`&&window.MASTRA_EXPERIMENTAL_UI===`true`}),lVi=()=>{let{toggleSidebar:e}=r3();return Lx({"[":e},{repeat:!1}),null};function uVi(){let{setOpenMobile:e}=r3(),{setOpen:t}=IBi({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)(LZ,{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)(QM,{})})]})}var dVi={"studio-frame":100,"route-side-panel":0},fVi={overflow:`visible`};function pVi({children:e,className:t}){let n=Gw(),{hasPanel:r,panelHandle:i,onPanelResize:a}=V8(),{defaultLayout:o,onLayoutChange:s}=bGr({id:`studio-frame-layout-v1`,storage:localStorage});return(0,K.jsx)(`div`,{className:`relative flex min-h-0 flex-1`,children:(0,K.jsxs)(p6,{className:`min-h-0 flex-1`,style:fVi,orientation:`horizontal`,defaultLayout:o??dVi,onLayoutChange:s,children:[(0,K.jsx)(f6,{id:`studio-frame`,className:c(`min-w-0`,t),style:fVi,children:e}),r&&!n&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(m6,{className:`w-2`}),(0,K.jsx)(jGr,{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)(g2r,{className:`h-full min-h-0`})})]})]})})}function mVi({children:e}){let{data:t,isFetched:n}=D_(),{pathname:r}=wv(),i=!(n&&t?.enabled&&!E_(t));return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(XBi,{}),(0,K.jsx)(vBi,{sidebar:i?(0,K.jsx)($Bi,{}):void 0,mobileHeader:i?(0,K.jsx)(uVi,{}):void 0,children:(0,K.jsx)(pVi,{className:`flex min-h-0 flex-1 flex-col`,children:(0,K.jsx)(yBi,{children:(0,K.jsx)(tVi,{children:(0,K.jsx)(yJe,{resetKeys:[r],children:e})})})})})]})}var hVi=({children:e})=>{let{experimentalUIEnabled:t}=cVi(),{Link:n}=sn();return(0,K.jsxs)(`div`,{className:`h-screen bg-sidebar`,children:[(0,K.jsx)($x,{position:`bottom-right`}),(0,K.jsx)(M,{defaultTheme:`system`,children:(0,K.jsx)(gx,{delayDuration:0,children:(0,K.jsx)(oVi,{experiments:t?sVi:[],children:(0,K.jsxs)(f3.Provider,{LinkComponent:n,children:[(0,K.jsx)(lVi,{}),(0,K.jsx)(h2r,{children:(0,K.jsx)(mVi,{children:e})})]})})})})]})},gVi=({children:e})=>(0,K.jsxs)(`div`,{className:`h-screen bg-sidebar`,children:[(0,K.jsx)($x,{position:`bottom-right`}),(0,K.jsx)(M,{defaultTheme:`system`,children:(0,K.jsx)(gx,{delayDuration:0,children:(0,K.jsx)(`div`,{className:`h-full overflow-y-auto`,children:(0,K.jsx)(tVi,{children:e})})})})]}),_Vi={name:`Agents`,url:`/agent-builder/agents`,icon:(0,K.jsx)(PN,{})},vVi={name:`Skills`,url:`/agent-builder/skills`,icon:(0,K.jsx)(Qur,{className:`size-icon-lg`})},yVi={name:`Favorites`,url:`/agent-builder/favorite`,icon:(0,K.jsx)(SK,{className:`size-icon-lg`})},bVi={name:`Library`,url:`/agent-builder/library`,icon:(0,K.jsx)(IN,{className:`size-icon-lg`})},xVi={name:`Infra`,url:`/agent-builder/infrastructure`,icon:(0,K.jsx)(hXr,{className:`size-icon-lg`})};function SVi(){let{Link:e}=sn(),{pathname:t}=wv(),n=CK(),{canManageSkills:r,canUseFavorites:i}=sS(),{hasPermission:a}=oS(),o=a(`infrastructure:read`),s=(0,G.useMemo)(()=>{let e=[_Vi];return n.skills&&r&&e.push(vVi),i&&e.push(yVi),e.push(bVi),o&&e.push(xVi),e},[n.skills,r,i,o]);return(0,K.jsx)(`nav`,{"aria-label":`Primary`,className:`fixed inset-x-0 bottom-0 z-40 border-t border-border bg-sidebar/95 pb-[env(safe-area-inset-bottom)] backdrop-blur-sm md:hidden`,children:(0,K.jsx)(`ul`,{className:`grid`,style:{gridTemplateColumns:`repeat(${s.length}, minmax(0, 1fr))`},children:s.map(n=>{let r=t.startsWith(n.url);return(0,K.jsx)(`li`,{children:(0,K.jsxs)(e,{href:n.url,"aria-current":r?`page`:void 0,className:c(r?`text-foreground`:`text-muted-foreground`,`relative flex flex-col items-center justify-center gap-1 py-2`,A,r?`before:absolute before:inset-x-0 before:-top-px before:h-0.5 before:bg-current`:`hover:text-foreground`),children:[(0,K.jsx)(`span`,{className:`flex size-6 items-center justify-center`,"aria-hidden":`true`,children:(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`block`,children:n.icon})}),(0,K.jsx)(T,{as:`span`,variant:`caption`,children:n.name})]})},n.name)})})})}var CVi={name:`My agents`,url:`/agent-builder/agents`,icon:(0,K.jsx)(PN,{})},wVi={name:`Favorites`,url:`/agent-builder/favorite`,icon:(0,K.jsx)(SK,{})},TVi={name:`Library`,url:`/agent-builder/library`,icon:(0,K.jsx)(IN,{})},EVi={name:`Skills`,url:`/agent-builder/skills`,icon:(0,K.jsx)(Qur,{className:`size-icon-md`})},DVi={name:`Infrastructure`,url:`/agent-builder/infrastructure`,icon:(0,K.jsx)(hXr,{className:`size-icon-md`})};function OVi({forceExpanded:e=!1}={}){let{Link:t}=sn(),{state:n,isMobile:r}=r3(),{pathname:i}=wv(),a=CK(),{canManageSkills:o,canUseFavorites:s}=sS(),{hasPermission:c}=oS(),l=c(`infrastructure:read`),u=e?`default`:n,{data:d}=D_(),f=d&&E_(d),p=[CVi];a.skills&&o&&p.push(EVi),s&&p.push(wVi),p.push(TVi);let m=(0,K.jsx)(t,{href:`/agents`,"aria-label":`Back to Mastra Studio`,children:(0,K.jsx)(LZ,{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)(mer,{}),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)(LZ,{className:`size-6`}),title:`Mastra Studio`})}),!r&&(0,K.jsx)(f3.Trigger,{})]}),(0,K.jsx)(SBi,{}),(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:DVi,isActive:i.startsWith(DVi.url)})})})]})})]})}var Z9=()=>(0,K.jsx)(`div`,{className:`h-screen bg-sidebar`,children:(0,K.jsxs)(ABr,{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)(OVi,{})}),(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)(Av,{})})})]}),(0,K.jsx)(SVi,{})]})}),kVi=()=>(0,K.jsx)(`div`,{className:`grid h-screen grid-cols-[minmax(0,1fr)] grid-rows-1 bg-sidebar`,children:(0,K.jsx)(Av,{})});function AVi({agentId:e,children:t,disabled:n=!1}){let r=Gw(),i=(0,K.jsx)(MZ,{children:(0,K.jsx)(b2r,{agentId:e})},e);return n?t:(0,K.jsxs)(Iw,{side:`right`,children:[t,r?(0,K.jsxs)(Rw,{children:[(0,K.jsx)(zw,{}),(0,K.jsx)(Bw,{children:(0,K.jsxs)(Vw,{className:`w-[calc(100vw-2.5rem)] max-w-md`,children:[(0,K.jsx)(Uw,{className:`sr-only`,children:`Config`}),(0,K.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:i})]})})]}):(0,K.jsx)(B8,{owner:`agent-detail`,children:i})]})}var jVi=()=>{let{toggle:e}=V8();return Lx({"]":e}),null};function MVi(){let e=Gw(),{isCollapsed:t,toggle:n}=V8();return e?(0,K.jsx)(Lw,{asChild:!0,children:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,type:`button`,"aria-label":`Config`,tooltip:`Show config panel`,"data-testid":`agent-overview-panel-toggle`,children:(0,K.jsx)(O3,{side:`right`})})}):(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,type:`button`,"aria-label":`Config`,"aria-pressed":!t,tooltip:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[t?`Show config panel`:`Hide config panel`,(0,K.jsx)(Fx,{size:`xs`,children:`]`})]}),"data-testid":`agent-overview-panel-toggle`,onClick:n,children:(0,K.jsx)(O3,{side:`right`})})}function NVi({agentId:e,showConfig:t=!0}){let{data:n}=hN({agentId:e,requestContext:IS(`agent`,e)[0],queryOptions:{enabled:!!e}}),{canCreateAgent:r}=POn(),{Link:i,paths:a}=sn(),{handleCopy:o,isCopied:s}=lC({text:`${window.location.origin}${RZ(`/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)(XV,{}),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)(sC,{}):(0,K.jsx)(YX,{})}),t&&(0,K.jsx)(MVi,{})]})}function PVi(e){if(e)try{return XO(e)}catch{return}}function FVi(e){let t=PVi(e.inputSchema);return{inputSchema:t,outputSchema:PVi(e.outputSchema),requestContextSchema:PVi(e.requestContextSchema),zodInputSchema:z9(t)}}function IVi(e,t){let{data:n={},isLoading:r,isError:i}=gN(),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 LVi({agent:e,isCurrent:t}){let{Link:n,paths:r}=sn(),i=(0,K.jsx)(Z.NameCell,{children:(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(xx,{size:`sm`,className:`shrink-0 text-muted-foreground`,children:(0,K.jsx)(PN,{})}),e.name]})});return t?(0,K.jsxs)(Z.RowStatic,{children:[i,(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(JS,{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 RVi({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 zVi({toolId:e,currentAgentId:t}){let{agents:n,isLoading:r,isError:i}=IVi(e,t),a=RVi({isLoading:r,isError:i,isEmpty:n.length===0});return a?(0,K.jsx)(fZ,{children:(0,K.jsx)(mPi,{message:a})}):(0,K.jsx)(Z,{columns:`minmax(0,1fr) auto`,fit:`container`,children:n.map(e=>(0,K.jsx)(LVi,{agent:e,isCurrent:e.id===t},e.id))})}function BVi(e){return(0,K.jsxs)(pZ,{children:[(0,K.jsx)(uPi,{children:(0,K.jsx)(mZ,{children:`Used by`})}),(0,K.jsx)(zVi,{...e})]})}function VVi({tool:e,execution:t,currentAgentId:n,requestContextEntityType:r,requestContextEntityId:i}){let{canExecute:a}=oS(),{inputSchema:o,outputSchema:s,requestContextSchema:c,zodInputSchema:l}=FVi(e);return(0,K.jsx)(lPi,{description:e.description,overview:(0,K.jsx)(oFi,{inputSchema:o,outputSchema:s,requestContextSchema:c,footer:(0,K.jsx)(BVi,{toolId:e.id,currentAgentId:n})}),canRun:a(`tools`),playground:(0,K.jsx)(tFi,{zodInputSchema:l,execution:t,requestContextEntityType:r,requestContextEntityId:i})})}function HVi({agentId:e}){let t=aFi(),[n]=IS(`agent`,e),{data:r,isLoading:i}=hN({agentId:e,requestContext:n}),{mutateAsync:a,status:o,data:s,error:c}=PAt(),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)(dQ.LoadingData,{}):l?(0,K.jsx)(VVi,{tool:l,execution:u,currentAgentId:e,requestContextEntityType:`agent-tool`,requestContextEntityId:`${e}:${l.id}`}):(0,K.jsxs)(dQ.NoData,{children:[`This agent has no tool "`,t,`".`]})}var UVi=[KN(`/agents`),wMt],WVi=({agentId:e})=>{let t=Tv();return Lx({"g$+t":()=>t(`/agents/${e}/traces`)}),null},GVi=x8.threadId;function KVi(e,t,n){if(e===`chat`){let e=L_(`/agents/:agentId/threads/:threadId`,t)?.params.threadId;return e===`new`?void 0:e}if(e===`traces`){let e=new URLSearchParams(n),t=e.get(C8(GVi));return t&&t!==`is`?void 0:e.get(GVi)||void 0}}var qVi=({children:e})=>{let{agentId:t}=Ev(),n=wv(),{isCmsAvailable:r}=w3(),{hasObservability:i}=aAt(),a=At.has(`datasets`),o=r&&a,s=i&&a,{data:c}=hN({agentId:t,requestContext:IS(`agent`,t)[0],queryOptions:{enabled:!!t}}),l=wK(c?.provider??``),u=c?.modelId??``,d=n.pathname.includes(`/threads`)?`chat`:n.pathname.includes(`/editor`)?`versions`:n.pathname.includes(`/traces`)?`traces`:`none`,f=KVi(d,n.pathname,n.search);return(0,K.jsx)(yLr,{defaultProvider:l,defaultModel:u,children:(0,K.jsxs)(tn,{children:[(0,K.jsx)(WVi,{agentId:t}),(0,K.jsx)(jVi,{}),(0,K.jsx)(NFi,{children:(0,K.jsx)(HVi,{agentId:t})}),(0,K.jsx)(AVi,{agentId:t,disabled:d===`versions`,children:(0,K.jsxs)(MS,{variant:`fit`,breadcrumbs:(0,K.jsx)(uN,{crumbs:UVi}),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)(D$r,{agentId:t,activeTab:d,threadId:f,showPlayground:o,showObservability:s}),e]})]})})]})},`${t}:${l}/${u}`)};function JVi(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:XDi(n,r),childCount:t?.pages.length?`${t.pages.length}${t.nextCursor?`+`:``}`:void 0}}function YVi(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 XVi(e){let t=Y(),n=Yji().data?.[0]?.key,r=e.pageId??e.pageRef,i=S_({queryKey:[`knowledge`,n,`tree`,null,null],queryFn:n?async()=>t.getKnowledge(n).tree({}):h_,staleTime:3e4}),a=e.pageId!==void 0||e.pageRef!==void 0&&YVi(e.pageRef,i.data),{data:o}=S_({queryKey:[`knowledge`,n,`page`,r,null],queryFn:n&&r&&a?async()=>t.getKnowledge(n).page(r):h_,retry:!1,staleTime:3e4}),s=o?.page.id,c=S_({queryKey:[`knowledge`,n,`tree`,s??null,null],queryFn:n&&s?async()=>t.getKnowledge(n).tree({parentId:s}):h_,staleTime:3e4});return o?JVi(o,c.data):void 0}function ZVi({children:e}){return(0,K.jsx)(f0n,{pageHref:sX,refHref:sX,usePagePreview:XVi,children:e})}var QVi=()=>{let e=Tv();return Lx({"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},$Vi=KN(`/traces`);function eHi(e){return e.startsWith(`/spans`)?`spans`:e.startsWith(`/threads`)?`threads`:`traces`}function tHi({children:e}){let{pathname:t}=wv(),n=Tv(),r=eHi(t),i=IIi({current:r,features:g7});return(0,K.jsx)(PIi,{current:r,views:i,onViewChange:e=>n(`/${e}`),breadcrumbs:e=>{let t=JIi(e);return(0,K.jsx)(uN,{crumbs:t?[$Vi,{id:e.current,label:t}]:[$Vi]})},children:e})}var nHi=()=>(0,K.jsx)(Hx,{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)(qN,{}),children:`Processors documentation`}),variant:`fill`}),rHi=[`input`,`inputStep`,`outputStep`,`outputStream`,`outputResult`],iHi={name:e=>e.name||e.id,agents:e=>e.agentIds?.length??0};function aHi({processors:e,isLoading:t,search:n=``,sort:r,onSortChange:i}){let{paths:a,Link:o}=sn(),s=(0,G.useMemo)(()=>Object.values(e??{}).filter(e=>e.phases&&e.phases.length>0),[e]),c=(0,G.useMemo)(()=>{let e=n.toLowerCase();return AZ(s.filter(t=>t.id.toLowerCase().includes(e)||(t.name||``).toLowerCase().includes(e)),r,iHi)},[s,n,r]),{containerRef:l,getRowProps:u}=OZ({count:c.length,global:!0});if(t)return(0,K.jsx)(yH,{columns:`auto 1fr auto auto auto auto auto auto`});let d=e=>r?.key===e?r.direction:void 0;return(0,K.jsxs)(Z,{columns:`auto 1fr auto auto auto auto auto auto`,scrollRef:l,children:[(0,K.jsxs)(Z.Top,{children:[i?(0,K.jsx)(Z.SortableTopCell,{sortKey:`name`,sort:d(`name`),onSortChange:i,children:`Name`}):(0,K.jsx)(Z.TopCell,{children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`Description`}),(0,K.jsx)(Z.TopCellSmart,{long:`Input`,short:`Input`,tooltip:`Contains input phase`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Input Step`,short:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(H4,{}),` Step`]}),tooltip:`Contains input step phase`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Output Step`,short:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(U4,{}),` Step`]}),tooltip:`Contains output step phase`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Output Stream`,short:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(U4,{}),` Stream`]}),tooltip:`Contains output stream phase`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Output Result`,short:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(U4,{}),` Result`]}),tooltip:`Contains output result phase`,className:`text-center`}),i?(0,K.jsx)(Z.SortableTopCell,{sortKey:`agents`,sort:d(`agents`),onSortChange:i,align:`end`,children:`Used by`}):(0,K.jsx)(Z.TopCellSmart,{short:`Used by`,long:`Used by Agents`,className:`text-center`})]}),c.length===0&&n?(0,K.jsx)(Z.NoMatch,{message:`No Processors match your search`}):null,c.map((e,t)=>{let n=rJ(e.name||e.id,50),r=rJ(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}),rHi.map(e=>(0,K.jsx)(Z.TextCell,{className:`text-center`,children:s.has(e)&&(0,K.jsx)(sC,{className:`mx-auto size-icon-md`})},e)),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:i||``})]},e.id)})]})}var Q9=[KN(`/processors`)];function oHi(){let{data:e={},isLoading:t,error:n}=EN(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)();return n&&DN(n)?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:Q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Processors`}),(0,K.jsx)(_H,{variant:`fill`})]}):n&&ON(n)?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:Q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Processors`}),(0,K.jsx)(gH,{variant:`fill`,resource:`processors`})]}):n?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:Q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Processors`}),(0,K.jsx)(Hx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load processors`,descriptionSlot:n.message})]}):Object.keys(e).length===0&&!t?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:Q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Processors`}),(0,K.jsx)(nHi,{})]}):(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:Q9}),actionRow:(0,K.jsx)(_K,{children:(0,K.jsx)(_K.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(wH,{...TH,onValueChange:i,label:`Search processors`,placeholder:`Search by name`})})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Processors`}),(0,K.jsx)(aHi,{processors:e,isLoading:t,search:r,sort:a,onSortChange:(e,t)=>o({key:t,direction:e})})]})}var sHi={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 cHi({processorId:e}){let{data:t,isLoading:n,error:r}=Ajt({processorId:e,queryOptions:{enabled:!!e}});return(0,G.useEffect)(()=>{if(r){let e=r instanceof Error?r.message:`Failed to load processor`;Qx.error(`Error loading processor: ${e}`)}},[r]),n?(0,K.jsxs)(`div`,{className:`p-4`,children:[(0,K.jsx)(NS,{className:`mb-4 h-8 w-48`}),(0,K.jsx)(NS,{className:`h-32 w-full`})]}):r?null:t?(0,K.jsx)(lHi,{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 lHi({processor:e}){let t=pw(),[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=jjt(),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)(uHi,{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)($O,{children:[(0,K.jsx)(tk,{children:`Phase`}),(0,K.jsxs)(Pk,{value:n,onValueChange:t=>{let n=e.phases.find(e=>e===t);n&&r(n)},children:[(0,K.jsx)(Ik,{className:`w-full`,children:(0,K.jsx)(Fk,{placeholder:`Select phase`})}),(0,K.jsx)(Lk,{children:e.phases.map(e=>(0,K.jsx)(Rk,{value:e,children:e},e))})]})]}),(0,K.jsx)(T,{variant:`meta`,tone:`muted`,children:sHi[n]})]}),e.configurations.length>1&&(0,K.jsxs)($O,{children:[(0,K.jsx)(tk,{children:`Agent Configuration`}),(0,K.jsxs)(Pk,{value:i,onValueChange:a,children:[(0,K.jsx)(Ik,{className:`w-full`,children:(0,K.jsx)(Fk,{placeholder:`Select agent`})}),(0,K.jsx)(Lk,{children:e.configurations.map(e=>(0,K.jsxs)(Rk,{value:e.agentId,children:[e.agentName,` (`,e.type,`)`]},e.agentId))})]})]}),(0,K.jsxs)($O,{children:[(0,K.jsx)(tk,{children:`Test Message`}),(0,K.jsx)(Vk,{value:o,onChange:e=>s(e.target.value),placeholder:`Enter a test message`,rows:4})]}),(0,K.jsx)(X,{icon:(0,K.jsx)(xT,{}),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)(JS,{variant:c.success?`success`:`destructive`,children:c.success?`Success`:`Failed`}),c.tripwire?.triggered&&(0,K.jsx)(JS,{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)(uC,{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)(dw,{value:u||m,editable:!0,theme:t,extensions:[mt,fw],basicSetup:{foldGutter:!1}})})]})}function uHi({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)(JS,{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 dHi=[KN(`/processors`),EMt];function fHi(){let{processorId:e}=Ev(),{data:t,isLoading:n,error:r}=Ajt({processorId:e,queryOptions:{enabled:!!e}});return r&&DN(r)?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:dHi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(_H,{variant:`fill`})]}):r&&ON(r)?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:dHi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(gH,{variant:`fill`,resource:`processors`})]}):!n&&t?.isWorkflow?(0,K.jsx)(kv,{to:`/workflows/${e}/graph`,replace:!0}):n?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:dHi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(NS,{className:`mb-4 h-8 w-48`}),(0,K.jsx)(NS,{className:`h-32 w-full`})]}):(0,K.jsxs)(MS,{variant:`fit`,breadcrumbs:(0,K.jsx)(uN,{crumbs:dHi}),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)(cHi,{processorId:e})})]})}function pHi(){let e=aFi(),{data:t,isLoading:n}=CPn({toolId:e}),{mutateAsync:r,status:i,data:a,error:o}=wPn(),s={execute:(t,n)=>r({toolId:e,input:t,requestContext:n}),status:i,output:a,error:o};return n?(0,K.jsx)(dQ.LoadingData,{}):t?(0,K.jsx)(VVi,{tool:t,execution:s,requestContextEntityType:`tool`,requestContextEntityId:t.id}):(0,K.jsxs)(dQ.NoData,{children:[`Tool "`,e,`" not found.`]})}var mHi=()=>(0,K.jsx)(Hx,{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)(qN,{}),children:`Tools documentation`}),variant:`fill`}),hHi=(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())},gHi={name:e=>e.id,agents:e=>e.agents.length};function _Hi({tools:e,agents:t,isLoading:n,search:r=``,sort:i,onSortChange:a,selectedToolId:o}){let{paths:s,Link:c}=sn(),l=(0,G.useMemo)(()=>hHi(e,t),[e,t]),u=(0,G.useMemo)(()=>AZ(l.filter(e=>e.id.toLowerCase().includes(r.toLowerCase())),i,gHi),[l,r,i]),{containerRef:d,getRowProps:f}=OZ({count:u.length,global:!0});if(n)return(0,K.jsx)(yH,{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)(PN,{}),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=rJ(e.id,50),r=rJ(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=[KN(`/tools`)];function vHi(){let{data:e={},isLoading:t,error:n}=gN(),{data:r={},isLoading:i,error:a}=Dq(),[o,s]=(0,G.useState)(``),[c,l]=(0,G.useState)(),{toolId:u}=MFi(),d=t||i,f=a||n;return f&&DN(f)?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:$9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Tools`}),(0,K.jsx)(_H,{variant:`fill`})]}):f&&ON(f)?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:$9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Tools`}),(0,K.jsx)(gH,{variant:`fill`,resource:`tools`})]}):f?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:$9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Tools`}),(0,K.jsx)(Hx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load tools`,descriptionSlot:f.message})]}):Object.keys(r).length===0&&!d?(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:$9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Tools`}),(0,K.jsx)(mHi,{})]}):(0,K.jsxs)(MS,{breadcrumbs:(0,K.jsx)(uN,{crumbs:$9}),actionRow:(0,K.jsx)(_K,{children:(0,K.jsx)(_K.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(wH,{...TH,onValueChange:s,label:`Search tools`,placeholder:`Search by name`})})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Tools`}),(0,K.jsx)(_Hi,{tools:r,agents:e,isLoading:d,search:o,sort:c,onSortChange:(e,t)=>l({key:t,direction:e}),selectedToolId:u}),(0,K.jsx)(NFi,{children:(0,K.jsx)(pHi,{})})]})}var yHi=()=>{let e=Tv();return(0,K.jsx)(on,{Link:cS,navigate:t=>e(t),paths:gK,children:(0,K.jsxs)(en,{children:[(0,K.jsx)(QVi,{}),(0,K.jsx)(ZVi,{children:(0,K.jsx)(hVi,{children:(0,K.jsx)(nJe,{children:(0,K.jsx)(Av,{})})})})]})})},bHi=()=>{let e=Tv();return(0,K.jsx)(on,{Link:cS,navigate:t=>e(t),paths:gK,children:(0,K.jsx)(gVi,{children:(0,K.jsx)(Av,{})})})},xHi=!!window.MASTRA_CLOUD_API_ENDPOINT,SHi=At.has(`datasets`),CHi=[{index:!0,element:(0,K.jsx)(kui,{})},{path:`instruction-blocks`,element:(0,K.jsx)(Aui,{})},{path:`tools`,element:(0,K.jsx)(Pui,{})},{path:`agents`,element:(0,K.jsx)(xui,{})},{path:`scorers`,element:(0,K.jsx)(Mui,{})},{path:`workflows`,element:(0,K.jsx)(Iui,{})},{path:`skills`,element:(0,K.jsx)(Nui,{})},{path:`memory`,element:(0,K.jsx)(jui,{})},{path:`variables`,element:(0,K.jsx)(Fui,{})}],wHi=[{element:(0,K.jsx)(bBi,{}),children:[{path:`/login`,element:(0,K.jsx)(dMi,{})},{path:`/signup`,element:(0,K.jsx)(kIi,{})}]},{path:`/agent-builder`,element:(0,K.jsx)(Xqe,{paths:gK}),children:[{index:!0,element:(0,K.jsx)(XDn,{})},{path:`agents`,element:(0,K.jsx)(Z9,{}),children:[{index:!0,element:(0,K.jsx)(SPn,{})}]},{path:`agents`,element:(0,K.jsx)(kVi,{}),children:[{path:`create`,element:(0,K.jsx)(FPn,{})},{path:`:id`,loader:({params:e})=>U_(`/agent-builder/agents/${e.id}/view`)},{path:`:id/edit`,element:(0,K.jsx)(y8n,{})},{path:`:id/view`,element:(0,K.jsx)(A5n,{})}]},{path:`skills`,element:(0,K.jsx)(Z9,{}),children:[{index:!0,element:(0,K.jsx)(j7n,{})}]},{path:`skills`,element:(0,K.jsx)(kVi,{}),children:[{path:`create`,element:(0,K.jsx)(F7n,{})},{path:`:id`,loader:({params:e})=>U_(`/agent-builder/skills/${e.id}/edit`)},{path:`:id/edit`,element:(0,K.jsx)(s9n,{})},{path:`:id/view`,element:(0,K.jsx)(h9n,{})}]},{path:`infrastructure`,element:(0,K.jsx)(Z9,{}),children:[{index:!0,element:(0,K.jsx)(y7n,{})}]},{path:`favorite`,element:(0,K.jsx)(Z9,{}),children:[{index:!0,element:(0,K.jsx)(V5n,{})}]},{path:`library`,element:(0,K.jsx)(Z9,{}),children:[{index:!0,element:(0,K.jsx)(b7n,{})}]}]},{element:(0,K.jsx)(bHi,{}),children:[{path:`/agents/:agentId/session`,element:(0,K.jsx)(o1r,{})},{path:`/agents/:agentId/session/:threadId`,element:(0,K.jsx)(o1r,{})}]},{element:(0,K.jsx)(yHi,{}),children:[...xHi?[]:[{path:`/settings`,element:(0,K.jsx)(OIi,{})},{path:`/templates`,element:(0,K.jsx)(RLi,{})},{path:`/templates/:templateSlug`,element:(0,K.jsx)(tRi,{})}],{path:`/logs`,element:(0,K.jsx)(dNi,{})},{path:`/scorers`,element:(0,K.jsx)(uIi,{})},{path:`/scorers/:scorerId`,element:(0,K.jsx)(vIi,{})},{path:`/metrics`,element:(0,K.jsx)(QFi,{})},{path:`/intelligence`,element:(0,K.jsx)(Khn,{})},{path:`/intelligence/entities/:entityType/:entityId`,element:(0,K.jsx)(hgn,{})},{element:(0,K.jsx)(tHi,{children:(0,K.jsx)(Av,{})}),children:[{path:`/traces`,element:(0,K.jsx)(yui,{})},{path:`/spans`,element:(0,K.jsx)(_Li,{})},{path:`/threads`,element:(0,K.jsx)(hRi,{})}]},{path:`/traces/:traceId`,loader:({params:e,request:t})=>{let n=new URL(t.url).searchParams;return n.set(`traceId`,e.traceId??``),U_(`/traces?${n.toString()}`)}},{path:`/observability`,loader:({request:e})=>U_(`/traces${new URL(e.url).search}`)},{path:`/resources`,element:(0,K.jsx)(cIi,{})},{path:`/agents`,element:(0,K.jsx)(Y9n,{})},{path:`/cms/agents/create`,element:(0,K.jsx)(Cui,{}),children:CHi},{path:`/cms/agents/:agentId/edit`,element:(0,K.jsx)(Oui,{}),children:CHi},{path:`/cms/scorers/create`,element:(0,K.jsx)(Gui,{})},{path:`/cms/scorers/:scorerId/edit`,element:(0,K.jsx)(Yui,{})},{path:`/prompts`,element:(0,K.jsx)(iIi,{})},{path:`/cms/prompts/create`,element:(0,K.jsx)(Rui,{})},{path:`/cms/prompts/:promptBlockId/edit`,element:(0,K.jsx)(Uui,{})},{path:`/agents/:agentId`,element:(0,K.jsx)(qVi,{children:(0,K.jsx)(Av,{})}),children:[{index:!0,loader:UDn},{path:`chat`,loader:WDn},{path:`chat/:threadId`,loader:WDn},{path:`threads`,loader:HDn},{path:`threads/:threadId`,element:(0,K.jsx)(V0r,{})},{path:`overview`,loader:KDn},{path:`settings`,loader:KDn},...SHi?[{path:`editor`,element:(0,K.jsx)(T2r,{})}]:[],{path:`traces`,element:(0,K.jsx)(bui,{})},{path:`channels`,loader:({params:e})=>U_(`/agents/${e.agentId}/threads/new`)}]},{path:`/tools`,element:(0,K.jsx)(vHi,{})},{path:`/integrations`,element:(0,K.jsx)(_Di,{})},{path:`/connections`,element:(0,K.jsx)(Xdi,{})},{path:`/processors`,element:(0,K.jsx)(oHi,{})},{path:`/processors/:processorId`,element:(0,K.jsx)(fHi,{})},{path:`/mcps`,element:(0,K.jsx)(jNi,{})},{path:`/mcps/:serverId`,element:(0,K.jsx)(PFi,{})},{path:`/workspaces`,element:(0,K.jsx)(_Bi,{})},{path:`/workspaces/:workspaceId`,element:(0,K.jsx)(_Bi,{})},{path:`/workspaces/:workspaceId/skills/:skillName`,loader:({params:e,request:t})=>U_(hK(e.workspaceId,new URL(t.url).searchParams.get(`path`)))},{path:`/workflows`,element:(0,K.jsx)(ORi,{})},{path:`/workflows/schedules`,element:(0,K.jsx)(KRi,{})},{path:`/workflows/schedules/:scheduleId`,element:(0,K.jsx)(BRi,{})},{path:`/workflows/:workflowId`,element:(0,K.jsx)(XMt,{children:(0,K.jsx)(Av,{})}),children:[{index:!0,loader:({params:e})=>U_(`/workflows/${e.workflowId}/graph`)},{path:`graph`,element:(0,K.jsx)(pzi,{})},{path:`graph/:runId`,element:(0,K.jsx)(pzi,{})},{path:`traces`,element:(0,K.jsx)(hzi,{})},{path:`schedules`,element:(0,K.jsx)(mzi,{})}]},{path:`/knowledge`,element:(0,K.jsx)(cMi,{})},...SHi?[{path:`/datasets`,element:(0,K.jsx)(jfi,{})},{path:`/datasets/:datasetId`,element:(0,K.jsx)(svi,{}),children:[{path:`items/:itemId`,element:null}]},{path:`/datasets/:datasetId/edit`,element:(0,K.jsx)(mvi,{})},{path:`/datasets/:datasetId/items/:itemId/versions`,element:(0,K.jsx)(yvi,{})},{path:`/experiments`,element:(0,K.jsx)(pbi,{})},{path:`/experiments/compare`,element:(0,K.jsx)(Obi,{})},{path:`/experiments/review-queue`,element:(0,K.jsx)(oDi,{})},{path:`/experiments/:experimentId`,element:(0,K.jsx)(HEi,{}),children:[{path:`items/:itemId`,element:null}]},{path:`/datasets/:datasetId/versions`,element:(0,K.jsx)(Cvi,{})}]:[],{index:!0,element:(0,K.jsx)(JDn,{})}]}];function THi(){let e=window.MASTRA_STUDIO_BASE_PATH||``,{baseUrl:t,headers:n,apiPrefix:r,isLoading:i}=pS(),a=(0,G.useMemo)(()=>t?AFe(t,r):void 0,[t,r]),o=(0,G.useMemo)(()=>({...n,"x-mastra-client-type":`studio`}),[n]),s=(0,G.useMemo)(()=>Kze(wHi,{basename:e}),[e]);return i?(0,K.jsx)(`div`,{className:`flex h-screen w-full items-center justify-center`,children:(0,K.jsx)(It,{})}):t?(0,K.jsx)(pPe,{baseUrl:t,headers:o,apiPrefix:r,customFetch:a,children:(0,K.jsx)(Kqe,{children:(0,K.jsx)(VDn,{children:(0,K.jsx)(mJe,{baseUrl:t,children:(0,K.jsx)(Eze,{router:s})})})})}):(0,K.jsx)(lHr,{})}function EHi(){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)(Lhn,{children:(0,K.jsx)(pJe,{endpoint:o,defaultApiPrefix:r,children:(0,K.jsx)(THi,{})})})}function DHi(){(0,kt.createRoot)(document.getElementById(`root`)).render((0,K.jsx)(G.StrictMode,{children:(0,K.jsx)(EHi,{})}))}export{DHi as startStudio};
|