evals-lab 0.12.0 → 0.14.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.
- package/CHANGELOG.md +88 -0
- package/README.md +2 -2
- package/bin/run.js +4 -2
- package/lab/VERSION +1 -1
- package/lab/demo/CREDITS.md +14 -0
- package/lab/demo/datasets/demo-1.json +2 -2
- package/lab/demo/datasets/demo-2.json +2 -2
- package/lab/demo/datasets/documents-type.json +79 -0
- package/lab/demo/datasets/documents-valid.json +117 -0
- package/lab/demo/datasets/sentiment.json +2 -2
- package/lab/demo/datasets/weather-alerts.json +2 -2
- package/lab/demo/datasets/wordings.json +1 -1
- package/lab/demo/manifest.json +3 -3
- package/lab/demo/pipelines/demo-1.json +4 -4
- package/lab/demo/pipelines/demo-2.json +4 -4
- package/lab/demo/pipelines/documents.json +102 -0
- package/lab/demo/pipelines/sentiment.json +4 -4
- package/lab/demo/pipelines/weather-alerts.json +9 -5
- package/lab/demo/pipelines/wordings.json +3 -3
- package/lab/demo/sources/Demo 1/source.json +1 -1
- package/lab/demo/sources/Demo 2/source.json +1 -1
- package/lab/demo/sources/documents/invoice.pdf +65 -0
- package/lab/demo/sources/documents/letter.pdf +63 -0
- package/lab/demo/sources/documents/not-a-pdf.pdf +2 -0
- package/lab/demo/sources/documents/receipt.pdf +62 -0
- package/lab/demo/sources/documents/report.pdf +59 -0
- package/lab/demo/sources/documents/source.json +3 -0
- package/lab/demo/sources/documents/truncated.pdf +19 -0
- package/lab/demo/sources/sentiment/source.json +1 -1
- package/lab/demo/sources/weather-alerts/source.json +1 -1
- package/lab/evals-core.mjs +382 -84
- package/lab/flows/record.mjs +5 -4
- package/lab/flows/wdl.mjs +19 -0
- package/lab/kinds/list.mjs +77 -23
- package/lab/metrics/builtin.mjs +34 -7
- package/lab/run-evals.js +33 -12
- package/lab/server.py +668 -108
- package/lab/web/dist/assets/gallery-qrf0ZGXK.js +5 -0
- package/lab/web/dist/assets/main-D6xARg2A.js +16 -0
- package/lab/web/dist/assets/main-xVU6J7Gi.css +1 -0
- package/lab/web/dist/assets/tokens-C8dqXDHN.js +62 -0
- package/lab/web/dist/assets/tokens-tQ7zTPkd.css +1 -0
- package/lab/web/dist/gallery.html +3 -3
- package/lab/web/dist/index.html +4 -4
- package/package.json +1 -1
- package/lab/web/dist/assets/gallery-CFntjQFG.js +0 -5
- package/lab/web/dist/assets/main-BlTG2i20.css +0 -1
- package/lab/web/dist/assets/main-D6MNWqak.js +0 -17
- package/lab/web/dist/assets/tokens-DwzzdSIF.css +0 -1
- package/lab/web/dist/assets/tokens-bvuNFuYg.js +0 -60
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import{$ as e,$n as t,$t as n,A as r,An as i,At as a,B as o,Bn as s,Bt as c,C as l,Cn as u,Ct as d,D as f,Dn as p,Dt as m,E as h,En as g,Et as _,F as v,Fn as y,Ft as b,G as x,Gn as S,Gt as C,H as w,Hn as T,Ht as E,I as D,In as O,It as k,J as A,Jn as j,Jt as M,K as N,Kn as P,Kt as F,L as I,Ln as L,Lt as R,M as z,Mn as B,N as ee,Nn as V,Nt as H,O as te,On as U,Ot as W,P as ne,Pn as G,Pt as re,Q as ie,Qn as ae,Qt as K,R as q,Rn as oe,Rt as se,S as ce,Sn as le,St as ue,T as de,Tn as fe,Tt as J,U as pe,Ut as me,V as he,Vn as ge,Vt as _e,W as ve,Wn as ye,Wt as Y,X as be,Xn as xe,Xt as Se,Y as Ce,Yn as we,Yt as Te,Z as Ee,Zn as De,Zt as Oe,_ as ke,_n as Ae,_t as je,a as Me,an as Ne,at as Pe,b as Fe,bn as Ie,bt as Le,c as Re,cn as ze,ct as Be,d as Ve,dn as He,dt as Ue,en as We,er as Ge,et as Ke,f as qe,fn as Je,ft as Ye,g as Xe,gn as Ze,gt as Qe,h as $e,hn as et,ht as tt,i as nt,in as rt,it,j as at,jn as ot,jt as st,k as ct,kn as lt,kt as ut,ln as dt,lt as ft,m as pt,mn as mt,mt as ht,n as gt,nn as _t,nr as vt,nt as yt,o as bt,on as xt,ot as St,p as Ct,pn as wt,pt as Tt,q as Et,qn as Dt,qt as Ot,r as kt,rn as At,rr as jt,rt as Mt,s as Nt,sn as Pt,st as Ft,t as It,tn as Lt,tr as Rt,tt as zt,un as Bt,ut as Vt,v as Ht,vn as Ut,vt as Wt,w as Gt,wn as Kt,wt as qt,x as Jt,xn as Yt,xt as Xt,y as Zt,yn as Qt,yt as $t,z as en,zn as tn}from"./tokens-bvuNFuYg.js";var nn=vt(),X=jt(),rn=(0,X.createContext)(null);function Z(){let e=(0,X.useContext)(rn);if(!e)throw Error(`useApi outside an ApiContext: main.tsx mounts one at the root`);return e}var an=`modulepreload`,on=function(e){return`/`+e},sn={},cn=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=on(t,n),t=s(t),t in sn)return;sn[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:an,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},ln={},un=new Set,dn=e=>`/plugins/${encodeURIComponent(e.id)}/${encodeURIComponent(e.version)}/${e.entry.split(`/`).map(encodeURIComponent).join(`/`)}`;async function fn(e){if(!un.has(e.id))try{let t=await cn(()=>import(dn(e)),[]);if(typeof t.default!=`function`)throw Error(`its entry exports no register function`);await t.default(L().pluginHost(e.id)),un.add(e.id),delete ln[e.id]}catch(t){ln[e.id]=t instanceof Error?t.message:String(t)}}async function pn(e){let t=[];try{t=(await e.plugins()).plugins}catch{return}for(let e of t)await fn(e)}var mn=class extends Error{status;body;constructor(e,t,n=null){super(t),this.name=`ApiError`,this.status=e,this.body=n}},hn=(e,t)=>`${e}:${t}`,gn=new EventTarget,_n=e=>/^\/api\/(sources|queue)(\/|\?|$)/.test(e);function vn(e=(...e)=>fetch(...e),t=``){let n=e=>t+e;async function r(e){let t=await e.text(),n=t;try{n=t?JSON.parse(t):null}catch{}if(!e.ok){let t=n&&typeof n==`object`&&`error`in n?n.error:null,r=typeof t==`string`?t:t&&typeof t==`object`&&typeof t.message==`string`?`${t.type?`${t.type}: `:``}${t.message}`:t==null?``:JSON.stringify(t);throw new mn(e.status,r||`HTTP ${e.status}`,n)}return n}async function i(t,i){let a=await r(await e(n(t),i?.body===void 0?{method:i?.method??`GET`}:{method:i.method??`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(i.body),...i.keepalive?{keepalive:!0}:{}}));return(i?.method??(i?.body===void 0?`GET`:`POST`))!==`GET`&&_n(t)&&gn.dispatchEvent(new Event(`write`)),a}let a=e=>({...e,snapshot:L().upgradePipeline(e.snapshot),results:L().upgradeResults(e.results)}),o=e=>{let t=new URLSearchParams;return e.limit&&t.set(`limit`,String(e.limit)),e.before&&t.set(`before`,e.before),e.beforeId&&t.set(`beforeId`,e.beforeId),e.full&&t.set(`full`,`1`),`/api/queue${t.size?`?${t}`:``}`},s=new Map,c=async e=>({...e,runs:await Promise.all(e.runs.map(e=>f(a(e))))}),l=async e=>{let t=await e;return{...t,run:a(t.run)}},u=new Map,d=e=>L().evalsOf(e.snapshot).some(e=>L().isWholeRun(L().EVAL_TYPES[e.type],e)),f=e=>{if(!e.brief||!d(e))return Promise.resolve(e);let t=`${e.status} ${e.progress?.n??0} ${e.finishedAt??``}`,n=u.get(e.id);if(n?.at===t)return n.row;let r=i(`/api/queue/${encodeURIComponent(e.id)}`).then(a,()=>(u.delete(e.id),e));return u.set(e.id,{at:t,row:r}),r};return{config:()=>i(`/api/config`),google:()=>i(`/api/google`),setGoogle:e=>i(`/api/google`,{method:`PUT`,body:e}),setMicrosoft:(e,t)=>i(`/api/microsoft`,{method:`PUT`,body:{clientId:e,tenant:t}}),state:()=>i(`/api/state`),writeState:(e,t=!1)=>i(`/api/state`,{body:{docs:e},keepalive:t}),queue:(e={})=>{let t=o(e),n=s.get(t);return s.delete(t),n??i(t).then(c)},askQueue:(e,t)=>{let n=o(e),r=i(n),a=t.then(()=>r).then(c);a.catch(()=>{}),s.set(n,a)},run:e=>i(`/api/queue/${encodeURIComponent(e)}`).then(a),setComment:(e,t)=>i(`/api/queue/${encodeURIComponent(e)}`,{method:`PATCH`,body:{comment:t}}).then(a),submit:e=>l(i(`/api/queue`,{body:e})),cancel:e=>l(i(`/api/queue/${encodeURIComponent(e)}/cancel`,{body:{}})),resume:e=>l(i(`/api/queue/${encodeURIComponent(e)}/resume`,{body:{}})),rerunRun:e=>l(i(`/api/queue/${encodeURIComponent(e)}/rerun`,{body:{}})),rerun:(e,t)=>l(i(`/api/queue/${encodeURIComponent(e)}/items/${t}`,{body:{}})),rescore:(e,t)=>l(i(`/api/queue/${encodeURIComponent(e)}/rescore/${t}`,{body:{}})),clear:()=>i(`/api/queue`,{method:`DELETE`}),sources:()=>i(`/api/sources`),source:e=>i(`/api/sources/${encodeURIComponent(e)}`),datasets:()=>i(`/api/datasets`),dataset:e=>i(`/api/datasets/${encodeURIComponent(e)}`),archivedRules:()=>i(`/api/datasets/archived-rules`),createDataset:e=>i(`/api/datasets`,{body:e}),renameDataset:(e,t)=>i(`/api/datasets/${encodeURIComponent(e)}`,{method:`PATCH`,body:{name:t}}),setDatasetPreview:(e,t)=>i(`/api/datasets/${encodeURIComponent(e)}`,{method:`PATCH`,body:{preview:t}}),saveDataset:(e,t,n)=>i(`/api/datasets/${encodeURIComponent(e)}`,{method:`PUT`,body:{version:t,body:n}}),deleteDataset:e=>i(`/api/datasets/${encodeURIComponent(e)}`,{method:`DELETE`}),restoreDataset:e=>i(`/api/datasets/trash/${encodeURIComponent(e)}/restore`,{body:{}}),exportDatasetUrl:e=>n(`/api/datasets/${encodeURIComponent(e)}/export`),exportAllDatasetsUrl:()=>n(`/api/datasets/export`),importDatasets:e=>i(`/api/datasets/import`,{body:e}),runDataset:e=>i(`/api/queue/${encodeURIComponent(e)}/dataset`),runGroups:e=>i(`/api/queue/${encodeURIComponent(e)}/groups`),filterSets:()=>i(`/api/filter-sets`),filterSet:e=>i(`/api/filter-sets/${encodeURIComponent(e)}`),createFilterSet:e=>i(`/api/filter-sets`,{body:e}),renameFilterSet:(e,t)=>i(`/api/filter-sets/${encodeURIComponent(e)}`,{method:`PATCH`,body:{name:t}}),saveFilterSet:(e,t,n)=>i(`/api/filter-sets/${encodeURIComponent(e)}`,{method:`PUT`,body:{version:t,body:n}}),deleteFilterSet:e=>i(`/api/filter-sets/${encodeURIComponent(e)}`,{method:`DELETE`}),restoreFilterSet:e=>i(`/api/filter-sets/trash/${encodeURIComponent(e)}/restore`,{body:{}}),prompts:()=>i(`/api/prompts`),prompt:e=>i(`/api/prompts/${encodeURIComponent(e)}`),createPrompt:e=>i(`/api/prompts`,{body:e}),editPrompt:(e,t,n)=>i(`/api/prompts/${encodeURIComponent(e)}`,{method:`PUT`,body:{base:t,...n}}),setDefaultPrompt:e=>i(`/api/prompts/${encodeURIComponent(e)}/default`,{body:{}}),restorePromptVersion:(e,t)=>i(`/api/prompts/${encodeURIComponent(e)}/versions/${t}/restore`,{body:{}}),deletePrompt:e=>i(`/api/prompts/${encodeURIComponent(e)}`,{method:`DELETE`}),restorePrompt:e=>i(`/api/prompts/trash/${encodeURIComponent(e)}/restore`,{body:{}}),createSource:(e,t,n)=>i(`/api/sources`,{body:{name:e,type:t,...n?{config:n}:{}}}),definition:e=>i(`/api/sources/${encodeURIComponent(e)}/definition`),saveDefinition:(e,t,n)=>i(`/api/sources/${encodeURIComponent(e)}/definition`,{method:`PUT`,body:{version:t,body:n}}),updateSource:(e,t)=>i(`/api/sources/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),sourceCalls:e=>i(`/api/sources/${encodeURIComponent(e)}/calls`),snapshotSource:e=>i(`/api/sources/${encodeURIComponent(e)}/snapshot`,{body:{}}),removeCalls:(e,t)=>i(`/api/sources/${encodeURIComponent(e)}/calls/remove`,{body:{names:t}}),editCall:(e,t,n)=>i(`/api/sources/${encodeURIComponent(e)}/calls/edit`,{body:{name:t,...n}}),cloneCall:(e,t)=>i(`/api/sources/${encodeURIComponent(e)}/calls/clone`,{body:{name:t}}),removeSource:e=>i(`/api/sources/${encodeURIComponent(e)}`,{method:`DELETE`}),removeFiles:(e,t)=>i(`/api/sources/${encodeURIComponent(e)}/remove`,{body:{names:t}}),restoreTrash:e=>i(`/api/sources/trash/${encodeURIComponent(e)}/restore`,{body:{}}),copyFiles:(e,t,n,r=!1)=>i(`/api/sources/${encodeURIComponent(e)}/copy`,{body:{from:t,names:n,move:r}}),upload:async(t,i,a)=>r(await e(n(`/api/sources/${encodeURIComponent(t)}`),{method:`POST`,headers:{"X-File-Name":i},body:a})),zip:async(t,i)=>{let a=await e(n(`/api/sources/${encodeURIComponent(t)}/zip`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({names:i})});return a.ok||await r(a),a.blob()},bundle:async t=>{let i=await e(n(`/api/bundle`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});return i.ok||await r(i),i.blob()},file:async(t,i)=>{let a=await e(n(`/api/sources/${encodeURIComponent(t)}/files/${encodeURIComponent(i)}`),{cache:`no-store`});return a.ok||await r(a),a.blob()},samples:()=>i(`/api/samples`),presets:()=>i(`/api/presets`),plugins:()=>i(`/api/plugins`),installPlugin:async t=>r(await e(n(`/api/plugins`),{method:`POST`,headers:{"Content-Type":`application/zip`},body:t})),removePlugin:e=>i(`/api/plugins/${encodeURIComponent(e)}`,{method:`DELETE`}),restorePlugin:e=>i(`/api/plugins/trash/${encodeURIComponent(e)}/restore`,{body:{}}),connections:()=>i(`/api/connections`),signIn:e=>i(`/api/connections/${encodeURIComponent(e)}/start`,{body:{}}),signOut:e=>i(`/api/connections/${encodeURIComponent(e)}`,{method:`DELETE`}),connectionShares:()=>i(`/api/connections/shares`),setConnectionShares:(e,t,n)=>i(`/api/connections/shares`,{method:`PUT`,body:{kind:e,id:t,workspaces:n}}),shareConnection:(e,t,n=!1)=>i(`/api/connections/share`,{body:{kind:e,id:t,...n?{undo:!0}:{}}}),packs:()=>i(`/api/packs`),installPack:async t=>r(await e(n(`/api/packs`),{method:`POST`,headers:{"Content-Type":`application/zip`},body:t})),removePack:e=>i(`/api/packs/${encodeURIComponent(e)}`,{method:`DELETE`}),restorePack:e=>i(`/api/packs/trash/${encodeURIComponent(e)}/restore`,{body:{}}),workspaces:()=>i(`/api/workspaces`),createWorkspace:e=>i(`/api/workspaces`,{body:e}),renameWorkspace:(e,t)=>i(`/api/workspaces/${encodeURIComponent(e)}`,{method:`PATCH`,body:{name:t}}),regenerateWorkspace:e=>i(`/api/workspaces/${encodeURIComponent(e)}/regenerate`,{body:{}}),archiveWorkspace:e=>i(`/api/workspaces/${encodeURIComponent(e)}/archive`,{body:{}}),unarchiveWorkspace:e=>i(`/api/workspaces/${encodeURIComponent(e)}/unarchive`,{body:{}}),setDefaultWorkspace:e=>i(`/api/workspaces/${encodeURIComponent(e)}/default`,{body:{}}),deleteWorkspace:e=>i(`/api/workspaces/${encodeURIComponent(e)}`,{method:`DELETE`}),restoreWorkspace:e=>i(`/api/workspaces/trash/${encodeURIComponent(e)}/restore`,{body:{}}),copyMovePreflight:e=>i(`/api/copy-move/preflight`,{body:e}),copyAsset:e=>i(`/api/copy-move/copy`,{body:e}),moveAsset:e=>i(`/api/copy-move/move`,{body:e}),forWorkspace:t=>vn(e,`/w/${encodeURIComponent(t)}`),models:e=>i(`/api/models`,{body:e}),modelsAsk:e=>i(`/api/models/ask`,{body:e})}}var yn=O(`archive-restore`,[[`rect`,{width:`20`,height:`5`,x:`2`,y:`3`,rx:`1`,key:`1wp1u1`}],[`path`,{d:`M4 8v11a2 2 0 0 0 2 2h2`,key:`tvwodi`}],[`path`,{d:`M20 8v11a2 2 0 0 1-2 2h-2`,key:`1gkqxj`}],[`path`,{d:`m9 15 3-3 3 3`,key:`1pd0qc`}],[`path`,{d:`M12 12v9`,key:`192myk`}]]),bn=O(`archive`,[[`rect`,{width:`20`,height:`5`,x:`2`,y:`3`,rx:`1`,key:`1wp1u1`}],[`path`,{d:`M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8`,key:`1s80jp`}],[`path`,{d:`M10 12h4`,key:`a56b0p`}]]),xn=O(`ban`,[[`path`,{d:`M4.929 4.929 19.07 19.071`,key:`196cmz`}],[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}]]),Sn=O(`boxes`,[[`path`,{d:`M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z`,key:`lc1i9w`}],[`path`,{d:`m7 16.5-4.74-2.85`,key:`1o9zyk`}],[`path`,{d:`m7 16.5 5-3`,key:`va8pkn`}],[`path`,{d:`M7 16.5v5.17`,key:`jnp8gn`}],[`path`,{d:`M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z`,key:`8zsnat`}],[`path`,{d:`m17 16.5-5-3`,key:`8arw3v`}],[`path`,{d:`m17 16.5 4.74-2.85`,key:`8rfmw`}],[`path`,{d:`M17 16.5v5.17`,key:`k6z78m`}],[`path`,{d:`M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z`,key:`1xygjf`}],[`path`,{d:`M12 8 7.26 5.15`,key:`1vbdud`}],[`path`,{d:`m12 8 4.74-2.85`,key:`3rx089`}],[`path`,{d:`M12 13.5V8`,key:`1io7kd`}]]),Cn=O(`check-check`,[[`path`,{d:`M18 6 7 17l-5-5`,key:`116fxf`}],[`path`,{d:`m22 10-7.5 7.5L13 16`,key:`ke71qq`}]]),wn=O(`circle-check`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),Tn=O(`columns-3`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M9 3v18`,key:`fh3hqa`}],[`path`,{d:`M15 3v18`,key:`14nvp0`}]]),En=O(`external-link`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`M10 14 21 3`,key:`gplh6r`}],[`path`,{d:`M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`,key:`a6xqqp`}]]),Dn=O(`file-code-corner`,[[`path`,{d:`M4 12.15V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2h-3.35`,key:`1wthlu`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`m5 16-3 3 3 3`,key:`331omg`}],[`path`,{d:`m9 22 3-3-3-3`,key:`lsp7cz`}]]),On=O(`file-text`,[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M10 9H8`,key:`b1mrlr`}],[`path`,{d:`M16 13H8`,key:`t4e002`}],[`path`,{d:`M16 17H8`,key:`z1uh3a`}]]),kn=O(`file-up`,[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M12 12v6`,key:`3ahymv`}],[`path`,{d:`m15 15-3-3-3 3`,key:`15xj92`}]]),An=O(`flag`,[[`path`,{d:`M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528`,key:`1jaruq`}]]),jn=O(`folder-down`,[[`path`,{d:`M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z`,key:`1kt360`}],[`path`,{d:`M12 10v6`,key:`1bos4e`}],[`path`,{d:`m15 13-3 3-3-3`,key:`6j2sf0`}]]),Mn=O(`folder-input`,[[`path`,{d:`M2 9V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-1`,key:`fm4g5t`}],[`path`,{d:`M2 13h10`,key:`pgb2dq`}],[`path`,{d:`m9 16 3-3-3-3`,key:`6m91ic`}]]),Nn=O(`folder-plus`,[[`path`,{d:`M12 10v6`,key:`1bos4e`}],[`path`,{d:`M9 13h6`,key:`1uhe8q`}],[`path`,{d:`M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z`,key:`1kt360`}]]),Pn=O(`folder-up`,[[`path`,{d:`M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z`,key:`1kt360`}],[`path`,{d:`M12 10v6`,key:`1bos4e`}],[`path`,{d:`m9 13 3-3 3 3`,key:`1pxg3c`}]]),Fn=O(`gavel`,[[`path`,{d:`m14 13-8.381 8.38a1 1 0 0 1-3.001-3l8.384-8.381`,key:`pgg06f`}],[`path`,{d:`m16 16 6-6`,key:`vzrcl6`}],[`path`,{d:`m21.5 10.5-8-8`,key:`a17d9x`}],[`path`,{d:`m8 8 6-6`,key:`18bi4p`}],[`path`,{d:`m8.5 7.5 8 8`,key:`1oyaui`}]]),In=O(`link-2`,[[`path`,{d:`M9 17H7A5 5 0 0 1 7 7h2`,key:`8i5ue5`}],[`path`,{d:`M15 7h2a5 5 0 1 1 0 10h-2`,key:`1b9ql8`}],[`line`,{x1:`8`,x2:`16`,y1:`12`,y2:`12`,key:`1jonct`}]]),Ln=O(`log-in`,[[`path`,{d:`m10 17 5-5-5-5`,key:`1bsop3`}],[`path`,{d:`M15 12H3`,key:`6jk70r`}],[`path`,{d:`M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4`,key:`u53s6r`}]]),Rn=O(`log-out`,[[`path`,{d:`m16 17 5-5-5-5`,key:`1bji2h`}],[`path`,{d:`M21 12H9`,key:`dn1m92`}],[`path`,{d:`M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4`,key:`1uf3rs`}]]),zn=O(`minus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}]]),Bn=O(`pin-off`,[[`path`,{d:`M12 17v5`,key:`bb1du9`}],[`path`,{d:`M15 9.34V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H7.89`,key:`znwnzq`}],[`path`,{d:`m2 2 20 20`,key:`1ooewy`}],[`path`,{d:`M9 9v1.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h11`,key:`c9qhm2`}]]),Vn=O(`pin`,[[`path`,{d:`M12 17v5`,key:`bb1du9`}],[`path`,{d:`M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z`,key:`1nkz8b`}]]),Hn=O(`refresh-cw`,[[`path`,{d:`M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8`,key:`v9h5vc`}],[`path`,{d:`M21 3v5h-5`,key:`1q7to0`}],[`path`,{d:`M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16`,key:`3uifl3`}],[`path`,{d:`M8 16H3v5`,key:`1cv678`}]]),Un=O(`replace`,[[`path`,{d:`M14 4a1 1 0 0 1 1-1`,key:`dhj8ez`}],[`path`,{d:`M15 10a1 1 0 0 1-1-1`,key:`1mnyi5`}],[`path`,{d:`M21 4a1 1 0 0 0-1-1`,key:`sfs9ap`}],[`path`,{d:`M21 9a1 1 0 0 1-1 1`,key:`mp6qeo`}],[`path`,{d:`m3 7 3 3 3-3`,key:`x25e72`}],[`path`,{d:`M6 10V5a2 2 0 0 1 2-2h2`,key:`15xut4`}],[`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`,key:`1bkyp8`}]]),Wn=O(`rotate-cw`,[[`path`,{d:`M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8`,key:`1p45f6`}],[`path`,{d:`M21 3v5h-5`,key:`1q7to0`}]]),Gn=O(`shapes`,[[`path`,{d:`M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z`,key:`1bo67w`}],[`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`,key:`1bkyp8`}],[`circle`,{cx:`17.5`,cy:`17.5`,r:`3.5`,key:`w3z12y`}]]),Kn=O(`square-code`,[[`path`,{d:`m10 9-3 3 3 3`,key:`1oro0q`}],[`path`,{d:`m14 15 3-3-3-3`,key:`bz13h7`}],[`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`,key:`h1oib`}]]),qn=O(`square-terminal`,[[`path`,{d:`m7 11 2-2-2-2`,key:`1lz0vl`}],[`path`,{d:`M11 13h4`,key:`1p7l4v`}],[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`,key:`1m3agn`}]]),Jn=O(`star`,[[`path`,{d:`M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z`,key:`r04s7s`}]]),Yn=O(`unlink`,[[`path`,{d:`m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71`,key:`yqzxt4`}],[`path`,{d:`m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71`,key:`4qinb0`}],[`line`,{x1:`8`,x2:`8`,y1:`2`,y2:`5`,key:`1041cp`}],[`line`,{x1:`2`,x2:`5`,y1:`8`,y2:`8`,key:`14m1p5`}],[`line`,{x1:`16`,x2:`16`,y1:`19`,y2:`22`,key:`rzdirn`}],[`line`,{x1:`19`,x2:`22`,y1:`16`,y2:`16`,key:`ox905f`}]]),Xn=(0,X.createContext)(null);function Zn(){let e=(0,X.useContext)(Xn);if(!e)throw Error(`useStore outside a StoreContext: the app mounts one at its root`);return e}function Q(e){let t=Zn();return[(0,X.useSyncExternalStore)(t.subscribe,()=>t.get(e)),(0,X.useCallback)(n=>t.set(e,n),[t,e])]}function Qn(){let e=Zn();return{sync:(0,X.useSyncExternalStore)(e.subscribe,e.sync),resolve:e.resolve}}var $n=e=>e,er=()=>({version:9,scoring:{mode:`all`,threshold:null},grader:null,every:[],run:[],cases:[]}),tr=e=>e?.state===`conflict`?`Not saved: changed in another browser.`:e?.state===`offline`?`Not saved: ${e.message}`:null,nr=(e,t)=>JSON.stringify(e)===JSON.stringify(t),rr=e=>e instanceof Error?e.message:String(e),ir=({body:e,...t})=>t;function ar({api:e,pause:t=800,idle:n}){let r=$n(e),i={list:null,error:null},a=new Map,o=new Set,s=new Map,c=new Map,l=new Map,u=new Set,d=null,f=()=>{d=null,u.forEach(e=>e())},p=(e,t)=>{let n=a.get(e)??{id:e,doc:null,sync:{state:`loading`}};a.set(e,{...n,...t,id:e}),f()},m=e=>{i={list:e,error:null},f()},h=e=>{if(!i.list)return;let t=i.list.findIndex(t=>t.id===e.id);m(t<0?[...i.list,e]:i.list.map((n,r)=>r===t?e:n))},g=e=>{for(let t of[s,c]){let n=t.get(e);n&&clearTimeout(n),t.delete(e)}o.delete(e),a.delete(e),i.list?m(i.list.filter(t=>t.id!==e)):f()},_=e=>{p(e.id,{doc:e,sync:{state:`saved`}}),h(ir(e))};async function v(e){let t=a.get(e);if(!t?.doc||!o.has(e)||t.sync.state===`conflict`)return;let{body:n,version:i}=t.doc;p(e,{sync:{state:`saving`}});try{let t=await r.saveDataset(e,i,n),s=a.get(e);if(!s?.doc)return;s.doc.body===n&&o.delete(e);let c={...s.doc,version:t.version,cases:n.cases.length};if(p(e,{doc:c,sync:{state:`saved`}}),h(ir(c)),o.has(e))return v(e)}catch(t){let n=a.get(e);if(!n?.doc)return;let r=t instanceof mn&&t.status===409?t.body?.current??null:null;if(r){if(nr(r.body,n.doc.body)){o.delete(e),p(e,{doc:{...n.doc,version:r.version},sync:{state:`saved`}});return}p(e,{sync:{state:`conflict`,theirs:r}});return}p(e,{sync:{state:`offline`,message:rr(t)}})}}function y(e){let t=s.get(e);t&&(clearTimeout(t),s.delete(e));let n=l.get(e);return n||(n=v(e).finally(()=>l.delete(e)),l.set(e,n)),n}return{list:()=>i,entry:e=>a.get(e),held:()=>d??=[...a.values()],async refresh(){i.error&&(i={list:i.list,error:null},f());try{let e=(await r.datasets()).datasets;m(e);for(let t of e){let e=a.get(t.id);e?.doc&&!o.has(t.id)&&t.version>e.doc.version&&r.dataset(t.id).then(e=>{a.has(t.id)&&!o.has(t.id)&&_(e)},()=>{})}}catch(e){i={list:i.list,error:rr(e)},f()}},load(e){a.has(e)&&a.get(e).sync.state!==`missing`||(p(e,{sync:{state:`loading`}}),r.dataset(e).then(t=>{a.has(e)&&p(e,{doc:t,sync:{state:`saved`}})},t=>{a.has(e)&&p(e,{sync:{state:`missing`,message:rr(t)}})}))},edit(e,r){let i=a.get(e);if(!i?.doc)return;let l=r(i.doc.body);if(l===i.doc.body)return;p(e,{doc:{...i.doc,body:l,cases:l.cases.length}}),o.add(e);let u=s.get(e);if(u&&clearTimeout(u),s.set(e,setTimeout(()=>{s.delete(e),y(e)},t)),n){let t=c.get(e);t&&clearTimeout(t),c.set(e,setTimeout(()=>{c.delete(e);let t=a.get(e)?.doc;t&&n.cut(e,t.body)},n.ms))}},async flush(e){await Promise.all((e?[e]:[...o]).map(y))},async resolve(e,t){let n=a.get(e);if(!n?.doc||n.sync.state!==`conflict`)return;let r=n.sync.theirs;if(t===`theirs`){o.delete(e),_(r);return}p(e,{doc:{...n.doc,version:r.version},sync:{state:`saved`}}),o.add(e),await y(e)},async create(e,t,n){let i=await r.createDataset({name:e,...t?{body:t}:{},...n?{preview:n}:{}});return _(i),i},async rename(e,t){let n=await r.renameDataset(e,t),i=a.get(e)?.doc;i&&p(e,{doc:{...i,name:n.name,version:n.version,updated:n.updated}}),h({...ir(n),cases:i?.body.cases.length??n.cases})},async setPreview(e,t){let n=await r.setDatasetPreview(e,t),i=a.get(e)?.doc;i&&p(e,{doc:{...i,preview:n.preview??null}}),h({...ir(n),cases:i?.body.cases.length??n.cases})},async remove(e){let{trash:t}=await r.deleteDataset(e);return g(e),t},async restore(e){let t=await r.restoreDataset(e);return _(t),t},async importFile(e){let{created:t}=await r.importDatasets(e);for(let e of t)h(e);return t},exportUrl:e=>r.exportDatasetUrl(e),exportAllUrl:()=>r.exportAllDatasetsUrl(),subscribe(e){return u.add(e),()=>{u.delete(e)}}}}var or=3e4,sr=(e,t)=>e.get(`promptlab.versions`)[t]??{};function cr(e,t){return(e.get(`promptlab.versions`).dataset?.[t]??[]).map(e=>({...e,doc:L().upgradeDatasetBody(e?.doc)})).filter(e=>lr(e.doc))}var lr=e=>!!e&&typeof e==`object`&&Array.isArray(e.cases);function ur(e,t,n,r,i){let a=e.get(`promptlab.versions`),o=sr(e,t),s=(o[n]??[]).slice(),c=structuredClone(r);s[0]&&fr(s[0].doc,c)||(s.unshift({at:new Date().toISOString(),doc:c,reason:i}),s.length>10&&(s.length=10),e.set(`promptlab.versions`,{...a,[t]:{...o,[n]:s}}))}function dr(e,t,n,r){let i=e.get(`promptlab.versions`),a=(i.dataset?.[t]??[]).slice(),o=structuredClone(n);a[0]&&fr(a[0].doc,o)||(a.unshift({at:new Date().toISOString(),doc:o,reason:r}),a.length>10&&(a.length=10),e.set(`promptlab.versions`,{...i,dataset:{...i.dataset??{},[t]:a}}))}var fr=(e,t)=>JSON.stringify(e)===JSON.stringify(t),$=Te(),pr=(0,X.createContext)(null);function mr({children:e,pause:t}){let n=Z(),r=Zn(),i=(0,X.useMemo)(()=>ar({api:n,...t==null?{}:{pause:t},idle:{ms:or,cut:(e,t)=>dr(r,e,t,`idle`)}}),[n,r,t]);return(0,X.useEffect)(()=>{let e=()=>{i.flush()};return addEventListener(`pagehide`,e),()=>removeEventListener(`pagehide`,e)},[i]),(0,$.jsx)(pr.Provider,{value:i,children:e})}function hr(){let e=(0,X.useContext)(pr);if(!e)throw Error(`useDatasets outside a DatasetsProvider: the app mounts one at its root`);return e}function gr(){let e=hr(),t=(0,X.useSyncExternalStore)(e.subscribe,e.list);return(0,X.useEffect)(()=>{e.list().list===null&&e.refresh()},[e]),t}function _r(e){let t=hr(),n=(0,X.useSyncExternalStore)(t.subscribe,()=>e?t.entry(e):void 0);return(0,X.useEffect)(()=>{e&&t.load(e)},[t,e]),n}var vr=e=>e.name.trim()||e.text.trim().split(`
|
|
2
|
-
`)[0].trim()||`Untitled prompt`,yr=e=>e?.state===`conflict`?`Not saved: changed in another browser.`:e?.state===`offline`?`Not saved: ${e.message}`:null,br=e=>e instanceof Error?e.message:String(e),xr=({versions:e,uses:t,...n})=>n;function Sr({api:e,pause:t=800}){let n={list:null,error:null},r=new Map,i=new Set,a=new Map,o=new Map,s=new Set,c=()=>s.forEach(e=>e()),l=(e,t)=>{let n=r.get(e)??{id:e,doc:null,sync:{state:`loading`}};r.set(e,{...n,...t,id:e}),c()},u=e=>{n={list:e,error:null},c()},d=e=>{if(!n.list)return;let t=n.list.findIndex(t=>t.id===e.id),r=e.default?n.list.map(t=>t.default&&t.id!==e.id?{...t,default:!1}:t):n.list;u(t<0?[e,...r]:r.map((n,r)=>r===t?e:n))},f=e=>{l(e.id,{doc:e,sync:{state:`saved`}}),d(xr(e))};async function p(t){let n=r.get(t);if(!n?.doc||!i.has(t)||n.sync.state===`conflict`)return;let{name:a,text:o,version:s}=n.doc;l(t,{sync:{state:`saving`}});try{let n=await e.editPrompt(t,s,{name:a,text:o}),c=r.get(t);if(!c?.doc)return;let u=c.doc.name!==a||c.doc.text!==o;u||i.delete(t);let f=u?{...n,name:c.doc.name,text:c.doc.text}:n;if(l(t,{doc:f,sync:{state:u?`saving`:`saved`}}),d(xr(f)),u)return p(t)}catch(e){let n=r.get(t);if(!n?.doc)return;let a=e instanceof mn&&e.status===409?e.body?.current??null:null;if(a){if(a.text===n.doc.text&&a.name===n.doc.name){i.delete(t),f(a);return}l(t,{sync:{state:`conflict`,theirs:a}});return}l(t,{sync:{state:`offline`,message:br(e)}})}}function m(e){let t=a.get(e);t&&(clearTimeout(t),a.delete(e));let n=o.get(e);return n||(n=p(e).finally(()=>o.delete(e)),o.set(e,n)),n}return{list:()=>n,entry:e=>r.get(e),async refresh(){n.error&&(n={list:n.list,error:null},c());try{u((await e.prompts()).prompts)}catch(e){n={list:n.list,error:br(e)},c()}},load(t){i.has(t)||(r.has(t)||l(t,{sync:{state:`loading`}}),e.prompt(t).then(e=>{r.has(t)&&!i.has(t)&&f(e)},e=>{r.has(t)&&l(t,{sync:{state:`missing`,message:br(e)}})}))},edit(e,n){let o=r.get(e);if(!o?.doc)return;let s={...o.doc,...n};if(s.name===o.doc.name&&s.text===o.doc.text)return;l(e,{doc:s}),d(xr(s)),i.add(e);let c=a.get(e);c&&clearTimeout(c),a.set(e,setTimeout(()=>{a.delete(e),m(e)},t))},async flush(e){await Promise.all((e?[e]:[...i]).map(m))},async resolve(e,t){let n=r.get(e);if(!n?.doc||n.sync.state!==`conflict`)return;let a=n.sync.theirs;if(t===`theirs`){i.delete(e),f(a);return}l(e,{doc:{...n.doc,version:a.version},sync:{state:`saved`}}),i.add(e),await m(e)},async create(t={}){let n=await e.createPrompt(t);return f(n),n},async setDefault(t){await m(t),f(await e.setDefaultPrompt(t))},async restoreVersion(t,n){await m(t),f(await e.restorePromptVersion(t,n))},async remove(t){await m(t);let{trash:o}=await e.deletePrompt(t),s=a.get(t);return s&&clearTimeout(s),a.delete(t),i.delete(t),r.delete(t),n.list?u(n.list.filter(e=>e.id!==t)):c(),o},async restore(t){let n=await e.restorePrompt(t);return f(n),n},subscribe(e){return s.add(e),()=>{s.delete(e)}}}}var Cr=(0,X.createContext)(null);function wr({children:e,pause:t}){let n=Z(),r=(0,X.useMemo)(()=>Sr({api:n,...t==null?{}:{pause:t}}),[n,t]);return(0,X.useEffect)(()=>{let e=()=>{r.flush()};return addEventListener(`pagehide`,e),()=>removeEventListener(`pagehide`,e)},[r]),(0,$.jsx)(Cr.Provider,{value:r,children:e})}function Tr(){let e=(0,X.useContext)(Cr);if(!e)throw Error(`usePrompts outside a PromptsProvider: the app mounts one at its root`);return e}function Er(){let e=Tr(),t=(0,X.useSyncExternalStore)(e.subscribe,e.list);return(0,X.useEffect)(()=>{e.refresh()},[e]),t}function Dr(e){let t=Tr(),n=(0,X.useSyncExternalStore)(t.subscribe,()=>e?t.entry(e):void 0);return(0,X.useEffect)(()=>{e&&t.load(e)},[t,e]),n}var Or=[`datasets`,`filters`,`prompts`,`sources`],kr=[`connections`,`wizards`,`workspaces`],Ar=[`connections`,`wizards`],jr={tab:`home`};function Mr(e){let t=e.replace(/^#\/?/,``).split(`/`).map(Rr),n=null;return(t[0]===`evals`||t[0]===`datasets`||t[0]===`sources`)&&(t=[`library`,t[0]===`sources`?`sources`:`datasets`,...t.slice(1)],n=`#/${t.map(encodeURIComponent).join(`/`)}`),{route:Nr(t),rewrite:n}}function Nr([e=``,...t]){let n=t.join(`/`)||null;switch(e){case``:case`home`:return jr;case`history`:return t.length?jr:{tab:`history`};case`runs`:return{tab:`runs`,id:n};case`results`:return n?{tab:`results`,id:n}:{tab:`history`};case`library`:{let[e=``,...r]=t,i=Or.find(t=>t===e);return i?{tab:`library`,section:i,id:r.join(`/`)||null}:{tab:`library`,section:`datasets`,id:n}}case`setup`:{let[e=``,...n]=t;if(!e)return{tab:`setup`,section:`connections`,id:null};if(e===`profiles`){let e=n.join(`/`)||null;return e?{tab:`setup`,section:`connections`,id:e,kind:`profile`}:{tab:`setup`,section:`connections`,id:null}}let r=kr.find(t=>t===e),i=n.join(`/`)||null;return!r||i&&!Ar.includes(r)?jr:{tab:`setup`,section:r,id:i}}default:return jr}}function Pr(e){switch(e.tab){case`home`:return`#/home`;case`history`:return`#/history`;case`runs`:return e.id?`#/runs/${encodeURIComponent(e.id)}`:`#/runs`;case`results`:return`#/results/${encodeURIComponent(e.id)}`;case`library`:return`#/library/${e.section}${e.id?`/${encodeURIComponent(e.id)}`:``}`;case`setup`:return e.kind===`profile`&&e.id?`#/setup/profiles/${encodeURIComponent(e.id)}`:`#/setup/${e.section}${e.id?`/${encodeURIComponent(e.id)}`:``}`}}function Fr(e){location.hash=Pr(e)}function Ir(e){history.replaceState(history.state,``,Pr(e)),window.dispatchEvent(new HashChangeEvent(`hashchange`))}function Lr(){return Mr(location.hash).route}function Rr(e){try{return decodeURIComponent(e)}catch{return e}}var zr=e=>(typeof e.id==`string`?e.id.trim():``)||`item:${L().caseItem(e)}`,Br=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase(),Vr=e=>Array.isArray(e.metrics)?e.metrics:[],Hr=e=>!e.not&&e.weight!==0,Ur=e=>e.type===`contains`&&e.not===!0&&e.weight!==0,Wr=e=>L().metricLines(e);function Gr(e,t){let n=Vr(e);switch(t.type){case`bounds`:{let r=n.findIndex(e=>e.type===`item-count`&&Hr(e)),i=r>=0?n[r]:null,a=e=>e==null||e===``?null:Number(e),o=(e,t)=>e.kind===`keep`?t:e.kind===`clear`?null:e.n,s=o(t.min,a(i?.min)),c=o(t.max,a(i?.max));if(s===a(i?.min)&&c===a(i?.max))return e;let l=s==null&&c==null?null:{...i??{type:`item-count`},min:s,max:c};return{...e,metrics:r>=0?n.flatMap((e,t)=>t===r?l?[l]:[]:[e]):[...n,...l?[l]:[]]}}case`addTerm`:{let r=t.term.trim();if(!r)return e;if(t.list===`forbid`)return n.some(e=>Ur(e)&&Br(String(e.value??``),r))?e:{...e,metrics:[...n,{type:`contains`,value:r,not:!0,ignoreCase:!0}]};let i=n.findIndex(e=>e.type===`contains-all`&&Hr(e));return i>=0&&Wr(n[i].values).some(e=>Br(e,r))?e:{...e,metrics:i>=0?n.map((e,t)=>t===i?{...e,values:[...Wr(e.values),r].join(`
|
|
3
|
-
`)}:e):[...n,{type:`contains-all`,values:r,ignoreCase:!0}]}}case`removeTerm`:{let r=t.term.trim();if(!r)return e;let i=!1,a=n.flatMap(e=>{if(Ur(e)&&Br(String(e.value??``),r))return i=!0,[];if((e.type===`contains-all`||e.type===`contains-any`)&&Hr(e)&&Wr(e.values).some(e=>Br(e,r))){i=!0;let t=Wr(e.values).filter(e=>!Br(e,r));return t.length?[{...e,values:t.join(`
|
|
4
|
-
`)}]:[]}return[e]});return i?{...e,metrics:a}:e}case`status`:return!!e.todo===t.todo?e:{...e,todo:t.todo}}}function Kr(e,t,n){let r=[];return n.type===`delete`?{next:e.filter(e=>{let n=t.has(zr(e));return n&&r.push(zr(e)),!n}),changed:r}:{next:e.map(e=>{if(!t.has(zr(e)))return e;let i=Gr(e,n);return i!==e&&r.push(zr(e)),i}),changed:r}}function qr(e,t,n){let r=new Map(e.map(e=>[zr(e),e])),i=new Map(t.map(e=>[zr(e),e])),a=[];for(let e of n){let t=r.get(e),n=i.get(e);if(!t||!n)continue;let o=new Set(L().validateEvals({cases:[t]})),s=`${n.id}: `,c=L().validateEvals({cases:[n]}).filter(e=>!o.has(e)).map(e=>e.startsWith(s)?e.slice(s.length):e);c.length&&a.push({key:e,file:L().caseItem(n),reasons:c})}return{cases:a}}var Jr={expect:`Expect`,forbid:`Forbid`},Yr=e=>Jr[e],Xr=e=>`${e} ${e===1?`case`:`cases`}`;function Zr(e,t){let n=Xr(t);switch(e.type){case`bounds`:{let t=[];return e.min.kind!==`keep`&&t.push({verb:e.min.kind===`set`?`Set`:`Cleared`,what:`Min`}),e.max.kind!==`keep`&&t.push({verb:e.max.kind===`set`?`Set`:`Cleared`,what:`Max`}),t.length===2&&t[0].verb===t[1].verb?`${t[0].verb} Min and Max items on ${n}`:t.length===2?`${t[0].verb} Min items and ${t[1].verb.toLowerCase()} Max items on ${n}`:t[0]?`${t[0].verb} ${t[0].what} items on ${n}`:`Changed ${n}`}case`addTerm`:return`Added ${e.term.trim()} to ${Jr[e.list]} on ${n}`;case`removeTerm`:return`Removed ${e.term.trim()} from ${n}`;case`status`:return`Marked ${n} ${e.todo?`To do`:`graded`}`;case`delete`:return`Deleted ${n}`}}var Qr={graded:`Graded`,todo:`To do`,missing:`Missing`};function $r(e,t){return t&&!t.includes(L().caseItem(e))?`missing`:e.todo?`todo`:`graded`}function ei(e,t){let n=new Set(e.map(e=>L().caseItem(e)));return t.filter(e=>!n.has(e))}var ti={file:``,status:`all`,show:`all`};function ni(e,t,n,r=null){let i=t.file.trim().toLowerCase();return e.filter(e=>(!i||L().caseItem(e).toLowerCase().includes(i))&&(t.status===`all`||$r(e,r)===t.status)&&(t.show===`all`||n.has(zr(e))))}var ri=(0,X.createContext)(null);function ii({children:e}){let[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(new Set),[a,o]=(0,X.useState)(ti),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(null),d=_r(l?.dataset??null),f=(0,X.useRef)(null),p=(0,X.useCallback)(e=>{e!==f.current&&(f.current=e,n(e),i(new Set),o(ti),c(null))},[]),m=(0,X.useCallback)(e=>{i(e)},[]),h=(0,X.useCallback)(e=>{o(t=>({...t,...e}))},[]),g=(0,X.useCallback)((e,t,r)=>{f.current=e,n(e),i(new Set),o({...ti,show:`selected`}),c(null),u({dataset:e,files:t,from:r});let a=Pr({tab:`library`,section:`datasets`,id:e});location.hash===a?window.dispatchEvent(new HashChangeEvent(`hashchange`)):location.hash=a},[]),_=d?.doc?.body??null,v=d?.sync.state===`missing`;(0,X.useEffect)(()=>{if(!l||!_&&!v)return;let e=new Set(l.files),t=(_?.cases??[]).filter(t=>e.has(L().caseItem(t))).map(zr);i(new Set(t)),c({from:l.from,wanted:e.size,found:t.length}),u(null)},[l,_,v]);let y=(0,X.useMemo)(()=>({datasetId:t,pickDataset:p,selected:r,setSelected:m,filters:a,setFilters:h,handedOver:s,showCases:g}),[t,p,r,m,a,h,s,g]);return(0,$.jsx)(ri.Provider,{value:y,children:e})}function ai(){let e=(0,X.useContext)(ri);if(!e)throw Error(`useCases outside an CasesProvider: the app mounts one at its root`);return e}var oi=(0,X.createContext)(null);function si({children:e}){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(null),a=(0,X.useRef)(t);a.current=t;let o=(0,X.useRef)(r);o.current=r;let s=(0,X.useRef)(0),c=(0,X.useCallback)((e,t)=>{a.current=e,n(e),o.current=t,i(t)},[]),l=(0,X.useCallback)((e,t={})=>{let n=++s.current,r=a.current,i=r.find(t=>t.id===e),o;if(i)o=r.map(r=>r.id===e?{...r,from:t.from??r.from,last:n}:r);else if(o=[...r,{id:e,at:t.at??``,from:t.from??`runs`,show:`all`,last:n}],o.length>4){let e=o.reduce((e,t)=>e.last<t.last?e:t);o=o.filter(t=>t.id!==e.id)}c(o,e)},[c]),u=(0,X.useCallback)(e=>{let t=a.current,n=t.findIndex(t=>t.id===e);if(n<0)return;let r=t[n].from,i=t.filter(t=>t.id!==e);if(i.length===0){c(i,null),window.location.hash=`#/${r}`;return}c(i,o.current===e?i[Math.min(n,i.length-1)].id:o.current)},[c]),d=(0,X.useCallback)((e,t)=>{let n=++s.current;c(a.current.map(r=>r.id===e?{...r,from:t??r.from,last:n}:r),e)},[c]),f=(0,X.useCallback)((e,t)=>{c(a.current.map(n=>n.id===e?{...n,show:t}:n),o.current)},[c]),p=(0,X.useCallback)(()=>{c(a.current,null)},[c]),m=(0,X.useCallback)(()=>{let e=a.current.find(e=>e.id===o.current);window.location.hash=`#/${e?.from??`runs`}`,p()},[p]),h=(0,X.useMemo)(()=>({tabs:t,focusedId:r,openRun:l,closeRun:u,focusRun:d,setShow:f,goBack:m,hide:p}),[t,r,l,u,d,f,m,p]);return(0,$.jsx)(oi.Provider,{value:h,children:e})}function ci(){let e=(0,X.useContext)(oi);if(!e)throw Error(`useResults outside a ResultsProvider: the app mounts one at its root`);return e}function li({n:e,of:t}){return(0,$.jsxs)(`span`,{className:`fig-part`,children:[e,(0,$.jsxs)(`span`,{className:`fig-of`,children:[`/`,t]})]})}var ui=e=>e===`good`?` fig-good`:e===`bad`?` fig-bad`:``;function di({fig:e}){return(0,$.jsx)(`span`,{className:`fig-value${ui(e.tone)}`,children:e.value??(e.of?(0,$.jsx)(li,{n:e.of[0],of:e.of[1]}):`—`)})}function fi({fig:e}){return(0,$.jsxs)(`div`,{className:`fig`,children:[(0,$.jsx)(`span`,{className:`fig-label`,children:e.label}),(0,$.jsx)(di,{fig:e})]},e.key)}function pi({label:e,lead:t,rest:n,dense:r}){return(0,$.jsxs)(`div`,{className:`figures${r?` dense`:``}`,role:`group`,"aria-label":e,children:[(0,$.jsxs)(`div`,{className:`fig fig-lead`,children:[(0,$.jsx)(`span`,{className:`fig-label`,children:t.label}),(0,$.jsxs)(`div`,{className:`fig-headline`,children:[(0,$.jsx)(di,{fig:t}),t.under&&(0,$.jsx)(`span`,{className:`fig-under`,children:(0,$.jsx)(li,{n:t.under[0],of:t.under[1]})})]})]}),!!n.length&&(0,$.jsx)(`div`,{className:`fig-rest`,children:n.map(e=>(0,$.jsx)(fi,{fig:e},e.key))})]})}var mi={type:`Connection type`,profile:`Request profile`,px:`Resolution`,format:`Image format`,quality:`Image quality`,seed:`Seed`,nPredict:`Reply tokens`,repeatPenalty:`Repeat penalty`,frequencyPenalty:`Frequency penalty`,presencePenalty:`Presence penalty`,dryMultiplier:`DRY multiplier`,dryBase:`DRY base`,dryAllowedLength:`DRY allowed length`,grammar:`Grammar`,url:`Address`,model:`Model`,temperature:`Temperature`,imagePosition:`Image position`,cachePrompt:`Cache prompt`,thinking:`Thinking`,rejectLoops:`Reject looping replies`,maxTokens:`Reply tokens`},hi={format:`image/jpeg`,quality:`0.92`,seed:``,nPredict:``,repeatPenalty:``,frequencyPenalty:``,presencePenalty:``,dryMultiplier:``,dryBase:``,dryAllowedLength:``,grammar:``,px:`921600`},gi=[`type`,`profile`,`px`,`format`,`quality`,`seed`,`nPredict`,`maxTokens`,`repeatPenalty`,`frequencyPenalty`,`presencePenalty`,`dryMultiplier`,`dryBase`,`dryAllowedLength`,`grammar`,`imagePosition`,`cachePrompt`,`thinking`,`rejectLoops`,`url`,`model`,`temperature`],_i=[`type`,`profile`,`url`,`model`,`temperature`],vi=[`px`,`format`,`quality`,`imagePosition`];function yi(e){let t=(t,n)=>String(e[t]??``).trim()?[`${n} ${e[t]}`]:[];return[...t(`frequencyPenalty`,`frequency`),...t(`presencePenalty`,`presence`),...String(e.dryMultiplier??``).trim()?[`DRY ${e.dryMultiplier} / ${e.dryBase||`–`} / ${e.dryAllowedLength||`–`}`]:[],...String(e.grammar??``).trim()?[`grammar`]:[]].join(`, `)}var bi=(e,t)=>({...hi,...t?.setupProfile?.settings||{}});function xi(e){return mi[e]??e}function Si(e,t){return e===`type`?Ci(String(t)):e===`profile`?t===`speed`?`Speed`:`Quality`:e===`px`?L().budgetLabel(t):e===`format`?String(t).replace(`image/`,``).toUpperCase():String(t)}function Ci(e){return L().CONNECTION_TYPES[e]?.label??e}var wi=e=>e.content?e.content!==`text`:null,Ti=e=>Number(new Date(e)).toString(36).slice(-6).toUpperCase(),Ei=(e,t,n=`${t}s`)=>`${e} ${e===1?t:n}`,Di=e=>{let t=e?e.timed??e.ran:0;return t?e.ms/t:null};function Oi(e,t){let n=e.scenarios.map(()=>0);for(let e of t.results||[])e&&!e.unrun&&(e.scenarios||[]).forEach((e,t)=>{t<n.length&&typeof e?.res?.ms==`number`&&n[t]++});return{...e,scenarios:e.scenarios.map((e,t)=>({...e,timed:n[t]??0}))}}var ki=e=>new Date(e).toLocaleString(void 0,{dateStyle:`medium`,timeStyle:`short`}),Ai={queued:`Queued`,running:`Running`,done:`Done`,incomplete:`Incomplete`,cancelled:`Cancelled`,failed:`Failed`,interrupted:`Interrupted`},ji=e=>Ai[e]??e;function Mi(e){return Ai[e]?(0,$.jsx)(`span`,{className:`rchip ${e}`,children:Ai[e]}):null}var Ni=e=>e.length?e.reduce((e,t)=>e+t,0)/e.length:null;function Pi(e){if(Math.round(e)<1e3)return`${Math.max(0,Math.round(e))} ms`;let t=Math.round(e/100);if(t<600)return`${(t/10).toFixed(1)}s`;let n=Math.round(e/1e3),r=Math.floor(n/60),i=n%60;if(r<60)return i?`${r}m ${i}s`:`${r}m`;let a=Math.floor(r/60),o=r%60;return o?`${a}hr ${o}`:`${a}hr`}function Fi(e,t){if(!e)return null;let n=new Date(e).getTime();if(Number.isNaN(n))return null;let r=t?new Date(t).getTime():Date.now();return Number.isNaN(r)?null:Math.max(0,r-n)}var Ii=e=>{let t=(e.scenarios||[]).filter(Boolean),n=t.reduce((e,t)=>e+(t.passed||0),0),r=t.reduce((e,t)=>e+(t.cases||0),0),i=t.map(e=>e.percent).filter(e=>e!=null),a=t.map(Di).filter(e=>e!=null);return{pct:r?Math.round(100*n/r):null,avgScore:i.length?Math.round(Ni(i)):null,avgTime:a.length?Ni(a):null}},Li=e=>{let t=Ii(e);return{pct:t.pct==null?`—`:`${t.pct}%`,avgScore:t.avgScore==null?`—`:`${t.avgScore}%`,avgTime:t.avgTime==null?`—`:Pi(t.avgTime)}},Ri=e=>e.profile??`(Default)`,zi=e=>!!e.run&&(e.status===`cancelled`||e.status===`interrupted`),Bi=e=>e.rerunOf?(0,$.jsxs)(`span`,{className:`hrerun note`,children:[`Re-run of `,e.rerunOfAt?Ti(e.rerunOfAt):`a cleared run`]}):null,Vi=[{key:`runid`,label:`Run ID`,on:!0,sort:e=>e.at,get:e=>(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`code`,{className:`runlink`,"data-openrun":e.run??void 0,children:Ti(e.at)}),Bi(e)]})},{key:`date`,label:`Date`,on:!0,sort:e=>e.at,get:e=>(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`time`,{dateTime:e.at,title:new Date(e.at).toLocaleString(),children:ki(e.at)}),e.cancelled&&(0,$.jsx)(`span`,{className:`err`,children:` cancelled`})]})},{key:`state`,label:`State`,on:!0,sort:e=>ji(e.status),get:e=>Mi(e.status)},{key:`content`,label:`Content`,on:!0,get:e=>e.content||`—`},{key:`pct`,label:`% Passed Items`,on:!0,numeric:!0,sort:e=>Ii(e).pct,get:e=>Li(e).pct},{key:`avgscore`,label:`Avg Score`,on:!0,numeric:!0,sort:e=>Ii(e).avgScore,get:e=>Li(e).avgScore},{key:`avgtime`,label:`Avg Time`,on:!0,numeric:!0,sort:e=>Ii(e).avgTime,get:e=>Li(e).avgTime},{key:`duration`,label:`Duration`,on:!1,numeric:!0,sort:e=>Fi(e.startedAt,e.finishedAt),get:e=>{let t=Fi(e.startedAt,e.finishedAt);return t==null?`—`:Pi(t)}},{key:`ran`,label:`Ran`,on:!1,numeric:!0,sort:e=>e.done,get:e=>(0,$.jsx)(li,{n:e.done,of:e.total})},{key:`setup`,label:`Pipeline`,on:!1,get:e=>e.setup||`—`},{key:`plugins`,label:`Plugins`,on:!1,get:e=>e.plugins||`—`},{key:`comment`,label:`Comment`,on:!1,sort:e=>e.comment,get:e=>(0,$.jsx)(`button`,{type:`button`,className:`ghost linkish hcomment-btn`,"data-editcomment":e.run??void 0,"aria-label":e.comment?void 0:`Add a comment`,children:e.comment?(0,$.jsx)(`span`,{className:`hcomment`,title:e.comment,children:e.comment}):(0,$.jsx)(`span`,{className:`hcomment empty`,children:`——`})})}],Hi=[{key:`name`,label:`Name`,on:!0,sort:(e,t)=>e?.name||`Target ${L().targetLetter(t)}`,get:(e,t,n)=>(0,$.jsx)(`button`,{type:`button`,className:`ghost linkish`,"data-scenario":n,children:t?.name||`Target ${L().targetLetter(n)}`})},{key:`outcome`,label:`Outcome`,on:!0,sort:e=>e.pass,get:(e,t)=>t.pass==null?(0,$.jsx)(`span`,{className:`note`,children:`—`}):(0,$.jsx)(`b`,{className:t.pass?`hit`:`fault`,children:t.pass?`Pass`:`Fail`})},{key:`evals`,label:`Evals`,on:!0,sort:e=>e.evals||null,get:(e,t)=>t.evalParts?.length?t.evalParts.map((e,t)=>(0,$.jsxs)(`span`,{children:[t>0&&`, `,e.label,` `,e.mark==null?e.value:(0,$.jsx)(_e,{pass:e.mark})]},t)):t.evals||`—`},{key:`connection`,label:`Connection`,on:!0,sort:e=>e?.connection,get:(e,t)=>t?.connection||`—`},{key:`profile`,label:`Profile`,on:!0,sort:e=>e?.setupProfile?Ri(e):null,get:(e,t,n)=>t?.setupProfile?(0,$.jsx)(`button`,{type:`button`,className:`ghost linkish`,"data-prof":n,children:Ri(t)}):`—`},{key:`passed`,label:`Passed Items`,on:!0,numeric:!0,sort:e=>e.cases?e.passed/e.cases:null,get:(e,t)=>t.cases?(0,$.jsx)(li,{n:t.passed,of:t.cases}):`—`},{key:`score`,label:`Score`,on:!0,numeric:!0,sort:e=>e.percent,get:(e,t)=>t.percent==null?`—`:`${t.percent}%`},{key:`avgtime`,label:`Avg Time`,on:!0,numeric:!0,sort:e=>Di(e),get:(e,t)=>{let n=Di(t);return n==null?`—`:Pi(n)}},{key:`total`,label:`Total`,on:!1,numeric:!0,sort:e=>e.ms||null,get:(e,t)=>t.ms?Pi(t.ms):`—`},{key:`model`,label:`Model`,on:!1,get:(e,t)=>t.model||`—`},{key:`res`,label:`Resolution`,on:!1,image:!0,get:(e,t)=>String(L().budgetLabel(bi(e,t).px))},{key:`format`,label:`Format`,on:!1,image:!0,get:(e,t)=>String(bi(e,t).format).replace(`image/`,``).toUpperCase()},{key:`quality`,label:`Quality`,on:!1,image:!0,get:(e,t)=>bi(e,t).format===`image/png`?`—`:String(bi(e,t).quality)},{key:`seed`,label:`Seed`,on:!1,get:(e,t)=>String(bi(e,t).seed||`1234`)},{key:`predict`,label:`Reply tokens`,on:!1,get:(e,t)=>String(bi(e,t).nPredict||bi(e,t).maxTokens||`—`)},{key:`penalty`,label:`Repeat penalty`,on:!1,get:(e,t)=>String(bi(e,t).repeatPenalty||`—`)},{key:`decoding`,label:`Decoding`,on:!1,get:(e,t)=>yi(bi(e,t))||`—`},...[[`case`,`Case`],[`tidy`,`Tidy items`],[`dedupe`,`Remove duplicates`],[`keep-first`,`Keep first`],[`drop-echoes`,`Drop prompt echoes`]].map(([e,t])=>({key:`modifier-${e}`,label:t,on:!1,get:(t,n)=>n.modifiers?.[e]||`—`}))],Ui={"Run Scenarios":`Run Targets`},Wi={tests:`evals`},Gi={connection:`profile`},Ki=[[`Runs`,Vi],[`Run Scenarios`,Hi]],qi=e=>![`queued`,`running`].includes(e),Ji=()=>({ran:0,passed:0,found:0,of:0,ms:0,timed:0,share:0,shared:0});function Yi(e){return e.of?Math.round(100*e.found/e.of):e.shared?Math.round(100*e.share/e.shared):null}var Xi=(e,t)=>e.filter(e=>!e.whole).map(e=>e.items[t]).filter(e=>!!e&&!L().isSkipped(e)),Zi=e=>Array.isArray(e)?e.length:typeof e==`number`?e:0;function Qi(e,t){let n=t.map(Ji);return(e||[]).forEach((e,r)=>{e&&!e.unrun&&(e.scenarios||[]).forEach((e,i)=>{let a=n[i];if(!a||!e)return;let o=Xi(t[i],r);if(o.length){a.ran++,o.every(e=>e.pass)&&a.passed++;for(let e of o)a.found+=Zi(e.found),a.of+=Zi(e.found)+Zi(e.missed)+Zi(e.invented),e.found==null&&e.missed==null&&typeof e.score==`number`&&!e.points&&(a.share+=e.score,a.shared++)}e.res&&(a.timed++,a.ms+=e.res.ms||0)})}),n}var $i=(e,t,n)=>L().targetsOf(e).map((r,i)=>L().scenarioEvals(e,i,t,qi(n))),ea=(e,t,n)=>(e.outcomes[n]??[]).some(e=>!e.whole&&L().failedScore(e.items[t]));function ta(e){return e.skipped?`Skipped`:e.whole?e.verdict?.ran?e.verdict.pass?`Passed`:`Failed`:`—`:e.ran?`${e.passed}/${e.ran}`:e.skippedItems?`Skipped`:`—`}var na=e=>!e.skipped&&e.whole&&e.verdict?.ran?!!e.verdict.pass:null,ra=e=>e.map(e=>`${e.label} ${ta(e)}`).join(`, `),ia=e=>e.map(e=>({label:e.label,value:ta(e),mark:na(e)})),aa=e=>{if(!e.group)return null;let t=L().casesRef(e)?.n??e.pin;return t==null?null:`v${t}`},oa=(e,t,n)=>e.group?.name||e.group?.id||(e.name||``).trim()||L().evalLabel({evals:n},t);function sa(e){let t=e.evals,n=t.map((n,r)=>({key:n.id,name:oa(n,r,t),version:aa(n),cells:e.scenarios.map((t,n)=>{let i=e.outcomes[n]?.[r];return{pct:i&&!i.whole&&i.ran?Math.round(100*i.passed/i.ran):null,pass:i?L().groupPass(i):null,skipped:!!i?.skipped}})})),r=e.snapshot.pass;return{rows:n,overall:t.length?{label:r?.mode===`atLeast`?`At least ${r.count}`:`All groups pass`,pass:e.scenarios.map((t,n)=>L().overallVerdict(e.outcomes[n]??[],r))}:null}}var ca=e=>e.scenarios.map((t,n)=>L().recordedTargetOf(e.snapshot,n)),la=e=>e.findIndex(e=>!e);function ua(e){return!e||e.error?null:e.transcript?.at(-1)?.got??e.raw??null}function da(e,t,n,r){let i=e.results[t]?.scenarios?.[n]?.scores?.[r];return i&&!L().isSkipped(i)?i.metrics??[]:[]}var fa=e=>`${e.type}::${e.label}`;function pa(e,t){let n=e.scenarios.length,r=(n,r)=>da(e,n,r,t),i=[],a=new Set,o=[];e.results.forEach((e,t)=>{for(let e=0;e<n;e++){let n=r(t,e);n.length>o.length&&(o=n)}});let s=e=>{let t=fa(e);a.has(t)||(a.add(t),i.push({key:t,label:e.label}))};return o.forEach(s),e.results.forEach((e,t)=>{for(let e=0;e<n;e++)r(t,e).forEach(s)}),i.map(({key:t,label:i})=>({key:t,label:i,cells:Array.from({length:n},(n,i)=>{let a=0,o=0;return e.results.forEach((e,n)=>{let s=r(n,i).find(e=>fa(e)===t);s&&s.weight!==0&&(o++,s.pass&&a++)}),o?{passed:a,ran:o}:null})}))}var ma=e=>typeof e.n==`number`&&Number.isInteger(e.n)?`${e.id}@${e.n}`:e.id;function ha(e,t,n,r=[],i=null){let a=e.own??(e.group?n[ma(e.group)]:void 0),o=L().casesRef(e),s=o?n[ma(o)]?.cases??(o.id===i?r:[]):[],c=t?s.find(e=>!e.todo&&L().caseItem(e)===t):void 0;return[...a?.every??[],...c?.metrics??[]]}function ga(e,t){let n=e=>[typeof e.metric==`string`&&e.metric.trim()||``,L().METRICS[e.type]?.label??e.type],r=0;return e.map(e=>{let i=t.findIndex((t,i)=>i>=r&&t.type===e.type&&n(t).includes(e.label));if(i<0)return null;r=i+1;let a=t[i];return[a.not?`not`:``,L().metricCheck(a)].filter(Boolean).join(` `)||null})}function _a(e){let t=e.snapshot||{},n=L().contentOf(t),r=!!(n&&L().CONTENT_TYPES[n.type]?.inline),i=L().lastKind(t),a=e.results||[],o=$i(t,a,e.status);return{id:e.id,status:e.status,at:e.submittedAt,behind:e.behind,name:t.name||`Run`,error:e.error,progress:e.progress||{current:null,n:0,total:0},scenarios:L().targetsOf(t).map((e,n)=>({id:e?.id||`scenario-${n}`,name:L().targetLabel(t,n),kind:i,plain:!(i&&L().OUTPUT_KINDS[i]?.terms)})),items:r?[null]:n?.type===`source`&&n.files||[],content:r?{type:`text`,text:n.text??``}:{type:`source`,source:n?.ref?.id??``,sourceName:n?.ref?.name??``},evals:L().evalsOf(t),snapshot:t,results:a,outcomes:o,tallies:Qi(a,o),startedAt:e.startedAt,finishedAt:e.finishedAt}}var va={LOWER:`lower case`,SENTENCE:`Sentence case`,TITLE:`Title Case`,UPPER:`UPPER CASE`,NONE:`No change`};function ya(e){if(!e)return{};let t={};for(let n of L().outOf(e)?.modifiers||[])t[n.type]=n.type===`case`?va[n.mode]??String(n.mode):L().modifierSummary(n);for(let n of L().filterSetsOf(e,`items`))for(let e of n.own?.filters||[]){let n=e.op,r=e.match;e.type===`rewrite-item`&&n?.kind===`case`?t.case=va[n.mode??``]??String(n.mode):e.type===`rewrite-item`&&n?.kind===`tidy`?t.tidy=`on`:e.type===`keep-first`?t[`keep-first`]=String(n?.n??``):e.type===`drop-item`&&r?.duplicate?t.dedupe=`on`:e.type===`drop-item`&&r?.echoes&&(t[`drop-echoes`]=`on`)}return t}function ba(e,t){let n=L().scenarioProfile(e,t),r=L().targetsOf(e)[t],i=e.profiles,a=!r?.connection||!!i&&Object.hasOwn(i,L().answerKey(r.connection.id,r.profile?.id??null));return n?a?{connection:n.name,profile:r?.profile?.name??null}:{connection:null,profile:n.name}:{connection:null,profile:null}}function xa(e){let t=e.snapshot||{},n=L().contentOf(t),r=e.results||[],i=L().targetsOf(t),a=t.jobs||[],o=$i(t,r,e.status),s=Qi(r,o),c=i.map((e,n)=>{let r=s[n]??Ji(),i=(a.length?L().stagesFor(t,n).connections:[]).map(e=>String(e.model||``)),c=i[0]?new Set(i).size===1?i[0]:i.join(` → `):``,l=Yi(r),u=L().overallVerdict(o[n]??[],t.pass);return{name:L().targetLabel(t,n),id:e?.id,model:c,setupProfile:L().scenarioProfile(t,n),...ba(t,n),modifiers:ya(t.jobs?.at(-1)),percent:l,passed:r.passed,cases:r.ran,pass:u,detail:u==null?`not graded`:ra(o[n]??[]),evals:ra(o[n]??[]),evalParts:ia(o[n]??[]),ms:r.ms,ran:r.ran}}),l=e.progress||{},u=l.n??l.total??0;return{at:e.submittedAt,run:e.id,status:e.status,cancelled:e.status===`cancelled`,startedAt:e.startedAt,finishedAt:e.finishedAt,setup:t.name||``,comment:t.comment||``,plugins:(t.plugins||[]).map(e=>`${e.id} ${e.version}`).join(`, `),done:u,total:l.total??u,content:n&&L().CONTENT_TYPES[n.type]?.inline?`text`:n?.type===`source`&&(n.ref?.name||n.ref?.id)||``,scenarios:c,rerunOf:e.rerunOf??null,rerunOfAt:e.rerunOfAt??null}}var Sa=e=>({key:`state`,label:`State`,value:ji(e),tone:e===`done`?`good`:[`failed`,`incomplete`,`cancelled`,`interrupted`].includes(e)?`bad`:null}),Ca=e=>e.length?e.reduce((e,t)=>e+t,0)/e.length:null;function wa(e){let t=0,n=0;for(let r of e||[])for(let e of r?.scenarios||[])for(let r of Object.values(e?.scores||{}))if(r&&!L().isSkipped(r))for(let e of r.metrics||[])typeof e.asked==`number`&&(t++,n+=e.asked);return{calls:t,ms:n}}function Ta(e){let t=e.tallies,n=t.reduce((e,t)=>e+t.passed,0),r=t.reduce((e,t)=>e+t.ran,0),i=t.map(Yi).filter(e=>e!=null),a=i.length?`${Math.round(Ca(i))}%`:`—`,o=Fi(e.startedAt,e.finishedAt),s=wa(e.results),c={key:`ran`,label:`Run Items`,of:e.progress.total?[e.progress.n,e.progress.total]:null};return{lead:r?{key:`pct`,label:`% Passed Items`,value:`${Math.round(100*n/r)}%`}:{...c,key:`lead-ran`},rest:[{key:`run`,label:`Run ID`,value:e.at?(0,X.createElement)(`code`,null,Ti(e.at)):`—`},Sa(e.status),{key:`score`,label:`Avg Score`,value:a},{key:`duration`,label:`Duration`,value:o==null?`—`:Pi(o)},...s.calls?[{key:`grader`,label:`Grader`,value:`${s.calls} ${s.calls===1?`call`:`calls`}, ${Pi(s.ms)}`}]:[],...r?[c]:[],{key:`start`,label:`Start Date`,value:e.at?ka(e.at):`—`},...e.snapshot.comment?[{key:`comment`,label:`Comment`,value:(0,X.createElement)(`span`,{className:`fig-comment`,title:e.snapshot.comment},e.snapshot.comment)}]:[]]}}var Ea=e=>e.evals.length&&qi(e.status)?`No assertions`:`—`;function Da(e,t){let n=e.tallies[t],r={key:`time`,label:`Avg Time`,value:Oa(n)??`—`};return n?.ran?{lead:{key:`pct`,label:`% Passed Items`,value:`${Math.round(100*n.passed/n.ran)}%`},rest:[{key:`score`,label:`Score`,value:Yi(n)==null?`—`:`${Yi(n)}%`},r]}:e.evals.length&&qi(e.status)&&ja(e,t)==null?{lead:{key:`pct`,label:`% Passed Items`,value:Ea(e)},rest:[r]}:{lead:r,rest:[]}}function Oa(e){return e?.timed?Pi(e.ms/e.timed):null}function ka(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return`—`;let n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`}function Aa(e){let t=ji(e.status);return e.status===`queued`?{state:t,detail:e.behind?`behind ${e.behind}`:`next in line`}:e.status===`running`?{state:t,detail:e.progress.current||``}:null}function ja(e,t){return L().overallVerdict(e.outcomes[t]??[],e.snapshot.pass)}function Ma(e,t){let n=e.content?.type===`source`?e.content.source:null;return n===`samples`?`/api/samples/thumbs/${encodeURIComponent(t)}`:n?`/api/sources/${encodeURIComponent(n)}/thumbs/${encodeURIComponent(t)}`:``}function Na(e,t){let n=e.content?.type===`source`?e.content.source:null;return n===`samples`?`/api/samples/zoom/${encodeURIComponent(t)}`:n?`/api/sources/${encodeURIComponent(n)}/zoom/${encodeURIComponent(t)}`:`/api/samples/zoom/${encodeURIComponent(t)}`}var Pa=(e,t)=>t==null||t===``?null:`${e}: ${t}`,Fa=e=>(e||[]).map(String).join(`, `),Ia=e=>e.length?e.every(t=>t===e[0])?String(e[0]):e.join(` → `):``,La=e=>{let t=L().OUTPUT_KINDS[L().lastKind(e)??L().defaultKind()];return t?!t.terms:!1},Ra=e=>{let t=e.metric&&String(e.metric)||L().METRICS[e.type]?.label||e.type,n=L().metricCheck(e);return[e.not?`not`:``,`${t}${n?` ${n}`:``}`,e.weight===0?`(watched, not scored)`:typeof e.weight==`number`&&e.weight!==1?`×${e.weight}`:``].filter(Boolean).join(` `)};function za(e,t,n,r){let i=L().readCase(t,n,La(e)),{stages:a,connections:o}=L().stagesFor(e,r),s=o.map(e=>L().connectionSettings(e)),c=e=>Ia(s.map(e)),l=L().evalsDataset(e);return[`An eval case is failing.`,``,`## The case`,Pa(`item`,L().caseItem(t)),Pa(`case id`,t.id),Pa(`note`,t.note),...(t.metrics||[]).map((e,t)=>Pa(`metric ${t+1}`,Ra(e))),``,`## What came back`,Pa(`verdict`,i.pass?`pass`:`fail`),Pa(`score`,i.score==null?`—`:`${Math.round(i.score*100)}%`),Pa(`items`,Fa(n?.terms)||`(none)`),Pa(`missed`,Fa((i.missed??[]).map(e=>Array.isArray(e)?e.join(` / `):e))),Pa(`invented`,Fa(i.invented)),Pa(`dropped`,Fa((n?.dropped||[]).map(e=>`${e.item} (${e.by})`))),Pa(`reasons`,Fa(i.reasons)),Pa(`error`,n?.error),Pa(`took`,n?.ms==null?null:`${n.ms} ms`),``,`## How it was asked`,Pa(`scenario`,`${r+1} of ${L().targetsOf(e).length}`),Pa(`model`,c(e=>e.model)),Pa(`endpoint`,c(e=>e.url||`(the lab's own Ollama)`)),Pa(`connection type`,c(e=>Ci(String(e.type??``)))),Pa(`image`,a[0]?.withImage?Ba(s[0]):`no image`),Pa(`seed`,c(e=>e.seed||`1234`)),Pa(`reply tokens`,c(e=>e.nPredict||e.maxTokens||`not set`)),Pa(`repeat penalty`,c(e=>e.repeatPenalty||`(profile default)`)),Pa(`other decoding`,Va(s.at(-1))),Pa(`modifiers`,(L().outOf(e.jobs.at(-1))?.modifiers||[]).map(e=>`${L().MODIFIERS[e.type]?.label??e.type}: ${L().modifierSummary(e)}`).join(`; `)||`none`),``,`## The prompt`,...a.flatMap((e,t)=>[a.length>1?`job ${t+1}${e.withImage?` (with image)`:``}, answering as ${e.kind}, on ${String(o[t]?.name||`unnamed`)}:`:null,e.text]),``,`## Where things live`,l?`the graded set: ${l.name||l.id} (this case is id "${t.id}")`:null,`the parser and scorer, shared by the lab, the CLI and CI: evals-core.ts`,`what the grading means: the dataset's README`].filter(e=>e!==null).join(`
|
|
5
|
-
`)}function Ba(e){let{px:t,format:n}=L().connectionImage(e);return`${t==null?`default budget`:L().budgetLabel(t)}, ${n.replace(`image/`,``).toUpperCase()}`}function Va(e){let t=(t,n)=>String(e?.[t]??``).trim()?[`${n} ${e?.[t]}`]:[];return[...t(`frequencyPenalty`,`frequency`),...t(`presencePenalty`,`presence`),...String(e?.dryMultiplier??``).trim()?[`DRY`]:[],...String(e?.grammar??``).trim()?[`grammar`]:[]].join(`, `)}function Ha(e,t){let n=[];return!qi(e.status)||!L().evalsDataset(e.snapshot)||(e.results||[]).forEach((r,i)=>{r&&!r.unrun&&(r.scenarios||[]).forEach((a,o)=>{let s=t.find(e=>L().caseItem(e)===r.name);ea(e,i,o)&&s&&a.res&&n.push({kase:s,res:a.res,scenarioIndex:o,item:r.name??``})})}),n}var Ua=e=>{let t=Math.min(...e),n=Math.max(...e);return t===n?String(t):`${t}–${n}`};function Wa(e,t,n){let r=L().evalsDataset(e.snapshot);if(!qi(e.status)||!r)return[];let i=e.outcomes[n]?.find(t=>e.evals.find(e=>e.id===t.id&&L().casesRef(e))),a=new Map(t.map(e=>[L().caseItem(e),e])),o=new Map,s=(e,t,n,r,i,a)=>{let s=o.get(e);s||(s={key:e,label:n,note:null,files:[],rank:t,counts:[],limits:[]},o.set(e,s)),s.files.includes(r)||s.files.push(r),i!=null&&s.counts.push(i),a!=null&&s.limits.push(a)};return e.results.forEach((e,t)=>{if(!e||e.unrun||!e.name)return;let r=a.get(e.name),o=e.scenarios?.[n]?.res,c=i?.items[t];if(!r||r.todo||!o||!c||L().isSkipped(c)||c.pass)return;let l=e.name;if(o.error){s(`error`,6,`Error`,l);return}let u=(o.terms||[]).length,d=(r.metrics||[]).filter(e=>e.type===`item-count`&&e.weight!==0),f=(c.metrics??[]).filter(e=>e.type===`item-count`&&e.weight!==0);d.forEach((e,t)=>{let n=f[t];if(e.not||!n||n.pass)return;let r=e.max==null||e.max===``?null:Number(e.max),i=e.min==null||e.min===``?null:Number(e.min);r!=null&&u>r?s(`over`,0,`Too many items`,l,u,r):i!=null&&s(`under`,1,`Too few items`,l,u,i)});for(let e of c.missed??[])Array.isArray(e)?s(`none:${e.join(`/`)}`,3,`None of ${e.join(` / `)}`,l):s(`missed:${e}`,2,`Missed ${e}`,l);for(let e of c.invented??[])s(`invented:${e}`,4,`Invented ${e}`,l)}),[...o.values()].sort((e,t)=>e.rank-t.rank||t.files.length-e.files.length||e.label.localeCompare(t.label)).map(({key:e,label:t,files:n,counts:r,limits:i})=>({key:e,label:t,files:n,note:r.length&&i.length?`${Ua(r)}, ${e===`over`?`max`:`min`} ${Ua(i)}`:null}))}var Ga=[{id:`home`,label:`Home`,icon:et,built:!0},{id:`runs`,label:`Runs`,icon:Yt,built:!0},{id:`history`,label:`History`,icon:Ze,built:!0},{id:`library`,label:`Library`,icon:mt,built:!0},{id:`setup`,label:`Setup`,icon:Ne,built:!0}],Ka=e=>e.replace(/[^A-Za-z0-9._-]+/g,`-`).replace(/^[-.]+|[-.]+$/g,``);function qa(e=new Date){let t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}${t(e.getMonth()+1)}${t(e.getDate())}-${t(e.getHours())}${t(e.getMinutes())}`}function Ja(e,t,n,r,i=new Date){return`${e}-${Ka(t)||e}-v${n}-${qa(i)}.${r}`}function Ya(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(n),0)}var Xa=()=>Fr({tab:`library`,section:`datasets`,id:null}),Za=e=>Fr({tab:`library`,section:`datasets`,id:e}),Qa=()=>Ir({tab:`library`,section:`datasets`,id:null}),$a=(e,t=location.hash)=>`/w/${encodeURIComponent(e)}${t}`,eo=`promptlab.ws.undo`;function to(e){try{localStorage.setItem(eo,JSON.stringify(e))}catch{}}function no(){let e=null;try{e=localStorage.getItem(eo),localStorage.removeItem(eo)}catch{return null}if(!e)return null;try{let t=JSON.parse(e);return t&&t.id&&t.slug&&t.name?{id:t.id,slug:t.slug,name:t.name}:null}catch{return null}}function ro(e){let t=e.filter(e=>!e.archived);return t.length?[...t].sort((e,t)=>(t.lastUsed??``).localeCompare(e.lastUsed??``)||Number(t.isDefault)-Number(e.isDefault))[0]??null:null}var io=(0,X.createContext)({current:{id:`default`,slug:`default`,name:`Default`,archived:!1,isDefault:!0},requestedSlug:null,list:[],switchTo:()=>{}}),ao=()=>(0,X.useContext)(io),oo=1600,so=(0,X.createContext)(null);function co({children:e}){let t=ao(),[n,r]=(0,X.useState)(null),i=(0,X.useRef)(null);(0,X.useEffect)(()=>()=>{i.current&&clearTimeout(i.current)},[]);let a=t.current?.slug??null,o=(0,X.useCallback)(e=>{a&&Ft(lo(a,e)).then(e=>{r(e?`Copied to clipboard.`:`Could not copy.`),i.current&&clearTimeout(i.current),i.current=setTimeout(()=>r(null),oo)})},[a]);return(0,$.jsxs)(so.Provider,{value:o,children:[e,n&&(0,$.jsx)(`div`,{className:`undo-toast copy-link-said`,role:`status`,children:(0,$.jsx)(`span`,{className:`undo-label`,children:n})})]})}var lo=(e,t)=>`${location.origin}${$a(e,Pr(t))}`;function uo(){let e=(0,X.useContext)(so),t=ao();return(0,X.useCallback)(n=>({label:`Copy link`,icon:M.link,onSelect:()=>{e?e(n):t.current&&Ft(lo(t.current.slug,n))}}),[e,t.current])}var fo={"eval-group":{noun:`eval group`,href:e=>Pr({tab:`library`,section:`datasets`,id:e})},"filter-set":{noun:`filter set`,href:e=>Pr({tab:`library`,section:`filters`,id:e})},prompt:{noun:`prompt`,href:e=>Pr({tab:`library`,section:`prompts`,id:e})},source:{noun:`Source`,href:e=>Pr({tab:`library`,section:`sources`,id:e})},pipeline:{noun:`pipeline`,href:e=>Pr({tab:`runs`,id:e})}};function po(e){let t=new Set,n=new Set,r=new Set,i=new Set,a=(e,t)=>{typeof t==`string`&&t&&e.add(t)},o=Array.isArray(e?.evals)?e.evals:[];for(let e of o)a(t,e?.group?.id),a(t,e?.dataset?.id);for(let t of e?.targets??[])for(let e of t?.steps??[])a(n,e?.from?.id);for(let t of e?.jobs??[])for(let e of t?.steps??[])if(e?.content?.type===`source`&&a(i,e.content.ref?.id),Array.isArray(e?.filterSets))for(let t of e.filterSets)a(r,t?.set?.id);let s=L().profileIds(e)??[];return{groups:[...t],prompts:[...n],filterSets:[...r],sources:[...i],profiles:s}}var mo=(e,t)=>e?.find(e=>e.id===t)?.name||t;function ho(e,t){if(e.kind===`pipeline`){let n=t.pipelines.find(t=>t.id===e.id);if(!n)return[];let r=po(n.work),i=[],a=(e,t,n)=>{for(let r of t)i.push({kind:e,id:r,name:mo(n,r),href:fo[e].href(r)})};return a(`eval-group`,r.groups,t.groups),a(`prompt`,r.prompts,t.prompts),a(`filter-set`,r.filterSets,t.filterSets),a(`source`,r.sources,t.sources),i}let n={"eval-group":`groups`,"filter-set":`filterSets`,prompt:`prompts`,source:`sources`}[e.kind];return t.pipelines.filter(t=>po(t.work)[n].includes(e.id)).map(e=>({kind:`pipeline`,id:e.id,name:e.name,href:fo.pipeline.href(e.id)}))}function go({subject:e,scan:t,undo:n,onClose:r,onChanged:i,accountShare:a}){let o=Z(),s=ao();return s.current?(0,$.jsx)(ht,{api:o,subject:e,workspaces:s.list,current:s.current,dependents:ho(e,t),undo:n,onClose:r,onChanged:i,accountShare:a}):null}function _o({undo:e}){let t=uo(),n=hr(),{list:r,error:i}=gr(),[a]=Q(`promptlab.workflows`),[o,s]=W(`eval-groups`,20),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)(null),g=(0,X.useRef)(null),[,v]=(0,X.useState)(0);(0,X.useEffect)(()=>n.subscribe(()=>v(e=>e+1)),[n]),(0,X.useEffect)(()=>{for(let e of r??[])n.load(e.id)},[r,n]);let y=e=>d(e instanceof Error?e.message:String(e)),b=(0,X.useMemo)(()=>{let e=new Map;for(let t of a.list)for(let n of t.work.evals??[]){if(n.type!==`group`)continue;let r=n,i=r.group?.id??r.own?.casesFrom?.id;if(!i)continue;let a=e.get(i)??{names:[],pinned:!1};a.names.includes(t.name)||a.names.push(t.name),typeof r.pin==`number`&&(a.pinned=!0),e.set(i,a)}return e},[a.list]),x=(r??[]).map(e=>({...e,body:n.entry(e.id)?.doc?.body??null,links:b.get(e.id)??{names:[],pinned:!1}})),S=()=>new Set((n.list().list??[]).map(e=>e.name)),w=async()=>{d(null);try{Za((await n.create(yo(`Untitled eval group`,S()))).id)}catch(e){y(e)}},T=async t=>{d(null);try{await n.flush(t.id);let r=await n.remove(t.id);e.offer({label:`Deleted ${t.name}`,restore:()=>{n.restore(r).catch(y)}})}catch(e){y(e)}},D=async e=>{d(null);let t;try{t=await vo(e)}catch(e){y(e);return}let r;try{r=JSON.parse(t)}catch(e){d(`Not JSON: ${e instanceof Error?e.message:String(e)}`);return}p(`import`);try{let e=await n.importFile(r);e[0]&&Za(e[0].id)}catch(e){y(e)}finally{p(null)}},O=async()=>{p(`exportAll`);try{let e=await fetch(n.exportAllUrl());if(!e.ok)throw Error(`the export answered ${e.status}`);let t=await e.json();Ya(new Blob([JSON.stringify(t,null,2)+`
|
|
6
|
-
`],{type:`application/json`}),Ja(`eval-groups`,`all`,t.version,`json`))}catch(e){y(e)}finally{p(null)}},k=e=>[{label:`Open`,icon:Ie,onSelect:()=>Za(e.id)},t({tab:`library`,section:`datasets`,id:e.id}),{label:`Copy or move…`,icon:M.transfer,onSelect:()=>h(e)},{label:`Delete`,icon:M.remove,destructive:!0,onSelect:()=>void T(e)}],A=e=>e.scoring.mode===`weighted`?`Points`:`All`,j=[{key:`group`,header:`Eval group`,role:`title`,sort:e=>e.name.toLowerCase(),cell:e=>(0,$.jsx)(`button`,{type:`button`,className:`eg-open`,onClick:()=>Za(e.id),children:e.name})},{key:`preview`,header:`Preview Source`,sort:e=>e.preview?.name??``,tdProps:e=>({"data-state":e.preview?void 0:`none`}),cell:e=>e.preview?.name??`None`},{key:`cases`,header:`Cases`,className:`num`,sort:e=>e.cases,cell:e=>e.cases},{key:`every`,header:`Every item`,className:`num`,sort:e=>e.body?.every.length??-1,cell:e=>e.body?e.body.every.length:`…`},{key:`scoring`,header:`Scoring`,sort:e=>e.body?A(e.body):``,cell:e=>e.body?A(e.body):`…`},{key:`linked`,header:`Linked by`,sort:e=>e.links.names.length,tdProps:e=>({"data-state":e.links.names.length?void 0:`none`}),cell:e=>e.links.names.length?(0,$.jsx)(`span`,{title:e.links.names.join(`, `),children:`${e.links.names.length} ${e.links.names.length===1?`pipeline`:`pipelines`}${e.links.pinned?`, pinned`:``}`}):`—`},{key:`menu`,header:``,label:``,role:`menu`,sort:null,cell:e=>(0,$.jsx)(Y,{label:`${e.name} actions`,actions:k(e)})}],N=[{label:`Import JSON…`,icon:K,busy:f===`import`,onSelect:()=>g.current?.click()},{label:`Export all`,icon:jn,disabled:!r?.length,busy:f===`exportAll`,onSelect:()=>void O()},{label:`Page size…`,icon:M.pageSize,onSelect:()=>l(!0)}];return(0,$.jsxs)(E,{id:`evals`,title:`Evals`,note:r?String(r.length):void 0,actions:N,about:`Checks of a reply, defined once and linked by the pipelines they grade.`,children:[(0,$.jsx)(`input`,{ref:g,type:`file`,accept:`.json,application/json`,hidden:!0,"aria-label":`Import JSON file`,onChange:e=>{let t=e.target.files?.[0];e.target.value=``,t&&D(t)}}),r===null?(0,$.jsx)(C,{label:`Eval groups`,error:i,onRetry:()=>void n.refresh()}):r.length===0?(0,$.jsx)(`p`,{className:`note`,children:`No eval groups yet.`}):(0,$.jsx)(J,{className:`eg-groups`,cards:!0,label:`Eval groups`,rows:x,rowKey:e=>e.id,pageSize:o,columns:j}),u&&(0,$.jsx)(`p`,{className:`note bad`,role:`alert`,children:u}),(0,$.jsxs)(`button`,{type:`button`,className:`ghost eg-add`,onClick:()=>void w(),children:[(0,$.jsx)(ze,{size:14,"aria-hidden":`true`}),`Add eval group`]}),c&&(0,$.jsx)(_,{value:o,onChange:s,onClose:()=>l(!1)}),m&&(0,$.jsx)(go,{subject:{kind:`eval-group`,id:m.id,name:m.name},scan:{pipelines:a.list},undo:e,onClose:()=>h(null),onChanged:()=>void n.refresh()})]})}function vo(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result??``)),r.onerror=()=>n(r.error??Error(`The file could not be read.`)),r.readAsText(e)})}var yo=(e,t)=>{if(!t.has(e))return e;for(let n=2;;n++)if(!t.has(`${e} ${n}`))return`${e} ${n}`};function bo(e){return[e.every&&`Every reply`,e.not&&`Not`,e.of===`said`&&`Raw reply`,e.weight!=null&&`Weight ${e.weight}`].filter(Boolean).join(`, `)}var xo=(e,t)=>({type:e,...L().METRICS[e].defaults(),...t?.weight==null?{}:{weight:t.weight},...t?.not?{not:!0}:{},...t?.metric?{metric:t.metric}:{}});function So({label:e,metrics:t,set:n,undoable:r,over:i=`item`,rawReply:o}){let s=L(),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(null),f=(e,r)=>n(t.map((t,n)=>n===e?r:t)),p=e=>{c===`new`?n([...t,xo(e)]):typeof c==`number`&&f(c,xo(e,t[c])),l(null)};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(tt,{noun:`metric`,items:[...t],empty:(0,$.jsx)(`p`,{className:`note`,children:`No metrics.`}),onAdd:()=>l(`new`),onRemove:e=>r(t.filter((t,n)=>n!==e),`Removed a metric`),onRename:e=>d(e),extra:(e,t)=>[{label:`Change type…`,icon:Gn,onSelect:()=>l(t)}],renderItem:(t,n,r)=>{let c=s.METRICS[t.type],l=(t.metric||c?.label||t.type)+(t.not?` (not)`:``)+(t.weight===0?` (watch)`:``),u=`${e.replace(/\W+/g,`-`).toLowerCase()}-metric-${n}`,d=!!(t.every||t.not||t.of||t.weight!=null),p=!c?.parsedOnly&&(o!==!1||t.of===`said`),m=!c?.expects||!!t.not,h=(c?.options??[]).map(e=>St(e,t,e=>f(n,e)));return(0,$.jsx)(E,{id:u,title:l,level:3,actions:r,about:c?.description,children:(0,$.jsxs)(re,{children:[h.length>0&&(0,$.jsx)(a,{label:`${e}, metric ${n+1}`,rows:h}),(0,$.jsx)(E,{id:`${u}-counts`,title:`Options`,level:3,open:d,note:d?bo(t):`Defaults`,children:(0,$.jsx)(a,{label:`${e}, metric ${n+1}, options`,rows:[...i===`run`?[{key:`every`,label:`Every reply`,control:{type:`checkbox`,checked:!!t.every,onChange:e=>{let{every:r,...i}=t;f(n,e?{...i,every:!0}:i)}}}]:[],...m?[{key:`not`,label:`Not`,control:{type:`checkbox`,checked:!!t.not,onChange:e=>{let{not:r,...i}=t;f(n,e?{...i,not:!0}:i)}}}]:[],...p?[{key:`of`,label:`Reads`,...o==null?{hint:`Raw reply: the API's text before Read as`}:{},control:{type:`select`,value:t.of??`reply`,options:[{value:`reply`,label:`Parsed reply`},{value:`said`,label:`Raw reply`}],onChange:e=>{let{of:r,...i}=t;f(n,e===`said`?{...i,of:`said`}:i)}}}]:[],{key:`weight`,label:`Weight`,width:`quarter`,control:{type:`text`,value:t.weight==null?``:String(t.weight),placeholder:`1`,onChange:e=>{let{weight:r,...i}=t;f(n,e.trim()?{...i,weight:/^-?\d+(\.\d+)?$/.test(e.trim())?Number(e):e}:i)}}}]})})]})},n)}}),u!==null&&t[u]&&(0,$.jsx)(Tt,{title:`Rename metric`,value:t[u].metric||s.METRICS[t[u].type]?.label||t[u].type,onCommit:e=>{let{metric:n,...r}=t[u];f(u,e&&e!==s.METRICS[r.type]?.label?{...r,metric:e}:r)},onClose:()=>d(null)}),c!==null&&(0,$.jsx)(Co,{title:c===`new`?`Add metric`:`Change type`,current:typeof c==`number`?t[c]?.type??null:null,over:i,onPick:p,onClose:()=>l(null)})]})}function Co({title:e,current:t,over:n,onPick:r,onClose:i}){let[a,o]=(0,X.useState)(``),s=(0,X.useMemo)(()=>{let e=new Map;for(let[t,r]of Object.entries(L().METRICS)){if(n===`run`&&(r.graded||r.perItem))continue;let i=`${r.label} ${r.description??``}`.toLowerCase();if(a.trim()&&!i.includes(a.trim().toLowerCase()))continue;let o=r.family??`Other`;e.set(o,[...e.get(o)??[],{id:t,label:r.label,description:r.description??``}])}return[...e]},[a,n]);return(0,$.jsxs)(b,{title:e,onClose:i,className:`metric-picker`,children:[(0,$.jsx)(`input`,{type:`search`,className:`mp-search`,"aria-label":`Find a metric`,placeholder:`Find a metric`,value:a,onChange:e=>o(e.target.value),autoComplete:`off`}),s.length===0&&(0,$.jsx)(`p`,{className:`note`,children:`No metric matches.`}),s.map(([e,n])=>(0,$.jsxs)(`fieldset`,{className:`mp-family`,children:[(0,$.jsx)(`legend`,{children:e}),(0,$.jsx)(`div`,{className:`mp-grid`,children:n.map(e=>(0,$.jsx)(`button`,{type:`button`,className:`mp-type${e.id===t?` on`:``}`,...e.id===t?{"aria-current":`true`}:{},title:e.description,onClick:()=>r(e.id),children:e.label},e.id))})]},e))]})}function wo(e,t,n=[]){return{options:[...n.map(e=>({...e,fixed:!0})),...e.map(e=>{let n=t(e.id);return{id:e.id,label:e.name||`Untitled`,used:n?{at:n,label:ki(n)}:null}})],recent:e.filter(e=>t(e.id)).sort((e,n)=>t(n.id).localeCompare(t(e.id))).slice(0,5).map(e=>e.id)}}function To({name:e,body:t,onSave:n,onClose:r}){let[i]=(0,X.useState)(()=>JSON.stringify(t,null,2)),[a,o]=(0,X.useState)(i),[s,c]=(0,X.useState)(()=>Do(a));(0,X.useEffect)(()=>{let e=setTimeout(()=>c(Do(a)),400);return()=>clearTimeout(e)},[a]);let l=s.problems;return(0,$.jsxs)(b,{title:`Edit raw… ${e}`,onClose:r,wide:!0,dirty:a!==i,children:[(0,$.jsx)(`textarea`,{className:`raw-content`,"aria-label":`Dataset JSON`,spellCheck:!1,value:a,onChange:e=>o(e.target.value)}),(0,$.jsxs)(`div`,{className:`raw-foot`,children:[(0,$.jsx)(`span`,{className:`note ${l.length?` bad`:``}`,role:l.length?`alert`:void 0,children:l.length?`${l.length} to fix — ${l.join(`, `)}`:`Validated before it is accepted.`}),(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:r,children:`Cancel`}),(0,$.jsx)(`button`,{type:`button`,className:`run`,onClick:()=>{let e=Do(a);e.body?n(e.body):c(e)},disabled:l.length>0,children:`Save & Close`})]})]})}var Eo=[`version`,`source`,`scoring`,`grader`,`every`,`run`,`cases`];function Do(e){let t;try{t=JSON.parse(e)}catch(e){return{body:null,problems:[`Not JSON: ${e instanceof Error?e.message:String(e)}`]}}if(!t||typeof t!=`object`||Array.isArray(t))return{body:null,problems:[`a dataset has to be a JSON object`]};let n=t,r=[];for(let e of Object.keys(n))Eo.includes(e)||r.push(`${e} is not part of a dataset`);Array.isArray(n.cases)||r.push(`cases has to be a list`);let i=L().DATASET_BODY_VERSION;if(`version`in n&&n.version!==i&&r.push(`version has to be ${i}`),r.length)return{body:null,problems:r};let a=er(),o={version:i,scoring:n.scoring??a.scoring,grader:n.grader??null,every:n.every??[],run:n.run??[],cases:n.cases};return r.push(...L().validateEvals(o)),r.length?{body:null,problems:r}:{body:o,problems:[]}}function Oo(e,t){return`/api/sources/${encodeURIComponent(e)}/thumbs/${encodeURIComponent(t)}`}function ko(e){return/\.(?:jpe?g|png|gif|webp|bmp|heic|heif|dng|tiff?)$/i.test(e)}function Ao(e){let t=Z(),[n,r]=(0,X.useState)(null);return(0,X.useEffect)(()=>{if(!e)return;let n=!0;return t.source(e).then(t=>{n&&r({id:e,files:t.files.map(e=>e.name)})}).catch(()=>{n&&r(null)}),()=>{n=!1}},[t,e]),e&&n?.id===e?n.files:null}function jo({title:e,action:t,start:n,taken:r,initial:i=``,onPick:o,onClose:s}){let c=Z(),[l,u]=(0,X.useState)(null);(0,X.useEffect)(()=>{let e=!0;return c.sources().then(t=>{e&&u(t.sources)}).catch(()=>{e&&u([])}),()=>{e=!1}},[c]);let[d,f]=(0,X.useState)(n),p=Ao(d?.id),m=(0,X.useMemo)(()=>(p??[]).filter(e=>!r.has(e)),[p,r]),[h,g]=(0,X.useState)(i),[_,v]=(0,X.useState)(!!i);(0,X.useEffect)(()=>{!_&&m[0]&&g(m[0])},[_,m]);let[y,x]=(0,X.useState)(``),S=m.filter(e=>!y.trim()||e.toLowerCase().includes(y.trim().toLowerCase())),C=h.trim(),w=!!C&&r.has(C),T=[{key:`browse`,label:`Browse`,control:{type:`picker`,kind:`Source`,value:d?.id??``,usedLabel:`Last changed`,...wo(l??(n?[n]:[]),e=>l?.find(t=>t.id===e)?.changed??null,[{id:``,label:`None`}]),onChange:e=>{let t=l?.find(t=>t.id===e)??(n?.id===e?n:null);f(t?{id:t.id,name:t.name}:null),v(!0),x(``)}}},{key:`item`,label:`Item`,width:`full`,control:{type:`text`,value:h,onChange:e=>{v(!0),g(e)}}}];return(0,$.jsxs)(b,{title:e,onClose:s,className:`item-picker`,footer:(0,$.jsxs)(`div`,{className:`edit-actions`,children:[w&&(0,$.jsxs)(`span`,{className:`note bad`,role:`alert`,children:[C,` has a case`]}),(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:s,children:`Cancel`}),(0,$.jsx)(`button`,{type:`button`,className:`edit-done`,disabled:!C||w,onClick:()=>o(C),children:t})]}),children:[(0,$.jsx)(a,{label:e,rows:T}),d&&p&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`input`,{type:`search`,className:`ip-search`,"aria-label":`Find an item`,placeholder:`Find an item`,value:y,onChange:e=>x(e.target.value),autoComplete:`off`}),(0,$.jsxs)(`fieldset`,{className:`ip-items`,children:[(0,$.jsxs)(`legend`,{className:`note`,children:[m.length,` `,m.length===1?`item`:`items`,` without a case`]}),m.length?S.length?S.map(e=>(0,$.jsxs)(`label`,{className:`ip-item${e===C?` on`:``}`,children:[(0,$.jsx)(`input`,{type:`radio`,name:`item`,checked:e===C,onChange:()=>g(e)}),ko(e)?(0,$.jsx)(`img`,{src:Oo(d.id,e),alt:``,loading:`lazy`}):(0,$.jsx)(`span`,{className:`ip-thumb`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`ip-name`,children:e})]},e)):(0,$.jsx)(`p`,{className:`note`,children:`No item matches.`}):(0,$.jsxs)(`p`,{className:`note`,children:[`Every item of `,d.name,` has a case.`]})]})]})]})}var Mo=2e3,No=e=>({id:``,item:e,todo:!0,note:``,metrics:[]}),Po=e=>{let t=e.map(e=>/^sample-(\d+)$/.exec(String(e?.id??``))?.[1]??0);return`sample-${String(Math.max(0,...t.map(Number))+1).padStart(3,`0`)}`};function Fo({item:e,cases:t,onWrite:n,problem:r,resultFor:a,scenarioCount:o,plain:s=!1,files:c,onFile:l,onClose:u,run:d,source:f=null,sourceFiles:p=null,onRemove:m}){let h=t.find(t=>L().caseItem(t)===e),g=!h,[_,v]=(0,X.useState)(()=>structuredClone(h??No(e))),[y,b]=(0,X.useState)(0),[x,S]=(0,X.useState)(null),[C,w]=(0,X.useState)(null),[T,E]=(0,X.useState)(!1),[D,O]=(0,X.useState)(!1),[k,A]=(0,X.useState)(!1),j=(0,X.useRef)(_);j.current=_;let M=(0,X.useRef)(t);M.current=t;let N=(0,X.useRef)(null),P=t=>M.current.filter(n=>!(t.id&&n.id===t.id)&&!(!t.id&&L().caseItem(n)===e)).some(e=>L().caseItem(e)===L().caseItem(t))?`${L().caseItem(t)} has a case already`:L().validateEvals({cases:[{...t,id:t.id||`new`}]})[0]?.replace(/^[^:]*: /,``)??null,F=P(_),I=(0,X.useCallback)(()=>{let e=j.current;if(P(e))return!1;e.id||(e={...e,id:Po(M.current)},j.current=e,v(e));let t=e;return n(e=>Io({cases:e},t)),!0},[n,e]);(0,X.useEffect)(()=>()=>{N.current&&clearTimeout(N.current)},[]);let[R,z]=(0,X.useState)(!1),B=e=>{v(e),z(!0)},ee=e=>{let t=j.current;B({...t,metrics:e,...t.todo&&!(t.metrics??[]).length&&e.length?{todo:!1}:{}})},V=C&&C[y]?C[y]:a(y),H=!V||_.todo||!(_.metrics??[]).length?null:L().readCase(_,V,s),te=async()=>{if(d&&!T){E(!0),S(null);try{let e=await d(L().caseItem(j.current));w(e),S(e.length?null:`No reply to grade.`)}catch(e){S(e instanceof Error?e.message:String(e))}finally{E(!1)}}},U=c.indexOf(e),W=e=>{let t=U<0?null:c[U+e];if(!t)return;let n=R||g;(!n||I())&&(n&&(O(!0),N.current&&clearTimeout(N.current),N.current=setTimeout(()=>O(!1),Mo)),l(t))};(0,X.useEffect)(()=>{let e=e=>{(e.key===`ArrowLeft`||e.key===`ArrowRight`)&&(e.target?.closest?.(`input, textarea, select, [contenteditable]`)||(e.preventDefault(),W(e.key===`ArrowRight`?1:-1)))};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)});let ne=()=>{(!R&&!g||I())&&u()},G=L().caseItem(_),re=new Set(t.filter(t=>!(_.id&&t.id===_.id)&&L().caseItem(t)!==e).map(e=>L().caseItem(e))),ie=!!p&&!p.includes(G),ae=[{key:`item`,label:`Item`,control:f?{type:`static`,text:ie?`${G||`None`} (missing)`:G}:{type:`text`,value:G,onChange:e=>B({...j.current,item:e.trim()})}},{key:`todo`,label:`To do`,control:{type:`checkbox`,checked:!!_.todo,label:`Not graded yet`,onChange:e=>B({...j.current,todo:e})}},{key:`note`,label:`Note`,control:{type:`textarea`,value:_.note??``,onChange:e=>B({...j.current,note:e})}}],K=[];o>1&&K.push({key:`scenario`,label:`Show result of`,control:{type:`select`,value:String(y),options:Array.from({length:o},(e,t)=>({value:String(t),label:`Target ${L().targetLetter(t)}`})),onChange:e=>b(Number(e))}}),H&&(K.push({key:`verdict`,label:`Result`,control:{type:`static`,text:H.pass?`Pass`:`Fail`}}),H.watch.length&&K.push({key:`watch`,label:`Watch`,control:{type:`static`,text:`${H.watch.filter(e=>e.pass).length} of ${H.watch.length}`}}));let q=f&&G&&ko(G)&&p?.includes(G)?{src:Oo(f.id,G),file:G,source:f.name}:null,oe=[...q?[{key:`preview`,title:`Preview`,children:(0,$.jsxs)(`div`,{className:`cf-preview`,children:[(0,$.jsx)(`img`,{src:q.src,alt:q.file,loading:`lazy`}),(0,$.jsxs)(`p`,{className:`note`,children:[q.file,` in `,q.source]})]})}]:[],{key:`case`,title:`Case`,rows:ae},{key:`metrics`,title:`Metrics`,children:(0,$.jsx)(So,{label:`${G||`Case`} metrics`,metrics:_.metrics??[],set:ee,undoable:ee})},...K.length?[{key:`result`,title:`Result`,rows:K}]:[]],se=[{label:`Previous`,icon:i,disabled:U<=0,onSelect:()=>W(-1)},{label:`Next`,icon:lt,disabled:U<0||U>=c.length-1,onSelect:()=>W(1)},...d?[{label:`Run`,icon:Hn,disabled:T,onSelect:()=>void te()}]:[]],ce=[{label:`Change item…`,icon:Un,onSelect:()=>A(!0)},...m?[{label:`Remove`,icon:Lt,destructive:!0,onSelect:()=>{m(L().caseItem(j.current)),u()}}]:[]],le=x??r??(F?`Not saved: ${F}`:null);return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ut,{title:G||`Case`,status:le??(T?`Running…`:D?`Saved.`:void 0),...le?{statusBad:!0}:{},sections:oe,...ce.length?{menu:ce}:{},actions:se,dirty:R,onSave:ne,onClose:u}),k&&(0,$.jsx)(jo,{title:`Change item`,action:`Change`,start:f,taken:re,onPick:e=>{A(!1),B({...j.current,item:e})},onClose:()=>A(!1)})]})}function Io(e,t){let n=e.cases.findIndex(e=>e.id===t.id),r=structuredClone(e.cases);return n>=0?r[n]=structuredClone(t):r.push(structuredClone(t)),r}function Lo(e,t){return structuredClone(e.cases).filter(e=>L().caseItem(e)!==t)}var Ro=(0,X.createContext)(null);function zo({children:e}){let t=hr(),[n,r]=(0,X.useState)(null),i=_r(n?.dataset??null),a=(0,X.useCallback)((e,t)=>{r({item:e,...t})},[]),o=(0,X.useCallback)(e=>{r(t=>t&&{...t,item:e})},[]),s=i?.doc?.preview??null,c=Ao(s?.id),l=n?.dataset??``,u=(0,X.useCallback)(e=>{t.edit(l,t=>({...t,cases:e(t.cases)}))},[t,l]),d=(0,X.useMemo)(()=>({openCaseEditor:a}),[a]),f=i?.doc;return(0,$.jsxs)(Ro.Provider,{value:d,children:[e,n&&f&&(0,$.jsx)(Fo,{item:n.item,cases:f.body.cases,onWrite:u,problem:tr(i.sync),resultFor:n.resultFor??(()=>null),scenarioCount:n.scenarioCount??0,files:n.files??[],onFile:o,...n.run?{run:n.run}:{},...n.plain?{plain:!0}:{},source:s,sourceFiles:c,...n.onRemove?{onRemove:n.onRemove}:{},onClose:()=>r(null)},n.item)]})}function Bo(){let e=(0,X.useContext)(Ro);if(!e)throw Error(`useCaseEditor outside a CaseEditorProvider: the app mounts one at its root`);return e}function Vo({rows:e,shown:t,filters:n,onFilters:r,selected:i,onSelect:a,selectionActions:o,sourceFiles:s,noCase:c,pageSize:l,onEdit:u,onAdd:f,onRemove:p,loading:m,loadError:h,onRetry:g,children:_}){let v=t.map(zr),y=v.filter(e=>i.has(e)).length,b=y>0&&y===v.length,x=t=>e.filter(e=>$r(e,s)===t).length,S={label:`Status`,value:n.status,onChange:e=>r({status:e}),options:[{value:`all`,label:`All`},{value:`graded`,label:`Graded ${x(`graded`)}`},{value:`todo`,label:`To do ${x(`todo`)}`},...s&&c?[{value:`missing`,label:`Missing ${x(`missing`)}`},{value:`nocase`,label:`No case ${c.length}`}]:[]]},w=n.status===`nocase`&&c?c.filter(e=>!n.file.trim()||e.toLowerCase().includes(n.file.trim().toLowerCase())):null,T=[{key:`show`,label:`Show`,value:n.show,onChange:e=>r({show:e}),options:[{value:`all`,label:`All`},{value:`selected`,label:`Selected`}]}];return m?(0,$.jsxs)(`div`,{className:`ds-casebody`,children:[_,(0,$.jsx)(C,{label:`Cases`,error:h,onRetry:g})]}):(0,$.jsxs)(`div`,{className:`ds-casebody`,children:[(e.length>0||!!c?.length)&&(0,$.jsx)(d,{noun:`cases`,search:{label:`Item`,placeholder:`Search items`,value:n.file,onChange:e=>r({file:e})},filters:T,quick:S,...w?{}:{count:{shown:t.length,total:e.length}},lead:(0,$.jsx)(`label`,{className:`ev-check ev-all`,children:(0,$.jsx)(Ho,{all:b,some:y>0,disabled:!t.length,onChange:()=>a(e=>{let t=new Set(e);for(let e of v)b?t.delete(e):t.add(e);return t})})})}),_,w?w.length===0?(0,$.jsx)(`p`,{className:`note`,children:`No items match.`}):(0,$.jsx)(`div`,{className:`ds-cases`,children:(0,$.jsx)(J,{className:`dstable`,cards:!0,label:`Items with no case`,rows:w,pageSize:l,defaultSort:null,rowKey:e=>e,columns:[{key:`item`,header:`Item`,role:`title`,sort:e=>e,cell:e=>(0,$.jsx)(`button`,{type:`button`,className:`ds-file`,onClick:()=>f(e),children:e})},{key:`status`,header:`Status`,sort:()=>`No case`,cell:()=>(0,$.jsx)(`span`,{className:`ds-status ds-nocase`,children:`No case`})}]})}):e.length===0?(0,$.jsx)(`p`,{className:`ds-none`,children:`No cases.`}):(0,$.jsx)($.Fragment,{children:t.length===0?(0,$.jsxs)($.Fragment,{children:[i.size>0&&(0,$.jsx)(qt,{count:i.size,noun:`case`,hidden:i.size,actions:o,onClear:()=>a(()=>new Set)}),(0,$.jsx)(`p`,{className:`note`,children:`No cases match these filters.`})]}):(0,$.jsx)(`div`,{className:`ds-cases`,children:(0,$.jsx)(J,{className:`dstable`,cards:!0,label:`Cases`,rows:t,pageSize:l,defaultSort:null,rowKey:e=>zr(e),select:{noun:`case`,selected:i,onChange:e=>a(()=>e),actions:()=>o},columns:Uo(s,u,p)})})}),(0,$.jsxs)(`button`,{type:`button`,className:`ghost ds-add`,onClick:()=>f(),children:[(0,$.jsx)(ze,{size:14,"aria-hidden":`true`}),`Add case`]})]})}function Ho({all:e,some:t,disabled:n,onChange:r}){let i=(0,X.useRef)(null);return(0,X.useEffect)(()=>{i.current&&(i.current.indeterminate=t&&!e)},[t,e]),(0,$.jsx)(`input`,{ref:i,type:`checkbox`,"aria-label":`Select all shown`,checked:e,disabled:n,onChange:r})}function Uo(e,t,n){let r=t=>$r(t,e);return[{key:`item`,header:`Item`,role:`title`,sort:e=>e.item,cell:e=>(0,$.jsx)(`button`,{type:`button`,className:`ds-file`,onClick:()=>t(e.item),children:e.item})},{key:`status`,header:`Status`,sort:e=>Qr[r(e)],tdProps:e=>({"data-state":r(e)}),cell:e=>(0,$.jsx)(`span`,{className:`ds-status ds-${r(e)}`,children:Qr[r(e)]})},{key:`metrics`,header:`Metrics`,className:`num`,sort:e=>Wo(e).length,cell:e=>Wo(e).length},{key:`note`,header:`Note`,sort:e=>e.note??``,tdProps:e=>({"data-state":e.note?.trim()?void 0:`none`}),cell:e=>(0,$.jsx)(`span`,{className:`ds-note`,children:e.note})},{key:`menu`,header:``,label:``,role:`menu`,sort:null,cell:e=>(0,$.jsx)(Y,{label:`${e.item} actions`,actions:[{label:`Edit…`,icon:M.edit,onSelect:()=>t(e.item)},{label:`Remove`,icon:M.remove,destructive:!0,onSelect:()=>n(e.item)}]})}]}var Wo=e=>(e.metrics??[]).filter(e=>e.weight!==0),Go={bounds:`Set count`,addTerm:`Add term`,removeTerm:`Remove term`,todo:`Mark To do`,graded:`Mark graded`},Ko=[{value:`keep`,label:`Keep`},{value:`set`,label:`Set`},{value:`clear`,label:`Clear`}],qo=e=>/^\s*\d+\s*$/.test(e)?Number(e):null;function Jo({kind:e,cases:t,keys:n,onApply:r,onClose:i}){let[o,s]=(0,X.useState)(`keep`),[c,l]=(0,X.useState)(`keep`),[u,d]=(0,X.useState)(``),[f,p]=(0,X.useState)(``),[m,h]=(0,X.useState)(`expect`),[g,_]=(0,X.useState)(``),[v,y]=(0,X.useState)(null),x=(0,X.useMemo)(()=>{switch(e){case`bounds`:{let e=o===`set`?qo(u):null,t=c===`set`?qo(f):null;return o===`set`&&e==null?`Min items needs a whole number.`:c===`set`&&t==null?`Max items needs a whole number.`:{type:`bounds`,min:o===`set`?{kind:`set`,n:e}:{kind:o},max:c===`set`?{kind:`set`,n:t}:{kind:c}}}case`addTerm`:return g.trim()?{type:`addTerm`,list:m,term:g}:`Name the term.`;case`removeTerm`:return g.trim()?{type:`removeTerm`,term:g}:`Name the term.`;case`todo`:return{type:`status`,todo:!0};case`graded`:return{type:`status`,todo:!1}}},[e,o,c,u,f,m,g]),S=(0,X.useMemo)(()=>{if(typeof x==`string`)return null;let{next:e,changed:r}=Kr(t,n,x);return{changed:r,problems:qr(t,e,r)}},[x,t,n]),C=v??S?.problems??null,w=!!C&&C.cases.length>0,T=S?.changed.length??0,E=(0,X.useCallback)(()=>{if(typeof x==`string`)return;let e=r(x);e&&y(e)},[x,r]),D=e=>t=>{y(null),e(t)},O=[];return e===`bounds`&&(O.push({key:`min`,label:`Min items`,required:!0,control:{type:`select`,value:o,options:Ko,onChange:D(e=>s(e))}}),o===`set`&&O.push({key:`minN`,label:`Min`,required:!0,width:`quarter`,control:{type:`text`,value:u,onChange:D(d)}}),O.push({key:`max`,label:`Max items`,required:!0,control:{type:`select`,value:c,options:Ko,onChange:D(e=>l(e))}}),c===`set`&&O.push({key:`maxN`,label:`Max`,required:!0,width:`quarter`,control:{type:`text`,value:f,onChange:D(p)}})),e===`addTerm`&&O.push({key:`list`,label:`List`,required:!0,control:{type:`select`,value:m,onChange:D(e=>h(e)),options:[`expect`,`forbid`].map(e=>({value:e,label:Yr(e)}))}}),(e===`addTerm`||e===`removeTerm`)&&O.push({key:`term`,label:`Term`,required:!0,control:{type:`text`,value:g,onChange:D(_)}}),(0,$.jsxs)(b,{title:Go[e],onClose:i,dirty:o!==`keep`||c!==`keep`||!!u||!!f||!!g,className:`ev-bulk`,footer:(0,$.jsxs)(`div`,{className:`edit-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:i,children:`Cancel`}),(0,$.jsx)(`button`,{type:`button`,className:`edit-done`,disabled:!T||w,onClick:E,children:`Apply`})]}),children:[O.length>0&&(0,$.jsx)(a,{label:Go[e],rows:O}),(0,$.jsx)(`p`,{className:`note ev-changes`,role:`status`,children:typeof x==`string`?x:`Changes ${T} of ${n.size}`}),w&&C&&(0,$.jsx)(`div`,{className:`ev-refusal`,role:`alert`,children:C.cases.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{className:`ev-refusal-head`,children:[C.cases.length,` of `,n.size,` would break`]}),(0,$.jsx)(`ul`,{children:C.cases.map(e=>(0,$.jsxs)(`li`,{children:[(0,$.jsx)(`b`,{children:e.file}),` `,e.reasons.join(`; `)]},e.key))})]})})]})}function Yo({pageSize:e=20}){let t=Zn(),n=hr(),r=Ye(),{openCaseEditor:i}=Bo(),{list:a}=gr(),{datasetId:o,selected:s,setSelected:c,filters:l,setFilters:u,handedOver:d}=ai(),[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)(null),g=(0,X.useCallback)(()=>p(null),[]),_=a?.find(e=>e.id===o)??a?.[0]??null,v=_?.id??``,y=_r(v||null),b=y?.doc?.body??null,x=b?.cases,S=(0,X.useMemo)(()=>x?L().gradedSetFrom({cases:x}):[],[x]),C=y?.doc?.preview??_?.preview??null,w=Ao(C?.id),T=(0,X.useMemo)(()=>w?ei(S,w):null,[S,w]),E=(0,X.useMemo)(()=>new Set(S.map(zr)),[S]),D=(0,X.useMemo)(()=>new Set([...s].filter(e=>E.has(e))),[s,E]),O=(0,X.useMemo)(()=>ni(S,l,D,w),[S,l,D,w]),k=!!y?.doc&&!C;(0,X.useEffect)(()=>{k&&(l.status===`missing`||l.status===`nocase`)&&u({status:`all`})},[k,l.status,u]);let A=(0,X.useCallback)(()=>n.entry(v)?.doc?.body??null,[n,v]),j=(0,X.useCallback)(e=>{v&&n.edit(v,t=>({...t,cases:e}))},[n,v]),N=e=>{i(e,{dataset:v,files:O.map(e=>e.item),onRemove:F})},P=e=>{h(null),i(e,{dataset:v,files:[...S.map(e=>e.item),e],onRemove:F})};function F(e){let t=A()?.cases??[];j(Lo({cases:t},e)),r.offer({label:`Removed ${e}`,restore:()=>j(t)})}let I=e=>{let i=A();if(!v||!i)return null;let{next:a,changed:o}=Kr(i.cases,D,e);if(!o.length)return p(null),null;if(e.type!==`delete`){let e=qr(i.cases,a,o);if(e.cases.length)return e}dr(t,v,i,`bulk`);let s=i.cases;if(n.edit(v,e=>({...e,cases:a})),e.type===`delete`){let e=new Set(o);c(t=>new Set([...t].filter(t=>!e.has(t))))}return r.offer({label:Zr(e,o.length),restore:()=>n.edit(v,e=>({...e,cases:s}))}),p(null),null},R=D.size===0,z=[{label:`Set count…`,icon:rt,disabled:R,onSelect:()=>p(`bounds`)},{label:`Add term…`,icon:M.add,disabled:R,onSelect:()=>p(`addTerm`)},{label:`Remove term…`,icon:zn,disabled:R,onSelect:()=>p(`removeTerm`)},{label:`Mark To do…`,icon:xn,disabled:R,onSelect:()=>p(`todo`)},{label:`Mark graded…`,icon:wn,disabled:R,onSelect:()=>p(`graded`)},{label:`Delete`,icon:M.remove,destructive:!0,disabled:R,onSelect:()=>void I({type:`delete`})}];return(0,$.jsxs)(`div`,{className:`cases`,children:[a?.length?(0,$.jsx)(Vo,{rows:S,shown:O,filters:l,onFilters:u,selected:D,onSelect:c,selectionActions:z,sourceFiles:w,noCase:T,loading:!b,loadError:y?.sync.state===`missing`?y.sync.message:null,onRetry:()=>{v&&n.load(v)},pageSize:e,onEdit:N,onAdd:e=>h({item:e??``}),onRemove:F,children:d&&_&&(0,$.jsxs)(`p`,{className:`note ev-from`,role:`status`,children:[(0,$.jsxs)(`span`,{children:[`From `,d.from]}),d.found<d.wanted&&(0,$.jsxs)(`span`,{children:[d.found,` of `,d.wanted,` are in `,_.name,` now`]})]})}):null,m&&b&&(0,$.jsx)(jo,{title:`Add case`,action:`Add case`,start:C,initial:m.item,taken:new Set(S.map(e=>e.item)),onPick:P,onClose:()=>h(null)}),f&&b&&(0,$.jsx)(Jo,{kind:f,cases:b.cases,keys:D,onApply:I,onClose:g}),(0,$.jsx)(Vt,{undo:r.undo,onUndo:r.undoNow,onDismiss:r.dismiss})]})}function Xo({groupId:e,undo:t}){let n=uo(),r=Z(),i=Zn(),o=hr(),{list:s,error:c}=gr(),{pickDataset:l}=ai(),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(!1),[m,h]=(0,X.useState)(null),[g,v]=(0,X.useState)(!1),[y,x]=(0,X.useState)(!1),[S,w]=W(`dataset-cases`,20),[T,D]=(0,X.useState)(!1),[O,A]=(0,X.useState)(null),j=(0,X.useRef)(null),[N]=Q(`promptlab.versions`),[P]=Q(`promptlab.connections`),F=e=>N.profile?.[e]?.[0]?.at??null,[I,R]=(0,X.useState)(null);(0,X.useEffect)(()=>{let e=!0;return r.sources().then(t=>{e&&R(t.sources)}).catch(()=>{e&&R([])}),()=>{e=!1}},[r]);let z=_r(e)?.doc??null,B=z?.body??null,ee=s?.find(t=>t.id===e)??null;(0,X.useEffect)(()=>{l(e)},[e,l]),(0,X.useEffect)(()=>{s&&!ee&&Qa()},[s,ee]);let V=(0,X.useMemo)(()=>e?cr(i,e):[],[i,e,N]),H=e=>h({text:e instanceof Error?e.message:String(e),bad:!0}),te=(0,X.useCallback)(()=>o.entry(e)?.doc?.body??null,[o,e]),U=(0,X.useCallback)(t=>o.edit(e,t),[o,e]),ne=()=>new Set((o.list().list??[]).map(e=>e.name)),G=async()=>{h(null);try{Za((await o.create(Qo(`Untitled eval group`,ne()))).id)}catch(e){H(e)}},re=t=>{let n=t.trim();z&&n&&n!==z.name&&(h(null),o.rename(e,n).catch(e=>{e instanceof mn&&e.status===409?h({text:`An eval group is already called ${n}.`,bad:!0}):H(e)}))},ie=async()=>{if(z){h(null);try{await o.flush(e),Za((await o.create(Qo(`${z.name} copy`,ne()),structuredClone(z.body),z.preview??null)).id)}catch(e){H(e)}}},ae=async()=>{if(!z)return;h(null);let{name:n}=z;try{await o.flush(e);let r=await o.remove(e);Xa(),t.offer({label:`Deleted ${n}`,restore:()=>{o.restore(r).then(e=>{Za(e.id),e.name!==n&&h({text:`Restored as ${e.name}.`,bad:!1})}).catch(H)}})}catch(e){H(e)}},q=async e=>{h(null);let t;try{t=await Zo(e)}catch(e){H(e);return}let n;try{n=JSON.parse(t)}catch(e){h({text:`Not JSON: ${e instanceof Error?e.message:String(e)}`,bad:!0});return}A(`import`);try{let e=await o.importFile(n);e[0]&&Za(e[0].id),h({text:`Imported ${e.map(e=>e.name).join(`, `)}.`,bad:!1})}catch(e){H(e)}finally{A(null)}},oe=async()=>{e&&(A(`export`),await o.flush(e).catch(()=>{}),await se(o.exportUrl(e),e=>Ja(`eval-group`,e.group?.name??e.dataset?.name??``,e.version,`json`)),A(null))},se=async(e,t)=>{try{let n=await fetch(e);if(!n.ok)throw Error(`the export answered ${n.status}`);let r=await n.json();Ya(new Blob([JSON.stringify(r,null,2)+`
|
|
7
|
-
`],{type:`application/json`}),t(r))}catch(e){H(e)}},ce=n=>{let r=te();r&&(dr(i,e,r,`restore`),U(()=>structuredClone(n.doc)),x(!1),t.offer({label:`Restored the eval group`,restore:()=>U(()=>r)}))},le=(0,X.useMemo)(()=>{let e=P.list.find(e=>e.id===P.grader);return e?{id:e.id,name:e.name}:null},[P]),de=(0,X.useMemo)(()=>P.list.filter(e=>(L().CONNECTION_TYPES[e.type??``]?.answers??[`prompt`]).includes(`prompt`)),[P.list]),J=e=>{let{mode:t,threshold:n}=e.scoring;return[{key:`mode`,label:`Scoring`,control:{type:`select`,value:t,options:[{value:`all`,label:`All must pass`},{value:`weighted`,label:`Weighted points`}],onChange:e=>U(t=>({...t,scoring:{mode:e===`weighted`?`weighted`:`all`,threshold:e===`weighted`?t.scoring.threshold??1:t.scoring.threshold}}))}},...t===`weighted`?[{key:`threshold`,label:`Pass at`,width:`quarter`,control:{type:`text`,value:n==null?``:String(n),onChange:e=>U(t=>({...t,scoring:{mode:`weighted`,threshold:e.trim()?/^-?\d+(\.\d+)?$/.test(e.trim())?Number(e):e:null}}))}}]:[],{key:`grader`,label:`Grader`,control:{type:`picker`,kind:`Connection`,value:e.grader?.id??``,usedLabel:`Last changed`,...wo(de,F,[{id:``,label:le?`Lab (${le.name})`:`None`}]),onChange:e=>{let t=de.find(t=>t.id===e);U(e=>({...e,grader:t?{id:t.id,name:t.name}:null}))}}}]},pe=z?.preview??null,me=[{key:`preview`,label:`Preview Source`,control:{type:`picker`,kind:`Source`,value:pe?.id??``,usedLabel:`Last changed`,...wo([...pe&&I&&!I.some(e=>e.id===pe.id)?[{id:pe.id,name:`${pe.name} (missing)`}]:[],...I??[]],e=>I?.find(t=>t.id===e)?.changed??null,[{id:``,label:`None`}]),onChange:t=>{let n=I?.find(e=>e.id===t),r=n?{id:n.id,name:n.name}:pe?.id===t?pe:null;o.setPreview(e,r).catch(H)}}}],he=e=>t=>U(n=>({...n,[e]:t})),ge=e=>(n,r)=>{let i=te()?.[e]??[];he(e)(n),t.offer({label:r,restore:()=>U(t=>({...t,[e]:i}))})},_e=B?B.cases.filter(e=>!e.todo).length:0,ve=[{label:`Rename…`,icon:He,disabled:!z,onSelect:()=>d(!0)},{label:`Clone`,icon:M.clone,disabled:!z,onSelect:()=>void ie()},n({tab:`library`,section:`datasets`,id:e}),{label:`Import JSON…`,icon:K,busy:O===`import`,onSelect:()=>j.current?.click()},{label:`Export JSON`,icon:fe,disabled:!z,busy:O===`export`,onSelect:()=>void oe()},{label:`Export all`,icon:jn,disabled:!s?.length,busy:O===`exportAll`,onSelect:()=>{A(`exportAll`),se(o.exportAllUrl(),e=>Ja(`eval-groups`,`all`,e.version,`json`)).finally(()=>A(null))}},{label:`Restore…`,icon:Ze,disabled:!V.length||!z,onSelect:()=>x(!0)},{label:`Edit raw…`,icon:Dn,disabled:!z,onSelect:()=>v(!0)},{label:`Delete`,icon:Lt,destructive:!0,disabled:!z,onSelect:()=>void ae()}],ye=(0,$.jsx)(`input`,{ref:j,type:`file`,accept:`.json,application/json`,hidden:!0,"aria-label":`Import JSON file`,onChange:e=>{let t=e.target.files?.[0];e.target.value=``,t&&q(t)}}),Y=B?`${B.cases.length} cases, ${_e} graded`:void 0;return(0,$.jsxs)(`div`,{className:`datasets`,children:[(0,$.jsx)(k,{kind:`Eval group`,name:z?.name??ee?.name??(s===null?`Loading…`:`None`),onPick:s?.length?()=>p(!0):void 0,meta:Y,primary:{label:`New eval group`,icon:ze,onSelect:()=>void G()},actions:ve}),m&&(0,$.jsx)(`p`,{className:`note${m.bad?` bad`:``}`,role:m.bad?`alert`:`status`,children:m.text}),ye,B==null?(0,$.jsx)(C,{label:`Eval group`,error:c,onRetry:()=>void o.refresh()}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(E,{id:`grades`,title:`Grades`,level:2,children:(0,$.jsx)(a,{label:`Grades`,rows:J(B)})}),(0,$.jsx)(E,{id:`every`,title:`Every item`,level:2,note:B.every.length?String(B.every.length):void 0,children:(0,$.jsx)(So,{label:`Every item`,metrics:B.every,over:`item`,set:he(`every`),undoable:ge(`every`)})}),(0,$.jsx)(E,{id:`run`,title:`Whole run`,level:2,note:B.run.length?String(B.run.length):void 0,children:(0,$.jsx)(So,{label:`Whole run`,metrics:B.run,over:`run`,set:he(`run`),undoable:ge(`run`)})}),(0,$.jsxs)(E,{id:`cases`,title:`Cases`,level:2,note:String(B.cases.length),actions:[{label:`Page size…`,icon:M.pageSize,onSelect:()=>D(!0)}],children:[(0,$.jsx)(a,{label:`Preview`,rows:me}),(0,$.jsx)(Yo,{pageSize:S})]})]}),f&&s&&(0,$.jsx)(ue,{kind:`Eval group`,value:e,onClose:()=>p(!1),options:s.map(e=>({id:e.id,label:e.name})),onPick:e=>{h(null),Za(e)}}),u&&z&&(0,$.jsx)(Tt,{title:`Rename eval group`,value:z.name,onCommit:re,onClose:()=>d(!1)}),T&&(0,$.jsx)(_,{value:S,onChange:w,onClose:()=>D(!1)}),y&&z&&(0,$.jsx)(b,{title:`Restore eval group`,onClose:()=>x(!1),children:(0,$.jsxs)(`div`,{className:`version-list`,children:[V.length===0&&(0,$.jsx)(`p`,{className:`note`,children:`No versions of this eval group yet.`}),V.map((e,t)=>(0,$.jsxs)(`div`,{className:`version-row`,children:[(0,$.jsxs)(`span`,{className:`version-when`,children:[es(e.at),`, `,$o(e.reason)]}),(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>ce(e),children:`Restore`})]},`${e.at}-${t}`))]})}),g&&z&&(0,$.jsx)(To,{name:z.name,body:z.body,onSave:e=>{U(()=>e),v(!1)},onClose:()=>v(!1)})]})}function Zo(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result??``)),r.onerror=()=>n(r.error??Error(`The file could not be read.`)),r.readAsText(e)})}var Qo=(e,t)=>{if(!t.has(e))return e;for(let n=2;;n++)if(!t.has(`${e} ${n}`))return`${e} ${n}`},$o=e=>e===`idle`?`after editing`:e===`restore`?`before a restore`:e===`bulk`?`before a bulk edit`:e===`pack`?`before a pack update`:e,es=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()};function ts({groupId:e}){let t=Ye();return(0,$.jsxs)($.Fragment,{children:[e?(0,$.jsx)(Xo,{groupId:e,undo:t}):(0,$.jsx)(_o,{undo:t}),(0,$.jsx)(Vt,{undo:t.undo,onUndo:t.undoNow,onDismiss:t.dismiss})]})}var ns=e=>e,rs=e=>e?.state===`conflict`?`Not saved: changed in another browser.`:e?.state===`offline`?`Not saved: ${e.message}`:null,is=(e,t)=>JSON.stringify(e)===JSON.stringify(t),as=e=>e instanceof Error?e.message:String(e),os=({body:e,...t})=>t;function ss({api:e,pause:t=800}){let n=ns(e),r={list:null,error:null},i=new Map,a=new Set,o=new Map,s=new Map,c=new Set,l=null,u=()=>{l=null,c.forEach(e=>e())},d=(e,t)=>{let n=i.get(e)??{id:e,doc:null,sync:{state:`loading`}};i.set(e,{...n,...t,id:e}),u()},f=e=>{r={list:e,error:null},u()},p=e=>{if(!r.list)return;let t=r.list.findIndex(t=>t.id===e.id);f(t<0?[...r.list,e]:r.list.map((n,r)=>r===t?e:n))},m=e=>{let t=o.get(e);t&&clearTimeout(t),o.delete(e),a.delete(e),i.delete(e),r.list?f(r.list.filter(t=>t.id!==e)):u()},h=e=>{d(e.id,{doc:e,sync:{state:`saved`}}),p(os(e))};async function g(e){let t=i.get(e);if(!t?.doc||!a.has(e)||t.sync.state===`conflict`)return;let{body:r,version:o}=t.doc;d(e,{sync:{state:`saving`}});try{let t=await n.saveFilterSet(e,o,r),s=i.get(e);if(!s?.doc)return;s.doc.body===r&&a.delete(e);let c={...s.doc,version:t.version,filters:r.filters.length};if(d(e,{doc:c,sync:{state:`saved`}}),p(os(c)),a.has(e))return g(e)}catch(t){let n=i.get(e);if(!n?.doc)return;let r=t instanceof mn&&t.status===409?t.body?.current??null:null;if(r){if(is(r.body,n.doc.body)){a.delete(e),d(e,{doc:{...n.doc,version:r.version},sync:{state:`saved`}});return}d(e,{sync:{state:`conflict`,theirs:r}});return}d(e,{sync:{state:`offline`,message:as(t)}})}}function _(e){let t=o.get(e);t&&(clearTimeout(t),o.delete(e));let n=s.get(e);return n||(n=g(e).finally(()=>s.delete(e)),s.set(e,n)),n}return{list:()=>r,entry:e=>i.get(e),held:()=>l??=[...i.values()],async refresh(){r.error&&(r={list:r.list,error:null},u());try{let e=(await n.filterSets()).filterSets;f(e);for(let t of e){let e=i.get(t.id);e?.doc&&!a.has(t.id)&&t.version>e.doc.version&&n.filterSet(t.id).then(e=>{i.has(t.id)&&!a.has(t.id)&&h(e)},()=>{})}}catch(e){r={list:r.list,error:as(e)},u()}},load(e){i.has(e)&&i.get(e).sync.state!==`missing`||(d(e,{sync:{state:`loading`}}),n.filterSet(e).then(t=>{i.has(e)&&d(e,{doc:t,sync:{state:`saved`}})},t=>{i.has(e)&&d(e,{sync:{state:`missing`,message:as(t)}})}))},edit(e,n){let r=i.get(e);if(!r?.doc)return;let s=n(r.doc.body);if(s===r.doc.body)return;d(e,{doc:{...r.doc,body:s,filters:s.filters.length}}),a.add(e);let c=o.get(e);c&&clearTimeout(c),o.set(e,setTimeout(()=>{o.delete(e),_(e)},t))},async flush(e){await Promise.all((e?[e]:[...a]).map(_))},async resolve(e,t){let n=i.get(e);if(!n?.doc||n.sync.state!==`conflict`)return;let r=n.sync.theirs;if(t===`theirs`){a.delete(e),h(r);return}d(e,{doc:{...n.doc,version:r.version},sync:{state:`saved`}}),a.add(e),await _(e)},async create(e,t){let r=await n.createFilterSet(t?{name:e,body:t}:{name:e});return h(r),r},async rename(e,t){let r=await n.renameFilterSet(e,t),a=i.get(e)?.doc;a&&d(e,{doc:{...a,name:r.name,version:r.version,updated:r.updated}}),p({...os(r),filters:a?.body.filters.length??r.filters})},async remove(e){let{trash:t}=await n.deleteFilterSet(e);return m(e),t},async restore(e){let t=await n.restoreFilterSet(e);return h(t),t},subscribe(e){return c.add(e),()=>{c.delete(e)}}}}var cs=(0,X.createContext)(null);function ls({children:e,pause:t}){let n=Z(),r=(0,X.useMemo)(()=>ss({api:n,...t==null?{}:{pause:t}}),[n,t]);return(0,X.useEffect)(()=>{let e=()=>{r.flush()};return addEventListener(`pagehide`,e),()=>removeEventListener(`pagehide`,e)},[r]),(0,$.jsx)(cs.Provider,{value:r,children:e})}function us(){let e=(0,X.useContext)(cs);if(!e)throw Error(`useFilterSets outside a FilterSetsProvider: the app mounts one at its root`);return e}function ds(){let e=us(),t=(0,X.useSyncExternalStore)(e.subscribe,e.list);return(0,X.useEffect)(()=>{e.list().list===null&&e.refresh()},[e]),t}function fs(e){let t=us(),n=(0,X.useSyncExternalStore)(t.subscribe,()=>e?t.entry(e):void 0);return(0,X.useEffect)(()=>{e&&t.load(e)},[t,e]),n}function ps(e){let t=[];for(let n of e.jobs??[])for(let e of n.steps??[]){let n=e.filterSets;if(Array.isArray(n))for(let e of n)e&&typeof e==`object`&&t.push(e)}return t}var ms=()=>Fr({tab:`library`,section:`filters`,id:null}),hs=e=>Fr({tab:`library`,section:`filters`,id:e}),gs=()=>Ir({tab:`library`,section:`filters`,id:null});function _s({undo:e}){let t=uo(),n=us(),{list:r,error:i}=ds(),[a]=Q(`promptlab.workflows`),[o,s]=W(`filter-sets`,20),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)(null),m=e=>d(e instanceof Error?e.message:String(e)),h=(0,X.useMemo)(()=>{let e=new Map;for(let t of a.list)for(let n of ps(t.work)){let r=n.set?.id;if(!r)continue;let i=e.get(r)??{names:[],pinned:!1};i.names.includes(t.name)||i.names.push(t.name),typeof n.pin==`number`&&(i.pinned=!0),e.set(r,i)}return e},[a.list]),g=(r??[]).map(e=>({...e,links:h.get(e.id)??{names:[],pinned:!1}})),v=()=>new Set((n.list().list??[]).map(e=>e.name)),y=async()=>{d(null);try{hs((await n.create(vs(`Untitled filter set`,v()),L().blankFilterSetBody())).id)}catch(e){m(e)}},b=async t=>{d(null);try{await n.flush(t.id);let r=await n.remove(t.id);e.offer({label:`Deleted ${t.name}`,restore:()=>{n.restore(r).catch(m)}})}catch(e){m(e)}},x=e=>[{label:`Open`,icon:Ie,onSelect:()=>hs(e.id)},t({tab:`library`,section:`filters`,id:e.id}),{label:`Copy or move…`,icon:M.transfer,onSelect:()=>p(e)},{label:`Delete`,icon:M.remove,destructive:!0,onSelect:()=>void b(e)}],S=[{key:`set`,header:`Filter set`,role:`title`,sort:e=>e.name.toLowerCase(),cell:e=>(0,$.jsx)(`button`,{type:`button`,className:`eg-open`,onClick:()=>hs(e.id),children:e.name})},{key:`filters`,header:`Filters`,className:`num`,sort:e=>e.filters,cell:e=>e.filters},{key:`linked`,header:`Linked by`,sort:e=>e.links.names.length,tdProps:e=>({"data-state":e.links.names.length?void 0:`none`}),cell:e=>e.links.names.length?(0,$.jsx)(`span`,{title:e.links.names.join(`, `),children:`${e.links.names.length} ${e.links.names.length===1?`pipeline`:`pipelines`}${e.links.pinned?`, pinned`:``}`}):`—`},{key:`menu`,header:``,label:``,role:`menu`,sort:null,cell:e=>(0,$.jsx)(Y,{label:`${e.name} actions`,actions:x(e)})}],w=[{label:`Page size…`,icon:M.pageSize,onSelect:()=>l(!0)}];return(0,$.jsxs)(E,{id:`filter-sets`,title:`Filter sets`,note:r?String(r.length):void 0,actions:w,about:`Item filters defined once and linked by the pipelines whose list replies they clean.`,children:[r===null?(0,$.jsx)(C,{label:`Filter sets`,error:i,onRetry:()=>void n.refresh()}):r.length===0?(0,$.jsx)(`p`,{className:`note`,children:`No filter sets yet.`}):(0,$.jsx)(J,{className:`eg-groups`,cards:!0,label:`Filter sets`,rows:g,rowKey:e=>e.id,pageSize:o,columns:S}),u&&(0,$.jsx)(`p`,{className:`note bad`,role:`alert`,children:u}),(0,$.jsxs)(`button`,{type:`button`,className:`ghost eg-add`,onClick:()=>void y(),children:[(0,$.jsx)(ze,{size:14,"aria-hidden":`true`}),`Add filter set`]}),c&&(0,$.jsx)(_,{value:o,onChange:s,onClose:()=>l(!1)}),f&&(0,$.jsx)(go,{subject:{kind:`filter-set`,id:f.id,name:f.name},scan:{pipelines:a.list},undo:e,onClose:()=>p(null),onChanged:()=>void n.refresh()})]})}var vs=(e,t)=>{if(!t.has(e))return e;for(let n=2;;n++)if(!t.has(`${e} ${n}`))return`${e} ${n}`},ys=[{id:`terms`,scope:`item`,keys:[`terms`],label:`is one of these words`,control:`chips`},{id:`regex`,scope:`item`,keys:[`regex`],label:`matches a pattern`,control:`regex`},{id:`shorter`,scope:`item`,keys:[`length`],label:`is shorter than`,control:`num`,dir:`below`,unit:`characters`},{id:`longer`,scope:`item`,keys:[`length`],label:`is longer than`,control:`num`,dir:`above`,unit:`characters`},{id:`fewerWords`,scope:`item`,keys:[`words`],label:`has fewer words than`,control:`num`,dir:`below`,unit:`words`},{id:`moreWords`,scope:`item`,keys:[`words`],label:`has more words than`,control:`num`,dir:`above`,unit:`words`},{id:`duplicate`,scope:`item`,keys:[`duplicate`],label:`is already in the list`,control:`flag`},{id:`echoes`,scope:`item`,keys:[`echoes`],label:`is made only of the prompt's words`,control:`flag`},{id:`blank`,scope:`answer`,keys:[`blank`],label:`it is blank`,control:`blank`},{id:`fewerItems`,scope:`answer`,keys:[`itemCount`],label:`it has fewer items than`,control:`num`,dir:`below`,unit:`items`},{id:`moreItems`,scope:`answer`,keys:[`itemCount`],label:`it has more items than`,control:`num`,dir:`above`,unit:`items`},{id:`share`,scope:`answer`,keys:[`share`,`items`],label:`too many items are one of these words`,control:`share`},{id:`textBlank`,scope:`text`,keys:[`blank`],label:`the text is blank`,control:`blank`},{id:`textRegex`,scope:`text`,keys:[`regex`],label:`the text matches a pattern`,control:`regex`}],bs=(e,t)=>ys.filter(n=>n.scope===e&&(!t||n.keys.every(e=>t.includes(e)))),xs=e=>{let t=L().FILTER_TYPES[e];return t?bs(t.scope,t.conditions):[]},Ss=e=>!!e&&typeof e==`object`&&!Array.isArray(e);function Cs(e,t,n,r){let i=bs(e,r).filter(e=>e.keys[0]===t);return i.length===0?null:i.length===1?i[0]:(Ss(n)&&n.above!=null?i.find(e=>e.dir===`above`):i.find(e=>e.dir===`below`))??i[0]}function ws(e,t,n){let r=[],i=new Set;for(let a of bs(t,n)){let o=a.keys[0];if(i.has(o)||e[o]==null)continue;let s=Cs(t,o,e[o],n);s&&(r.push(s),s.keys.forEach(e=>i.add(e)))}return r}function Ts(e,t){let n={...e};for(let e of t.keys)delete n[e];switch(t.control){case`chips`:n.terms=[];break;case`regex`:n.regex=``;break;case`num`:n[t.keys[0]]={[t.dir]:``};break;case`blank`:n.blank=!0;break;case`flag`:n[t.keys[0]]=!0;break;case`share`:n.share={above:``},n.items={terms:[]}}return n}function Es(e,t,n){return bs(t,n).find(t=>t.keys.every(t=>e[t]==null))??null}function Ds(e,t,n){let r=Es(e,t,n);return r?Ts(e,r):e}function Os(e,t){let n={...e};for(let e of t.keys)delete n[e];return n}function ks(e,t,n){return Ts(Os(e,t),n)}function As(e,t,n,r){let i=n.keys[0];return bs(t,r).filter(t=>t.keys[0]===i||t.keys.every(t=>e[t]==null))}var js=e=>e==null||e===``?``:String(e),Ms=e=>/^-?\d+(\.\d+)?$/.test(e.trim())?Number(e):e.trim(),Ns=e=>Array.isArray(e.terms)?e.terms.map(String):[],Ps=(e,t)=>({...e,terms:t}),Fs=e=>typeof e.regex==`string`?e.regex:``,Is=(e,t)=>({...e,regex:t}),Ls=(e,t)=>js(Ss(e[t.keys[0]])?e[t.keys[0]][t.dir]:void 0),Rs=(e,t,n)=>({...e,[t.keys[0]]:{[t.dir]:Ms(n)}}),zs=e=>({pct:js(Ss(e.share)&&e.share.above!=null&&e.share.above!==``?Math.round(Number(e.share.above)*100):``),words:Ss(e.items)&&Array.isArray(e.items.terms)?e.items.terms.map(String):[]}),Bs=(e,t)=>({...e,share:{above:/^\d+(\.\d+)?$/.test(t.trim())?Number(t)/100:t.trim()}}),Vs=(e,t)=>({...e,items:{terms:t}});function Hs(e){switch(e){case`rewrite-item`:return{kind:`tidy`};case`rewrite-text`:return{kind:`thinking`};case`keep-first`:return{n:10};default:return}}function Us(e,t){let n=xs(t)[0],r=Hs(t);return{id:e,type:t,match:n?Ts({},n):{},...r?{op:r}:{},options:{ignoreFailures:!1,repeat:1},tests:[]}}var Ws={item:[`Drop an item when it`,`and it`],answer:[`Reject the whole reply when`,`and`],text:[`Reject the reply when`,`and`],list:[``,``]};function Gs({scope:e,allowed:t,match:n,onChange:r}){let i=ws(n,e,t),[a,o]=Ws[e];return(0,$.jsxs)(`div`,{className:`cond-builder`,children:[i.map((i,s)=>(0,$.jsxs)(`div`,{className:`cond-row`,"data-control":i.control,children:[(0,$.jsxs)(`div`,{className:`cond-line`,children:[(0,$.jsx)(`span`,{className:`cond-prefix`,children:s===0?a:o}),(0,$.jsx)(`select`,{className:`cond-pick`,"aria-label":`Condition`,value:i.id,onChange:a=>{let o=As(n,e,i,t).find(e=>e.id===a.target.value);o&&r(ks(n,i,o))},children:As(n,e,i,t).map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.label},e.id))}),i.control===`num`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`input`,{type:`text`,inputMode:`numeric`,className:`cond-num`,"aria-label":i.label,value:Ls(n,i),onChange:e=>r(Rs(n,i,e.target.value))}),i.unit&&(0,$.jsx)(`span`,{className:`cond-unit`,children:i.unit})]}),i.control===`regex`&&(0,$.jsx)(`input`,{type:`text`,className:`cond-regex`,"aria-label":`Pattern`,placeholder:`a regular expression`,spellCheck:!1,value:Fs(n),onChange:e=>r(Is(n,e.target.value))}),(0,$.jsx)(`button`,{type:`button`,className:`cond-x`,"aria-label":`Remove condition ${s+1}`,onClick:()=>r(Os(n,i)),children:(0,$.jsx)(Se,{size:14,"aria-hidden":`true`})})]}),i.control===`chips`&&(0,$.jsx)(Xt,{value:Ns(n),onChange:e=>r(Ps(n,e))}),i.control===`share`&&(0,$.jsxs)(`div`,{className:`cond-share`,children:[(0,$.jsx)(`input`,{type:`text`,inputMode:`numeric`,className:`cond-num`,"aria-label":`Share, percent`,value:zs(n).pct,onChange:e=>r(Bs(n,e.target.value))}),(0,$.jsx)(`span`,{className:`cond-unit`,children:`% or more of items are one of these words`}),(0,$.jsx)(Xt,{value:zs(n).words,onChange:e=>r(Vs(n,e))})]})]},i.id)),(0,$.jsxs)(`button`,{type:`button`,className:`ghost add-btn cond-add`,disabled:!Es(n,e,t),onClick:()=>r(Ds(n,e,t)),children:[(0,$.jsx)(ze,{size:14,"aria-hidden":`true`}),`Add condition`]})]})}var Ks={comma:`Comma`,lines:`New line`,semicolon:`Semicolon`,none:`None (whole reply)`},qs={"rewrite-item":[{kind:`tidy`,label:`Tidy — strip bullets, numbering, stray quotes and extra spaces`},{kind:`case`,label:`Change case`}],"rewrite-text":[{kind:`thinking`,label:`Remove thinking — drop a <think>…</think> block`},{kind:`preamble`,label:`Remove preamble — drop everything up to the first colon`},{kind:`replace`,label:`Replace pattern`}]},Js=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Ys=e=>/^\d+$/.test(e.trim())?Number(e):e.trim();function Xs({filter:e,isNew:t,others:n,onSave:r,onClose:i}){let o=L(),s=o.FILTER_TYPES[e.type],c=s?.scope??`item`,l=s?.label??e.type,u=s?.conditions??[],d=qs[e.type],f=c===`text`,[p,m]=(0,X.useState)(e.id),[h,g]=(0,X.useState)(e.why??``),[_,v]=(0,X.useState)(()=>structuredClone(e.match??{})),[y,b]=(0,X.useState)(()=>structuredClone(e.op??{})),[x,S]=(0,X.useState)(!!e.options?.ignoreFailures),[C,w]=(0,X.useState)(String(e.options?.repeat??1)),[T,E]=(0,X.useState)(()=>structuredClone(e.tests??[])),[D,O]=(0,X.useState)(null),k=()=>O(null),A=e=>{b(t=>({...t,...e})),k()},j=(0,X.useMemo)(()=>({id:p.trim(),type:e.type,...h.trim()?{why:h.trim()}:{},match:_,...d||e.type===`keep-first`?{op:y}:{},options:{ignoreFailures:x,repeat:Ys(C)},tests:T}),[p,h,_,y,x,C,T,e.type,d]),M=o.tryFilter(j),N=(e,t)=>E(n=>n.map((n,r)=>r===e?{...n,...t}:n)),P=()=>{let e=j,t=[...e.id?[]:[`A filter needs a name.`],...n.some(t=>t.id===e.id)?[`A filter is already called ${e.id}.`]:[],...o.filterProblems([e],`This filter`),...M.flatMap((e,t)=>e.ok?[]:[`Test ${t+1} does not come out as expected.`])];if(t.length)return O(t);r(e)},F=[{key:`filter`,rows:[{key:`id`,label:`Name`,width:`full`,required:!0,control:{type:`text`,value:p,onChange:e=>{m(e),k()}}},{key:`type`,label:`Type`,control:{type:`static`,text:l},hint:`Set when the filter was created — delete and recreate to change it.`},{key:`why`,label:`Comments`,control:{type:`textarea`,value:h,onChange:g}}]}];if(d){let e=typeof y.kind==`string`?y.kind:d[0].kind,t=[{key:`op`,label:`Operation`,control:{type:`select`,value:e,options:d.map(e=>({value:e.kind,label:e.label})),onChange:e=>A({kind:e})}}];e===`case`&&t.push({key:`mode`,label:`Case`,control:{type:`select`,value:y.mode??`LOWER`,options:o.CASE_MODES.map(e=>({value:e,label:e})),onChange:e=>A({mode:e})}}),e===`replace`&&(t.push({key:`pattern`,label:`Pattern`,control:{type:`text`,value:y.pattern??``,onChange:e=>A({pattern:e})}}),t.push({key:`replacement`,label:`Replace with`,control:{type:`text`,value:y.replacement??``,onChange:e=>A({replacement:e})}})),F.push({key:`operation`,title:`Operation`,rows:t})}else e.type===`keep-first`&&F.push({key:`operation`,title:`Operation`,rows:[{key:`n`,label:`Keep`,hint:`The first items, as many as set.`,width:`quarter`,control:{type:`text`,value:String(y.n??``),onChange:e=>A({n:Ys(e)})}}]});return u.length&&F.push({key:`match`,title:e.type===`rewrite-item`?`Only items that`:`Match`,children:(0,$.jsx)(Gs,{scope:c,allowed:u,match:_,onChange:e=>{v(e),k()}})}),F.push({key:`options`,title:`Options`,rows:[{key:`ignore`,label:`Ignore failures`,control:{type:`checkbox`,checked:x,label:`Keep going if this filter errors`,onChange:e=>{S(e),k()}}},{key:`repeat`,label:`Repeat`,hint:`Passes over the reply.`,width:`quarter`,control:{type:`text`,value:C,onChange:e=>{w(e),k()}}}]}),F.push({key:`tests`,title:`Tests`,children:(0,$.jsxs)(`div`,{className:`filter-tests`,children:[(0,$.jsx)(`p`,{className:`note`,children:`A sample reply, and what the filter should leave.`}),T.map((e,t)=>{let n=M[t],r=!!n?.ok;return(0,$.jsxs)(`div`,{className:`filter-test`,children:[(0,$.jsx)(a,{label:`Test ${t+1}`,rows:[...f?[]:[{key:`sep`,label:`Separator`,hint:`Splits a sample into items.`,control:{type:`select`,value:e.separator,options:o.FILTER_SEPARATORS.filter(e=>e!==`none`).map(e=>({value:e,label:Ks[e]??e})),onChange:e=>{N(t,{separator:e}),k()}}}],{key:`in`,label:`Sample input`,control:{type:`textarea`,value:e.sampleInput,onChange:e=>{N(t,{sampleInput:e}),k()}}},{key:`out`,label:`Expected output`,control:{type:`textarea`,value:e.expectedOutput,onChange:e=>{N(t,{expectedOutput:e}),k()}}}]}),(0,$.jsxs)(`div`,{className:`filter-test-result`,children:[(0,$.jsx)(`span`,{className:`filter-test-verdict ${r?`hit`:`fault`}`,role:`status`,children:Zs(c,!!s?.rejects,r,n?.got??``,e)}),(0,$.jsx)(`button`,{type:`button`,className:`icon-btn`,"aria-label":`Remove test ${t+1}`,onClick:()=>{E(e=>e.filter((e,n)=>n!==t)),k()},children:(0,$.jsx)(Se,{size:14,"aria-hidden":`true`})})]})]},t)}),(0,$.jsxs)(`button`,{type:`button`,className:`ghost add-btn`,onClick:()=>{E(e=>[...e,{separator:f?`none`:`comma`,sampleInput:``,expectedOutput:``}]),k()},children:[(0,$.jsx)(ze,{size:14,"aria-hidden":`true`}),`Add test`]})]})}),(0,$.jsx)(ut,{title:t?`New filter`:e.id,...D?.length?{status:D.join(` `),statusBad:!0}:{},sections:F,onSave:P,dirty:!Js(j,e),focusRow:`id`,wide:!0,onClose:i})}function Zs(e,t,n,r,i){if(t)return`${n?`Pass`:`Fail`} — ${r===`rejected`?`rejected`:`kept`}`;if(e===`text`)return n?`Pass — reads as expected`:`Fail — left ${r?JSON.stringify(r):`nothing`}`;let a=L().splitSample(i.expectedOutput,i.separator);return n?`Pass — ${a.length} of ${a.length} items as expected`:`Fail — kept ${r||`nothing`}`}var Qs={text:`Pre-format`,items:`Post-format`},$s=[`text`,`items`].map(e=>({stage:e,label:Qs[e]}));function ec({stage:e,title:t=`New filter`,onPick:n,onClose:r}){let i=L(),a=$s.filter(t=>!e||t.stage===e).map(e=>({...e,types:Object.entries(i.FILTER_TYPES).filter(([,t])=>i.stageOfScope(t.scope)===e.stage)})).filter(e=>e.types.length),[o,s]=(0,X.useState)(a[0]?.types[0]?.[0]??``);return(0,$.jsxs)(b,{title:t,onClose:r,className:`new-filter`,footer:(0,$.jsxs)(`div`,{className:`edit-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`edit-done ghost`,onClick:r,children:`Cancel`}),(0,$.jsx)(`button`,{type:`button`,className:`edit-save`,disabled:!o,onClick:()=>o&&n(o),children:`Continue`})]}),children:[(0,$.jsx)(`p`,{className:`note`,children:`A filter's type can't change once it's made.`}),a.map(t=>(0,$.jsxs)(`fieldset`,{className:`nf-types`,children:[(0,$.jsx)(`legend`,{className:e?`sr-only`:`nf-stage`,children:e?`Filter type`:t.label}),t.types.map(([e,t])=>(0,$.jsxs)(`label`,{className:`nf-type${e===o?` on`:``}`,children:[(0,$.jsx)(`input`,{type:`radio`,name:`filter-type`,value:e,checked:e===o,onChange:()=>s(e)}),(0,$.jsxs)(`span`,{className:`nf-type-text`,children:[(0,$.jsx)(`span`,{className:`nf-type-name`,children:t.label}),(0,$.jsx)(`span`,{className:`nf-type-about`,children:t.about})]})]},e))]},t.stage))]})}function tc({label:e,filters:t,onChange:n,onRemoved:r}){let[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(null),u=[...t],d=(e,t)=>{let r=[...u],[i]=r.splice(e,1);r.splice(e+t,0,i),n(r)},f=[{key:`id`,header:`Filter`,role:`title`,sort:e=>e.id.toLowerCase(),cell:e=>(0,$.jsx)(`button`,{type:`button`,className:`ds-file`,onClick:()=>a(u.indexOf(e)),children:e.id})},{key:`examples`,header:`Examples`,sort:e=>{let t=L().tryFilter(e);return t.length?t.filter(e=>e.ok).length/t.length:null},cell:e=>{let t=L().tryFilter(e),n=t.filter(e=>e.ok).length;return t.length?(0,$.jsxs)(`span`,{className:n<t.length?`ds-nomatch`:void 0,children:[n,` of `,t.length,` pass`]}):(0,$.jsx)(`span`,{className:`ds-nomatch`,children:`None`})}},{key:`menu`,header:``,label:``,role:`menu`,sort:null,cell:e=>{let t=u.indexOf(e),i=[{label:`Edit…`,icon:M.edit,onSelect:()=>a(t)},{label:`Clone`,icon:M.clone,onSelect:()=>n([...u.slice(0,t+1),{...structuredClone(e),id:nc(u,`${e.id} copy`)},...u.slice(t+1)])},{label:`Move up`,icon:M.moveUp,disabled:t===0,onSelect:()=>d(t,-1)},{label:`Move down`,icon:M.moveDown,disabled:t===u.length-1,onSelect:()=>d(t,1)},{label:`Remove`,icon:M.remove,destructive:!0,onSelect:()=>{n(u.filter((e,n)=>n!==t)),r?.(`Removed ${e.id}`,u)}}];return(0,$.jsx)(Y,{actions:i,label:`${e.id} actions`})}}],p=i==null?void 0:u[i];return(0,$.jsxs)(`div`,{className:`filters-table`,children:[u.length?(0,$.jsx)(J,{className:`rules`,cards:!0,label:e,rows:u,rowKey:e=>e.id,columns:f,defaultSort:null,select:{noun:`filter`,actions:e=>[{label:`Remove`,icon:M.remove,destructive:!0,onSelect:()=>{let t=new Set(e);n(u.filter(e=>!t.has(e))),r?.(e.length===1?`Removed ${e[0].id}`:`Removed ${e.length} filters`,u)}}]}}):(0,$.jsx)(`p`,{className:`note`,children:`No filters.`}),(0,$.jsxs)(`button`,{type:`button`,className:`ghost add-btn`,onClick:()=>s(!0),children:[(0,$.jsx)(M.add,{size:14,"aria-hidden":`true`}),`Add filter`]}),o&&(0,$.jsx)(ec,{onPick:e=>{s(!1),l(Us(nc(u,`New filter`),e))},onClose:()=>s(!1)}),(c||p)&&(0,$.jsx)(Xs,{filter:c??p,isNew:!!c,others:c?u:u.filter((e,t)=>t!==i),onSave:e=>{n(c?[...u,e]:u.map((t,n)=>n===i?e:t)),l(null),a(null)},onClose:()=>{l(null),a(null)}},c?`new`:i)]})}function nc(e,t){let n=t,r=2;for(;e.some(e=>e.id===n);)n=`${t} ${r++}`;return n}function rc({setId:e,undo:t}){let n=uo(),r=us(),{list:i,error:a}=ds(),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(null),f=fs(e)?.doc??null,p=f?.body??null,m=i?.find(t=>t.id===e)??null;(0,X.useEffect)(()=>{i&&!m&&gs()},[i,m]);let h=e=>d({text:e instanceof Error?e.message:String(e),bad:!0}),g=(0,X.useCallback)(t=>r.edit(e,t),[r,e]),_=()=>new Set((r.list().list??[]).map(e=>e.name)),v=async()=>{d(null);try{hs((await r.create(ic(`Untitled filter set`,_()))).id)}catch(e){h(e)}},y=t=>{let n=t.trim();f&&n&&n!==f.name&&(d(null),r.rename(e,n).catch(e=>{e instanceof mn&&e.status===409?d({text:`A filter set is already called ${n}.`,bad:!0}):h(e)}))},b=async()=>{if(f){d(null);try{await r.flush(e),hs((await r.create(ic(`${f.name} copy`,_()),structuredClone(f.body))).id)}catch(e){h(e)}}},x=async()=>{if(!f)return;d(null);let{name:n}=f;try{await r.flush(e);let i=await r.remove(e);ms(),t.offer({label:`Deleted ${n}`,restore:()=>{r.restore(i).then(e=>{hs(e.id),e.name!==n&&d({text:`Restored as ${e.name}.`,bad:!1})}).catch(h)}})}catch(e){h(e)}},S=[{label:`Rename…`,icon:M.rename,disabled:!f,onSelect:()=>s(!0)},{label:`Clone`,icon:M.clone,disabled:!f,onSelect:()=>void b()},n({tab:`library`,section:`filters`,id:e}),{label:`Delete`,icon:Lt,destructive:!0,disabled:!f,onSelect:()=>void x()}],w=p?p.filters.length:0,T=p?`${w} ${w===1?`filter`:`filters`}`:void 0;return(0,$.jsxs)(`div`,{className:`filters-page`,children:[(0,$.jsx)(k,{kind:`Filter set`,name:f?.name??m?.name??(i===null?`Loading…`:`None`),onPick:i?.length?()=>l(!0):void 0,meta:T,primary:{label:`New filter set`,icon:ze,onSelect:()=>void v()},actions:S}),u&&(0,$.jsx)(`p`,{className:`note${u.bad?` bad`:``}`,role:u.bad?`alert`:`status`,children:u.text}),p==null?(0,$.jsx)(C,{label:`Filter set`,error:a,onRetry:()=>void r.refresh()}):(0,$.jsx)(E,{id:`filters`,title:`Filters`,level:2,note:w?String(w):void 0,about:`Change a filter here; every run that follows latest grades against it. Filters run top to bottom; the first that matches wins.`,children:(0,$.jsx)(tc,{label:`Filters`,filters:p.filters,onChange:e=>g(t=>({...t,filters:e})),onRemoved:(e,n)=>t.offer({label:e,restore:()=>g(e=>({...e,filters:[...n]}))})})}),c&&i&&(0,$.jsx)(ue,{kind:`Filter set`,value:e,onClose:()=>l(!1),options:i.map(e=>({id:e.id,label:e.name})),onPick:e=>{d(null),hs(e)}}),o&&f&&(0,$.jsx)(Tt,{title:`Rename filter set`,value:f.name,onCommit:y,onClose:()=>s(!1)})]})}var ic=(e,t)=>{if(!t.has(e))return e;for(let n=2;;n++)if(!t.has(`${e} ${n}`))return`${e} ${n}`};function ac({setId:e}){let t=Ye();return(0,$.jsxs)($.Fragment,{children:[e?(0,$.jsx)(rc,{setId:e,undo:t}):(0,$.jsx)(_s,{undo:t}),(0,$.jsx)(Vt,{undo:t.undo,onUndo:t.undoNow,onDismiss:t.dismiss})]})}var oc=[{value:`all`,label:`All`},{value:`used`,label:`Used`},{value:`unused`,label:`Unused`}],sc=[{value:`all`,label:`All`},{value:`scenario`,label:`Used by this target`},{value:`scenarios`,label:`Used by all targets`}];function cc(e,t,n){let r=t.trim().toLowerCase();return r&&!e.name.toLowerCase().includes(r)&&!e.text.toLowerCase().includes(r)?!1:n===`all`||n===`used`==e.useCount>0}function lc(e,t,n,r){let i=t.trim().toLowerCase();return i&&!e.name.toLowerCase().includes(i)&&!e.text.toLowerCase().includes(i)?!1:n===`scenario`?r.byScenario.has(e.id):n!==`scenarios`||r.byAll.has(e.id)}var uc=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()};function dc(e){return e.id===null?(0,$.jsx)(fc,{onClose:e.onClose}):(0,$.jsx)(pc,{...e,id:e.id})}function fc({onClose:e}){let t=Tr(),[n,r]=(0,X.useState)(``),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(!1),u=async()=>{l(!0);try{await t.create({name:n,text:i}),e()}catch(e){s(e instanceof Error?e.message:String(e)),l(!1)}};return(0,$.jsx)(ut,{title:`New prompt`,status:o??void 0,statusBad:!!o,focusRow:`text`,wide:!0,sections:[{key:`prompt`,rows:[{key:`name`,label:`Name`,width:`full`,control:{type:`text`,value:n,placeholder:`First line`,onChange:r}},{key:`text`,label:`Prompt`,required:!0,control:{type:`textarea`,value:i,placeholder:`None`,onChange:a}}]}],dirty:!!n||!!i,saving:c,onSave:()=>void u(),onClose:e})}function pc({id:e,onClose:t,onDuplicate:r,onDelete:i}){let a=Tr(),o=Dr(e),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(!1),{openRun:d}=ci(),[f,p]=(0,X.useState)(new Set),[m,h]=(0,X.useState)(new Set),[g,_]=(0,X.useState)(null),v=uo(),y=o?.doc;if(!y)return(0,$.jsx)(ut,{title:`Prompt`,sections:[{key:`loading`,children:(0,$.jsx)(C,{label:`Prompt`,error:o?.sync.state===`missing`?o.sync.message:null,onRetry:()=>a.load(e)})}],onClose:t});let b=(e,t,n)=>{let r=new Set(e);r.has(t)?r.delete(t):r.add(t),n(r)},x=e=>_(e instanceof Error?e.message:String(e)),S=e=>y.versions.find(t=>t.version===e)?.text??``,w=y.uses.some(e=>e.job>0),T=[{key:`version`,header:`Version`,sort:e=>e.version,cell:e=>`v${e.version}${e.version===y.version?` (newest)`:``}`},{key:`created`,header:`Made`,sort:e=>e.created,cell:e=>uc(e.created)},{key:`uses`,header:`Uses`,className:`num`,sort:e=>e.uses,cell:e=>e.uses},{key:`menu`,header:``,label:``,className:`pl-menu`,role:`menu`,sort:null,cell:t=>(0,$.jsx)(Y,{label:`v${t.version} actions`,actions:[{label:f.has(t.version)?`Hide words`:`Show words`,icon:le,onSelect:()=>b(f,t.version,p)},{label:`Restore`,icon:n,disabled:t.version===y.version,onSelect:()=>{_(null),a.restoreVersion(e,t.version).catch(x)}}]})}],E=e=>`${e.runId}:${e.scenarioId}:${e.job}`,D=[{key:`run`,header:`Run`,sort:e=>e.submittedAt,cell:e=>(0,$.jsx)(`a`,{className:`pl-run`,href:Pr({tab:`results`,id:e.runId}),onClick:n=>{n.preventDefault(),t(),d(e.runId,{at:e.submittedAt,from:`history`})},children:Ti(e.submittedAt)})},{key:`scenario`,header:`Scenario`,sort:e=>e.scenarioName,cell:e=>e.scenarioName},...w?[{key:`job`,header:`Job`,className:`num`,sort:e=>e.job,cell:e=>e.job+1}]:[],{key:`version`,header:`Version`,sort:e=>e.version,cell:e=>`v${e.version}`},{key:`when`,header:`When`,sort:e=>e.submittedAt,cell:e=>uc(e.submittedAt)},{key:`menu`,header:``,label:``,className:`pl-menu`,role:`menu`,sort:null,cell:e=>(0,$.jsx)(Y,{label:`${Ti(e.submittedAt)} ${e.scenarioName} actions`,actions:[{label:m.has(E(e))?`Hide words`:`Show words`,icon:le,onSelect:()=>b(m,E(e),h)}]})}],O=[{label:`Set as default`,icon:Jn,disabled:y.default,onSelect:()=>{_(null),a.setDefault(e).catch(x)}},{label:`Duplicate`,icon:M.clone,onSelect:()=>r(y)},v({tab:`library`,section:`prompts`,id:e}),{label:`Delete`,icon:M.remove,destructive:!0,disabled:y.default,onSelect:()=>i(y)}],k=s?.name??y.name,A=s?.text??y.text,j=k!==y.name||A!==y.text,N=e=>c({name:k,text:A,...e}),P=async()=>{if(!j){t();return}u(!0),a.edit(e,{name:k,text:A});try{if(await a.flush(e),a.entry(e)?.sync.state===`conflict`){c(null),u(!1);return}t()}catch(e){x(e),u(!1)}},F=g??yr(o.sync),I=o.sync.state===`conflict`;return(0,$.jsx)(ut,{title:vr({...y,name:k,text:A}),status:F??void 0,statusBad:!!F,menu:O,wide:!0,actions:I?[{label:`Take theirs`,onSelect:()=>void a.resolve(e,`theirs`)},{label:`Keep mine`,onSelect:()=>void a.resolve(e,`mine`)}]:[],dirty:j,saving:l,onSave:()=>void P(),onClose:t,sections:[{key:`prompt`,rows:[{key:`name`,label:`Name`,width:`full`,control:{type:`text`,value:k,placeholder:`First line`,onChange:e=>N({name:e})}},{key:`version`,label:`Version`,required:!0,control:{type:`static`,text:`v${y.version}${y.default?` (Default)`:``}`}},{key:`text`,label:`Prompt`,required:!0,control:{type:`textarea`,value:A,placeholder:`None`,onChange:e=>N({text:e})}}]},{key:`versions`,title:`Versions`,children:(0,$.jsx)(J,{className:`pltable pl-versions`,label:`Versions`,rows:y.versions,rowKey:e=>String(e.version),defaultSort:{key:`version`,dir:`desc`},columns:T,after:e=>f.has(e.version)&&(0,$.jsx)(`tr`,{className:`pl-words-row`,children:(0,$.jsx)(`td`,{colSpan:T.length,children:(0,$.jsx)(`pre`,{className:`pl-words`,children:e.text})})})})},{key:`uses`,title:`Uses`,children:y.uses.length===0?(0,$.jsx)(`p`,{className:`note`,children:`No uses yet.`}):(0,$.jsx)(J,{className:`pltable pl-uses`,label:`Uses`,rows:y.uses,rowKey:E,pageSize:10,defaultSort:{key:`when`,dir:`desc`},columns:D,after:e=>m.has(E(e))&&(0,$.jsx)(`tr`,{className:`pl-words-row`,children:(0,$.jsx)(`td`,{colSpan:D.length,children:(0,$.jsx)(`pre`,{className:`pl-words`,children:S(e.version)})})})})}]})}var mc=`#new`,hc={tab:`library`,section:`prompts`,id:null},gc=e=>({tab:`library`,section:`prompts`,id:e});function _c({promptId:e=null}){let t=Tr(),{list:n,error:r}=Er(),[i]=Q(`promptlab.workflows`),a=Ye(),[o,s]=W(`prompts`,20),[c,l]=(0,X.useState)(!1),[u,f]=(0,X.useState)(``),[p,m]=(0,X.useState)(`all`),[h,g]=(0,X.useState)(!1),v=h?mc:e,y=t=>{g(t===mc),t!==mc&&t!==e&&Fr(t?gc(t):hc)},b=uo(),[x,S]=(0,X.useState)(null),[w,T]=(0,X.useState)(null);(0,X.useEffect)(()=>{e&&n&&!n.some(t=>t.id===e)&&!t.entry(e)?.doc&&Ir(hc)},[e,n,t]);let D=n??[],O=D.filter(e=>cc(e,u,p)),k=e=>S(e instanceof Error?e.message:String(e)),A=async()=>{S(null),y(mc)},j=async e=>{S(null);try{await t.flush(e.id);let n=await t.create({name:`${vr(e)} copy`,text:t.entry(e.id)?.doc?.text??e.text});y(n.id)}catch(e){k(e)}},N=async e=>{S(null);let n=[];try{for(let r of e)n.push(await t.remove(r.id)),v===r.id&&y(null)}catch(e){k(e)}n.length&&a.offer({label:e.length===1?`Deleted ${vr(e[0])}`:`Deleted ${n.length} prompts`,restore:()=>{for(let e of n)t.restore(e).catch(k)}})},P=e=>N([e]),F=e=>{S(null),t.setDefault(e.id).catch(k)},I=e=>[{label:`Edit…`,icon:M.edit,onSelect:()=>y(e.id)},{label:`Set as default`,icon:Jn,disabled:e.default,onSelect:()=>F(e)},{label:`Duplicate`,icon:M.clone,onSelect:()=>void j(e)},b(gc(e.id)),{label:`Copy or move…`,icon:M.transfer,onSelect:()=>T(e)},{label:`Delete`,icon:M.remove,destructive:!0,disabled:e.default,onSelect:()=>void P(e)}];return(0,$.jsxs)(E,{id:`prompts`,title:`Prompt library`,note:n?`${D.length} ${D.length===1?`prompt`:`prompts`}`:void 0,actions:[{label:`Page size…`,icon:M.pageSize,onSelect:()=>l(!0)}],about:`Wordings kept with every version and the runs that used them. The Default is the one a new target starts from.`,children:[n===null?(0,$.jsx)(C,{label:`Prompts`,error:r,onRetry:()=>void t.refresh()}):D.length===0?(0,$.jsx)(`p`,{className:`note`,children:`No prompts yet.`}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(d,{noun:`prompts`,search:{label:`Search prompts`,placeholder:`Search prompts`,value:u,onChange:f},filters:[{key:`show`,label:`Show`,value:p,onChange:e=>m(e),options:oc}],count:{shown:O.length,total:D.length}}),O.length===0?(0,$.jsx)(`p`,{className:`note`,children:`No prompts match these filters.`}):(0,$.jsx)(J,{className:`pl-prompts`,cards:!0,label:`Prompts`,rows:O,rowKey:e=>e.id,pageSize:o,rowProps:e=>({"data-default":e.default||void 0}),columns:[{key:`prompt`,header:`Prompt`,role:`title`,sort:e=>vr(e).toLowerCase(),cell:e=>(0,$.jsxs)(`button`,{type:`button`,className:`pl-open`,onClick:()=>y(e.id),children:[(0,$.jsxs)(`span`,{className:`pl-title`,children:[vr(e),e.default&&(0,$.jsx)(`span`,{className:`pl-default`,children:`Default`})]}),e.name.trim()&&e.text.trim()&&(0,$.jsx)(`span`,{className:`pl-preview`,children:e.text.trim()})]})},{key:`version`,header:`Version`,sort:e=>e.version,cell:e=>`v${e.version}`},{key:`uses`,header:`Uses`,className:`num`,sort:e=>e.useCount,cell:e=>e.useCount},{key:`last`,header:`Last used`,sort:e=>e.lastUsed??null,tdProps:e=>({"data-state":e.lastUsed?void 0:`none`}),cell:e=>e.lastUsed?uc(e.lastUsed):`—`},{key:`menu`,header:``,label:``,role:`menu`,sort:null,cell:e=>(0,$.jsx)(Y,{label:`${vr(e)} actions`,actions:I(e)})}],select:{noun:`prompt`,label:vr,actions:e=>[{label:`Delete`,icon:M.remove,destructive:!0,disabled:e.every(e=>e.default),onSelect:()=>void N(e.filter(e=>!e.default))}]}})]}),x&&(0,$.jsx)(`p`,{className:`note bad`,role:`alert`,children:x}),(0,$.jsxs)(`button`,{type:`button`,className:`ghost pl-add`,onClick:()=>void A(),children:[(0,$.jsx)(ze,{size:14,"aria-hidden":`true`}),`Add prompt`]}),v&&(0,$.jsx)(dc,{id:v===mc?null:v,onClose:()=>y(null),onDuplicate:e=>void j(e),onDelete:e=>void P(e)}),c&&(0,$.jsx)(_,{value:o,onChange:s,onClose:()=>l(!1)}),w&&(0,$.jsx)(go,{subject:{kind:`prompt`,id:w.id,name:vr(w)},scan:{pipelines:i.list},undo:a,onClose:()=>T(null),onChanged:()=>void t.refresh()}),(0,$.jsx)(Vt,{undo:a.undo,onUndo:a.undoNow,onDismiss:a.dismiss})]})}var vc=`evals-lab.sources`,yc={view:`thumbs`,sort:`name`,dir:1};function bc(){try{let e=window.localStorage.getItem(vc);if(e){let t=JSON.parse(e);if(t.view===`thumbs`||t.view===`list`)return{view:t.view,sort:t.sort===`added`||t.sort===`size`?t.sort:`name`,dir:t.dir===-1?-1:1}}}catch{}return yc}function xc(e){try{window.localStorage.setItem(vc,JSON.stringify(e))}catch{}}var Sc=e=>{let t=e.lastIndexOf(`.`);return t<0?``:e.slice(t).toLowerCase()},Cc=[`.heic`,`.heif`,`.dng`,`.tif`,`.tiff`],wc=[`.jpg`,`.jpeg`,`.png`],Tc=e=>wc.includes(Sc(e))||Cc.includes(Sc(e)),Ec=(e,t)=>`/api/sources/${encodeURIComponent(e)}/thumbs/${encodeURIComponent(t.name)}${t.v?`?v=${t.v}`:``}`,Dc=(e,t)=>Cc.includes(Sc(t.name))?`/api/sources/${encodeURIComponent(e)}/zoom/${encodeURIComponent(t.name)}`:`/api/sources/${encodeURIComponent(e)}/files/${encodeURIComponent(t.name)}`;function Oc(e,t,n){let r=[...e];return r.sort((e,r)=>{let i;return i=t===`size`?e.bytes-r.bytes:t===`added`?(e.added??0)-(r.added??0):e.name.localeCompare(r.name,void 0,{numeric:!0,sensitivity:`base`}),i*n}),r}function kc(e,t){let n=t.trim().toLowerCase();return n?e.filter(e=>e.name.toLowerCase().includes(n)):[...e]}function Ac(e){if(e<1024)return`${e} B`;let t=[`KB`,`MB`,`GB`,`TB`],n=e,r=-1;do n/=1024,r+=1;while(n>=1024&&r<t.length-1);let i=Math.round(n*10)/10;return`${Number.isInteger(i)?i:i.toFixed(1)} ${t[r]}`}function jc(e){return new Date(e*1e3).toLocaleDateString(void 0,{year:`numeric`,month:`short`,day:`numeric`})}var Mc=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function Nc(e){let t=new Date(e);return Number.isNaN(t.getTime())?``:`${t.getFullYear()}-${Mc[t.getMonth()]}-${String(t.getDate()).padStart(2,`0`)}`}function Pc(e){let t=Nc(e);if(!t)return``;let n=new Date(e);return`${t} ${String(n.getHours()).padStart(2,`0`)}:${String(n.getMinutes()).padStart(2,`0`)}`}function Fc(e){let t=e.platform??e.config?.platform,n=e.provider??e.config?.provider;return{id:e.id,name:e.name,system:e.system,type:e.type,...t?{platform:t}:{},...n?{provider:n}:{},files:e.files.length,bytes:e.bytes}}var Ic=`[redacted]`,Lc=/^(?:api[-_]?key|x-api-key|authorization|ocp-apim-subscription-key|password|secret|client[-_]?secret|token|access[-_]?token|refresh[-_]?token|sig)$/i,Rc=/^(?:headers|authentication)$/,zc=[[/sk-ant-[A-Za-z0-9_-]+/g,Ic],[/sk-[A-Za-z0-9_-]{20,}/g,Ic],[/Bearer\s+[A-Za-z0-9._~+/=-]+/g,`Bearer ${Ic}`],[/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,Ic],[/([?&](?:sig|code)=)[^&"\s]+/g,`$1${Ic}`]];function Bc(e){let t=0,n=e=>{let n=e;for(let[e,r]of zc)n=n.replace(e,(...e)=>(t++,r.replace(`$1`,e[1]??``)));return n},r=e=>{if(Array.isArray(e))return e.map(r);if(e&&typeof e==`object`){let n={};for(let[i,a]of Object.entries(e))Rc.test(i)&&a&&typeof a==`object`&&!Array.isArray(a)?n[i]=Object.fromEntries(Object.keys(a).map(e=>(t++,[e,Ic]))):Rc.test(i)&&typeof a==`string`||Lc.test(i)&&a!=null&&typeof a!=`object`?(t++,n[i]=Ic):n[i]=r(a);return n}return typeof e==`string`?n(e):e};return{value:r(e),count:t}}var Vc=[`https://service.flow.microsoft.com//.default`];function Hc(e){let t=e.trim();return!t||t.toLowerCase()===`organizations`?`Any organisation`:`${t} only`}var Uc=null;function Wc(e){let t=`${e.clientId}/${e.tenant}`;return Uc?.key!==t&&(Uc={key:t,pca:cn(()=>import(`./dist-DI3ewZYj.js`).then(async t=>{let n=await t.createStandardPublicClientApplication({auth:{clientId:e.clientId,authority:`https://login.microsoftonline.com/${e.tenant}`,redirectUri:`${window.location.origin}/`,OIDCOptions:{responseMode:t.ResponseMode.QUERY}},cache:{cacheLocation:`sessionStorage`}}),r=await n.handleRedirectPromise();return r?.account&&n.setActiveAccount(r.account),n}),[])}),Uc.pca}var Gc=()=>{let e=new URLSearchParams(window.location.search);return e.has(`state`)&&(e.has(`code`)||e.has(`error`))};async function Kc(e){await Wc(e)}async function qc(e){let t=await Wc(e);return(t.getActiveAccount()??t.getAllAccounts()[0]??null)?.username??null}var Jc=`signin`;function Yc(e=window.location.href){let t=new URL(e);return t.hostname===`127.0.0.1`?(t.hostname=`localhost`,t.searchParams.set(Jc,`microsoft`),t.href):null}function Xc(){let e=new URL(window.location.href);return e.searchParams.get(`signin`)===`microsoft`&&(e.searchParams.delete(Jc),window.history.replaceState(window.history.state,``,e.href),!0)}async function Zc(e,t=window.location.href){let n=Yc();if(n){window.location.assign(n);return}await(await Wc(e)).loginRedirect({scopes:Vc,prompt:`select_account`,redirectStartPage:t})}async function Qc(e){let t=await Wc(e),n=t.getActiveAccount()??t.getAllAccounts()[0];n&&await t.clearCache({account:n})}async function $c(e){let t=await Wc(e),n=t.getActiveAccount()??t.getAllAccounts()[0];if(!n)throw Error(`sign in to Microsoft first`);try{return(await t.acquireTokenSilent({scopes:Vc,account:n})).accessToken}catch(e){let{InteractionRequiredAuthError:r}=await cn(async()=>{let{InteractionRequiredAuthError:e}=await import(`./dist-DI3ewZYj.js`);return{InteractionRequiredAuthError:e}},[]);throw e instanceof r&&await t.acquireTokenRedirect({scopes:Vc,account:n,redirectStartPage:window.location.href}),e}}var el=new EventTarget,tl=()=>el.dispatchEvent(new Event(`change`));function nl(){let e=Z(),[t,n]=(0,X.useState)({cfg:void 0,editable:!1});return(0,X.useEffect)(()=>{let t=!0,r=()=>e.config().then(e=>{t&&n({cfg:e.microsoft??null,editable:!!e.microsoftEditable})},()=>{t&&n({cfg:null,editable:!1})});return r(),el.addEventListener(`change`,r),()=>{t=!1,el.removeEventListener(`change`,r)}},[e]),t}var rl=()=>nl().cfg,il=e=>T(()=>$c(e));async function al(e,t,n){let r=await e.flow(t,n);return{name:r.name,definition:Bc(r.definition).value}}async function ol(e,t,n,r,i){let a=await e.run(t,n,r),o=ye(i),s=new Map,c=new Map,l=t=>t?(c.has(t)||c.set(t,e.content(t)),c.get(t)):Promise.resolve(null),u=i=>(s.has(i)||s.set(i,e.repetitions(t,n,r,i)),s.get(i)),d=async(e,t)=>{let n=o[e]?.loops??[];return n.length?(await u(e)).find(e=>n.every(n=>!(n in t)||e.at[n]===t[n]))??null:a.actions[e]??null},f=e=>e.status!==`Skipped`&&(e.inputsLink||e.outputsLink||e.error),p=async e=>({run:r,at:e.at,startTime:e.startTime,inputs:await l(e.inputsLink),outputs:await l(e.outputsLink),error:e.error});return{detail:a,triggerOutputs:()=>l(a.trigger?.outputsLink??null),actionInputs:async(e,t)=>l((await d(e,t))?.inputsLink??null),actionOutputs:async(e,t)=>l((await d(e,t))?.outputsLink??null),callsOf:async e=>{let t=e.loops.length?await u(e.name):[a.actions[e.name]].filter(e=>!!e);return Promise.all(t.filter(f).map(p))}}}async function sl(e,t,n,r,i,a){if(!r.length)return[];let o=(await e.runs(t,n)).slice(0,a).map(e=>e.id);if(!o.length)return[];let s=new Set,c=[];for(let a of r){let{records:r}=await cl(e,t,n,o,a,i,s);for(let e of r)s.add(De(e)),c.push(e)}return c}async function cl(e,t,n,r,i,a,o,s){let c=new Set(o),l=[],u=0,d=0;for(let o of r){let r=await ol(e,t,n,o,a);for(let e of await r.callsOf(i)){let t=Bc(await xe(i,e,r,a)).value,n=De(t);if(c.has(n)){u++;continue}c.add(n),l.push(t)}s?.(++d)}return{records:l,skipped:u}}var ll=5;function ul({typeRow:e,initial:t,onMade:n,bind:r}){let i=Z(),o=rl(),s=(0,X.useMemo)(()=>o?il(o):null,[o]),[c,l]=(0,X.useState)(void 0),[u,d]=(0,X.useState)(null),f=t?.config??{},[p,m]=(0,X.useState)(``),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)(``),[y,b]=(0,X.useState)(t?.name??``),[x,S]=(0,X.useState)(!1),[w,T]=(0,X.useState)(null),E=e=>T(e instanceof Error?e.message:String(e));(0,X.useEffect)(()=>{o&&qc(o).then(l,()=>l(null))},[o]),(0,X.useEffect)(()=>{s&&c&&s.environments().then(e=>{d(e),m((e.find(e=>e.id===f.environment)??e.find(e=>e.isDefault)??e[0])?.id??``)},E)},[s,c,f.environment]),(0,X.useEffect)(()=>{s&&p&&(g(null),v(``),s.flows(p).then(e=>{if(g(e),t){v(e.find(e=>e.id===f.flow)?.id??``);return}v(e[0]?.id??``),b(e[0]?.name??``)},E))},[s,p,t,f.flow]);let D=!!s&&!!c,O=!!t&&D&&(_!==f.flow||p!==f.environment),k=!!t&&y.trim()!==t.name,A=O||k,j=!!y.trim()&&(t&&!D?!0:D&&!!_),M=(0,X.useRef)(async()=>{});(0,X.useEffect)(()=>{r({enabled:j&&!x,busy:x,changed:A,run:()=>void M.current()})},[r,j,x,A]),(0,X.useEffect)(()=>()=>r(null),[r]);let N=t?t.name:`New Source`,P={key:`name`,label:`Name`,width:`full`,control:{type:`text`,value:y,onChange:b}},F=(0,$.jsx)(a,{label:N,rows:t?[e,P]:[e]}),I=async(e,t,n)=>{try{for(let r of await sl(e,p,_,Ge(n),n,ll))try{await i.upload(t,ae(r),new Blob([JSON.stringify(r,null,2)],{type:`application/json`}))}catch{}}catch{}},L=()=>{let e=u?.find(e=>e.id===p)?.name;return{platform:`power-automate`,environment:p,...e?{environmentName:e}:{},flow:_,displayName:h?.find(e=>e.id===_)?.name??_}},R=async e=>{if(!A){await n(e);return}S(!0),T(null);try{let t=O&&s?await al(s,p,_):null,r=await i.updateSource(e.id,{...k?{name:y.trim()}:{},...t?{config:L()}:{}});t&&await i.saveDefinition(e.id,(await i.definition(e.id)).version,t.definition),await n(r)}catch(e){E(e instanceof mn?Error(e.message):e)}finally{S(!1)}};return M.current=async()=>{if(!j)return;if(t){await R(t);return}if(!s)return;S(!0),T(null);let e=null;try{let t=await i.createSource(y.trim(),`workflow`,L());e=t.id;let r=await al(s,p,_);await i.saveDefinition(t.id,0,r.definition),I(s,t.id,r.definition),await n(t)}catch(t){e&&await i.removeSource(e).catch(()=>{}),E(t instanceof mn?Error(t.message):t)}finally{S(!1)}},o===void 0||o&&c===void 0?(0,$.jsxs)($.Fragment,{children:[F,(0,$.jsx)(C,{label:`Account`})]}):o===null?(0,$.jsxs)($.Fragment,{children:[F,(0,$.jsx)(`p`,{className:`note`,children:`Microsoft: Not Configured`})]}):c?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(a,{label:N,rows:[e,{key:`account`,label:`Account`,control:{type:`static`,text:c}},{key:`env`,label:`Environment`,control:u?{type:`select`,value:p,options:u.map(e=>({value:e.id,label:e.name})),onChange:m}:{type:`static`,text:`Loading…`}},{key:`flow`,label:`Flow`,control:h?{type:`select`,value:_,options:[..._?[]:[{value:``,label:`—`}],...h.map(e=>({value:e.id,label:e.name}))],onChange:e=>{v(e),t||b(h.find(t=>t.id===e)?.name??``)}}:{type:`static`,text:p?`Loading…`:`—`}},P]}),h&&!h.length&&(0,$.jsx)(`p`,{className:`note`,children:`No flows in this environment.`}),w&&(0,$.jsx)(`p`,{className:`note bad`,role:`alert`,children:w})]}):(0,$.jsxs)($.Fragment,{children:[F,(0,$.jsx)(`div`,{className:`sacts`,children:(0,$.jsxs)(`button`,{type:`button`,className:`ghost`,onClick:()=>void Zc(o).catch(E),children:[(0,$.jsx)(Ln,{size:14,"aria-hidden":`true`}),` Sign in with Microsoft`]})}),w&&(0,$.jsx)(`p`,{className:`note bad`,role:`alert`,children:w})]})}function dl(e){let t=/^https?:\/\/[^/?#]+(\/[^?#]*)?(?:\?([^#]*))?/i.exec(e);if(!t)return{path:e,query:{}};let n={};for(let e of(t[2]??``).split(`&`).filter(Boolean)){let t=e.indexOf(`=`);n[t<0?e:e.slice(0,t)]=t<0?``:e.slice(t+1)}return{path:t[1]||`/`,query:n}}var fl=e=>{try{return new URL(/^https?:\/\//i.test(e)?e:`https://`+e).host}catch{return null}},pl=e=>(L().CONNECTION_TYPES[e??``]?.answers??[`prompt`]).includes(`request`);function ml(e,t){let n=fl(e);return n&&t.find(e=>pl(e.type)&&fl(L().addressOf(e))===n)||null}function hl(e,t){let n=L(),r=n.httpApiFor(e);if(r!==`raw`)return r;let i=ml(e,t);return i&&n.CONNECTION_TYPES[i.type]?.speaks?.(i)||`raw`}function gl(e,t){let n=ml(e,t)??t.find(e=>pl(e.type));return n?{id:n.id,name:n.name??``}:{id:`http-endpoint`,name:`HTTP endpoint`}}function _l(e){let t=fl(e),n=Object.values(L().CONNECTION_TYPES).filter(e=>e.picker!==!1&&pl(e.id)),r=n.find(e=>e.url&&fl(e.url)===t);if(r)return{type:r.id,name:r.label,url:``};let i=n.find(e=>!e.url)??n[0],a=(()=>{try{return new URL(e).origin}catch{return``}})();return{type:i.id,name:i.label,url:a}}function vl(e,t){let n=we(e,t.name),r=n?j(e,n.name):[],i=L();return[...n?[{type:`is-json`,schema:n.schema?JSON.stringify(n.schema,null,2):``}]:[],r.length?{type:`fields-equal-recorded`,fields:r.join(`
|
|
8
|
-
`)}:n?{type:`same-as-recorded`}:{type:`judge-vs-production`,...i.METRICS[`judge-vs-production`].defaults()}]}function yl(e,t,n,r,i){let a=L(),o=n.template,s=String(o.uri??``),c=hl(s,r),l={type:`httpRequest`,method:String(o.method??`POST`).toUpperCase(),...dl(s),body:o.body??null,...a.HTTP_APIS[c].cellOf(o.body??null)},u=we(t,n.name),d=gl(s,r),f=a.withOut({type:`job`,id:a.newId(),name:n.name,steps:[{type:`attachContent`,content:{type:`source`,ref:e,first:null,loops:1}},{type:`flowStep`,step:n.name,loop:n.loops.at(-1)??null,api:c},...u?.expression?[{type:`readAs`,readAs:u.expression}]:[]]},{kind:`text`,...a.OUTPUT_KINDS.text?.settingDefaults?.()??{},modifiers:a.OUTPUT_KINDS.text?.modifiers?.()??[]});return{version:a.PIPELINE_VERSION,id:a.newId(),name:`${e.name} · ${n.name}`,jobs:[f],targets:[{id:a.newId(),name:`Recorded`,connection:null,profile:null,steps:[{type:`recorded`,prompt:``}]},{id:a.newId(),name:`Edited`,connection:d,profile:null,steps:[structuredClone(l)]}],evals:[a.newLink(i)],pass:{mode:`all`}}}function bl(e,t,n){let r=e.result;if(!r||!(`status`in r))return null;let i=Ge(t).find(t=>t.name===e.step);if(!i)return null;let a=String(i.template.uri??``),o={step:i.name,loop:i.loops.at(-1)??null,api:hl(a,n),readAs:we(t,i.name)?.expression??null};try{return L().httpReplyOf(o,{prompt:``},r.body,r.status,{scope:e.scope,now:e.at}).raw}catch{return null}}function xl(e,t){let n;try{n=JSON.parse(e)}catch{return[{type:`equals`,value:e,json:!1}]}if(!n||typeof n!=`object`||Array.isArray(n))return[{type:`equals`,value:e,json:!0}];let r=n,i=t.length?t.filter(e=>e in r):Object.keys(r).filter(e=>r[e]==null||typeof r[e]!=`object`);return i.length?i.map(e=>({type:`json-field`,path:e,op:`equals`,value:typeof r[e]==`string`?r[e]:JSON.stringify(r[e])})):[{type:`equals`,value:e,json:!0}]}var Sl=e=>e.replace(/\.json$/i,``).replace(/[^A-Za-z0-9._-]/g,`_`);function Cl(e,t,n){let r=[],i=0;for(let{name:a,record:o}of e){if(bl(o,t,n)==null){i++;continue}r.push({id:Sl(a),item:a,todo:!1,note:``,metrics:[]})}return{cases:r,skipped:i}}function wl(e){return e.map(e=>({id:e.replace(/\.[a-z0-9]+$/i,``).replace(/[^A-Za-z0-9._-]/g,`_`),item:e,todo:!0,note:``,metrics:[]}))}function Tl(e,t,n){let r=[],i=0;for(let{name:a,record:o}of e){let e=bl(o,t,n);if(e==null){i++;continue}let s=we(t,o.step),c=s?j(t,s.name):[];r.push({id:a.replace(/\.json$/i,``).replace(/[^A-Za-z0-9._-]/g,`_`),item:a,todo:!0,note:``,metrics:xl(e,c)})}return{cases:r,skipped:i}}var El=e=>e instanceof Error?e.message:String(e),Dl={snapshot:`Snapshot`,run:`Run`,upload:`Upload`,hand:`By hand`,edited:`Edited`},Ol=e=>e&&Dl[e]||`—`;function kl({name:e,facts:t,sections:n,changed:r,valid:i,taken:a,menu:o,onSave:s,onClose:c}){let l=e.lastIndexOf(`.`),u=l>0?e.slice(l):``,d=e.slice(0,e.length-u.length),[f,p]=(0,X.useState)(d),[m,h]=(0,X.useState)(),[g,_]=(0,X.useState)(),[v,y]=(0,X.useState)(!1),b=async()=>{let t=f.trim(),n=t+u;if(!t)return h(`A call needs a name.`);if(n!==e&&a(n))return h(`${n} is taken.`);if(!i||i()){if(n===e&&!r)return c();y(!0),_(void 0);try{await s(n),c()}catch(e){e instanceof mn&&e.body?.field===`name`?h(El(e)):_(El(e)),y(!1)}}};return(0,$.jsx)(ut,{title:e,menu:o,wide:!0,sections:[{key:`call`,rows:s?[{key:`name`,label:`Name`,width:`full`,control:{type:`text`,value:f,suffix:u,onChange:e=>{p(e),h(void 0)}},error:m},...t]:t},...n??[]],...s?{onSave:()=>void b(),saving:v,dirty:f!==d||!!r,refusal:g}:{},onClose:c})}var Al=e=>e.name.toLowerCase().endsWith(`.json`),jl=e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result)),r.onerror=()=>n(r.error),r.readAsText(e)}),Ml=`evals-lab.flow.importing`;function Nl(e){try{return sessionStorage.getItem(e)}catch{return null}}function Pl(e,t){try{t?sessionStorage.setItem(e,t):sessionStorage.removeItem(e)}catch{}}var Fl=e=>e instanceof Error?e.message:String(e);function Il({source:e,definition:t,cfg:n}){let r=Z(),i=hr(),[a]=Q(`promptlab.connections`),o=Ye(),[s,c]=(0,X.useState)(e.files.filter(Al)),[l,u]=(0,X.useState)({}),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(()=>{let t=Nl(Ml)===e.id;return t&&Pl(Ml,null),t?`import`:null}),[h,_]=(0,X.useState)(null),v=(0,X.useMemo)(()=>Ge(t),[t]),[y,b]=(0,X.useState)(!1),[x,S]=(0,X.useState)(null),w=(0,X.useCallback)(async()=>{let t=(await r.source(e.id)).files.filter(Al);c(t);let n=await Promise.all(t.map(async t=>{try{return[t.name,Rt(JSON.parse(await jl(await r.file(e.id,t.name))))]}catch{return[t.name,null]}}));u(Object.fromEntries(n))},[r,e.id]),T=(0,X.useCallback)(()=>{S(null),w().then(()=>b(!0),e=>S(Fl(e)))},[w]);(0,X.useEffect)(T,[T]);let D=e=>{let n=l[e],r=n?v.find(e=>e.name===n.step):void 0;return n&&r?Dt(r,n,t):null},O=(0,X.useMemo)(()=>new Set(s.flatMap(e=>l[e.name]?[De(l[e.name])]:[])),[s,l]),k=async(t,n=0)=>{let i=0,a=[];for(let n of t)try{await r.upload(e.id,ae(n),new Blob([JSON.stringify(n,null,2)],{type:`application/json`})),i++}catch(e){a.push(e instanceof mn?e.message:Fl(e))}await w(),f([`Added ${i}`,n?`Skipped ${n}`:``,a.length?`Refused ${a.length}: ${a[0]}`:``].filter(Boolean).join(`, `))},A=async()=>{let{cases:n,skipped:r}=Tl(s.flatMap(e=>l[e.name]?[{name:e.name,record:l[e.name]}]:[]),t,a.list);if(!n.length)return f(`No call holds a production reply.`);try{let t=await i.create(`${e.name} · production`,{...er(),cases:n},{id:e.id,name:e.name});f([`Made ${t.name}: ${n.length} ${n.length===1?`case`:`cases`}`,r?`Skipped ${r}`:``].filter(Boolean).join(`, `))}catch(e){f(Fl(e))}},j=async t=>{try{let{trash:n}=await r.removeFiles(e.id,t);c(e=>e.filter(e=>!t.includes(e.name))),o.offer({label:t.length===1?`Removed ${t[0]}`:`Removed ${t.length} calls`,restore:()=>void r.restoreTrash(n).then(w,e=>f(Fl(e)))})}catch(e){f(Fl(e))}},N=async t=>{let n=URL.createObjectURL(await r.file(e.id,t)),i=document.createElement(`a`);i.href=n,i.download=t,document.body.append(i),i.click(),i.remove(),URL.revokeObjectURL(n)},P=async t=>{try{let{call:n}=await r.cloneCall(e.id,t);c(e=>e.flatMap(e=>e.name===t?[e,{...e,name:n.name}]:[e])),u(e=>({...e,[n.name]:e[t]??null})),o.offer({label:`Cloned ${t}`,restore:()=>void r.removeFiles(e.id,[n.name]).then(()=>c(e=>e.filter(e=>e.name!==n.name)),e=>f(Fl(e)))})}catch(e){f(Fl(e))}},F=async(t,n,i)=>{let a=l[t],s=i?JSON.stringify(Bc(i).value,null,2):void 0,{call:c}=await r.editCall(e.id,t,{...n===t?{}:{to:n},...s===void 0?{}:{content:s}});await w(),o.offer({label:s===void 0?`Renamed ${t}`:`Edited ${t}`,restore:()=>void r.editCall(e.id,c.name,{...c.name===t?{}:{to:t},...s===void 0?{}:{content:JSON.stringify(a,null,2)}}).then(w,e=>f(Fl(e)))})},I=(e,t)=>[...t?[]:[{label:`Edit…`,icon:M.edit,disabled:!l[e],onSelect:()=>_(e)}],{label:`Clone`,icon:M.clone,onSelect:()=>{t&&_(null),P(e)}},{label:`Download`,icon:fe,onSelect:()=>void N(e).catch(e=>f(Fl(e)))},{label:`Remove`,icon:Lt,destructive:!0,onSelect:()=>{t&&_(null),j([e])}}],L=(0,X.useCallback)(()=>m(null),[]),R=(0,X.useCallback)(()=>_(null),[]),z=h?l[h]:null;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(E,{id:`flow-calls`,title:`Calls`,note:String(s.length),about:`Calls are Power Automate steps that have been run previously.`,actions:[{label:`Import runs`,icon:Ze,disabled:!v.length||!n,onSelect:()=>m(`import`)},{label:`Upload…`,icon:K,disabled:!v.length,onSelect:()=>m(`upload`)},{label:`New dataset`,icon:g,disabled:!s.length,onSelect:()=>void A()}],children:[d&&(0,$.jsx)(`p`,{className:`note`,role:`status`,children:d}),y?s.length?(0,$.jsx)(`div`,{className:`sflow`,children:(0,$.jsx)(J,{className:`slist`,cards:!0,label:`Calls`,rows:s,rowKey:e=>e.name,select:{noun:`call`,actions:e=>[{label:`Download`,icon:fe,onSelect:()=>void(async()=>{for(let t of e)await N(t.name)})().catch(e=>f(Fl(e)))},{label:`Remove`,icon:Lt,destructive:!0,onSelect:()=>void j(e.map(e=>e.name))}]},columns:[{key:`action`,header:`Action`,role:`title`,sort:e=>l[e.name]?.step??``,cell:e=>l[e.name]?(0,$.jsx)(`button`,{type:`button`,className:`sopen`,onClick:()=>_(e.name),children:l[e.name].step}):`Unreadable`},{key:`origin`,header:`Origin`,sort:e=>Ol(l[e.name]?.origin.kind),cell:e=>Ol(l[e.name]?.origin.kind)},{key:`at`,header:`Recorded`,sort:e=>l[e.name]?.at??``,cell:e=>{let t=l[e.name]?.at;return t&&Nc(t)||`—`}},{key:`result`,header:`Result`,sort:e=>Rl(l[e.name])?.word??``,cell:e=>{let t=Rl(l[e.name]);return t?(0,$.jsxs)(`span`,{className:`sresult`,title:t.code,children:[(0,$.jsx)(_e,{pass:t.ok,decorative:!0}),t.word]}):`—`}},{key:`request`,header:`Request`,sort:e=>Ll(D(e.name)),tdProps:e=>{let t=D(e.name);return t&&t.match===!1?{title:t.where}:{}},cell:e=>Ll(D(e.name))},{key:`menu`,header:``,className:`s-actions`,role:`menu`,sort:null,cell:e=>(0,$.jsx)(me,{label:`${e.name} actions`,actions:I(e.name,!1)})}]})}):(0,$.jsx)(`p`,{className:`note`,children:`No calls yet. Import runs, in this group's menu, reads them from the flow's run history.`}):(0,$.jsx)(C,{label:`Calls`,error:x,onRetry:T}),(0,$.jsxs)(`button`,{type:`button`,className:`ghost add-btn`,disabled:!v.length,onClick:()=>m(`hand`),children:[(0,$.jsx)(ze,{size:14,"aria-hidden":`true`}),` Add call`]})]}),p===`import`&&n&&(0,$.jsx)(Gl,{cfg:n,source:e,steps:v,definition:t,held:O,onClose:L,onRead:async(e,t)=>{m(null),await k(e,t)}}),p===`hand`&&(0,$.jsx)(Kl,{steps:v,onClose:L,onAdd:async e=>{m(null),await k([e])}}),p===`upload`&&(0,$.jsx)(Jl,{steps:v,onClose:L,onRead:async e=>{m(null),await k(e)}}),h&&z&&(0,$.jsx)(Wl,{name:h,record:z,menu:I(h,!0),taken:e=>s.some(t=>t.name===e),onSave:(e,t)=>F(h,e,t),onClose:R}),(0,$.jsx)(Vt,{undo:o.undo,onUndo:o.undoNow,onDismiss:o.dismiss})]})}var Ll=e=>!e||e.match===null?`—`:e.match?`In sync`:`Out of sync`;function Rl(e){let t=e?.result;if(!t)return null;if(`error`in t)return{ok:!1,word:`Failed`,code:t.error.code||`Error`};let n=t.status>=200&&t.status<300;return{ok:n,word:n?`Succeeded`:`Failed`,code:String(t.status)}}var zl=e=>e.map(e=>({value:e.name,label:e.name})),Bl=e=>e.from===`trigger`?`Trigger body`:S(e);function Vl(e){let t=e.scope;return[...t.trigger?[{key:`trigger`,label:Bl({from:`trigger`}),value:t.trigger.body,put:(e,t)=>{e.scope.trigger={...e.scope.trigger,body:t}}}]:[],...Object.entries(t.actions??{}).map(([e,t])=>({key:`action-${e}`,label:e,value:t.body,put:(t,n)=>{t.scope.actions[e]={...t.scope.actions[e],body:n}}})),...Object.entries(t.variables??{}).map(([e,t])=>({key:`variable-${e}`,label:e,value:t,put:(t,n)=>{t.scope.variables[e]=n}})),...Object.entries(t.items??{}).map(([e,t])=>({key:`item-${e}`,label:e,value:t,put:(t,n)=>{t.scope.items[e]=n}}))]}var Hl=e=>typeof e==`string`?e:e==null?``:JSON.stringify(e,null,2),Ul=e=>{if(e===``)return null;try{return JSON.parse(e)}catch{return e}};function Wl({name:e,record:t,menu:n,taken:r,onSave:i,onClose:a}){let o=(0,X.useMemo)(()=>Vl(t),[t]),s=t.result,c=(0,X.useMemo)(()=>({...Object.fromEntries(o.map(e=>[e.key,Hl(e.value)])),...s&&`status`in s?{status:String(s.status),body:Hl(s.body)}:{},...s&&`error`in s?{code:s.error.code??``,message:s.error.message??``}:{}}),[o,s]),[l,u]=(0,X.useState)(c),[d,f]=(0,X.useState)(),p=Object.keys(c).filter(e=>l[e]!==c[e]),m=(e,t,n=!0)=>({key:e,label:t,control:{type:`textarea`,mono:n,value:l[e]??``,onChange:t=>u(n=>({...n,[e]:t}))}}),h=async e=>{if(!p.length)return i(e,null);let n=structuredClone(t);for(let e of o)p.includes(e.key)&&e.put(n,Ul(l[e.key]));s&&`status`in s?n.result={status:Number(l.status),body:p.includes(`body`)?Ul(l.body):s.body}:s&&`error`in s&&(n.result={error:{...s.error,code:l.code,message:l.message}});let{run:r,iteration:a}=t.origin;return n.origin={kind:`edited`,...r?{run:r}:{},...a?{iteration:a}:{}},i(e,n)},g=()=>!(s&&`status`in s)||/^\d+$/.test(l.status.trim())?!0:(f(`A status is a whole number.`),!1),_=t.request?`${t.request.method} ${t.request.uri}`:null,v=[{key:`action`,label:`Action`,control:{type:`static`,text:t.step}},..._?[{key:`request`,label:`Request`,control:{type:`code`,text:_}}]:[],{key:`at`,label:`Recorded`,control:{type:`static`,text:t.at&&Pc(t.at)||`—`}}],y=[...o.length?[{key:`reads`,title:`Reads`,rows:o.map(e=>m(e.key,e.label))}]:[],...s&&`status`in s?[{key:`reply`,title:`Reply`,rows:[{key:`status`,label:`Status`,width:`quarter`,error:d,control:{type:`text`,numeric:!0,value:l.status??``,onChange:e=>{f(void 0),u(t=>({...t,status:e}))}}},m(`body`,`Body`)]}]:[],...s&&`error`in s?[{key:`reply`,title:`Reply`,rows:[{key:`code`,label:`Code`,control:{type:`text`,value:l.code??``,onChange:e=>u(t=>({...t,code:e}))}},m(`message`,`Message`,!1)]}]:[]];return(0,$.jsx)(kl,{name:e,facts:v,sections:y,changed:p.length>0,taken:r,menu:n,valid:g,onSave:h,onClose:a})}function Gl({cfg:e,source:t,steps:n,definition:r,held:i,onClose:o,onRead:s}){let c=(0,X.useMemo)(()=>il(e),[e]),l=t.config??{},[u,f]=(0,X.useState)(void 0),[p,m]=(0,X.useState)(n[0]?.name??``),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)(``),[y,x]=(0,X.useState)(new Set),[S,w]=(0,X.useState)(``),[T,E]=(0,X.useState)(null),[D,O]=(0,X.useState)(null),[k,A]=(0,X.useState)(null),[j,M]=(0,X.useState)(0);(0,X.useEffect)(()=>{qc(e).then(f,()=>f(null))},[e]),(0,X.useEffect)(()=>{u&&l.environment&&l.flow&&(A(null),c.runs(l.environment,l.flow).then(g,e=>A(Fl(e))))},[u,c,l.environment,l.flow,j]);let N=(0,X.useMemo)(()=>[...new Set((h??[]).map(e=>e.status))].sort(),[h]),P=(0,X.useMemo)(()=>(h??[]).filter(e=>!_||e.status===_),[h,_]),I=e=>x(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),L=P.length>0&&P.every(e=>y.has(e.id)),R=P.filter(e=>y.has(e.id)).map(e=>e.id),z=async()=>{let e=n.find(e=>e.name===p);if(!e||!l.environment||!l.flow)return;let t=R;O(null),E(`Reading 0 of ${t.length}`);try{let{records:n,skipped:a}=await cl(c,l.environment,l.flow,t,e,r,i,e=>E(`Reading ${e} of ${t.length}`));await s(n,a)}catch(e){O(Fl(e)),E(null)}};return(0,$.jsxs)(b,{title:`Import runs`,onClose:o,wide:!0,dirty:R.length>0,footer:(0,$.jsxs)(`div`,{className:`sacts`,children:[T&&(0,$.jsx)(`span`,{className:`note`,role:`status`,children:T}),(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:o,children:`Cancel`}),(0,$.jsxs)(`button`,{type:`button`,disabled:!!T||!R.length||!p,"aria-busy":!!T||void 0,onClick:()=>void z(),children:[T&&(0,$.jsx)(F,{}),`Import `,R.length||``]})]}),children:[u===void 0?(0,$.jsx)(C,{label:`Account`}):u?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(a,{label:`Import`,rows:[{key:`step`,label:`Step`,control:{type:`select`,value:p,options:zl(n),onChange:m}},{key:`latest`,label:`Latest`,width:`quarter`,control:{type:`text`,value:S,placeholder:`N`,onChange:e=>{w(e);let t=Number.parseInt(e,10);t>0&&x(new Set(P.slice(0,t).map(e=>e.id)))}}}]}),h?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(d,{noun:`runs`,count:{shown:P.length,total:h.length},lead:(0,$.jsx)(`input`,{type:`checkbox`,"aria-label":`Select all shown`,checked:L,disabled:!P.length,onChange:()=>x(L?new Set:new Set(P.map(e=>e.id)))}),filters:[{key:`status`,label:`Status`,value:_,onChange:v,options:[{value:``,label:`All`},...N.map(e=>({value:e,label:e}))]}]}),P.length?(0,$.jsx)(`div`,{className:`sflow`,children:(0,$.jsx)(J,{className:`slist`,label:`Runs`,rows:P,rowKey:e=>e.id,pageSize:20,rowProps:e=>({onClick:()=>I(e.id),"data-selected":y.has(e.id)||void 0}),columns:[{key:`pick`,header:``,sort:null,cell:e=>(0,$.jsx)(`input`,{type:`checkbox`,"aria-label":`Run ${e.id}`,checked:y.has(e.id),onChange:()=>I(e.id),onClick:e=>e.stopPropagation()})},{key:`start`,header:`Started`,sort:e=>e.startTime??``,cell:e=>e.startTime?jc(Date.parse(e.startTime)/1e3):`—`},{key:`status`,header:`Status`,sort:e=>e.status,cell:e=>e.status}]})}):(0,$.jsx)(`p`,{className:`note`,children:`No runs.`})]}):(0,$.jsx)(C,{label:`Runs`,error:k,onRetry:()=>M(e=>e+1)})]}):(0,$.jsx)(`div`,{className:`sacts`,children:(0,$.jsxs)(`button`,{type:`button`,className:`ghost`,onClick:()=>{Pl(Ml,t.id),Zc(e).catch(e=>{Pl(Ml,null),O(Fl(e))})},children:[(0,$.jsx)(Ln,{size:14,"aria-hidden":`true`}),` Sign in with Microsoft`]})}),D&&(0,$.jsx)(`p`,{className:`note bad`,role:`alert`,children:D})]})}function Kl({steps:e,onClose:n,onAdd:r}){let[i,o]=(0,X.useState)(e[0]?.name??``),[s,c]=(0,X.useState)({}),l=e.find(e=>e.name===i),u=(l?.reads??[]).filter(e=>S(e));return(0,$.jsxs)(b,{title:`Add call`,onClose:n,wide:!0,dirty:Object.values(s).some(Boolean),footer:(0,$.jsxs)(`div`,{className:`sacts`,children:[(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:n,children:`Cancel`}),(0,$.jsx)(`button`,{type:`button`,disabled:!l,onClick:()=>{if(!l)return;let e=Object.fromEntries(Object.entries(s).filter(([e,t])=>t!==``&&u.some(t=>S(t)===e))),[n]=t(l,[e]).records;r({...n,origin:{kind:`hand`}})},children:`Add`})]}),children:[(0,$.jsx)(a,{label:`Call`,rows:[{key:`step`,label:`Step`,control:{type:`select`,value:i,options:zl(e),onChange:e=>{o(e),c({})}}},...u.map(e=>({key:`read-${S(e)}`,label:Bl(e),control:{type:`textarea`,value:s[S(e)]??``,onChange:t=>c(n=>({...n,[S(e)]:t}))}}))]}),l&&!u.length&&(0,$.jsx)(`p`,{className:`note`,children:`Reads nothing.`})]})}function ql(e,t){if(e.toLowerCase().endsWith(`.csv`))return{rows:P(t)};let n=JSON.parse(t),r=Array.isArray(n)?n:[n];if(r.length&&r.every(e=>!!e&&typeof e==`object`&&e.format===`evals-lab/record`))return{records:r.map(Rt)};if(r.every(e=>e&&typeof e==`object`&&!Array.isArray(e)))return{rows:r};throw Error(`a file of records, or rows of objects`)}function Jl({steps:e,onClose:n,onRead:r}){let i=(0,X.useRef)(null),[o,s]=(0,X.useState)(e[0]?.name??``),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(null),f=e.find(e=>e.name===o),p=c&&f&&`rows`in c.parsed?t(f,c.parsed.rows):null,m=c?`records`in c.parsed?c.parsed.records:p?.records??[]:[],h=async e=>{if(e){d(null);try{l({name:e.name,parsed:ql(e.name,await jl(e))})}catch(t){l(null),d(`${e.name}: ${Fl(t)}`)}}};return(0,$.jsxs)(b,{title:`Upload`,onClose:n,wide:!0,dirty:!!c,footer:(0,$.jsxs)(`div`,{className:`sacts`,children:[(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:n,children:`Cancel`}),(0,$.jsxs)(`button`,{type:`button`,disabled:!m.length,onClick:()=>void r(m),children:[`Add `,m.length||``]})]}),children:[(0,$.jsx)(a,{label:`Upload`,rows:[...c&&`records`in c.parsed?[]:[{key:`step`,label:`Step`,control:{type:`select`,value:o,options:zl(e),onChange:s}}],{key:`file`,label:`File`,control:{type:`static`,text:c?.name??`—`}},...c?[{key:`count`,label:`records`in c.parsed?`Calls`:`Rows`,control:{type:`static`,text:String(m.length)}}]:[],...p?.unmatched.length?[{key:`unmatched`,label:`Unmatched`,control:{type:`static`,text:p.unmatched.join(`, `)}}]:[]]}),(0,$.jsxs)(`div`,{className:`sacts`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`ghost`,onClick:()=>i.current?.click(),children:[(0,$.jsx)(K,{size:14,"aria-hidden":`true`}),` Choose file`]}),(0,$.jsx)(`input`,{ref:i,type:`file`,accept:`.json,.csv`,hidden:!0,"aria-hidden":`true`,onChange:e=>{h(e.target.files?.[0]),e.target.value=``}})]}),u&&(0,$.jsx)(`p`,{className:`note bad`,role:`alert`,children:u})]})}var Yl=e=>e instanceof Error?e.message:String(e),Xl=e=>e.toLowerCase().endsWith(`.json`),Zl=e=>L().METRICS[e.type]?.label??e.type;function Ql({source:e,definition:t,step:n,connections:r,onClose:i}){let o=Z(),s=hr(),c=Ye(),[l,u]=Q(`promptlab.connections`),[d,f]=Q(`promptlab.workflows`),[p]=Q(`promptlab.versions`),[m,h]=(0,X.useState)(null),[g,_]=(0,X.useState)(null),[v,y]=(0,X.useState)(!1),[x,S]=(0,X.useState)(null),w=(0,X.useCallback)(()=>{_(null),(async()=>{try{let t=(await o.source(e.id)).files.filter(e=>Xl(e.name)),n=await Promise.all(t.map(async t=>({name:t.name,record:JSON.parse(await jl(await o.file(e.id,t.name)))})));h(n)}catch(e){_(Yl(e))}})()},[o,e.id]);(0,X.useEffect)(w,[w]);let T=vl(t,n),E=m?Cl(m,t,r):null,D=T.some(e=>L().METRICS[e.type]?.graded),O=(0,X.useMemo)(()=>r.filter(e=>(L().CONNECTION_TYPES[e.type??``]?.answers??[`prompt`]).includes(`prompt`)),[r]),k=r.find(e=>e.id===l.grader)??null,[A,j]=(0,X.useState)(``),M=O.find(e=>e.id===A)??null,N=e=>{if(ml(e,r))return r;let t={id:L().newId(),model:``,key:``,..._l(e)};return u({...l,list:[...l.list,t]}),[...r,t]},P=async()=>{if(!E)return;y(!0),S(null);let r=String(n.template.uri??``),a=d;try{let o=await s.create(`${e.name} · ${n.name}`,{...er(),every:T,cases:E.cases,...M?{grader:{id:M.id,name:M.name}}:{}},{id:e.id,name:e.name}),l={id:o.id,name:o.name},u=yl({id:e.id,name:e.name},t,n,N(r),l),p={id:u.id,name:u.name,work:u};f({...d,list:[...d.list,p],at:p.id}),i(),location.hash=`#/runs`,c.offer({label:`Made a test of ${n.name}`,restore:()=>{f(a),s.remove(o.id).catch(()=>{})}})}catch(e){S(Yl(e)),y(!1)}};return(0,$.jsxs)(b,{title:`Create new pipeline test`,onClose:i,className:`edit`,footer:(0,$.jsxs)(`div`,{className:`sacts`,children:[v&&(0,$.jsx)(`span`,{className:`note`,role:`status`,children:`Making the test…`}),(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:i,children:`Cancel`}),(0,$.jsxs)(`button`,{type:`button`,disabled:v||!E?.cases.length,"aria-busy":v||void 0,onClick:()=>void P(),children:[v&&(0,$.jsx)(F,{}),`Create`]})]}),children:[m?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(a,{label:`Test`,rows:[{key:`pipeline`,label:`Pipeline`,control:{type:`static`,text:`${e.name} · ${n.name}`}},{key:`a`,label:`Target A`,control:{type:`static`,text:`Recorded — the reply each call got when the flow ran`}},{key:`b`,label:`Target B`,control:{type:`static`,text:`Edited — the step's own request, to change`}},{key:`checks`,label:`Checks`,control:{type:`static`,text:T.map(Zl).join(`, `)||`—`}},...D?[{key:`grader`,label:`Grader`,control:{type:`picker`,kind:`Connection`,value:A,usedLabel:`Last changed`,...wo(O,e=>p.profile?.[e]?.[0]?.at??null,[{id:``,label:k?`Lab (${k.name})`:`None — add one later`}]),onChange:j}}]:[],{key:`calls`,label:`Calls graded`,control:{type:`static`,text:`${E.cases.length}${E.skipped?`, ${E.skipped} with no recorded reply left out`:``}`}}]}),!E.cases.length&&(0,$.jsx)(`p`,{className:`note`,children:`No call holds a recorded reply to grade against.`})]}):(0,$.jsx)(C,{label:`Calls`,error:g,onRetry:w}),x&&(0,$.jsx)(`p`,{className:`note bad`,role:`alert`,children:x})]})}function $l({source:e}){let t=Z(),n=rl(),[r,i]=(0,X.useState)(null),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(!1),[u,f]=(0,X.useState)(null),p=e.config??{},m=(0,X.useCallback)(()=>{f(null),t.definition(e.id).then(i,e=>{i(null),f(e instanceof Error?e.message:String(e))})},[t,e.id,p.flow]);(0,X.useEffect)(m,[m]);let h=async()=>{if(n&&r&&p.environment&&p.flow){l(!0),s(null);try{if(!await qc(n)){await Zc(n);return}let a=await al(il(n),p.environment,p.flow);i(await t.saveDefinition(e.id,r.version,a.definition)),s(`Synced.`)}catch(e){e instanceof mn&&e.status===409?(m(),s(`It changed since: reloaded.`)):s(e instanceof Error?e.message:String(e))}finally{l(!1)}}},g=(0,X.useMemo)(()=>eu(r?.body),[r]),_=(0,X.useMemo)(()=>Ge(r?.body),[r]),[v]=Q(`promptlab.connections`),[y,b]=(0,X.useState)(null),[x,S]=(0,X.useState)(``),[w,T]=(0,X.useState)(`testable`),[D,O]=(0,X.useState)(``),k=e=>_.some(t=>t.name===e.name),A=(0,X.useMemo)(()=>[...new Set(g.map(e=>e.type).filter(Boolean))].sort(),[g]),j=g.filter(e=>(w===`all`||k(e))&&(!D||e.type===D)&&e.name.toLowerCase().includes(x.trim().toLowerCase()));return(0,$.jsxs)(`div`,{className:`sources`,"data-level":`flow`,children:[o&&(0,$.jsx)(`p`,{className:`note`,role:`status`,children:o}),(0,$.jsxs)(E,{id:`flow-source`,title:`Flow`,actions:[{label:`Re-sync`,icon:Hn,busy:c,disabled:!n||!r,onSelect:()=>void h()}],children:[(0,$.jsx)(a,{label:`Flow`,rows:[...p.displayName&&p.displayName!==e.name?[{key:`flow`,label:`Flow`,control:{type:`static`,text:p.displayName}}]:[],{key:`env`,label:`Environment`,control:{type:`static`,text:p.environmentName||p.environment||`—`}},...r?[{key:`version`,label:`Definition`,control:{type:`static`,text:r.version?`V${r.version}${r.at?`, ${Nc(r.at)}`:``}`:`None`}}]:[]]}),!r&&(0,$.jsx)(C,{label:`Definition`,error:u,onRetry:m})]}),(0,$.jsx)(E,{id:`flow-actions`,title:`Actions`,note:r?String(g.length):void 0,children:r?g.length?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(d,{noun:`actions`,search:{label:`Find an action`,value:x,placeholder:`Name`,onChange:S},quick:{label:`Show`,value:w,onChange:e=>T(e),options:[{value:`all`,label:`All`},{value:`testable`,label:`Can be tested`}]},filters:[{key:`type`,label:`Type`,value:D,onChange:O,options:[{value:``,label:`All`},...A.map(e=>({value:e,label:e}))]}],count:{shown:j.length,total:g.length}}),j.length?(0,$.jsx)(`div`,{className:`sflow`,children:(0,$.jsx)(J,{className:`slist`,label:`Actions`,rows:j,rowKey:e=>e.name,defaultSort:null,columns:[{key:`name`,header:`Name`,role:`title`,sort:e=>e.name,cell:e=>(0,$.jsxs)($.Fragment,{children:[e.name,e.in&&(0,$.jsxs)(`span`,{className:`sflow-in`,children:[`in `,e.in]})]})},{key:`type`,header:`Type`,sort:e=>e.type,cell:e=>e.type},{key:`calls`,header:`Calls`,sort:e=>e.calls,cell:e=>e.calls||`—`},{key:`menu`,header:``,className:`s-actions`,role:`menu`,sort:null,cell:e=>{let t=_.find(t=>t.name===e.name);return t?(0,$.jsx)(me,{label:`${e.name} actions`,actions:[{label:`Test…`,icon:Yt,onSelect:()=>b(t)}]}):null}}]})}):(0,$.jsx)(`p`,{className:`note`,children:`No actions match.`})]}):(0,$.jsx)(`p`,{className:`note`,children:`No actions.`}):(0,$.jsx)(C,{label:`Actions`,error:u,onRetry:m})}),(0,$.jsx)(Il,{source:e,definition:r?.body??null,cfg:n}),y&&r&&(0,$.jsx)(Ql,{source:e,definition:r.body,step:y,connections:v.list,onClose:()=>b(null)})]})}function eu(e){let t=[],n=(e,i)=>{for(let[a,o]of Object.entries(e??{})){t.push({name:a,type:o.type??``,in:i,calls:r(o)}),n(o.actions,a),n(o.else?.actions,`${a} (else)`);for(let[e,t]of Object.entries(o.cases??{}))n(t.actions,`${a} (${e})`);n(o.default?.actions,`${a} (default)`)}},r=e=>{if(e.type===`Http`&&typeof e.inputs?.uri==`string`)try{return new URL(e.inputs.uri).host}catch{return e.inputs.uri.startsWith(`@`)?`(expression)`:``}let t=e.inputs?.host?.apiId??e.inputs?.host?.connectionName;return t?t.split(`/`).pop()??``:``};return n(e?.actions,``),t}var tu={url:`URL`,reqHeaders:`Headers`,body:`Body`,method:`Method`,connection:`Auth connection`,path:`Path`,command:`Command`,args:`Arguments`},nu=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`];function ru({typeRow:e,which:t,initial:n,onMade:r,bind:i}){let o=Z(),[s]=Q(`promptlab.connections`),c=L().DYNAMIC_PROVIDERS,l=n?n.config?.provider:t,u=l&&l in c?l:n?``:Object.keys(c)[0]??``,d=c[u],f=!!d&&d.tier!==`supplied`&&!n,[p,m]=(0,X.useState)(()=>{let{provider:e,...t}=n?.config??{};return t}),[h,g]=(0,X.useState)(n?.name??``),[_,v]=(0,X.useState)(!0),[y,b]=(0,X.useState)(!1),[x,S]=(0,X.useState)(null),C=d?d.configProblems(p):[`unknown provider`],w=!!d&&!!h.trim()&&C.length===0,T={provider:u,...p},E=!!n&&!iu(T,n.config??{}),D=!!n&&h.trim()!==n.name,O=E||D,k=(0,X.useRef)(async()=>{});(0,X.useEffect)(()=>{i({enabled:w&&!y,busy:y,changed:O,run:()=>void k.current()})},[i,w,y,O]),(0,X.useEffect)(()=>()=>i(null),[i]),k.current=async()=>{if(!d||!w)return;if(n&&!O){await r(n);return}b(!0),S(null);let e=null;try{if(n){await r(await o.updateSource(n.id,{...D?{name:h.trim()}:{},...E?{config:T}:{}}));return}let t=await o.createSource(h.trim(),`dynamic`,T);e=t.id,f&&_&&await o.snapshotSource(t.id).catch(()=>{}),await r(t)}catch(t){e&&await o.removeSource(e).catch(()=>{}),S(t instanceof mn||t instanceof Error?t.message:String(t))}finally{b(!1)}};let A=e=>t=>m(n=>({...n,[e]:t})),j=e=>{let t=p[e]??``;return e===`method`?{type:`select`,value:t||`GET`,onChange:A(e),options:nu.map(e=>({value:e,label:e}))}:e===`connection`?{type:`select`,value:t,onChange:A(e),options:[{value:``,label:`No auth`},...s.list.map(e=>({value:e.id,label:e.name||e.id}))]}:e===`reqHeaders`||e===`body`||e===`args`?{type:`textarea`,value:t,onChange:A(e),placeholder:e===`reqHeaders`?`Name: value; Name: value`:e===`args`?`One a line`:``}:{type:`text`,value:t,onChange:A(e),...e===`url`?{placeholder:`https://…`}:{}}},M=(d?.config??[]).map(e=>({key:e,label:tu[e]??e.charAt(0).toUpperCase()+e.slice(1),control:j(e)}));return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(a,{label:n?n.name:`New Source`,rows:[e,...M,{key:`name`,label:`Name`,width:`full`,control:{type:`text`,value:h,onChange:g}}]}),f&&(0,$.jsx)(`div`,{className:`sacts`,children:(0,$.jsx)(st,{checked:_,onChange:v,label:`Snapshot now`})}),d?.warning&&(0,$.jsxs)(`p`,{className:`swarn`,role:`note`,children:[(0,$.jsx)(We,{size:14,"aria-hidden":`true`}),d.warning]}),!!h.trim()&&C.length>0&&(0,$.jsx)(`p`,{className:`note bad`,role:`alert`,children:C[0]}),x&&(0,$.jsx)(`p`,{className:`note bad`,role:`alert`,children:x})]})}var iu=(e,t)=>[...new Set([...Object.keys(e),...Object.keys(t)])].every(n=>(e[n]??``)===(t[n]??``)),au=`The reply does what the prompt asks of the item, and says nothing the item does not support.`,ou=`#default`,su=e=>e instanceof Error?e.message:String(e);function cu({source:e,calls:t,plural:n,onClose:i}){let o=hr(),s=Ye(),[c]=Q(`promptlab.connections`),[l]=Q(`promptlab.connectionProfiles`),[u,d]=Q(`promptlab.workflows`),[f]=Q(`promptlab.versions`),{list:p,error:m}=Er(),[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(null),y=(0,X.useMemo)(()=>c.list.filter(e=>(L().CONNECTION_TYPES[e.type??``]?.answers??[`prompt`]).includes(`prompt`)),[c.list]),x=(0,X.useMemo)(()=>L().answersOf(L().withSlugs(c.list),l.list).split,[c.list,l.list]),S=e=>f.profile?.[e]?.[0]?.at??null,[C,w]=(0,X.useState)(y[0]?.id??``),[T,E]=(0,X.useState)(null),[D,O]=(0,X.useState)(null),[k,A]=(0,X.useState)(``),[j,M]=(0,X.useState)(``),N=y.find(e=>e.id===c.grader)??null,P=T??x(C)?.id??ou,I=D??(N?``:C),R=p!==null||m!==null,z=k.trim()||(p?.find(e=>e.default)?.text??``),B=(e,t)=>{let n=e.find(e=>e.id===t);return n?{id:n.id,name:n.name}:null},ee=async()=>{let a=B(y,C);if(!a)return;g(!0),v(null);let c=u,f={type:`llm-rubric`,...L().METRICS[`llm-rubric`].defaults(),rubric:j.trim()||`The reply does what the prompt asks of the item, and says nothing the item does not support.`},p=I?B(y,I):null;try{let m=await o.create(`${e.name} · ${n}`,{...er(),every:[f],cases:wl(t).map(e=>({...e,todo:!1})),...p?{grader:p}:{}},{id:e.id,name:e.name}),h=r(e,{connection:a,profile:P===ou?null:B(l.list,P)},{id:m.id,name:m.name},z),g={id:h.id,name:h.name,work:h};d({...u,list:[...u.list,g],at:g.id}),i(),location.hash=`#/runs`,s.offer({label:`Made a test of ${e.name}`,restore:()=>{d(c),o.remove(m.id).catch(()=>{})}})}catch(e){v(su(e)),g(!1)}};return(0,$.jsxs)(b,{title:`Create new pipeline test`,onClose:i,className:`edit`,footer:(0,$.jsxs)(`div`,{className:`sacts`,children:[h&&(0,$.jsx)(`span`,{className:`note`,role:`status`,children:`Making the test…`}),(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:i,children:`Cancel`}),(0,$.jsxs)(`button`,{type:`button`,disabled:h||!C||!R||!z,"aria-busy":h||void 0,onClick:()=>void ee(),children:[h&&(0,$.jsx)(F,{}),`Create`]})]}),children:[(0,$.jsx)(a,{label:`Test`,rows:[{key:`pipeline`,label:`Pipeline`,control:{type:`static`,text:e.name}},{key:`connection`,label:`Connection`,required:!0,control:{type:`picker`,kind:`Connection`,value:C,usedLabel:`Last changed`,...wo(y,S),onChange:e=>{w(e),E(null)}}},{key:`profile`,label:`Profile`,control:{type:`picker`,kind:`Profile`,value:P,...wo(l.list,()=>null,[{id:ou,label:`(Default)`}]),onChange:E}},{key:`prompt`,label:`Prompt`,required:!z,control:{type:`textarea`,value:k,onChange:A,placeholder:p?.find(e=>e.default)?.text??``}},{key:`rubric`,label:`Rubric`,control:{type:`textarea`,value:j,onChange:M,placeholder:au}},{key:`grader`,label:`Grader`,control:{type:`picker`,kind:`Connection`,value:I,usedLabel:`Last changed`,...wo(y,S,[{id:``,label:N?`Lab (${N.name})`:`None — add one later`}]),onChange:O}},{key:`calls`,label:`${n[0].toUpperCase()}${n.slice(1)} graded`,control:{type:`static`,text:String(t.length)}}]}),_&&(0,$.jsx)(`p`,{className:`note bad`,role:`alert`,children:_})]})}var lu=e=>e instanceof Error?e.message:String(e);function uu({source:e,bind:t}){let n=e.config??{},r=L().DYNAMIC_PROVIDERS[n.provider??``];return(0,$.jsxs)(`div`,{className:`sources`,"data-level":`dynamic`,children:[n.url&&(0,$.jsx)(E,{id:`dynamic-provider`,title:`Provider`,children:(0,$.jsx)(a,{label:`Provider`,rows:[{key:`url`,label:`URL`,control:{type:`code`,text:n.url}}]})}),(0,$.jsx)(du,{source:e,noun:r?.noun??`call`,canProduce:r?.tier!==`supplied`,takes:Object.keys(r?.uploads??{}),bind:t})]})}function du({source:e,noun:t,canProduce:n,takes:r,bind:i}){let a=Z(),o=hr(),s=Ye(),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)(!1),_=(0,X.useRef)(null),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(null),[S,w]=(0,X.useState)(null),[T,D]=(0,X.useState)(!1),O=`${t}s`,k=(c??[]).filter(e=>!e.error).map(e=>e.name),A=k.join(`
|
|
9
|
-
`);(0,X.useEffect)(()=>{i?.({label:`Create test…`,icon:Yt,disabled:!A,onSelect:()=>D(!0)})},[i,A]),(0,X.useEffect)(()=>()=>i?.(null),[i]);let j=(0,X.useCallback)(()=>{d(null),a.sourceCalls(e.id).then(e=>{l(e.calls),w(null)},e=>d(lu(e)))},[a,e.id]);(0,X.useEffect)(j,[j]);let N=async()=>{h(!0),p(null);try{let{call:n}=await a.snapshotSource(e.id);p(n.error?`The ${t} failed: ${n.error}`:`Snapshotted ${n.name}`),j()}catch(e){p(lu(e))}finally{h(!1)}},P=async t=>{if(t){p(null);try{await a.upload(e.id,t.name,t),j()}catch(e){p(lu(e))}}},F=async()=>{let n=k;if(!n.length)return p(`No ${t} to grade yet.`);try{let t=await o.create(`${e.name} · ${O}`,{...er(),cases:wl(n)},{id:e.id,name:e.name});p(`Made ${t.name}: ${n.length} ${n.length===1?`case`:`cases`}`)}catch(e){p(lu(e))}},I=async t=>{try{let{trash:n}=await a.removeCalls(e.id,t);l(e=>(e??[]).filter(e=>!t.includes(e.name)));let r=t.length===1?`Removed ${t[0]}`:`Removed ${t.length} ${O}`;n?s.offer({label:r,restore:()=>void a.restoreTrash(n).then(j,e=>p(lu(e)))}):p(r)}catch(e){p(lu(e))}},L=async t=>{if(t.error)return x({call:t,text:null});try{x({call:t,text:await(await a.file(e.id,t.name)).text()})}catch(e){p(lu(e))}},R=async(t,n,r,i)=>{let o=i===n?void 0:i,{call:c}=await a.editCall(e.id,t.name,{...r===t.name?{}:{to:r},...o===void 0?{}:{content:o}});j(),s.offer({label:o===void 0?`Renamed ${t.name}`:`Edited ${t.name}`,restore:()=>void a.editCall(e.id,c.name,{...c.name===t.name?{}:{to:t.name},...o===void 0?{}:{content:n},origin:t.origin}).then(j,e=>p(lu(e)))})},z=async t=>{try{let{call:n}=await a.cloneCall(e.id,t);l(e=>(e??[]).flatMap(e=>e.name===t?[e,{...e,name:n.name}]:[e])),w(n.name),s.offer({label:`Cloned ${t}`,restore:()=>void a.removeCalls(e.id,[n.name]).then(()=>l(e=>(e??[]).filter(e=>e.name!==n.name)),e=>p(lu(e)))})}catch(e){p(lu(e))}},B=(t,n)=>[...n?[]:[{label:`Edit…`,icon:M.edit,disabled:!!t.error,onSelect:()=>void L(t)}],{label:`Clone`,icon:M.clone,disabled:!!t.error,onSelect:()=>{n&&x(null),z(t.name)}},{label:`Download`,icon:M.export,disabled:!!t.error,onSelect:()=>void mu(a,e.id,t.name).catch(e=>p(lu(e)))},{label:`Remove`,icon:M.remove,destructive:!0,onSelect:()=>{n&&x(null),I([t.name])}}],ee=[{label:`Upload…`,icon:K,onSelect:()=>_.current?.click()},{label:`New dataset`,icon:g,disabled:!(c??[]).some(e=>!e.error),onSelect:()=>void F()}];return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(E,{id:`dynamic-calls`,title:`Calls`,note:c?String(c.length):void 0,about:n?`Calls are captures this Source produced; grade them, or produce fresh at run time.`:`Items handed in to this Source: write or upload them here, or hand them in through the CLI, and grade them.`,actions:ee,children:[f&&(0,$.jsx)(`p`,{className:`note`,role:`status`,children:f}),c===null?(0,$.jsx)(C,{label:`Calls`,error:u,onRetry:j}):c.length?(0,$.jsx)(`div`,{className:`sflow`,children:(0,$.jsx)(J,{className:`slist`,cards:!0,label:`Calls`,rows:c,rowKey:e=>e.name,select:{noun:t,actions:e=>[{label:`Remove`,icon:M.remove,destructive:!0,onSelect:()=>void I(e.map(e=>e.name))}]},rowProps:e=>e.name===S?{"data-fresh":``}:{},columns:[{key:`name`,header:`Name`,role:`title`,sort:e=>e.name.replace(/\.[^.]*$/,``),cell:e=>(0,$.jsx)(`button`,{type:`button`,className:`sopen`,onClick:()=>void L(e),children:e.name})},{key:`origin`,header:`Origin`,sort:e=>Ol(e.origin),cell:e=>Ol(e.origin)},{key:`at`,header:`Produced`,sort:e=>e.at??``,cell:e=>e.at&&Nc(e.at)||`—`},{key:`result`,header:`Result`,sort:e=>e.error?`fail`:`ok`,cell:e=>e.error?(0,$.jsxs)(`span`,{className:`sresult`,title:e.error,children:[(0,$.jsx)(_e,{pass:!1,decorative:!0}),`Failed`]}):(0,$.jsxs)(`span`,{className:`sresult`,children:[(0,$.jsx)(_e,{pass:!0,decorative:!0}),e.status??`OK`]})},{key:`menu`,header:``,className:`s-actions`,role:`menu`,sort:null,cell:e=>(0,$.jsx)(me,{label:`${e.name} actions`,actions:B(e,!1)})}]})}):(0,$.jsxs)(`p`,{className:`note`,children:[`No `,O,` yet. `,n?`Snapshot now produces one, below.`:`Write or upload one, or hand them in through the CLI.`]}),n?(0,$.jsxs)(`button`,{type:`button`,className:`ghost add-btn`,"aria-busy":m||void 0,disabled:m,onClick:()=>void N(),children:[(0,$.jsx)(ze,{size:14,"aria-hidden":`true`}),` Snapshot now`]}):(0,$.jsxs)(`button`,{type:`button`,className:`ghost add-btn`,onClick:()=>y(!0),children:[(0,$.jsx)(ze,{size:14,"aria-hidden":`true`}),` New `,t,`…`]})]}),(0,$.jsx)(`input`,{ref:_,type:`file`,accept:`.txt,.json,.csv,.md`,hidden:!0,"aria-hidden":`true`,onChange:e=>{P(e.target.files?.[0]),e.target.value=``}}),v&&(0,$.jsx)(fu,{noun:t,takes:r,onSave:async(t,n)=>{try{await a.upload(e.id,t,new Blob([n],{type:`text/plain`}))}finally{j()}},onClose:()=>y(!1)}),T&&(0,$.jsx)(cu,{source:e,calls:k,plural:O,onClose:()=>D(!1)}),b&&(0,$.jsx)(pu,{call:b.call,text:b.text,menu:B(b.call,!0),taken:e=>(c??[]).some(t=>t.name===e),onSave:(e,t)=>R(b.call,b.text??``,e,t),onClose:()=>x(null)}),(0,$.jsx)(Vt,{undo:s.undo,onUndo:s.undoNow,onDismiss:s.dismiss})]})}function fu({noun:e,takes:t,onSave:n,onClose:r}){let[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(null),f=async()=>{let a=i.trim(),s=/\.[^./]+$/.exec(a)?.[0].toLowerCase(),c=s?a:`${a}.txt`;if(!a)return d(`A ${e} needs a name.`);if(s&&t.length&&!t.includes(s))return d(`A ${e}'s name ends ${t.join(`, `)}.`);if(!o.trim())return d(`A ${e} needs some text.`);l(!0);try{await n(c,o),r()}catch(e){d(lu(e)),l(!1)}};return(0,$.jsx)(ut,{title:`New ${e}`,focusRow:`name`,status:u??void 0,statusBad:!!u,wide:!0,sections:[{key:`item`,rows:[{key:`name`,label:`Name`,width:`full`,required:!0,control:{type:`text`,value:i,onChange:a,placeholder:`notes.txt`}},{key:`text`,label:`Text`,required:!0,control:{type:`textarea`,value:o,onChange:s}}]}],onSave:()=>void f(),saving:c,onClose:r})}function pu({call:e,text:t,menu:n,taken:r,onSave:i,onClose:a}){let[o,s]=(0,X.useState)(t??``),c=e.request,l=c?.url?`${c.method??`GET`} ${c.url}`:c?.path??c?.command,u=[...l?[{key:`request`,label:`Request`,control:{type:`code`,text:l}}]:[],...e.error?[{key:`error`,label:`Error`,control:{type:`static`,text:e.error}}]:[...e.status==null?[]:[{key:`status`,label:`Status`,control:{type:`static`,text:String(e.status)}}],...e.at?[{key:`at`,label:`Produced`,control:{type:`static`,text:Pc(e.at)}}]:[]]];return t===null?(0,$.jsx)(kl,{name:e.name,facts:u,taken:r,menu:n,onClose:a}):(0,$.jsx)(kl,{name:e.name,facts:u,taken:r,menu:n,onClose:a,changed:o!==t,onSave:e=>i(e,o),sections:[{key:`content`,title:`Content`,children:(0,$.jsx)(`textarea`,{className:`mono call-content`,"aria-label":`Content`,spellCheck:!1,value:o,onChange:e=>s(e.target.value)})}]})}async function mu(e,t,n){let r=URL.createObjectURL(await e.file(t,n)),i=document.createElement(`a`);i.href=r,i.download=n,document.body.append(i),i.click(),i.remove(),URL.revokeObjectURL(r)}var hu={workflow:{Create:ul,Level:$l},dynamic:{Create:ru,Level:uu}},gu=e=>{let t=L().SOURCE_TYPES[e.type]?.label??e.type,n=e.provider?L().DYNAMIC_PROVIDERS[e.provider]?.label??e.provider:e.platform?L().WORKFLOW_PLATFORMS[e.platform]?.label??e.platform:null;return n?`${t} · ${n}`:t},_u=e=>e instanceof mn?e.message:`the request failed`;function vu({source:e,onSaved:t,onClose:n}){let r={key:`kind`,label:`Kind`,control:{type:`code`,text:gu(e)}},i=hu[e.type]?.Create;return i?(0,$.jsx)(bu,{source:e,kindRow:r,Create:i,onSaved:t,onClose:n}):(0,$.jsx)(yu,{source:e,kindRow:r,onSaved:t,onClose:n})}function yu({source:e,kindRow:t,onSaved:n,onClose:r}){let i=Z(),[a,o]=(0,X.useState)(e.name),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(null),d=async()=>{let t=a.trim();if(!t||t===e.name){r();return}c(!0);try{n(await i.updateSource(e.id,{name:t})),r()}catch(e){u(_u(e)),c(!1)}};return(0,$.jsx)(ut,{title:`Edit ${e.name}`,focusRow:`name`,status:l??void 0,statusBad:!!l,sections:[{key:`source`,rows:[{key:`name`,label:`Name`,width:`full`,required:!0,control:{type:`text`,value:a,onChange:o}},t]}],onSave:()=>void d(),saving:s,onClose:r})}function bu({source:e,kindRow:t,Create:n,onSaved:r,onClose:i}){let a=Z(),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(0),[f,p]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let t=!0;return a.source(e.id).then(e=>{t&&s(e)},e=>{t&&l(_u(e))}),()=>{t=!1}},[a,e.id,u]),(0,$.jsx)(ut,{title:`Edit ${e.name}`,dirty:!!f?.changed,sections:[{key:`source`,children:o?(0,$.jsx)(n,{typeRow:t,initial:o,bind:p,onMade:e=>{r(e),i()}}):(0,$.jsx)(C,{label:`Source`,error:c,onRetry:()=>{l(null),d(e=>e+1)}})}],actions:[{label:`Save & Close`,primary:!0,disabled:!f?.enabled,busy:!!f?.busy,onSelect:()=>f?.run()}],onClose:i})}var xu={folder:Qt,workflow:Oe,globe:Ae,upload:K,file:On,terminal:qn,"square-code":Kn},Su=new Set([`square-code`]);function Cu(e,t,n){let r=t?L().WORKFLOW_PLATFORMS[t]:void 0,i=n?L().DYNAMIC_PROVIDERS[n]:void 0;return r?.icon??i?.icon??L().SOURCE_TYPES[e]?.icon}function wu({name:e,size:t=16}){let n=e&&xu[e]||Qt;return(0,$.jsx)(n,{className:`skind`,size:t,fill:e&&Su.has(e)?`none`:`currentColor`,"aria-hidden":`true`})}function Tu({sourceId:e=null,onOpen:t,onGone:n,mode:r=`browse`,onPick:i,disabled:o}){let s=uo(),c=Z(),l=Ye(),[u]=Q(`promptlab.workflows`),[f,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(0),[_,v]=(0,X.useState)(0),[y,x]=(0,X.useState)(null),[S,w]=(0,X.useState)(bc),[T,D]=(0,X.useState)(``),[O,A]=(0,X.useState)(new Set),[j,N]=(0,X.useState)(null),[P,I]=(0,X.useState)(!1),[R,z]=(0,X.useState)(()=>r===`browse`&&Du()!==null),[ee,V]=(0,X.useState)(null),[H,te]=(0,X.useState)(null),[U,W]=(0,X.useState)(null),[ne,G]=(0,X.useState)(void 0),[re,ie]=(0,X.useState)(!1),[ae,q]=(0,X.useState)(``),[oe,se]=(0,X.useState)(()=>r===`browse`&&Du()||L().DEFAULT_SOURCE_TYPE),[ce,de]=(0,X.useState)(null),[pe,me]=(0,X.useState)(null),[he,ge]=(0,X.useState)(``),[_e,ve]=(0,X.useState)(``),[ye,be]=(0,X.useState)([]),[xe,Se]=(0,X.useState)(null),[Ce,we]=(0,X.useState)([]),[Te,Ee]=(0,X.useState)(!1),[De,Oe]=(0,X.useState)(!1),[ke,Ae]=(0,X.useState)(null),[je,Me]=(0,X.useState)(null),[Ne,Pe]=(0,X.useState)(0),[Fe,Ie]=(0,X.useState)(0),Le=(0,X.useRef)(null),Re=(0,X.useRef)(1),{view:Be,sort:Ve,dir:Ue}=S,We=(0,X.useCallback)(()=>V(null),[]),Ge=(0,X.useCallback)(()=>z(!1),[]),Ke=(0,X.useCallback)(()=>te(null),[]),qe=(0,X.useCallback)(()=>ie(!1),[]);(0,X.useEffect)(()=>xc(S),[S]),(0,X.useEffect)(()=>{r===`browse`&&Ou(R?oe:null)},[r,R,oe]),(0,X.useEffect)(()=>{let e=!0;return c.config().then(t=>{e&&be(t.dynamicProviders??[])},()=>{}),()=>{e=!1}},[c]),(0,X.useEffect)(()=>{if(!U?.platform){G(void 0);return}let e=!0;return Promise.all([c.connections(),c.connectionShares()]).then(([{connections:t},{shares:n}])=>{if(!e)return;let r=t.find(e=>e.id===`microsoft`);if(!r){G(void 0);return}let i=n[hn(`account`,r.id)];G({name:r.label,sharedWith:e=>!i||i.includes(e)||i.includes(`*all`)})},()=>{e&&G(void 0)}),()=>{e=!1}},[U,c]);let Je=async()=>{try{let e=await c.sources();m(e.sources),g(e.cap),v(e.used)}catch{}};(0,X.useEffect)(()=>{let e=!0;return c.sources().then(t=>{e&&(m(t.sources),g(t.cap),v(t.used))}).catch(t=>{e&&Ae(Qe(t))}),()=>{e=!1}},[c,Ne]),(0,X.useEffect)(()=>{A(new Set),we([]);let t=!0;return Me(null),e?c.source(e).then(e=>{t&&x(e)}).catch(e=>{t&&(x(null),e instanceof mn&&e.status===404&&n?n():Me(Qe(e)))}):x(null),()=>{t=!1}},[e,Fe]);let Xe=async()=>{if(!e){x(null);return}try{x(await c.source(e))}catch{x(null)}},Ze=e=>{Se(e),e&&window.setTimeout(()=>Se(null),6e3)},Qe=e=>e instanceof mn?e.message:`the request failed`,$e=kc(Oc(y?.files??[],Ve,Ue),T),et=e=>{A(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},tt=()=>A(new Set($e.map(e=>e.name))),nt=()=>A(new Set),rt=async e=>{let t=[];try{for(let n of e)t.push((await c.removeSource(n.id)).trash),m(e=>(e??[]).filter(e=>e.id!==n.id))}catch(e){Ze(Qe(e))}t.length&&l.offer({label:e.length===1?`Deleted ${e[0].name}`:`Deleted ${t.length} Sources`,restore:()=>void(async()=>{try{for(let e of t)await c.restoreTrash(e);await Je()}catch(e){Ze(Qe(e))}})()})},it=e=>rt([e]),at=async e=>{if(y)try{let{trash:t}=await c.removeFiles(y.id,e),n=new Set(e);x(t=>t&&{...t,files:t.files.filter(e=>!n.has(e.name)),bytes:t.bytes-e.reduce((e,n)=>e+(t.files.find(e=>e.name===n)?.bytes??0),0)}),A(e=>new Set([...e].filter(e=>!n.has(e)))),l.offer({label:e.length===1?`Removed ${e[0]}`:`Removed ${e.length} files`,restore:()=>void(async()=>{try{let e=await c.restoreTrash(t);x(e.source)}catch(e){Ze(Qe(e))}})()})}catch(e){Ze(Qe(e))}},ot=(e,t)=>{let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,document.body.append(r),r.click(),r.remove(),URL.revokeObjectURL(n)},st=async e=>{if(!y)return;let t=e.length===1?e[0]:null;Oe(!0);try{let n=t?await c.file(y.id,t):await c.zip(y.id,e);ot(n,t??`${y.name}.zip`)}catch(e){Ze(Qe(e))}finally{Oe(!1)}},ct=async e=>{if(!y||y.system)return;let t=[...e];if(!t.length)return;let n=t.map(e=>({id:Re.current++,file:e,state:`uploading`}));we(e=>[...e,...n]);for(let e of n)try{await c.upload(y.id,e.file.name,e.file),we(t=>t.map(t=>t.id===e.id?{...t,state:`done`}:t))}catch(t){we(n=>n.map(n=>n.id===e.id?{...n,state:`error`,error:Qe(t)}:n))}await Xe()},lt=e=>void ct([e.file]),ut=async(e,t)=>{if(y&&H)try{await c.copyFiles(t.id,y.id,H.names,e===`move`),te(null),A(new Set),await Xe(),Ze(e===`move`?`Moved to ${t.name}.`:`Copied to ${t.name}.`)}catch(e){Ze(Qe(e)),te(null)}},dt=async()=>{if(y&&ae.trim())try{let e=await c.createSource(ae.trim(),y.type);try{await c.copyFiles(e.id,y.id,[...O],!1)}catch(t){throw await c.removeSource(e.id).catch(()=>{}),t}ie(!1),q(``),A(new Set),await Je(),Ze(`Made a new Source.`)}catch(e){Ze(Qe(e))}},ft=async()=>{if(ae.trim())try{await c.createSource(ae.trim(),oe),z(!1),q(``),se(L().DEFAULT_SOURCE_TYPE),await Je()}catch(e){Ze(Qe(e))}},pt=j&&(0,$.jsx)(vu,{source:j,onSaved:e=>{m(t=>(t??[]).map(t=>t.id===e.id?Fc(e):t)),x(t=>t?.id===e.id?{...t,name:e.name,config:e.config??null}:t)},onClose:()=>N(null)}),mt=e=>s({tab:`library`,section:`sources`,id:e.id}),ht=(e,t)=>e.system?[mt(e)]:[{label:`Edit…`,icon:He,onSelect:()=>N(e)},mt(e),{label:`Copy or move…`,icon:M.transfer,onSelect:()=>W(e)},{label:`Delete`,icon:Lt,destructive:!0,onSelect:()=>void it(e).then(t)}],gt=e=>[{label:`Preview`,icon:le,disabled:!Tc(e.name),onSelect:()=>V(e)},{label:`Download`,icon:fe,onSelect:()=>void st([e.name])},...y?.system?[]:[{label:`Remove`,icon:Lt,destructive:!0,onSelect:()=>void at([e.name])}]],_t=[...y?.system?[]:[{label:`Remove`,icon:Lt,destructive:!0,onSelect:()=>void at([...O])}],{label:`Download`,icon:fe,busy:De,onSelect:()=>void st([...O])},...y?.system?[]:[{label:`Move to…`,icon:Mn,onSelect:()=>te({kind:`move`,names:[...O]})}],{label:`Copy to…`,icon:p,onSelect:()=>te({kind:`copy`,names:[...O]})},...y?.system?[]:[{label:`New Source from selection…`,icon:Nn,onSelect:()=>ie(!0)}]],vt=e=>{e.preventDefault(),Ee(!1),y&&!y.system&&ct(e.dataTransfer.files)},yt=U&&(0,$.jsx)(go,{subject:{kind:`source`,id:U.id,name:U.name},scan:{pipelines:u.list},undo:l,accountShare:ne,onClose:()=>{W(null),G(void 0)},onChanged:()=>{Je(),e===U.id&&t?.(null)}}),bt=(f??[]).filter(e=>(!_e||zu(e)===_e)&&e.name.toLowerCase().includes(he.trim().toLowerCase())),xt=(0,$.jsx)(Au,{view:Be,onChange:e=>w(t=>({...t,view:e}))}),St=e=>(0,$.jsx)(d,{noun:`Sources`,search:{label:`Find a Source`,value:he,placeholder:`Name`,onChange:ge},filters:[{key:`type`,label:`Type`,value:_e,onChange:ve,options:[{value:``,label:`All`},...Iu(ye).filter(e=>!e.disabled)]}],trail:e,count:{shown:bt.length,total:(f??[]).length}}),Ct=()=>(0,$.jsxs)(`div`,{className:`sources`,"data-level":`sources`,children:[xe&&(0,$.jsx)(`p`,{className:`note`,role:`status`,children:xe}),(0,$.jsxs)(`header`,{className:`shead`,children:[(0,$.jsx)(`h2`,{className:`shead-title`,children:`Sources`}),xt]}),f!==null&&f.length>0&&St(),f===null?(0,$.jsx)(C,{label:`Sources`,error:ke,onRetry:()=>{Ae(null),Pe(e=>e+1)}}):f.length===0?(0,$.jsx)(`p`,{className:`note`,children:`No Sources on the server yet.`}):Be===`thumbs`?(0,$.jsx)(`ul`,{className:`sfolders`,children:bt.map(e=>(0,$.jsx)(`li`,{className:`sfolder`,children:(0,$.jsxs)(`button`,{type:`button`,className:`sfolder-open${o?.(e)?` off`:``}`,disabled:o?.(e),onClick:()=>i?.(e),children:[(0,$.jsx)(wu,{name:Ru(e)}),(0,$.jsx)(`span`,{className:`sfolder-name`,children:e.name}),(0,$.jsx)(`span`,{className:`sfolder-meta`,children:Bu(e)})]})},e.id))}):(0,$.jsx)(J,{className:`slist slist-folders`,label:`Sources`,rows:bt,rowKey:e=>e.id,columns:[{key:`name`,header:`Name`,className:`sfile-name`,role:`title`,sort:e=>e.name,cell:e=>(0,$.jsxs)(`button`,{type:`button`,className:`srow-pick${o?.(e)?` off`:``}`,disabled:o?.(e),onClick:()=>i?.(e),children:[(0,$.jsx)(wu,{name:Ru(e)}),e.name]})},{key:`type`,header:`Type`,sort:e=>Bu(e),cell:e=>Bu(e)},{key:`files`,header:`Items`,className:`num`,cell:e=>e.files},{key:`size`,header:`Size`,className:`num`,sort:e=>e.bytes,cell:e=>Ac(e.bytes)}]})]});if(r===`pick`)return Ct();if(e){if(!y)return(0,$.jsx)(`div`,{className:`sources`,children:(0,$.jsx)(C,{label:`Files`,error:je,onRetry:()=>Ie(e=>e+1)})});let e=hu[y.type]?.Level,n=!e&&!y.system,r=()=>t?.(null),i=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(k,{kind:`Source`,name:y.name,onPick:f?.length?()=>I(!0):void 0,meta:Bu(Fc(y)),primary:n?{label:`Upload…`,icon:K,onSelect:()=>Le.current?.click()}:e?pe??void 0:void 0,actions:ht(Fc(y),r)}),P&&f&&(0,$.jsx)(ue,{kind:`Source`,value:y.id,onPick:e=>t?.(e),onClose:()=>I(!1),options:f.map(e=>({id:e.id,label:e.name}))}),pt]});return e?(0,$.jsxs)(`div`,{className:`sources`,children:[i,(0,$.jsx)(e,{source:y,onBack:r,bind:me}),(0,$.jsx)(Vt,{undo:l.undo,onUndo:l.undoNow,onDismiss:l.dismiss})]}):(0,$.jsxs)(`div`,{className:`sources`,"data-level":`files`,children:[i,xe&&(0,$.jsx)(`p`,{className:`note`,role:`status`,children:xe}),(0,$.jsxs)(`header`,{className:`shead`,children:[(0,$.jsx)(Au,{view:Be,onChange:e=>w(t=>({...t,view:e}))}),(0,$.jsx)(ju,{sort:Ve,dir:Ue,onChange:(e,t)=>w(n=>({...n,sort:e,dir:t}))}),(0,$.jsxs)(`label`,{className:`sfilter`,children:[(0,$.jsx)(Pt,{size:14,"aria-hidden":`true`}),(0,$.jsx)(`input`,{type:`search`,"aria-label":`Filter by name`,placeholder:`Filter`,value:T,onChange:e=>D(e.target.value)})]})]}),O.size>0&&(0,$.jsx)(qt,{count:O.size,noun:`file`,onClear:nt,actions:Be===`thumbs`?[{label:`Select all`,icon:Cn,disabled:O.size===$e.length,onSelect:tt},..._t]:_t}),(0,$.jsx)(`div`,{className:`sfiles${Te?` drag`:``}`,onDragOver:e=>{e.preventDefault(),Ee(!0)},onDragLeave:()=>Ee(!1),onDrop:vt,children:$e.length===0?(0,$.jsx)(`p`,{className:`note`,children:T?`No files match that name.`:`No files in this Source yet.`}):Be===`thumbs`?(0,$.jsx)(`ul`,{className:`stiles`,children:$e.map(e=>(0,$.jsx)(`li`,{children:(0,$.jsxs)(`button`,{type:`button`,className:`stile${O.has(e.name)?` sel`:``}`,"aria-pressed":O.has(e.name),"aria-label":e.name,onClick:()=>et(e.name),children:[(0,$.jsx)(ku,{id:y.id,file:e}),(0,$.jsx)(`span`,{className:`stile-name`,children:e.name}),O.has(e.name)&&(0,$.jsx)(`span`,{className:`stile-check`,children:(0,$.jsx)(B,{size:12,"aria-hidden":`true`})})]})},e.name))}):(0,$.jsx)(J,{className:`slist`,label:`${y.name} files`,rows:$e,rowKey:e=>e.name,defaultSort:null,select:{noun:`file`,selected:O,onChange:A},rowProps:e=>({onClick:()=>et(e.name)}),columns:[{key:`name`,header:`Name`,className:`sfile-name`,role:`title`,cell:e=>e.name},{key:`type`,header:`Type`,className:`stype`,cell:e=>Mu(e.name)},{key:`size`,header:`Size`,className:`num`,sort:e=>e.bytes,cell:e=>Ac(e.bytes)},{key:`added`,header:`Added`,sort:e=>e.added,cell:e=>e.added?jc(e.added):`—`},{key:`menu`,header:``,className:`s-actions`,role:`menu`,sort:null,tdProps:()=>({onClick:e=>e.stopPropagation()}),cell:e=>(0,$.jsx)(Y,{label:`${e.name} actions`,actions:gt(e)})}]})}),n&&(0,$.jsxs)(`div`,{className:`supload`,children:[(0,$.jsx)(`input`,{ref:Le,type:`file`,multiple:!0,hidden:!0,"aria-hidden":`true`,accept:L().sourceTypeOf(y)?.uploads?.join(`,`),onChange:e=>{e.target.files&&ct(e.target.files),e.target.value=``}}),Ce.length>0&&(0,$.jsx)(`ul`,{className:`suploads`,children:Ce.map(e=>(0,$.jsxs)(`li`,{className:`supload ${e.state}`,children:[(0,$.jsx)(`span`,{className:`supload-name`,children:e.file.name}),e.state===`uploading`&&(0,$.jsx)(`span`,{className:`supload-bar`,role:`status`,children:`Uploading…`}),e.state===`done`&&(0,$.jsx)(`span`,{className:`note`,children:`Uploaded`}),e.state===`error`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`note bad`,children:e.error}),(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>lt(e),children:`Retry`})]})]},e.id))})]}),ee&&(0,$.jsxs)(b,{title:ee.name,onClose:We,children:[Tc(ee.name)?(0,$.jsx)(`img`,{className:`spreview-img`,src:Dc(y.id,ee),alt:ee.name}):null,(0,$.jsx)(`p`,{className:`note`,children:Ac(ee.bytes)})]}),H&&(0,$.jsx)(b,{title:H.kind===`move`?`Move to…`:`Copy to…`,onClose:Ke,children:(0,$.jsx)(Tu,{mode:`pick`,disabled:e=>e.id===y.id||e.system||e.type!==y.type,onPick:e=>void ut(H.kind,e)})}),re&&(0,$.jsxs)(b,{title:`New Source from selection`,onClose:qe,dirty:!!ae.trim(),children:[(0,$.jsxs)(`label`,{className:`prompt`,children:[(0,$.jsx)(`span`,{className:`prop-name`,children:`Name`}),(0,$.jsx)(`input`,{"aria-label":`New Source name`,value:ae,autoFocus:!0,onChange:e=>q(e.target.value),onKeyDown:e=>{e.key===`Enter`&&dt()}})]}),(0,$.jsxs)(`div`,{className:`sacts`,children:[(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>ie(!1),children:`Cancel`}),(0,$.jsx)(`button`,{type:`button`,disabled:!ae.trim(),onClick:()=>void dt(),children:`Make`})]})]}),yt,(0,$.jsx)(Vt,{undo:l.undo,onUndo:l.undoNow,onDismiss:l.dismiss})]})}let wt=hu[Lu(oe,ye)]?.Create,Tt={key:`type`,label:`Type`,control:{type:`cards`,value:oe,onChange:e=>{se(e),de(null)},options:Iu(ye).map(e=>({...e,icon:(0,$.jsx)(wu,{name:e.icon})}))}},Et=()=>{wt?ce?.enabled&&ce.run():ft()};return(0,$.jsxs)(`div`,{className:`sources`,"data-level":`sources`,children:[xe&&(0,$.jsx)(`p`,{className:`note`,role:`status`,children:xe}),(0,$.jsxs)(E,{id:`library-sources`,title:`Sources`,children:[f!==null&&f.length>0&&St(xt),f===null?(0,$.jsx)(C,{label:`Sources`,error:ke,onRetry:()=>{Ae(null),Pe(e=>e+1)}}):f.length===0?(0,$.jsx)(`p`,{className:`note`,children:`No Sources yet.`}):Be===`thumbs`?(0,$.jsx)(`ul`,{className:`sfolders`,children:bt.map(e=>(0,$.jsxs)(`li`,{className:`sfolder`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`sfolder-open`,onClick:()=>t?.(e.id),children:[(0,$.jsx)(wu,{name:Ru(e)}),(0,$.jsx)(`span`,{className:`sfolder-name`,children:e.name}),(0,$.jsx)(`span`,{className:`sfolder-meta`,children:Bu(e)}),(0,$.jsx)(Fu,{source:e,cap:h,children:e.system?(0,$.jsx)(`span`,{className:`squota-none`,children:`—`}):(0,$.jsx)(`span`,{className:`squota-bar`,children:(0,$.jsx)(`span`,{className:`squota-fill`,style:{width:`${Nu(e.bytes,h)}%`}})})})]}),(0,$.jsx)(`span`,{className:`sfolder-menu`,children:(0,$.jsx)(Y,{label:`${e.name} actions`,actions:ht(e)})})]},e.id))}):(0,$.jsx)(`div`,{className:`sfiles`,children:(0,$.jsx)(J,{className:`slist slist-folders`,label:`Sources`,rows:bt,rowKey:e=>e.id,rowProps:e=>({"data-open":e.id,onClick:()=>t?.(e.id)}),select:{noun:`Source`,actions:e=>[{label:`Delete`,icon:Lt,destructive:!0,disabled:e.every(e=>e.system),onSelect:()=>void rt(e.filter(e=>!e.system))}]},columns:[{key:`name`,header:`Name`,className:`sfile-name`,role:`title`,sort:e=>e.name,cell:e=>(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(wu,{name:Ru(e)}),e.name]})},{key:`type`,header:`Type`,sort:e=>Bu(e),cell:e=>Bu(e)},{key:`files`,header:`Items`,className:`num`,cell:e=>e.files},{key:`size`,header:`Size`,className:`num`,sort:e=>e.bytes,cell:e=>Ac(e.bytes)},{key:`used`,header:`Used`,className:`num`,sort:e=>e.system?null:e.bytes,cell:e=>(0,$.jsx)(Fu,{source:e,cap:h,children:e.system?`—`:`${Nu(e.bytes,h)}%`})},{key:`menu`,header:``,className:`s-actions`,role:`menu`,sort:null,tdProps:()=>({onClick:e=>e.stopPropagation()}),cell:e=>(0,$.jsx)(Y,{label:`${e.name} actions`,actions:ht(e)})}]})}),pt,(0,$.jsxs)(`div`,{className:`sfoot`,children:[(0,$.jsxs)(`p`,{className:`note`,children:[`Used `,Ac(_),` of `,Ac(h)]}),(0,$.jsxs)(`button`,{type:`button`,className:`ghost add-btn`,onClick:()=>z(!0),children:[(0,$.jsx)(ze,{size:14,"aria-hidden":`true`}),` Add source`]})]})]}),R&&(0,$.jsx)(b,{title:`Add source`,onClose:Ge,dirty:!!ae.trim(),className:`edit sadd`,initialFocus:`.prop[data-key="name"] input`,footer:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:Ge,children:`Cancel`}),(0,$.jsxs)(`button`,{type:`button`,disabled:wt?!ce?.enabled:!ae.trim(),"aria-busy":ce?.busy||void 0,onClick:Et,children:[ce?.busy&&(0,$.jsx)(F,{}),`Add source`]})]}),children:(0,$.jsx)(`div`,{onKeyDown:e=>{e.key===`Enter`&&e.target.matches(`input[type="text"]`)&&(e.preventDefault(),Et())},children:wt?(0,$.jsx)(wt,{typeRow:Tt,which:oe,bind:de,onMade:async()=>{z(!1),se(L().DEFAULT_SOURCE_TYPE),await Je()}}):(0,$.jsx)(a,{label:`New Source`,rows:[Tt,{key:`name`,label:`Name`,width:`full`,control:{type:`text`,value:ae,onChange:q}}]})})}),yt,(0,$.jsx)(Vt,{undo:l.undo,onUndo:l.undoNow,onDismiss:l.dismiss})]})}var Eu=`evals-lab.sources.adding`;function Du(){try{return sessionStorage.getItem(Eu)}catch{return null}}function Ou(e){try{e?sessionStorage.setItem(Eu,e):sessionStorage.removeItem(Eu)}catch{}}function ku({id:e,file:t}){let[n,r]=(0,X.useState)(!1);return!t.thumb||n?(0,$.jsx)(`span`,{className:`stile-type`,children:Mu(t.name)||`FILE`}):(0,$.jsx)(`img`,{className:`stile-img`,src:Ec(e,t),alt:``,loading:`lazy`,onError:()=>r(!0)})}function Au({view:e,onChange:t}){return(0,$.jsxs)(`div`,{className:`sview`,role:`group`,"aria-label":`View`,children:[(0,$.jsx)(`button`,{type:`button`,className:e===`thumbs`?`on`:void 0,"aria-pressed":e===`thumbs`,onClick:()=>t(`thumbs`),children:`Thumbnails`}),(0,$.jsx)(`button`,{type:`button`,className:e===`list`?`on`:void 0,"aria-pressed":e===`list`,onClick:()=>t(`list`),children:`List`})]})}function ju({sort:e,dir:t,onChange:n}){return(0,$.jsxs)(`div`,{className:`ssort`,role:`group`,"aria-label":`Sort`,children:[(0,$.jsxs)(`select`,{"aria-label":`Sort by`,value:e,onChange:e=>n(e.target.value,t),children:[(0,$.jsx)(`option`,{value:`name`,children:`Name`}),(0,$.jsx)(`option`,{value:`added`,children:`Date added`}),(0,$.jsx)(`option`,{value:`size`,children:`Size`})]}),(0,$.jsx)(`button`,{type:`button`,className:`icon-btn`,"aria-label":`Sort ${t===1?`ascending`:`descending`}`,onClick:()=>n(e,t===1?-1:1),children:(0,$.jsx)(t===1?V:y,{size:14,"aria-hidden":`true`})})]})}function Mu(e){let t=e.lastIndexOf(`.`);return t<0?``:e.slice(t+1).toUpperCase()}function Nu(e,t){return t<=0?0:Math.max(0,Math.min(100,Math.round(e/t*100)))}function Pu(e,t){return e.system?`Quota: not counted`:`Quota: ${Ac(e.bytes)} of ${Ac(t)}`}function Fu({source:e,cap:t,children:n}){let r=Pu(e,t);return(0,$.jsxs)(`span`,{className:`squota`,role:`img`,"aria-label":r,children:[n,(0,$.jsx)(`span`,{className:`squota-pop`,"aria-hidden":`true`,children:r})]})}var Iu=(e=[])=>Object.entries(L().SOURCE_TYPES).flatMap(([t,n])=>n.platforms?n.platforms.flatMap(e=>{let n=L().WORKFLOW_PLATFORMS[e];return n?[{value:e,label:n.label,icon:Cu(t,e)}]:[]}):n.providers?e.map(e=>({value:e.id,label:e.label,icon:Cu(t,void 0,e.id),...e.enrolled?{}:{disabled:!0,note:e.note??`set by the server`}})):[{value:t,label:n.label,icon:Cu(t)}]),Lu=(e,t=[])=>{if(e in L().SOURCE_TYPES)return e;let n=Object.entries(L().SOURCE_TYPES).find(([,t])=>t.platforms?.includes(e))?.[0];if(n)return n;if(t.some(t=>t.id===e)||e in L().DYNAMIC_PROVIDERS){let e=Object.entries(L().SOURCE_TYPES).find(([,e])=>e.providers)?.[0];if(e)return e}return e},Ru=e=>Cu(e.type,e.platform,e.provider),zu=e=>e.provider??e.platform??e.type,Bu=e=>e.provider?L().DYNAMIC_PROVIDERS[e.provider]?.label??L().SOURCE_TYPES[e.type]?.label??e.type:e.platform?L().WORKFLOW_PLATFORMS[e.platform]?.label??L().SOURCE_TYPES[e.type]?.label??e.type:L().SOURCE_TYPES[e.type]?.label??e.type;function Vu({sourceId:e}){let[t,n]=(0,X.useState)(e);return(0,X.useEffect)(()=>n(e),[e]),(0,$.jsx)(Tu,{sourceId:t,onOpen:e=>{n(e),Fr({tab:`library`,section:`sources`,id:e})},onGone:()=>Ir({tab:`library`,section:`sources`,id:null})})}var Hu=[{id:`datasets`,label:`Evals`,icon:g},{id:`filters`,label:`Filter sets`,icon:Ut},{id:`prompts`,label:`Prompts`,icon:Je},{id:`sources`,label:`Sources`,icon:Ie}];function Uu({section:e,id:t}){return(0,$.jsxs)(`div`,{className:`library`,children:[(0,$.jsx)(R,{label:`Library`,level:`section`,className:`lib-sections`,current:e,items:Hu.map(({id:e,label:t,icon:n})=>({key:e,label:t,href:Pr({tab:`library`,section:e,id:null}),icon:n}))}),(0,$.jsx)(`section`,{className:`lib-section`,"data-section":e,children:e===`datasets`?(0,$.jsx)(ts,{groupId:t}):e===`filters`?(0,$.jsx)(ac,{setId:t}):e===`prompts`?(0,$.jsx)(_c,{promptId:t}):(0,$.jsx)(Vu,{sourceId:t})})]})}var Wu=`0.12.0 (2026.10.12-718)`,Gu=3,Ku=3,qu=e=>Ga.find(t=>t.id===e),Ju=e=>Hu.find(t=>t.id===e),Yu=e=>new Date(e).toLocaleString(void 0,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`});function Xu(){let e=Z(),[t]=Q(`promptlab.connections`),[n,r]=Q(`promptlab.workflows`),i=gr(),a=Er(),{pickDataset:o}=ai(),{openRun:s}=ci(),c=hr(),l=Tr(),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)(null),[g,_]=(0,X.useState)(null),[v,y]=(0,X.useState)(0),[b,x]=(0,X.useState)(0),S=e=>e instanceof Error?e.message:String(e);(0,X.useEffect)(()=>{let t=!0;return h(null),e.sources().then(e=>{t&&d(e.sources)},e=>{t&&h(S(e))}),()=>{t=!1}},[e,v]),(0,X.useEffect)(()=>{let t=!0;return _(null),e.queue({limit:Ku}).then(e=>{t&&p(e.runs)},e=>{t&&_(S(e))}),()=>{t=!1}},[e,b]);let C=(0,X.useMemo)(()=>n.list.filter(e=>e.work?.version===17),[n.list]),w=i.list??[],T=w.reduce((e,t)=>e+t.cases,0),E=(f??[]).filter(e=>e.status===`queued`||e.status===`running`).length,D=t.list.length===0?`setup`:i.list===null?null:w.length===0||T===0?`datasets`:f!==null&&f.length===0?`runs`:null,O=(...e)=>e.filter(Boolean).join(`, `)||void 0,k=qu(`library`),A=k.icon;return(0,$.jsxs)(`div`,{className:`home`,children:[(0,$.jsx)(`div`,{className:`home-pane`,children:(0,$.jsxs)(`ol`,{className:`home-line`,"aria-label":`Lab`,children:[(0,$.jsx)(Zu,{id:`runs`,icon:qu(`runs`).icon,name:qu(`runs`).label,hub:!0,start:D===`runs`,fact:O(Ei(C.length,`pipeline`),E>0&&`${E} running`),total:C.length,items:C.map(e=>({key:e.id,label:e.name,href:Pr({tab:`runs`,id:e.id}),onPick:()=>r({...n,at:e.id})}))}),(0,$.jsx)(Zu,{id:`history`,icon:qu(`history`).icon,name:qu(`history`).label,fact:f&&f.length===0?`No runs yet`:void 0,wait:f?void 0:{error:g,onRetry:()=>x(e=>e+1)},items:(f??[]).map(e=>{let t=xa(e).scenarios.map(e=>e.percent==null?`–`:`${e.percent}%`).join(`, `);return{key:e.id,label:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`code`,{children:Ti(e.submittedAt)}),e.status!==`done`&&Mi(e.status)]}),sub:O(Yu(e.submittedAt),!!t&&t),href:`#/history`,onOpen:()=>s(e.id,{at:e.submittedAt,from:`home`})}})}),(0,$.jsxs)(`li`,{className:`home-stop home-fork`,"data-stop":`library`,children:[(0,$.jsxs)(`a`,{className:`home-name`,href:`#/library`,children:[(0,$.jsx)(`span`,{className:`home-mark`,"aria-hidden":`true`,children:(0,$.jsx)(A,{size:18})}),k.label]}),(0,$.jsxs)(`ol`,{className:`home-branch`,"aria-label":k.label,children:[(0,$.jsx)(Zu,{id:`datasets`,to:`library/datasets`,branch:!0,icon:Ju(`datasets`).icon,name:Ju(`datasets`).label,start:D===`datasets`,fact:i.list?O(Ei(w.length,`eval group`),Ei(T,`case`)):void 0,total:w.length,wait:i.list?void 0:{error:i.error,onRetry:()=>void c.refresh()},items:w.map(e=>({key:e.id,label:e.name,sub:Ei(e.cases,`case`),href:Pr({tab:`library`,section:`datasets`,id:e.id}),onPick:()=>o(e.id)}))}),(0,$.jsx)(Zu,{id:`prompts`,to:`library/prompts`,branch:!0,icon:Ju(`prompts`).icon,name:Ju(`prompts`).label,fact:a.list?O(Ei(a.list.length,`prompt`)):void 0,total:a.list?.length??0,wait:a.list?void 0:{error:a.error,onRetry:()=>void l.refresh()},items:(a.list??[]).map(e=>({key:e.id,label:e.name||e.text.split(`
|
|
10
|
-
`)[0]||`Untitled`,sub:e.default?`Default`:void 0,href:Pr({tab:`library`,section:`prompts`,id:e.id})}))}),(0,$.jsx)(Zu,{id:`sources`,to:`library/sources`,branch:!0,icon:Ju(`sources`).icon,name:Ju(`sources`).label,fact:u?O(Ei(u.length,`source`)):void 0,total:u?.length??0,wait:u?void 0:{error:m,onRetry:()=>y(e=>e+1)},items:(u??[]).map(e=>({key:e.id,label:e.name,sub:Ei(e.files,`file`),href:Pr({tab:`library`,section:`sources`,id:e.id})}))})]})]}),(0,$.jsx)(Zu,{id:`setup`,icon:qu(`setup`).icon,name:qu(`setup`).label,start:D===`setup`,fact:O(Ei(t.list.length,`connection`)),total:t.list.length,items:t.list.map(e=>({key:e.id,label:e.name||`Untitled`,sub:e.model,href:Pr({tab:`setup`,section:`connections`,id:e.id})}))})]})}),(0,$.jsxs)(`p`,{className:`home-version`,children:[`Evals Lab `,Wu]})]})}function Zu({id:e,icon:t,name:n,to:r,fact:i,items:a,total:o=a.length,hub:s,start:c,branch:l,wait:u}){let d=o-Math.min(a.length,Gu);return(0,$.jsxs)(`li`,{className:[`home-stop`,s&&`hub`,c&&`start`,l&&`branch`].filter(Boolean).join(` `),"data-stop":e,children:[(0,$.jsxs)(`a`,{className:`home-name`,href:`#/${r??e}`,children:[(0,$.jsx)(`span`,{className:`home-mark`,"aria-hidden":`true`,children:(0,$.jsx)(t,{size:l?15:18})}),n]}),c&&(0,$.jsx)(`span`,{className:`home-start`,children:`Start Here`}),u&&(0,$.jsx)(C,{label:n,error:u.error,onRetry:u.onRetry}),!u&&i&&(0,$.jsx)(`span`,{className:`home-fact`,children:i}),!u&&a.length>0&&(0,$.jsxs)(`ul`,{className:`home-items`,children:[a.slice(0,Gu).map(e=>(0,$.jsx)(`li`,{children:(0,$.jsxs)(`a`,{href:e.href,onClick:t=>{e.onOpen?(t.preventDefault(),e.onOpen()):e.onPick?.()},children:[(0,$.jsx)(`span`,{className:`home-item`,children:e.label}),e.sub&&(0,$.jsx)(`span`,{className:`home-sub`,children:e.sub})]})},e.key)),d>0&&(0,$.jsx)(`li`,{children:(0,$.jsxs)(`a`,{className:`home-more`,href:`#/${r??e}`,children:[d,` more`]})})]})]})}function Qu({list:e,at:t,canRestore:n,onSelect:r,onNew:i,onClone:a,link:o,onCopyMove:s,onRename:c,onDelete:l,onRestore:u,onExport:d,onExportCi:f,onImport:m,used:h={}}){let[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)(!1),b=e.find(e=>e.id===t),x=[{label:`Rename…`,icon:He,onSelect:()=>_(!0)},{label:`Clone`,icon:p,onSelect:a},o,{label:`Copy or move…`,icon:M.transfer,onSelect:s},{label:`Export YAML`,icon:fe,onSelect:d},{label:`Export for CI…`,icon:fe,onSelect:f},{label:`Import YAML…`,icon:K,onSelect:m},{label:`Restore…`,icon:Ze,disabled:!n,onSelect:u},{label:`Delete`,icon:Lt,destructive:!0,onSelect:l}],S=b?.work.jobs?.length??0,C=b?.work.targets?.length??0;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(k,{kind:`Pipeline`,name:b?.name?.trim()||`Untitled`,onPick:()=>y(!0),meta:`${ed(S,`job`)}, ${ed(C,`target`)}`,primary:{label:`New pipeline`,icon:ze,onSelect:i},actions:x,docked:!0}),v&&(0,$.jsx)(ue,{kind:`Pipeline`,value:t,onPick:r,onClose:()=>y(!1),options:e.map(e=>{let t=h[e.id];return{id:e.id,label:e.name||`Untitled`,used:t?{at:t,label:ki(t)}:null}}),recent:e.filter(e=>h[e.id]).sort((e,t)=>h[t.id].localeCompare(h[e.id])).slice(0,$u).map(e=>e.id)}),g&&(0,$.jsx)(Tt,{title:`Rename pipeline`,value:b?.name??``,onCommit:c,onClose:()=>_(!1)})]})}var $u=5,ed=(e,t)=>`${e} ${e===1?t:`${t}s`}`;function td({hasItems:e,onExport:t,onClose:n}){let[r,i]=(0,X.useState)(!1),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null),l=async()=>{o(!0),c(null);try{await t(e&&r),n()}catch(e){c(e instanceof Error?e.message:String(e))}finally{o(!1)}};return(0,$.jsx)(ut,{title:`Export for CI`,status:s??void 0,statusBad:!!s,onClose:n,sections:[{key:`bundle`,rows:[{key:`items`,label:`Include files`,...e?{hint:`Copy the Source's files into the zip. Off, evals-lab run needs --items`}:{},control:e?{type:`checkbox`,checked:r,onChange:i}:{type:`static`,text:`None`}}]}],actions:[{label:`Export`,icon:fe,busy:a,primary:!0,onSelect:()=>void l()}]})}function nd({problems:e,error:t,run:n,submitting:r,onRun:i,onStop:a,onOpen:o,onShare:s}){let c=!!n&&!qi(n.status),l=n?.progress?.total??0,u=n?.progress?.n??0,d=c&&l?Math.round(u/l*100):null,f=n&&(0,$.jsxs)(`button`,{type:`button`,className:`runbar-open`,title:`Open this run`,onClick:o,children:[(0,$.jsx)(`span`,{className:`runbar-word`,children:ji(n.status)}),rd(n)&&(0,$.jsx)(`span`,{className:`runbar-detail`,children:rd(n)})]}),p=c?f:e.length?(0,$.jsxs)(`span`,{className:`runbar-why`,children:[od(e[0]),ad(e[0])]}):t?(0,$.jsxs)(`span`,{className:`runbar-why bad`,children:[od(t),s&&(0,$.jsxs)($.Fragment,{children:[` `,(0,$.jsx)(`button`,{type:`button`,className:`runbar-fix`,onClick:s,children:`Share`})]})]}):f??(0,$.jsx)(`span`,{className:`runbar-word`,children:`Ready to run`});return(0,$.jsx)(Qe,{className:`runbar`,primary:{label:`Run`,icon:Bt,onSelect:i,disabled:e.length>0,busy:r},status:p,secondary:c?{label:`Stop`,icon:_t,onSelect:a}:void 0,progress:d,progressLabel:`Run progress`})}function rd(e){if(e.status===`queued`)return e.behind?`behind ${e.behind}`:`next in line`;if(e.status===`running`)return e.progress?.total?`${e.progress.n} of ${e.progress.total}`:``;if(e.status===`done`&&e.progress?.total){let t=Fi(e.startedAt,e.finishedAt);return t==null?String(e.progress.total):`${e.progress.total} in ${Pi(t)}`}return``}var id=[[/^Connection(?: Profile)? .* not found$/,`#/setup`,`Open\xA0Setup`],[/^Source .* not found$/,`#/library/sources`,`Open\xA0Sources`],[/^Dataset .* not found$/,`#/library/datasets`,`Open\xA0Evals`]];function ad(e){let t=id.find(([t])=>t.test(e.trim()));return t?(0,$.jsxs)($.Fragment,{children:[` `,(0,$.jsx)(`a`,{className:`runbar-fix`,href:t[1],children:t[2]})]}):null}var od=e=>{let t=e.trim();if(!t)return t;let n=t[0].toUpperCase()+t.slice(1);return/[.!?]$/.test(n)?n:`${n}.`},sd=10;function cd({onPick:e,onClose:t,used:n}){let{list:r,error:i}=Er(),a=Tr(),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(`all`),[u,f]=(0,X.useState)(0),p=r??[],m=p.filter(e=>lc(e,o,c,n??{byScenario:new Set,byAll:new Set})).sort((e,t)=>Number(t.default)-Number(e.default)),h=Math.ceil(m.length/sd),g=Math.min(u,Math.max(0,h-1)),_=m.slice(g*sd,(g+1)*sd);return(0,$.jsxs)(b,{title:`Select prompt`,onClose:t,className:`sp`,initialFocus:`.sp input[type=search]`,children:[(0,$.jsx)(d,{noun:`prompts`,search:{label:`Search prompts`,placeholder:`Search prompts`,value:o,onChange:e=>{s(e),f(0)}},filters:[{key:`show`,label:`Show`,value:c,onChange:e=>{l(e),f(0)},options:sc}],count:{shown:m.length,total:p.length}}),r===null?(0,$.jsx)(C,{label:`Prompts`,error:i,onRetry:()=>void a.refresh()}):p.length===0?(0,$.jsx)(`p`,{className:`note`,children:`No prompts yet.`}):m.length===0?(0,$.jsx)(`p`,{className:`note`,children:`No prompts match these filters.`}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`ul`,{className:`sp-list`,"aria-label":`Prompts`,children:_.map(t=>(0,$.jsx)(`li`,{children:(0,$.jsxs)(`button`,{type:`button`,className:`sp-pick`,onClick:()=>e(t),children:[(0,$.jsxs)(`span`,{className:`sp-head`,children:[(0,$.jsx)(`span`,{className:`sp-title`,children:vr(t)}),t.default&&(0,$.jsx)(`span`,{className:`pl-default`,children:`Default`})]}),(0,$.jsx)(`span`,{className:`sp-text`,children:t.text.trim()||`—`}),(0,$.jsxs)(`span`,{className:`sp-meta`,children:[(0,$.jsx)(`span`,{children:t.useCount===1?`1 use`:`${t.useCount} uses`}),t.lastUsed&&(0,$.jsxs)(`span`,{children:[`last `,uc(t.lastUsed)]}),(0,$.jsxs)(`span`,{children:[`v`,t.version]})]})]})},t.id))}),h>1&&(0,$.jsxs)(`div`,{className:`sp-pager`,children:[(0,$.jsx)(`button`,{type:`button`,className:`ghost`,disabled:g===0,onClick:()=>f(g-1),children:`Back`}),(0,$.jsxs)(`span`,{className:`sp-page`,children:[g+1,` of `,h]}),(0,$.jsx)(`button`,{type:`button`,className:`ghost`,disabled:g>=h-1,onClick:()=>f(g+1),children:`Forward`})]})]})]})}function ld({what:e,options:t,recent:n,taken:r,linkedHere:i,ready:a,onPick:o,onMove:s,onClose:c}){let[l,u]=(0,X.useState)(`new`),[d,f]=(0,X.useState)(``),[p,m]=(0,X.useState)(``),[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(null),y=d.trim(),x=l===`new`&&r.has(y),S=t.find(e=>e.id===p),C=!h&&(l===`new`?!!y&&!x:!!p&&a(p)),w=async()=>{if(!C)return;g(!0),v(null);let e=await s(l===`new`?{kind:l,name:y}:{kind:l,id:p});if(e){v(e),g(!1);return}c()};return(0,$.jsxs)(b,{title:`Move ${e} to a filter set`,onClose:c,className:`move-to-set`,dirty:!!y||!!p,initialFocus:`.mv-name`,footer:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:c,children:`Cancel`}),(0,$.jsx)(`button`,{type:`button`,disabled:!C,"aria-busy":h||void 0,onClick:()=>void w(),children:`Move`})]}),children:[(0,$.jsxs)(`fieldset`,{className:`nf-types`,children:[(0,$.jsx)(`legend`,{className:`sr-only`,children:`Filter set`}),(0,$.jsxs)(`label`,{className:`nf-type${l===`new`?` on`:``}`,children:[(0,$.jsx)(`input`,{type:`radio`,name:`move-to`,checked:l===`new`,onChange:()=>u(`new`)}),(0,$.jsxs)(`span`,{className:`nf-type-text`,children:[(0,$.jsx)(`span`,{className:`nf-type-name`,children:`New filter set`}),(0,$.jsx)(`input`,{className:`mv-name`,type:`text`,"aria-label":`Name`,placeholder:`Name`,value:d,onFocus:()=>u(`new`),onChange:e=>f(e.target.value)})]})]}),(0,$.jsxs)(`div`,{className:`nf-type${l===`existing`?` on`:``}`,children:[(0,$.jsx)(`input`,{type:`radio`,name:`move-to`,id:`mv-existing`,checked:l===`existing`,onChange:()=>u(`existing`)}),(0,$.jsxs)(`span`,{className:`nf-type-text`,children:[(0,$.jsx)(`label`,{className:`nf-type-name`,htmlFor:`mv-existing`,id:`mv-existing-label`,children:`Existing filter set`}),(0,$.jsx)(H,{kind:`Filter set`,value:p,options:t,recent:n,usedLabel:`Last changed`,placeholder:`Choose a filter set`,labelledBy:`mv-existing-label`,onChange:e=>{u(`existing`),m(e),o?.(e)}})]})]})]}),x&&(0,$.jsxs)(`p`,{className:`note bad`,role:`alert`,children:[`A filter set named `,y,` already exists.`]}),l===`existing`&&S&&i.has(p)&&(0,$.jsxs)(`p`,{className:`note`,children:[S.label,` is already linked here, so `,e,` joins its end and runs where it runs.`]}),_&&(0,$.jsx)(`p`,{className:`note bad`,role:`alert`,children:_})]})}var ud=(e,t)=>e.entry(t)?.doc?.body.filters??null,dd=(e,t)=>e.filter(e=>fd(e)===t).length,fd=e=>L().stageOfScope(L().FILTER_TYPES[e.type]?.scope??`item`);function pd({pipeline:e,job:t,stage:n,edit:r,offer:i,moveAll:a,onMoveAllClose:o}){let s=us(),{list:c}=ds(),[u,d]=(0,X.useState)(new Set),[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)(null),[g,_]=(0,X.useState)(null),[v,y]=(0,X.useState)(null),b=L().filterSetsOf(e.jobs[t],n),x=zt(b),S=x.flatMap(e=>e.kind===`filter`?[e.filter]:[]),C=new Map((c??[]).map(e=>[e.id,e])),[,w]=(0,X.useState)(0);(0,X.useEffect)(()=>s.subscribe(()=>w(e=>e+1)),[s]);let T=x.flatMap(e=>e.kind===`set`?[e.link.set.id]:[]).join(` `);(0,X.useEffect)(()=>{for(let e of T.split(` `).filter(Boolean))s.load(e)},[s,T]);let E=i=>r(Ee(e,t,i,n)),D=(t,n)=>{let a=e;r(t),i({label:n,restore:()=>r(a)})},O=(e,t)=>{let n=[...x],[r]=n.splice(e,1);n.splice(e+t,0,r),E(n)},k=e=>e.set.name||e.set.id,A=(r,i)=>[{label:`Edit…`,icon:M.edit,onSelect:()=>p(i)},{label:`Clone`,icon:M.clone,onSelect:()=>{let e=x[i];E([...x.slice(0,i+1),{...e,filter:{...structuredClone(r),id:l(S,`${r.id} copy`)}},...x.slice(i+1)])}},{label:`Move up`,icon:M.moveUp,disabled:i===0,onSelect:()=>O(i,-1)},{label:`Move down`,icon:M.moveDown,disabled:i===x.length-1,onSelect:()=>O(i,1)},{label:`Move to filter set…`,icon:Pn,onSelect:()=>y([i])},{label:`Remove`,icon:M.remove,destructive:!0,onSelect:()=>D(Ee(e,t,x.filter((e,t)=>t!==i),n),`Removed ${r.id}`)}],j=(r,i)=>{let a=C.get(r.set.id)?.versions;return[{label:`Open in Library`,icon:Ie,onSelect:()=>hs(r.set.id)},r.pin==null?{label:`Pin`,icon:Vn,disabled:a==null,onSelect:()=>D(pe(e,t,r.id,a,n),`Pinned ${k(r)}`)}:{label:`Follow latest`,icon:Bn,onSelect:()=>D(pe(e,t,r.id,null,n),`${k(r)} follows the latest`)},{label:`Move up`,icon:M.moveUp,disabled:i===0,onSelect:()=>O(i,-1)},{label:`Move down`,icon:M.moveDown,disabled:i===x.length-1,onSelect:()=>O(i,1)},{label:`Unlink`,icon:Yn,onSelect:()=>D(it(e,t,r.id,n),`Unlinked ${k(r)}`)}]},N=x.flatMap((e,t)=>{let n={...e,n:t+1,at:t};return e.kind!==`set`||!u.has(e.link.id)?[n]:[n,...(ud(s,e.link.set.id)??[]).map((t,n)=>({kind:`inner`,filter:t,key:`${e.link.id}/${n}`}))]}),P=e=>d(t=>{let n=new Set(t);return n.delete(e)||n.add(e),n}),F=e=>L().FILTER_TYPES[e.type]?.label??e.type,I=[{key:`n`,header:`#`,label:``,className:`num fs-n`,sort:null,cell:e=>e.kind===`inner`?null:e.n},{key:`filter`,header:`Filter`,role:`title`,sort:null,cell:e=>{if(e.kind===`filter`)return(0,$.jsx)(`button`,{type:`button`,className:`ds-file`,onClick:()=>p(e.at),children:e.filter.id});if(e.kind===`set`){let t=u.has(e.link.id),n=t?ot:lt;return(0,$.jsxs)(`span`,{className:`fs-set`,children:[(0,$.jsx)(`button`,{type:`button`,className:`ghost fs-toggle`,"aria-expanded":t,"aria-label":`${t?`Hide`:`Show`} ${k(e.link)}'s filters`,onClick:()=>P(e.link.id),children:(0,$.jsx)(n,{size:14,"aria-hidden":`true`})}),(0,$.jsx)(`button`,{type:`button`,className:`eg-open`,onClick:()=>hs(e.link.set.id),children:k(e.link)}),(0,$.jsx)(`span`,{className:`fs-badge`,children:e.link.pin==null?`Latest`:`Pinned v${e.link.pin}`})]})}let t=fd(e.filter)!==n;return(0,$.jsxs)(`span`,{className:`fs-inner`,children:[e.filter.id,t&&(0,$.jsx)(`span`,{className:`fs-badge`,children:Qs[fd(e.filter)]})]})}},{key:`type`,header:`Type`,className:`fs-type`,sort:null,cell:e=>{if(e.kind!==`set`)return F(e.filter);let t=ud(s,e.link.set.id),r=t?dd(t,n):null;return`Filter set, ${r==null?`…`:r===0?`none`:r} run here`}},{key:`menu`,header:``,label:``,role:`menu`,sort:null,cell:e=>e.kind===`filter`?(0,$.jsx)(Y,{label:`${e.filter.id} actions`,actions:A(e.filter,e.at)}):e.kind===`set`?(0,$.jsx)(Y,{label:`${k(e.link)} actions`,actions:j(e.link,e.at)}):null}],R=f!=null&&x[f]?.kind===`filter`?x[f]:null,z=new Set(b.flatMap(e=>e.set?[e.set.id]:[])),{options:B,recent:ee}=wo((c??[]).filter(e=>!z.has(e.id)),e=>C.get(e)?.updated),V=`${Qs[n]} filters`,H=x.flatMap((e,t)=>e.kind===`filter`?[t]:[]),te=a?H:v,U=()=>{y(null),o?.()},W=e=>e.length===1?x[e[0]].filter.id:`${e.length} filters`,ne=async(a,o)=>{let c=a.map(e=>x[e].filter),l=e,u=null,d,f,p;if(o.kind===`new`){let r;try{r=await s.create(o.name,{...L().blankFilterSetBody(),filters:c.map(e=>structuredClone(e))})}catch(e){return e instanceof Error?e.message:String(e)}d=r.name,u=L().newFilterLink({id:r.id,name:d}),f=Ee(e,t,at(x,a,u),n),p=()=>{s.remove(r.id).catch(()=>{})}}else{let r=s.entry(o.id)?.doc;if(!r)return`That filter set hasn't loaded.`;s.edit(o.id,e=>$e(e,c.map(e=>structuredClone(e)))),await s.flush(o.id);let i=s.entry(o.id),l=rs(i?.sync);if(l)return s.edit(o.id,()=>r.body),l;d=r.name||r.id;let m=b.find(e=>e.set?.id===o.id);m||(u=L().newFilterLink({id:o.id,name:r.name})),f=Ee(e,t,at(x,a,u),n),m?.pin!=null&&i?.doc&&(f=pe(f,t,m.id,i.doc.version,n)),p=()=>s.edit(o.id,()=>r.body)}let m=W(a);return U(),r(f),i({label:`Moved ${m} to ${d}`,restore:()=>{r(l),p()}}),null},G=wo(c??[],e=>C.get(e)?.updated);return(0,$.jsxs)(`div`,{className:`filter-stage`,id:`job-${t}-filters-${n}`,children:[x.length>0&&(0,$.jsx)(J,{className:`fs-table`,cards:!0,label:V,rows:N,defaultSort:null,rowKey:e=>e.kind===`inner`?e.key:e.kind===`set`?e.link.id:`${e.from}/${e.filter.id}`,rowProps:e=>e.kind===`inner`?{className:`fs-inner-row${fd(e.filter)===n?``:` fs-elsewhere`}`}:{},columns:I}),(0,$.jsx)(`span`,{className:`add-btn fs-add`,children:(0,$.jsx)(Y,{label:`Add filter`,trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(M.add,{size:14,"aria-hidden":`true`}),`Add filter`]}),actions:[{label:`New filter…`,icon:At,onSelect:()=>_(`type`)},{label:`Link filter set…`,icon:In,onSelect:()=>_(`link`)}]})}),g===`type`&&(0,$.jsx)(ec,{stage:n,title:`New ${Qs[n].toLowerCase()} filter`,onPick:e=>{_(null),h(Us(l(S,`New filter`),e))},onClose:()=>_(null)}),(m||R)&&(0,$.jsx)(Xs,{filter:m??R.filter,isNew:!!m,others:m?S:S.filter(e=>e!==R.filter),onSave:e=>{E(m?[...x,{kind:`filter`,filter:e,from:``}]:x.map((t,n)=>n===f?{...R,filter:e}:t)),h(null),p(null)},onClose:()=>{h(null),p(null)}},m?`new`:f),te&&te.length>0&&te.every(e=>x[e]?.kind===`filter`)&&(0,$.jsx)(ld,{what:W(te),options:G.options,recent:G.recent,taken:new Set((c??[]).map(e=>e.name)),linkedHere:z,ready:e=>!!s.entry(e)?.doc,onPick:e=>s.load(e),onMove:e=>ne(te,e),onClose:U}),g===`link`&&(0,$.jsx)(ue,{kind:`Filter set`,title:`Link filter set`,usedLabel:`Last changed`,value:``,options:B,recent:ee,onPick:i=>r(de(e,t,{id:i,name:C.get(i)?.name??``},n)),onClose:()=>_(null),footer:(0,$.jsxs)(`button`,{type:`button`,className:`ghost pick-item`,onClick:()=>void(async()=>{let i=await s.create(hd(`Untitled filter set`,new Set((c??[]).map(e=>e.name))),L().blankFilterSetBody());r(de(e,t,{id:i.id,name:i.name},n)),_(null)})(),children:[(0,$.jsx)(M.add,{size:14,"aria-hidden":`true`}),`New filter set…`]})})]})}function md(e,t,n){return[`text`,`items`].reduce((r,i)=>r+L().filterSetsOf(t.jobs[n],i).reduce((t,n)=>t+(n.own?n.own.filters.length:dd(ud(e,n.set.id)??[],i)),0),0)}function hd(e,t){if(!t.has(e))return e;for(let n=2;;n++)if(!t.has(`${e} ${n}`))return`${e} ${n}`}function gd({k:e,pipeline:t,sources:n,edit:r,offer:i,open:o,onToggle:c}){let[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(null),p=L(),m=t.jobs[e],h=e===0?p.contentOf(t):null,g=p.flowStepOf(m),_=p.sendsImage(m),v=p.tokensOf(m),y=p.CONTENT_TYPES,x=p.targetsOf(t).some((n,r)=>p.STEP_TYPES[p.targetStepOf(t,r,e)?.type??``]?.asks===`request`)||e===0&&!!y[h?.type??``]?.inline,S=h?.type===`source`?n.find(e=>e.id===h.ref.id):void 0,C=S?.type===`dynamic`&&(!S?.provider||p.DYNAMIC_PROVIDERS[S.provider]?.tier!==`supplied`),w=C&&h?.type===`source`?h.live??(S?S.files===0:!1):!1,T=[...e>0?[{kind:`reply`}]:[],...h?[{kind:`attach`}]:[],...g?[{kind:`flow`}]:[],..._?[{kind:`image`}]:[],...v.map(e=>({kind:`mapping`,name:e.name}))],D=(e,n)=>{let a=t;r(n),i({label:e,restore:()=>r(a)})},O=(e,n)=>r(ve(p.withContent(t,e),0,n)),k=[...e===0&&!h?[{label:`Source…`,icon:M.add,onSelect:()=>u(!0)},{label:y.text?.label??`Text`,icon:M.add,onSelect:()=>O({type:`text`,text:``},!1)},{label:y.prompt?.label??`Prompt only`,icon:M.add,onSelect:()=>O({type:`prompt`},!1)}]:[],...!_&&!x?[{label:p.STEP_TYPES.attachImage?.label??`Image`,icon:M.add,onSelect:()=>r(ve(t,e,!0))}]:[],{label:`Token mapping`,icon:M.add,onSelect:()=>f({mode:`add`})}],A=n=>{n.kind===`attach`?D(`Removed the content`,p.withContent(t,null)):n.kind===`image`?D(`Stopped sending the image`,ve(t,e,!1)):n.kind===`mapping`&&D(`Removed {${n.name}}`,I(t,e,n.name))},j=d?.mode===`edit`?v.find(e=>e.name===d.name):void 0,P=n=>{let a=t;d?.mode===`add`?r(Ct(a,e,n.name,n.type)):j&&(r(Fe(a,e,j.name,n)),n.type!==j.type&&j.value&&i({label:`Changed {${j.name}} to ${p.TOKEN_TYPES[n.type]?.label.toLowerCase()??n.type}`,restore:()=>r(a)})),f(null)},F=(i,a)=>{switch(i.kind){case`reply`:return[{key:`reply`,label:`${p.jobLabel(t,e-1)} reply`,locked:!0,control:{type:`static`,text:`Each target's ${s(p.outOf(t.jobs[e-1]).kind)}`}}];case`attach`:return[h?.type===`text`?{key:`attach`,label:p.STEP_TYPES.attachContent?.label??`Attach Content`,required:!0,actions:a,control:{type:`textarea`,value:h.text,placeholder:`The item every target is sent`,onChange:e=>r(p.withContent(t,{...h,text:e}))}}:{key:`attach`,label:p.STEP_TYPES.attachContent?.label??`Attach Content`,required:!0,actions:a,control:{type:`static`,text:yd(h,n)}},...C&&h?.type===`source`?[{key:`freshness`,label:`Produce live`,hint:w?`Fresh at submit, kept with the run`:`Grade the stored snapshots`,control:{type:`switch`,checked:w,onChange:e=>r(p.withContent(t,{...h,live:e}))}}]:[]];case`flow`:return[{key:`flow`,label:p.STEP_TYPES.flowStep?.label??`Flow step`,required:!0,actions:a,control:{type:`static`,text:g?.step??``}}];case`image`:return[{key:`image`,label:p.STEP_TYPES.attachImage?.label??`Attach Image`,required:!0,actions:a,control:{type:`static`,text:`Each item`}}];case`mapping`:{let n=v.find(e=>e.name===i.name),o=p.TOKEN_TYPES[n.type],s=o?.fields??[];return[{key:`mapping-${n.name}`,label:o?o.notation(n.name):`{${n.name}}`,code:!0,required:!0,control:s.includes(`value`)?{type:`text`,value:n.value??``,onChange:i=>r(N(t,e,n.name,{value:i}))}:{type:`static`,text:o?.label??n.type},...s.includes(`enabled`)?{enabled:{checked:!!n.enabled,onChange:i=>r(N(t,e,n.name,{enabled:i}))}}:{},actions:[{label:`Edit…`,icon:M.edit,onSelect:()=>f({mode:`edit`,name:n.name})},...a]}]}}},R=t=>t.kind===`reply`?`Job ${e+1} reply`:t.kind===`flow`?`Job ${e+1} flow step`:t.kind===`mapping`?`{${t.name}}`:t.kind===`attach`?`Content`:`Image`,z=T.map(r=>_d[r.kind](t,e,n)).join(`, `)||`none`;return(0,$.jsxs)(E,{id:`job-${e}-content`,title:`Content`,level:3,note:z,open:o,onToggle:c,children:[(0,$.jsx)(tt,{noun:`content`,items:T,onAdd:k,onRemove:e=>A(T[e]),locked:e=>e.kind===`reply`||e.kind===`flow`,extra:e=>e.kind===`attach`?[{label:`Change content`,icon:M.rename,onSelect:()=>u(!0)}]:[],empty:(0,$.jsx)(`p`,{className:`note`,children:`No content`}),renderItem:(t,n,r)=>(0,$.jsx)(`div`,{className:`stage-row`,id:t.kind===`mapping`?void 0:`job-${e}-${t.kind}`,children:(0,$.jsx)(a,{label:R(t),rows:F(t,r)})},t.kind===`mapping`?`m-${t.name}`:t.kind)}),d&&(d.mode===`add`||j)&&(0,$.jsx)(Re,{title:j?p.TOKEN_TYPES[j.type]?.notation(j.name)??`{${j.name}}`:`New mapping`,initial:j?{name:j.name,type:j.type}:{name:``,type:`value`},problem:n=>te(t,e,n,j?.name),onSave:P,onClose:()=>f(null)},d.mode===`edit`?d.name:`add`),l&&(0,$.jsxs)(b,{title:h?`Change content`:`Add content`,onClose:()=>u(!1),children:[(0,$.jsx)(Tu,{mode:`pick`,onPick:e=>{O({type:`source`,ref:ge(e.id,e.name),first:null,loops:1},p.sourceTypeOf(e)?.sendsImage??!1),u(!1)}}),(0,$.jsxs)(`div`,{className:`pick-others`,children:[(0,$.jsx)(`h2`,{className:`shead-title`,children:`Without a Source`}),(0,$.jsxs)(`button`,{type:`button`,className:`ghost pick-item`,onClick:()=>{O({type:`text`,text:``},!1),u(!1)},children:[(0,$.jsx)(`span`,{children:y.text?.label??`Text`}),y.text?.description&&(0,$.jsx)(`span`,{className:`pick-about`,children:y.text.description})]}),(0,$.jsxs)(`button`,{type:`button`,className:`ghost pick-item`,onClick:()=>{O({type:`prompt`},!1),u(!1)},children:[(0,$.jsx)(`span`,{children:y.prompt?.label??`Prompt only`}),y.prompt?.description&&(0,$.jsx)(`span`,{className:`pick-about`,children:y.prompt.description})]})]})]})]})}var _d={reply:(e,t)=>`${L().jobLabel(e,t-1)}, ${s(L().outOf(e.jobs[t-1]).kind)}`,attach:(e,t,n)=>yd(L().contentOf(e),n),flow:(e,t)=>L().flowStepOf(e.jobs[t])?.step??``,image:()=>`image`,mapping:()=>`token mapping`},vd=(e,t)=>{let n=t.find(t=>t.id===e.ref.id);if(!n)return`A Source that is gone: ${e.ref.name}`;let r=`${n.name}, ${n.files} ${n.files===1?`file`:`files`}`;return n.type===`dynamic`&&(!n.provider||L().DYNAMIC_PROVIDERS[n.provider]?.tier!==`supplied`)?`${r}, ${e.live??n.files===0?`live`:`snapshot`}`:r},yd=(e,t)=>e?e.type===`source`?vd(e,t):L().CONTENT_TYPES[e.type]?.label??e.type:`none`;function bd({index:e}){return(0,$.jsx)(`span`,{className:`target-badge`,"aria-hidden":`true`,children:L().targetLetter(e)})}var xd=e=>e instanceof Error?e.message:String(e);function Sd({pipeline:e,title:t,onClose:n}){let r=Z(),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(null),c=L().contentOf(e),l=c?.type===`source`?c.ref.id:null,u=(0,X.useCallback)(()=>{if(s(null),!l){a([]);return}(async()=>{try{let t=(await r.source(l)).files.filter(e=>e.name.toLowerCase().endsWith(`.json`));a(await Promise.all(t.map(async t=>{let n=JSON.parse(await jl(await r.file(l,t.name)));return{name:t.name,reply:L().recordedReplyOf(e,n)}})))}catch(e){s(xd(e))}})()},[r,l,e]);return(0,X.useEffect)(u,[u]),(0,$.jsx)(b,{title:t,wide:!0,className:`edit`,onClose:n,children:i?i.length?(0,$.jsx)(`div`,{className:`recorded-replies`,children:i.map(e=>(0,$.jsxs)(`section`,{"aria-label":e.name,children:[(0,$.jsx)(`h3`,{children:e.name}),(0,$.jsx)(`pre`,{children:e.reply??`(no recorded reply)`})]},e.name))}):(0,$.jsx)(`p`,{className:`note`,children:`No calls.`}):(0,$.jsx)(C,{label:`Replies`,error:o,onRetry:u})})}function Cd({k:e,pipeline:t,connections:n,connectionProfiles:r,targetCap:i,onRequestRename:a,onAdd:o,onClone:s,onRemove:c,onConnection:l,onProfile:u,onEcho:d,onPrompt:f,onStep:p,onSelectPrompt:m,onClearPrompt:h,onSaveToLibrary:g,onCopyRequest:_,defaultPrompt:v,onRevert:y,say:b=()=>{}}){let x=L(),[S]=Q(`promptlab.versions`),C=e=>S.profile?.[e]?.[0]?.at??null,w=x.targetsOf(t),T=w.length,[D,O]=(0,X.useState)(null),k=Mt(t,e).map(e=>({label:x.STEP_TYPES[e].label??e,icon:bt(e).icon??ze,onSelect:()=>o(e)}));return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(E,{id:`job-${e}-targets`,title:`Targets`,level:3,note:`${T} ${T===1?`target`:`targets`}`,children:(0,$.jsx)(tt,{noun:`target`,items:w,min:1,max:i,onAdd:k,onClone:s,onRemove:c,onRename:a,extra:(n,r)=>bt(x.targetStepOf(t,r,e)?.type).actions?.({pipeline:t,i:r,k:e,say:b,onSelectPrompt:()=>m(r),onClearPrompt:()=>h(r),onSaveToLibrary:()=>g(r),onCopyRequest:()=>_(r),onPreviewReplies:()=>O(r),defaultPrompt:v,onRevert:y&&(()=>y(r))})??[],empty:(0,$.jsx)(`p`,{className:`note`,children:`No targets`}),renderItem:(i,a,o)=>{let s=yt(t,a),c=Me(t,a,e)??{type:`prompt`,prompt:``},m=bt(c.type),h=x.STEP_TYPES[c.type],g=e>0&&!!h?.firstJobOnly,_=!!x.CONNECTION_TYPES[h?.replaces??``]?.replays,v=!g&&_?kt(t,e):null;return(0,$.jsxs)(`div`,{className:`target`,id:`job-${e}-target-${a}`,children:[(0,$.jsxs)(`div`,{className:`target-head`,children:[(0,$.jsx)(bd,{index:a}),(0,$.jsx)(`h4`,{className:`target-name`,children:s}),g&&(0,$.jsx)(`span`,{className:`target-idle`,children:`Job 1 only`}),(0,$.jsx)(Y,{actions:o,label:`${s} actions`})]}),!g&&_&&(0,$.jsxs)($.Fragment,{children:[h?.description&&(0,$.jsx)(`p`,{className:`note`,children:h.description}),v!=null&&(0,$.jsxs)(`div`,{className:`prompt`,children:[(0,$.jsx)(`span`,{className:`prop-name`,children:`Prompt`}),(0,$.jsx)(Nt,{className:`readonly`,words:v,showExprs:!1})]})]}),!g&&!_&&(0,$.jsx)(gt,{label:s,asks:kd(e===0?{connection:Dd(c)?wd:i.connection?.id??``,at:i.connection,profile:i.profile,fixed:Od(),echo:Dd(c)}:{connection:c.connection?.id??Ed,at:c.connection,profile:c.profile,own:c.connection!=null||c.profile!=null,same:`Same as ${x.jobLabel(t,0)}`},n,r,C,{connection:e=>e===wd?d(a):l(a,e===Ed?null:jd(n,e)),profile:e=>u(a,e===Ed?`same`:e===Td?null:jd(r,e))}),prompt:c.prompt,onPrompt:e=>f(a,e),rows:m.rows?.(c,e=>p(a,e))??[],request:m.request?.(c)??[],requestId:`job-${e}-target-${a}-request`,promptLabel:m.promptLabel?.(c)??`Prompt`,words:m.words?.(c),fields:m.fields?.(c)})]},`${a}-${e}`)}})}),D!==null&&(0,$.jsx)(Sd,{pipeline:t,title:`${yt(t,D)} replies`,onClose:()=>O(null)})]})}var wd=`#echo`,Td=`#default`,Ed=``,Dd=e=>!!L().STEP_TYPES[e.type]?.local,Od=()=>Object.entries(L().STEP_TYPES).filter(([,e])=>e.slot===`target`&&e.local&&!L().CONNECTION_TYPES[e.replaces??``]?.replays).map(([,e])=>({id:wd,label:e.label??`Echo`}));function kd(e,t,n,r,i){let a=e.same!=null,o={key:`connection`,label:`Connection`,required:!a,control:{type:`picker`,kind:`Connection`,value:e.connection,usedLabel:`Last changed`,...wo(Ad(t,e.at),r,a?[{id:Ed,label:e.same}]:e.fixed),onChange:i.connection}};if(e.echo)return[o];let s=a&&!e.own?Ed:e.profile?.id??Td,c=[...a&&e.connection===Ed?[{id:Ed,label:e.same}]:[],{id:Td,label:`(Default)`}];return[o,{key:`profile`,label:`Profile`,control:{type:`picker`,kind:`Profile`,value:s,...wo(Ad(n,e.profile),()=>null,c),onChange:i.profile}}]}var Ad=(e,t)=>[...t?.id&&!e.some(e=>e.id===t.id)?[{id:t.id,name:`${t.name||t.id} (missing)`}]:[],...e.map(e=>({id:e.id,name:e.name}))],jd=(e,t)=>{let n=e.find(e=>e.id===t);return n?{id:n.id,name:n.name}:null};function Md({text:e,writtenFor:t,say:n,onClose:r}){let i=async()=>{n(await Ft(e)?`Copied the request.`:`Could not copy.`),r()};return(0,$.jsx)(ut,{title:`Copy request`,wide:!0,onClose:r,sections:[{key:`request`,rows:[{key:`for`,label:`Written for`,control:{type:`static`,text:t}},{key:`body`,label:`Request`,control:{type:`code`,text:e}}]}],actions:[{label:`Copy`,icon:U,primary:!0,onSelect:()=>void i()}]})}function Nd({pipeline:t,connections:n,connectionProfiles:r,resolve:i,sources:a,targetCap:s,prompt:c=``,defaultPrompt:l,protectedTerms:u,edit:d,offer:f}){let[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(null),[_,b]=(0,X.useState)(null),[S,C]=(0,X.useState)(null),[w,T]=(0,X.useState)(null),[O,k]=(0,X.useState)(null),[A,j]=(0,X.useState)({}),M=e=>A[e]??!1,N=e=>t=>j(n=>({...n,[e]:t})),P=Tr(),F=us(),[,I]=(0,X.useState)(0);(0,X.useEffect)(()=>F.subscribe(()=>I(e=>e+1)),[F]);let R=()=>{let e=L().contentOf(t),n=e?.type===`source`?e.ref.id:null,r=n?a.find(e=>e.id===n)?.platform:void 0;return r&&L().WORKFLOW_PLATFORMS[r]||null},B=(e,n)=>{let r=t;d(n),f({label:e,restore:()=>d(r)})},V=(e,n)=>(0,$.jsx)(pd,{pipeline:t,job:e,stage:n,edit:d,offer:f,moveAll:w?.k===e&&w.stage===n,onMoveAllClose:()=>T(null)}),H=(e,n)=>[{label:`Move all to filter set…`,icon:Pn,disabled:!L().filterSetsOf(t.jobs[e],n).some(e=>e.own?.filters.length),onSelect:()=>T({k:e,stage:n})}],te=e=>{let t=i(L().answerKey(e.connection.id,e.profile?.id));return t?L().CONNECTION_TYPES[L().typeOf(t)]?.answers??[`prompt`]:void 0},U=e=>{let t=r.find(t=>t.fromProfile===e);return t?{id:t.id,name:t.name}:null},W=!L().targetsOf(t).length;return(0,$.jsxs)(`div`,{className:`jobs`,children:[O&&(0,$.jsx)(`p`,{className:`note`,role:`status`,children:O}),(0,$.jsx)(tt,{noun:`job`,items:t.jobs,min:1,addDisabled:W,onAdd:()=>d(qe(t)),onClone:e=>d(ke(t,e)),onRemove:e=>B(`Removed ${L().jobLabel(t,e)}`,D(t,e)),onRename:e=>m({job:e}),renderItem:(i,o,p)=>{let h=`Job ${o+1}${i.name?.trim()?` - ${i.name.trim()}`:``}`,_=L().flowStepOf(i)?L().readAsOf(i):void 0;return(0,$.jsxs)(X.Fragment,{children:[o>0&&(0,$.jsxs)(`div`,{className:`job-reply`,"aria-hidden":`true`,children:[(0,$.jsx)(y,{size:16}),(0,$.jsx)(`span`,{children:`Reply`})]}),(0,$.jsx)(E,{id:`job-${o}`,title:h,level:2,actions:p,note:Fd(t,o),children:(0,$.jsxs)(`div`,{className:`stages`,children:[(0,$.jsx)(gd,{k:o,pipeline:t,sources:a,edit:d,offer:f,open:M(`job-${o}-content`),onToggle:N(`job-${o}-content`)}),(0,$.jsx)(Cd,{k:o,pipeline:t,connections:L().flowStepOf(i)?n:n.filter(Pd),connectionProfiles:r,targetCap:s,onRequestRename:e=>m({job:o,scenario:e}),onAdd:e=>d(pt(t,o,e,ce(n,U),c)),onClone:e=>d(Ht(t,e)),onRemove:e=>B(`Removed ${yt(t,e)}`,q(t,e)),onConnection:(e,n)=>d(ie(t,e,o,n,te)),onProfile:(e,n)=>d(Ke(t,e,o,n,te)),onEcho:n=>d(e(t,n)),onPrompt:(e,n)=>d(Ce(t,e,o,n)),onStep:(e,n)=>d(Id(t,e,o,n)),say:k,onSelectPrompt:e=>g({i:e,k:o}),onClearPrompt:e=>B(`Cleared ${yt(t,e)}'s prompt`,Ce(t,e,o,``)),onSaveToLibrary:e=>b({i:e,k:o}),onCopyRequest:e=>C({i:e,k:o}),...o===0&&l?{defaultPrompt:l.text,onRevert:e=>B(`Reverted ${yt(t,e)} to the default`,ct(t,e,0,l.text,{id:l.id,name:vr(l)}))}:{}}),(0,$.jsx)(Pe,{id:`job-${o}-responses`,open:M(`job-${o}-responses`),onToggle:N(`job-${o}-responses`),out:L().outOf(i),format:!!L().replyOf(i),readAs:_,outputKinds:tn(),modifiers:oe(),onFormat:e=>e==null?B(`Set Response Format to Text`,v(t,o)):d(x(L().replyOf(i)?t:Ve(t,o),o,e)),onSetting:(e,n)=>d(Ld(t,o,t=>({...t,[e]:n}))),onReadAs:e=>e==null?B(`Removed Read as`,be(t,o,null)):d(be(t,o,e)),...u?{protectedTerms:u}:{},offer:f,onModifier:(e,n)=>d(Rd(t,o,e,n)),onAddModifier:e=>d(Ld(t,o,t=>({...t,modifiers:[...t.modifiers,e]}))),onRemoveModifier:e=>B(`Removed a modifier`,Ld(t,o,t=>({...t,modifiers:t.modifiers.filter((t,n)=>n!==e)}))),filters:md(F,t,o),pre:V(o,`text`),preActions:H(o,`text`),...L().OUTPUT_KINDS[L().outOf(i).kind]?.offers?.includes(`items`)?{post:V(o,`items`),postActions:H(o,`items`)}:{}})]})})]},i.id||o)}}),W&&(0,$.jsx)(`p`,{className:`note add-why`,children:`Add a target first.`}),p&&`scenario`in p?(0,$.jsx)(Tt,{title:`Rename ${yt(t,p.scenario)}`,value:L().targetsOf(t)[p.scenario]?.name??``,onCommit:e=>d(he(t,p.scenario,e)),onClose:()=>m(null)}):p?(0,$.jsx)(Tt,{title:`Rename ${L().jobLabel(t,p.job)}`,value:t.jobs[p.job]?.name??``,onCommit:e=>d(o(t,p.job,e)),onClose:()=>m(null)}):null,h&&(0,$.jsx)(cd,{onClose:()=>g(null),used:{byScenario:z(t,h.i),byAll:ee(t)},onPick:e=>{let n=t;d(ct(n,h.i,h.k,e.text,{id:e.id,name:vr(e)})),g(null),f({label:`Picked ${vr(e)}`,restore:()=>d(n)})}}),_&&(()=>{let{i:e,k:n}=_,r=L().targetStepOf(t,e,n)?.prompt??``;return(0,$.jsx)(Tt,{title:`Save to library`,value:r.split(`
|
|
11
|
-
`)[0]?.trim()??``,onCommit:i=>void(async()=>{let a=await P.create({name:i,text:r});d(ct(t,e,n,r,{id:a.id,name:vr(a)})),k(`Saved ${vr(a)} to the library.`)})(),onClose:()=>b(null)})})(),S&&(()=>{let e=Me(t,S.i,S.k);if(!e)return null;let{text:n,writtenFor:r}=nt(e,R());return(0,$.jsx)(Md,{text:n,writtenFor:r,say:k,onClose:()=>C(null)})})()]})}var Pd=e=>(L().CONNECTION_TYPES[e.type??``]?.answers??[`prompt`]).includes(`prompt`);function Fd(e,t){let n=L(),r=r=>e.jobs[t].steps.filter(e=>n.STEP_TYPES[e.type]?.slot===r).length,i=e.jobs[t],a=i.steps.filter(e=>e.type!==`tokenMappings`&&n.STEP_TYPES[e.type]?.slot===`content`).length+n.tokensOf(i).length;return`Content ${t>0&&!a?`Reply`:a} → Targets ${n.targetsOf(e).length} → Responses ${r(`responses`)}`}var Id=(e,t,n,r)=>L().withTarget(e,t,n,e=>{let t={...e,...r};for(let[e,n]of Object.entries(r))n===``&&e!==`prompt`&&e!==`system`&&delete t[e];return t}),Ld=(e,t,n)=>({...e,jobs:e.jobs.map((e,r)=>r===t?L().withOut(e,n(L().outOf(e))):e)}),Rd=(e,t,n,r)=>Ld(e,t,e=>({...e,modifiers:e.modifiers.map((e,t)=>t===n?r:e)}));function zd(e,t){if(!e||!t)return null;let n=e.cases.map(e=>L().caseItem(e));return{found:L().itemsFound(n,t),total:n.length}}function Bd({pipeline:e,edit:t,offer:n,children:r,profiles:i=[],labGrader:a=null,contentFiles:o}){let s=hr(),{list:c}=gr(),[l,u]=(0,X.useState)(!1),[d,p]=(0,X.useState)(null),m=e.evals,[,g]=(0,X.useState)(0);(0,X.useEffect)(()=>s.subscribe(()=>g(e=>e+1)),[s]),(0,X.useEffect)(()=>{for(let e of m)e.group&&s.load(e.group.id)},[m,s]);let _=(r,i)=>{let a=e;t(r),n({label:i,restore:()=>t(a)})},v=e=>s.entry(e)?.doc?.body??null,y=new Map((c??[]).map(e=>[e.id,e])),b=new Set(m.flatMap(e=>e.group?[e.group.id]:[])),x=m.flatMap((e,t)=>e.group?[{t:e,j:t}]:[]),S=m.flatMap((e,t)=>e.own?[{t:e,j:t}]:[]),C=({t,j:n})=>{let r=t.group.id,i=y.get(r)?.versions;return[{label:`Open in Library`,icon:Ie,onSelect:()=>Za(r)},t.pin==null?{label:`Pin`,icon:Vn,disabled:i==null,onSelect:()=>_(A(e,n,i),`Pinned ${t.group.name||r}`)}:{label:`Follow latest`,icon:Bn,onSelect:()=>_(A(e,n,null),`${t.group.name||r} follows the latest`)},{label:`Unlink`,icon:Yn,onSelect:()=>_(ne(e,n),`Unlinked ${t.group.name||r}`)}]};return(0,$.jsxs)(E,{id:`evals`,title:`Evals`,level:2,note:m.length?String(m.length):`None`,children:[m.length===0&&(0,$.jsx)(`p`,{className:`note evals-empty`,children:`No evals — the run is unscored.`}),m.length>0&&(0,$.jsx)(Hd,{pass:e.pass,count:m.length,edit:n=>t(Et(e,n))}),x.length>0&&(0,$.jsx)(J,{className:`eg-links`,cards:!0,label:`Linked eval groups`,rows:x,rowKey:e=>e.t.id,columns:[{key:`group`,header:`Eval group`,role:`title`,sort:e=>(e.t.group.name||``).toLowerCase(),cell:e=>(0,$.jsx)(`button`,{type:`button`,className:`eg-open`,onClick:()=>Za(e.t.group.id),children:e.t.group.name||e.t.group.id})},{key:`items`,header:`Items here`,sort:e=>zd(v(e.t.group.id),o)?.found??-1,cell:e=>{let t=zd(v(e.t.group.id),o);if(!t)return`…`;let n=`${t.found} of ${t.total}`;return t.found<t.total?(0,$.jsxs)(`span`,{className:`eval-flag`,title:`${t.total-t.found} not in this run's content`,children:[(0,$.jsx)(An,{size:12,"aria-hidden":`true`}),n]}):n}},{key:`follows`,header:`Version`,sort:e=>e.t.pin??0,cell:e=>e.t.pin==null?`Follow latest`:`Pinned v${e.t.pin}`},{key:`menu`,header:``,label:``,role:`menu`,sort:null,cell:e=>(0,$.jsx)(Y,{label:`${e.t.group.name||e.t.group.id} actions`,actions:C(e)})}]}),(0,$.jsxs)(`button`,{type:`button`,className:`ghost eg-add`,onClick:()=>u(!0),children:[(0,$.jsx)(M.add,{size:14,"aria-hidden":`true`}),`Link eval group`]}),r,S.map(({t:n,j:r})=>(0,$.jsx)(Vd,{ev:n,label:L().evalLabel(e,r),renaming:d===r,onRename:()=>p(r),profiles:i,labGrader:a,rawReply:e.jobs.some(e=>L().readAsOf(e)!=null),casesBody:n.own.casesFrom?v(n.own.casesFrom.id):null,loadCases:()=>{n.own.casesFrom&&s.load(n.own.casesFrom.id)},set:n=>t(w(e,r,n)),undoableSet:(t,n)=>_(w(e,r,t),n),onCommitName:n=>{t(en(e,r,n)),p(null)},onCancelName:()=>p(null),onCopyCases:t=>_(Zt(e,r,t),`Copied ${L().evalLabel(e,r)}'s cases in`),onMoveToLibrary:async()=>{let t=Wd((n.name||``).trim()||L().evalLabel(e,r),new Set((c??[]).map(e=>e.name))),{casesFrom:i,...a}=n.own,o=await s.create(t,a);_(f(e,r,{id:o.id,name:o.name}),`Moved ${t} to the Library`)},onRemove:()=>_(ne(e,r),`Removed ${L().evalLabel(e,r)}`)},n.id)),l&&(0,$.jsx)(Ud,{list:c??[],linkedIds:b,contentFiles:o,onLink:n=>{t(h(e,n)),u(!1)},onNew:async()=>{let n=await s.create(Wd(`Untitled eval group`,new Set((c??[]).map(e=>e.name))));t(h(e,{id:n.id,name:n.name})),u(!1)},onClose:()=>u(!1)})]})}function Vd({ev:e,label:t,renaming:n,onRename:r,profiles:i,labGrader:o,rawReply:s,casesBody:c,loadCases:l,set:u,undoableSet:d,onCommitName:f,onCancelName:p,onCopyCases:m,onMoveToLibrary:h,onRemove:g}){let _=L(),[v]=Q(`promptlab.versions`),y=e.own;(0,X.useEffect)(()=>{y.casesFrom&&l()},[y.casesFrom,l]);let b=_.isWholeRun(_.EVAL_TYPES.group,e),x=b?y.run:y.every,S=t=>u({...e,own:{...y,...t}}),C=t=>({...e,own:{...y,...b?{run:t}:{every:t}}}),w=x.some(e=>_.METRICS[e.type]?.graded),T=i.filter(e=>(_.CONNECTION_TYPES[e.type??``]?.answers??[`prompt`]).includes(`prompt`)),{mode:D,threshold:O}=y.scoring,k=[{label:`Rename…`,icon:M.rename,onSelect:r},...y.casesFrom?[{label:`Copy cases in`,icon:U,disabled:!c,onSelect:()=>c&&m(c.cases)}]:[],{label:`Move to Library`,icon:Pn,onSelect:()=>void h()},{label:`Remove`,icon:M.remove,destructive:!0,onSelect:g}],A=[{key:`mode`,label:`Scored`,control:{type:`select`,value:D,options:[{value:`all`,label:`All must pass`},{value:`weighted`,label:`Weighted points`}],onChange:e=>S({scoring:{mode:e===`weighted`?`weighted`:`all`,threshold:e===`weighted`?O??1:O}})}},...D===`weighted`?[{key:`threshold`,label:`Pass at`,width:`quarter`,control:{type:`text`,value:O==null?``:String(O),onChange:e=>S({scoring:{mode:D,threshold:e.trim()?/^-?\d+(\.\d+)?$/.test(e.trim())?Number(e):e:null}})}}]:[],...y.casesFrom?[]:[{key:`over`,label:`Reads`,control:{type:`select`,value:b?`run`:`item`,options:[{value:`item`,label:`Each item`},{value:`run`,label:`Whole run`}],onChange:e=>S(e===`run`?{every:[],run:[...y.every,...y.run]}:{every:[...y.every,...y.run],run:[]})}}],...y.casesFrom?[{key:`cases-from`,label:`Cases from`,control:{type:`static`,text:y.casesFrom.name||y.casesFrom.id}}]:[],...w||y.grader?[{key:`grader`,label:`Grader`,control:{type:`picker`,kind:`Connection`,value:y.grader?.id??``,usedLabel:`Last changed`,...wo(T,e=>v.profile?.[e]?.[0]?.at??null,[{id:``,label:o?`Lab (${o.name})`:`None`}]),onChange:e=>{let t=i.find(t=>t.id===e);S({grader:t?{id:t.id,name:t.name}:null})}}}]:[]];return(0,$.jsx)(E,{id:`eval-${e.id}`,title:t,level:3,note:_.EVAL_TYPES.group?.label??`Eval group`,about:`A group of this pipeline's own, defined here rather than in the Library.`,actions:k,...n?{rename:{value:e.name||t,onCommit:f,onCancel:p}}:{},children:(0,$.jsxs)(re,{children:[(0,$.jsx)(a,{label:t,rows:A}),(0,$.jsx)(So,{label:t,metrics:x,over:b?`run`:`item`,rawReply:s,set:e=>u(C(e)),undoable:(e,t)=>d(C(e),t)}),(0,$.jsx)(a,{label:`${t} on failure`,rows:[{key:`continue`,label:`Continue on failure`,control:{type:`checkbox`,checked:e.continueOnFailure,onChange:t=>u({...e,continueOnFailure:t})}}]})]})})}function Hd({pass:e,count:t,edit:n}){let r=e.mode===`atLeast`?e.count:t,i=[{key:`pass`,label:`Pass when`,control:{type:`select`,value:e.mode,options:[{value:`all`,label:`All groups pass`},{value:`atLeast`,label:`At least`}],onChange:e=>n(e===`atLeast`?{mode:`atLeast`,count:Math.min(Math.max(r,1),t)}:{mode:`all`})}},...e.mode===`atLeast`?[{key:`count`,label:`Groups`,width:`quarter`,control:{type:`text`,value:String(e.count),onChange:e=>{let t=Number(e);n({mode:`atLeast`,count:Number.isInteger(t)&&t>0?t:e.trim()})}}}]:[]];return(0,$.jsx)(a,{label:`Pass rule`,rows:i})}function Ud({list:e,linkedIds:t,contentFiles:n,onLink:r,onNew:i,onClose:a}){let o=hr(),[,s]=(0,X.useState)(0);(0,X.useEffect)(()=>o.subscribe(()=>s(e=>e+1)),[o]),(0,X.useEffect)(()=>{for(let t of e)o.load(t.id)},[e,o]);let c=e=>zd(o.entry(e)?.doc?.body,n);return(0,$.jsxs)(b,{title:`Link eval group`,onClose:a,children:[e.length===0?(0,$.jsx)(`p`,{className:`note`,children:`No eval groups yet.`}):(0,$.jsx)(`ul`,{className:`pick-list`,"aria-label":`Eval groups`,children:e.map(e=>{let n=t.has(e.id),i=c(e.id),a=n?`Linked`:i&&i.total?`${i.found} of ${i.total} items here`:``;return(0,$.jsx)(`li`,{children:(0,$.jsxs)(`button`,{type:`button`,className:`ghost pick-item`,disabled:n,onClick:()=>r({id:e.id,name:e.name}),children:[(0,$.jsx)(`span`,{children:e.name}),a&&(0,$.jsx)(`span`,{className:`pick-about`,children:a})]})},e.id)})}),(0,$.jsx)(`div`,{className:`pick-others`,children:(0,$.jsxs)(`button`,{type:`button`,className:`ghost pick-item`,onClick:()=>void i(),children:[(0,$.jsx)(M.add,{size:14,"aria-hidden":`true`}),`New eval group…`]})})]})}function Wd(e,t){if(!t.has(e))return e;for(let n=2;;n++)if(!t.has(`${e} ${n}`))return`${e} ${n}`}function Gd({pipeline:e,sourceFiles:t,graded:n,openCaseEditor:r}){let[i,a]=(0,X.useState)({graded:!1,todo:!0,missing:!0});if((L().evalsDataset(e)?.id??null)===null)return null;let o=t??[],s=new Set(n.map(e=>e.item)),c=new Set(o),l=[{key:`graded`,label:`Graded`,tone:`ok`,files:o.filter(e=>s.has(e))},{key:`todo`,label:`To do`,tone:`todo`,files:o.filter(e=>!s.has(e))},{key:`missing`,label:`Missing`,tone:`missing`,files:n.filter(e=>!c.has(e.item)).map(e=>e.item)}];l[0].files.length;let u=l[1].files.length+l[2].files.length,d=l.filter(e=>i[e.key]).flatMap(e=>e.files.map(t=>({file:t,tone:e.tone})));return(0,$.jsx)(E,{id:`mapping`,title:`Mapping`,level:3,note:f(),about:`Which of the content's items the dataset has a case for, and so which are graded.`,children:o.length?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`pills mkey`,role:`group`,"aria-label":`Show`,children:l.filter(e=>e.files.length).map(e=>(0,$.jsxs)(`label`,{className:`pill`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:i[e.key],onChange:()=>a({...i,[e.key]:!i[e.key]})}),(0,$.jsxs)(`span`,{children:[e.label,` `,e.files.length]})]},e.key))}),d.length?(0,$.jsx)(`div`,{className:`mchips`,children:d.map(({file:e,tone:t})=>(0,$.jsx)(`button`,{type:`button`,className:`mchip ${t}`,onClick:()=>r(e),children:e},`${t}-${e}`))}):(0,$.jsx)(`p`,{className:`note`,children:u?`Nothing shown.`:`Every content item is graded.`})]}):(0,$.jsx)(`p`,{className:`note`,children:`No items in the content to map against.`})});function f(){let r=L().contentOf(e),i=r?L().CONTENT_TYPES[r.type]:void 0;if(i?.inline)return i.label;let a=t??[],o=new Set(n.map(e=>e.item)),s=a.filter(e=>o.has(e)).length;return`${Ei(n.length,`case`)}, ${s} of ${a.length} matched`}}function Kd({pipeline:e,edit:t,comment:n,setComment:r,onClear:i,onCopyFailures:o}){let s=[{label:`Clear comment`,icon:Kt,destructive:!0,onSelect:i},{label:`Copy last run's failures`,icon:p,onSelect:o}],c=L().contentOf(e),l=c?.type===`source`?[{key:`first`,label:`Run first`,width:`quarter`,control:{type:`text`,value:c.first==null?``:String(c.first),placeholder:`all`,clearable:!0,onChange:n=>t(L().withContent(e,{...c,first:n.trim()?qd(n):null}))}},{key:`loops`,label:`Loop`,width:`quarter`,control:{type:`text`,value:String(c.loops),placeholder:`1`,onChange:n=>t(L().withContent(e,{...c,loops:Math.max(1,qd(n)??1)}))}}]:[];return(0,$.jsx)(E,{id:`control`,title:`Run settings`,level:2,actions:s,children:(0,$.jsx)(a,{label:`Run settings`,rows:[...l,{key:`comment`,label:`Comment`,width:`full`,control:{type:`text`,value:n,placeholder:`A note to find this run by in History`,onChange:e=>r(e)}}]})})}var qd=e=>{let t=Number.parseInt(e,10);return Number.isNaN(t)?null:t};function Jd({pipelineId:e=null}){let t=Zn(),n=Z(),r=Ye(),i=uo(),{openRun:a}=ci(),{openCaseEditor:o}=Bo(),[s,c]=Q(`promptlab.workflows`),[l]=Q(`promptlab.connections`),[u]=Q(`promptlab.connectionProfiles`),d=(0,X.useMemo)(()=>L().answersOf(L().withSlugs(l.list),u.list),[l.list,u.list]),f=(0,X.useRef)(d);f.current=d;let[p,m]=Q(`promptlab.comment`),[h]=Q(`promptlab.versions`),[g,_]=(0,X.useState)([]),{list:v,error:y}=gr(),{list:x,error:S}=Er(),{list:w}=ds(),T=x?.find(e=>e.default)??null,E=hr(),D=(0,X.useMemo)(()=>(v??[]).map(e=>ge(e.id,e.name)),[v]),O=(0,X.useCallback)(()=>(v??[]).map(e=>{let t=E.entry(e.id)?.doc?.body;return{id:e.id,name:e.name,grader:t?t.grader??null:e.grader??null}}),[v,E]),[k,A]=(0,X.useState)(4),[j,M]=(0,X.useState)(void 0),[N,P]=(0,X.useState)(null),[F,I]=(0,X.useState)(null),R=(0,X.useRef)(F);R.current=F;let[z,B]=(0,X.useState)(!1),[ee,V]=(0,X.useState)(!1),[H,te]=(0,X.useState)(null),U=(0,X.useRef)(null),[W,ne]=(0,X.useState)(null),[G,re]=(0,X.useState)(!1),[ie,ae]=(0,X.useState)(!1),K=(0,X.useRef)(null);(0,X.useEffect)(()=>{let e=!0;return n.sources().then(t=>{e&&_(t.sources)}).catch(()=>{}),n.config().then(t=>{e&&A(t.targetCap)}).catch(()=>{}),()=>{e=!1}},[n]),(0,X.useEffect)(()=>{let e=!0,t,r=async()=>{let i=5e3;try{let t=(await n.queue({limit:1})).runs[0]??null;if(!e)return;!U.current&&t&&!qi(t.status)&&(U.current=t.id),t&&t.id===U.current&&(te(t),qi(t.status)||(i=1e3))}catch{}e&&(t=setTimeout(()=>void r(),i))};return r(),()=>{e=!1,t&&clearTimeout(t)}},[n]);let q=(0,X.useMemo)(()=>s.list.filter(e=>e.work?.version===17),[s.list]),oe=e?q.find(t=>t.id===e):void 0,se=oe??q.find(e=>e.id===s.at)??q[0],le=se?.work,ue=se?.id??``,de=!!e&&!oe&&q.length>0;(0,X.useEffect)(()=>{de&&Ir({tab:`runs`,id:null})},[de]);let fe=(0,X.useCallback)(e=>Fr({tab:`runs`,id:e}),[]),J=le?L().evalsDataset(le)?.id??null:null,pe=_r(J),me=pe?.doc?.body.cases,he=(0,X.useMemo)(()=>(me??[]).map(e=>({id:e.id??``,item:L().caseItem(e)})),[me]),_e=pe?.doc?.body.cases,ve=(0,X.useMemo)(()=>[...new Set((_e??[]).flatMap(e=>(e.metrics??[]).filter(e=>!e.not&&e.weight!==0&&(e.type===`contains-all`||e.type===`contains-any`)).flatMap(e=>L().metricLines(e.values))))],[_e]),ye=T?.text||le&&L().targetStepOf(le,L().targetsOf(le).length-1,0)?.prompt||``,Y=(0,X.useRef)(l.list);Y.current=l.list;let be=(0,X.useRef)(u.list);be.current=u.list;let xe=q.length?null:v?.[0]??null,Se=v!==null||y!==null,Ce=x!==null||S!==null,we=T?.text??``;(0,X.useEffect)(()=>{if(q.length||!Se||!Ce)return;let e=Xd(Y.current,f.current.split,xe?{id:xe.id,name:xe.name}:void 0,we);c({list:[e],at:e.id})},[q.length,c,Se,Ce,xe,we]);let Te=()=>{let e=E.list().list?.[0];return e?{id:e.id,name:e.name}:void 0},Ee=(0,X.useRef)(s);Ee.current=s;let De=(0,X.useRef)(se);De.current=se;let Oe=(0,X.useRef)(le);Oe.current=le;let ke=(0,X.useRef)(null),Ae=(0,X.useRef)(null),je=(0,X.useCallback)(()=>{Ae.current&&clearTimeout(Ae.current);let e=De.current?.id,n=Oe.current;e&&n&&(ke.current={id:e,doc:n},Ae.current=setTimeout(()=>{let e=ke.current;e&&ur(t,`pipeline`,e.id,e.doc,`idle`)},or))},[t]);(0,X.useEffect)(()=>()=>{Ae.current&&clearTimeout(Ae.current)},[]);let Me=(0,X.useCallback)(e=>{let t=Ee.current,n=De.current.id,r={...t,list:t.list.filter(e=>e.work?.version===17).map(t=>t.id===n?{...t,work:e}:t)};Ee.current=r,c(r),je(),P(null)},[c,je]),Ne=l.list[0]?.id??``;(0,X.useEffect)(()=>{let e=Oe.current,t=De.current?.id;if(!e||!t||!Ne)return;let n=Jt(e,ce(Y.current,f.current.split));if(n===e)return;let r=Ee.current,i={...r,list:r.list.map(e=>e.id===t?{...e,work:n}:e)};Ee.current=i,c(i)},[Ne,ue,c]),(0,X.useEffect)(()=>{let e=ke.current;e&&e.id!==ue&&(ur(t,`pipeline`,e.id,e.doc,`idle`),ke.current=null,Ae.current&&=(clearTimeout(Ae.current),null))},[ue,t]);let Pe=le?L().contentOf(le):null,Fe=Pe?.type===`source`?Pe.ref.id:null;(0,X.useEffect)(()=>{if(Fe===null){M(void 0);return}let e=!0;return n.source(Fe).then(t=>{e&&M(t.files.map(e=>e.name))}).catch(()=>{}),()=>{e=!1}},[Fe,n]);let Ie=(0,X.useCallback)(e=>{let t=g.find(t=>t.id===e);return t?{name:t.name,type:t.type,files:e===Fe&&j?j:[]}:null},[g,Fe,j]),Le=(0,X.useMemo)(()=>{let e=l.list.find(e=>e.id===l.grader);return e?{id:e.id,name:e.name}:null},[l]),Re=(0,X.useMemo)(()=>{if(!le)return[];if(!l.list.length&&L().targetsOf(le).length)return[`add a connection first`];let e={profiles:d.resolve,connections:d.connection,sources:Ie,grader:Le,...v?{groups:v}:{}};return L().validatePipeline(le,e)},[le,l.list,d,Ie,v,Le]),ze=ue?h.pipeline?.[ue]??[]:[],Be=(0,X.useCallback)(async()=>{let e=Oe.current,r=De.current.id;ur(t,`pipeline`,r,e,`run`);let i=L().resolvePipeline(e,{profiles:d.resolve,grader:Le,groups:O(),...Fe!==null&&j!==void 0?{files:j}:{},comment:p?.text??``});B(!0),P(null),I(null);try{let e=await n.submit(i);U.current=e.run.id,te(e.run),a(e.run.id,{at:e.run.submittedAt,from:`runs`})}catch(e){P(e instanceof Error?e.message:String(e));let t=e instanceof mn&&e.status===403&&e.body?.unshared;I(Array.isArray(t)?t:null),U.current=null,te(null)}finally{B(!1)}},[n,p,Fe,a,d,j,t,Le,O]),Ve=(0,X.useCallback)(async()=>{let e=R.current;if(e?.length)try{for(let t of e)await n.shareConnection(t.kind,t.id);I(null),P(null);let t=e.map(e=>e.name).join(`, `);r.offer({label:`Shared ${t} with this workspace`,restore:()=>void(async()=>{for(let t of e)try{await n.shareConnection(t.kind,t.id,!0)}catch{}})()})}catch(e){P(e instanceof Error?e.message:String(e))}},[n,r]),He=(0,X.useCallback)(async()=>{let e=U.current;if(e)try{te((await n.cancel(e)).run)}catch{}},[n]),Ue=(0,X.useCallback)(async()=>{try{let e=(await n.queue({limit:1})).runs[0];if(!e)return;let t=(e.results??[]).filter(e=>(e.scenarios??[]).some(e=>Object.values(e?.scores??{}).some(L().failedScore))).map(e=>e.name??`an item`);t.length&&await navigator.clipboard?.writeText(t.join(`
|
|
12
|
-
`))}catch{}},[n]),We=(0,X.useCallback)(async e=>{let r=Oe.current,i=De.current.id;ur(t,`pipeline`,i,r,`run`);let a=L().resolvePipeline(r,{profiles:d.resolve,grader:Le,groups:O(),files:[e],comment:p?.text??``}),o=await n.submit(a),s=o.run;for(;s.status===`queued`||s.status===`running`;)await new Promise(e=>setTimeout(e,500)),s=await n.run(o.run.id);return((s.results??[]).find(t=>t.name===e)?.scenarios??[]).map(e=>e.res??null)},[n,p,d,t,Le,O]),Ge=(0,X.useCallback)(e=>{J&&o(e,{dataset:J,files:j??[],run:We})},[o,j,We,J]),Ke=(0,X.useCallback)(()=>{let e=p?.text??``;m({text:``}),r.offer({label:`Cleared the comment`,restore:()=>m({text:e})})},[p,m,r]),qe=(0,X.useCallback)(()=>{let e=L().pipelineToYaml(Oe.current,{profiles:Y.current});Ya(new Blob([e],{type:`text/yaml`}),Ja(`pipeline`,Oe.current.name||`pipeline`,17,`yml`))},[]),Je=(0,X.useCallback)(async e=>{let t=Oe.current,r={};for(let e of L().evalsOf(t)){let t=L().casesRef(e)?.id??null;if(t&&!r[t]){let e=await n.dataset(t);r[t]={name:e.name,body:e.body}}}let i=L().exportBundle(t,{connections:Y.current,connectionProfiles:be.current,grader:Le,datasets:r});if(`error`in i)throw Error(i.error);Ya(await n.bundle({files:i.files,source:Fe,items:e}),Ja(`ci`,t.name||`pipeline`,17,`zip`))},[n,Fe,Le]),Xe=(0,X.useCallback)(async e=>{let t=await n.archivedRules().then(e=>e.rules,()=>({})),r=L().yamlToPipeline(e,{profiles:Y.current,connectionProfiles:be.current,profileType:e=>f.current.connection(e)?.type,connectionSplit:f.current.split,sources:g,groups:D,rulesFor:e=>t[e]??null});if(`error`in r){ne(r);return}let{doc:i,missing:a}=r,o={id:Zd(),name:i.name||`Imported`,work:i},s={...Ee.current,at:o.id,list:[...q,o]};Ee.current=s,c(s),fe(o.id),ne({doc:i,missing:a})},[n,q,c,g,D,fe]);if(!se||!le)return(0,$.jsx)(`div`,{className:`runs`,children:(0,$.jsx)(C,{label:`Pipelines`})});let Ze=e=>{let n=De.current.id;ur(t,`pipeline`,n,Oe.current,`restore`),Me(e.doc),V(!1)};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Qu,{list:q,at:ue,canRestore:ze.length>0,used:Object.fromEntries(q.map(e=>[e.id,h.pipeline?.[e.id]?.[0]?.at??null])),onSelect:e=>{c({...Ee.current,at:e}),fe(e)},onNew:()=>{let e=Yd(q.map(e=>e.name));if(c({...Ee.current,list:[...q,e],at:e.id}),fe(e.id),p?.text){let e=p.text;m({text:``}),r.offer({label:`Cleared the comment`,restore:()=>m({text:e})})}},onClone:()=>{let e={id:Zd(),name:`${se.name} copy`,work:structuredClone(le)};c({...Ee.current,list:[...q,e],at:e.id}),fe(e.id)},link:i({tab:`runs`,id:ue}),onCopyMove:()=>ae(!0),onRename:e=>{let t=e.trim(),n=Ee.current,r=De.current.id,i={...n,list:n.list.filter(e=>e.work?.version===17).map(e=>e.id===r?{...e,name:t,work:{...e.work,name:t}}:e)};Ee.current=i,c(i),je()},onDelete:()=>{let t=Ee.current,n=ue,i=q.filter(e=>e.id!==n),a=i.length?i:[Xd(l.list,d.split,Te(),we)],o=a.some(e=>e.id===t.at)?t.at:a[0].id;c({...Ee.current,list:a,at:o}),e&&Ir({tab:`runs`,id:null}),r.offer({label:`Deleted ${se.name||`the pipeline`}`,restore:()=>{Ee.current=t,c(t),fe(n)}})},onRestore:()=>V(!0),onExport:qe,onExportCi:()=>re(!0),onImport:()=>K.current?.click()}),(0,$.jsx)(nd,{problems:Re,error:N,run:H,submitting:z,onRun:()=>void Be(),onStop:()=>void He(),onOpen:()=>{H&&a(H.id,{at:H.submittedAt,from:`runs`})},...F?.length?{onShare:()=>void Ve()}:{}}),(0,$.jsxs)(`div`,{className:`runs`,children:[(0,$.jsx)(`input`,{ref:K,type:`file`,accept:`.yml,.yaml`,hidden:!0,"aria-hidden":`true`,onChange:e=>{let t=e.target.files?.[0];e.target.value=``,t&&t.text().then(Xe).catch(()=>ne({error:`the file could not be read`}))}}),(0,$.jsx)(Kd,{pipeline:le,edit:Me,comment:p?.text??``,setComment:e=>m({text:e}),onClear:Ke,onCopyFailures:()=>void Ue()}),(0,$.jsx)(Nd,{pipeline:le,connections:l.list,connectionProfiles:u.list,resolve:d.resolve,sources:g,targetCap:k,prompt:ye,...T?{defaultPrompt:T}:{},protectedTerms:ve,edit:Me,offer:r.offer}),(0,$.jsx)(Bd,{contentFiles:j,profiles:l.list,labGrader:Le,pipeline:le,edit:Me,offer:r.offer,children:(0,$.jsx)(Gd,{pipeline:le,sourceFiles:j,graded:he,openCaseEditor:Ge})}),ie&&se&&(0,$.jsx)(go,{subject:{kind:`pipeline`,id:se.id,name:se.name},scan:{pipelines:q,groups:v??[],prompts:(x??[]).map(e=>({id:e.id,name:vr(e)})),filterSets:w??[],sources:g},undo:r,onClose:()=>ae(!1),onChanged:()=>void t.refresh()}),(0,$.jsx)(Vt,{undo:r.undo,onUndo:r.undoNow,onDismiss:r.dismiss}),ee&&(0,$.jsx)(b,{title:`Restore pipeline`,onClose:()=>V(!1),children:(0,$.jsxs)(`div`,{className:`version-list`,children:[ze.length===0&&(0,$.jsx)(`p`,{className:`note`,children:`No versions of this pipeline yet.`}),ze.map((e,t)=>(0,$.jsxs)(`div`,{className:`version-row`,children:[(0,$.jsxs)(`span`,{className:`version-when`,children:[$d(e.at),`, `,Qd(e.reason)]}),(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>Ze(e),children:`Restore`})]},`${e.at}-${t}`))]})}),G&&(0,$.jsx)(td,{hasItems:Fe!==null,onExport:Je,onClose:()=>re(!1)}),W&&(`doc`in W?(0,$.jsx)(b,{title:`Imported ${W.doc.name||`Untitled`}`,onClose:()=>ne(null),children:W.missing.length>0?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{className:`note`,children:`A run is blocked until each of these exists here — create it, or pick a replacement in the Content, Connection and Profile rows:`}),(0,$.jsx)(`ul`,{className:`import-missing`,children:W.missing.map(e=>(0,$.jsx)(`li`,{children:e},e))})]}):(0,$.jsx)(`p`,{className:`note`,children:`Ready to run.`})}):(0,$.jsx)(b,{title:`Nothing imported`,onClose:()=>ne(null),children:(0,$.jsx)(`p`,{className:`note`,children:W.error})}))]})]})}var Yd=e=>{let t=Gt(e),n=L().blankPipeline({name:t});return{id:Zd(),name:t,work:{...n,jobs:n.jobs.map(e=>({...e,steps:[]}))}}},Xd=(e,t,n,r)=>({id:Zd(),name:Gt([]),work:Xe(ce(e,t),n,r)}),Zd=()=>`w${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`,Qd=e=>e===`run`?`before a run`:e===`restore`?`before a restore`:e===`pack`?`before a pack update`:`after editing`,$d=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},ef=e=>!!e.id&&qi(e.status),tf=e=>`Queued ${Ti(e.submittedAt)}`;async function nf(e,t){try{(await e.run(t)).status===`queued`&&await e.cancel(t)}catch{}}var rf=[``,`queued`,`running`,`done`,`cancelled`,`failed`,`incomplete`,`interrupted`],af=e=>e.numeric?`hnum num`:void 0,of=e=>[...new Map(e.map(e=>[e.id,e])).values()].sort((e,t)=>String(t.submittedAt).localeCompare(String(e.submittedAt))||(e.id<t.id?1:e.id>t.id?-1:0)),sf=e=>e&&{before:e.submittedAt,beforeId:e.id};function cf(){let e=Z(),t=Ye(),{openRun:n}=ci(),r=uo(),[i,a]=Q(`promptlab.history.columns`),[o,s]=(0,X.useState)([]),[c,l]=(0,X.useState)(!1),[u,f]=(0,X.useState)(``),[p,h]=(0,X.useState)(new Set),[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)(null),[x,S]=(0,X.useState)(null),[w,T]=(0,X.useState)(null),[D,O]=(0,X.useState)(null),[k,A]=(0,X.useState)(!1),[j,M]=(0,X.useState)(!1),[N,P]=(0,X.useState)(!1),[I,R]=(0,X.useState)(!1),[z,B]=(0,X.useState)(null),[ee,V]=(0,X.useState)(0),H=(0,X.useRef)(I);H.current=I;let[te,U]=(0,X.useState)(null),[W,ne]=(0,X.useState)(0),G=(0,X.useRef)(o);G.current=o;let re=(0,X.useMemo)(()=>o.map(e=>Oi(xa(e),e)),[o]),ie=(0,X.useMemo)(()=>df(i),[i]),ae=(0,X.useCallback)(async(t,n=!1)=>{try{return await e.queue({limit:25,...t,...n?{full:n}:{}})}catch{return null}},[e]),K=(0,X.useCallback)(e=>{let t=new Set(e.runs.map(e=>e.id));s(n=>of([...n.filter(e=>!t.has(e.id)),...e.runs])),l(e.more)},[]);(0,X.useEffect)(()=>{let e=!0,t,n=async()=>{let r=await ae();e&&(r?(K(r),R(!0),B(null)):H.current||B(`Runs not loaded: server unreachable.`),G.current.some(e=>[`queued`,`running`].includes(e.status))&&(t=setTimeout(()=>void n(),3e3)))};return n(),()=>{e=!1,t&&clearTimeout(t)}},[ae,K,ee,W]);let q=(0,X.useMemo)(()=>re.filter(e=>!u||(e.status||`done`)===u),[re,u]),oe=(e=>({Runs:Vi.filter(t=>e.Runs.has(t.key)),"Run Scenarios":Hi.filter(t=>e[`Run Scenarios`].has(t.key))}))(ie),se=(0,X.useCallback)(e=>{h(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),ce=(0,X.useCallback)((e,t)=>{n(e,{at:t,from:`history`})},[n]),le=(0,X.useCallback)(async t=>{try{let n=await e.resume(t),r={runs:[n.run],more:G.current.length>25};K(r),ce(t,n.run.submittedAt)}catch{}},[e,K,ce]),ue=(0,X.useCallback)(async n=>{O(null);try{let{run:r}=await e.rerunRun(n);K({runs:[r],more:G.current.length>25}),U(r.id),ne(e=>e+1),t.offer({label:tf(r),restore:()=>void nf(e,r.id).then(()=>ne(e=>e+1))})}catch(e){O(`Not re-run: ${e instanceof Error?e.message:`server unreachable`}.`)}},[e,K,t]),de=e=>{let t=e.run?G.current.find(t=>t.id===e.run):void 0,n=[];return zi(e)&&n.push({label:`Resume`,icon:Bt,onSelect:()=>void le(e.run)}),t&&ef(t)&&n.push({label:`Re-run`,icon:Wn,onSelect:()=>void ue(t.id)}),e.run&&n.push(r({tab:`results`,id:e.run})),n},pe=(0,X.useCallback)(async()=>{let n=G.current;P(!0);try{await e.clear()}catch{O(`Not cleared: server unreachable.`);return}finally{P(!1)}s([]),l(!1),t.offer({label:`Cleared ${Ei(n.length,`run`)}`,restore:()=>{for(let t of n)e.submit(L().upgradePipeline(t.snapshot)).catch(()=>{})}})},[e,t]),me=(0,X.useCallback)(async()=>{M(!0);let e=[],t=!1,n;for(let r=0;;r++){let i=await ae(n,!0);if(!i){t=!0;break}if(e=of([...e,...i.runs]),n=sf(i.runs.at(-1)),!i.more||!n||r>100)break}if(t){let t=new Set(e.map(e=>e.id));e=of([...e,...G.current.filter(e=>!t.has(e.id))])}if(M(!1),!e.length){O(`Nothing to export yet.`);return}Ya(new Blob([JSON.stringify({exported:new Date().toISOString(),runs:e},null,2)],{type:`application/json`}),Ja(`runs`,`all`,17,`json`)),O(t?`Exported ${Ei(e.length,`run`)}. Server unreachable, so only those this browser had.`:`Exported ${Ei(e.length,`run`)}.`)},[e,ae]),he=[{label:`Select Columns`,icon:Tn,onSelect:()=>_(!0)},{label:`Export JSON`,icon:fe,busy:j,onSelect:()=>void me()},{label:`Clear`,icon:Kt,destructive:!0,busy:N,disabled:!I,onSelect:()=>void pe()}],ge=(0,X.useCallback)(e=>{let t=e.target.closest(`[data-openrun]`);if(t){e.stopPropagation();let n=t.closest(`tr[data-run]`),r=n?q[Number(n.getAttribute(`data-run`))]:null;r?.run&&ce(r.run,r.at);return}let n=e.target.closest(`[data-editcomment]`);if(n){e.stopPropagation();let t=n.closest(`tr[data-run]`),r=t?q[Number(t.getAttribute(`data-run`))]:null;r?.run&&S({id:r.run,comment:r.comment});return}let r=e.target.closest(`[data-scenario]`);if(r){e.stopPropagation();let t=r.closest(`tr[data-scen]`)?.previousElementSibling,n=t?q[Number(t.getAttribute(`data-run`))]:null,i=n?.run?G.current.find(e=>e.id===n.run):null;i?.snapshot&&T({run:i.snapshot,i:Number(r.getAttribute(`data-scenario`))});return}let i=e.target.closest(`[data-prof]`);if(i){e.stopPropagation();let t=i.closest(`tr[data-scen]`)?.previousElementSibling,n=t?q[Number(t.getAttribute(`data-run`))]:null,r=i.getAttribute(`data-prof`);if(n&&r!=null){let e=n.scenarios[Number(r)];e&&y({name:Ri(e),connection:e.connection,settings:{...e.setupProfile?.settings||{}},images:wi(n)===!0})}}},[q,ce]),_e=(0,X.useCallback)((e,t)=>{s(n=>n.map(n=>n.id===e?{...n,snapshot:{...n.snapshot,comment:t}}:n)),S(null)},[]),ve=(e,t)=>e.image&&wi(t)!==!0?(0,$.jsx)(`span`,{className:`note`,children:`—`}):e.get(t),ye=(e,t,n,r)=>n?e.image&&wi(t)!==!0?(0,$.jsx)(`span`,{className:`note`,children:`—`}):e.get(t,n,r):`—`;return(0,$.jsxs)(`div`,{className:`history`,children:[(0,$.jsxs)(E,{id:`history`,title:`History`,actions:he,children:[!I&&(0,$.jsx)(C,{label:`Runs`,error:z,onRetry:()=>{B(null),V(e=>e+1)}}),I&&(re.length>0||u)&&(0,$.jsx)(d,{noun:`runs`,lead:q.length>0&&(0,$.jsx)(`p`,{className:`note hstatus`,role:`status`,children:Ei(q.length,`run`)}),filters:[{key:`show`,label:`Show`,value:u,onChange:f,options:rf.map(e=>({value:e,label:e?ji(e):`All`}))}]}),D&&(0,$.jsx)(`p`,{className:`note hstatus`,role:`status`,children:D}),I?q.length?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`scrollx`,onClick:ge,children:(0,$.jsx)(J,{className:`htable`,label:`Runs`,defaultSort:null,rows:q,rowKey:e=>e.at,rowProps:(e,t)=>({className:`runrow${p.has(e.at)?` open`:``}${e.run&&e.run===te?` fresh`:``}`,"data-run":t}),columns:[{key:`expand`,header:(0,$.jsx)(`span`,{className:`hvh`,children:`Targets`}),label:``,className:`hexpand`,sort:null,cell:(e,t)=>{let n=p.has(e.at);return(0,$.jsx)(`button`,{type:`button`,className:`icon-btn`,"aria-label":n?`Collapse`:`Expand`,"aria-expanded":n,"aria-controls":n?`hscen-${t}`:void 0,onClick:()=>se(e.at),children:(0,$.jsx)(lt,{size:16,"aria-hidden":`true`})})}},...oe.Runs.map(e=>({key:e.key,header:e.label,className:af(e),sort:e.sort??(t=>m(e.get(t))),cell:t=>(0,$.jsx)(`span`,{className:`hval`,children:ve(e,t)})})),{key:`actions`,header:(0,$.jsx)(`span`,{className:`hvh`,children:`Actions`}),label:``,className:`hactions`,sort:null,cell:e=>{let t=de(e);return t.length?(0,$.jsx)(Y,{actions:t,label:`${Ti(e.at)} actions`}):null}}],after:(e,t)=>p.has(e.at)&&(0,$.jsx)(`tr`,{className:`scenrows`,id:`hscen-${t}`,"data-run":t,"data-scen":e.at,children:(0,$.jsx)(`td`,{colSpan:oe.Runs.length+2,children:(0,$.jsx)(J,{className:`scen-table`,label:`Targets`,defaultSort:null,rows:((e.scenarios||[]).length?e.scenarios:[null]).map((e,t)=>({sc:e,n:t})),rowKey:({sc:e,n:t})=>e?.id??String(t),columns:oe[`Run Scenarios`].map(t=>({key:t.key,header:t.label,className:af(t),sort:({sc:n,n:r})=>{if(!n)return null;if(t.sort)return t.sort(n,r);let i=t.get(e,n,r);return m(i)},cell:({sc:n,n:r})=>(0,$.jsx)(`span`,{className:`hval`,children:ye(t,e,n,r)})}))})})})})}),c&&(0,$.jsxs)(`button`,{type:`button`,className:`ghost older-btn`,disabled:k,"aria-busy":k||void 0,onClick:async()=>{A(!0);let e=await ae(sf(G.current.at(-1)));if(A(!1),!e){O(`Server unreachable.`);return}K(e)},children:[k&&(0,$.jsx)(F,{}),`Older`]})]}):(0,$.jsx)(`p`,{className:`note`,children:D??(re.length?`No runs match this filter.`:(0,$.jsxs)($.Fragment,{children:[`No runs yet. `,(0,$.jsx)(`a`,{href:`#/runs`,children:`Start one in Runs`})]}))}):null]}),(0,$.jsx)(Vt,{undo:t.undo,onUndo:t.undoNow,onDismiss:t.dismiss}),g&&(0,$.jsx)(pf,{cols:ie,onSave:e=>{a(ff(e)),_(!1)},onClose:()=>_(!1)}),w&&(0,$.jsx)(It,{run:w.run,i:w.i,onClose:()=>T(null)}),v&&(0,$.jsx)(b,{title:v.name||`Settings`,onClose:()=>y(null),children:(0,$.jsx)(lf,{connection:v.connection,settings:v.settings,images:v.images})}),x&&(0,$.jsx)(uf,{runId:x.id,comment:x.comment,onSaved:e=>_e(x.id,e),onClose:()=>S(null)})]})}function lf({connection:e,settings:t,images:n}){let r=e=>e.filter(e=>String(t[e]??``)!==``).map(e=>({key:e,label:xi(e),control:{type:`static`,text:Si(e,t[e])}})),i=[...e?[{key:`connection`,label:`Connection`,control:{type:`static`,text:e}}]:[],...r(_i)],o=n?r(vi):[],s=r(gi.filter(e=>!_i.includes(e)&&!vi.includes(e)));return!i.length&&!s.length&&!o.length?(0,$.jsx)(`p`,{className:`note`,children:`No settings recorded.`}):(0,$.jsxs)(re,{children:[i.length>0&&(0,$.jsx)(a,{label:e?`Connection`:`Target profile`,rows:i}),s.length>0&&(0,$.jsx)(E,{id:`profile-settings`,title:`Settings`,level:3,children:(0,$.jsx)(a,{label:`Settings`,rows:s})}),o.length>0&&(0,$.jsx)(E,{id:`profile-vision`,title:`Vision Capabilities`,level:3,children:(0,$.jsx)(a,{label:`Vision Capabilities`,rows:o})})]})}function uf({runId:e,comment:t,onSaved:n,onClose:r}){let i=Z(),[a,o]=(0,X.useState)(t),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(!1);return(0,$.jsx)(ut,{title:`Run comment`,...s?{status:s,statusBad:!0}:{},sections:[{key:`comment`,rows:[{key:`comment`,label:`Comment`,control:{type:`text`,value:a,onChange:o,placeholder:`optional`}}]}],actions:[{label:`Save & Close`,icon:B,busy:l,primary:!0,onSelect:async()=>{u(!0),c(null);try{await i.setComment(e,a),n(a)}catch{c(`Not saved: the server is unreachable.`),u(!1)}}}],focusRow:`comment`,dirty:a!==t,onClose:r})}function df(e){let t=()=>({Runs:new Set(Vi.filter(e=>e.on).map(e=>e.key)),"Run Scenarios":new Set(Hi.filter(e=>e.on).map(e=>e.key))});if(!e)return t();let n=t();for(let t of Ki){let r=t[0],i=e[r],a=new Set(t[1].map(e=>e.key)),o=e=>Wi[e]??e,s=new Set(i?.seen?.map(o)??[...a]),c=(i?.on??[]).map(o);for(let[e,t]of Object.entries(Gi))a.has(e)&&!s.has(e)&&s.has(t)&&(s.add(e),c.includes(t)&&c.push(e));let l=[...c.filter(e=>a.has(e)),...t[1].filter(e=>e.on&&!s.has(e.key)).map(e=>e.key)];l.length&&(n[r]=new Set(l))}return n}function ff(e){return{Runs:{on:[...e.Runs],seen:Vi.map(e=>e.key)},"Run Scenarios":{on:[...e[`Run Scenarios`]],seen:Hi.map(e=>e.key)}}}function pf({cols:e,onSave:t,onClose:n}){let[r,i]=(0,X.useState)(()=>({Runs:new Set(e.Runs),"Run Scenarios":new Set(e[`Run Scenarios`])})),[a,o]=(0,X.useState)(null),s=(e,t)=>e.size===t.size&&[...e].every(e=>t.has(e)),c=!s(r.Runs,e.Runs)||!s(r[`Run Scenarios`],e[`Run Scenarios`]);return(0,$.jsx)(b,{title:`Select Columns`,onClose:n,dirty:c,children:(0,$.jsxs)(`div`,{className:`hcols`,children:[Ki.map(([e,t])=>(0,$.jsxs)(`div`,{className:`groups`,children:[(0,$.jsx)(`h3`,{children:Ui[e]??e}),t.map(t=>(0,$.jsxs)(`label`,{children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:r[e].has(t.key),onChange:n=>{let a=new Set(r[e]);n.target.checked?a.add(t.key):a.delete(t.key),i({...r,[e]:a}),o(null)}}),` `,t.label]},t.key))]},e)),a&&(0,$.jsx)(`p`,{className:`note bad`,children:a}),(0,$.jsxs)(`div`,{className:`hcols-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:n,children:`Cancel`}),(0,$.jsx)(`button`,{type:`button`,className:`run`,onClick:()=>{if(!r.Runs.size){o(`the Runs group needs at least one column`);return}t(r)},children:`Save & Close`})]})]})})}var mf=e=>!!e&&e.startsWith(`•held:`),hf={"promptlab.workflows":{list:[],at:``},"promptlab.connections":{list:[],at:``},"promptlab.connectionProfiles":{list:[]},"promptlab.comment":null,"promptlab.versions":gf(),"promptlab.history.columns":null,"promptlab.wizard":null,"promptlab.tokens":null};function gf(){return{pipeline:{},profile:{},dataset:{}}}var _f=[`promptlab.workflows`,`promptlab.connections`,`promptlab.connectionProfiles`,`promptlab.versions`,`promptlab.tokens`],vf=[`px`,`format`,`quality`],yf=[{value:`200704`,label:`448 square`},{value:`edge448`,label:`448 edge`},{value:`409920`,label:`480p`},{value:`518400`,label:`540p`},{value:`921600`,label:`720p`},{value:`1440000`,label:`900p`},{value:`2073600`,label:`1080p`},{value:`3686400`,label:`1440p`}],bf={"image/jpeg":`JPEG`,"image/webp":`WebP`,"image/png":`PNG`},xf=e=>bf[e]??e.replace(`image/`,``).toUpperCase(),Sf={px:`921600`,quality:`0.92`};function Cf(e,t,{inherit:n=!1}={}){let r=L().connectionImage({}).format,i=String(e.px??``),a=String(e.format??``),o=String(e.quality??``),s=yf.some(e=>e.value===i)||!i?yf:[...yf,{value:i,label:L().budgetLabel(i)}],c={value:``,label:`(inherit)`},l=n?[c,...s]:s.map(e=>e.value===Sf.px?{value:``,label:e.label}:e),u=n?[c,...L().IMAGE_FORMATS.map(e=>({value:e,label:xf(e)}))]:L().IMAGE_FORMATS.map(e=>e===r?{value:``,label:xf(e)}:{value:e,label:xf(e)}),d=(a||r)===`image/png`,f=n?`(inherit)`:Sf.quality,p={type:`text`,value:o,onChange:t(`quality`),...d||o?{}:{placeholder:f}};return[{key:`px`,label:`Resolution`,control:{type:`select`,value:!n&&i===Sf.px?``:i,options:l,onChange:t(`px`)}},{key:`format`,label:`Format`,control:{type:`select`,value:!n&&a===r?``:a,options:u,onChange:t(`format`)}},{key:`quality`,label:n?`Image quality`:`Quality`,width:`quarter`,...d?{hint:`Unused for PNG`}:{},control:p}]}function wf(e,t){return e===`px`?yf.find(e=>e.value===t)?.label??L().budgetLabel(t):e===`format`?xf(t):t}function Tf(e){let{px:t,format:n,quality:r}=L().connectionImage(e),i=n===`image/png`?``:` q${r??Sf.quality}`;return`${L().budgetLabel(t??Number(Sf.px))}, ${xf(n)}${i}`}var Ef=e=>({kind:`pipeline`,id:e.id,name:e.name||`Untitled pipeline`}),Df=e=>({kind:`group`,id:e.id,name:e.name||`Untitled eval group`});function Of(e,t,n,r){let i=new Set(r.filter(t=>t.connection?.id===e).map(e=>e.id)),a=[];for(let n of t)(L().profileIds(n.work).includes(e)||L().answerKeys(n.work).some(e=>{let t=L().answerOfKey(e);return!!t.profile&&i.has(t.profile)}))&&a.push(Ef(n));for(let t of n)t.grader?.id===e&&a.push(Df(t));return a}function kf(e,t,n){let r=[];for(let n of t)L().answerKeys(n.work).some(t=>{let n=L().answerOfKey(t);return n.bare?!!e.fromProfile&&n.connection===e.fromProfile:n.profile===e.id})&&r.push(Ef(n));if(e.fromProfile)for(let t of n)t.grader?.id===e.fromProfile&&r.push(Df(t));return r}function Af(e){if(!e.length)return`Not used`;let t=(t,n)=>{let r=e.filter(e=>e.kind===t);return r.length===0?null:r.length===1?r[0].name:`${r.length} ${n}`};return[t(`pipeline`,`pipelines`),t(`group`,`eval groups`)].filter(Boolean).join(`, `)}function jf({uses:e}){return e.length?(0,$.jsx)(`span`,{className:`setup-used`,children:Af(e)}):(0,$.jsx)(`span`,{className:`setup-unset`,children:`Not used`})}function Mf({uses:e}){return(0,$.jsxs)(`div`,{className:`setup-usedby`,children:[(0,$.jsx)(`span`,{className:`setup-usedby-label`,children:`Used by`}),e.length===0?(0,$.jsx)(`span`,{className:`setup-unset`,children:`Not used`}):(0,$.jsx)(`ul`,{className:`setup-usedby-list`,children:e.map(e=>(0,$.jsxs)(`li`,{children:[(0,$.jsx)(`a`,{href:Pr(e.kind===`group`?{tab:`library`,section:`datasets`,id:e.id}:{tab:`runs`,id:e.id}),children:e.name}),(0,$.jsx)(`span`,{className:`setup-usedby-kind`,children:e.kind===`group`?`eval group`:`pipeline`})]},`${e.kind}-${e.id}`))})]})}var Nf={tab:`setup`,section:`connections`,id:null},Pf=e=>({tab:`setup`,section:`connections`,id:e,kind:`profile`}),Ff=()=>{let e=Lr();e.tab===`setup`&&e.id&&Fr(Nf)},If=[`id`,`name`,`connection`,`fromProfile`];function Lf({profileId:e,connections:t,workflows:n,groups:r,presets:i,offer:a}){let o=uo(),[s,c]=Q(`promptlab.connectionProfiles`),l=(0,X.useRef)(s);l.current=s;let[u,d]=(0,X.useState)(null),f=(0,X.useRef)(u);f.current=u;let[p,m]=(0,X.useState)(void 0),h=(0,X.useCallback)(e=>{let t={...l.current,list:e};l.current=t,c(t)},[c]),g=(0,X.useCallback)((e,t)=>{let n=l.current.list.find(t=>t.id===e);n&&(d({p:structuredClone(n),was:n,start:n}),m(t))},[]),_=(0,X.useCallback)((e,t)=>{g(e,t),Fr(Pf(e))},[g]),v=(0,X.useCallback)(()=>{d(null),m(void 0)},[]),y=(0,X.useCallback)(()=>{v(),Ff()},[v]);(0,X.useEffect)(()=>{if(!e){f.current?.was&&v();return}f.current?.p.id!==e&&(l.current.list.some(t=>t.id===e)?g(e):Ir(Nf))},[e,g,v]);let b=(0,X.useCallback)(()=>{let e={id:Kf(),name:`New profile`};d({p:e,was:null,start:e}),m(`name`)},[]),x=(0,X.useCallback)(e=>{let t=f.current;if(!t)return;let n={...t,p:e};f.current=n,d(n)},[]),S=(0,X.useCallback)(()=>{let e=f.current;if(!e)return;let t=Gf(e.p),n=l.current.list;h(e.was?n.map(e=>e.id===t.id?t:e):[...n,t]),v(),Ff()},[h,v]),C=(0,X.useCallback)(e=>{let t=l.current.list.find(t=>t.id===e);if(!t)return;let{fromProfile:n,...r}=structuredClone(t);h([...l.current.list,{...r,id:Kf(),name:`${t.name||`Profile`} copy`}])},[h]),w=(0,X.useCallback)(e=>{let t=l.current.list,n=t.find(t=>t.id===e);n&&(h(t.filter(t=>t.id!==e)),v(),Ff(),a({label:`Deleted ${n.name||`the profile`}`,restore:()=>h(t)}))},[h,v,a]),T=(0,X.useMemo)(()=>{let e=new Map;for(let t of s.list)e.set(t.id,kf(t,n,r));return e},[s.list,n,r]),D=e=>e.name||`Unnamed profile`,O=e=>[{label:`Edit…`,icon:M.edit,onSelect:()=>_(e.id)},{label:`Rename…`,icon:M.rename,onSelect:()=>_(e.id,`name`)},{label:`Clone`,icon:M.clone,onSelect:()=>C(e.id)},o(Pf(e.id)),{label:`Remove`,icon:M.remove,destructive:!0,onSelect:()=>w(e.id)}],k=[{key:`name`,header:`Profile`,role:`title`,sort:D,cell:e=>(0,$.jsx)(`button`,{type:`button`,className:`setup-open`,onClick:()=>_(e.id),children:D(e)})},{key:`sets`,header:`Sets`,label:``,sort:e=>Wf(e,t),cell:e=>(0,$.jsx)(`span`,{className:`setup-sets`,children:Wf(e,t)})},{key:`used`,header:`Used by`,label:``,sort:e=>Af(T.get(e.id)??[]),cell:e=>(0,$.jsx)(jf,{uses:T.get(e.id)??[]})},{key:`menu`,header:``,label:``,className:`setup-menu`,role:`menu`,sort:null,cell:e=>(0,$.jsx)(Y,{actions:O(e),label:`${D(e)} actions`})}],A=u;return(0,$.jsxs)(E,{id:`setup-connection-profiles`,title:`Connection Profiles`,children:[(0,$.jsx)(`div`,{className:`setup-intro`,children:(0,$.jsx)(`p`,{className:`note`,children:`Optional settings a target can carry — model, image, or a connection override. Empty settings inherit the lab default.`})}),(0,$.jsx)(J,{className:`setup-table`,cards:!0,label:`Connection Profiles`,rows:s.list,rowKey:e=>e.id,rowProps:e=>({className:`setup-row`,onClick:t=>{t.target.closest(`button, a, .menu`)||_(e.id)}}),pinned:(0,$.jsxs)(`tr`,{className:`setup-row setup-default`,"data-default":``,children:[(0,$.jsx)(`td`,{className:`dt-title`,children:(0,$.jsx)(`span`,{className:`setup-unset`,children:`(Default)`})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(`span`,{className:`setup-unset`,children:`Nothing — the connection runs on the lab's defaults`})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(`span`,{className:`setup-unset`,children:`—`})}),(0,$.jsx)(`td`,{className:`setup-menu`})]}),columns:k}),(0,$.jsxs)(`button`,{type:`button`,className:`ghost add-btn`,onClick:b,children:[(0,$.jsx)(ze,{size:14,"aria-hidden":`true`}),`Add profile`]}),A&&(0,$.jsx)(Rf,{profile:A.p,connections:t,presets:i,uses:T.get(A.p.id)??[],...p?{focus:p}:{},dirty:JSON.stringify(A.p)!==JSON.stringify(A.start),...A.was?{link:o(Pf(A.p.id))}:{},onEdit:x,onSave:S,onClose:y})]})}function Rf({profile:e,connections:t,presets:n,uses:r,focus:i,dirty:a,link:o,onEdit:s,onSave:c,onClose:l}){let u=zf(e,t),d=t=>n=>{let r={...e};for(let e of t)r[e]=n;s(r)},f=e=>d([e]),p=e.connection??null,m=[{id:``,label:`(inherit — the target's)`,fixed:!0},...t.map(e=>({id:e.id,label:e.name||`Unnamed connection`})),...p&&!t.some(e=>e.id===p.id)?[{id:p.id,label:`${p.name||p.id} (missing)`}]:[]],h=[{key:`name`,label:`Name`,width:`full`,required:!0,control:{type:`text`,value:e.name,onChange:f(`name`)}},{key:`connection`,label:`Connection`,hint:`Override the AI connection the target picked, or leave it to answer on the target's.`,control:{type:`picker`,kind:`Connection`,value:p?.id??``,options:m,placeholder:`(inherit — the target's)`,onChange:n=>{let r=t.find(e=>e.id===n),{connection:i,...a}=e;s(r?{...a,connection:{id:r.id,name:r.name}}:a)}}}],g=Vf(e,u).map(t=>Uf(e,t,d(t.keys))),_=u?L().CONNECTION_TYPES[u.type]:void 0,v=!_||(_.answers??[`prompt`]).includes(`prompt`)&&!_.local,y=[{key:`identity`,rows:h},...g.length?[{key:`model`,title:`Model settings`,rows:g}]:[],...v?[{key:`image`,title:`Image settings`,rows:Cf(e,f,{inherit:!0})}]:[],{key:`use`,title:`Use`,rows:[],children:(0,$.jsx)(Mf,{uses:r})}],b=u?n.filter(e=>(e.type??`llama.cpp`)===u.type):[],x=t=>{let n={...e};for(let e of _?.settings??[])e.key!==`temperature`&&e.scope!==`connection`&&delete n[e.key];s({...n,...t.opts})},S=[...o?[o]:[],...b.map(e=>({label:`Apply preset: ${e.label}`,icon:M.preset,onSelect:()=>x(e)}))];return(0,$.jsx)(ut,{title:e.name||`Unnamed profile`,...i?{focusRow:i}:{},sections:y,...S.length?{menu:S}:{},dirty:a,onSave:c,onClose:l})}function zf(e,t){let n=e.connection?.id??e.fromProfile;return n&&t.find(e=>e.id===n)||null}function Bf(){let e=Object.values(L().CONNECTION_TYPES).filter(e=>e.picker!==!1&&!e.local&&(e.answers??[`prompt`]).includes(`prompt`)),t=new Map;for(let n of e)for(let e of n.settings){if(e.scope===`connection`)continue;let n=t.get(e.label)??{label:e.label,keys:[],setting:e,n:0};n.keys.includes(e.key)||n.keys.push(e.key),n.n+=1,t.set(e.label,n)}return[...t.values()].filter(t=>t.n*2>e.length).sort((e,t)=>t.n-e.n).map(({n:e,...t})=>t)}function Vf(e,t){let n;if(t){let r=L().mergeAnswer(t,e);n=(L().CONNECTION_TYPES[t.type]?.settings??[]).filter(e=>e.scope!==`connection`&&(!e.appliesTo||e.appliesTo(r))).map(e=>({label:e.label,keys:[e.key],setting:e}))}else n=Bf();let r=new Set(n.flatMap(e=>e.keys));for(let[t,i]of Object.entries(e)){if(If.includes(t)||vf.includes(t)||r.has(t)||i==null||i===``)continue;let e=Hf(t);n.push({label:e?.label??t,keys:[t],setting:e??{key:t,label:t,control:`text`,default:``,hint:``}})}return n}function Hf(e){for(let t of Object.values(L().CONNECTION_TYPES)){let n=t.settings.find(t=>t.key===e);if(n)return n}}function Uf(e,t,n){let r=String(t.keys.map(t=>e[t]).find(e=>e!=null&&e!==``)??``),i=t.setting;return i.control===`select`&&i.choices?{key:t.keys[0],label:t.label,control:{type:`select`,value:r,onChange:n,options:[{value:``,label:`(inherit)`},...i.choices.filter(e=>e.value!==``)]}}:i.key===`grammar`?{key:t.keys[0],label:t.label,control:{type:`textarea`,value:r,onChange:n}}:{key:t.keys[0],label:t.label,width:`quarter`,control:{type:`text`,value:r,onChange:n,...r?{}:{placeholder:`(inherit)`}}}}function Wf(e,t){let n=[];if(e.connection?.id){let r=t.find(t=>t.id===e.connection.id);n.push(`Connection → ${r?r.name||`Unnamed connection`:`${e.connection.name||e.connection.id} (missing)`}`)}let r=zf(e,t),i=new Set;for(let t of Vf(e,r)){let r=t.keys.map(t=>e[t]).find(e=>e!=null&&e!==``);r==null||i.has(t.label)||(i.add(t.label),n.push(`${t.label} ${String(r)}`))}let a={px:`Resolution`,format:`Format`,quality:`Image quality`};for(let t of vf){let r=e[t];r!=null&&r!==``&&n.push(`${a[t]} ${wf(t,String(r))}`)}return n.join(`, `)||`Nothing`}function Gf(e){let t={id:e.id,name:e.name};for(let[n,r]of Object.entries(e))n!==`id`&&n!==`name`&&r!=null&&r!==``&&(t[n]=r);return t}var Kf=()=>`cp${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`;function qf(e){return!e||e.length===0||e.includes(`*all`)?``:[...e].sort().join(`,`)}function Jf(e){let[t,n]=(0,X.useState)({});return(0,X.useEffect)(()=>{let t=!0;return e.connectionShares().then(e=>{t&&n(e.shares)}).catch(()=>{}),()=>{t=!1}},[e]),{sharesFor:(0,X.useCallback)((e,n)=>t[hn(e,n)],[t]),setFor:(0,X.useCallback)((t,r,i)=>{e.setConnectionShares(t,r,i).then(e=>n(e.shares)).catch(()=>{})},[e]),setForEach:(0,X.useCallback)(async(t,r)=>{let i=null;for(let{id:n,workspaces:a}of r)try{i=(await e.setConnectionShares(t,n,a)).shares}catch{}i&&n(i)},[e])}}function Yf({offer:e}){let t=Z(),n=Zn(),r=hr(),i=Tr(),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(!1),p=(0,X.useRef)(null),m=e=>c({text:e instanceof Error?e.message:String(e),bad:!0}),h=(0,X.useCallback)(()=>{u(null),t.packs().then(e=>o(e.packs),e=>u(e instanceof Error?e.message:String(e)))},[t]);(0,X.useEffect)(h,[h]);let g=async()=>{await Promise.all([n.refresh(),r.refresh(),i.refresh()]),h()},_=async e=>{c({text:`Installing ${e.name}…`,bad:!1}),f(!0);try{let n=await t.installPack(e);await g();let r=(await t.packs()).packs.find(e=>e.id===n.pack),i=r?`${r.name} ${r.version}`:n.pack;c({text:n.installed?`Installed ${i}.`:`${i} is up to date.`,bad:!1})}catch(e){m(e)}finally{f(!1)}},v=async n=>{let r=[];try{for(let e of n)r.push((await t.removePack(e.id)).trash)}catch(e){m(e)}r.length&&(await g(),e({label:n.length===1?`Removed ${n[0].name}`:`Removed ${r.length} packs`,restore:()=>{(async()=>{for(let e of r)await t.restorePack(e);await g()})()}}))};return(0,$.jsxs)(E,{id:`setup-packs`,title:`Packs`,note:a?Xf(a.length,`pack`):``,actions:[{label:`Install pack…`,icon:K,busy:d,onSelect:()=>p.current?.click()}],children:[a===null&&(0,$.jsx)(C,{label:`Packs`,error:l,onRetry:h}),a&&!a.length&&(0,$.jsx)(`p`,{className:`note`,children:`No packs installed.`}),a&&a.length>0&&(0,$.jsx)(J,{className:`setup-table`,cards:!0,label:`Packs`,rows:a,rowKey:e=>e.id,select:{noun:`pack`,actions:e=>[{label:`Remove`,icon:M.remove,destructive:!0,onSelect:()=>void v(e)}]},columns:[{key:`name`,header:`Pack`,role:`title`,cell:e=>e.name},{key:`version`,header:`Version`,cell:e=>e.version},{key:`made`,header:`Made`,sort:e=>e.datasets.length+e.pipelines.length+e.sources.length+e.presets,cell:e=>Zf(e)},{key:`menu`,header:``,className:`ds-menu`,role:`menu`,sort:null,cell:e=>(0,$.jsx)(Y,{label:`${e.name} actions`,actions:[{label:`Remove`,icon:M.remove,destructive:!0,onSelect:()=>void v([e])}]})}]}),s&&(0,$.jsx)(`p`,{className:`note${s.bad?` bad`:``}`,role:s.bad?`alert`:`status`,children:s.text}),(0,$.jsx)(`input`,{ref:p,type:`file`,accept:`.labpack,.zip,application/zip`,hidden:!0,"aria-label":`Install pack file`,onChange:e=>{let t=e.target.files?.[0];e.target.value=``,t&&_(t)}})]})}var Xf=(e,t)=>`${e} ${t}${e===1?``:`s`}`,Zf=e=>[Xf(e.datasets.length,`dataset`),Xf(e.pipelines.length,`pipeline`),Xf(e.sources.length,`source`),Xf(e.presets,`preset`)].join(`, `);function Qf({offer:e}){let t=Z(),[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(!1),u=(0,X.useRef)(null),d=(0,X.useCallback)(()=>{s(null),t.plugins().then(e=>r(e.plugins),e=>s(e instanceof Error?e.message:String(e)))},[t]);(0,X.useEffect)(d,[d]);let f=async e=>{a(null),l(!0);try{let n=await t.installPlugin(e),i=(await t.plugins()).plugins;r(i);let o=i.find(e=>e.id===n.plugin);o&&n.installed&&await fn(o),a({text:n.installed?ln[n.plugin]?`Installed ${n.plugin}, and it did not load: ${ln[n.plugin]}`:`Installed ${n.plugin}.`:`${n.plugin} is up to date.`,bad:!!ln[n.plugin]})}catch(e){a({text:e instanceof Error?e.message:String(e),bad:!0})}finally{l(!1)}},p=async n=>{let r=[];try{for(let e of n)r.push((await t.removePlugin(e.id)).trash)}catch(e){a({text:e instanceof Error?e.message:String(e),bad:!0})}d(),r.length&&e({label:n.length===1?`Removed ${n[0].id}`:`Removed ${r.length} plugins`,restore:()=>{Promise.all(r.map(e=>t.restorePlugin(e))).then(d)}})};return(0,$.jsxs)(E,{id:`setup-plugins`,title:`Plugins`,note:n?`${n.length} ${n.length===1?`plugin`:`plugins`}`:``,actions:[{label:`Install plugin…`,icon:K,busy:c,onSelect:()=>u.current?.click()}],children:[n===null&&(0,$.jsx)(C,{label:`Plugins`,error:o,onRetry:d}),n&&!n.length&&(0,$.jsx)(`p`,{className:`note`,children:`No plugins installed.`}),n&&n.length>0&&(0,$.jsx)(J,{className:`setup-table`,cards:!0,label:`Plugins`,rows:n,rowKey:e=>e.id,select:{noun:`plugin`,actions:e=>[{label:`Remove`,icon:M.remove,destructive:!0,onSelect:()=>void p(e)}]},columns:[{key:`id`,header:`Plugin`,role:`title`,cell:e=>e.id},{key:`version`,header:`Version`,cell:e=>e.version},{key:`sha`,header:`SHA-256`,sort:e=>e.sha256,cell:e=>(0,$.jsx)(`code`,{title:e.sha256,children:e.sha256.slice(0,12)})},{key:`registers`,header:`Registers`,sort:e=>$f(e),cell:e=>$f(e)||`—`},{key:`state`,header:`State`,cell:e=>ep(e)},{key:`menu`,header:``,className:`ds-menu`,role:`menu`,sort:null,cell:e=>(0,$.jsx)(Y,{label:`${e.id} actions`,actions:[{label:`Remove`,icon:M.remove,destructive:!0,onSelect:()=>void p([e])}]})}]}),i&&(0,$.jsx)(`p`,{className:`note${i.bad?` bad`:``}`,role:i.bad?`alert`:`status`,children:i.text}),(0,$.jsx)(`input`,{ref:u,type:`file`,accept:`.labplugin,.zip,application/zip`,hidden:!0,"aria-label":`Install plugin file`,onChange:e=>{let t=e.target.files?.[0];e.target.value=``,t&&f(t)}})]})}var $f=e=>[...e.registers.outputKinds??[],...e.registers.modifiers??[],...e.registers.evalTypes??[],...(e.registers.connectionTypes??[]).map(e=>e.id)].join(`, `),ep=e=>ln[e.id]?`Failed: ${ln[e.id]}`:un.has(e.id)?`Loaded`:`Not Loaded`,tp={env:`Deployment`,lab:`Own`,default:`Default`};function np({cfg:e,editable:t,onClose:n}){let r=Z(),i=e?.from===`lab`?e:null,[a,o]=(0,X.useState)(i?.clientId??``),[s,c]=(0,X.useState)(i?.tenant??``),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(!1),p=a!==(i?.clientId??``)||s!==(i?.tenant??``),m=async()=>{if(!p){n();return}f(!0);try{await r.setMicrosoft(a,s),tl(),n()}catch(e){u(e instanceof Error?e.message:String(e)),f(!1)}},h=e=>t=>{u(null),e(t)},g=!t,_=new URL(`/`,Yc()??window.location.href).href,v=Hc(g?e?.tenant??``:s||`organizations`),y=[g?{key:`client`,label:`Client ID`,control:{type:`code`,text:e?.clientId??`—`}}:{key:`client`,label:`Client ID`,control:{type:`text`,value:a,onChange:h(o),placeholder:e?.from==="default"?e.clientId:`00000000-0000-0000-0000-000000000000`}},g?{key:`tenant`,label:`Tenant`,control:{type:`code`,text:e?.tenant??`—`}}:{key:`tenant`,label:`Tenant`,control:{type:`text`,value:s,onChange:h(c),placeholder:`00000000-0000-0000-0000-000000000000`}},{key:`signin`,label:`Sign-in`,control:{type:`static`,text:v}},{key:`redirect`,label:`Redirect URI`,control:{type:`code`,text:_}},{key:`app`,label:`App`,control:{type:`static`,text:e?.from?tp[e.from]:`None`}}];return(0,$.jsx)(ut,{title:`Microsoft 365`,status:l??void 0,statusBad:!!l,focusRow:g?void 0:`client`,sections:[{key:`app`,rows:y}],...g?{}:{onSave:()=>void m(),saving:d,dirty:p},onClose:n})}var rp={env:`Deployment`,lab:`Own`,default:`Default`},ip=`https://console.cloud.google.com/apis/credentials`,ap=[{value:`installed`,label:`Desktop app`},{value:`web`,label:`Web application`}],op={installed:`For a lab on this machine; Google needs no redirect registered.`,web:`For a lab at its own address; register the redirect below with the client.`},sp=`/api/connections/google/callback`,cp=()=>/^(localhost|127\.|\[::1\])/.test(window.location.hostname);function lp(e){let t;try{t=JSON.parse(e)}catch{return`that file is not JSON`}let n=t??{},r=n.installed?`installed`:n.web?`web`:null,i=r?n[r]:void 0;return!r||typeof i?.client_id!=`string`||typeof i.client_secret!=`string`?`that is not a client file from Google Cloud`:{clientId:i.client_id,clientSecret:i.client_secret,apiKey:``,clientType:r}}function up({onClose:e,onSaved:t}){let n=Z(),[r,i]=(0,X.useState)(void 0),[a,o]=(0,X.useState)(!0),[s,c]=(0,X.useState)(``),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(``),[p,m]=(0,X.useState)(cp()?`installed`:`web`),[h,g]=(0,X.useState)({clientId:``,apiKey:``,kind:``}),[_,v]=(0,X.useState)(null),[y,b]=(0,X.useState)(null),[x,S]=(0,X.useState)(!1);(0,X.useEffect)(()=>{n.google().then(e=>{i(e.google),o(e.editable);let t=e.google?.from===`lab`?e.google:null;t&&(c(t.clientId),f(t.apiKey??``),m(t.clientType)),g({clientId:t?.clientId??``,apiKey:t?.apiKey??``,kind:t?.clientType??(cp()?`installed`:`web`)})},e=>{i(null),v(e instanceof Error?e.message:String(e))})},[n]);let C=s!==h.clientId||d!==h.apiKey||p!==h.kind||!!l,w=async()=>{if(!C){e();return}S(!0);try{await n.setGoogle({clientId:s,apiKey:d,clientType:p,...l?{clientSecret:l}:{}}),t(),e()}catch(e){v(e instanceof Error?e.message:String(e)),S(!1)}},T=e=>t=>{v(null),b(null),e(t)},E=()=>{let e=document.createElement(`input`);e.type=`file`,e.accept=`.json,application/json`,e.onchange=()=>{let t=e.files?.[0];t&&D(t)},e.click()},D=async e=>{let t=lp(await e.text());if(typeof t==`string`){v(t);return}c(t.clientId),m(t.clientType),u(t.clientSecret??``),b(`Loaded the client file`)};if(r===void 0)return null;let O=!a,k=!!r?.hasSecret&&r.from!=="default",A=O?r?.clientType??`web`:p,j=O?[{key:`client`,label:`Client ID`,control:{type:`code`,text:r?.clientId??`—`}},{key:`secret`,label:`Client secret`,control:{type:`static`,text:r?.hasSecret?`Held`:`None`}},{key:`key`,label:`API key`,control:{type:`code`,text:r?.apiKey??`—`}},{key:`type`,label:`Type`,control:{type:`static`,text:ap.find(e=>e.value===A).label}}]:[{key:`client`,label:`Client ID`,control:{type:`text`,value:s,onChange:T(c),placeholder:r?.from==="default"?r.clientId:`000000000000-….apps.googleusercontent.com`}},{key:`secret`,label:`Client secret`,control:{type:`secret`,value:l,onChange:T(e=>u(e??``)),...k?{placeholder:`Saved`}:{}}},{key:`key`,label:`API key`,control:{type:`text`,value:d,onChange:T(f),placeholder:`AIza…`}},{key:`type`,label:`Type`,hint:op[p],control:{type:`select`,value:p,options:ap,onChange:e=>T(m)(e)}}];return j.push({key:`redirect`,label:`Redirect URI`,control:A===`web`?{type:`code`,text:new URL(sp,window.location.href).href}:{type:`static`,text:`Not Needed`}},{key:`app`,label:`App`,control:{type:`static`,text:r?.from?rp[r.from]:`None`}}),(0,$.jsx)(ut,{title:`Google Drive`,status:_??y??void 0,statusBad:!!_,focusRow:O?void 0:`client`,sections:[{key:`app`,rows:j}],actions:[{label:`Google Cloud`,icon:En,onSelect:()=>{window.open(ip,`_blank`,`noopener`)}},...O?[]:[{label:`Load client file…`,icon:kn,onSelect:E}]],...O?{}:{onSave:()=>void w(),saving:x,dirty:C},onClose:e})}var dp=`microsoft`,fp=`google`;function pp(){let e=Z(),{list:t}=ao(),n=t.filter(e=>!e.archived).map(e=>({id:e.id,name:e.name})),{sharesFor:r,setFor:i}=Jf(e),{cfg:a,editable:o}=nl(),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(void 0),[p,m]=(0,X.useState)(null),h=(0,X.useCallback)(()=>{e.connections().then(e=>u(e.connections),()=>u([]))},[e]);(0,X.useEffect)(h,[h]),(0,X.useEffect)(()=>{if(!a){f(null);return}qc(a).then(f,()=>f(null))},[a]);let g=[...l??[],...a||o?[{id:dp,label:`Microsoft 365`,configured:!!a,signedIn:!!d,account:d??null,problem:null}]:[]],_=async t=>{m(null);try{t.id===dp&&a?await Zc(a):window.location.assign((await e.signIn(t.id)).url)}catch(e){m(e instanceof Error?e.message:String(e))}},v=async t=>{m(null);try{t.id===dp&&a?(await Qc(a),f(null)):u((await e.signOut(t.id)).connections)}catch(e){m(e instanceof Error?e.message:String(e))}};if(l===null)return(0,$.jsx)(E,{id:`setup-connections`,title:`Accounts`,children:(0,$.jsx)(C,{label:`Accounts`})});if(!g.length)return null;let y=g.filter(e=>e.problem);return(0,$.jsxs)(E,{id:`setup-connections`,title:`Accounts`,note:`${g.filter(e=>e.signedIn).length} of ${g.length}`,children:[(0,$.jsx)(J,{className:`setup-table`,cards:!0,label:`Accounts`,rows:g,rowKey:e=>e.id,columns:[{key:`label`,header:`Account`,role:`title`,cell:e=>e.label},{key:`status`,header:`Status`,cell:e=>e.id===dp&&a&&d===void 0?(0,$.jsxs)(`span`,{className:`loading-status`,children:[(0,$.jsx)(F,{}),`Checking`]}):mp(e)},{key:`account`,header:`Account`,cell:e=>e.account||`—`},{key:`workspaces`,header:`Workspaces`,sort:e=>qf(r(`account`,e.id)),cell:e=>(0,$.jsx)($t,{label:e.label,workspaces:n,shares:r(`account`,e.id),onChange:t=>i(`account`,e.id,t)})},{key:`menu`,header:``,className:`ds-menu`,role:`menu`,sort:null,cell:e=>(0,$.jsx)(Y,{label:`${e.label} actions`,actions:[e.signedIn?{label:`Sign out`,icon:Rn,onSelect:()=>void v(e)}:{label:`Sign in`,icon:Ln,disabled:!e.configured,onSelect:()=>void _(e)},...e.id===dp||e.id===fp?[{label:`Configure…`,icon:xt,onSelect:()=>c(e.id)}]:[]]})}]}),y.map(e=>(0,$.jsxs)(`p`,{className:`note bad`,role:`alert`,children:[e.label,`: `,e.problem]},e.id)),p&&(0,$.jsx)(`p`,{className:`note bad`,role:`alert`,children:p}),s===dp&&a!==void 0&&(0,$.jsx)(np,{cfg:a,editable:o,onClose:()=>c(null)}),s===fp&&(0,$.jsx)(up,{onClose:()=>c(null),onSaved:h})]})}var mp=e=>e.configured?e.signedIn?`Signed In`:`Signed Out`:`Not Configured`,hp=L().WIZARDS,gp=L().wizardProgress;function _p(e){return!!e?.targets?.some(e=>e.steps?.some(e=>e.type===`recorded`))}L().WIZARDS[`test-workflow`]={id:`test-workflow`,title:`Test a Power Automate workflow`,blurb:`Vary a workflow action's request and grade the replies against what it recorded.`,steps:[{id:`source`,title:`Add a workflow Source`,detail:`In the Library, add the workflow and let it import its recent calls.`,where:`#/library/sources`,focus:`.add-btn`,done:e=>e.sources.some(e=>!!e.platform)},{id:`test`,title:`Test an action`,detail:`Open the Source and Test… the action that calls the model.`,where:`#/library/sources`,done:e=>e.pipelines.some(e=>_p(e.work))},{id:`run`,title:`Run the test`,detail:`On Runs, change the editable target's request and run it.`,where:`#/runs`,focus:`.action-bar-primary`,done:e=>e.runs.some(e=>_p(e.snapshot))},{id:`compare`,title:`Compare the replies`,detail:`Open the finished run and read the two replies side by side.`,where:`#/history`,done:e=>e.runs.some(e=>e.status===`done`&&_p(e.snapshot))}]};var vp=(0,X.createContext)(null);function yp({children:e}){let t=Z(),[n,r]=Q(`promptlab.wizard`),[i]=Q(`promptlab.connections`),[a]=Q(`promptlab.workflows`),[o,s]=(0,X.useState)([]),[c,l]=(0,X.useState)([]),u=(0,X.useRef)(!!n);u.current=!!n,(0,X.useEffect)(()=>{let e=!0,n=()=>{t.sources().then(t=>{e&&s(t.sources)},()=>{}),t.queue({limit:20}).then(t=>{e&&l(t.runs)},()=>{})};n();let r=()=>{u.current&&n()};return window.addEventListener(`hashchange`,r),gn.addEventListener(`write`,r),()=>{e=!1,window.removeEventListener(`hashchange`,r),gn.removeEventListener(`write`,r)}},[t,n?.id]);let d=(0,X.useMemo)(()=>({profiles:i.list,pipelines:a.list,sources:o,runs:c}),[i.list,a.list,o,c]),f=(0,X.useMemo)(()=>Object.values(hp),[]),p=n?hp[n.id]??null:null,m=(0,X.useCallback)(e=>{hp[e]&&r({id:e})},[r]),h=(0,X.useCallback)(()=>r(null),[r]),g=(0,X.useCallback)(e=>{location.hash!==e.where&&(location.hash=e.where),e.focus&&Sp(e.focus)},[]),_=(0,X.useMemo)(()=>({entries:f,active:p,lab:d,start:m,cancel:h,goToStep:g}),[f,p,d,m,h,g]);return(0,$.jsx)(vp.Provider,{value:_,children:e})}function bp(){let e=(0,X.useContext)(vp);if(!e)throw Error(`useWizard outside a WizardProvider: the app mounts one at its root`);return e}function xp(){let{active:e,lab:t}=bp();return(0,X.useMemo)(()=>e?{entry:e,...gp(e,t)}:null,[e,t])}function Sp(e,t=20){let n=document.querySelector(e);if(n){n.focus({preventScroll:!1});try{n.focus({focusVisible:!0})}catch{}n.scrollIntoView?.({block:`center`,behavior:`smooth`});return}t>0&&requestAnimationFrame(()=>Sp(e,t-1))}var Cp=e=>({tab:`setup`,section:`wizards`,id:e});function wp({wizardId:e=null}){let{entries:t,active:n,lab:r,start:i,cancel:a,goToStep:o}=bp(),s=uo(),c=e?t.find(t=>t.id===e)??null:null;(0,X.useEffect)(()=>{e&&!c&&Ir(Cp(null))},[e,c]);let l=c??(e?null:n);if(!l)return(0,$.jsxs)(E,{id:`setup-wizards`,title:`Wizards`,note:`${t.length} available`,children:[(0,$.jsx)(`p`,{className:`note`,children:`Get started quickly with a wizard to guide you through the steps.`}),(0,$.jsx)(J,{className:`setup-table wiz-table`,cards:!0,label:`Wizards`,rows:t,rowKey:e=>e.id,columns:[{key:`name`,header:`Wizard`,role:`title`,cell:e=>(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`a`,{className:`wiz-list-name`,href:Pr(Cp(e.id)),children:e.title}),(0,$.jsx)(`span`,{className:`note`,children:e.blurb})]})},{key:`progress`,header:`Steps`,sort:e=>gp(e,r).done,cell:e=>{let t=gp(e,r);return`${t.done}/${t.total}`}},{key:`start`,header:``,role:`menu`,sort:null,cell:e=>(0,$.jsx)(me,{label:`${e.title} actions`,actions:[{label:`Start`,icon:Bt,onSelect:()=>{i(e.id),Fr(Cp(e.id))}}]})}]})]});let u=l.id===n?.id,{ticks:d,done:f,total:p,current:m}=gp(l,r),h=m>=0?l.steps[m]:null,g=m<0;return(0,$.jsxs)(`div`,{className:`setup-wizard`,children:[(0,$.jsx)(k,{kind:`Wizard`,name:l.title,meta:`${f} of ${p} complete`,actions:[s(Cp(l.id))],docked:!0}),u?(0,$.jsx)(Qe,{primary:{label:`Next step`,icon:G,onSelect:()=>h&&o(h),disabled:g},status:g?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`b`,{children:`All steps done.`}),` Cancel to close it.`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`b`,{children:[`Step `,m+1,` of `,p]}),` · `,h.title]}),secondary:{label:`Cancel wizard`,icon:g?Se:_t,onSelect:a}}):(0,$.jsx)(Qe,{primary:{label:`Start`,icon:Bt,onSelect:()=>i(l.id)},status:g?(0,$.jsx)(`b`,{children:`All steps done.`}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`b`,{children:[`Step `,m+1,` of `,p]}),` · `,h.title]})}),(0,$.jsx)(E,{id:`setup-wizard-steps`,title:l.title,note:l.blurb,children:(0,$.jsx)(J,{className:`setup-table wiz-table`,cards:!0,label:`${l.title} steps`,rows:l.steps.map((e,t)=>({...e,n:t,state:d[t]?`done`:t===m?`now`:`todo`})),rowKey:e=>e.id,columns:[{key:`step`,header:`Step`,role:`title`,cell:e=>(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`span`,{className:`wiz-step-title${e.state===`now`?` current`:``}`,children:[e.n+1,`. `,e.title]}),(0,$.jsx)(`span`,{className:`note`,children:e.detail})]})},{key:`state`,header:`Status`,cell:e=>(0,$.jsx)(`span`,{className:`wiz-row-state ${e.state}`,children:e.state===`done`?`Done`:e.state===`now`?`Next`:`To do`})},{key:`go`,header:``,role:`menu`,sort:null,cell:e=>(0,$.jsx)(me,{label:`${e.title} actions`,actions:[{label:`Go to step`,icon:wt,onSelect:()=>o(e)}]})}]})})]})}var Tp={google:`Google Drive`,microsoft:`Microsoft 365`},Ep=e=>`/w/${e}`,Dp=e=>L().slugOf(e),Op=e=>{let t=Dp(e.name);return!!t&&t!==e.slug&&t!==e.slug.replace(/-\d+$/,``)};function kp(){let e=Z(),t=Ye(),{current:n}=ao(),[r,i]=(0,X.useState)(null),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(null),_=e=>c({text:e instanceof Error?e.message:String(e),bad:!0}),v=(0,X.useCallback)(()=>{o(null),e.workspaces().then(e=>i(e.workspaces),e=>o(e instanceof Error?e.message:String(e)))},[e]);(0,X.useEffect)(v,[v]);let y=(r??[]).filter(e=>!e.archived).length,b=(0,X.useCallback)(async t=>{try{let n=await e.createWorkspace(t);i(n.workspaces),c(null)}catch(e){_(e)}},[e]),x=(0,X.useCallback)(async(t,n)=>{try{i((await e.renameWorkspace(t.id,n)).workspaces)}catch(e){_(e)}},[e]),S=(0,X.useCallback)(async t=>{try{i((await e.regenerateWorkspace(t.id)).workspaces),c(null)}catch(e){_(e)}},[e]),w=(0,X.useCallback)(async r=>{try{let a=await e.archiveWorkspace(r.id);if(r.slug===n?.slug){let e=ro(a.workspaces);if(e){to({id:r.id,slug:r.slug,name:r.name}),location.assign($a(e.slug));return}}i(a.workspaces),t.offer({label:`Archived ${r.name}`,restore:()=>void(async()=>{try{i((await e.unarchiveWorkspace(r.id)).workspaces)}catch(e){_(e)}})()})}catch(e){_(e)}},[e,t,n]),T=(0,X.useCallback)(async t=>{try{i((await e.unarchiveWorkspace(t.id)).workspaces)}catch(e){_(e)}},[e]),D=(0,X.useCallback)(async t=>{try{i((await e.setDefaultWorkspace(t.id)).workspaces)}catch(e){_(e)}},[e]),O=(0,X.useCallback)(async n=>{try{let{trash:r}=await e.deleteWorkspace(n.id);i(e=>(e??[]).filter(e=>e.id!==n.id)),t.offer({label:`Deleted ${n.name}`,restore:()=>void(async()=>{try{i((await e.restoreWorkspace(r)).workspaces)}catch(e){_(e)}})()})}catch(e){_(e)}},[e,t]),k=(r??[]).filter(e=>e.archived),A=(r??[]).filter(e=>l||!e.archived);return(0,$.jsxs)(E,{id:`setup-workspaces`,title:`Workspaces`,note:r?Np(r.length):``,children:[(0,$.jsx)(`p`,{className:`note`,children:`Workspaces contain pipelines, runs, library content, and packs. Connections can be shared.`}),r===null&&(0,$.jsx)(C,{label:`Workspaces`,error:a,onRetry:v}),r&&(0,$.jsxs)($.Fragment,{children:[k.length>0&&(0,$.jsx)(`div`,{className:`pills ws-archived`,role:`group`,"aria-label":`Show`,children:(0,$.jsxs)(`label`,{className:`pill`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:l,onChange:e=>u(e.target.checked)}),(0,$.jsx)(`span`,{children:`Archived`})]})}),(0,$.jsx)(J,{className:`setup-table ws-table`,cards:!0,label:`Workspaces`,rows:A,rowKey:e=>e.id,columns:Ap({onlyActive:y<=1,currentSlug:n?.slug??null,onRename:m,onRegenerate:g,onArchive:e=>void w(e),onUnarchive:e=>void T(e),onDelete:e=>void O(e),onSetDefault:e=>void D(e)})}),(0,$.jsxs)(`button`,{type:`button`,className:`ghost add-btn`,onClick:()=>f(!0),children:[(0,$.jsx)(ze,{size:14,"aria-hidden":`true`}),`Add workspace`]})]}),s&&(0,$.jsx)(`p`,{className:`note${s.bad?` bad`:``}`,role:s.bad?`alert`:`status`,children:s.text}),(0,$.jsx)(Vt,{undo:t.undo,onUndo:t.undoNow,onDismiss:t.dismiss}),d&&(0,$.jsx)(jp,{onCreate:e=>void b(e),onClose:()=>f(!1)}),p&&(0,$.jsx)(Tt,{title:`Rename ${p.name}`,value:p.name,onCommit:e=>void x(p,e),onClose:()=>m(null)}),h&&(0,$.jsx)(Mp,{workspace:h,onRegenerate:()=>void S(h),onClose:()=>g(null)})]})}function Ap(e){let t=t=>t.archived?[{label:`Rename…`,icon:M.rename,onSelect:()=>e.onRename(t)},{label:`Unarchive`,icon:yn,onSelect:()=>e.onUnarchive(t)},{label:`Delete permanently`,icon:M.remove,destructive:!0,onSelect:()=>e.onDelete(t)}]:[{label:`Rename…`,icon:M.rename,onSelect:()=>e.onRename(t)},...t.isDefault?[]:[{label:`Set as default`,icon:Jn,onSelect:()=>e.onSetDefault(t)}],...e.onlyActive?[]:[{label:`Archive`,icon:bn,onSelect:()=>e.onArchive(t)}]];return[{key:`name`,header:`Workspace`,role:`title`,sort:e=>e.name,cell:e=>e.name},{key:`slug`,header:`Address`,sort:e=>e.slug,cell:t=>(0,$.jsxs)(`span`,{className:`ws-address`,children:[(0,$.jsx)(`a`,{className:`ws-addr`,href:Ep(t.slug),children:(0,$.jsx)(`code`,{children:Ep(t.slug)})}),!t.archived&&Op(t)&&(0,$.jsxs)(`button`,{type:`button`,className:`ws-regen`,onClick:()=>e.onRegenerate(t),children:[(0,$.jsx)(Hn,{size:12,"aria-hidden":`true`}),`Regenerate…`]})]})},{key:`pipelines`,header:`Pipelines`,sort:e=>e.pipelines,cell:e=>e.pipelines},{key:`runs`,header:`Runs`,sort:e=>e.runs,cell:e=>e.runs},{key:`lastUsed`,header:`Last used`,sort:e=>e.lastUsed??``,cell:e=>Ip(e.lastUsed)},{key:`status`,header:`Status`,sort:t=>Pp(t,e.currentSlug),cell:t=>{if(t.archived)return(0,$.jsx)(`span`,{className:`setup-unset`,children:`Archived`});let n=[t.slug===e.currentSlug?`Current`:``,t.isDefault?`Default`:``].filter(Boolean);return n.length?(0,$.jsx)(`span`,{className:t.slug===e.currentSlug?`ws-current`:`setup-unset`,children:n.join(`, `)}):(0,$.jsx)(`span`,{className:`setup-unset`,children:`—`})}},{key:`menu`,header:``,label:``,className:`setup-menu`,role:`menu`,sort:null,cell:e=>(0,$.jsx)(Y,{actions:t(e),label:`${e.name} actions`})}]}function jp({onCreate:e,onClose:t}){let n=Z(),[r]=Q(`promptlab.connections`),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(`nothing`),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)({});(0,X.useEffect)(()=>{let e=!0;return n.connectionShares().then(t=>{e&&d(t.shares)}).catch(()=>{e&&d({})}),()=>{e=!1}},[n]);let m=(0,X.useMemo)(()=>{let e=[];for(let[t,n]of Object.entries(u??{})){if(n.includes(`*all`))continue;let i=t.indexOf(`:`),a=t.slice(0,i),o=t.slice(i+1),s=a===`profile`?r.list.find(e=>e.id===o)?.name:Tp[o];s&&e.push({key:t,kind:a,id:o,label:s,prefill:n.includes(Wt)})}return e.sort((e,t)=>e.label.localeCompare(t.label))},[u,r.list]),h=e=>e.key in f?f[e.key]:e.prefill,g=[{key:`new`,rows:[{key:`name`,label:`Name`,width:`full`,required:!0,control:{type:`text`,value:i,onChange:a}},{key:`slug`,label:`Address`,width:`full`,control:{type:`text`,value:o,placeholder:Ep(Dp(i)||`workspace`),onChange:e=>s(e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+/,``).slice(0,L().SLUG_MAX))}},{key:`content`,label:`Starting content`,control:{type:`select`,value:c,onChange:e=>l(e),options:[{value:`nothing`,label:`Nothing`},{value:`demo`,label:`Demo pack`}]}}]}];return m.length&&g.push({key:`connections`,title:`Connections`,rows:m.map(e=>({key:e.key,label:e.label,control:{type:`checkbox`,checked:h(e),onChange:t=>p(n=>({...n,[e.key]:t}))}}))}),u===null?null:(0,$.jsx)(ut,{title:`New workspace`,focusRow:`name`,sections:g,dirty:!!i.trim()||!!o.trim()||c!==`nothing`,onSave:()=>{let n=m.filter(h).map(e=>({kind:e.kind,id:e.id}));e({name:i.trim(),...o.trim()?{slug:o.trim()}:{},content:c,...m.length?{connections:n}:{}}),t()},onClose:t})}function Mp({workspace:e,onRegenerate:t,onClose:n}){let r=Ep(Dp(e.name)||`workspace`);return(0,$.jsx)(b,{title:`Regenerate address`,onClose:n,footer:(0,$.jsxs)(`div`,{className:`edit-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:n,children:`Cancel`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>{t(),n()},children:`Regenerate`})]}),children:(0,$.jsxs)(`div`,{className:`ws-regen-dialog`,children:[(0,$.jsxs)(`dl`,{className:`ws-regen-rows`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Now`}),(0,$.jsx)(`dd`,{children:(0,$.jsx)(`code`,{children:Ep(e.slug)})})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`New`}),(0,$.jsx)(`dd`,{children:(0,$.jsx)(`code`,{children:r})})]})]}),(0,$.jsx)(`p`,{className:`note bad`,role:`alert`,children:`The old address stops working. Bookmarks and links to it break, and the lab will not redirect them.`})]})})}var Np=e=>e===1?`1 workspace`:`${e} workspaces`,Pp=(e,t)=>e.archived?`Archived`:[e.slug===t?`Current`:``,e.isDefault?`Default`:``].filter(Boolean).join(`, `),Fp=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],Ip=e=>{if(!e)return`—`;let t=new Date(e);return Number.isNaN(t.getTime())?e:`${t.getFullYear()}-${Fp[t.getMonth()]}-${String(t.getDate()).padStart(2,`0`)}`},Lp=[{id:`connections`,label:`Connections`,icon:dt},{id:`workspaces`,label:`Workspaces`,icon:Sn},{id:`wizards`,label:`Wizards`,icon:wt}];function Rp({section:e=`connections`,id:t=null,kind:n}){return(0,$.jsxs)(`div`,{className:`setup`,children:[(0,$.jsx)(R,{label:`Setup`,level:`section`,className:`setup-sections`,current:e,items:Lp.map(({id:e,label:t,icon:n})=>({key:e,label:t,href:Pr({tab:`setup`,section:e,id:null}),icon:n}))}),(0,$.jsx)(`section`,{className:`setup-section`,"data-section":e,children:e===`wizards`?(0,$.jsx)(wp,{wizardId:t}):e===`workspaces`?(0,$.jsx)(kp,{}):(0,$.jsx)(Hp,{connectionId:n===`profile`?null:t,profileId:n===`profile`?t:null})})]})}var zp={tab:`setup`,section:`connections`,id:null},Bp=e=>({tab:`setup`,section:`connections`,id:e}),Vp=()=>{let e=Lr();e.tab===`setup`&&e.id&&Fr(zp)};function Hp({connectionId:e=null,profileId:t=null}){let n=Zn(),r=uo(),i=Z(),a=Ye(),{list:o}=ao(),s=o.filter(e=>!e.archived).map(e=>({id:e.id,name:e.name})),{sharesFor:c,setFor:l,setForEach:u}=Jf(i),[f,p]=Q(`promptlab.connections`),[m]=Q(`promptlab.connectionProfiles`),[h]=Q(`promptlab.versions`),[g]=Q(`promptlab.workflows`),{list:_}=gr(),v=_??[],[y,b]=(0,X.useState)(null),[x,S]=(0,X.useState)(null),C=(0,X.useRef)(x);C.current=x;let[w,T]=(0,X.useState)(null),[D,O]=(0,X.useState)(null),[k,A]=(0,X.useState)({}),[j,N]=(0,X.useState)(``),[P,F]=(0,X.useState)(`all`),[I,R]=(0,X.useState)({key:`name`,dir:`asc`}),[z,B]=(0,X.useState)([]),[ee,V]=(0,X.useState)({}),[H,te]=(0,X.useState)(()=>new Set),U=(0,X.useRef)(null);(0,X.useEffect)(()=>{let e=!0;return i.presets().then(t=>{e&&B(t)}).catch(()=>{}),()=>{e=!1}},[i]);let W=(0,X.useRef)(f);W.current=f;let ne=(0,X.useRef)(!0);(0,X.useEffect)(()=>()=>{ne.current=!1},[]);let G=[...H].sort().join(`,`);(0,X.useEffect)(()=>{U.current=null},[G]);let re=(0,X.useCallback)(e=>{let t=C.current;return t?.p.id===e?t.p:W.current.list.find(t=>t.id===e)},[]),ie=(0,X.useCallback)(e=>{let t=C.current;if(t?.p.id!==e.id)return;let n={...t,p:e};C.current=n,S(n)},[]),ae=(0,X.useCallback)(()=>{let e=C.current;if(!e)return;let t=W.current,r=e.was?{...t,list:t.list.map(t=>t.id===e.p.id?e.p:t)}:{...t,list:[...t.list,e.p],at:e.p.id};W.current=r,p(r),ur(n,`profile`,e.p.id,e.p,`idle`),S(null),b(null),Vp()},[p,n]),K=(0,X.useCallback)(()=>{S(null),b(null)},[]),q=(0,X.useCallback)(()=>{K(),Vp()},[K]),oe=(0,X.useCallback)(()=>{let e=pm(W.current.list);S({p:e,was:null,start:e}),b({id:``,focus:`name`})},[]),se=(0,X.useCallback)(e=>{let t=W.current.list.find(t=>t.id===e);if(!t)return;let n=`${t.name||`Connection`} copy`,r={...structuredClone(t),id:dm(),name:n,slug:fm(n,W.current.list),key:t.key},i={...W.current,list:[...W.current.list,r]};W.current=i,p(i)},[p]),ce=(0,X.useCallback)(e=>{let t=W.current,n=new Set(e),r=t.list.filter(e=>!n.has(e.id));if(!r.length||r.length===t.list.length)return;let i=n.has(t.at)?r[0].id:t.at,o={...t,list:r,at:i,...t.grader&&n.has(t.grader)?{grader:``}:{}};W.current=o,p(o),b(null),S(null),Vp(),te(new Set);let s=t.list.filter(e=>n.has(e.id));a.offer({label:s.length===1?`Deleted ${s[0].name||`the connection`}`:`Removed ${s.length} connections`,restore:()=>{W.current=t,p(t)}})},[p,a]),le=(0,X.useCallback)(e=>ce([e]),[ce]),ue=(0,X.useCallback)(e=>{let t=e.doc.id,r=W.current.list.find(e=>e.id===t);r&&ur(n,`profile`,t,r,`restore`);let i=L().splitProfile(e.doc).connection,a=W.current,o={...a,list:a.list.map(e=>e.id===t?i:e)};W.current=o,p(o),de()},[n,p]),de=(0,X.useCallback)(()=>{T(e=>(e?.back&&Te(e.id),null))},[]),fe=(0,X.useCallback)(async e=>{let t=re(e);if(!t)return;let n=L().CONNECTION_TYPES[t.type];if(n?.local){A(t=>({...t,[e]:{phase:`connected`,ms:0,lines:[`${n.label} answers each text item with its own text, and sends nothing anywhere.`]}}));return}let r=n?.keyless?``:t.key,a=rm(t,n),o=performance.now(),s=()=>Math.round(performance.now()-o),c=[];A(t=>({...t,[e]:{phase:`checking`,lines:[`Checking…`]}}));try{let o=((await i.models({url:L().addressOf(t),key:r,type:t.type,settings:im(t,n)})).data||[]).map(e=>e.id).sort();if(V(t=>({...t,[e]:o})),c.push(`Reached ${a}.`,`${o.length} ${o.length===1?`model`:`models`}: ${o.join(`, `)||`none`}.`),(n?.answers??[`prompt`]).includes(`prompt`)){if(t.model.trim()){let e=L().apiBase(t.url||n?.url||``),a=L().connectionRequest(t,`hi`,null,e,r),o=await i.modelsAsk({url:L().addressOf(t),key:r,type:t.type,body:a.body}),{raw:s}=L().connectionReply(t,o);c.push(``,`Asked ${t.model} “hi”; it replied:`,s||`(an empty reply)`)}else c.push(``,`No model is picked, so nothing was asked.`)}A(t=>({...t,[e]:{phase:`connected`,lines:c,ms:s()}}))}catch(t){c.push(...c.length?[``]:[],t instanceof Error?t.message:String(t)),A(t=>({...t,[e]:{phase:`error`,lines:c,ms:s()}}))}},[i,re]),pe=(0,X.useCallback)(async e=>{let t=L().CONNECTION_TYPES[e.type],n=t?.keyless?``:e.key,r=rm(e,t),a=performance.now(),o=()=>Math.round(performance.now()-a);try{let a=await i.models({url:L().addressOf(e),key:n,type:e.type,settings:im(e,t),quiet:!0});if(a.error)return{state:{phase:`error`,lines:[a.error],ms:o()}};let s=(a.data||[]).map(e=>e.id).sort();return{models:s,state:{phase:`connected`,ms:o(),lines:[`Reached ${r}.`,`${s.length} ${s.length===1?`model`:`models`}: ${s.join(`, `)||`none`}.`]}}}catch(e){return{state:{phase:`error`,lines:[e instanceof Error?e.message:String(e)],ms:o()}}}},[i]),me=(0,X.useCallback)(async e=>{let{state:t,models:n}=await pe(e);ne.current&&(n&&V(t=>({...t,[e.id]:n})),A(n=>e.id in n?n:{...n,[e.id]:t}))},[pe]),he=(0,X.useCallback)(e=>{let t=new Set(e),n=W.current.list.filter(e=>t.has(e.id)&&tm(e));if(n.length){A(e=>{let t={...e};for(let e of n)t[e.id]={phase:`checking`,lines:[`Checking…`]};return t});for(let e of n)(async()=>{let{state:t,models:n}=await pe(e);ne.current&&(n&&V(t=>({...t,[e.id]:n})),A(n=>({...n,[e.id]:t})))})()}},[pe]),ge=(0,X.useCallback)((e,t)=>{if(!e.length)return;U.current||=new Map(e.map(e=>[e,c(`profile`,e)]));let n=U.current;u(`profile`,e.map(e=>({id:e,workspaces:t})));let r=e.length===1?W.current.list.find(t=>t.id===e[0])?.name||`the connection`:`${e.length} connections`;a.offer({label:`Workspaces for ${r}`,restore:()=>{u(`profile`,[...n].map(([e,t])=>({id:e,workspaces:t&&t.length?[...t]:[je]}))),U.current=null}})},[c,u,a]),_e=(0,X.useRef)(!1),[ve,ye]=(0,X.useState)(!1);(0,X.useEffect)(()=>{if(_e.current)return;let e=y?.id,t=t=>f.list.find(n=>n.id!==e&&!(n.id in k)&&!t.has(n.id)&&tm(n));if(!t(new Set))return;_e.current=!0,ye(!0);let n=new Set;(async()=>{for(let e=t(n);e;e=t(n))n.add(e.id),await me(e);_e.current=!1,ne.current&&ye(!1)})()},[k,f,y,me]);let Y=y?x?.p:void 0,be=Y?JSON.stringify([Y.id,Y.url,Y.type,Y.key]):``;(0,X.useEffect)(()=>{if(!Y)return;let e=Y;if(L().CONNECTION_TYPES[e.type]?.local||L().CONNECTION_TYPES[e.type]?.lists===!1)return;let t=L().CONNECTION_TYPES[e.type]?.keyless,n=!0,r=setTimeout(()=>{i.models({url:L().addressOf(e),key:t?``:e.key,type:e.type,quiet:!0}).then(t=>{n&&V(n=>({...n,[e.id]:(t.data||[]).map(e=>e.id).sort()}))}).catch(()=>{n&&V(t=>({...t,[e.id]:[]}))})},400);return()=>{n=!1,clearTimeout(r)}},[i,be]);let xe=(0,X.useCallback)((e,t)=>{let n=re(e);if(!n)return;let r={...n};for(let e of um(n.type))r[e]=``;for(let[e,n]of Object.entries(t))r[e]=n;ie(r)},[re,ie]),Se=(0,X.useCallback)(e=>{A(t=>{if(!(e in t))return t;let{[e]:n,...r}=t;return r})},[]),Ce=(0,X.useCallback)((e,t,n)=>{let r=re(e);if(r){if([`url`,`key`,`model`].includes(t)&&Se(e),t===`name`){let t=W.current.list.filter(t=>t.id!==e);if(!r.slug||r.slug===fm(r.name,t)){ie({...r,name:n,slug:fm(n,t)});return}}t===`slug`&&(n=n.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+/,``).slice(0,L().SLUG_MAX)),ie({...r,[t]:n})}},[re,ie,Se]),we=(0,X.useCallback)((e,t)=>{let n=re(e);if(!n)return;let r={...n,type:t};Se(e),V(t=>({...t,[e]:[]}));let i=L().CONNECTION_TYPES[t];i?.keyless&&(r.key=``);let a=L().CONNECTION_TYPES[n.type]?.url;(i?.url||a&&r.url.trim()===a)&&(r.url=``);for(let e of Object.keys(r))[`id`,`name`,`slug`,`url`,`model`,`key`,`type`].includes(e)||r[e]===``||um(t).includes(e)||delete r[e];ie(r)},[re,ie,Se]),Te=(0,X.useCallback)((e,t)=>{let n=W.current.list.find(t=>t.id===e);n&&(S({p:structuredClone(n),was:n,start:n}),b(t?{id:e,focus:t}:{id:e}))},[]),Ee=(0,X.useCallback)((e,t)=>{Te(e,t),Fr(Bp(e))},[Te]);(0,X.useEffect)(()=>{if(!e){C.current?.was&&K();return}C.current?.p.id!==e&&(W.current.list.some(t=>t.id===e)?Te(e):Ir(zp))},[e,Te,K]);let De=(0,X.useCallback)(e=>h.profile?.[e]??[],[h]),Oe=y?x?.p??null:null,ke=x?x.was?f.list.map(e=>e.id===x.p.id?x.p:e):[...f.list,x.p]:f.list,Ae=f.grader??null,Me=(0,X.useMemo)(()=>{let e=new Map;for(let t of f.list)e.set(t.id,Of(t.id,g.list,v,m.list));return e},[f.list,g.list,v,m.list]),Ne=j.trim().toLowerCase(),Pe=f.list.filter(e=>Wp(P,e,k[e.id])&&(!Ne||[e.name,e.model].some(e=>String(e??``).toLowerCase().includes(Ne)))),Fe=new Set(Pe.map(e=>e.id)),Ie=Pe.filter(e=>H.has(e.id)),Le=[...H].filter(e=>!Fe.has(e)).length,Re=[{label:`Test connection`,icon:dt,disabled:!Ie.some(tm),onSelect:()=>he(Ie.map(e=>e.id))},{label:`Remove`,icon:M.remove,destructive:!0,disabled:!Ie.length||Ie.length>=f.list.length,onSelect:()=>ce(Ie.map(e=>e.id))}],Be=H.size>0?(0,$.jsx)(qt,{count:H.size,noun:`connection`,hidden:Le,actions:Re,onClear:()=>te(new Set),children:Ie.length>0&&(0,$.jsx)($t,{label:Ie.length===1?`1 connection`:`${Ie.length} connections`,workspaces:s,shares:nm(Ie.map(e=>c(`profile`,e.id))),onChange:e=>ge(Ie.map(e=>e.id),e)})}):null;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(E,{id:`setup-ai-connections`,title:`AI Connections`,children:[(0,$.jsxs)(`div`,{className:`setup-intro`,children:[(0,$.jsx)(`p`,{className:`note`,children:`Where the lab sends a prompt — an endpoint and its key, or a signed-in account.`}),ve&&(0,$.jsx)(am,{})]}),f.list.length>0&&(0,$.jsx)(d,{noun:`connections`,search:{label:`Search connections`,placeholder:`Name or model`,value:j,onChange:N},filters:[],quick:{label:`Show`,value:P,onChange:e=>F(e),options:Up}}),f.list.length===0?(0,$.jsx)(`p`,{className:`note`,children:`No connections yet.`}):Pe.length===0?(0,$.jsxs)($.Fragment,{children:[Be,(0,$.jsx)(`p`,{className:`note`,children:`No connections match these filters.`})]}):(0,$.jsxs)($.Fragment,{children:[Be,(0,$.jsx)(J,{className:`setup-table`,cards:!0,label:`AI Connections`,sort:I,onSort:R,rows:Pe,rowKey:e=>e.id,select:{noun:`connection`,label:e=>e.name||`Unnamed connection`,selected:H,onChange:te},rowProps:e=>({className:`setup-row`,onClick:t=>{t.target.closest(`button, a, .menu`)||Ee(e.id)}}),columns:Gp({tests:k,only:f.list.length===1,grader:Ae,uses:e=>Me.get(e)??[],onGrader:e=>{let t=W.current,n={...t,grader:t.grader===e?``:e};W.current=n,p(n)},onOpen:Ee,onClone:se,link:e=>r(Bp(e)),onRemove:le,onTest:fe,onResult:e=>O({id:e,back:!1}),workspaces:s,sharesFor:e=>c(`profile`,e),onShare:(e,t)=>l(`profile`,e,t)})})]}),(0,$.jsxs)(`button`,{type:`button`,className:`ghost add-btn`,onClick:oe,children:[(0,$.jsx)(ze,{size:14,"aria-hidden":`true`}),`Add connection`]})]}),(0,$.jsx)(Lf,{profileId:t,connections:f.list,workflows:g.list,groups:v,presets:z,offer:a.offer}),(0,$.jsx)(pp,{}),(0,$.jsx)(Qf,{offer:a.offer}),(0,$.jsx)(Yf,{offer:a.offer}),(0,$.jsx)(Vt,{undo:a.undo,onUndo:a.undoNow,onDismiss:a.dismiss}),Oe&&(0,$.jsx)(Jp,{connection:Oe,slug:L().withSlugs(ke).find(e=>e.id===Oe.id)?.slug??``,...y?.focus?{focus:y.focus}:{},test:k[Oe.id],models:ee[Oe.id]??[],canRestore:!!x?.was&&!!De(Oe.id).length,uses:Me.get(Oe.id)??[],dirty:!!x&&JSON.stringify(x.p)!==JSON.stringify(x.start),onSave:ae,onClose:q,...x?.was?{link:r(Bp(Oe.id))}:{},onSetting:Ce,onType:we,onTest:fe,onResult:()=>{b(null),O({id:Oe.id,back:!0})},onRestore:()=>{K(),T({id:Oe.id,back:!0})},onApplyTemplate:e=>xe(Oe.id,e)}),D&&k[D.id]&&(0,$.jsx)(om,{test:k[D.id],onClose:()=>{D.back&&C.current?.p.id===D.id&&b({id:D.id}),O(null)}}),w&&(0,$.jsx)(Zp,{versions:De(w.id),onClose:de,onRestore:ue})]})}var Up=[{value:`all`,label:`All`},{value:`connected`,label:`Connected`},{value:`attention`,label:`Needs attention`}];function Wp(e,t,n){if(e===`all`)return!0;let r=em(t,n)?.kind;return e===`connected`?r===`connected`:r===`key-needed`||r===`unreachable`}function Gp({tests:e,only:t,grader:n,onGrader:r,onOpen:i,onClone:a,link:o,onRemove:s,onTest:c,onResult:l,uses:u,workspaces:d,sharesFor:f,onShare:p}){let m=e=>e.name||`Unnamed connection`,h=e=>L().CONNECTION_TYPES[e.type]?.label??e.type,g=l=>[{label:`Edit…`,icon:M.edit,onSelect:()=>i(l.id)},{label:`Rename…`,icon:M.rename,onSelect:()=>i(l.id,`name`)},{label:`Clone`,icon:M.clone,onSelect:()=>a(l.id)},o(l.id),{label:`Test connection`,icon:dt,busy:e[l.id]?.phase===`checking`,onSelect:()=>void c(l.id)},...(L().CONNECTION_TYPES[l.type]?.answers??[`prompt`]).includes(`prompt`)&&!L().CONNECTION_TYPES[l.type]?.local?[{label:n===l.id?`Stop grading`:`Make grader`,icon:Fn,onSelect:()=>r(l.id)}]:[],...t?[]:[{label:`Remove`,icon:M.remove,destructive:!0,onSelect:()=>s(l.id)}]];return[{key:`name`,header:`Connection`,role:`title`,sort:m,cell:t=>{let n=em(t,e[t.id]);return(0,$.jsxs)(`div`,{className:`setup-profile`,children:[n&&(0,$.jsx)(`button`,{type:`button`,className:`setup-dot ${n.kind}`,title:n.title,"aria-label":`Connection status: ${n.label}`,onClick:()=>{e[t.id]?l(t.id):c(t.id)},children:(0,$.jsx)(`span`,{className:`setup-dot-mark`,"aria-hidden":`true`})}),(0,$.jsxs)(`span`,{className:`setup-profile-main`,children:[(0,$.jsx)(`span`,{className:`setup-profile-name`,children:(0,$.jsx)(`button`,{type:`button`,className:`setup-open`,onClick:()=>i(t.id),children:m(t)})}),(0,$.jsx)(`span`,{className:`setup-sub`,children:h(t)})]})]})}},{key:`endpoint`,header:`Endpoint`,label:``,sort:e=>qp(e),cell:e=>{let t=qp(e);return t?(0,$.jsx)(`span`,{className:`setup-endpoint`,children:t}):(0,$.jsx)(`span`,{className:`setup-unset`,children:`—`})}},{key:`model`,header:`Model`,label:``,sort:e=>e.model.trim(),cell:e=>(0,$.jsx)(Kp,{p:e})},{key:`used`,header:`Used by`,label:``,sort:e=>Af(u(e.id)),cell:e=>(0,$.jsx)(jf,{uses:u(e.id)})},{key:`workspaces`,header:`Workspaces`,sort:e=>qf(f(e.id)),cell:e=>(0,$.jsx)($t,{label:m(e),workspaces:d,shares:f(e.id),onChange:t=>p(e.id,t)})},{key:`menu`,header:``,label:``,className:`setup-menu`,role:`menu`,sort:null,cell:e=>(0,$.jsx)(Y,{actions:g(e),label:`${m(e)} actions`})}]}function Kp({p:e}){let t=L().CONNECTION_TYPES[e.type];return t?.local?(0,$.jsx)(`span`,{className:`setup-unset`,children:`—`}):(t?.answers??[`prompt`]).includes(`prompt`)?e.model.trim()?(0,$.jsx)($.Fragment,{children:e.model.trim()}):(0,$.jsx)(`span`,{className:`setup-unset`,children:`Not set`}):(0,$.jsx)(`span`,{className:`setup-unset`,children:`from the request`})}function qp(e){let t=L().CONNECTION_TYPES[e.type];return t?.local?``:rm(e,t).replace(/^https?:\/\//,``).replace(/\/+$/,``)}function Jp({connection:e,slug:t,focus:n,test:r,models:i,canRestore:a,uses:o,dirty:s,link:c,onSave:l,onClose:u,onSetting:d,onType:f,onTest:p,onResult:m,onRestore:h,onApplyTemplate:g}){let _=L().CONNECTION_TYPES[e.type],v=(_?.answers??[`prompt`]).includes(`prompt`),y=(0,X.useMemo)(()=>Xp(e),[e]),b=t=>n=>d(e.id,t,n),x=[{key:`name`,label:`Name`,width:`full`,required:!0,control:{type:`text`,value:e.name,onChange:b(`name`)}},{key:`slug`,label:`Slug`,width:`full`,required:!0,...e.slug&&L().slugOf(e.slug)!==t?{hint:`Taken`}:{},control:{type:`text`,value:e.slug??``,placeholder:t,onChange:b(`slug`)}},{key:`type`,label:`Type`,required:!0,hint:_?.description,control:{type:`select`,value:e.type,onChange:t=>f(e.id,t),options:Object.entries(L().CONNECTION_TYPES).filter(([t,n])=>n.picker!==!1||t===e.type).map(([e,t])=>({value:e,label:t.label}))}},..._?.local?[]:[..._?.url?[]:[{key:`url`,label:`Address`,width:`full`,control:{type:`text`,value:e.url,placeholder:`the lab's Ollama`,onChange:b(`url`)}}],..._?.keyless?[]:[{key:`key`,label:`Key`,control:{type:`secret`,value:mf(e.key)?``:e.key,held:mf(e.key),onChange:b(`key`)}}],...v?[{key:`model`,label:`Model`,width:`full`,control:lm(e.model,i,b(`model`))}]:[]]],S={...e},C=(_?.settings??[]).filter(e=>e.scope===`connection`&&(!e.appliesTo||e.appliesTo(S))).map(t=>Yp(e,t,b(t.key))),[w]=(0,X.useState)(()=>({address:!!e.url.trim()})),T=!_?.local&&!_?.keyless?[{key:`ci`,label:`CI secret`,hint:`The run reads this connection's key from this variable`,control:{type:`code`,text:L().keyVar(e.id,t)}}]:[],E=[{key:`identity`,rows:x},...C.length?[{key:`settings`,title:`Settings`,rows:C}]:[],{key:`use`,title:`Use`,rows:T,children:(0,$.jsx)(Mf,{uses:o})},..._?.url&&!_.local?[{key:`advanced`,title:`Advanced`,folded:!w.address,rows:[{key:`url`,label:`Address`,width:`full`,hint:`Only for a proxy or a gateway`,control:{type:`text`,value:e.url,placeholder:_.url,onChange:b(`url`)}}]}]:[],..._?.local||!v?[]:[{key:`debug`,title:`Debug`,rows:y,folded:!0}]],D=[{label:`Restore…`,icon:Ze,disabled:!a,onSelect:h},...c?[c]:[],...(_?.templates??[]).map(e=>({label:`Apply template: ${e.label}`,icon:M.preset,onSelect:()=>g(e.settings)}))];return(0,$.jsx)(ut,{title:e.name||`Unnamed connection`,...n?{focusRow:n}:{},sections:E,menu:D,actions:_?.tests===!1?[]:[{label:`Test connection`,icon:dt,busy:r?.phase===`checking`,onSelect:()=>p(e.id),outcome:r?{label:Qp[r.phase],bad:r.phase===`error`,onOpen:m}:void 0}],dirty:s,onSave:l,onClose:u})}function Yp(e,t,n){let r=e[t.key]??t.default??``;return t.control===`select`&&t.choices?{key:t.key,label:t.label,control:{type:`select`,value:r,options:t.choices,onChange:n}}:{key:t.key,label:t.label,width:`full`,control:{type:`text`,value:r,onChange:n}}}function Xp(e){let t=L().apiBase(e.url),n=[];try{let{url:r,body:i}=L().connectionRequest(e,`(prompt)`,null,t);n.push({key:`endpoint`,label:`Endpoint`,required:!0,control:{type:`code`,text:r}});let a=i,o=a.messages,s=Array.isArray(o?.[0]?.content)?o[0].content.find(e=>e.type===`text`)?.text??``:o?.[0]?.content??``;n.push({key:`prompt`,label:`Prompt`,required:!0,control:{type:`static`,text:String(s).slice(0,40)}}),n.push({key:`image`,label:`Image`,required:!0,control:{type:`code`,text:Tf(e)}});for(let[e,t]of Object.entries(a))e!==`messages`&&n.push({key:e,label:e,control:{type:`code`,text:typeof t==`object`?JSON.stringify(t):String(t)}})}catch(e){n.push({key:`error`,label:`Error`,required:!0,control:{type:`static`,text:e instanceof Error?e.message:String(e)}})}return n}function Zp({versions:e,onClose:t,onRestore:n}){return(0,$.jsx)(b,{title:`Restore connection`,onClose:t,children:(0,$.jsxs)(`div`,{className:`version-list`,children:[e.length===0&&(0,$.jsx)(`p`,{className:`note`,children:`No versions of this connection yet.`}),e.map((e,t)=>(0,$.jsxs)(`div`,{className:`version-row`,children:[(0,$.jsxs)(`span`,{className:`version-when`,children:[hm(e.at),`, `,mm(e.reason)]}),(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>n(e),children:`Restore`})]},`${e.at}-${t}`))]})})}var Qp={checking:`Checking…`,connected:`Connected`,error:`Error`},$p={untested:`Not tested`,connected:`Connected`,"key-needed":`Key needed`,unreachable:`Unreachable`};function em(e,t){let n=L().CONNECTION_TYPES[e.type];if(n?.local||n?.tests===!1)return null;let r=(e,t)=>({kind:e,label:$p[e],title:t?`${$p[e]} — ${t}`:$p[e]});return!n?.keyless&&!e.key?r(`key-needed`,`no key is set`):!t||t.phase===`checking`?r(`untested`):t.phase===`error`?r(`unreachable`,t.lines[t.lines.length-1]):r(`connected`)}function tm(e){let t=L().CONNECTION_TYPES[e.type];return t?.local||t?.tests===!1?!1:t?.keyless?!0:!!e.key}function nm(e){if(!e.length)return;let t=qf(e[0]);return e.every(e=>qf(e)===t)?e[0]:void 0}var rm=(e,t)=>e.url.trim()||t?.url||`the lab's Ollama`;function im(e,t){let n=Object.fromEntries((t?.settings??[]).map(t=>[t.key,String(e[t.key]??``)]));if(`testPath`in n&&!n.testPath.trim()){let r=t?.templates?.find(t=>sm(t.settings.url,e.url));r?.settings.testPath&&(n.testPath=r.settings.testPath)}return n}function am(){return Ot(!0)?(0,$.jsxs)(`span`,{className:`loading-status`,role:`status`,children:[(0,$.jsx)(F,{}),`Checking…`]}):null}function om({test:e,onClose:t}){return(0,$.jsx)(ut,{title:`Test connection`,sections:[{key:`result`,rows:[{key:`time`,label:`Time`,required:!0,control:{type:`static`,text:e.ms==null?`—`:cm(e.ms)}},{key:`result`,label:`Result`,required:!0,control:{type:`textarea`,value:e.lines.join(`
|
|
13
|
-
`)}}]}],onClose:t})}function sm(e,t){let n=e=>{let t=String(e??``).trim();if(!t)return``;try{return new URL(/^https?:\/\//.test(t)?t:`https://${t}`).origin}catch{return``}},r=n(e);return!!r&&r===n(t)}var cm=e=>e<1e3?`${e} ms`:`${(e/1e3).toFixed(1)}s`;function lm(e,t,n){if(!t.length)return{type:`text`,value:e,placeholder:`model name`,onChange:n};let r=e&&!t.includes(e)?[e,...t]:[...t];return{type:`select`,value:e,onChange:n,options:[...e?[]:[{value:``,label:`Pick a model`}],...r.map(e=>({value:e,label:e}))]}}function um(e){return L().CONNECTION_TYPES[e]?.settings.filter(e=>e.scope===`connection`).map(e=>e.key)??[]}var dm=()=>`p${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`,fm=(e,t)=>L().uniqueSlug(L().slugOf(e),new Set(L().withSlugs(t).map(e=>e.slug))),pm=e=>({id:dm(),name:`New connection`,slug:fm(`New connection`,e),url:``,model:``,key:``,nPredict:``,maxTokens:``,type:`ollama`}),mm=e=>e===`run`?`before a run`:e===`restore`?`before a restore`:`after editing`,hm=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},gm=[];function _m(e,t){let n=Z(),[r,i]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(t===null)return;let r=!0,a=$n(n);return a.runDataset(e).then(n=>{if(n){r&&i({run:e,cases:L().upgradeDatasetBody(n).cases,current:!1});return}return a.dataset(t).then(t=>{r&&i({run:e,cases:L().upgradeDatasetBody(t.body).cases,current:!0})}).catch(()=>{})}).catch(()=>{}),()=>{r=!1}},[n,e,t]);let a=t!==null&&r?.run===e?r:null;return{cases:a?a.cases:gm,current:a?.current??!1}}var vm={};function ym(e){let t=Z(),[n,r]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let n=!0;return t.runGroups(e).then(t=>{if(!n)return;let i={};for(let[e,n]of Object.entries(t??{}))i[e]=L().upgradeDatasetBody(n);r({run:e,groups:i})}).catch(()=>{}),()=>{n=!1}},[t,e]),n?.run===e?n.groups:vm}var bm=(e,t)=>`${L().targetLetter(t)} ${e.scenarios[t]?.name??``}`.trim(),xm=e=>e?`${e.passed}/${e.ran}`:(0,$.jsx)(`span`,{className:`note`,children:`n/a`});function Sm({id:e,view:t,pinned:n}){let r=sa(t),i=t.evals.flatMap((e,n)=>{let i=r.rows[n];return[{kind:`group`,key:e.id,name:i?.name??``,verdict:(i?.cells??[]).map(e=>e.pass)},...pa(t,e.id).map(t=>({kind:`metric`,key:`${e.id}:${t.key}`,label:t.label,cells:t.cells}))]});return(0,$.jsx)(`div`,{className:`scrollx`,style:{"--scenarios":t.scenarios.length},children:(0,$.jsx)(J,{className:`egtable recorded`,label:`Evals Summary`,rows:i,rowKey:e=>e.key,defaultSort:null,pinned:n,rowProps:e=>e.kind===`group`?{className:`eg-group`,"data-group":e.key}:{className:`eg-metric`},columns:[{key:`eval`,header:`Eval`,label:``,role:`title`,sort:null,className:`col-eg`,cell:e=>e.kind===`group`?(0,$.jsx)(`span`,{className:`eg-name`,children:e.name}):(0,$.jsx)(`span`,{className:`eg-metric-name`,children:e.label})},...t.scenarios.map((e,n)=>({key:`t-${n}`,header:bm(t,n),label:bm(t,n),sort:null,cell:e=>e.kind===`group`?e.verdict[n]==null?(0,$.jsx)(`span`,{className:`eg-none`,children:`—`}):(0,$.jsx)(_e,{pass:e.verdict[n]}):xm(e.cells[n])}))]})})}function Cm({view:e,x:t,evalId:n,onClose:r}){let i=e.items[t]??e.results[t]?.name??`Call`;return(0,$.jsx)(b,{title:i,wide:!0,onClose:r,children:(0,$.jsx)(`div`,{className:`rec-compare`,style:{"--scenarios":e.scenarios.length},children:e.scenarios.map((r,i)=>{let a=ua(e.results[t]?.scenarios?.[i]?.res),o=n?da(e,t,i,n):[];return(0,$.jsxs)(`div`,{className:`rec-side`,children:[(0,$.jsx)(`h3`,{className:`rec-side-title`,children:bm(e,i)}),(0,$.jsx)(`pre`,{className:`raw`,children:a??`(no reply)`}),o.length>0&&(0,$.jsx)(`ul`,{className:`rec-checks`,"aria-label":`${bm(e,i)} checks`,children:o.map((e,t)=>(0,$.jsxs)(`li`,{children:[(0,$.jsx)(`span`,{className:`eval-name`,children:e.label}),(0,$.jsx)(_e,{pass:e.pass})]},t))})]},r.id)})})})}function wm(e){let t=(e.metrics??[]).filter(e=>e.weight!==0);return{wanted:t.filter(e=>!e.not&&(e.type===`contains-all`||e.type===`contains-any`)).flatMap(e=>L().metricLines(e.values)),forbidden:t.filter(e=>e.not&&e.type===`contains`).map(e=>({value:String(e.value??``),except:L().metricLines(e.except)}))}}var Tm=e=>e==null?`—`:Pi(e);function Em(e,t){return t.flatMap((t,n)=>{let r=t.replays?[]:e?.scenarios?.[n]?.res?.transcript||[];return r.filter(e=>e.sent).map(e=>({...e,target:t.name,stages:r.length,at:n}))})}function Dm(e){let t=e.trim();if(!/^[[{]/.test(t))return null;try{return{value:JSON.parse(t)}}catch{return null}}function Om({text:e}){let t=Dm(e);if(t)return(0,$.jsx)(c,{value:t.value});let n=/^([A-Z]+ \S+)\n\n([\s\S]*)$/.exec(e),r=n?Dm(n[2]):null;return n&&r?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`pre`,{className:`tx-line`,children:n[1]}),(0,$.jsx)(c,{value:r.value})]}):(0,$.jsx)(`pre`,{className:`tx-text`,children:e||`(empty)`})}function km({label:e,text:t,bad:n}){return(0,$.jsxs)(`div`,{className:`tx-part`,children:[(0,$.jsx)(`span`,{className:`tx-label`,children:e}),n?(0,$.jsx)(`pre`,{className:`tx-text err`,children:t}):(0,$.jsx)(Om,{text:t})]})}function Am({stages:e,graders:t}){if(!e.length&&!t.length)return null;let n=[...new Set([...e.map(e=>e.at),...t.map(e=>e.at)])].sort((e,t)=>e-t),r=e=>[e.target,e.stages>1?`job ${e.n}`:``,Tm(e.ms)].filter(Boolean).join(`, `);return(0,$.jsx)(`div`,{className:`transcript`,children:n.flatMap(n=>[...e.filter(e=>e.at===n).map(e=>{let t=e.body??e.said??e.got;return(0,$.jsxs)(`section`,{className:`tx-block`,children:[(0,$.jsx)(`h4`,{className:`tx-head`,children:r(e)}),(0,$.jsx)(km,{label:`Sent`,text:e.sent??``}),t!=null&&(e.body!=null||!e.error)&&(0,$.jsx)(km,{label:`Returned`,text:t}),e.error&&(0,$.jsx)(km,{label:`Error`,text:e.error,bad:!0})]},`s-${n}-${e.n}`)}),...t.filter(e=>e.at===n).map(e=>(0,$.jsxs)(`section`,{className:`tx-block`,id:e.id,tabIndex:-1,children:[(0,$.jsx)(`h4`,{className:`tx-head`,children:e.ms==null?e.head:`${e.head}, ${Tm(e.ms)}`}),e.calls.map((e,t)=>(0,$.jsxs)(`div`,{className:`tx-call`,children:[(0,$.jsx)(km,{label:`Sent`,text:e.sent}),e.error==null?(0,$.jsx)(km,{label:`Returned`,text:e.got??``}):(0,$.jsx)(km,{label:`Error`,text:e.error,bad:!0})]},t))]},e.id))])})}function jm({text:e,kind:t}){return(0,$.jsx)(`span`,{className:`term${t?` ${t}`:``}`,children:e})}function Mm({res:e,kase:t}){let n=e?.dropped||[];if(!n.length)return null;let r=e=>t?wm(t).wanted.some(t=>L().termIn([e],t)):!1;return(0,$.jsxs)(`details`,{className:`dropped`,children:[(0,$.jsxs)(`summary`,{children:[`Dropped `,n.length]}),n.map((e,t)=>(0,$.jsxs)(`div`,{className:`droppedrow`,children:[(0,$.jsx)(jm,{text:e.item,kind:`no`}),(0,$.jsxs)(`span`,{className:`note`,children:[e.by,r(e.item)&&(0,$.jsx)(`b`,{className:`fault`,children:`, wanted`})]})]},t))]})}function Nm({kase:e}){return(0,$.jsx)($.Fragment,{children:(e.metrics??[]).map((e,t)=>(0,$.jsx)(`div`,{className:`wants${e.weight===0?` watched`:``}`,children:Ra(e)},t))})}var Pm=e=>e?.transcript?.at(-1)?.kind===`text`;function Fm(e){let t=e.filteredBy,n=new Set((e?.transcript||[]).map(e=>e.n)).size;return[`${L().FILTER_STAGE_LABEL[t.stage]} filter`,n>1?`job ${t.job}`:``].filter(Boolean).join(`, `)}function Im({res:e}){let t=e?.filteredBy;return t&&!t.rejected?(0,$.jsxs)(`div`,{className:`meta`,children:[`Emptied by `,t.filter,`, `,Fm(e)]}):null}function Lm({res:e}){let t=e?.filteredBy;return t?.rejected?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`span`,{className:`err`,children:[`Discarded by `,t.filter]}),(0,$.jsx)(`div`,{className:`meta`,children:Fm(e)})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`err`,children:e?.error}),(0,$.jsx)(Im,{res:e})]})}function Rm({res:e}){return e?.error?(0,$.jsx)(Lm,{res:e}):Pm(e)?(0,$.jsx)(`pre`,{children:e?.transcript?.at(-1)?.got||`(empty)`}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`chips`,children:(e?.terms||[]).map((e,t)=>(0,$.jsx)(jm,{text:String(e)},t))}),(0,$.jsx)(Mm,{res:e,kase:null}),(0,$.jsxs)(`div`,{className:`meta`,children:[(e?.terms||[]).length,` items`]}),(0,$.jsx)(Im,{res:e})]})}function zm({res:e}){if(e?.error)return(0,$.jsx)(Lm,{res:e});let t=e?.transcript?.at(-1)?.got??e?.raw??``;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`pre`,{children:t||`(empty)`}),!Pm(e)&&(0,$.jsxs)(`div`,{className:`meta`,children:[`read as `,(e?.terms||[]).length,` items`]}),(0,$.jsx)(Im,{res:e})]})}function Bm({tab:e,undo:t}){let n=Z(),r=Ye(),i=t??r,{setShow:a,openRun:o,closeRun:s}=ci(),{openCaseEditor:c}=Bo(),[l,f]=(0,X.useState)(null),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(null),[v,y]=(0,X.useState)(new Set),[b,x]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(!b)return;let e=document.getElementById(b);if(e){try{e.focus({preventScroll:!0,focusVisible:!0})}catch{e.focus()}e.scrollIntoView?.({block:`nearest`,behavior:`smooth`}),x(null)}},[b,v]);let[S,w]=(0,X.useState)(!1),T=uo(),[D,O]=(0,X.useState)(null),[k,A]=(0,X.useState)(null),[j,N]=(0,X.useState)(0),[P,I]=(0,X.useState)(null),[R,z]=(0,X.useState)(null),ee=hr();(0,X.useEffect)(()=>{let t=!0,r=!1,i,a=async()=>{try{let o=await n.run(e.id);if(!t)return;r=!0,f(o),A(null),qi(o.status)||(i=setTimeout(()=>void a(),1e3))}catch(e){if(!t)return;r?i=setTimeout(()=>void a(),1e3):A(e instanceof mn?e.message:`Run not loaded: server unreachable.`)}};return a(),()=>{t=!1,i&&clearTimeout(i)}},[n,e.id,j]);let V=(0,X.useMemo)(()=>l?_a(l):null,[l]),H=V?L().evalsDataset(V.snapshot)?.id??null:null,te=V?ca(V):[],U=te.some(Boolean),W=la(te),ne=_r(U?H:null),G=_m(e.id,H),re=ym(e.id),ie=(0,X.useMemo)(()=>new Map(G.cases.map(e=>[L().caseItem(e),e])),[G.cases]),ae=(0,X.useCallback)(async()=>{I(null);try{let{run:t}=await n.rerunRun(e.id);o(t.id,{at:t.submittedAt,from:e.from}),i.offer({label:tf(t),restore:()=>{nf(n,t.id),s(t.id)}})}catch(e){I(`Not re-run: ${e instanceof Error?e.message:`server unreachable`}.`)}},[n,e.id,e.from,o,s,i]),K=(0,X.useCallback)(async()=>{h(!0);try{await n.cancel(e.id)}catch{}h(!1)},[n,e.id]);if(!V)return(0,$.jsx)(E,{id:`run-${e.id}`,title:Ti(e.at)||`Run`,children:(0,$.jsx)(C,{label:`Run`,error:k,onRetry:()=>{A(null),N(e=>e+1)}})});let q=V.progress,oe=q.n??q.total??0,se=!qi(V.status),ce=q.total&&oe!=null&&se?Math.round(oe/q.total*100):null,ue=Ha(V,G.cases),de=V.scenarios.map((e,t)=>Wa(V,G.cases,t)),fe=Aa(V),pe=(e,t,n)=>{let r=new Set(e);r.has(t)?r.delete(t):r.add(t),n(r)},me=async(e,t,n)=>{let r=Math.max(0,V.scenarios.findIndex((t,n)=>ea(V,e,n))),i=(t.scenarios??[])[r]?.res;i&&await Ft(za(V.snapshot,n,i,r))&&(w(!0),setTimeout(()=>w(!1),1600))},he=async()=>{let e=ue.map(e=>za(V.snapshot,e.kase,e.res,e.scenarioIndex)).join(`
|
|
14
|
-
|
|
15
|
-
`+`-`.repeat(60)+`
|
|
16
|
-
|
|
17
|
-
`);await Ft(e)&&(w(!0),setTimeout(()=>w(!1),1600))},ge=[T({tab:`results`,id:e.id}),...ue.length?[{label:`Copy all failures`,icon:p,onSelect:()=>void he()}]:[],...l&&ef(l)?[{label:`Re-run`,icon:Wn,onSelect:()=>void ae()}]:[]],_e={label:`Show`,value:e.show,onChange:t=>a(e.id,t),options:[{value:`all`,label:`All`},{value:`failed`,label:`Failed`}]},ve=!!H,ye=V.evals.find(e=>L().casesRef(e))?.id??null,be=!!(V.content&&L().CONTENT_TYPES[V.content.type]?.inline),xe=V.scenarios.map((e,t)=>U?bm(V,t):e.name),Ce=xe.map((e,t)=>({name:e,replays:!!te[t]})),we=ve&&!U,Te=(e,t)=>{let n=V.evals.find(t=>t.id===e);return n?ha(n,V.results[t]?.name,re,G.cases,H):[]},Ee=(0,$.jsxs)(`tr`,{className:`scenstats`,children:[(0,$.jsx)(`td`,{className:`scenstats-label`,children:`Statistics`}),we&&(0,$.jsx)(`td`,{className:`scenstats-blank`}),V.scenarios.map((e,t)=>(0,$.jsx)(`td`,{className:`scenstat`,"data-label":xe[t],children:(0,$.jsx)(pi,{dense:!0,label:`${e.name} statistics`,...Da(V,t)})},e.id))]}),De=(e,t)=>{let n=ne?.doc?.body;if(!H||!n||W<0)return;let{body:r,taken:a}=L().takeAsExpected(n,{[e]:ua(V.results[t]?.scenarios?.[W]?.res)});if(!a.length){I(`Not taken: ${e} has no Target B reply to take.`);return}I(null),ee.edit(H,()=>r),i.offer({label:`Took ${e} as expected`,restore:()=>ee.edit(H,()=>n)})},Oe=(t,n,r,i)=>`run-${e.id}-grader-${t}-${n}-${r}-${i}`,ke=e=>V.scenarios.flatMap((t,n)=>(V.outcomes[n]??[]).filter(e=>!e.whole).flatMap(t=>{let r=t.items[e];if(!r||L().isSkipped(r)||!r.metrics?.length)return[];let i=ga(r.metrics,Te(t.id,e));return r.metrics.flatMap((r,a)=>r.calls?.length?[{id:Oe(e,n,t.id,a),at:n,head:[`${r.label}${i[a]?` ${i[a]}`:``}`,xe[n]??``].filter(Boolean).join(`, `),ms:r.asked??null,calls:r.calls}]:[])})),Ae=(e,t,n,r)=>{v.has(e)||y(new Set(v).add(e)),x(Oe(e,t,n,r))},je=e=>{let t=V.results[e]?.name;return t?ie.get(t):void 0},Me=t=>{let r=V.results[t],i=je(t),a=!!r&&!r.unrun&&qi(V.status),o=[];if((Em(r,Ce).length||ke(t).length)&&o.push(v.has(t)?{label:`Hide details`,icon:u,onSelect:()=>pe(v,t,y)}:{label:`Show details`,icon:le,onSelect:()=>pe(v,t,y)}),a&&r?.name&&i&&o.push({label:`Edit case`,icon:M.edit,onSelect:()=>H&&c(r.name,{dataset:H,resultFor:e=>V.results[t]?.scenarios?.[e]?.res??null,scenarioCount:V.scenarios.length,files:V.results.filter(e=>e.kind!==`text`).map(e=>e.name??``)})}),a&&U&&W>=0&&r?.name){let e=r.name;o.push({label:`Take B as expected`,icon:B,onSelect:()=>De(e,t)})}return a&&V.id&&o.push({label:`Re-run row`,icon:Bt,onSelect:()=>void n.rerun(e.id,t).then(e=>f(e.run)).catch(()=>{})}),a&&i&&Vm(V,t)&&o.push({label:`Copy as AI prompt`,icon:p,onSelect:()=>void me(t,r,i)}),o};return(0,$.jsxs)(`div`,{className:`runview`,children:[(0,$.jsxs)(E,{id:`run-${e.id}`,title:V.name||Ti(e.at),actions:ge,children:[(0,$.jsxs)(`div`,{className:`runhead`,children:[fe&&(0,$.jsxs)(`span`,{className:`note run-queue`,children:[(0,$.jsx)(`span`,{className:`run-state`,children:fe.state}),fe.detail&&(0,$.jsx)(`span`,{className:`run-item`,children:fe.detail})]}),se&&(0,$.jsxs)(`button`,{type:`button`,className:`ghost stop-btn`,disabled:m,onClick:()=>void K(),children:[m?(0,$.jsx)(F,{}):(0,$.jsx)(_t,{size:14,"aria-hidden":`true`}),`Stop`]})]}),se&&(0,$.jsx)(`div`,{className:`rrbar`,children:ce==null?(0,$.jsx)(`span`,{className:`rrprogress`,children:`Waiting`}):(0,$.jsxs)(`div`,{className:`rrmeter`,role:`progressbar`,"aria-valuenow":ce,"aria-valuemin":0,"aria-valuemax":100,children:[(0,$.jsx)(`div`,{className:`rrbarfill`,style:{width:`${ce}%`}}),(0,$.jsxs)(`span`,{className:`rrpct`,style:{"--pct":`${ce}%`},children:[ce,`%`]})]})}),l?.rerunOf&&(0,$.jsxs)(`p`,{className:`note rrorigin`,children:[`Re-run of`,` `,l.rerunOfAt?(0,$.jsx)(`a`,{href:`#`,onClick:t=>{t.preventDefault(),o(l.rerunOf,{at:l.rerunOfAt,from:e.from})},children:Ti(l.rerunOfAt)}):`a cleared run`]}),V.error&&(0,$.jsx)(`p`,{className:`note bad rrstatus`,role:`status`,children:V.error}),P&&(0,$.jsx)(`p`,{className:`note bad rrstatus`,role:`status`,children:P}),(0,$.jsx)(`div`,{id:`run-${e.id}-stats`,className:`runstats`,children:(0,$.jsx)(pi,{label:`Run Statistics`,...Ta(V)})}),S&&(0,$.jsx)(`p`,{className:`note`,role:`status`,children:`Copied to clipboard.`})]}),U?(0,$.jsx)(E,{id:`run-${e.id}-evals`,title:`Evals Summary`,children:(0,$.jsx)(Sm,{id:`run-${e.id}-evals-t`,view:V,pinned:Ee})}):(0,$.jsx)(Um,{id:`run-${e.id}-evals`,summary:sa(V),scenarios:V.scenarios,split:we,pinned:Ee,onScenario:O}),(0,$.jsxs)(E,{id:`run-${e.id}-results`,title:`Results`,children:[(0,$.jsx)(d,{noun:`results`,filters:[],quick:_e}),G.current&&(0,$.jsx)(`p`,{className:`note`,children:`Graded before the lab kept a copy of its dataset: the expectations are the dataset as it is now.`}),(0,$.jsx)(`div`,{className:`scrollx`,style:{"--scenarios":V.scenarios.length},children:(0,$.jsx)(J,{className:[we?`graded`:``,U?`recorded`:``,`rrtable`].filter(Boolean).join(` `),defaultSort:null,label:`Results`,rows:V.items.map((e,t)=>t),rowKey:e=>`${V.items[e]}-${e}`,pinned:de.some(e=>e.length>0)&&H&&(0,$.jsx)(Hm,{from:Ti(e.at)||V.name,datasetId:H,failing:de,scenarios:V.scenarios,heads:xe,items:V.items.length,graded:we}),rowProps:t=>({"data-item":t,className:v.has(t)?`hasdetail`:void 0,hidden:e.show===`failed`&&!Vm(V,t)}),after:t=>v.has(t)&&(0,$.jsx)(`tr`,{className:`rrdetail`,"data-detail":t,hidden:e.show===`failed`&&!Vm(V,t),children:(0,$.jsx)(`td`,{colSpan:1+ +!!we+V.scenarios.length,children:(0,$.jsxs)(`div`,{className:`rrdetail-panel`,children:[(0,$.jsx)(`button`,{type:`button`,className:`icon-btn rrdetail-x`,"aria-label":`Hide details`,onClick:()=>pe(v,t,y),children:(0,$.jsx)(Se,{size:16,"aria-hidden":`true`})}),(0,$.jsx)(Am,{stages:Em(V.results[t],Ce),graders:ke(t)})]})})}),columns:[{key:`item`,header:be?`Text`:`Item`,label:``,className:`col-item`,sort:e=>V.items[e]||``,cell:e=>{let t=V.results[e],n=V.items[e];return(0,$.jsxs)($.Fragment,{children:[t?.name&&!be&&ko(t.name)?(0,$.jsx)(`button`,{type:`button`,className:`thumb`,"aria-label":`Open ${t.name}`,onClick:()=>_(t.name),children:(0,$.jsx)(`img`,{src:Ma(V,t.name),alt:``,loading:`lazy`,"data-name":t.name})}):null,(0,$.jsxs)(`div`,{className:`rritem`,children:[U&&t?.name?(0,$.jsx)(`button`,{type:`button`,className:`rrcall`,onClick:()=>z(e),children:n||``}):(0,$.jsx)(`div`,{className:`meta`,children:n||``}),(0,$.jsx)(Y,{actions:Me(e),label:`${n||`row`} actions`})]})]})}},...we?[{key:`expected`,header:`Expected`,className:`col-expected`,sort:e=>{let t=je(e);return t&&!t.todo?t.metrics?.length??0:null},cell:e=>{let t=je(e);return V.results[e]?t&&!t.todo?(0,$.jsx)(Nm,{kase:t}):(0,$.jsx)(`span`,{className:`note`,children:`n/a`}):``}}]:[],...V.scenarios.map((e,t)=>({key:`scenario-${t}`,header:xe[t]??e.name,label:xe[t]??e.name,onHeader:()=>O(t),cell:e=>(0,$.jsx)(Wm,{item:V.results[e],i:t,readings:(V.outcomes[t]??[]).filter(e=>!e.whole).map(n=>({label:n.label,dataset:n.id===ye,score:n.items[e]??null,metrics:Te(n.id,e),open:r=>Ae(e,t,n.id,r)}))})}))]})})]}),D!=null&&(0,$.jsx)(It,{run:V.snapshot,i:D,onClose:()=>O(null)}),R!=null&&(0,$.jsx)(Cm,{view:V,x:R,evalId:ye,onClose:()=>z(null)}),g&&(0,$.jsx)(Ym,{src:Na(V,g),name:g,onClose:()=>_(null)})]})}var Vm=(e,t)=>{let n=e.results[t];return!!n&&(!!n.unrun||(n.scenarios??[]).some((n,r)=>ea(e,t,r)||!!n?.res?.error))};function Hm({from:e,datasetId:t,failing:n,scenarios:r,heads:i,items:a,graded:o}){let{showCases:s}=ai(),{list:c}=gr(),l=c!==null&&!c.some(e=>e.id===t),u=r.length>1;return(0,$.jsxs)(`tr`,{className:`reasons`,children:[(0,$.jsx)(`td`,{className:`scenstats-label`,children:`Reasons`}),o&&(0,$.jsx)(`td`,{className:`scenstats-blank`}),r.map((r,o)=>{let c=r.name,d=n[o]??[];return(0,$.jsx)(`td`,{className:`reasons-cell`,"data-label":i[o]??c,children:d.length===0?(0,$.jsx)(`span`,{className:`reasons-none`,children:`No failures`}):(0,$.jsx)(`ul`,{className:`reasons-list`,"aria-label":`${c} reasons`,children:d.map(n=>{let r=n.files.length,i=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`reason-n`,children:r}),(0,$.jsxs)(`span`,{className:`reason-t`,children:[n.label,n.note&&(0,$.jsxs)(`span`,{className:`reason-note`,children:[` `,n.note]})]})]});return(0,$.jsx)(`li`,{"data-group":n.key,style:{"--share":`${Math.round(r/Math.max(a,1)*100)}%`},children:l?(0,$.jsx)(`span`,{className:`reason`,children:i}):(0,$.jsx)(`a`,{className:`reason`,href:`#/library/datasets`,title:`${n.label}${n.note?` (${n.note})`:``}: open ${Ei(r,`case`)} in the Library`,"aria-label":`${n.label}: open ${Ei(r,`case`)} in the Library`,onClick:r=>{r.preventDefault(),s(t,n.files,`${e}${u?`, ${c}`:``}, ${n.label}`)},children:i})},n.key)})})},r.id)})]})}function Um({id:e,summary:t,scenarios:n,split:r,pinned:i,onScenario:a}){let o=[...t.rows.map(e=>({kind:`group`,group:e})),...t.overall?[{kind:`overall`,...t.overall}]:[]],s=(e,t)=>e==null&&t==null?(0,$.jsx)(`span`,{className:`eg-none`,children:`—`}):(0,$.jsxs)(`span`,{className:`eg-cell`,children:[e!=null&&(0,$.jsx)(_e,{pass:e}),t!=null&&(0,$.jsxs)(`span`,{className:`eg-pct`,children:[t,`%`]})]});return(0,$.jsx)(E,{id:e,title:`Evals Summary`,children:(0,$.jsx)(`div`,{className:`scrollx`,style:{"--scenarios":n.length},children:(0,$.jsx)(J,{className:r?`egtable split`:`egtable`,label:`Evals Summary`,rows:o,rowKey:e=>e.kind===`group`?e.group.key:`overall`,defaultSort:null,pinned:i,rowProps:e=>e.kind===`overall`?{className:`eg-overall`,"data-group":`overall`}:{"data-group":e.group.key},columns:[{key:`group`,header:`Eval group`,label:``,role:`title`,sort:null,className:`col-eg`,cell:e=>e.kind===`group`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`eg-name`,children:e.group.name}),!r&&e.group.version&&(0,$.jsxs)(`span`,{className:`eg-ver`,children:[` `,e.group.version]})]}):(0,$.jsxs)(`span`,{className:`eg-overall-name`,children:[(0,$.jsx)(`span`,{className:`eg-name`,children:`Overall`}),` `,(0,$.jsx)(`span`,{className:`eg-rule`,children:e.label})]})},...r?[{key:`version`,header:`Version`,label:`Version`,sort:null,className:`col-egver`,cell:e=>e.kind===`group`?e.group.version??``:``}]:[],...n.map((e,t)=>({key:`scenario-${t}`,header:e.name,label:e.name,onHeader:()=>a(t),cell:e=>{if(e.kind===`overall`)return s(e.pass[t]??null);let n=e.group.cells[t];return n?n.skipped?(0,$.jsx)(`span`,{className:`eg-none`,children:`Skipped`}):s(n.pass,n.pct):null}}))]})})})}function Wm({item:e,i:t,readings:n}){let r=e?.scenarios?.[t]?.res;if(e?.unrun)return(0,$.jsx)(`span`,{className:`err`,children:e.unrun});if(!r)return(0,$.jsx)(`span`,{className:`spin`,"aria-hidden":`true`});let i=n.some(e=>e.score&&!L().isSkipped(e.score)&&e.score.metrics?.length),a=n.length===1&&L().isSkipped(n[0].score),o=(0,$.jsxs)($.Fragment,{children:[(n.length>1||!i&&n.some(e=>e.score))&&(0,$.jsx)(Jm,{readings:n}),a&&n.length===1&&(0,$.jsx)(`span`,{className:`verdict skipped`,children:`Skipped`}),(0,$.jsx)(Gm,{readings:n})]});return(0,$.jsxs)($.Fragment,{children:[o,e?.kind===`text`?(0,$.jsx)(zm,{res:r}):(0,$.jsx)(Rm,{res:r})]})}function Gm({readings:e}){let t=e.flatMap(e=>e.score&&!L().isSkipped(e.score)&&e.score.metrics?.length?[{...e,score:e.score}]:[]);return t.length?(0,$.jsx)($.Fragment,{children:t.map((e,t)=>{let n=ga(e.score.metrics,e.metrics),r=e.score.metrics.map((t,r)=>({m:t,want:n[r]??null,open:t.calls?.length?()=>e.open(r):null})),i=r.filter(({m:e})=>e.weight!==0),a=r.filter(({m:e})=>e.weight===0);return(0,$.jsxs)(`div`,{className:`metric-readings`,children:[(0,$.jsx)(`span`,{className:`verdict ${e.score.pass?`pass`:`fail`}`,children:e.score.pass?`Pass`:`Fail`}),e.score.score!=null&&(0,$.jsx)(`span`,{className:`metric-score`,children:qm(e.score.score,!!e.score.points)}),i.length>0&&(0,$.jsx)(Km,{lines:i}),a.length>0&&(0,$.jsxs)(`div`,{className:`watched`,children:[(0,$.jsx)(`b`,{children:`Watch`}),(0,$.jsx)(Km,{lines:a})]})]},t)})}):null}function Km({lines:e}){return(0,$.jsx)(`ul`,{children:e.map(({m:e,want:t,open:n},r)=>{let i=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`eval-name`,children:e.label}),t&&(0,$.jsxs)($.Fragment,{children:[` `,(0,$.jsx)(`span`,{className:`metric-want`,children:t})]})]});return(0,$.jsxs)(`li`,{className:e.pass?`pass`:`fail`,children:[(0,$.jsx)(_e,{pass:e.pass}),n?(0,$.jsx)(`button`,{type:`button`,className:`metric-open`,onClick:n,children:i}):(0,$.jsx)(`span`,{children:i})]},r)})})}var qm=(e,t)=>t?`${Math.round(e*100)/100} points`:`${Math.round(e*100)}%`;function Jm({readings:e}){return(0,$.jsx)(`ul`,{className:`eval-verdicts`,children:e.map((e,t)=>{let n=e.score?L().isSkipped(e.score)?`Skipped`:e.score.pass?`Pass`:`Fail`:null;return n&&(0,$.jsxs)(`li`,{children:[(0,$.jsx)(`span`,{className:`eval-name`,children:e.label}),(0,$.jsx)(`span`,{className:`verdict ${n.toLowerCase()}`,children:n})]},t)})})}function Ym({src:e,name:t,onClose:n}){return(0,$.jsx)(b,{title:t||`Image`,onClose:n,children:(0,$.jsx)(`img`,{className:`lightbox-img`,src:e,alt:t})})}function Xm(){let{tabs:e,focusedId:t,closeRun:n,focusRun:r,goBack:a}=ci(),o=Ye(),s=e.find(e=>e.id===t);return s?(0,$.jsxs)(`div`,{className:`results`,role:`region`,"aria-label":`Open runs`,children:[(0,$.jsxs)(`div`,{className:`results-bar`,children:[(0,$.jsx)(`button`,{type:`button`,className:`ghost icon-btn rrback`,onClick:a,"aria-label":`Back`,children:(0,$.jsx)(i,{size:18,"aria-hidden":`true`})}),(0,$.jsx)(`code`,{className:`rrcode`,children:Ti(s.at)||`…`}),(0,$.jsx)(`div`,{className:`rtabs`,role:`tablist`,"aria-label":`Open runs`,children:e.map(e=>(0,$.jsxs)(`div`,{className:`rtab${e.id===t?` on`:``}`,children:[(0,$.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":e.id===t,className:`rname`,title:Ti(e.at)||`run`,onClick:()=>r(e.id),children:Ti(e.at)||`…`}),(0,$.jsx)(`button`,{type:`button`,className:`rx`,"aria-label":`Close`,onClick:()=>n(e.id),children:(0,$.jsx)(Se,{size:14,"aria-hidden":`true`})})]},e.id))})]}),(0,$.jsx)(Bm,{tab:s,undo:o}),(0,$.jsx)(Vt,{undo:o.undo,onUndo:o.undoNow,onDismiss:o.dismiss})]}):null}function Zm(){let e=hr(),t=(0,X.useSyncExternalStore)(e.subscribe,e.held),n=t.filter(e=>e.sync.state===`conflict`),r=t.filter(e=>e.sync.state===`offline`);return!n.length&&!r.length?null:(0,$.jsxs)($.Fragment,{children:[n.map(t=>(0,$.jsxs)(`div`,{className:`sync bad`,role:`alert`,children:[(0,$.jsxs)(`span`,{children:[t.doc?.name??t.id,` changed in another browser.`]}),(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>void e.resolve(t.id,`theirs`),children:`Use theirs`}),(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>void e.resolve(t.id,`mine`),children:`Keep mine`})]},t.id)),r.map(t=>(0,$.jsxs)(`div`,{className:`sync bad`,role:`status`,children:[(0,$.jsxs)(`span`,{children:[t.doc?.name??t.id,` not saved: `,t.sync.state===`offline`?t.sync.message.replace(/\.$/,``):``,`.`]}),(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>void e.flush(t.id),children:`Retry`})]},t.id))]})}function Qm(){let e=us(),t=(0,X.useSyncExternalStore)(e.subscribe,e.held),n=t.filter(e=>e.sync.state===`conflict`),r=t.filter(e=>e.sync.state===`offline`);return!n.length&&!r.length?null:(0,$.jsxs)($.Fragment,{children:[n.map(t=>(0,$.jsxs)(`div`,{className:`sync bad`,role:`alert`,children:[(0,$.jsxs)(`span`,{children:[t.doc?.name??t.id,` changed in another browser.`]}),(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>void e.resolve(t.id,`theirs`),children:`Use theirs`}),(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>void e.resolve(t.id,`mine`),children:`Keep mine`})]},t.id)),r.map(t=>(0,$.jsxs)(`div`,{className:`sync bad`,role:`status`,children:[(0,$.jsxs)(`span`,{children:[t.doc?.name??t.id,` not saved: `,t.sync.state===`offline`?t.sync.message.replace(/\.$/,``):``,`.`]}),(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>void e.flush(t.id),children:`Retry`})]},t.id))]})}var $m=`promptlab.theme`,eh=typeof matchMedia==`function`?matchMedia(`(prefers-color-scheme: light)`):null;function th(){try{let e=JSON.parse(localStorage.getItem($m)||`null`)?.choice;return e===`light`||e===`dark`?e:null}catch{return null}}var nh=()=>th()??`system`,rh=()=>th()??(eh?.matches?`light`:`dark`),ih=()=>{let e=rh();return document.documentElement.setAttribute(`data-theme`,e),e};ih();function ah(e){try{e===`system`?localStorage.removeItem($m):localStorage.setItem($m,JSON.stringify({choice:e}))}catch{}ih()}function oh(){let[e,t]=(0,X.useState)(nh);return(0,X.useEffect)(()=>{let e=()=>{ih(),t(nh())};return eh?.addEventListener?.(`change`,e),()=>eh?.removeEventListener?.(`change`,e)},[]),[e,e=>{ah(e),t(e)}]}var sh=()=>{let{route:e,rewrite:t}=Mr(location.hash);return t&&history.replaceState(null,``,t),e};function ch(){return(0,$.jsx)(Ue,{children:(0,$.jsx)(mr,{children:(0,$.jsx)(ls,{children:(0,$.jsx)(wr,{children:(0,$.jsx)(si,{children:(0,$.jsx)(ii,{children:(0,$.jsx)(zo,{children:(0,$.jsx)(yp,{children:(0,$.jsx)(co,{children:(0,$.jsx)(lh,{})})})})})})})})})})}function lh(){let[e,t]=(0,X.useState)(sh),n=(0,X.useRef)(e);n.current=e;let{hide:r,tabs:i,focusedId:a,openRun:o,focusRun:s}=ci(),c=(0,X.useRef)(i);c.current=i;let l=ao(),u=Z(),d=Ye();(0,X.useEffect)(()=>{let e=()=>{let e=sh();t(e),e.tab!==`results`&&r()};return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[r]);let f=e.tab===`results`?e.id:null;if((0,X.useEffect)(()=>{if(!f)return;if(c.current.some(e=>e.id===f)){s(f);return}let e=!0;return u.run(f).then(t=>{e&&o(f,{at:t.submittedAt,from:`history`})},t=>{e&&(t instanceof mn&&t.status===404?Ir({tab:`history`}):o(f,{from:`history`}))}),()=>{e=!1}},[f,u,o,s]),(0,X.useEffect)(()=>{let e=n.current;a&&(e.tab!==`results`||e.id!==a)&&Fr({tab:`results`,id:a})},[a]),(0,X.useEffect)(()=>{document.title=l.current?`${l.current.name}, Evals Lab`:`No workspace, Evals Lab`},[l.current]),(0,X.useEffect)(()=>{let e=no();e&&d.offer({label:`Archived ${e.name}`,restore:()=>u.unarchiveWorkspace(e.id).then(()=>{location.assign($a(e.slug))})})},[]),!l.current)return(0,$.jsx)(ph,{ws:l});let p=e.tab===`results`?i.find(t=>t.id===e.id)?.from??`history`:e.tab,m=Ga.find(e=>e.id===p),h=l.current.archived;return(0,$.jsxs)(`div`,{className:`app`,children:[(0,$.jsxs)(`header`,{className:`app-head`,children:[(0,$.jsx)(`h1`,{children:`Evals Lab`}),(0,$.jsx)(hh,{}),(0,$.jsx)(Zm,{}),(0,$.jsx)(Qm,{}),(0,$.jsx)(uh,{}),(0,$.jsx)(Be,{}),(0,$.jsx)(dh,{ws:l})]}),(0,$.jsx)(ft,{}),(0,$.jsx)(Vt,{undo:d.undo,onUndo:d.undoNow,onDismiss:d.dismiss}),h&&(0,$.jsx)(fh,{id:l.current.id}),(0,$.jsx)(R,{label:`Lab`,className:`app-tabs`,tablist:!0,current:p,items:Ga.map(e=>({key:e.id,label:e.label,href:`#/${e.id}`,icon:e.icon,id:`tab-${e.id}`,controls:`panel-${e.id}`}))}),(0,$.jsx)(mh,{tab:m,route:e,readOnly:h})]})}function uh(){let{cancel:e}=bp(),t=xp();return t?(0,$.jsx)(se,{name:t.entry.title,done:t.done,total:t.total,current:t.current,steps:t.entry.steps.map((e,n)=>({title:e.title,done:t.ticks[n]})),onOpen:()=>Fr({tab:`setup`,section:`wizards`,id:t.entry.id}),onCancel:e}):null}function dh({ws:e}){let t=Z(),[n,r]=oh(),[i,a]=(0,X.useState)(!1),o=e.list.filter(e=>!e.archived).map(e=>({id:e.id,slug:e.slug,name:e.name})),s=async e=>{try{let n=await t.createWorkspace(e);n.workspace&&location.assign($a(n.workspace.slug))}catch{}};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Le,{current:e.current?{id:e.current.id,slug:e.current.slug,name:e.current.name}:null,workspaces:o,onSwitch:e.switchTo,onNew:()=>a(!0),onManage:()=>Fr({tab:`setup`,section:`workspaces`,id:null}),theme:n,onTheme:r}),i&&(0,$.jsx)(jp,{onCreate:e=>void s(e),onClose:()=>a(!1)})]})}function fh({id:e}){let t=Z(),[n,r]=(0,X.useState)(!1),i=async()=>{r(!0);try{await t.unarchiveWorkspace(e),location.reload()}catch{r(!1)}};return(0,$.jsxs)(`div`,{className:`ws-archived-bar`,role:`status`,children:[(0,$.jsx)(`span`,{children:`This workspace is archived — read-only until you unarchive it.`}),(0,$.jsxs)(`button`,{type:`button`,className:`ghost`,disabled:n,onClick:()=>void i(),children:[(0,$.jsx)(yn,{size:14,"aria-hidden":`true`}),`Unarchive`]})]})}function ph({ws:e}){let t=ro(e.list);return(0,$.jsxs)(`div`,{className:`app`,children:[(0,$.jsxs)(`header`,{className:`app-head`,children:[(0,$.jsx)(`h1`,{children:`Evals Lab`}),(0,$.jsx)(dh,{ws:e})]}),(0,$.jsxs)(`main`,{className:`ws-gone`,children:[(0,$.jsxs)(`p`,{role:`alert`,children:[`No workspace at `,(0,$.jsxs)(`code`,{children:[`/w/`,e.requestedSlug]}),`.`]}),t&&(0,$.jsxs)(`button`,{type:`button`,onClick:()=>e.switchTo(t.slug),children:[`Open `,t.name]})]})]})}function mh({tab:e,route:t,readOnly:n}){let{focusedId:r}=ci(),i=r?(0,$.jsx)(Xm,{}):e.id===`home`?(0,$.jsx)(Xu,{}):e.id===`runs`?(0,$.jsx)(Jd,{pipelineId:t.tab===`runs`?t.id:null}):e.id===`history`?(0,$.jsx)(cf,{}):t.tab===`library`?(0,$.jsx)(Uu,{section:t.section,id:t.id}):t.tab===`setup`?(0,$.jsx)(Rp,{section:t.section,id:t.id,...t.kind?{kind:t.kind}:{}}):null,a=n&&e.id!==`setup`;return(0,$.jsx)(`main`,{role:`tabpanel`,id:`panel-${e.id}`,"aria-labelledby":`tab-${e.id}`,"data-tab":e.id,inert:a,children:i})}function hh(){let{sync:e,resolve:t}=Qn();return e.state===`offline`?(0,$.jsxs)(`p`,{className:`sync bad`,role:`status`,children:[`Not saved to the server: `,e.message,`. Kept in this browser.`]}):e.state===`conflict`?(0,$.jsxs)(`div`,{className:`sync bad`,role:`alert`,children:[(0,$.jsx)(`span`,{children:`Changed on another device.`}),(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>void t(`theirs`),children:`Use theirs`}),(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>void t(`mine`),children:`Keep mine`})]}):null}var gh=`promptlab.sync`,_h=new Set([`promptlab.workflows`,`promptlab.versions`,gh]),vh=e=>typeof e==`object`&&!!e&&!Array.isArray(e),yh=(e,t)=>{let n=hf[e];return vh(n)&&vh(t)?{...n,...t}:t};function bh({api:e,storage:t,server:n,workspace:r,pause:i=800}){let a=e=>r&&_h.has(e)?`${e}@${r}`:e,o=e=>{try{return t.getItem(a(e))}catch{return null}},s=new Map,c=(e,n)=>{s.delete(e);try{n==null?t.removeItem(a(e)):t.setItem(a(e),JSON.stringify(n))}catch{}s.set(e,n??null)},l=e=>{try{return JSON.parse(o(e)??`null`)}catch{return null}},u=(e,t)=>o(e)===(t==null?null:JSON.stringify(t)),d=n!==null,f=l(gh)??{},p={},m=new Set,h=()=>c(gh,{versions:p,dirty:[...m]}),g=new Set,_=()=>g.forEach(e=>e()),v=d?{state:`saved`}:{state:`local`},y=null,b=null,x=e=>{v=e,_()};if(n){for(let e of _f){let t=n[e];t&&u(e,t.body)?p[e]=t.version:f.dirty?.includes(e)?(p[e]=f.versions?.[e]??0,m.add(e)):t?(p[e]=t.version,c(e,t.body)):(p[e]=0,o(e)!=null&&m.add(e))}h()}async function S(t=!1){if(!d||v.state===`conflict`)return;if(!m.size){v.state===`saving`&&x({state:`saved`});return}let n=[...m],r=Object.fromEntries(n.map(e=>[e,{version:p[e]??0,body:l(e)}]));x({state:`saving`});try{let{versions:i}=await e.writeState(r,t);Object.assign(p,i);for(let e of n)u(e,r[e].body)&&m.delete(e);if(h(),x({state:`saved`}),m.size)return S(t)}catch(e){if(e instanceof mn&&e.status===409){let t=e.body?.stale??{};for(let[e,n]of Object.entries(t))p[e]=n.version;let n=Object.keys(t).filter(e=>!u(e,t[e].body));for(let e of Object.keys(t))n.includes(e)||m.delete(e);return h(),n.length?(C=t,x({state:`conflict`,keys:n})):S()}x({state:`offline`,message:e instanceof Error?e.message:String(e)})}}let C={};function w(e=!1){return y&&=(clearTimeout(y),null),b??=S(e).finally(()=>{b=null}),b}return m.size&&(y=setTimeout(()=>{w()},0)),{get(e){return s.has(e)||s.set(e,yh(e,l(e))),s.get(e)??hf[e]},set(e,t){c(e,t),d&&_f.includes(e)&&(m.add(e),h(),y&&clearTimeout(y),y=setTimeout(()=>{w()},i)),_()},subscribe(e){return g.add(e),()=>{g.delete(e)}},sync:()=>v,async resolve(e){if(v.state!==`conflict`)return;let t=v.keys;if(e===`theirs`){for(let e of t)c(e,C[e]?.body??null),m.delete(e);h()}C={},x({state:`saved`}),await w()},flush:w,async refresh(){if(!d)return;await w();let{docs:t}=await e.state(),n=!1;for(let e of _f){let r=t[e];!r||m.has(e)||r.version<=(p[e]??0)||(p[e]=r.version,c(e,r.body),n=!0)}n&&(h(),_())}}}var xh=e=>[1,2,3,4,5,6,7,8,9,10].includes(e?.version)||L().fatProfileRef(e),Sh=e=>e?.version===1||e?.version===2;function Ch(e){let t=[...e.get(`promptlab.workflows`).list.map(e=>e.work),...Object.values(e.get(`promptlab.versions`).pipeline??{}).flat().map(e=>e.doc)].filter(Sh).map(e=>e?.tests?.type===`graded`?e.tests.dataset?.id:void 0);return[...new Set(t.filter(e=>!!e))]}function wh(e,t={}){let n=L().answersOf(e.get(`promptlab.connections`).list,e.get(`promptlab.connectionProfiles`).list),r={rulesFor:e=>t[e]??null,profileType:e=>n.connection(e)?.type,connectionSplit:n.split},i=e=>L().upgradePipeline(e,r),a=e=>xh(e)||i(e)!==e,o=e.get(`promptlab.workflows`);o.list.some(e=>a(e.work))&&e.set(`promptlab.workflows`,{...o,list:o.list.map(e=>({...e,work:i(e.work)}))});let s=e.get(`promptlab.versions`),c=s.pipeline??{};Object.values(c).some(e=>e.some(e=>a(e.doc)))&&e.set(`promptlab.versions`,{...s,pipeline:Object.fromEntries(Object.entries(c).map(([e,t])=>[e,t.map(e=>({...e,doc:i(e.doc)}))]))})}function Th(e,t){let n=e=>t.list.find(t=>t.fromProfile===e)??null;return{...e,list:e.list.map(e=>L().mergeAnswer(e,n(e.id)))}}function Eh(e,t){let n=L(),r=new Map(e.list.map(e=>[e.id,n.splitProfile(e)])),i=e=>{let{id:t,name:n,fromProfile:i,...a}=r.get(e)?.profile??{};return a},a=[],o=new Set;for(let n of t.list){if(!n.fromProfile){a.push(n);continue}let t=e.list.find(e=>e.id===n.fromProfile);t&&(o.add(n.fromProfile),a.push({id:n.id,name:t.name,fromProfile:n.fromProfile,...n.connection?{connection:n.connection}:{},...i(t.id)}))}for(let t of e.list){let e=r.get(t.id)?.profile;!o.has(t.id)&&e&&a.push(e)}let{list:s,split:c,...l}=e;return{connections:{...l,list:e.list.map(e=>r.get(e.id).connection)},connectionProfiles:{list:a}}}var Dh=e=>Th(e.get(`promptlab.connections`),e.get(`promptlab.connectionProfiles`));function Oh(e,t){let n=e.get(`promptlab.connectionProfiles`),r=Eh(t,n);e.set(`promptlab.connections`,r.connections),JSON.stringify(r.connectionProfiles)!==JSON.stringify(n)&&e.set(`promptlab.connectionProfiles`,r.connectionProfiles)}function kh(e,t){let n=L();if(t)try{let r=JSON.parse(t);Array.isArray(r?.list)&&Oh(e,{list:r.list.map(e=>n.pinReplyTokens(`profile`in e?n.convertProfile(e):e)),at:r.at??``,...r.grader?{grader:r.grader}:{}})}catch{}let r=Dh(e),i=e=>n.splitOllama(`profile`in e?n.convertProfile(e):e);r.list.some(e=>i(e)!==e)&&Oh(e,{...r,list:r.list.map(i)});let a=e.get(`promptlab.connections`),o=L().withSlugs(a.list);o!==a.list&&e.set(`promptlab.connections`,{...a,list:o})}async function Ah(e){let t=document.getElementById(`labstate`)?.textContent;if(t)try{return JSON.parse(t).docs??null}catch{return null}try{return(await e.state()).docs}catch{return null}}function jh(){let e=location.pathname.match(/^\/w\/([^/]+)/);return e?decodeURIComponent(e[1]):null}async function Mh(){L();let e=jh(),t=vn(void 0,e?`/w/${encodeURIComponent(e)}`:``),n=()=>{},r=new Promise(e=>{n=e});if(/^#\/?history\/?$/.test(location.hash)&&t.askQueue({limit:25},r),Gc())try{let e=(await t.config()).microsoft;e&&await Kc(e)}catch{}if(Xc())try{let e=(await t.config()).microsoft;if(e){await Zc(e);return}}catch{}await pn(t),n();let i=await t.workspaces().then(e=>e.workspaces,()=>[]),a=i.find(e=>e.isDefault)?.slug??`default`,o=e?i.find(t=>t.slug===e):i.find(e=>e.isDefault),s=o?{id:o.id,slug:o.slug,name:o.name,archived:o.archived,isDefault:o.isDefault}:null,c={current:s,requestedSlug:e,list:i,switchTo:e=>{location.assign($a(e))}};document.title=s?`${s.name}, Evals Lab`:`No workspace, Evals Lab`;let l=await Ah(t),u=bh({api:t,storage:localStorage,server:l,workspace:s?.slug??a});kh(u,l||localStorage.getItem(`promptlab.connections`)?null:localStorage.getItem(`promptlab.profiles`));let d={};if(Ch(u).length)try{d=(await t.archivedRules()).rules}catch{}wh(u,d),addEventListener(`pagehide`,()=>{u.flush(!0)}),(0,nn.createRoot)(document.getElementById(`root`)).render((0,$.jsx)(X.StrictMode,{children:(0,$.jsx)(Xn.Provider,{value:u,children:(0,$.jsx)(rn.Provider,{value:t,children:(0,$.jsx)(io.Provider,{value:c,children:(0,$.jsx)(ch,{})})})})}))}Mh();
|