@mastra/deployer-cloud 1.84.0-alpha.7 → 1.84.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -721,6 +721,6 @@ window.parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/sandbox-proxy-
721
721
  ]`,Ofi=[{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 kfi(){let{isCopied:e,handleCopy:t}=hC({text:Dfi,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:Ofi.map(e=>(0,K.jsxs)(`div`,{className:`grid grid-cols-[7rem_1fr] gap-3 px-3 py-2.5`,children:[(0,K.jsx)(`dt`,{className:H({tone:`ink`,variant:`meta`}),children:(0,K.jsx)(uX,{children:e.name})}),(0,K.jsxs)(`dd`,{className:`flex flex-col items-start gap-1.5 text-muted-foreground`,children:[(0,K.jsx)(T,{as:`span`,variant:`meta`,children:e.description}),e.required?(0,K.jsx)(eC,{variant:`success`,size:`xs`,children:`required`}):(0,K.jsx)(eC,{variant:`neutral`,emphasis:`subtle`,size:`xs`,children:`optional`})]})]},e.name))}),(0,K.jsxs)(`div`,{className:`overflow-hidden rounded-lg border border-border`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between border-b border-border bg-card py-1.5 pr-1.5 pl-3`,children:[(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,font:`mono`,children:`example.json`}),(0,K.jsx)(X,{icon:e?(0,K.jsx)(pC,{}):(0,K.jsx)(mC,{}),variant:`ghost`,size:`sm`,onClick:t,children:e?`Copied`:`Copy`})]}),(0,K.jsx)(bw,{variant:`embedded`,language:`json`,editable:!1,lineNumbers:!1,showCopyButton:!1,value:Dfi,className:`p-3`})]}),(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:Efi,target:`_blank`,rel:`noopener noreferrer`}),className:`self-start`,icon:(0,K.jsx)(tP,{}),children:`Datasets documentation`})]})}var Afi=10,jfi=`[
722
722
  { "input": "…", "groundTruth": "…" }
723
723
  ]`,Mfi=`flex min-h-0 flex-1 flex-col py-0`;function Nfi({tab:e,onTabChange:t,file:n,onFileSelect:r,onReplace:i,pastedText:a,onPastedTextChange:o,validation:s,isImporting:c}){return(0,K.jsxs)(gk,{value:e,defaultTab:`upload`,onValueChange:t,className:`flex h-full flex-col gap-3`,children:[(0,K.jsxs)(hk,{variant:`pill`,children:[(0,K.jsx)(_k,{value:`upload`,children:`Upload file`}),(0,K.jsx)(_k,{value:`paste`,children:`Paste JSON`})]}),(0,K.jsx)(vk,{value:`upload`,className:Mfi,children:n?(0,K.jsx)(Lfi,{file:n,validation:s,onReplace:i,isImporting:c}):(0,K.jsx)(Pfi,{onFileSelect:r,disabled:c})}),(0,K.jsx)(vk,{value:`paste`,className:Mfi,children:(0,K.jsx)(bw,{"aria-label":`JSON items`,language:`json`,lineNumbers:!1,showCopyButton:!1,placeholder:jfi,value:a,onChange:o,editable:!c,className:`min-h-50 flex-1`})})]})}function Pfi({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)(dfi,{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 `,Hli]})]})}function Ffi(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`}function Ifi(e){return typeof e==`string`?e:JSON.stringify(e)??``}function Lfi({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,Afi);return(0,K.jsxs)(`div`,{"data-testid":`json-file-card`,className:`rounded-lg border border-border`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2`,children:[(0,K.jsx)(xk,{className:`size-icon-md shrink-0 text-muted-foreground`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`ink`,font:`mono`,className:`min-w-0 flex-1 truncate`,children:e.name}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`shrink-0`,children:Ffi(e.size)}),(0,K.jsx)(X,{icon:(0,K.jsx)(xS,{}),variant:`ghost`,size:`sm`,onClick:n,disabled:r,children:`Replace`})]}),o.map(e=>(0,K.jsxs)(`div`,{className:`grid grid-cols-[2rem_1fr_auto] items-center gap-2 border-t border-border px-3 py-1.5`,children:[(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:e.index}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`ink`,font:`mono`,className:`truncate`,children:Ifi(e.input)}),e.hasInput?e.hasGroundTruth?null:(0,K.jsx)(eC,{variant:`warning`,size:`xs`,children:`no groundTruth`}):(0,K.jsx)(eC,{variant:`destructive`,size:`xs`,children:`no input`})]},e.index)),a>Afi&&(0,K.jsxs)(T,{as:`p`,variant:`meta`,tone:`muted`,className:`border-t border-border px-3 py-1.5`,children:[`+ `,a-Afi,` more`]})]})}var Rfi=e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsText(e)});function zfi({datasetId:e,datasetName:t,open:n,onOpenChange:r,onSuccess:i}){let[a,o]=(0,G.useState)(`upload`),[s,c]=(0,G.useState)(null),[l,u]=(0,G.useState)(``),[d,f]=(0,G.useState)(null),[p,m]=(0,G.useState)(``),[h,g]=(0,G.useState)(!1),_=(0,G.useRef)(0),v=(0,G.useRef)(void 0),y=(0,G.useRef)(!1),{batchInsertItems:b}=ON(),x=a===`upload`?l:p,S=(0,G.useMemo)(()=>a===`upload`&&d?{status:`error`,kind:`parse`,message:d}:Gli(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 ${Hli}`);else try{let n=await Rfi(e);if(t!==_.current)return;c({name:e.name,size:e.size}),u(n),f(null)}catch{if(t!==_.current)return;f(`Could not read the file`)}},[]),w=(0,G.useCallback)(()=>{_.current++,c(null),u(``),f(null)},[]),T=(0,G.useCallback)(()=>{_.current++,o(`upload`),c(null),u(``),f(null),m(``)},[]),E=(0,G.useCallback)(()=>{clearTimeout(v.current),y.current&&(v.current=setTimeout(T,150))},[T]);(0,G.useEffect)(()=>(y.current=!0,()=>{y.current=!1,clearTimeout(v.current)}),[]);let D=(0,G.useCallback)(()=>{r(!1),E()},[r,E]),O=(0,G.useCallback)(async()=>{if(S.status===`ready`){g(!0);try{await b.mutateAsync({datasetId:e,items:S.items}),iS.success(`Imported ${S.total} item${S.total===1?``:`s`}`),i?.(),r(!1),E()}catch(e){iS.error(e instanceof Error?e.message:`Failed to import items`)}finally{g(!1)}}},[S,b,e,i,r,E]);return(0,K.jsx)(nT,{open:n,onOpenChange:D,pending:h,children:(0,K.jsxs)(rT,{size:`xl`,children:[(0,K.jsxs)(iT,{children:[(0,K.jsx)(sT,{children:`Import into dataset`}),(0,K.jsxs)(cT,{children:[`Add items to `,t?(0,K.jsx)(`span`,{className:`text-foreground`,children:t}):`this dataset`,` from a JSON file or paste them directly.`]})]}),(0,K.jsx)(oT,{flush:!0,children:(0,K.jsxs)(`div`,{className:`grid divide-y divide-border md:grid-cols-[1.15fr_1fr] md:divide-x md:divide-y-0`,children:[(0,K.jsx)(`div`,{className:`flex min-h-[360px] flex-col p-4`,children:(0,K.jsx)(Nfi,{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)(kfi,{})})]})}),(0,K.jsxs)(aT,{children:[(0,K.jsx)(Bfi,{validation:S}),(0,K.jsx)(lT,{children:`Cancel`}),(0,K.jsxs)(tT,{onConfirm:O,disabled:S.status!==`ready`,children:[h&&(0,K.jsx)(It,{}),S.status===`ready`?`Import ${S.total} item${S.total===1?``:`s`}`:`Import`]})]})]})})}function Bfi({validation:e}){let t=c(`size-1.5 shrink-0 rounded-full`,e.status===`idle`&&`bg-muted-foreground`,e.status===`ready`&&`bg-success-indicator`,e.status===`error`&&`bg-destructive-indicator`),n;switch(e.status){case`idle`:n=`No items yet`;break;case`ready`:n=(0,K.jsxs)(AC,{singleLine:!0,children:[(0,K.jsxs)(AC.Item,{className:`shrink-0`,children:[(0,K.jsx)(T,{as:`b`,variant:`label`,tone:`ink`,children:e.total}),` `,`item`,e.total===1?``:`s`,` ready`]}),e.missingGroundTruthCount>0&&(0,K.jsxs)(AC.Item,{children:[e.missingGroundTruthCount,` without groundTruth`]})]});break;case`error`:switch(e.kind){case`parse`:n=`Not valid JSON: ${e.message}`;break;case`not-array`:n=`Top level must be an array of items`;break;case`empty`:n=`The array has no items`;break;case`too-large`:n=`JSON is larger than ${Hli}`;break;case`missing-input`:n=(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`b`,variant:`label`,tone:`ink`,children:e.missingInputCount}),` `,`of `,e.total,` item`,e.total===1?``:`s`,` `,e.missingInputCount===1?`has`:`have`,` no`,` `,(0,K.jsx)(uX,{children:`input`})]})}}return(0,K.jsxs)(`div`,{role:`status`,className:`mr-auto flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(`span`,{className:t}),(0,K.jsx)(T,{tone:`muted`,as:`span`,variant:`caption`,className:`truncate`,children:n})]})}function Vfi(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 Hfi({active:e,onPrevious:t,onNext:n,onClose:r}){(0,G.useEffect)(()=>{if(!e)return;let i=e=>{e.defaultPrevented||Vfi(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 Ufi=(0,G.createContext)(null);function Wfi({datasetId:e,items:t,isLoadingItems:n,children:r}){let i=Ov(),a=SRe(`/datasets/:datasetId/items/:itemId`)?.params.itemId,o=(0,G.useCallback)(t=>{i(`/datasets/${e}/items/${encodeURIComponent(t)}`)},[i,e]),s=(0,G.useCallback)(()=>{i(`/datasets/${e}`)},[i,e]),c=(0,G.useMemo)(()=>a?t.findIndex(e=>e.id===a):-1,[t,a]),l=(0,G.useMemo)(()=>{if(c<=0)return;let e=t[c-1].id;return()=>o(e)},[c,t,o]),u=(0,G.useMemo)(()=>{if(c<0||c>=t.length-1)return;let e=t[c+1].id;return()=>o(e)},[c,t,o]);Hfi({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)(Ufi.Provider,{value:d,children:r})}function Gfi(){let e=(0,G.useContext)(Ufi);if(!e)throw Error(`useDatasetItemPanel must be used within a DatasetItemPanelProvider`);return e}var Kfi=[`createdAt`];function qfi({datasetId:e,onAddItemClick:t,onNavigateToDataset:n,toolbarActionsSlot:r}){let[i,a]=Rv(),{activeVersion:o}=MN(i,a),{sort:s,onSortChange:c}=u7({searchParams:i,setSearchParams:a,allowedKeys:Kfi}),l=(0,G.useMemo)(()=>s?{field:s.key,direction:s.direction===`asc`?`ASC`:`DESC`}:void 0,[s]),[u,d]=(0,G.useState)(!1),[f,p]=(0,G.useState)(!1),[m,h]=(0,G.useState)(!1),[g,_]=(0,G.useState)([]),[v,y]=(0,G.useState)(!1),[b,x]=(0,G.useState)([]),[S,C]=(0,G.useState)(!1),[w,T]=(0,G.useState)([]),[E,D]=(0,G.useState)(0),[O,k]=(0,G.useState)(``),[A]=lC(O,300),{data:j}=AN({datasetId:e,queryOptions:{enabled:!!e}}),{data:M=[],isLoading:N,setEndOfListElement:P,isFetchingNextPage:F,hasNextPage:I}=DN({datasetId:e,search:A||void 0,version:o,orderBy:l,queryOptions:{enabled:!!e}}),{deleteItems:L}=ON(),{currentItemId:R,openItem:z,close:B}=Gfi();return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`grid h-full overflow-auto`,children:(0,K.jsx)(Tfi,{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)(gfi,{datasetId:e,open:u,onOpenChange:d}),(0,K.jsx)(zfi,{datasetId:e,datasetName:j?.name,open:f,onOpenChange:p}),(0,K.jsx)(eui,{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)(tui,{open:v,onOpenChange:e=>{y(e),e||(x([]),D(e=>e+1))},items:b,currentDatasetId:e}),(0,K.jsx)(QM,{open:S,onOpenChange:C,children:(0,K.jsxs)(QM.Content,{children:[(0,K.jsxs)(QM.Header,{children:[(0,K.jsx)(QM.Title,{children:`Delete Items`}),(0,K.jsxs)(QM.Description,{children:[`Are you sure you want to delete `,w.length,` item`,w.length===1?``:`s`,`? This action cannot be undone.`]})]}),(0,K.jsxs)(QM.Footer,{children:[(0,K.jsx)(QM.Cancel,{children:`Cancel`}),(0,K.jsx)(QM.Action,{onClick:async()=>{await L.mutateAsync({datasetId:e,itemIds:w}),iS.success(`Deleted ${w.length} items`),C(!1),T([]),D(e=>e+1)},children:L.isPending?`Deleting...`:`Delete`})]})]})})]})}var Jfi=`__create_tag__`;function Yfi({datasetId:e}){let{data:t}=AN({datasetId:e,queryOptions:{enabled:!!e}}),{data:n}=kN(),{updateDataset:r}=ON(),[i,a]=(0,G.useState)(``),o=(0,G.useMemo)(()=>Array.isArray(t?.tags)?t.tags:[],[t?.tags]),s=(0,G.useMemo)(()=>tli(n?.datasets??[]),[n?.datasets]),c=(0,G.useMemo)(()=>{let e=s.map(e=>({label:e,value:e,end:o.includes(e)?(0,K.jsx)(pC,{"data-testid":`tag-applied`,className:`size-icon-sm`}):void 0})),t=i.trim();return t.length>0&&!s.includes(t)&&!o.includes(t)?[{label:`Create "${t}"`,value:Jfi},...e]:e},[s,o,i]),l=t=>{r.mutate({datasetId:e,tags:t},{onError:()=>iS.error(`Failed to update tags`)})},u=e=>{let t=e===Jfi?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)(rli,{value:e,size:`md`,className:`gap-1 pr-1`,children:[e,(0,K.jsx)(`button`,{type:`button`,"aria-label":`Remove tag ${e}`,disabled:r.isPending,onClick:()=>d(e),className:`cursor-pointer rounded-sm hover:opacity-70 disabled:opacity-50`,children:(0,K.jsx)(xw,{className:`size-icon-xs`})})]},e)),(0,K.jsx)(_N,{options:c,value:void 0,onValueChange:u,onInputValueChange:a,placeholder:`Add tag`,searchPlaceholder:`Search or create tag`,emptyText:`Type to create a tag`,variant:`ghost`,size:`sm`,className:`w-auto min-w-0`,disabled:r.isPending})]})}var F7=e=>JSON.stringify(e??null,null,2),Xfi=e=>e==null||e===``||typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0,Zfi=[{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=>Xfi(e.groundTruth)?void 0:F7(e.groundTruth),payload:e=>Xfi(e.groundTruth)?null:e.groundTruth},{key:`expectedTrajectory`,title:`Expected Trajectory`,icon:(0,K.jsx)(Emn,{}),value:e=>e.expectedTrajectory==null?void 0:F7(e.expectedTrajectory)},{key:`toolMocks`,title:`Tool Mocks`,icon:(0,K.jsx)(YS,{}),value:e=>e.toolMocks?.length?F7(e.toolMocks):void 0},{key:`requestContext`,title:`Request Context`,icon:(0,K.jsx)(JS,{}),value:e=>e.requestContext==null?void 0:F7(e.requestContext)},{key:`metadata`,title:`Metadata`,icon:(0,K.jsx)(wX,{}),value:e=>F7(e.metadata)}],Qfi=e=>e.toFixed(2);function $fi({delta:e,format:t=Qfi,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)(MIr,{}):null})]}),u=c(`inline-flex items-center gap-1 tabular-nums`,i);return s?(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{render:(0,K.jsx)(`span`,{tabIndex:0,className:u}),children:l}),(0,K.jsx)(Tx,{children:o})]}):(0,K.jsx)(`span`,{className:u,children:l})}function epi({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 tpi({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)($fi,{delta:a,format:o,higherIsBetter:l,baseline:s==null?void 0:s-a})})]},e))})}function I7({value:e}){return(0,K.jsx)(`div`,{className:`min-w-0 p-3 text-foreground`,children:typeof e==`string`?(0,K.jsx)(xY,{children:e}):(0,K.jsx)(bw,{value:JSON.stringify(e??null,null,2),language:`json`,editable:!1,lineNumbers:!1,showCopyButton:!1,variant:`embedded`,"aria-label":`JSON payload`})})}var npi=`grid content-start gap-5`;function L7({title:e,actions:t,tone:n=`default`,collapsible:r=!0,framed:i=!1,expanded:a,onExpandedChange:o,children:s}){let l=i$({collapsedHeight:160}),u=a===void 0||!o?l:{...l,isExpanded:a,setExpanded:o,toggleExpanded:()=>o(!a)},d=r?(0,K.jsx)(r$,{state:u,expandLabel:`Expand`,children:s}):s;return(0,K.jsxs)(`section`,{className:`grid min-w-0 gap-2`,children:[(0,K.jsxs)(`div`,{className:`flex h-7 items-center justify-between gap-2`,children:[(0,K.jsx)(jQ.SectionHeading,{className:c(n===`negative`&&`text-destructive-foreground`),children:e}),(0,K.jsx)(`div`,{className:`ml-auto flex items-center gap-1`,children:t})]}),(0,K.jsxs)(`div`,{role:`region`,"aria-label":e,className:`min-w-0`,children:[i?n===`negative`?(0,K.jsx)(`div`,{className:`min-w-0 overflow-hidden rounded-lg border border-destructive-edge bg-destructive-subtle`,children:d}):(0,K.jsx)(nP,{className:`min-w-0 overflow-hidden`,children:d}):d,r&&u.isExpanded&&u.isClipped&&(0,K.jsx)(`div`,{className:`flex justify-center pt-1`,children:(0,K.jsx)(X,{size:`sm`,variant:`ghost`,icon:(0,K.jsx)(hZ,{}),onClick:()=>u.setExpanded(!1),children:`Collapse`})})]})]})}function rpi({item:e,diff:t}){return(0,K.jsxs)(`div`,{className:npi,children:[(0,K.jsx)(tpi,{metrics:ipi(e)}),Zfi.map(n=>{if(n.payload&&!t){let t=n.payload(e);return t==null?null:(0,K.jsx)(L7,{title:n.title,framed:!0,actions:(0,K.jsx)(gC,{content:typeof t==`string`?t:JSON.stringify(t,null,2)}),children:(0,K.jsx)(I7,{value:t})},n.key)}let r=n.value(e),i=t?n.value(t.against):void 0;return r===void 0&&i===void 0?null:r===void 0?(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,K.jsx)(jQ.SectionHeading,{icon:n.icon,children:n.title}),(0,K.jsx)(T,{as:`p`,variant:`body`,tone:`muted`,children:`Not set in this version`})]},n.key):(0,K.jsx)(jQ.CodeSection,{title:n.title,icon:n.icon,codeStr:r,diff:t?{against:i??``,side:t.side}:void 0},n.key)})]})}function ipi(e){let t=e.updatedAt&&new Date(e.updatedAt).getTime()!==new Date(e.createdAt).getTime(),n=[{id:`item-id`,icon:(0,K.jsx)(W6,{}),label:`Item Id`,value:(0,K.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,K.jsx)(`span`,{className:`font-mono`,title:e.id,children:aH(e.id)}),(0,K.jsx)(gC,{content:e.id,tooltip:`Copy item ID to clipboard`,variant:`link`})]}),delta:null},{id:`created`,icon:(0,K.jsx)($j,{}),label:`Created`,value:bC(e.createdAt,`date-time`),delta:null}];return t&&n.push({id:`updated`,icon:(0,K.jsx)(qS,{}),label:`Updated`,value:bC(e.updatedAt,`date-time`),delta:null}),n}function api({field:e,errors:t}){return t.length===0?null:(0,K.jsx)(lk,{children:(0,K.jsx)(`span`,{className:`space-y-1`,children:t.map(t=>(0,K.jsxs)(`span`,{className:`block`,children:[(0,K.jsxs)(`code`,{className:`rounded bg-destructive-subtle px-1`,children:[e,t.path===`/`?``:t.path]}),`: `,t.message]},`${t.path}:${t.message}`))})})}function opi({inputValue:e,setInputValue:t,groundTruthValue:n,setGroundTruthValue:r,metadataValue:i,setMetadataValue:a,trajectoryValue:o,setTrajectoryValue:s,toolMocksValue:c,setToolMocksValue:l,requestContextValue:u,setRequestContextValue:d,validationErrors:f,onSave:p,onCancel:m,isSaving:h}){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`mb-4`,children:(0,K.jsxs)(T,{as:`h3`,variant:`heading`,className:`flex items-center gap-2`,children:[(0,K.jsx)(iH,{className:`size-icon-lg`}),` Edit Item`]})}),(0,K.jsxs)(`div`,{className:`space-y-6`,children:[(0,K.jsxs)(ak,{invalid:f?.field===`input`,children:[(0,K.jsx)(sk,{required:!0,children:`Input (JSON)`}),(0,K.jsx)(bw,{value:e,onChange:t,showCopyButton:!1,className:`min-h-[120px]`}),f?.field===`input`&&(0,K.jsx)(api,{field:`input`,errors:f.errors})]}),(0,K.jsxs)(ak,{invalid:f?.field===`groundTruth`,children:[(0,K.jsx)(sk,{children:`Ground Truth (JSON, optional)`}),(0,K.jsx)(bw,{value:n,onChange:r,showCopyButton:!1,className:`min-h-[100px]`}),f?.field===`groundTruth`&&(0,K.jsx)(api,{field:`groundTruth`,errors:f.errors})]}),(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{children:`Expected Trajectory (JSON, optional)`}),(0,K.jsx)(bw,{value:o,onChange:s,showCopyButton:!1,className:`min-h-[80px]`})]}),(0,K.jsxs)(ak,{invalid:f?.field===`toolMocks`,children:[(0,K.jsx)(sk,{children:`Tool Mocks (JSON array, optional)`}),(0,K.jsxs)(ck,{children:[`Ordered static mocks served in place of executing the tool. Each entry is`,` `,(0,K.jsx)(`code`,{children:`{ "toolName", "args", "output" }`}),`. Calling a mocked tool with non-matching args fails the item; unmocked tools run live.`]}),(0,K.jsx)(bw,{value:c,onChange:l,showCopyButton:!1,className:`min-h-[100px]`}),f?.field===`toolMocks`&&(0,K.jsx)(api,{field:`toolMocks`,errors:f.errors})]}),(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{children:`Request Context (JSON, optional)`}),(0,K.jsx)(bw,{value:u,onChange:d,showCopyButton:!1,className:`min-h-[80px]`})]}),(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{children:`Metadata (JSON, optional)`}),(0,K.jsx)(bw,{value:i,onChange:a,showCopyButton:!1,className:`min-h-[80px]`})]}),(0,K.jsxs)(`div`,{className:`flex gap-2 pt-4`,children:[(0,K.jsx)(X,{icon:(0,K.jsx)(pC,{}),variant:`primary`,onClick:p,disabled:h,children:h?`Saving...`:`Save changes`}),(0,K.jsx)(X,{icon:(0,K.jsx)(xw,{}),onClick:m,disabled:h,children:`Cancel`})]})]})]})}function spi(){return(0,K.jsxs)(OC,{className:`inline-flex h-control-md w-fit cursor-pointer items-center gap-1.5 rounded-sm text-label text-muted-foreground focus-visible:outline-offset-2`,children:[(0,K.jsx)(y,{direction:`right`,className:`-mr-0.5 -ml-[4.3px] size-icon-md in-aria-expanded:translate-x-[2px]`}),`Advanced`]})}function cpi({provider:e,modelId:t,canReset:n,onProviderChange:r,onModelIdChange:i,onReset:a,container:o}){let s=uS(),{isLoading:c}=Aq(),[l,u]=(0,G.useState)(!1);return s.active&&s.pickerVisible===!1?(0,K.jsxs)(uk,{className:`gap-2`,children:[(0,K.jsx)(dk,{children:`Model`}),(0,K.jsx)(`div`,{children:(0,K.jsx)(eC,{icon:(0,K.jsx)(CH,{}),children:`Locked by admin`})})]}):(0,K.jsxs)(uk,{className:`gap-2`,children:[(0,K.jsx)(dk,{children:`Model`}),c?(0,K.jsx)(zS,{className:`h-control-md w-60 rounded-full`}):(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsxs)($V,{className:`min-w-0`,children:[(0,K.jsx)(Mq,{value:e,onValueChange:e=>{r(e),u(!0)},container:o,"aria-label":`Model provider`,className:`w-auto min-w-0 shrink-0 gap-1 px-3`}),(0,K.jsx)(Nq,{llmId:e,value:t,onValueChange:i,open:l,onOpenChange:u,container:o,disabled:!e,"aria-label":`Model`,className:`w-auto min-w-0 gap-1 px-3`})]}),n&&(0,K.jsx)(X,{variant:`ghost`,size:`icon-md`,tooltip:`Use the agent's model`,onClick:a,children:(0,K.jsx)(vS,{})})]})]})}var lpi=(e,t)=>`${e}:${t}`,upi=(e,t)=>e?.value===t?.value;function dpi({datasets:e,datasetId:t,version:n,onDatasetChange:r,container:i}){let{total:a}=DN({datasetId:t,search:void 0,version:n,queryOptions:{enabled:!!t}}),o=e.find(e=>e.value===t)??null;return(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{required:!0,info:`The items to run. Each item's input goes to the target. Runs on the latest version unless you pick one under Advanced.`,children:`Dataset`}),(0,K.jsxs)(fN,{items:e,value:o,onValueChange:e=>e&&r(e.value),isItemEqualToValue:upi,autoHighlight:!0,children:[(0,K.jsx)(GOt,{placeholder:`Select a dataset`,children:a!==void 0&&(0,K.jsxs)(AC,{children:[(0,K.jsxs)(AC.Item,{children:[a,` `,a===1?`item`:`items`]}),(0,K.jsx)(AC.Item,{children:n===void 0?`latest`:`v${n}`})]})}),(0,K.jsxs)(pN,{container:i,children:[(0,K.jsx)(gN,{children:`No datasets found`}),(0,K.jsx)(mN,{children:e=>(0,K.jsx)(hN,{value:e,children:e.label},e.value)})]})]})]})}function fpi(e,t){return t!==void 0||(e??1)>1}function ppi({datasetId:e,version:t,onVersionChange:n,container:r}){let{data:i}=AN({datasetId:e,queryOptions:{enabled:!!e}});return fpi(i?.version,t)?(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{children:`Dataset version`}),(0,K.jsx)(VAt,{datasetId:e,value:t??null,onValueChange:e=>n(e??void 0),container:r})]}):null}function mpi({description:e,onDescriptionChange:t,disabled:n}){return(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{children:`Description`}),(0,K.jsx)(qk,{value:e,onChange:e=>t(e.target.value),placeholder:`Optional`,rows:2,disabled:n})]})}function hpi({name:e,defaultName:t,onNameChange:n,disabled:r}){return(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{children:`Experiment name`}),(0,K.jsx)(Jj,{value:e,placeholder:t,onChange:e=>n(e.target.value),disabled:r})]})}function gpi(e){try{return zO(e)}catch(e){console.error(`Failed to parse requestContextSchema:`,e);return}}function _pi({requestContextSchema:e,onChange:t}){let[n]=(0,G.useState)(()=>gpi(e));return n?(0,K.jsxs)(uk,{children:[(0,K.jsx)(dk,{children:`Request context`}),(0,K.jsx)(XM,{schema:n,onValuesChange:t,className:`[&_button[type=submit]]:hidden`})]}):(0,K.jsx)(`div`,{role:`alert`,children:(0,K.jsx)(Sk,{variant:`destructive`,children:`Failed to parse request context schema`})})}function vpi({schema:e,raw:t,onRawChange:n,onValuesChange:r}){return e?(0,K.jsx)(_pi,{requestContextSchema:e,onChange:r}):(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{children:`Request context (JSON)`}),(0,K.jsx)(bw,{value:t,onChange:n,showCopyButton:!1,"aria-label":`Request context JSON`,className:`min-h-[120px]`})]})}function ypi({onRun:e,canRun:t,isRunning:n}){return(0,K.jsx)(tT,{onConfirm:e,disabled:!t,children:(0,K.jsx)(bpi,{isRunning:n})})}function bpi({isRunning:e}){return e?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(It,{className:`h-4 w-4`}),`Starting…`]}):`Run experiment`}function xpi({scorer:e}){let t=(0,K.jsx)(hN,{value:e,children:e.label});return e.description?(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{render:t}),(0,K.jsx)(Tx,{side:`right`,className:`max-w-64`,children:e.description})]}):t}function Spi(){let{data:e}=VN();return Object.entries(e??{}).filter(([,e])=>e.isRegistered).map(([e,t])=>({value:e,label:t.scorer?.config?.name||e,description:t.scorer?.config?.description||void 0}))}function Cpi(e,t){return e.map(e=>t.find(t=>t.value===e)??{value:e,label:e})}function wpi({scorerIds:e,usesDefaultScorers:t,onScorerIdsChange:n,container:r}){let i=Spi();return(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{info:`Grade each output automatically. Outputs are saved either way, so you can always review them yourself.`,children:`Scorers`}),(0,K.jsxs)(fN,{multiple:!0,items:i,value:Cpi(e,i),onValueChange:e=>n(e.map(e=>e.value)),isItemEqualToValue:upi,autoHighlight:!0,children:[(0,K.jsx)(QOt,{children:(0,K.jsx)(VOt,{children:e=>(0,K.jsxs)(K.Fragment,{children:[e.map(e=>(0,K.jsx)($Ot,{children:e.label},e.value)),(0,K.jsx)(ekt,{placeholder:e.length===0?`No scoring, read the outputs yourself`:void 0})]})})}),(0,K.jsxs)(pN,{container:r,children:[(0,K.jsx)(gN,{children:`No scorers registered`}),(0,K.jsx)(mN,{children:e=>(0,K.jsx)(xpi,{scorer:e},e.value)})]})]}),t&&(0,K.jsx)(ck,{children:`The dataset's default scorers.`})]})}var Tpi=[{type:`agent`,label:`Agents`},{type:`workflow`,label:`Workflows`},{type:`scorer`,label:`Scorers`}];function Epi(e){return Tpi.map(t=>({value:t.label,items:e.filter(e=>e.type===t.type)})).filter(e=>e.items.length>0)}function Dpi({options:e,isLoading:t,target:n,onTargetValueChange:r,container:i,className:a}){return(0,K.jsxs)(ak,{className:a,children:[(0,K.jsx)(sk,{required:!0,info:`What runs on each item: an agent, a workflow, or a scorer you want to test.`,children:`Target`}),(0,K.jsxs)(fN,{items:Epi(e),value:n??null,onValueChange:e=>r(e?.value??``),isItemEqualToValue:upi,disabled:t,autoHighlight:!0,children:[(0,K.jsx)(GOt,{placeholder:`Pick an agent, workflow or scorer`}),(0,K.jsxs)(pN,{container:i,children:[(0,K.jsx)(gN,{children:`Nothing to run`}),(0,K.jsx)(mN,{children:(e,t)=>(0,K.jsxs)(JOt,{items:e.items,children:[t>0?(0,K.jsx)(ZOt,{}):null,(0,K.jsx)(YOt,{children:e.value}),(0,K.jsx)(XOt,{children:e=>(0,K.jsx)(hN,{value:e,children:e.label},e.value)})]},e.value)})]})]})]})}var Opi=(e,t)=>e.provider===t?.provider&&e.modelId===t?.modelId;function kpi(e){let[t,n]=(0,G.useState)(null),r=t??e??{provider:``,modelId:``},i=t?.provider&&t.modelId&&!Opi(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&&!Opi(t,e),agentModel:i}}function Api(e,t){return e||(t[0]?.value??``)}function jpi({initialDatasetId:e,initialDatasetVersion:t}){let{data:n}=kN(),r=(n?.datasets??[]).map(e=>({value:e.id,label:e.name})),[i,a]=(0,G.useState)(e??``),[o,s]=(0,G.useState)(t);return{datasets:r,datasetId:Api(i,r),version:o,setVersion:s,selectDataset:e=>{a(e),s(void 0)}}}function Mpi({initialName:e,targetLabel:t}){let[n,r]=(0,G.useState)(e??``),[i]=(0,G.useState)(csi),a=lsi(t??`experiment`,i);return{name:n,setName:r,defaultName:a,runName:n.trim()||a}}var Npi=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Ppi(e){if(Npi(e)&&Object.keys(e).length!==0)return e}function Fpi(e){try{return{ok:!0,value:JSON.parse(e)}}catch{return{ok:!1}}}function Ipi(e){if(!e.trim())return{ok:!0};let t=Fpi(e);return t.ok?Npi(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 Lpi(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 Rpi(e){let{data:t}=AN({datasetId:e,queryOptions:{enabled:!!e}}),[n,r]=(0,G.useState)(``),[i,a]=(0,G.useState)({}),o=Ppi(t?.requestContextSchema);return{schema:o,raw:n,setRaw:r,setValues:a,resetValues:()=>a({}),resolve:()=>o?Lpi(i):Ipi(n)}}function zpi({datasetId:e,initialScorerIds:t}){let{data:n}=AN({datasetId:e,queryOptions:{enabled:!!e}}),[r,i]=(0,G.useState)(t),a=n?.scorerIds??[];return{scorerIds:r??a,usesDefaultScorers:r===void 0&&a.length>0,setScorerIds:i,resetScorers:()=>i(void 0)}}var Bpi=(e,t,n,r)=>({value:lpi(e,t),label:n,type:e,id:t,defaultModel:r});function Vpi(e,t){if(e&&t)return{provider:MK(e),modelId:t}}function Hpi(){let{data:e,isLoading:t}=wN(),{data:n,isLoading:r}=eN({}),{data:i,isLoading:a}=VN();return{options:[...Object.entries(e??{}).map(([e,t])=>Bpi(`agent`,e,t.name||e,Vpi(t.provider,t.modelId))),...Object.entries(n??{}).map(([e,t])=>Bpi(`workflow`,e,t.name||e)),...Object.entries(i??{}).map(([e,t])=>Bpi(`scorer`,e,t.scorer?.config?.name||e))],isLoading:t||r||a}}function Upi({initialTargetType:e,initialTargetId:t}){return!e||!t?``:lpi(e,t)}function Wpi(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 Gpi(e){let{options:t,isLoading:n}=Hpi(),[r,i]=(0,G.useState)(()=>Upi(e));return{options:t,isLoading:n,target:Wpi(t,r,e),setTargetValue:i}}var Kpi=e=>(e.metaKey||e.ctrlKey)&&e.key===`Enter`,qpi=e=>e.trim()||void 0,Jpi=e=>e.length>0?e:void 0;function Ypi({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=Gpi({initialTargetType:s,initialTargetId:c}),p=jpi({initialDatasetId:i,initialDatasetVersion:a}),m=zpi({datasetId:p.datasetId,initialScorerIds:o}),h=Rpi(p.datasetId),{target:g}=f,_=kpi(g?.defaultModel),v=g?.type===`agent`,y=v?_.agentModel:void 0,b=Mpi({initialName:l,targetLabel:y&&g?`${g.label} ${y.modelId}`:g?.label}),[x,S]=(0,G.useState)(u??``),[C,w]=(0,G.useState)(!1),{triggerExperiment:T}=ON(),{datasetId:E}=p,D=T.isPending,O=h.schema?E:void 0,k=!!(E&&g)&&!f.isLoading&&!D,A=e=>{f.setTargetValue(e),_.reset()},j=e=>{p.selectDataset(e),m.resetScorers(),h.resetValues()},M=async()=>{if(!k||!g)return;let e=h.resolve();if(!e.ok)$x.error(e.message);else try{let n=await T.mutateAsync({datasetId:E,name:b.runName,description:qpi(x),targetType:g.type,targetId:g.id,agentModel:y,scorerIds:Jpi(m.scorerIds),version:p.version,requestContext:e.requestContext});$x.success(`Experiment started`),t(!1),r?.(n.experimentId)}catch(e){$x.error(e instanceof Error?e.message:`Failed to start experiment`)}};return(0,K.jsx)(nT,{open:e,onOpenChange:t,onOpenChangeComplete:n,pending:D,children:(0,K.jsxs)(rT,{ref:d,size:`lg`,onKeyDown:e=>{Kpi(e)&&k&&(e.preventDefault(),M())},children:[(0,K.jsxs)(iT,{children:[(0,K.jsx)(sT,{children:`New experiment`}),(0,K.jsx)(cT,{children:`Run every item in a dataset through an agent, workflow or scorer.`})]}),(0,K.jsx)(oT,{children:(0,K.jsxs)(DC,{open:C,onOpenChange:w,className:`py-3`,children:[(0,K.jsxs)(`div`,{className:`space-y-6`,children:[(0,K.jsx)(hpi,{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)(Dpi,{options:f.options,isLoading:f.isLoading,target:g,onTargetValueChange:A,container:d,className:`min-w-0 flex-1`}),v&&(0,K.jsx)(cpi,{provider:_.provider,modelId:_.modelId,canReset:_.canReset,onProviderChange:_.setProvider,onModelIdChange:_.setModelId,onReset:_.reset,container:d})]}),(0,K.jsx)(dpi,{datasets:p.datasets,datasetId:E,version:p.version,onDatasetChange:j,container:d}),(0,K.jsx)(wpi,{scorerIds:m.scorerIds,usesDefaultScorers:m.usesDefaultScorers,onScorerIdsChange:m.setScorerIds,container:d})]}),(0,K.jsx)(`div`,{className:`mt-6`,children:(0,K.jsx)(spi,{})}),(0,K.jsxs)(kC,{className:`space-y-6 pt-4`,children:[E&&(0,K.jsx)(ppi,{datasetId:E,version:p.version,onVersionChange:p.setVersion,container:d}),(0,K.jsx)(mpi,{description:x,onDescriptionChange:S,disabled:D}),(0,K.jsx)(vpi,{schema:h.schema,raw:h.raw,onRawChange:h.setRaw,onValuesChange:h.setValues},O)]})]})}),(0,K.jsxs)(aT,{children:[(0,K.jsx)(lT,{children:`Cancel`}),(0,K.jsx)(ypi,{onRun:M,canRun:k,isRunning:D})]})]})})}function Xpi({open:e,onOpenChange:t,onSuccess:n,...r}){let[i,a]=(0,G.useState)(0);return(0,K.jsx)(Ypi,{open:e,onOpenChange:t,onOpenChangeComplete:e=>{e||a(e=>e+1)},onSuccess:n,...r},`${i}:${JSON.stringify(r)}`)}var Zpi=`mastra_model_total_input_tokens`,Qpi=`mastra_model_total_output_tokens`,$pi=()=>({estimatedCost:0,costUnits:new Set,hasUnknownCostUnit:!1});function emi(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 tmi(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 nmi(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 rmi=2e3;function imi(e){let t=$pi(),n=new Map;for(let r of e.groups){let e=emi(r);if(!e)continue;tmi(t,e,r);let i=r.dimensions.traceId;i&&tmi(K6(n,i,$pi),e,r)}let r={};for(let[e,t]of n)r[e]=nmi(t);return{summary:nmi(t),traces:r}}var ami=5,omi=e=>!e||Object.keys(e.traces).length===0&&e.summary.inputTokens===void 0&&e.summary.outputTokens===void 0,smi=({experiments:e,supportsMetrics:t})=>{let n=Y(),r=pAt(e.map(e=>e.id));return w_({queries:e.map(({id:e,status:r})=>{let i=r!==`running`&&r!==`pending`;return{queryKey:[`experiment-item-usage`,e,i],queryFn:async()=>imi(await n.getMetricBreakdown({name:[Zpi,Qpi],aggregation:`sum`,groupBy:[`traceId`,`name`],filters:{experimentId:e}})),enabled:t&&i,refetchInterval:e=>omi(e.state.data)&&e.state.dataUpdateCount<ami?rmi:!1}}),combine:r})},cmi=({experimentId:e,experimentStatus:t,supportsMetrics:n,queryOptions:r})=>{let i=Y(),a=!!e&&n,o=T_({queryKey:[`experiment-metrics`,e],refetchInterval:t===`running`||t===`pending`?2e3:!1,queryFn:async()=>{if(!e)throw Error(`experimentId is required`);let t={experimentId:e},[n,r,a]=await Promise.all([i.getMetricAggregate({name:[`mastra_model_total_input_tokens`,`mastra_model_total_output_tokens`],aggregation:`sum`,filters:t}),i.getMetricAggregate({name:[`mastra_agent_duration_ms`],aggregation:`avg`,filters:t}),i.getMetricAggregate({name:[`mastra_agent_duration_ms`],aggregation:`count`,filters:t})]);return{totalTokens:n.value??null,estimatedCost:n.estimatedCost??null,costUnit:n.costUnit??null,avgAgentDurationMs:r.value??null,agentRuns:a.value??null}},...r});return{data:o.data,isLoading:o.isLoading,isEnabled:a}},lmi=({traceId:e,queryOptions:t})=>{let n=Y();return T_({queryKey:[`experiment-trace-light`,e],queryFn:async()=>{if(!e)throw Error(`Trace ID is required`);return n.getTraceLight(e)},...t})};function umi({datasetId:e,target:t,queryOptions:n}){let r=Y(),i={perPage:100};return t?.targetType&&(i.targetType=t.targetType),t?.targetId&&(i.targetId=t.targetId),T_({queryKey:e?[`dataset-experiments`,e,i]:[`experiments`,i],queryFn:()=>e?r.listDatasetExperiments(e,i):r.listExperiments(i),...n})}var dmi=`mastra_agent_duration_ms`,fmi=500,pmi=5e3;function mmi(e){let t=[];for(let n=0;n<e.length;n+=fmi)t.push(e.slice(n,n+fmi));return t}function hmi(e){return e.flatMap(e=>e.status===`fulfilled`?[e.value]:[])}function gmi(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=emi(e);t&&r.has(t)&&n&&tmi(K6(i,t,$pi),n,e)}let a=new Map;for(let[e,t]of i)a.set(e,nmi(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 _mi=({experiments:e,supportsMetrics:t})=>{let n=Y(),r=[...new Set(e.map(e=>e.id))].toSorted(),i=e.some(({status:e})=>e===`running`||e===`pending`);return T_({queryKey:[`experiments-list-metrics`,r],enabled:t&&r.length>0,queryFn:async()=>{let e=mmi(r),[t,i]=await Promise.all([Promise.allSettled(e.map(e=>n.getMetricBreakdown({name:[Zpi,Qpi],aggregation:`sum`,groupBy:[`experimentId`,`name`],filters:{experimentIds:e},limit:e.length*2}))),Promise.allSettled(e.map(e=>n.getMetricBreakdown({name:[dmi],aggregation:`avg`,groupBy:[`experimentId`],filters:{experimentIds:e},limit:e.length})))]);return gmi(r,hmi(t),hmi(i))},placeholderData:__,refetchInterval:i?pmi:!1})};function vmi({datasetId:e,target:t,orderBy:n,queryOptions:r}){let i=Y(),{inView:a,setRef:o}=$M(),s=t?.targetType||void 0,c=t?.targetId||void 0,l=O_({queryKey:e?[`dataset-experiments`,e,`infinite`,{targetType:s,targetId:c,orderBy:n}]:[`experiments`,`infinite`,{targetType:s,targetId:c,orderBy:n}],queryFn:({pageParam:t})=>{let r={page:t,perPage:100};return s&&(r.targetType=s),c&&(r.targetId=c),n&&(r.orderBy=n),e?i.listDatasetExperiments(e,r):i.listExperiments(r)},initialPageParam:0,getNextPageParam:(e,t,n)=>{if(e?.experiments?.length&&e.pagination?.hasMore)return n+1},select:e=>e.pages.flatMap(e=>e?.experiments??[]),...r});return(0,G.useEffect)(()=>{a&&l.hasNextPage&&!l.isFetchingNextPage&&l.fetchNextPage()},[a,l]),{...l,setEndOfListElement:o}}var ymi=(0,G.createContext)(null);function bmi({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:i,hasNextPage:a,children:o}){let s=Ov(),c=SRe(`/experiments/:experimentId/items/:itemId`)?.params.itemId,l=(0,G.useCallback)(t=>{s(`/experiments/${e}/items/${encodeURIComponent(t)}`)},[s,e]),u=(0,G.useCallback)(()=>{s(`/experiments/${e}`)},[s,e]),d=(0,G.useMemo)(()=>c?r.findIndex(e=>e.itemId===c):-1,[r,c]),f=(0,G.useMemo)(()=>{if(d<=0)return;let e=r[d-1].itemId;return()=>l(e)},[d,r,l]),p=(0,G.useMemo)(()=>{if(d<0||d>=r.length-1)return;let e=r[d+1].itemId;return()=>l(e)},[d,r,l]);Hfi({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)(ymi.Provider,{value:m,children:o})}function xmi(){let e=(0,G.useContext)(ymi);if(!e)throw Error(`useExperimentItemPanel must be used within an ExperimentItemPanelProvider`);return e}function Smi(e,t){if(!e||typeof e!=`object`||!(t in e))return;let n=e[t];return typeof n==`string`&&n?n:void 0}function Cmi(e){if(e.targetType===`agent`)return Smi(e.output,`text`)}function wmi(e){if(e.targetType)return Cmi(e);let{output:t}=e;if(t!=null&&t!==``)return typeof t==`string`?t:JSON.stringify(t)}function Tmi(e){let t=[];return e.some(e=>wmi(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=Smi(e.error,`message`);if(t)return t;if(e.targetType===`agent`&&e.output&&typeof e.output==`object`)return Smi(e.output.error,`message`)}function Emi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Dmi(e){return Array.isArray(e)?e.flatMap(e=>Emi(e)&&Emi(e.payload)?[e.payload]:[]):[]}function Omi(e){if(e.targetType!==`agent`||!Emi(e.output))return[];let t=new Map(Dmi(e.output.toolResults).map(e=>[e.toolCallId,e]));return Dmi(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 kmi(e){if(Cmi(e)||R7(e))return;let t=Omi(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),Ami=e=>iC(e)??`-`,jmi=(e,t)=>e!=null&&t!=null?e-t:null,Mmi=new Set(Intl.supportedValuesOf(`currency`)),Nmi={minimumFractionDigits:3,maximumFractionDigits:3},B7=(e,t)=>{if(e===void 0)return`-`;let n=(t??`usd`).toUpperCase();return Mmi.has(n)?new Intl.NumberFormat(`en-US`,{style:`currency`,currency:n,...Nmi}).format(e):`${new Intl.NumberFormat(`en-US`,Nmi).format(e)} ${t}`},Pmi=e=>t=>B7(t,e),Fmi=new Intl.NumberFormat(`en-US`),V7=e=>e===void 0?`-`:Fmi.format(e),H7=e=>{if(e?.inputTokens!==void 0||e?.outputTokens!==void 0)return(e.inputTokens??0)+(e.outputTokens??0)};function Imi({scorerId:e,reason:t,nested:n=!1}){let r=`text-muted-foreground hover:text-foreground [&>svg]:size-icon-sm`;return(0,K.jsxs)(yX,{children:[(0,K.jsx)(bX,{delay:0,closeDelay:100,render:n?(0,K.jsx)(`span`,{"aria-hidden":!0,"data-testid":`score-reason-${e}`,className:`flex ${r}`}):(0,K.jsx)(`button`,{type:`button`,"aria-label":`Show ${e} reason`,className:`cursor-pointer ${r}`}),children:(0,K.jsx)(Yx,{})}),(0,K.jsx)(xX,{side:`left`,align:`start`,className:`max-h-80 max-w-100 overflow-y-auto`,onClick:e=>e.stopPropagation(),children:(0,K.jsx)(xY,{children:t})})]})}var Lmi=new Set([`itemId`,`id`,`status`,`input`,`output`,`error`,`tags`,`scores`,`cost`,`tokens`,`duration`]);function Rmi({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=>Lmi.has(e.name)||o?.includes(e.name)),v=[g?`2rem`:``,..._.map(e=>e.size)].filter(Boolean).join(` `),y=e=>_.some(t=>t.name===e),b=y(`itemId`)||y(`id`),x=y(`status`),S=y(`input`),C=y(`output`),w=y(`error`),T=y(`tags`),E=y(`scores`),D=y(`cost`),O=y(`tokens`),k=y(`duration`),A=d?e.filter(e=>d.has(e.id)).length:0,j=e.length>0&&A===e.length,{containerRef:M,getRowProps:N}=PZ({count:e.length}),P=e=>o?.includes(e.name)?(0,K.jsx)(Z.TopCell,{children:(0,K.jsxs)(m,{href:h.scorerLink(e.name),className:`flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-icon-sm [&>svg]:shrink-0`,children:[(0,K.jsx)(JN,{}),(0,K.jsx)(`span`,{className:`min-w-0 truncate`,children:e.label})]})},e.name):(0,K.jsx)(Z.TopCell,{children:e.label},e.name);return t?(0,K.jsx)(DH,{columns:v}):(0,K.jsxs)(Z,{columns:v,className:`min-w-0`,scrollRef:M,children:[(0,K.jsxs)(Z.Top,{hasLeadingCell:g,children:[g&&(p?(0,K.jsx)(Z.TopSelectCell,{checked:j?!0:A>0&&`indeterminate`,onToggle:p,"aria-label":`Select all`}):(0,K.jsx)(Z.TopCell,{children:`\xA0`})),g?(0,K.jsx)(Z.TopCells,{colStart:2,children:_.map(P)}):_.map(P)]}),e.length===0?(0,K.jsx)(Z.NoMatch,{message:u}):(0,K.jsxs)(K.Fragment,{children:[e.map((e,t)=>{let i=!!e.error,s=e.id===n,c=(0,K.jsxs)(K.Fragment,{children:[b&&(0,K.jsx)(Z.Cell,{className:`text-muted-foreground`,children:e.itemId?.slice(0,8)??``}),x&&(0,K.jsx)(Z.Cell,{className:`flex items-center`,"data-testid":`result-status-${e.id}`,children:e.status?(0,K.jsx)(y7r,{status:e.status}):(0,K.jsx)(`span`,{className:`text-placeholder`,children:`—`})}),S&&(0,K.jsx)(Z.TextCell,{font:`mono`,children:Hmi(Vmi(e.input),200)}),C&&(0,K.jsx)(Z.Cell,{className:`truncate font-mono`,"data-testid":`result-output-${e.id}`,children:wmi(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)(rli,{value:e,className:`shrink-0`},e))}),E&&(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(zmi,{scores:e.scores})}),D&&(0,K.jsx)(Z.Cell,{className:`text-muted-foreground tabular-nums`,"data-testid":`result-cost-${e.id}`,children:B7(e.usage?.estimatedCost,e.usage?.costUnit)}),O&&(0,K.jsx)(Z.Cell,{className:`text-muted-foreground tabular-nums`,"data-testid":`result-tokens-${e.id}`,children:V7(H7(e.usage))}),k&&(0,K.jsx)(Z.Cell,{className:`text-muted-foreground tabular-nums`,"data-testid":`result-duration-${e.id}`,children:iC(Bmi(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)(Imi,{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 zmi({scores:e}){let t=Array.isArray(e)?e.map(e=>e.score).filter(e=>e!=null):Object.values(e??{});return t.length===0?(0,K.jsx)(T,{variant:`meta`,tone:`faint`,children:`—`}):(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(Dx,{size:`xs`,className:`text-muted-foreground`,children:(0,K.jsx)(G4,{})}),(0,K.jsx)(T,{variant:`meta`,tone:`muted`,font:`mono`,children:t[0].toFixed(2)}),t.length>1&&(0,K.jsxs)(eC,{children:[`+`,t.length-1]})]})}function Bmi({startedAt:e,completedAt:t}){if(e&&t)return new Date(t).getTime()-new Date(e).getTime()}function Vmi(e){return e==null?`-`:typeof e==`string`?e:JSON.stringify(e,null,2)}function Hmi(e,t){return e.length<=t?e:e.slice(0,t-1)+`...`}function Umi({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}=xmi(),m=(0,G.useMemo)(()=>d?n.find(e=>e.itemId===d)?.id??null:null,[n,d]),{data:h}=jN({experimentId:e,experimentStatus:t,queryOptions:{enabled:!!e}}),{data:g}=smi({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`},...Tmi(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)(Rmi,{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 Wmi({children:e,className:t}){return(0,K.jsx)(`div`,{className:c(`grid content-start gap-4 overflow-y-auto`,t),children:e})}function Gmi({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 Kmi({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 qmi=Object.assign(Gmi,{Content:Wmi,Toolbar:Kmi});function Jmi({children:e,className:t}){return(0,K.jsx)(`div`,{className:c(`grid size-full grid-cols-1 overflow-y-auto`,t),children:e})}function Ymi({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){let{data:i}=IAt({datasetId:e,queryOptions:{enabled:!!e}}),a=(i??[]).map(e=>{let t=`v${e.version}`,n=bC(e.createdAt,`date-time`),r=e.isCurrent?`(current)`:void 0;return{value:String(e.version),label:[t,n,r].filter(e=>e!==void 0).join(` `),content:(0,K.jsxs)(AC,{children:[(0,K.jsx)(AC.Item,{children:t}),n&&(0,K.jsx)(AC.Item,{children:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:n})}),r&&(0,K.jsx)(AC.Item,{children:r})]})}});return(0,K.jsxs)(qmi.Toolbar,{className:`grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4`,children:[(0,K.jsx)(`div`,{}),(0,K.jsxs)(Bk,{items:a,value:t??``,onValueChange:e=>r?.(e,n??``),children:[(0,K.jsx)(Hk,{"aria-label":`Version A`,size:`md`,children:(0,K.jsx)(Vk,{placeholder:`Select version`})}),(0,K.jsx)(Uk,{children:a.map(e=>(0,K.jsx)(Wk,{value:e.value,label:e.label,children:e.content},e.value))})]}),(0,K.jsxs)(Bk,{items:a,value:n??``,onValueChange:e=>r?.(t??``,e),children:[(0,K.jsx)(Hk,{"aria-label":`Version B`,size:`md`,children:(0,K.jsx)(Vk,{placeholder:`Select an option`})}),(0,K.jsx)(Uk,{children:a.map(e=>(0,K.jsx)(Wk,{value:e.value,label:e.label,children:e.content},e.value))})]}),(0,K.jsx)(`div`,{})]})}var Xmi={added:{badgeVariant:`info`,borderColor:`border-info-edge`,icon:(0,K.jsx)(Hx,{}),tooltip:`Added in this version`},changed:{badgeVariant:`warning`,borderColor:`border-warning-edge`,icon:(0,K.jsx)(iH,{}),tooltip:`Changed in this version`},same:{badgeVariant:`success`,borderColor:`border-success-edge`,icon:(0,K.jsx)(PLr,{}),tooltip:`Same in both versions`}};function Zmi({red:e=!1,tooltip:t}){return(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{render:(0,K.jsx)(`span`,{}),role:`img`,tabIndex:0,"aria-label":t,className:c(`rounded`,p),children:(0,K.jsx)(Kx,{className:c(`size-icon-lg text-muted-foreground/40`,{"text-destructive-foreground":e})})}),(0,K.jsx)(Tx,{children:t})]})}function Qmi({href:e,tooltip:t,className:n,children:r}){let{Link:i}=sn(),a=(0,K.jsx)(i,{href:e,className:c(`flex w-full items-center justify-center gap-4 rounded-lg px-3 py-2 text-left hover:bg-fill-subtle`,u.colors,p,n),children:r});return t===void 0?a:(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{render:a}),(0,K.jsx)(Tx,{children:t})]})}function $mi({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}=Xmi[e];return(0,K.jsxs)(`div`,{className:`grid grid-cols-[1fr_auto]`,children:[t!==void 0&&(0,K.jsxs)(T,{as:`span`,tone:`muted`,className:`flex min-w-16 justify-end pr-3`,children:[`v. `,t]}),(0,K.jsx)(`span`,{className:`inline-flex`,role:`img`,"aria-label":i,children:(0,K.jsx)(eC,{variant:n,size:`xs`,icon:r})})]})}function ehi(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?`same`:e&&t&&e.datasetVersion!==t.datasetVersion?`changed`:e?`added`:`removed`}function thi({otherVersionExists:e,status:t,isNewer:n}){if(!e&&n)return`added`;if(t===`changed`&&n)return`changed`}function nhi({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=ehi(n,r),l=thi({otherVersionExists:r!==void 0,status:s,isNewer:o}),d=thi({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)(Qmi,{href:`/datasets/${e}/items/${t}`,className:`col-span-2 gap-2`,tooltip:Xmi.same.tooltip,children:(0,K.jsx)($mi,{variant:`same`,version:r?.datasetVersion})}):(0,K.jsxs)(K.Fragment,{children:[n?.datasetVersion?(0,K.jsx)(Qmi,{href:`/datasets/${e}/items/${t}`,className:`gap-2`,tooltip:l?Xmi[l].tooltip:void 0,children:(0,K.jsx)($mi,{variant:l,version:n.datasetVersion})}):(0,K.jsx)(`div`,{className:`flex items-center justify-center`,children:(0,K.jsx)(Zmi,{red:o,tooltip:o?`Deleted in this version`:`Not present in this version`})}),r?.datasetVersion?(0,K.jsx)(Qmi,{href:`/datasets/${e}/items/${t}`,className:`gap-2`,tooltip:d?Xmi[d].tooltip:void 0,children:(0,K.jsx)($mi,{variant:d,version:r.datasetVersion})}):(0,K.jsx)(`div`,{className:`flex items-center justify-center`,children:(0,K.jsx)(Zmi,{red:!o,tooltip:o?`Not present in this version`:`Deleted in this version`})})]}),s===`changed`?(0,K.jsx)(Qmi,{href:`/datasets/${e}/items/${t}/versions?version=${n?.datasetVersion}&compare=${r?.datasetVersion}`,children:`Compare`}):(0,K.jsx)(`div`,{children:(0,K.jsx)(Zmi,{tooltip:`Comparing is available only for changed items`})})]},t)})})})}var rhi=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 ihi(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 ahi({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)(ohi,{item:e,onClose:r,...a},e.id):t?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(jQ.Header,{children:[(0,K.jsx)(jQ.Heading,{children:`Dataset item`}),(0,K.jsx)(jQ.HeaderActions,{children:(0,K.jsx)(jQ.CloseButton,{icon:`x`,onClick:r,tooltip:`Close detail panel`})})]}),n]}):null;return i===`inline`?c?(0,K.jsx)(jQ,{variant:`inline`,title:s,children:c}):null:(0,K.jsx)(jQ,{open:!!o,onClose:r,title:s,children:c})}function ohi({datasetId:e,item:t,items:n,onItemChange:r,onClose:i}){let{navigate:a}=sn(),{updateItem:o,deleteItem:s}=ON(),[c,l]=(0,G.useState)(!1),[u,d]=(0,G.useState)(``),[f,p]=(0,G.useState)(``),[m,h]=(0,G.useState)(``),[g,_]=(0,G.useState)(``),[v,y]=(0,G.useState)(``),[b,x]=(0,G.useState)(``),[S,C]=(0,G.useState)(null),[w,T]=(0,G.useState)(!1);(0,G.useEffect)(()=>{t&&(d(JSON.stringify(t.input,null,2)),p(t.groundTruth?JSON.stringify(t.groundTruth,null,2):``),h(t.metadata?JSON.stringify(t.metadata,null,2):``),_(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):``),y(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):``),x(t.requestContext?JSON.stringify(t.requestContext,null,2):``),l(!1),T(!1),C(null))},[t?.id]);let E=n.findIndex(e=>e.id===t.id),D=E>0?()=>r(n[E-1].id):void 0,O=E>=0&&E<n.length-1?()=>r(n[E+1].id):void 0;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(jQ.Header,{children:[(0,K.jsx)(jQ.Heading,{children:`Dataset item`}),(0,K.jsxs)(jQ.HeaderActions,{children:[!c&&(0,K.jsxs)(rE,{children:[(0,K.jsx)(rE.Trigger,{asChild:!0,children:(0,K.jsx)(X,{size:`icon-sm`,variant:`ghost`,tooltip:`Open actions menu`,"aria-label":`Open actions menu`,children:(0,K.jsx)(iE,{})})}),(0,K.jsxs)(rE.Content,{align:`end`,className:`w-48`,children:[(0,K.jsxs)(rE.Item,{onSelect:()=>a(`/datasets/${e}/items/${t.id}/versions?version=${t.datasetVersion}`),children:[(0,K.jsx)(rhi,{}),`Item versions`]}),(0,K.jsxs)(rE.Item,{onSelect:()=>l(!0),children:[(0,K.jsx)(iH,{}),`Edit`]}),(0,K.jsxs)(rE.Item,{onSelect:()=>T(!0),variant:`destructive`,children:[(0,K.jsx)(Kj,{}),`Delete item`]})]})]}),(0,K.jsx)(jQ.NextPrevNav,{onPrevious:D,onNext:O,previousLabel:`Go to previous item`,nextLabel:`Go to next item`}),(0,K.jsx)(jQ.CloseButton,{icon:`x`,onClick:i,tooltip:`Close detail panel`})]})]}),(0,K.jsx)(jQ.Content,{children:c?(0,K.jsx)(opi,{inputValue:u,setInputValue:e=>{d(e),S?.field===`input`&&C(null)},groundTruthValue:f,setGroundTruthValue:e=>{p(e),S?.field===`groundTruth`&&C(null)},metadataValue:m,setMetadataValue:h,trajectoryValue:g,setTrajectoryValue:_,toolMocksValue:v,setToolMocksValue:y,requestContextValue:b,setRequestContextValue:x,validationErrors:S,onSave:async()=>{let n;try{n=JSON.parse(u)}catch{iS.error(`Input must be valid JSON`);return}let r;if(f.trim())try{r=JSON.parse(f)}catch{iS.error(`Ground Truth must be valid JSON`);return}let i;if(m.trim())try{i=JSON.parse(m)}catch{iS.error(`Metadata must be valid JSON`);return}let a=null;if(g.trim())try{a=JSON.parse(g)}catch{iS.error(`Expected Trajectory must be valid JSON`);return}let s;if(v.trim())try{let e=JSON.parse(v);if(!Array.isArray(e)){iS.error(`Tool Mocks must be a JSON array`);return}s=e}catch{iS.error(`Tool Mocks must be valid JSON`);return}else s=[];let c;if(b.trim())try{c=JSON.parse(b)}catch{iS.error(`Request Context must be valid JSON`);return}try{await o.mutateAsync({datasetId:e,itemId:t.id,input:n,groundTruth:r,metadata:i,expectedTrajectory:a,toolMocks:s,requestContext:c}),iS.success(`Item updated successfully`),l(!1),C(null)}catch(e){let t=ihi(e);t?C(t):iS.error(`Failed to update item: ${e instanceof Error?e.message:`Unknown error`}`)}},onCancel:()=>{d(JSON.stringify(t.input,null,2)),p(t.groundTruth?JSON.stringify(t.groundTruth,null,2):``),h(t.metadata?JSON.stringify(t.metadata,null,2):``),_(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):``),y(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):``),x(t.requestContext?JSON.stringify(t.requestContext,null,2):``),l(!1),C(null)},isSaving:o.isPending}):(0,K.jsx)(rpi,{item:t})}),(0,K.jsx)(QM,{open:w,onOpenChange:T,children:(0,K.jsxs)(QM.Content,{children:[(0,K.jsxs)(QM.Header,{children:[(0,K.jsx)(QM.Title,{children:`Delete Item`}),(0,K.jsx)(QM.Description,{children:`Are you sure you want to delete this item? This action cannot be undone.`})]}),(0,K.jsxs)(QM.Footer,{children:[(0,K.jsx)(QM.Cancel,{children:`Cancel`}),(0,K.jsx)(QM.Action,{onClick:async()=>{try{await s.mutateAsync({datasetId:e,itemId:t.id}),iS.success(`Item deleted successfully`),T(!1),i()}catch(e){iS.error(`Failed to delete item: ${e instanceof Error?e.message:`Unknown error`}`)}},children:s.isPending?`Deleting...`:`Yes, delete`})]})]})})]})}function shi(){let{datasetId:e,items:t,isLoadingItems:n,currentItemId:r,openItem:i,close:a}=Gfi(),o=Zw();K1r(r,a);let s=(0,G.useMemo)(()=>r?t.find(e=>e.id===r):void 0,[t,r]),{data:c,isLoading:l}=mAt({datasetId:s?``:e,itemId:!s&&r?r:``,queryOptions:{enabled:!(s||!e)&&!!(!s&&r&&r)}}),u=(0,K.jsx)(ahi,{datasetId:e,item:s??c??void 0,itemId:r,fallback:n||l?(0,K.jsx)(jQ.LoadingData,{}):(0,K.jsxs)(jQ.NoData,{children:[`No loaded item "`,r,`".`]}),items:t,onItemChange:i,onClose:a,variant:o?`drawer`:`inline`});return o?u:r?(0,K.jsx)(Y8,{owner:`dataset-item`,children:u}):null}function chi({crumbs:e,children:t}){return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:e}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Dataset`}),(0,K.jsx)(`div`,{}),(0,K.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:t})]})}function lhi(){let{datasetId:e}=kv(),t=Ov(),[n,r]=Rv(),{activeVersion:i}=MN(n,r),a=[eP(`/datasets`),iMt],o=[...a,aMt],[s,c]=(0,G.useState)(!1),[l,u]=(0,G.useState)(!1),[d,f]=(0,G.useState)(!1),[p,m]=(0,G.useState)(!1),[h,g]=(0,G.useState)(!1),{data:_,error:v,isLoading:y}=AN({datasetId:e,queryOptions:{enabled:!!e}}),{data:b=[],isLoading:x}=DN({datasetId:e,search:void 0,version:i,queryOptions:{enabled:!!e}});if(y)return null;if(v&&FN(v))return(0,K.jsx)(chi,{crumbs:a,children:(0,K.jsx)(TH,{})});if(v&&IN(v))return(0,K.jsx)(chi,{crumbs:a,children:(0,K.jsx)(wH,{resource:`datasets`})});if(v&&LN(v)||!y&&!v&&!_)return(0,K.jsx)(chi,{crumbs:a,children:(0,K.jsx)(Jx,{titleSlot:`Dataset not found`,descriptionSlot:`No dataset with id "${e}".`,actionSlot:(0,K.jsx)(X,{render:(0,K.jsx)(Lv,{to:`/datasets`}),icon:(0,K.jsx)(sS,{}),children:`Back to datasets`})})});if(v)return(0,K.jsx)(chi,{crumbs:a,children:(0,K.jsx)(Jx,{tone:`error`,titleSlot:`Failed to load dataset`,descriptionSlot:v instanceof Error?v.message:`An unexpected error occurred. Please try again.`})});let S=e=>{t(`/experiments/${e}`)},C=()=>{t(`/datasets`)},w=b.length>0,T=(_?.version??0)>0,E=w||T,D=w||(_?.tags?.length??0)>0,O=(0,K.jsxs)(K.Fragment,{children:[w&&(0,K.jsx)(X,{variant:`ghost`,size:`sm`,onClick:()=>c(!0),icon:(0,K.jsx)(Hx,{}),children:`New experiment`}),E&&(0,K.jsx)(X,{variant:`ghost`,size:`sm`,render:(0,K.jsx)(Lv,{to:`/experiments?dataset=${e}`}),icon:(0,K.jsx)(Ijt,{}),children:`Experiments`}),(0,K.jsx)(X,{variant:`ghost`,size:`sm`,onClick:()=>g(!0),icon:(0,K.jsx)(JS,{}),children:`Schema`}),(0,K.jsxs)(rE,{children:[(0,K.jsx)(rE.Trigger,{asChild:!0,children:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,"aria-label":`Dataset actions menu`,children:(0,K.jsx)(iE,{})})}),(0,K.jsxs)(rE.Content,{align:`end`,className:`w-48`,children:[(0,K.jsxs)(rE.Item,{onSelect:()=>void t(`/datasets/${e}/edit`),children:[(0,K.jsx)(iH,{}),` Edit dataset`]}),(0,K.jsxs)(rE.Item,{onSelect:()=>m(!0),children:[(0,K.jsx)(mC,{}),` Duplicate dataset`]}),(0,K.jsxs)(rE.Item,{onSelect:()=>f(!0),variant:`destructive`,children:[(0,K.jsx)(Kj,{}),` Delete dataset`]})]})]})]});return(0,K.jsxs)(Wfi,{datasetId:e,items:b,isLoadingItems:x,children:[(0,K.jsxs)(`div`,{className:`h-full`,children:[(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:o}),headerActions:O,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(`div`,{children:(0,K.jsx)(qfi,{datasetId:e,onAddItemClick:()=>u(!0),toolbarActionsSlot:D?(0,K.jsx)(Yfi,{datasetId:e}):void 0})})]}),(0,K.jsx)(shi,{})]}),(0,K.jsx)(Xpi,{initialDatasetId:e,initialDatasetVersion:i??void 0,open:s,onOpenChange:c,onSuccess:S},`${e}:${i??`latest`}`),(0,K.jsx)(zor,{datasetId:e,open:l,onOpenChange:u}),_&&(0,K.jsx)(nui,{open:p,onOpenChange:m,sourceDatasetId:_.id,sourceDatasetName:_.name,sourceDatasetDescription:_.description,sourceDatasetTargetType:_.targetType}),_&&(0,K.jsx)(rfi,{open:h,onOpenChange:g,dataset:_}),_&&(0,K.jsx)(xui,{open:d,onOpenChange:f,datasetId:_.id,datasetName:_.name,onSuccess:C})]})}function uhi({children:e,className:t}){return(0,K.jsx)(`div`,{className:c(`grid content-start`,t),children:e})}function dhi({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 fhi({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 phi({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(fhi,{Title:phi,Description:dhi,Column:uhi}),mhi=[eP(`/datasets`),iMt,{id:`dataset-edit`,label:`Edit dataset`}];function hhi({children:e}){return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:mhi}),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 ghi(){let{datasetId:e}=kv(),t=Ov(),{data:n,error:r,isLoading:i}=AN({datasetId:e,queryOptions:{enabled:!!e}}),a=()=>void t(`/datasets/${e}`);return i?null:r&&FN(r)?(0,K.jsx)(hhi,{children:(0,K.jsx)(TH,{})}):r&&IN(r)?(0,K.jsx)(hhi,{children:(0,K.jsx)(wH,{resource:`datasets`})}):r||!n?(0,K.jsx)(hhi,{children:(0,K.jsx)(Jx,{tone:`error`,titleSlot:`Failed to load dataset`,descriptionSlot:r instanceof Error?r.message:`An unexpected error occurred. Please try again.`})}):(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:mhi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Edit dataset`}),(0,K.jsx)(`div`,{}),(0,K.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:(0,K.jsxs)(`div`,{className:`w-full max-w-2xl overflow-y-auto px-4 py-5`,children:[(0,K.jsx)(U7,{className:`mb-6 p-0`,children:(0,K.jsxs)(U7.Column,{children:[(0,K.jsxs)(U7.Title,{children:[(0,K.jsx)(uT,{}),` Edit dataset`]}),(0,K.jsx)(U7.Description,{children:n.name})]})}),(0,K.jsx)(nP,{className:`p-4`,children:(0,K.jsx)(bui,{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 _hi=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 vhi(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 yhi(e,t){return e.map(e=>{let n=typeof e.updatedAt==`string`?new Date(e.updatedAt):e.updatedAt;return{value:String(e.datasetVersion),label:(0,K.jsxs)(`span`,{className:`flex w-full items-center gap-2`,children:[(0,K.jsxs)(AC,{children:[(0,K.jsx)(AC.Item,{children:(0,K.jsxs)(`b`,{children:[`v. `,e.datasetVersion]})}),(0,K.jsx)(AC.Item,{children:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:bC(n,`date-time`)})})]}),e.isLatest?(0,K.jsx)(eC,{variant:`blue`,size:`xs`,className:`ml-auto`,children:`Latest`}):null]}),disabled:t?.has(e.datasetVersion)??!1}})}function bhi(e){let t=Number(e);return e!=null&&Number.isFinite(t)&&t>0?t:null}function xhi(){let{datasetId:e,itemId:t}=kv(),[n,r]=Rv(),i=[eP(`/datasets`),iMt,{id:`dataset-item`,label:Qjt(t),to:e&&t?`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}`:void 0},{id:`dataset-item-versions`,label:`Item Version History`}],a=bhi(n.get(`version`)),o=bhi(n.get(`compare`)),s=n.get(`view`)===`diff`,{data:c,error:l}=AN({datasetId:e??``,queryOptions:{enabled:!!e}}),{data:u,isLoading:d}=NAt({datasetId:e??``,itemId:t??``,queryOptions:{enabled:!!e&&!!t}}),f=(a==null?void 0:u?.find(e=>e.datasetVersion===a))??u?.[0],p=f?.datasetVersion??null,m=o!=null&&o!==p?o:null,{data:h,isLoading:g}=PAt({datasetId:e??``,itemId:t??``,datasetVersion:m??0,latestVersion:c?.version,queryOptions:{enabled:!!e&&!!t&&(m??0)>0}}),_=(e,t)=>r(n=>{let r=new URLSearchParams(n);return t==null?r.delete(e):r.set(e,String(t)),r},{replace:!0});if(l&&FN(l))return(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:i}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Item Version History`}),(0,K.jsx)(TH,{variant:`fill`})]});if(l&&IN(l))return(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:i}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Item Version History`}),(0,K.jsx)(wH,{variant:`fill`,resource:`datasets`})]});if(!e||!t)return(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:i}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Item Version History`}),(0,K.jsx)(`div`,{className:`grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto`,children:(0,K.jsx)(`div`,{className:`py-5 text-center text-muted-foreground`,children:(0,K.jsx)(`p`,{children:`Item not found.`})})})]});let v=!!(f&&h),y=s&&v,b=f?vhi(f,e):null,x=h?vhi(h,e):null,S=(f?.datasetVersion??0)<(h?.datasetVersion??0);return(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:i}),headerActions:v&&(0,K.jsx)(X,{variant:`ghost`,size:`sm`,onClick:()=>_(`view`,s?null:`diff`),children:s?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(X0r,{}),` Default view`]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(_hi,{}),` Diff view`]})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Item Version History`}),(0,K.jsxs)(`div`,{className:`grid min-h-0 grid-cols-1 gap-4 md:grid-cols-2`,children:[(0,K.jsxs)(nP,{className:`grid min-h-0 grid-rows-[auto_1fr] overflow-hidden`,children:[(0,K.jsx)(rP,{children:(0,K.jsx)(Shi,{label:`Version`,value:p==null?``:String(p),options:yhi(u??[],m==null?void 0:new Set([m])),onValueChange:e=>_(`version`,Number(e))})}),(0,K.jsx)(oP,{className:`grid content-start gap-5 overflow-y-auto`,children:d?(0,K.jsx)(T,{as:`p`,variant:`body`,tone:`muted`,children:`Loading...`}):b?(0,K.jsx)(rpi,{item:b,diff:y&&x?{against:x,side:S?`a`:`b`}:void 0}):(0,K.jsx)(T,{as:`p`,variant:`body`,tone:`muted`,children:`Item data not available`})})]}),(0,K.jsxs)(nP,{className:`grid min-h-0 grid-rows-[auto_1fr] overflow-hidden`,children:[(0,K.jsx)(rP,{children:(0,K.jsx)(Shi,{label:`Compare version`,value:m==null?``:String(m),placeholder:`Select a version to compare`,options:yhi(u??[],p==null?void 0:new Set([p])),onValueChange:e=>_(`compare`,Number(e))})}),(0,K.jsx)(oP,{className:`grid content-start gap-5 overflow-y-auto`,children:m==null?(0,K.jsx)(Jx,{className:`h-full`,titleSlot:`No version selected`,descriptionSlot:`Pick a version above to compare it with the one on the left.`}):g?(0,K.jsx)(T,{as:`p`,variant:`body`,tone:`muted`,children:`Loading...`}):x?(0,K.jsx)(rpi,{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 Shi({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)(rhi,{className:`size-icon-md opacity-50`}),(0,K.jsxs)(Bk,{value:t,onValueChange:i,children:[(0,K.jsx)(Hk,{"aria-label":e,className:`w-full`,children:(0,K.jsx)(Vk,{placeholder:r,className:`flex-1`})}),(0,K.jsx)(Uk,{children:n.map(e=>(0,K.jsx)(Wk,{value:e.value,disabled:e.disabled,children:e.label},e.value))})]})]})}var Chi=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`})),whi=[eP(`/datasets`),iMt,{id:`dataset-versions`,label:`Versions`}];function Thi(){let{datasetId:e}=kv(),[t]=Rv(),n=t.get(`ids`)?.split(`,`).map(Number).filter(e=>!isNaN(e)&&e>0)??[],r=Ov(),{data:i,error:a}=AN({datasetId:e??``,queryOptions:{enabled:!!e}}),o=DN({datasetId:e??``,search:void 0,version:n[0]??null,queryOptions:{enabled:!!e}}),s=DN({datasetId:e??``,search:void 0,version:n[1]??null,queryOptions:{enabled:!!e}}),c=(0,G.useMemo)(()=>o.data??[],[o.data]),l=(0,G.useMemo)(()=>s.data??[],[s.data]),u=(0,G.useMemo)(()=>{let e=new Map;for(let t of[...c,...l])e.has(t.id)||e.set(t.id,{id:t.id,createdAt:new Date(t.createdAt)});return[...e.values()].sort((e,t)=>t.createdAt.getTime()-e.createdAt.getTime())},[c,l]),d=(0,G.useMemo)(()=>new Map(c.map(e=>[e.id,e])),[c]),f=(0,G.useMemo)(()=>new Map(l.map(e=>[e.id,e])),[l]);return a&&FN(a)?(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:whi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Versions`}),(0,K.jsx)(TH,{variant:`fill`})]}):a&&IN(a)?(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:whi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Versions`}),(0,K.jsx)(wH,{variant:`fill`,resource:`datasets`})]}):!e||n.length<2?(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:whi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Versions`}),(0,K.jsx)(`div`,{className:`grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto`,children:(0,K.jsx)(`div`,{className:`py-5 text-center text-muted-foreground`,children:(0,K.jsx)(`p`,{children:`Select at least two versions to compare.`})})})]}):(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:whi}),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)(Chi,{}),` Compare Dataset Versions`]}),(0,K.jsx)(U7.Description,{children:(0,K.jsxs)(MZ,{children:[(0,K.jsx)(rhi,{}),` Comparing `,n.length,` versions of`,` `,i?.name||e?.slice(0,8)]})})]}),(0,K.jsx)(U7.Column,{children:(0,K.jsx)(X,{render:(0,K.jsx)(Lv,{to:`/datasets/${e}`}),icon:(0,K.jsx)(sS,{}),children:`Back to dataset`})})]}),(0,K.jsx)(Jmi,{children:(0,K.jsxs)(qmi,{children:[(0,K.jsx)(Ymi,{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)(nhi,{datasetId:e,versionA:n[0],versionB:n[1],allItems:u,itemsAMap:d,itemsBMap:f})]})})]})})]})}var Ehi=100,Dhi=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:Ehi,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}},Ohi=(e,{experimentId:t,targetType:n,targetId:r,experiments:i,isLoadingExperiments:a=!1,queryOptions:o})=>{let s=Y(),{inView:c,setRef:l}=$M(),u=i!==void 0,{data:d,isLoading:f}=umi({datasetId:void 0,target:{targetType:n,targetId:r},queryOptions:{enabled:!u}}),p=u?i:d?.experiments,m=u?a:f,h=t?p?.filter(e=>e.id===t):p,g=O_({queryKey:[`review-items`,e,`infinite`,t??`all`,u?`supplied`:`discovered`,u?void 0:n||`all`,u?void 0:r||`all`,h?.map(e=>[e.datasetId,e.id])],queryFn:async({pageParam:t})=>{let n=await Dhi(s,e,t);for(;n.items.length===0&&n.next;)n=await Dhi(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}},khi=(e={})=>Ohi(`needs-review`,e),Ahi=(e={})=>Ohi(`complete`,e);function jhi({queryOptions:e}={}){let t=Y();return T_({queryKey:[`experiment-review-summary`],queryFn:()=>t.getExperimentReviewSummary(),...e})}var Mhi={baseline:`purple`,contender:`blue`},W7=e=>e===0?`Baseline`:`Contender ${e}`;function Nhi({open:e,onOpenChange:t,experimentId:n,experimentName:r,onSuccess:i}){let{deleteExperiment:a}=ON();return(0,K.jsx)(QM,{open:e,onOpenChange:t,children:(0,K.jsxs)(QM.Content,{children:[(0,K.jsxs)(QM.Header,{children:[(0,K.jsx)(QM.Title,{children:`Delete Experiment`}),(0,K.jsxs)(QM.Description,{children:[`Are you sure you want to delete "`,r||n,`"? This will permanently delete the experiment, all its results, and the traces it produced, including their spans and any scores, feedback, metrics and logs attached to those traces. This action cannot be undone.`]})]}),(0,K.jsxs)(QM.Footer,{children:[(0,K.jsx)(QM.Cancel,{children:`Cancel`}),(0,K.jsx)(X,{icon:(0,K.jsx)(Kj,{}),variant:`primary`,onClick:async()=>{try{await a.mutateAsync(n),iS.success(`Experiment deleted successfully`),t(!1),i?.()}catch(e){iS.error(`Failed to delete experiment: ${e instanceof Error?e.message:`Unknown error`}`)}},disabled:a.isPending,children:a.isPending?`Deleting...`:`Delete`})]})]})})}var Phi=`minmax(9rem,1fr)`,Fhi=`minmax(8rem,16rem)`,Ihi=`auto auto auto auto auto auto auto auto`,Lhi=`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`},Rhi={completed:`neutral`,running:`warning`,failed:`destructive`,pending:`neutral`},K7={completed:`Run completed`,running:`Run in progress`,failed:`Run failed`,pending:`Run queued`};function zhi(e){let t=aH(e.id)??e.id;return e.name||`Experiment #${t}`}var Bhi=60;function Vhi({experiment:e}){return(0,K.jsx)(`span`,{className:`block min-w-0 truncate text-left text-muted-foreground`,children:zhi(e)})}function Hhi({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<=Bhi?n:(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{asChild:!0,children:n}),(0,K.jsx)(Tx,{children:t})]})}function Uhi(){let{data:e}=wN(),{data:t}=eN(),{data:n}=VN(),{data:r}=PN();return{agents:e,workflows:t,scorers:n,processors:r}}var Whi={agent:HN,workflow:ZS,scorer:JN,processor:qN},Ghi={agent:`Agent`,workflow:`Workflow`,scorer:`Scorer`,processor:`Processor`},Khi=`External (caller-run)`;function qhi(e,{agents:t,workflows:n,scorers:r,processors:i}){let{targetType:a,targetId:o}=e;if(!o)return Khi;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 Jhi({experiment:e,datasetName:t,review:n,selectionRole:r,showUsage:i=!1,metrics:a}){let o=e.status??`pending`,s=e.succeededCount??0,c=e.failedCount??0,l=e.totalItems??0;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Z.Cell,{children:r?(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(eC,{variant:r.variant,className:`shrink-0`,children:r.label}),(0,K.jsx)(Vhi,{experiment:e})]}):(0,K.jsx)(Vhi,{experiment:e})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(Hhi,{experiment:e})}),t!==void 0&&(0,K.jsx)(Z.TextCell,{children:t}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(Qhi,{experiment:e})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(eC,{variant:Rhi[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)(Zhi,{value:Yhi(e),format:iC}),i&&(0,K.jsx)(Xhi,{metrics:a}),(0,K.jsx)(Z.Cell,{className:`text-center`,children:(0,K.jsx)($hi,{review:n})}),(0,K.jsx)(Z.TextCell,{children:bC(e.createdAt,`date`)??`—`})]})}function Yhi(e){if(e.startedAt&&e.completedAt)return new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime()}function Xhi({metrics:e}){let t=e?.avgDurationMs===void 0?void 0:Math.round(e.avgDurationMs);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Zhi,{value:t,format:iC}),(0,K.jsx)(Zhi,{value:H7(e),format:N5}),(0,K.jsx)(Zhi,{value:e?.estimatedCost,format:t=>B7(t,e?.costUnit)})]})}function Zhi({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 Qhi({experiment:e}){let t=qhi(e,Uhi()),n=e.targetId?e.targetType:null,r=n?Whi[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":Ghi[n],children:(0,K.jsx)(r,{})}),(0,K.jsx)(`span`,{className:n?`truncate`:`truncate text-placeholder`,children:t})]})}function $hi({review:e}){if(!e)return(0,K.jsx)(`span`,{className:`text-placeholder`,children:`—`});let t=e.needsReview+e.complete;return t===0?(0,K.jsx)(`span`,{className:`text-placeholder`,children:`—`}):e.needsReview>0?(0,K.jsxs)(eC,{size:`xs`,variant:`warning`,children:[e.needsReview,` pending`]}):(0,K.jsxs)(eC,{size:`xs`,variant:`success`,children:[e.complete,`/`,t,` reviewed`]})}var egi=`${Phi} ${Fhi} 1fr ${Ihi}`,tgi=`${egi} auto`,ngi=`${egi} ${Lhi} auto`,rgi=[{label:G7.avgDuration,className:`text-center`},{label:G7.tokens,className:`text-center`},{label:G7.cost,className:`text-center`}],igi=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?rgi:[],{label:G7.review,className:`text-center`},{label:G7.date,sortKey:`createdAt`}],agi=e=>e.stopPropagation();function ogi({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:agi,children:o}),(0,K.jsx)(Z.ActionsCell,{className:`pl-2`,children:(0,K.jsx)(X,{type:`button`,variant:`ghost`,size:`icon-sm`,tooltip:`Delete experiment`,"aria-label":`Delete experiment ${e.name??e.id}`,onClick:e=>{e.stopPropagation(),i()},children:(0,K.jsx)(Kj,{})})})]})}function sgi({experiments:e,datasets:t,reviewByExperiment:n,metricsByExperiment:r,isLoading:i,search:a=``,statusFilter:o=`all`,datasetFilter:s=`all`,selection:c,onSelectExperiment:l,selectedExperimentId:u,keyboardGlobal:d=!0,isFetchingNextPage:f,hasNextPage:p,setEndOfListElement:m,sort:h,onSortChange:g}){let _=(0,G.useMemo)(()=>{let e=new Map;return t?.forEach(t=>e.set(t.id,t.name)),e},[t]),v=(0,G.useMemo)(()=>h?e:[...e].sort((e,t)=>{let n=e.createdAt?new Date(e.createdAt).getTime():0;return(t.createdAt?new Date(t.createdAt).getTime():0)-n}),[e,h]),y=(0,G.useMemo)(()=>{let e=a.toLowerCase();return v.filter(t=>{let n=t.datasetId?_.get(t.datasetId)??``:``,r=!e||t.id.toLowerCase().includes(e)||(t.name??``).toLowerCase().includes(e)||n.toLowerCase().includes(e)||(t.targetId??``).toLowerCase().includes(e),i=o===`all`||t.status===o,a=s===`all`||t.datasetId===s;return r&&i&&a})},[v,a,_,o,s]),{containerRef:b,getRowProps:x}=PZ({count:y.length,global:d}),[S,C]=(0,G.useState)(null),w=r!==void 0,T=w?ngi:tgi;if(i)return(0,K.jsx)(DH,{columns:T});let E=(c?.selectedExperimentIds.length??0)===0||y.length===0?!1:y.every(e=>c?.selectedExperimentIds.includes(e.id))?!0:`indeterminate`,D=c?`auto ${T}`:T,O=igi(w).map(e=>e.sortKey&&g?(0,K.jsx)(Z.SortableTopCell,{className:e.className,sortKey:e.sortKey,sort:h?.key===e.sortKey?h.direction:void 0,onSortChange:g,children:e.label},e.label):(0,K.jsx)(Z.TopCell,{className:e.className,children:e.label},e.label));return(0,K.jsxs)(Z,{columns:D,scrollRef:b,children:[(0,K.jsx)(Z.Top,{hasLeadingCell:c!==void 0,children:c?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Z.TopSelectCell,{checked:E,onToggle:()=>c.onToggleAll(y.map(e=>e.id)),"aria-label":`Select all experiments`}),(0,K.jsxs)(Z.TopCells,{colStart:2,children:[O,(0,K.jsx)(Z.TopCell,{"aria-hidden":!0,children:null})]})]}):(0,K.jsxs)(K.Fragment,{children:[O,(0,K.jsx)(Z.TopCell,{"aria-hidden":!0,children:null})]})}),y.length===0&&!p?(0,K.jsx)(Z.NoMatch,{message:`No experiments match your filters`}):null,y.map((e,t)=>{let i=e.datasetId?_.get(e.datasetId)??aH(e.datasetId)??e.datasetId:`—`,a=c?.selectedExperimentIds.indexOf(e.id)??-1,o=a!==-1,s=!o&&c?.comparableDatasetId!==void 0&&e.datasetId!==c.comparableDatasetId,d=(0,K.jsx)(Jhi,{experiment:e,datasetName:i,review:n?.get(e.id),showUsage:w,metrics:r?.get(e.id),selectionRole:o?{label:W7(a),variant:a===0?Mhi.baseline:Mhi.contender}:void 0});return(0,K.jsx)(ogi,{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)(Nhi,{open:!0,onOpenChange:e=>{e||C(null)},experimentId:S.id,experimentName:S.name??void 0})]})}var cgi=[{value:`all`,label:`All statuses`},{value:`completed`,label:`Completed`},{value:`running`,label:`Running`},{value:`failed`,label:`Failed`},{value:`pending`,label:`Pending`}];function lgi(e){return[{value:`all`,label:`All datasets`},...(e??[]).map(e=>({value:e.id,label:e.name}))]}var ugi=({onRunExperiment:e})=>(0,K.jsx)(Jx,{titleSlot:`No Experiments yet`,descriptionSlot:(0,K.jsxs)(K.Fragment,{children:[`Run an experiment from a dataset to evaluate `,(0,K.jsx)(`br`,{}),`your agents and workflows.`]}),actionSlot:(0,K.jsxs)(`div`,{className:`flex flex-col items-center gap-2`,children:[e&&(0,K.jsx)(X,{variant:`primary`,onClick:e,icon:(0,K.jsx)(Hx,{}),children:`New experiment`}),(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/docs/evals/experiments`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(tP,{}),children:`Experiments documentation`})]}),variant:`fill`}),dgi=e=>`${e} experiment${e===1?``:`s`}`;function fgi({experimentIds:e,onDeleted:t}){let[n,r]=(0,G.useState)(!1),[i,a]=(0,G.useState)(!1),{deleteExperiment:o}=ON(),s=e.length;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(X,{size:`sm`,variant:`destructive-ghost`,disabled:s===0,icon:(0,K.jsx)(Kj,{}),onClick:()=>r(!0),children:`Delete`}),(0,K.jsx)(QM,{open:n,onOpenChange:r,children:(0,K.jsxs)(QM.Content,{children:[(0,K.jsxs)(QM.Header,{children:[(0,K.jsxs)(QM.Title,{children:[`Delete `,dgi(s)]}),(0,K.jsxs)(QM.Description,{children:[s===1?`Its`:`Their`,` results and traces will be deleted too. This can't be undone.`]})]}),(0,K.jsxs)(QM.Footer,{children:[(0,K.jsx)(QM.Cancel,{children:`Cancel`}),(0,K.jsx)(X,{icon:(0,K.jsx)(Kj,{}),variant:`destructive`,onClick:async()=>{a(!0);let n=await Promise.allSettled(e.map(e=>o.mutateAsync(e)));a(!1);let i=n.filter(e=>e.status===`rejected`).length;i>0?iS.error(`Failed to delete ${i} of ${dgi(s)}`):(iS.success(`Deleted ${dgi(s)}`),r(!1),t())},disabled:i,children:i?`Deleting…`:s===1?`Delete experiment`:`Delete experiments`})]})]})})]})}function pgi({selectedIds:e,onClearSelection:t,onCompare:n,compareDisabledReason:r}){let i=e.length,a=i===0;return(0,K.jsxs)(`div`,{className:`flex items-center gap-1 whitespace-nowrap`,children:[(0,K.jsxs)(X,{variant:`ghost`,size:`sm`,disabled:a,iconEnd:a?void 0:(0,K.jsx)(xw,{}),onClick:t,tooltip:a?void 0:`Clear selection`,className:`mr-2 tabular-nums`,children:[i,` selected`]}),(0,K.jsx)(fgi,{experimentIds:e,onDeleted:t}),r?(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{render:(0,K.jsx)(`span`,{className:`cursor-not-allowed`,tabIndex:0}),children:(0,K.jsx)(X,{size:`sm`,disabled:!0,tabIndex:-1,icon:(0,K.jsx)(_hi,{}),children:`Compare`})}),(0,K.jsx)(Tx,{children:r})]}):(0,K.jsx)(X,{size:`sm`,onClick:n,icon:(0,K.jsx)(_hi,{}),children:`Compare`})]})}function mgi({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 hgi=`search`,ggi=`status`,_gi=`dataset`,q7=`all`,vgi=[{id:`contains`,label:`contains`},{id:`is`,label:`is`}],ygi=cgi.filter(e=>e.value!==q7),bgi=({search:e,statusFilter:t,datasetFilter:n,targetType:r,targetId:i})=>{let a=[];return e&&a.push(T7(hgi,e,`contains`)),a.push(...yli({targetType:r,targetId:i})),t!==q7&&a.push(T7(ggi,t)),n!==q7&&a.push(T7(_gi,n)),a},xgi=e=>({...bli(e),search:E7(e,hgi),statusFilter:E7(e,ggi)||q7,datasetFilter:E7(e,_gi)||q7});function Sgi({search:e,statusFilter:t,datasetFilter:n,targetType:r,targetId:i,datasetOptions:a,onChange:o}){let s=xli(r),c=(0,G.useMemo)(()=>[{id:hgi,label:`Search`,icon:oN,search:!0,operators:[`contains`]},...s,{id:ggi,label:`Status`,icon:EX,color:sP(`orange`),operators:[`is`],strict:!0,suggestions:ygi},{id:_gi,label:`Dataset`,icon:uT,color:sP(`blue`),operators:[`is`],strict:!0,suggestions:a.filter(e=>e.value!==q7)}],[s,a]),l=(0,G.useMemo)(()=>bgi({search:e,statusFilter:t,datasetFilter:n,targetType:r,targetId:i}),[e,t,n,r,i]);return(0,K.jsxs)(m5,{fields:c,operators:vgi,value:l,onValueChange:e=>o(xgi(e)),createItemId:e=>e,"aria-label":`Experiments filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(m5.Chips,{}),(0,K.jsx)(m5.Input,{placeholder:`Filter experiments`})]})}function Cgi({search:e,statusFilter:t,datasetFilter:n,datasetOptions:r,targetType:i,targetId:a,onFiltersChange:o,selection:s,comparableDataset:c}){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(TK,{children:(0,K.jsx)(TK.Start,{children:(0,K.jsx)(Sgi,{search:e,statusFilter:t,datasetFilter:n,datasetOptions:r,targetType:i,targetId:a,onChange:o})})}),(0,K.jsxs)(TK,{children:[(0,K.jsx)(TK.Start,{className:`self-end`,children:(0,K.jsx)(mgi,{dataset:c})}),(0,K.jsx)(TK.End,{children:(0,K.jsx)(pgi,{...s})})]})]})}var wgi={present:!1,targetType:null,output:null,metadata:null,comment:null,error:null,startedAt:null,completedAt:null,scores:[]},Tgi=e=>e?e instanceof Date?e.toISOString():e:null,Egi=e=>{let t=new Map;for(let n of e??[])t.set(n.itemId,n);return t},Dgi=(e,t,n,r)=>{if(!e)return wgi;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:Tgi(t?.startedAt),completedAt:Tgi(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}},Ogi=(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 kgi(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 Agi=(e,t)=>{let n=kgi(e),r=kgi(t);return n!=null&&r!=null?r-n:void 0},jgi=(e,t)=>{let n=J7(e),r=J7(t);return n!=null&&r!=null?r-n:null},Mgi=(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},Ngi=(e,t)=>{let n=H7(e.usage),r=H7(t.usage);return n!==void 0&&r!==void 0?r-n:void 0},Pgi=({comparison:e,experimentIds:t,resultsById:n,scoresById:r,usageById:i})=>{if(!e)return[];let a=new Map(t.map(e=>[e,Egi(n?.[e])]));return e.items.map(e=>{let n=t.map(t=>Dgi(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:Ogi(o,e),durationDeltaMs:n===0?null:jgi(o,e),costDelta:n===0?void 0:Mgi(o,e),tokenDelta:n===0?void 0:Ngi(o,e),averageScoreDelta:n===0?void 0:Agi(o,e)}))}})};function Fgi({datasetId:e,itemId:t,onClose:n}){let{data:r,isLoading:i}=mAt({datasetId:e,itemId:t??``,queryOptions:{enabled:!!e&&!!t}});return(0,K.jsx)(ahi,{datasetId:e,item:r,itemId:t,fallback:i?(0,K.jsx)(jQ.LoadingData,{}):(0,K.jsxs)(jQ.NoData,{children:[`Dataset item "`,t,`" not found.`]}),items:r?[r]:[],onItemChange:()=>{},onClose:n})}function Igi({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 Lgi=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 Rgi({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)(Lgi,{}),label:`Cost`,value:B7(e?.estimatedCost,c),rawValue:e?.estimatedCost,delta:r??null,formatDelta:Pmi(c),higherIsBetter:!1}]:[],u=t?[{id:`tokens`,icon:(0,K.jsx)(Z4,{}),label:`Tokens`,value:V7(H7(e)),rawValue:H7(e),delta:i??null,formatDelta:V7,higherIsBetter:!1}]:[],d=n==null?[]:[{id:`duration`,icon:(0,K.jsx)(tC,{}),label:`Duration`,value:iC(n)??`-`,rawValue:n,delta:a??null,formatDelta:Ami,higherIsBetter:!1}],f=o?[{id:`avg-score`,icon:(0,K.jsx)(G4,{}),label:`Avg score`,value:z7(o.value),rawValue:o.value,delta:o.delta??null}]:[];return[...l,...d,...f,...u,...s.map(e=>({id:`scorer:${e.scorerId}`,icon:(0,K.jsx)(JN,{}),label:e.label??(0,K.jsx)(epi,{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)(Imi,{scorerId:e.scorerId,reason:e.reason})]}):z7(e.value),rawValue:e.value,delta:e.delta??null}))]}function zgi({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 Bgi(e){return(0,G.useSyncExternalStore)(e.subscribe,e.read,()=>e.defaultValue)}var Vgi={cost:`cost`,"total-cost":`cost`,duration:`duration`,"avg-duration":`duration`,"avg-score":`average`,tokens:`tokens`,"total-tokens":`tokens`,errors:`errors`};function Hgi(e){return e.startsWith(`scorer:`)?e:Vgi[e]}var Ugi=[],Wgi=zgi({key:`mastra:experiments-compare:hidden-metrics`,defaultValue:Ugi,parse:e=>bd(q()).parse(e)});function Ggi(){let e=Bgi(Wgi);return{isHidden:t=>e.includes(t),isMetricVisible:t=>{let n=Hgi(t);return n===void 0||!e.includes(n)},toggle:t=>Wgi.write(e.includes(t)?e.filter(e=>e!==t):[...e,t]),reset:()=>Wgi.write(Ugi)}}function Kgi(e){return e==null?`-`:typeof e==`string`?e:JSON.stringify(e,null,2)}function qgi(e,t){return Rgi({usage:e.usage,showUsage:t,durationMs:J7(e),costDelta:e.costDelta,tokenDelta:e.tokenDelta,durationDeltaMs:e.durationDeltaMs,averageScore:e.scores.length>0?{value:kgi(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 Jgi({column:e,isLoading:t,showUsage:n=!1,outputExpanded:r,onOutputExpandedChange:i,onShowTrace:a}){let{isMetricVisible:o}=Ggi();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=Kgi(e.output),c=Cmi(e),l=R7(e),u=Omi(e),d=kmi(e),f=qgi(e,n).filter(e=>o(e.id)),{traceId:p}=e,m=p&&a?(0,K.jsx)(X,{size:`icon-sm`,variant:`ghost`,tooltip:`View trace`,"aria-label":`View trace`,onClick:()=>a(p),children:(0,K.jsx)(QN,{})}):void 0,h=f.length>0,g=e=>(0,K.jsxs)(K.Fragment,{children:[!h&&m,(0,K.jsx)(gC,{content:e,variant:`ghost`})]});return(0,K.jsxs)(`div`,{className:npi,children:[h&&(0,K.jsx)(L7,{title:`Metrics`,collapsible:!1,actions:m,children:(0,K.jsx)(tpi,{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)(sei,{toolCalls:u})}),e.comment&&(0,K.jsx)(L7,{title:`Comment`,framed:!0,children:(0,K.jsx)(I7,{value:e.comment})}),e.metadata&&Object.keys(e.metadata).length>0&&(0,K.jsx)(L7,{title:`Metadata`,framed:!0,actions:(0,K.jsx)(gC,{content:Kgi(e.metadata),variant:`ghost`}),children:(0,K.jsx)(I7,{value:e.metadata})})]})}var Ygi=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 Xgi({experiment:e,open:t,onOpenChange:n}){let[r,i]=(0,G.useState)(e.name??``),[a,o]=(0,G.useState)(e.description??``),{updateExperiment:s}=ON(),c=!!r.trim();return(0,K.jsx)(nT,{open:t,onOpenChange:n,pending:s.isPending,children:(0,K.jsxs)(rT,{children:[(0,K.jsx)(iT,{children:(0,K.jsx)(sT,{children:`Rename Experiment`})}),(0,K.jsxs)(ZV,{onSubmit:async t=>{if(t.preventDefault(),c&&!s.isPending&&e.datasetId)try{await s.mutateAsync({datasetId:e.datasetId,experimentId:e.id,name:r.trim(),description:a.trim()}),iS.success(`Experiment renamed`),n(!1)}catch(e){iS.error(`Failed to rename experiment: ${e instanceof Error?e.message:`Unknown error`}`)}},children:[(0,K.jsxs)(oT,{children:[(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{required:!0,children:`Name`}),(0,K.jsx)(Jj,{required:!0,value:r,onChange:e=>i(e.target.value),placeholder:`Enter experiment name`,autoFocus:!0})]}),(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{children:`Description`}),(0,K.jsx)(Jj,{value:a,onChange:e=>o(e.target.value),placeholder:`Enter experiment description (optional)`})]})]}),(0,K.jsxs)(aT,{children:[(0,K.jsx)(lT,{children:`Cancel`}),(0,K.jsx)(tT,{type:`submit`,disabled:!c,children:s.isPending?`Saving...`:`Save`})]})]})]})})}function Zgi({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 Qgi({role:e,label:t,experiment:n,onSetBaseline:r}){let{Link:i}=sn(),[a,o]=(0,G.useState)(!1),s=n?aH(n.id)??n.id:null,l=!!n?.datasetId;return(0,K.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[n&&(0,K.jsxs)(rE,{children:[(0,K.jsx)(rE.Trigger,{render:(0,K.jsxs)(X,{size:`sm`,className:`max-w-full min-w-0`,children:[(0,K.jsx)(`span`,{className:`min-w-0 truncate`,children:n.name||s}),(0,K.jsx)(_,{"aria-hidden":!0})]})}),(0,K.jsxs)(rE.Content,{align:`start`,className:`min-w-48`,children:[(0,K.jsxs)(rE.Item,{render:(0,K.jsx)(i,{href:`/experiments/${n.id}`}),children:[(0,K.jsx)(tZ,{}),` View experiment`]}),l&&(0,K.jsxs)(rE.Item,{onSelect:()=>o(!0),children:[(0,K.jsx)(iH,{}),` Rename experiment`]})]})]}),n&&a&&(0,K.jsx)(Xgi,{experiment:n,open:!0,onOpenChange:o}),(0,K.jsx)(`div`,{className:`ml-auto shrink-0`,children:r?(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{render:(0,K.jsx)(`button`,{type:`button`,"aria-label":`Set as baseline`,onClick:r,className:c(`cursor-pointer rounded-[7px] hover:brightness-110`,p)}),children:(0,K.jsx)(eC,{variant:Mhi[e],size:`md`,icon:(0,K.jsx)(AK,{}),children:t})}),(0,K.jsx)(Tx,{children:`Set as baseline`})]}):(0,K.jsx)(eC,{variant:Mhi[e],size:`md`,icon:e===`baseline`?(0,K.jsx)(AK,{className:`fill-current`}):(0,K.jsx)(AK,{}),children:t})})]})}function $gi({role:e,experiment:t,summary:n,metrics:r,baselineMetrics:i,versionMismatch:a,showUsage:o=!1}){let{Link:s,paths:c}=sn(),{isMetricVisible:l}=Ggi(),u=t?.createdAt?new Date(t.createdAt):null,d=e===`contender`,f=(e,t)=>d?jmi(e,t):null,p=t?[...t.targetId?[{id:`target`,icon:t.targetType===`agent`?(0,K.jsx)(HN,{}):(0,K.jsx)(Ygi,{}),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)(rhi,{}),label:`Dataset version`,value:(0,K.jsx)(Zgi,{datasetId:t.datasetId,version:t.datasetVersion,differsFromBaseline:a}),delta:null}]:[],...u?[{id:`created-at`,icon:(0,K.jsx)($j,{}),label:`Created`,value:bC(u,`date`),delta:null}]:[]]:[],m=o?r:void 0,h=[...m?[{id:`total-cost`,icon:(0,K.jsx)(Lgi,{}),label:`Total cost`,value:B7(m.cost,m.costUnit),rawValue:m.cost,delta:m.costUnit===i?.costUnit?f(m.cost,i?.cost):null,formatDelta:Pmi(m.costUnit),higherIsBetter:!1,emphasis:!0}]:[],...r?[{id:`avg-duration`,icon:(0,K.jsx)(tC,{}),label:`Avg duration`,value:iC(r.averageDurationMs)??`-`,rawValue:r.averageDurationMs,delta:f(r.averageDurationMs,i?.averageDurationMs),formatDelta:Ami,higherIsBetter:!1,emphasis:!0}]:[],...r&&n&&n.length>0?[{id:`avg-score`,icon:(0,K.jsx)(G4,{}),label:`Avg score`,value:z7(r.averageScore),rawValue:r.averageScore,delta:f(r.averageScore,i?.averageScore),emphasis:!0}]:[],...m?[{id:`total-tokens`,icon:(0,K.jsx)(Z4,{}),label:`Total tokens`,value:V7(m.tokens),rawValue:m.tokens,delta:f(m.tokens,i?.tokens),formatDelta:V7,higherIsBetter:!1}]:[],...p,...r?[{id:`errors`,icon:(0,K.jsx)(Xx,{}),label:`Errors`,value:String(r.errorCount),delta:f(r.errorCount,i?.errorCount),formatDelta:String,higherIsBetter:!1}]:[],...(n??[]).map(({scorerId:e,average:t,delta:n})=>({id:`scorer:${e}`,icon:(0,K.jsx)(JN,{}),label:(0,K.jsx)(epi,{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)(tpi,{metrics:h})})}function e_i(e){return(0,K.jsx)(Gri,{...e,headerActionsSlot:e.traceId?(0,K.jsx)(_si,{traceId:e.traceId,spans:e.spans},e.traceId):void 0})}function t_i({traceId:e,onClose:t,withQueryTrace:n,withFeedback:r}){let{navigate:i}=sn(),[a,o]=(0,G.useState)(),{data:s,isLoading:c}=lmi({traceId:e,queryOptions:{enabled:!!e}}),l=s?.spans,u=l?.find(e=>!e.parentSpanId),{data:d}=s8({traceId:e,queryOptions:{enabled:r&&!!e}}),{data:f}=o8({traceId:e,spanId:a,queryOptions:{enabled:r&&!!e&&!!a}}),{data:p}=BN({traceId:e,spanId:u?.spanId,page:0,queryOptions:{enabled:!!e&&!!u?.spanId}});return(0,K.jsx)(e_i,{size:`wide`,traceId:e,spans:l,isLoadingSpans:c,selectedSpanId:a??null,onClose:()=>{o(void 0),t()},onSpanSelect:o,showUnavailableFeaturesMsg:!1,traceHref:e?`/traces?traceId=${encodeURIComponent(e)}`:void 0,anchorSpanId:u?.spanId,withQueryTrace:n,withFeedback:r,onOpenScore:(e,t)=>i(CK(e,t)),feedbackTabBadge:r?d?.pagination?.total??void 0:void 0,feedbackTabSlot:r?({traceId:e})=>(0,K.jsx)(B5,{traceId:e}):void 0,scoresTabBadge:p?.pagination?.total??void 0,scoresTabSlot:({traceId:e,rootSpanId:t})=>t?(0,K.jsx)(eLr,{traceId:e,spanId:t,onScoreSelect:t=>i(CK(e,t))}):null,spanFeedbackTabBadge:r?f?.pagination?.total??void 0:void 0,spanFeedbackTabSlot:r?({traceId:e,spanId:t})=>e&&t?(0,K.jsx)(Z7r,{traceId:e,spanId:t},`${e}:${t}`):null:void 0})}var Y7=`min-w-0 px-4 py-3`,n_i=`grid grid-cols-[minmax(22rem,26rem)_repeat(var(--compare-cols),minmax(32rem,1fr))] divide-x divide-border border-border`,r_i=e=>!(e.target instanceof Element)||!e.currentTarget.contains(e.target)||e.target.closest(`a, button, input, select, textarea, [role="button"], [role="link"], [data-slot="collapsible-box-fade"]`)!==null,i_i=()=>!!window.getSelection()?.toString(),a_i=e=>e!=null,o_i=e=>e.length>0?e.reduce((e,t)=>e+t,0)/e.length:null,s_i=(e,t,n)=>o_i(e.map(e=>e.sides[t]?.scores.find(e=>e.scorerId===n)?.value??null).filter(a_i)),c_i=(e,t)=>{let n=e.map(e=>e.sides[t]).filter(e=>e?.present);return{errorCount:n.filter(e=>e.error).length,averageScore:o_i(n.flatMap(e=>e.scores.map(e=>e.value)).filter(a_i)),averageDurationMs:o_i(n.map(J7).filter(a_i))}};function l_i({datasetId:e,baselineId:t,contenderIds:n,onSetBaseline:r}){let i=(0,G.useMemo)(()=>[t,...n],[t,n]),[a,o]=(0,G.useState)(),[s,l]=(0,G.useState)(),u=a5(),d=e=>{l(void 0),o(e)},f=e=>{o(void 0),l(e)},{data:p,isLoading:m,error:h}=bAt({datasetId:e,experimentIds:i,baselineId:t,queryOptions:{enabled:!!e&&!!t&&n.length>0}}),{data:g,isLoading:_}=kAt({datasetId:e,experimentIds:i}),v=(0,G.useMemo)(()=>i.map(e=>({id:e,status:g[e]?.status})),[i,g]),{data:y,isLoading:b}=jAt({datasetId:e,experiments:v}),{data:x}=MAt({experiments:v}),{supportsMetrics:S,isLoading:C}=S7(),{data:w,isLoading:E}=smi({experiments:v,supportsMetrics:S}),D=(0,G.useMemo)(()=>Pgi({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=s_i(D,n,e),r=s_i(D,0,e);return{scorerId:e,average:t,delta:n>0&&t!=null&&r!=null?t-r:null}}))},[D,i]),k=(0,G.useMemo)(()=>i.map((e,t)=>{let n=w[e]?.summary;return{...c_i(D,t),cost:n?.estimatedCost,costUnit:n?.costUnit,tokens:H7(n)}}),[D,i,w]);if(m||_||C||E)return(0,K.jsx)(`div`,{className:`pointer-events-none fixed inset-0 flex items-center justify-center`,children:(0,K.jsx)(It,{})});if(h)return(0,K.jsx)(Sk,{variant:`warning`,title:`Error loading comparison`,children:(0,K.jsx)(Sk.Message,{children:h instanceof Error?h.message:`Unknown error`})});if(!p||p.items.length===0)return(0,K.jsx)(T,{as:`p`,variant:`body`,tone:`muted`,className:`py-5 text-center`,children:`No comparison data`});let A=g[t];return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{role:`table`,"aria-label":`Experiments comparison`,className:`grid min-w-[calc(22rem_+_var(--compare-cols)_*_32rem)]`,style:{"--compare-cols":i.length},children:[(0,K.jsxs)(`div`,{role:`row`,className:c(n_i,`sticky top-0 z-20 bg-background`),children:[(0,K.jsx)(`div`,{role:`columnheader`,"aria-label":`Items`,className:Y7}),i.map((e,t)=>(0,K.jsx)(`div`,{role:`columnheader`,"aria-label":W7(t),className:c(Y7,`border-b`),children:(0,K.jsx)(Qgi,{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(n_i,`border-b`),children:[(0,K.jsx)(`div`,{role:`cell`,"aria-label":`Items`,className:Y7}),i.map((e,t)=>{let n=g[e]??void 0;return(0,K.jsx)(`div`,{role:`cell`,"aria-label":W7(t),className:Y7,children:(0,K.jsx)($gi,{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)(u_i,{row:e,isLoading:b,showUsage:S,onOpen:()=>d(e.itemId),onShowTrace:f},e.itemId))]}),(0,K.jsx)(Fgi,{datasetId:e,itemId:a,onClose:()=>o(void 0)}),(0,K.jsx)(t_i,{traceId:s,onClose:()=>l(void 0),withQueryTrace:u.enabled,withFeedback:u.enabled})]})}function u_i({row:e,isLoading:t,showUsage:n,onOpen:r,onShowTrace:i}){let[a,o]=(0,G.useState)({input:!1,groundTruth:!1,output:!1}),s=e=>({expanded:a[e],onExpandedChange:t=>o(n=>({...n,[e]:t}))}),l=s(`output`);return(0,K.jsxs)(`div`,{role:`row`,"aria-label":e.itemId,tabIndex:0,onClick:e=>{r_i(e)||i_i()||r()},onKeyDown:e=>{e.target!==e.currentTarget||e.key!==`Enter`&&e.key!==` `||(e.preventDefault(),r())},className:c(n_i,`cursor-pointer border-b transition-colors duration-normal ease-out-custom hover:bg-fill-subtle`,m),children:[(0,K.jsxs)(`div`,{role:`cell`,className:c(Y7,npi),children:[(0,K.jsx)(Igi,{label:`Input`,value:e.input,...s(`input`)}),(0,K.jsx)(Igi,{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)(Jgi,{column:e,isLoading:t,showUsage:n,outputExpanded:l.expanded,onOutputExpandedChange:l.onExpandedChange,onShowTrace:i})},e.experimentId))]})}function d_i(e){let t=new Map;if(!e?.counts)return t;for(let n of e.counts)t.set(n.experimentId,{needsReview:n.needsReview,complete:n.complete,total:n.total});return t}var X7=[eP(`/experiments`)],f_i=[`createdAt`,`status`],p_i=new Map;function m_i(){let[e,t]=(0,G.useState)(``),[n,r]=(0,G.useState)(`all`),[i,a]=(0,G.useState)(!1),[o,s]=(0,G.useState)([]),c=Ov(),[l,u]=Rv(),{sort:d,onSortChange:f}=u7({searchParams:l,setSearchParams:u,allowedKeys:f_i}),p=(0,G.useMemo)(()=>d?{field:d.key,direction:d.direction===`asc`?`ASC`:`DESC`}:void 0,[d]),m=l.get(`dataset`)??`all`,{targetType:h,targetId:g}=jli(),_=e=>{t(e.search),r(e.statusFilter),u(t=>{let n=new URLSearchParams(t),r=(e,t)=>{t?n.set(e,t):n.delete(e)};return r(`dataset`,e.datasetFilter===`all`?``:e.datasetFilter),r(O7,e.targetType),r(k7,e.targetType===h?e.targetId:``),n},{replace:!0})},{data:v,isLoading:y,error:b}=kN(),{data:x,isLoading:S,error:C,isFetchingNextPage:w,hasNextPage:T,setEndOfListElement:E}=vmi({datasetId:m===`all`?void 0:m,target:{targetType:h,targetId:g},orderBy:p}),{data:D}=jhi(),{supportsMetrics:O}=S7(),k=(0,G.useMemo)(()=>v?.datasets??[],[v?.datasets]),A=(0,G.useMemo)(()=>x??[],[x]),j=(0,G.useMemo)(()=>lgi(k),[k]),{data:M}=yAt({datasetIds:(0,G.useMemo)(()=>A.flatMap(e=>e.datasetId?[e.datasetId]:[]),[A])}),N=(0,G.useMemo)(()=>{let e=new Map(k.map(e=>[e.id,e]));return M?.forEach(t=>e.set(t.id,t)),[...e.values()]},[k,M]),{data:P}=_mi({experiments:A,supportsMetrics:O}),F=O?P??p_i:void 0,I=(0,G.useMemo)(()=>d_i(D),[D]),L=y||S,R=C||b,z=e=>{let t=new Set(A.map(e=>e.id));s(n=>{let r=n.filter(e=>t.has(e));return r.includes(e)?r.filter(t=>t!==e):r.length>=10?[...r.slice(0,9),e]:[...r,e]})},B=e=>{let t=new Map(A.map(e=>[e.id,e.datasetId])),n=t.get(e[0]);s(r=>r.length>0?[]:e.filter(e=>t.get(e)===n).slice(0,10))},{selectedIds:V,selectedDatasetIds:H}=(0,G.useMemo)(()=>{let e=new Map(A.map(e=>[e.id,e.datasetId])),t=o.filter(t=>e.has(t));return{selectedIds:t,selectedDatasetIds:new Set(t.map(t=>e.get(t)))}},[A,o]),ee=A.find(e=>e.id===V[0])?.datasetId??void 0,te=ee?{id:ee,name:N.find(e=>e.id===ee)?.name??ee}:void 0,U=V.length<2?`Select at least two experiments to compare`:H.size===1?void 0:`Only experiments from the same dataset can be compared`,W=()=>{if(V.length<2||U)return;let[e,...t]=V,[n]=H;if(!n)return;let r=new URLSearchParams({dataset:n,baseline:e});for(let e of t)r.append(`contender`,e);c(`/experiments/compare?${r.toString()}`)};if(R&&FN(R))return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:X7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(TH,{variant:`fill`})]});if(C&&IN(C))return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:X7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(wH,{variant:`fill`,resource:`experiments`})]});if(b&&IN(b))return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:X7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(wH,{variant:`fill`,resource:`datasets`})]});if(R)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:X7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load experiments`,descriptionSlot:R.message})]});let ne=(0,K.jsx)(Xpi,{open:i,onOpenChange:a,onSuccess:e=>void c(`/experiments/${e}`)});return A.length===0&&!L&&m===`all`&&!h?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:X7}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiments`}),(0,K.jsx)(ugi,{onRunExperiment:()=>a(!0)}),ne]}):(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:X7}),headerActions:(0,K.jsx)(X,{variant:`primary`,size:`sm`,icon:(0,K.jsx)(Hx,{}),onClick:()=>a(!0),children:`New experiment`}),actionRow:(0,K.jsx)(Cgi,{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)(sgi,{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 h_i={baseline:`bg-badge-purple-indicator`,contender:`bg-badge-blue-indicator`};function g_i({experimentId:e,name:t,role:n,className:r,trailing:i}){let{Link:a,paths:o}=sn(),s=t||e.slice(0,8);return(0,K.jsxs)(X,{render:(0,K.jsx)(a,{href:o.experimentLink(e)}),variant:`ghost`,size:`sm`,className:c(`max-w-48 min-w-0`,r),"aria-label":`Open experiment ${s}`,children:[n&&(0,K.jsx)(`span`,{"aria-hidden":`true`,className:c(`size-1.5 shrink-0 rounded-full`,h_i[n])}),(0,K.jsx)(`span`,{className:`min-w-0 truncate`,children:s}),i&&(0,K.jsx)(`span`,{className:`ml-auto flex shrink-0`,children:i})]})}function __i(){let[e]=Rv(),t=e.get(`dataset`)??void 0,n=e.get(`baseline`)??void 0;return{datasetId:t,baselineId:n,contenderIds:(0,G.useMemo)(()=>[...new Set(e.getAll(`contender`))].filter(e=>e&&e!==n).slice(0,9),[e,n])}}function v_i(){let{datasetId:e,baselineId:t,contenderIds:n}=__i();return{datasetId:e,experimentIds:e&&t&&n.length>0&&t?[t,...n]:[]}}function y_i(){let{experimentIds:e}=v_i();return e.length>0?`Comparing ${e.length} experiments`:`Comparing`}function b_i(){let{datasetId:e,experimentIds:t}=v_i(),{data:n}=kAt({datasetId:e??``,experimentIds:t});return t.length===0?null:(0,K.jsxs)(yX,{children:[(0,K.jsx)(bX,{delay:0,closeDelay:100,render:(0,K.jsx)(X,{type:`button`,variant:`ghost`,size:`icon-sm`,"aria-label":`Show compared experiments`,children:(0,K.jsx)(_,{})})}),(0,K.jsx)(xX,{side:`bottom`,align:`end`,sideOffset:4,showArrow:!1,className:`w-72 p-1.5`,children:(0,K.jsx)(`ul`,{"aria-label":`Compared experiments`,className:`grid gap-0.5`,children:t.map((e,t)=>(0,K.jsx)(`li`,{className:`grid`,children:(0,K.jsx)(g_i,{className:`w-full max-w-none justify-start`,experimentId:e,name:n[e]?.name,role:t===0?`baseline`:`contender`,trailing:t===0&&(0,K.jsx)(eC,{variant:`purple`,size:`sm`,icon:(0,K.jsx)(AK,{className:`fill-current`}),children:`Baseline`})})},e))})})]})}function x_i({experimentIds:e}){return e.map((t,n)=>(0,K.jsxs)(`span`,{className:`flex items-center gap-2`,children:[n>0&&n===e.length-1&&`and`,(0,K.jsxs)(`span`,{className:`flex items-center`,children:[(0,K.jsx)(g_i,{experimentId:t}),n<e.length-2&&`,`]})]},t))}function S_i({datasetId:e,baselineId:t,contenderIds:n}){let[,r]=Rv(),i=(0,G.useMemo)(()=>[t,...n],[t,n]),{data:a,isLoading:o,error:s}=kAt({datasetId:e,experimentIds:i});return s&&FN(s)?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Compare`}),(0,K.jsx)(TH,{variant:`fill`})]}):s&&IN(s)?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Compare`}),(0,K.jsx)(wH,{variant:`fill`,resource:`experiments`})]}):s&&!LN(s)?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Compare`}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load experiments`,descriptionSlot:s.message})]}):!o&&(s||i.some(e=>!a[e]))?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Compare`}),(0,K.jsx)(`div`,{className:`grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto`,children:(0,K.jsxs)(`div`,{className:`py-5 text-center text-muted-foreground`,children:[(0,K.jsxs)(T,{as:`p`,children:[`Experiments must belong to the same dataset (`,e,`) to be compared.`]}),(0,K.jsxs)(T,{className:`mt-2 flex items-center justify-center gap-2`,children:[`One of`,(0,K.jsx)(x_i,{experimentIds:i}),`was not found in it.`]})]})})]}):(0,K.jsx)(`div`,{className:`h-full overflow-auto`,children:(0,K.jsxs)(`div`,{className:`grid w-full content-start`,children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Experiments comparison`}),(0,K.jsx)(l_i,{datasetId:e,baselineId:t,contenderIds:n,onSetBaseline:t=>{let n=new URLSearchParams({dataset:e,baseline:t});for(let e of i)e!==t&&n.append(`contender`,e);r(n)}})]})})}function C_i(){let{datasetId:e,baselineId:t,contenderIds:n}=__i();return!e||!t||n.length===0?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h1`,variant:`heading`,className:`sr-only`,children:`Compare`}),(0,K.jsx)(`div`,{className:`grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto`,children:(0,K.jsxs)(`div`,{className:`py-5 text-center text-muted-foreground`,children:[(0,K.jsx)(T,{as:`p`,children:`Select two to ten experiments to compare.`}),(0,K.jsxs)(T,{className:`mt-2`,children:[`Use the URL format: /experiments/compare?dataset=`,`{datasetId}`,`&baseline=`,`{experimentId}`,`&contender=`,`{experimentId}`,`&contender=`,`{experimentId}`]})]})})]}):(0,K.jsx)(S_i,{datasetId:e,baselineId:t,contenderIds:n})}function w_i(){let{datasetId:e}=__i(),{Link:t,paths:n}=sn(),{data:r,isLoading:i}=AN({datasetId:e??``,queryOptions:{enabled:!!e}});if(!e||i)return null;let a=r?.name||e;return(0,K.jsx)(t,{href:n.datasetLink(e),"aria-label":`Open dataset ${a}`,className:c(`flex max-w-64 min-w-0 rounded-[7px] hover:brightness-110`,p),children:(0,K.jsx)(eC,{size:`md`,icon:(0,K.jsx)(uT,{}),className:`max-w-full min-w-0`,children:(0,K.jsx)(`span`,{className:`min-w-0 truncate`,children:a})})})}var T_i=[{key:`cost`,label:`Cost`,usage:!0},{key:`duration`,label:`Duration`},{key:`average`,label:`Avg score`},{key:`tokens`,label:`Tokens`,usage:!0},{key:`errors`,label:`Errors`}];function E_i({datasetId:e,baselineId:t,contenderIds:n}){let{data:r}=bAt({datasetId:e,experimentIds:(0,G.useMemo)(()=>[t,...n],[t,n]),baselineId:t}),{supportsMetrics:i}=S7(),{isHidden:a,toggle:o,reset:s}=Ggi(),c=(0,G.useMemo)(()=>[...new Set((r?.items??[]).flatMap(e=>Object.values(e.results).flatMap(e=>e?Object.keys(e.scores):[])))].sort(),[r]),l=T_i.filter(e=>i||!e.usage);return(0,K.jsxs)(rE,{children:[(0,K.jsx)(rE.Trigger,{render:(0,K.jsx)(X,{variant:`ghost`,size:`md`,icon:(0,K.jsx)(X0r,{"aria-hidden":!0}),children:`Metrics`})}),(0,K.jsxs)(rE.Content,{align:`end`,className:`min-w-56`,children:[(0,K.jsx)(rE.Label,{children:`Run metrics`}),l.map(e=>(0,K.jsx)(rE.CheckboxItem,{checked:!a(e.key),onCheckedChange:()=>o(e.key),children:e.label},e.key)),c.length>0&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(rE.Separator,{}),(0,K.jsx)(rE.Label,{children:`Scorers`}),c.map(e=>{let t=`scorer:${e}`;return(0,K.jsx)(rE.CheckboxItem,{checked:!a(t),onCheckedChange:()=>o(t),children:e},t)})]}),(0,K.jsx)(rE.Separator,{}),(0,K.jsx)(rE.Item,{onSelect:s,children:`Show all metrics`})]})]})}function D_i(){let{datasetId:e,baselineId:t,contenderIds:n}=__i();return(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[e&&t&&n.length>0&&(0,K.jsx)(E_i,{datasetId:e,baselineId:t,contenderIds:n}),(0,K.jsx)(w_i,{})]})}var O_i=[eP(`/experiments`),{id:`experiments-compare`,Component:y_i,Switcher:b_i}];function k_i(){return(0,K.jsx)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:O_i}),headerActions:(0,K.jsx)(D_i,{}),children:(0,K.jsx)(C_i,{})})}function A_i(e){let{data:t}=jN({experimentId:e.id,experimentStatus:e.status,queryOptions:{enabled:!!e.id}});return(0,G.useMemo)(()=>{if(e.scorerIds?.length)return e.scorerIds;if(!t)return[];let n=new Set;for(let e of Object.values(t))for(let t of e)n.add(t.scorerId);return[...n].sort()},[e.scorerIds,t])}var j_i=[`agent`,`workflow`,`scorer`];function M_i({experiment:e}){let[t,n]=(0,G.useState)(!1),r=Ov(),{paths:i}=sn(),a=A_i(e),o=j_i.find(t=>t===e.targetType),s=e.status===`running`||e.status===`pending`;return!e.datasetId||!o||!e.targetId?null:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(X,{variant:`primary`,size:`sm`,onClick:()=>n(!0),disabled:s,tooltip:s?`Available once this run finishes`:`Run this experiment again with the same configuration`,icon:(0,K.jsx)(DT,{}),children:`Rerun`}),t&&(0,K.jsx)(Xpi,{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 N_i({experiment:e,onDeleteClick:t}){let[n,r]=(0,G.useState)(!1),i=!!e.datasetId;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(M_i,{experiment:e}),(i||!!t)&&(0,K.jsxs)(rE,{children:[(0,K.jsx)(rE.Trigger,{asChild:!0,children:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,"aria-label":`Experiment actions menu`,children:(0,K.jsx)(iE,{})})}),(0,K.jsxs)(rE.Content,{align:`end`,className:`w-48`,children:[i&&(0,K.jsxs)(rE.Item,{onSelect:()=>r(!0),children:[(0,K.jsx)(iH,{}),` Rename experiment`]}),t&&(0,K.jsxs)(rE.Item,{onSelect:t,variant:`destructive`,children:[(0,K.jsx)(Kj,{}),` Delete experiment`]})]})]}),n&&(0,K.jsx)(Xgi,{experiment:e,open:!0,onOpenChange:r})]})}var P_i=U(`IconCircleRecord`,()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{fillRule:`evenodd`,clipRule:`evenodd`,d:`M9.91422 10.5858C10.6953 11.3668 10.6953 12.6332 9.91422 13.4142C9.13317 14.1953 7.86684 14.1953 7.08579 13.4142C6.30474 12.6332 6.30474 11.3668 7.08579 10.5858C7.86684 9.80474 9.13317 9.80474 9.91422 10.5858Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{fillRule:`evenodd`,clipRule:`evenodd`,d:`M16.9142 10.5858C17.6953 11.3668 17.6953 12.6332 16.9142 13.4142C16.1332 14.1953 14.8668 14.1953 14.0858 13.4142C13.3047 12.6332 13.3047 11.3668 14.0858 10.5858C14.8668 9.80474 16.1332 9.80474 16.9142 10.5858Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M8.5 14H15.5`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`}),(0,K.jsx)(`path`,{d:`M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z`,stroke:`currentColor`,strokeWidth:`2`})]}));function F_i(e){let{data:t,isLoading:n}=i8({traceId:e,queryOptions:{enabled:!!e}}),r=t?.spans.find(e=>!e.parentSpanId)?.entityType===`agent`,{supportsMetrics:i,isLoading:a}=S7(),o=r&&i,s=uXr({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 I_i=`__create_tag__`;function L_i({selectedResults:e,vocabulary:t,onAddTag:n,disabled:r,variant:i}){let[a,o]=(0,G.useState)(``),s=(0,G.useMemo)(()=>[...t].sort(),[t]),c=(0,G.useMemo)(()=>{if(e.length===0)return new Set;let[t,...n]=e;return new Set((t.tags??[]).filter(e=>n.every(t=>(t.tags??[]).includes(e))))},[e]),l=(0,G.useMemo)(()=>{let e=s.map(e=>({label:e,value:e,end:c.has(e)?(0,K.jsx)(pC,{"data-testid":`tag-applied`,className:`size-icon-sm`}):void 0})),t=a.trim();return t.length>0&&!s.includes(t)?[{label:`Create "${t}"`,value:I_i},...e]:e},[s,c,a]);return(0,K.jsx)(_N,{"data-testid":`experiment-results-tag-picker`,options:l,value:void 0,onValueChange:e=>{let t=e===I_i?a.trim():e;t&&!c.has(t)&&n(t)},onInputValueChange:o,placeholder:`Add tag`,searchPlaceholder:`Search or create tag`,emptyText:`Type to create a tag`,variant:i,size:`sm`,className:`w-auto min-w-0`,disabled:r})}function R_i(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function z_i({report:e}){let{served:t,unconsumed:n,liveCalls:r,failure:i}=e,a=[...t.map(e=>({outcome:`served`,toolName:e.toolName,args:e.args})),...r.map(e=>({outcome:`live`,toolName:e.toolName,args:e.args})),...n.map(e=>({outcome:`unconsumed`,toolName:e.toolName,args:e.args}))];return(0,K.jsxs)(`div`,{className:`grid gap-2`,"data-testid":`tool-mock-report`,children:[(0,K.jsx)(jQ.SectionHeading,{icon:(0,K.jsx)(YS,{}),children:`Tool Mocks`}),i&&(0,K.jsx)(Sk,{variant:`destructive`,title:`Mock mismatch`,children:(0,K.jsxs)(Sk.Message,{children:[(0,K.jsx)(`span`,{className:`block`,children:`Tool "${i.toolName}" was called with arguments that did not match an available mock (${i.code}).`}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`mt-1 block`,children:[`Called with: `,(0,K.jsx)(uX,{children:R_i(i.args)})]}),n.length>0&&(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`mt-1 block`,children:[`Unconsumed mocks: `,(0,K.jsx)(uX,{children:n.map(e=>R_i(e.args)).join(`, `)})]})]})}),(0,K.jsx)(`div`,{className:`divide-y divide-border rounded border border-border`,children:a.map((e,t)=>(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-2 px-3 py-1.5`,children:[(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`min-w-0 truncate`,children:[(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`muted`,font:`mono`,children:e.toolName}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,font:`mono`,className:`ml-2`,children:R_i(e.args)})]}),(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`shrink-0 rounded px-2 py-0.5 ${B_i(e.outcome)}`,children:e.outcome})]},`${e.outcome}-${e.toolName}-${t}`))})]})}function B_i(e){switch(e){case`served`:return`bg-success-subtle text-success-subtle-foreground`;case`live`:return`bg-badge-orange-subtle text-badge-orange-foreground`;case`unconsumed`:return`bg-muted-foreground/10 text-muted-foreground`}}function V_i({result:e,itemId:t,fallback:n,title:r,onClose:i,variant:a=`drawer`,...o}){let s=r??(t?`Experiment item ${t}`:`Experiment result ${e?.id??``}`),c=e?(0,K.jsx)(H_i,{result:e,onClose:i,...o}):t?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(jQ.Header,{children:[(0,K.jsxs)(jQ.Heading,{children:[`Experiment item`,(0,K.jsx)(jQ.CopyId,{id:t})]}),(0,K.jsx)(jQ.HeaderActions,{children:(0,K.jsx)(jQ.CloseButton,{icon:`x`,onClick:i})})]}),n]}):null;return a===`inline`?c?(0,K.jsx)(jQ,{variant:`inline`,title:s,children:c}):null:(0,K.jsx)(jQ,{open:!!(e??t),onClose:i,title:s,depth:1,children:c})}function H_i({result:e,scores:t,onPrevious:n,onNext:r,onClose:i,onShowTrace:a,onScoreClick:o,featuredScoreId:s,onFlagForReview:c,onTagsChange:l,tagVocabulary:u=[],isUpdatingTags:d=!1,experimentLink:f,onComplete:p,feedbackTabSlot:m}){let h=G_i(e.input),g=G_i(e.output),_=Cmi(e),v=Omi(e),y=kmi(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}=F_i(e.traceId),A=k&&(e.targetType==null||e.targetType===`agent`),j=Rgi({usage:O,showUsage:!!O||A,durationMs:J7(e),scores:[]}).map(e=>A&&(e.id===`cost`||e.id===`tokens`)?{...e,value:(0,K.jsx)(zS,{"aria-hidden":!0,className:`h-4 w-14`})}:e),M=typeof e.error==`string`&&e.error?e.error:R7(e),N=[...j,{id:`item-id`,icon:(0,K.jsx)(W6,{}),label:`Item Id`,value:(0,K.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,K.jsx)(`span`,{className:`font-mono`,title:e.itemId,children:aH(e.itemId)}),(0,K.jsx)(gC,{content:e.itemId,tooltip:`Copy item ID to clipboard`,variant:`link`})]}),delta:null},...e.createdAt?[{id:`created`,icon:(0,K.jsx)($j,{}),label:`Created`,value:bC(e.createdAt,`date-time`),delta:null}]:[],...e.status?[{id:`status`,icon:(0,K.jsx)(P_i,{}),label:`Status`,value:(0,K.jsx)(y7r,{status:e.status}),delta:null}]:[],...C?[{id:`tags`,icon:(0,K.jsx)(wX,{}),label:`Tags`,value:(0,K.jsx)(W_i,{tags:x,selectedResults:S,onTagsChange:l,tagVocabulary:u,isUpdatingTags:d}),delta:null}]:[],...Rgi({showUsage:!1,durationMs:null,scores:(t??[]).map(e=>({scorerId:e.scorerId,value:e.score,reason:e.reason,label:o?(0,K.jsx)(U_i,{scorerId:e.scorerId,featured:s===e.id,onClick:()=>o(e.id)}):void 0}))})],P=(0,K.jsx)(jQ.Content,{children:(0,K.jsxs)(`div`,{className:npi,children:[(0,K.jsx)(tpi,{metrics:N}),(0,K.jsx)(L7,{title:`Input`,framed:!0,actions:(0,K.jsx)(gC,{content:h}),children:(0,K.jsx)(I7,{value:e.input})}),e.groundTruth!=null&&(0,K.jsx)(L7,{title:`Ground Truth`,framed:!0,actions:(0,K.jsx)(gC,{content:G_i(e.groundTruth)}),children:(0,K.jsx)(I7,{value:e.groundTruth})}),M?(0,K.jsx)(L7,{title:`Error`,tone:`negative`,framed:!0,actions:(0,K.jsx)(gC,{content:M}),children:(0,K.jsx)(T,{tone:`muted`,className:`p-3 break-words`,children:M})}):(0,K.jsx)(L7,{title:`Output`,framed:!0,actions:(0,K.jsx)(gC,{content:g}),children:y?(0,K.jsx)(T,{tone:`muted`,className:`p-3 break-words`,children:y}):(0,K.jsx)(I7,{value:_??e.output})}),v.length>0&&(0,K.jsx)(L7,{title:`Tool calls (${v.length})`,children:(0,K.jsx)(sei,{toolCalls:v})}),e.toolMockReport&&(0,K.jsx)(z_i,{report:e.toolMockReport})]})});return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(jQ.Header,{children:[b&&(0,K.jsx)(X,{size:`sm`,variant:`primary`,onClick:()=>c(e.id),icon:(0,K.jsx)(UN,{}),children:`Request review`}),p&&e.status===`needs-review`&&(0,K.jsx)(X,{size:`sm`,variant:`primary`,onClick:p,icon:(0,K.jsx)(EX,{}),children:`Mark as reviewed`}),(0,K.jsxs)(jQ.HeaderActions,{children:[f&&(0,K.jsx)(X,{size:`icon-sm`,variant:`ghost`,render:(0,K.jsx)(w,{href:f}),tooltip:`See experiment`,"aria-label":`See experiment`,children:(0,K.jsx)(GN,{})}),e.traceId&&a&&(0,K.jsx)(X,{size:`icon-sm`,variant:`ghost`,onClick:a,tooltip:`See trace`,"aria-label":`See trace`,children:(0,K.jsx)(QN,{})}),(0,K.jsx)(jQ.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:`Go to previous result`,nextLabel:`Go to next result`}),(0,K.jsx)(jQ.CloseButton,{icon:`x`,onClick:i})]})]}),E?(0,K.jsxs)(gk,{defaultTab:`details`,className:`grid h-full min-h-0 grid-rows-[auto_1fr]`,children:[(0,K.jsx)(jQ.Header,{children:(0,K.jsxs)(hk,{variant:`pill-ghost`,size:`sm`,children:[(0,K.jsx)(_k,{value:`details`,children:`Details`}),(0,K.jsxs)(_k,{value:`feedback`,children:[`Feedback`,D?.pagination?.total!=null&&(0,K.jsxs)(K.Fragment,{children:[` (`,D.pagination.total,`)`]})]})]})}),(0,K.jsx)(vk,{value:`details`,flush:!0,children:P}),(0,K.jsx)(vk,{value:`feedback`,flush:!0,children:(0,K.jsx)(jQ.Content,{children:m({traceId:E})})})]}):P]})}function U_i({scorerId:e,featured:t,onClick:n}){return(0,K.jsx)(`button`,{type:`button`,"aria-pressed":t,onClick:n,className:c(`min-w-0 cursor-pointer truncate hover:text-foreground hover:underline`,t&&`text-foreground`),children:e})}function W_i({tags:e,selectedResults:t,onTagsChange:n,tagVocabulary:r,isUpdatingTags:i}){return(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center justify-end gap-1.5`,children:[e.map(t=>(0,K.jsxs)(rli,{value:t,className:n?`gap-1 pr-1`:void 0,children:[t,n&&(0,K.jsx)(`button`,{type:`button`,"aria-label":`Remove tag ${t}`,disabled:i,onClick:()=>n(e.filter(e=>e!==t)),className:`cursor-pointer rounded-sm hover:opacity-70 disabled:opacity-50`,children:(0,K.jsx)(xw,{className:`size-icon-xs`})})]},t)),n&&(0,K.jsx)(L_i,{selectedResults:t,vocabulary:r,onAddTag:t=>n([...e,t]),disabled:i,variant:`ghost`})]})}function G_i(e){return e==null?`-`:typeof e==`string`?e:JSON.stringify(e,null,2)}function K_i(e){let t=e.scorer;return t?.hasJudge===!1||t?.hasJudge!==!0&&!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function q_i({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:i}){return(0,K.jsx)(jQ,{open:!!e,onClose:r,title:e?`Score ${e.scorerId}`:`Score`,depth:2,children:e&&(0,K.jsx)(J_i,{score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:i})})}function J_i({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:i}){let a=K_i(e),o=a?`Not applicable (code-based scorer)`:`Step not configured`;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(jQ.Header,{children:[(0,K.jsx)(jQ.CloseButton,{onClick:r,tooltip:`Close score panel`}),(0,K.jsxs)(jQ.Heading,{children:[`Score`,(0,K.jsx)(jQ.CopyId,{id:e.scorerId})]}),(0,K.jsxs)(jQ.HeaderActions,{children:[i&&e.traceId&&(0,K.jsx)(X,{size:`icon-sm`,variant:`ghost`,onClick:i,tooltip:`See trace`,"aria-label":`See trace`,children:(0,K.jsx)(QN,{})}),(n||t)&&(0,K.jsx)(jQ.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:`Go to previous score`,nextLabel:`Go to next score`})]})]}),(0,K.jsx)(jQ.Content,{children:(0,K.jsxs)(`div`,{className:`grid gap-3`,children:[(0,K.jsx)(jQ.CodeSection,{title:`Score: ${e.score}`,icon:(0,K.jsx)(G4,{}),codeStr:e.reason||o,simplified:!0}),!a&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(jQ.CodeSection,{title:`Preprocess Prompt`,icon:(0,K.jsx)(K4,{}),codeStr:e.preprocessPrompt||o,simplified:!0}),(0,K.jsx)(jQ.CodeSection,{title:`Analyze Prompt`,icon:(0,K.jsx)(K4,{}),codeStr:e.analyzePrompt||o,simplified:!0}),(0,K.jsx)(jQ.CodeSection,{title:`Generate Score Prompt`,icon:(0,K.jsx)(K4,{}),codeStr:e.generateScorePrompt||o,simplified:!0}),(0,K.jsx)(jQ.CodeSection,{title:`Generate Reason Prompt`,icon:(0,K.jsx)(K4,{}),codeStr:e.generateReasonPrompt||o,simplified:!0})]})]})})]})}function Y_i(e,t){let[n,r]=(0,G.useState)(null),[i,a]=(0,G.useState)(void 0),[o,s]=(0,G.useState)(null),[c,l]=(0,G.useState)(t);return t!==c&&(l(t),r(null),a(void 0),s(null)),{featuredTraceId:n,setFeaturedTraceId:r,featuredSpanId:i,setFeaturedSpanId:a,featuredScoreId:o,setFeaturedScoreId:s,featuredScore:e?.find(e=>e.id===o)??null}}function X_i({result:e,scores:t,state:n,withQueryTrace:r,withFeedback:i,...a}){let o=Y_i(t,e?.id),{navigate:s}=sn(),{featuredTraceId:c,setFeaturedTraceId:l,featuredSpanId:u,setFeaturedSpanId:d,featuredScoreId:f,setFeaturedScoreId:p,featuredScore:m}=n??o,h=e=>{p(t=>e===t?null:e),l(null),d(void 0)},g=e=>{e&&(l(e),d(void 0),p(null))},_=()=>{if(!f||!t)return;let e=t.findIndex(e=>e.id===f);if(e>=0&&e<t.length-1)return()=>p(t[e+1].id)},v=()=>{if(!f||!t)return;let e=t.findIndex(e=>e.id===f);if(e>0)return()=>p(t[e-1].id)},{data:y,isLoading:b}=lmi({traceId:c,queryOptions:{enabled:!!c}}),x=y?.spans,S=x?.find(e=>!e.parentSpanId),{data:C}=s8({traceId:c??void 0,queryOptions:{enabled:i&&!!c}}),{data:w}=o8({traceId:c??void 0,spanId:u,queryOptions:{enabled:i&&!!c&&!!u}}),{data:T}=BN({traceId:c??void 0,spanId:S?.spanId,page:0,queryOptions:{enabled:!!c&&!!S?.spanId}});return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(V_i,{...a,result:e,scores:t,onScoreClick:h,featuredScoreId:f,onShowTrace:e?.traceId?()=>g(e.traceId):void 0,feedbackTabSlot:i?({traceId:e})=>(0,K.jsx)(B5,{traceId:e},e):void 0}),(0,K.jsx)(q_i,{score:m??void 0,onNext:_(),onPrevious:v(),onClose:()=>p(null),onShowTrace:m?()=>g(m.traceId):void 0}),(0,K.jsx)(e_i,{size:`wide`,depth:2,traceId:c??void 0,spans:x,isLoadingSpans:b,selectedSpanId:u??null,onClose:()=>{l(null),d(void 0)},onSpanSelect:d,showUnavailableFeaturesMsg:!1,traceHref:c?`/traces?traceId=${encodeURIComponent(c)}`:void 0,anchorSpanId:S?.spanId,withQueryTrace:r,withFeedback:i,onOpenScore:(e,t)=>s(CK(e,t)),feedbackTabBadge:i?C?.pagination?.total??void 0:void 0,feedbackTabSlot:i?({traceId:e})=>(0,K.jsx)(B5,{traceId:e}):void 0,scoresTabBadge:T?.pagination?.total??void 0,scoresTabSlot:({traceId:e,rootSpanId:n})=>n?(0,K.jsx)(eLr,{traceId:e,spanId:n,onScoreSelect:e=>{t?.some(t=>t.id===e)&&(l(null),d(void 0),p(e))}}):null,spanFeedbackTabBadge:i?w?.pagination?.total??void 0:void 0,spanFeedbackTabSlot:i?({traceId:e,spanId:t})=>e&&t?(0,K.jsx)(Z7r,{traceId:e,spanId:t},`${e}:${t}`):null:void 0})]})}function Z_i({withQueryTrace:e,withFeedback:t,variant:n}){let{currentItemId:r,experimentId:i,datasetId:a,experimentStatus:o,results:s,isLoadingResults:c,hasNextPage:l,close:u,goToPreviousItem:d,goToNextItem:f}=xmi(),p=(0,G.useMemo)(()=>r?s.find(e=>e.itemId===r):void 0,[s,r]),{data:m}=jN({experimentId:i,experimentStatus:o,queryOptions:{enabled:!!i}}),{updateExperimentResult:h}=ON(),g=(0,G.useCallback)(async e=>{try{await h.mutateAsync({datasetId:a,experimentId:i,resultId:e,status:`needs-review`}),iS(`Result flagged for review`)}catch{iS.error(`Failed to flag result for review`)}},[a,i,h]),_=(0,G.useCallback)(async e=>{try{await h.mutateAsync({datasetId:a,experimentId:i,resultId:e,status:`complete`}),iS(`Result marked as reviewed`)}catch{iS.error(`Failed to complete result`)}},[a,i,h]),v=p?m?.[p.itemId]:void 0,y=Y_i(v,p?.id);return(0,K.jsx)(X_i,{variant:n,result:p,itemId:r,fallback:c||l?(0,K.jsx)(jQ.LoadingData,{}):(0,K.jsxs)(jQ.NoData,{children:[`No loaded result for item "`,r,`".`]}),scores:v,state:y,withQueryTrace:e,withFeedback:t,onPrevious:d,onNext:f,onClose:u,onComplete:p?()=>_(p.id):void 0,onFlagForReview:p?()=>void g(p.id):void 0})}function Q_i(e){let{currentItemId:t,close:n}=xmi(),r=Zw();return K1r(t,n),r?(0,K.jsx)(Z_i,{...e}):t?(0,K.jsx)(Y8,{owner:`experiment-item`,children:(0,K.jsx)(Z_i,{...e,variant:`inline`})}):null}function $_i({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 evi=[{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`},tvi=Object.keys(Q7),nvi=`mastra:metrics:saved-filters`;function rvi(e){let t=_vi(e);try{localStorage.setItem(nvi,t.toString())}catch{}}function ivi(){try{let e=localStorage.getItem(nvi);if(!e)return null;let t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function avi(e){if(e.has(`rootEntityType`))return!0;for(let t of tvi)if(e.has(Q7[t]))return!0;return!1}var ovi=`hasAll`,svi=[{id:`is`,label:`is`},{id:ovi,label:`has all of`,arity:`many`}],cvi={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`},lvi={provider:U6,model:mP},uvi=[`threadId`,`resourceId`,`userId`,`organizationId`,`runId`,`sessionId`,`requestId`,`experimentId`],dvi=e=>({id:e,label:cvi[e],icon:lvi[e]??A8(e),color:j8(e)}),fvi=(e,t)=>e.label.localeCompare(t.label);function pvi({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r}){let i=(e,t)=>({...dvi(e),operators:[`is`],strict:!0,suggestions:t}),a=e=>({...dvi(e),operators:[`is`]}),o=e=>e.map(e=>({value:e})),s=[i(`rootEntityType`,evi.map(e=>({value:e.entityType,label:e.label}))),i(`entityName`,o(t)),{...i(`tags`,o(e)),operators:[ovi]},i(`serviceName`,o(n)),i(`environment`,o(r))],c=uvi.map(a),l=[`provider`,`model`].map(e=>({...a(e),hidden:!0}));return[...s.toSorted(fvi),...c.toSorted(fvi),...l]}function mvi(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:ovi,value:t}}let t=Array.isArray(e.value)?e.value[0]??``:e.value;return{id:e.fieldId,fieldId:e.fieldId,operatorId:`is`,value:bvi(t)?``:t}})}function hvi(e){return e.map(e=>({fieldId:e.fieldId,value:Array.isArray(e.value)?e.value.map(String):String(e.value)}))}function gvi(e){let t=[],n=new Map([[Z7,`rootEntityType`]]);for(let e of tvi)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 _vi(e){let t=new URLSearchParams,n=e.getAll(Z7);for(let e of n)t.append(Z7,e);for(let n of tvi){let r=Q7[n],i=e.getAll(r);for(let e of i)t.append(r,e)}return t}function vvi(e,t){e.delete(Z7);for(let t of tvi)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 yvi=`Any`;function bvi(e){let t=e.trim();return t===``||t===yvi}var xvi=new Set(evi.map(e=>e.entityType));function Svi(e){let t=e.trim();return xvi.has(t)?t:void 0}function Cvi(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=>!bvi(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:Svi(e);n&&(t.rootEntityType=n)}else t[e]=r[0]}else if(typeof n.value==`string`){if(bvi(n.value))continue;let r=n.value.trim();if(e===`rootEntityType`){let e=Svi(r);e&&(t.rootEntityType=e)}else t[e]=r}}return t}var wvi={first:0,normal:1,last:2},Tvi=class extends Error{constructor(){super(`Skipped: nothing is waiting for this request any more`),this.name=`SkippedRequestError`}};function Evi(e){let t=0,n=[],r=()=>{t<e&&n.shift()?.start()};return{run(i,{priority:a=wvi.normal,isWanted:o}={}){return new Promise((s,c)=>{let l=e=>{e&&o&&!o()?(c(new Tvi),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 Dvi=(0,G.createContext)(void 0);function Ovi(){let e=(0,G.use)(Dvi);if(!e)throw Error(`useAggregateLimiter must be used inside MetricsProvider or AggregateLimiterProvider`);return e}function kvi(e,t){let n=Ovi(),r=u_();return({queryKey:i})=>n.run(e,{priority:t,isWanted:()=>(r.getQueryCache().find({queryKey:i,exact:!0})?.getObserversCount()??0)>0})}function Avi({children:e}){let t=(0,G.use)(Dvi),[n]=(0,G.useState)(()=>t?void 0:Evi(3));return(0,K.jsx)(Dvi,{value:t??n,children:e})}var jvi=864e5,Mvi={"24h":jvi,"3d":2592e5,"7d":6048e5,"14d":12096e5,"30d":2592e6};function Nvi(e,t,n){if(e!==`custom`){let t=Mvi[e]??jvi;return{start:new Date(n-t),end:new Date(n)}}return{start:t?.from??new Date(n-jvi),end:t?.to??new Date(n)}}function Pvi({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)(()=>Nvi(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 Fvi(e){let t=Y(),{filters:n,filterKey:r,queryOptions:i}=e;return T_({queryKey:[`metrics`,`agent-runs-kpi`,r],queryFn:()=>t.getMetricAggregate({name:[`mastra_agent_duration_ms`],aggregation:`count`,filters:n,comparePeriod:`previous_period`}),...i})}new Intl.NumberFormat(`en-US`,{notation:`compact`,maximumSignificantDigits:3}),new Intl.NumberFormat(`en-US`),new Set(Intl.supportedValuesOf(`currency`));function Ivi(e){let t=Y(),{filters:n,filterKey:r,queryOptions:i}=e;return T_({queryKey:[`metrics`,`token-usage-by-agent`,r],queryFn:async()=>{let e={groupBy:[`entityName`],aggregation:`sum`,orderDirection:`DESC`,filters:n},[r,i]=await Promise.all([t.getMetricBreakdown({...e,name:[`mastra_model_total_input_tokens`]}),t.getMetricBreakdown({...e,name:[`mastra_model_total_output_tokens`]})]),a=new Map,o=e=>K6(a,e,()=>({input:0,output:0,cost:null,costUnit:null})),s=(e,t)=>{t.estimatedCost!=null&&(e.cost=(e.cost??0)+t.estimatedCost,t.costUnit&&(e.costUnit=t.costUnit))};for(let e of r.groups){let t=o(e.dimensions.entityName??`unknown`);t.input=e.value,s(t,e)}for(let e of i.groups){let t=o(e.dimensions.entityName??`unknown`);t.output=e.value,s(t,e)}return Array.from(a.entries()).map(([e,t])=>({name:e,input:t.input,output:t.output,total:t.input+t.output,cost:t.cost,costUnit:t.costUnit})).sort((e,t)=>t.total-e.total)},...i})}async function Lvi(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 Rvi(e){let t=Y(),{filters:n,filterKey:r,queryOptions:i}=e;return T_({queryKey:[`metrics`,`trace-volume`,r],queryFn:async()=>{let[e,r,i]=await Promise.all([Lvi(t,`mastra_agent_duration_ms`,n),Lvi(t,`mastra_workflow_duration_ms`,n),Lvi(t,`mastra_tool_duration_ms`,n)]);return{agentData:e,workflowData:r,toolData:i}},...i})}var zvi=[{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`}],Bvi=new Set(zvi.map(e=>e.value));function Vvi(e){return typeof e==`string`&&(Bvi.has(e)||e===`custom`)}var Hvi=(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)(Hvi)}function Uvi(e,t){return e===`custom`?t?.from?t.to?`${yC(t.from)} – ${yC(t.to)}`:yC(t.from)??``:`Custom range`:zvi.find(t=>t.value===e)?.label??e}var Wvi=36e5;function Gvi(e,t){if(e!==`custom`)return`vs previous ${e}`;let n=t?.to?.getTime()??Date.now(),r=t?.from?.getTime()??n-24*Wvi,i=Math.round((n-r)/Wvi);return`vs previous ${i>24&&i%24==0?`${i/24}d`:`${i}h`}`}function Kvi({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)(()=>Cvi(l),[l]),d=(0,G.useMemo)(()=>JSON.stringify(u),[u]),f=Pvi({datePreset:t,customRange:a,dimensionalFilter:u,dimensionalFilterKey:d}),p=(0,G.useMemo)(()=>s??{},[s]),m=Uvi(t,a),h=Gvi(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)(Hvi.Provider,{value:g,children:(0,K.jsx)(Avi,{children:e})})}var qvi=[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`];function Jvi(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 Yvi(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 Xvi=864e5;function Zvi(){let{data:e}=i5(),t=e?.capabilities.traceRetentionDays;if(t===void 0)return;let n=new Date(Date.now()-t*Xvi);return new Date(n.getFullYear(),n.getMonth(),n.getDate())}function Qvi(){let{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=$7(),i=Zvi();return(0,K.jsx)(u3r,{preset:Jvi(e),onPresetChange:e=>t(Yvi(e)),dateFrom:n?.from,dateTo:n?.to,onDateRangeChange:(e,t)=>r({from:e,to:t}),presets:qvi,minDate:i})}var $vi=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}));$vi.displayName=`MetricsCardAction`;function eyi({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 tyi({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 nyi({className:e,...t}){return(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,className:c(`-my-1 shrink-0 cursor-grab active:cursor-grabbing`,e),...t,children:(0,K.jsx)(yP,{})})}function ryi({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 iyi({label:e,value:t,change:n,isLoading:r=!1,className:i}){return(0,K.jsxs)(`div`,{className:c(`grid gap-1.5`,i),children:[(0,K.jsx)(`h3`,{className:`text-body-sm text-muted-foreground`,children:e}),(0,K.jsxs)(`span`,{className:`flex items-baseline gap-2`,children:[(0,K.jsx)(`span`,{className:c(`text-title text-foreground tabular-nums [text-box:trim-both_cap_alphabetic]`,r&&`relative min-w-24`),children:r?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`span`,{className:`invisible`,children:`0`}),(0,K.jsx)(zS,{className:`absolute inset-0`})]}):t}),!r&&n&&(0,K.jsxs)(`span`,{className:`text-body-sm text-muted-foreground tabular-nums [text-box:trim-both_cap_alphabetic]`,children:[n,` vs previous`]})]})]})}function ayi({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 oyi({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 syi({children:e,className:t}){return(0,K.jsx)(nP,{className:c(`group/metrics-card grid min-h-72 min-w-80 flex-1 grid-rows-[auto_1fr] gap-4 px-4 py-3 2xl:min-w-120 md:min-w-88 lg:min-w-sm xl:min-w-104`,t),children:e})}function cyi({children:e,className:t,as:n=`h3`}){return(0,K.jsx)(n,{className:c(`text-subheading text-foreground`,t),children:e})}function lyi({title:e,value:t,onValueChange:n,options:r,className:i}){return(0,K.jsx)(`div`,{className:`flex min-w-0`,children:(0,K.jsxs)(rE,{modal:!1,children:[(0,K.jsxs)(rE.Trigger,{render:(0,K.jsx)(`button`,{type:`button`,className:c(`-mx-1.5 -my-0.5 flex items-center gap-1 self-start rounded-md px-1.5 py-0.5 text-left text-subheading text-foreground hover:bg-fill-subtle`,i)}),children:[e,(0,K.jsx)(_,{className:`size-icon-sm text-muted-foreground`})]}),(0,K.jsx)(rE.Content,{align:`start`,children:(0,K.jsx)(rE.RadioOptions,{options:r,value:t,onValueChange:n,closeOnSelect:!0})})]})})}function uyi({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 dyi({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 fyi({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)(pyi,{value:e,isLoading:t})})}function pyi({value:e,isLoading:t}){return t?(0,K.jsx)(BS,{line:`text-body`,className:`h-4 w-14`}):typeof e==`string`?e:(0,K.jsx)(`span`,{className:`inline-flex items-center gap-3`,children:e.map(e=>(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,K.jsx)(`span`,{"aria-hidden":!0,className:`size-2 shrink-0 rounded-[2px]`,style:{backgroundColor:e.color}}),(0,K.jsxs)(`span`,{className:`sr-only`,children:[e.label,` `]}),e.value]},e.label))})}var e9=Object.assign(syi,{Root:syi,Kpi:z4,TopBar:dyi,Toolbar:uyi,Actions:eyi,Action:$vi,DragHandle:nyi,Title:cyi,TitleMenu:lyi,Total:fyi,Headline:iyi,Loading:ayi,Error:ryi,Content:tyi,NoData:oyi}),myi=`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 hyi({onClick:e}){return(0,K.jsx)(e9.Action,{label:`View in traces`,className:myi,onClick:e,children:(0,K.jsx)(QN,{})})}function gyi({onClick:e}){return(0,K.jsx)(e9.Action,{label:`View errors in logs`,className:myi,onClick:e,children:(0,K.jsx)(Ljt,{})})}function t9({isEmpty:e=!1,emptyMessage:t=`No data in this range`,children:n}){return(0,K.jsxs)(`div`,{className:`relative flex min-h-0 flex-1 flex-col`,"data-chart-empty":e||void 0,children:[(0,K.jsx)(`div`,{className:c(`flex min-h-0 flex-1 flex-col`,e&&`invisible [&_.recharts-xAxis-tick-labels]:visible`),children:(0,K.jsx)(U3r.Provider,{value:e,children:n})}),e&&(0,K.jsx)(vyi,{message:t})]})}function _yi({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 vyi({message:e}){return(0,K.jsxs)(`div`,{className:`absolute inset-0 flex flex-col justify-between`,style:{paddingTop:x5.top,paddingBottom:22},children:[(0,K.jsx)(_yi,{}),(0,K.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,K.jsx)(_yi,{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)(_yi,{className:`flex-1`})]}),(0,K.jsx)(_yi,{})]})}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)(byi,{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`,yyi(e,m),_),children:g})]})]})}function yyi(e,t){if(e===`compact`)return`flex-1`;if(e!==`hero`)return t===`fit`?`min-h-60`:`min-h-60 flex-1`}function byi({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)(xyi,{...t})]}):(0,K.jsx)(xyi,{...t})}function xyi({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)(Cyi,{href:t,LinkComponent:n,children:e})}):i?(0,K.jsx)(Syi,{title:e,onTitleChange:i}):(0,K.jsx)(e9.Title,{children:e})}function Syi({title:e,onTitleChange:t}){return(0,K.jsx)(`h3`,{className:`flex min-w-0`,children:(0,K.jsx)(`input`,{"aria-label":`Widget title`,defaultValue:e,...Gk,onBlur:n=>{let r=n.currentTarget.value.trim();n.currentTarget.value=r,r!==e&&t(r)},onKeyDown:t=>{t.key===`Escape`&&(t.currentTarget.value=e),(t.key===`Enter`||t.key===`Escape`)&&(t.preventDefault(),t.currentTarget.blur())},className:c(`-mx-1.5 -my-0.5 field-sizing-content min-w-12 truncate rounded-md bg-transparent px-1.5 py-0.5`,`text-body zoom-safe-text font-medium text-foreground`,`outline-1 -outline-offset-1 outline-transparent outline-dashed hover:outline-border-strong focus:outline-border-focus`)},e)})}function Cyi({href:e,LinkComponent:t,children:n}){return(0,K.jsxs)(t??`a`,{href:e,className:c(`-mx-1.5 -my-0.5 inline-flex items-center gap-1.5 rounded-md px-1.5 py-0.5 text-subheading text-foreground hover:bg-fill-subtle`,`focus-visible:outline-1 focus-visible:-outline-offset-1 focus-visible:outline-border-focus focus-visible:outline-solid`),children:[n,(0,K.jsx)(dZ,{"aria-hidden":!0,className:`size-icon-sm text-muted-foreground`})]})}function r9({error:e,onRetry:t}){return FN(e)?(0,K.jsx)(TH,{}):IN(e)?(0,K.jsx)(wH,{resource:`traces`}):(0,K.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3`,children:[(0,K.jsx)(e9.Error,{message:`Couldn't load this data. Try again in a moment.`}),t&&(0,K.jsx)(X,{size:`sm`,icon:(0,K.jsx)(vS,{}),onClick:t,children:`Retry`})]})}function wyi({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)(Tyi,{}):(0,K.jsx)(Eyi,{...r})]})}function Tyi(){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 Eyi({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 Dyi={2:`@3xl:grid-cols-2`,3:`@3xl:grid-cols-2 @7xl:grid-cols-3`},Oyi={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`,Dyi[t]),children:e})})}function kyi({children:e,span:t=1,className:n}){return(0,K.jsx)(`div`,{className:c(`min-w-0 *:size-full *:min-w-0!`,Oyi[t],n),children:e})}i9.Item=kyi;var Ayi=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 jyi(e,t){if(t>=24)return Math.floor(e/Ayi)*Ayi;let n=new Date(e),r=Math.floor(n.getHours()/t)*t;return new Date(n.getFullYear(),n.getMonth(),n.getDate(),r).getTime()}function Myi(e,t){if(t>=24)return jyi(e,t)+Ayi;let n=new Date(e);return jyi(new Date(n.getFullYear(),n.getMonth(),n.getDate(),n.getHours()+t).getTime(),t)}function Nyi(e,t,n){let r=h8r(e,t),i=[];for(let a=jyi(e.getTime(),n);a<=t.getTime();a=Myi(a,n))i.push(v8r(a,n,r));return i}function Pyi(e,t){let n=new Map(e.map((e,t)=>[e.ts,t]));return e=>n.get(jyi(new Date(e.timestamp).getTime(),t))}function s9(e,t){return{from:new Date(e),to:new Date(Myi(e,t))}}function c9(){let{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r,queryFilters:i}=$7(),a=Pvi({datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r});return i??a}var Fyi={input:`mastra_model_total_input_tokens`,output:`mastra_model_total_output_tokens`,cacheRead:`mastra_model_input_cache_read_tokens`},Iyi=`mastra_agent_duration_ms`;function Lyi(){let e=Y(),{filters:t,filterKey:n,timestamp:r}=c9(),{interval:i,stepHours:a}=a9(r.start,r.end);return T_({queryKey:[`metrics`,`activity`,n,i],placeholderData:__,queryFn:async()=>{let n=n=>e.getMetricTimeSeries({name:[n],interval:i,aggregation:`sum`,filters:t}),[o,s,c,l]=await Promise.all([n(Fyi.input),n(Fyi.output),n(Fyi.cacheRead),e.getMetricTimeSeries({name:[Iyi],interval:i,aggregation:`count`,groupBy:[`status`],filters:t})]),u=Nyi(r.start,r.end,a).map(e=>({...e,input:0,cacheRead:0,output:0,cost:0,completed:0,failed:0,failureRate:0})),d=Pyi(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 Ryi=[{dataKey:`input`,label:`Input`,color:g5.green},{dataKey:`cacheRead`,label:`Cache read`,color:g5.violet},{dataKey:`output`,label:`Output`,color:g5.sky}],zyi=[{dataKey:`cost`,label:`Cost`,color:g5.green}],Byi={tokens:`Token usage`,cost:`Model cost`},Vyi=[{value:`tokens`,label:Byi.tokens},{value:`cost`,label:Byi.cost}];function Hyi({onViewTraces:e,onTimeRangeClick:t}){let[n,r]=(0,G.useState)(`tokens`),{data:i=[],isLoading:a,isError:o,isPlaceholderData:s}=Lyi(),{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?Ryi:zyi,m={title:Byi[n],titleMenu:{value:n,onValueChange:r,options:Vyi},actions:e&&(0,K.jsx)(hyi,{onClick:e}),toolbar:(0,K.jsx)(e9.Toolbar,{children:(0,K.jsx)(T5,{series:p})})};return o?(0,K.jsx)(n9,{...m,children:(0,K.jsx)(r9,{})}):(0,K.jsx)(n9,{...m,total:f?v5(u):b5(d),isLoading:a,isUpdating:s,children:(0,K.jsx)(t9,{isEmpty:!a&&u===0&&d===0,children:(0,K.jsx)(o8r,{data:i,series:p,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:f?v5:b5,axisFormatter:f?B3r:V3r,onBucketClick:t&&(e=>t(s9(Number(e.ts),l))),isLoading:a,...h5})})})}var Uyi=[{dataKey:`failureRate`,label:`Failed runs`,color:g5.error}],Wyi=e=>`${Math.round(e*100)}%`;function Gyi({onViewErrors:e,onTimeRangeClick:t,titleMenu:n}){let{data:r=[],isLoading:i,isError:a,isPlaceholderData:o}=Lyi(),{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)(gyi,{onClick:e}),toolbar:(0,K.jsx)(e9.Toolbar,{children:(0,K.jsx)(T5,{series:Uyi})})};return a?(0,K.jsx)(n9,{...f,children:(0,K.jsx)(r9,{})}):(0,K.jsx)(n9,{...f,total:y5(l>0?u/l:0),isLoading:i,isUpdating:o,children:(0,K.jsx)(t9,{isEmpty:!i&&l===0,children:(0,K.jsx)(R6r,{lineStyle:`thin`,data:r,series:Uyi,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:y5,axisFormatter:Wyi,yDomain:d,onBucketClick:t&&(e=>t(s9(Number(e.ts),c))),isLoading:i,...h5})})})}var Kyi=[{dataKey:`completed`,label:`Completed`,color:g5.green},{dataKey:`failed`,label:`Failed`,color:g5.error}],qyi=[{value:`runs`,label:`Agent runs`},{value:`failure`,label:`Failure rate`}];function Jyi({onTimeRangeClick:e,onFailureTimeRangeClick:t,onViewErrors:n}){let[r,i]=(0,G.useState)(`runs`),a={value:r,onValueChange:i,options:qyi};return r===`failure`?(0,K.jsx)(Gyi,{titleMenu:a,onViewErrors:n,onTimeRangeClick:t}):(0,K.jsx)(Yyi,{titleMenu:a,onTimeRangeClick:e})}function Yyi({onTimeRangeClick:e,titleMenu:t}){let{data:n=[],isLoading:r,isError:i,isPlaceholderData:a}=Lyi(),{timestamp:o}=c9(),{stepHours:s}=a9(o.start,o.end),c=n.reduce((e,t)=>e+t.completed+t.failed,0),l={title:`Agent runs`,titleMenu:t,toolbar:(0,K.jsx)(e9.Toolbar,{children:(0,K.jsx)(T5,{series:Kyi})})};return i?(0,K.jsx)(n9,{...l,children:(0,K.jsx)(r9,{})}):(0,K.jsx)(n9,{...l,total:v5(c),isLoading:r,isUpdating:a,children:(0,K.jsx)(t9,{isEmpty:!r&&c===0,children:(0,K.jsx)(o8r,{data:n,series:Kyi,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:v5,onBucketClick:e&&(t=>e(s9(Number(t.ts),s))),isLoading:r,...h5})})})}var Xyi={.5:`p50`,.95:`p95`,.99:`p99`},Zyi={agents:`mastra_agent_duration_ms`,workflows:`mastra_workflow_duration_ms`,tools:`mastra_tool_duration_ms`};function Qyi(e){let t=Y(),{filters:n,filterKey:r,timestamp:i}=c9(),{interval:a}=a9(i.start,i.end),o=o9(a);return T_({queryKey:[`metrics`,`latency-percentiles`,e,r,a],placeholderData:__,queryFn:async()=>{let r=await t.getMetricPercentiles({name:Zyi[e],percentiles:[.5,.95,.99],interval:a,filters:n}),s=Nyi(i.start,i.end,o),c=Pyi(s,o);for(let e of r.series){let t=Xyi[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 $yi={agents:Dp.AGENT,workflows:Dp.WORKFLOW_RUN,tools:Dp.TOOL},ebi=[{dataKey:`p50`,label:`P50`,color:g5.sky},{dataKey:`p95`,label:`P95`,color:g5.green,emphasis:!0},{dataKey:`p99`,label:`P99`,color:g5.violet}],tbi={agents:`Agent latency`,workflows:`Workflow latency`,tools:`Tool latency`},nbi=[{value:`agents`,label:tbi.agents},{value:`workflows`,label:tbi.workflows},{value:`tools`,label:tbi.tools}];function rbi({onViewTraces:e,onTimeRangeClick:t}){let[n,r]=(0,G.useState)(`agents`),{data:i=[],isLoading:a,isError:o,isPlaceholderData:s}=Qyi(n),{timestamp:c}=c9(),l=o9(a9(c.start,c.end).interval),u=Math.max(0,...i.map(e=>e.p95??0)),d={title:tbi[n],titleMenu:{value:n,onValueChange:r,options:nbi},actions:e&&(0,K.jsx)(hyi,{onClick:()=>e($yi[n])}),toolbar:(0,K.jsx)(e9.Toolbar,{children:(0,K.jsx)(T5,{series:ebi})})};return o?(0,K.jsx)(n9,{...d,children:(0,K.jsx)(r9,{})}):(0,K.jsx)(n9,{...d,total:z3r(u),isLoading:a,isUpdating:s,children:(0,K.jsx)(t9,{isEmpty:!a&&u===0,children:(0,K.jsx)(R6r,{lineStyle:`thin`,data:i,series:ebi,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:z3r,axisFormatter:H3r,onBucketClick:t&&(e=>t(s9(Number(e.ts),l))),isLoading:a,...h5})})})}var ibi=`-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 abi({row:e,columns:t,valueWidth:n,share:r,highlighted:i,dimmed:a,onHover:o,LinkComponent:s}){let l=c(ibi,i&&`bg-fill-subtle`,(e.href||e.onClick)&&`hover:bg-fill-subtle`);return(0,K.jsx)(`li`,{children:(0,K.jsxs)(obi,{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)(sbi,{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 obi({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 sbi({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 cbi=`var(--chart-share-1)`,lbi=[1,2,3,4,5].map(e=>`var(--chart-share-${e})`),ubi=[3,4,2,5,1].map(e=>`var(--chart-share-${e})`),dbi=[1,.7,.48,.32,.2,.14],fbi={color:`var(--chart-share-rest)`,alpha:1},pbi=50,mbi=`__rest`;function hbi(e,t,n){if(n===`hues`){let n=lbi.includes(e)?[e,...lbi.filter(t=>t!==e)]:[e,...ubi];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:dbi[n]??.1}))}var gbi=e=>e.reduce((e,t)=>e+Math.max(t.share,0),0);function _bi(e){return e.map(e=>Number.isFinite(e.share)&&e.share>0?e:{...e,share:0}).toSorted((e,t)=>t.share-e.share)}function vbi(e,{limit:t,other:n,color:r,palette:i}){if(e.length<=t+1){let t=ybi(e,r,i);return{shown:t,bar:t,rest:[]}}let a=e.slice(t),o=n?.(a),s={key:mbi,label:`Other (${a.length})`,share:gbi(a),value:o?.value,cells:o?.cells,paint:fbi,segment:mbi},c=ybi(e.slice(0,t),r,i);return{shown:[...c,s],bar:c,rest:a}}function ybi(e,t,n){let r=hbi(t,e.length,n);return e.map((e,t)=>({...e,paint:bbi(e)??r[t]??fbi,segment:e.key}))}var bbi=e=>e.color?{color:e.color,alpha:1}:void 0;function xbi(e,{count:t,color:n,palette:r}){let i=Math.min(t,e.length,pbi),a=ybi(e.slice(0,i),n,r),o=e.slice(i,t).map(e=>({...e,paint:fbi,segment:mbi}));return{shown:[...a,...o],bar:a,rest:e.slice(i)}}function Sbi(e,t){let n=e.map(e=>({key:e.key,share:e.share,paint:e.paint})),r=t.length?[{key:mbi,share:gbi(t),paint:fbi}]:[],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 Cbi(e,t){if(t!==void 0)return e.find(e=>e.key===t)?.segment??t}var wbi=(e,t)=>t!==void 0&&t!==e;function Tbi(e,t){return t===void 0||t===e.key?!1:t!==`__rest`||e.segment!==`__rest`}var Ebi=(e,t)=>{let n=e/(t||1);return n>0?n<.001?`<0.1%`:`${(n*100).toFixed(+(n<.1))}%`:`0%`};function Dbi({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 Obi=[`w-32`,`w-24`,`w-36`,`w-20`,`w-28`];function kbi({className:e}){return(0,K.jsxs)(K.Fragment,{children:[`​`,(0,K.jsx)(zS,{className:c(`absolute top-1/2 h-3.5 -translate-y-1/2`,e)})]})}function Abi({rows:e,columns:t,valueWidth:n,header:r}){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`flex h-2`,children:(0,K.jsx)(zS,{className:`size-full rounded-full`})}),r,(0,K.jsx)(`ul`,{className:`grid min-w-0 grid-cols-1 gap-0.5`,"aria-busy":!0,children:Array.from({length:e},(e,r)=>(0,K.jsxs)(`li`,{className:ibi,children:[(0,K.jsx)(zS,{className:`size-2 shrink-0 rounded-[2px]`}),(0,K.jsx)(`span`,{className:`min-w-0 flex-1`,children:(0,K.jsx)(T,{as:`span`,variant:`body-sm`,className:`relative`,children:(0,K.jsx)(kbi,{className:c(`left-0`,Obi[r%Obi.length])})})}),t.map(e=>(0,K.jsx)(`span`,{className:c(l9,`relative`,e.width??`w-16`),children:(0,K.jsx)(kbi,{className:`right-0 w-10`})},e.label)),(0,K.jsx)(`span`,{className:c(l9,`relative w-12`),children:(0,K.jsx)(kbi,{className:`right-0 w-9`})}),(0,K.jsx)(`span`,{className:c(l9,`relative`,n),children:(0,K.jsx)(kbi,{className:`right-0 w-12`})})]},r))})]})}function jbi({className:e,...t}){return(0,K.jsx)(`div`,{className:c(`grid grid-cols-1`,e),children:(0,K.jsx)(Mbi,{...t})})}function Mbi({rows:e,columns:t=[],valueLabel:n,valueWidth:r=`w-14`,palette:i=`shades`,color:a=cbi,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)(Nbi,{columns:t,valueLabel:n,valueWidth:r});if(d)return(0,K.jsx)(Abi,{rows:s===`other`?o+1:o,columns:t,valueWidth:r,header:v});let y=_bi(e);if(y.length===0)return(0,K.jsx)(T,{variant:`body-sm`,tone:`muted`,className:`py-6 text-center`,children:u});let b=gbi(y),x=s===`more`,{shown:S,bar:C,rest:w}=x?xbi(y,{count:_,color:a,palette:i}):vbi(y,{limit:o,other:l,color:a,palette:i}),E=Sbi(C,w),D=Cbi(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*(wbi(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)(abi,{row:e,columns:t,valueWidth:r,share:Ebi(e.share,b),highlighted:p===e.key,dimmed:Tbi(e,p),onHover:()=>m(e.key),LinkComponent:f},e.key)),x&&(0,K.jsx)(Dbi,{shown:Math.min(_,y.length),total:y.length,limit:o,pageSize:c,onMore:()=>g(e=>e+1),onLess:()=>g(0)})]})]})}function Nbi({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 Pbi={agents:Dp.AGENT,workflows:Dp.WORKFLOW_RUN,tools:Dp.TOOL},Fbi=[{label:`Error rate`}],Ibi={agents:`Agent runs`,workflows:`Workflow runs`,tools:`Tool calls`},Lbi=[{value:`agents`,label:Ibi.agents},{value:`workflows`,label:Ibi.workflows},{value:`tools`,label:Ibi.tools}],Rbi=(e,t)=>y5(t>0?e/t:0);function zbi({onViewTraces:e,onViewErrors:t,onEntityClick:n}){let[r,i]=(0,G.useState)(`agents`),a=Pbi[r],o=Rvi({...c9(),queryOptions:{placeholderData:__}}),s={agents:o.data?.agentData??[],workflows:o.data?.workflowData??[],tools:o.data?.toolData??[]}[r],c=s.map(e=>({key:e.name,label:e.name,share:e.completed+e.errors,value:v5(e.completed+e.errors),cells:[Rbi(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:Ibi[r],titleMenu:{value:r,onValueChange:i,options:Lbi},actions:(e||t)&&(0,K.jsxs)(K.Fragment,{children:[e&&(0,K.jsx)(hyi,{onClick:()=>e(a)}),t&&(0,K.jsx)(gyi,{onClick:()=>t(a)})]})};return o.isError?(0,K.jsx)(n9,{...d,children:(0,K.jsx)(r9,{})}):(0,K.jsx)(n9,{...d,total:v5(u),isLoading:o.isLoading,isUpdating:o.isPlaceholderData,children:(0,K.jsx)(t9,{children:(0,K.jsx)(jbi,{rows:c,columns:Fbi,valueLabel:`Runs`,color:g5.sky,other:e=>{let t=e.reduce((e,t)=>e+(l.get(t.key)??0),0),n=e.reduce((e,t)=>e+t.share,0);return{value:v5(n),cells:[Rbi(t,n)]}},emptyState:`No runs in this range.`,isLoading:o.isLoading},r)})})}var Bbi=[`mastra_model_total_input_tokens`,`mastra_model_total_output_tokens`],Vbi=100;function Hbi(e){let t=Y(),{filters:n,filterKey:r}=c9();return T_({queryKey:[`metrics`,`token-spend`,e,r],placeholderData:__,queryFn:async()=>{let{groups:r}=await t.getMetricBreakdown({name:Bbi,groupBy:[e],aggregation:`sum`,orderDirection:`DESC`,limit:Vbi,filters:n});return r.map(t=>({key:String(t.dimensions[e]??`unknown`),tokens:t.value,cost:t.estimatedCost??0}))}})}var Ubi={agents:`Usage by agent`,models:`Usage by model`,threads:`Usage by thread`},Wbi=[{value:`agents`,label:Ubi.agents},{value:`models`,label:Ubi.models},{value:`threads`,label:Ubi.threads}],Gbi={placeholderData:__},Kbi=[{label:`Tokens`}];function qbi(e){let[t,n]=(0,G.useState)(`agents`);return t===`models`?(0,K.jsx)(Ybi,{...e,onViewChange:n}):t===`threads`?(0,K.jsx)(Xbi,{...e,onViewChange:n}):(0,K.jsx)(Jbi,{...e,onViewChange:n})}function Jbi(e){let{onAgentClick:t}=e,{data:n=[],isLoading:r,isPlaceholderData:i,isError:a}=Ivi({...c9(),queryOptions:Gbi}),o=n.map(e=>({key:e.name,cost:e.cost??0,tokens:e.total,onClick:t&&(()=>t(e.name))}));return(0,K.jsx)(Zbi,{view:`agents`,...e,rows:o,isLoading:r,isUpdating:i,isError:a})}function Ybi(e){let{onModelClick:t}=e,{data:n=[],isLoading:r,isPlaceholderData:i,isError:a}=Hbi(`model`),o=n.map(e=>({...e,onClick:t&&(()=>t(e.key))}));return(0,K.jsx)(Zbi,{view:`models`,...e,rows:o,isLoading:r,isUpdating:i,isError:a})}function Xbi(e){let{onThreadClick:t}=e,{data:n=[],isLoading:r,isPlaceholderData:i,isError:a}=Hbi(`threadId`),o=n.map(e=>({...e,onClick:t&&(()=>t(e.key))}));return(0,K.jsx)(Zbi,{view:`threads`,...e,rows:o,isLoading:r,isUpdating:i,isError:a})}function Zbi({view:e,onViewChange:t,onViewTraces:n,rows:r,isLoading:i,isUpdating:a,isError:o}){let s=new Map(r.map(e=>[e.key,e.tokens])),c=r.map(e=>({key:e.key,label:e.key,share:e.cost,value:b5(e.cost),cells:[v5(e.tokens)],onClick:e.onClick})),l={title:Ubi[e],titleMenu:{value:e,onValueChange:t,options:Wbi},actions:n&&(0,K.jsx)(hyi,{onClick:n})};return o?(0,K.jsx)(n9,{...l,children:(0,K.jsx)(r9,{})}):(0,K.jsx)(n9,{...l,total:b5(r.reduce((e,t)=>e+t.cost,0)),isLoading:i,isUpdating:a,children:(0,K.jsx)(t9,{children:(0,K.jsx)(jbi,{rows:c,columns:Kbi,valueLabel:`Cost`,color:g5.green,other:e=>({value:b5(e.reduce((e,t)=>e+t.share,0)),cells:[v5(e.reduce((e,t)=>e+(s.get(t.key)??0),0))]}),emptyState:`No model usage in this range.`,isLoading:i})})})}var Qbi=100;function $bi(){let e=Y(),{filters:t,filterKey:n,timestamp:r}=c9(),{interval:i}=a9(r.start,r.end),a=o9(i);return T_({queryKey:[`metrics`,`scores`,n,i],placeholderData:__,queryFn:async()=>{let n=await e.listScores({filters:t,pagination:{page:0,perPage:Qbi}}),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=Nyi(r.start,r.end,a),u=Pyi(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 exi=[g5.green,g5.sky,g5.violet,g5.teal,g5.indigo],txi=e=>e.toFixed(2),nxi=e=>String(+e.toFixed(2));function rxi(e){return e.map(({scorerId:e,name:t},n)=>({dataKey:e,label:t,color:exi[n%exi.length]??g5.neutral}))}function ixi(){let{data:e,isLoading:t,isError:n,isPlaceholderData:r}=$bi(),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)(R6r,{lineStyle:`thin`,data:e?.buckets??[],series:rxi(i),height:`fill`,yDomain:[0,1],valueFormatter:txi,axisFormatter:nxi,isLoading:t,...L3r})})})}var axi=[`entityName`,`environment`,`threadId`,`resourceId`,`userId`,`organizationId`,`runId`,`sessionId`],oxi=[`provider`,`model`],sxi=[`serviceName`,`requestId`,`experimentId`],cxi=(e,t)=>({op:`eq`,left:{path:e},right:{literal:t}});function lxi(e){let t=sxi.filter(t=>e[t]!==void 0);if(t.length)return{supported:!1,unsupportedFields:t};let n=[];e.rootEntityType&&n.push(cxi(`entityType`,e.rootEntityType));for(let t of axi){let r=e[t];r!==void 0&&n.push(cxi(t,r))}for(let t of e.tags??[])n.push({op:`includes`,path:`tags`,value:t});for(let t of oxi){let r=e[t];r!==void 0&&n.push({spans:{some:cxi(t,r)}})}return n.length===0?{supported:!0,where:void 0}:{supported:!0,where:n.length===1?n[0]:{op:`and`,args:n}}}var uxi=({start:e,end:t})=>({from:e.toISOString(),to:t.toISOString()}),dxi=({start:e,end:t})=>a9(e,t).interval;function fxi(e,t){let n=o9(dxi(t)),r=Nyi(t.start,t.end,n).map(e=>({...e,rows:[]})),i=Pyi(r,n);for(let t of e)t.bucket&&r[i({timestamp:t.bucket,value:0})??-1]?.rows.push(t);return r}function pxi({requiresRootSpanFields:e=!1}={}){let{data:t,isLoading:n}=i5(),{timestamp:r,dimensionalFilter:i}=c9();if(n)return{status:`loading`};let a=t?.capabilities;if(a?.traceAggregate!==!0||e&&a.traceQueryRootSpanFields!==!0)return{status:`unavailable`};let o=lxi(i);return o.supported?{status:`ready`,scope:{timeRange:uxi(r),...o.where?{where:o.where}:{},interval:dxi(r),window:r}}:{status:`unsupported-filter`,unsupportedFields:o.unsupportedFields}}function u9(e,{priority:t,enabled:n}={}){let r=Y();return LYr({request:e,enabled:n,queryOptions:{queryFn:kvi(()=>r.aggregateTraces(e),t),placeholderData:__,staleTime:1/0}})}var mxi=[{measure:`countDistinct.resourceId`,dataKey:`resources`,label:`Resources`,color:g5.sky},{measure:`countDistinct.threadId`,dataKey:`threads`,label:`Threads`,color:g5.green},{measure:`countDistinct.userId`,dataKey:`users`,label:`Users`,color:g5.violet},{measure:`countDistinct.sessionId`,dataKey:`sessions`,label:`Sessions`,color:g5.teal}],hxi=mxi.map(e=>e.measure),gxi=`Resources and threads`;function _xi(e,t){return e?.measures[t.measure]??0}function vxi({scope:e,onTimeRangeClick:t}){let n=u9({timeRange:e.timeRange,where:e.where,interval:e.interval,measures:hxi,limit:10}),r=u9({timeRange:e.timeRange,where:e.where,measures:hxi}),i=r.data?.rows[0],a=mxi.filter(e=>_xi(i,e)>0),o=a.map((e,t)=>({dataKey:e.dataKey,label:e.label,color:e.color,emphasis:t===0})),s=fxi(n.data?.rows??[],e.window).map(({rows:e,...t})=>({...t,...Object.fromEntries(a.map(t=>[t.dataKey,_xi(e[0],t)]))})),c=o9(e.interval===`1d`?`1d`:`1h`),l=n.error??r.error,u=n.isLoading||r.isLoading,d={title:gxi,total:l?void 0:a.length?a.map(e=>({label:e.label,value:v5(_xi(i,e)),color:e.color})):v5(0),isLoading:r.isLoading,toolbar:o.length>0&&(0,K.jsx)(e9.Toolbar,{children:(0,K.jsx)(T5,{series:o})})};return l?(0,K.jsx)(n9,{...d,children:(0,K.jsx)(r9,{error:l,onRetry:()=>{n.error&&n.refetch(),r.error&&r.refetch()}})}):(0,K.jsx)(n9,{...d,isUpdating:n.isPlaceholderData||r.isPlaceholderData,children:(0,K.jsx)(t9,{isEmpty:!u&&a.length===0,children:(0,K.jsx)(R6r,{lineStyle:`thin`,data:s,series:o,height:`fill`,xLabels:`edges`,showLegend:!1,valueFormatter:v5,axisFormatter:B3r,onBucketClick:t&&(e=>t({window:s9(Number(e.ts),c)})),isLoading:u,...h5})})})}var yxi={serviceName:`service`,requestId:`request ID`,experimentId:`experiment`};function bxi({requiresRootSpanFields:e,children:t,...n}){let r=pxi({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=>yxi[e]??e).join(` or `)} filter.`})})}function xxi(e){return(0,K.jsx)(bxi,{title:gxi,children:t=>(0,K.jsx)(vxi,{scope:t,...e})})}function Sxi(){return $7().scope}var Cxi=[`entityName`,`environment`,`serviceName`,`threadId`,`resourceId`,`userId`,`organizationId`,`runId`,`sessionId`,`requestId`,`experimentId`],wxi=[`tags`,`provider`,`model`],Txi=(e,t)=>({op:`eq`,left:{path:e},right:{literal:t}});function Exi(e){let t=wxi.filter(t=>e[t]!==void 0);if(t.length)return{supported:!1,unsupportedFields:t};let n=[];e.rootEntityType&&n.push(Txi(`entityType`,e.rootEntityType));for(let t of Cxi){let r=e[t];r!==void 0&&n.push(Txi(t,r))}return n.length===0?{supported:!0,where:void 0}:{supported:!0,where:n.length===1?n[0]:{op:`and`,args:n}}}function Dxi(){let{data:e,isLoading:t}=i5(),{timestamp:n,dimensionalFilter:r}=c9();if(t)return{status:`loading`};if(e?.capabilities.spanAggregate!==!0)return{status:`unavailable`};let i=Exi(r);return i.supported?{status:`ready`,scope:{timeRange:uxi(n),...i.where?{where:i.where}:{},interval:dxi(n),window:n}}:{status:`unsupported-filter`,unsupportedFields:i.unsupportedFields}}function Oxi(e,{priority:t,enabled:n}={}){let r=Y();return IYr({request:e,enabled:n,queryOptions:{queryFn:kvi(()=>r.aggregateSpans(e),t),placeholderData:__,staleTime:1/0}})}var kxi=`Breakdown`,Axi={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 jxi({tab:e,tabs:t,onTabChange:n,isUpdating:r,children:i}){return(0,K.jsx)(n9,{title:Axi[e],titleMenu:t.length>1?{value:e,onValueChange:n,options:t.map(e=>({value:e,label:Axi[e]}))}:void 0,isUpdating:r,bodyHeight:`fit`,children:i})}var Mxi={agents:[`agent_run`],workflows:[`workflow_run`],tools:[`tool_call`,`mcp_tool_call`]},Nxi=e=>e in Mxi;function Pxi(e){let t=Mxi[e];return t.length===1?{op:`eq`,left:{path:`spanType`},right:{literal:t[0]??``}}:{op:`in`,value:{path:`spanType`},set:[...t]}}var Fxi=e=>e!==`workflows`&&e!==`tools`,Ixi=e=>e!==`models`,Lxi=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 Rxi({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 zxi({timeRange:e,where:t},n){return{timeRange:e,...t?{where:t}:{},groupBy:d9(`environments`,n),measures:[`count`,`errorRate`,`duration.p95`],limit:f9.trace}}function Bxi(e){let t={op:`exists`,path:`threadId`};return e?{op:`and`,args:[t,e]}:t}function Vxi({timeRange:e,where:t},n){return{timeRange:e,where:Bxi(t),groupBy:n?[`projectId`,`threadId`]:[`resourceId`,`threadId`],measures:[`count`,`errorRate`,`duration.p95`],limit:f9.trace}}function Hxi(e,t,n){return e===`projects`?Rxi(t):e===`environments`?zxi(t,n):Vxi(t,n)}function Uxi({timeRange:e,where:t}){return{timeRange:e,where:Bxi(t),groupBy:[`resourceId`,`threadId`],measures:[`count`],limit:f9.trace}}function Wxi(e){let t=new Map;for(let n of e){let e=qxi(n,`resourceId`);e&&t.set(qxi(n,`threadId`),e)}return t}var Gxi=e=>e===`agents`||e===`workflows`?`countDistinct.traceId`:`count`;function Kxi(e,{timeRange:t,where:n},r){let i=Pxi(e);return{timeRange:t,where:n?{op:`and`,args:[i,n]}:i,groupBy:d9(e,r),measures:[`count`,...Gxi(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},qxi=(e,t)=>{let n=e.dimensions?.[t];return n==null?``:String(n)},Jxi=(e,t)=>t.map(t=>e.dimensions[t]==null?``:String(e.dimensions[t])).join(`|`);function Yxi({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=Gxi(e);for(let e of n){let n=l(t.map(t=>qxi(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(Jxi(e,t)).count=e.value;for(let e of r??[]){let n=l(Jxi(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 Xxi({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=Gxi(e);for(let e of n){let n=o(t.map(t=>qxi(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(Jxi(e,t)).count=e.value;for(let e of r){let n=o(Jxi(e,t));n.tokens=e.value,n.cost=e.estimatedCost??void 0}return a}function Zxi(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 Qxi(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:$xi(n,a,i),isNew:!1}}function $xi(e,t,n){return e===`errorRate`?t:n>0?t/n:void 0}function eSi(e,t){if(e.delta!==void 0&&e.delta!==0)return e.delta>0==(t===`count`)?`good`:`bad`}var tSi=[`mastra_model_total_input_tokens`,`mastra_model_total_output_tokens`];function m9({groupBy:e,filters:t,window:n,measure:r=`tokens`,enabled:i=!0}){let a=Y(),{filters:o,filterKey:s}=c9();return T_({queryKey:[`metrics`,`cost-breakdown`,r,e,t,s,n.start.toISOString(),n.end.toISOString()],staleTime:1/0,enabled:i,queryFn:()=>a.getMetricBreakdown({name:r===`tokens`?tSi:[`mastra_model_total_input_tokens`],groupBy:e,aggregation:r===`tokens`?`sum`:`count`,orderDirection:`DESC`,limit:1e3,filters:{...o,...t,timestamp:n}})})}function nSi({start:e,end:t}){return{start:new Date(2*e.getTime()-t.getTime()),end:new Date(e.getTime())}}var rSi=[`count`,`errorRate`,`p95`,`tokens`,`cost`],iSi=e=>rSi.includes(e),aSi=e=>Lxi(e)?`Spans`:`Traces`,oSi=`A trace is one end-to-end request, with every step it took.`,sSi=`A span is one step inside a trace, such as a tool call or a model call. One trace can have many.`,cSi=e=>Lxi(e)?sSi:oSi,lSi={errorRate:`Errors`,p95:`P95 latency`,tokens:`Tokens`,cost:`Cost`},uSi=e=>e.toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`}),dSi=({start:e,end:t})=>`${uSi(e)} – ${uSi(t)}`;function fSi(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: ${dSi(e)}`,previous:`Previous: ${dSi(nSi(e))}`}}var pSi=(e,t)=>t&&e!==`projects`,mSi=(e,t)=>t===`count`?aSi(e):lSi[t];function hSi({tab:e,built:t,previous:n,truncated:r,groupBy:i,usage:a}){return e===`threads`?t.filter(e=>e.name!==``):!n||r?t:Zxi(t,n,i,a)}function gSi(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 _Si=(e,t)=>e===`projects`?t.key:t.projectId;function vSi(e,t){let n=_Si(e,t),r=n?{projectId:n}:{};return Nxi(e)?{...r,span:{spanTypes:Mxi[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 ySi(e,t){return t&&t.toUpperCase()!==`USD`?`${v5(e)} ${t}`:b5(e)}function bSi(e,t){if(e.isNew)return`New`;if(e.change===void 0)return`—`;if(e.change===0)return t===`errorRate`?`0 pt`:`0%`;let n=e.change>0?`+`:`−`,r=Math.abs(e.change);return t===`errorRate`?r<5e-4?`${n}<0.1 pt`:`${n}${(r*100).toFixed(1)} pt`:`${n}${y5(r)}`}function xSi(e){let t=nSi(e.window);return{...e,window:t,timeRange:uxi(t)}}var SSi={good:`text-badge-green-foreground`,bad:`text-badge-red-foreground`};function CSi({trend:e,children:t}){return t===void 0?(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`—`}):(0,K.jsx)(`span`,{className:e?SSi[e]:`text-muted-foreground`,children:t})}function wSi({change:e,metric:t}){return e?(0,K.jsx)(CSi,{trend:eSi(e,t),children:bSi(e,t)}):(0,K.jsx)(CSi,{trend:void 0})}function TSi({window:e,label:t}){let{summary:n,current:r,previous:i}=fSi(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 ESi(){return(0,K.jsx)(`span`,{title:`No price for this model`,children:`Not priced`})}function DSi({row:e}){return e.cost===void 0?e.tokens?(0,K.jsx)(ESi,{}):`—`:ySi(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 OSi({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)(yni,{parts:QOn(n.name,n.provider)}):t})]})}var kSi=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`})]}),ASi={agent:HN,workflow:ZS,tool:XN},jSi={agents:`agent`,workflows:`workflow`,tools:`tool`};function MSi({entity:e}){let t=ASi[e];return(0,K.jsx)(ekn,{icon:(0,K.jsx)(t,{className:`size-3`})})}function NSi({provider:e}){return e?(0,K.jsx)(tkn,{provider:e}):(0,K.jsx)(ekn,{icon:(0,K.jsx)(kSi,{className:`size-icon-xs`})})}function PSi({tab:e,row:t}){let n=jSi[e];return n?(0,K.jsx)(MSi,{entity:n}):e===`models`?(0,K.jsx)(NSi,{provider:t.provider}):null}function FSi({tab:e,row:t}){let{projectLabel:n}=Sxi();return(0,K.jsx)(OSi,{mark:(0,K.jsx)(PSi,{tab:e,row:t}),title:gSi(e,t,n),model:e===`models`&&t.name!==``?{name:t.name,provider:t.provider}:void 0})}function ISi({text:e}){return(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`muted`,className:`truncate`,title:e,children:e})}var LSi={asc:cH,desc:sH},RSi=`focus-visible:outline-1 focus-visible:outline-solid focus-visible:outline-border-focus focus-visible:-outline-offset-1`,zSi=`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 BSi({header:e,explained:t,sorted:n,className:r,...i}){let a=n&&LSi[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`,RSi,r),children:[(0,K.jsx)(`span`,{className:c(t&&zSi),children:e}),a&&(0,K.jsx)(a,{"aria-hidden":!0,className:`size-3`})]})}function VSi({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`,RSi,n),children:(0,K.jsx)(`span`,{className:c(t&&zSi),children:e})})}function HSi({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)(BSi,{header:e,explained:a,sorted:n,onClick:r,"aria-describedby":o}):(0,K.jsx)(VSi,{header:e,explained:a,"aria-describedby":o});return a?(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{render:s}),(0,K.jsx)(Tx,{id:i,keepMounted:!0,side:`top`,className:`max-w-72`,children:t})]}):s}var USi=`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)]`,WSi=`pt-1.75 pb-2 text-body-sm`,GSi=c(`relative col-span-full grid grid-cols-subgrid items-center px-3`,WSi,USi),KSi=[`w-32`,`w-24`,`w-36`,`w-20`,`w-28`],qSi=`a, button, input, select, textarea, label, [role="button"], [role="link"], [contenteditable]`;function JSi(e){if(!(e.target instanceof Element))return!1;let t=e.target.closest(qSi);return!!(t&&e.currentTarget.contains(t))}function YSi(e,t,n){return e.align===`end`?`right-0 w-10`:t>0?`left-0 w-16`:c(`left-0`,KSi[n%KSi.length])}function XSi({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)(QSi,{columns:e,rowIndex:n},n)):t.length===0?i?r===void 0?(0,K.jsx)(ZSi,{count:i}):(0,K.jsxs)(`div`,{role:`row`,className:`col-span-full grid *:col-start-1 *:row-start-1`,children:[(0,K.jsx)(ZSi,{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)($Si,{row:t,columns:e,...o},n(t)))}function ZSi({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:WSi,children:`​`},t))})}function QSi({columns:e,rowIndex:t}){return(0,K.jsx)(`div`,{role:`row`,"aria-busy":!0,className:GSi,children:e.map((e,n)=>(0,K.jsxs)(`div`,{role:`cell`,className:c(`relative flex min-w-0`,e.align===`end`&&`justify-end`),children:[`​`,(0,K.jsx)(zS,{className:c(`absolute top-1/2 h-3.5 -translate-y-1/2`,YSi(e,n,t))})]},e.id))})}function $Si({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=>{JSi(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(GSi,`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 eCi=`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)]`,tCi={asc:`ascending`,desc:`descending`};function nCi(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 rCi(e,t){return typeof e==`number`&&typeof t==`number`?e-t:String(e).localeCompare(String(t))}function iCi(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*rCi(n,a)})}var aCi=e=>e.width??(e.align===`end`?`minmax(max-content,1fr)`:`max-content`);function oCi({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=iCi(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(aCi).join(` `)},D=!m&&C>1,O=e=>{let t=nCi(x,e)??i;v(t),b(0),a?.(t)};return(0,K.jsxs)(`div`,{className:c(`grid min-w-0 gap-3`,g),children:[(0,K.jsxs)(LS,{orientation:`horizontal`,children:[(0,K.jsxs)(`div`,{role:`table`,"aria-label":h,className:`grid min-w-min gap-x-4`,style:E,children:[(0,K.jsx)(`div`,{role:`row`,className:c(`relative col-span-full grid grid-cols-subgrid items-end px-3 pb-1.5 text-label text-placeholder`,eCi),children:e.map(e=>{let t=x?.column===e.id?x.direction:void 0;return(0,K.jsx)(`div`,{role:`columnheader`,"aria-sort":t&&tCi[t],className:c(`flex min-w-0 items-center gap-1`,e.align===`end`&&`justify-end text-right`),children:(0,K.jsx)(HSi,{header:e.header,description:e.description,sorted:t,onSort:e.sortValue?()=>O(e):void 0})},e.id)})}),(0,K.jsx)(XSi,{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)(ZSi,{count:p-T.length})]}),D&&(0,K.jsx)(_ci,{page:w,pageCount:C,onPageChange:b})]})}var sCi=10,cCi={column:`count`,direction:`desc`},lCi={projects:`Project`,agents:`Agent`,workflows:`Workflow`,tools:`Tool`,models:`Model`,threads:`Thread`,environments:`Environment`},uCi={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 dCi({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=Sxi(),[p,m]=(0,G.useState)(cCi),[h,g]=(0,G.useState)(`count`),_=(e=cCi)=>{m(e),iSi(e.column)&&g(e.column)},v=[r,i,a].filter(e=>e!==void 0);if(v.some(e=>e.isError))return(0,K.jsx)(jxi,{...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=Ixi(e),x=i!==void 0,S=pSi(e,d.byProject),C=r?.data?.truncated===!0,w=y?[]:Yxi({tab:e,groupBy:t,aggregateRows:r?.data?.rows,usageGroups:i?.data?.groups,spanGroups:a?.data?.groups,resources:o?.data?Wxi(o.data.rows):void 0}),E=[s,c,l].every(e=>!e||!e.isLoading&&!e.isError)&&!y?Xxi({tab:e,groupBy:t,aggregateRows:s?.data?.rows,usageGroups:c?.data?.groups,spanGroups:l?.data?.groups}):void 0,D=hSi({tab:e,built:w,previous:E,truncated:C,groupBy:t,usage:x}),O=aSi(e),k=e=>E?Qxi(e,E.get(e.key),h):void 0,A=e=>e.projectId?f.projectLabel?.(e.projectId)??e.projectId:`—`,j={id:`name`,header:lCi[e],width:`minmax(12rem,3fr)`,cell:t=>(0,K.jsx)(FSi,{tab:e,row:t})},M={id:`project`,header:`Project`,width:`minmax(8rem,2fr)`,cell:e=>(0,K.jsx)(ISi,{text:A(e)})},N={id:`resource`,header:`Resource`,width:`minmax(6rem,1fr)`,cell:e=>(0,K.jsx)(ISi,{text:e.resource??`—`})},P=[{id:`errorRate`,header:`Errors`,align:`end`,sortValue:e=>e.errorRate,cell:e=>(0,K.jsx)(h9,{muted:!0,children:e.errorRate===void 0?`—`:y5(e.errorRate)})},{id:`p95`,header:`P95 latency`,align:`end`,sortValue:e=>e.p95,cell:e=>(0,K.jsx)(h9,{muted:!0,children:e.p95===void 0?`—`:z3r(e.p95)})}],F=[{id:`tokens`,header:`Tokens`,align:`end`,sortValue:e=>e.tokens,cell:e=>(0,K.jsx)(h9,{muted:!0,children:e.tokens===void 0?`—`:v5(e.tokens)})},{id:`cost`,header:`Cost`,align:`end`,sortValue:e=>e.cost,cell:e=>(0,K.jsx)(h9,{muted:!0,children:(0,K.jsx)(DSi,{row:e})})}],I={id:`count`,header:O,align:`end`,description:cSi(e),sortValue:e=>e.count,cell:e=>(0,K.jsx)(h9,{children:v5(e.count)})},L={id:`change`,header:`% Change`,align:`end`,description:(0,K.jsx)(TSi,{window:n,label:mSi(e,h)}),sortValue:e=>k(e)?.change,cell:e=>(0,K.jsx)(h9,{children:(0,K.jsx)(wSi,{change:k(e),metric:h})})},R=[j,...S?[M]:[],...e===`threads`?[N]:[],...b?P:[],...x?F:[],I,L];return(0,K.jsx)(jxi,{...d,tab:e,isUpdating:r?.isPlaceholderData,children:(0,K.jsxs)(t9,{children:[(0,K.jsx)(oCi,{"aria-label":`${lCi[e]} breakdown`,columns:R,rows:D,getRowKey:e=>e.key,sort:p,defaultSort:cCi,onSortChange:_,onRowClick:d.onRowClick&&(t=>d.onRowClick?.(vSi(e,t))),pageSize:sCi,isLoading:y,empty:uCi[e]},e),!y&&C&&(0,K.jsxs)(T,{variant:`caption`,tone:`muted`,className:`pt-2`,children:[`Showing the `,v5(u),` busiest; sorting covers only these.`]})]})})}var fCi={entityType:`agent`};function pCi({tab:e,scope:t,...n}){let r=d9(e,n.byProject),i=Fxi(e),a=xSi(t),o=Oxi(Kxi(e,t,n.byProject)),s=Oxi(Kxi(e,a,n.byProject),{priority:wvi.last}),c=m9({groupBy:r,filters:fCi,window:t.window,enabled:i}),l=m9({groupBy:r,filters:fCi,window:a.window,enabled:i});return(0,K.jsx)(dCi,{...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 mCi(e){let t=d9(`models`,e.byProject),{timestamp:n}=c9(),r=nSi(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)(dCi,{...e,tab:`models`,groupBy:t,window:n,totals:i,spans:a,previousUsage:o,previousSpans:s,limit:f9.trace})}function hCi({tab:e,scope:t,...n}){let r=d9(e,n.byProject),i=xSi(t),a=u9(Hxi(e,t,n.byProject)),o=u9(Hxi(e,i,n.byProject),{priority:wvi.last}),s=u9(Uxi(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)(dCi,{...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 gCi={serviceName:`service`,requestId:`request ID`,experimentId:`experiment`,tags:`tags`,provider:`provider`,model:`model`};function _Ci({tab:e,traceGate:t,spanGate:n,...r}){if(e===`models`)return(0,K.jsx)(mCi,{...r},e);let i=Nxi(e)?n:t;return i.status===`unsupported-filter`?(0,K.jsx)(jxi,{...r,tab:e,children:(0,K.jsx)(e9.NoData,{message:`Not available with a ${i.unsupportedFields.map(e=>gCi[e]??e).join(` or `)} filter.`})}):Nxi(e)?n.status===`ready`&&(0,K.jsx)(pCi,{...r,tab:e,scope:n.scope},e):t.status===`ready`&&(0,K.jsx)(hCi,{...r,tab:e,scope:t.scope},e)}function vCi({chosen:e,traceScope:t,spanGate:n,...r}){let i=u9(Rxi(t)).data?.rows.filter(e=>(e.measures.count??0)>0).length,a=e??yCi(i);return(0,K.jsx)(_Ci,{...r,tab:a,traceGate:{status:`ready`,scope:t},spanGate:n})}function yCi(e){return e===void 0||e>=2?`projects`:`agents`}var bCi=[`projects`,`agents`,`workflows`,`tools`,`models`,`threads`,`environments`],xCi=bCi.filter(e=>e!==`projects`);function SCi({onRowClick:e}){let t=Sxi().projectLabel!==void 0,n=pxi(),r=Dxi(),[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:kxi,bodyHeight:`fit`,children:(0,K.jsx)(e9.Loading,{})});let o={tabs:t?bCi:xCi,onTabChange:a,onRowClick:e,byProject:t};return t&&n.status===`ready`?(0,K.jsx)(vCi,{...o,chosen:i,traceScope:n.scope,spanGate:r}):(0,K.jsx)(_Ci,{...o,tab:i??`agents`,traceGate:n,spanGate:r})}function CCi({experiment:e,metrics:t}){let{data:n}=jN({experimentId:e.id,experimentStatus:e.status,queryOptions:{enabled:!!e.id}}),{data:r,isLoading:i}=smi({experiments:(0,G.useMemo)(()=>[{id:e.id,status:e.status}],[e.id,e.status]),supportsMetrics:t?.isEnabled??!1}),a=e.status===`running`||e.status===`pending`||i,o=(0,G.useMemo)(()=>{if(!n)return;let e=Object.values(n).flat();return e.length===0?null:e.reduce((e,t)=>e+t.score,0)/e.length},[n]),s=e.startedAt??e.createdAt,c=!e.startedAt||!e.completedAt?`—`:iC(new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime())??`—`,l=r[e.id]?.summary,u=H7(l),d=l?.inputTokens===void 0&&l?.outputTokens===void 0?`input + output`:(0,K.jsxs)(AC,{singleLine:!0,children:[(0,K.jsxs)(AC.Item,{children:[V7(l.inputTokens??0),` in`]}),(0,K.jsxs)(AC.Item,{children:[V7(l.outputTokens??0),` out`]})]}),f=t?.isEnabled?t.data?.avgAgentDurationMs:void 0,p=f==null?void 0:iC(Math.round(f)),m=p?`${p} avg per item`:s?`started ${bC(new Date(s),`date-time`)}`:`not started`;return(0,K.jsxs)($_i,{children:[t?.isEnabled&&(0,K.jsx)(wyi,{label:`Total cost`,icon:Lgi,value:l?.estimatedCost===void 0?`—`:B7(l.estimatedCost,l.costUnit),detail:`estimated`,isLoading:a}),(0,K.jsx)(wyi,{label:`Run duration`,icon:XS,value:c,detail:m}),t?.isEnabled&&(0,K.jsx)(wyi,{label:`Total tokens`,icon:Z4,value:u===void 0?`—`:V7(u),detail:d,isLoading:a}),(0,K.jsx)(wyi,{label:`Avg score`,icon:G4,value:o==null?`—`:o.toFixed(3),detail:o==null?`no scores`:`across all scorers`,isLoading:o===void 0})]})}function wCi({selection:e}){let{selectedIds:t,selectedResults:n,tagVocabulary:r,isFlagging:i,isTagging:a}=e,o=i||a,s=t.size===0;return(0,K.jsxs)(`div`,{className:`flex min-h-8 items-center gap-2 whitespace-nowrap`,children:[(0,K.jsxs)(X,{variant:`ghost`,size:`sm`,disabled:s,iconEnd:s?void 0:(0,K.jsx)(xw,{}),onClick:e.clearSelection,tooltip:s?void 0:`Clear selection`,className:`tabular-nums`,children:[t.size,` selected`]}),!s&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(X,{size:`sm`,disabled:o,onClick:e.flagSelectedForReview,icon:(0,K.jsx)(UN,{}),children:`Request review`}),(0,K.jsx)(L_i,{selectedResults:n,vocabulary:r,onAddTag:e.addTagToSelected,disabled:o})]})]})}var TCi=e=>Math.floor(Math.random()*e);function ECi({messages:e,intervalMs:t=3e3}){let n=e.length,[r,i]=(0,G.useState)(()=>TCi(n));return(0,G.useEffect)(()=>{if(n<2)return;let e=setInterval(()=>i(e=>(e+1+TCi(n-1))%n),t);return()=>clearInterval(e)},[n,t]),n===0?null:(0,K.jsx)(K.Fragment,{children:e[r%n]})}function DCi(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 OCi=[`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…`],kCi=`Waiting to start…`;function ACi({experiment:e}){let{status:t,totalItems:n,succeededCount:r,failedCount:i,startedAt:a}=e,o=DCi(),s=r+i,c=n===1?`item`:`items`,l=t===`pending`,u=a?Math.floor((o-new Date(a).getTime())/1e3)*1e3:void 0,d=!l&&u!==void 0?iC(u):void 0;return(0,K.jsx)(Jx,{variant:`fill`,as:`h2`,iconSlot:(0,K.jsx)(It,{}),titleSlot:l?`Experiment queued`:`Experiment in progress`,descriptionSlot:(0,K.jsxs)(`span`,{className:`flex flex-col items-center gap-1`,children:[(0,K.jsx)(`span`,{children:l?kCi:(0,K.jsx)(ECi,{messages:OCi})}),(0,K.jsxs)(AC,{className:`justify-center tabular-nums`,children:[(0,K.jsxs)(AC.Item,{children:[s,` / `,n,` `,c,` finished`]}),d&&(0,K.jsxs)(AC.Item,{children:[d,` elapsed`]})]})]})})}var jCi={pending:{icon:(0,K.jsx)(tC,{className:`size-icon-md text-warning-foreground`}),label:K7.pending},running:{icon:(0,K.jsx)(It,{size:`sm`}),label:K7.running},completed:{icon:(0,K.jsx)(EX,{className:`size-icon-md text-muted-foreground`}),label:K7.completed},failed:{icon:(0,K.jsx)(qx,{className:`size-icon-md text-destructive-foreground`}),label:K7.failed}};function MCi({status:e,className:t}){let n=jCi[e]??jCi.pending;return(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{render:(0,K.jsx)(`span`,{tabIndex:0,className:c(`flex shrink-0 items-center`,t),children:n.icon})}),(0,K.jsx)(Tx,{children:n.label})]})}var NCi=()=>{let{experimentId:e}=kv(),{data:t}=RAt({experimentId:e??``,queryOptions:{enabled:!!e,retryOnMount:!1}});return{experimentId:e,experiment:t}},PCi=()=>{let{experimentId:e,experiment:t}=NCi(),n=t?.datasetId??``,{data:r}=OAt({datasetId:n,experimentId:e??``,queryOptions:{enabled:!!(n&&e),retryOnMount:!1}});return r??t};function FCi(){let{experimentId:e,experiment:t}=NCi();if(!e)return null;let n=e.length>8?`${e.slice(0,8)}...`:e;return t?.name||n}function ICi(){let e=PCi();return e?.status?(0,K.jsx)(MCi,{status:e.status}):null}function LCi(){let e=PCi();if(!e||e.status===`running`||e.status===`pending`)return null;let{totalItems:t,failedCount:n}=e,r=`${t} ${t===1?`item`:`items`}`;return(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`tabular-nums`,children:(0,K.jsxs)(AC,{children:[(0,K.jsx)(AC.Item,{children:r}),n>0&&(0,K.jsxs)(AC.Item,{children:[n,` errored`]})]})})}function RCi({datasetId:e,experimentId:t}){let[n,r]=(0,G.useState)(!1),{updateExperimentResult:i}=ON();return{addTag:(0,G.useCallback)(async(a,o)=>{let s=o.filter(e=>!(e.tags??[]).includes(a));if(n||s.length===0)return;r(!0);let c=0;try{c=(await Promise.allSettled(s.map(n=>i.mutateAsync({datasetId:e,experimentId:t,resultId:n.id,tags:[...n.tags??[],a]})))).filter(e=>e.status===`fulfilled`).length}finally{r(!1)}c>0?iS(`Tag "${a}" added to ${c} result${c>1?`s`:``}`):iS.error(`Failed to add tag`)},[e,t,n,i]),isPending:n}}function zCi(e,t){let{data:n}=AN({datasetId:e,queryOptions:{enabled:!!e}});return(0,G.useMemo)(()=>[...new Set([...n?.tags??[],...t.flatMap(e=>e.tags??[])])].sort(),[n?.tags,t])}function BCi({datasetId:e,experimentId:t,results:n}){let[r,i]=(0,G.useState)(new Set),[a,o]=(0,G.useState)(!1),{updateExperimentResult:s}=ON(),{addTag:c,isPending:l}=RCi({datasetId:e,experimentId:t}),u=zCi(e,n),d=(0,G.useMemo)(()=>n.filter(e=>r.has(e.id)),[n,r]),f=(0,G.useCallback)(e=>{i(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),p=(0,G.useCallback)(()=>i(new Set),[]);return{selectedIds:r,selectedResults:d,toggleSelect:f,toggleSelectAll:(0,G.useCallback)(()=>{i(e=>n.length>0&&n.every(t=>e.has(t.id))?new Set:new Set(n.map(e=>e.id)))},[n]),clearSelection:p,flagSelectedForReview:(0,G.useCallback)(async()=>{if(a||r.size===0)return;o(!0);let n=new Set;try{for(let i of r)try{await s.mutateAsync({datasetId:e,experimentId:t,resultId:i,status:`needs-review`}),n.add(i)}catch{}}finally{o(!1)}n.size>0&&(i(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),iS(`${n.size} result${n.size>1?`s`:``} flagged for review`))},[e,t,a,r,s]),isFlagging:a,addTagToSelected:(0,G.useCallback)(e=>c(e,d),[c,d]),isTagging:l,tagVocabulary:u}}var VCi=[];function HCi({crumbs:e,children:t}){return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:e}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Experiment`}),(0,K.jsx)(`div`,{}),(0,K.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:t})]})}function UCi(){let{experimentId:e}=kv(),t=[eP(`/experiments`),{id:`experiment`,Component:FCi,icon:ICi,Action:LCi}],n=Ov(),[r,i]=(0,G.useState)(!1),a=a5(),{data:o,isLoading:s,error:c}=RAt({experimentId:e??``,queryOptions:{enabled:!!e}}),l=o?.datasetId??``,{data:u,isLoading:d,error:f}=OAt({datasetId:l,experimentId:e??``,queryOptions:{enabled:!!l&&!!e}}),p=u?.status===`completed`||u?.status===`failed`,{data:m,isLoading:h,setEndOfListElement:g,isFetchingNextPage:_,hasNextPage:v}=AAt({datasetId:l,experimentId:e??``,experimentStatus:u?.status,queryOptions:{enabled:!!l&&!!e&&p}}),{supportsMetrics:y}=S7(),b=cmi({experimentId:e,experimentStatus:u?.status,supportsMetrics:y,queryOptions:{enabled:!!e&&y&&p}}),x=BCi({datasetId:l,experimentId:e??``,results:m??VCi}),S=c??f;if(!e||s||d)return null;if(S&&FN(S))return(0,K.jsx)(HCi,{crumbs:t,children:(0,K.jsx)(TH,{})});if(S&&IN(S))return(0,K.jsx)(HCi,{crumbs:t,children:(0,K.jsx)(wH,{resource:`datasets`})});let C=(0,K.jsx)(HCi,{crumbs:t,children:(0,K.jsx)(Jx,{titleSlot:`Experiment not found`,descriptionSlot:`No experiment with id "${e}".`,actionSlot:(0,K.jsx)(X,{render:(0,K.jsx)(Lv,{to:`/experiments`}),icon:(0,K.jsx)(sS,{}),children:`Back to experiments`})})});return S&&LN(S)?C:S?(0,K.jsx)(HCi,{crumbs:t,children:(0,K.jsx)(Jx,{tone:`error`,titleSlot:`Failed to load experiment`,descriptionSlot:S instanceof Error?S.message:`An unexpected error occurred. Please try again.`})}):!l||!u?C:(0,K.jsx)(bmi,{experimentId:e,datasetId:l,experimentStatus:u.status,results:m??[],isLoadingResults:h,hasNextPage:v,children:(0,K.jsxs)(`div`,{className:`h-full`,children:[(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:t}),headerActions:(0,K.jsx)(N_i,{experiment:u,onDeleteClick:()=>i(!0)}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),p?(0,K.jsxs)(`div`,{className:`grid content-start gap-4`,children:[(0,K.jsx)(CCi,{experiment:u,metrics:b}),(0,K.jsxs)(`div`,{className:`grid content-start gap-1`,children:[(0,K.jsx)(wCi,{selection:x}),(0,K.jsx)(Umi,{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)(ACi,{experiment:u})]}),(0,K.jsx)(Q_i,{withQueryTrace:a.enabled,withFeedback:a.enabled}),(0,K.jsx)(Nhi,{open:r,onOpenChange:i,experimentId:e,experimentName:u.name??void 0,onSuccess:()=>n(`/experiments`)})]})})}function WCi({tag:e,onRename:t,onRemove:n}){let[r,i]=(0,G.useState)(!1),[a,o]=(0,G.useState)(e),s=(0,G.useRef)(null);(0,G.useEffect)(()=>{r&&(s.current?.focus(),s.current?.select())},[r]);let l=()=>{let n=a.trim();n&&n!==e&&t(n),i(!1)};return r?(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 rounded-md border border-border bg-card px-1`,children:[(0,K.jsx)(Jj,{variant:`unstyled`,ref:s,value:a,onChange:e=>o(e.target.value),onKeyDown:t=>{t.key===`Enter`&&(t.preventDefault(),l()),t.key===`Escape`&&(o(e),i(!1))},onBlur:l,className:`h-auto w-20 bg-transparent px-0 py-0.5 text-caption text-muted-foreground outline-hidden`}),(0,K.jsx)(`button`,{type:`button`,onMouseDown:e=>{e.preventDefault(),l()},className:c(SS,`p-0.5`),children:(0,K.jsx)(pC,{className:`size-icon-xs`})})]}):(0,K.jsxs)(`span`,{className:`group inline-flex items-center gap-0.5 rounded-md border border-border bg-card px-1.5 py-0.5 text-muted-foreground`,children:[(0,K.jsx)(T,{as:`span`,variant:`caption`,children:e}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>{o(e),i(!0)},className:c(SS,`p-0.5 opacity-0 transition-opacity group-hover:opacity-100`),title:`Edit tag`,children:(0,K.jsx)(iH,{className:`size-icon-xs`})}),(0,K.jsx)(`button`,{type:`button`,onClick:n,className:`p-0.5 text-placeholder opacity-0 transition-opacity group-hover:opacity-100 hover:text-destructive-foreground`,title:`Remove tag`,children:(0,K.jsx)(xw,{className:`size-icon-xs`})})]})}function GCi({selectedCount:e,vocabulary:t,onApplyTag:n,onRemoveTag:r,onNewTag:i,size:a=`sm`}){let[o,s]=(0,G.useState)(!1),[c,l]=(0,G.useState)(``),u=t.filter(e=>e.toLowerCase().includes(c.toLowerCase())),d=c.trim()&&!t.includes(c.trim());return(0,K.jsxs)(Xj,{open:o,onOpenChange:s,children:[(0,K.jsx)(Zj,{asChild:!0,children:(0,K.jsxs)(X,{size:a,icon:(0,K.jsx)(wX,{}),children:[`Tag `,e,` items`]})}),(0,K.jsxs)(Qj,{className:`w-56 p-2`,align:`end`,children:[(0,K.jsx)(Jj,{value:c,onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Enter`&&c.trim()&&(e.preventDefault(),d?i(c.trim()):n(c.trim()),l(``))},placeholder:`Search or create tag`,className:`mb-1 h-7 text-caption`,autoFocus:!0}),(0,K.jsxs)(`div`,{className:`max-h-40 space-y-0.5 overflow-y-auto`,children:[u.map(e=>(0,K.jsxs)(`div`,{className:`flex items-center justify-between rounded px-2 py-1 hover:bg-fill-subtle`,children:[(0,K.jsx)(`button`,{type:`button`,onClick:()=>n(e),className:`flex-1 text-left text-muted-foreground`,children:(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`block`,children:e})}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>r(e),className:`ml-2 text-placeholder hover:text-destructive-foreground`,children:(0,K.jsx)(xw,{className:`size-icon-xs`})})]},e)),d&&(0,K.jsx)(`button`,{type:`button`,onClick:()=>{i(c.trim()),l(``)},className:`w-full rounded px-2 py-1 text-left text-info-indicator hover:bg-fill-subtle`,children:(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[`Create & apply "`,c.trim(),`"`]})})]})]})]})}var KCi=[{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`}],qCi=`__untagged__`,JCi=`all`,YCi=[{value:`review`,label:`Review queue`},{value:`completed`,label:`Completed`}];function XCi({datasetId:e,experimentId:t,experiments:n,isLoadingExperiments:r,targetType:i,targetId:a,featuredItemId:o,toolbarStart:s,renderFilters:l,toolbarEnd:u,onCreateScorer:d,breadcrumbs:f,withQueryTrace:p,withFeedback:m}){let h=Y(),{paths:g}=sn(),{data:_}=AN({datasetId:e??``,queryOptions:{enabled:!!e}}),v=khi({experimentId:t,targetType:i,targetId:a,experiments:n,isLoadingExperiments:r}),y=Ahi({experimentId:t,targetType:i,targetId:a,experiments:n,isLoadingExperiments:r}),{data:b,isLoading:x}=v,{data:S,isLoading:C}=y,{updateExperimentResult:w}=ON(),[E,D]=(0,G.useState)(o??null);(0,G.useEffect)(()=>{o!==void 0&&D(o)},[o]);let[O,k]=(0,G.useState)(null),[A,j]=(0,G.useState)(new Set),[M,N]=(0,G.useState)(!1),[P,F]=(0,G.useState)(!1),[I,L]=(0,G.useState)(!1),[R,z]=(0,G.useState)(``),[B,V]=(0,G.useState)(``),[H,ee]=(0,G.useState)(``),[te,U]=(0,G.useState)([]),[W,ne]=(0,G.useState)(!1),re=(0,G.useMemo)(()=>b??[],[b]),ie=(0,G.useMemo)(()=>{let e=new Set;if(_?.tags)for(let t of _.tags)e.add(t);for(let t of re)for(let n of t.tags)e.add(n);return[...e].sort()},[_,re]),ae=(0,G.useMemo)(()=>O?O===qCi?re.filter(e=>e.tags.length===0):re.filter(e=>e.tags.includes(O)):re,[re,O]),oe=(0,G.useMemo)(()=>{let e=new Map,t=0;for(let n of re){n.tags.length===0&&t++;for(let t of n.tags)e.set(t,(e.get(t)??0)+1)}let n=[...e.entries()].sort((e,t)=>t[1]-e[1]).map(([e])=>({value:e,label:e}));return[{value:JCi,label:`All tags`},...t>0?[{value:qCi,label:`Untagged`}]:[],...n]},[re]),se=!!O||M,ce=(0,G.useCallback)(()=>{k(null),N(!1),D(null)},[]),le=(0,G.useCallback)((e,t)=>{let n=re.find(t=>t.id===e);n?.experimentId&&n?.datasetId&&w.mutate({datasetId:n.datasetId,experimentId:n.experimentId,resultId:n.id,tags:t})},[re,w]),ue=(0,G.useCallback)(e=>{let t=re.find(t=>t.id===e);j(t=>{let n=new Set(t);return n.delete(e),n}),E===e&&D(null),t?.experimentId&&t?.datasetId&&w.mutate({datasetId:t.datasetId,experimentId:t.experimentId,resultId:t.id,status:null})},[re,w,E]),de=(0,G.useCallback)(e=>{let t=re.find(t=>t.id===e);j(t=>{let n=new Set(t);return n.delete(e),n}),E===e&&D(null),t?.experimentId&&t?.datasetId&&w.mutate({datasetId:t.datasetId,experimentId:t.experimentId,resultId:t.id,status:`complete`})},[re,w,E]),fe=(0,G.useMemo)(()=>{let e=M?S??[]:ae;return!M||!O?e:O===qCi?e.filter(e=>e.tags.length===0):e.filter(e=>e.tags.includes(O))},[M,S,ae,O]),pe=M?C:!1,me=(0,G.useMemo)(()=>new Set(fe.map(e=>e.id)),[fe]),he=(0,G.useMemo)(()=>[...A].filter(e=>me.has(e)).length,[A,me]),ge=fe.length>0&&he===fe.length,_e=(0,G.useCallback)(e=>{j(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),ve=(0,G.useCallback)(()=>{j(ge?new Set:new Set(fe.map(e=>e.id)))},[ge,fe]),ye=(0,G.useCallback)(e=>{for(let t of A){let n=re.find(e=>e.id===t);n&&!n.tags.includes(e)&&le(t,[...n.tags,e])}},[re,A,le]),be=(0,G.useCallback)(e=>{for(let t of A){let n=re.find(e=>e.id===t);n&&n.tags.includes(e)&&le(t,n.tags.filter(t=>t!==e))}},[re,A,le]),xe=(0,G.useCallback)(()=>{for(let e of A)de(e);j(new Set)},[A,de]),Se=(0,G.useCallback)(()=>{for(let e of A)ue(e);j(new Set)},[A,ue]),Ce=(0,G.useCallback)(()=>{z(``),L(!0)},[]),we=(0,G.useCallback)(async()=>{if(B&&H){F(!0),L(!1);try{let e=re.filter(e=>A.has(e.id));if(e.length===0){F(!1);return}let t=await h.clusterFailures({modelId:`${B}/${H}`,items:e.map(e=>({id:e.id,input:e.input,output:e.output??void 0,error:typeof e.error==`string`?e.error:e.error?String(e.error):void 0,scores:e.scores,existingTags:e.tags.length>0?e.tags:void 0})),availableTags:ie.length>0?ie:void 0,prompt:R||void 0});t.proposedTags&&t.proposedTags.length>0&&(U(t.proposedTags.map(e=>({...e,accepted:!0}))),ne(!0))}catch(e){console.error(`Analysis failed:`,e)}finally{F(!1)}}},[B,H,re,A,h,ie,R]),Te=(0,G.useCallback)(()=>{for(let e of te){if(!e.accepted)continue;let t=re.find(t=>t.id===e.itemId);if(t){let n=[...new Set([...t.tags,...e.tags])];le(t.id,n)}}ne(!1)},[te,re,le]),Ee=(0,G.useCallback)(e=>{D(t=>t===e?null:e)},[]),De=(0,G.useMemo)(()=>E?fe.find(e=>e.id===E)??null:null,[E,fe]),{data:Oe}=jN({experimentId:De?.experimentId??``,queryOptions:{enabled:!!De?.experimentId}}),ke=M?y:v,Ae=fe.length===0||!(!E||De);(0,G.useEffect)(()=>{Ae&&ke.hasNextPage&&!ke.isFetching&&ke.fetchNextPage({cancelRefetch:!1})},[Ae,ke]);let je=E?fe.findIndex(e=>e.id===E):-1,Me=je>0?()=>D(fe[je-1].id):void 0,Ne=je>=0&&je<fe.length-1?()=>D(fe[je+1].id):void 0,Pe=!M&&A.size>0,Fe=!!d&&!M&&ae.length>0,Ie=M?`completed`:`review`,Le=e=>{N(e===`completed`),D(null)},Re=(0,K.jsxs)(TK,{children:[(0,K.jsx)(TK.Start,{children:l?(0,K.jsxs)(K.Fragment,{children:[s,l({status:Ie,onStatusChange:Le,tag:O,onTagChange:k,tagOptions:oe.filter(e=>e.value!==JCi)})]}):(0,K.jsxs)(K.Fragment,{children:[s,(0,K.jsxs)(Bk,{value:Ie,onValueChange:e=>Le(e===`completed`?`completed`:`review`),children:[(0,K.jsx)(Hk,{"aria-label":`Status`,size:`md`,className:`whitespace-nowrap`,children:(0,K.jsx)(Vk,{placeholder:`Select an option`})}),(0,K.jsx)(Uk,{children:YCi.map(e=>(0,K.jsx)(Wk,{value:e.value,children:e.label},e.value))})]}),oe.length>1&&(0,K.jsxs)(Bk,{value:O??JCi,onValueChange:e=>k(e===JCi?null:e),children:[(0,K.jsx)(Hk,{"aria-label":`Tags`,size:`md`,className:`whitespace-nowrap`,children:(0,K.jsx)(Vk,{placeholder:`Select an option`})}),(0,K.jsx)(Uk,{children:oe.map(e=>(0,K.jsx)(Wk,{value:e.value,children:e.label},e.value))})]}),se&&(0,K.jsx)(X,{onClick:ce,size:`sm`,variant:`default`,icon:(0,K.jsx)(xw,{}),children:`Reset`})]})}),(Pe||u||Fe)&&(0,K.jsxs)(TK.End,{children:[u,Fe&&(0,K.jsxs)(X,{size:`md`,onClick:()=>d?.(ae.map(e=>({input:e.input,output:e.output}))),children:[(0,K.jsx)(Dx,{size:`xs`,children:(0,K.jsx)(G4,{})}),`Create scorer`]}),Pe&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(GCi,{size:`md`,selectedCount:A.size,vocabulary:ie,onApplyTag:ye,onRemoveTag:be,onNewTag:e=>ye(e)}),(0,K.jsx)(X,{variant:`primary`,onClick:xe,icon:(0,K.jsx)(EX,{}),children:`Mark as reviewed`}),(0,K.jsxs)(rE,{children:[(0,K.jsx)(rE.Trigger,{asChild:!0,children:(0,K.jsx)(X,{size:`icon-md`,disabled:P,"aria-label":`More actions`,children:P?(0,K.jsx)(It,{className:`h-4 w-4`}):(0,K.jsx)(M4,{})})}),(0,K.jsxs)(rE.Content,{align:`end`,children:[(0,K.jsxs)(rE.Item,{onSelect:Ce,children:[(0,K.jsx)(Dx,{size:`xs`,children:(0,K.jsx)(DZ,{})}),`Analyze`]}),(0,K.jsx)(rE.Separator,{}),(0,K.jsxs)(rE.Item,{onSelect:Se,children:[(0,K.jsx)(Dx,{size:`xs`,children:(0,K.jsx)(Kj,{})}),`Remove from queue`]})]})]})]})]})]});if(x)return(0,K.jsxs)(RS,{breadcrumbs:f,actionRow:Re,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(It,{fill:!0})]});let ze=(0,K.jsx)(X_i,{withQueryTrace:p,withFeedback:m,result:De??void 0,title:`Review item ${De?.id??``}`,scores:De?Oe?.[De.itemId]:void 0,experimentLink:De?.experimentId?g.experimentItemLink(De.experimentId,De.itemId):void 0,onComplete:M||!De?void 0:()=>de(De.id),onPrevious:Me,onNext:Ne,onClose:()=>D(null)});return(0,K.jsxs)(RS,{breadcrumbs:f,actionRow:Re,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(nT,{open:I,onOpenChange:L,children:(0,K.jsxs)(rT,{children:[(0,K.jsxs)(iT,{children:[(0,K.jsx)(sT,{children:`Analyze Items`}),(0,K.jsx)(cT,{children:`Use an LLM to automatically suggest tags for the selected items.`})]}),(0,K.jsxs)(oT,{children:[(0,K.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[(0,K.jsxs)(ak,{className:`gap-1`,children:[(0,K.jsx)(sk,{children:`Provider`}),(0,K.jsx)(Mq,{value:B,onValueChange:V})]}),(0,K.jsxs)(ak,{className:`gap-1`,children:[(0,K.jsx)(sk,{children:`Model`}),(0,K.jsx)(Nq,{llmId:B,value:H,onValueChange:ee})]})]}),(0,K.jsxs)(T,{variant:`meta`,tone:`muted`,children:[A.size,` item`,A.size===1?``:`s`,` will be analyzed`]}),(0,K.jsxs)(ak,{className:`gap-1`,children:[(0,K.jsx)(sk,{children:`Instructions (optional)`}),(0,K.jsx)(qk,{className:`text-caption`,value:R,onChange:e=>z(e.target.value),placeholder:`E.g., Focus on safety issues and factual errors`,rows:3})]})]}),(0,K.jsxs)(aT,{children:[(0,K.jsx)(lT,{children:`Cancel`}),(0,K.jsx)(tT,{onConfirm:we,disabled:!B||!H||P,children:`Analyze`})]})]})}),(0,K.jsx)(nT,{open:W,onOpenChange:ne,children:(0,K.jsxs)(rT,{size:`lg`,children:[(0,K.jsxs)(iT,{children:[(0,K.jsx)(sT,{children:`Review Proposed Tags`}),(0,K.jsxs)(cT,{children:[te.filter(e=>e.accepted).length,` of `,te.length,` proposals selected`]})]}),(0,K.jsx)(oT,{children:te.map((e,t)=>{let n=re.find(t=>t.id===e.itemId);return(0,K.jsx)(`div`,{className:c(`rounded-lg border p-3`,!e.accepted&&`opacity-50`),children:(0,K.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,K.jsx)(qj,{checked:e.accepted,onCheckedChange:e=>U(n=>n.map((n,r)=>r===t?{...n,accepted:!!e}:n))}),(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsx)(T,{variant:`meta`,tone:`muted`,className:`block truncate`,children:n?typeof n.input==`string`?n.input.slice(0,100):JSON.stringify(n.input).slice(0,100):e.itemId}),(0,K.jsx)(`div`,{className:`mt-1.5 flex flex-wrap gap-1`,children:e.tags.map((e,n)=>(0,K.jsx)(WCi,{tag:e,onRename:e=>U(r=>r.map((r,i)=>i===t?{...r,tags:r.tags.map((t,r)=>r===n?e:t)}:r)),onRemove:()=>U(e=>e.map((e,r)=>r===t?{...e,tags:e.tags.filter((e,t)=>t!==n)}:e))},`${e}-${n}`))}),e.reason&&(0,K.jsx)(T,{variant:`meta`,tone:`muted`,className:`mt-1 block italic`,children:e.reason})]})]})},e.itemId)})}),(0,K.jsxs)(aT,{children:[(0,K.jsx)(lT,{children:`Cancel`}),(0,K.jsxs)(tT,{onConfirm:Te,disabled:te.filter(e=>e.accepted).length===0,children:[`Accept `,te.filter(e=>e.accepted).length,` proposals`]})]})]})}),(0,K.jsxs)(`div`,{className:`grid h-full min-h-0 w-full grid-cols-1 gap-4 overflow-hidden`,children:[(0,K.jsx)(`div`,{className:`min-h-0 w-full overflow-hidden`,children:pe||fe.length===0&&ke.hasNextPage?(0,K.jsx)(It,{fill:!0}):fe.length===0?(0,K.jsx)(Jx,{titleSlot:M?`No completed reviews yet`:`No items to review`,descriptionSlot:M?`Items marked as complete will appear here for auditing.`:`When experiment results are flagged for review, they will appear here.`,variant:`fill`}):(0,K.jsx)(Rmi,{results:fe,isLoading:!1,featuredResultId:E,onResultClick:Ee,columns:KCi,selectedIds:M?void 0:A,onToggleSelect:M?void 0:_e,onToggleSelectAll:M?void 0:ve,setEndOfListElement:ke.setEndOfListElement,hasNextPage:ke.hasNextPage,isFetchingNextPage:ke.isFetchingNextPage})}),ze]})]})}var ZCi=`experiment`,QCi=`status`,$Ci=[{value:`review`,label:`Review queue`},{value:`completed`,label:`Completed`}],ewi=[{id:`is`,label:`is`}],twi=({targetType:e,targetId:t,experimentId:n,status:r,tag:i})=>{let a=yli({targetType:e,targetId:t});return n&&a.push(T7(ZCi,n)),r!==`review`&&a.push(T7(QCi,r)),i&&a.push(T7(`tag`,i)),a},nwi=e=>({...bli(e),experimentId:E7(e,ZCi),status:E7(e,`status`)===`completed`?`completed`:`review`,tag:E7(e,`tag`)||null});function rwi({targetType:e,targetId:t,experimentId:n,status:r,tag:i,experiments:a,tagOptions:o,onChange:s}){let c=xli(e),l=(0,G.useMemo)(()=>[...c,{id:ZCi,label:`Experiment`,icon:GN,color:sP(`pink`),strict:!0,suggestions:a.map(e=>({value:e.id,label:zhi(e)}))},{id:QCi,label:`Status`,icon:EX,color:sP(`orange`),strict:!0,suggestions:$Ci},{id:`tag`,label:`Tag`,icon:wX,color:sP(`pink`),strict:!0,hidden:o.length===0,suggestions:o}],[c,a,o]),u=(0,G.useMemo)(()=>twi({targetType:e,targetId:t,experimentId:n,status:r,tag:i}),[e,t,n,r,i]);return(0,K.jsxs)(m5,{fields:l,operators:ewi,value:u,onValueChange:e=>s(nwi(e)),createItemId:e=>e,"aria-label":`Review queue filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(m5.Chips,{}),(0,K.jsx)(m5.Input,{placeholder:`Filter review queue`})]})}var iwi=[eP(`/experiments`),eP(`/experiments/review-queue`)],awi=`experiment`,owi=`review`;function swi(){let[e,t]=Rv(),n=e.get(O7),r=hli(n)?n:``,i=r?e.get(`targetId`)??``:``,a=e.get(awi),o=e.get(owi),{Link:s,paths:c}=sn(),l=a5(),{data:u,error:d}=umi({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(awi,o):n.delete(awi),n.delete(owi),n},{replace:!0})};return d&&FN(d)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:iwi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(TH,{variant:`fill`})]}):d&&IN(d)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:iwi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(wH,{variant:`fill`,resource:`experiments`})]}):d?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:iwi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Review Queue`}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load experiments`,descriptionSlot:d.message})]}):(0,K.jsx)(XCi,{withQueryTrace:l.enabled,withFeedback:l.enabled,breadcrumbs:(0,K.jsx)(vN,{crumbs:iwi}),datasetId:f?.datasetId??void 0,experimentId:a??void 0,targetType:r,targetId:i,featuredItemId:o,renderFilters:e=>(0,K.jsx)(rwi,{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 cwi({connection:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){let i=t?e.authorId:void 0;return(0,K.jsxs)(`li`,{className:`flex items-center justify-between gap-4 border-b py-2`,children:[(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-2`,children:[(0,K.jsx)(T,{as:`p`,variant:`caption`,font:`mono`,className:`wrap-anywhere`,children:e.connectionId}),(0,K.jsxs)(AC,{children:[(0,K.jsx)(AC.Item,{children:(0,K.jsx)(T,{as:`span`,variant:`caption`,children:e.label??`(no label)`})}),(0,K.jsx)(AC.Item,{children:(0,K.jsx)(eC,{size:`xs`,emphasis:`subtle`,children:e.status})})]}),(e.scope||i)&&(0,K.jsxs)(`dl`,{className:`flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1`,children:[e.scope&&(0,K.jsxs)(`div`,{className:`flex min-w-0 items-baseline gap-1`,children:[(0,K.jsx)(`dt`,{children:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`faint`,children:`Scope`})}),(0,K.jsx)(`dd`,{className:`min-w-0`,children:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:e.scope})})]}),i&&(0,K.jsxs)(`div`,{className:`flex min-w-0 items-baseline gap-1`,children:[(0,K.jsx)(`dt`,{children:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`faint`,children:`Author`})}),(0,K.jsx)(`dd`,{className:`min-w-0 wrap-anywhere`,children:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:i})})]})]})]}),(0,K.jsx)(`button`,{type:`button`,className:`shrink-0 text-destructive-foreground underline disabled:opacity-50`,onClick:r,disabled:n,children:`Disconnect`})]})}function lwi({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return(0,K.jsx)(`ul`,{className:`space-y-1`,children:e.map(e=>(0,K.jsx)(cwi,{connection:e,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(e.connectionId)},e.connectionId))})}function uwi({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)(lwi,{connections:i,isAdmin:t,disconnectPending:n,onDisconnect:r})]},e))})}function dwi({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)(uwi,{groups:r,isAdmin:i,disconnectPending:s,onDisconnect:l}):(0,K.jsx)(lwi,{connections:n,isAdmin:i,disconnectPending:s,onDisconnect:l}),c?(0,K.jsx)(`p`,{className:`text-destructive-foreground`,children:String(c)}):null]})}function fwi({providers:e,toolkits:t,providerId:n,toolkit:r,label:i,providersLoading:a,providersError:o,toolkitsLoading:s,toolkitsError:c,authorizePending:l,authorizeError:u,authorizedConnection:d,onProviderChange:f,onToolkitChange:p,onLabelChange:m,onConnect:h}){return(0,K.jsxs)(`div`,{className:`space-y-4 rounded border p-4`,children:[(0,K.jsxs)(ak,{invalid:!!o,disabled:a,children:[(0,K.jsx)(sk,{children:`Provider`}),(0,K.jsxs)(Bk,{value:n,onValueChange:f,children:[(0,K.jsx)(Hk,{children:(0,K.jsx)(Vk,{placeholder:a?`Loading providers…`:`Select provider`})}),(0,K.jsx)(Uk,{children:e.map(e=>(0,K.jsx)(Wk,{value:e.id,children:`${e.displayName??e.name} (${e.id})`},e.id))})]}),(0,K.jsx)(lk,{children:o?String(o):void 0})]}),(0,K.jsxs)(ak,{invalid:!!c,disabled:!n||s,children:[(0,K.jsx)(sk,{children:`Toolkit`}),(0,K.jsxs)(Bk,{value:r,onValueChange:p,children:[(0,K.jsx)(Hk,{children:(0,K.jsx)(Vk,{placeholder:s?`Loading toolkits…`:`Select toolkit`})}),(0,K.jsx)(Uk,{children:t.map(e=>(0,K.jsx)(Wk,{value:e.slug,children:`${e.name} (${e.slug})`},e.slug))})]}),(0,K.jsx)(lk,{children:c?String(c):void 0})]}),(0,K.jsxs)(ak,{disabled:!n||!r,children:[(0,K.jsx)(sk,{children:`Label (optional)`}),(0,K.jsx)(Jj,{placeholder:`My personal Gmail`,value:i,onChange:e=>m(e.target.value)})]}),(0,K.jsx)(X,{type:`button`,variant:`primary`,onClick:h,disabled:!n||!r||l,children:l?`Authorizing…`:`Connect`}),u?(0,K.jsx)(`div`,{role:`alert`,children:(0,K.jsx)(Sk,{variant:`destructive`,children:String(u)})}):null,d?(0,K.jsxs)(Sk,{variant:`success`,children:[`Authorized: `,d.connectionId,` (status: `,d.status,`)`]}):null]})}var pwi=e=>e.authorId?.trim()||`shared`,mwi=(e,t)=>{if(!t||new Set(e.map(pwi)).size<=1)return null;let n=new Map;for(let t of e){let e=pwi(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},hwi=[`*`,`tool-providers:*`,`tool-providers:admin`];function gwi(){let{data:e}=j_();return e?.permissions?.some(e=>hwi.includes(e))??!1}var _wi=[{id:`integrations`,label:`Integrations`}];function vwi(){let[e,t]=(0,G.useState)(``),[n,r]=(0,G.useState)(``),[i,a]=(0,G.useState)(``),o=Bq(),s=Hq({providerId:e||null,queryOptions:{enabled:!!e}}),c=_Pn({providerId:e||null,toolkit:n||null}),l=hPn(),u=gPn(),d=gwi(),f=o.data?.providers??[],p=s.data?.data??[],m=(0,G.useMemo)(()=>c.data?.items??[],[c.data?.items]),h=(0,G.useMemo)(()=>mwi(m,d),[m,d]);return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:_wi}),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)(fwi,{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)(dwi,{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 ywi(e){return!e.deletedAt&&!e.mergedInto}function bwi(e){let t=new Map;for(let n of e)ywi(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 xwi(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 Swi(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 Cwi(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 wwi=`more:`,Twi=`rest:`,Ewi=`group:`;function v9(e){return e.id.startsWith(wwi)}function y9(e){return e.id.startsWith(Twi)}function b9(e){return e.id.startsWith(Ewi)}function Dwi(e){return e.filter(e=>!e.deletedAt&&!e.mergedInto)}function Owi(e,t,n=Pwi){let r=Dwi(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=Cwi(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 kwi=230,Awi=300,jwi=150,Mwi=70,Nwi=28,x9=16,Pwi=new Set;function Fwi(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 Iwi(e,t,n,r=Pwi){let i=Dwi(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*Awi))),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(kwi,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?jwi:Mwi,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/Nwi)),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*Nwi);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=Fwi(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=Fwi(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*Nwi/(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)+Mwi;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 Lwi=[`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 Rwi(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,Lwi[t%Lwi.length]]))}var zwi=.7,Bwi=.7;function Vwi(e){return e<=16?1:Math.max(Bwi,Math.sqrt(16/e))}var Hwi={author:``};function Uwi(e,t,n){return{id:e,scopeId:t.scopeId,parentId:t.id,isScope:!1,position:``,name:``,version:0,createdBy:Hwi,updatedBy:Hwi,createdAt:``,updatedAt:``,...n}}function Wwi(e){if(!e.isScope||!e.address)return null;let t=e.address.indexOf(`:`);return t>0?e.address.slice(0,t):null}function Gwi(e){let t=e.cap??48,n=Dwi(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=Cwi(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=Uwi(`${wwi}${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=Wwi(e);t&&g.set(t,[...g.get(t)??[],e])}let _=new Set;if(n!==f?.id)for(let[t,r]of g){let i=`${Ewi}${n}:${t}`;if(r.length<3||e.openGroups.has(i))continue;for(let e of r)_.add(e.id);let c=Uwi(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=Uwi(`${Twi}${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 Kwi={linear:{label:`Linear`,icon:e=>(0,K.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 100 100`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,...e,children:(0,K.jsx)(`path`,{d:`M1.22541 61.5228c-.2225-.9485.90748-1.5459 1.59638-.857L39.3342 97.1782c.6889.6889.0915 1.8189-.857 1.5964C20.0515 94.4522 5.54779 79.9485 1.22541 61.5228ZM.00189135 46.8891c-.01764375.2833.08887215.5599.28957165.7606L52.3503 99.7085c.2007.2007.4773.3075.7606.2896 2.3692-.1476 4.6938-.46 6.9624-.9259.7645-.157 1.0301-1.0963.4782-1.6481L2.57595 39.4485c-.55186-.5519-1.49117-.2863-1.648174.4782-.465915 2.2686-.77832 4.5932-.92588465 6.9624ZM4.21093 29.7054c-.16649.3738-.08169.8106.20765 1.1l64.77602 64.776c.2894.2894.7262.3742 1.1.2077 1.7861-.7956 3.5171-1.6927 5.1855-2.684.5521-.328.6373-1.0867.1832-1.5407L8.43566 24.3367c-.45409-.4541-1.21271-.3689-1.54074.1832-.99132 1.6684-1.88843 3.3994-2.68399 5.1855ZM12.6587 18.074c-.3701-.3701-.393-.9637-.0443-1.3541C21.7795 6.45931 35.1114 0 49.9519 0 77.5927 0 100 22.4073 100 50.0481c0 14.8405-6.4593 28.1724-16.7199 37.3375-.3903.3487-.984.3258-1.3542-.0443L12.6587 18.074Z`})})},notion:{label:`Notion`,icon:e=>(0,K.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,...e,children:(0,K.jsx)(`path`,{d:`M4.459 4.208c.746.606 1.026.56 2.428.466l13.215-.793c.28 0 .047-.28-.046-.326L17.86 1.968c-.42-.326-.981-.7-2.055-.607L3.01 2.295c-.466.046-.56.28-.374.466zm.793 3.08v13.904c0 .747.373 1.027 1.214.98l14.523-.84c.841-.046.935-.56.935-1.167V6.354c0-.606-.233-.933-.748-.887l-15.177.887c-.56.047-.747.327-.747.933zm14.337.745c.093.42 0 .84-.42.888l-.7.14v10.264c-.608.327-1.168.514-1.635.514-.748 0-.935-.234-1.495-.933l-4.577-7.186v6.952L12.21 19s0 .84-1.168.84l-3.222.186c-.093-.186 0-.653.327-.746l.84-.233V9.854L7.822 9.76c-.094-.42.14-1.026.793-1.073l3.456-.233 4.764 7.279v-6.44l-1.215-.139c-.093-.514.28-.887.747-.933zM1.936 1.035l13.31-.98c1.634-.14 2.055-.047 3.082.7l4.249 2.986c.7.513.934.653.934 1.213v16.378c0 1.026-.373 1.634-1.68 1.726l-15.458.934c-.98.047-1.448-.093-1.962-.747l-3.129-4.06c-.56-.747-.793-1.306-.793-1.96V2.667c0-.839.374-1.54 1.447-1.632z`})})},confluence:{label:`Confluence`,icon:e=>(0,K.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,...e,children:(0,K.jsx)(`path`,{d:`M.87 18.257c-.248.382-.53.875-.763 1.245a.764.764 0 0 0 .255 1.04l4.965 3.054a.764.764 0 0 0 1.058-.26c.199-.332.454-.763.733-1.221 1.967-3.247 3.945-2.853 7.508-1.146l4.957 2.337a.764.764 0 0 0 1.028-.382l2.364-5.346a.764.764 0 0 0-.382-1 599.851 599.851 0 0 1-4.965-2.361C10.911 10.97 5.224 11.185.87 18.257zM23.131 5.743c.249-.405.531-.875.764-1.25a.764.764 0 0 0-.256-1.034L18.675.404a.764.764 0 0 0-1.058.26c-.195.335-.451.763-.734 1.225-1.966 3.246-3.945 2.85-7.508 1.146L4.437.694a.764.764 0 0 0-1.027.382L1.046 6.422a.764.764 0 0 0 .382 1c1.039.49 3.105 1.467 4.965 2.361 6.698 3.246 12.392 3.029 16.738-4.04z`})})},zendesk:{label:`Zendesk`,icon:e=>(0,K.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,...e,children:(0,K.jsx)(`path`,{d:`M12.914 2.904V16.29L24 2.905H12.914zM0 2.906C0 5.966 2.483 8.45 5.543 8.45s5.542-2.484 5.543-5.544H0zm11.086 4.807L0 21.096h11.086V7.713zm7.37 7.84c-3.063 0-5.542 2.48-5.542 5.543H24c0-3.06-2.48-5.543-5.543-5.543z`})})},fireflies:{label:`Fireflies`},github:{label:`GitHub`,icon:kZ},slack:{label:`Slack`,icon:e=>(0,K.jsxs)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,...e,children:[(0,K.jsx)(`path`,{d:`M5.042 15.165a2.528 2.528 0 0 1-2.52 2.523A2.528 2.528 0 0 1 0 15.165a2.527 2.527 0 0 1 2.522-2.52h2.52v2.52zm1.271 0a2.527 2.527 0 0 1 2.521-2.52 2.527 2.527 0 0 1 2.521 2.52v6.313A2.528 2.528 0 0 1 8.834 24a2.528 2.528 0 0 1-2.521-2.522v-6.313z`,fill:`#E01E5A`}),(0,K.jsx)(`path`,{d:`M8.834 5.042a2.528 2.528 0 0 1-2.521-2.52A2.528 2.528 0 0 1 8.834 0a2.528 2.528 0 0 1 2.521 2.522v2.52H8.834zm0 1.271a2.527 2.527 0 0 1 2.521 2.521 2.527 2.527 0 0 1-2.521 2.521H2.522A2.528 2.528 0 0 1 0 8.834a2.528 2.528 0 0 1 2.522-2.521h6.312z`,fill:`#36C5F0`}),(0,K.jsx)(`path`,{d:`M18.956 8.834a2.528 2.528 0 0 1 2.522-2.521A2.528 2.528 0 0 1 24 8.834a2.528 2.528 0 0 1-2.522 2.521h-2.522V8.834zm-1.27 0a2.528 2.528 0 0 1-2.523 2.521 2.527 2.527 0 0 1-2.52-2.521V2.522A2.527 2.527 0 0 1 15.165 0a2.528 2.528 0 0 1 2.523 2.522v6.312z`,fill:`#2EB67D`}),(0,K.jsx)(`path`,{d:`M15.165 18.956a2.528 2.528 0 0 1 2.523 2.522A2.528 2.528 0 0 1 15.165 24a2.527 2.527 0 0 1-2.52-2.522v-2.522h2.52zm0-1.27a2.527 2.527 0 0 1-2.52-2.523 2.527 2.527 0 0 1 2.52-2.52h6.313A2.528 2.528 0 0 1 24 15.165a2.528 2.528 0 0 1-2.522 2.523h-6.313z`,fill:`#ECB22E`})]})},google:{label:`Google`,icon:gOn}};function qwi(e){if(!e.isScope||!e.address)return;let t=e.address.slice(0,e.address.indexOf(`:`));return Object.hasOwn(Kwi,t)?Kwi[t]:void 0}function S9(e){let t=qwi(e);return t&&e.name===e.address?t.label:e.name}function Jwi(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 Ywi(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 Xwi(e){return e.normalize(`NFKC`).trim().replace(/\s+/g,` `).toLowerCase()}function Zwi(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=Xwi(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(Xwi(i))??void 0}}}function Qwi(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&&$wi(n,c,l,t)?[n]:[]});return u.length===1?u[0]:void 0}function $wi(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 eTi=/\[\[([^\]]+)\]\]/g,tTi=/^(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:^\1[ \t]*$|(?![\s\S]))/gm,nTi=/(`+)[\s\S]*?\1/g;function rTi(e){return[...e.replace(tTi,``).replace(nTi,``).matchAll(eTi)].map(e=>e[1]??``)}function iTi(e){let t=Zwi(e),n=[];for(let r of e){if(!r.body||r.deletedAt||r.mergedInto)continue;let e=new Map;for(let n of rTi(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 aTi=(0,G.createContext)(new Map),oTi=12,sTi=320;function cTi({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+oTi,maxHeight:Math.min(sTi,e.y-oTi-8)};let r=t.height>0?t.height-e.y-oTi-8:sTi;return{left:n,top:e.y+oTi,maxHeight:Math.min(sTi,r)}}function lTi(e,t){let n=(0,G.useRef)(e);return t(n.current,e)||(n.current=e),n.current}var uTi=/^(#{1,3})[ \t]+(.+?)[ \t#]*$/gm,dTi=/^(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:^\1[ \t]*$|(?![\s\S]))/gm;function fTi(e){return[...e.replace(dTi,``).matchAll(uTi)].map(([,e,t])=>({depth:e?.length??1,text:(t??``).replace(/\[\[([^\]]+)\]\]/g,`$1`).replace(/[*_`]/g,``)}))}var pTi=/\[\[([^\]]+)\]\]/g;function mTi(e){let t=[],n=0;for(let r of e.matchAll(pTi))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 hTi({page:e,className:t}){let n=qwi(e)?.icon;return n?(0,K.jsx)(n,{"aria-hidden":!0,className:c(`shrink-0 text-foreground`,t)}):null}function C9({label:e,children:t}){return(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{render:t}),(0,K.jsx)(Tx,{children:e})]})}var gTi={"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 _Ti(e){return e.startsWith(`importer:`)?`Importer`:e}function vTi({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 yTi(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 bTi=(0,G.createContext)(null);function xTi({node:e,...t}){let n=(0,G.useContext)(bTi),r=e?.properties[TX];if(typeof r!=`string`||!n)return(0,K.jsx)(`span`,{...t});let i=n.index.resolve(r);return i?(0,K.jsx)(C9,{label:r,children:(0,K.jsx)(`button`,{type:`button`,"data-testid":`knowledge-body-link`,className:`rounded bg-badge-blue-subtle px-1 text-left font-medium wrap-anywhere text-badge-blue-foreground hover:underline`,onClick:()=>n.onPageClick(i),children:i.name})}):(0,K.jsx)(C9,{label:`No loaded page has this address`,children:(0,K.jsx)(`span`,{"data-testid":`knowledge-body-link-unresolved`,className:`rounded border border-dashed border-border px-1 wrap-anywhere text-muted-foreground`,children:r})})}var STi=[J1n];function CTi(e,t){let n=new Map;for(let r of e.body?rTi(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 wTi({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 TTi={span:xTi};function w9({label:e,count:t,children:n}){return(0,K.jsxs)(`section`,{"aria-label":e,className:`flex flex-col gap-2`,children:[(0,K.jsxs)(T,{as:`h3`,variant:`label`,tone:`ink`,className:`flex items-center gap-1.5`,children:[e,t?(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`muted`,className:`tabular-nums`,children:t}):null]}),n]})}function ETi({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 DTi=new WeakMap;function OTi(e,t){let n=DTi.get(e);n||DTi.set(e,n=new WeakMap);let r=n.get(t);return r||n.set(t,r=Zwi(e.values(),t)),r}function kTi({note:e,pagesById:t,onPageClick:n,highlighted:r,itemRef:i,showPage:a,compact:o}){let s=OTi(t,(0,G.useContext)(aTi)),c=n=>Qwi(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)(vTi,{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:_Ti(e.provenance.author)}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:(0,K.jsx)(Dk,{value:e.updatedAt})}),u?(0,K.jsxs)(T,{as:`span`,variant:`caption`,tone:`muted`,children:[`on `,(0,K.jsx)(ETi,{page:u,onPageClick:n})]}):null]}),(0,K.jsx)(`p`,{className:`text-body wrap-anywhere text-foreground`,children:mTi(e.text).map((e,t)=>{if(e.type===`text`)return(0,K.jsx)(`span`,{children:e.value},t);let r=c(e.value);return r?(0,K.jsx)(C9,{label:e.value,children:(0,K.jsx)(`button`,{type:`button`,"data-testid":`knowledge-note-link`,className:`rounded bg-badge-blue-subtle px-1 text-left font-medium wrap-anywhere text-badge-blue-foreground hover:underline`,onClick:()=>n(r),children:r.name})},t):(0,K.jsx)(`span`,{className:`font-medium wrap-anywhere`,children:e.value},t)})}),e.stampScopeIds.length>0?(0,K.jsx)(`div`,{className:`flex min-w-0 flex-wrap gap-1`,"aria-label":`Stamped to`,children:e.stampScopeIds.map(e=>(0,K.jsx)(eC,{variant:`neutral`,size:`xs`,title:l(e),children:(0,K.jsx)(`span`,{className:`truncate`,children:l(e)})},e))}):null]})]})}function ATi({page:e,notes:t,pin:n,pagesById:r,onPageClick:i,highlightMentionOf:a,ancestors:o=[],mentionedBy:s=[],notesMore:c,childPages:l,activity:u,onOpenPage:d,compact:f=!1}){let p=(0,G.useRef)(null);(0,G.useEffect)(()=>{p.current?.scrollIntoView?.({block:`nearest`})},[a,t]);let m=!1,h=e.isScope?e:o.find(t=>t.id===e.scopeId)??r.get(e.scopeId),g=yTi(e,o),_=e.isScope?e.displayLabel??`Scope`:`Page`,v=(0,G.useMemo)(()=>new Map([...r,...[...o,e].map(e=>[e.id,e])]),[r,o,e]),y=(0,G.useContext)(aTi),b=(0,G.useMemo)(()=>Zwi([...r.values(),...o,e],y),[r,o,e,y]),x=(0,G.useMemo)(()=>({index:b,onPageClick:i}),[b,i]),S=(0,G.useRef)(null),C=(0,G.useMemo)(()=>e.body?fTi(e.body):[],[e.body]),w=(0,G.useMemo)(()=>CTi(e,b),[e,b]),E=(0,K.jsx)(bTi.Provider,{value:x,children:(0,K.jsx)(xY,{remarkPlugins:STi,components:TTi,children:e.body??``})}),D=(0,K.jsxs)(T,{variant:`body`,tone:`muted`,children:[`This `,e.isScope?`scope`:`page`,` has no body yet.`]}),O=e=>(0,K.jsx)(`ul`,{className:`flex flex-col gap-2`,children:e.map(e=>{let t=!!a&&e.mentions.includes(a),n=t&&!m;return n&&(m=!0),(0,K.jsx)(kTi,{note:e,pagesById:v,onPageClick:i,highlighted:t,compact:f,itemRef:n?e=>{p.current=e}:void 0},e.id)})}),k=a?t.filter(e=>e.mentions.includes(a)):[],A=t.reduce((e,t)=>!e||t.updatedAt>e.updatedAt?t:e,void 0),j=k.length>0?k:A?[A]:[],M=w.length>0||s.length>0?(0,K.jsx)(w9,{label:`Connections`,count:w.length+s.length,children:(0,K.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[w.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:w.map(({page:e,count:t})=>(0,K.jsxs)(`li`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(oH,{"aria-hidden":!0,className:`size-icon-xs shrink-0 text-muted-foreground`}),(0,K.jsx)(`button`,{type:`button`,className:`min-w-0 truncate text-left text-body-sm text-foreground hover:underline`,onClick:()=>i(e),children:e.name}),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)(kTi,{note:e,pagesById:v,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:f?`flex flex-col gap-3 border-b border-surface-rim px-4 pt-3 pb-4`:`flex flex-col gap-3 border-b border-border bg-fill-subtle px-6 pt-5 pb-4`,children:[(0,K.jsxs)(hDt,{label:`Breadcrumb`,className:`ml-[-.9em] min-w-0`,listClassName:`overflow-hidden`,children:[o.map(e=>(0,K.jsx)(iN,{as:`button`,onClick:()=>i(e),children:S9(e)},e.id)),(0,K.jsx)(iN,{as:`span`,isCurrent:!0,children:S9(e)})]}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[f?null:(0,K.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(hTi,{page:e,className:`size-icon-lg`}),(0,K.jsx)(C9,{label:(e.isScope?e.address:g)??e.name,children:(0,K.jsx)(T,{as:`h2`,variant:`title`,className:`min-w-0 break-words`,"data-testid":`knowledge-page-title`,children:S9(e)})}),(0,K.jsxs)(eC,{variant:`neutral`,size:`sm`,className:`shrink-0 tabular-nums`,children:[`v`,e.version]})]}),e.description?(0,K.jsx)(T,{variant:`body`,tone:`muted`,className:`wrap-anywhere ${f?`line-clamp-3`:`line-clamp-6`}`,children:e.description}):null,(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,K.jsx)(eC,{variant:e.isScope?`info`:`neutral`,size:`sm`,children:_}),n?(0,K.jsx)(eC,{variant:`warning`,size:`sm`,icon:(0,K.jsx)(DX,{"aria-hidden":!0}),children:n.audience.length>0?`Pinned for ${n.audience.join(`, `)}`:`Pinned`}):null,f?(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,"data-testid":`knowledge-page-version`,children:(0,K.jsxs)(AC,{children:[e.isScope?null:(0,K.jsxs)(AC.Item,{children:[`In `,h?S9(h):e.scopeId]}),(0,K.jsxs)(AC.Item,{children:[`v`,e.version]}),(0,K.jsxs)(AC.Item,{children:[`Updated`,` `,(0,K.jsx)(Dk,{value:e.updatedAt,label:`Updated by ${_Ti(e.updatedBy.author)}`})]})]})}):null]})]})]}),f?(0,K.jsxs)(`div`,{className:`flex flex-col gap-6 p-4`,children:[(0,K.jsxs)(`dl`,{"aria-label":`Links and notes`,className:`grid grid-cols-3 divide-x divide-border rounded-lg border border-border`,children:[(0,K.jsx)(wTi,{label:`Links in`,value:s.length}),(0,K.jsx)(wTi,{label:`Links out`,value:w.length}),(0,K.jsx)(wTi,{label:`Notes`,value:c?`${t.length}+`:t.length})]}),(0,K.jsx)(w9,{label:`Preview`,children:e.body?(0,K.jsx)(LS,{maxHeight:`12rem`,children:(0,K.jsx)(`div`,{"data-testid":`knowledge-page-body`,children:E})}):D}),M,j.length>0?(0,K.jsxs)(w9,{label:a?`Notes that mention it`:`Latest note`,children:[O(j),d&&t.length>j.length?(0,K.jsxs)(X,{variant:`ghost`,size:`sm`,className:`self-start`,onClick:d,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:S,"data-testid":`knowledge-page-body`,className:`max-w-3xl`,children:E}):D,t.length>0||c?(0,K.jsxs)(w9,{label:`Notes`,count:c?void 0:t.length,children:[O(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:[C.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:C.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:()=>{(S.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:h?S9(h):e.scopeId})]}),(0,K.jsx)(V4.Key,{children:`Updated`}),(0,K.jsx)(V4.Value,{children:(0,K.jsx)(Dk,{value:e.updatedAt})}),(0,K.jsx)(V4.Key,{children:`By`}),(0,K.jsx)(V4.Value,{children:_Ti(e.updatedBy.author)}),(0,K.jsx)(V4.Key,{children:`Created`}),(0,K.jsx)(V4.Value,{children:(0,K.jsx)(Dk,{value:e.createdAt})}),(0,K.jsx)(V4.Key,{children:`Version`}),(0,K.jsxs)(V4.Value,{children:[`v`,e.version]})]})}),M,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:gTi[e.action]??e.action}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`min-w-0`,children:(0,K.jsxs)(AC,{singleLine:!0,children:[(0,K.jsx)(AC.Item,{className:`min-w-0`,children:(0,K.jsx)(C9,{label:e.provenance.author,children:(0,K.jsx)(`span`,{className:`truncate`,children:_Ti(e.provenance.author)})})}),(0,K.jsx)(AC.Item,{className:`shrink-0`,children:(0,K.jsx)(Dk,{value:e.createdAt})})]})})]},e.id))})}):null]})]})]},e.id)}function jTi(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 MTi(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 NTi=.15,PTi={left:0,right:0};function FTi(e,t){return e-t.left-t.right>0?t:PTi}function ITi({bounds:e,width:t,height:n,ring:r,anchor:i,insets:a=PTi}){let o=FTi(t,a),s=r?NTi:zwi,c=t-o.left-o.right,l=VD(e,c,n,s,2,.1);if(i&&l.zoom<=s){let e=i.position.x+(i.width??0)/2,t=i.position.y+(i.height??0)/2;return{zoom:l.zoom,x:o.left+c/2-e*l.zoom,y:n/2-t*l.zoom}}return{...l,x:l.x+o.left}}var LTi=.05,RTi=3e3;function zTi({bounds:e,nodes:t,width:n,height:r,legend:i,insets:a=PTi}){let o=FTi(n,a),s=(t,i)=>{let a=VD(e,n-t-o.right,r-i,NTi,1,LTi);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 BTi(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 VTi(e){let t=+this._x.call(null,e),n=+this._y.call(null,e);return HTi(this.cover(t,n),t,n,e)}function HTi(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 UTi(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)HTi(this,n[i],r[i],e[i]);return this}function WTi(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 GTi(){var e=[];return this.visit(function(t){if(!t.length)do e.push(t.data);while(t=t.next)}),e}function KTi(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 qTi(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 JTi(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 YTi(e){for(var t=0,n=e.length;t<n;++t)this.remove(e[t]);return this}function XTi(){return this._root}function ZTi(){var e=0;return this.visit(function(t){if(!t.length)do++e;while(t=t.next)}),e}function QTi(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 $Ti(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 eEi(e){return e[0]}function tEi(e){return arguments.length?(this._x=e,this):this._x}function nEi(e){return e[1]}function rEi(e){return arguments.length?(this._y=e,this):this._y}function iEi(e,t,n){var r=new aEi(t??eEi,n??nEi,NaN,NaN,NaN,NaN);return e==null?r:r.addAll(e)}function aEi(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 oEi(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}var O9=iEi.prototype=aEi.prototype;O9.copy=function(){var e=new aEi(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=oEi(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]=oEi(r));return e},O9.add=VTi,O9.addAll=UTi,O9.cover=WTi,O9.data=GTi,O9.extent=KTi,O9.find=qTi,O9.remove=JTi,O9.removeAll=YTi,O9.root=XTi,O9.size=ZTi,O9.visit=QTi,O9.visitAfter=$Ti,O9.x=tEi,O9.y=rEi;function sEi(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 cEi(e){return e.x+e.vx}function lEi(e){return e.y+e.vy}function uEi(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=iEi(t,cEi,lEi).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 dEi(e){return e.index}function fEi(e,t){var n=e.get(t);if(!n)throw Error(`node not found: `+t);return n}function pEi(e){var t=dEi,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=fEi(u,d.source)),typeof d.target!=`object`&&(d.target=fEi(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 mEi=1664525,hEi=1013904223,gEi=4294967296;function _Ei(){let e=1;return()=>(e=(mEi*e+hEi)%gEi)/gEi}function vEi(e){return e.x}function yEi(e){return e.y}var bEi=10,xEi=Math.PI*(3-Math.sqrt(5));function SEi(e){var t,n=1,r=.001,i=1-r**(1/300),a=0,o=.6,s=new Map,c=qtt(d),l=lE(`tick`,`end`),u=_Ei();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=bEi*Math.sqrt(.5+t),a=t*xEi;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 CEi(){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=iEi(e,vEi,yEi).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 wEi(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 TEi(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 EEi=28,DEi=300;function OEi(e,t,n={}){let r=n.ticks??DEi,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??EEi,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}));SEi(i).force(`link`,pEi(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`,CEi().strength(e=>e.size<=24?-60:-700)).force(`collide`,uEi().radius(e=>e.size/2+e.padding).strength(1).iterations(3)).force(`center`,sEi(0,0)).force(`x`,wEi(0).strength(.06)).force(`y`,TEi(0).strength(.08)).stop().tick(r),kEi(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 kEi(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 AEi(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 jEi(e){return`unplaced:${e}`}function MEi(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=jEi(e.principal),r.has(t)||r.set(t,NEi(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 NEi(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 PEi(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 FEi(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 IEi=[`top`,`bottom`,`right`,`left`];function LEi(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 REi(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 zEi(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 BEi(e){let t=e=>(e.right-e.left)*(e.bottom-e.top),n=`top`,r=1/0;for(let i of IEi){let a=LEi(i,e),o=(t(a)-REi(a,e.bounds))*100;for(let t of e.obstacles)o+=REi(a,t)*4;for(let t of e.lines)zEi(a,t.from,t.to)&&(o+=2e3);o<r&&(n=i,r=o)}return n}var VEi=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`})]})),HEi={left:0,right:0},UEi={"--knowledge-color":`var(--chart-blue)`,background:`color-mix(in oklab, var(--chart-blue) 16%, var(--card))`},WEi={"--knowledge-color":`var(--border-strong)`},GEi=`var(--muted-foreground)`,KEi={"--knowledge-color":GEi,background:GEi},qEi={stroke:`var(--foreground)`,strokeOpacity:.45,strokeDasharray:`4 4`,strokeWidth:1.25},JEi=`var(--chart-cyan)`,YEi={stroke:JEi,strokeWidth:2.25},XEi={type:TD.ArrowClosed,color:JEi,width:14,height:14},ZEi=`var(--chart-blue)`,QEi=`var(--muted-foreground)`,$Ei={type:TD.Arrow,color:QEi,width:12,height:12,strokeWidth:1.5},eDi=`var(--chart-purple)`,tDi={stroke:eDi,strokeWidth:1.75,strokeDasharray:`8 3 2 3`},nDi={type:TD.ArrowClosed,color:eDi,width:13,height:13},j9=`var(--chart-green)`,rDi={stroke:j9,strokeWidth:1.25},iDi={type:TD.ArrowClosed,color:j9,width:12,height:12},aDi={out:{stroke:j9},in:{stroke:`var(--chart-orange)`,strokeDasharray:`6 3`}},oDi={out:iDi,in:{type:TD.ArrowClosed,color:`var(--chart-orange)`,width:12,height:12}},sDi={stroke:`var(--foreground)`,strokeOpacity:.2,strokeWidth:1},cDi={background:`var(--card)`,borderColor:`var(--chart-purple)`,borderStyle:`dashed`};function lDi(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 uDi=150,dDi=4e3,fDi=3;function pDi(e){let{left:t,top:n,right:r,bottom:i}=e.getBoundingClientRect();return{left:t,top:n,right:r,bottom:i}}function mDi(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 hDi={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 gDi({level:e}){return(0,K.jsx)(e===`scope`?nC:VEi,{"aria-hidden":!0,"data-testid":`knowledge-level-icon-${e}`,className:`mr-1 inline-block size-3 align-text-bottom`})}function _Di({data:e}){let{page:t,size:n,color:r,path:i,ref:a,links:o,notShown:s}=e,[c,l]=(0,G.useState)(!1),u=(0,G.useRef)(null),d=(0,G.useRef)(null),[f,p]=(0,G.useState)(`top`),m=rO(e=>e.transform[2]),h=Math.min(Math.max(1/m,1),fDi),g=v9(t),_=b9(t),v=g?`Hover or click to load them`:_?`Click to show them`:null,y=!v&&t.childCount?`${_9(t)} ${t.childCount===1?`child`:`children`}`:null,b=t.isScope?t.displayLabel??`Scope`:`Page`,x=o&&(o.in>0||o.out>0)?_X(o,s):null,S=[t.name,v??i,y,x].filter(Boolean).join(`, `);(0,G.useLayoutEffect)(()=>{let e=u.current,t=d.current,n=e?.closest(`.knowledge-graph`);if(!c||!e||!t||!n)return;let r=pDi(e),i=pDi(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(pDi).filter(e=>e.right>e.left&&(e.left!==i.left||e.top!==i.top)&&(e.left!==r.left||e.top!==r.top));p(BEi({dot:r,tip:{width:a,height:o},gap:8,bounds:pDi(n),obstacles:s,lines:mDi(n)}))},[c,h]);let C=hDi[f];return(0,K.jsxs)(`div`,{ref:u,"data-testid":`knowledge-page-dot`,"data-page-id":t.id,"data-page-type":g?`stand-in`:_?`group`:t.isScope?`scope`:`page`,"aria-label":S,className:`relative cursor-pointer transition-opacity`,style:{width:n,height:n,opacity:g?.5:void 0},onPointerEnter:()=>l(!0),onPointerLeave:()=>l(!1),children:[(0,K.jsx)(`span`,{"aria-hidden":!0,"data-testid":`knowledge-dot-hit-area`,className:`absolute rounded-full`,style:{inset:-8}}),(0,K.jsx)(`div`,{className:`size-full rounded-full border`,style:{background:g?`transparent`:r??`var(--muted-foreground)`,borderColor:r??`var(--muted-foreground)`,borderStyle:g?`dashed`:`solid`},children:e.showCount&&!g&&!_&&o&&o.in+o.out>0?(0,K.jsx)(T,{as:`span`,variant:`meta`,"data-testid":`knowledge-dot-count`,className:`flex size-full items-center justify-center`,style:{color:`var(--background)`},children:o.in+o.out}):null}),c?(0,K.jsxs)(`div`,{role:`tooltip`,ref:d,"data-side":f,className:`pointer-events-none absolute ${C.tip} flex w-max max-w-72 flex-col rounded-md border border-border bg-card px-2 py-1 shadow-overlay`,style:{transform:`${C.transform} scale(${h})`,transformOrigin:C.origin},children:[(0,K.jsx)(`span`,{"data-testid":`knowledge-tooltip-tail`,"aria-hidden":!0,className:`absolute size-2 rotate-45 border-border bg-card ${C.tail}`}),v?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`ink`,children:t.name}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:(0,K.jsxs)(AC,{children:[_&&(0,K.jsx)(AC.Item,{children:i}),(0,K.jsx)(AC.Item,{children:v})]})})]}):(0,K.jsx)(v1n,{name:t.name,kind:b,pageRef:a,path:i,childCount:t.childCount?_9(t):void 0,links:o,notShown:s})]}):null,(0,K.jsx)(fO,{type:`target`,position:ED.Top,className:`!invisible`}),(0,K.jsx)(fO,{type:`source`,position:ED.Bottom,className:`!invisible`})]})}var vDi=96,yDi=.74;function bDi({data:e}){if(e.form===`dot`)return(0,K.jsx)(_Di,{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=SDi(t),l=y9(t),u=n<vDi,d=Math.max(4,Math.floor(n*yDi/(u?6.5:7.5))),f=xDi(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?cDi:e.far?KEi:t.isScope?UEi:WEi,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)(gDi,{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)(CDi,{text:jTi(S9(t),d)})})]})}),i?(0,K.jsx)(wDi,{size:n}):null,e.hiddenLinks&&(e.hiddenLinks.in>0||e.hiddenLinks.out>0)?(0,K.jsx)(C9,{label:_X(e.hiddenLinks),children:(0,K.jsxs)(`span`,{"data-testid":`knowledge-hidden-links`,"aria-label":_X(e.hiddenLinks),className:`absolute bottom-full left-1/2 -mb-1 flex -translate-x-1/2 gap-1 rounded-full border border-border bg-card px-1.5 shadow-raised`,children:[e.hiddenLinks.in>0?(0,K.jsxs)(T,{as:`span`,variant:`meta`,style:{color:`var(--chart-orange)`},children:[`→`,e.hiddenLinks.in]}):null,e.hiddenLinks.out>0?(0,K.jsxs)(T,{as:`span`,variant:`meta`,style:{color:j9},children:[e.hiddenLinks.out,`→`]}):null]})}):null,a?(0,K.jsx)(C9,{label:`${a} children, not all drawn`,children:(0,K.jsx)(`span`,{"data-testid":`knowledge-child-count-badge`,"aria-label":`${a} children, not all drawn`,className:`absolute top-full left-1/2 -mt-1 -translate-x-1/2 rounded-full border border-border bg-card px-1.5 shadow-raised`,children:(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`ink`,children:a})})}):null,(0,K.jsx)(fO,{type:`target`,position:ED.Top,className:`!invisible`}),(0,K.jsx)(fO,{type:`source`,position:ED.Bottom,className:`!invisible`})]})}function xDi(e,t){let{page:n,links:r,notShown:i}=e;if(SDi(n))return`${t}: ${n.address}. Nothing written to it yet.`;if(y9(n))return`Show ${Math.min(12,n.childCount??12)} more of ${n.childCount??`the rest`}`;if(b9(n))return`${n.name}: click to show them`;if(n.isScope&&n.address){let e=S9(n);return e===n.address?`${t}: ${e}`:`${t}: ${e} (${n.address})`}return r&&r.in+r.out>0?`${n.name}: ${_X(r,i)}`:n.name}function SDi(e){return e.id.startsWith(`unplaced:`)}function CDi({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 wDi({size:e}){let{badge:t,style:n}=lDi(e);return(0,K.jsx)(`span`,{"data-testid":`knowledge-pin-badge`,className:`absolute flex items-center justify-center rounded-full bg-badge-amber-strong text-badge-amber-foreground shadow-raised`,style:n,"aria-label":`Pinned`,children:(0,K.jsx)(DX,{size:Math.round(t*.6),"aria-hidden":!0})})}function TDi(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 EDi({id:e,data:t,style:n,markerEnd:r}){if(!t)return null;let{x1:i,y1:a,x2:o,y2:s}=TDi(t.from,t.to),c=t.kind===`mention`,l=`M ${i} ${a} L ${o} ${s}`;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(mO,{id:e,path:l,style:n,markerEnd:r,interactionWidth:c?20:0}),t.kind===`grant`&&t.role?(0,K.jsx)(`path`,{d:l,fill:`none`,stroke:`transparent`,strokeWidth:14,"data-testid":`knowledge-grant-edge`,"data-role":t.role,"aria-label":`Grants ${t.role}`,children:(0,K.jsx)(`title`,{children:`Grants ${t.role}`})}):null]})}var DDi={rim:(0,G.memo)(EDi)},ODi={page:(0,G.memo)(bDi)};function kDi(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 ADi=`knowledge-circle inline-block size-3 shrink-0 rounded-full border-2`;function jDi({drawn:e,counts:t,dots:n,linkEnds:r,focused:i,levels:a,branches:o,collapsible:s}){let[c,l]=(0,G.useState)(!s),[u,d]=(0,G.useState)(!1),f=c||u;return(0,K.jsxs)(`div`,{className:`absolute top-3 left-3 z-10 flex translate-x-(--knowledge-pane-left) flex-col items-start gap-1.5 transition-transform duration-slow ease-out-custom motion-reduce:transition-none`,onPointerEnter:s?()=>d(!0):void 0,onPointerLeave:s?()=>d(!1):void 0,children:[s?(0,K.jsx)(X,{size:`sm`,icon:(0,K.jsx)(Yx,{}),"aria-expanded":f,className:`shadow-overlay`,onFocus:()=>d(!0),onBlur:()=>d(!1),onClick:()=>{l(e=>!e),d(!1)},children:`Legend`}):null,(0,K.jsxs)(`ul`,{"aria-label":`Legend`,hidden:s&&!f,className:`pointer-events-none flex flex-col gap-1 rounded-lg px-2.5 py-2 ${s?`bg-card shadow-overlay`:`rounded-md border border-border bg-card/90 shadow-raised`}`,children:[(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`span`,{className:ADi,style:{...UEi},"aria-hidden":!0}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Scope`})]}),a.includes(`scope`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-level-scope`,children:[(0,K.jsx)(nC,{"aria-hidden":!0,className:`size-icon-xs shrink-0 text-muted-foreground`}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Scope, above its pages`})]}):null,a.includes(`ancestor`)?(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,"data-testid":`knowledge-legend-level-ancestor`,children:[(0,K.jsx)(VEi,{"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:ADi,style:{...WEi},"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:ADi,style:{...WEi,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,LDi).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>LDi?(0,K.jsx)(`li`,{className:`pl-0.5`,children:(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,children:[`+`,o.length-LDi,` 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:ZEi,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`,...rDi}),(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`,...sDi,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`,...YEi}),(0,K.jsx)(`polygon`,{points:`9,1 15,4 9,7`,fill:JEi})]}),(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`,...qEi,strokeDasharray:`3 2`}),(0,K.jsx)(`polyline`,{points:`10,1 14,4 10,7`,fill:`none`,stroke:QEi,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`,...tDi,strokeDasharray:`4 2 1 2`,strokeWidth:`1.5`}),(0,K.jsx)(`polygon`,{points:`11,1 16,4 11,7`,fill:eDi})]}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Grants access (hover for role)`})]}):null,(0,K.jsxs)(`li`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`span`,{className:`flex size-3 shrink-0 items-center justify-center rounded-full bg-badge-amber-strong text-badge-amber-foreground [&>svg]:size-2`,"aria-hidden":!0,children:(0,K.jsx)(DX,{})}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,children:`Pinned`})]})]})]})}var MDi=4,NDi=`knowledge-neighbour`;function PDi(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 FDi=1.2,IDi=.8,LDi=4,RDi=40;function zDi(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),uDi),n=setTimeout(()=>i(!0),dDi);return()=>{clearTimeout(e),clearTimeout(n)}},[t,e.selectedPageId]),(0,K.jsxs)(hO,{children:[(0,K.jsx)(BDi,{...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 BDi({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=HEi,collapsibleLegend:y}){let{graphPages:b,allEdges:x}=(0,G.useMemo)(()=>{let n=MEi(e,r);return{graphPages:n.placeholders.length?[...e,...n.placeholders]:e,allEdges:[...AEi(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=Owi(b,i??a??null,c),t=Rwi(b,e),n=FEi(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*FDi):t.data.size=Math.round(108*(e.linked.has(t.id)?IDi:1));let r=n.nodes.filter(t=>e.depth.get(t.id)===1&&e.form.get(t.id)===`full`),o=Vwi(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=Iwi(b,e,e=>s.get(e.id)??20,c),u=OEi(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>=RDi))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)?PEi(L,[...x,...F.map(e=>({kind:e.data?.kind??`link`,source:e.source,target:e.target}))]):null,[L,E,x,F]),z=(0,G.useMemo)(()=>E.nodes.map(e=>{let t=E.positions.get(e.id)??{x:0,y:0};return{...e,width:e.data.size,height:e.data.size,handles:[{type:`target`,position:ED.Top,x:e.data.size/2,y:0,width:1,height:1},{type:`source`,position:ED.Bottom,x:e.data.size/2,y:e.data.size,width:1,height:1}],position:{x:t.x-e.data.size/2,y:t.y-e.data.size/2},data:{...e.data,selected:e.id===i,pinned:j.has(e.id),form:E.shape.form.get(e.id)??`full`,color:E.colors.get(E.shape.branch.get(e.id)??``),badge:M.has(e.id)?_9(e.data.page):void 0,path:Jwi(e.data.page,D),hiddenLinks:E.shape.form.get(e.id)===`full`?o?.get(e.id):void 0,ref:Ywi(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?{...aDi[s],strokeWidth:r?2:1.5}:r?{stroke:ZEi,strokeWidth:Math.min(1.5+(t.data?.count??1)*.5,4)}:c?YEi:i?tDi:a?rDi:o?sDi:qEi,markerEnd:s?oDi[s]:c?XEi:r?{type:TD.ArrowClosed,color:ZEi,width:14,height:14}:i?nDi:a?iDi:o?void 0:$Ei}}),drawnEdgeStyles:e}},[E,F,_,L,O]),H=PDi(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:NDi}:{},...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,NDi].filter(Boolean).join(` `)}:e):H,[H,R]),U=(0,G.useMemo)(()=>new Map(e.map(e=>[e.id,e])),[e]),W=uO(),ne=(0,G.useRef)(null),re=z.length>0,ie=MTi(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=kDi(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=ITi({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=zTi({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=FTi(n,c),d=s.getViewport(),f=BTi(l.position.x*d.zoom+d.x-u.left,(l.width??0)*d.zoom,n-u.left-u.right),p=BTi(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)=>{SDi(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)>MDi||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)(jDi,{collapsible:y,branches:A,levels:k,focused:!!i&&E.positions.has(i),dots:[...E.shape.form.values()].includes(`dot`),linkEnds:E.shape.linked.size>0,drawn:V,counts:[...o??[]].some(([e,t])=>E.shape.form.get(e)===`full`&&(t.in>0||t.out>0))}),(0,K.jsx)(Bct,{nodes:ie,edges:te,nodeTypes:ODi,edgeTypes:DDi,onInit:()=>{he.current=!0,ge.current=Date.now()+RTi,_e.current=se.current.selectedPageId??null,ve.current=se.current.nodes.map(e=>`${e.id}@${e.position.x},${e.position.y}`).join(`|`),de()},minZoom:.1,proOptions:{hideAttribution:!0},nodesConnectable:!1,nodesDraggable:!1,onPaneClick:Oe,onNodeMouseEnter:we,onNodeMouseLeave:Te,onNodeClick:Ee,onEdgeClick:De,children:(0,K.jsx)($ct,{variant:gO.Dots,gap:26,size:1.4,color:`var(--border-strong)`})}),(0,K.jsx)(`div`,{className:`absolute bottom-3 left-3 z-10 translate-x-(--knowledge-tree-drawer-inset,0px) transition-transform duration-slow ease-out-custom motion-reduce:transition-none`,children:(0,K.jsxs)($V,{size:`sm`,"aria-label":`Zoom`,"data-knowledge-graph-zoom":!0,className:`rounded-full shadow-overlay`,children:[(0,K.jsx)(X,{size:`icon-sm`,tooltip:`Zoom out`,"aria-label":`Zoom out`,onClick:()=>void W.zoomOut({duration:E9(T9())}),children:(0,K.jsx)(A6e,{})}),(0,K.jsx)(X,{size:`icon-sm`,tooltip:`Zoom in`,"aria-label":`Zoom in`,onClick:()=>void W.zoomIn({duration:E9(T9())}),children:(0,K.jsx)(Hx,{})}),(0,K.jsx)(X,{size:`icon-sm`,tooltip:`Fit view`,"aria-label":`Fit view`,onClick:()=>ue(E9(T9())),children:(0,K.jsx)(k6e,{})})]})})]}):(0,K.jsx)(`div`,{className:`flex h-full items-center justify-center p-6`,children:(0,K.jsx)(T,{variant:`body`,tone:`muted`,children:`No pages yet.`})})}function VDi(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 HDi=1/3,UDi=.1,WDi=.7;function GDi({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)(()=>bwi(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=Swi(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)(()=>xwi(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=VDi(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*UDi&&i.bottom<=r.top+r.height*WDi)return;e.style.scrollMarginTop=`${r.height*HDi}px`}e.scrollIntoView?.({block:`start`,behavior:t&&T9()?`smooth`:`auto`}),e.style.scrollMarginTop=``}},[v,n]);let C=m&&v.some(e=>e.page.id===m)?m:v.find(e=>e.page.id===n)?.page.id??v[0]?.page.id,w=(e,t)=>p(n=>{if(n.has(e)===t)return n;let r=new Set(n);return t?r.add(e):r.delete(e),r}),T=e=>{e&&(h(e),g.current.get(e)?.focus())},E=(e,t)=>{let n=v[t];if(n){switch(e.key){case`ArrowDown`:T(v[t+1]?.page.id);break;case`ArrowUp`:T(v[t-1]?.page.id);break;case`ArrowRight`:n.hasChildren&&!n.expanded?w(n.page.id,!0):n.expanded&&T(v[t+1]?.page.id);break;case`ArrowLeft`:n.expanded?w(n.page.id,!1):T(v.slice(0,t).findLast(e=>e.depth<n.depth)?.page.id);break;case`Enter`:case` `:r(n.page);break;default:return}e.preventDefault()}};if(v.length===0)return(0,K.jsx)(`p`,{className:`px-3 py-2 text-body text-muted-foreground`,children:`No pages yet.`});let D=[];return(0,K.jsx)(`div`,{ref:b,role:`tree`,"aria-label":l,className:`min-h-0 overflow-y-auto py-1`,onWheel:()=>S.current=!0,onTouchMove:()=>S.current=!0,onPointerDown:()=>S.current=!0,onKeyDown:()=>S.current=!0,children:v.map((e,t)=>{let i=e.page.id===n;D[e.depth]=e.page.id;let a=v[t+1]?.depth??-1,o=[];for(let t=e.depth-1;t>=a;t--){let e=t<0?``:D[t];e!==void 0&&o.push({parentId:e,depth:t+1})}return e.expanded&&v[t+1]?.depth!==e.depth+1&&o.unshift({parentId:e.page.id,depth:e.depth+1}),(0,K.jsxs)(G.Fragment,{children:[(0,K.jsxs)(`div`,{ref:t=>{t?g.current.set(e.page.id,t):g.current.delete(e.page.id)},role:`treeitem`,"aria-level":e.depth+1,"aria-selected":i,"aria-expanded":e.hasChildren?e.expanded:void 0,tabIndex:e.page.id===C?0:-1,onFocus:()=>h(e.page.id),onKeyDown:e=>E(e,t),onClick:()=>{r(e.page),e.hasChildren&&w(e.page.id,!0)},className:c(`flex h-8 cursor-pointer items-center gap-2 rounded-md pr-2 text-body-sm text-foreground outline-none focus-visible:bg-fill-subtle`,i?`bg-fill-hover`:`hover:bg-fill-subtle`),style:{paddingLeft:`${e.depth*12+4}px`},children:[e.hasChildren?(0,K.jsx)(`button`,{type:`button`,tabIndex:-1,"aria-label":e.expanded?`Collapse ${e.page.name}`:`Expand ${e.page.name}`,className:`flex size-3 shrink-0 items-center justify-center text-muted-foreground hover:text-foreground`,onClick:t=>{t.stopPropagation(),w(e.page.id,!e.expanded)},children:(0,K.jsx)(y,{direction:`right`,open:e.expanded,className:`size-3`})}):(0,K.jsx)(`span`,{className:`size-3 shrink-0`,"aria-hidden":!0}),(0,K.jsx)(`span`,{className:`flex shrink-0 items-center text-muted-foreground [&>svg]:size-icon-sm`,"aria-hidden":!0,children:e.page.isScope&&S9(e.page)!==e.page.name?(0,K.jsx)(hTi,{page:e.page}):e.hasChildren?(0,K.jsx)($N,{}):(0,K.jsx)(xk,{})}),(0,K.jsx)(`span`,{className:c(`min-w-0 flex-1 truncate`,e.page.isScope&&`font-medium`),children:S9(e.page)}),e.page.childCount?(0,K.jsx)(`span`,{"data-testid":`knowledge-tree-count`,"aria-label":`${_9(e.page)} below`,className:`shrink-0 text-caption text-placeholder tabular-nums`,children:_9(e.page)}):null,d.has(e.page.id)?(0,K.jsx)(DX,{className:`size-icon-xs shrink-0 text-badge-amber-indicator`,"aria-label":`Pinned`}):null,e.page.isScope&&e.page.address&&e.page.address!==e.page.name?(0,K.jsx)(`span`,{"data-testid":`knowledge-tree-address`,className:`max-w-1/2 min-w-0 truncate text-caption text-muted-foreground`,children:e.page.address}):null]}),o.map(({parentId:e,depth:t})=>{let n=s?.get(e);return n?(0,K.jsx)(`button`,{type:`button`,className:`flex h-8 w-full items-center text-left text-caption text-muted-foreground hover:text-foreground`,style:{paddingLeft:`${t*12+42}px`},onClick:n,children:`Load more`},`more-${e}`):null})]},e.page.id)})})}var KDi=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`})]})),qDi=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`})]})),JDi=/^[0-9A-Z]{26}$/,YDi=6e4,XDi=e=>Date.now()-Date.parse(e.createdAt)<YDi,ZDi=2,QDi=40;function $Di(e){return`${e.kind}\u0000${e.source}\u0000${e.target}`}function eOi(e,t,n,r){let i=new Map;for(let t of e)t.source!==t.target&&!i.has($Di(t))&&i.set($Di(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($Di(e))),hidden:l,more:s}}function tOi(e,t){return t?`page`:e===`tree`?`tree`:`graph`}var nOi=296,rOi=44;function iOi(e,t){return e?t?nOi:rOi:0}var aOi=392,oOi=()=>[],sOi=[],cOi=()=>[],lOi=()=>({isPending:!1,isError:!1,error:null}),uOi=150;function dOi(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 fOi=()=>({isPending:!1,isError:!1,error:null});function pOi(e){return!!e&&typeof e==`object`&&`status`in e&&e.status===404}function mOi(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 hOi(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 gOi=[`w-32`,`w-24`,`w-40`,`w-28`,`w-36`,`w-20`];function _Oi({label:e,rows:t}){return(0,K.jsx)(`div`,{role:`status`,"aria-label":e,className:`flex flex-col`,children:gOi.slice(0,t).map((e,t)=>(0,K.jsxs)(`div`,{className:`flex h-8 items-center gap-2 px-1`,style:{paddingLeft:`${t%3*12+4}px`},children:[(0,K.jsx)(zS,{className:`size-3.5 shrink-0`}),(0,K.jsx)(BS,{className:e})]},e))})}function vOi(){return(0,K.jsx)(`div`,{role:`status`,"aria-label":`Loading notes`,className:`flex flex-col gap-2`,children:[0,1].map(e=>(0,K.jsxs)(`div`,{className:`flex flex-col gap-2 rounded-lg border border-border p-3`,children:[(0,K.jsx)(BS,{className:`w-24`}),(0,K.jsx)(BS,{className:`w-full`}),(0,K.jsx)(BS,{className:`w-2/3`})]},e))})}function yOi({compact:e}){return(0,K.jsxs)(`div`,{role:`status`,"aria-label":`Loading page`,className:`flex flex-col`,children:[(0,K.jsxs)(`div`,{className:`flex flex-col gap-2 border-b border-border ${e?`px-4 pt-3 pb-4`:`bg-fill-subtle px-6 pt-5 pb-4`}`,children:[(0,K.jsx)(BS,{line:`text-caption`,className:`w-28`}),e?null:(0,K.jsx)(BS,{line:`text-title`,className:`h-5 w-56`}),(0,K.jsx)(BS,{className:`w-72 max-w-full`}),(0,K.jsx)(BS,{line:`text-caption`,className:`w-40`})]}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-3 ${e?`p-4`:`p-6`}`,children:[(0,K.jsx)(BS,{className:`w-full max-w-3xl`}),(0,K.jsx)(BS,{className:`w-5/6 max-w-2xl`}),(0,K.jsx)(BS,{className:`w-2/3 max-w-xl`})]})]})}function bOi({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 xOi({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)(()=>mOi(r,a.data?.related??[]),[a.data,r]);if(a.isPending)return(0,K.jsx)(vOi,{});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)(kTi,{note:e,pagesById:c,onPageClick:i},e.id))}),l?o?(0,K.jsx)(xOi,{source:e,pageId:t,cursor:l,pagesById:r,onPageClick:i}):(0,K.jsx)(bOi,{label:`Load more notes`,onClick:()=>s(!0)}):null]})}function SOi({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)(_Oi,{label:`Loading pages`,rows:3})});let c=s?.data?.nextCursor;return o.length===0&&!c?null:(0,K.jsxs)(w9,{label:`Pages`,children:[(0,K.jsx)(`div`,{className:`rounded-xl p-1 ${Bv}`,children:(0,K.jsx)(N6,{className:`rounded-lg bg-background p-1`,onSelect:n,children:(0,K.jsx)(COi,{pages:o,useTreeLevels:e,onOpen:n})})}),c?(0,K.jsx)(bOi,{onClick:()=>i(e=>[...e,c])}):null]})}function COi({pages:e,useTreeLevels:t,onOpen:n}){return e.map(e=>e.childCount===0?(0,K.jsxs)(N6.File,{id:e.id,children:[(0,K.jsx)(N6.Icon,{className:`text-muted-foreground`,children:(0,K.jsx)(xk,{})}),(0,K.jsx)(wOi,{page:e})]},e.id):(0,K.jsx)(TOi,{page:e,useTreeLevels:t,onOpen:n},e.id))}function wOi({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 TOi({page:e,useTreeLevels:t,onOpen:n}){let[r,i]=(0,G.useState)(!1);return(0,K.jsxs)(N6.Folder,{id:e.id,open:r,onOpenChange:i,children:[(0,K.jsxs)(N6.FolderTrigger,{actions:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`Open ${e.name}`,"aria-label":`Open ${e.name}`,onClick:()=>n(e.id),children:(0,K.jsx)(oH,{})}),children:[(0,K.jsx)(N6.Icon,{className:`text-muted-foreground`,children:(0,K.jsx)($N,{})}),(0,K.jsx)(wOi,{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)(EOi,{parentId:e.id,useTreeLevels:t,onOpen:n}):null})]})}function EOi({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)(_Oi,{label:`Loading pages`,rows:2})}):a[0]?.isError?(0,K.jsx)(DOi,{children:`Couldn’t load the pages under this one.`}):o.length===0&&!s?(0,K.jsx)(DOi,{children:`No pages under this one.`}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(COi,{pages:o,useTreeLevels:t,onOpen:n}),s?(0,K.jsx)(`li`,{role:`none`,className:`pl-9`,children:(0,K.jsx)(bOi,{onClick:()=>i(e=>[...e,s])})}):null]})}function DOi({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 OOi({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:cTi(t),children:[(0,K.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,K.jsxs)(T,{as:`h3`,variant:`card-title`,className:`min-w-0 flex-1`,children:[(0,K.jsx)(`button`,{type:`button`,className:`hover:underline`,onClick:()=>r(t.source.id),children:t.source.name}),(0,K.jsxs)(T,{as:`span`,variant:`card-title`,tone:`muted`,children:[` `,`mentions`,` `]}),(0,K.jsx)(`button`,{type:`button`,className:`hover:underline`,onClick:()=>r(t.target.id),children:t.target.name})]}),(0,K.jsx)(`button`,{type:`button`,"aria-label":`Close`,className:`rounded p-0.5 text-muted-foreground hover:bg-fill hover:text-foreground`,onClick:i,children:(0,K.jsx)(xw,{className:`size-icon-sm`,"aria-hidden":!0})})]}),(0,K.jsx)(`div`,{className:`min-h-0 overflow-y-auto`,children:a.isPending?(0,K.jsx)(vOi,{}):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)(kTi,{note:e,pagesById:mOi(n,a.data?[...a.data.related,...a.data.ancestors,a.data.page]:[]),onPageClick:e=>r(e.id),compact:!0},e.id))})})]})}function kOi({source:e,pageId:t,pagesById:n,onSelect:r,highlightMentionOf:i,compact:a,onOpenPage:o}){let s=e.usePage(t),c=(e.useActivity??fOi)(t),[l,u]=(0,G.useState)(null),d=(0,G.useMemo)(()=>s.data?mOi(n,[...s.data.ancestors,...s.data.related]):n,[s.data,n]);if(s.isPending)return(0,K.jsx)(yOi,{compact:a});if(s.isError||!s.data){let e=pOi(s.error);return(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:e?`Page not found`:`Failed to load the page`,descriptionSlot:e?`It may have been deleted or merged.`:s.error?.message??``})}let f=e=>r(e.id),p=s.data.notesNextCursor;return(0,K.jsx)(ATi,{compact:a,onOpenPage:o,page:s.data.page,notes:s.data.notes,pin:s.data.pin??void 0,pagesById:d,onPageClick:f,highlightMentionOf:i,ancestors:s.data.ancestors,mentionedBy:s.data.mentionedBy,activity:c.data?.events,childPages:e.useTreeLevels?(0,K.jsx)(SOi,{useTreeLevels:e.useTreeLevels,parentId:t,onOpen:r},t):void 0,notesMore:p?l?.pageId===t?(0,K.jsx)(xOi,{source:e,pageId:t,cursor:p,pagesById:d,onPageClick:f}):(0,K.jsx)(bOi,{label:`Load more notes`,onClick:()=>u({pageId:t})}):void 0})}var AOi=30;function jOi(e,t){let n=t.trim()?e.toLowerCase().indexOf(t.trim().toLowerCase()):-1;if(n<=AOi)return e;let r=e.lastIndexOf(` `,n-AOi)+1;return`…${e.slice(r)}`}function MOi({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 NOi({source:e,onSelect:t}){let[n,r]=(0,G.useState)(``),i=e.useSearch(n),a=n.trim().length>=ZDi?i.data?.results??[]:[],o=new Set,s=a.map(e=>e.page).filter(e=>!o.has(e.id)&&(o.add(e.id),!0)).slice(0,10);return(0,K.jsxs)(`div`,{className:`relative w-64 min-w-0`,children:[(0,K.jsx)(MH,{label:`Search knowledge`,placeholder:`Search pages and notes`,size:`sm`,value:n,onValueChange:r}),s.length>0?(0,K.jsx)(`div`,{className:`absolute z-20 mt-1 w-full overflow-hidden rounded-xl ${Vv}`,children:(0,K.jsx)(LS,{maxHeight:`18rem`,children:(0,K.jsx)(`ul`,{role:`listbox`,"aria-label":`Search results`,className:`p-1`,children:s.map(e=>(0,K.jsx)(`li`,{role:`option`,"aria-selected":!1,children:(0,K.jsx)(`button`,{type:`button`,className:c(kT,`whitespace-normal`),onClick:()=>{t(e.id),r(``)},children:(0,K.jsxs)(`span`,{className:`flex min-w-0 flex-col gap-0.5`,children:[(0,K.jsx)(`span`,{className:`line-clamp-2 wrap-anywhere`,children:(0,K.jsx)(MOi,{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)(MOi,{text:jOi(e.description,n),query:n})}):null]})})},e.id))})})}):null]})}function POi(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 FOi(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??oOi)(c),{pages:u,loaded:d,failed:f,nextCursor:p}=lTi((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]),POi),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?!XDi(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 IOi({graph:e,source:t,selectedPageId:n,onSelect:r,view:i,onViewChange:a,toolbarEnd:o,flush:s=!1}){let c=Zw(1024),l=!c&&i===`tree`?`graph`:i,u=t.usePage(n),d=!!t.useTreeLevels,[f,p]=(0,G.useState)([]),[m,h]=(0,G.useState)([]),[g,_]=(0,G.useState)(()=>new Set),[v,y]=(0,G.useState)(()=>new Map),[b,x]=(0,G.useState)(!1),[S,C]=(0,G.useState)(!0),w=FOi(t,e,u.data,f),E=(0,G.useMemo)(()=>d?Gwi({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??lOi)(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=Zwi(t.values()),i=e.page.id,a=e.notes.flatMap(e=>e.mentions).filter(e=>e&&e!==i),o=rTi(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(`:`)&&!JDi.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,QDi-_(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??sOi,j=(t.useLinkedPages??cOi)(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`),...iTi(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)(()=>eOi(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??lOi)(l===`graph`?te:[]),W=(0,G.useMemo)(()=>U.data?new Map(Object.entries(U.data)):void 0,[U.data]),ne=(0,G.useMemo)(()=>W?dOi(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),uOi):ie(null)},[]);(0,G.useEffect)(()=>()=>clearTimeout(ae.current),[]);let se=(t.usePageLinks??lOi)(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&&!hOi([...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=hOi(t.useTreeLevels?w.pages:e.pages,Re?z:null),Be=(0,G.useMemo)(()=>hOi(I.pages,Re?z:null),[I.pages,Re,z]),Ve=l===`graph`?L.get(n??I.hub??``):void 0;Ve&&I.hiddenChildren.get(Ve.id);let He=[{value:`tree`,label:`Tree`,icon:(0,K.jsx)(ZN,{}),narrowOnly:!0},{value:`graph`,label:`Graph`,icon:(0,K.jsx)(n7e,{}),narrowOnly:!1},{value:`page`,label:`Page`,icon:(0,K.jsx)(xk,{}),narrowOnly:!1}],Ue=tOi(l,Te),We=he&&Te,Ge=he&&!Te&&n&&!pOi(u.error)&&n?n:void 0;Ge&&Ge!==ve&&ye(Ge);let Ke=Ge??ve,qe={left:iOi(he,ge),right:Ge?aOi:0},Je={"--knowledge-tree-inset":`${qe.left}px`,"--knowledge-tree-drawer-inset":`${he&&ge?nOi:0}px`,"--knowledge-drawer-inset":`${qe.right}px`},Ye=()=>be.current?.querySelector(`[role="tab"][aria-selected="true"]`)?.focus(),Xe=e=>{e&&Ce.current&&(Ce.current=!1,Ye())},Ze=e=>{(0,Pt.flushSync)(()=>_e(e)),(e?Se:xe).current?.focus()},Qe=he&&!ge,$e=he?(0,K.jsxs)(jQ.Header,{children:[(0,K.jsx)(jQ.Heading,{children:`Pages`}),(0,K.jsx)(jQ.HeaderActions,{children:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`Hide pages`,"aria-label":`Hide pages`,ref:Se,onClick:()=>Ze(!1),children:(0,K.jsx)(qDi,{})})})]}):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)(hTi,{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)(_Oi,{label:`Loading pages`,rows:6})}):(0,K.jsx)(GDi,{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)(aTi.Provider,{value:N,children:(0,K.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col ${s?``:`gap-2`}`,children:[(0,K.jsxs)(TK,{className:s?`shrink-0 border-b border-surface-rim px-3 py-2`:void 0,children:[(0,K.jsxs)(TK.Start,{children:[(0,K.jsx)(gk,{ref:be,value:Ue,defaultTab:Ue,onValueChange:e=>a(e),"aria-label":`View`,children:(0,K.jsx)(hk,{variant:`pill-ghost`,size:`sm`,children:He.map(e=>(0,K.jsxs)(_k,{value:e.value,disabled:e.value===`page`&&!n,className:e.narrowOnly?`lg:hidden`:void 0,children:[(0,K.jsx)(Dx,{size:`xs`,children:e.icon}),(0,K.jsx)(T,{variant:`caption`,className:`text-inherit`,children:e.label})]},e.value))})}),(0,K.jsx)(NOi,{source:t,onSelect:Le})]}),o?(0,K.jsx)(TK.End,{children:o}):null]}),!d&&e.truncated&&!Te?(0,K.jsxs)(T,{variant:`caption`,tone:`muted`,className:s?`px-3 pt-2`:void 0,children:[`The graph shows the first `,e.pages.length,` pages. Open the tree or search to reach the rest.`]}):null,n&&!Te&&pOi(u.error)?(0,K.jsx)(T,{role:`alert`,variant:`caption`,className:`text-destructive-foreground ${s?`px-3 pt-2`:``}`,children:`Page not found. The linked page may have been deleted or merged.`}):null,(0,K.jsxs)(`div`,{style:Je,className:`relative flex min-h-0 flex-1 flex-col gap-3 lg:flex-row`,children:[he?(0,K.jsx)(`div`,{inert:Qe,"aria-hidden":Qe||void 0,"data-state":Qe?`closed`:`open`,className:`absolute inset-y-2 left-2 z-10 flex w-72 transition duration-slow ease-out-custom motion-reduce:transition-none ${Qe?`pointer-events-none -translate-x-4 opacity-0`:`translate-x-0 opacity-100`}`,children:(0,K.jsxs)(jQ,{variant:`inline`,title:`Pages`,className:`shadow-overlay`,children:[$e,et]})}):(0,K.jsx)(`aside`,{"aria-label":`Pages`,className:`min-h-0 w-full flex-1 flex-col overflow-hidden rounded-lg border border-border bg-card lg:w-72 lg:flex-none lg:shrink-0 ${l===`tree`?`flex`:`hidden`}`,children:et}),he?(0,K.jsx)(X,{tooltip:`Show pages`,"aria-label":`Show pages`,size:`icon-sm`,inert:!Qe,"aria-hidden":!Qe||void 0,className:`absolute top-3 left-3 z-10 shadow-overlay transition-opacity duration-slow ease-out-custom motion-reduce:transition-none ${Qe?`opacity-100`:`pointer-events-none opacity-0`}`,ref:xe,onClick:()=>Ze(!0),children:(0,K.jsx)(KDi,{})}):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)(kOi,{source:t,pageId:n,pagesById:L,onSelect:Ie,highlightMentionOf:we})}):(0,K.jsxs)(`div`,{className:`relative min-h-0 min-w-0 flex-1 overflow-hidden bg-sidebar lg:block lg:h-full ${s?``:`rounded-xl border border-border`} ${l===`graph`||We?`block`:`hidden`}`,"data-testid":`knowledge-graph-container`,children:[me&&!We?(0,K.jsx)(`div`,{className:`absolute top-3 right-3 z-10 -translate-x-(--knowledge-drawer-inset) transition-transform duration-slow ease-out-custom motion-reduce:transition-none`,children:(0,K.jsxs)($V,{orientation:`vertical`,size:`sm`,"aria-label":`Graph options`,className:`rounded-xl shadow-overlay`,children:[(0,K.jsx)(X,{"data-testid":`knowledge-graph-back`,"aria-label":`Back`,tooltip:Ae?`Back to the previous page`:`Nothing to go back to yet`,tooltipPosition:`left`,size:`icon-sm`,disabled:!Ae,onClick:je,children:(0,K.jsx)(sS,{})}),(0,K.jsx)(X,{"aria-label":`All links`,"aria-pressed":b,"data-testid":`knowledge-graph-all-links`,tooltip:b?`Show only the selected page’s links`:`Show every link between pages`,tooltipPosition:`left`,size:`icon-sm`,className:b?`[--control-icon:var(--foreground)]`:void 0,onClick:()=>x(e=>!e),children:(0,K.jsx)(tZ,{})}),(0,K.jsx)(X,{"aria-label":`Link counts`,"aria-pressed":S,"data-testid":`knowledge-graph-dot-counts`,tooltip:S?`Hide link counts`:`Show link counts on each dot`,tooltipPosition:`left`,size:`icon-sm`,className:S?`[--control-icon:var(--foreground)]`:void 0,onClick:()=>C(e=>!e),children:(0,K.jsx)(Z4,{})})]})}):null,me&&!We?(0,K.jsx)(zDi,{pages:Be,edges:ee,pinnedIds:e.pinnedIds,grants:e.grants,selectedPageId:n,centerId:I.hub,hiddenLinks:ne,knownLinks:V,fetchedLinks:ce,exactLinkCounts:W,onHover:oe,nearIds:F,settled:D,insets:qe,collapsibleLegend:he,showCounts:S,onPreview:e=>{v9(e)&&e.parentId&&R(e.parentId)},onSelect:e=>{if(v9(e))return e.parentId?R(e.parentId):void 0;if(y9(e)){let t=e.parentId;return t?(y(e=>new Map(e).set(t,(e.get(t)??0)+12)),w.loadMore.get(t)?.()):void 0}if(b9(e))return _(t=>new Set(t).add(e.id));Ne(e.id)},onOpen:e=>Me(e.id),onClearSelection:()=>{ue(null),n&&r(null)},onMentionSelect:ue}):null,he?(0,K.jsx)(`div`,{inert:!Ge,"aria-hidden":!Ge||void 0,"data-state":Ge?`open`:`closed`,onTransitionEnd:e=>{!Ge&&e.target===e.currentTarget&&ye(void 0)},className:`absolute inset-y-2 right-2 z-10 flex w-96 transition duration-slow ease-out-custom motion-reduce:transition-none ${Ge?`translate-x-0 opacity-100`:`pointer-events-none translate-x-4 opacity-0`}`,children:Ke?(0,K.jsxs)(jQ,{variant:`inline`,title:`Page details`,className:`shadow-overlay`,children:[(0,K.jsxs)(jQ.Header,{children:[(0,K.jsx)(jQ.Heading,{className:`min-w-0 flex-1 shrink`,children:(0,K.jsx)(`span`,{className:`truncate`,children:tt?.name??`Page`})}),(0,K.jsxs)(jQ.HeaderActions,{children:[(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`Open page`,"aria-label":`Open page`,onClick:()=>{Ce.current=!0,Me(Ke)},children:(0,K.jsx)(tP,{})}),(0,K.jsx)(jQ.CloseButton,{icon:`x`,label:`Close page details`,tooltip:`Close`,onClick:()=>{Ye(),r(null)}})]})]}),(0,K.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden`,children:(0,K.jsx)(kOi,{source:t,pageId:Ke,pagesById:L,onSelect:Le,highlightMentionOf:we,compact:!0,onOpenPage:()=>{Ce.current=!0,Me(Ke)}})})]}):null}):null,We?(0,K.jsx)(`section`,{ref:Xe,"aria-label":`Selected page`,className:`absolute inset-y-2 right-2 left-[calc(var(--knowledge-tree-inset)+0.5rem)] z-20 flex transition-[left] duration-slow ease-out-custom motion-reduce:transition-none`,children:(0,K.jsxs)(jQ,{variant:`inline`,title:`Page`,className:`shadow-overlay`,children:[(0,K.jsxs)(jQ.Header,{children:[(0,K.jsx)(jQ.Heading,{children:`Page`}),(0,K.jsx)(jQ.HeaderActions,{children:(0,K.jsx)(jQ.CloseButton,{icon:`x`,label:`Close page`,tooltip:`Close`,onClick:()=>{Ye(),a(`graph`)}})})]}),(0,K.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden`,children:(0,K.jsx)(kOi,{source:t,pageId:n,pagesById:L,onSelect:Ie,highlightMentionOf:we})})]})}):null,le&&me?(0,K.jsx)(OOi,{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 LOi=2,ROi=5e3,zOi=6e4,BOi=5e3,VOi=150,M9=e=>e?zOi:ROi,HOi=e=>e instanceof qf&&(e.status>=400&&e.status<500||e.status===501);function UOi(e,t){return new Promise(n=>{let r=setTimeout(n,e);t.addEventListener(`abort`,()=>(clearTimeout(r),n()),{once:!0})})}function WOi(e){return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)}var GOi=()=>document.visibilityState!==`hidden`;function KOi(e){let t=Y(),n=u_(),[r,i]=(0,G.useState)(!1),a=(0,G.useSyncExternalStore)(WOi,GOi,()=>!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]}),VOi)};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(HOi(e)){i(!1);return}}if(r.signal.aborted)return;i(!1),await UOi(BOi,r.signal)}})(),()=>{r.abort(),clearTimeout(s),i(!1)}},[t,n,e,a]),r}function qOi(){let e=Y();return T_({queryKey:[`knowledge`,`instances`],queryFn:async()=>(await e.listKnowledge()).instances})}function JOi(e,t){let n=Y();return T_({queryKey:[`knowledge`,e,`graph`],queryFn:e?async()=>n.getKnowledge(e).graph():v_,refetchInterval:M9(t)})}function YOi(e,t,n,r){let i=Y();return T_({queryKey:[`knowledge`,e,`page`,n,r??null],queryFn:e&&n?async()=>i.getKnowledge(e).page(n,{noteCursor:r}):v_,refetchInterval:!r&&M9(t)})}function XOi(e,t){let n=Y();return w_({queries:t.map(t=>({queryKey:[`knowledge`,e,`page`,t,null],queryFn:e?async()=>n.getKnowledge(e).page(t):v_,retry:(e,t)=>!(t&&`status`in t&&t.status===404)&&e<2,staleTime:3e4}))})}function ZOi(e,t,n){let r=Y();return w_({queries:n.map(n=>({queryKey:[`knowledge`,e,`tree`,n.parentId,n.cursor??null],queryFn:e?async()=>r.getKnowledge(e).tree({parentId:n.parentId??void 0,cursor:n.cursor}):v_,refetchInterval:!n.cursor&&M9(t)}))})}var QOi=200,$Oi=(e,t)=>!HOi(t)&&e<2;function eki(e,t,n){let r=Y();return T_({queryKey:[`knowledge`,e,`link-counts`,n],queryFn:e&&n.length?async()=>{let t=r.getKnowledge(e),i=[];for(let e=0;e<n.length;e+=QOi)i.push(n.slice(e,e+QOi));let a=await Promise.all(i.map(e=>t.linkCounts(e)));return Object.assign({},...a.map(e=>e.counts))}:v_,placeholderData:__,retry:$Oi,refetchInterval:M9(t)})}function tki(e,t){let n=Y();return T_({queryKey:[`knowledge`,e,`page-links`,t],queryFn:e&&t?async()=>n.getKnowledge(e).pageLinks(t):v_,staleTime:3e4,retry:$Oi})}function nki(e,t,n){let r=Y();return T_({queryKey:[`knowledge`,e,`activity`,n],queryFn:e?async()=>r.getKnowledge(e).activity({pageId:n}):v_,refetchInterval:M9(t)})}function rki(e,t){let n=Y(),r=t.trim();return T_({queryKey:[`knowledge`,e,`search`,r],queryFn:e&&r.length>=LOi?async()=>n.getKnowledge(e).search(r):v_,placeholderData:__})}var iki=[eP(`/knowledge`)];function N9({children:e}){return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:iki}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Knowledge`}),e]})}function aki({knowledgeKey:e,live:t,graph:n}){let[r,i]=Rv(),a=r.get(`page`),o=r.get(`view`),s=o===`graph`||o===`page`||o===`tree`?o:a?`page`:`tree`,c=(0,G.useMemo)(()=>({usePage:(n,r)=>YOi(e,t,n,r),useSearch:t=>rki(e,t),useTreeLevels:n=>ZOi(e,t,n),useLinkCounts:n=>eki(e,t,n),usePageLinks:t=>tki(e,t),useLinkedPages:t=>XOi(e,t),useActivity:n=>nki(e,t,n)}),[e,t]),l=YOi(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)(IOi,{graph:n,source:c,selectedPageId:a,onSelect:e=>d(`page`,e),view:s,onViewChange:e=>d(`view`,e)})}function oki(){let[e,t]=Rv(),n=qOi(),r=e.get(`instance`)??n.data?.[0]?.key,i=KOi(r),a=JOi(r,i),o=n.error??a.error;return o&&FN(o)?(0,K.jsx)(N9,{children:(0,K.jsx)(TH,{variant:`fill`})}):o&&IN(o)?(0,K.jsx)(N9,{children:(0,K.jsx)(wH,{variant:`fill`,resource:`knowledge`})}):n.error&&!n.data&&LN(n.error)?(0,K.jsx)(N9,{children:(0,K.jsx)(Jx,{variant:`fill`,titleSlot:`Knowledge browsing is not enabled`,descriptionSlot:`This server does not register the Knowledge routes. Add KNOWLEDGE_ROUTES from @mastra/server/server-adapter to server.apiRoutes, then reload.`})}):n.error&&!n.data?(0,K.jsx)(N9,{children:(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load Knowledge`,descriptionSlot:n.error.message})}):n.data&&n.data.length===0?(0,K.jsx)(N9,{children:(0,K.jsx)(Jx,{variant:`fill`,titleSlot:`No Knowledge instances`,descriptionSlot:`Register one on your Mastra instance with the knowledge option to browse it here.`})}):(0,K.jsx)(N9,{children:(0,K.jsxs)(`div`,{className:`flex h-full min-h-0 flex-1 flex-col gap-3`,children:[n.data&&n.data.length>1?(0,K.jsx)(`select`,{"aria-label":`Knowledge instance`,className:`text-ui-md h-8 w-fit rounded border border-border bg-card px-2`,value:r,onChange:e=>t(new URLSearchParams({instance:e.target.value})),children:n.data.map(e=>(0,K.jsx)(`option`,{value:e.key,children:e.key},e.key))}):null,!r||a.isPending?(0,K.jsx)(`p`,{className:`text-ui-md p-4 text-muted-foreground`,children:`Loading knowledge…`}):a.data?a.data.pages.length===0?(0,K.jsx)(Jx,{variant:`fill`,titleSlot:`No pages yet`,descriptionSlot:`Agents add pages and notes to Knowledge as they run. They will appear here.`}):(0,K.jsx)(aki,{knowledgeKey:r,live:i,graph:a.data}):(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load Knowledge`,descriptionSlot:a.error?.message})]})})}function ski({title:e,description:t,errorBanner:n,children:r}){return(0,K.jsxs)(`div`,{"data-testid":`login-page`,className:`w-full max-w-sm space-y-6 p-6`,children:[(0,K.jsxs)(`div`,{className:`flex flex-col items-center space-y-2`,children:[(0,K.jsx)(UZ,{className:`h-10 w-10`}),(0,K.jsx)(T,{as:`h1`,variant:`heading`,tone:`ink`,children:e})]}),t,n,r]})}function cki({redirectUri:e,onSuccess:t,initialMode:n=`signin`,errorMessage:r}){let{data:i,isLoading:a}=A_(),{mutate:o,isPending:s,error:c}=AFe(),{mutate:l,isPending:u,error:d}=MFe(),{mutate:f,isPending:p}=NFe(),[m,h]=(0,G.useState)(n),[g,_]=(0,G.useState)(``),[v,y]=(0,G.useState)(``),[b,x]=(0,G.useState)(``);if(a)return(0,K.jsx)(`div`,{className:`text-muted-foreground`,children:`Loading...`});if(!i?.enabled||!i?.login)return(0,K.jsx)(`div`,{className:`text-muted-foreground`,children:`Authentication is not configured`});let{login:S}=i,C=S.type===`sso`||S.type===`both`,w=S.type===`credentials`||S.type===`both`,E=S.sso,D=S.signUpEnabled!==!1,O=m===`signin`||!D,k=O?s:u,A=O?c:d,j=()=>{t?t():e?window.location.href=e:window.location.href=WZ(`/`)},M=e=>{e.preventDefault(),O?o({email:v,password:b},{onSuccess:j}):l({email:v,password:b,name:g||void 0},{onSuccess:j})},N=()=>{f({redirectUri:e},{onSuccess:e=>{window.location.href=e.url}})},P=()=>{h(O?`signup`:`signin`)},F=S.description?(0,K.jsxs)(`div`,{className:`flex items-start gap-2.5 rounded-md border border-border bg-sidebar p-3`,children:[(0,K.jsx)(CH,{className:`mt-0.5 size-icon-md shrink-0 text-muted-foreground`}),(0,K.jsx)(T,{tone:`muted`,children:S.description})]}):null;return(0,K.jsxs)(ski,{title:O?`Sign in to Mastra Studio`:`Create your account`,description:F,errorBanner:r?(0,K.jsx)(`div`,{role:`alert`,children:(0,K.jsx)(Sk,{variant:`destructive`,children:r})}):null,children:[w&&(0,K.jsxs)(ZV,{onSubmit:M,children:[!O&&(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{children:`Name`}),(0,K.jsx)(Jj,{name:`name`,type:`text`,autoComplete:`name`,value:g,onChange:e=>_(e.target.value),placeholder:`Your name`,variant:`default`,size:`lg`})]}),(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{required:!0,children:`Email`}),(0,K.jsx)(Jj,{name:`email`,type:`email`,autoComplete:`email`,value:v,onChange:e=>y(e.target.value),placeholder:`you@example.com`,required:!0,variant:`default`,size:`lg`}),(0,K.jsx)(lk,{})]}),(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{required:!0,children:`Password`}),(0,K.jsx)(Jj,{name:`password`,type:`password`,autoComplete:O?`current-password`:`new-password`,value:b,onChange:e=>x(e.target.value),placeholder:O?`Enter your password`:`Create a password`,required:!0,variant:`default`,size:`lg`}),(0,K.jsx)(lk,{})]}),A?(0,K.jsx)(`div`,{role:`alert`,children:(0,K.jsx)(Sk,{variant:`destructive`,children:A.message})}):null,(0,K.jsx)(X,{icon:(0,K.jsx)(Cmn,{}),type:`submit`,disabled:k,className:`w-full`,size:`lg`,children:k?O?`Signing in...`:`Creating account...`:O?`Sign in`:`Create account`}),D&&(0,K.jsxs)(`div`,{className:`text-center`,children:[(0,K.jsx)(T,{as:`span`,variant:`body`,tone:`muted`,children:O?`Don't have an account? `:`Already have an account? `}),(0,K.jsx)(`button`,{type:`button`,onClick:P,className:`text-foreground hover:underline`,children:(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:O?`Sign up`:`Sign in`})})]})]}),C&&w&&(0,K.jsxs)(`div`,{className:`relative`,children:[(0,K.jsx)(`div`,{className:`absolute inset-0 flex items-center`,children:(0,K.jsx)(`div`,{className:`w-full border-t border-border`})}),(0,K.jsx)(`div`,{className:`relative flex justify-center`,children:(0,K.jsx)(T,{as:`span`,variant:`body`,tone:`muted`,className:`bg-sidebar px-2`,children:`or continue with`})})]}),C&&E&&(0,K.jsxs)(X,{onClick:N,disabled:p,className:`w-full`,size:`lg`,children:[E.icon&&(0,K.jsx)(`span`,{className:`mr-2`,children:E.icon}),p?`Redirecting...`:E.text||`Sign in`]})]})}function lki(){let[e]=Rv(),t=Ov(),n=e.get(`redirect`)||`/`,r=e.get(`mode`)===`signup`?`signup`:`signin`,i=e.get(`error_description`)||e.get(`error`)||null;return(0,K.jsx)(cki,{redirectUri:n,onSuccess:()=>{n.startsWith(`http`)?window.location.href=n:t(n,{replace:!0})},initialMode:r,errorMessage:i})}function uki({disabled:e,onClear:t,onRemoveAll:n,onSave:r,onRemoveSaved:i}){let a=!!(n||r||i);return!t&&!a?null:(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[t&&(0,K.jsx)(X,{disabled:e,size:`md`,onClick:t,icon:(0,K.jsx)(xw,{}),children:`Clear`}),a&&(0,K.jsxs)(rE,{children:[(0,K.jsx)(rE.Trigger,{asChild:!0,children:(0,K.jsx)(X,{disabled:e,size:`icon-md`,"aria-label":`More filter actions`,children:(0,K.jsx)(iE,{})})}),(0,K.jsxs)(rE.Content,{align:`end`,children:[n&&(0,K.jsxs)(rE.Item,{onSelect:()=>n(),children:[(0,K.jsx)(xw,{}),`Remove all filters`]}),n&&(r||i)&&(0,K.jsx)(rE.Separator,{}),r&&(0,K.jsxs)(rE.Item,{onSelect:()=>r(),children:[(0,K.jsx)(W4,{}),`Save filters for next time`]}),i&&(0,K.jsxs)(rE.Item,{onSelect:()=>i(),children:[(0,K.jsx)(Kj,{}),`Remove saved filters`]})]})]})]})}var dki=c(kT,`min-w-0`);function fki({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:dki,onClick:r,children:[(0,K.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:n}),t&&(0,K.jsx)(`span`,{className:jT,children:(0,K.jsx)(pC,{})})]})}function pki({field:e,tokens:t,onChange:n}){let[r,i]=(0,G.useState)(``),a=`max-h-[80dvh] overflow-auto p-1`,o=(0,G.useMemo)(()=>{let t=r.trim().toLowerCase();return t?e.options.filter(e=>e.label.toLowerCase().includes(t)):e.options},[e.options,r]),s=(0,G.useMemo)(()=>t.find(t=>t.fieldId===e.id),[t,e.id]),l=typeof s?.value==`string`?s.value:e.multi?void 0:e.defaultValue,u=(0,G.useMemo)(()=>{let e=s?.value;return Array.isArray(e)?e:typeof e==`string`?[e]:[]},[s]);return(0,K.jsxs)(K.Fragment,{children:[e.searchable!==!1&&(0,K.jsxs)(`div`,{className:FT.container,children:[(0,K.jsx)(oN,{className:FT.icon}),(0,K.jsx)(`input`,{type:`text`,value:r,onChange:e=>i(e.target.value),placeholder:`Search ${e.label.toLowerCase()}`,className:FT.input,...Gk,onKeyDown:e=>{if(e.key!==`ArrowDown`)return;let t=e.currentTarget.closest(`[data-pick-multi-panel]`)?.querySelector(`[data-pick-multi-item]:not([disabled])`);t&&(e.preventDefault(),e.stopPropagation(),t.focus())}})]}),e.isLoading?(0,K.jsxs)(`div`,{className:c(I6e,`m-1`),children:[(0,K.jsx)(It,{size:`sm`,className:`size-3 text-muted-foreground`}),`Loading options…`]}):o.length===0?(0,K.jsx)(`div`,{className:c(I6e,`m-1`),children:e.emptyText??`No option found.`}):e.multi?(0,K.jsx)(`div`,{className:a,children:(0,K.jsx)(K.Fragment,{children:o.map(t=>{let r=u.includes(t.value);return(0,K.jsx)(fki,{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)(fki,{role:`radio`,checked:l===t.value,label:t.label,onClick:()=>n(e.id,t.value)},t.value)),!e.omitAnyOption&&(0,K.jsx)(fki,{role:`radio`,checked:l===`Any`,label:`Any`,onClick:()=>n(e.id,`Any`)})]})})]})}function mki(e){return Array.isArray(e)?e.length===0?`Any`:e.join(`, `):e}var hki=`This filter is set by the current context and cannot be removed here.`;function gki(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:mki(t)}function _ki({field:e,value:t,tooltipContent:n}){let r=gki(e,t),i=`${e.label} filter is locked by context`;return(0,K.jsx)(Sx,{delayDuration:150,children:(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{asChild:!0,children:(0,K.jsxs)($V,{"data-locked-field-id":e.id,"data-property-filter-pill":`locked`,tabIndex:0,"aria-label":i,children:[(0,K.jsx)(eH,{children:e.label}),(0,K.jsx)(eH,{children:`is`}),(0,K.jsx)(eH,{children:r}),(0,K.jsx)(eH,{children:(0,K.jsx)(CH,{})})]})}),(0,K.jsx)(Tx,{children:n})]})})}function vki({field:e,value:t,onChange:n,onRemove:r,disabled:i,autoFocus:a}){let[o,s]=(0,G.useState)(t),c=(0,G.useRef)(null);return(0,G.useEffect)(()=>{o.trim()!==t&&s(t)},[t]),(0,G.useEffect)(()=>{a&&c.current?.focus()},[a]),(0,K.jsxs)($V,{children:[(0,K.jsx)(eH,{children:e.label}),(0,K.jsx)(eH,{children:`is`}),(0,K.jsx)(Jj,{ref:c,disabled:i,value:o,placeholder:e.placeholder??`Enter ${e.label}`,onChange:e=>{let r=e.target.value;s(r),r.trim()!==t&&n(r)},onKeyDown:e=>{if(e.key===`Enter`){e.preventDefault();let r=o.trim();r!==t&&n(r)}else e.key===`Escape`&&(e.preventDefault(),s(t),e.currentTarget.blur())}}),(0,K.jsx)(X,{size:`icon-md`,type:`button`,disabled:i,"aria-label":`Remove ${e.label} filter`,onMouseDown:e=>e.preventDefault(),onClick:r,children:(0,K.jsx)(xw,{})})]})}function yki({field:e,token:t,tokens:n,onChange:r,onRemove:i,disabled:a}){let[o,s]=(0,G.useState)(!1);return(0,K.jsxs)($V,{children:[(0,K.jsx)(eH,{children:e.label}),(0,K.jsx)(eH,{children:`is`}),(0,K.jsxs)(Xj,{open:o,onOpenChange:s,children:[(0,K.jsx)(Zj,{asChild:!0,children:(0,K.jsx)(X,{type:`button`,disabled:a,children:mki(t.value)})}),(0,K.jsx)(Qj,{align:`start`,sideOffset:4,className:`w-64 p-0`,"data-pick-multi-panel":!0,children:(0,K.jsx)(pki,{field:e,tokens:n,onChange:r})})]}),(0,K.jsx)(X,{size:`icon-md`,type:`button`,disabled:a,"aria-label":`Remove ${e.label} filter`,onClick:i,children:(0,K.jsx)(xw,{})})]})}function bki({fields:e,tokens:t,onTokensChange:n,disabled:r,autoFocusFieldId:i,lockedFieldIds:a,lockedTooltipContent:o=hki}){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)(_ki,{field:u,value:n.value,tooltipContent:o},`${n.fieldId}-${a}`):u.kind===`text`&&!Array.isArray(n.value)?(0,K.jsx)(vki,{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)(yki,{field:u,token:n,tokens:t,disabled:r,onChange:(e,t)=>c(a,{fieldId:e,value:t}),onRemove:()=>l(a)},`${n.fieldId}-${a}`):(0,K.jsxs)($V,{children:[(0,K.jsx)(eH,{children:u.label}),(0,K.jsx)(eH,{children:`is`}),(0,K.jsx)(eH,{children:mki(n.value)}),(0,K.jsx)(X,{size:`icon-md`,type:`button`,disabled:r,"aria-label":`Remove ${u.label} filter`,onClick:()=>l(a),children:(0,K.jsx)(xw,{})})]},`${n.fieldId}-${a}`):null})})}var xki=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`})),Ski=(0,G.forwardRef)((e,t)=>(0,K.jsx)(`button`,{type:`button`,role:`menuitem`,"data-filter-item":``,ref:t,...e}));Ski.displayName=`FilterMenuButton`;function Cki({fields:e,tokens:t,onTokensChange:n,label:r=`Add filter`,disabled:i,size:a,onStartTextFilter:o,hiddenFieldIds:s}){let l=(0,G.useMemo)(()=>{if(!s||s.length===0)return e;let t=new Set(s);return e.filter(e=>!t.has(e.id))},[e,s]),[u,d]=(0,G.useState)(!1),[f,p]=(0,G.useState)(),[m,h]=(0,G.useState)([]),[g,_]=(0,G.useState)(),[v,y]=(0,G.useState)(),b=(0,G.useRef)(!1),x=(0,G.useCallback)(e=>{y(t=>t===e?void 0:e)},[]),S=(0,G.useCallback)(()=>y(void 0),[]);(0,G.useEffect)(()=>{u||y(void 0)},[u]);let C=(0,G.useMemo)(()=>l.find(e=>e.id===f),[l,f]),w=(0,G.useMemo)(()=>{let n=new Set;for(let r of t){let t=e.find(e=>e.id===r.fieldId);t&&t.kind!==`pick-multi`&&n.add(r.fieldId)}return n},[t,e]),E=(0,G.useCallback)(()=>{p(void 0),h([]),_(void 0)},[]);(0,G.useEffect)(()=>{u||E()},[u,E]);let D=(0,G.useCallback)((e,r)=>{let i=t.findIndex(t=>t.fieldId===e);if(Array.isArray(r)&&r.length===0){if(i===-1)return;n(t.filter((e,t)=>t!==i));return}if(i===-1){n([...t,{fieldId:e,value:r}]);return}let a=[...t];a[i]={fieldId:e,value:r},n(a)},[n,t]),O=(0,G.useCallback)(()=>{C?w.has(C.id)?_(`Remove the existing ${C.label} filter before adding another.`):m.length===0?_(`Choose at least one ${C.label.toLowerCase()} value.`):(n([...t,{fieldId:C.id,value:m}]),d(!1)):_(`Choose a property first.`)},[m,n,C,w,t]);return(0,K.jsxs)(Xj,{open:u,onOpenChange:d,children:[(0,K.jsx)(Zj,{asChild:!0,children:(0,K.jsx)(X,{size:a,disabled:i,icon:(0,K.jsx)(NZ,{}),children:r})}),(0,K.jsx)(Qj,{align:`start`,sideOffset:4,className:c(`w-64`,C?`p-3`:`p-1`),initialFocus:!1,finalFocus:()=>!b.current||(b.current=!1,!1),children:(0,K.jsxs)(`div`,{className:c(`grid`,C&&`gap-3`),children:[C&&(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`button`,{type:`button`,"aria-label":`Back to properties`,className:c(`text-muted-foreground hover:text-foreground`,`transition-[color] duration-fast ease-out-custom motion-reduce:transition-none`),onClick:E,children:(0,K.jsx)(sS,{className:`size-icon-md`})}),(0,K.jsx)(xki,{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)(wki,{field:e,tokens:t,onChange:D,open:v===e.id,onToggle:x,onClose:S},e.id):(0,K.jsxs)(Ski,{className:c(kT,`group`),disabled:r,onClick:()=>{_(void 0),e.kind===`text`?(n([...t,{fieldId:e.id,value:``}]),o?.(e.id),b.current=!0,d(!1)):p(e.id)},children:[(0,K.jsx)(`span`,{className:`truncate`,children:e.label}),r?(0,K.jsx)(`span`,{className:`ml-auto text-muted-foreground`,children:`In use`}):(0,K.jsx)(`span`,{className:c(AT,`text-muted-foreground opacity-0 group-hover:opacity-100 group-focus:opacity-100`),children:(0,K.jsx)(Hx,{})})]},e.id)}):(0,K.jsx)(`div`,{className:`flex h-control-md items-center gap-2 px-2 py-0.5 text-menu text-muted-foreground box-content`,children:`No matching property.`})})}),C&&(0,K.jsxs)(ak,{invalid:!!g,children:[(0,K.jsx)(_N,{multiple:!0,options:C.options??[],value:m,onValueChange:e=>{h(e),_(void 0)},placeholder:C.placeholder??`Choose ${C.label}`,searchPlaceholder:`Search ${C.label.toLowerCase()}`,emptyText:C.emptyText??`No option found.`,size:`md`,"aria-label":C.label}),(0,K.jsx)(lk,{children:g})]}),C&&(0,K.jsxs)(`div`,{className:`flex items-center justify-end gap-2`,children:[(0,K.jsx)(X,{icon:(0,K.jsx)(xw,{}),variant:`ghost`,size:`md`,onClick:()=>d(!1),children:`Cancel`}),(0,K.jsx)(X,{icon:(0,K.jsx)(NZ,{}),size:`md`,onClick:O,children:`Add filter`})]})]})})]})}function wki({field:e,tokens:t,onChange:n,open:r,onToggle:i,onClose:a}){let o=(0,G.useRef)(null);return(0,K.jsxs)(Xj,{open:r,onOpenChange:t=>{t?i(e.id):a()},children:[(0,K.jsx)(Zj,{asChild:!0,children:(0,K.jsxs)(Ski,{className:kT,onKeyDown:t=>{(t.key===`ArrowRight`||t.key===`ArrowLeft`)&&(r||i(e.id),t.preventDefault(),requestAnimationFrame(()=>{(o.current?.querySelector(`input, button, [tabindex]:not([tabindex="-1"])`))?.focus()}))},children:[r&&(0,K.jsx)(f,{className:`text-muted-foreground`}),(0,K.jsx)(`span`,{className:`truncate`,children:e.label}),!r&&(0,K.jsx)(`span`,{className:c(AT,`text-muted-foreground`),children:(0,K.jsx)(f,{})})]})}),(0,K.jsx)(Qj,{ref:o,side:`right`,align:`start`,sideOffset:4,className:`w-64 p-0`,initialFocus:!1,onKeyDown:e=>{if(e.key!==`ArrowDown`&&e.key!==`ArrowUp`&&e.key!==`Home`&&e.key!==`End`)return;let t=Array.from(e.currentTarget.querySelectorAll(`[data-pick-multi-item]:not([disabled])`));if(t.length===0)return;e.preventDefault(),e.stopPropagation();let n=document.activeElement,r=t.findIndex(e=>e===n),i;i=e.key===`Home`?0:e.key===`End`?t.length-1:e.key===`ArrowDown`?r<0?0:(r+1)%t.length:r<=0?t.length-1:r-1,t[i]?.focus()},"data-pick-multi-panel":!0,children:(0,K.jsx)(pki,{field:e,tokens:t,onChange:n})})]})}function Tki({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:i,onNext:a,depth:o,actions:s}){let c=e?xC(e.timestamp)??``:``;return(0,K.jsx)(jQ,{open:!!e,onClose:t,title:e?`Log ${c}`:`Log`,depth:o,children:e&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(jQ.Header,{children:[(0,K.jsx)(jQ.CloseButton,{onClick:t}),(0,K.jsx)(jQ.Heading,{children:`Log`}),(0,K.jsx)(jQ.Metadata,{children:(0,K.jsx)(jQ.Meta,{tooltip:c,children:c})}),(0,K.jsxs)(jQ.HeaderActions,{children:[s,(0,K.jsx)(jQ.NextPrevNav,{onPrevious:i,onNext:a,previousLabel:`Go to previous log`,nextLabel:`Go to next log`})]})]}),(0,K.jsx)(jQ.Content,{children:(0,K.jsxs)(`div`,{className:`grid gap-6 p-2`,children:[(0,K.jsxs)(V4,{children:[e.entityType&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(V4.Key,{children:`Entity Type`}),(0,K.jsx)(V4.Value,{children:e.entityType})]}),e.entityName&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(V4.Key,{children:`Entity Name`}),(0,K.jsx)(V4.Value,{children:e.entityName})]}),e.serviceName&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(V4.Key,{children:`Service`}),(0,K.jsx)(V4.Value,{children:e.serviceName})]}),e.environment&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(V4.Key,{children:`Environment`}),(0,K.jsx)(V4.Value,{children:e.environment})]}),e.source&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(V4.Key,{children:`Source`}),(0,K.jsx)(V4.Value,{children:e.source})]}),e.metadata&&Object.entries(e.metadata).map(([e,t])=>(0,K.jsxs)(G.Fragment,{children:[(0,K.jsx)(V4.Key,{children:e}),(0,K.jsx)(V4.Value,{children:String(t)})]},e))]}),(0,K.jsx)(jQ.CodeSection,{title:`Message`,codeStr:e.message,simplified:!0}),(e.traceId||e.spanId)&&(0,K.jsxs)(`div`,{className:`grid gap-2`,children:[e.traceId&&(0,K.jsxs)($V,{className:`w-full min-w-0`,children:[(0,K.jsxs)(X,{className:`min-w-0 flex-1 justify-between overflow-hidden`,icon:(0,K.jsx)(oH,{}),onClick:()=>e.traceId&&n?.(e.traceId),children:[(0,K.jsx)(`span`,{children:`Trace`}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,tone:`faint`,className:`ml-auto min-w-0 truncate`,children:[`# `,e.traceId]})]}),(0,K.jsx)(gC,{content:e.traceId,tooltip:`Copy trace ID to clipboard`})]}),e.spanId&&(0,K.jsxs)($V,{className:`w-full min-w-0`,children:[(0,K.jsxs)(X,{className:`min-w-0 flex-1 justify-between overflow-hidden`,disabled:!e.traceId||!r,onClick:()=>e.traceId&&e.spanId&&r?.(e.traceId,e.spanId),icon:(0,K.jsx)(oH,{}),children:[(0,K.jsx)(`span`,{children:`Span`}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,tone:`faint`,className:`ml-auto min-w-0 truncate`,children:[`# `,e.spanId]})]}),(0,K.jsx)(gC,{content:e.spanId,tooltip:`Copy span ID to clipboard`})]})]}),e.data&&Object.keys(e.data).length>0&&(0,K.jsx)(jQ.CodeSection,{title:`Data`,codeStr:JSON.stringify(e.data,null,2)})]})})]})})}function Eki({error:e,resource:t,errorTitle:n}){if(FN(e))return(0,K.jsx)(TH,{});if(IN(e))return(0,K.jsx)(wH,{resource:t});if(zN(e))return(0,K.jsx)(Jx,{titleSlot:`Observability storage is not available`,descriptionSlot:`The observability storage domain is disabled or not configured. Enable it in your storage configuration to view logs in Studio.`});if(RN(e,`logs`))return(0,K.jsx)(Jx,{titleSlot:`Logs are not available with your current storage`,descriptionSlot:`The configured observability storage provider does not support listing logs. Switch to a storage provider with logs support to view runtime logs in Studio.`});let r=e instanceof Error?e.message:void 0;return(0,K.jsx)(Jx,{tone:`error`,titleSlot:n,descriptionSlot:r??`Unknown error`})}var Dki={debug:`neutral`,info:`info`,warn:`warning`,error:`destructive`,fatal:`destructive`};function Oki({level:e}){return(0,K.jsx)(uH,{children:(0,K.jsx)(eC,{variant:Dki[e],children:e})})}function kki({entityType:e,className:t}){let n=c(`size-3.5 shrink-0 text-placeholder`,t);switch(e.toLowerCase()){case`agent`:return(0,K.jsx)(HN,{className:n,"aria-hidden":!0});case`workflow`:case`workflow_run`:return(0,K.jsx)(ZS,{className:n,"aria-hidden":!0});case`tool`:return(0,K.jsx)(XN,{className:n,"aria-hidden":!0});default:return null}}function Aki({entityType:e,entityName:t}){return(0,K.jsxs)(uH,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(kki,{entityType:e??``}),t?(0,K.jsx)(T,{as:`span`,variant:`body-sm`,className:`min-w-0 truncate`,children:t}):`-`]})}function jki({message:e}){return(0,K.jsx)(uH,{className:`min-w-0 truncate font-mono text-body-sm text-muted-foreground`,children:e})}function Mki({data:e}){if(!e||Object.keys(e).length===0)return(0,K.jsx)(uH,{children:null});let t=Object.entries(e).map(([e,t])=>{if(typeof t==`string`)return`${e}: ${t}`;try{return`${e}: ${JSON.stringify(t)}`}catch{return`${e}: <unserializable>`}}).join(`, `);return(0,K.jsx)(pH,{font:`mono`,children:t})}var P9=Object.assign(_H,{Top:SH,TopCell:yH,SortableTopCell:xH,TopCellWithTooltip:bH,TopCellSmart:dmn,RowWrapper:omn,RowButton:vH,RowLink:imn,Spacer:_mn,NoMatch:hH,DateCell:Epn,TimeCell:Opn,LevelCell:Oki,EntityCell:Aki,MessageCell:jki,DataCell:Mki,NextPageLoading:mH}),Nki=`6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)`,Pki=36,Fki=8;function Iki({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=a7r({count:e.length,getScrollElement:()=>u.current,estimateSize:()=>Pki,overscan:Fki}),{getRowProps:f}=PZ({count:e.length,containerRef:u,onNavigate:e=>d.scrollToIndex(e),global:!0}),p=(0,G.useRef)(t);if((0,G.useEffect)(()=>{p.current&&!t&&u.current?.dispatchEvent(new Event(`scroll`)),p.current=t},[t]),t)return(0,K.jsx)(DH,{columns:Nki,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:Nki,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 Lki({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=>Rki(e,a));return u?(0,K.jsxs)(`div`,{className:c(`grid grid-cols-[1fr_auto] items-start gap-3`),children:[(0,K.jsx)(bki,{fields:a,tokens:o,onTokensChange:s,disabled:i,autoFocusFieldId:l}),u&&(0,K.jsx)(uki,{disabled:i,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]}):null}function Rki(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 zki={"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`},Bki=`Pick a wider range or lower the logging level. Verbose entries (debug, info) may be filtered out.`;function Vki({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!==`all`&&e!==`custom`?{title:`No logs for ${zki[e]}`,description:Bki}:t&&n?{title:`No logs between ${bC(t,`date-time`)} and ${bC(n,`date-time`)}`,description:Bki}:t?{title:`No logs since ${bC(t,`date-time`)}`,description:Bki}:{title:`No logs yet`,description:`Logs will appear here once agents, workflows, or tools are executed.`}}var Hki=({datePreset:e,dateFrom:t,dateTo:n}={})=>{let{title:r,description:i}=Vki({datePreset:e,dateFrom:t,dateTo:n});return(0,K.jsx)(Jx,{titleSlot:r,descriptionSlot:i,actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/en/docs/observability/logging`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(tP,{}),children:`Logging documentation`}),variant:`fill`})},Uki=`Filters setting for Logs saved`,Wki=`Filters setting for Logs cleared up`;function Gki(e,t,n){let{storageKey:r,messages:i,skipHydration:a}=n??{},[o,s]=(0,G.useState)(()=>qii(r)!==null),c=(0,G.useCallback)(()=>{Gii(e,r),s(!0);let t=i?.saved??Uki;t!==!1&&iS.success(t)},[e,r,i?.saved]),l=(0,G.useCallback)(()=>{Kii(r),s(!1);let e=i?.cleared??Wki;e!==!1&&iS.success(e)},[r,i?.cleared]),u=(0,G.useRef)(!1);return(0,G.useEffect)(()=>{if(a||u.current||(u.current=!0,Jii(e)))return;let n=qii(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 Kki(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return(t>>>0).toString(36)}function qki(e){let t=new Map;for(let n of e){if(n.logId){t.set(n,n.logId);continue}let e=n.timestamp instanceof Date?n.timestamp.toISOString():n.timestamp;t.set(n,Kki(`${e}${n.message??``}${n.data?JSON.stringify(n.data):``}`))}return t}function Jki(e,t,n,r){let i=(0,G.useMemo)(()=>qki(e),[e]),a=(0,G.useMemo)(()=>{let t=new Map;for(let[n,r]of e.entries()){let e=i.get(r);e&&t.set(e,{log:r,idx:n})}return t},[e,i]),o=(t?a.get(t):void 0)?.idx??-1,s=o>=0?e[o]??null:null;return{logIdMap:i,getLogId:(0,G.useCallback)(e=>i.get(e),[i]),featuredLog:s,handleLogClick:(0,G.useCallback)(e=>{let a=i.get(e);a&&n(t===a?{logId:null}:r?{logId:a,traceId:e.traceId??null,spanId:null}:{logId:a})},[i,t,r,n]),handlePreviousLog:o>0?()=>{let t=e[o-1];if(!t)return;let a=i.get(t);a&&n(r?{logId:a,traceId:t.traceId??null,spanId:null}:{logId:a})}:void 0,handleNextLog:o>=0&&o<e.length-1?()=>{let t=e[o+1];if(!t)return;let a=i.get(t);a&&n(r?{logId:a,traceId:t.traceId??null,spanId:null}:{logId:a})}:void 0}}var Yki=`logId`,Xki=`traceId`,Zki=`spanId`,F9=864e5,Qki={"last-24h":F9,"last-3d":3*F9,"last-7d":7*F9,"last-14d":14*F9,"last-30d":30*F9};function $ki(e){e.delete(Yki),e.delete(Xki),e.delete(Zki)}function eAi(e,t,n){let{onRemoveAll:r}=n??{},i=(0,G.useMemo)(()=>{let t=e.get(p7);return t&&Hii.has(t)?t:zii},[e]),a=e.get(m7),o=e.get(h7),s=(0,G.useMemo)(()=>{if(i===`custom`){if(!a)return;let e=new Date(a);return Number.isNaN(e.getTime())?void 0:e}if(i===`all`)return;let e=Qki[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(Yki),d=e.get(Xki),f=e.get(Zki),p=(0,G.useMemo)(()=>Lii.find(t=>t.entityType===e.get(f7)),[e]),m=(0,G.useMemo)(()=>Xii(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`?Yki:t===`traceId`?Xki:Zki;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 Qii(n,e),$ki(n),n},{replace:!0})},[t]),_=g,v=(0,G.useCallback)((e,n)=>{if(l.current!==`custom`)return;let r=n===`from`?m7:h7;t(t=>{let n=new URLSearchParams(t);return e?n.set(r,e.toISOString()):n.delete(r),$ki(n),n},{replace:!0})},[t]),y=(0,G.useCallback)(e=>{l.current=e,t(t=>{let n=new URLSearchParams(t);return e===`last-24h`?(n.delete(p7),n.delete(m7),n.delete(h7)):e===`custom`?n.set(p7,`custom`):(n.set(p7,e),n.delete(m7),n.delete(h7)),$ki(n),n},{replace:!0})},[t]),b=(0,G.useCallback)(()=>{t(e=>{let t=new URLSearchParams(e);t.delete(f7);for(let e of _7)t.delete(g7[e]);return t.delete(p7),t.delete(m7),t.delete(h7),$ki(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 tAi=20,nAi=1e4,rAi={field:`timestamp`,direction:`DESC`};function iAi(e,t,n){if(e?.pagination?.hasMore)return n+1}function aAi(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 oAi(e){return RN(e.state.error,`logs`)||zN(e.state.error)?!1:nAi}var sAi=({filters:e,orderBy:t=rAi,queryOptions:n}={})=>{let r=Y(),{inView:i,setRef:a}=$M(),{hasNextPage:o,isFetchingNextPage:s,fetchNextPage:c,data:l,isLoading:u,isError:d,error:f}=O_({queryKey:[`logs`,e,t],queryFn:({pageParam:n})=>r.listLogsVNext({pagination:{page:n,perPage:tAi},filters:e,orderBy:t}),initialPageParam:0,getNextPageParam:iAi,select:aAi,retry:!1,refetchInterval:oAi,...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}},cAi=[eP(`/logs`)];function lAi(){let[e,t]=Rv(),n=Ov(),r=eAi(e,t),i=a5(),{sort:a,onSortChange:o}=u7({searchParams:e,setSearchParams:t,allowedKeys:Bii,defaultSort:Vii}),s=(0,G.useMemo)(()=>({field:`timestamp`,direction:a?.direction===`asc`?`ASC`:`DESC`}),[a?.direction]),c=Gki(e,t),[l,u]=(0,G.useState)(),{data:d=[],isPending:f}=jYr(),{data:p=[],isPending:m}=t8({entityType:r.selectedEntityOption?.entityType,rootOnly:!0}),{data:h=[],isPending:g}=n8(),{data:_=[],isPending:v}=kYr(),y=(0,G.useMemo)(()=>Yii({availableTags:d,availableRootEntityNames:p,availableServiceNames:_,availableEnvironments:h,loading:{tags:f,entityNames:m,serviceNames:v,environments:g}}),[d,p,_,h,f,m,v,g]),{data:b=[],isLoading:x,error:S,isFetchingNextPage:C,hasNextPage:w,setEndOfListElement:T}=sAi({filters:(0,G.useMemo)(()=>$ii({rootEntityType:r.selectedEntityOption?.entityType,dateFrom:r.selectedDateFrom,dateTo:r.selectedDateTo,tokens:r.filterTokens}),[r.filterTokens,r.selectedDateFrom,r.selectedDateTo,r.selectedEntityOption]),orderBy:s}),{logIdMap:E,featuredLog:D,handleLogClick:O,handlePreviousLog:k,handleNextLog:A}=Jki(b,r.featuredLogId,r.handleFeaturedChange,r.featuredTraceId),{data:j,isLoading:M}=i8({traceId:r.featuredTraceId??null,queryOptions:{enabled:!!r.featuredTraceId}}),N=(0,G.useCallback)(()=>r.applyFilterTokens(eai(y,r.filterTokens)),[y,r]),P=(0,G.useCallback)(()=>r.handleFeaturedChange({logId:null}),[r]),F=(0,G.useCallback)(e=>r.handleFeaturedChange({traceId:e,spanId:null}),[r]),I=(0,G.useCallback)((e,t)=>r.handleFeaturedChange({traceId:e,spanId:t}),[r]),L=(0,G.useCallback)(()=>r.handleFeaturedChange({traceId:null,spanId:null}),[r]),R=(0,G.useCallback)(e=>r.handleFeaturedChange({spanId:e??null}),[r]),z=(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(TK,{children:(0,K.jsxs)(TK.Start,{children:[(0,K.jsx)(Nhn,{preset:r.datePreset,onPresetChange:r.handleDatePresetChange,dateFrom:r.selectedDateFrom,dateTo:r.selectedDateTo,onDateChange:r.handleDateChange,disabled:x,presets:[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`]}),(0,K.jsx)(Cki,{fields:y,tokens:r.filterTokens,onTokensChange:r.handleFilterTokensChange,disabled:x,onStartTextFilter:u,size:`sm`})]})}),(0,K.jsx)(Lki,{isLoading:x,filterFields:y,filterTokens:r.filterTokens,onFilterTokensChange:r.handleFilterTokensChange,onClear:N,onRemoveAll:r.handleRemoveAll,onSave:c.handleSave,onRemoveSaved:c.hasSavedFilters?c.handleRemoveSaved:void 0,autoFocusFilterFieldId:l})]});if(S)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:cAi}),actionRow:z,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Logs`}),(0,K.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:(0,K.jsx)(Eki,{error:S,resource:`logs`,errorTitle:`Failed to load logs`})})]});let B=!!r.selectedEntityOption||r.filterTokens.length>0;return b.length===0&&!x&&!B?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:cAi}),actionRow:z,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Logs`}),(0,K.jsx)(Hki,{datePreset:r.datePreset,dateFrom:r.selectedDateFrom,dateTo:r.selectedDateTo})]}):(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:cAi}),actionRow:z,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Logs`}),(0,K.jsx)(Iki,{logs:b,isLoading:x,isFetchingNextPage:C,hasNextPage:w,setEndOfListElement:T,logIdMap:E,featuredLogId:r.featuredLogId,onLogClick:O,timestampSort:a?.direction,onSortChange:o}),(0,K.jsx)(Tki,{log:D??void 0,onClose:P,onTraceClick:F,onSpanClick:I,onPrevious:k,onNext:A}),(0,K.jsx)(e_i,{depth:2,traceId:D?r.featuredTraceId??void 0:void 0,spans:j?.spans,isLoadingSpans:M,selectedSpanId:r.featuredSpanId??null,onSpanSelect:R,onClose:L,withQueryTrace:i.enabled,withFeedback:i.enabled,onOpenScore:(e,t)=>n(CK(e,t))})]})}function uAi(){let e=Y();return T_({queryKey:[`builtin-mcp-server`],queryFn:()=>e.getBuiltinMcpServer(),retry:!1})}var dAi=`<your-token>`;function fAi(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function pAi(e,{protectedServer:t}){let n=fAi(e),r=`Authorization: Bearer ${dAi}`,i=t?{headers:{Authorization:`Bearer ${dAi}`}}:{};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 mAi=`https://mastra.ai/docs/server/mcp`;function hAi(){let{data:e,error:t}=uAi();return e?(0,K.jsx)(gAi,{descriptor:e}):!t||FN(t)||IN(t)||LN(t)?null:(0,K.jsx)(_Ai,{children:(0,K.jsx)(Sk,{variant:`destructive`,children:`Couldn't load the built-in MCP server. Try reloading the page.`})})}function gAi({descriptor:e}){return(0,K.jsx)(_Ai,{status:(0,K.jsx)(vAi,{descriptor:e}),children:e.enabled?e.mcpPackageInstalled?(0,K.jsx)(SAi,{descriptor:e}):(0,K.jsx)(xAi,{}):(0,K.jsx)(bAi,{descriptor:e})})}function _Ai({status:e,children:t}){return(0,K.jsxs)(nP,{role:`region`,"aria-label":`Mastra (built-in) MCP server`,children:[(0,K.jsxs)(rP,{className:`flex-row flex-wrap items-center gap-3 space-y-0 border-b border-border`,children:[(0,K.jsx)(iP,{className:`shrink-0`,children:`Mastra (built-in)`}),e]}),(0,K.jsx)(oP,{className:`flex flex-col gap-4`,children:t})]})}function vAi({descriptor:e}){let{label:t,variant:n}=yAi(e);return(0,K.jsx)(eC,{variant:n,emphasis:`subtle`,indicator:`dot`,children:t})}function yAi(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 bAi({descriptor:e}){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{tone:`muted`,children:e.disabledReason===`config`?(0,K.jsxs)(K.Fragment,{children:[`The built-in MCP server is turned off because `,(0,K.jsx)(uX,{children:`server.mcp.enabled`}),` is`,` `,(0,K.jsx)(uX,{children:`false`}),`.`]}):(0,K.jsxs)(K.Fragment,{children:[`The built-in MCP server only runs under `,(0,K.jsx)(uX,{children:`mastra dev`}),` unless the server has auth. Configure `,(0,K.jsx)(uX,{children:`server.auth`}),`, or set `,(0,K.jsx)(uX,{children:`server.mcp.enabled`}),` to`,` `,(0,K.jsx)(uX,{children:`true`}),`.`]})}),(0,K.jsx)(wAi,{})]})}function xAi(){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(T,{tone:`muted`,children:[`The built-in MCP server is enabled, but it needs the `,(0,K.jsx)(uX,{children:`@mastra/mcp`}),` package. Install it and restart the server.`]}),(0,K.jsx)(pJ,{code:`npm install @mastra/mcp`,lang:`bash`,copyTooltip:`Copy install command`}),(0,K.jsx)(wAi,{})]})}function SAi({descriptor:e}){let t=`${(Y().options.baseUrl||window.location.origin).replace(/\/$/,``)}${e.path}`,n=pAi(t,{protectedServer:e.auth.type===`protected`}),[r,i]=(0,G.useState)(n[0].value),a=n.find(e=>e.value===r)??n[0];return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`muted`,children:`Endpoint`}),(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-3 rounded-lg bg-muted py-2 pr-2 pl-3`,children:[(0,K.jsx)(T,{as:`span`,font:`mono`,className:`min-w-0 break-all`,children:t}),(0,K.jsx)(gC,{tooltip:`Copy MCP endpoint URL`,content:t})]})]}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`muted`,children:`Toolsets`}),(0,K.jsxs)(`ul`,{className:`flex flex-wrap gap-2`,"aria-label":`Toolsets`,children:[e.toolsets.map(e=>(0,K.jsx)(`li`,{children:(0,K.jsx)(eC,{variant:`neutral`,emphasis:`subtle`,children:CAi(e)})},e)),e.readOnly&&(0,K.jsx)(`li`,{children:(0,K.jsx)(eC,{variant:`info`,emphasis:`subtle`,children:`Read-only`})})]})]}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`muted`,children:`Connect a client`}),(0,K.jsx)(pJ,{code:a.code,lang:a.lang,options:n.map(({value:e,label:t})=>({value:e,label:t})),value:r,onValueChange:i,selector:`tabs`,copyTooltip:`Copy snippet`}),(0,K.jsx)(T,{variant:`body-sm`,tone:`muted`,children:`Tools are listed per caller, so connect a client to see the tools your token can use.`})]})]})}function CAi(e){let t=e.replaceAll(`_`,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function wAi(){return(0,K.jsx)(`div`,{children:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:mAi,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(tP,{}),children:`MCP server docs`})})}var TAi={name:e=>e.name||e.id};function EAi({server:e,rowProps:t}){let{paths:n,Link:r}=sn(),i=Y().options.baseUrl,a=e.transports?.includes(`sse`)??!0?`sse`:`mcp`,o=i?`${i}/api/mcp/${e.id}/${a}`:``,{data:s}=QAt({selectedServer:e}),c=Object.values(s||{}),l=c.length,u=c.filter(e=>e.toolType===`agent`).length,d=c.filter(e=>e.toolType===`workflow`).length,f=dJ(e.name,50);return(0,K.jsxs)(Z.RowLink,{to:n.mcpServerLink(e.id),LinkComponent:r,...t,children:[(0,K.jsx)(Z.NameCell,{children:f}),(0,K.jsx)(Z.DescriptionCell,{children:o}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:u||``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:l||``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:d||``})]})}function DAi({mcpServers:e,isLoading:t,search:n=``,sort:r,onSortChange:i}){let a=(0,G.useMemo)(()=>{let t=n.toLowerCase();return IZ(e.filter(e=>e.name?.toLowerCase().includes(t)||e.id?.toLowerCase().includes(t)),r,TAi)},[e,n,r]),{containerRef:o,getRowProps:s}=PZ({count:a.length,global:!0});return t?(0,K.jsx)(DH,{columns:`auto 1fr auto auto auto`}):(0,K.jsxs)(Z,{columns:`auto 1fr auto auto auto`,scrollRef:o,children:[(0,K.jsxs)(Z.Top,{children:[i?(0,K.jsx)(Z.SortableTopCell,{sortKey:`name`,sort:r?.key===`name`?r.direction:void 0,onSortChange:i,children:`Name`}):(0,K.jsx)(Z.TopCell,{children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`URL`}),(0,K.jsx)(Z.TopCellSmart,{long:`Agents`,short:(0,K.jsx)(HN,{}),tooltip:`Agent tools`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Tools`,short:(0,K.jsx)(XN,{}),tooltip:`Tools`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Workflows`,short:(0,K.jsx)(ZS,{}),tooltip:`Workflow tools`,className:`text-center`})]}),a.length===0&&n?(0,K.jsx)(Z.NoMatch,{message:`No MCP Servers match your search`}):null,a.map((e,t)=>(0,K.jsx)(EAi,{server:e,rowProps:s(t)},e.id))]})}var OAi=()=>(0,K.jsx)(Jx,{titleSlot:`No MCP Servers yet`,descriptionSlot:(0,K.jsxs)(K.Fragment,{children:[`MCP servers are not configured yet. `,(0,K.jsx)(`br`,{}),`More information in the documentation.`]}),actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/docs/tools-mcp/mcp-overview`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(tP,{}),children:`MCP documentation`}),variant:`fill`}),I9=[eP(`/mcps`)],kAi=()=>{let{data:e=[],isLoading:t,error:n}=NN(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)();return n&&FN(n)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:I9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsx)(TH,{variant:`fill`})]}):n&&IN(n)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:I9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsx)(wH,{variant:`fill`,resource:`MCP servers`})]}):n?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:I9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load MCP servers`,descriptionSlot:n.message})]}):e.length===0&&!t?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:I9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-6`,children:[(0,K.jsx)(hAi,{}),(0,K.jsx)(OAi,{})]})]}):(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:I9}),actionRow:(0,K.jsx)(TK,{children:(0,K.jsx)(TK.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(MH,{...NH,onValueChange:i,label:`Search MCP servers`,placeholder:`Search by name`})})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`MCP Servers`}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-6`,children:[(0,K.jsx)(hAi,{}),(0,K.jsx)(DAi,{mcpServers:e,isLoading:t,search:r,sort:a,onSortChange:(e,t)=>o({key:t,direction:e})})]})]})};function AAi(){let[e,t]=Rv();return{eventName:e.get(`event`)??void 0,close:()=>t(e=>{let t=new URLSearchParams(e);return t.delete(`event`),t},{replace:!0})}}var jAi=e=>`?${new URLSearchParams({event:e}).toString()}`;function MAi(e,{enabled:t=!0}={}){let n=Y();return T_({queryKey:[`mcp-server-events`,e],queryFn:()=>n.getMcpServerEvents(e),enabled:t})}function NAi(e,t){let n=Y();return D_({mutationFn:r=>n.emitMcpServerEvent(e,t,r)})}function PAi(e){if(e instanceof qf&&typeof e.body==`object`&&e.body!==null){let t=`error`in e.body?e.body.error:void 0;if(typeof t==`string`&&t)return t}return`The event request failed.`}var FAi={push:`blue`,poll:`neutral`,webhook:`purple`};function IAi({delivery:e}){return(0,K.jsx)(`span`,{className:`flex flex-wrap items-center gap-1`,children:e.map(e=>(0,K.jsx)(eC,{size:`xs`,variant:FAi[e],emphasis:`subtle`,children:e},e))})}var LAi=0,RAi=()=>`feed-${LAi++}`;function zAi(e,t){return[...t,...e].slice(0,200)}function BAi(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:zAi(e.items,[{kind:`gap`,key:RAi()}])};case`occurrences`:{let n=[...t.occurrences].reverse().map(e=>({kind:`occurrence`,key:RAi(),occurrence:e}));return{...e,items:zAi(e.items,n)}}case`warning`:return{...e,warning:t.message};case`error`:return{...e,status:`error`,error:t.message}}}var VAi={status:`idle`,items:[]};function HAi(e,t){let n=Y(),[r,i]=(0,G.useReducer)(BAi,VAi),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:PAi(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:PAi(e)})}};return{...r,start:l,stop:c,pollOnce:u}}function L9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function UAi(e){return e.map(e=>JSON.stringify(e)).join(` | `)}function WAi(e){return e.map(R9).join(` | `)}function R9(e){return L9(e)?Array.isArray(e.enum)?UAi(e.enum):`const`in e?JSON.stringify(e.const):Array.isArray(e.anyOf)?WAi(e.anyOf):Array.isArray(e.oneOf)?WAi(e.oneOf):Array.isArray(e.type)?e.type.join(` | `):e.type===`array`?`${R9(e.items)}[]`:qAi(e)?`Record<string, ${R9(e.additionalProperties)}>`:typeof e.type==`string`?e.type:`unknown`:`unknown`}function GAi(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 KAi(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])=>GAi(e,r,n,t))}function qAi(e){return L9(e)&&e.type===`object`&&!L9(e.properties)&&L9(e.additionalProperties)}function JAi(e){return L9(e)&&(e.type===`object`||L9(e.properties))}var YAi=[`type`,`properties`,`items`,`enum`,`const`,`anyOf`,`oneOf`,`allOf`,`$ref`];function XAi(e){return!L9(e)||!YAi.some(t=>t in e)}function z9(e){return L9(e)?zO(e):J({})}function ZAi({inputSchema:e,onChange:t}){return XAi(e)?(0,K.jsx)(T,{tone:`muted`,children:`This event takes no arguments.`}):(0,K.jsx)(XM,{schema:z9(e),onValuesChange:e=>t(e??{})})}function QAi({occurrence:e}){return(0,K.jsx)(nP,{children:(0,K.jsxs)(DC,{children:[(0,K.jsxs)(OC,{className:`flex w-full cursor-pointer items-center gap-2 px-3 py-2 text-left`,children:[(0,K.jsx)(y,{direction:`right`,className:`size-4 shrink-0`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,className:`min-w-0 flex-1 truncate`,children:e.eventId}),e.eventId.startsWith(`mastra-test-`)&&(0,K.jsx)(eC,{size:`xs`,variant:`amber`,emphasis:`subtle`,children:`test`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,tone:`muted`,className:`shrink-0`,children:e.timestamp})]}),(0,K.jsx)(kC,{children:(0,K.jsx)(bw,{value:JSON.stringify(e.data,null,2),language:`json`,editable:!1,lineNumbers:!1,showCopyButton:!1,variant:`embedded`,"aria-label":`Event ${e.eventId} data`,className:`px-3 pb-3`})})]})})}var $Ai=`Gap: events may have been skipped`;function eji({items:e}){return e.length===0?(0,K.jsx)(Jx,{iconSlot:(0,K.jsx)(G6,{}),titleSlot:`No events yet`,descriptionSlot:`Start listening or poll to see occurrences here.`}):(0,K.jsx)(`ol`,{"aria-label":`Occurrences`,className:`grid grid-cols-1 gap-2`,children:e.map(e=>(0,K.jsx)(`li`,{children:e.kind===`gap`?(0,K.jsx)(Sk,{variant:`warning`,children:$Ai}):(0,K.jsx)(QAi,{occurrence:e.occurrence})},e.key))})}var tji={idle:`Not listening`,connecting:`Connecting…`,polling:`Polling…`,polled:`Polled`,stopped:`Stopped`,error:`Failed`};function nji({status:e,canStream:t}){if(e===`live`)return(0,K.jsx)(eC,{variant:`green`,indicator:`pulse`,size:`sm`,children:`Listening`});let n=e===`idle`&&!t?`Not polled yet`:tji[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 rji({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)(nji,{status:e,canStream:t}),n&&(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1`,children:[(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:`Cursor`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,className:`min-w-0 truncate`,children:n}),(0,K.jsx)(gC,{tooltip:`Copy cursor`,content:n})]})]})}function iji({serverId:e,event:t,onEmitted:n}){let{mutateAsync:r,isPending:i,isSuccess:a,error:o}=NAi(e,t.name);return(0,K.jsxs)(`section`,{"aria-label":`Send test event`,className:`grid grid-cols-1 gap-3`,children:[(0,K.jsx)(T,{as:`h3`,variant:`subheading`,children:`Send test event`}),(0,K.jsx)(XM,{schema:z9(t.payloadSchema),onSubmit:async e=>{try{await r(e??{}),n?.()}catch{}},isSubmitLoading:i,submitButtonLabel:`Send test event`}),a&&!o&&(0,K.jsx)(T,{tone:`muted`,children:`Test event sent.`}),o&&(0,K.jsx)(Sk,{variant:`destructive`,children:PAi(o)})]})}function aji({serverId:e,event:t,testEmit:n,canEmit:r}){let[i,a]=(0,G.useState)({}),o=HAi(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)(ZAi,{inputSchema:t.inputSchema,onChange:a}),(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,K.jsx)(rji,{status:o.status,canStream:s,cursor:o.cursor}),s&&c&&(0,K.jsx)(X,{onClick:o.stop,children:`Stop`}),s&&!c&&(0,K.jsx)(X,{variant:`primary`,onClick:()=>void o.start(i),children:`Start`}),!s&&(0,K.jsx)(X,{variant:`primary`,disabled:o.status===`polling`,onClick:()=>void o.pollOnce(i),children:`Poll once`})]}),o.error&&(0,K.jsx)(Sk,{variant:`destructive`,children:o.error}),o.warning&&(0,K.jsx)(Sk,{variant:`warning`,children:o.warning}),n&&t.emittable&&r&&(0,K.jsx)(iji,{serverId:e,event:t,onEmitted:s?void 0:()=>void o.pollOnce(i)}),(0,K.jsx)(eji,{items:o.items})]})}function oji({description:e}){let t=i$({collapsedHeight:140});return(0,K.jsx)(r$,{state:t,expandLabel:`Read more`,children:(0,K.jsx)(xY,{children:e})})}function sji({description:e,overview:t,playground:n,canRun:r}){return(0,K.jsx)(K.Fragment,{children:(0,K.jsxs)(gk,{defaultTab:`overview`,className:`grid flex-1 grid-rows-[auto_1fr] gap-4 overflow-visible`,children:[(0,K.jsxs)(hk,{variant:`pill`,size:`sm`,children:[(0,K.jsx)(_k,{value:`overview`,children:`Overview`}),(0,K.jsx)(_k,{value:`playground`,disabled:!r,disabledTooltip:`You don't have permission to execute tools.`,children:`Playground`})]}),(0,K.jsxs)(vk,{value:`overview`,flush:!0,className:`content-start gap-6`,children:[e&&(0,K.jsx)(nP,{className:`p-4`,children:(0,K.jsx)(oji,{description:e})}),t]}),(0,K.jsx)(vk,{value:`playground`,flush:!0,keepMounted:!0,className:`h-full`,children:r&&n})]})})}function cji(e){return(0,K.jsx)(C5n,{className:`min-h-control-md`,...e})}function lji(){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 uji({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 dji({field:e}){let t=!!e.description||e.defaultValue!==void 0;return(0,K.jsx)(_Z,{label:(0,K.jsxs)(T,{as:`span`,variant:`body-sm`,font:`mono`,tone:`ink`,children:[e.name,e.required&&(0,K.jsx)(lji,{})]}),description:t&&(0,K.jsx)(uji,{field:e}),children:(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,tone:`muted`,children:e.type})})}function fji({message:e}){return(0,K.jsx)(xZ,{children:e})}function pji({schema:e,emptyMessage:t,defaultsAreOptional:n}){if(XAi(e))return(0,K.jsx)(fji,{message:t});if(!JAi(e)||qAi(e))return(0,K.jsx)(_Z,{label:`Type`,children:(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,tone:`muted`,children:R9(e)})});let r=KAi(e,{defaultsAreOptional:n});return r.length===0?(0,K.jsx)(fji,{message:t}):r.map(e=>(0,K.jsx)(dji,{field:e},e.name))}function B9({title:e,...t}){return(0,K.jsxs)(yZ,{children:[(0,K.jsx)(cji,{children:(0,K.jsx)(bZ,{children:e})}),(0,K.jsx)(vZ,{children:(0,K.jsx)(pji,{...t})})]})}function mji({serverId:e,eventName:t}){let{canExecute:n,canEdit:r}=fS(),{data:i,isLoading:a}=MAi(e),o=i?.events.find(e=>e.name===t);return a?(0,K.jsx)(jQ.LoadingData,{}):!i||!o?(0,K.jsxs)(jQ.NoData,{children:[`This server has no event "`,t,`".`]}):(0,K.jsx)(sji,{description:o.description,overview:(0,K.jsxs)(`div`,{className:`grid grid-cols-1 gap-6`,children:[(0,K.jsx)(IAi,{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)(aji,{serverId:e,event:o,testEmit:i.testEmit,canEmit:r(`mcp`)})})}function hji({serverId:e}){let{eventName:t,close:n}=AAi();return(0,K.jsxs)(jQ,{open:t!==void 0,onClose:n,title:t??``,children:[(0,K.jsxs)(jQ.Header,{children:[(0,K.jsxs)(jQ.Heading,{children:[(0,K.jsx)(Dx,{size:`sm`,className:`text-muted-foreground`,children:(0,K.jsx)(G6,{})}),(0,K.jsx)(`span`,{className:`truncate`,children:t})]}),(0,K.jsx)(jQ.HeaderActions,{children:(0,K.jsx)(jQ.CloseButton,{icon:`x`,tooltip:`Close event`,onClick:n})})]}),(0,K.jsx)(jQ.Content,{className:`flex flex-col gap-4 px-3`,children:t&&(0,K.jsx)(mji,{serverId:e,eventName:t},t)})]})}var gji=new Set([`completed`,`failed`,`cancelled`]),_ji={working:`working`,input_required:`input required`,completed:`completed`,failed:`failed`,cancelled:`cancelled`},vji=e=>gji.has(e.status),yji=2e3,V9=e=>[`mcp-server-tasks`,e],bji=e=>!!e?.some(e=>!vji(e));function xji(e,t={}){let n=Y();return O_({queryKey:[...V9(e),`list`,t],queryFn:({pageParam:r})=>n.getMcpServerTasks(e,{...t,cursor:r}),initialPageParam:void 0,getNextPageParam:e=>e.nextCursor,refetchInterval:e=>e.state.data?.pages.some(e=>bji(e.tasks))?yji:!1})}function Sji(e,{enabled:t=!0}={}){let n=Y();return T_({queryKey:[...V9(e),`surfaces`],queryFn:()=>n.getMcpServerTasks(e,{limit:1}),select:e=>e.surfaces,enabled:t})}function Cji(e,t){let n=Y();return T_({queryKey:[...V9(e),`task`,t],queryFn:async()=>(await n.getMcpServerTasks(e,{key:t,limit:1})).tasks[0]??null,enabled:t!==void 0,refetchInterval:e=>e.state.data&&!vji(e.state.data)?yji:!1})}function wji(e){let t=Y();return D_({mutationFn:n=>t.findMcpServerTask(e,n)})}function Tji(e){let t=Y(),n=u_();return D_({mutationFn:n=>t.cancelMcpServerTask(e,n),onSettled:()=>n.invalidateQueries({queryKey:V9(e)})})}function Eji(e){let t=Y(),n=u_();return D_({mutationFn:({taskKey:n,inputResponses:r})=>t.answerMcpServerTaskInput(e,n,r),onSettled:()=>n.invalidateQueries({queryKey:V9(e)})})}function Dji(){let[e,t]=Rv();return{taskKey:e.get(`task`)??void 0,open:e=>t(t=>{let n=new URLSearchParams(t);return n.set(`task`,e),n},{replace:!0}),close:()=>t(e=>{let t=new URLSearchParams(e);return t.delete(`task`),t},{replace:!0})}}var Oji=(e,t=``)=>{let n=new URLSearchParams(t);return n.set(`task`,e),`?${n.toString()}`},kji=e=>`${e.slice(0,8)}…`,Aji=new Set([`working`,`input_required`,`completed`,`failed`,`cancelled`]);function jji(){let[e,t]=Rv(),n=e.get(`status`),r=e.get(`surface`),i=e.get(`client`);return{filters:{...n&&Aji.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 Mji=e=>`${e.slice(0,8)}…`,Nji={working:{variant:`info`,indicator:`pulse`},input_required:{variant:`warning`,indicator:`dot`},completed:{variant:`success`},failed:{variant:`destructive`},cancelled:{variant:`neutral`}};function Pji({status:e}){let{variant:t,indicator:n}=Nji[e];return(0,K.jsx)(eC,{size:`sm`,variant:t,emphasis:`subtle`,indicator:n,children:_ji[e]})}function Fji({serverId:e}){let{taskKey:t,close:n}=Dji(),{data:r,isSuccess:i}=Cji(e,t);return(0,K.jsxs)(jQ,{open:t!==void 0,onClose:n,title:r?.surface??`Task`,children:[(0,K.jsxs)(jQ.Header,{children:[(0,K.jsxs)(jQ.Heading,{children:[(0,K.jsx)(Dx,{size:`sm`,className:`text-muted-foreground`,children:(0,K.jsx)(l8n,{})}),(0,K.jsx)(`span`,{className:`truncate`,children:r?`${r.surface} task`:`Task`})]}),(0,K.jsx)(jQ.HeaderActions,{children:(0,K.jsx)(jQ.CloseButton,{icon:`x`,tooltip:`Close task`,onClick:n})})]}),(0,K.jsx)(jQ.Content,{className:`flex flex-col gap-4 px-3`,children:r?(0,K.jsx)(Iji,{serverId:e,task:r},r.taskKey):i&&(0,K.jsx)(T,{tone:`muted`,children:`This task is no longer listed.`})})]})}function Iji({serverId:e,task:t}){let n=Tji(e),{canEdit:r,isLoading:i}=fS(),a=!i&&r(`mcp`),o=Object.entries(t.inputRequests??{});return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(V4,{children:[(0,K.jsx)(V4.Key,{children:`Status`}),(0,K.jsx)(V4.Value,{children:(0,K.jsx)(Pji,{status:t.status})}),t.statusMessage&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(V4.Key,{children:`Message`}),(0,K.jsx)(V4.Value,{children:t.statusMessage})]}),(0,K.jsx)(V4.Key,{children:`Created`}),(0,K.jsx)(V4.Value,{children:(0,K.jsx)(Dk,{value:t.createdAt})}),(0,K.jsx)(V4.Key,{children:`Updated`}),(0,K.jsx)(V4.Value,{children:(0,K.jsx)(Dk,{value:t.lastUpdatedAt})}),(0,K.jsx)(V4.Key,{children:`Expires`}),(0,K.jsx)(V4.Value,{children:t.expiresAt?(0,K.jsx)(Dk,{value:t.expiresAt}):`never`}),(0,K.jsx)(V4.Key,{children:`Task key`}),(0,K.jsx)(V4.ValueWithCopyBtn,{copyValue:t.taskKey,copyTooltip:`Copy task key`,children:kji(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:kji(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)(Rji,{serverId:e,taskKey:t.taskKey,inputKey:n,request:r,canAnswer:a},n)),!vji(t)&&!i&&!a&&(0,K.jsx)(T,{tone:`muted`,variant:`caption`,children:`Cancelling or answering a task needs the mcp:write permission.`}),!vji(t)&&a&&(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,K.jsx)(X,{variant:`destructive-ghost`,className:`self-start`,disabled:n.isPending,onClick:()=>n.mutate(t.taskKey),children:`Cancel task`}),n.error&&(0,K.jsx)(Sk,{variant:`destructive`,children:Bji(n.error)})]}),t.result&&(0,K.jsx)(zji,{label:`Result`,value:t.result}),t.error&&(0,K.jsx)(zji,{label:`Error`,value:t.error})]})}var Lji=J({message:q().optional(),requestedSchema:Ad(q(),hd())});function Rji({serverId:e,taskKey:t,inputKey:n,request:r,canAnswer:i}){let a=Eji(e),o=r.method===`elicitation/create`?Lji.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)(zji,{label:`Request`,value:r})]}):o?.success?(0,K.jsxs)(K.Fragment,{children:[o.data.message&&(0,K.jsx)(T,{children:o.data.message}),(0,K.jsx)(XM,{schema:z9(o.data.requestedSchema),onSubmit:e=>s({action:`accept`,content:e??{}}),isSubmitLoading:a.isPending,submitButtonLabel:`Accept`,submitButtonVariant:`primary`,submitActions:(0,K.jsx)(X,{type:`button`,disabled:a.isPending,onClick:()=>s({action:`decline`}),children:`Decline`})})]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(T,{tone:`muted`,children:[`Studio can't answer a `,r.method,` request; the client that started the task has to.`]}),(0,K.jsx)(zji,{label:`Request`,value:r})]}),a.error&&(0,K.jsx)(Sk,{variant:`destructive`,children:Bji(a.error)})]})}function zji({label:e,value:t}){return(0,K.jsxs)(`section`,{className:`flex flex-col gap-2`,children:[(0,K.jsx)(T,{as:`h3`,variant:`subheading`,children:e}),(0,K.jsx)(bw,{value:JSON.stringify(t,null,2),language:`json`,editable:!1,lineNumbers:!1,"aria-label":`Task ${e.toLowerCase()}`})]})}function Bji(e){let t=PAi(e);return t===`Task not found`?`The task is no longer waiting for this; the list has been refreshed.`:t}function Vji(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 Hji(e){return L9(e)&&e.status===`suspended`}function Uji(e){return e<1e3?`${Math.round(e)} ms`:`${(e/1e3).toFixed(2)} s`}function Wji(e){return e===void 0?`undefined`:JSON.stringify(e,null,2)}function Gji(e){return e.status===`error`?e.error:Wji(e.output)}function Kji({status:e,output:t,error:n},r){if(r!==void 0){if(e===`success`)return{status:`success`,output:t,durationMs:r};if(e===`error`)return{status:`error`,error:qji(n),durationMs:r}}}function qji(e){return e instanceof Error?JSON.stringify({error:e.message},null,2):JSON.stringify({error:String(e)},null,2)}function Jji({zodInputSchema:e,isRunning:t,onRun:n,requestContextEntityType:r,requestContextEntityId:i}){let a=!PTt(e),[o,s]=(0,G.useState)({view:`form`,value:void 0}),c=(0,G.useRef)(void 0),[l,u]=(0,G.useState)([]);function d(t){if(t===o.view)return;if(u([]),o.view===`form`)return s({view:`json`,value:JSON.stringify(c.current??{},null,2)});let n=YTt(o.value);if(!n.ok)return u([n.error]);let r=XTt(e,n.value);if(r)return u([r]);c.current=n.value,s({view:`form`,value:n.value})}function f(t){let r=ZTt(e,t);r.ok?n(r.value):u(r.errors)}let p={isSubmitLoading:t,submitButtonLabel:`Run`,submitButtonIcon:(0,K.jsx)(DT,{}),submitButtonVariant:`primary`};return(0,K.jsxs)(yZ,{children:[(0,K.jsx)(cji,{action:(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(mMt,{entityType:r,entityId:i}),(0,K.jsx)(gk,{defaultTab:`form`,value:o.view,onValueChange:d,children:(0,K.jsxs)(hk,{size:`md`,children:[(0,K.jsxs)(_k,{value:`form`,disabled:t,children:[(0,K.jsx)(Dx,{size:`sm`,children:(0,K.jsx)(pgt,{})}),`Form`]}),(0,K.jsxs)(_k,{value:`json`,disabled:t,children:[(0,K.jsx)(Dx,{size:`sm`,children:(0,K.jsx)(JS,{})}),`JSON`]})]})})]}),children:(0,K.jsx)(bZ,{children:`Request`})}),(0,K.jsx)(vZ,{children:(0,K.jsx)(`div`,{className:`p-4`,children:o.view===`json`?(0,K.jsxs)(`div`,{className:`grid gap-4`,children:[(0,K.jsxs)(ak,{invalid:l.length>0,children:[(0,K.jsx)(bw,{variant:`embedded`,language:`json`,value:o.value,onChange:e=>{s({view:`json`,value:e}),u([])},editable:!t,"aria-label":`Request JSON`}),l.length>0&&(0,K.jsx)(lk,{children:l.map(e=>(0,K.jsx)(`span`,{className:`block`,children:e},e))})]}),(0,K.jsx)(kk,{...p,onSubmit:()=>f(o.value)})]}):(0,K.jsx)(XM,{...p,schema:e,defaultValues:o.value,onValuesChange:e=>{c.current=e},onSubmit:n,className:`gap-0`,children:!a&&(0,K.jsx)(T,{variant:`body-sm`,tone:`muted`,className:`pb-4`,children:`This tool takes no input. Run it as is.`})})})})]})}var Yji=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 Xji({isRunning:e,lastRun:t}){return e?(0,K.jsx)(Jx,{iconSlot:(0,K.jsx)(It,{}),titleSlot:`Running…`,descriptionSlot:`Waiting for the tool to respond.`}):t?t.status===`error`?(0,K.jsx)(uC,{code:Gji(t),className:`overflow-x-auto p-4 text-caption whitespace-pre`}):(0,K.jsx)(bw,{value:Gji(t),language:`json`,editable:!1,lineNumbers:!1,showCopyButton:!1,variant:`embedded`,"aria-label":`Tool response`,className:`p-4`}):(0,K.jsx)(Jx,{iconSlot:(0,K.jsx)(Yji,{}),titleSlot:`No response yet`,descriptionSlot:`Run the tool to see its output here.`})}function Zji({run:e}){return(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[e.status===`success`?(0,K.jsx)(eC,{variant:`success`,emphasis:`subtle`,indicator:`dot`,children:`Success`}):(0,K.jsx)(eC,{variant:`destructive`,emphasis:`subtle`,indicator:`dot`,children:`Error`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,tone:`muted`,children:Uji(e.durationMs)}),(0,K.jsx)(gC,{content:Gji(e),copyMessage:`Response copied`,tooltip:`Copy response`,size:`icon-sm`})]})}function Qji({isRunning:e,lastRun:t}){return(0,K.jsxs)(yZ,{className:`h-full`,children:[(0,K.jsx)(cji,{action:!e&&t&&(0,K.jsx)(Zji,{run:t}),children:(0,K.jsx)(bZ,{children:`Response`})}),(0,K.jsx)(vZ,{className:c(`grid min-h-48 flex-1`,e||!t?`content-center`:`content-start`),children:(0,K.jsx)(Xji,{isRunning:e,lastRun:t})})]})}function $ji({zodInputSchema:e,execution:t,requestContextEntityType:n,requestContextEntityId:r}){let[i]=HS(n,r),[a,o]=(0,G.useState)(),s=async e=>{let n=performance.now();await t.execute(e,i).catch(()=>void 0),o(performance.now()-n)},c=t.status===`pending`;return(0,K.jsxs)(`div`,{className:`grid h-full grid-rows-[auto_1fr] gap-6`,children:[(0,K.jsx)(Jji,{zodInputSchema:e,isRunning:c,onRun:s,requestContextEntityType:n,requestContextEntityId:r}),(0,K.jsx)(Qji,{isRunning:c,lastRun:Kji(t,a)})]})}function eMi({serverId:e,tool:t}){let n=hmr(e),{mutateAsync:r,status:i,data:a,error:o}=ZAt({serverId:e,toolId:t.name}),{data:s}=JAt({serverId:e,appResourceUri:Vji(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)(uPr,{html:s,toolName:t.name,onToolCall:n}),Hji(a)&&(0,K.jsxs)(Sk,{variant:`warning`,children:[`This tool asked for more input, which Studio cannot provide. The suspend payload below shows what it needs. Call it from an MCP client with an `,(0,K.jsx)(uX,{children:`inputRequests`}),` handler to finish the request.`]}),(0,K.jsx)($ji,{zodInputSchema:c,execution:l,requestContextEntityType:`mcp-tool`,requestContextEntityId:`${e}:${t.name}`})]})}var tMi=(0,G.createContext)(void 0),nMi=tMi.Provider;function rMi(){let e=(0,G.useContext)(tMi);if(e===void 0)throw Error(`useOpenToolId must be used inside ToolDrawer`);return e}function iMi({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 aMi({serverId:e}){let t=rMi(),{canExecute:n}=fS(),{data:r,isLoading:i}=XAt({serverId:e,toolId:t});return i?(0,K.jsx)(jQ.LoadingData,{}):r?(0,K.jsx)(sji,{description:r.description,overview:(0,K.jsx)(iMi,{inputSchema:r.inputSchema}),canRun:n(`tools`),playground:(0,K.jsx)(eMi,{serverId:e,tool:r})}):(0,K.jsxs)(jQ.NoData,{children:[`This server has no tool "`,t,`".`]})}var oMi=`auto 1fr auto`;function sMi({server:e}){let{data:t,isLoading:n,isError:r}=MAi(e.id),i=t?.events??[],{Link:a}=sn(),{containerRef:o,getRowProps:s}=PZ({count:i.length});return(0,K.jsxs)(`section`,{className:`flex flex-col gap-3`,children:[(0,K.jsx)(T,{as:`h2`,variant:`heading`,children:`Events`}),n&&(0,K.jsx)(DH,{columns:oMi}),r&&(0,K.jsx)(Sk,{variant:`destructive`,children:`Could not load this server's events.`}),t&&(0,K.jsxs)(Z,{columns:oMi,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}${jAi(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)(IAi,{delivery:t.delivery})})]},t.name))]})]})}var cMi=`minmax(0,1fr) auto auto auto auto auto auto auto`,lMi={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.`},uMi=[{id:`is`,label:`is`}],dMi=Object.entries(_ji).map(([e,t])=>({value:e,label:t})),fMi=e=>e.stopPropagation(),pMi=e=>e.clientLabel??Mji(e.principalKey),mMi=e=>[`status`,`surface`,`client`].flatMap(t=>{let n=e[t];return n?[{id:t,fieldId:t,operatorId:`is`,value:n}]:[]}),hMi=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 gMi({server:e}){let{filters:t,setFilters:n}=jji(),{data:r,isLoading:i,isError:a,hasNextPage:o,fetchNextPage:s,isFetchingNextPage:c}=xji(e.id,t),{data:l=[]}=Sji(e.id),u=(0,G.useMemo)(()=>r?.pages.flatMap(e=>e.tasks)??[],[r]),d=r?.pages[0]?.unavailable,{containerRef:f,getRowProps:p}=PZ({count:u.length}),m=mMi(t).length>0,h=(0,G.useMemo)(()=>{let e=new Map(u.map(e=>[e.principalKey,pMi(e)]));return t.client&&!e.has(t.client)&&e.set(t.client,Mji(t.client)),[...e]},[u,t.client]),g=(0,G.useMemo)(()=>[{id:`status`,label:`Status`,icon:EX,color:sP(`orange`),operators:[`is`],strict:!0,suggestions:dMi},{id:`surface`,label:`Surface`,icon:YS,color:sP(`blue`),operators:[`is`],strict:!0,suggestions:l.map(e=>({value:e.name}))},{id:`client`,label:`Client`,icon:sYr,color:sP(`purple`),operators:[`is`],suggestions:h.map(([e,t])=>({value:e,label:t}))}],[l,h]);return(0,K.jsxs)(`section`,{"aria-label":`Tasks`,className:`flex flex-col gap-3`,children:[(0,K.jsx)(T,{as:`h2`,variant:`heading`,children:`Tasks`}),a&&(0,K.jsx)(Sk,{variant:`destructive`,children:`Could not load this server's tasks.`}),d&&(0,K.jsx)(Sk,{variant:`info`,children:lMi[d]}),!d&&(0,K.jsxs)(TK,{children:[(0,K.jsx)(TK.Start,{children:(0,K.jsxs)(m5,{fields:g,operators:uMi,value:mMi(t),onValueChange:e=>n(hMi(e)),createItemId:e=>e,"aria-label":`Task filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(m5.Chips,{}),(0,K.jsx)(m5.Input,{placeholder:`Filter tasks`})]})}),(0,K.jsx)(TK.End,{children:(0,K.jsx)(vMi,{serverId:e.id})})]}),i&&(0,K.jsx)(DH,{columns:cMi}),r&&!d&&(0,K.jsxs)(Z,{columns:cMi,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)(_Mi,{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 _Mi({serverId:e,task:t,rowProps:n,onFilterClient:r}){let{Link:i}=sn(),[a]=Rv(),o=(0,G.useRef)(null);return(0,K.jsxs)(Z.RowWrapper,{...n,onSelectRow:()=>o.current?.click(),children:[(0,K.jsxs)(Z.RowLink,{ref:o,colEnd:-2,to:`/mcps/${e}${Oji(t.taskKey,a)}`,LinkComponent:i,tabIndex:-1,onClick:fMi,"aria-label":`${t.surface} task ${kji(t.taskKey)}`,children:[(0,K.jsx)(Z.NameCell,{children:t.surface}),(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(Pji,{status:t.status})}),(0,K.jsx)(Z.CreatedCell,{timestamp:t.createdAt,preset:`day-time-seconds`}),(0,K.jsx)(Z.Cell,{className:`text-muted-foreground`,children:(0,K.jsx)(Dk,{value:t.lastUpdatedAt})}),(0,K.jsx)(Z.Cell,{className:`text-muted-foreground`,children:t.expiresAt?(0,K.jsx)(Dk,{value:t.expiresAt}):`never`}),(0,K.jsx)(Z.TextCell,{children:Object.keys(t.inputRequests??{}).length||`—`}),(0,K.jsx)(Z.TextCell,{font:`mono`,className:`text-muted-foreground`,children:kji(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 ${pMi(t)}`,onClick:e=>{e.stopPropagation(),r()},children:pMi(t)})})]})}function vMi({serverId:e}){let[t,n]=(0,G.useState)(``),r=wji(e),{open:i}=Dji();return(0,K.jsxs)(`form`,{onSubmit:e=>{e.preventDefault();let a=t.trim();a&&r.mutate(a,{onSuccess:({task:e})=>{n(``),i(e.taskKey)}})},className:`flex items-center gap-2`,"aria-label":`Find a task by MCP task id`,children:[(0,K.jsx)(Jj,{size:`sm`,value:t,onChange:e=>{n(e.target.value),r.reset()},placeholder:`MCP task id`,"aria-label":`MCP task id`,"aria-invalid":r.isError||void 0,className:`w-56 font-mono`}),(0,K.jsx)(X,{type:`submit`,size:`sm`,variant:`default`,disabled:!t.trim()||r.isPending,children:`Find`}),r.isError&&(0,K.jsx)(T,{variant:`caption`,role:`status`,className:`text-destructive-foreground`,children:`No task with that id.`})]})}var yMi={agent:HN,workflow:ZS,tool:XN},bMi=`auto minmax(0, 1fr) auto`,xMi=`auto minmax(0, 1fr) auto auto`,SMi={tool:`Tool`,agent:`Agent`,workflow:`Workflow`};function CMi(e){return e in yMi}function wMi({type:e}){let t=CMi(e)?e:`tool`,n=yMi[t],r=SMi[t];return(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{asChild:!0,children:(0,K.jsx)(`span`,{"aria-label":t,className:`inline-flex text-muted-foreground [&>svg]:size-icon-md`,children:(0,K.jsx)(n,{})})}),(0,K.jsx)(Tx,{children:r})]})}var TMi=J({ui:J({resourceUri:q().optional()}).optional(),"ui/resourceUri":q().optional()});function EMi(e){let t=TMi.safeParse(e);return t.success?!!(t.data.ui?.resourceUri?.startsWith(`ui://`)||t.data[`ui/resourceUri`]?.startsWith(`ui://`)):!1}function DMi({surface:e}){return e?(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{asChild:!0,children:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,K.jsx)(eC,{size:`xs`,variant:e.mode===`always`?`info`:`neutral`,emphasis:`subtle`,children:e.mode}),e.required&&(0,K.jsx)(eC,{size:`xs`,variant:`warning`,emphasis:`subtle`,children:`required`}),e.recover&&(0,K.jsx)(eC,{size:`xs`,variant:`neutral`,emphasis:`subtle`,children:`recover`})]})}),(0,K.jsxs)(Tx,{children:[e.mode===`always`?`Always runs as a task`:`Runs as a task when the client asks for one`,e.required?`; clients without task support are refused`:``,e.recover?`; resumed after a server restart`:``]})]}):null}function OMi({server:e}){let[t,n]=(0,G.useState)(``),{data:r={},isLoading:i}=QAt({selectedServer:e}),{Link:a,paths:o}=sn(),{data:s}=Sji(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?xMi:bMi,d=(0,G.useMemo)(()=>{let e=t.toLowerCase();return Object.values(r).filter(t=>t.name.toLowerCase().includes(e)||t.description?.toLowerCase().includes(e))},[r,t]),{containerRef:f,getRowProps:p}=PZ({count:d.length});return(0,K.jsxs)(`section`,{className:`flex flex-col gap-3`,children:[(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,K.jsx)(T,{as:`h2`,variant:`heading`,children:`Available tools`}),(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(MH,{size:`sm`,debounceMs:300,className:`max-w-120`,onValueChange:n,label:`Search tools`,placeholder:`Search by name`})})]}),i?(0,K.jsx)(DH,{columns:u}):(0,K.jsxs)(Z,{columns:u,fit:`container`,scrollRef:f,children:[(0,K.jsxs)(Z.Top,{children:[(0,K.jsx)(Z.TopCell,{children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`Description`}),(0,K.jsx)(Z.TopCell,{className:`justify-center text-center`,children:`Type`}),l&&(0,K.jsx)(Z.TopCell,{children:`Task`})]}),d.length===0&&t?(0,K.jsx)(Z.NoMatch,{message:`No tools match your search`}):null,d.map((t,n)=>(0,K.jsxs)(Z.RowLink,{to:o.mcpServerToolLink(e.id,t.name),LinkComponent:a,...p(n),children:[(0,K.jsx)(Z.NameCell,{children:(0,K.jsxs)(`span`,{className:`flex items-center gap-2`,children:[t.name,EMi(t._meta)&&(0,K.jsx)(eC,{size:`xs`,children:`App`})]})}),(0,K.jsx)(Z.DescriptionCell,{children:t.description}),(0,K.jsx)(Z.TextCell,{className:`justify-center text-center`,children:(0,K.jsx)(wMi,{type:t.toolType??`tool`})}),l&&(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(DMi,{surface:c.get(t.name)})})]},t.name))]})]})}var kMi=({isLoading:e,server:t})=>{let[{sseUrl:n,httpStreamUrl:r},i]=(0,G.useState)({sseUrl:``,httpStreamUrl:``});if((0,G.useEffect)(()=>{if(!t)return;let e=window.MASTRA_SERVER_HOST,n=window.MASTRA_SERVER_PORT,r=null;e&&n&&(r=`http://${e}:${n}`);let a=r||`http://localhost:4111`,o=`${a}/api/mcp/${t.id}/sse`,s=`${a}/api/mcp/${t.id}/mcp`;i({sseUrl:o,httpStreamUrl:s})},[t]),e)return null;if(!t)return(0,K.jsx)(T,{as:`h1`,variant:`heading`,tone:`muted`,className:`py-20 text-center`,children:`Server not found`});let a=t.transports?.includes(`sse`)??!0,o=`npx -y mcp-remote ${a?n:r}`,s=[{value:`http`,label:`HTTP`,description:`Use for stateless HTTP transport with streamable responses.`,content:r,tooltip:`Copy HTTP Stream URL`},...a?[{value:`sse`,label:`SSE`,description:`Use for real-time communication via SSE.`,content:n,tooltip:`Copy SSE URL`}]:[],{value:`cli`,label:`CLI`,description:`Use for local command-line access via npx and mcp-remote.`,content:o,tooltip:`Copy command line config`}];return(0,K.jsxs)(`div`,{className:`flex flex-col gap-6 pt-4`,children:[(0,K.jsx)(nP,{children:(0,K.jsxs)(gk,{defaultTab:`http`,children:[(0,K.jsxs)(rP,{className:`flex-row items-center justify-between gap-3 space-y-0 border-b border-border`,children:[(0,K.jsx)(iP,{className:`shrink-0`,children:`Connect`}),(0,K.jsx)(`div`,{className:`min-w-0`,children:(0,K.jsx)(hk,{variant:`pill-ghost`,size:`sm`,children:s.map(e=>(0,K.jsx)(_k,{value:e.value,children:e.label},e.value))})})]}),s.map(e=>(0,K.jsx)(vk,{value:e.value,flush:!0,children:(0,K.jsxs)(oP,{className:`flex flex-col gap-3`,children:[(0,K.jsx)(T,{tone:`muted`,children:e.description}),(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-3 rounded-lg bg-muted py-2 pr-2 pl-3`,children:[(0,K.jsx)(T,{as:`span`,font:`mono`,className:`min-w-0 break-all`,children:e.content}),(0,K.jsx)(gC,{tooltip:e.tooltip,content:e.content})]})]})},e.value))]})}),(0,K.jsx)(OMi,{server:t}),t.tasks_capability&&(0,K.jsx)(gMi,{server:t}),t.events_capability&&(0,K.jsx)(sMi,{server:t})]})};function AMi(){let[e,t]=Rv();return{toolId:e.get(`tool`)??void 0,close:()=>t(e=>{let t=new URLSearchParams(e);return t.delete(`tool`),t},{replace:!0})}}function jMi({children:e}){let{toolId:t,close:n}=AMi();return(0,K.jsxs)(jQ,{open:t!==void 0,onClose:n,title:t??``,children:[(0,K.jsxs)(jQ.Header,{children:[(0,K.jsxs)(jQ.Heading,{children:[(0,K.jsx)(Dx,{size:`sm`,className:`text-muted-foreground`,children:(0,K.jsx)(XN,{})}),(0,K.jsx)(`span`,{className:`truncate`,children:t})]}),(0,K.jsx)(jQ.HeaderActions,{children:(0,K.jsx)(jQ.CloseButton,{icon:`x`,tooltip:`Close tool`,onClick:n})})]}),(0,K.jsx)(jQ.Content,{className:`flex flex-col gap-4 px-3`,children:t&&(0,K.jsx)(nMi,{value:t,children:e},t)})]})}var MMi=()=>{let{serverId:e}=kv(),t=[eP(`/mcps`),nMt],{data:n=[],isLoading:r}=NN(),i=n.find(t=>t.id===e),a=i?.transports?.includes(`sse`)??!0,o=r||i?(0,K.jsxs)(DK,{children:[(0,K.jsx)(DK.Title,{isLoading:r,children:i?.name}),i&&(0,K.jsx)(DK.Meta,{beside:!0,children:(0,K.jsxs)(eC,{size:`sm`,children:[`v`,i.version_detail.version]})}),i&&(0,K.jsx)(DK.Description,{children:a?`This MCP server can be accessed through multiple transport methods. Choose the one that best fits your use case.`:`This MCP server speaks Streamable HTTP only (protocol 2026-07-28).`})]}):void 0;return(0,K.jsxs)(RS,{variant:`narrow`,breadcrumbs:(0,K.jsx)(vN,{crumbs:t}),header:o,children:[(0,K.jsx)(kMi,{isLoading:r,server:i}),e&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(jMi,{children:(0,K.jsx)(aMi,{serverId:e})}),(0,K.jsx)(hji,{serverId:e}),(0,K.jsx)(Fji,{serverId:e})]})]})};function NMi(){let{data:e,isLoading:t}=i5();if(t)return`loading`;let n=e?.capabilities;return n?.traceAggregate===!0&&n.spanAggregate===!0?`unified`:`legacy`}var H9=[eP(`/metrics`)],PMi=e=>e.fieldId===c3r;function FMi({fields:e}){let{filterTokens:t,setFilterTokens:n}=$7(),r=[p5,...mvi(t)];return(0,K.jsxs)(m5,{fields:[l3r,...e],operators:svi,value:r,onValueChange:e=>n(hvi(e.filter(e=>!PMi(e)))),createItemId:e=>e,"aria-label":`Metrics filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(m5.Chips,{renderChip:e=>PMi(e)?(0,K.jsx)(Qvi,{}):(0,K.jsx)(m5.Chip,{item:e})}),(0,K.jsx)(m5.Input,{placeholder:`Filter metrics`})]})}function IMi({children:e,filterFields:t}){return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:H9}),actionRow:(0,K.jsx)(TK,{children:(0,K.jsx)(TK.Start,{children:(0,K.jsx)(FMi,{fields:t})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),e]})}function LMi({error:e}){return FN(e)?(0,K.jsx)(TH,{}):IN(e)?(0,K.jsx)(wH,{resource:`metrics`}):(0,K.jsx)(Jx,{tone:`error`,titleSlot:`Failed to load storage capabilities`,descriptionSlot:e.message})}var RMi=pvi({availableTags:[],availableEntityNames:[],availableServiceNames:[],availableEnvironments:[]});function zMi({children:e}){let{supportsMetrics:t,isLoading:n,error:r}=S7();return n?(0,K.jsx)(IMi,{filterFields:RMi,children:(0,K.jsxs)(`div`,{className:`flex h-full items-center justify-center gap-2`,children:[(0,K.jsx)(It,{"aria-label":`Loading storage capabilities`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:`Loading storage capabilities`})]})}):r?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:H9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),(0,K.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:(0,K.jsx)(LMi,{error:r})})]}):t?e:(0,K.jsx)(IMi,{filterFields:RMi,children:(0,K.jsx)(Jx,{titleSlot:`Metrics are not available with your current storage`,descriptionSlot:`Metrics require ClickHouse, DuckDB, Postgres v-next, Spanner, or in-memory storage for observability. Other relational databases (LibSQL, MSSQL) and document stores (MongoDB) do not support metrics collection. To enable metrics on an existing project, switch the observability storage in the Mastra configuration.`,actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/docs/observability/metrics/overview`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(tP,{}),children:`Metrics documentation`}),variant:`fill`})})}function BMi(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 VMi(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=BMi(i);s&&e.set(t,s)}function U9(e,t,n){typeof n==`string`&&n.length>0&&e.set(t,n)}function HMi(e,t,n){if(Array.isArray(n)&&n.length!==0)for(let r of n)r&&e.append(t,r)}function UMi({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 WMi({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:i=`/traces`}){let a=new URLSearchParams;a.set(_8,`branches`),VMi(a,v8,y8,b8,e,t,r.window);let o=r.rootEntityType??n.rootEntityType;if(o&&a.set(h8,o),r.status&&a.set(g8,r.status),U9(a,S8.entityName,r.entityName??n.entityName),U9(a,S8.threadId,r.threadId??n.threadId),U9(a,S8.resourceId,r.resourceId??n.resourceId),U9(a,S8.runId,n.runId),U9(a,S8.sessionId,r.sessionId??n.sessionId),U9(a,S8.requestId,n.requestId),U9(a,S8.userId,r.userId??n.userId),U9(a,S8.organizationId,n.organizationId),U9(a,S8.experimentId,n.experimentId),U9(a,S8.serviceName,n.serviceName),U9(a,S8.environment,r.environment??n.environment),HMi(a,S8.tags,n.tags),r.span&&a.append(I8,JSON.stringify(UMi(r.span))),r.model){let e={id:`metrics-model`,logic:`and`,nodes:[{id:`model`,fieldId:`spans.model`,value:r.model}]};a.append(I8,JSON.stringify(e))}let s=a.toString();return s?`${i}?${s}`:i}function GMi({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:i=`/logs`}){let a=new URLSearchParams;VMi(a,p7,m7,h7,e,t,r.window);let o=r.rootEntityType??n.rootEntityType;o&&a.set(f7,o),U9(a,g7.entityName,r.entityName??n.entityName),U9(a,g7.threadId,r.threadId??n.threadId),U9(a,g7.resourceId,r.resourceId??n.resourceId),U9(a,g7.runId,n.runId),U9(a,g7.sessionId,n.sessionId),U9(a,g7.requestId,n.requestId),U9(a,g7.userId,n.userId),U9(a,g7.organizationId,n.organizationId),U9(a,g7.experimentId,n.experimentId),U9(a,g7.serviceName,n.serviceName),U9(a,g7.environment,n.environment),HMi(a,g7.tags,n.tags),r.status===`error`&&a.append(g7.level,`error`);let s=a.toString();return s?`${i}?${s}`:i}function KMi(){let{datePreset:e,customRange:t,dimensionalFilter:n}=$7(),r=Ov(),i={preset:e,customRange:t,dashboardFilter:n};return{openTraces:(e={})=>{r(WMi({...i,scope:e}))},openLogs:(e={})=>{r(GMi({...i,scope:e}))}}}var qMi=`period`,JMi=`dateFrom`,YMi=`dateTo`;function XMi(){let[e,t]=Rv(),n=e.get(qMi),r=Vvi(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(JMi)),i=t(e.get(YMi));if(n||i)return{from:n,to:i}},[r,e.toString()]),a=(0,G.useMemo)(()=>gvi(e),[e.toString()]),o=(0,G.useCallback)(e=>{t(t=>{let n=new URLSearchParams(t);return e===`24h`?n.delete(qMi):n.set(qMi,e),e!==`custom`&&(n.delete(JMi),n.delete(YMi)),n},{replace:!0})},[t]),s=(0,G.useCallback)(e=>{t(t=>{let n=new URLSearchParams(t);return e?.from?n.set(JMi,e.from.toISOString()):n.delete(JMi),e?.to?n.set(YMi,e.to.toISOString()):n.delete(YMi),n},{replace:!0})},[t]),c=(0,G.useCallback)(e=>{t(t=>{let n=new URLSearchParams(t);return vvi(n,e),rvi(n),n},{replace:!0})},[t]),l=(0,G.useRef)(!1);return(0,G.useEffect)(()=>{if(l.current||(l.current=!0,avi(e)))return;let n=ivi();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)(Kvi,{preset:r,filterTokens:a,onPresetChange:o,onFilterTokensChange:c,customRange:i,onCustomRangeChange:s,children:(0,K.jsx)(zMi,{children:(0,K.jsx)(ZMi,{})})})}function ZMi(){let{error:e}=Fvi(c9()),{isInMemory:t}=S7(),{data:n}=jYr(),{data:r}=t8(),{data:i}=kYr(),{data:a}=n8(),o=pvi({availableTags:n??[],availableEntityNames:r??[],availableServiceNames:i??[],availableEnvironments:a??[]});return e&&FN(e)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:H9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),(0,K.jsx)(TH,{variant:`fill`})]}):e&&IN(e)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:H9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),(0,K.jsx)(wH,{variant:`fill`,resource:`metrics`})]}):e?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:H9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Metrics`}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load metrics`,descriptionSlot:e.message})]}):(0,K.jsx)(IMi,{filterFields:o,children:(0,K.jsxs)(`div`,{className:`grid content-start gap-4`,children:[t&&(0,K.jsx)(Sk,{variant:`info`,title:`Metrics are not persisted`,children:(0,K.jsx)(Sk.Message,{children:`This project uses in-memory storage for observability. Metrics will be lost on every server restart. For persistent metrics, switch the observability storage to ClickHouse, DuckDB, Postgres v-next, or Spanner.`})}),(0,K.jsx)(QMi,{})]})})}function QMi(){let{openTraces:e,openLogs:t}=KMi(),n=Dp.AGENT,r=NMi(),i=(0,K.jsx)(Jyi,{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)(rbi,{onViewTraces:t=>e({rootEntityType:t}),onTimeRangeClick:t=>e({window:t})}),o=(0,K.jsx)(qbi,{onViewTraces:()=>e(),onAgentClick:t=>e({rootEntityType:n,entityName:t}),onModelClick:t=>e({model:t}),onThreadClick:t=>e({threadId:t})}),s=(0,K.jsx)(Hyi,{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)(xxi,{onTimeRangeClick:e})})]}),(0,K.jsx)(SCi,{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)(zbi,{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)(ixi,{})]})}function $Mi(){let{isCmsAvailable:e}=w3(),{paths:t}=sn();return e?(0,K.jsx)(U7n,{href:t.cmsPromptBlockCreateLink(),tooltip:`Create a prompt`,children:`New prompt`}):null}var W9=[eP(`/prompts`)],eNi=50,tNi=[`updatedAt`];function nNi(){let[e,t]=(0,G.useState)(``),[n,r]=(0,G.useState)(0),[i,a]=Rv(),{sort:o,onSortChange:s}=u7({searchParams:i,setSearchParams:a,allowedKeys:tNi}),{data:c,isLoading:l,error:u,isPlaceholderData:d}=GWr({page:n,perPage:eNi,orderBy:(0,G.useMemo)(()=>o?{field:o.key,direction:o.direction===`asc`?`ASC`:`DESC`}:void 0,[o])}),f=c?.promptBlocks??[],p=c?.hasMore??!1,m=(0,G.useCallback)(()=>{d||r(e=>e+1)},[d]),h=(0,G.useCallback)(()=>{d||r(e=>Math.max(0,e-1))},[d]),g=(0,G.useCallback)(e=>{t(e),r(0)},[]),_=(0,G.useCallback)((e,t)=>{s(e,t),r(0)},[s]);return u&&FN(u)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(TH,{variant:`fill`})]}):u&&IN(u)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(wH,{variant:`fill`,resource:`prompt blocks`})]}):u?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load prompt blocks`,descriptionSlot:u.message})]}):f.length===0&&!l&&n===0?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:W9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(MGr,{})]}):(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:W9}),headerActions:(0,K.jsx)($Mi,{}),actionRow:(0,K.jsx)(TK,{children:(0,K.jsx)(TK.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(MH,{...NH,onValueChange:g,label:`Search prompts`,placeholder:`Search by name or description`})})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Prompts`}),(0,K.jsx)(jGr,{promptBlocks:f,isLoading:l,search:e,currentPage:n,hasMore:p,onNextPage:m,onPrevPage:h,updatedSort:o?.direction,onSortChange:_})]})}var rNi=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`})]})),iNi=[eP(`/resources`)],aNi=[{title:`Mastra APIs`,description:`Explore and test the available REST API endpoints with the interactive Swagger UI.`,icon:rNi,href:`/swagger-ui`,external:!1},{title:`Documentation`,description:`Read the official Mastra documentation for guides, references, and tutorials.`,icon:Njt,href:`https://mastra.ai/en/docs`,external:!0},{title:`Github`,description:`Browse the source code, report issues, and contribute to the Mastra project.`,icon:tP,href:`https://github.com/mastra-ai/mastra`,external:!0},{title:`Community`,description:`Join the Mastra Discord community for help, discussion, and collaboration.`,icon:a$,href:`https://discord.gg/mastra-ai`,external:!0},{title:`Share with your team`,description:`Running Mastra Studio locally? Deploy to the cloud so your team can collaborate.`,icon:LFr,href:`https://mastra.ai/cloud`,external:!0},{title:`Talk to our Sales team`,description:`Get a custom demo, discuss on-prem deployments, and how we can help you accelerate getting agents into production.`,icon:I0n,href:`https://mastra.ai/contact?ref=studio`,external:!0}];function oNi(){return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:iNi}),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:aNi.map(e=>(0,K.jsxs)(`a`,{href:e.href,...e.external?{target:`_blank`,rel:`noreferrer`}:{},className:`group flex flex-col gap-3 rounded-lg border border-border bg-background state-layer p-5 hover:border-border-strong`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[(0,K.jsx)(e.icon,{className:c(`h-5 w-5 text-muted-foreground group-hover:text-info-indicator`,A)}),(0,K.jsx)(T,{as:`span`,variant:`subheading`,tone:`ink`,children:e.title}),e.external&&(0,K.jsx)(tP,{className:`ml-auto size-icon-sm text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100`})]}),(0,K.jsx)(T,{variant:`caption`,tone:`muted`,children:e.description})]},e.href))})})]})}function sNi(){let{isCmsAvailable:e}=w3(),{paths:t}=sn();return e?(0,K.jsx)(U7n,{href:t.cmsScorersCreateLink(),tooltip:`Create a scorer`,children:`New scorer`}):null}var G9=[eP(`/scorers`)];function cNi(){let{data:e={},isLoading:t,error:n}=VN(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)(`all`),[s,c]=(0,G.useState)();if(n&&FN(n))return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:G9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Scorers`}),(0,K.jsx)(TH,{variant:`fill`})]});if(n&&IN(n))return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:G9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Scorers`}),(0,K.jsx)(wH,{variant:`fill`,resource:`scorers`})]});if(n)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:G9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Scorers`}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load scorers`,descriptionSlot:n.message})]});if(Object.keys(e).length===0&&!t)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:G9}),headerActions:(0,K.jsx)(sNi,{}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Scorers`}),(0,K.jsx)(CLr,{})]});let l=a!==`all`||r!==``;return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:G9}),headerActions:(0,K.jsx)(sNi,{}),actionRow:(0,K.jsx)(TLr,{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)(SLr,{scorers:e,isLoading:t,search:r,sourceFilter:a,sort:s,onSortChange:(e,t)=>c({key:t,direction:e})})]})}var lNi=[`input`,`entity`],uNi={input:`Input`,entity:`Entity`};function dNi(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 fNi(){let[e,t]=(0,G.useState)(new Set),n=(0,G.useMemo)(()=>new Set(lNi.filter(t=>!e.has(t))),[e]);return{visibleColumns:n,columns:(0,G.useMemo)(()=>dNi(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 pNi({visibleColumns:e,toggleColumn:t}){return(0,K.jsxs)(rE,{children:[(0,K.jsx)(rE.Trigger,{asChild:!0,children:(0,K.jsx)(X,{icon:(0,K.jsx)(X0r,{}),children:`Columns`})}),(0,K.jsxs)(rE.Content,{align:`end`,children:[(0,K.jsx)(rE.Label,{children:`Toggle columns`}),lNi.map(n=>(0,K.jsx)(rE.CheckboxItem,{checked:e.has(n),onClick:()=>t(n),children:uNi[n]},n))]})]})}var mNi=[eP(`/scorers`),eMt],hNi=[`date`,`score`];function gNi(){let{scorerId:e}=kv(),[t,n]=Rv(),r=t.get(`scoreId`)??void 0,[i,a]=(0,G.useState)(r),[o,s]=(0,G.useState)(!1),c=Ov(),[l,u]=(0,G.useState)({value:`all`,label:`All Entities`,type:`ALL`}),{scorer:d,error:f}=bjt(e),p=fNi(),{data:m={},isLoading:h,error:g}=wN(),{isLoading:_,error:v}=eN({}),{sort:y,onSortChange:b}=u7({searchParams:t,setSearchParams:n,allowedKeys:hNi}),{data:x=[],isLoading:S,error:C,isFetchingNextPage:w,hasNextPage:T,setEndOfListElement:E}=yjt({scorerId:e,entityId:l?.value===`all`?void 0:l?.value,entityType:l?.type===`ALL`?void 0:l?.type}),D=(0,G.useMemo)(()=>IZ(x,y,{date:e=>e.createdAt,score:e=>typeof e.score==`number`?e.score:void 0}),[x,y]),O=(0,G.useMemo)(()=>d?.agentIds?.filter(e=>m[e]).map(e=>({value:e,label:m[e].name,type:`AGENT`}))||[],[d?.agentIds,m]),k=(0,G.useMemo)(()=>d?.workflowIds?.map(e=>({value:e,label:e,type:`WORKFLOW`}))||[],[d?.workflowIds]),A=(0,G.useMemo)(()=>[{value:`all`,label:`All Entities`,type:`ALL`},...O,...k],[O,k]),j=t.get(`entity`)??`all`,M=A.find(e=>e.value===j);M&&M.value!==l?.value&&u(M),(0,G.useEffect)(()=>{if(f){let e=f instanceof Error?f.message:`Failed to load scorer`;iS.error(`Error loading scorer: ${e}`)}},[f]),(0,G.useEffect)(()=>{if(g){let e=g instanceof Error?g.message:`Failed to load agents`;iS.error(`Error loading agents: ${e}`)}},[g]),(0,G.useEffect)(()=>{if(v){let e=v instanceof Error?v.message:`Failed to load workflows`;iS.error(`Error loading workflows: ${e}`)}},[v]);let N=e=>{e?.value&&n(t=>{let n=new URLSearchParams(t);return n.set(`entity`,e.value),n})};(0,G.useEffect)(()=>{let e=t.get(`scoreId`)??void 0;e!==i&&(e?D.find(t=>t.id===e)&&a(e):a(void 0))},[t,D]);let P=(0,G.useCallback)(e=>{a(e||void 0),n(t=>{let n=new URLSearchParams(t);return e?n.set(`scoreId`,e):n.delete(`scoreId`),n})},[n]);if(!d)return null;let F=FN(f)||FN(g)||FN(v),I=f&&IN(f),L=!F&&!I&&(f||g||v),R=!S&&D.length===0,z=l?.value!==`all`,B=d?.source===`stored`,V=e?(0,K.jsx)(Xpi,{open:o,onOpenChange:s,initialScorerIds:[e],onSuccess:e=>void c(`/experiments/${e}`)}):null,H=B?(0,K.jsxs)(rE,{children:[(0,K.jsx)(rE.Trigger,{asChild:!0,children:(0,K.jsx)(X,{size:`icon-lg`,"aria-label":`Scorer actions menu`,children:(0,K.jsx)(iE,{})})}),(0,K.jsx)(rE.Content,{align:`end`,className:`w-48`,children:(0,K.jsxs)(rE.Item,{onSelect:()=>void c(`/cms/scorers/${e}/edit`),children:[(0,K.jsx)(iH,{}),` Edit scorer`]})})]}):null;if(F||I||L||R&&!z){let t=(f instanceof Error?f.message:void 0)??(g instanceof Error?g.message:void 0)??(v instanceof Error?v.message:void 0)??`An unexpected error occurred`;return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:mNi}),actionRow:!(F||I||L)&&H?(0,K.jsx)(TK,{children:(0,K.jsx)(TK.End,{children:H})}):void 0,children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:F?(0,K.jsx)(TH,{}):I?(0,K.jsx)(wH,{resource:`scorers`}):L?(0,K.jsx)(Jx,{tone:`error`,titleSlot:`Failed to load scorer`,descriptionSlot:t}):(0,K.jsx)(vLr,{onRunExperiment:()=>s(!0)})}),V]})}return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:mNi}),actionRow:(0,K.jsxs)(TK,{children:[(0,K.jsx)(TK.Start,{children:(0,K.jsx)(yLr,{selectedEntity:l,entityOptions:A,onEntityChange:N,onReset:()=>{n(e=>{let t=new URLSearchParams(e);return t.set(`entity`,`all`),t})},isLoading:S||h||_})}),(0,K.jsxs)(TK.End,{children:[(0,K.jsx)(pNi,{visibleColumns:p.visibleColumns,toggleColumn:p.toggleColumn}),(0,K.jsx)(X,{variant:`primary`,onClick:()=>s(!0),icon:(0,K.jsx)(Hx,{}),children:`New experiment`}),H]})]}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(_Lr,{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 _Ni=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`})),vNi=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`})),yNi=[{value:`system`,label:`System`,icon:(0,K.jsx)(u8n,{})},{value:`light`,label:`Light`,icon:(0,K.jsx)(vNi,{})},{value:`dark`,label:`Dark`,icon:(0,K.jsx)(_Ni,{})}];function bNi(e,t){if(e.some(e=>e.value===t))return t;let[n]=e;return n?n.value:`system`}var xNi=({value:e,onChange:t,options:n=yNi,size:r=`md`,"aria-label":i=`Theme`,...a})=>{let{theme:o,setTheme:s}=B(),c=e??o,l=t??s,u=bNi(n,c);return(0,K.jsx)(wor,{...a,"aria-label":i,iconOnly:!0,size:r===`xs`?`sm`:r,value:u,onValueChange:l,children:n.map(e=>(0,K.jsx)(Tor,{value:e.value,"aria-label":e.label,children:e.icon},e.value))})};function SNi(e){return Object.fromEntries(e.filter(e=>e.name.trim()).map(e=>[e.name.trim(),e.value]))}function CNi(e,t){return e.baseUrl.trim()===t.baseUrl.trim()&&e.apiPrefix.trim()===(t.apiPrefix??``).trim()&&JSON.stringify(SNi(e.headers))===JSON.stringify(t.headers)}function wNi(e){return e===0?`No request headers`:e===1?`1 request header`:`${e} request headers`}function TNi({initialConfig:e}){let{setConfig:t}=yS(),n=(0,G.useRef)(0),r=()=>({baseUrl:e.baseUrl,apiPrefix:e.apiPrefix??``,headers:Object.entries(e.headers).map(([e,t])=>({id:n.current++,name:e,value:t}))}),[i,a]=(0,G.useState)(r),[o,s]=(0,G.useState)(),c=!CNi(i,e),l=(e,t)=>a(n=>({...n,headers:n.headers.map(n=>n.id===e?{...n,...t}:n)}));function u(e){e.preventDefault(),i.baseUrl.trim()?(t({baseUrl:i.baseUrl.trim(),apiPrefix:i.apiPrefix.trim()||void 0,headers:SNi(i.headers)}),iS.success(`Connection saved`)):s(`Enter the server URL`)}function d(){a(r()),s(void 0)}return(0,K.jsx)(`form`,{onSubmit:u,onReset:d,noValidate:!0,children:(0,K.jsxs)(vZ,{children:[(0,K.jsx)(_Z,{label:`Mastra instance URL`,description:`The server this studio talks to.`,errorMsg:o,children:(0,K.jsx)(Jj,{name:`url`,value:i.baseUrl,placeholder:`http://localhost:4111`,spellCheck:!1,onChange:e=>{a(t=>({...t,baseUrl:e.target.value})),s(void 0)}})}),(0,K.jsx)(_Z,{label:`API prefix`,description:`Path in front of every API route.`,children:(0,K.jsx)(Jj,{name:`apiPrefix`,value:i.apiPrefix,placeholder:`/api (default)`,spellCheck:!1,onChange:e=>a(t=>({...t,apiPrefix:e.target.value}))})}),(0,K.jsx)(E5n,{action:(0,K.jsx)(X,{type:`button`,size:`sm`,icon:(0,K.jsx)(Hx,{}),onClick:()=>a(e=>({...e,headers:[...e.headers,{id:n.current++,name:``,value:``}]})),children:`Add header`}),children:wNi(i.headers.length)}),i.headers.map(e=>(0,K.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(Jj,{"aria-label":`Header name`,value:e.name,placeholder:`Authorization`,spellCheck:!1,onChange:t=>l(e.id,{name:t.target.value})}),(0,K.jsx)(Jj,{"aria-label":e.name?`Value of ${e.name}`:`Header value`,value:e.value,placeholder:`Bearer <token>`,spellCheck:!1,onChange:t=>l(e.id,{value:t.target.value})}),(0,K.jsx)(X,{type:`button`,size:`icon-md`,variant:`ghost`,"aria-label":e.name?`Remove ${e.name}`:`Remove header`,tooltip:`Remove header`,onClick:()=>a(t=>({...t,headers:t.headers.filter(t=>t.id!==e.id)})),children:(0,K.jsx)(Kj,{})})]},e.id)),c?(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,K.jsx)(`span`,{className:`text-body-sm text-muted-foreground`,children:`Unsaved changes`}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(X,{type:`reset`,size:`sm`,variant:`ghost`,children:`Discard`}),(0,K.jsx)(X,{type:`submit`,size:`sm`,variant:`primary`,children:`Save changes`})]})]}):null]})})}function ENi(){let{baseUrl:e,apiPrefix:t,headers:n}=yS(),r=JSON.stringify([e,t??``,n]);return(0,K.jsxs)(yZ,{children:[(0,K.jsx)(bZ,{info:`The Mastra instance the studio talks to, the path in front of its API routes, and the headers sent with every request.`,children:`Mastra connection`}),(0,K.jsx)(TNi,{initialConfig:{baseUrl:e,apiPrefix:t,headers:n}},r)]})}var DNi=()=>(0,K.jsx)(RS,{children:(0,K.jsxs)(A5n,{title:`Settings`,children:[(0,K.jsxs)(yZ,{children:[(0,K.jsx)(bZ,{info:`Stored in this browser.`,children:`General`}),(0,K.jsx)(vZ,{children:(0,K.jsx)(_Z,{label:`Theme`,description:`Color scheme for the interface.`,children:(0,K.jsx)(xNi,{})})})]}),(0,K.jsx)(ENi,{})]})});function ONi(){let[e]=Rv(),t=Ov(),n=e.get(`redirect`)||`/`;return(0,K.jsx)(cki,{redirectUri:n,onSuccess:()=>{n.startsWith(`http`)?window.location.href=n:t(n,{replace:!0})},initialMode:`signup`})}function kNi({current:e,features:t}){let n=t2r(),r=n2r(),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 ANi=[`traces`,`spans`],jNi={traces:{icon:(0,K.jsx)(QN,{}),label:`Traces`},spans:{icon:(0,K.jsx)(YV,{}),label:`Spans`},threads:{icon:(0,K.jsx)(Iq,{}),label:`Threads`}};function MNi({current:e,views:t=ANi,onViewChange:n}){return(0,K.jsx)(`nav`,{"aria-label":`Observability views`,children:(0,K.jsx)(gk,{value:e,defaultTab:e,onValueChange:n,children:(0,K.jsx)(hk,{variant:`pill-ghost`,children:t.map(e=>(0,K.jsxs)(_k,{value:e,children:[(0,K.jsx)(Dx,{size:`xs`,children:jNi[e].icon}),(0,K.jsx)(T,{variant:`caption`,className:`text-inherit`,children:jNi[e].label})]},e))})})})}function NNi(){return(0,K.jsxs)(`div`,{role:`status`,"aria-label":`Loading views`,className:`flex min-h-control-md items-center gap-0.5`,children:[(0,K.jsx)(zS,{className:`h-control-md w-20 rounded-full`}),(0,K.jsx)(zS,{className:`h-control-md w-20 rounded-full`})]})}function PNi({current:e,features:t,onViewChange:n,breadcrumbs:r,children:i}){let{views:a,isLoading:o,showSwitch:s}=kNi({current:e,features:t}),[c,l]=(0,G.useState)(null),u=vii(),d;return o?d=(0,K.jsx)(NNi,{}):s&&(d=(0,K.jsx)(MNi,{current:e,views:a,onViewChange:n})),(0,K.jsx)(RS,{breadcrumbs:r({current:e,isLoading:o,showSwitch:s}),actionRow:(d||u)&&(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center justify-between gap-3`,children:[d,(0,K.jsx)(`div`,{ref:l,className:`flex min-w-0 grow justify-end`})]}),children:(0,K.jsx)(Doi.Provider,{value:c??void 0,children:i})})}function FNi({isLoading:e,enabled:t,heading:n,title:r,description:i,children:a}){return t?a:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:n}),e?(0,K.jsxs)(`div`,{className:`flex h-full items-center justify-center gap-2`,children:[(0,K.jsx)(It,{"aria-label":`Loading storage capabilities`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:`Loading storage capabilities`})]}):(0,K.jsx)(Jx,{variant:`fill`,titleSlot:r,descriptionSlot:i})]})}var INi={refetchInterval:({state:e})=>Lri(e.error),refetchOnWindowFocus:!1};function LNi(e){let[t,n]=(0,G.useState)(()=>new URLSearchParams);return e||{searchParams:t,setSearchParams:e=>n(t=>typeof e==`function`?e(t):e)}}function RNi(e,{sortFields:t,withTokenSearch:n=!1,defaultDatePreset:r=Tii}={}){let{searchParams:i,setSearchParams:a}=LNi(e),o=JSON.stringify(jii(i,r)),s=JSON.stringify(Nii(i)),{datePreset:c,dateFrom:l,dateTo:u}=(0,G.useMemo)(()=>jii(i,r),[o]),{tokens:d,groups:f}=(0,G.useMemo)(()=>{let e=Nii(i);return n?e:{...e,tokens:e.tokens.filter(e=>e.operatorId!==`hasAllTokens`)}},[s,n]),p=Fii(i,t??Cii),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=L2r(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=>Mii(t,e(jii(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=cii(x.current,n,e,t),{datePreset:`custom`,dateFrom:e,dateTo:t})),D=e=>b(t=>{let n=lii(x.current,t);return x.current=void 0,n??{datePreset:e}}),O=(e,t)=>y(n=>Pii(n,{tokens:e,groups:t})),k=e=>y(t=>Iii(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 zNi(e){return[`observability-list-head`,...e]}function BNi(e){let t=m_([e]),[n,r]=(0,G.useState)();return{anchorTo:n?.selectionHash===t?n.to:void 0,reanchor:()=>r({selectionHash:t,to:new Date().toISOString()})}}var VNi=()=>({rows:[],watermark:void 0});function HNi({queryKey:e,fetchHead:t,getId:n,getEndedAt:r,enabled:i,since:a,limit:o=50,maxRows:s=500,interval:c=Nri,onOverflow:l}){let u=u_(),d=zNi(e),{data:f}=T_({queryKey:d,queryFn:async()=>{let e=u.getQueryData(d)??VNi(),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?.(),VNi();let m=c.length>0?Math.max(e.watermark??-1/0,...c):e.watermark;return{rows:[...f.values()],watermark:m}},initialData:VNi,staleTime:1/0,enabled:i,refetchInterval:e=>!Fri(e.state.error)&&c,refetchOnWindowFocus:!1,refetchOnReconnect:!1,retry:!1});return{headRows:f.rows}}function UNi(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 WNi(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),UNi(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 GNi={traces:`Traces`,spans:`Spans`,threads:`Threads`};function KNi({current:e,isLoading:t,showSwitch:n}){if(!(t||n||e===`traces`))return GNi[e]}function qNi(e){let t=e.get(`traceId`),n=e.get(`spanId`);return t&&n?{traceId:t,spanId:n}:void 0}function JNi(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 YNi({traceId:e,spanId:t}){return new URLSearchParams({traceId:e,spanId:t})}function XNi(e){return e.get(`threadId`)??void 0}function ZNi(e,t){let n=new URLSearchParams(e);return t?n.set(`threadId`,t):n.delete(`threadId`),n}var QNi=e=>`${e.traceId}:${e.spanId}`;function $Ni(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 ePi({query:e,rolling:t,autoRefetch:n=!0,limit:r,enabled:i=!0}){let a=Y(),{anchorTo:o,reanchor:s}=BNi(e),c=(0,G.useMemo)(()=>o?{...e,timeRange:{...e.timeRange,to:o}}:e,[e,o]),l=eXr({query:c,limit:r,enabled:i,queryOptions:INi}),{headRows:u}=HNi({queryKey:[`spans`,e],fetchHead:async t=>(await a.querySpans({...e,timeRange:{from:e.timeRange.from,to:t},orderBy:[{field:`endedAt`,direction:`desc`}],page:{limit:50}})).spans,getId:QNi,getEndedAt:e=>e.endedAt,since:Date.parse(c.timeRange.to),enabled:i&&t&&n&&l.spans!==void 0&&!l.isFetching&&!l.isError,onOverflow:s}),{orderBy:d}=e,f=l.spans,p=(0,G.useMemo)(()=>f&&WNi(f,u,{getId:QNi,compare:$Ni(d),hasNextPage:l.hasNextPage}),[f,u,d,l.hasNextPage]);return{...l,spans:p}}function tPi(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 nPi({timeRange:e,where:t,onZoom:n}){let r=i2r(),i=(0,G.useMemo)(()=>({timeRange:e,...t?{where:t}:{},interval:D8r(e).interval,measures:[...y8r],limit:1}),[e,t]),a=!r.enabled||O8r(e),{data:o,isLoading:s,isError:c,isPlaceholderData:l}=IYr({request:i,enabled:!a,queryOptions:{placeholderData:__}}),u=(0,G.useMemo)(()=>N8r(o?.rows??[],e),[o,e]);return a?null:(0,K.jsx)(m8r,{label:`Spans over time`,resourceLabel:`Spans`,buckets:u,isLoading:s,isError:c,isUpdating:l,onZoom:n&&(t=>n(P8r(u,t,e)))})}var rPi=[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`],iPi=[];function aPi({timeRange:e,withTokenSearch:t=!1}){let n=Y(),{data:r}=i5(),i=r?.capabilities.spanQueryContextFields??!1,a=r?.capabilities.traceQueryTimeToFirstChunk??!1,o=r?.capabilities.traceQueryTimeToFirstToken??!1,s=r?.capabilities.spanQueryOutcomeFields??!1,c=r?.capabilities.spanQueryModelFields??!1,{data:l=iPi}=t8(),{data:u=iPi}=n8();return(0,G.useMemo)(()=>[l3r,...V6(gai({withContextFields:i,withTimeToFirstChunk:a,withTimeToFirstToken:o,withOutcomeFields:s,withModelFields:c,entityNames:l,environments:u,valueSuggestions:t=>AXr(n,e,`spans`,t)}),t)],[t,i,a,o,s,c,l,u,n,e])}function oPi({tokens:e,groups:t,onFiltersChange:n}){let r=(0,G.useMemo)(()=>P8(e),[e]),i=(0,G.useMemo)(()=>{let e=F8([],t);return{...e,nodes:[p5,...r,...e.nodes]}},[r,t]),a=(0,G.useCallback)(e=>{let t=VZr({...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 sPi=e=>e;function cPi({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=aPi({timeRange:a,withTokenSearch:e}),{filterBarValue:g,onFilterBarChange:_}=oPi({tokens:o,groups:s,onFiltersChange:f});return(0,K.jsxs)(m5,{fields:h,operators:mZr,value:g,onValueChange:_,createItemId:sPi,describeSuggestionsError:p,maxDepth:3,"aria-label":`Span filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(m5.Chips,{renderChip:e=>e.fieldId===`timeRange`?(0,K.jsx)(m5.TimeRange,{preset:t,onPresetChange:c,dateFrom:n,dateTo:r,minDate:i,onDateChange:l,onDateRangeChange:u,disabled:m,presets:rPi,defaultPreset:o5.datePreset,onReset:d&&(()=>d(o5.datePreset))}):(0,K.jsx)(m5.Chip,{item:e})}),(0,K.jsx)(m5.Input,{placeholder:`Filter spans`})]})}function lPi({selection:e,onSelectionChange:t,renderPanel:n,urlState:r}){let{data:i,isLoading:a}=i5(),o=!!(i?.capabilities.spanQueryTokenSearch&&i.capabilities.spanAggregateTokenSearch),s=RNi(r,{sortFields:wii,withTokenSearch:o}),{timeRange:c,tokens:l,groups:u}=s,d=iii({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:C0r(d.preferences,{withTimeToFirstChunk:p,withTimeToFirstToken:m}),[d.preferences,a,p,m]),v=(0,G.useMemo)(()=>{let e=[`startedAt`];return p&&i?.capabilities.traceQueryTimeToFirstChunkSort&&e5(_,`timeToFirstChunk`)&&e.push(`timeToFirstChunkMs`),m&&i?.capabilities.traceQueryTimeToFirstTokenSort&&e5(_,`timeToFirstToken`)&&e.push(`timeToFirstTokenMs`),e},[i,p,m,_]),y=v.includes(s.sort.field)?s.sort:{field:`startedAt`,direction:`desc`},{field:b,direction:x}=y,S=(0,G.useMemo)(()=>yai(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}=ePi({query:(0,G.useMemo)(()=>({timeRange:c,orderBy:[{field:b,direction:x}],where:S}),[c,b,x,S]),enabled:!a,rolling:s.rolling}),A=(0,G.useMemo)(()=>(C??[]).map(tPi),[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)(q0r,{toolbar:(0,K.jsxs)(K.Fragment,{children:[r&&(0,K.jsx)(Foi,{page:`spans`,...r,columns:d}),(0,K.jsxs)(TK,{children:[(0,K.jsx)(TK.Start,{children:(0,K.jsx)(cPi,{withTokenSearch:o,datePreset:s.datePreset,dateFrom:s.dateFrom,dateTo:s.dateTo,timeRange:c,tokens:l,groups:u,onDatePresetChange:s.onDatePresetChange,onDateChange:s.onDateChange,onDateRangeChange:s.onDateRangeChange,onDateReset:s.onDateReset,onFiltersChange:s.onFiltersChange,disabled:D})}),(0,K.jsx)(TK.End,{children:(0,K.jsx)(d2r,{scope:`spans`,value:d.preferences,onChange:d.setPreferences})})]})]}),chart:(0,K.jsx)(nPi,{timeRange:c,where:S,onZoom:({from:e,to:t})=>s.onZoom(e,t)}),error:O?(0,K.jsx)(Q8,{error:k,resource:`spans`,errorTitle:`Failed to load spans`}):void 0,empty:N?(0,K.jsx)(t0r,{resource:`spans`,datePreset:s.datePreset,dateFrom:s.dateFrom,dateTo:s.dateTo}):void 0,children:(0,K.jsx)(h7r,{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 uPi({selection:e,spans:t,onSelect:n,onClose:r,onShowTrace:i}){let{data:a,isLoading:o}=r8({traceId:e.traceId,spanId:e.spanId}),s=t.findIndex(t=>t.traceId===e.traceId&&t.spanId===e.spanId),c=s>0?t[s-1]:void 0,l=s>=0&&s<t.length-1?t[s+1]:void 0;return(0,K.jsx)(Pti,{traceId:e.traceId,spanId:e.spanId,span:a?.span,isLoading:o,onPrevious:c?()=>n(c):void 0,onNext:l?()=>n(l):void 0,onClose:r,onShowTrace:i})}function dPi({selection:e,spans:t,onSelect:n,onClose:r,onShowTrace:i}){let a=Zw();K1r(e?`${e.traceId}:${e.spanId}`:void 0,r);let o=e?(0,K.jsx)(uPi,{selection:e,spans:t,onSelect:n,onClose:r,onShowTrace:i}):null;return a?(0,K.jsx)(jQ,{open:!!e,onClose:r,title:`Span details`,children:o}):o?(0,K.jsx)(Y8,{owner:`span-detail`,children:(0,K.jsx)(jQ,{variant:`inline`,title:`Span details`,children:o})}):null}function fPi(){let{enabled:e,isLoading:t}=t2r(),n=Ov(),[r,i]=Rv();return(0,K.jsx)(FNi,{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)(lPi,{urlState:{searchParams:r,setSearchParams:i},selection:qNi(r),onSelectionChange:e=>i(t=>JNi(t,e),{replace:!0}),renderPanel:e=>(0,K.jsx)(dPi,{...e,onShowTrace:e=>n(`/traces?${YNi(e)}`)})})})}async function pPi(){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 mPi({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 hPi({repoOrSlug:e,owner:t}){let{templates:n}=await pPi(),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 mPi({repo:e,owner:t});if(r)return r;throw Error(`Template ${e} not found`)}return r}async function gPi({repo:e,owner:t,branch:n}){let r=`https://raw.githubusercontent.com/${t}/${e}/${n}/.env.example`,i=await fetch(r);return i.ok?(await i.text()).split(`
724
- `).reduce((e,t)=>{if(!t||t.startsWith(`#`))return e;let[n,r]=t.split(`=`);return n&&(e[n]=r?.split(``)?.every(e=>e===`*`)?``:r?.replaceAll(`"`,``)),e},{}):{}}var _Pi=({queryOptions:e}={})=>T_({queryKey:[`mastra-templates`],queryFn:pPi,...e}),vPi=({repoOrSlug:e,owner:t,queryOptions:n})=>T_({queryKey:[`template-repo`,e,t],queryFn:()=>hPi({repoOrSlug:e,owner:t}),...n}),yPi=({repo:e,owner:t,branch:n,queryOptions:r})=>T_({queryKey:[`template-repo-env-vars`,e,t,n],queryFn:()=>gPi({repo:e,owner:t,branch:n}),...r}),bPi=({queryOptions:e}={})=>{let t=Y();return T_({queryKey:[`agent-builder-workflow`],queryFn:async()=>await t.getAgentBuilderAction(`merge-template`).details(),...e})},xPi=({queryOptions:e}={})=>{let t=Y();return D_({mutationFn:async({runId:e})=>await t.getAgentBuilderAction(`merge-template`).createRun({runId:e}),...e})},SPi=({queryOptions:e}={})=>{let t=Y();return D_({mutationFn:async({runId:e})=>await t.getAgentBuilderAction(`merge-template`).runById(e),...e})},CPi=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)},wPi=(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=CPi(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=CPi(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}},TPi=(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)}},EPi=(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}=wPi(a,s,e);s=c,r(c),(a.runId||i||t)&&TPi(a.runId||i||t,c)}}catch(t){console.error(`💥 [processStream] Error processing template installation stream:`,t);let{newState:n}=wPi({type:`error`,payload:{error:t instanceof Error?t.message:`Unknown error`}},s,e);r(n)}finally{a(!1),o.releaseLock()}}}},DPi=({workflowInfo:e,queryOptions:t}={})=>{let n=Y(),{streamResult:r,isStreaming:i,processStream:a}=EPi(e);return{streamInstall:D_({mutationFn:async({inputData:e,selectedModel:t,runId:r})=>{for(let i=1;i<=3;i++)try{let i=n.getAgentBuilderAction(`merge-template`),o=new On;o.set(`selectedModel`,t);let s=await i.stream({inputData:e,requestContext:o},r);await a(s,r);return}catch(e){console.error(`💥 [streamInstall] Attempt ${i} failed:`,e);let t=e?.message?.includes(`Failed to fetch`)||e?.message?.includes(`NetworkError`)||e?.message?.includes(`network error`)||e?.message?.includes(`fetch`)||e?.code===`NETWORK_ERROR`||e?.name===`TypeError`;if(console.warn(`Stream attempt ${i}/3 failed:`,e),t){let e=r?`Network error during template installation (likely hot reload). Please refresh the page to resume from where you left off using runId: ${r}`:`Network error during template installation (likely hot reload). Please try again.`;throw console.error(`🔌 Stream network error:`,e),Error(e)}throw console.error(`❌ [streamInstall] Non-network error or max retries reached, throwing:`,e),e}},...t?.streamInstall}),streamResult:r,isStreaming:i}},OPi=({workflowInfo:e,queryOptions:t}={})=>{let n=Y(),{streamResult:r,isStreaming:i,processStream:a}=EPi(e);return{observeInstall:D_({mutationFn:async({runId:e})=>{let t=2e3;for(let r=1;r<=3;r++)try{let t=await n.getAgentBuilderAction(`merge-template`).observeStream({runId:e});await a(t,e);return}catch(e){console.error(`💥 [observeInstall] Attempt ${r} failed:`,e);let n=e?.message?.includes(`Failed to fetch`)||e?.message?.includes(`NetworkError`)||e?.message?.includes(`network error`)||e?.message?.includes(`fetch`)||e?.code===`NETWORK_ERROR`||e?.name===`TypeError`;if(console.warn(`ObserveStream attempt ${r}/3 failed:`,e),n&&r<3){console.info(`🔄 ObserveStream network error detected (likely hot reload), retrying in ${t}ms... (attempt ${r+1}/3)`),await new Promise(e=>setTimeout(e,t));continue}throw console.error(`❌ [observeInstall] Non-network error or max retries reached, throwing:`,e),e}},...t?.observeInstall}),streamResult:r,isStreaming:i}};function kPi(e){return e.replace(/\/$/,``).split(`/`).pop()}function APi({templates:e,linkComponent:t,className:n,isLoading:r}){let i=t||`a`;return r?(0,K.jsx)(`div`,{className:c(`grid gap-y-4`,n),children:Array.from({length:5}).map((e,t)=>(0,K.jsx)(`div`,{className:`h-16 animate-pulse rounded-lg bg-card`},t))}):(0,K.jsx)(`div`,{className:c(`grid gap-y-4`,n),children:e.map(e=>{let t=e?.agents||e?.tools||e?.networks||e?.workflows||e?.mcp;return(0,K.jsxs)(`article`,{className:c(Bv,`grid w-full grid-cols-[1fr_auto] overflow-hidden rounded-lg state-layer`),children:[(0,K.jsxs)(i,{to:`/templates/${e.slug}`,className:c(`group grid`,{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":e.imageURL}),children:[e.imageURL&&(0,K.jsx)(`div`,{className:`overflow-hidden`,children:(0,K.jsx)(`div`,{className:`thumb transition-scale h-full w-full bg-cover duration-150`,style:{backgroundImage:`url(${e.imageURL})`}})}),(0,K.jsxs)(`div`,{className:c(`grid w-full gap-0.5 px-4 py-3`,`[&_svg]:h-[1em] [&_svg]:w-[1em] [&_svg]:text-muted-foreground`),children:[(0,K.jsx)(T,{as:`h2`,tone:`ink`,children:e.title}),(0,K.jsx)(T,{className:c(CS,A),children:e.description}),(0,K.jsxs)(`div`,{className:`mt-3 hidden flex-wrap items-center gap-x-8 gap-y-4 text-muted-foreground 2xl:flex`,children:[t&&(0,K.jsxs)(`ul`,{className:c(`text-muted-foreground`,`m-0 flex list-none gap-4 p-0`,`[&>li]:flex [&>li]:items-center [&>li]:gap-0.5`),children:[e?.agents&&e.agents.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(HN,{}),` `,e.agents.length]})}),e?.tools&&e.tools.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(XN,{}),` `,e.tools.length]})}),e?.networks&&e.networks.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(n7e,{}),` `,e.networks.length]})}),e?.workflows&&e.workflows.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(ZS,{}),` `,e.workflows.length]})}),e?.mcp&&e.mcp.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(KN,{}),` `,e.mcp.length]})})]}),(0,K.jsx)(`div`,{className:`flex items-center gap-4`,children:e.supportedProviders.map(e=>(0,K.jsx)(T,{tone:`muted`,as:`span`,variant:`body`,children:e},e))})]})]})]}),(0,K.jsx)(`a`,{href:e.githubUrl,className:c(`group ml-auto hidden items-center gap-2 pr-4`,`lg:flex`),target:`_blank`,rel:`noopener noreferrer`,children:(0,K.jsx)(T,{as:`span`,variant:`body`,children:(0,K.jsxs)(`span`,{className:c(`flex items-center gap-2 rounded bg-sidebar px-2 py-1`,Jze,CS,A),children:[(0,K.jsx)(kZ,{}),` `,kPi(e.githubUrl)]})})})]},e.slug)})})}function jPi({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:i,onProviderChange:a,searchTerm:o,onSearchChange:s,onReset:l,className:u,isLoading:d}){return d?(0,K.jsxs)(`div`,{className:c(`flex h-[6.5rem] items-center gap-5`,`[&>div]:h-8 [&>div]:w-48 [&>div]:animate-pulse [&>div]:bg-card`,u),children:[(0,K.jsx)(`div`,{}),` `,(0,K.jsx)(`div`,{}),` `,(0,K.jsx)(`div`,{})]}):(0,K.jsxs)(`div`,{className:c(`sticky top-0 mx-auto flex flex-wrap gap-1.5 bg-background py-5`,u),children:[(0,K.jsx)(MH,{label:`Search templates`,placeholder:`Search templates`,size:`sm`,value:o,onValueChange:s}),(0,K.jsxs)(Bk,{value:t,onValueChange:i,children:[(0,K.jsx)(Hk,{"aria-label":`Search by tag`,size:`sm`,className:`w-auto`,children:(0,K.jsx)(Vk,{placeholder:`Select an option`})}),(0,K.jsx)(Uk,{children:e.map(e=>(0,K.jsx)(Wk,{value:e.value,children:e.label},e.value))})]}),(0,K.jsxs)(Bk,{value:r,onValueChange:a,children:[(0,K.jsx)(Hk,{"aria-label":`Search by provider`,size:`sm`,className:`w-auto`,children:(0,K.jsx)(Vk,{placeholder:`Select an option`})}),(0,K.jsx)(Uk,{children:n.map(e=>(0,K.jsx)(Wk,{value:e.value,children:e.label},e.value))})]}),l&&(0,K.jsx)(J4,{onClick:l})]})}var MPi=[{id:`templates`,label:`Templates`}];function NPi(){let{data:e,isLoading:t}=_Pi(),{templates:n,tags:r,providers:i}=e??{templates:[],tags:[],providers:[]},[a,o]=(0,G.useState)(`all`),[s,l]=(0,G.useState)(`all`),[u,d]=(0,G.useState)(``),f=[{value:`all`,label:`Any tag`}];(r||[]).forEach(e=>{f.push({value:e,label:e})});let p=[{value:`all`,label:`Any provider`}];(i||[]).forEach(e=>{p.push({value:e,label:e})});let m=(e,t)=>{t===`tag`?o(e):t===`provider`&&l(e)},h=e=>{d(e)},g=()=>{o(`all`),l(`all`),d(``)},_=n.filter(e=>!(u&&!e.title.toLowerCase().includes(u)&&!e.description.toLowerCase().includes(u)||a!==`all`&&!e.tags.includes(a)||s!==`all`&&!e.supportedProviders.includes(s))),v=u||a!==`all`||s!==`all`;return(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:MPi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Templates`}),(0,K.jsx)(wS,{children:(0,K.jsxs)(nJe,{children:[(0,K.jsx)(Dx,{children:(0,K.jsx)(OZ,{})}),`Templates`]})}),(0,K.jsxs)(`div`,{className:c(`z-10 h-full w-full overflow-y-auto px-5 pb-12`),children:[(0,K.jsx)(jPi,{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)(APi,{templates:_,linkComponent:Lv,className:`mx-auto max-w-[80rem]`,isLoading:t})]})]})}var PPi=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 FPi({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 IPi({errorMsg:e,validationErrors:t}){let n=typeof e==`string`?e:e==null?void 0:String(e),r=n?.includes(`Invalid schema for function`),i=n?.includes(`validation issue`)||t&&t.length>0,a=()=>i?`Template installation completed but some validation issues remain. The template may still be functional, but you should review and fix these issues.`:r?`There was an issue with the AI model configuration. This may be related to the selected model or AI SDK version compatibility.`:`An unexpected error occurred during template installation.`,{icon:o,title:s}=i?{icon:(0,K.jsx)(Zx,{className:`text-warning-foreground`}),title:`Template Installed with Warnings`}:{icon:(0,K.jsx)(PPi,{}),title:`Template Installation Failed`};return(0,K.jsxs)(FPi,{className:`mb-5 content-center space-y-4 text-muted-foreground`,children:[(0,K.jsxs)(`div`,{className:`grid content-center items-center justify-items-center gap-4 [&>svg]:h-8 [&>svg]:w-8`,children:[o,(0,K.jsxs)(`div`,{className:`space-y-2 text-center`,children:[(0,K.jsx)(T,{variant:`subheading`,tone:`ink`,children:s}),(0,K.jsx)(T,{tone:`muted`,children:a()})]})]}),t&&t.length>0&&(0,K.jsxs)(`details`,{children:[(0,K.jsx)(`summary`,{className:c(`text-muted-foreground hover:text-foreground`,`cursor-pointer text-center select-none`),children:(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[`Show Validation Issues (`,t.length,`)`]})}),(0,K.jsx)(`div`,{className:`mt-4 max-h-60 space-y-2 overflow-auto rounded bg-muted p-3 text-left`,children:t.map((e,t)=>(0,K.jsxs)(`div`,{className:`border-l-2 border-destructive-indicator pl-2`,children:[(0,K.jsx)(T,{as:`p`,variant:`column`,className:`text-destructive-foreground`,children:e.type===`typescript`?`🔴 TypeScript Error`:`⚠️ Lint Error`}),(0,K.jsx)(uC,{className:`mt-1 text-caption wrap-break-word whitespace-pre-wrap text-muted-foreground`,code:e.message})]},t))})]}),n&&!i&&(0,K.jsxs)(`details`,{children:[(0,K.jsx)(`summary`,{className:c(`text-muted-foreground hover:text-foreground`,`cursor-pointer text-center select-none`),children:(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`block`,children:`Show Details`})}),(0,K.jsx)(`div`,{className:`mt-4 max-h-60 overflow-auto rounded bg-muted p-3 text-left`,children:(0,K.jsx)(uC,{className:`text-caption wrap-break-word whitespace-pre-wrap`,code:n})})]})]})}function LPi({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)(FPi,{children:(0,K.jsxs)(`div`,{className:`mx-auto my-4 grid max-w-[40rem] gap-5 p-4 lg:p-5`,children:[(0,K.jsxs)(T,{as:`h2`,variant:`heading`,tone:`muted`,className:c(`flex items-center gap-2`,`[&_svg]:h-[1.2em] [&_svg]:opacity-70 [&>svg]:w-[1.2em]`),children:[`Install Template `,(0,K.jsx)(OZ,{})]}),(0,K.jsxs)(ak,{orientation:`horizontal`,children:[(0,K.jsx)(sk,{children:`Template AI Model Provider`}),(0,K.jsx)(Tpt,{className:`flex-1`,children:(0,K.jsxs)(Bk,{name:`template-provider`,value:t,onValueChange:n,children:[(0,K.jsx)(Hk,{size:`md`,children:(0,K.jsx)(Vk,{placeholder:`Select`})}),(0,K.jsx)(Uk,{children:e.map(e=>(0,K.jsx)(Wk,{value:e.value,children:e.label},e.value))})]})})]}),t&&Object.entries(r||{}).length>0&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h3`,tone:`muted`,children:`Set required Environmental Variables`}),(0,K.jsx)(`div`,{className:`grid grid-cols-[1fr_1fr] items-start gap-4`,children:s?(0,K.jsxs)(`div`,{className:c(`text-muted-foreground`,`col-span-2 flex items-center justify-center gap-4`,`[&_svg]:h-[1.1em] [&_svg]:w-[1.1em] [&_svg]:opacity-50`,`animate-in duration-300 fade-in`),children:[(0,K.jsx)(It,{}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[` `,`Loading variables...`]})]}):Object.entries(r).map(([e,t])=>(0,K.jsxs)(G.Fragment,{children:[(0,K.jsxs)(ak,{className:`w-full`,children:[(0,K.jsx)(sk,{className:`sr-only`,children:`Key`}),(0,K.jsx)(Jj,{name:`env-${e}`,value:e,disabled:!0,className:`w-full`})]}),(0,K.jsxs)(ak,{invalid:i.includes(e),className:`w-full`,children:[(0,K.jsx)(sk,{className:`sr-only`,children:`Value`}),(0,K.jsx)(Jj,{name:e,value:t,onChange:o,autoComplete:`off`,className:`w-full`}),(0,K.jsx)(lk,{children:i.includes(e)?`Value is required.`:void 0})]})]},e))}),(0,K.jsxs)(`div`,{className:`relative mt-3.5 border-t border-border pt-12`,children:[(0,K.jsx)(`div`,{className:`absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full bg-background`,children:(0,K.jsx)(T,{tone:`muted`,as:`span`,variant:`caption`,className:`block`,children:`And`})}),(0,K.jsx)(T,{as:`h3`,tone:`muted`,children:`Set AI Model for Template Installation`}),(0,K.jsx)(T,{tone:`muted`,className:`mt-2 mb-5`,children:`This model will be used by the workflow to process and install the template`}),(0,K.jsx)(w1r,{defaultProvider:u||``,defaultModel:d||``,updateModel:f||(()=>Promise.resolve({message:`Updated`})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:`Provider`})]})]}),t&&!s&&(0,K.jsx)(X,{className:c(`mt-4 flex min-h-10 w-full items-center justify-center gap-2 rounded-lg bg-card state-layer text-foreground`,`[&_svg]:h-[1.1em] [&_svg]:text-foreground [&>svg]:w-[1.1em]`),onClick:a,disabled:!t||!u||!d||i.length>0||l,children:l?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(It,{className:`h-4 w-4`}),` Installing...`]}):(0,K.jsxs)(K.Fragment,{children:[`Install `,(0,K.jsx)(oH,{})]})})]})})}function RPi({title:e,description:t,githubUrl:n,isLoading:r,infoData:i,templateSlug:a}){let o=a?`feat/install-template-${a}`:`feat/install-template-[slug]`;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`mt-5 grid items-center`,children:(0,K.jsxs)(`div`,{className:c(`flex items-center gap-3`,`[&>svg]:h-[1.2em] [&>svg]:w-[1.2em] [&>svg]:opacity-50`,{"[&>svg]:opacity-20":r}),children:[(0,K.jsx)(OZ,{}),(0,K.jsx)(`h2`,{className:c({"flex min-w-[50%] rounded-lg bg-muted":r}),children:(0,K.jsx)(T,{as:`span`,variant:`title`,className:`block`,children:r?(0,K.jsx)(K.Fragment,{children:`\xA0`}):e})})]})}),(0,K.jsxs)(`div`,{className:`grid gap-x-24 lg:grid-cols-[1fr_1fr]`,children:[(0,K.jsxs)(`div`,{className:`grid`,children:[(0,K.jsx)(T,{tone:`muted`,className:c(`mt-2 mb-4`,{"rounded-lg bg-muted":r}),children:r?(0,K.jsx)(K.Fragment,{children:`\xA0`}):t}),!r&&a&&(0,K.jsxs)(`div`,{className:c(`mb-4 rounded-lg border border-border bg-background p-4`,`flex items-start gap-3`),children:[(0,K.jsx)(`div`,{className:`mt-0.5 shrink-0`,children:(0,K.jsx)(Yx,{className:`h-[1.1em] w-[1.1em] text-info-indicator`})}),(0,K.jsxs)(`div`,{className:`flex-1 space-y-2`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(KS,{className:`h-[1em] w-[1em] text-muted-foreground`}),(0,K.jsx)(T,{as:`span`,variant:`subheading`,tone:`ink`,children:`A new Git branch will be created`})]}),(0,K.jsxs)(`div`,{className:`space-y-1`,children:[(0,K.jsxs)(T,{tone:`muted`,as:`p`,variant:`caption`,children:[(0,K.jsx)(T,{as:`span`,variant:`column`,children:`Branch name:`}),` `,(0,K.jsx)(uX,{children:o})]}),(0,K.jsx)(T,{tone:`muted`,as:`p`,variant:`caption`,children:`This ensures safe installation with easy rollback if needed. Your main branch remains unchanged.`})]})]})]}),n&&(0,K.jsxs)(`a`,{href:n,target:`_blank`,rel:`noopener noreferrer`,className:c(`text-muted-foreground hover:text-foreground`,`mt-auto flex items-center gap-2`),children:[(0,K.jsx)(kZ,{}),(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:n?.split(`/`)?.pop()})]})]}),i&&(0,K.jsx)(O1r,{data:i,labelsAreHidden:!0,isLoading:r})]})]})}function zPi(e){switch(e){case`running`:return(0,K.jsx)(It,{size:`sm`,"aria-hidden":!0});case`success`:return(0,K.jsx)(pC,{"aria-hidden":!0});case`failed`:return(0,K.jsx)(xw,{"aria-hidden":!0});default:return null}}function BPi(){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 VPi({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)(BPi,{}):zPi(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:zPi(e)})}function HPi({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)(VPi,{status:e.status,variant:r})]})}function UPi({currentStep:e,steps:t=[],className:n}){return(0,K.jsx)(`div`,{className:c(n),children:t.map((t,n)=>(0,K.jsx)(HPi,{step:t,isActive:e?.id===t.id,position:n+1},t.id))})}function WPi({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 GPi=(0,G.createContext)(3);function KPi({title:e,description:t,action:n,done:r,className:i,children:a}){let o=(0,G.useContext)(GPi);return(0,K.jsxs)(`li`,{className:c(`group/step grid grid-cols-[1.5rem_minmax(0,1fr)] gap-x-4 [counter-increment:ds-step]`,i),children:[(0,K.jsxs)(`div`,{className:`flex flex-col items-center`,children:[(0,K.jsx)(`span`,{className:c(`flex size-6 shrink-0 items-center justify-center rounded-full`,u.colors,r?`bg-success-indicator/18 text-success-indicator`:`bg-fill text-foreground`),children:r?(0,K.jsx)(pC,{className:`size-icon-sm`,"aria-label":`Done`}):(0,K.jsx)(T,{as:`span`,variant:`column`,className:`before:content-[counter(ds-step)]`,"aria-hidden":!0})}),(0,K.jsx)(`span`,{"aria-hidden":!0,className:`w-px flex-1 bg-border group-last/step:hidden`})]}),(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-3 pb-8 group-last/step:pb-0`,children:[(0,K.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,K.jsxs)(`div`,{className:`flex min-h-6 flex-wrap items-center justify-between gap-x-6 gap-y-2`,children:[(0,K.jsx)(T,{as:o===2?`h2`:`h3`,variant:`label`,className:`text-pretty`,children:e}),n==null?null:(0,K.jsx)(`div`,{className:`flex shrink-0 items-center gap-2`,children:n})]}),t==null?null:(0,K.jsx)(T,{as:`p`,variant:`body-sm`,tone:`muted`,className:`max-w-[70ch] text-pretty`,children:t})]}),a]})]})}function qPi({headingLevel:e=3,className:t,children:n}){return(0,K.jsx)(GPi.Provider,{value:e,children:(0,K.jsx)(`ol`,{className:c(`flex flex-col [counter-reset:ds-step]`,t),children:n})})}Object.assign(qPi,{Step:KPi});function JPi({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)(FPi,{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)(WPi,{steps:h})}),s&&i===`error`&&(0,K.jsxs)(`div`,{className:c(`text-foreground`,`flex items-center gap-3 rounded-lg bg-destructive-subtle p-4`,`[&>svg]:h-6 [&>svg]:w-6 [&>svg]:text-destructive-foreground [&>svg]:opacity-70`),children:[(0,K.jsx)(qx,{}),(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:s||`Something went wrong`})]}),u&&(0,K.jsx)(UPi,{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 YPi({name:e,installedEntities:t}){return(0,K.jsxs)(FPi,{className:c(`grid content-center items-center justify-items-center gap-4`,`[&>svg]:h-8 [&>svg]:w-8`),children:[(0,K.jsx)(OZ,{}),(0,K.jsx)(T,{as:`h2`,variant:`heading`,children:`Done!`}),(0,K.jsxs)(T,{tone:`muted`,className:`text-center`,children:[`The `,(0,K.jsx)(`b`,{className:`text-muted-foreground`,children:e}),` template has been successfully installed.`,t&&t.length>0&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`br`,{}),` Installed entities are listed below.`]})]}),t&&t.length>0&&(0,K.jsx)(O1r,{data:t})]})}function XPi(){let{templateSlug:e}=kv(),t=[{id:`templates`,label:`Templates`,to:`/templates`},{id:`template`,label:Zjt(e)}],[n,r]=Rv(),[i,a]=(0,G.useState)(``),[o,s]=(0,G.useState)(``),[l,u]=(0,G.useState)(``),[d,f]=(0,G.useState)({}),[p,m]=(0,G.useState)([]),[h,g]=(0,G.useState)(null),[_,v]=(0,G.useState)(!1),[y,b]=(0,G.useState)(``),[x,S]=(0,G.useState)(!1),[C,w]=(0,G.useState)(!1),[T,E]=(0,G.useState)([]),{data:D,isLoading:O}=vPi({repoOrSlug:e,owner:`mastra-ai`}),k=`1.84.0-alpha.7`.includes(`beta`)??!1?`beta`:`main`,{data:A,isLoading:j}=yPi({repo:D?.githubUrl?new URL(D.githubUrl).pathname.split(`/`)[2]:`template-${e}`,owner:`mastra-ai`,branch:k}),{data:M,isLoading:N}=bPi(),{mutateAsync:P,isPending:F}=xPi(),{mutateAsync:I}=SPi(),{streamInstall:L,streamResult:R,isStreaming:z}=DPi({workflowInfo:M}),{observeInstall:B,streamResult:V,isStreaming:H}=OPi({workflowInfo:M});(0,G.useEffect)(()=>{let e=n.get(`runId`);!e||_||h||z||H||(console.info(`🔄 Checking completed run after hot reload:`,{runId:e}),b(e),I({runId:e}).then(e=>{let t=e.snapshot;if(t?.status===`success`&&t?.result?.success)v(!0);else if(t?.result?.success===!1){if(t?.result?.validationResults&&!t?.result?.validationResults?.valid&&t?.result?.validationResults?.remainingErrors>0){let{remainingErrors:e,errors:n}=t.result.validationResults,r=`Template installation completed but ${e} validation issue${e>1?`s`:``} remain unresolved.`;g(r),E(n||[])}else{let e=t?.result?.message||t?.result?.error||`Template installation failed`;g(typeof e==`string`?e:String(e))}}}).catch(e=>{console.error(`❌ Failed to fetch run details:`,e),g(`Failed to retrieve installation status after reload`)}))},[n,_,h,z,H,I]),(0,G.useEffect)(()=>{let e=n.get(`runId`),t=n.get(`resume`),i=n.get(`provider`);if(e&&t===`true`&&i&&!z&&!H&&!x&&!C&&M){b(e),S(!0);try{I({runId:e}).then(t=>{if(t.snapshot?.status===`running`)return B.mutateAsync({runId:e})}).then(()=>{r(e=>{let t=new URLSearchParams(e);return t.delete(`resume`),t})}).catch(e=>{console.error(`❌ Failed to resume template installation:`,e),e.message?.includes(`404`)||e.message?.includes(`not found`)?g(`Template installation run not found. It may have expired or been completed.`):g(`Failed to resume template installation. Please try again.`)})}catch(e){console.error(`❌ Auto-resume failed with error:`,e),g(`Failed to resume template installation. Please refresh and try again.`)}}},[n,e,z,H,x,C,M,I,B,r]);let ee=[{value:`openai`,label:`OpenAI`},{value:`anthropic`,label:`Anthropic`},{value:`groq`,label:`Groq`},{value:`google`,label:`Google`}],te=[{key:`tools`,label:`Tools`,value:D?.tools?.length?D.tools.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(XN,{})},{key:`agents`,label:`Agents`,value:D?.agents?.length?D.agents.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(HN,{})},{key:`workflows`,label:`Workflows`,value:D?.workflows?.length?D.workflows.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(ZS,{})},{key:`providers`,label:`Providers`,value:D?.supportedProviders?.length?D.supportedProviders.join(`, `):`n/a`,icon:(0,K.jsx)(k3,{})},{key:`tags`,label:`Tags`,value:D?.tags?.length?D.tags.join(`, `):`n/a`,icon:(0,K.jsx)(wX,{})}],U=[{...te[0]},{...te[1]},{...te[2]}].filter(e=>e.value!==`n/a`);return(0,G.useEffect)(()=>{A&&f(A)},[A]),(0,G.useEffect)(()=>{let e=R||V;e?.phase===`error`&&e?.error&&g(typeof e.error==`string`?e.error:String(e.error))},[R?.phase,R?.error,V?.phase,V?.error]),(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(`div`,{className:c(`h-full w-full overflow-y-scroll lg:px-12`),children:(0,K.jsxs)(`div`,{className:`mx-auto grid w-full max-w-[80rem] gap-y-4 p-4`,children:[(0,K.jsx)(RPi,{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)(JPi,{name:D.title,streamResult:H?V:R,runId:y,workflowInfo:M}),_&&(0,K.jsx)(YPi,{name:D.title,installedEntities:U,linkComponent:Lv}),h&&(0,K.jsx)(IPi,{errorMsg:h,validationErrors:T.length>0?T:R?.validationResults?.errors||V?.validationResults?.errors}),!z&&!H&&!_&&!h&&(0,K.jsx)(LPi,{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 ZPi=e=>e.threadId;function QPi(e,t){return`traces`in e?{traces:{...e.traces,to:t}}:{threads:{...e.threads,to:t}}}var $Pi=e=>`traces`in e?e.traces:e.threads;function eFi(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 tFi({query:e,rolling:t,autoRefetch:n=!0,limit:r,enabled:i=!0}){let a=Y(),{anchorTo:o,reanchor:s}=BNi(e),c=(0,G.useMemo)(()=>o?{...e,timeRange:QPi(e.timeRange,o)}:e,[e,o]),l=nXr({query:c,limit:r,enabled:i,queryOptions:INi}),{headRows:u}=HNi({queryKey:[`threads`,e],fetchHead:async t=>(await a.queryTraceThreads({...e,timeRange:QPi(e.timeRange,t),orderBy:[{field:`endedAt`,direction:`desc`}],page:{limit:50}})).threads,getId:ZPi,getEndedAt:e=>e.endedAt,since:Date.parse($Pi(c.timeRange).to),enabled:i&&t&&n&&l.threads!==void 0&&!l.isFetching&&!l.isError,onOverflow:s}),{orderBy:d}=e,f=l.threads,p=(0,G.useMemo)(()=>f&&WNi(f,u,{getId:ZPi,compare:eFi(d),hasNextPage:l.hasNextPage}),[f,u,d,l.hasNextPage]);return{...l,threads:p}}function nFi(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 rFi=[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`],iFi=[];function aFi(){let{data:e}=i5(),t=e?.capabilities.traceQueryTimeToFirstChunk??!1,n=e?.capabilities.traceQueryTimeToFirstToken??!1,{data:r=iFi}=t8(),{data:i=iFi}=n8();return(0,G.useMemo)(()=>[l3r,...Mai({withTimeToFirstChunk:t,withTimeToFirstToken:n,entityNames:r,environments:i})],[t,n,r,i])}function oFi({tokens:e,groups:t,onFiltersChange:n}){let r=(0,G.useMemo)(()=>P8(e),[e]),i=(0,G.useMemo)(()=>{let e=F8([],t);return{...e,nodes:[p5,...r,...e.nodes]}},[r,t]),a=(0,G.useCallback)(e=>{let t=VZr({...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 sFi=e=>e;function cFi({datePreset:e,dateFrom:t,dateTo:n,minDate:r,tokens:i,groups:a,onDatePresetChange:o,onDateChange:s,onDateRangeChange:c,onFiltersChange:l,disabled:u}){let d=aFi(),{filterBarValue:f,onFilterBarChange:p}=oFi({tokens:i,groups:a,onFiltersChange:l});return(0,K.jsxs)(m5,{fields:d,operators:mZr,value:f,onValueChange:p,createItemId:sFi,maxDepth:3,"aria-label":`Thread filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(m5.Chips,{renderChip:i=>i.fieldId===`timeRange`?(0,K.jsx)(m5.TimeRange,{preset:e,onPresetChange:o,dateFrom:t,dateTo:n,minDate:r,onDateChange:s,onDateRangeChange:c,disabled:u,presets:rFi,defaultPreset:o5.datePreset}):(0,K.jsx)(m5.Chip,{item:i})}),(0,K.jsx)(m5.Input,{placeholder:`Filter threads`})]})}function lFi({selectedThreadId:e,onSelectedThreadChange:t,onOpenScore:n,urlState:r}){let i=RNi(r),{timeRange:a,tokens:o,groups:s,sort:c}=i,l=a5().enabled,u=c2r().enabled,d=iii({scope:`threads`}),{data:f,isLoading:p}=i5(),m=f?.capabilities.traceQueryTimeToFirstChunk??!1,h=f?.capabilities.traceQueryTimeToFirstToken??!1,g=(0,G.useMemo)(()=>p?d.preferences:C0r(d.preferences,{withTimeToFirstChunk:m,withTimeToFirstToken:h}),[d.preferences,p,m,h]),{threads:_,hasNextPage:v,isFetchingNextPage:y,setEndOfListElement:b,isLoading:x,isError:S,error:C}=tFi({query:(0,G.useMemo)(()=>{let e=Fai(o,s,{withTimeToFirstChunk:m,withTimeToFirstToken:h});return{timeRange:{traces:a},orderBy:[{field:`startedAt`,direction:c.direction}],...e?{where:e}:{}}},[a,c,o,s,m,h]),rolling:i.rolling}),w=(0,G.useMemo)(()=>(_??[]).map(nFi),[_]),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)(q0r,{toolbar:(0,K.jsxs)(K.Fragment,{children:[r&&(0,K.jsx)(Foi,{page:`threads`,...r,columns:d}),(0,K.jsxs)(TK,{children:[(0,K.jsx)(TK.Start,{children:(0,K.jsx)(cFi,{datePreset:i.datePreset,dateFrom:i.dateFrom,dateTo:i.dateTo,tokens:o,groups:s,onDatePresetChange:i.onDatePresetChange,onDateChange:i.onDateChange,onDateRangeChange:i.onDateRangeChange,onFiltersChange:i.onFiltersChange,disabled:x})}),(0,K.jsx)(TK.End,{children:(0,K.jsx)(d2r,{scope:`threads`,value:d.preferences,onChange:d.setPreferences})})]})]}),error:S?(0,K.jsx)(Q8,{error:C,resource:`threads`,errorTitle:`Failed to load threads`}):void 0,empty:D?(0,K.jsx)(t0r,{resource:`threads`,datePreset:i.datePreset,dateFrom:i.dateFrom,dateTo:i.dateTo}):void 0,children:(0,K.jsx)(h7r,{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)(Uri,{open:!!e,threadId:e??``,depth:1,closeLabel:`Close`,withQueryTrace:l,withFeedback:u,onOpenScore:n,onClose:()=>t(void 0)})]})}function uFi(){let{enabled:e,isLoading:t}=n2r(),n=Ov(),[r,i]=Rv();return(0,K.jsx)(FNi,{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)(lFi,{urlState:{searchParams:r,setSearchParams:i},selectedThreadId:XNi(r),onSelectedThreadChange:e=>i(t=>ZNi(t,e),{replace:!0}),onOpenScore:(e,t)=>n(CK(e,t))})})}var dFi=()=>(0,K.jsx)(Jx,{titleSlot:`No Workflows yet`,descriptionSlot:(0,K.jsxs)(K.Fragment,{children:[`Mastra workflows are not configured yet. `,(0,K.jsx)(`br`,{}),`More information in the documentation.`]}),actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/docs/workflows/overview`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(tP,{}),children:`Workflows documentation`}),variant:`fill`});function fFi(e,t,n){return IZ(e,t,{name:e=>e.name,running:e=>n[e.id]?.running??0,suspended:e=>n[e.id]?.suspended??0,steps:e=>Object.keys(e.steps??{}).length})}function pFi(e){return Object.keys(e.steps??{}).filter(t=>e.allSteps?.[t]?.isWorkflow)}function mFi(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 hFi(e,t,n){let r=mFi(t),i=[],a=(e,o,s,c,l,u)=>{let d=pFi(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 gFi=`auto 24rem minmax(0, 1fr) auto auto auto`;function _Fi({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 vFi({row:e,isExpanded:t,onToggle:n}){let r=e.kind===`workflow`&&e.nestedIds.length>0,i=e.kind===`workflow`?e.workflow.name:e.stepId;return(0,K.jsx)(`div`,{className:`flex items-center pl-5`,children:r?(0,K.jsx)(`button`,{type:`button`,"aria-expanded":t,"aria-label":`${t?`Collapse`:`Expand`} nested workflows of ${i}`,className:c(SS,`relative grid size-5 shrink-0 place-items-center before:absolute before:-inset-1.5 before:content-['']`),onClick:e=>{e.stopPropagation(),n()},children:(0,K.jsx)(y,{direction:`right`,className:`size-4`})}):(0,K.jsx)(`span`,{className:`size-5 shrink-0`,"aria-hidden":!0})})}var yFi=e=>e.stopPropagation();function bFi({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 xFi({row:e,isExpanded:t,onToggle:n,runCount:r,rowProps:i}){let{paths:a,Link:o}=sn(),s=(0,G.useRef)(null),{workflow:c,nestedIds:l}=e,u=dJ(c.name,50),d=dJ(c.description??``,200),f=Object.keys(c.steps??{}).length,p=r?.running??0,m=r?.suspended??0,h=l.length>0;return(0,K.jsxs)(Z.RowWrapper,{...i,onSelectRow:()=>s.current?.click(),children:[(0,K.jsx)(vFi,{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:yFi,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)(_Fi,{guides:e.guides,isLastChild:e.isLastChild}):null,(0,K.jsx)(`span`,{className:`truncate`,children:u}),c.origin===`dynamic`?(0,K.jsx)(eC,{size:`xs`,variant:`blue`,title:`Registered via the dynamic-workflows API`,children:`Dynamic`}):null,h?(0,K.jsxs)(T,{as:`span`,variant:`body-sm`,tone:`muted`,title:`Nested workflows: ${l.join(`, `)}`,className:`inline-flex shrink-0 items-center gap-1`,children:[(0,K.jsx)(ZS,{"aria-hidden":!0,className:`size-icon-sm`}),l.length]}):null]})}),(0,K.jsx)(Z.DescriptionCell,{children:d}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:p>0?(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-info-indicator`,"aria-label":`${p} run${p===1?``:`s`} in progress`,children:[(0,K.jsx)(`span`,{"aria-hidden":!0,className:`size-2 rounded-full bg-info-indicator motion-safe:animate-pulse`}),p]}):``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:m>0?(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-warning-foreground`,"aria-label":`${m} run${m===1?``:`s`} awaiting input`,children:[(0,K.jsx)(ET,{"aria-hidden":!0,className:`size-icon-sm`}),m]}):``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:f||``})]})]})}function SFi({workflows:e,isLoading:t,search:n=``,sort:r,onSortChange:i,requestContext:a}){let[o,s]=(0,G.useState)(new Set),l=wEt({requestContext:a}),u=(0,G.useMemo)(()=>Object.entries(e).map(([e,t])=>({...t,id:e})),[e]),d=(0,G.useMemo)(()=>{let e=n.toLowerCase();return u.filter(t=>t.name?.toLowerCase().includes(e)||t.description?.toLowerCase().includes(e))},[u,n]),f=(0,G.useMemo)(()=>fFi(d,r,l),[d,r,l]),m=(0,G.useMemo)(()=>hFi(f,e,o),[f,e,o]),h=(0,G.useMemo)(()=>{let e=new Map;for(let t of m)t.kind===`workflow`&&e.set(t.pathKey,e.size);return e},[m]),{containerRef:g,getRowProps:_}=PZ({count:h.size,global:!0}),v=e=>{s(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})};return t?(0,K.jsx)(DH,{columns:gFi,fit:`container`}):(0,K.jsxs)(Z,{columns:gFi,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)(bFi,{sortKey:`name`,sort:r,onSortChange:i,children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`Description`}),(0,K.jsx)(bFi,{sortKey:`running`,sort:r,onSortChange:i,children:`Running`}),(0,K.jsx)(bFi,{sortKey:`suspended`,sort:r,onSortChange:i,children:`Pending input`}),(0,K.jsx)(bFi,{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)(vFi,{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)(_Fi,{guides:e.guides,isLastChild:e.isLastChild}),(0,K.jsx)(`span`,{className:`truncate`,children:dJ(e.stepId,50)}),(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{render:(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`muted`}),role:`note`,tabIndex:0,className:c(`shrink-0 rounded-sm`,p),children:`not registered`}),(0,K.jsx)(Tx,{className:`max-w-72`,children:`Runs as a step of its parent workflow. Add it to the workflows of your Mastra instance to open, run, and inspect it on its own page.`})]})]})}),(0,K.jsx)(Z.DescriptionCell,{children:dJ(e.description??``,200)}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:``})]})]},`workflow-${e.pathKey}`):(0,K.jsx)(xFi,{row:e,isExpanded:t,onToggle:n,runCount:l[e.workflow.id],rowProps:_(h.get(e.pathKey)??-1)},`workflow-${e.pathKey}`)})]})}var K9=[eP(`/workflows`)];function CFi(){let{data:e,isLoading:t,error:n}=eN(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)();return n&&FN(n)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:K9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(TH,{variant:`fill`})]}):n&&IN(n)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:K9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(wH,{variant:`fill`,resource:`workflows`})]}):n?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:K9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load workflows`,descriptionSlot:n.message})]}):Object.keys(e||{}).length===0&&!t?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:K9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(dFi,{})]}):(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:K9}),actionRow:(0,K.jsxs)(TK,{children:[(0,K.jsx)(TK.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(MH,{...NH,onValueChange:i,label:`Search workflows`,placeholder:`Search by name or description`})})}),(0,K.jsx)(TK.End,{children:(0,K.jsx)(X,{render:(0,K.jsx)(Lv,{to:`/workflows/schedules`}),variant:`primary`,icon:(0,K.jsx)(qS,{}),children:`Schedules`})})]}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(SFi,{workflows:e||{},isLoading:t,search:r,sort:a,onSortChange:(e,t)=>o({key:t,direction:e})})]})}var wFi={active:`bg-success-indicator`,paused:`bg-info-indicator`,completed:`bg-muted-foreground`},TFi={active:`text-success-indicator`,paused:`text-info-indicator`,completed:`text-muted-foreground`},EFi=({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 ${wFi[e]}`,"aria-hidden":!0}),(0,K.jsx)(T,{as:`span`,variant:`caption`,className:TFi[e],children:e})]});function DFi({status:e}){let{icon:t,color:n}=OFi(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 OFi(e){switch(e){case`success`:return{icon:(0,K.jsx)(pC,{className:`size-icon-sm`}),color:`text-success-indicator`};case`failed`:return{icon:(0,K.jsx)(xw,{className:`size-icon-sm`}),color:`text-destructive-foreground`};case`running`:return{icon:(0,K.jsx)(It,{}),color:`text-muted-foreground`};case`suspended`:return{icon:(0,K.jsx)(ET,{className:`size-icon-sm`}),color:`text-info-indicator`};case`canceled`:return{icon:(0,K.jsx)(Kx,{className:`size-icon-sm`}),color:`text-muted-foreground`};case`pending`:case`waiting`:return{icon:(0,K.jsx)(tC,{className:`size-icon-sm`}),color:`text-muted-foreground`};default:return{icon:null,color:`text-muted-foreground`}}}var kFi=`auto auto auto auto 1fr`,AFi=3e4,jFi=3e5;function MFi({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:i,setEndOfListElement:a}){let{Link:o,paths:s}=sn(),c=e=>!!(n&&e.runId&&e.outcome!==`failed`),l=e.filter(c).length,{containerRef:u,getRowProps:d}=PZ({count:l}),f=-1;return t?(0,K.jsx)(DH,{columns:kFi}):e.length===0?(0,K.jsx)(T,{variant:`body`,tone:`muted`,className:`p-4`,children:`No trigger history yet.`}):(0,K.jsxs)(Z,{columns:kFi,className:`min-w-0`,scrollRef:u,children:[(0,K.jsxs)(Z.Top,{children:[(0,K.jsx)(Z.TopCell,{children:`Run`}),(0,K.jsx)(Z.TopCell,{children:`Status`}),(0,K.jsx)(Z.TopCell,{children:`Started`}),(0,K.jsx)(Z.TopCell,{children:`Duration`}),(0,K.jsx)(Z.TopCell,{children:` `})]}),e.map(e=>{let t=e.actualFireAt-e.scheduledFireAt,r=iC(t,{signed:!0}),i=e.outcome===`failed`,a=i?e.error:e.run?.error,l=Math.abs(t),u=!i&&l>AFi&&l<=jFi,p=`${e.scheduleId}-${e.runId}-${e.actualFireAt}`,m=c(e);m&&(f+=1);let h=(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,tone:m?`ink`:`muted`,className:`whitespace-nowrap`,children:e.runId}),g=(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Z.Cell,{children:h}),(0,K.jsx)(Z.Cell,{children:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[i?(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`inline-flex items-center gap-1.5 whitespace-nowrap text-destructive-foreground`,children:[(0,K.jsx)(Zx,{className:`size-icon-sm`}),`publish failed`]}):e.run?(0,K.jsx)(DFi,{status:e.run.status}):(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`inline-flex items-center gap-1.5 whitespace-nowrap`,children:`pending`}),a?(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{asChild:!0,children:(0,K.jsx)(`span`,{className:`inline-flex text-destructive-foreground`,children:(0,K.jsx)(Zx,{className:`size-icon-sm`})})}),(0,K.jsx)(Tx,{children:a})]}):null]})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-2 whitespace-nowrap`,children:[e.actualFireAt?(0,K.jsx)(Dk,{value:e.actualFireAt}):`—`,u?(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{asChild:!0,children:(0,K.jsx)(`span`,{className:`inline-flex text-info-indicator`,children:(0,K.jsx)(Zx,{className:`size-icon-sm`})})}),(0,K.jsxs)(Tx,{children:[`Published `,r,` after the scheduled fire time`]})]}):null]})}),(0,K.jsx)(Z.Cell,{children:e.run?(0,K.jsx)(T,{as:`span`,variant:`body-sm`,font:`mono`,children:iC(e.run.durationMs)||`—`}):(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`—`})}),(0,K.jsx)(Z.Cell,{children:` `})]});return m?(0,K.jsx)(Z.RowLink,{to:s.workflowRunLink(n,e.runId),LinkComponent:o,...d(f),children:g},p):(0,K.jsx)(Z.RowStatic,{children:g},p)}),(0,K.jsx)(Z.NextPageLoading,{isLoading:i,hasMore:r,setEndOfListElement:a})]})}var NFi={id:`workflow-schedules`,label:`Schedules`,icon:qS,to:`/workflows/schedules`};function PFi({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 FFi(){let{scheduleId:e}=kv(),t=[eP(`/workflows`),NFi,{id:`schedule`,label:Zjt(e),icon:qS}],{paths:n}=sn(),{data:r,error:i}=vMt({scheduleId:e,queryOptions:{enabled:!!e}}),{data:a,isLoading:o,error:s,hasNextPage:c,isFetchingNextPage:l,setEndOfListElement:u}=xMt({scheduleId:e,queryOptions:{enabled:!!e}}),d=SMt({scheduleId:e});if(i&&FN(i))return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(TH,{variant:`fill`})]});if(i&&IN(i))return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(wH,{variant:`fill`,resource:`schedules`})]});if(i)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load schedule`,descriptionSlot:i.message})]});let f=r?.workflowId,p=r?.agentId;return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:t}),actionRow:(0,K.jsx)(TK,{children:(0,K.jsxs)(TK.End,{children:[(0,K.jsx)(X,{render:(0,K.jsx)(Lv,{to:n.schedulesLink()}),variant:`ghost`,icon:(0,K.jsx)(sS,{}),children:`Back to schedules`}),f?(0,K.jsx)(X,{icon:(0,K.jsx)(ZS,{}),render:(0,K.jsx)(Lv,{to:n.workflowLink(f)}),variant:`ghost`,children:`Open workflow`}):null,r&&r.status!==`completed`?(0,K.jsx)(X,{onClick:()=>{let e=r.status===`active`?`pause`:`resume`;d.mutate(e,{onSuccess:()=>iS.success(e===`pause`?`Schedule paused`:`Schedule resumed`),onError:e=>iS.error(e.message)})},disabled:d.isPending,"data-testid":`schedule-toggle-button`,children:r.status===`active`?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(ET,{}),`Pause`]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(DT,{}),`Resume`]})}):null]})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),r?(0,K.jsxs)(`div`,{className:`grid h-full grid-cols-[minmax(0,20rem)_1fr] gap-4 overflow-hidden`,children:[(0,K.jsxs)(`div`,{className:`flex h-fit flex-col gap-4 rounded-md border border-border p-4`,children:[(0,K.jsx)(PFi,{label:p?`Agent`:`Workflow`,children:f?(0,K.jsx)(Lv,{to:n.workflowLink(f),className:`text-foreground hover:underline`,children:f}):p?(0,K.jsx)(Lv,{to:n.agentLink(p),className:`text-foreground hover:underline`,children:p}):`—`}),(0,K.jsxs)(PFi,{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)(PFi,{label:`Status`,children:(0,K.jsx)(EFi,{status:r.status})}),(0,K.jsx)(PFi,{label:`Next fire`,children:r.nextFireAt?(0,K.jsx)(Dk,{value:r.nextFireAt}):`—`})]}),(0,K.jsxs)(`div`,{className:`overflow-y-auto`,"data-testid":`schedule-triggers-panel`,children:[(0,K.jsx)(T,{variant:`body`,className:`mb-3`,children:`Trigger history`}),s?(0,K.jsx)(Jx,{tone:`error`,titleSlot:`Failed to load trigger history`,descriptionSlot:s.message}):(0,K.jsx)(MFi,{triggers:a??[],isLoading:o,workflowId:f,hasNextPage:c,isFetchingNextPage:l,setEndOfListElement:u})]})]}):null]})}var IFi={target:e=>e.workflowId??e.agentId??``,status:e=>e.status,nextFireAt:e=>e.nextFireAt,lastFireAt:e=>e.lastFireAt},LFi=`minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto`;function RFi({schedules:e,isLoading:t,search:n=``,sort:r,onSortChange:i}){let{paths:a,Link:o}=sn(),s=(0,G.useMemo)(()=>{let t=n.toLowerCase();return IZ(t?e.filter(e=>e.id.toLowerCase().includes(t)||(e.workflowId??e.agentId??``).toLowerCase().includes(t)):e,r,IFi)},[e,n,r]),{containerRef:c,getRowProps:l}=PZ({count:s.length,global:!0});if(t)return(0,K.jsx)(DH,{columns:LFi});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:LFi,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)(EFi,{status:e.status})}),(0,K.jsx)(Z.Cell,{children:e.nextFireAt?(0,K.jsx)(Dk,{value:e.nextFireAt}):`—`}),(0,K.jsx)(Z.Cell,{children:e.lastRun?(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-2 whitespace-nowrap`,children:[(0,K.jsx)(DFi,{status:e.lastRun.status}),e.lastFireAt?(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:(0,K.jsx)(Dk,{value:e.lastFireAt})}):null]}):e.lastFireAt?(0,K.jsx)(Dk,{value:e.lastFireAt}):(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`Never`})})]},e.id))]})}function zFi({workflowId:e}={}){let{data:t,isLoading:n,error:r}=yMt(e?{workflowId:e}:{}),[i,a]=(0,G.useState)(``),[o,s]=(0,G.useState)();return r?(0,K.jsx)(Jx,{tone:`error`,titleSlot:`Failed to load schedules`,descriptionSlot:r.message}):(0,K.jsxs)(`div`,{className:`grid h-full grid-rows-[auto_1fr] gap-4 overflow-hidden`,children:[(0,K.jsx)(`div`,{className:`max-w-120`,children:(0,K.jsx)(MH,{...NH,onValueChange:a,label:`Search schedules`,placeholder:`Search by id or workflow`})}),(0,K.jsx)(`div`,{className:`overflow-y-auto`,children:(0,K.jsx)(RFi,{schedules:t??[],isLoading:n,search:i,sort:o,onSortChange:(e,t)=>s({key:t,direction:e})})})]})}var BFi=[eP(`/workflows`),NFi];function VFi(){let[e]=Rv(),t=e.get(`workflowId`)??void 0,{error:n}=yMt(t?{workflowId:t}:{});return n&&FN(n)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:BFi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(TH,{variant:`fill`})]}):n&&IN(n)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:BFi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(wH,{variant:`fill`,resource:`schedules`})]}):(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:BFi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(`div`,{className:`h-full`,children:(0,K.jsx)(zFi,{workflowId:t})})]})}var HFi=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),UFi={"--belt-hue":`var(--warning-indicator)`};function WFi(e){let t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function GFi(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 KFi({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:(0,K.jsxs)(`section`,{className:c(REt,`pointer-events-auto relative isolate`),"data-testid":`workflow-suspended-steps`,"aria-label":`Step suspended`,children:[(0,K.jsxs)(`div`,{className:`max-h-[calc(100cqh-64px)] overflow-y-auto overscroll-contain rounded-[inherit]`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-3 border-b border-border bg-background px-5 py-4`,children:[(0,K.jsxs)(T,{as:`h2`,variant:`column`,tone:`ink`,className:`flex items-center gap-2`,children:[(0,K.jsx)(Dx,{children:(0,K.jsx)(ET,{})}),`Step suspended`]}),(0,K.jsx)(eC,{variant:`orange`,emphasis:`subtle`,children:`Needs input`})]}),e.map(e=>{let n=t.allSteps[e.stepId];if(!n||n.isWorkflow)return null;let i=n?.resumeSchema?zO(nk(n.resumeSchema)):Ad(q(),md());return(0,K.jsx)(qFi,{step:e,stepSchema:i,description:n.description,onResume:r},`${e.runId}-${e.stepId}`)})]}),(0,K.jsx)(kXe,{status:`ready`,label:`Needs input`,className:`before:hidden`,style:UFi})]})}function qFi({step:e,stepSchema:t,description:n,onResume:r}){let[i,a]=(0,G.useState)(!1),[o,s]=(0,G.useState)(!1);return(0,K.jsxs)(`div`,{className:`space-y-5 p-5 [&+&]:border-t [&+&]:border-border`,children:[(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(T,{as:`p`,variant:`subheading`,tone:`ink`,className:`break-words`,children:e.stepId}),n&&(0,K.jsx)(T,{as:`p`,variant:`caption`,tone:`muted`,children:n})]}),e.suspendPayload!==void 0&&(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsxs)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`flex items-center gap-2`,children:[(0,K.jsx)(Dx,{children:(0,K.jsx)(HFi,{})}),`The step is asking`]}),(0,K.jsxs)(DC,{open:i,onOpenChange:a,children:[(0,K.jsxs)(OC,{className:c(`bg-card hover:bg-card active:bg-card shadow-raised [--field:var(--field-on-surface)] [--field-disabled:var(--field-on-surface)] [--field-rim:var(--field-rim-on-surface)]`,`flex w-full items-center justify-between gap-2 rounded-lg px-3 py-2.5`),children:[(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(Dx,{children:(0,K.jsx)(y,{direction:`right`,className:`text-muted-foreground`})}),(0,K.jsx)(T,{as:`span`,variant:`body`,tone:`ink`,className:`truncate`,children:GFi(e.suspendPayload,e.stepId)})]}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`shrink-0`,children:WFi(e.suspendPayload)})]}),(0,K.jsx)(kC,{children:(0,K.jsx)(`div`,{"data-testid":`suspended-payload`,className:`pt-2`,children:(0,K.jsx)(bw,{value:JSON.stringify(e.suspendPayload,null,2),editable:!1,className:`w-full overflow-x-auto p-2`,showCopyButton:!1})})})]})]}),(0,K.jsxs)(`div`,{className:`space-y-3`,children:[(0,K.jsxs)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`flex items-center gap-2`,children:[(0,K.jsx)(Dx,{children:(0,K.jsx)(R4,{})}),`Your response`]}),(0,K.jsx)(`div`,{className:`-mx-5`,children:(0,K.jsx)(eEt,{schema:t,isSubmitLoading:o,submitButtonLabel:`Resume`,submitButtonVariant:`primary`,submitButtonIcon:(0,K.jsx)(DT,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:async t=>{s(!0);try{await r({stepId:e.stepId.split(`.`),runId:e.runId,resumeData:t})}catch(e){iS.error(e instanceof Error?e.message:`Error resuming workflow`)}finally{s(!1)}}})})]})]})}function JFi({hidden:e,requestContext:t,canResume:n}){let{result:r,workflow:i,runId:a,isStreamingWorkflow:o}=(0,G.useContext)(WS),s=Gft(r,a),c=Xft(t),l=r?.status===`suspended`&&s.length>0&&!o;return!i||!l||!n?null:(0,K.jsx)(`div`,{hidden:e,"data-testid":`workflow-suspended-overlay`,className:`pointer-events-none absolute top-12 right-2 z-30 w-95 max-w-[calc(100%-16px)] animate-in duration-300 fade-in-0 slide-in-from-top-2 motion-reduce:animate-none`,children:(0,K.jsx)(KFi,{suspendedSteps:s,workflow:i,isStreaming:o,onResume:c})},a)}var YFi=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`})),XFi={success:{label:`Completed`,icon:pC},failed:{label:`Failed`,icon:qx},suspended:{label:`Needs input`,icon:ET},waiting:{label:`Waiting`,icon:XS},paused:{label:`Paused`,icon:ET},skipped:{label:`Skipped`,icon:YFi},running:{label:`Running`,icon:TT},canceled:{label:`Canceled`,icon:Kx}},ZFi={label:`Status unavailable`,icon:Lq};function QFi({row:e,isSelected:t,isHovered:n,onSelectStep:r,onHoverStep:i,onOpenInput:a,onOpenOutput:o}){let s=Object.hasOwn(XFi,e.status)?XFi[e.status]:ZFi,l=s.icon,u=Fmt(e.status),d=e.stepId.slice(0,e.stepId.lastIndexOf(`.`)),f=e.isNestedEntry?e.stepId.slice(e.stepId.lastIndexOf(`.`)+1):e.stepId;return(0,K.jsxs)(`div`,{"data-testid":`workflow-timeline-row`,"data-workflow-step-key":e.stepId,onMouseEnter:()=>!e.isNestedEntry&&i(e.stepId),onMouseLeave:()=>!e.isNestedEntry&&i(null),className:c(`grid grid-cols-[minmax(130px,1fr)_minmax(64px,1fr)_56px_64px] items-center gap-3 rounded-md px-2 py-1`,`@max-[540px]/workflow-timeline:grid-cols-[minmax(0,1fr)_48px_64px] @max-[540px]/workflow-timeline:gap-x-1.5 @max-[540px]/workflow-timeline:gap-y-1 @max-[540px]/workflow-timeline:py-2`,(t||n)&&`bg-fill-subtle`),children:[(0,K.jsxs)(`button`,{type:`button`,"aria-disabled":e.isNestedEntry,"aria-pressed":t,onClick:()=>{e.isNestedEntry||r(e.stepId)},title:e.stepId,className:c(`text-foreground`,`flex min-h-9 min-w-0 cursor-pointer items-center gap-2.5 text-left focus-visible:rounded-sm aria-disabled:cursor-default`,p),children:[(0,K.jsx)(`span`,{"aria-label":s.label,className:c(`grid size-6 flex-none place-items-center rounded-md border border-border bg-background`,Imt[u]),children:(0,K.jsx)(l,{"aria-hidden":!0,className:c(`size-3.5`,e.status===`running`&&`motion-safe:animate-spin`)})}),(0,K.jsxs)(`span`,{className:`min-w-0`,children:[(0,K.jsx)(T,{as:`span`,variant:`meta`,className:`block truncate`,children:f}),e.isNestedEntry&&(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`flex min-w-0 items-center gap-1`,children:[(0,K.jsx)(XYe,{"aria-hidden":!0,className:`size-icon-xs shrink-0`}),(0,K.jsx)(`span`,{className:`truncate`,children:d})]})]})]}),(0,K.jsx)(`div`,{className:`relative h-5 min-w-0 overflow-hidden rounded-sm bg-muted @max-[540px]/workflow-timeline:col-span-full @max-[540px]/workflow-timeline:row-start-2 @max-[540px]/workflow-timeline:ml-[34px]`,"aria-hidden":!0,children:e.timing&&(0,K.jsx)(`div`,{"data-testid":`workflow-timeline-bar`,"data-offset":e.timing.offsetPct,"data-width":e.timing.widthPct,className:c(`absolute top-0 h-full min-w-0.5 rounded-sm`,Lmt[u]),style:{left:`${e.timing.offsetPct}%`,width:`${e.timing.widthPct}%`}})}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`text-right whitespace-nowrap`,title:e.timing&&e.spansSuspension?`Includes time spent suspended waiting for input`:void 0,children:e.timing?(0,K.jsx)(T,{as:`span`,variant:`meta`,font:`mono`,children:iC(e.timing.durationMs)}):(0,K.jsx)(`span`,{"aria-label":`Timing unavailable`,children:`—`})}),(0,K.jsxs)(`div`,{className:`flex items-center`,children:[(0,K.jsx)(X,{type:`button`,variant:`ghost`,size:`icon-sm`,tooltip:`View step input`,disabled:e.step.input===void 0,onClick:t=>a(e,t.currentTarget),children:(0,K.jsx)(bk,{})}),(0,K.jsx)(X,{type:`button`,variant:`ghost`,size:`icon-sm`,tooltip:`View step output`,disabled:e.step.output===void 0,onClick:t=>o(e,t.currentTarget),children:(0,K.jsx)(yk,{})})]})]})}var $Fi=e=>e.includes(`.`),eIi=e=>e===`input`||e.endsWith(`.input`),tIi=1;function nIi(e,t){let n=Bmt(e),r=n?.isLive?Math.max(t,n.start):n?.end;return{span:n&&r!==void 0?{start:n.start,end:r}:void 0,isLive:n?.isLive??!1,spansSuspension:n?.spansSuspension??!1}}function rIi(e,t){let n=Object.entries(e).filter(([e])=>!eIi(e)).map(([e,n])=>({stepId:e,step:n,...nIi(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,tIi),100-t)}}return{stepId:e,step:t,status:wk(t)?`suspended`:t.status,timing:s,spansSuspension:a,isRunning:r,isNestedEntry:$Fi(e)}})}var iIi=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`})]})),aIi=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 oIi(){let{steps:e}=e$(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:i}=US(),[a,o]=(0,G.useState)(()=>Date.now()),[s,l]=(0,G.useState)(!0),[u,d]=(0,G.useState)(!1),{showData:f}=nN(),p=(0,G.useRef)(null),m=rIi(e,a),h=m.some(e=>e.isRunning);return iJe(p,{enabled:h&&!s}),(0,G.useEffect)(()=>{if(!h||s)return;let e=setInterval(()=>o(Date.now()),100);return()=>clearInterval(e)},[h,s]),m.length===0?null:(0,K.jsx)(`div`,{"data-testid":`workflow-timeline`,className:`relative z-20 shrink-0 px-2 pb-2`,children:(0,K.jsxs)(DC,{open:!s,onOpenChange:e=>l(!e),className:c(Bv,`@container/workflow-timeline pointer-events-auto overflow-hidden rounded-xl`),children:[(0,K.jsxs)(`div`,{className:`flex items-center`,children:[(0,K.jsxs)(OC,{className:`flex min-h-11 min-w-0 flex-1 items-center gap-2 px-3.5 py-2.5 text-caption text-foreground hover:bg-fill-subtle`,"aria-label":s?`Expand timeline`:`Collapse timeline`,children:[(0,K.jsx)(`span`,{children:(0,K.jsx)(YV,{"aria-hidden":!0,className:`size-icon-md text-muted-foreground`})}),(0,K.jsx)(`span`,{children:`Timeline`}),(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,children:[m.length,` events`]}),(0,K.jsx)(`span`,{className:`ml-auto`,children:(0,K.jsx)(y,{direction:`right`,className:`size-4`})})]}),!s&&(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:u?`Restore timeline height`:`Enlarge timeline`,"aria-pressed":u,onClick:()=>d(!u),className:`mr-2 shrink-0`,children:u?(0,K.jsx)(aIi,{}):(0,K.jsx)(iIi,{})})]}),(0,K.jsx)(kC,{children:(0,K.jsx)(`div`,{ref:p,"data-testid":`workflow-timeline-list`,className:c(`overflow-auto overscroll-contain px-1.5 pb-1.5`,u?`max-h-[min(720px,calc(100dvh-112px))]`:`max-h-[min(320px,40dvh)]`),children:m.map(e=>(0,K.jsx)(QFi,{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 sIi=({workflowId:e,workflow:t,isLoading:n})=>{let[r]=HS(`workflow`,e),{canExecute:i,isLoading:a}=fS(),{stepDetail:o}=nN(),s=Zw(),c=o?.type===`data`,l=(0,K.jsxs)(`div`,{className:`[container-type:size] relative h-full min-h-0`,children:[(0,K.jsx)(Qlr,{workflowId:e,workflow:t,isLoading:n,requestContext:r}),(0,K.jsx)(JFi,{hidden:c,requestContext:r,canResume:!a&&i(`workflows`)}),c&&(0,K.jsx)(`div`,{className:`pointer-events-auto absolute top-12 right-2 z-30 flex max-h-[calc(100cqh-64px)] w-[440px] max-w-[calc(100%-16px)] flex-col`,children:(0,K.jsx)(n$,{requestContext:r})}),(0,K.jsx)(`div`,{className:`pointer-events-none absolute right-0 bottom-0 left-[var(--workflow-left-panel-width,0px)] z-20`,children:(0,K.jsx)(oIi,{})})]});return s&&o&&!c?(0,K.jsx)(`div`,{className:`h-full min-h-0 overflow-hidden`,children:(0,K.jsx)(n$,{requestContext:r})}):(0,K.jsxs)(`div`,{className:`relative h-full min-h-0`,children:[l,(0,K.jsxs)(p6,{className:`pointer-events-none absolute inset-0 z-30 min-h-0 w-full min-w-0 p-2`,children:[(0,K.jsx)(f6,{id:`workflow-graph`,className:`pointer-events-none min-w-0`}),o&&!c&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(m6,{className:`pointer-events-auto`}),(0,K.jsx)(f6,{id:`workflow-step-detail`,minSize:300,maxSize:`60%`,defaultSize:420,className:`min-w-0`,children:(0,K.jsx)(`div`,{className:`pointer-events-auto h-full min-h-0 overflow-hidden rounded-studio-panel border border-border bg-background`,children:(0,K.jsx)(n$,{requestContext:r})})})]})]})]})},cIi=()=>{let{workflowId:e}=kv(),{data:t,isLoading:n,error:r}=tN({workflowId:e,requestContext:HS(`workflow`,e)[0],queryOptions:{enabled:!!e}});return r&&FN(r)?(0,K.jsx)(TH,{variant:`fill`}):r&&IN(r)?(0,K.jsx)(wH,{variant:`fill`,resource:`workflows`}):(0,K.jsx)(sIi,{workflowId:e,workflow:t??void 0,isLoading:n})};function lIi(){let{workflowId:e}=kv(),{error:t}=yMt(e?{workflowId:e}:{});if(!e)return null;let n;return n=t&&FN(t)?(0,K.jsx)(TH,{variant:`fill`}):t&&IN(t)?(0,K.jsx)(wH,{variant:`fill`,resource:`schedules`}):(0,K.jsx)(`div`,{className:`h-full`,children:(0,K.jsx)(zFi,{workflowId:e})}),(0,K.jsxs)(RS,{children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),n]})}function uIi(){let{workflowId:e}=kv();return e?(0,K.jsx)(xsi,{scopedEntityId:e,scopedEntityType:Dp.WORKFLOW_RUN}):null}var dIi=(0,G.createContext)(null);function q9(){let e=(0,G.useContext)(dIi);if(!e)throw Error(`Workspace components must be rendered inside <Workspace.Root>`);return e}var fIi=e=>e?.status;function pIi(e,t){return FN(e)?`Your session has expired. Sign in again to continue.`:IN(e)?`You don't have permission to access this.`:LN(e)?`This path no longer exists.`:fIi(e)===501?`This workspace does not support this operation.`:t}function mIi({error:e,fallback:t,className:n}){return(0,K.jsx)(Sk,{variant:`destructive`,className:n,children:(0,K.jsx)(Sk.Message,{children:pIi(e,t)})})}var hIi=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;function gIi(e){let t=hIi.exec(e);return t?{frontmatter:t[1]??``,body:e.slice(t[0].length)}:{frontmatter:null,body:e}}function _Ii({content:e}){let{frontmatter:t,body:n}=gIi(e);return(0,K.jsxs)(K.Fragment,{children:[t!==null&&(0,K.jsx)(`div`,{"data-testid":`workspace-frontmatter`,className:`border-b border-border`,children:(0,K.jsx)(pJ,{code:t,lang:`yaml`,overflow:`wrap`,className:`rounded-none border-0 bg-transparent [&_pre]:p-4`})}),(0,K.jsx)(`div`,{className:`p-4`,children:(0,K.jsx)(xY,{children:n})})]})}function vIi(){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 yIi({path:e,content:t,mimeType:n}){return WFn(e,n)?(0,K.jsx)(`div`,{className:`flex justify-center p-4`,children:(0,K.jsx)(`img`,{src:`data:${n||`image/png`};base64,${t}`,alt:e.split(`/`).pop(),className:`max-w-full object-contain`})}):GFn(e,n)?(0,K.jsx)(`div`,{className:`flex justify-center p-4`,children:(0,K.jsx)(`video`,{controls:!0,"aria-label":e.split(`/`).pop(),className:`max-w-full`,children:(0,K.jsx)(`source`,{src:`data:${qFn(e,n)};base64,${t}`,type:qFn(e,n)})})}):JFn(e)?(0,K.jsx)(_Ii,{content:t}):(0,K.jsx)(pJ,{code:t,lang:uXe(e),overflow:`scroll`,className:`rounded-none border-0 bg-transparent [&_pre]:p-4`})}function bIi({renderPreview:e}){let{workspaceId:t,activeFilePath:n}=q9(),{data:r,isLoading:i,error:a}=lIn({workspaceId:t,path:n,queryOptions:{enabled:!!n}});if(!n)return null;if(i)return(0,K.jsxs)(`div`,{"aria-busy":`true`,className:`flex flex-col gap-2 p-4`,children:[(0,K.jsx)(zS,{className:`h-4 w-1/2`}),(0,K.jsx)(zS,{className:`h-4 w-5/6`}),(0,K.jsx)(zS,{className:`h-4 w-2/3`})]});if(!r)return(0,K.jsx)(mIi,{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)(yIi,{...o})}var xIi=(e,t)=>e===`.`?t:`${e}/${t}`,SIi=e=>e.split(`/`).slice(0,-1).map((e,t,n)=>n.slice(0,t+1).join(`/`)),CIi=e=>{let t=e.lastIndexOf(`/`);return t===-1?`.`:e.slice(0,t)};function wIi({labeled:e=!1}={}){let{workspaceId:t,onCreateDirectory:n,isReadOnly:r}=q9(),i=u_(),[a,o]=(0,G.useState)(!1),[s,c]=(0,G.useState)(``),[l,u]=(0,G.useState)(!1);if(!n||r(`.`))return null;let d=s.trim().replace(/^\.?\/+|\/+$/g,``),f=async()=>{if(d){u(!0);try{await n(d),await i.invalidateQueries({queryKey:[`workspace`,t,`fs`,`list`,CIi(d)]}),o(!1),c(``)}catch{}finally{u(!1)}}};return(0,K.jsxs)(K.Fragment,{children:[e?(0,K.jsx)(X,{variant:`ghost`,icon:(0,K.jsx)(P6,{}),onClick:()=>o(!0),children:`New folder`}):(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`New folder`,onClick:()=>o(!0),children:(0,K.jsx)(P6,{})}),(0,K.jsx)(nT,{open:a,onOpenChange:o,pending:l,children:(0,K.jsx)(rT,{size:`sm`,children:(0,K.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),f()},children:[(0,K.jsx)(iT,{children:(0,K.jsx)(sT,{children:`New folder`})}),(0,K.jsx)(oT,{children:(0,K.jsx)(Jj,{autoFocus:!0,"aria-label":`Folder path`,placeholder:`docs/guides`,value:s,onChange:e=>c(e.target.value)})}),(0,K.jsxs)(aT,{children:[(0,K.jsx)(lT,{children:`Cancel`}),(0,K.jsx)(X,{type:`submit`,variant:`primary`,disabled:!d||l,children:`Create`})]})]})})})]})}function TIi(e){return`${e.topSource}/${e.name}`}function EIi(e){let t=QFn(e.topSource,e.name);return t?`${t.owner}/${t.repo}/${e.name}`:null}function DIi({open:e,onOpenChange:t,workspaceId:n,onInstall:r,isInstalling:i,installedSkillIds:a=[],installedSkillNames:o=[],writableMounts:s,installedSkillPaths:l}){let[u,d]=(0,G.useState)(``),[f,p]=(0,G.useState)(null),[m,h]=(0,G.useState)(),g=s?.some(e=>e.path===m)?m:s?.[0]?.path,{data:_,isLoading:v}=XFn({workspaceId:n,queryOptions:{enabled:!!n}}),y=YFn({workspaceId:n}),b=(0,G.useMemo)(()=>f?.topSource?QFn(f.topSource,f.name):null,[f]),x=(0,G.useMemo)(()=>!b||!f?null:`https://skills.sh/${b.owner}/${b.repo}/${f.name}`,[b,f]),{data:S,isLoading:C}=ZFn({workspaceId:n,owner:b?.owner,repo:b?.repo,skillPath:f?.name,queryOptions:{enabled:!!n&&!!b&&!!f}}),w=cC(e=>{e.trim().length>=2&&y.mutate(e)},300),E=(0,G.useCallback)(e=>{d(e),w(e)},[w]),D=(0,G.useMemo)(()=>u.trim().length>=2?y.data?.skills??[]:_?.skills??[],[u,y.data,_]),O=y.isPending,k=u.trim().length>=2,A=(0,G.useMemo)(()=>{if(!f)return!1;let e=EIi(f);return!!(e&&a.includes(e)||o.includes(f.name))},[f,a,o]),j=(0,G.useCallback)(()=>{f&&b&&r({repository:`${b.owner}/${b.repo}`,skillName:f.name,mount:s&&s.length>1?g:void 0})},[f,b,r,s,g]),M=(0,G.useCallback)(e=>{e||(d(``),p(null),h(void 0)),t(e)},[t]);return(0,K.jsx)(nT,{open:e,onOpenChange:M,pending:i,children:(0,K.jsxs)(rT,{size:`xl`,className:`h-[80vh]`,children:[(0,K.jsxs)(iT,{children:[(0,K.jsx)(sT,{children:`Add Skill`}),(0,K.jsx)(cT,{children:`Search and install skills from the community registry`})]}),(0,K.jsxs)(oT,{layout:`fill`,children:[(0,K.jsx)(MH,{label:`Search skills`,placeholder:`Search skills`,value:u,onValueChange:E}),(0,K.jsxs)(`div`,{className:`flex min-h-0 flex-1 gap-4`,children:[(0,K.jsxs)(`div`,{className:`flex min-h-0 w-1/2 flex-col`,children:[(0,K.jsx)(T,{as:`p`,variant:`eyebrow`,tone:`muted`,className:`mb-2`,children:k?`Search Results`:`Popular Skills`}),(0,K.jsx)(LS,{className:`flex-1 rounded-lg border border-border`,children:(0,K.jsx)(IS,{className:!v&&!O&&D.length===0?`flex flex-col [&>div]:flex [&>div]:flex-1 [&>div]:flex-col`:void 0,children:v||O?(0,K.jsx)(`div`,{className:`flex items-center justify-center py-5`,children:(0,K.jsx)(It,{className:`text-muted-foreground`})}):D.length===0?(0,K.jsx)(Jx,{className:`flex-1`,titleSlot:k?`No skills found`:`No skills available`}):(0,K.jsx)(`div`,{className:`space-y-1 p-2`,children:D.map(e=>{let t=TIi(e),n=EIi(e),r=n&&a.includes(n)||o.includes(e.name),i=f?TIi(f):null;return(0,K.jsx)(`button`,{onClick:()=>p(e),className:c(`w-full rounded-md px-3 py-2 text-left`,`hover:bg-fill-subtle`,i===t&&`border border-border-strong bg-fill-hover`),children:(0,K.jsxs)(`div`,{className:`flex items-start justify-between gap-2`,children:[(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(T,{as:`span`,variant:`subheading`,tone:`ink`,className:`truncate`,children:e.name}),r&&(0,K.jsxs)(T,{as:`span`,variant:`meta`,className:`inline-flex items-center gap-1 rounded bg-info-subtle px-1.5 py-0.5 text-info-subtle-foreground`,children:[(0,K.jsx)(pC,{className:`size-icon-xs`}),`Installed`]})]}),(0,K.jsx)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`truncate`,children:e.topSource})]}),(0,K.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 text-muted-foreground`,children:[(0,K.jsx)(fJ,{className:`size-icon-xs`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,children:e.installs.toLocaleString()})]})]})},t)})})})})]}),(0,K.jsxs)(`div`,{className:`flex min-h-0 w-1/2 flex-col`,children:[(0,K.jsx)(T,{as:`p`,variant:`eyebrow`,tone:`muted`,className:`mb-2`,children:`Preview`}),(0,K.jsx)(`div`,{className:`flex flex-1 flex-col overflow-hidden rounded-lg border border-border`,children:f?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`border-b border-border bg-card p-4`,children:(0,K.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,K.jsx)(`div`,{className:`rounded-lg bg-muted p-2`,children:(0,K.jsx)(AZ,{className:`size-icon-lg text-muted-foreground`})}),(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsx)(T,{as:`h3`,variant:`subheading`,tone:`ink`,className:`truncate`,children:f.name}),(0,K.jsxs)(`div`,{className:`mt-1 flex items-center gap-3 text-muted-foreground`,children:[(0,K.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(kZ,{className:`size-icon-xs`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`block`,children:f.topSource})]}),(0,K.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(fJ,{className:`size-icon-xs`}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[f.installs.toLocaleString(),` installs`]})]})]})]}),b&&(0,K.jsx)(`a`,{href:`https://github.com/${b.owner}/${b.repo}`,target:`_blank`,rel:`noopener noreferrer`,className:c(`text-muted-foreground hover:text-foreground`,`transition-[color] duration-fast ease-out-custom motion-reduce:transition-none`),title:`View on GitHub`,children:(0,K.jsx)(tP,{className:`size-icon-md`})})]})}),C?(0,K.jsx)(`div`,{className:`flex flex-1 items-center justify-center`,children:(0,K.jsx)(It,{className:`text-muted-foreground`})}):S?(0,K.jsx)(LS,{className:`flex-1`,children:(0,K.jsx)(`div`,{className:`p-4`,children:(0,K.jsx)(xY,{children:S})})}):(0,K.jsx)(Jx,{className:`flex-1`,iconSlot:(0,K.jsx)(OZ,{}),titleSlot:`Preview unavailable`,actionSlot:x&&(0,K.jsxs)(`a`,{href:x,target:`_blank`,rel:`noopener noreferrer`,className:`flex items-center gap-1 text-info-indicator hover:underline`,children:[(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[`View on skills.sh`,` `]}),(0,K.jsx)(tP,{className:`size-icon-xs`})]})})]}):(0,K.jsx)(Jx,{variant:`fill`,iconSlot:(0,K.jsx)(OZ,{}),titleSlot:`Select a skill to preview`})})]})]}),f&&s&&s.length>1&&(0,K.jsxs)(ak,{orientation:`horizontal`,className:c(`bg-card hover:bg-card active:bg-card shadow-raised [--field:var(--field-on-surface)] [--field-disabled:var(--field-on-surface)] [--field-rim:var(--field-rim-on-surface)]`,`gap-3 rounded-lg p-3`),children:[(0,K.jsx)($N,{className:`size-icon-md shrink-0 text-muted-foreground`}),(0,K.jsx)(sk,{className:`whitespace-nowrap`,children:`Install to`}),(0,K.jsxs)(Bk,{value:g,onValueChange:h,children:[(0,K.jsx)(Hk,{className:`flex-1`,children:(0,K.jsx)(Vk,{})}),(0,K.jsx)(Uk,{children:s.map(e=>{let t=e.displayName??e.name??e.provider??`unknown`;return(0,K.jsxs)(Wk,{value:e.path,children:[t,` (`,e.path,`)`]},e.path)})})]})]})]}),f&&(0,K.jsxs)(aT,{children:[A&&s&&s.length>1&&(()=>{let e=l?.[f.name];if(!e)return null;let t=s.find(t=>e.startsWith(t.path+`/`)||e===t.path);return t?(0,K.jsxs)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`mr-auto`,children:[`Installed at `,t.path]}):null})(),(0,K.jsx)(lT,{children:`Cancel`}),(0,K.jsx)(tT,{onConfirm:j,disabled:!b||A,"data-testid":`install-skill-button`,children:i?`Installing...`:A?`Already installed`:`Install`})]})]})})}function OIi({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)(K5n,{}),`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)(K5n,{})}),(0,K.jsx)(DIi,{...c,open:r,onOpenChange:i,workspaceId:t,onInstall:e=>void l(e),isInstalling:a})]})}function kIi({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(SIi(t??``))),[v,y]=(0,G.useState)(t);if(t!==v){y(t);let e=SIi(t??``).filter(e=>!g.has(e));e.length>0&&_(new Set([...g,...e]))}let b=a?.join(`
724
+ `).reduce((e,t)=>{if(!t||t.startsWith(`#`))return e;let[n,r]=t.split(`=`);return n&&(e[n]=r?.split(``)?.every(e=>e===`*`)?``:r?.replaceAll(`"`,``)),e},{}):{}}var _Pi=({queryOptions:e}={})=>T_({queryKey:[`mastra-templates`],queryFn:pPi,...e}),vPi=({repoOrSlug:e,owner:t,queryOptions:n})=>T_({queryKey:[`template-repo`,e,t],queryFn:()=>hPi({repoOrSlug:e,owner:t}),...n}),yPi=({repo:e,owner:t,branch:n,queryOptions:r})=>T_({queryKey:[`template-repo-env-vars`,e,t,n],queryFn:()=>gPi({repo:e,owner:t,branch:n}),...r}),bPi=({queryOptions:e}={})=>{let t=Y();return T_({queryKey:[`agent-builder-workflow`],queryFn:async()=>await t.getAgentBuilderAction(`merge-template`).details(),...e})},xPi=({queryOptions:e}={})=>{let t=Y();return D_({mutationFn:async({runId:e})=>await t.getAgentBuilderAction(`merge-template`).createRun({runId:e}),...e})},SPi=({queryOptions:e}={})=>{let t=Y();return D_({mutationFn:async({runId:e})=>await t.getAgentBuilderAction(`merge-template`).runById(e),...e})},CPi=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)},wPi=(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=CPi(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=CPi(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}},TPi=(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)}},EPi=(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}=wPi(a,s,e);s=c,r(c),(a.runId||i||t)&&TPi(a.runId||i||t,c)}}catch(t){console.error(`💥 [processStream] Error processing template installation stream:`,t);let{newState:n}=wPi({type:`error`,payload:{error:t instanceof Error?t.message:`Unknown error`}},s,e);r(n)}finally{a(!1),o.releaseLock()}}}},DPi=({workflowInfo:e,queryOptions:t}={})=>{let n=Y(),{streamResult:r,isStreaming:i,processStream:a}=EPi(e);return{streamInstall:D_({mutationFn:async({inputData:e,selectedModel:t,runId:r})=>{for(let i=1;i<=3;i++)try{let i=n.getAgentBuilderAction(`merge-template`),o=new On;o.set(`selectedModel`,t);let s=await i.stream({inputData:e,requestContext:o},r);await a(s,r);return}catch(e){console.error(`💥 [streamInstall] Attempt ${i} failed:`,e);let t=e?.message?.includes(`Failed to fetch`)||e?.message?.includes(`NetworkError`)||e?.message?.includes(`network error`)||e?.message?.includes(`fetch`)||e?.code===`NETWORK_ERROR`||e?.name===`TypeError`;if(console.warn(`Stream attempt ${i}/3 failed:`,e),t){let e=r?`Network error during template installation (likely hot reload). Please refresh the page to resume from where you left off using runId: ${r}`:`Network error during template installation (likely hot reload). Please try again.`;throw console.error(`🔌 Stream network error:`,e),Error(e)}throw console.error(`❌ [streamInstall] Non-network error or max retries reached, throwing:`,e),e}},...t?.streamInstall}),streamResult:r,isStreaming:i}},OPi=({workflowInfo:e,queryOptions:t}={})=>{let n=Y(),{streamResult:r,isStreaming:i,processStream:a}=EPi(e);return{observeInstall:D_({mutationFn:async({runId:e})=>{let t=2e3;for(let r=1;r<=3;r++)try{let t=await n.getAgentBuilderAction(`merge-template`).observeStream({runId:e});await a(t,e);return}catch(e){console.error(`💥 [observeInstall] Attempt ${r} failed:`,e);let n=e?.message?.includes(`Failed to fetch`)||e?.message?.includes(`NetworkError`)||e?.message?.includes(`network error`)||e?.message?.includes(`fetch`)||e?.code===`NETWORK_ERROR`||e?.name===`TypeError`;if(console.warn(`ObserveStream attempt ${r}/3 failed:`,e),n&&r<3){console.info(`🔄 ObserveStream network error detected (likely hot reload), retrying in ${t}ms... (attempt ${r+1}/3)`),await new Promise(e=>setTimeout(e,t));continue}throw console.error(`❌ [observeInstall] Non-network error or max retries reached, throwing:`,e),e}},...t?.observeInstall}),streamResult:r,isStreaming:i}};function kPi(e){return e.replace(/\/$/,``).split(`/`).pop()}function APi({templates:e,linkComponent:t,className:n,isLoading:r}){let i=t||`a`;return r?(0,K.jsx)(`div`,{className:c(`grid gap-y-4`,n),children:Array.from({length:5}).map((e,t)=>(0,K.jsx)(`div`,{className:`h-16 animate-pulse rounded-lg bg-card`},t))}):(0,K.jsx)(`div`,{className:c(`grid gap-y-4`,n),children:e.map(e=>{let t=e?.agents||e?.tools||e?.networks||e?.workflows||e?.mcp;return(0,K.jsxs)(`article`,{className:c(Bv,`grid w-full grid-cols-[1fr_auto] overflow-hidden rounded-lg state-layer`),children:[(0,K.jsxs)(i,{to:`/templates/${e.slug}`,className:c(`group grid`,{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":e.imageURL}),children:[e.imageURL&&(0,K.jsx)(`div`,{className:`overflow-hidden`,children:(0,K.jsx)(`div`,{className:`thumb transition-scale h-full w-full bg-cover duration-150`,style:{backgroundImage:`url(${e.imageURL})`}})}),(0,K.jsxs)(`div`,{className:c(`grid w-full gap-0.5 px-4 py-3`,`[&_svg]:h-[1em] [&_svg]:w-[1em] [&_svg]:text-muted-foreground`),children:[(0,K.jsx)(T,{as:`h2`,tone:`ink`,children:e.title}),(0,K.jsx)(T,{className:c(CS,A),children:e.description}),(0,K.jsxs)(`div`,{className:`mt-3 hidden flex-wrap items-center gap-x-8 gap-y-4 text-muted-foreground 2xl:flex`,children:[t&&(0,K.jsxs)(`ul`,{className:c(`text-muted-foreground`,`m-0 flex list-none gap-4 p-0`,`[&>li]:flex [&>li]:items-center [&>li]:gap-0.5`),children:[e?.agents&&e.agents.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(HN,{}),` `,e.agents.length]})}),e?.tools&&e.tools.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(XN,{}),` `,e.tools.length]})}),e?.networks&&e.networks.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(n7e,{}),` `,e.networks.length]})}),e?.workflows&&e.workflows.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(ZS,{}),` `,e.workflows.length]})}),e?.mcp&&e.mcp.length>0&&(0,K.jsx)(`li`,{children:(0,K.jsxs)(T,{as:`span`,variant:`body`,className:`block`,children:[(0,K.jsx)(KN,{}),` `,e.mcp.length]})})]}),(0,K.jsx)(`div`,{className:`flex items-center gap-4`,children:e.supportedProviders.map(e=>(0,K.jsx)(T,{tone:`muted`,as:`span`,variant:`body`,children:e},e))})]})]})]}),(0,K.jsx)(`a`,{href:e.githubUrl,className:c(`group ml-auto hidden items-center gap-2 pr-4`,`lg:flex`),target:`_blank`,rel:`noopener noreferrer`,children:(0,K.jsx)(T,{as:`span`,variant:`body`,children:(0,K.jsxs)(`span`,{className:c(`flex items-center gap-2 rounded bg-sidebar px-2 py-1`,Jze,CS,A),children:[(0,K.jsx)(kZ,{}),` `,kPi(e.githubUrl)]})})})]},e.slug)})})}function jPi({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:i,onProviderChange:a,searchTerm:o,onSearchChange:s,onReset:l,className:u,isLoading:d}){return d?(0,K.jsxs)(`div`,{className:c(`flex h-[6.5rem] items-center gap-5`,`[&>div]:h-8 [&>div]:w-48 [&>div]:animate-pulse [&>div]:bg-card`,u),children:[(0,K.jsx)(`div`,{}),` `,(0,K.jsx)(`div`,{}),` `,(0,K.jsx)(`div`,{})]}):(0,K.jsxs)(`div`,{className:c(`sticky top-0 mx-auto flex flex-wrap gap-1.5 bg-background py-5`,u),children:[(0,K.jsx)(MH,{label:`Search templates`,placeholder:`Search templates`,size:`sm`,value:o,onValueChange:s}),(0,K.jsxs)(Bk,{value:t,onValueChange:i,children:[(0,K.jsx)(Hk,{"aria-label":`Search by tag`,size:`sm`,className:`w-auto`,children:(0,K.jsx)(Vk,{placeholder:`Select an option`})}),(0,K.jsx)(Uk,{children:e.map(e=>(0,K.jsx)(Wk,{value:e.value,children:e.label},e.value))})]}),(0,K.jsxs)(Bk,{value:r,onValueChange:a,children:[(0,K.jsx)(Hk,{"aria-label":`Search by provider`,size:`sm`,className:`w-auto`,children:(0,K.jsx)(Vk,{placeholder:`Select an option`})}),(0,K.jsx)(Uk,{children:n.map(e=>(0,K.jsx)(Wk,{value:e.value,children:e.label},e.value))})]}),l&&(0,K.jsx)(J4,{onClick:l})]})}var MPi=[{id:`templates`,label:`Templates`}];function NPi(){let{data:e,isLoading:t}=_Pi(),{templates:n,tags:r,providers:i}=e??{templates:[],tags:[],providers:[]},[a,o]=(0,G.useState)(`all`),[s,l]=(0,G.useState)(`all`),[u,d]=(0,G.useState)(``),f=[{value:`all`,label:`Any tag`}];(r||[]).forEach(e=>{f.push({value:e,label:e})});let p=[{value:`all`,label:`Any provider`}];(i||[]).forEach(e=>{p.push({value:e,label:e})});let m=(e,t)=>{t===`tag`?o(e):t===`provider`&&l(e)},h=e=>{d(e)},g=()=>{o(`all`),l(`all`),d(``)},_=n.filter(e=>!(u&&!e.title.toLowerCase().includes(u)&&!e.description.toLowerCase().includes(u)||a!==`all`&&!e.tags.includes(a)||s!==`all`&&!e.supportedProviders.includes(s))),v=u||a!==`all`||s!==`all`;return(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:MPi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Templates`}),(0,K.jsx)(wS,{children:(0,K.jsxs)(nJe,{children:[(0,K.jsx)(Dx,{children:(0,K.jsx)(OZ,{})}),`Templates`]})}),(0,K.jsxs)(`div`,{className:c(`z-10 h-full w-full overflow-y-auto px-5 pb-12`),children:[(0,K.jsx)(jPi,{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)(APi,{templates:_,linkComponent:Lv,className:`mx-auto max-w-[80rem]`,isLoading:t})]})]})}var PPi=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 FPi({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 IPi({errorMsg:e,validationErrors:t}){let n=typeof e==`string`?e:e==null?void 0:String(e),r=n?.includes(`Invalid schema for function`),i=n?.includes(`validation issue`)||t&&t.length>0,a=()=>i?`Template installation completed but some validation issues remain. The template may still be functional, but you should review and fix these issues.`:r?`There was an issue with the AI model configuration. This may be related to the selected model or AI SDK version compatibility.`:`An unexpected error occurred during template installation.`,{icon:o,title:s}=i?{icon:(0,K.jsx)(Zx,{className:`text-warning-foreground`}),title:`Template Installed with Warnings`}:{icon:(0,K.jsx)(PPi,{}),title:`Template Installation Failed`};return(0,K.jsxs)(FPi,{className:`mb-5 content-center space-y-4 text-muted-foreground`,children:[(0,K.jsxs)(`div`,{className:`grid content-center items-center justify-items-center gap-4 [&>svg]:h-8 [&>svg]:w-8`,children:[o,(0,K.jsxs)(`div`,{className:`space-y-2 text-center`,children:[(0,K.jsx)(T,{variant:`subheading`,tone:`ink`,children:s}),(0,K.jsx)(T,{tone:`muted`,children:a()})]})]}),t&&t.length>0&&(0,K.jsxs)(`details`,{children:[(0,K.jsx)(`summary`,{className:c(`text-muted-foreground hover:text-foreground`,`cursor-pointer text-center select-none`),children:(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[`Show Validation Issues (`,t.length,`)`]})}),(0,K.jsx)(`div`,{className:`mt-4 max-h-60 space-y-2 overflow-auto rounded bg-muted p-3 text-left`,children:t.map((e,t)=>(0,K.jsxs)(`div`,{className:`border-l-2 border-destructive-indicator pl-2`,children:[(0,K.jsx)(T,{as:`p`,variant:`column`,className:`text-destructive-foreground`,children:e.type===`typescript`?`🔴 TypeScript Error`:`⚠️ Lint Error`}),(0,K.jsx)(uC,{className:`mt-1 text-caption wrap-break-word whitespace-pre-wrap text-muted-foreground`,code:e.message})]},t))})]}),n&&!i&&(0,K.jsxs)(`details`,{children:[(0,K.jsx)(`summary`,{className:c(`text-muted-foreground hover:text-foreground`,`cursor-pointer text-center select-none`),children:(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`block`,children:`Show Details`})}),(0,K.jsx)(`div`,{className:`mt-4 max-h-60 overflow-auto rounded bg-muted p-3 text-left`,children:(0,K.jsx)(uC,{className:`text-caption wrap-break-word whitespace-pre-wrap`,code:n})})]})]})}function LPi({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)(FPi,{children:(0,K.jsxs)(`div`,{className:`mx-auto my-4 grid max-w-[40rem] gap-5 p-4 lg:p-5`,children:[(0,K.jsxs)(T,{as:`h2`,variant:`heading`,tone:`muted`,className:c(`flex items-center gap-2`,`[&_svg]:h-[1.2em] [&_svg]:opacity-70 [&>svg]:w-[1.2em]`),children:[`Install Template `,(0,K.jsx)(OZ,{})]}),(0,K.jsxs)(ak,{orientation:`horizontal`,children:[(0,K.jsx)(sk,{children:`Template AI Model Provider`}),(0,K.jsx)(Tpt,{className:`flex-1`,children:(0,K.jsxs)(Bk,{name:`template-provider`,value:t,onValueChange:n,children:[(0,K.jsx)(Hk,{size:`md`,children:(0,K.jsx)(Vk,{placeholder:`Select`})}),(0,K.jsx)(Uk,{children:e.map(e=>(0,K.jsx)(Wk,{value:e.value,children:e.label},e.value))})]})})]}),t&&Object.entries(r||{}).length>0&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(T,{as:`h3`,tone:`muted`,children:`Set required Environmental Variables`}),(0,K.jsx)(`div`,{className:`grid grid-cols-[1fr_1fr] items-start gap-4`,children:s?(0,K.jsxs)(`div`,{className:c(`text-muted-foreground`,`col-span-2 flex items-center justify-center gap-4`,`[&_svg]:h-[1.1em] [&_svg]:w-[1.1em] [&_svg]:opacity-50`,`animate-in duration-300 fade-in`),children:[(0,K.jsx)(It,{}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[` `,`Loading variables...`]})]}):Object.entries(r).map(([e,t])=>(0,K.jsxs)(G.Fragment,{children:[(0,K.jsxs)(ak,{className:`w-full`,children:[(0,K.jsx)(sk,{className:`sr-only`,children:`Key`}),(0,K.jsx)(Jj,{name:`env-${e}`,value:e,disabled:!0,className:`w-full`})]}),(0,K.jsxs)(ak,{invalid:i.includes(e),className:`w-full`,children:[(0,K.jsx)(sk,{className:`sr-only`,children:`Value`}),(0,K.jsx)(Jj,{name:e,value:t,onChange:o,autoComplete:`off`,className:`w-full`}),(0,K.jsx)(lk,{children:i.includes(e)?`Value is required.`:void 0})]})]},e))}),(0,K.jsxs)(`div`,{className:`relative mt-3.5 border-t border-border pt-12`,children:[(0,K.jsx)(`div`,{className:`absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full bg-background`,children:(0,K.jsx)(T,{tone:`muted`,as:`span`,variant:`caption`,className:`block`,children:`And`})}),(0,K.jsx)(T,{as:`h3`,tone:`muted`,children:`Set AI Model for Template Installation`}),(0,K.jsx)(T,{tone:`muted`,className:`mt-2 mb-5`,children:`This model will be used by the workflow to process and install the template`}),(0,K.jsx)(w1r,{defaultProvider:u||``,defaultModel:d||``,updateModel:f||(()=>Promise.resolve({message:`Updated`})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:`Provider`})]})]}),t&&!s&&(0,K.jsx)(X,{className:c(`mt-4 flex min-h-10 w-full items-center justify-center gap-2 rounded-lg bg-card state-layer text-foreground`,`[&_svg]:h-[1.1em] [&_svg]:text-foreground [&>svg]:w-[1.1em]`),onClick:a,disabled:!t||!u||!d||i.length>0||l,children:l?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(It,{className:`h-4 w-4`}),` Installing...`]}):(0,K.jsxs)(K.Fragment,{children:[`Install `,(0,K.jsx)(oH,{})]})})]})})}function RPi({title:e,description:t,githubUrl:n,isLoading:r,infoData:i,templateSlug:a}){let o=a?`feat/install-template-${a}`:`feat/install-template-[slug]`;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`mt-5 grid items-center`,children:(0,K.jsxs)(`div`,{className:c(`flex items-center gap-3`,`[&>svg]:h-[1.2em] [&>svg]:w-[1.2em] [&>svg]:opacity-50`,{"[&>svg]:opacity-20":r}),children:[(0,K.jsx)(OZ,{}),(0,K.jsx)(`h2`,{className:c({"flex min-w-[50%] rounded-lg bg-muted":r}),children:(0,K.jsx)(T,{as:`span`,variant:`title`,className:`block`,children:r?(0,K.jsx)(K.Fragment,{children:`\xA0`}):e})})]})}),(0,K.jsxs)(`div`,{className:`grid gap-x-24 lg:grid-cols-[1fr_1fr]`,children:[(0,K.jsxs)(`div`,{className:`grid`,children:[(0,K.jsx)(T,{tone:`muted`,className:c(`mt-2 mb-4`,{"rounded-lg bg-muted":r}),children:r?(0,K.jsx)(K.Fragment,{children:`\xA0`}):t}),!r&&a&&(0,K.jsxs)(`div`,{className:c(`mb-4 rounded-lg border border-border bg-background p-4`,`flex items-start gap-3`),children:[(0,K.jsx)(`div`,{className:`mt-0.5 shrink-0`,children:(0,K.jsx)(Yx,{className:`h-[1.1em] w-[1.1em] text-info-indicator`})}),(0,K.jsxs)(`div`,{className:`flex-1 space-y-2`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(KS,{className:`h-[1em] w-[1em] text-muted-foreground`}),(0,K.jsx)(T,{as:`span`,variant:`subheading`,tone:`ink`,children:`A new Git branch will be created`})]}),(0,K.jsxs)(`div`,{className:`space-y-1`,children:[(0,K.jsxs)(T,{tone:`muted`,as:`p`,variant:`caption`,children:[(0,K.jsx)(T,{as:`span`,variant:`column`,children:`Branch name:`}),` `,(0,K.jsx)(uX,{children:o})]}),(0,K.jsx)(T,{tone:`muted`,as:`p`,variant:`caption`,children:`This ensures safe installation with easy rollback if needed. Your main branch remains unchanged.`})]})]})]}),n&&(0,K.jsxs)(`a`,{href:n,target:`_blank`,rel:`noopener noreferrer`,className:c(`text-muted-foreground hover:text-foreground`,`mt-auto flex items-center gap-2`),children:[(0,K.jsx)(kZ,{}),(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:n?.split(`/`)?.pop()})]})]}),i&&(0,K.jsx)(O1r,{data:i,labelsAreHidden:!0,isLoading:r})]})]})}function zPi(e){switch(e){case`running`:return(0,K.jsx)(It,{size:`sm`,"aria-hidden":!0});case`success`:return(0,K.jsx)(pC,{"aria-hidden":!0});case`failed`:return(0,K.jsx)(xw,{"aria-hidden":!0});default:return null}}function BPi(){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 VPi({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)(BPi,{}):zPi(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:zPi(e)})}function HPi({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)(VPi,{status:e.status,variant:r})]})}function UPi({currentStep:e,steps:t=[],className:n}){return(0,K.jsx)(`div`,{className:c(n),children:t.map((t,n)=>(0,K.jsx)(HPi,{step:t,isActive:e?.id===t.id,position:n+1},t.id))})}function WPi({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 GPi=(0,G.createContext)(3);function KPi({title:e,description:t,action:n,done:r,className:i,children:a}){let o=(0,G.useContext)(GPi);return(0,K.jsxs)(`li`,{className:c(`group/step grid grid-cols-[1.5rem_minmax(0,1fr)] gap-x-4 [counter-increment:ds-step]`,i),children:[(0,K.jsxs)(`div`,{className:`flex flex-col items-center`,children:[(0,K.jsx)(`span`,{className:c(`flex size-6 shrink-0 items-center justify-center rounded-full`,u.colors,r?`bg-success-indicator/18 text-success-indicator`:`bg-fill text-foreground`),children:r?(0,K.jsx)(pC,{className:`size-icon-sm`,"aria-label":`Done`}):(0,K.jsx)(T,{as:`span`,variant:`column`,className:`before:content-[counter(ds-step)]`,"aria-hidden":!0})}),(0,K.jsx)(`span`,{"aria-hidden":!0,className:`w-px flex-1 bg-border group-last/step:hidden`})]}),(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-3 pb-8 group-last/step:pb-0`,children:[(0,K.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,K.jsxs)(`div`,{className:`flex min-h-6 flex-wrap items-center justify-between gap-x-6 gap-y-2`,children:[(0,K.jsx)(T,{as:o===2?`h2`:`h3`,variant:`label`,className:`text-pretty`,children:e}),n==null?null:(0,K.jsx)(`div`,{className:`flex shrink-0 items-center gap-2`,children:n})]}),t==null?null:(0,K.jsx)(T,{as:`p`,variant:`body-sm`,tone:`muted`,className:`max-w-[70ch] text-pretty`,children:t})]}),a]})]})}function qPi({headingLevel:e=3,className:t,children:n}){return(0,K.jsx)(GPi.Provider,{value:e,children:(0,K.jsx)(`ol`,{className:c(`flex flex-col [counter-reset:ds-step]`,t),children:n})})}Object.assign(qPi,{Step:KPi});function JPi({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)(FPi,{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)(WPi,{steps:h})}),s&&i===`error`&&(0,K.jsxs)(`div`,{className:c(`text-foreground`,`flex items-center gap-3 rounded-lg bg-destructive-subtle p-4`,`[&>svg]:h-6 [&>svg]:w-6 [&>svg]:text-destructive-foreground [&>svg]:opacity-70`),children:[(0,K.jsx)(qx,{}),(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:s||`Something went wrong`})]}),u&&(0,K.jsx)(UPi,{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 YPi({name:e,installedEntities:t}){return(0,K.jsxs)(FPi,{className:c(`grid content-center items-center justify-items-center gap-4`,`[&>svg]:h-8 [&>svg]:w-8`),children:[(0,K.jsx)(OZ,{}),(0,K.jsx)(T,{as:`h2`,variant:`heading`,children:`Done!`}),(0,K.jsxs)(T,{tone:`muted`,className:`text-center`,children:[`The `,(0,K.jsx)(`b`,{className:`text-muted-foreground`,children:e}),` template has been successfully installed.`,t&&t.length>0&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`br`,{}),` Installed entities are listed below.`]})]}),t&&t.length>0&&(0,K.jsx)(O1r,{data:t})]})}function XPi(){let{templateSlug:e}=kv(),t=[{id:`templates`,label:`Templates`,to:`/templates`},{id:`template`,label:Zjt(e)}],[n,r]=Rv(),[i,a]=(0,G.useState)(``),[o,s]=(0,G.useState)(``),[l,u]=(0,G.useState)(``),[d,f]=(0,G.useState)({}),[p,m]=(0,G.useState)([]),[h,g]=(0,G.useState)(null),[_,v]=(0,G.useState)(!1),[y,b]=(0,G.useState)(``),[x,S]=(0,G.useState)(!1),[C,w]=(0,G.useState)(!1),[T,E]=(0,G.useState)([]),{data:D,isLoading:O}=vPi({repoOrSlug:e,owner:`mastra-ai`}),k=`1.84.0`.includes(`beta`)??!1?`beta`:`main`,{data:A,isLoading:j}=yPi({repo:D?.githubUrl?new URL(D.githubUrl).pathname.split(`/`)[2]:`template-${e}`,owner:`mastra-ai`,branch:k}),{data:M,isLoading:N}=bPi(),{mutateAsync:P,isPending:F}=xPi(),{mutateAsync:I}=SPi(),{streamInstall:L,streamResult:R,isStreaming:z}=DPi({workflowInfo:M}),{observeInstall:B,streamResult:V,isStreaming:H}=OPi({workflowInfo:M});(0,G.useEffect)(()=>{let e=n.get(`runId`);!e||_||h||z||H||(console.info(`🔄 Checking completed run after hot reload:`,{runId:e}),b(e),I({runId:e}).then(e=>{let t=e.snapshot;if(t?.status===`success`&&t?.result?.success)v(!0);else if(t?.result?.success===!1){if(t?.result?.validationResults&&!t?.result?.validationResults?.valid&&t?.result?.validationResults?.remainingErrors>0){let{remainingErrors:e,errors:n}=t.result.validationResults,r=`Template installation completed but ${e} validation issue${e>1?`s`:``} remain unresolved.`;g(r),E(n||[])}else{let e=t?.result?.message||t?.result?.error||`Template installation failed`;g(typeof e==`string`?e:String(e))}}}).catch(e=>{console.error(`❌ Failed to fetch run details:`,e),g(`Failed to retrieve installation status after reload`)}))},[n,_,h,z,H,I]),(0,G.useEffect)(()=>{let e=n.get(`runId`),t=n.get(`resume`),i=n.get(`provider`);if(e&&t===`true`&&i&&!z&&!H&&!x&&!C&&M){b(e),S(!0);try{I({runId:e}).then(t=>{if(t.snapshot?.status===`running`)return B.mutateAsync({runId:e})}).then(()=>{r(e=>{let t=new URLSearchParams(e);return t.delete(`resume`),t})}).catch(e=>{console.error(`❌ Failed to resume template installation:`,e),e.message?.includes(`404`)||e.message?.includes(`not found`)?g(`Template installation run not found. It may have expired or been completed.`):g(`Failed to resume template installation. Please try again.`)})}catch(e){console.error(`❌ Auto-resume failed with error:`,e),g(`Failed to resume template installation. Please refresh and try again.`)}}},[n,e,z,H,x,C,M,I,B,r]);let ee=[{value:`openai`,label:`OpenAI`},{value:`anthropic`,label:`Anthropic`},{value:`groq`,label:`Groq`},{value:`google`,label:`Google`}],te=[{key:`tools`,label:`Tools`,value:D?.tools?.length?D.tools.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(XN,{})},{key:`agents`,label:`Agents`,value:D?.agents?.length?D.agents.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(HN,{})},{key:`workflows`,label:`Workflows`,value:D?.workflows?.length?D.workflows.map(e=>e).join(`, `):`n/a`,icon:(0,K.jsx)(ZS,{})},{key:`providers`,label:`Providers`,value:D?.supportedProviders?.length?D.supportedProviders.join(`, `):`n/a`,icon:(0,K.jsx)(k3,{})},{key:`tags`,label:`Tags`,value:D?.tags?.length?D.tags.join(`, `):`n/a`,icon:(0,K.jsx)(wX,{})}],U=[{...te[0]},{...te[1]},{...te[2]}].filter(e=>e.value!==`n/a`);return(0,G.useEffect)(()=>{A&&f(A)},[A]),(0,G.useEffect)(()=>{let e=R||V;e?.phase===`error`&&e?.error&&g(typeof e.error==`string`?e.error:String(e.error))},[R?.phase,R?.error,V?.phase,V?.error]),(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(`div`,{className:c(`h-full w-full overflow-y-scroll lg:px-12`),children:(0,K.jsxs)(`div`,{className:`mx-auto grid w-full max-w-[80rem] gap-y-4 p-4`,children:[(0,K.jsx)(RPi,{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)(JPi,{name:D.title,streamResult:H?V:R,runId:y,workflowInfo:M}),_&&(0,K.jsx)(YPi,{name:D.title,installedEntities:U,linkComponent:Lv}),h&&(0,K.jsx)(IPi,{errorMsg:h,validationErrors:T.length>0?T:R?.validationResults?.errors||V?.validationResults?.errors}),!z&&!H&&!_&&!h&&(0,K.jsx)(LPi,{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 ZPi=e=>e.threadId;function QPi(e,t){return`traces`in e?{traces:{...e.traces,to:t}}:{threads:{...e.threads,to:t}}}var $Pi=e=>`traces`in e?e.traces:e.threads;function eFi(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 tFi({query:e,rolling:t,autoRefetch:n=!0,limit:r,enabled:i=!0}){let a=Y(),{anchorTo:o,reanchor:s}=BNi(e),c=(0,G.useMemo)(()=>o?{...e,timeRange:QPi(e.timeRange,o)}:e,[e,o]),l=nXr({query:c,limit:r,enabled:i,queryOptions:INi}),{headRows:u}=HNi({queryKey:[`threads`,e],fetchHead:async t=>(await a.queryTraceThreads({...e,timeRange:QPi(e.timeRange,t),orderBy:[{field:`endedAt`,direction:`desc`}],page:{limit:50}})).threads,getId:ZPi,getEndedAt:e=>e.endedAt,since:Date.parse($Pi(c.timeRange).to),enabled:i&&t&&n&&l.threads!==void 0&&!l.isFetching&&!l.isError,onOverflow:s}),{orderBy:d}=e,f=l.threads,p=(0,G.useMemo)(()=>f&&WNi(f,u,{getId:ZPi,compare:eFi(d),hasNextPage:l.hasNextPage}),[f,u,d,l.hasNextPage]);return{...l,threads:p}}function nFi(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 rFi=[`last-24h`,`last-3d`,`last-7d`,`last-14d`,`last-30d`,`custom`],iFi=[];function aFi(){let{data:e}=i5(),t=e?.capabilities.traceQueryTimeToFirstChunk??!1,n=e?.capabilities.traceQueryTimeToFirstToken??!1,{data:r=iFi}=t8(),{data:i=iFi}=n8();return(0,G.useMemo)(()=>[l3r,...Mai({withTimeToFirstChunk:t,withTimeToFirstToken:n,entityNames:r,environments:i})],[t,n,r,i])}function oFi({tokens:e,groups:t,onFiltersChange:n}){let r=(0,G.useMemo)(()=>P8(e),[e]),i=(0,G.useMemo)(()=>{let e=F8([],t);return{...e,nodes:[p5,...r,...e.nodes]}},[r,t]),a=(0,G.useCallback)(e=>{let t=VZr({...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 sFi=e=>e;function cFi({datePreset:e,dateFrom:t,dateTo:n,minDate:r,tokens:i,groups:a,onDatePresetChange:o,onDateChange:s,onDateRangeChange:c,onFiltersChange:l,disabled:u}){let d=aFi(),{filterBarValue:f,onFilterBarChange:p}=oFi({tokens:i,groups:a,onFiltersChange:l});return(0,K.jsxs)(m5,{fields:d,operators:mZr,value:f,onValueChange:p,createItemId:sFi,maxDepth:3,"aria-label":`Thread filters`,className:`min-w-64 flex-1`,children:[(0,K.jsx)(m5.Chips,{renderChip:i=>i.fieldId===`timeRange`?(0,K.jsx)(m5.TimeRange,{preset:e,onPresetChange:o,dateFrom:t,dateTo:n,minDate:r,onDateChange:s,onDateRangeChange:c,disabled:u,presets:rFi,defaultPreset:o5.datePreset}):(0,K.jsx)(m5.Chip,{item:i})}),(0,K.jsx)(m5.Input,{placeholder:`Filter threads`})]})}function lFi({selectedThreadId:e,onSelectedThreadChange:t,onOpenScore:n,urlState:r}){let i=RNi(r),{timeRange:a,tokens:o,groups:s,sort:c}=i,l=a5().enabled,u=c2r().enabled,d=iii({scope:`threads`}),{data:f,isLoading:p}=i5(),m=f?.capabilities.traceQueryTimeToFirstChunk??!1,h=f?.capabilities.traceQueryTimeToFirstToken??!1,g=(0,G.useMemo)(()=>p?d.preferences:C0r(d.preferences,{withTimeToFirstChunk:m,withTimeToFirstToken:h}),[d.preferences,p,m,h]),{threads:_,hasNextPage:v,isFetchingNextPage:y,setEndOfListElement:b,isLoading:x,isError:S,error:C}=tFi({query:(0,G.useMemo)(()=>{let e=Fai(o,s,{withTimeToFirstChunk:m,withTimeToFirstToken:h});return{timeRange:{traces:a},orderBy:[{field:`startedAt`,direction:c.direction}],...e?{where:e}:{}}},[a,c,o,s,m,h]),rolling:i.rolling}),w=(0,G.useMemo)(()=>(_??[]).map(nFi),[_]),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)(q0r,{toolbar:(0,K.jsxs)(K.Fragment,{children:[r&&(0,K.jsx)(Foi,{page:`threads`,...r,columns:d}),(0,K.jsxs)(TK,{children:[(0,K.jsx)(TK.Start,{children:(0,K.jsx)(cFi,{datePreset:i.datePreset,dateFrom:i.dateFrom,dateTo:i.dateTo,tokens:o,groups:s,onDatePresetChange:i.onDatePresetChange,onDateChange:i.onDateChange,onDateRangeChange:i.onDateRangeChange,onFiltersChange:i.onFiltersChange,disabled:x})}),(0,K.jsx)(TK.End,{children:(0,K.jsx)(d2r,{scope:`threads`,value:d.preferences,onChange:d.setPreferences})})]})]}),error:S?(0,K.jsx)(Q8,{error:C,resource:`threads`,errorTitle:`Failed to load threads`}):void 0,empty:D?(0,K.jsx)(t0r,{resource:`threads`,datePreset:i.datePreset,dateFrom:i.dateFrom,dateTo:i.dateTo}):void 0,children:(0,K.jsx)(h7r,{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)(Uri,{open:!!e,threadId:e??``,depth:1,closeLabel:`Close`,withQueryTrace:l,withFeedback:u,onOpenScore:n,onClose:()=>t(void 0)})]})}function uFi(){let{enabled:e,isLoading:t}=n2r(),n=Ov(),[r,i]=Rv();return(0,K.jsx)(FNi,{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)(lFi,{urlState:{searchParams:r,setSearchParams:i},selectedThreadId:XNi(r),onSelectedThreadChange:e=>i(t=>ZNi(t,e),{replace:!0}),onOpenScore:(e,t)=>n(CK(e,t))})})}var dFi=()=>(0,K.jsx)(Jx,{titleSlot:`No Workflows yet`,descriptionSlot:(0,K.jsxs)(K.Fragment,{children:[`Mastra workflows are not configured yet. `,(0,K.jsx)(`br`,{}),`More information in the documentation.`]}),actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/docs/workflows/overview`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(tP,{}),children:`Workflows documentation`}),variant:`fill`});function fFi(e,t,n){return IZ(e,t,{name:e=>e.name,running:e=>n[e.id]?.running??0,suspended:e=>n[e.id]?.suspended??0,steps:e=>Object.keys(e.steps??{}).length})}function pFi(e){return Object.keys(e.steps??{}).filter(t=>e.allSteps?.[t]?.isWorkflow)}function mFi(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 hFi(e,t,n){let r=mFi(t),i=[],a=(e,o,s,c,l,u)=>{let d=pFi(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 gFi=`auto 24rem minmax(0, 1fr) auto auto auto`;function _Fi({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 vFi({row:e,isExpanded:t,onToggle:n}){let r=e.kind===`workflow`&&e.nestedIds.length>0,i=e.kind===`workflow`?e.workflow.name:e.stepId;return(0,K.jsx)(`div`,{className:`flex items-center pl-5`,children:r?(0,K.jsx)(`button`,{type:`button`,"aria-expanded":t,"aria-label":`${t?`Collapse`:`Expand`} nested workflows of ${i}`,className:c(SS,`relative grid size-5 shrink-0 place-items-center before:absolute before:-inset-1.5 before:content-['']`),onClick:e=>{e.stopPropagation(),n()},children:(0,K.jsx)(y,{direction:`right`,className:`size-4`})}):(0,K.jsx)(`span`,{className:`size-5 shrink-0`,"aria-hidden":!0})})}var yFi=e=>e.stopPropagation();function bFi({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 xFi({row:e,isExpanded:t,onToggle:n,runCount:r,rowProps:i}){let{paths:a,Link:o}=sn(),s=(0,G.useRef)(null),{workflow:c,nestedIds:l}=e,u=dJ(c.name,50),d=dJ(c.description??``,200),f=Object.keys(c.steps??{}).length,p=r?.running??0,m=r?.suspended??0,h=l.length>0;return(0,K.jsxs)(Z.RowWrapper,{...i,onSelectRow:()=>s.current?.click(),children:[(0,K.jsx)(vFi,{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:yFi,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)(_Fi,{guides:e.guides,isLastChild:e.isLastChild}):null,(0,K.jsx)(`span`,{className:`truncate`,children:u}),c.origin===`dynamic`?(0,K.jsx)(eC,{size:`xs`,variant:`blue`,title:`Registered via the dynamic-workflows API`,children:`Dynamic`}):null,h?(0,K.jsxs)(T,{as:`span`,variant:`body-sm`,tone:`muted`,title:`Nested workflows: ${l.join(`, `)}`,className:`inline-flex shrink-0 items-center gap-1`,children:[(0,K.jsx)(ZS,{"aria-hidden":!0,className:`size-icon-sm`}),l.length]}):null]})}),(0,K.jsx)(Z.DescriptionCell,{children:d}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:p>0?(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-info-indicator`,"aria-label":`${p} run${p===1?``:`s`} in progress`,children:[(0,K.jsx)(`span`,{"aria-hidden":!0,className:`size-2 rounded-full bg-info-indicator motion-safe:animate-pulse`}),p]}):``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:m>0?(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-warning-foreground`,"aria-label":`${m} run${m===1?``:`s`} awaiting input`,children:[(0,K.jsx)(ET,{"aria-hidden":!0,className:`size-icon-sm`}),m]}):``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:f||``})]})]})}function SFi({workflows:e,isLoading:t,search:n=``,sort:r,onSortChange:i,requestContext:a}){let[o,s]=(0,G.useState)(new Set),l=wEt({requestContext:a}),u=(0,G.useMemo)(()=>Object.entries(e).map(([e,t])=>({...t,id:e})),[e]),d=(0,G.useMemo)(()=>{let e=n.toLowerCase();return u.filter(t=>t.name?.toLowerCase().includes(e)||t.description?.toLowerCase().includes(e))},[u,n]),f=(0,G.useMemo)(()=>fFi(d,r,l),[d,r,l]),m=(0,G.useMemo)(()=>hFi(f,e,o),[f,e,o]),h=(0,G.useMemo)(()=>{let e=new Map;for(let t of m)t.kind===`workflow`&&e.set(t.pathKey,e.size);return e},[m]),{containerRef:g,getRowProps:_}=PZ({count:h.size,global:!0}),v=e=>{s(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})};return t?(0,K.jsx)(DH,{columns:gFi,fit:`container`}):(0,K.jsxs)(Z,{columns:gFi,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)(bFi,{sortKey:`name`,sort:r,onSortChange:i,children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`Description`}),(0,K.jsx)(bFi,{sortKey:`running`,sort:r,onSortChange:i,children:`Running`}),(0,K.jsx)(bFi,{sortKey:`suspended`,sort:r,onSortChange:i,children:`Pending input`}),(0,K.jsx)(bFi,{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)(vFi,{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)(_Fi,{guides:e.guides,isLastChild:e.isLastChild}),(0,K.jsx)(`span`,{className:`truncate`,children:dJ(e.stepId,50)}),(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{render:(0,K.jsx)(T,{as:`span`,variant:`body-sm`,tone:`muted`}),role:`note`,tabIndex:0,className:c(`shrink-0 rounded-sm`,p),children:`not registered`}),(0,K.jsx)(Tx,{className:`max-w-72`,children:`Runs as a step of its parent workflow. Add it to the workflows of your Mastra instance to open, run, and inspect it on its own page.`})]})]})}),(0,K.jsx)(Z.DescriptionCell,{children:dJ(e.description??``,200)}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:``}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:``})]})]},`workflow-${e.pathKey}`):(0,K.jsx)(xFi,{row:e,isExpanded:t,onToggle:n,runCount:l[e.workflow.id],rowProps:_(h.get(e.pathKey)??-1)},`workflow-${e.pathKey}`)})]})}var K9=[eP(`/workflows`)];function CFi(){let{data:e,isLoading:t,error:n}=eN(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)();return n&&FN(n)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:K9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(TH,{variant:`fill`})]}):n&&IN(n)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:K9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(wH,{variant:`fill`,resource:`workflows`})]}):n?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:K9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load workflows`,descriptionSlot:n.message})]}):Object.keys(e||{}).length===0&&!t?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:K9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(dFi,{})]}):(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:K9}),actionRow:(0,K.jsxs)(TK,{children:[(0,K.jsx)(TK.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(MH,{...NH,onValueChange:i,label:`Search workflows`,placeholder:`Search by name or description`})})}),(0,K.jsx)(TK.End,{children:(0,K.jsx)(X,{render:(0,K.jsx)(Lv,{to:`/workflows/schedules`}),variant:`primary`,icon:(0,K.jsx)(qS,{}),children:`Schedules`})})]}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workflows`}),(0,K.jsx)(SFi,{workflows:e||{},isLoading:t,search:r,sort:a,onSortChange:(e,t)=>o({key:t,direction:e})})]})}var wFi={active:`bg-success-indicator`,paused:`bg-info-indicator`,completed:`bg-muted-foreground`},TFi={active:`text-success-indicator`,paused:`text-info-indicator`,completed:`text-muted-foreground`},EFi=({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 ${wFi[e]}`,"aria-hidden":!0}),(0,K.jsx)(T,{as:`span`,variant:`caption`,className:TFi[e],children:e})]});function DFi({status:e}){let{icon:t,color:n}=OFi(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 OFi(e){switch(e){case`success`:return{icon:(0,K.jsx)(pC,{className:`size-icon-sm`}),color:`text-success-indicator`};case`failed`:return{icon:(0,K.jsx)(xw,{className:`size-icon-sm`}),color:`text-destructive-foreground`};case`running`:return{icon:(0,K.jsx)(It,{}),color:`text-muted-foreground`};case`suspended`:return{icon:(0,K.jsx)(ET,{className:`size-icon-sm`}),color:`text-info-indicator`};case`canceled`:return{icon:(0,K.jsx)(Kx,{className:`size-icon-sm`}),color:`text-muted-foreground`};case`pending`:case`waiting`:return{icon:(0,K.jsx)(tC,{className:`size-icon-sm`}),color:`text-muted-foreground`};default:return{icon:null,color:`text-muted-foreground`}}}var kFi=`auto auto auto auto 1fr`,AFi=3e4,jFi=3e5;function MFi({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:i,setEndOfListElement:a}){let{Link:o,paths:s}=sn(),c=e=>!!(n&&e.runId&&e.outcome!==`failed`),l=e.filter(c).length,{containerRef:u,getRowProps:d}=PZ({count:l}),f=-1;return t?(0,K.jsx)(DH,{columns:kFi}):e.length===0?(0,K.jsx)(T,{variant:`body`,tone:`muted`,className:`p-4`,children:`No trigger history yet.`}):(0,K.jsxs)(Z,{columns:kFi,className:`min-w-0`,scrollRef:u,children:[(0,K.jsxs)(Z.Top,{children:[(0,K.jsx)(Z.TopCell,{children:`Run`}),(0,K.jsx)(Z.TopCell,{children:`Status`}),(0,K.jsx)(Z.TopCell,{children:`Started`}),(0,K.jsx)(Z.TopCell,{children:`Duration`}),(0,K.jsx)(Z.TopCell,{children:` `})]}),e.map(e=>{let t=e.actualFireAt-e.scheduledFireAt,r=iC(t,{signed:!0}),i=e.outcome===`failed`,a=i?e.error:e.run?.error,l=Math.abs(t),u=!i&&l>AFi&&l<=jFi,p=`${e.scheduleId}-${e.runId}-${e.actualFireAt}`,m=c(e);m&&(f+=1);let h=(0,K.jsx)(T,{as:`span`,variant:`caption`,font:`mono`,tone:m?`ink`:`muted`,className:`whitespace-nowrap`,children:e.runId}),g=(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Z.Cell,{children:h}),(0,K.jsx)(Z.Cell,{children:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[i?(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`inline-flex items-center gap-1.5 whitespace-nowrap text-destructive-foreground`,children:[(0,K.jsx)(Zx,{className:`size-icon-sm`}),`publish failed`]}):e.run?(0,K.jsx)(DFi,{status:e.run.status}):(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`inline-flex items-center gap-1.5 whitespace-nowrap`,children:`pending`}),a?(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{asChild:!0,children:(0,K.jsx)(`span`,{className:`inline-flex text-destructive-foreground`,children:(0,K.jsx)(Zx,{className:`size-icon-sm`})})}),(0,K.jsx)(Tx,{children:a})]}):null]})}),(0,K.jsx)(Z.Cell,{children:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-2 whitespace-nowrap`,children:[e.actualFireAt?(0,K.jsx)(Dk,{value:e.actualFireAt}):`—`,u?(0,K.jsxs)(Cx,{children:[(0,K.jsx)(wx,{asChild:!0,children:(0,K.jsx)(`span`,{className:`inline-flex text-info-indicator`,children:(0,K.jsx)(Zx,{className:`size-icon-sm`})})}),(0,K.jsxs)(Tx,{children:[`Published `,r,` after the scheduled fire time`]})]}):null]})}),(0,K.jsx)(Z.Cell,{children:e.run?(0,K.jsx)(T,{as:`span`,variant:`body-sm`,font:`mono`,children:iC(e.run.durationMs)||`—`}):(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`—`})}),(0,K.jsx)(Z.Cell,{children:` `})]});return m?(0,K.jsx)(Z.RowLink,{to:s.workflowRunLink(n,e.runId),LinkComponent:o,...d(f),children:g},p):(0,K.jsx)(Z.RowStatic,{children:g},p)}),(0,K.jsx)(Z.NextPageLoading,{isLoading:i,hasMore:r,setEndOfListElement:a})]})}var NFi={id:`workflow-schedules`,label:`Schedules`,icon:qS,to:`/workflows/schedules`};function PFi({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 FFi(){let{scheduleId:e}=kv(),t=[eP(`/workflows`),NFi,{id:`schedule`,label:Zjt(e),icon:qS}],{paths:n}=sn(),{data:r,error:i}=vMt({scheduleId:e,queryOptions:{enabled:!!e}}),{data:a,isLoading:o,error:s,hasNextPage:c,isFetchingNextPage:l,setEndOfListElement:u}=xMt({scheduleId:e,queryOptions:{enabled:!!e}}),d=SMt({scheduleId:e});if(i&&FN(i))return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(TH,{variant:`fill`})]});if(i&&IN(i))return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(wH,{variant:`fill`,resource:`schedules`})]});if(i)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:t}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load schedule`,descriptionSlot:i.message})]});let f=r?.workflowId,p=r?.agentId;return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:t}),actionRow:(0,K.jsx)(TK,{children:(0,K.jsxs)(TK.End,{children:[(0,K.jsx)(X,{render:(0,K.jsx)(Lv,{to:n.schedulesLink()}),variant:`ghost`,icon:(0,K.jsx)(sS,{}),children:`Back to schedules`}),f?(0,K.jsx)(X,{icon:(0,K.jsx)(ZS,{}),render:(0,K.jsx)(Lv,{to:n.workflowLink(f)}),variant:`ghost`,children:`Open workflow`}):null,r&&r.status!==`completed`?(0,K.jsx)(X,{onClick:()=>{let e=r.status===`active`?`pause`:`resume`;d.mutate(e,{onSuccess:()=>iS.success(e===`pause`?`Schedule paused`:`Schedule resumed`),onError:e=>iS.error(e.message)})},disabled:d.isPending,"data-testid":`schedule-toggle-button`,children:r.status===`active`?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(ET,{}),`Pause`]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(DT,{}),`Resume`]})}):null]})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),r?(0,K.jsxs)(`div`,{className:`grid h-full grid-cols-[minmax(0,20rem)_1fr] gap-4 overflow-hidden`,children:[(0,K.jsxs)(`div`,{className:`flex h-fit flex-col gap-4 rounded-md border border-border p-4`,children:[(0,K.jsx)(PFi,{label:p?`Agent`:`Workflow`,children:f?(0,K.jsx)(Lv,{to:n.workflowLink(f),className:`text-foreground hover:underline`,children:f}):p?(0,K.jsx)(Lv,{to:n.agentLink(p),className:`text-foreground hover:underline`,children:p}):`—`}),(0,K.jsxs)(PFi,{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)(PFi,{label:`Status`,children:(0,K.jsx)(EFi,{status:r.status})}),(0,K.jsx)(PFi,{label:`Next fire`,children:r.nextFireAt?(0,K.jsx)(Dk,{value:r.nextFireAt}):`—`})]}),(0,K.jsxs)(`div`,{className:`overflow-y-auto`,"data-testid":`schedule-triggers-panel`,children:[(0,K.jsx)(T,{variant:`body`,className:`mb-3`,children:`Trigger history`}),s?(0,K.jsx)(Jx,{tone:`error`,titleSlot:`Failed to load trigger history`,descriptionSlot:s.message}):(0,K.jsx)(MFi,{triggers:a??[],isLoading:o,workflowId:f,hasNextPage:c,isFetchingNextPage:l,setEndOfListElement:u})]})]}):null]})}var IFi={target:e=>e.workflowId??e.agentId??``,status:e=>e.status,nextFireAt:e=>e.nextFireAt,lastFireAt:e=>e.lastFireAt},LFi=`minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto`;function RFi({schedules:e,isLoading:t,search:n=``,sort:r,onSortChange:i}){let{paths:a,Link:o}=sn(),s=(0,G.useMemo)(()=>{let t=n.toLowerCase();return IZ(t?e.filter(e=>e.id.toLowerCase().includes(t)||(e.workflowId??e.agentId??``).toLowerCase().includes(t)):e,r,IFi)},[e,n,r]),{containerRef:c,getRowProps:l}=PZ({count:s.length,global:!0});if(t)return(0,K.jsx)(DH,{columns:LFi});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:LFi,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)(EFi,{status:e.status})}),(0,K.jsx)(Z.Cell,{children:e.nextFireAt?(0,K.jsx)(Dk,{value:e.nextFireAt}):`—`}),(0,K.jsx)(Z.Cell,{children:e.lastRun?(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-2 whitespace-nowrap`,children:[(0,K.jsx)(DFi,{status:e.lastRun.status}),e.lastFireAt?(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,children:(0,K.jsx)(Dk,{value:e.lastFireAt})}):null]}):e.lastFireAt?(0,K.jsx)(Dk,{value:e.lastFireAt}):(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`Never`})})]},e.id))]})}function zFi({workflowId:e}={}){let{data:t,isLoading:n,error:r}=yMt(e?{workflowId:e}:{}),[i,a]=(0,G.useState)(``),[o,s]=(0,G.useState)();return r?(0,K.jsx)(Jx,{tone:`error`,titleSlot:`Failed to load schedules`,descriptionSlot:r.message}):(0,K.jsxs)(`div`,{className:`grid h-full grid-rows-[auto_1fr] gap-4 overflow-hidden`,children:[(0,K.jsx)(`div`,{className:`max-w-120`,children:(0,K.jsx)(MH,{...NH,onValueChange:a,label:`Search schedules`,placeholder:`Search by id or workflow`})}),(0,K.jsx)(`div`,{className:`overflow-y-auto`,children:(0,K.jsx)(RFi,{schedules:t??[],isLoading:n,search:i,sort:o,onSortChange:(e,t)=>s({key:t,direction:e})})})]})}var BFi=[eP(`/workflows`),NFi];function VFi(){let[e]=Rv(),t=e.get(`workflowId`)??void 0,{error:n}=yMt(t?{workflowId:t}:{});return n&&FN(n)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:BFi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(TH,{variant:`fill`})]}):n&&IN(n)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:BFi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(wH,{variant:`fill`,resource:`schedules`})]}):(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:BFi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),(0,K.jsx)(`div`,{className:`h-full`,children:(0,K.jsx)(zFi,{workflowId:t})})]})}var HFi=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),UFi={"--belt-hue":`var(--warning-indicator)`};function WFi(e){let t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function GFi(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 KFi({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:(0,K.jsxs)(`section`,{className:c(REt,`pointer-events-auto relative isolate`),"data-testid":`workflow-suspended-steps`,"aria-label":`Step suspended`,children:[(0,K.jsxs)(`div`,{className:`max-h-[calc(100cqh-64px)] overflow-y-auto overscroll-contain rounded-[inherit]`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-3 border-b border-border bg-background px-5 py-4`,children:[(0,K.jsxs)(T,{as:`h2`,variant:`column`,tone:`ink`,className:`flex items-center gap-2`,children:[(0,K.jsx)(Dx,{children:(0,K.jsx)(ET,{})}),`Step suspended`]}),(0,K.jsx)(eC,{variant:`orange`,emphasis:`subtle`,children:`Needs input`})]}),e.map(e=>{let n=t.allSteps[e.stepId];if(!n||n.isWorkflow)return null;let i=n?.resumeSchema?zO(nk(n.resumeSchema)):Ad(q(),md());return(0,K.jsx)(qFi,{step:e,stepSchema:i,description:n.description,onResume:r},`${e.runId}-${e.stepId}`)})]}),(0,K.jsx)(kXe,{status:`ready`,label:`Needs input`,className:`before:hidden`,style:UFi})]})}function qFi({step:e,stepSchema:t,description:n,onResume:r}){let[i,a]=(0,G.useState)(!1),[o,s]=(0,G.useState)(!1);return(0,K.jsxs)(`div`,{className:`space-y-5 p-5 [&+&]:border-t [&+&]:border-border`,children:[(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(T,{as:`p`,variant:`subheading`,tone:`ink`,className:`break-words`,children:e.stepId}),n&&(0,K.jsx)(T,{as:`p`,variant:`caption`,tone:`muted`,children:n})]}),e.suspendPayload!==void 0&&(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsxs)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`flex items-center gap-2`,children:[(0,K.jsx)(Dx,{children:(0,K.jsx)(HFi,{})}),`The step is asking`]}),(0,K.jsxs)(DC,{open:i,onOpenChange:a,children:[(0,K.jsxs)(OC,{className:c(`bg-card hover:bg-card active:bg-card shadow-raised [--field:var(--field-on-surface)] [--field-disabled:var(--field-on-surface)] [--field-rim:var(--field-rim-on-surface)]`,`flex w-full items-center justify-between gap-2 rounded-lg px-3 py-2.5`),children:[(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(Dx,{children:(0,K.jsx)(y,{direction:`right`,className:`text-muted-foreground`})}),(0,K.jsx)(T,{as:`span`,variant:`body`,tone:`ink`,className:`truncate`,children:GFi(e.suspendPayload,e.stepId)})]}),(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`shrink-0`,children:WFi(e.suspendPayload)})]}),(0,K.jsx)(kC,{children:(0,K.jsx)(`div`,{"data-testid":`suspended-payload`,className:`pt-2`,children:(0,K.jsx)(bw,{value:JSON.stringify(e.suspendPayload,null,2),editable:!1,className:`w-full overflow-x-auto p-2`,showCopyButton:!1})})})]})]}),(0,K.jsxs)(`div`,{className:`space-y-3`,children:[(0,K.jsxs)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`flex items-center gap-2`,children:[(0,K.jsx)(Dx,{children:(0,K.jsx)(R4,{})}),`Your response`]}),(0,K.jsx)(`div`,{className:`-mx-5`,children:(0,K.jsx)(eEt,{schema:t,isSubmitLoading:o,submitButtonLabel:`Resume`,submitButtonVariant:`primary`,submitButtonIcon:(0,K.jsx)(DT,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:async t=>{s(!0);try{await r({stepId:e.stepId.split(`.`),runId:e.runId,resumeData:t})}catch(e){iS.error(e instanceof Error?e.message:`Error resuming workflow`)}finally{s(!1)}}})})]})]})}function JFi({hidden:e,requestContext:t,canResume:n}){let{result:r,workflow:i,runId:a,isStreamingWorkflow:o}=(0,G.useContext)(WS),s=Gft(r,a),c=Xft(t),l=r?.status===`suspended`&&s.length>0&&!o;return!i||!l||!n?null:(0,K.jsx)(`div`,{hidden:e,"data-testid":`workflow-suspended-overlay`,className:`pointer-events-none absolute top-12 right-2 z-30 w-95 max-w-[calc(100%-16px)] animate-in duration-300 fade-in-0 slide-in-from-top-2 motion-reduce:animate-none`,children:(0,K.jsx)(KFi,{suspendedSteps:s,workflow:i,isStreaming:o,onResume:c})},a)}var YFi=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`})),XFi={success:{label:`Completed`,icon:pC},failed:{label:`Failed`,icon:qx},suspended:{label:`Needs input`,icon:ET},waiting:{label:`Waiting`,icon:XS},paused:{label:`Paused`,icon:ET},skipped:{label:`Skipped`,icon:YFi},running:{label:`Running`,icon:TT},canceled:{label:`Canceled`,icon:Kx}},ZFi={label:`Status unavailable`,icon:Lq};function QFi({row:e,isSelected:t,isHovered:n,onSelectStep:r,onHoverStep:i,onOpenInput:a,onOpenOutput:o}){let s=Object.hasOwn(XFi,e.status)?XFi[e.status]:ZFi,l=s.icon,u=Fmt(e.status),d=e.stepId.slice(0,e.stepId.lastIndexOf(`.`)),f=e.isNestedEntry?e.stepId.slice(e.stepId.lastIndexOf(`.`)+1):e.stepId;return(0,K.jsxs)(`div`,{"data-testid":`workflow-timeline-row`,"data-workflow-step-key":e.stepId,onMouseEnter:()=>!e.isNestedEntry&&i(e.stepId),onMouseLeave:()=>!e.isNestedEntry&&i(null),className:c(`grid grid-cols-[minmax(130px,1fr)_minmax(64px,1fr)_56px_64px] items-center gap-3 rounded-md px-2 py-1`,`@max-[540px]/workflow-timeline:grid-cols-[minmax(0,1fr)_48px_64px] @max-[540px]/workflow-timeline:gap-x-1.5 @max-[540px]/workflow-timeline:gap-y-1 @max-[540px]/workflow-timeline:py-2`,(t||n)&&`bg-fill-subtle`),children:[(0,K.jsxs)(`button`,{type:`button`,"aria-disabled":e.isNestedEntry,"aria-pressed":t,onClick:()=>{e.isNestedEntry||r(e.stepId)},title:e.stepId,className:c(`text-foreground`,`flex min-h-9 min-w-0 cursor-pointer items-center gap-2.5 text-left focus-visible:rounded-sm aria-disabled:cursor-default`,p),children:[(0,K.jsx)(`span`,{"aria-label":s.label,className:c(`grid size-6 flex-none place-items-center rounded-md border border-border bg-background`,Imt[u]),children:(0,K.jsx)(l,{"aria-hidden":!0,className:c(`size-3.5`,e.status===`running`&&`motion-safe:animate-spin`)})}),(0,K.jsxs)(`span`,{className:`min-w-0`,children:[(0,K.jsx)(T,{as:`span`,variant:`meta`,className:`block truncate`,children:f}),e.isNestedEntry&&(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`flex min-w-0 items-center gap-1`,children:[(0,K.jsx)(XYe,{"aria-hidden":!0,className:`size-icon-xs shrink-0`}),(0,K.jsx)(`span`,{className:`truncate`,children:d})]})]})]}),(0,K.jsx)(`div`,{className:`relative h-5 min-w-0 overflow-hidden rounded-sm bg-muted @max-[540px]/workflow-timeline:col-span-full @max-[540px]/workflow-timeline:row-start-2 @max-[540px]/workflow-timeline:ml-[34px]`,"aria-hidden":!0,children:e.timing&&(0,K.jsx)(`div`,{"data-testid":`workflow-timeline-bar`,"data-offset":e.timing.offsetPct,"data-width":e.timing.widthPct,className:c(`absolute top-0 h-full min-w-0.5 rounded-sm`,Lmt[u]),style:{left:`${e.timing.offsetPct}%`,width:`${e.timing.widthPct}%`}})}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`text-right whitespace-nowrap`,title:e.timing&&e.spansSuspension?`Includes time spent suspended waiting for input`:void 0,children:e.timing?(0,K.jsx)(T,{as:`span`,variant:`meta`,font:`mono`,children:iC(e.timing.durationMs)}):(0,K.jsx)(`span`,{"aria-label":`Timing unavailable`,children:`—`})}),(0,K.jsxs)(`div`,{className:`flex items-center`,children:[(0,K.jsx)(X,{type:`button`,variant:`ghost`,size:`icon-sm`,tooltip:`View step input`,disabled:e.step.input===void 0,onClick:t=>a(e,t.currentTarget),children:(0,K.jsx)(bk,{})}),(0,K.jsx)(X,{type:`button`,variant:`ghost`,size:`icon-sm`,tooltip:`View step output`,disabled:e.step.output===void 0,onClick:t=>o(e,t.currentTarget),children:(0,K.jsx)(yk,{})})]})]})}var $Fi=e=>e.includes(`.`),eIi=e=>e===`input`||e.endsWith(`.input`),tIi=1;function nIi(e,t){let n=Bmt(e),r=n?.isLive?Math.max(t,n.start):n?.end;return{span:n&&r!==void 0?{start:n.start,end:r}:void 0,isLive:n?.isLive??!1,spansSuspension:n?.spansSuspension??!1}}function rIi(e,t){let n=Object.entries(e).filter(([e])=>!eIi(e)).map(([e,n])=>({stepId:e,step:n,...nIi(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,tIi),100-t)}}return{stepId:e,step:t,status:wk(t)?`suspended`:t.status,timing:s,spansSuspension:a,isRunning:r,isNestedEntry:$Fi(e)}})}var iIi=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`})]})),aIi=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 oIi(){let{steps:e}=e$(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:i}=US(),[a,o]=(0,G.useState)(()=>Date.now()),[s,l]=(0,G.useState)(!0),[u,d]=(0,G.useState)(!1),{showData:f}=nN(),p=(0,G.useRef)(null),m=rIi(e,a),h=m.some(e=>e.isRunning);return iJe(p,{enabled:h&&!s}),(0,G.useEffect)(()=>{if(!h||s)return;let e=setInterval(()=>o(Date.now()),100);return()=>clearInterval(e)},[h,s]),m.length===0?null:(0,K.jsx)(`div`,{"data-testid":`workflow-timeline`,className:`relative z-20 shrink-0 px-2 pb-2`,children:(0,K.jsxs)(DC,{open:!s,onOpenChange:e=>l(!e),className:c(Bv,`@container/workflow-timeline pointer-events-auto overflow-hidden rounded-xl`),children:[(0,K.jsxs)(`div`,{className:`flex items-center`,children:[(0,K.jsxs)(OC,{className:`flex min-h-11 min-w-0 flex-1 items-center gap-2 px-3.5 py-2.5 text-caption text-foreground hover:bg-fill-subtle`,"aria-label":s?`Expand timeline`:`Collapse timeline`,children:[(0,K.jsx)(`span`,{children:(0,K.jsx)(YV,{"aria-hidden":!0,className:`size-icon-md text-muted-foreground`})}),(0,K.jsx)(`span`,{children:`Timeline`}),(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,children:[m.length,` events`]}),(0,K.jsx)(`span`,{className:`ml-auto`,children:(0,K.jsx)(y,{direction:`right`,className:`size-4`})})]}),!s&&(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:u?`Restore timeline height`:`Enlarge timeline`,"aria-pressed":u,onClick:()=>d(!u),className:`mr-2 shrink-0`,children:u?(0,K.jsx)(aIi,{}):(0,K.jsx)(iIi,{})})]}),(0,K.jsx)(kC,{children:(0,K.jsx)(`div`,{ref:p,"data-testid":`workflow-timeline-list`,className:c(`overflow-auto overscroll-contain px-1.5 pb-1.5`,u?`max-h-[min(720px,calc(100dvh-112px))]`:`max-h-[min(320px,40dvh)]`),children:m.map(e=>(0,K.jsx)(QFi,{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 sIi=({workflowId:e,workflow:t,isLoading:n})=>{let[r]=HS(`workflow`,e),{canExecute:i,isLoading:a}=fS(),{stepDetail:o}=nN(),s=Zw(),c=o?.type===`data`,l=(0,K.jsxs)(`div`,{className:`[container-type:size] relative h-full min-h-0`,children:[(0,K.jsx)(Qlr,{workflowId:e,workflow:t,isLoading:n,requestContext:r}),(0,K.jsx)(JFi,{hidden:c,requestContext:r,canResume:!a&&i(`workflows`)}),c&&(0,K.jsx)(`div`,{className:`pointer-events-auto absolute top-12 right-2 z-30 flex max-h-[calc(100cqh-64px)] w-[440px] max-w-[calc(100%-16px)] flex-col`,children:(0,K.jsx)(n$,{requestContext:r})}),(0,K.jsx)(`div`,{className:`pointer-events-none absolute right-0 bottom-0 left-[var(--workflow-left-panel-width,0px)] z-20`,children:(0,K.jsx)(oIi,{})})]});return s&&o&&!c?(0,K.jsx)(`div`,{className:`h-full min-h-0 overflow-hidden`,children:(0,K.jsx)(n$,{requestContext:r})}):(0,K.jsxs)(`div`,{className:`relative h-full min-h-0`,children:[l,(0,K.jsxs)(p6,{className:`pointer-events-none absolute inset-0 z-30 min-h-0 w-full min-w-0 p-2`,children:[(0,K.jsx)(f6,{id:`workflow-graph`,className:`pointer-events-none min-w-0`}),o&&!c&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(m6,{className:`pointer-events-auto`}),(0,K.jsx)(f6,{id:`workflow-step-detail`,minSize:300,maxSize:`60%`,defaultSize:420,className:`min-w-0`,children:(0,K.jsx)(`div`,{className:`pointer-events-auto h-full min-h-0 overflow-hidden rounded-studio-panel border border-border bg-background`,children:(0,K.jsx)(n$,{requestContext:r})})})]})]})]})},cIi=()=>{let{workflowId:e}=kv(),{data:t,isLoading:n,error:r}=tN({workflowId:e,requestContext:HS(`workflow`,e)[0],queryOptions:{enabled:!!e}});return r&&FN(r)?(0,K.jsx)(TH,{variant:`fill`}):r&&IN(r)?(0,K.jsx)(wH,{variant:`fill`,resource:`workflows`}):(0,K.jsx)(sIi,{workflowId:e,workflow:t??void 0,isLoading:n})};function lIi(){let{workflowId:e}=kv(),{error:t}=yMt(e?{workflowId:e}:{});if(!e)return null;let n;return n=t&&FN(t)?(0,K.jsx)(TH,{variant:`fill`}):t&&IN(t)?(0,K.jsx)(wH,{variant:`fill`,resource:`schedules`}):(0,K.jsx)(`div`,{className:`h-full`,children:(0,K.jsx)(zFi,{workflowId:e})}),(0,K.jsxs)(RS,{children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Schedules`}),n]})}function uIi(){let{workflowId:e}=kv();return e?(0,K.jsx)(xsi,{scopedEntityId:e,scopedEntityType:Dp.WORKFLOW_RUN}):null}var dIi=(0,G.createContext)(null);function q9(){let e=(0,G.useContext)(dIi);if(!e)throw Error(`Workspace components must be rendered inside <Workspace.Root>`);return e}var fIi=e=>e?.status;function pIi(e,t){return FN(e)?`Your session has expired. Sign in again to continue.`:IN(e)?`You don't have permission to access this.`:LN(e)?`This path no longer exists.`:fIi(e)===501?`This workspace does not support this operation.`:t}function mIi({error:e,fallback:t,className:n}){return(0,K.jsx)(Sk,{variant:`destructive`,className:n,children:(0,K.jsx)(Sk.Message,{children:pIi(e,t)})})}var hIi=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;function gIi(e){let t=hIi.exec(e);return t?{frontmatter:t[1]??``,body:e.slice(t[0].length)}:{frontmatter:null,body:e}}function _Ii({content:e}){let{frontmatter:t,body:n}=gIi(e);return(0,K.jsxs)(K.Fragment,{children:[t!==null&&(0,K.jsx)(`div`,{"data-testid":`workspace-frontmatter`,className:`border-b border-border`,children:(0,K.jsx)(pJ,{code:t,lang:`yaml`,overflow:`wrap`,className:`rounded-none border-0 bg-transparent [&_pre]:p-4`})}),(0,K.jsx)(`div`,{className:`p-4`,children:(0,K.jsx)(xY,{children:n})})]})}function vIi(){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 yIi({path:e,content:t,mimeType:n}){return WFn(e,n)?(0,K.jsx)(`div`,{className:`flex justify-center p-4`,children:(0,K.jsx)(`img`,{src:`data:${n||`image/png`};base64,${t}`,alt:e.split(`/`).pop(),className:`max-w-full object-contain`})}):GFn(e,n)?(0,K.jsx)(`div`,{className:`flex justify-center p-4`,children:(0,K.jsx)(`video`,{controls:!0,"aria-label":e.split(`/`).pop(),className:`max-w-full`,children:(0,K.jsx)(`source`,{src:`data:${qFn(e,n)};base64,${t}`,type:qFn(e,n)})})}):JFn(e)?(0,K.jsx)(_Ii,{content:t}):(0,K.jsx)(pJ,{code:t,lang:uXe(e),overflow:`scroll`,className:`rounded-none border-0 bg-transparent [&_pre]:p-4`})}function bIi({renderPreview:e}){let{workspaceId:t,activeFilePath:n}=q9(),{data:r,isLoading:i,error:a}=lIn({workspaceId:t,path:n,queryOptions:{enabled:!!n}});if(!n)return null;if(i)return(0,K.jsxs)(`div`,{"aria-busy":`true`,className:`flex flex-col gap-2 p-4`,children:[(0,K.jsx)(zS,{className:`h-4 w-1/2`}),(0,K.jsx)(zS,{className:`h-4 w-5/6`}),(0,K.jsx)(zS,{className:`h-4 w-2/3`})]});if(!r)return(0,K.jsx)(mIi,{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)(yIi,{...o})}var xIi=(e,t)=>e===`.`?t:`${e}/${t}`,SIi=e=>e.split(`/`).slice(0,-1).map((e,t,n)=>n.slice(0,t+1).join(`/`)),CIi=e=>{let t=e.lastIndexOf(`/`);return t===-1?`.`:e.slice(0,t)};function wIi({labeled:e=!1}={}){let{workspaceId:t,onCreateDirectory:n,isReadOnly:r}=q9(),i=u_(),[a,o]=(0,G.useState)(!1),[s,c]=(0,G.useState)(``),[l,u]=(0,G.useState)(!1);if(!n||r(`.`))return null;let d=s.trim().replace(/^\.?\/+|\/+$/g,``),f=async()=>{if(d){u(!0);try{await n(d),await i.invalidateQueries({queryKey:[`workspace`,t,`fs`,`list`,CIi(d)]}),o(!1),c(``)}catch{}finally{u(!1)}}};return(0,K.jsxs)(K.Fragment,{children:[e?(0,K.jsx)(X,{variant:`ghost`,icon:(0,K.jsx)(P6,{}),onClick:()=>o(!0),children:`New folder`}):(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`New folder`,onClick:()=>o(!0),children:(0,K.jsx)(P6,{})}),(0,K.jsx)(nT,{open:a,onOpenChange:o,pending:l,children:(0,K.jsx)(rT,{size:`sm`,children:(0,K.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),f()},children:[(0,K.jsx)(iT,{children:(0,K.jsx)(sT,{children:`New folder`})}),(0,K.jsx)(oT,{children:(0,K.jsx)(Jj,{autoFocus:!0,"aria-label":`Folder path`,placeholder:`docs/guides`,value:s,onChange:e=>c(e.target.value)})}),(0,K.jsxs)(aT,{children:[(0,K.jsx)(lT,{children:`Cancel`}),(0,K.jsx)(X,{type:`submit`,variant:`primary`,disabled:!d||l,children:`Create`})]})]})})})]})}function TIi(e){return`${e.topSource}/${e.name}`}function EIi(e){let t=QFn(e.topSource,e.name);return t?`${t.owner}/${t.repo}/${e.name}`:null}function DIi({open:e,onOpenChange:t,workspaceId:n,onInstall:r,isInstalling:i,installedSkillIds:a=[],installedSkillNames:o=[],writableMounts:s,installedSkillPaths:l}){let[u,d]=(0,G.useState)(``),[f,p]=(0,G.useState)(null),[m,h]=(0,G.useState)(),g=s?.some(e=>e.path===m)?m:s?.[0]?.path,{data:_,isLoading:v}=XFn({workspaceId:n,queryOptions:{enabled:!!n}}),y=YFn({workspaceId:n}),b=(0,G.useMemo)(()=>f?.topSource?QFn(f.topSource,f.name):null,[f]),x=(0,G.useMemo)(()=>!b||!f?null:`https://skills.sh/${b.owner}/${b.repo}/${f.name}`,[b,f]),{data:S,isLoading:C}=ZFn({workspaceId:n,owner:b?.owner,repo:b?.repo,skillPath:f?.name,queryOptions:{enabled:!!n&&!!b&&!!f}}),w=cC(e=>{e.trim().length>=2&&y.mutate(e)},300),E=(0,G.useCallback)(e=>{d(e),w(e)},[w]),D=(0,G.useMemo)(()=>u.trim().length>=2?y.data?.skills??[]:_?.skills??[],[u,y.data,_]),O=y.isPending,k=u.trim().length>=2,A=(0,G.useMemo)(()=>{if(!f)return!1;let e=EIi(f);return!!(e&&a.includes(e)||o.includes(f.name))},[f,a,o]),j=(0,G.useCallback)(()=>{f&&b&&r({repository:`${b.owner}/${b.repo}`,skillName:f.name,mount:s&&s.length>1?g:void 0})},[f,b,r,s,g]),M=(0,G.useCallback)(e=>{e||(d(``),p(null),h(void 0)),t(e)},[t]);return(0,K.jsx)(nT,{open:e,onOpenChange:M,pending:i,children:(0,K.jsxs)(rT,{size:`xl`,className:`h-[80vh]`,children:[(0,K.jsxs)(iT,{children:[(0,K.jsx)(sT,{children:`Add Skill`}),(0,K.jsx)(cT,{children:`Search and install skills from the community registry`})]}),(0,K.jsxs)(oT,{layout:`fill`,children:[(0,K.jsx)(MH,{label:`Search skills`,placeholder:`Search skills`,value:u,onValueChange:E}),(0,K.jsxs)(`div`,{className:`flex min-h-0 flex-1 gap-4`,children:[(0,K.jsxs)(`div`,{className:`flex min-h-0 w-1/2 flex-col`,children:[(0,K.jsx)(T,{as:`p`,variant:`eyebrow`,tone:`muted`,className:`mb-2`,children:k?`Search Results`:`Popular Skills`}),(0,K.jsx)(LS,{className:`flex-1 rounded-lg border border-border`,children:(0,K.jsx)(IS,{className:!v&&!O&&D.length===0?`flex flex-col [&>div]:flex [&>div]:flex-1 [&>div]:flex-col`:void 0,children:v||O?(0,K.jsx)(`div`,{className:`flex items-center justify-center py-5`,children:(0,K.jsx)(It,{className:`text-muted-foreground`})}):D.length===0?(0,K.jsx)(Jx,{className:`flex-1`,titleSlot:k?`No skills found`:`No skills available`}):(0,K.jsx)(`div`,{className:`space-y-1 p-2`,children:D.map(e=>{let t=TIi(e),n=EIi(e),r=n&&a.includes(n)||o.includes(e.name),i=f?TIi(f):null;return(0,K.jsx)(`button`,{onClick:()=>p(e),className:c(`w-full rounded-md px-3 py-2 text-left`,`hover:bg-fill-subtle`,i===t&&`border border-border-strong bg-fill-hover`),children:(0,K.jsxs)(`div`,{className:`flex items-start justify-between gap-2`,children:[(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(T,{as:`span`,variant:`subheading`,tone:`ink`,className:`truncate`,children:e.name}),r&&(0,K.jsxs)(T,{as:`span`,variant:`meta`,className:`inline-flex items-center gap-1 rounded bg-info-subtle px-1.5 py-0.5 text-info-subtle-foreground`,children:[(0,K.jsx)(pC,{className:`size-icon-xs`}),`Installed`]})]}),(0,K.jsx)(T,{as:`p`,variant:`caption`,tone:`muted`,className:`truncate`,children:e.topSource})]}),(0,K.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 text-muted-foreground`,children:[(0,K.jsx)(fJ,{className:`size-icon-xs`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,children:e.installs.toLocaleString()})]})]})},t)})})})})]}),(0,K.jsxs)(`div`,{className:`flex min-h-0 w-1/2 flex-col`,children:[(0,K.jsx)(T,{as:`p`,variant:`eyebrow`,tone:`muted`,className:`mb-2`,children:`Preview`}),(0,K.jsx)(`div`,{className:`flex flex-1 flex-col overflow-hidden rounded-lg border border-border`,children:f?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`border-b border-border bg-card p-4`,children:(0,K.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,K.jsx)(`div`,{className:`rounded-lg bg-muted p-2`,children:(0,K.jsx)(AZ,{className:`size-icon-lg text-muted-foreground`})}),(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsx)(T,{as:`h3`,variant:`subheading`,tone:`ink`,className:`truncate`,children:f.name}),(0,K.jsxs)(`div`,{className:`mt-1 flex items-center gap-3 text-muted-foreground`,children:[(0,K.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(kZ,{className:`size-icon-xs`}),(0,K.jsx)(T,{as:`span`,variant:`caption`,className:`block`,children:f.topSource})]}),(0,K.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(fJ,{className:`size-icon-xs`}),(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[f.installs.toLocaleString(),` installs`]})]})]})]}),b&&(0,K.jsx)(`a`,{href:`https://github.com/${b.owner}/${b.repo}`,target:`_blank`,rel:`noopener noreferrer`,className:c(`text-muted-foreground hover:text-foreground`,`transition-[color] duration-fast ease-out-custom motion-reduce:transition-none`),title:`View on GitHub`,children:(0,K.jsx)(tP,{className:`size-icon-md`})})]})}),C?(0,K.jsx)(`div`,{className:`flex flex-1 items-center justify-center`,children:(0,K.jsx)(It,{className:`text-muted-foreground`})}):S?(0,K.jsx)(LS,{className:`flex-1`,children:(0,K.jsx)(`div`,{className:`p-4`,children:(0,K.jsx)(xY,{children:S})})}):(0,K.jsx)(Jx,{className:`flex-1`,iconSlot:(0,K.jsx)(OZ,{}),titleSlot:`Preview unavailable`,actionSlot:x&&(0,K.jsxs)(`a`,{href:x,target:`_blank`,rel:`noopener noreferrer`,className:`flex items-center gap-1 text-info-indicator hover:underline`,children:[(0,K.jsxs)(T,{as:`span`,variant:`caption`,className:`block`,children:[`View on skills.sh`,` `]}),(0,K.jsx)(tP,{className:`size-icon-xs`})]})})]}):(0,K.jsx)(Jx,{variant:`fill`,iconSlot:(0,K.jsx)(OZ,{}),titleSlot:`Select a skill to preview`})})]})]}),f&&s&&s.length>1&&(0,K.jsxs)(ak,{orientation:`horizontal`,className:c(`bg-card hover:bg-card active:bg-card shadow-raised [--field:var(--field-on-surface)] [--field-disabled:var(--field-on-surface)] [--field-rim:var(--field-rim-on-surface)]`,`gap-3 rounded-lg p-3`),children:[(0,K.jsx)($N,{className:`size-icon-md shrink-0 text-muted-foreground`}),(0,K.jsx)(sk,{className:`whitespace-nowrap`,children:`Install to`}),(0,K.jsxs)(Bk,{value:g,onValueChange:h,children:[(0,K.jsx)(Hk,{className:`flex-1`,children:(0,K.jsx)(Vk,{})}),(0,K.jsx)(Uk,{children:s.map(e=>{let t=e.displayName??e.name??e.provider??`unknown`;return(0,K.jsxs)(Wk,{value:e.path,children:[t,` (`,e.path,`)`]},e.path)})})]})]})]}),f&&(0,K.jsxs)(aT,{children:[A&&s&&s.length>1&&(()=>{let e=l?.[f.name];if(!e)return null;let t=s.find(t=>e.startsWith(t.path+`/`)||e===t.path);return t?(0,K.jsxs)(T,{as:`span`,variant:`caption`,tone:`muted`,className:`mr-auto`,children:[`Installed at `,t.path]}):null})(),(0,K.jsx)(lT,{children:`Cancel`}),(0,K.jsx)(tT,{onConfirm:j,disabled:!b||A,"data-testid":`install-skill-button`,children:i?`Installing...`:A?`Already installed`:`Install`})]})]})})}function OIi({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)(K5n,{}),`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)(K5n,{})}),(0,K.jsx)(DIi,{...c,open:r,onOpenChange:i,workspaceId:t,onInstall:e=>void l(e),isInstalling:a})]})}function kIi({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(SIi(t??``))),[v,y]=(0,G.useState)(t);if(t!==v){y(t);let e=SIi(t??``).filter(e=>!g.has(e));e.length>0&&_(new Set([...g,...e]))}let b=a?.join(`
725
725
  `)??``,x=(0,G.useMemo)(()=>({workspaceId:e,activeFilePath:t,setActiveFilePath:i,isSearching:f,setSearching:e=>{p(e),e||h(``)},query:m,setQuery:h,onDelete:n,onCreateDirectory:r,isReadOnly:e=>(b?b.split(`
726
726
  `):[]).some(t=>t===`.`||e===t||e.startsWith(`${t}/`)),searchFiles:o,searchSkills:s,fileCount:c,skillCount:l,addSkill:u,openFolders:g,setFolderOpen:(e,t)=>_(n=>{if(n.has(e)===t)return n;let r=new Set(n);return t?r.add(e):r.delete(e),r})}),[e,t,f,m,n,r,i,b,o,s,c,l,u,g]);return(0,K.jsx)(dIi.Provider,{value:x,children:d})}var AIi=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`})}),jIi=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 MIi(){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)(jIi,{})})}function NIi(){let{isSearching:e}=q9();return e?(0,K.jsx)(IIi,{}):(0,K.jsx)(FIi,{})}var PIi=(e,t)=>`${e} ${t}${e===1?``:`s`}`;function FIi(){let{fileCount:e,skillCount:t}=q9();return(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`muted`,className:`block min-w-0`,children:(0,K.jsxs)(AC,{singleLine:!0,children:[(0,K.jsx)(AC.Item,{children:e===void 0?`Files`:PIi(e,`File`)}),t===void 0?null:(0,K.jsx)(AC.Item,{children:PIi(t,`Skill`)})]})})}function IIi(){let{setSearching:e,setQuery:t}=q9(),[n,r]=(0,G.useState)(``),[,i]=(0,G.useTransition)();return(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(Jj,{type:`search`,size:`sm`,autoFocus:!0,"aria-label":`Search query`,placeholder:`Search files and skills`,value:n,onChange:e=>{let n=e.target.value;r(n),i(()=>t(n))},onKeyDown:t=>{t.key===`Escape`&&e(!1)}}),(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`Close search`,onClick:()=>e(!1),children:(0,K.jsx)(xw,{})})]})}function LIi(){let{workspaceId:e,query:t,activeFilePath:n,setActiveFilePath:r,searchFiles:i,searchSkills:a}=q9(),{data:o,isLoading:s,isError:l,error:u}=pIn({workspaceId:e,query:t,files:i,skills:a,queryOptions:{enabled:t.trim().length>0&&(i||a)}});return t.trim()?s?(0,K.jsxs)(`div`,{"aria-busy":`true`,className:`flex flex-col gap-2 p-2`,children:[(0,K.jsx)(zS,{className:`h-4 w-3/4`}),(0,K.jsx)(zS,{className:`h-4 w-2/3`})]}):l?(0,K.jsx)(mIi,{error:u,fallback:`Search failed.`,className:`m-2`}):o?.length?(0,K.jsx)(`ul`,{"aria-label":`Search results`,className:`flex flex-col py-1`,children:o.map(e=>(0,K.jsx)(`li`,{children:(0,K.jsxs)(`button`,{type:`button`,title:e.path,onClick:()=>r(e.path),className:c(`text-foreground`,`flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left hover:bg-fill-subtle`,n===e.path&&`bg-fill`),children:[(0,K.jsx)(Dx,{size:`sm`,children:e.kind===`skill`?(0,K.jsx)(AZ,{}):(0,K.jsx)(AIi,{})}),(0,K.jsx)(T,{as:`span`,variant:`body-sm`,className:`truncate`,children:e.label})]})},e.path))}):(0,K.jsx)(Jx,{titleSlot:`No results`}):(0,K.jsx)(Jx,{titleSlot:`Search files and skills`,descriptionSlot:`Type to find matching content.`})}function RIi({mount:e}){switch(e.icon||e.provider){case`aws-s3`:case`s3`:return(0,K.jsx)(dOn,{className:`text-foreground`});case`google-cloud`:case`google-cloud-storage`:case`gcs`:return(0,K.jsx)(gOn,{});case`azure-blob`:case`azure`:return(0,K.jsx)(mOn,{className:`text-badge-blue-indicator`});case`cloudflare`:case`cloudflare-r2`:case`r2`:return(0,K.jsx)(U6,{className:`text-badge-orange-indicator`});case`neon`:return(0,K.jsx)(U6,{className:`text-badge-green-indicator`});case`minio`:return(0,K.jsx)(pcr,{className:`text-badge-red-indicator`});case`database`:return(0,K.jsx)(uT,{className:`text-badge-green-indicator`});case`local`:case`folder`:return(0,K.jsx)($N,{className:`text-badge-amber-indicator`});case`hard-drive`:return(0,K.jsx)(pcr,{className:`text-muted-foreground`});default:return(0,K.jsx)(U6,{className:`text-muted-foreground`})}}var zIi=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`})}),BIi=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 VIi(){let{workspaceId:e,activeFilePath:t,setActiveFilePath:n}=q9(),{data:r,isLoading:i,error:a}=iJ({workspaceId:e,path:`.`}),[o,s]=(0,G.useState)(null);return i?(0,K.jsx)(YIi,{}):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)(HIi,{entries:r,parent:`.`,onRequestDelete:s})}),(0,K.jsx)(JIi,{entry:o,onClose:()=>s(null)})]}):(0,K.jsx)(mIi,{error:a,fallback:`Could not load files.`,className:`m-2`})}function HIi({entries:e,parent:t,onRequestDelete:n}){return e.map(e=>{let r=xIi(t,e.name);return e.type===`directory`?(0,K.jsx)(GIi,{name:e.name,path:r,mount:e.mount,onRequestDelete:n},e.name):(0,K.jsx)(qIi,{name:e.name,size:e.size,path:r,onRequestDelete:n},e.name)})}function UIi({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 WIi({name:e,onClick:t}){return(0,K.jsx)(X,{variant:`destructive-ghost`,size:`icon-sm`,tooltip:`Delete ${e}`,onClick:e=>{e.stopPropagation(),t()},onKeyDown:e=>e.stopPropagation(),children:(0,K.jsx)(Kj,{})})}function GIi({name:e,path:t,mount:n,onRequestDelete:r}){let{workspaceId:i,onDelete:a,onCreateDirectory:o,isReadOnly:s,openFolders:c,setFolderOpen:l}=q9(),u=c.has(t),{isLoading:d}=iJ({workspaceId:i,path:t,queryOptions:{enabled:u}}),[f,p]=(0,G.useState)(!1),m=a&&!s(t),h=o&&!s(t);return(0,K.jsxs)(N6.Folder,{id:t,open:u,onOpenChange:e=>l(t,e),children:[(0,K.jsxs)(N6.FolderTrigger,{actions:m||h?(0,K.jsxs)(UIi,{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)(WIi,{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)(RIi,{mount:n})}):(0,K.jsx)(zIi,{})}),(0,K.jsx)(N6.Label,{children:e}),n?.status===`error`?(0,K.jsx)(`span`,{role:`img`,"aria-label":`Mount error: ${n.error??`unavailable`}`,title:n.error,className:`flex shrink-0`,children:(0,K.jsx)(Xx,{className:`size-icon-xs text-destructive-foreground`})}):null,n&&s(t)?(0,K.jsx)(`span`,{role:`img`,"aria-label":`Read-only`,title:`Read-only`,className:`flex shrink-0`,children:(0,K.jsx)(CH,{className:`size-icon-xs text-muted-foreground`})}):null,u&&d?(0,K.jsx)(`span`,{className:`flex shrink-0 animate-in delay-200 fill-mode-backwards fade-in`,children:(0,K.jsx)(It,{size:`sm`,"aria-label":`Loading ${e}`,className:`size-3 text-muted-foreground`})}):null]}),(0,K.jsx)(N6.FolderContent,{children:u?(0,K.jsx)(KIi,{path:t,creating:f,onCreated:()=>p(!1),onRequestDelete:r}):null})]})}function KIi({path:e,creating:t,onCreated:n,onRequestDelete:r}){let{workspaceId:i,onCreateDirectory:a}=q9(),o=u_(),{data:s,isLoading:c,error:l}=iJ({workspaceId:i,path:e}),u=async t=>{try{await a?.(xIi(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)(HIi,{entries:s,parent:e,onRequestDelete:r}):(0,K.jsx)(mIi,{error:l,fallback:`Could not load folder.`,className:`my-1 mr-1`})]})}function qIi({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)(AIi,{})}),(0,K.jsx)(N6.Label,{children:e}),(0,K.jsxs)(UIi,{children:[t===void 0?null:(0,K.jsx)(T,{as:`span`,variant:`caption`,tone:`faint`,font:`mono`,children:BIi(t)}),s?(0,K.jsx)(WIi,{name:e,onClick:()=>r({path:n,type:`file`})}):null]})]})}function JIi({entry:e,onClose:t}){let{workspaceId:n,activeFilePath:r,setActiveFilePath:i,onDelete:a}=q9(),o=u_(),[s,c]=(0,G.useState)(!1),l=e?.path.split(`/`).pop(),u=async()=>{if(e&&a){c(!0);try{await a(e)}catch{return}finally{c(!1)}(r===e.path||r?.startsWith(`${e.path}/`))&&i(void 0),o.removeQueries({queryKey:[`workspace`,n,`fs`,`list`,e.path]}),await o.invalidateQueries({queryKey:[`workspace`,n,`fs`,`list`,CIi(e.path)]}),t()}},d=null;return e&&(d=e.type===`directory`?`This permanently deletes the folder "${l}" and everything inside it.`:`This permanently deletes "${l}".`),(0,K.jsx)(QM,{open:e!==null,onOpenChange:e=>{!e&&!s&&t()},children:(0,K.jsxs)(QM.Content,{children:[(0,K.jsxs)(QM.Header,{children:[(0,K.jsxs)(QM.Title,{children:[`Delete `,e?.type===`directory`?`folder`:`file`,`?`]}),(0,K.jsxs)(QM.Description,{children:[d,` This action cannot be undone.`]})]}),(0,K.jsxs)(QM.Footer,{children:[(0,K.jsx)(QM.Cancel,{disabled:s,children:`Cancel`}),(0,K.jsx)(X,{variant:`destructive`,disabled:s,onClick:()=>void u(),children:s?`Deleting…`:`Delete`})]})]})})}function YIi(){return(0,K.jsxs)(`div`,{"data-testid":`workspace-tree-skeleton`,"aria-busy":`true`,className:`flex flex-col gap-2 py-2 pl-[18px]`,children:[(0,K.jsx)(zS,{className:`h-4 w-3/4`}),(0,K.jsx)(zS,{className:`h-4 w-1/2`}),(0,K.jsx)(zS,{className:`h-4 w-2/3`})]})}function XIi({children:e,...t}){return(0,K.jsx)(kIi,{...t,children:(0,K.jsx)(ZIi,{children:e})})}function ZIi({children:e}){let{workspaceId:t}=q9(),{data:n,error:r}=iJ({workspaceId:t,path:`.`});return(n?n.length===0:LN(r))?(0,K.jsx)(Jx,{variant:`fill`,titleSlot:`This workspace is empty`,descriptionSlot:`Files written by your agents will show up here.`,actionSlot:(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:[(0,K.jsx)(wIi,{labeled:!0}),(0,K.jsx)(OIi,{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 QIi({children:e}){return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(SWr,{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 $Ii({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 eLi(){let{isSearching:e}=q9();return(0,K.jsx)(LS,{className:`min-h-0 flex-1 px-2 py-1`,children:e?(0,K.jsx)(LIi,{}):(0,K.jsx)(VIi,{})})}function tLi({children:e}){return(0,K.jsx)(f6,{id:`workspace-active-file`,className:`flex min-w-0 flex-col`,minSize:30,children:e})}function nLi({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 rLi({renderPreview:e}){let{activeFilePath:t}=q9();return t?(0,K.jsx)(LS,{className:`min-h-0 flex-1`,children:(0,K.jsx)(bIi,{renderPreview:e})}):(0,K.jsx)(Jx,{variant:`fill`,titleSlot:`Select a file`})}var J9={Root:XIi,Aside:QIi,AsideHeader:$Ii,Search:NIi,SearchToggle:MIi,CreateDirectory:wIi,Tree:eLi,ActiveFile:tLi,ActiveFileHeader:nLi,FilePath:vIi,ActiveFileContent:rLi};function iLi({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)(OIi,{}),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 aLi=()=>(0,K.jsx)(Jx,{titleSlot:`No Workspaces yet`,descriptionSlot:(0,K.jsxs)(K.Fragment,{children:[`Add a workspace to your Mastra configuration to `,(0,K.jsx)(`br`,{}),`manage files, skills, and enable semantic search.`]}),actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/en/docs/workspace/overview`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(tP,{}),children:`Workspaces documentation`}),variant:`fill`}),oLi=()=>(0,K.jsx)(Jx,{titleSlot:`Workspace Not Configured`,descriptionSlot:(0,K.jsxs)(K.Fragment,{children:[`No workspace is configured. Add a workspace to your `,(0,K.jsx)(`br`,{}),`Mastra configuration to manage files, skills, and enable semantic search.`]}),actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/en/docs/workspace/overview`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(tP,{}),children:`Workspaces documentation`}),variant:`fill`}),sLi=()=>(0,K.jsx)(Jx,{titleSlot:`Workspace Not Supported`,descriptionSlot:(0,K.jsxs)(K.Fragment,{children:[`The workspace feature requires a newer version of `,(0,K.jsx)(`code`,{className:`text-foreground`,children:`@mastra/core`}),`.`,(0,K.jsx)(`br`,{}),`Please upgrade your dependencies to enable workspace functionality.`]}),actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/en/docs/workspace/overview`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(tP,{}),children:`Workspaces documentation`}),variant:`fill`}),cLi=`.agents/skills`,lLi=e=>e.replace(/^\.?\/+|\/+$/g,``);function uLi({workspaceId:e,showInitWarning:t,skills:n}){let{data:r}=iJ({workspaceId:e,path:cLi,queryOptions:{enabled:!!n}}),i=n&&r?r.filter(e=>e.type===`directory`&&!n.some(t=>t.name===e.name||lLi(t.path)===`${cLi}/${e.name}`)):[];return!t&&i.length===0?null:(0,K.jsxs)(`div`,{className:`flex shrink-0 flex-col gap-2 border-b border-border p-3`,children:[t&&(0,K.jsx)(Sk,{variant:`warning`,children:(0,K.jsxs)(Sk.Message,{children:[`File search requires `,(0,K.jsx)(`code`,{children:`workspace.init()`}),` to index files from your configured`,` `,(0,K.jsx)(`code`,{children:`autoIndexPaths`}),`.`]})}),i.length>0&&(0,K.jsx)(Sk,{variant:`warning`,title:`Skills installed but not discovered`,children:(0,K.jsxs)(Sk.Message,{children:[i.map(e=>e.name).join(`, `),` `,i.length===1?`is`:`are`,` in`,` `,(0,K.jsx)(`code`,{children:cLi}),` but not discovered. Add this path to your workspace skills configuration to see `,i.length===1?`it`:`them`,`.`]})})]})}var Y9=[eP(`/workspaces`)],dLi=e=>IN(e)?`you don't have permission to modify this workspace`:e instanceof Error?e.message:`Unknown error`;function fLi(){let{workspaceId:e}=kv(),[t,n]=Rv(),r=Ov(),i=u_(),a=t.get(`file`),{data:o,error:s,isLoading:c}=iIn(),l=o?.workspaces??[],u=e??l[0]?.id,{data:d,isLoading:f,error:p}=rIn({workspaceId:u,queryOptions:{enabled:!!u}}),m=FN(s)||FN(p),h=IN(s)||IN(p),g=zFn(s)||zFn(p),_=u?l.find(e=>e.id===u):void 0,v=e=>{let r=new URLSearchParams(t);for(let[t,n]of Object.entries(e))n===null?r.delete(t):r.set(t,n);n(r)},y=e=>{r(`/workspaces/${e}`)},b=e=>{v({file:e??null})},x=a??void 0,S=oIn(),C=sIn(),w=d?.isWorkspaceConfigured??!1,T=d?.capabilities?.hasDynamicFilesystem??!1,E=(d?.capabilities?.hasFilesystem??!1)&&!T,D=d?.capabilities?.hasSkills??!1,{data:O,refetch:k}=mIn({workspaceId:u,queryOptions:{enabled:!!u&&E}}),A=$Fn(),j=eIn(),M=tIn(),N=e=>{let t=/^\.agents\/skills\/([^/]+)$/.exec(e);if(t)return re.find(t=>t.path?.replace(/^\.?\/+|\/+$/g,``)===e)?.name??t[1]},P=async()=>{if(u)try{let e=await j.mutateAsync({workspaceId:u}),t=e.updated.filter(e=>!e.success);t.length>0?iS.error(`Failed to update ${t.map(e=>e.skillName).join(`, `)}`):iS.success(`${e.updated.length} skill(s) updated`),i.invalidateQueries({queryKey:[`workspace`,u,`fs`]})}catch(e){iS.error(`Failed to update skills: ${e instanceof Error?e.message:`Unknown error`}`)}},F=async({path:e,type:t})=>{if(!u)return;let n=t===`directory`?N(e):void 0;if(n)try{if(!(await M.mutateAsync({workspaceId:u,skillName:n})).success)throw Error(`Failed to remove skill "${n}"`);iS.success(`Skill "${n}" removed`),k()}catch(e){throw iS.error(e instanceof Error?e.message:`Failed to remove skill`),e}else try{await S.mutateAsync({path:e,recursive:!0,force:!0,workspaceId:u})}catch(t){throw iS.error(`Failed to delete ${e}: ${dLi(t)}`),t}},I=_?.safety?.readOnly??!1,{canEdit:L,canDelete:R,canExecute:z,isLoading:B}=fS(),V=!B&&L(`workspaces`)&&!I,H=!B&&R(`workspaces`)&&!I,ee=!B&&z(`workspaces`),te=E&&D&&V,U=d?.mounts,W=U?.filter(e=>!e.readOnly).map(e=>({path:e.path,displayName:e.displayName,icon:e.icon,provider:e.provider,name:e.name})),ne=async e=>{if(u)try{let t=await A.mutateAsync({...e,workspaceId:u});if(!t.success)throw Error(`Unknown error`);i.invalidateQueries({queryKey:[`workspace`,u,`fs`]}),k(),iS.success(`Skill "${t.skillName}" installed successfully (${t.filesWritten} files)`)}catch(e){throw iS.error(`Failed to install skill: ${e instanceof Error?e.message:`Unknown error`}`),e}},re=O?.skills??[],ie=O?.isSkillsConfigured??!1,ae=ee&&E&&!!(d?.capabilities?.canBM25||d?.capabilities?.canVector),oe=ee&&D&&ie&&re.length>0,se=I?[`.`]:(U??[]).filter(e=>e.readOnly).map(e=>e.path.replace(/^\/+|\/+$/g,``)||`.`);if(c)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:Y9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(It,{fill:!0})]});if(m)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:Y9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(TH,{variant:`fill`})]});if(h)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:Y9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(wH,{variant:`fill`,resource:`workspaces`})]});if(g)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:Y9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(sLi,{})]});let ce=s||p;if(ce)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:Y9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load workspace`,descriptionSlot:ce.message})]});if(!c&&l.length===0)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:Y9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(aLi,{})]});if(!f&&!c&&!w)return(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:Y9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsx)(oLi,{})]});let le=l.map(e=>({value:e.id,label:e.name,description:e.source===`agent`?`Agent: ${e.agentName}`:`Global workspace`,end:(0,K.jsxs)(`span`,{className:`flex shrink-0 gap-1`,children:[e.safety?.readOnly&&(0,K.jsx)(eC,{size:`xs`,variant:`warning`,children:`Read-only`}),e.capabilities.hasFilesystem&&(0,K.jsx)(eC,{size:`xs`,children:`FS`}),e.capabilities.hasSandbox&&(0,K.jsx)(eC,{size:`xs`,children:`Sandbox`}),e.capabilities.hasSkills&&(0,K.jsx)(eC,{size:`xs`,children:`Skills`})]})}));return(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:Y9}),headerActions:(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(_N,{"aria-label":`Workspace`,variant:`ghost`,className:`w-auto`,options:le,value:_?.id,onValueChange:y,placeholder:`Select workspace`,searchPlaceholder:`Search workspaces`,emptyText:`No workspaces found.`}),I&&(0,K.jsx)(eC,{size:`xs`,variant:`warning`,children:`Read-only`})]}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Workspaces`}),(0,K.jsxs)(`div`,{className:`flex min-h-0 flex-col`,children:[E&&u&&(0,K.jsx)(uLi,{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)(iLi,{workspaceId:u,activeFilePath:x,onActiveFileChange:b,readOnlyPaths:se,skillCount:D&&O?re.length:void 0,searchFiles:ae,searchSkills:oe,onCreateDirectory:V?async e=>{try{await C.mutateAsync({path:e,recursive:!0,workspaceId:u})}catch(t){throw iS.error(`Failed to create ${e}: ${dLi(t)}`),t}}:void 0,asideActions:te&&re.some(e=>e.path?.includes(`.agents/skills/`))?(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,tooltip:`Update skills`,disabled:j.isPending,onClick:()=>void P(),children:(0,K.jsx)(xS,{className:j.isPending?`animate-spin`:void 0})}):void 0,addSkill:te?{onInstall:ne,installedSkillIds:re.filter(e=>e.skillsShSource).map(e=>`${e.skillsShSource.owner}/${e.skillsShSource.repo}/${e.name}`),installedSkillNames:re.filter(e=>!e.skillsShSource).map(e=>e.name),writableMounts:W,installedSkillPaths:Object.fromEntries(re.filter(e=>e.path).map(e=>[e.name,e.path]))}:void 0,onDelete:H?F:void 0},u)}),T&&!f&&(0,K.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,K.jsx)(Jx,{variant:`fill`,titleSlot:`Filesystem resolved per request`,descriptionSlot:`This workspace creates its filesystem when an agent runs, so its files can't be browsed here.`})}),!E&&!T&&!f&&(0,K.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,K.jsx)(Jx,{variant:`fill`,titleSlot:`No filesystem or skills configured`,descriptionSlot:`Add a filesystem or skills to this workspace to browse its files here.`})})]})]})}function pLi({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 mLi({children:e,className:t,edgeToEdge:n}){let r=n!==void 0;return(0,K.jsx)(`div`,{"data-slot":`main-card`,className:c(`relative min-h-0 flex-1 overflow-hidden`,r&&`transition-[border-radius,padding,box-shadow] duration-(--resize-dur) ease-(--resize-ease) motion-reduce:transition-none!`,r&&`in-data-[sidebar-gesture=active]:transition-none!`,!n&&`lg:rounded-studio-frame lg:p-px lg:shadow-raised`,Kze,t),children:e})}function hLi(){return(0,K.jsxs)(`div`,{className:`h-screen bg-sidebar`,children:[(0,K.jsx)(aS,{position:`bottom-right`}),(0,K.jsx)(M,{defaultTheme:`system`,children:(0,K.jsx)(Sx,{delayDuration:0,children:(0,K.jsx)(pLi,{children:(0,K.jsx)(mLi,{className:`flex items-center justify-center overflow-y-auto`,children:(0,K.jsx)(Iv,{})})})})})]})}function gLi(){let{data:e,isLoading:t}=A_(),{isLoading:n,canAccessAgentBuilder:r}=pS();return t||n||!e||e.enabled&&!k_(e)?{isVisible:!1}:{isVisible:r}}function _Li(){let{isImpersonating:e,impersonatedRole:t,stopImpersonation:n}=dS();return!e||!t?null:(0,K.jsxs)(`div`,{className:`mx-3 mb-2 flex items-center gap-2 rounded-md border border-info-edge bg-info-subtle px-3 py-1.5`,children:[(0,K.jsx)(cS,{className:`size-icon-sm shrink-0 text-info-subtle-foreground`}),(0,K.jsxs)(T,{variant:`meta`,className:`truncate text-info-subtle-foreground`,children:[`Previewing `,(0,K.jsx)(`span`,{className:`font-medium capitalize`,children:t.name}),` experience`]}),(0,K.jsx)(`button`,{type:`button`,onClick:n,className:`ml-auto shrink-0 rounded p-0.5 text-info-subtle-foreground hover:bg-info-edge`,title:`Exit role preview`,children:(0,K.jsx)(xw,{className:`size-icon-xs`})})]})}function vLi({children:e,contentClassName:t,commandClassName:n,showOverlay:r=!0,overlayClassName:i,...a}){return(0,K.jsx)(sNn,{size:`xl`,showOverlay:r,overlayClassName:c(`bg-sidebar/40 backdrop-blur-none`,i),contentClassName:c(`command-palette-popup overflow-visible bg-transparent shadow-none`,t),commandClassName:c(`command-palette-shell gap-2 overflow-visible rounded-none bg-transparent text-muted-foreground shadow-none backdrop-blur-none`,`[&_[data-slot=command-input-wrapper]_svg]:text-muted-foreground`,`**:[[cmdk-input]]:h-full **:[[cmdk-input]]:text-body`,`**:[[cmdk-group-heading]]:px-2 **:[[cmdk-group-heading]]:pt-2 **:[[cmdk-group-heading]]:pb-1 **:[[cmdk-group]]:p-0`,`**:[[cmdk-item]]:px-2 **:[[cmdk-item]]:py-1.5`,n),...a,children:e})}function yLi({wrapperClassName:e,...t}){return(0,K.jsx)(wq,{wrapperClassName:c(`command-palette-surface command-palette-surface-input`,Nx,`h-11 shrink-0 rounded-xl border-0 px-3 pr-11`,e),...t})}function bLi({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 xLi({children:e,className:t,...n}){return(0,K.jsx)(`aside`,{className:c(`command-palette-surface command-palette-surface-rail flex max-h-[min(14rem,32dvh)] min-h-0 flex-col overflow-hidden rounded-xl p-2 md:h-full md:max-h-none`,Vv,t),...n,children:(0,K.jsx)(LS,{className:`-m-1 min-h-0 flex-1 p-1`,children:(0,K.jsx)(IS,{className:`pr-1`,children:(0,K.jsx)(`div`,{className:`flex flex-col gap-1`,children:e})})})})}function SLi({icon:e,label:t,count:n,active:r,onSelect:i}){return(0,K.jsxs)(`button`,{type:`button`,className:c(SS,`flex h-9 w-full cursor-pointer items-center gap-2 rounded-lg border border-transparent px-2.5 text-left text-body-sm hover:border-border hover:bg-fill-subtle data-[active=true]:border-border data-[active=true]:bg-fill-hover data-[active=true]:text-foreground`,`transition-[color,transform] duration-fast ease-out-custom active:scale-[0.99] motion-reduce:transition-none`),"data-active":r,"aria-pressed":r,onClick:i,children:[(0,K.jsx)(`span`,{className:`flex size-icon-md shrink-0 items-center justify-center [&>svg]:size-icon-md`,children:e}),(0,K.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:t}),(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`rounded-md border border-border bg-muted/70 px-1.5 py-0.5 leading-none`,children:n})]})}function CLi({children:e,footer:t,...n}){return(0,K.jsxs)(`div`,{role:`region`,className:c(`command-palette-surface command-palette-surface-results command-palette-results-panel relative flex min-h-0 min-w-0 flex-col overflow-hidden rounded-xl`,Vv),...n,children:[(0,K.jsx)(Tq,{scrollArea:!0,scrollAreaClassName:`min-h-0 flex-1 rounded-none`,scrollAreaViewportClassName:`command-palette-scroll-viewport`,className:`command-palette-list max-h-none rounded-none border-none bg-transparent shadow-none`,children:e}),t]})}function X9({icon:e,title:t,subtitle:n,path:r,badge:i,shortcut:a,className:o,...s}){return(0,K.jsxs)(Oq,{className:c(`group h-auto items-start gap-3 rounded-lg border border-transparent px-3 py-2.5 data-[selected=true]:border-border`,o),...s,children:[(0,K.jsx)(`span`,{className:c(`mt-0.5 flex size-4 max-w-4 min-w-4 shrink-0 basis-4 items-center justify-center text-muted-foreground group-data-[selected=true]:text-foreground [&>svg]:!size-4 [&>svg]:shrink-0`),children:e}),(0,K.jsxs)(`span`,{className:`flex min-w-0 flex-1 flex-col gap-1`,children:[(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(T,{as:`span`,variant:`label`,tone:`ink`,className:`truncate`,children:t}),i&&(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`shrink-0 rounded-md border border-border bg-muted/60 px-1.5 py-0.5 leading-none uppercase`,children:i})]}),(n||r)&&(0,K.jsxs)(T,{as:`span`,variant:`meta`,tone:`muted`,className:`flex min-w-0 items-center gap-2`,children:[n&&(0,K.jsx)(`span`,{className:`min-w-0 truncate`,children:n}),r&&(0,K.jsx)(T,{as:`span`,variant:`meta`,tone:`muted`,font:`mono`,className:`max-w-52 truncate rounded-md border border-border bg-muted/70 px-1.5 py-0.5 leading-none`,children:r})]})]}),a&&(0,K.jsx)(lNn,{children:a})]})}function wLi({label:e}){return(0,K.jsxs)(`div`,{className:`command-palette-footer pointer-events-none absolute inset-x-0 bottom-0 z-20 flex items-end justify-between gap-3 px-3 pt-3 pb-2 text-meta text-muted-foreground`,children:[(0,K.jsx)(`span`,{className:`truncate`,children:e}),(0,K.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1.5`,children:[(0,K.jsx)(Vx,{size:`sm`,children:`↑`}),(0,K.jsx)(Vx,{size:`sm`,children:`↓`}),(0,K.jsx)(Vx,{size:`sm`,children:`↵`}),(0,K.jsx)(Vx,{size:`sm`,children:`Esc`})]})]})}var TLi=!1,ELi=new Set,DLi=()=>{ELi.forEach(e=>e())},OLi=e=>(ELi.add(e),()=>ELi.delete(e)),kLi=()=>TLi,ALi=e=>{let t=typeof e==`function`?e(TLi):e;t!==TLi&&(TLi=t,DLi())},jLi=({enableShortcut:e=!0}={})=>{let t=(0,G.useSyncExternalStore)(OLi,kLi,kLi),n=(0,G.useCallback)(e=>{ALi(e)},[]),r=(0,G.useCallback)(()=>{ALi(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 MLi(e,t){return[e.name,e.url,t,`path route navigate`].filter(Boolean).join(` `)}function NLi(e){return!e||e===`Studio`?`Path`:e}function PLi(e){return`/traces?entity=${encodeURIComponent(e)}`}var FLi=({scopeOptions:e,activeScope:t,onScopeChange:n})=>(0,K.jsx)(xLi,{"aria-label":`Search categories`,children:e.map(e=>(0,K.jsx)(SLi,{icon:e.icon,label:e.label,count:e.count,active:t===e.id,onSelect:()=>n(e.id)},e.id))}),ILi=({sidebar:e,activeScope:t,closeCommand:n})=>!e||t!==`all`&&t!==`settings`?null:(0,K.jsx)(Dq,{heading:`Commands`,children:(0,K.jsx)(X9,{value:`toggle sidebar collapse expand layout panel`,onSelect:()=>{e.toggleSidebar(),n()},icon:(0,K.jsx)(mRr,{}),title:`Toggle sidebar`,subtitle:`Studio layout`})}),LLi=({sections:e,handleSelect:t})=>(0,K.jsx)(K.Fragment,{children:e.map(e=>(0,K.jsx)(Dq,{heading:e.title,children:e.items.map(n=>{let r=n.Icon;return(0,K.jsx)(X9,{value:MLi(n,e.title),onSelect:()=>t(n.url),icon:(0,K.jsx)(r,{}),title:n.name,subtitle:`Studio path`,path:n.url,badge:NLi(e.title)},n.url)})},e.key))}),RLi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(Dq,{heading:`Agents`,children:t.map(([e,t])=>(0,K.jsx)(X9,{value:`${t.name} ${e} chat agent conversation thread ${n.agentLink(e)}`,onSelect:()=>r(n.agentLink(e)),icon:(0,K.jsx)(HN,{}),title:t.name,subtitle:`Agent chat`,path:n.agentLink(e),badge:`Agent`},e))}),zLi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(Dq,{heading:`Workflows`,children:t.map(([e,t])=>(0,K.jsx)(X9,{value:`${t.name} ${e} graph workflow view ${n.workflowLink(e)}`,onSelect:()=>r(n.workflowLink(e)),icon:(0,K.jsx)(ZS,{}),title:t.name,subtitle:`Workflow graph`,path:n.workflowLink(e),badge:`Workflow`},e))}),BLi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(Dq,{heading:`Tools`,children:t.map(([e,t])=>(0,K.jsx)(X9,{value:`tool ${t.id} ${e} ${n.toolLink(e)}`,onSelect:()=>r(n.toolLink(e)),icon:(0,K.jsx)(XN,{}),title:t.id,subtitle:`Tool definition`,path:n.toolLink(e),badge:`Tool`},e))}),VLi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(Dq,{heading:`Processors`,children:t.map(e=>{let t=e.name||e.id,i=e.isWorkflow?n.workflowLink(e.id)+`/graph`:n.processorLink(e.id);return(0,K.jsx)(X9,{value:`processor ${t} ${e.id} ${i}`,onSelect:()=>r(i),icon:(0,K.jsx)(mP,{}),title:t,subtitle:e.isWorkflow?`Workflow processor`:`Processor`,path:i,badge:`Processor`},e.id)})}),HLi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(Dq,{heading:`MCP Servers`,children:t.map(e=>(0,K.jsx)(X9,{value:`mcp server ${e.name} ${e.id} ${n.mcpServerLink(e.id)}`,onSelect:()=>r(n.mcpServerLink(e.id)),icon:(0,K.jsx)(KN,{}),title:e.name,subtitle:`MCP server`,path:n.mcpServerLink(e.id),badge:`MCP`},e.id))}),ULi=({visible:e,agentEntries:t,workflowEntries:n,handleSelect:r})=>e?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(Dq,{heading:`Observability`,children:[(0,K.jsx)(X9,{value:`observability traces telemetry signals /traces`,onSelect:()=>r(`/traces`),icon:(0,K.jsx)(cS,{}),title:`Traces`,subtitle:`Runtime traces`,path:`/traces`,badge:`Signal`}),(0,K.jsx)(X9,{value:`metrics usage latency performance tokens /metrics`,onSelect:()=>r(`/metrics`),icon:(0,K.jsx)(G4,{}),title:`Metrics`,subtitle:`Runtime metrics`,path:`/metrics`,badge:`Signal`}),(0,K.jsx)(X9,{value:`logs events runtime /logs`,onSelect:()=>r(`/logs`),icon:(0,K.jsx)(cS,{}),title:`Logs`,subtitle:`Runtime logs`,path:`/logs`,badge:`Signal`})]}),t.length>0&&(0,K.jsx)(Dq,{heading:`Agent Traces`,children:t.map(([e,t])=>{let n=PLi(e);return(0,K.jsx)(X9,{value:`${t.name} ${e} traces agent observability telemetry`,onSelect:()=>r(n),icon:(0,K.jsx)(cS,{}),title:t.name,subtitle:`Agent traces`,path:n,badge:`Trace`},e)})}),n.length>0&&(0,K.jsx)(Dq,{heading:`Workflow Traces`,children:n.map(([e,t])=>{let n=PLi(t.name);return(0,K.jsx)(X9,{value:`${t.name} ${e} traces workflow observability telemetry`,onSelect:()=>r(n),icon:(0,K.jsx)(cS,{}),title:t.name,subtitle:`Workflow traces`,path:n,badge:`Trace`},e)})})]}):null,WLi=({visible:e,entries:t,paths:n,handleSelect:r})=>!e||t.length===0?null:(0,K.jsx)(Dq,{heading:`Scorers`,children:t.map(([e,t])=>{let i=t.scorer?.config?.name||t.scorer?.config?.id||e;return(0,K.jsx)(X9,{value:`scorer score evaluation ${i} ${e} ${n.scorerLink(e)}`,onSelect:()=>r(n.scorerLink(e)),icon:(0,K.jsx)(G4,{}),title:i,subtitle:`Evaluation scorer`,path:n.scorerLink(e),badge:`Scorer`},e)})}),GLi=()=>{let{open:e,setOpen:t}=jLi(),{navigate:n,paths:r}=sn(),{isMastraPlatform:i}=Z8(),a=n3(),[o,s]=G.useState(`all`),{data:c={}}=wN(),{data:l={}}=eN(),{data:u={}}=Fq(),{data:d={}}=PN(),{data:f=[]}=NN(),{data:p={}}=VN(),{isCmsAvailable:m,isLoading:h}=w3(),{hasPermission:g,hasAnyPermission:_,isLoading:v}=fS(),y=e=>{t(e),e||s(`all`)},b=()=>y(!1),x=e=>{n(e),b()},S=G.useCallback(e=>{if(e.hidden||e.url===`/prompts`&&!m&&!h||i&&!e.isOnMastraPlatform)return!1;let t=gS(e.url);return v&&t&&t!==`public`?!1:_S(t,g,_)},[_,g,m,h,i,v]),C=Object.entries(c),w=Object.entries(l),T=Object.entries(u),E=Object.values(d).filter(e=>e.phases&&e.phases.length>0),D=Object.entries(p),O=G.useMemo(()=>{let e=[];for(let t of qjt){let n=t.items.filter(S);n.length>0&&e.push({key:t.key,title:t.title,items:n})}let t=[...Jjt.filter(S),...i?[]:[{name:`Templates`,url:`/templates`,Icon:OZ,isOnMastraPlatform:!1}]];return t.length===0?e:[...e,{key:`studio`,title:`Studio`,items:t}]},[S,i]),k=O.reduce((e,t)=>e+t.items.length,0),A=T.length+E.length+f.length,j=D.length,M=C.length+w.length+3,N=O.find(e=>e.key===`studio`)?.items.length??0,P=k+C.length+w.length+A+j+M,F=[{id:`all`,label:`All`,icon:(0,K.jsx)(oN,{}),count:P},{id:`paths`,label:`Paths`,icon:(0,K.jsx)(Emn,{}),count:k},{id:`agents`,label:`Agents`,icon:(0,K.jsx)(HN,{}),count:C.length},{id:`workflows`,label:`Workflows`,icon:(0,K.jsx)(ZS,{}),count:w.length},{id:`tooling`,label:`Tooling`,icon:(0,K.jsx)(koi,{}),count:A},{id:`evaluation`,label:`Evaluation`,icon:(0,K.jsx)(G4,{}),count:j},{id:`observability`,label:`Intelligence`,icon:(0,K.jsx)(cS,{}),count:M},{id:`settings`,label:`Studio`,icon:(0,K.jsx)(zq,{}),count:N}],I=o===`all`||o===`paths`,L=o===`all`||o===`agents`,R=o===`all`||o===`workflows`,z=o===`all`||o===`tooling`,B=o===`all`||o===`evaluation`,V=o===`all`||o===`observability`,H=o===`settings`,ee=G.useMemo(()=>{let e=[];for(let t of O)H?t.key===`studio`&&e.push(t):(o===`evaluation`&&t.key===`evaluation`||o===`observability`&&t.key===`observability`||I&&(o===`all`||t.key!==`studio`))&&e.push(t);return e},[o,O,I,H]);return(0,K.jsxs)(vLi,{open:e,onOpenChange:y,title:`Mastra Studio Search`,description:`Search Studio routes and runtime entities`,children:[(0,K.jsx)(yLi,{placeholder:`Search Studio, agents, workflows, tools, paths`}),(0,K.jsxs)(bLi,{children:[(0,K.jsx)(FLi,{scopeOptions:F,activeScope:o,onScopeChange:s}),(0,K.jsxs)(CLi,{"aria-label":`Search results`,footer:(0,K.jsx)(wLi,{label:`Studio search`}),children:[(0,K.jsx)(Eq,{children:`No matching results.`}),(0,K.jsx)(ILi,{sidebar:a,activeScope:o,closeCommand:b}),(0,K.jsx)(LLi,{sections:ee,handleSelect:x}),(0,K.jsx)(RLi,{visible:L,entries:C,paths:r,handleSelect:x}),(0,K.jsx)(zLi,{visible:R,entries:w,paths:r,handleSelect:x}),(0,K.jsx)(BLi,{visible:z,entries:T,paths:r,handleSelect:x}),(0,K.jsx)(VLi,{visible:z,entries:E,paths:r,handleSelect:x}),(0,K.jsx)(HLi,{visible:z,entries:f,paths:r,handleSelect:x}),(0,K.jsx)(ULi,{visible:V,agentEntries:C,workflowEntries:w,handleSelect:x}),(0,K.jsx)(WLi,{visible:B,entries:D,paths:r,handleSelect:x})]})]})]})};function KLi(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 qLi(e){let{Icon:t}=e;return{name:e.name,url:e.url,icon:(0,K.jsx)(t,{})}}function JLi(){let{state:e,isMobile:t,setOpenMobile:n}=r3(),{setOpen:r}=jLi({enableShortcut:!1}),i=V2r(`K`),a=Dv().pathname,{isMastraPlatform:o}=Z8(),{data:s}=A_(),{isCmsAvailable:c,isLoading:l}=w3(),{hasPermission:u,hasAnyPermission:d,isLoading:f}=fS(),{data:p}=Rdr(),m=p!==void 0&&p.status!==`not-mounted`,h=s&&k_(s),g=new Set([`/prompts`]),{isVisible:_}=gLi(),v=a===`/agent-builder`||a.startsWith(`/agent-builder/`),y=()=>{t&&n(!1),r(!0)},b=e=>{if(e.hidden||e.url===`/connections`&&!m||g.has(e.url)&&!c&&!l||o&&!e.isOnMastraPlatform)return!1;if(f){let t=gS(e.url);if(t&&t!==`public`)return!1}return!!_S(gS(e.url),u,d)},{data:x}=NN(),{data:S}=iIn(),C=Jjt.filter(b),w=qjt.map(e=>{let t=e.items.filter(b),n=e=>({...qLi(e),isActive:KLi(e,a,t)});return{key:e.key,title:e.title,href:e.href,isHeaderActive:!(!e.href||a!==e.href||t.some(e=>KLi(e,a,t))),links:t.filter(e=>!e.foldable).map(n),moreLinks:t.filter(e=>e.foldable).map(e=>({...n(e),defaultVisible:e.url===`/mcps`&&!!x?.length||e.url===`/workspaces`&&!!S?.workspaces.length}))}});return(0,K.jsxs)(f3,{"aria-label":`Sidebar`,children:[(0,K.jsxs)(f3.Header,{collapsedLogo:(0,K.jsx)(UZ,{className:`size-6`}),actions:h&&(0,K.jsx)(z9n,{}),children:[(0,K.jsx)(f3.Brand,{logo:(0,K.jsx)(UZ,{className:`size-6`}),title:`Mastra Studio`}),!t&&(0,K.jsx)(f3.SearchTrigger,{"aria-label":`Search and navigate`,shortcut:i,onClick:y}),(0,K.jsx)(f3.Trigger,{})]}),_&&(0,K.jsx)(f3.NavList,{className:`mb-1`,children:(0,K.jsx)(f3.NavLink,{state:e,link:{name:`Agent Builder`,url:`/agent-builder`,icon:(0,K.jsx)(YS,{})},isActive:v})}),(0,K.jsx)(_Li,{}),(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:qLi(t),isActive:KLi(t,a)},t.name)),(0,K.jsx)(nVr,{state:e})]})})]})}var YLi=()=>{let{baseUrl:e,headers:t,apiPrefix:n,setConfig:r}=yS(),[i,a]=(0,G.useState)(()=>Object.entries(t).map(([e,t])=>({name:e,value:t})));return(0,K.jsx)(Sx,{delayDuration:0,children:(0,K.jsxs)(ZV,{onSubmit:t=>{t.preventDefault();let a=new FormData(t.currentTarget),o={};for(let e=0;e<i.length;e++){let t=a.get(`headers.${e}.name`),n=a.get(`headers.${e}.value`);typeof t==`string`&&typeof n==`string`&&(o[t]=n)}r({headers:o,baseUrl:e,apiPrefix:n}),iS.success(`Headers saved`)},className:`w-full max-w-md gap-6 text-left`,children:[(0,K.jsx)(dRr,{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 XLi({children:e,loginUrl:t=`/login`,signupUrl:n=`/signup`}){let{data:r,isLoading:i}=A_();if(i||!r?.enabled||k_(r))return(0,K.jsx)(K.Fragment,{children:e});let a=typeof window<`u`?window.location.href:void 0;return r.login?(0,K.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,K.jsxs)(`div`,{className:`flex flex-col items-center space-y-6 text-center`,children:[(0,K.jsx)(UZ,{className:`h-16 w-16 opacity-50`}),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(T,{as:`h2`,variant:`heading`,tone:`ink`,children:`Sign in to continue`}),(0,K.jsx)(`p`,{className:`max-w-sm text-muted-foreground`,children:`You need to sign in to access this page.`})]}),r.login.description&&(0,K.jsxs)(`div`,{className:`flex items-start gap-2.5 rounded-md border border-border bg-background p-3 text-left`,children:[(0,K.jsx)(CH,{className:`mt-0.5 size-icon-md shrink-0 text-muted-foreground`}),(0,K.jsx)(T,{tone:`muted`,className:`max-w-sm`,children:r.login.description})]}),(0,K.jsx)(F9n,{config:r.login,redirectUri:a,loginUrl:t}),(r.login.type===`credentials`||r.login.type===`both`)&&r.login.signUpEnabled!==!1&&(0,K.jsxs)(`div`,{children:[(0,K.jsx)(T,{as:`span`,variant:`body`,tone:`muted`,children:`Don't have an account? `}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>{let e=new URL(WZ(n),window.location.origin);a&&e.searchParams.set(`redirect`,a),window.location.href=e.toString()},className:`text-foreground hover:underline`,children:(0,K.jsx)(T,{as:`span`,variant:`body`,className:`block`,children:`Sign up`})})]})]})}):(0,K.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,K.jsxs)(`div`,{className:`flex flex-col items-center space-y-6 text-center`,children:[(0,K.jsx)(UZ,{className:`h-16 w-16 opacity-50`}),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(T,{as:`h2`,variant:`heading`,tone:`ink`,children:`Authentication Required`}),(0,K.jsx)(`p`,{className:`max-w-sm text-muted-foreground`,children:`Add the authorization header that Studio needs to reach your Mastra server.`})]}),(0,K.jsx)(YLi,{})]})})}var ZLi=`experimental-ui:`,QLi=`current`,$Li=G.createContext(null);function eRi(e,t){let n=window.localStorage.getItem(ZLi+e);return n&&t.has(n)?n:QLi}function tRi({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]=eRi(r.key,e)}i(t)},[e,n]);let a=G.useCallback(e=>r[e]??QLi,[r]),o=G.useCallback((e,t)=>{window.localStorage.setItem(ZLi+e,t),i(n=>({...n,[e]:t}))},[]),s=G.useMemo(()=>({experiments:e,getVariant:a,setVariant:o}),[e,a,o]);return(0,K.jsx)($Li.Provider,{value:s,children:t})}var nRi=[{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`}]}],rRi=()=>({experimentalUIEnabled:typeof window<`u`&&window.MASTRA_EXPERIMENTAL_UI===`true`}),iRi=()=>{let{toggleSidebar:e}=r3();return Ux({"[":e},{repeat:!1}),null};function aRi(){let{setOpenMobile:e}=r3(),{setOpen:t}=jLi({enableShortcut:!1});return(0,K.jsxs)(`header`,{className:`sticky top-0 z-20 flex h-12 shrink-0 items-center justify-between gap-3 border-b border-border bg-sidebar px-3 lg:hidden`,children:[(0,K.jsxs)(`div`,{className:`flex min-w-0 items-center gap-3`,children:[(0,K.jsx)(f3.MobileTrigger,{}),(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(UZ,{className:`size-[1.5rem] shrink-0`}),(0,K.jsx)(T,{variant:`body-sm`,font:`display`,as:`span`,className:`whitespace-nowrap`,children:`Mastra Studio`})]})]}),(0,K.jsx)(X,{type:`button`,variant:`ghost`,size:`icon-md`,tooltip:`Search`,"aria-label":`Search and navigate`,onClick:()=>{e(!1),t(!0)},className:`shrink-0`,children:(0,K.jsx)(oN,{})})]})}var oRi={"studio-frame":100,"route-side-panel":0},sRi={overflow:`visible`};function cRi({children:e,className:t}){let n=Zw(),{hasPanel:r,panelHandle:i,onPanelResize:a}=X8(),{defaultLayout:o,onLayoutChange:s}=dWr({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:sRi,orientation:`horizontal`,defaultLayout:o??oRi,onLayoutChange:s,children:[(0,K.jsx)(f6,{id:`studio-frame`,className:c(`min-w-0`,t),style:sRi,children:e}),r&&!n&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(m6,{className:`w-2`}),(0,K.jsx)(SWr,{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)(U1r,{className:`h-full min-h-0`})})]})]})})}function lRi({children:e}){let{data:t,isFetched:n}=A_(),{pathname:r}=Dv(),i=!(n&&t?.enabled&&!k_(t));return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(GLi,{}),(0,K.jsx)(pLi,{sidebar:i?(0,K.jsx)(JLi,{}):void 0,mobileHeader:i?(0,K.jsx)(aRi,{}):void 0,children:(0,K.jsx)(cRi,{className:`flex min-h-0 flex-1 flex-col`,children:(0,K.jsx)(mLi,{children:(0,K.jsx)(XLi,{children:(0,K.jsx)(eJe,{resetKeys:[r],children:e})})})})})]})}var uRi=({children:e})=>{let{experimentalUIEnabled:t}=rRi(),{Link:n}=sn();return(0,K.jsxs)(`div`,{className:`h-screen bg-sidebar`,children:[(0,K.jsx)(aS,{position:`bottom-right`}),(0,K.jsx)(M,{defaultTheme:`system`,children:(0,K.jsx)(Sx,{delayDuration:0,children:(0,K.jsx)(tRi,{experiments:t?nRi:[],children:(0,K.jsxs)(f3.Provider,{LinkComponent:n,children:[(0,K.jsx)(iRi,{}),(0,K.jsx)(H1r,{children:(0,K.jsx)(lRi,{children:e})})]})})})})]})},dRi=({children:e})=>(0,K.jsxs)(`div`,{className:`h-screen bg-sidebar`,children:[(0,K.jsx)(aS,{position:`bottom-right`}),(0,K.jsx)(M,{defaultTheme:`system`,children:(0,K.jsx)(Sx,{delayDuration:0,children:(0,K.jsx)(`div`,{className:`h-full overflow-y-auto`,children:(0,K.jsx)(XLi,{children:e})})})})]}),fRi={name:`Agents`,url:`/agent-builder/agents`,icon:(0,K.jsx)(HN,{})},pRi={name:`Skills`,url:`/agent-builder/skills`,icon:(0,K.jsx)(ddr,{className:`size-icon-lg`})},mRi={name:`Favorites`,url:`/agent-builder/favorite`,icon:(0,K.jsx)(AK,{className:`size-icon-lg`})},hRi={name:`Library`,url:`/agent-builder/library`,icon:(0,K.jsx)(WN,{className:`size-icon-lg`})},gRi={name:`Infra`,url:`/agent-builder/infrastructure`,icon:(0,K.jsx)(iYr,{className:`size-icon-lg`})};function _Ri(){let{Link:e}=sn(),{pathname:t}=Dv(),n=jK(),{canManageSkills:r,canUseFavorites:i}=pS(),{hasPermission:a}=fS(),o=a(`infrastructure:read`),s=(0,G.useMemo)(()=>{let e=[fRi];return n.skills&&r&&e.push(pRi),i&&e.push(mRi),e.push(hRi),o&&e.push(gRi),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 vRi={name:`My agents`,url:`/agent-builder/agents`,icon:(0,K.jsx)(HN,{})},yRi={name:`Favorites`,url:`/agent-builder/favorite`,icon:(0,K.jsx)(AK,{})},bRi={name:`Library`,url:`/agent-builder/library`,icon:(0,K.jsx)(WN,{})},xRi={name:`Skills`,url:`/agent-builder/skills`,icon:(0,K.jsx)(ddr,{className:`size-icon-md`})},SRi={name:`Infrastructure`,url:`/agent-builder/infrastructure`,icon:(0,K.jsx)(iYr,{className:`size-icon-md`})};function CRi({forceExpanded:e=!1}={}){let{Link:t}=sn(),{state:n,isMobile:r}=r3(),{pathname:i}=Dv(),a=jK(),{canManageSkills:o,canUseFavorites:s}=pS(),{hasPermission:c}=fS(),l=c(`infrastructure:read`),u=e?`default`:n,{data:d}=A_(),f=d&&k_(d),p=[vRi];a.skills&&o&&p.push(xRi),s&&p.push(yRi),p.push(bRi);let m=(0,K.jsx)(t,{href:`/agents`,"aria-label":`Back to Mastra Studio`,children:(0,K.jsx)(UZ,{className:`size-6`})});return(0,K.jsxs)(f3,{className:`h-full`,mobileMode:`drawer`,children:[!e&&(0,K.jsxs)(f3.Header,{collapsedLogo:m,actions:f&&(0,K.jsx)(z9n,{}),children:[(0,K.jsx)(t,{href:`/agents`,"aria-label":`Back to Mastra Studio`,className:`min-w-0 flex-1`,children:(0,K.jsx)(f3.Brand,{logo:(0,K.jsx)(UZ,{className:`size-6`}),title:`Mastra Studio`})}),!r&&(0,K.jsx)(f3.Trigger,{})]}),(0,K.jsx)(_Li,{}),(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:SRi,isActive:i.startsWith(SRi.url)})})})]})})]})}var Z9=()=>(0,K.jsx)(`div`,{className:`h-screen bg-sidebar`,children:(0,K.jsxs)(wzr,{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)(CRi,{})}),(0,K.jsx)(`div`,{className:`flex h-full min-h-0 flex-col`,children:(0,K.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto bg-transparent pb-[calc(3.5rem+env(safe-area-inset-bottom))] md:pb-0`,children:(0,K.jsx)(Iv,{})})})]}),(0,K.jsx)(_Ri,{})]})}),wRi=()=>(0,K.jsx)(`div`,{className:`grid h-screen grid-cols-[minmax(0,1fr)] grid-rows-1 bg-sidebar`,children:(0,K.jsx)(Iv,{})});function TRi({agentId:e,children:t,disabled:n=!1}){let r=Zw(),i=(0,K.jsx)(RZ,{children:(0,K.jsx)(q1r,{agentId:e})},e);return n?t:(0,K.jsxs)(Hw,{side:`right`,children:[t,r?(0,K.jsxs)(Ww,{children:[(0,K.jsx)(Gw,{}),(0,K.jsx)(Kw,{children:(0,K.jsxs)(qw,{className:`w-[calc(100vw-2.5rem)] max-w-md`,children:[(0,K.jsx)(Yw,{className:`sr-only`,children:`Config`}),(0,K.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:i})]})})]}):(0,K.jsx)(Y8,{owner:`agent-detail`,children:i})]})}var ERi=()=>{let{toggle:e}=X8();return Ux({"]":e}),null};function DRi(){let e=Zw(),{isCollapsed:t,toggle:n}=X8();return e?(0,K.jsx)(Uw,{asChild:!0,children:(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,type:`button`,"aria-label":`Config`,tooltip:`Show config panel`,"data-testid":`agent-overview-panel-toggle`,children:(0,K.jsx)(O3,{side:`right`})})}):(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,type:`button`,"aria-label":`Config`,"aria-pressed":!t,tooltip:(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[t?`Show config panel`:`Hide config panel`,(0,K.jsx)(Vx,{size:`xs`,children:`]`})]}),"data-testid":`agent-overview-panel-toggle`,onClick:n,children:(0,K.jsx)(O3,{side:`right`})})}function ORi({agentId:e,showConfig:t=!0}){let{data:n}=CN({agentId:e,requestContext:HS(`agent`,e)[0],queryOptions:{enabled:!!e}}),{canCreateAgent:r}=cOn(),{Link:i,paths:a}=sn(),{handleCopy:o,isCopied:s}=hC({text:`${window.location.origin}${WZ(`/agents/${encodeURIComponent(e)}/session`)}`,copyMessage:`Session URL copied to clipboard!`}),c=a.cmsAgentEditLink(e),l=r&&n?.source===`stored`&&!!c;return(0,K.jsxs)(K.Fragment,{children:[l&&(0,K.jsx)(X,{variant:`ghost`,size:`sm`,render:(0,K.jsx)(i,{href:c}),icon:(0,K.jsx)(iH,{}),children:`Edit`}),(0,K.jsx)(X,{variant:`ghost`,size:`icon-sm`,type:`button`,"aria-label":`Copy session URL`,onClick:o,tooltip:`Copy session URL to share with your team`,"data-testid":`agent-entity-header-share`,children:s?(0,K.jsx)(pC,{}):(0,K.jsx)(tZ,{})}),t&&(0,K.jsx)(DRi,{})]})}function kRi(e){if(e)try{return nk(e)}catch{return}}function ARi(e){let t=kRi(e.inputSchema);return{inputSchema:t,outputSchema:kRi(e.outputSchema),requestContextSchema:kRi(e.requestContextSchema),zodInputSchema:z9(t)}}function jRi(e,t){let{data:n={},isLoading:r,isError:i}=wN(),a=Object.entries(n).filter(([,t])=>Object.values(t.tools??{}).some(t=>t.id===e)).map(([e,t])=>({id:e,name:t.name||e}));return{agents:[...a.filter(e=>e.id===t),...a.filter(e=>e.id!==t)],isLoading:r,isError:i}}function MRi({agent:e,isCurrent:t}){let{Link:n,paths:r}=sn(),i=(0,K.jsx)(Z.NameCell,{children:(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,K.jsx)(Dx,{size:`sm`,className:`shrink-0 text-muted-foreground`,children:(0,K.jsx)(HN,{})}),e.name]})});return t?(0,K.jsxs)(Z.RowStatic,{children:[i,(0,K.jsx)(Z.Cell,{children:(0,K.jsx)(eC,{variant:`neutral`,emphasis:`subtle`,children:`Current`})})]}):(0,K.jsxs)(Z.RowLink,{to:r.agentLink(e.id),LinkComponent:n,children:[i,(0,K.jsx)(`span`,{})]})}function NRi({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 PRi({toolId:e,currentAgentId:t}){let{agents:n,isLoading:r,isError:i}=jRi(e,t),a=NRi({isLoading:r,isError:i,isEmpty:n.length===0});return a?(0,K.jsx)(vZ,{children:(0,K.jsx)(fji,{message:a})}):(0,K.jsx)(Z,{columns:`minmax(0,1fr) auto`,fit:`container`,children:n.map(e=>(0,K.jsx)(MRi,{agent:e,isCurrent:e.id===t},e.id))})}function FRi(e){return(0,K.jsxs)(yZ,{children:[(0,K.jsx)(cji,{children:(0,K.jsx)(bZ,{children:`Used by`})}),(0,K.jsx)(PRi,{...e})]})}function IRi({tool:e,execution:t,currentAgentId:n,requestContextEntityType:r,requestContextEntityId:i}){let{canExecute:a}=fS(),{inputSchema:o,outputSchema:s,requestContextSchema:c,zodInputSchema:l}=ARi(e);return(0,K.jsx)(sji,{description:e.description,overview:(0,K.jsx)(iMi,{inputSchema:o,outputSchema:s,requestContextSchema:c,footer:(0,K.jsx)(FRi,{toolId:e.id,currentAgentId:n})}),canRun:a(`tools`),playground:(0,K.jsx)($ji,{zodInputSchema:l,execution:t,requestContextEntityType:r,requestContextEntityId:i})})}function LRi({agentId:e}){let t=rMi(),[n]=HS(`agent`,e),{data:r,isLoading:i}=CN({agentId:e,requestContext:n}),{mutateAsync:a,status:o,data:s,error:c}=lAt(),l=Object.values(r?.tools??{}).find(e=>e.id===t),u={execute:(n,r)=>a({agentId:e,toolId:t,input:n,playgroundRequestContext:r}),status:o,output:s,error:c};return i?(0,K.jsx)(jQ.LoadingData,{}):l?(0,K.jsx)(IRi,{tool:l,execution:u,currentAgentId:e,requestContextEntityType:`agent-tool`,requestContextEntityId:`${e}:${l.id}`}):(0,K.jsxs)(jQ.NoData,{children:[`This agent has no tool "`,t,`".`]})}var RRi=[eP(`/agents`),$jt],zRi=({agentId:e})=>{let t=Ov();return Ux({"g$+t":()=>t(`/agents/${e}/traces`)}),null},BRi=S8.threadId;function VRi(e,t,n){if(e===`chat`){let e=B_(`/agents/:agentId/threads/:threadId`,t)?.params.threadId;return e===`new`?void 0:e}if(e===`traces`){let e=new URLSearchParams(n),t=e.get(w8(BRi));return t&&t!==`is`?void 0:e.get(BRi)||void 0}}var HRi=({children:e})=>{let{agentId:t}=kv(),n=Dv(),{isCmsAvailable:r}=w3(),{hasObservability:i}=Pkt(),a=At.has(`datasets`),o=r&&a,s=i&&a,{data:c}=CN({agentId:t,requestContext:HS(`agent`,t)[0],queryOptions:{enabled:!!t}}),l=MK(c?.provider??``),u=c?.modelId??``,d=n.pathname.includes(`/threads`)?`chat`:n.pathname.includes(`/editor`)?`versions`:n.pathname.includes(`/traces`)?`traces`:`none`,f=VRi(d,n.pathname,n.search);return(0,K.jsx)(Jer,{defaultProvider:l,defaultModel:u,children:(0,K.jsxs)(tn,{children:[(0,K.jsx)(zRi,{agentId:t}),(0,K.jsx)(ERi,{}),(0,K.jsx)(jMi,{children:(0,K.jsx)(LRi,{agentId:t})}),(0,K.jsx)(TRi,{agentId:t,disabled:d===`versions`,children:(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:RRi}),headerActions:(0,K.jsx)(ORi,{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)($Zr,{agentId:t,activeTab:d,threadId:f,showPlayground:o,showObservability:s}),e]})]})})]})},`${t}:${l}/${u}`)};function URi(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:Ywi(n,r),childCount:t?.pages.length?`${t.pages.length}${t.nextCursor?`+`:``}`:void 0}}function WRi(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 GRi(e){let t=Y(),n=qOi().data?.[0]?.key,r=e.pageId??e.pageRef,i=T_({queryKey:[`knowledge`,n,`tree`,null,null],queryFn:n?async()=>t.getKnowledge(n).tree({}):v_,staleTime:3e4}),a=e.pageId!==void 0||e.pageRef!==void 0&&WRi(e.pageRef,i.data),{data:o}=T_({queryKey:[`knowledge`,n,`page`,r,null],queryFn:n&&r&&a?async()=>t.getKnowledge(n).page(r):v_,retry:!1,staleTime:3e4}),s=o?.page.id,c=T_({queryKey:[`knowledge`,n,`tree`,s??null,null],queryFn:n&&s?async()=>t.getKnowledge(n).tree({parentId:s}):v_,staleTime:3e4});return o?URi(o,c.data):void 0}function KRi({children:e}){return(0,K.jsx)(I1n,{pageHref:hX,refHref:hX,usePagePreview:GRi,children:e})}var qRi=()=>{let e=Ov();return Ux({"g$+a":()=>e(`/agents`),"g$+p":()=>e(`/prompts`),"g$+w":()=>e(`/workflows`),"g$+c":()=>e(`/processors`),"g$+m":()=>e(`/mcps`),"g$+o":()=>e(`/tools`),"g$+k":()=>e(`/workspaces`),"g$+s":()=>e(`/scorers`),"g$+d":()=>e(`/datasets`),"g$+x":()=>e(`/experiments`),"g$+q":()=>e(`/experiments/review-queue`),"g$+n":()=>e(`/metrics`),"g$+t":()=>e(`/traces`),"g$+l":()=>e(`/logs`),"g$+,":()=>e(`/settings`),"g$+h":()=>e(`/resources`)}),null},JRi=eP(`/traces`);function YRi(e){return e.startsWith(`/spans`)?`spans`:e.startsWith(`/threads`)?`threads`:`traces`}function XRi({children:e}){let{pathname:t}=Dv(),n=Ov();return(0,K.jsx)(PNi,{current:YRi(t),features:Roi,onViewChange:e=>n(`/${e}`),breadcrumbs:e=>{let t=KNi(e);return(0,K.jsx)(vN,{crumbs:t?[JRi,{id:e.current,label:t}]:[JRi]})},children:e})}var ZRi=()=>(0,K.jsx)(Jx,{titleSlot:`No Processors yet`,descriptionSlot:`Configure processors. Add input or output processors to your agents to transform messages.`,actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/docs/agents/processors`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(tP,{}),children:`Processors documentation`}),variant:`fill`}),QRi=[`input`,`inputStep`,`outputStep`,`outputStream`,`outputResult`],$Ri={name:e=>e.name||e.id,agents:e=>e.agentIds?.length??0};function ezi({processors:e,isLoading:t,search:n=``,sort:r,onSortChange:i}){let{paths:a,Link:o}=sn(),s=(0,G.useMemo)(()=>Object.values(e??{}).filter(e=>e.phases&&e.phases.length>0),[e]),c=(0,G.useMemo)(()=>{let e=n.toLowerCase();return IZ(s.filter(t=>t.id.toLowerCase().includes(e)||(t.name||``).toLowerCase().includes(e)),r,$Ri)},[s,n,r]),{containerRef:l,getRowProps:u}=PZ({count:c.length,global:!0});if(t)return(0,K.jsx)(DH,{columns:`auto 1fr auto auto auto auto auto auto`});let d=e=>r?.key===e?r.direction:void 0;return(0,K.jsxs)(Z,{columns:`auto 1fr auto auto auto auto auto auto`,scrollRef:l,children:[(0,K.jsxs)(Z.Top,{children:[i?(0,K.jsx)(Z.SortableTopCell,{sortKey:`name`,sort:d(`name`),onSortChange:i,children:`Name`}):(0,K.jsx)(Z.TopCell,{children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`Description`}),(0,K.jsx)(Z.TopCellSmart,{long:`Input`,short:`Input`,tooltip:`Contains input phase`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Input Step`,short:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(H4,{}),` Step`]}),tooltip:`Contains input step phase`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Output Step`,short:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(U4,{}),` Step`]}),tooltip:`Contains output step phase`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Output Stream`,short:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(U4,{}),` Stream`]}),tooltip:`Contains output stream phase`,className:`text-center`}),(0,K.jsx)(Z.TopCellSmart,{long:`Output Result`,short:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(U4,{}),` Result`]}),tooltip:`Contains output result phase`,className:`text-center`}),i?(0,K.jsx)(Z.SortableTopCell,{sortKey:`agents`,sort:d(`agents`),onSortChange:i,align:`end`,children:`Used by`}):(0,K.jsx)(Z.TopCellSmart,{short:`Used by`,long:`Used by Agents`,className:`text-center`})]}),c.length===0&&n?(0,K.jsx)(Z.NoMatch,{message:`No Processors match your search`}):null,c.map((e,t)=>{let n=dJ(e.name||e.id,50),r=dJ(e.description??``,200),i=e.agentIds?.length??0,s=new Set(e.phases||[]),c=e.isWorkflow?a.workflowLink(e.id)+`/graph`:a.processorLink(e.id);return(0,K.jsxs)(Z.RowLink,{to:c,LinkComponent:o,...u(t),children:[(0,K.jsx)(Z.NameCell,{children:n}),(0,K.jsx)(Z.DescriptionCell,{children:r}),QRi.map(e=>(0,K.jsx)(Z.TextCell,{className:`text-center`,children:s.has(e)&&(0,K.jsx)(pC,{className:`mx-auto size-icon-md`})},e)),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:i||``})]},e.id)})]})}var Q9=[eP(`/processors`)];function tzi(){let{data:e={},isLoading:t,error:n}=PN(),[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)();return n&&FN(n)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:Q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Processors`}),(0,K.jsx)(TH,{variant:`fill`})]}):n&&IN(n)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:Q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Processors`}),(0,K.jsx)(wH,{variant:`fill`,resource:`processors`})]}):n?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:Q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Processors`}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load processors`,descriptionSlot:n.message})]}):Object.keys(e).length===0&&!t?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:Q9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Processors`}),(0,K.jsx)(ZRi,{})]}):(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:Q9}),actionRow:(0,K.jsx)(TK,{children:(0,K.jsx)(TK.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(MH,{...NH,onValueChange:i,label:`Search processors`,placeholder:`Search by name`})})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Processors`}),(0,K.jsx)(ezi,{processors:e,isLoading:t,search:r,sort:a,onSortChange:(e,t)=>o({key:t,direction:e})})]})}var nzi={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 rzi({processorId:e}){let{data:t,isLoading:n,error:r}=ajt({processorId:e,queryOptions:{enabled:!!e}});return(0,G.useEffect)(()=>{if(r){let e=r instanceof Error?r.message:`Failed to load processor`;iS.error(`Error loading processor: ${e}`)}},[r]),n?(0,K.jsxs)(`div`,{className:`p-4`,children:[(0,K.jsx)(zS,{className:`mb-4 h-8 w-48`}),(0,K.jsx)(zS,{className:`h-32 w-full`})]}):r?null:t?(0,K.jsx)(izi,{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 izi({processor:e}){let t=yw(),[n,r]=(0,G.useState)(e.phases[0]||`input`),[i,a]=(0,G.useState)(e.configurations[0]?.agentId||``),[o,s]=(0,G.useState)(`Hello, this is a test message.`),[c,l]=(0,G.useState)(null),[u,d]=(0,G.useState)(),f=ojt(),p=async()=>{d(void 0),l(null);let t=n===`outputStep`||n===`outputResult`?`assistant`:`user`,r=[{id:crypto.randomUUID(),role:t,createdAt:new Date,content:{format:2,parts:[{type:`text`,text:o}]}}];try{let t=await f.mutateAsync({processorId:e.id,phase:n,messages:r,agentId:i||void 0});l(t),!t.success&&t.error&&d(t.error)}catch(e){d(e.message||`An error occurred`)}},m=c?JSON.stringify(c,null,2):`{}`;return(0,K.jsxs)(`div`,{className:`relative grid h-full min-w-min grid-cols-[auto_1fr] overflow-x-auto overflow-y-auto`,children:[(0,K.jsxs)(`div`,{className:`w-[22rem] overflow-y-auto border-r border-border`,children:[(0,K.jsx)(azi,{processor:e}),(0,K.jsxs)(`div`,{className:`space-y-5 p-5`,children:[(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{children:`Phase`}),(0,K.jsxs)(Bk,{value:n,onValueChange:t=>{let n=e.phases.find(e=>e===t);n&&r(n)},children:[(0,K.jsx)(Hk,{className:`w-full`,children:(0,K.jsx)(Vk,{placeholder:`Select phase`})}),(0,K.jsx)(Uk,{children:e.phases.map(e=>(0,K.jsx)(Wk,{value:e,children:e},e))})]})]}),(0,K.jsx)(T,{variant:`meta`,tone:`muted`,children:nzi[n]})]}),e.configurations.length>1&&(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{children:`Agent Configuration`}),(0,K.jsxs)(Bk,{value:i,onValueChange:a,children:[(0,K.jsx)(Hk,{className:`w-full`,children:(0,K.jsx)(Vk,{placeholder:`Select agent`})}),(0,K.jsx)(Uk,{children:e.configurations.map(e=>(0,K.jsxs)(Wk,{value:e.agentId,children:[e.agentName,` (`,e.type,`)`]},e.agentId))})]})]}),(0,K.jsxs)(ak,{children:[(0,K.jsx)(sk,{children:`Test Message`}),(0,K.jsx)(qk,{value:o,onChange:e=>s(e.target.value),placeholder:`Enter a test message`,rows:4})]}),(0,K.jsx)(X,{icon:(0,K.jsx)(DT,{}),onClick:p,disabled:f.isPending||n===`outputStream`||n===`llmRequest`,className:`w-full`,children:f.isPending?`Running...`:`Run processor`}),n===`outputStream`&&(0,K.jsx)(T,{variant:`meta`,className:`text-warning-foreground`,children:`Output Stream phase cannot be executed directly. Use streaming instead.`}),n===`llmRequest`&&(0,K.jsx)(T,{variant:`meta`,className:`text-warning-foreground`,children:`LLM Request phase cannot be executed directly. It runs on the provider prompt during an agent call.`}),c&&(0,K.jsxs)(`div`,{className:`space-y-2 border-t border-border pt-4`,children:[(0,K.jsx)(T,{variant:`caption`,tone:`muted`,children:`Status`}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(eC,{variant:c.success?`success`:`destructive`,children:c.success?`Success`:`Failed`}),c.tripwire?.triggered&&(0,K.jsx)(eC,{variant:`info`,children:`Tripwire Triggered`})]}),c.tripwire?.triggered&&c.tripwire.reason&&(0,K.jsxs)(`div`,{className:`mt-2 rounded-md border border-warning-edge bg-warning-subtle p-3`,children:[(0,K.jsx)(T,{variant:`column`,className:`text-warning-subtle-foreground`,children:`Tripwire Reason`}),(0,K.jsx)(T,{variant:`caption`,tone:`muted`,className:`mt-1`,children:c.tripwire.reason})]})]})]})]}),(0,K.jsx)(`div`,{className:`absolute top-4 right-4 z-10`,children:(0,K.jsx)(gC,{content:m,tooltip:`Copy JSON result to clipboard`})}),(0,K.jsx)(`div`,{className:`relative h-full overflow-x-auto overflow-y-auto p-5`,children:(0,K.jsx)(_w,{value:u||m,editable:!0,theme:t,extensions:[mt,vw],basicSetup:{foldGutter:!1}})})]})}function azi({processor:e}){return(0,K.jsxs)(`div`,{className:`border-b border-border px-5 pt-5 pb-4`,children:[(0,K.jsx)(T,{variant:`heading`,tone:`faint`,className:`mb-2`,children:e.name||e.id}),e.name&&e.name!==e.id&&(0,K.jsx)(T,{variant:`caption`,tone:`muted`,className:`mb-3`,children:e.id}),(0,K.jsx)(`div`,{className:`mt-3 flex flex-wrap gap-1`,children:e.phases.map(e=>(0,K.jsx)(eC,{children:e},e))}),(0,K.jsx)(`div`,{className:`mt-3`,children:(0,K.jsxs)(T,{variant:`meta`,tone:`muted`,children:[`Attached to `,e.configurations.length,` agent`,e.configurations.length===1?``:`s`]})})]})}var ozi=[eP(`/processors`),tMt];function szi(){let{processorId:e}=kv(),{data:t,isLoading:n,error:r}=ajt({processorId:e,queryOptions:{enabled:!!e}});return r&&FN(r)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:ozi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(TH,{variant:`fill`})]}):r&&IN(r)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:ozi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(wH,{variant:`fill`,resource:`processors`})]}):!n&&t?.isWorkflow?(0,K.jsx)(Fv,{to:`/workflows/${e}/graph`,replace:!0}):n?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:ozi}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:e}),(0,K.jsx)(zS,{className:`mb-4 h-8 w-48`}),(0,K.jsx)(zS,{className:`h-32 w-full`})]}):(0,K.jsxs)(RS,{variant:`fit`,breadcrumbs:(0,K.jsx)(vN,{crumbs:ozi}),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)(rzi,{processorId:e})})]})}function czi(){let e=rMi(),{data:t,isLoading:n}=ZNn({toolId:e}),{mutateAsync:r,status:i,data:a,error:o}=QNn(),s={execute:(t,n)=>r({toolId:e,input:t,requestContext:n}),status:i,output:a,error:o};return n?(0,K.jsx)(jQ.LoadingData,{}):t?(0,K.jsx)(IRi,{tool:t,execution:s,requestContextEntityType:`tool`,requestContextEntityId:t.id}):(0,K.jsxs)(jQ.NoData,{children:[`Tool "`,e,`" not found.`]})}var lzi=()=>(0,K.jsx)(Jx,{titleSlot:`No Tools yet`,descriptionSlot:(0,K.jsxs)(K.Fragment,{children:[`Mastra tools are not configured yet. `,(0,K.jsx)(`br`,{}),`More information in the documentation.`]}),actionSlot:(0,K.jsx)(X,{variant:`ghost`,render:(0,K.jsx)(`a`,{href:`https://mastra.ai/docs/agents/using-tools-and-mcp`,target:`_blank`,rel:`noopener noreferrer`}),icon:(0,K.jsx)(tP,{}),children:`Tools documentation`}),variant:`fill`}),uzi=(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())},dzi={name:e=>e.id,agents:e=>e.agents.length};function fzi({tools:e,agents:t,isLoading:n,search:r=``,sort:i,onSortChange:a,selectedToolId:o}){let{paths:s,Link:c}=sn(),l=(0,G.useMemo)(()=>uzi(e,t),[e,t]),u=(0,G.useMemo)(()=>IZ(l.filter(e=>e.id.toLowerCase().includes(r.toLowerCase())),i,dzi),[l,r,i]),{containerRef:d,getRowProps:f}=PZ({count:u.length,global:!0});if(n)return(0,K.jsx)(DH,{columns:`auto 1fr auto`});let p=e=>i?.key===e?i.direction:void 0;return(0,K.jsxs)(Z,{columns:`auto 1fr auto`,scrollRef:d,children:[(0,K.jsxs)(Z.Top,{children:[a?(0,K.jsx)(Z.SortableTopCell,{sortKey:`name`,sort:p(`name`),onSortChange:a,children:`Name`}):(0,K.jsx)(Z.TopCell,{children:`Name`}),(0,K.jsx)(Z.TopCell,{children:`Description`}),a?(0,K.jsx)(Z.SortableTopCell,{sortKey:`agents`,sort:p(`agents`),onSortChange:a,align:`end`,children:`Agents`}):(0,K.jsx)(Z.TopCellSmart,{long:`Agents`,short:(0,K.jsx)(HN,{}),tooltip:`Attached agents`,className:`text-center`})]}),u.length===0&&r?(0,K.jsx)(Z.NoMatch,{message:`No Tools match your search`}):null,u.map((e,t)=>{let n=dJ(e.id,50),r=dJ(e.description??``,200),i=e.agents.length;return(0,K.jsxs)(Z.RowLink,{to:s.toolLink(e.id),LinkComponent:c,featured:e.id===o,...f(t),children:[(0,K.jsx)(Z.NameCell,{children:n}),(0,K.jsx)(Z.DescriptionCell,{children:r}),(0,K.jsx)(Z.TextCell,{className:`text-center`,children:i||``})]},e.id)})]})}var $9=[eP(`/tools`)];function pzi(){let{data:e={},isLoading:t,error:n}=wN(),{data:r={},isLoading:i,error:a}=Fq(),[o,s]=(0,G.useState)(``),[c,l]=(0,G.useState)(),{toolId:u}=AMi(),d=t||i,f=a||n;return f&&FN(f)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:$9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Tools`}),(0,K.jsx)(TH,{variant:`fill`})]}):f&&IN(f)?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:$9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Tools`}),(0,K.jsx)(wH,{variant:`fill`,resource:`tools`})]}):f?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:$9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Tools`}),(0,K.jsx)(Jx,{tone:`error`,variant:`fill`,titleSlot:`Failed to load tools`,descriptionSlot:f.message})]}):Object.keys(r).length===0&&!d?(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:$9}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Tools`}),(0,K.jsx)(lzi,{})]}):(0,K.jsxs)(RS,{breadcrumbs:(0,K.jsx)(vN,{crumbs:$9}),actionRow:(0,K.jsx)(TK,{children:(0,K.jsx)(TK.Start,{children:(0,K.jsx)(`div`,{className:`max-w-120 flex-1`,children:(0,K.jsx)(MH,{...NH,onValueChange:s,label:`Search tools`,placeholder:`Search by name`})})})}),children:[(0,K.jsx)(`h1`,{className:`sr-only`,children:`Tools`}),(0,K.jsx)(fzi,{tools:r,agents:e,isLoading:d,search:o,sort:c,onSortChange:(e,t)=>l({key:t,direction:e}),selectedToolId:u}),(0,K.jsx)(jMi,{children:(0,K.jsx)(czi,{})})]})}var mzi=()=>{let e=Ov();return(0,K.jsx)(on,{Link:mS,navigate:t=>e(t),paths:xDn,children:(0,K.jsxs)(en,{children:[(0,K.jsx)(qRi,{}),(0,K.jsx)(KRi,{children:(0,K.jsx)(uRi,{children:(0,K.jsx)(Lqe,{children:(0,K.jsx)(Iv,{})})})})]})})},hzi=()=>{let e=Ov();return(0,K.jsx)(on,{Link:mS,navigate:t=>e(t),paths:xDn,children:(0,K.jsx)(dRi,{children:(0,K.jsx)(Iv,{})})})},gzi=!!window.MASTRA_CLOUD_API_ENDPOINT,_zi=At.has(`datasets`),vzi=[{index:!0,element:(0,K.jsx)(jsi,{})},{path:`instruction-blocks`,element:(0,K.jsx)(Msi,{})},{path:`tools`,element:(0,K.jsx)(Isi,{})},{path:`agents`,element:(0,K.jsx)(Csi,{})},{path:`scorers`,element:(0,K.jsx)(Psi,{})},{path:`workflows`,element:(0,K.jsx)(Rsi,{})},{path:`skills`,element:(0,K.jsx)(Fsi,{})},{path:`memory`,element:(0,K.jsx)(Nsi,{})},{path:`variables`,element:(0,K.jsx)(Lsi,{})}],yzi=[{element:(0,K.jsx)(hLi,{}),children:[{path:`/login`,element:(0,K.jsx)(lki,{})},{path:`/signup`,element:(0,K.jsx)(ONi,{})}]},{path:`/agent-builder`,element:(0,K.jsx)(jqe,{paths:xDn}),children:[{index:!0,element:(0,K.jsx)(wDn,{})},{path:`agents`,element:(0,K.jsx)(Z9,{}),children:[{index:!0,element:(0,K.jsx)(XNn,{})}]},{path:`agents`,element:(0,K.jsx)(wRi,{}),children:[{path:`create`,element:(0,K.jsx)(lPn,{})},{path:`:id`,loader:({params:e})=>K_(`/agent-builder/agents/${e.id}/view`)},{path:`:id/edit`,element:(0,K.jsx)(q6n,{})},{path:`:id/view`,element:(0,K.jsx)(i5n,{})}]},{path:`skills`,element:(0,K.jsx)(Z9,{}),children:[{index:!0,element:(0,K.jsx)(n7n,{})}]},{path:`skills`,element:(0,K.jsx)(wRi,{}),children:[{path:`create`,element:(0,K.jsx)(o7n,{})},{path:`:id`,loader:({params:e})=>K_(`/agent-builder/skills/${e.id}/edit`)},{path:`:id/edit`,element:(0,K.jsx)(M7n,{})},{path:`:id/view`,element:(0,K.jsx)(B7n,{})}]},{path:`infrastructure`,element:(0,K.jsx)(Z9,{}),children:[{index:!0,element:(0,K.jsx)(W5n,{})}]},{path:`favorite`,element:(0,K.jsx)(Z9,{}),children:[{index:!0,element:(0,K.jsx)(h5n,{})}]},{path:`library`,element:(0,K.jsx)(Z9,{}),children:[{index:!0,element:(0,K.jsx)(G5n,{})}]}]},{element:(0,K.jsx)(hzi,{}),children:[{path:`/agents/:agentId/session`,element:(0,K.jsx)(RQr,{})},{path:`/agents/:agentId/session/:threadId`,element:(0,K.jsx)(RQr,{})}]},{element:(0,K.jsx)(mzi,{}),children:[...gzi?[]:[{path:`/settings`,element:(0,K.jsx)(DNi,{})},{path:`/templates`,element:(0,K.jsx)(NPi,{})},{path:`/templates/:templateSlug`,element:(0,K.jsx)(XPi,{})}],{path:`/logs`,element:(0,K.jsx)(lAi,{})},{path:`/scorers`,element:(0,K.jsx)(cNi,{})},{path:`/scorers/:scorerId`,element:(0,K.jsx)(gNi,{})},{path:`/metrics`,element:(0,K.jsx)(XMi,{})},{path:`/intelligence`,element:(0,K.jsx)(bhn,{})},{path:`/intelligence/entities/:entityType/:entityId`,element:(0,K.jsx)(Uhn,{})},{element:(0,K.jsx)(XRi,{children:(0,K.jsx)(Iv,{})}),children:[{path:`/traces`,element:(0,K.jsx)(xsi,{})},{path:`/spans`,element:(0,K.jsx)(fPi,{})},{path:`/threads`,element:(0,K.jsx)(uFi,{})}]},{path:`/traces/:traceId`,loader:({params:e,request:t})=>{let n=new URL(t.url).searchParams;return n.set(`traceId`,e.traceId??``),K_(`/traces?${n.toString()}`)}},{path:`/observability`,loader:({request:e})=>K_(`/traces${new URL(e.url).search}`)},{path:`/resources`,element:(0,K.jsx)(oNi,{})},{path:`/agents`,element:(0,K.jsx)(b9n,{})},{path:`/cms/agents/create`,element:(0,K.jsx)(Tsi,{}),children:vzi},{path:`/cms/agents/:agentId/edit`,element:(0,K.jsx)(Asi,{}),children:vzi},{path:`/cms/scorers/create`,element:(0,K.jsx)(qsi,{})},{path:`/cms/scorers/:scorerId/edit`,element:(0,K.jsx)(Zsi,{})},{path:`/prompts`,element:(0,K.jsx)(nNi,{})},{path:`/cms/prompts/create`,element:(0,K.jsx)(Bsi,{})},{path:`/cms/prompts/:promptBlockId/edit`,element:(0,K.jsx)(Gsi,{})},{path:`/agents/:agentId`,element:(0,K.jsx)(HRi,{children:(0,K.jsx)(Iv,{})}),children:[{index:!0,loader:_Dn},{path:`chat`,loader:vDn},{path:`chat/:threadId`,loader:vDn},{path:`threads`,loader:gDn},{path:`threads/:threadId`,element:(0,K.jsx)(g1r,{})},{path:`overview`,loader:bDn},{path:`settings`,loader:bDn},..._zi?[{path:`editor`,element:(0,K.jsx)(Q1r,{})}]:[],{path:`traces`,element:(0,K.jsx)(Ssi,{})},{path:`channels`,loader:({params:e})=>K_(`/agents/${e.agentId}/threads/new`)}]},{path:`/tools`,element:(0,K.jsx)(pzi,{})},{path:`/integrations`,element:(0,K.jsx)(vwi,{})},{path:`/connections`,element:(0,K.jsx)(Qci,{})},{path:`/processors`,element:(0,K.jsx)(tzi,{})},{path:`/processors/:processorId`,element:(0,K.jsx)(szi,{})},{path:`/mcps`,element:(0,K.jsx)(kAi,{})},{path:`/mcps/:serverId`,element:(0,K.jsx)(MMi,{})},{path:`/workspaces`,element:(0,K.jsx)(fLi,{})},{path:`/workspaces/:workspaceId`,element:(0,K.jsx)(fLi,{})},{path:`/workspaces/:workspaceId/skills/:skillName`,loader:({params:e,request:t})=>K_(wK(e.workspaceId,new URL(t.url).searchParams.get(`path`)))},{path:`/workflows`,element:(0,K.jsx)(CFi,{})},{path:`/workflows/schedules`,element:(0,K.jsx)(VFi,{})},{path:`/workflows/schedules/:scheduleId`,element:(0,K.jsx)(FFi,{})},{path:`/workflows/:workflowId`,element:(0,K.jsx)(TMt,{children:(0,K.jsx)(Iv,{})}),children:[{index:!0,loader:({params:e})=>K_(`/workflows/${e.workflowId}/graph`)},{path:`graph`,element:(0,K.jsx)(cIi,{})},{path:`graph/:runId`,element:(0,K.jsx)(cIi,{})},{path:`traces`,element:(0,K.jsx)(uIi,{})},{path:`schedules`,element:(0,K.jsx)(lIi,{})}]},{path:`/knowledge`,element:(0,K.jsx)(oki,{})},..._zi?[{path:`/datasets`,element:(0,K.jsx)(Nli,{})},{path:`/datasets/:datasetId`,element:(0,K.jsx)(lhi,{}),children:[{path:`items/:itemId`,element:null}]},{path:`/datasets/:datasetId/edit`,element:(0,K.jsx)(ghi,{})},{path:`/datasets/:datasetId/items/:itemId/versions`,element:(0,K.jsx)(xhi,{})},{path:`/experiments`,element:(0,K.jsx)(m_i,{})},{path:`/experiments/compare`,element:(0,K.jsx)(k_i,{})},{path:`/experiments/review-queue`,element:(0,K.jsx)(swi,{})},{path:`/experiments/:experimentId`,element:(0,K.jsx)(UCi,{}),children:[{path:`items/:itemId`,element:null}]},{path:`/datasets/:datasetId/versions`,element:(0,K.jsx)(Thi,{})}]:[],{index:!0,element:(0,K.jsx)(SDn,{})}]}];function bzi(){let e=window.MASTRA_STUDIO_BASE_PATH||``,{baseUrl:t,headers:n,apiPrefix:r,isLoading:i}=yS(),a=(0,G.useMemo)(()=>t?vFe(t,r):void 0,[t,r]),o=(0,G.useMemo)(()=>({...n,"x-mastra-client-type":`studio`}),[n]),s=(0,G.useMemo)(()=>jze(yzi,{basename:e}),[e]);return i?(0,K.jsx)(`div`,{className:`flex h-screen w-full items-center justify-center`,children:(0,K.jsx)(It,{})}):t?(0,K.jsx)(tPe,{baseUrl:t,headers:o,apiPrefix:r,customFetch:a,children:(0,K.jsx)(Dqe,{children:(0,K.jsx)(hDn,{children:(0,K.jsx)(Yqe,{baseUrl:t,children:(0,K.jsx)(dze,{router:s})})})})}):(0,K.jsx)(rVr,{})}function xzi(){let e=window.MASTRA_SERVER_PROTOCOL||`http`,t=window.MASTRA_SERVER_HOST||`localhost`,n=window.MASTRA_SERVER_PORT||4111,r=window.MASTRA_API_PREFIX||`/api`,i=window.MASTRA_CLOUD_API_ENDPOINT||``,a=window.MASTRA_AUTO_DETECT_URL===`true`,o=i||(a?window.location.origin:`${e}://${t}:${n}`);return(0,K.jsx)(dhn,{children:(0,K.jsx)(Jqe,{endpoint:o,defaultApiPrefix:r,children:(0,K.jsx)(bzi,{})})})}function Szi(){(0,kt.createRoot)(document.getElementById(`root`)).render((0,K.jsx)(G.StrictMode,{children:(0,K.jsx)(xzi,{})}))}export{Szi as startStudio};