evals-lab 0.5.0 → 0.6.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.
@@ -0,0 +1,21 @@
1
+ import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as f,M as p,N as m,O as h,P as g,Q as _,R as v,S as y,T as b,U as x,V as S,W as C,X as w,Y as T,Z as E,_ as D,_t as O,a as k,at as A,b as j,c as M,ct as N,d as P,dt as F,et as I,f as ee,ft as L,g as R,gt as z,h as B,ht as V,i as te,it as H,j as U,k as W,l as ne,lt as re,m as ie,mt as G,nt as ae,o as oe,ot as K,p as se,pt as q,q as J,r as ce,rt as Y,s as le,st as ue,t as X,tt as de,u as fe,ut as Z,v as pe,w as me,x as he,y as ge,z as _e}from"./tokens-Bl8cOqkf.js";var ve=z(),Q=O(),ye=(0,Q.createContext)(null);function be(){let e=(0,Q.useContext)(ye);if(!e)throw Error(`useApi outside an ApiContext: main.tsx mounts one at the root`);return e}var xe=`modulepreload`,Se=function(e){return`/`+e},Ce={},we=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=Se(t,n),t=s(t),t in Ce)return;Ce[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`:xe,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)})},Te={},Ee=new Set,De=e=>`/plugins/${encodeURIComponent(e.id)}/${encodeURIComponent(e.version)}/${e.entry.split(`/`).map(encodeURIComponent).join(`/`)}`;async function Oe(e){if(!Ee.has(e.id))try{let t=await we(()=>import(De(e)),[]);if(typeof t.default!=`function`)throw Error(`its entry exports no register function`);await t.default(K().pluginHost(e.id)),Ee.add(e.id),delete Te[e.id]}catch(t){Te[e.id]=t instanceof Error?t.message:String(t)}}async function ke(e){let t=[];try{t=(await e.plugins()).plugins}catch{return}for(let e of t)await Oe(e)}var Ae=class extends Error{status;body;constructor(e,t,n=null){super(t),this.name=`ApiError`,this.status=e,this.body=n}};function je(e=(...e)=>fetch(...e)){async function t(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 Ae(e.status,r||`HTTP ${e.status}`,n)}return n}async function n(n,r){return t(await e(n,r?.body===void 0?{method:r?.method??`GET`}:{method:r.method??`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r.body),...r.keepalive?{keepalive:!0}:{}}))}let r=e=>({...e,snapshot:K().upgradePipeline(e.snapshot),results:K().upgradeResults(e.results)}),i=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}`:``}`},a=new Map,o=async e=>({...e,runs:await Promise.all(e.runs.map(e=>u(r(e))))}),s=async e=>{let t=await e;return{...t,run:r(t.run)}},c=new Map,l=e=>K().evalsOf(e.snapshot).some(e=>K().isWholeRun(K().EVAL_TYPES[e.type],e)),u=e=>{if(!e.brief||!l(e))return Promise.resolve(e);let t=`${e.status} ${e.progress?.n??0} ${e.finishedAt??``}`,i=c.get(e.id);if(i?.at===t)return i.row;let a=n(`/api/queue/${encodeURIComponent(e.id)}`).then(r,()=>(c.delete(e.id),e));return c.set(e.id,{at:t,row:a}),a};return{config:()=>n(`/api/config`),google:()=>n(`/api/google`),setGoogle:e=>n(`/api/google`,{method:`PUT`,body:e}),setMicrosoft:(e,t)=>n(`/api/microsoft`,{method:`PUT`,body:{clientId:e,tenant:t}}),state:()=>n(`/api/state`),writeState:(e,t=!1)=>n(`/api/state`,{body:{docs:e},keepalive:t}),queue:(e={})=>{let t=i(e),r=a.get(t);return a.delete(t),r??n(t).then(o)},askQueue:(e,t)=>{let r=i(e),s=n(r),c=t.then(()=>s).then(o);c.catch(()=>{}),a.set(r,c)},run:e=>n(`/api/queue/${encodeURIComponent(e)}`).then(r),setComment:(e,t)=>n(`/api/queue/${encodeURIComponent(e)}`,{method:`PATCH`,body:{comment:t}}).then(r),submit:e=>s(n(`/api/queue`,{body:e})),cancel:e=>s(n(`/api/queue/${encodeURIComponent(e)}/cancel`,{body:{}})),resume:e=>s(n(`/api/queue/${encodeURIComponent(e)}/resume`,{body:{}})),rerunRun:e=>s(n(`/api/queue/${encodeURIComponent(e)}/rerun`,{body:{}})),rerun:(e,t)=>s(n(`/api/queue/${encodeURIComponent(e)}/items/${t}`,{body:{}})),rescore:(e,t)=>s(n(`/api/queue/${encodeURIComponent(e)}/rescore/${t}`,{body:{}})),clear:()=>n(`/api/queue`,{method:`DELETE`}),sources:()=>n(`/api/sources`),source:e=>n(`/api/sources/${encodeURIComponent(e)}`),datasets:()=>n(`/api/datasets`),dataset:e=>n(`/api/datasets/${encodeURIComponent(e)}`),archivedRules:()=>n(`/api/datasets/archived-rules`),createDataset:e=>n(`/api/datasets`,{body:e}),renameDataset:(e,t)=>n(`/api/datasets/${encodeURIComponent(e)}`,{method:`PATCH`,body:{name:t}}),saveDataset:(e,t,r)=>n(`/api/datasets/${encodeURIComponent(e)}`,{method:`PUT`,body:{version:t,body:r}}),deleteDataset:e=>n(`/api/datasets/${encodeURIComponent(e)}`,{method:`DELETE`}),restoreDataset:e=>n(`/api/datasets/trash/${encodeURIComponent(e)}/restore`,{body:{}}),exportDatasetUrl:e=>`/api/datasets/${encodeURIComponent(e)}/export`,exportAllDatasetsUrl:()=>`/api/datasets/export`,importDatasets:e=>n(`/api/datasets/import`,{body:e}),runDataset:e=>n(`/api/queue/${encodeURIComponent(e)}/dataset`),prompts:()=>n(`/api/prompts`),prompt:e=>n(`/api/prompts/${encodeURIComponent(e)}`),createPrompt:e=>n(`/api/prompts`,{body:e}),editPrompt:(e,t,r)=>n(`/api/prompts/${encodeURIComponent(e)}`,{method:`PUT`,body:{base:t,...r}}),setDefaultPrompt:e=>n(`/api/prompts/${encodeURIComponent(e)}/default`,{body:{}}),restorePromptVersion:(e,t)=>n(`/api/prompts/${encodeURIComponent(e)}/versions/${t}/restore`,{body:{}}),deletePrompt:e=>n(`/api/prompts/${encodeURIComponent(e)}`,{method:`DELETE`}),restorePrompt:e=>n(`/api/prompts/trash/${encodeURIComponent(e)}/restore`,{body:{}}),createSource:(e,t,r)=>n(`/api/sources`,{body:{name:e,type:t,...r?{config:r}:{}}}),definition:e=>n(`/api/sources/${encodeURIComponent(e)}/definition`),saveDefinition:(e,t,r)=>n(`/api/sources/${encodeURIComponent(e)}/definition`,{method:`PUT`,body:{version:t,body:r}}),renameSource:(e,t)=>n(`/api/sources/${encodeURIComponent(e)}`,{method:`PATCH`,body:{name:t}}),removeSource:e=>n(`/api/sources/${encodeURIComponent(e)}`,{method:`DELETE`}),removeFiles:(e,t)=>n(`/api/sources/${encodeURIComponent(e)}/remove`,{body:{names:t}}),restoreTrash:e=>n(`/api/sources/trash/${encodeURIComponent(e)}/restore`,{body:{}}),copyFiles:(e,t,r,i=!1)=>n(`/api/sources/${encodeURIComponent(e)}/copy`,{body:{from:t,names:r,move:i}}),upload:async(n,r,i)=>t(await e(`/api/sources/${encodeURIComponent(n)}`,{method:`POST`,headers:{"X-File-Name":r},body:i})),zip:async(n,r)=>{let i=await e(`/api/sources/${encodeURIComponent(n)}/zip`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({names:r})});return i.ok||await t(i),i.blob()},bundle:async n=>{let r=await e(`/api/bundle`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});return r.ok||await t(r),r.blob()},file:async(n,r)=>{let i=await e(`/api/sources/${encodeURIComponent(n)}/files/${encodeURIComponent(r)}`);return i.ok||await t(i),i.blob()},samples:()=>n(`/api/samples`),presets:()=>n(`/api/presets`),plugins:()=>n(`/api/plugins`),installPlugin:async n=>t(await e(`/api/plugins`,{method:`POST`,headers:{"Content-Type":`application/zip`},body:n})),removePlugin:e=>n(`/api/plugins/${encodeURIComponent(e)}`,{method:`DELETE`}),restorePlugin:e=>n(`/api/plugins/trash/${encodeURIComponent(e)}/restore`,{body:{}}),connections:()=>n(`/api/connections`),signIn:e=>n(`/api/connections/${encodeURIComponent(e)}/start`,{body:{}}),signOut:e=>n(`/api/connections/${encodeURIComponent(e)}`,{method:`DELETE`}),packs:()=>n(`/api/packs`),installPack:async n=>t(await e(`/api/packs`,{method:`POST`,headers:{"Content-Type":`application/zip`},body:n})),removePack:e=>n(`/api/packs/${encodeURIComponent(e)}`,{method:`DELETE`}),restorePack:e=>n(`/api/packs/trash/${encodeURIComponent(e)}/restore`,{body:{}}),models:e=>n(`/api/models`,{body:e}),modelsAsk:e=>n(`/api/models/ask`,{body:e})}}var Me=(0,Q.createContext)(null);function Ne(){let e=(0,Q.useContext)(Me);if(!e)throw Error(`useStore outside a StoreContext: the app mounts one at its root`);return e}function Pe(e){let t=Ne();return[(0,Q.useSyncExternalStore)(t.subscribe,()=>t.get(e)),(0,Q.useCallback)(n=>t.set(e,n),[t,e])]}function Fe(){let e=Ne();return{sync:(0,Q.useSyncExternalStore)(e.subscribe,e.sync),resolve:e.resolve}}var Ie=e=>e,Le=()=>({version:7,source:null,scoring:{mode:`all`,threshold:null},grader:null,every:[],run:[],cases:[]}),Re=e=>e?.state===`conflict`?`Not saved: changed in another browser.`:e?.state===`offline`?`Not saved: ${e.message}`:null,ze=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Be=e=>e instanceof Error?e.message:String(e),Ve=({body:e,...t})=>t;function He({api:e,pause:t=800,idle:n}){let r=Ie(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(Ve(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(Ve(c)),o.has(e))return v(e)}catch(t){let n=a.get(e);if(!n?.doc)return;let r=t instanceof Ae&&t.status===409?t.body?.current??null:null;if(r){if(ze(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:Be(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:Be(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:Be(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){let n=await r.createDataset(t?{name:e,body:t}:{name:e});return _(n),n},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({...Ve(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 Ue=3e4,We=(e,t)=>e.get(`promptlab.versions`)[t]??{};function Ge(e,t){return(e.get(`promptlab.versions`).dataset?.[t]??[]).map(e=>({...e,doc:K().upgradeDatasetBody(e?.doc)})).filter(e=>Ke(e.doc))}var Ke=e=>!!e&&typeof e==`object`&&Array.isArray(e.cases);function qe(e,t,n,r,i){let a=e.get(`promptlab.versions`),o=We(e,t),s=(o[n]??[]).slice(),c=structuredClone(r);s[0]&&Ye(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 Je(e,t,n,r){let i=e.get(`promptlab.versions`),a=(i.dataset?.[t]??[]).slice(),o=structuredClone(n);a[0]&&Ye(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 Ye=(e,t)=>JSON.stringify(e)===JSON.stringify(t),$=A(),Xe=(0,Q.createContext)(null);function Ze({children:e,pause:t}){let n=be(),r=Ne(),i=(0,Q.useMemo)(()=>He({api:n,...t==null?{}:{pause:t},idle:{ms:Ue,cut:(e,t)=>Je(r,e,t,`idle`)}}),[n,r,t]);return(0,Q.useEffect)(()=>{let e=()=>{i.flush()};return addEventListener(`pagehide`,e),()=>removeEventListener(`pagehide`,e)},[i]),(0,$.jsx)(Xe.Provider,{value:i,children:e})}function Qe(){let e=(0,Q.useContext)(Xe);if(!e)throw Error(`useDatasets outside a DatasetsProvider: the app mounts one at its root`);return e}function $e(){let e=Qe(),t=(0,Q.useSyncExternalStore)(e.subscribe,e.list);return(0,Q.useEffect)(()=>{e.list().list===null&&e.refresh()},[e]),t}function et(e){let t=Qe(),n=(0,Q.useSyncExternalStore)(t.subscribe,()=>e?t.entry(e):void 0);return(0,Q.useEffect)(()=>{e&&t.load(e)},[t,e]),n}var tt=e=>e.name.trim()||e.text.trim().split(`
2
+ `)[0].trim()||`Untitled prompt`,nt=e=>e?.state===`conflict`?`Not saved: changed in another browser.`:e?.state===`offline`?`Not saved: ${e.message}`:null,rt=e=>e instanceof Error?e.message:String(e),it=({versions:e,uses:t,...n})=>n;function at({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(it(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(it(f)),u)return p(t)}catch(e){let n=r.get(t);if(!n?.doc)return;let a=e instanceof Ae&&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:rt(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:rt(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:rt(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(it(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 ot=(0,Q.createContext)(null);function st({children:e,pause:t}){let n=be(),r=(0,Q.useMemo)(()=>at({api:n,...t==null?{}:{pause:t}}),[n,t]);return(0,Q.useEffect)(()=>{let e=()=>{r.flush()};return addEventListener(`pagehide`,e),()=>removeEventListener(`pagehide`,e)},[r]),(0,$.jsx)(ot.Provider,{value:r,children:e})}function ct(){let e=(0,Q.useContext)(ot);if(!e)throw Error(`usePrompts outside a PromptsProvider: the app mounts one at its root`);return e}function lt(){let e=ct(),t=(0,Q.useSyncExternalStore)(e.subscribe,e.list);return(0,Q.useEffect)(()=>{e.refresh()},[e]),t}function ut(e){let t=ct(),n=(0,Q.useSyncExternalStore)(t.subscribe,()=>e?t.entry(e):void 0);return(0,Q.useEffect)(()=>{e&&t.load(e)},[t,e]),n}var dt=H(`ban`,[[`path`,{d:`M4.929 4.929 19.07 19.071`,key:`196cmz`}],[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}]]),ft=H(`check-check`,[[`path`,{d:`M18 6 7 17l-5-5`,key:`116fxf`}],[`path`,{d:`m22 10-7.5 7.5L13 16`,key:`ke71qq`}]]),pt=H(`circle-check`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),mt=H(`clipboard-copy`,[[`rect`,{width:`8`,height:`4`,x:`8`,y:`2`,rx:`1`,ry:`1`,key:`tgr4d6`}],[`path`,{d:`M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2`,key:`4jdomd`}],[`path`,{d:`M16 4h2a2 2 0 0 1 2 2v4`,key:`3hqy98`}],[`path`,{d:`M21 14H11`,key:`1bme5i`}],[`path`,{d:`m15 10-4 4 4 4`,key:`5dvupr`}]]),ht=H(`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`}]]),gt=H(`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`}]]),_t=H(`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`}]]),vt=H(`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`}]]),yt=H(`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`}]]),bt=H(`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`}]]),xt=H(`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`}]]),St=H(`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`}]]),Ct=H(`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`}]]),wt=H(`folder`,[[`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`}]]),Tt=H(`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`}]]),Et=H(`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`}]]),Dt=H(`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`}]]),Ot=H(`minus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}]]),kt=H(`moon`,[[`path`,{d:`M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401`,key:`kfwtm`}]]),At=H(`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`}]]),jt=H(`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`}]]),Mt=H(`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`}]]),Nt=H(`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`}]]),Pt=H(`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`}]]),Ft=H(`settings-2`,[[`path`,{d:`M14 17H5`,key:`gfn3mx`}],[`path`,{d:`M19 7h-9`,key:`6i9tg`}],[`circle`,{cx:`17`,cy:`17`,r:`3`,key:`18b49y`}],[`circle`,{cx:`7`,cy:`7`,r:`3`,key:`dfmy0x`}]]),It=H(`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`}]]),Lt=H(`sparkles`,[[`path`,{d:`M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z`,key:`1s2grr`}],[`path`,{d:`M20 2v4`,key:`1rf3ol`}],[`path`,{d:`M22 4h-4`,key:`gwowj6`}],[`circle`,{cx:`4`,cy:`20`,r:`2`,key:`6kqj1y`}]]),Rt=H(`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`}]]),zt=H(`sun`,[[`circle`,{cx:`12`,cy:`12`,r:`4`,key:`4exip2`}],[`path`,{d:`M12 2v2`,key:`tus03m`}],[`path`,{d:`M12 20v2`,key:`1lh1kg`}],[`path`,{d:`m4.93 4.93 1.41 1.41`,key:`149t6j`}],[`path`,{d:`m17.66 17.66 1.41 1.41`,key:`ptbguv`}],[`path`,{d:`M2 12h2`,key:`1t8f8n`}],[`path`,{d:`M20 12h2`,key:`1q8mjw`}],[`path`,{d:`m6.34 17.66-1.41 1.41`,key:`1m8zz5`}],[`path`,{d:`m19.07 4.93-1.41 1.41`,key:`1shlcs`}]]),Bt=H(`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`}]]),Vt=e=>(typeof e.id==`string`?e.id.trim():``)||`item:${K().caseItem(e)}`,Ht=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase(),Ut=e=>Array.isArray(e.metrics)?e.metrics:[],Wt=e=>!e.not&&e.weight!==0,Gt=e=>e.type===`contains`&&e.not===!0&&e.weight!==0,Kt=e=>K().metricLines(e);function qt(e,t){let n=Ut(e);switch(t.type){case`bounds`:{let r=n.findIndex(e=>e.type===`item-count`&&Wt(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=>Gt(e)&&Ht(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`&&Wt(e));return i>=0&&Kt(n[i].values).some(e=>Ht(e,r))?e:{...e,metrics:i>=0?n.map((e,t)=>t===i?{...e,values:[...Kt(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(Gt(e)&&Ht(String(e.value??``),r))return i=!0,[];if((e.type===`contains-all`||e.type===`contains-any`)&&Wt(e)&&Kt(e.values).some(e=>Ht(e,r))){i=!0;let t=Kt(e.values).filter(e=>!Ht(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 Jt(e,t,n){let r=[];return n.type===`delete`?{next:e.filter(e=>{let n=t.has(Vt(e));return n&&r.push(Vt(e)),!n}),changed:r}:{next:e.map(e=>{if(!t.has(Vt(e)))return e;let i=qt(e,n);return i!==e&&r.push(Vt(e)),i}),changed:r}}function Yt(e,t,n){let r=new Map(e.map(e=>[Vt(e),e])),i=new Map(t.map(e=>[Vt(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(K().validateEvals({cases:[t]})),s=`${n.id}: `,c=K().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:K().caseItem(n),reasons:c})}return{cases:a}}var Xt={expect:`Expect`,forbid:`Forbid`},Zt=e=>Xt[e],Qt=e=>`${e} ${e===1?`case`:`cases`}`;function $t(e,t){let n=Qt(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 ${Xt[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 en={graded:`Graded`,todo:`To do`,missing:`Missing`};function tn(e,t){return t&&!t.includes(K().caseItem(e))?`missing`:e.todo?`todo`:`graded`}var nn={file:``,status:`all`,show:`all`};function rn(e,t,n,r=null){let i=t.file.trim().toLowerCase();return e.filter(e=>(!i||K().caseItem(e).toLowerCase().includes(i))&&(t.status===`all`||tn(e,r)===t.status)&&(t.show===`all`||n.has(Vt(e))))}var an=(0,Q.createContext)(null);function on({children:e}){let[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(new Set),[a,o]=(0,Q.useState)(nn),[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(null),d=et(l?.dataset??null),f=(0,Q.useRef)(null),p=(0,Q.useCallback)(e=>{e!==f.current&&(f.current=e,n(e),i(new Set),o(nn),c(null))},[]),m=(0,Q.useCallback)(e=>{i(e)},[]),h=(0,Q.useCallback)(e=>{o(t=>({...t,...e}))},[]),g=(0,Q.useCallback)((e,t,r)=>{f.current=e,n(e),i(new Set),o({...nn,show:`selected`}),c(null),u({dataset:e,files:t,from:r});let a=`#/library/datasets/${encodeURIComponent(e)}`;location.hash===a?window.dispatchEvent(new HashChangeEvent(`hashchange`)):location.hash=a},[]),_=d?.doc?.body??null,v=d?.sync.state===`missing`;(0,Q.useEffect)(()=>{if(!l||!_&&!v)return;let e=new Set(l.files),t=(_?.cases??[]).filter(t=>e.has(K().caseItem(t))).map(Vt);i(new Set(t)),c({from:l.from,wanted:e.size,found:t.length}),u(null)},[l,_,v]);let y=(0,Q.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)(an.Provider,{value:y,children:e})}function sn(){let e=(0,Q.useContext)(an);if(!e)throw Error(`useCases outside an CasesProvider: the app mounts one at its root`);return e}var cn=(0,Q.createContext)(null);function ln({children:e}){let[t,n]=(0,Q.useState)([]),[r,i]=(0,Q.useState)(null),a=(0,Q.useRef)(t);a.current=t;let o=(0,Q.useRef)(r);o.current=r;let s=(0,Q.useRef)(0),c=(0,Q.useCallback)((e,t)=>{a.current=e,n(e),o.current=t,i(t)},[]),l=(0,Q.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,Q.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,Q.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,Q.useCallback)((e,t)=>{c(a.current.map(n=>n.id===e?{...n,show:t}:n),o.current)},[c]),p=(0,Q.useCallback)(()=>{c(a.current,null)},[c]),m=(0,Q.useCallback)(()=>{let e=a.current.find(e=>e.id===o.current);window.location.hash=`#/${e?.from??`runs`}`,p()},[p]),h=(0,Q.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)(cn.Provider,{value:h,children:e})}function un(){let e=(0,Q.useContext)(cn);if(!e)throw Error(`useResults outside a ResultsProvider: the app mounts one at its root`);return e}function dn({n:e,of:t}){return(0,$.jsxs)(`span`,{className:`fig-part`,children:[e,(0,$.jsxs)(`span`,{className:`fig-of`,children:[`/`,t]})]})}var fn=e=>e===`good`?` fig-good`:e===`bad`?` fig-bad`:``;function pn({fig:e}){return(0,$.jsx)(`span`,{className:`fig-value${fn(e.tone)}`,children:e.value??(e.of?(0,$.jsx)(dn,{n:e.of[0],of:e.of[1]}):`—`)})}function mn({fig:e}){return(0,$.jsxs)(`div`,{className:`fig`,children:[(0,$.jsx)(`span`,{className:`fig-label`,children:e.label}),(0,$.jsx)(pn,{fig:e})]},e.key)}function hn({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)(pn,{fig:t}),t.under&&(0,$.jsx)(`span`,{className:`fig-under`,children:(0,$.jsx)(dn,{n:t.under[0],of:t.under[1]})})]})]}),!!n.length&&(0,$.jsx)(`div`,{className:`fig-rest`,children:n.map(e=>(0,$.jsx)(mn,{fig:e},e.key))})]})}var gn={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`},_n={format:`image/jpeg`,quality:`0.92`,seed:``,nPredict:``,repeatPenalty:``,frequencyPenalty:``,presencePenalty:``,dryMultiplier:``,dryBase:``,dryAllowedLength:``,grammar:``,px:`921600`},vn=[`type`,`profile`,`px`,`format`,`quality`,`seed`,`nPredict`,`repeatPenalty`,`frequencyPenalty`,`presencePenalty`,`dryMultiplier`,`dryBase`,`dryAllowedLength`,`grammar`,`imagePosition`,`cachePrompt`,`thinking`,`rejectLoops`,`url`,`model`,`temperature`];function yn(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 bn=(e,t)=>({..._n,...t?.setupProfile?.settings||{}});function xn(e){return gn[e]??e}function Sn(e,t){return e===`type`?Cn(String(t)):e===`profile`?t===`speed`?`Speed`:`Quality`:e===`px`?K().budgetLabel(t):e===`format`?String(t).replace(`image/`,``).toUpperCase():String(t)}function Cn(e){return K().CONNECTION_TYPES[e]?.label??e}var wn=e=>e.content?e.content!==`text`:null;function Tn({pass:e}){return(0,$.jsx)(`span`,{className:`mark ${e?`met`:`not`}`,role:`img`,"aria-label":e?`Passed`:`Failed`,children:(0,$.jsx)(e?de:t,{size:14,strokeWidth:2.5,"aria-hidden":`true`})})}var En=e=>Number(new Date(e)).toString(36).slice(-6).toUpperCase(),Dn=(e,t,n=`${t}s`)=>`${e} ${e===1?t:n}`,On=e=>{let t=e?e.timed??e.ran:0;return t?e.ms/t:null};function kn(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 An=e=>new Date(e).toLocaleString(void 0,{dateStyle:`medium`,timeStyle:`short`}),jn={queued:`Queued`,running:`Running`,done:`Done`,incomplete:`Incomplete`,cancelled:`Cancelled`,failed:`Failed`,interrupted:`Interrupted`},Mn=e=>jn[e]??e;function Nn(e){return jn[e]?(0,$.jsx)(`span`,{className:`rchip ${e}`,children:jn[e]}):null}var Pn=e=>e.length?e.reduce((e,t)=>e+t,0)/e.length:null;function Fn(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 In(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 Ln=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(On).filter(e=>e!=null);return{pct:r?Math.round(100*n/r):null,avgScore:i.length?Math.round(Pn(i)):null,avgTime:a.length?Pn(a):null}},Rn=e=>{let t=Ln(e);return{pct:t.pct==null?`—`:`${t.pct}%`,avgScore:t.avgScore==null?`—`:`${t.avgScore}%`,avgTime:t.avgTime==null?`—`:Fn(t.avgTime)}},zn=e=>!!e.run&&(e.status===`cancelled`||e.status===`interrupted`),Bn=e=>e.rerunOf?(0,$.jsxs)(`span`,{className:`hrerun note`,children:[`Re-run of `,e.rerunOfAt?En(e.rerunOfAt):`a cleared run`]}):null,Vn=[{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:En(e.at)}),Bn(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:An(e.at)}),e.cancelled&&(0,$.jsx)(`span`,{className:`err`,children:` cancelled`})]})},{key:`state`,label:`State`,on:!0,sort:e=>Mn(e.status),get:e=>Nn(e.status)},{key:`content`,label:`Content`,on:!0,get:e=>e.content||`—`},{key:`pct`,label:`% Passed Items`,on:!0,numeric:!0,sort:e=>Ln(e).pct,get:e=>Rn(e).pct},{key:`avgscore`,label:`Avg Score`,on:!0,numeric:!0,sort:e=>Ln(e).avgScore,get:e=>Rn(e).avgScore},{key:`avgtime`,label:`Avg Time`,on:!0,numeric:!0,sort:e=>Ln(e).avgTime,get:e=>Rn(e).avgTime},{key:`duration`,label:`Duration`,on:!1,numeric:!0,sort:e=>In(e.startedAt,e.finishedAt),get:e=>{let t=In(e.startedAt,e.finishedAt);return t==null?`—`:Fn(t)}},{key:`ran`,label:`Ran`,on:!1,numeric:!0,sort:e=>e.done,get:e=>(0,$.jsx)(dn,{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:`——`})})}],Hn=[{key:`name`,label:`Name`,on:!0,sort:(e,t)=>e?.name||`Target ${K().targetLetter(t)}`,get:(e,t,n)=>(0,$.jsx)(`button`,{type:`button`,className:`ghost linkish`,"data-scenario":n,children:t?.name||`Target ${K().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)(Tn,{pass:e.mark})]},t)):t.evals||`—`},{key:`profile`,label:`Target Profile`,on:!0,sort:e=>e?.setupProfile?.name,get:(e,t,n)=>t?.setupProfile?.name?(0,$.jsx)(`button`,{type:`button`,className:`ghost linkish`,"data-prof":n,children:t.setupProfile.name}):`—`},{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)(dn,{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=>On(e),get:(e,t)=>{let n=On(t);return n==null?`—`:Fn(n)}},{key:`total`,label:`Total`,on:!1,numeric:!0,sort:e=>e.ms||null,get:(e,t)=>t.ms?Fn(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(K().budgetLabel(bn(e,t).px))},{key:`format`,label:`Format`,on:!1,image:!0,get:(e,t)=>String(bn(e,t).format).replace(`image/`,``).toUpperCase()},{key:`quality`,label:`Quality`,on:!1,image:!0,get:(e,t)=>bn(e,t).format===`image/png`?`—`:String(bn(e,t).quality)},{key:`seed`,label:`Seed`,on:!1,get:(e,t)=>String(bn(e,t).seed||`1234`)},{key:`predict`,label:`Reply tokens`,on:!1,get:(e,t)=>String(bn(e,t).nPredict||bn(e,t).maxTokens||`—`)},{key:`penalty`,label:`Repeat penalty`,on:!1,get:(e,t)=>String(bn(e,t).repeatPenalty||`—`)},{key:`decoding`,label:`Decoding`,on:!1,get:(e,t)=>yn(bn(e,t))||`—`},...Object.entries(K().MODIFIERS).map(([e,t])=>({key:`modifier-${e}`,label:t.label||e,on:!1,get:(t,n)=>n.modifiers?.[e]||`—`}))],Un={"Run Scenarios":`Run Targets`},Wn={tests:`evals`},Gn=[[`Runs`,Vn],[`Run Scenarios`,Hn]],Kn=e=>![`queued`,`running`].includes(e),qn=()=>({ran:0,passed:0,found:0,of:0,ms:0,timed:0,share:0,shared:0});function Jn(e){return e.of?Math.round(100*e.found/e.of):e.shared?Math.round(100*e.share/e.shared):null}var Yn=(e,t)=>e.filter(e=>!e.whole).map(e=>e.items[t]).filter(e=>!!e&&!K().isSkipped(e)),Xn=e=>Array.isArray(e)?e.length:typeof e==`number`?e:0;function Zn(e,t){let n=t.map(qn);return(e||[]).forEach((e,r)=>{e&&!e.unrun&&(e.scenarios||[]).forEach((e,i)=>{let a=n[i];if(!a||!e)return;let o=Yn(t[i],r);if(o.length){a.ran++,o.every(e=>e.pass)&&a.passed++;for(let e of o)a.found+=Xn(e.found),a.of+=Xn(e.found)+Xn(e.missed)+Xn(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 Qn=(e,t,n)=>K().targetsOf(e).map((r,i)=>K().scenarioEvals(e,i,t,Kn(n))),$n=(e,t,n)=>(e.outcomes[n]??[]).some(e=>!e.whole&&K().failedScore(e.items[t]));function er(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 tr=e=>!e.skipped&&e.whole&&e.verdict?.ran?!!e.verdict.pass:null,nr=e=>e.map(e=>`${e.label} ${er(e)}`).join(`, `),rr=e=>e.map(e=>({label:e.label,value:er(e),mark:tr(e)})),ir=e=>{if(!e.group)return null;let t=K().casesRef(e)?.n??e.pin;return t==null?null:`v${t}`},ar=(e,t,n)=>e.group?.name||e.group?.id||(e.name||``).trim()||K().evalLabel({evals:n},t);function or(e){let t=e.evals,n=t.map((n,r)=>({key:n.id,name:ar(n,r,t),version:ir(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?K().groupPass(i):null}})})),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)=>K().overallVerdict(e.outcomes[n]??[],r))}:null}}function sr(e){let t=e.snapshot||{},n=K().contentOf(t),r=!!(n&&K().CONTENT_TYPES[n.type]?.inline),i=K().lastKind(t),a=e.results||[],o=Qn(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:K().targetsOf(t).map((e,n)=>({id:e?.id||`scenario-${n}`,name:K().targetLabel(t,n),kind:i,plain:!(i&&K().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:K().evalsOf(t),snapshot:t,results:a,outcomes:o,tallies:Zn(a,o),startedAt:e.startedAt,finishedAt:e.finishedAt}}function cr(e){let t=e.snapshot||{},n=K().contentOf(t),r=e.results||[],i=K().targetsOf(t),a=t.jobs||[],o=Qn(t,r,e.status),s=Zn(r,o),c=i.map((e,n)=>{let r=s[n]??qn(),i=(a.length?K().stagesFor(t,n).connections:[]).map(e=>String(e.model||``)),c=i[0]?new Set(i).size===1?i[0]:i.join(` → `):``,l=Jn(r),u=K().overallVerdict(o[n]??[],t.pass);return{name:K().targetLabel(t,n),id:e?.id,model:c,setupProfile:K().scenarioProfile(t,n),modifiers:Object.fromEntries((K().outOf(t.jobs?.at(-1))?.modifiers||[]).map(e=>[e.type,K().modifierSummary(e)])),percent:l,passed:r.passed,cases:r.ran,pass:u,detail:u==null?`not graded`:nr(o[n]??[]),evals:nr(o[n]??[]),evalParts:rr(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&&K().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 lr=e=>({key:`state`,label:`State`,value:Mn(e),tone:e===`done`?`good`:[`failed`,`incomplete`,`cancelled`,`interrupted`].includes(e)?`bad`:null}),ur=e=>e.length?e.reduce((e,t)=>e+t,0)/e.length:null;function dr(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&&!K().isSkipped(r))for(let e of r.metrics||[])typeof e.asked==`number`&&(t++,n+=e.asked);return{calls:t,ms:n}}function fr(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(Jn).filter(e=>e!=null),a=i.length?`${Math.round(ur(i))}%`:`—`,o=In(e.startedAt,e.finishedAt),s=dr(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)}%`,under:[n,r]}:{...c,key:`lead-ran`},rest:[{key:`run`,label:`Run ID`,value:e.at?(0,Q.createElement)(`code`,null,En(e.at)):`—`},lr(e.status),{key:`score`,label:`Avg Score`,value:a},{key:`duration`,label:`Duration`,value:o==null?`—`:Fn(o)},...s.calls?[{key:`grader`,label:`Grader`,value:`${s.calls} ${s.calls===1?`call`:`calls`}, ${Fn(s.ms)}`}]:[],...r?[c]:[],{key:`start`,label:`Start Date`,value:e.at?gr(e.at):`—`},{key:`comment`,label:`Comment`,value:e.snapshot.comment?(0,Q.createElement)(`span`,{className:`fig-comment`,title:e.snapshot.comment},e.snapshot.comment):`—`}]}}var pr=e=>e.evals.length&&Kn(e.status)?`No assertions`:`—`;function mr(e,t){let n=e.tallies[t],r=vr(e,t),i={key:`state`,label:`State`,value:r==null?pr(e):r?`Pass`:`Fail`,tone:r==null?null:r?`good`:`bad`},a={key:`time`,label:`Avg Time`,value:hr(n)??`—`},o=e.outcomes[t]??[],s=o.length>1?o.map(e=>({key:`eval-${e.id}`,label:e.label,value:tr(e)==null?er(e):(0,Q.createElement)(Tn,{pass:tr(e)}),tone:e.skipped?null:e.whole?e.verdict?.ran?e.verdict.pass?`good`:`bad`:null:e.ran?e.passed===e.ran?`good`:`bad`:null})):[];return n?.ran?{lead:{key:`pct`,label:`% Passed Items`,value:`${Math.round(100*n.passed/n.ran)}%`,under:[n.passed,n.ran]},rest:[i,...s,{key:`score`,label:`Score`,value:Jn(n)==null?`—`:`${Jn(n)}%`},a]}:{lead:i,rest:[...s,a]}}function hr(e){return e?.timed?Fn(e.ms/e.timed):null}function gr(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 _r(e){let t=Mn(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 vr(e,t){return K().overallVerdict(e.outcomes[t]??[],e.snapshot.pass)}function yr(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 br(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 xr=(e,t)=>t==null||t===``?null:`${e}: ${t}`,Sr=e=>(e||[]).map(String).join(`, `),Cr=e=>e.length?e.every(t=>t===e[0])?String(e[0]):e.join(` → `):``,wr=e=>{let t=K().OUTPUT_KINDS[K().lastKind(e)??K().defaultKind()];return t?!t.terms:!1},Tr=e=>{let t=e.metric&&String(e.metric)||K().METRICS[e.type]?.label||e.type,n=K().metricSummary(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 Er(e,t,n,r){let i=K().readCase(t,n,wr(e)),{stages:a,connections:o}=K().stagesFor(e,r),s=o.map(e=>K().connectionSettings(e)),c=e=>Cr(s.map(e)),l=K().evalsDataset(e);return[`An eval case is failing.`,``,`## The case`,xr(`item`,K().caseItem(t)),xr(`case id`,t.id),xr(`note`,t.note),...(t.metrics||[]).map((e,t)=>xr(`metric ${t+1}`,Tr(e))),``,`## What came back`,xr(`verdict`,i.pass?`pass`:`fail`),xr(`score`,i.score==null?`—`:`${Math.round(i.score*100)}%`),xr(`items`,Sr(n?.terms)||`(none)`),xr(`missed`,Sr((i.missed??[]).map(e=>Array.isArray(e)?e.join(` / `):e))),xr(`invented`,Sr(i.invented)),xr(`dropped`,Sr((n?.dropped||[]).map(e=>`${e.item} (${e.by})`))),xr(`reasons`,Sr(i.reasons)),xr(`error`,n?.error),xr(`took`,n?.ms==null?null:`${n.ms} ms`),``,`## How it was asked`,xr(`scenario`,`${r+1} of ${K().targetsOf(e).length}`),xr(`model`,c(e=>e.model)),xr(`endpoint`,c(e=>e.url||`(the lab's own Ollama)`)),xr(`connection type`,c(e=>Cn(String(e.type??``)))),xr(`image`,a[0]?.withImage?Dr(s[0]):`no image`),xr(`seed`,c(e=>e.seed||`1234`)),xr(`reply tokens`,c(e=>e.nPredict||e.maxTokens||`not set`)),xr(`repeat penalty`,c(e=>e.repeatPenalty||`(profile default)`)),xr(`other decoding`,Or(s.at(-1))),xr(`modifiers`,(K().outOf(e.jobs.at(-1))?.modifiers||[]).map(e=>`${K().MODIFIERS[e.type]?.label??e.type}: ${K().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 Dr(e){let{px:t,format:n}=K().connectionImage(e);return`${t==null?`default budget`:K().budgetLabel(t)}, ${n.replace(`image/`,``).toUpperCase()}`}function Or(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 kr(e,t){let n=[];return!Kn(e.status)||!K().evalsDataset(e.snapshot)||(e.results||[]).forEach((r,i)=>{r&&!r.unrun&&(r.scenarios||[]).forEach((a,o)=>{let s=t.find(e=>K().caseItem(e)===r.name);$n(e,i,o)&&s&&a.res&&n.push({kase:s,res:a.res,scenarioIndex:o,item:r.name??``})})}),n}var Ar=e=>{let t=Math.min(...e),n=Math.max(...e);return t===n?String(t):`${t}–${n}`};function jr(e,t,n){let r=K().evalsDataset(e.snapshot);if(!Kn(e.status)||!r)return[];let i=e.outcomes[n]?.find(t=>e.evals.find(e=>e.id===t.id&&K().casesRef(e))),a=new Map(t.map(e=>[K().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||K().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?`${Ar(r)}, ${e===`over`?`max`:`min`} ${Ar(i)}`:null}))}var Mr=[{id:`home`,label:`Home`,icon:C,built:!0},{id:`runs`,label:`Runs`,icon:J,built:!0},{id:`history`,label:`History`,icon:s,built:!0},{id:`library`,label:`Library`,icon:x,built:!0},{id:`setup`,label:`Setup`,icon:l,built:!0}],Nr=e=>e.replace(/[^A-Za-z0-9._-]+/g,`-`).replace(/^[-.]+|[-.]+$/g,``);function Pr(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 Fr(e,t,n,r,i=new Date){return`${e}-${Nr(t)||e}-v${n}-${Pr(i)}.${r}`}function Ir(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 Lr=`#/library/datasets`,Rr=()=>{location.hash=Lr},zr=e=>{location.hash=`${Lr}/${encodeURIComponent(e)}`};function Br({undo:e}){let t=Qe(),{list:n,error:r}=$e(),[o]=Pe(`promptlab.workflows`),[s,c]=ge(`eval-groups`,20),[l,u]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)(null),g=(0,Q.useRef)(null),[,_]=(0,Q.useState)(0);(0,Q.useEffect)(()=>t.subscribe(()=>_(e=>e+1)),[t]),(0,Q.useEffect)(()=>{for(let e of n??[])t.load(e.id)},[n,t]);let y=e=>p(e instanceof Error?e.message:String(e)),x=(0,Q.useMemo)(()=>{let e=new Map;for(let t of o.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},[o.list]),S=(n??[]).map(e=>({...e,body:t.entry(e.id)?.doc?.body??null,links:x.get(e.id)??{names:[],pinned:!1}})),C=()=>new Set((t.list().list??[]).map(e=>e.name)),w=async()=>{p(null);try{zr((await t.create(Hr(`Untitled eval group`,C()))).id)}catch(e){y(e)}},T=async n=>{p(null);try{await t.flush(n.id);let r=await t.remove(n.id);e.offer({label:`Deleted ${n.name}`,restore:()=>{t.restore(r).catch(y)}})}catch(e){y(e)}},E=async e=>{p(null);let n;try{n=await Vr(e)}catch(e){y(e);return}let r;try{r=JSON.parse(n)}catch(e){p(`Not JSON: ${e instanceof Error?e.message:String(e)}`);return}h(`import`);try{let e=await t.importFile(r);e[0]&&zr(e[0].id)}catch(e){y(e)}finally{h(null)}},O=async()=>{h(`exportAll`);try{let e=await fetch(t.exportAllUrl());if(!e.ok)throw Error(`the export answered ${e.status}`);let n=await e.json();Ir(new Blob([JSON.stringify(n,null,2)+`
6
+ `],{type:`application/json`}),Fr(`eval-groups`,`all`,n.version,`json`))}catch(e){y(e)}finally{h(null)}},k=e=>[{label:`Open`,icon:d,onSelect:()=>zr(e.id)},{label:`Delete`,icon:W.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:()=>zr(e.id),children:e.name})},{key:`source`,header:`Source`,sort:e=>e.body?.source?.name??``,tdProps:e=>({"data-state":e.body?.source?void 0:`none`}),cell:e=>e.body?e.body.source?.name??`Any`:`…`},{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)(a,{label:`${e.name} actions`,actions:k(e)})}],M=[{label:`Import JSON…`,icon:U,busy:m===`import`,onSelect:()=>g.current?.click()},{label:`Export all`,icon:bt,disabled:!n?.length,busy:m===`exportAll`,onSelect:()=>void O()},{label:`Page size…`,icon:W.pageSize,onSelect:()=>u(!0)}];return(0,$.jsxs)(b,{id:`evals`,title:`Evals`,note:n?String(n.length):void 0,actions:M,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&&E(t)}}),n===null?(0,$.jsx)(i,{label:`Eval groups`,error:r,onRetry:()=>void t.refresh()}):n.length===0?(0,$.jsx)(`p`,{className:`note`,children:`No eval groups yet.`}):(0,$.jsx)(R,{className:`eg-groups`,cards:!0,label:`Eval groups`,rows:S,rowKey:e=>e.id,pageSize:s,columns:j}),f&&(0,$.jsx)(`p`,{className:`note bad`,role:`alert`,children:f}),(0,$.jsxs)(`button`,{type:`button`,className:`ghost eg-add`,onClick:()=>void w(),children:[(0,$.jsx)(v,{size:14,"aria-hidden":`true`}),`Add eval group`]}),l&&(0,$.jsx)(D,{value:s,onChange:c,onClose:()=>u(!1)})]})}function Vr(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 Hr=(e,t)=>{if(!t.has(e))return e;for(let n=2;;n++)if(!t.has(`${e} ${n}`))return`${e} ${n}`};function Ur(e){return[e.every&&`Every reply`,e.not&&`Not`,e.of===`said`&&`Raw reply`,e.weight!=null&&`Weight ${e.weight}`].filter(Boolean).join(`, `)}var Wr=(e,t)=>({type:e,...K().METRICS[e].defaults(),...t?.weight==null?{}:{weight:t.weight},...t?.not?{not:!0}:{},...t?.metric?{metric:t.metric}:{}});function Gr({label:e,metrics:t,set:n,undoable:r,over:i=`item`,rawReply:a}){let o=K(),[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(null),d=(e,r)=>n(t.map((t,n)=>n===e?r:t)),f=e=>{s===`new`?n([...t,Wr(e)]):typeof s==`number`&&d(s,Wr(e,t[s])),c(null)};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(P,{noun:`metric`,items:[...t],empty:(0,$.jsx)(`p`,{className:`note`,children:`No metrics.`}),onAdd:()=>c(`new`),onRemove:e=>r(t.filter((t,n)=>n!==e),`Removed a metric`),onRename:e=>u(e),extra:(e,t)=>[{label:`Change type…`,icon:It,onSelect:()=>c(t)}],renderItem:(t,n,r)=>{let s=o.METRICS[t.type],c=(t.metric||s?.label||t.type)+(t.not?` (not)`:``)+(t.weight===0?` (watch)`:``),l=`${e.replace(/\W+/g,`-`).toLowerCase()}-metric-${n}`,u=!!(t.every||t.not||t.of||t.weight!=null),f=a!==!1||t.of===`said`,p=(s?.options??[]).map(e=>te(e,t,e=>d(n,e)));return(0,$.jsxs)(b,{id:l,title:c,level:3,actions:r,about:s?.description,children:[p.length>0&&(0,$.jsx)(he,{label:`${e}, metric ${n+1}`,rows:p}),(0,$.jsx)(b,{id:`${l}-counts`,title:`Options`,level:3,open:u,note:u?Ur(t):`Defaults`,children:(0,$.jsx)(he,{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;d(n,e?{...i,every:!0}:i)}}}]:[],{key:`not`,label:`Not`,control:{type:`checkbox`,checked:!!t.not,onChange:e=>{let{not:r,...i}=t;d(n,e?{...i,not:!0}:i)}}},...f?[{key:`of`,label:`Reads`,...a==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;d(n,e===`said`?{...i,of:`said`}:i)}}}]:[],{key:`weight`,label:`Weight`,control:{type:`text`,size:`num`,value:t.weight==null?``:String(t.weight),placeholder:`1`,onChange:e=>{let{weight:r,...i}=t;d(n,e.trim()?{...i,weight:/^-?\d+(\.\d+)?$/.test(e.trim())?Number(e):e}:i)}}}]})})]},n)}}),l!==null&&t[l]&&(0,$.jsx)(fe,{title:`Rename metric`,value:t[l].metric||o.METRICS[t[l].type]?.label||t[l].type,onCommit:e=>{let{metric:n,...r}=t[l];d(l,e&&e!==o.METRICS[r.type]?.label?{...r,metric:e}:r)},onClose:()=>u(null)}),s!==null&&(0,$.jsx)(Kr,{title:s===`new`?`Add metric`:`Change type`,current:typeof s==`number`?t[s]?.type??null:null,over:i,onPick:f,onClose:()=>c(null)})]})}function Kr({title:e,current:t,over:n,onPick:r,onClose:i}){let[a,o]=(0,Q.useState)(``),s=(0,Q.useMemo)(()=>{let e=new Map;for(let[t,r]of Object.entries(K().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)(y,{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 qr(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:An(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 Jr({name:e,body:t,onSave:n,onClose:r}){let[i]=(0,Q.useState)(()=>JSON.stringify(t,null,2)),[a,o]=(0,Q.useState)(i),[s,c]=(0,Q.useState)(()=>Xr(a));(0,Q.useEffect)(()=>{let e=setTimeout(()=>c(Xr(a)),400);return()=>clearTimeout(e)},[a]);let l=s.problems;return(0,$.jsxs)(y,{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=Xr(a);e.body?n(e.body):c(e)},disabled:l.length>0,children:`Save & Close`})]})]})}var Yr=[`version`,`source`,`scoring`,`grader`,`every`,`run`,`cases`];function Xr(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))Yr.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=K().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=Le(),o={version:i,source:n.source??null,scoring:n.scoring??a.scoring,grader:n.grader??null,every:n.every??[],run:n.run??[],cases:n.cases};return r.push(...K().validateEvals(o)),r.length?{body:null,problems:r}:{body:o,problems:[]}}function Zr(e,t){return`/api/sources/${encodeURIComponent(e)}/thumbs/${encodeURIComponent(t)}`}function Qr(e){return/\.(?:jpe?g|png|gif|webp|bmp|heic|heif|dng|tiff?)$/i.test(e)}function $r({title:e,action:t,source:n,files:r,taken:i,onPick:a,onClose:o}){let s=(0,Q.useMemo)(()=>r.filter(e=>!i.has(e)),[r,i]),[c,l]=(0,Q.useState)(``),[u,d]=(0,Q.useState)(s[0]??null),f=s.filter(e=>!c.trim()||e.toLowerCase().includes(c.trim().toLowerCase()));return(0,$.jsxs)(y,{title:e,onClose:o,className:`item-picker`,footer:(0,$.jsxs)(`div`,{className:`edit-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:o,children:`Cancel`}),(0,$.jsx)(`button`,{type:`button`,className:`edit-done`,disabled:!u||!s.includes(u),onClick:()=>{u&&a(u)},children:t})]}),children:[(0,$.jsxs)(`div`,{className:`prop ip-source`,children:[(0,$.jsx)(`span`,{className:`prop-name`,children:`Source`}),(0,$.jsx)(`span`,{className:`prop-value`,children:n.name})]}),(0,$.jsx)(`input`,{type:`search`,className:`ip-search`,"aria-label":`Find an item`,placeholder:`Find an item`,value:c,onChange:e=>l(e.target.value),autoComplete:`off`}),(0,$.jsxs)(`fieldset`,{className:`ip-items`,children:[(0,$.jsxs)(`legend`,{className:`note`,children:[s.length,` `,s.length===1?`item`:`items`,` without a case`]}),s.length?f.length?f.map(e=>(0,$.jsxs)(`label`,{className:`ip-item${e===u?` on`:``}`,children:[(0,$.jsx)(`input`,{type:`radio`,name:`item`,checked:e===u,onChange:()=>d(e)}),Qr(e)?(0,$.jsx)(`img`,{src:Zr(n.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 `,n.name,` has a case.`]})]})]})}var ei=2e3,ti=e=>({id:``,item:e,todo:!0,note:``,metrics:[]}),ni=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 ri({item:t,cases:n,onWrite:r,problem:i,resultFor:a,scenarioCount:o,plain:s=!1,files:c,onFile:l,onClose:u,run:d,source:f=null,sourceFiles:p=null,onRemove:h}){let g=n.find(e=>K().caseItem(e)===t),_=!g,[v,y]=(0,Q.useState)(()=>structuredClone(g??ti(t))),[b,x]=(0,Q.useState)(0),[S,C]=(0,Q.useState)(null),[w,T]=(0,Q.useState)(null),[E,D]=(0,Q.useState)(!1),[O,k]=(0,Q.useState)(!1),[A,M]=(0,Q.useState)(!1),N=(0,Q.useRef)(v);N.current=v;let P=(0,Q.useRef)(n);P.current=n;let F=(0,Q.useRef)(null),ee=e=>P.current.filter(n=>!(e.id&&n.id===e.id)&&!(!e.id&&K().caseItem(n)===t)).some(t=>K().caseItem(t)===K().caseItem(e))?`${K().caseItem(e)} has a case already`:K().validateEvals({cases:[{...e,id:e.id||`new`}]})[0]?.replace(/^[^:]*: /,``)??null,L=ee(v),R=(0,Q.useCallback)(()=>{let e=N.current;if(ee(e))return!1;e.id||(e={...e,id:ni(P.current)},N.current=e,y(e));let t=e;return r(e=>ii({cases:e},t)),!0},[r,t]);(0,Q.useEffect)(()=>()=>{F.current&&clearTimeout(F.current)},[]);let[z,B]=(0,Q.useState)(!1),V=e=>{y(e),B(!0)},te=e=>{let t=N.current;V({...t,metrics:e,...t.todo&&!(t.metrics??[]).length&&e.length?{todo:!1}:{}})},H=w&&w[b]?w[b]:a(b),U=!H||v.todo||!(v.metrics??[]).length?null:K().readCase(v,H,s),W=async()=>{if(d&&!E){D(!0),C(null);try{let e=await d(K().caseItem(N.current));T(e),C(e.length?null:`No reply to grade.`)}catch(e){C(e instanceof Error?e.message:String(e))}finally{D(!1)}}},ne=c.indexOf(t),re=e=>{let t=ne<0?null:c[ne+e];if(!t)return;let n=z||_;(!n||R())&&(n&&(k(!0),F.current&&clearTimeout(F.current),F.current=setTimeout(()=>k(!1),ei)),l(t))};(0,Q.useEffect)(()=>{let e=e=>{(e.key===`ArrowLeft`||e.key===`ArrowRight`)&&(e.target?.closest?.(`input, textarea, select, [contenteditable]`)||(e.preventDefault(),re(e.key===`ArrowRight`?1:-1)))};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)});let ie=()=>{(!z&&!_||R())&&u()},G=K().caseItem(v),ae=new Set(n.filter(e=>!(v.id&&e.id===v.id)&&K().caseItem(e)!==t).map(e=>K().caseItem(e))),oe=!!p&&!p.includes(G),se=[{key:`item`,label:`Item`,control:f?{type:`static`,text:oe?`${G||`None`} (missing)`:G}:{type:`text`,value:G,onChange:e=>V({...N.current,item:e.trim()})}},{key:`todo`,label:`To do`,control:{type:`checkbox`,checked:!!v.todo,label:`Not graded yet`,onChange:e=>V({...N.current,todo:e})}},{key:`note`,label:`Note`,control:{type:`textarea`,value:v.note??``,onChange:e=>V({...N.current,note:e})}}],q=[];o>1&&q.push({key:`scenario`,label:`Show result of`,control:{type:`select`,value:String(b),options:Array.from({length:o},(e,t)=>({value:String(t),label:`Target ${K().targetLetter(t)}`})),onChange:e=>x(Number(e))}}),U&&(q.push({key:`verdict`,label:`Result`,control:{type:`static`,text:U.pass?`Pass`:`Fail`}}),U.watch.length&&q.push({key:`watch`,label:`Watch`,control:{type:`static`,text:`${U.watch.filter(e=>e.pass).length} of ${U.watch.length}`}}));let J=f&&G&&Qr(G)&&p?.includes(G)?{src:Zr(f.id,G),file:G,source:f.name}:null,ce=[...J?[{key:`preview`,title:`Preview`,children:(0,$.jsxs)(`div`,{className:`cf-preview`,children:[(0,$.jsx)(`img`,{src:J.src,alt:J.file,loading:`lazy`}),(0,$.jsxs)(`p`,{className:`note`,children:[J.file,` in `,J.source]})]})}]:[],{key:`case`,title:`Case`,rows:se},{key:`metrics`,title:`Metrics`,children:(0,$.jsx)(Gr,{label:`${G||`Case`} metrics`,metrics:v.metrics??[],set:te,undoable:te})},...q.length?[{key:`result`,title:`Result`,rows:q}]:[]],Y=[{label:`Previous`,icon:I,disabled:ne<=0,onSelect:()=>re(-1)},{label:`Next`,icon:e,disabled:ne<0||ne>=c.length-1,onSelect:()=>re(1)},...d?[{label:`Run`,icon:Mt,disabled:E,onSelect:()=>void W()}]:[]],le=[...f?[{label:`Change item…`,icon:Nt,disabled:!p,onSelect:()=>M(!0)}]:[],...h?[{label:`Remove`,icon:m,destructive:!0,onSelect:()=>{h(K().caseItem(N.current)),u()}}]:[]],ue=S??i??(L?`Not saved: ${L}`:null);return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(j,{title:G||`Case`,status:ue??(E?`Running…`:O?`Saved.`:void 0),...ue?{statusBad:!0}:{},sections:ce,...le.length?{menu:le}:{},actions:Y,dirty:z,onSave:ie,onClose:u}),A&&f&&p&&(0,$.jsx)($r,{title:`Change item`,action:`Change`,source:f,files:p,taken:new Set([...ae,G]),onPick:e=>{M(!1),V({...N.current,item:e})},onClose:()=>M(!1)})]})}function ii(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 ai(e,t){return structuredClone(e.cases).filter(e=>K().caseItem(e)!==t)}function oi(e){let t=be(),[n,r]=(0,Q.useState)(null);return(0,Q.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}var si=(0,Q.createContext)(null);function ci({children:e}){let t=Qe(),[n,r]=(0,Q.useState)(null),i=et(n?.dataset??null),a=(0,Q.useCallback)((e,t)=>{r({item:e,...t})},[]),o=(0,Q.useCallback)(e=>{r(t=>t&&{...t,item:e})},[]),s=i?.doc?.body.source??null,c=oi(s?.id),l=n?.dataset??``,u=(0,Q.useCallback)(e=>{t.edit(l,t=>({...t,cases:e(t.cases)}))},[t,l]),d=(0,Q.useMemo)(()=>({openCaseEditor:a}),[a]),f=i?.doc;return(0,$.jsxs)(si.Provider,{value:d,children:[e,n&&f&&(0,$.jsx)(ri,{item:n.item,cases:f.body.cases,onWrite:u,problem:Re(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 li(){let e=(0,Q.useContext)(si);if(!e)throw Error(`useCaseEditor outside a CaseEditorProvider: the app mounts one at its root`);return e}function ui({rows:e,shown:t,filters:n,onFilters:r,selected:a,onSelect:o,selectionActions:s,sourceFiles:c,hasSource:l,pageSize:u,onEdit:d,onAdd:f,onRemove:p,loading:m,loadError:h,onRetry:g,children:_}){let y=t.map(Vt),b=y.filter(e=>a.has(e)).length,x=b>0&&b===y.length,S=[{key:`status`,label:`Status`,value:n.status,onChange:e=>r({status:e}),options:[{value:`all`,label:`All`},{value:`graded`,label:`Graded`},{value:`todo`,label:`To do`},...c?[{value:`missing`,label:`Missing`}]:[]]},{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)(i,{label:`Cases`,error:h,onRetry:g})]}):(0,$.jsxs)(`div`,{className:`ds-casebody`,children:[e.length>0&&(0,$.jsx)(ie,{noun:`cases`,search:{label:`Item`,placeholder:`Search items`,value:n.file,onChange:e=>r({file:e})},filters:S,count:{shown:t.length,total:e.length},lead:(0,$.jsx)(`label`,{className:`ev-check ev-all`,children:(0,$.jsx)(di,{all:x,some:b>0,disabled:!t.length,onChange:()=>o(e=>{let t=new Set(e);for(let e of y)x?t.delete(e):t.add(e);return t})})})}),_,e.length===0?(0,$.jsx)(`p`,{className:`ds-none`,children:l?`No cases.`:`No Source yet.`}):(0,$.jsx)($.Fragment,{children:t.length===0?(0,$.jsxs)($.Fragment,{children:[a.size>0&&(0,$.jsx)(B,{count:a.size,noun:`case`,hidden:a.size,actions:s,onClear:()=>o(()=>new Set)}),(0,$.jsx)(`p`,{className:`note`,children:`No cases match these filters.`})]}):(0,$.jsx)(`div`,{className:`ds-cases`,children:(0,$.jsx)(R,{className:`dstable`,cards:!0,label:`Cases`,rows:t,pageSize:u,defaultSort:null,rowKey:e=>Vt(e),select:{noun:`case`,selected:a,onChange:e=>o(()=>e),actions:()=>s},columns:fi(c,d,p)})})}),(0,$.jsxs)(`button`,{type:`button`,className:`ghost ds-add`,onClick:f,disabled:!l||!c,children:[(0,$.jsx)(v,{size:14,"aria-hidden":`true`}),`Add case`]})]})}function di({all:e,some:t,disabled:n,onChange:r}){let i=(0,Q.useRef)(null);return(0,Q.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 fi(e,t,n){let r=t=>tn(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=>en[r(e)],tdProps:e=>({"data-state":r(e)}),cell:e=>(0,$.jsx)(`span`,{className:`ds-status ds-${r(e)}`,children:en[r(e)]})},{key:`metrics`,header:`Metrics`,className:`num`,sort:e=>pi(e).length,cell:e=>pi(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)(a,{label:`${e.item} actions`,actions:[{label:`Edit…`,icon:W.edit,onSelect:()=>t(e.item)},{label:`Remove`,icon:W.remove,destructive:!0,onSelect:()=>n(e.item)}]})}]}var pi=e=>(e.metrics??[]).filter(e=>e.weight!==0),mi={bounds:`Set count`,addTerm:`Add term`,removeTerm:`Remove term`,todo:`Mark To do`,graded:`Mark graded`},hi=[{value:`keep`,label:`Keep`},{value:`set`,label:`Set`},{value:`clear`,label:`Clear`}],gi=e=>/^\s*\d+\s*$/.test(e)?Number(e):null;function _i({kind:e,cases:t,keys:n,onApply:r,onClose:i}){let[a,o]=(0,Q.useState)(`keep`),[s,c]=(0,Q.useState)(`keep`),[l,u]=(0,Q.useState)(``),[d,f]=(0,Q.useState)(``),[p,m]=(0,Q.useState)(`expect`),[h,g]=(0,Q.useState)(``),[_,v]=(0,Q.useState)(null),b=(0,Q.useMemo)(()=>{switch(e){case`bounds`:{let e=a===`set`?gi(l):null,t=s===`set`?gi(d):null;return a===`set`&&e==null?`Min items needs a whole number.`:s===`set`&&t==null?`Max items needs a whole number.`:{type:`bounds`,min:a===`set`?{kind:`set`,n:e}:{kind:a},max:s===`set`?{kind:`set`,n:t}:{kind:s}}}case`addTerm`:return h.trim()?{type:`addTerm`,list:p,term:h}:`Name the term.`;case`removeTerm`:return h.trim()?{type:`removeTerm`,term:h}:`Name the term.`;case`todo`:return{type:`status`,todo:!0};case`graded`:return{type:`status`,todo:!1}}},[e,a,s,l,d,p,h]),x=(0,Q.useMemo)(()=>{if(typeof b==`string`)return null;let{next:e,changed:r}=Jt(t,n,b);return{changed:r,problems:Yt(t,e,r)}},[b,t,n]),S=_??x?.problems??null,C=!!S&&S.cases.length>0,w=x?.changed.length??0,T=(0,Q.useCallback)(()=>{if(typeof b==`string`)return;let e=r(b);e&&v(e)},[b,r]),E=e=>t=>{v(null),e(t)},D=[];return e===`bounds`&&(D.push({key:`min`,label:`Min items`,required:!0,control:{type:`select`,value:a,options:hi,onChange:E(e=>o(e))}}),a===`set`&&D.push({key:`minN`,label:`Min`,required:!0,control:{type:`text`,value:l,size:`num`,onChange:E(u)}}),D.push({key:`max`,label:`Max items`,required:!0,control:{type:`select`,value:s,options:hi,onChange:E(e=>c(e))}}),s===`set`&&D.push({key:`maxN`,label:`Max`,required:!0,control:{type:`text`,value:d,size:`num`,onChange:E(f)}})),e===`addTerm`&&D.push({key:`list`,label:`List`,required:!0,control:{type:`select`,value:p,onChange:E(e=>m(e)),options:[`expect`,`forbid`].map(e=>({value:e,label:Zt(e)}))}}),(e===`addTerm`||e===`removeTerm`)&&D.push({key:`term`,label:`Term`,required:!0,control:{type:`text`,value:h,onChange:E(g)}}),(0,$.jsxs)(y,{title:mi[e],onClose:i,dirty:a!==`keep`||s!==`keep`||!!l||!!d||!!h,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:!w||C,onClick:T,children:`Apply`})]}),children:[D.length>0&&(0,$.jsx)(he,{label:mi[e],rows:D}),(0,$.jsx)(`p`,{className:`note ev-changes`,role:`status`,children:typeof b==`string`?b:`Changes ${w} of ${n.size}`}),C&&S&&(0,$.jsx)(`div`,{className:`ev-refusal`,role:`alert`,children:S.cases.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{className:`ev-refusal-head`,children:[S.cases.length,` of `,n.size,` would break`]}),(0,$.jsx)(`ul`,{children:S.cases.map(e=>(0,$.jsxs)(`li`,{children:[(0,$.jsx)(`b`,{children:e.file}),` `,e.reasons.join(`; `)]},e.key))})]})})]})}function vi({pageSize:e=20}){let t=Ne(),n=Qe(),r=ne(),{openCaseEditor:i}=li(),{list:a}=$e(),{datasetId:s,selected:c,setSelected:l,filters:u,setFilters:d,handedOver:f}=sn(),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(!1),_=(0,Q.useCallback)(()=>m(null),[]),v=a?.find(e=>e.id===s)??a?.[0]??null,y=v?.id??``,b=et(y||null),x=b?.doc?.body??null,S=x?.cases,C=(0,Q.useMemo)(()=>S?K().gradedSetFrom({cases:S}):[],[S]),w=oi(x?.source?.id),T=(0,Q.useMemo)(()=>new Set(C.map(Vt)),[C]),E=(0,Q.useMemo)(()=>new Set([...c].filter(e=>T.has(e))),[c,T]),D=(0,Q.useMemo)(()=>rn(C,u,E,w),[C,u,E,w]),O=!!x&&!x.source;(0,Q.useEffect)(()=>{O&&u.status===`missing`&&d({status:`all`})},[O,u.status,d]);let k=(0,Q.useCallback)(()=>n.entry(y)?.doc?.body??null,[n,y]),A=(0,Q.useCallback)(e=>{y&&n.edit(y,t=>({...t,cases:e}))},[n,y]),j=e=>{i(e,{dataset:y,files:D.map(e=>e.item),onRemove:N})},M=e=>{g(!1),i(e,{dataset:y,files:[...C.map(e=>e.item),e],onRemove:N})};function N(e){let t=k()?.cases??[];A(ai({cases:t},e)),r.offer({label:`Removed ${e}`,restore:()=>A(t)})}let P=e=>{let i=k();if(!y||!i)return null;let{next:a,changed:o}=Jt(i.cases,E,e);if(!o.length)return m(null),null;if(e.type!==`delete`){let e=Yt(i.cases,a,o);if(e.cases.length)return e}Je(t,y,i,`bulk`);let s=i.cases;if(n.edit(y,e=>({...e,cases:a})),e.type===`delete`){let e=new Set(o);l(t=>new Set([...t].filter(t=>!e.has(t))))}return r.offer({label:$t(e,o.length),restore:()=>n.edit(y,e=>({...e,cases:s}))}),m(null),null},F=E.size===0,I=[{label:`Set count…`,icon:o,disabled:F,onSelect:()=>m(`bounds`)},{label:`Add term…`,icon:W.add,disabled:F,onSelect:()=>m(`addTerm`)},{label:`Remove term…`,icon:Ot,disabled:F,onSelect:()=>m(`removeTerm`)},{label:`Mark To do…`,icon:dt,disabled:F,onSelect:()=>m(`todo`)},{label:`Mark graded…`,icon:pt,disabled:F,onSelect:()=>m(`graded`)},{label:`Delete`,icon:W.remove,destructive:!0,disabled:F,onSelect:()=>void P({type:`delete`})}];return(0,$.jsxs)(`div`,{className:`cases`,children:[a?.length?(0,$.jsx)(ui,{rows:C,shown:D,filters:u,onFilters:d,selected:E,onSelect:l,selectionActions:I,sourceFiles:w,hasSource:!!x?.source,loading:!x,loadError:b?.sync.state===`missing`?b.sync.message:null,onRetry:()=>{y&&n.load(y)},pageSize:e,onEdit:j,onAdd:()=>g(!0),onRemove:N,children:f&&v&&(0,$.jsxs)(`p`,{className:`note ev-from`,role:`status`,children:[(0,$.jsxs)(`span`,{children:[`From `,f.from]}),f.found<f.wanted&&(0,$.jsxs)(`span`,{children:[f.found,` of `,f.wanted,` are in `,v.name,` now`]})]})}):null,h&&x?.source&&w&&(0,$.jsx)($r,{title:`Add case`,action:`Add case`,source:x.source,files:w,taken:new Set(C.map(e=>e.item)),onPick:M,onClose:()=>g(!1)}),p&&x&&(0,$.jsx)(_i,{kind:p,cases:x.cases,keys:E,onApply:P,onClose:_}),(0,$.jsx)(le,{undo:r.undo,onUndo:r.undoNow,onDismiss:r.dismiss})]})}function yi({groupId:e,undo:t}){let n=be(),a=Ne(),o=Qe(),{list:c,error:l}=$e(),{pickDataset:u}=sn(),[d,f]=(0,Q.useState)(!1),[p,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(null),[x,C]=(0,Q.useState)(!1),[T,E]=(0,Q.useState)(!1),[O,k]=ge(`dataset-cases`,20),[A,j]=(0,Q.useState)(!1),[M,N]=(0,Q.useState)(null),P=(0,Q.useRef)(null),[F]=Pe(`promptlab.versions`),[I]=Pe(`promptlab.profiles`),ee=e=>F.profile?.[e]?.[0]?.at??null,[L,R]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{let e=!0;return n.sources().then(t=>{e&&R(t.sources)}).catch(()=>{e&&R([])}),()=>{e=!1}},[n]);let z=et(e)?.doc??null,B=z?.body??null,V=c?.find(t=>t.id===e)??null;(0,Q.useEffect)(()=>{u(e)},[e,u]),(0,Q.useEffect)(()=>{c&&!V&&Rr()},[c,V]);let te=(0,Q.useMemo)(()=>e?Ge(a,e):[],[a,e,F]),H=e=>_({text:e instanceof Error?e.message:String(e),bad:!0}),ne=(0,Q.useCallback)(()=>o.entry(e)?.doc?.body??null,[o,e]),re=(0,Q.useCallback)(t=>o.edit(e,t),[o,e]),ie=()=>new Set((o.list().list??[]).map(e=>e.name)),G=async()=>{_(null);try{zr((await o.create(xi(`Untitled eval group`,ie()))).id)}catch(e){H(e)}},ae=t=>{let n=t.trim();z&&n&&n!==z.name&&(_(null),o.rename(e,n).catch(e=>{e instanceof Ae&&e.status===409?_({text:`An eval group is already called ${n}.`,bad:!0}):H(e)}))},oe=async()=>{if(z){_(null);try{await o.flush(e),zr((await o.create(xi(`${z.name} copy`,ie()),structuredClone(z.body))).id)}catch(e){H(e)}}},q=async()=>{if(!z)return;_(null);let{name:n}=z;try{await o.flush(e);let r=await o.remove(e);Rr(),t.offer({label:`Deleted ${n}`,restore:()=>{o.restore(r).then(e=>{zr(e.id),e.name!==n&&_({text:`Restored as ${e.name}.`,bad:!1})}).catch(H)}})}catch(e){H(e)}},J=async e=>{_(null);let t;try{t=await bi(e)}catch(e){H(e);return}let n;try{n=JSON.parse(t)}catch(e){_({text:`Not JSON: ${e instanceof Error?e.message:String(e)}`,bad:!0});return}N(`import`);try{let e=await o.importFile(n);e[0]&&zr(e[0].id),_({text:`Imported ${e.map(e=>e.name).join(`, `)}.`,bad:!1})}catch(e){H(e)}finally{N(null)}},ce=async()=>{e&&(N(`export`),await o.flush(e).catch(()=>{}),await Y(o.exportUrl(e),e=>Fr(`eval-group`,e.group?.name??e.dataset?.name??``,e.version,`json`)),N(null))},Y=async(e,t)=>{try{let n=await fetch(e);if(!n.ok)throw Error(`the export answered ${n.status}`);let r=await n.json();Ir(new Blob([JSON.stringify(r,null,2)+`
7
+ `],{type:`application/json`}),t(r))}catch(e){H(e)}},le=n=>{let r=ne();r&&(Je(a,e,r,`restore`),re(()=>structuredClone(n.doc)),E(!1),t.offer({label:`Restored the eval group`,restore:()=>re(()=>r)}))},ue=(0,Q.useMemo)(()=>{let e=I.list.find(e=>e.id===I.grader);return e?{id:e.id,name:e.name}:null},[I]),X=(0,Q.useMemo)(()=>I.list.filter(e=>(K().CONNECTION_TYPES[e.type??``]?.answers??[`prompt`]).includes(`prompt`)),[I.list]),de=e=>{let{mode:t,threshold:n}=e.scoring,r=e.source&&!(L??[]).some(t=>t.id===e.source.id)?e.source:null;return[{key:`source`,label:`Source`,control:{type:`picker`,kind:`Source`,value:e.source?.id??``,usedLabel:`Last changed`,...qr([...r?[{id:r.id,name:`${r.name} (missing)`}]:[],...L??[]],e=>L?.find(t=>t.id===e)?.changed??null,[{id:``,label:`Any`}]),onChange:e=>{let t=L?.find(t=>t.id===e);re(n=>({...n,source:t?{id:t.id,name:t.name}:r&&r.id===e?r:null}))}}},{key:`mode`,label:`Scoring`,control:{type:`select`,value:t,options:[{value:`all`,label:`All must pass`},{value:`weighted`,label:`Weighted points`}],onChange:e=>re(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`,control:{type:`text`,size:`num`,value:n==null?``:String(n),onChange:e=>re(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:`Profile`,value:e.grader?.id??``,usedLabel:`Last changed`,...qr(X,ee,[{id:``,label:ue?`Lab (${ue.name})`:`None`}]),onChange:e=>{let t=X.find(t=>t.id===e);re(e=>({...e,grader:t?{id:t.id,name:t.name}:null}))}}}]},Z=e=>t=>re(n=>({...n,[e]:t})),pe=e=>(n,r)=>{let i=ne()?.[e]??[];Z(e)(n),t.offer({label:r,restore:()=>re(t=>({...t,[e]:i}))})},me=B?B.cases.filter(e=>!e.todo).length:0,_e=[{label:`Rename…`,icon:S,disabled:!z,onSelect:()=>f(!0)},{label:`Clone`,icon:W.clone,disabled:!z,onSelect:()=>void oe()},{label:`Import JSON…`,icon:U,busy:M===`import`,onSelect:()=>P.current?.click()},{label:`Export JSON`,icon:w,disabled:!z,busy:M===`export`,onSelect:()=>void ce()},{label:`Export all`,icon:bt,disabled:!c?.length,busy:M===`exportAll`,onSelect:()=>{N(`exportAll`),Y(o.exportAllUrl(),e=>Fr(`eval-groups`,`all`,e.version,`json`)).finally(()=>N(null))}},{label:`Restore…`,icon:s,disabled:!te.length||!z,onSelect:()=>E(!0)},{label:`Edit raw…`,icon:_t,disabled:!z,onSelect:()=>C(!0)},{label:`Delete`,icon:m,destructive:!0,disabled:!z,onSelect:()=>void q()}],ve=(0,$.jsx)(`input`,{ref:P,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&&J(t)}}),ye=B?`${B.cases.length} cases, ${me} graded`:void 0;return(0,$.jsxs)(`div`,{className:`datasets`,children:[(0,$.jsx)(r,{kind:`Eval group`,name:z?.name??V?.name??(c===null?`Loading…`:`None`),onPick:c?.length?()=>h(!0):void 0,meta:ye,primary:{label:`New eval group`,icon:v,onSelect:()=>void G()},actions:_e}),g&&(0,$.jsx)(`p`,{className:`note${g.bad?` bad`:``}`,role:g.bad?`alert`:`status`,children:g.text}),ve,B==null?(0,$.jsx)(i,{label:`Eval group`,error:l,onRetry:()=>void o.refresh()}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(b,{id:`grades`,title:`Grades`,level:2,children:(0,$.jsx)(he,{label:`Grades`,rows:de(B)})}),(0,$.jsx)(b,{id:`every`,title:`Every item`,level:2,note:B.every.length?String(B.every.length):void 0,children:(0,$.jsx)(Gr,{label:`Every item`,metrics:B.every,over:`item`,set:Z(`every`),undoable:pe(`every`)})}),(0,$.jsx)(b,{id:`run`,title:`Whole run`,level:2,note:B.run.length?String(B.run.length):void 0,children:(0,$.jsx)(Gr,{label:`Whole run`,metrics:B.run,over:`run`,set:Z(`run`),undoable:pe(`run`)})}),(0,$.jsx)(b,{id:`cases`,title:`Cases`,level:2,note:String(B.cases.length),actions:[{label:`Page size…`,icon:W.pageSize,onSelect:()=>j(!0)}],children:(0,$.jsx)(vi,{pageSize:O})})]}),p&&c&&(0,$.jsx)(se,{kind:`Eval group`,value:e,onClose:()=>h(!1),options:c.map(e=>({id:e.id,label:e.name})),onPick:e=>{_(null),zr(e)}}),d&&z&&(0,$.jsx)(fe,{title:`Rename eval group`,value:z.name,onCommit:ae,onClose:()=>f(!1)}),A&&(0,$.jsx)(D,{value:O,onChange:k,onClose:()=>j(!1)}),T&&z&&(0,$.jsx)(y,{title:`Restore eval group`,onClose:()=>E(!1),children:(0,$.jsxs)(`div`,{className:`version-list`,children:[te.length===0&&(0,$.jsx)(`p`,{className:`note`,children:`No versions of this eval group yet.`}),te.map((e,t)=>(0,$.jsxs)(`div`,{className:`version-row`,children:[(0,$.jsxs)(`span`,{className:`version-when`,children:[Ci(e.at),`, `,Si(e.reason)]}),(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>le(e),children:`Restore`})]},`${e.at}-${t}`))]})}),x&&z&&(0,$.jsx)(Jr,{name:z.name,body:z.body,onSave:e=>{re(()=>e),C(!1)},onClose:()=>C(!1)})]})}function bi(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 xi=(e,t)=>{if(!t.has(e))return e;for(let n=2;;n++)if(!t.has(`${e} ${n}`))return`${e} ${n}`},Si=e=>e===`idle`?`after editing`:e===`restore`?`before a restore`:e===`bulk`?`before a bulk edit`:e===`pack`?`before a pack update`:e,Ci=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()};function wi({groupId:e}){let t=ne();return(0,$.jsxs)($.Fragment,{children:[e?(0,$.jsx)(yi,{groupId:e,undo:t}):(0,$.jsx)(Br,{undo:t}),(0,$.jsx)(le,{undo:t.undo,onUndo:t.undoNow,onDismiss:t.dismiss})]})}var Ti=[{value:`all`,label:`All`},{value:`used`,label:`Used`},{value:`unused`,label:`Unused`}],Ei=[{value:`all`,label:`All`},{value:`scenario`,label:`Used by this target`},{value:`scenarios`,label:`Used by all targets`}];function Di(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 Oi(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 ki=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()};function Ai(e){return e.id===null?(0,$.jsx)(ji,{onClose:e.onClose}):(0,$.jsx)(Mi,{...e,id:e.id})}function ji({onClose:e}){let t=ct(),[n,r]=(0,Q.useState)(``),[i,a]=(0,Q.useState)(``),[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.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)(j,{title:`New prompt`,status:o??void 0,statusBad:!!o,focusRow:`text`,wide:!0,sections:[{key:`prompt`,rows:[{key:`name`,label:`Name`,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 Mi({id:e,onClose:t,onDuplicate:n,onDelete:r}){let o=ct(),s=ut(e),[c,l]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(!1),{openRun:m}=un(),[h,g]=(0,Q.useState)(new Set),[_,v]=(0,Q.useState)(new Set),[y,b]=(0,Q.useState)(null),x=s?.doc;if(!x)return(0,$.jsx)(j,{title:`Prompt`,sections:[{key:`loading`,children:(0,$.jsx)(i,{label:`Prompt`,error:s?.sync.state===`missing`?s.sync.message:null,onRetry:()=>o.load(e)})}],onClose:t});let S=(e,t,n)=>{let r=new Set(e);r.has(t)?r.delete(t):r.add(t),n(r)},C=e=>b(e instanceof Error?e.message:String(e)),w=e=>x.versions.find(t=>t.version===e)?.text??``,T=x.uses.some(e=>e.job>0),E=[{key:`version`,header:`Version`,sort:e=>e.version,cell:e=>`v${e.version}${e.version===x.version?` (newest)`:``}`},{key:`created`,header:`Made`,sort:e=>e.created,cell:e=>ki(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)(a,{label:`v${t.version} actions`,actions:[{label:h.has(t.version)?`Hide words`:`Show words`,icon:u,onSelect:()=>S(h,t.version,g)},{label:`Restore`,icon:p,disabled:t.version===x.version,onSelect:()=>{b(null),o.restoreVersion(e,t.version).catch(C)}}]})}],D=e=>`${e.runId}:${e.scenarioId}:${e.job}`,O=[{key:`run`,header:`Run`,sort:e=>e.submittedAt,cell:e=>(0,$.jsx)(`a`,{className:`pl-run`,href:`#/history`,onClick:n=>{n.preventDefault(),t(),m(e.runId,{at:e.submittedAt,from:`history`})},children:En(e.submittedAt)})},{key:`scenario`,header:`Scenario`,sort:e=>e.scenarioName,cell:e=>e.scenarioName},...T?[{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=>ki(e.submittedAt)},{key:`menu`,header:``,label:``,className:`pl-menu`,role:`menu`,sort:null,cell:e=>(0,$.jsx)(a,{label:`${En(e.submittedAt)} ${e.scenarioName} actions`,actions:[{label:_.has(D(e))?`Hide words`:`Show words`,icon:u,onSelect:()=>S(_,D(e),v)}]})}],k=[{label:`Set as default`,icon:Rt,disabled:x.default,onSelect:()=>{b(null),o.setDefault(e).catch(C)}},{label:`Duplicate`,icon:W.clone,onSelect:()=>n(x)},{label:`Delete`,icon:W.remove,destructive:!0,disabled:x.default,onSelect:()=>r(x)}],A=c?.name??x.name,M=c?.text??x.text,N=A!==x.name||M!==x.text,P=e=>l({name:A,text:M,...e}),F=async()=>{if(!N){t();return}f(!0),o.edit(e,{name:A,text:M});try{if(await o.flush(e),o.entry(e)?.sync.state===`conflict`){l(null),f(!1);return}t()}catch(e){C(e),f(!1)}},I=y??nt(s.sync),ee=s.sync.state===`conflict`;return(0,$.jsx)(j,{title:tt({...x,name:A,text:M}),status:I??void 0,statusBad:!!I,menu:k,wide:!0,actions:ee?[{label:`Take theirs`,onSelect:()=>void o.resolve(e,`theirs`)},{label:`Keep mine`,onSelect:()=>void o.resolve(e,`mine`)}]:[],dirty:N,saving:d,onSave:()=>void F(),onClose:t,sections:[{key:`prompt`,rows:[{key:`name`,label:`Name`,control:{type:`text`,value:A,placeholder:`First line`,onChange:e=>P({name:e})}},{key:`version`,label:`Version`,required:!0,control:{type:`static`,text:`v${x.version}${x.default?` (Default)`:``}`}},{key:`text`,label:`Prompt`,required:!0,control:{type:`textarea`,value:M,placeholder:`None`,onChange:e=>P({text:e})}}]},{key:`versions`,title:`Versions`,children:(0,$.jsx)(R,{className:`pltable pl-versions`,label:`Versions`,rows:x.versions,rowKey:e=>String(e.version),defaultSort:{key:`version`,dir:`desc`},columns:E,after:e=>h.has(e.version)&&(0,$.jsx)(`tr`,{className:`pl-words-row`,children:(0,$.jsx)(`td`,{colSpan:E.length,children:(0,$.jsx)(`pre`,{className:`pl-words`,children:e.text})})})})},{key:`uses`,title:`Uses`,children:x.uses.length===0?(0,$.jsx)(`p`,{className:`note`,children:`No uses yet.`}):(0,$.jsx)(R,{className:`pltable pl-uses`,label:`Uses`,rows:x.uses,rowKey:D,pageSize:10,defaultSort:{key:`when`,dir:`desc`},columns:O,after:e=>_.has(D(e))&&(0,$.jsx)(`tr`,{className:`pl-words-row`,children:(0,$.jsx)(`td`,{colSpan:O.length,children:(0,$.jsx)(`pre`,{className:`pl-words`,children:w(e.version)})})})})}]})}var Ni=`#new`;function Pi(){let e=ct(),{list:t,error:n}=lt(),r=ne(),[o,s]=ge(`prompts`,20),[c,l]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)(``),[f,p]=(0,Q.useState)(`all`),[m,h]=(0,Q.useState)(null),[g,_]=(0,Q.useState)(null),y=t??[],x=y.filter(e=>Di(e,u,f)),S=e=>_(e instanceof Error?e.message:String(e)),C=async()=>{_(null),h(Ni)},w=async t=>{_(null);try{await e.flush(t.id);let n=await e.create({name:`${tt(t)} copy`,text:e.entry(t.id)?.doc?.text??t.text});h(n.id)}catch(e){S(e)}},T=async t=>{_(null);let n=[];try{for(let r of t)n.push(await e.remove(r.id)),m===r.id&&h(null)}catch(e){S(e)}n.length&&r.offer({label:t.length===1?`Deleted ${tt(t[0])}`:`Deleted ${n.length} prompts`,restore:()=>{for(let t of n)e.restore(t).catch(S)}})},E=e=>T([e]),O=t=>{_(null),e.setDefault(t.id).catch(S)},k=e=>[{label:`Edit…`,icon:W.edit,onSelect:()=>h(e.id)},{label:`Set as default`,icon:Rt,disabled:e.default,onSelect:()=>O(e)},{label:`Duplicate`,icon:W.clone,onSelect:()=>void w(e)},{label:`Delete`,icon:W.remove,destructive:!0,disabled:e.default,onSelect:()=>void E(e)}];return(0,$.jsxs)(b,{id:`prompts`,title:`Prompt library`,note:t?`${y.length} ${y.length===1?`prompt`:`prompts`}`:void 0,actions:[{label:`Page size…`,icon:W.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:[t===null?(0,$.jsx)(i,{label:`Prompts`,error:n,onRetry:()=>void e.refresh()}):y.length===0?(0,$.jsx)(`p`,{className:`note`,children:`No prompts yet.`}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ie,{noun:`prompts`,search:{label:`Search prompts`,placeholder:`Search prompts`,value:u,onChange:d},filters:[{key:`show`,label:`Show`,value:f,onChange:e=>p(e),options:Ti}],count:{shown:x.length,total:y.length}}),x.length===0?(0,$.jsx)(`p`,{className:`note`,children:`No prompts match these filters.`}):(0,$.jsx)(R,{className:`pl-prompts`,cards:!0,label:`Prompts`,rows:x,rowKey:e=>e.id,pageSize:o,rowProps:e=>({"data-default":e.default||void 0}),columns:[{key:`prompt`,header:`Prompt`,role:`title`,sort:e=>tt(e).toLowerCase(),cell:e=>(0,$.jsxs)(`button`,{type:`button`,className:`pl-open`,onClick:()=>h(e.id),children:[(0,$.jsxs)(`span`,{className:`pl-title`,children:[tt(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?ki(e.lastUsed):`—`},{key:`menu`,header:``,label:``,role:`menu`,sort:null,cell:e=>(0,$.jsx)(a,{label:`${tt(e)} actions`,actions:k(e)})}],select:{noun:`prompt`,label:tt,actions:e=>[{label:`Delete`,icon:W.remove,destructive:!0,disabled:e.every(e=>e.default),onSelect:()=>void T(e.filter(e=>!e.default))}]}})]}),g&&(0,$.jsx)(`p`,{className:`note bad`,role:`alert`,children:g}),(0,$.jsxs)(`button`,{type:`button`,className:`ghost pl-add`,onClick:()=>void C(),children:[(0,$.jsx)(v,{size:14,"aria-hidden":`true`}),`Add prompt`]}),m&&(0,$.jsx)(Ai,{id:m===Ni?null:m,onClose:()=>h(null),onDuplicate:e=>void w(e),onDelete:e=>void E(e)}),c&&(0,$.jsx)(D,{value:o,onChange:s,onClose:()=>l(!1)}),(0,$.jsx)(le,{undo:r.undo,onUndo:r.undoNow,onDismiss:r.dismiss})]})}var Fi=`evals-lab.sources`,Ii={view:`thumbs`,sort:`name`,dir:1};function Li(){try{let e=window.localStorage.getItem(Fi);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 Ii}function Ri(e){try{window.localStorage.setItem(Fi,JSON.stringify(e))}catch{}}var zi=e=>{let t=e.lastIndexOf(`.`);return t<0?``:e.slice(t).toLowerCase()},Bi=[`.heic`,`.heif`,`.dng`,`.tif`,`.tiff`],Vi=[`.jpg`,`.jpeg`,`.png`],Hi=e=>Vi.includes(zi(e))||Bi.includes(zi(e)),Ui=(e,t)=>`/api/sources/${encodeURIComponent(e)}/thumbs/${encodeURIComponent(t.name)}${t.v?`?v=${t.v}`:``}`,Wi=(e,t)=>Bi.includes(zi(t.name))?`/api/sources/${encodeURIComponent(e)}/zoom/${encodeURIComponent(t.name)}`:`/api/sources/${encodeURIComponent(e)}/files/${encodeURIComponent(t.name)}`;function Gi(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 Ki(e,t){let n=t.trim().toLowerCase();return n?e.filter(e=>e.name.toLowerCase().includes(n)):[...e]}function qi(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 Ji(e){return new Date(e*1e3).toLocaleDateString(void 0,{year:`numeric`,month:`short`,day:`numeric`})}function Yi(e){return{id:e.id,name:e.name,system:e.system,type:e.type,files:e.files.length,bytes:e.bytes}}var Xi=`[redacted]`,Zi=/^(?:api[-_]?key|x-api-key|authorization|ocp-apim-subscription-key|password|secret|client[-_]?secret|token|access[-_]?token|refresh[-_]?token|sig)$/i,Qi=/^(?:headers|authentication)$/,$i=[[/sk-ant-[A-Za-z0-9_-]+/g,Xi],[/sk-[A-Za-z0-9_-]{20,}/g,Xi],[/Bearer\s+[A-Za-z0-9._~+/=-]+/g,`Bearer ${Xi}`],[/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,Xi],[/([?&](?:sig|code)=)[^&"\s]+/g,`$1${Xi}`]];function ea(e){let t=0,n=e=>{let n=e;for(let[e,r]of $i)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))Qi.test(i)&&a&&typeof a==`object`&&!Array.isArray(a)?n[i]=Object.fromEntries(Object.keys(a).map(e=>(t++,[e,Xi]))):Qi.test(i)&&typeof a==`string`||Zi.test(i)&&a!=null&&typeof a!=`object`?(t++,n[i]=Xi):n[i]=r(a);return n}return typeof e==`string`?n(e):e};return{value:r(e),count:t}}var ta=`https://api.flow.microsoft.com/providers/Microsoft.ProcessSimple`,na=`api-version=2016-11-01`,ra=/\.powerplatformusercontent\.com$/,ia=4,aa=4;function oa(e,t=(e,t)=>fetch(e,t)){let n=async n=>{let r=`${ta}${n}${n.includes(`?`)?`&`:`?`}${na}`;if(!r.startsWith(`https://api.flow.microsoft.com/providers/Microsoft.ProcessSimple/`))throw Error(`the Flow API is the only address a Microsoft token goes to`);let i=await t(r,{headers:{Authorization:`Bearer ${await e()}`}}),a=await i.text(),o=null;try{o=JSON.parse(a)}catch{}if(!i.ok){let e=o?.error?.code;throw Error(`Power Automate answered ${i.status}${e?` (${e})`:``}`)}return o},r=encodeURIComponent,i=e=>({status:e?.status??``,startTime:e?.startTime??null,error:e?.error??null,inputsLink:e?.inputsLink?.uri??null,outputsLink:e?.outputsLink?.uri??null,at:Object.fromEntries((e?.repetitionIndexes??[]).filter(e=>e.scopeName&&typeof e.itemIndex==`number`).map(e=>[e.scopeName,e.itemIndex]))}),a=e=>{let t=new URL(e);return t.searchParams.delete(`api-version`),`${t.pathname.slice(new URL(ta).pathname.length)}${t.search}`},o=(e,t)=>`/environments/${r(e)}/flows/${r(t)}/runs`,s=0,c=[],l=async()=>{if(s<ia){s++;return}await new Promise(e=>c.push(e))},u=()=>{let e=c.shift();e?e():s--};return{environments:async()=>((await n(`/environments`)).value??[]).map(e=>({id:e.name,name:e.properties?.displayName||e.name,isDefault:!!e.properties?.isDefault})),flows:async e=>((await n(`/environments/${r(e)}/flows`)).value??[]).map(e=>({id:e.name,name:e.properties?.displayName||e.name,state:e.properties?.state??``})),flow:async(e,t)=>{let i=await n(`/environments/${r(e)}/flows/${r(t)}`);return{id:i.name,name:i.properties?.displayName||i.name,definition:i.properties?.definition??{}}},runs:async(e,t,r=250)=>{let i=[],s=o(e,t);for(;s&&i.length<r;){let e=await n(s);for(let t of e.value??[])i.push({id:t.name,status:t.properties?.status??``,startTime:t.properties?.startTime??null,error:t.properties?.error??null});s=e.nextLink?.startsWith(`https://api.flow.microsoft.com/providers/Microsoft.ProcessSimple/`)?a(e.nextLink):null}return i.slice(0,r)},run:async(e,t,a)=>{let s=await n(`${o(e,t)}/${r(a)}?$expand=properties/actions`),c=s.properties??{};return{run:{id:s.name,status:c.status??``,startTime:c.startTime??null,error:c.error??null},trigger:c.trigger?i(c.trigger):null,actions:Object.fromEntries(Object.entries(c.actions??{}).map(([e,t])=>[e,i(t)]))}},repetitions:async(e,t,a,s)=>((await n(`${o(e,t)}/${r(a)}/actions/${r(s)}/repetitions`)).value??[]).map(e=>i(e.properties)),content:async e=>{let n=new URL(e);if(n.protocol!==`https:`||!ra.test(n.hostname))throw Error(`that is not run history's content`);await l();try{for(let n=1;;n++){let r=await t(e,{});if(r.status===429&&n<aa){let e=Number(r.headers.get(`Retry-After`));await new Promise(t=>setTimeout(t,(e>0?e:n)*1e3));continue}if(!r.ok)throw Error(`run history answered ${r.status}`);let i=await r.text();try{return JSON.parse(i)}catch{return i}}}finally{u()}}}}var sa=[`https://service.flow.microsoft.com//.default`],ca=null;function la(e){let t=`${e.clientId}/${e.tenant}`;return ca?.key!==t&&(ca={key:t,pca:we(()=>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}),[])}),ca.pca}var ua=()=>{let e=new URLSearchParams(window.location.search);return e.has(`state`)&&(e.has(`code`)||e.has(`error`))};async function da(e){await la(e)}async function fa(e){let t=await la(e);return(t.getActiveAccount()??t.getAllAccounts()[0]??null)?.username??null}var pa=`signin`;function ma(e=window.location.href){let t=new URL(e);return t.hostname===`127.0.0.1`?(t.hostname=`localhost`,t.searchParams.set(pa,`microsoft`),t.href):null}function ha(){let e=new URL(window.location.href);return e.searchParams.get(`signin`)===`microsoft`&&(e.searchParams.delete(pa),window.history.replaceState(window.history.state,``,e.href),!0)}async function ga(e,t=window.location.href){let n=ma();if(n){window.location.assign(n);return}await(await la(e)).loginRedirect({scopes:sa,prompt:`select_account`,redirectStartPage:t})}async function _a(e){let t=await la(e),n=t.getActiveAccount()??t.getAllAccounts()[0];n&&await t.clearCache({account:n})}async function va(e){let t=await la(e),n=t.getActiveAccount()??t.getAllAccounts()[0];if(!n)throw Error(`sign in to Microsoft first`);try{return(await t.acquireTokenSilent({scopes:sa,account:n})).accessToken}catch(e){let{InteractionRequiredAuthError:r}=await we(async()=>{let{InteractionRequiredAuthError:e}=await import(`./dist-DI3ewZYj.js`);return{InteractionRequiredAuthError:e}},[]);throw e instanceof r&&await t.acquireTokenRedirect({scopes:sa,account:n,redirectStartPage:window.location.href}),e}}var ya=new EventTarget,ba=()=>ya.dispatchEvent(new Event(`change`));function xa(){let e=be(),[t,n]=(0,Q.useState)({cfg:void 0,editable:!1});return(0,Q.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(),ya.addEventListener(`change`,r),()=>{t=!1,ya.removeEventListener(`change`,r)}},[e]),t}var Sa=()=>xa().cfg,Ca=e=>oa(()=>va(e));async function wa(e,t,n){let r=await e.flow(t,n);return{name:r.name,definition:ea(r.definition).value}}function Ta({onMade:e}){let t=be(),n=Sa(),r=(0,Q.useMemo)(()=>n?Ca(n):null,[n]),[a,o]=(0,Q.useState)(void 0),[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(``),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(``),[h,g]=(0,Q.useState)(``),[_,v]=(0,Q.useState)(!1),[y,b]=(0,Q.useState)(null),x=e=>b(e instanceof Error?e.message:String(e));if((0,Q.useEffect)(()=>{n&&fa(n).then(o,()=>o(null))},[n]),(0,Q.useEffect)(()=>{r&&a&&r.environments().then(e=>{c(e),u((e.find(e=>e.isDefault)??e[0])?.id??``)},x)},[r,a]),(0,Q.useEffect)(()=>{r&&l&&(f(null),m(``),r.flows(l).then(e=>{f(e),m(e[0]?.id??``),g(e[0]?.name??``)},x))},[r,l]),n===void 0||n&&a===void 0)return(0,$.jsx)(i,{label:`Account`});if(n===null)return(0,$.jsx)(`p`,{className:`note`,children:`Microsoft: Not Configured`});if(!a)return(0,$.jsxs)(`div`,{className:`sacts`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`ghost`,onClick:()=>void ga(n).catch(x),children:[(0,$.jsx)(Et,{size:14,"aria-hidden":`true`}),` Sign in with Microsoft`]}),y&&(0,$.jsx)(`p`,{className:`note bad`,role:`alert`,children:y})]});let S=async()=>{if(!r||!p||!h.trim())return;v(!0),b(null);let n=null;try{let i=d?.find(e=>e.id===p),a=await t.createSource(h.trim(),`power-automate`,{environment:l,flow:p,displayName:i?.name??p});n=a.id;let o=await wa(r,l,p);await t.saveDefinition(a.id,0,o.definition),await e()}catch(e){n&&await t.removeSource(n).catch(()=>{}),x(e instanceof Ae?Error(e.message):e)}finally{v(!1)}};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(he,{label:`Flow`,rows:[{key:`account`,label:`Account`,control:{type:`static`,text:a}},{key:`env`,label:`Environment`,control:s?{type:`select`,value:l,options:s.map(e=>({value:e.id,label:e.name})),onChange:u}:{type:`static`,text:`Loading…`}},{key:`flow`,label:`Flow`,control:d?{type:`select`,value:p,options:d.map(e=>({value:e.id,label:e.name})),onChange:e=>{m(e),g(d.find(t=>t.id===e)?.name??``)}}:{type:`static`,text:l?`Loading…`:`—`}},{key:`name`,label:`Name`,control:{type:`text`,value:h,onChange:g}}]}),d&&!d.length&&(0,$.jsx)(`p`,{className:`note`,children:`No flows in this environment.`}),y&&(0,$.jsx)(`p`,{className:`note bad`,role:`alert`,children:y}),(0,$.jsx)(`div`,{className:`sacts`,children:(0,$.jsx)(`button`,{type:`button`,disabled:_||!p||!h.trim(),onClick:()=>void S(),children:`Add`})})]})}var Ea=`evals-lab/record`,Da=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Oa=/\b(triggerBody|triggerOutputs|body|outputs|actions|variables|items|item|parameters)\(\s*(?:'((?:[^']|'')*)')?\s*\)/g;function ka(e,t=[]){if(typeof e==`string`){e.startsWith(`@`)&&!e.startsWith(`@@`)&&!e.startsWith(`@{`)&&t.push(e.slice(1));for(let n of e.matchAll(/@\{([^}]*)\}/g))t.push(n[1])}else if(Array.isArray(e))for(let n of e)ka(n,t);else if(Da(e))for(let n of Object.values(e))ka(n,t);return t}function Aa(e,t=null){let n=new Map;for(let r of ka(e))for(let e of r.matchAll(Oa)){let r=e[1],i=(e[2]??``).replace(/''/g,`'`),a=r===`triggerBody`||r===`triggerOutputs`?{from:`trigger`}:r===`body`||r===`outputs`||r===`actions`?i?{from:`action`,name:i}:null:r===`variables`?i?{from:`variable`,name:i}:null:r===`items`?i?{from:`item`,name:i}:null:r===`item`?t?{from:`item`,name:t}:null:i?{from:`parameter`,name:i}:null;a&&n.set(JSON.stringify(a),a)}return[...n.values()]}function ja(e,t){let n={};for(let e of t)e.from===`trigger`?n.trigger={body:null}:e.from===`action`?(n.actions??={})[e.name]={body:null}:e.from===`variable`?(n.variables??={})[e.name]=null:e.from===`item`&&((n.items??={})[e.name]=null);return{format:Ea,version:1,step:e,at:null,scope:n,request:null,result:null,origin:{kind:`hand`}}}function Ma(e){if(e.origin?.kind===`run`&&e.origin.run)return JSON.stringify({step:e.step,run:e.origin.run,iteration:e.origin.iteration??``});let t=e=>Array.isArray(e)?e.map(t):Da(e)?Object.fromEntries(Object.keys(e).sort().map(n=>[n,t(e[n])])):e;return JSON.stringify(t({step:e.step,scope:e.scope,request:e.request}))}var Na=Object.create(null);Na.Http={label:`HTTP`,template:({headers:e,authentication:t,...n})=>n};var Pa=Object.create(null);Pa.Foreach={loops:!0},Pa.Until={loops:!0},Pa.InitializeVariable={declares:e=>(Array.isArray(e.variables)?e.variables:[]).flatMap(e=>Da(e)&&typeof e.name==`string`?[e.name]:[])};var Fa=e=>!!(e&&Pa[e]?.loops);function Ia(e){let t=[],n=(e,r)=>{for(let[i,a]of Object.entries(e??{})){let e=a.type?Na[a.type]:void 0;if(e&&Da(a.inputs)){let n=e.template(a.inputs);t.push({name:i,kind:a.type,loops:r,template:n,reads:Aa(n,r.at(-1)??null)})}let o=Fa(a.type)?[...r,i]:r;n(a.actions,o),n(a.else?.actions,o);for(let e of Object.values(a.cases??{}))n(e.actions,o);n(a.default?.actions,o)}};return n(Da(e)?e.actions:void 0,[]),t}function La(e){let t={},n=(e,r)=>{for(let[i,a]of Object.entries(e??{})){t[i]={...a,loops:r};let e=Fa(a.type)?[...r,i]:r;n(a.actions,e),n(a.else?.actions,e);for(let t of Object.values(a.cases??{}))n(t.actions,e);n(a.default?.actions,e)}};return n(Da(e)?e.actions:void 0,[]),t}async function Ra(e,t,n,r){let i=La(r),a={};for(let r of e.reads)if(r.from===`trigger`){let e=await n.triggerOutputs();a.trigger={body:Da(e)?e.body:e}}else if(r.from===`action`){let e=await n.actionOutputs(r.name,t.at);(a.actions??={})[r.name]=Da(e)?{body:e.body,...typeof e.statusCode==`number`?{statusCode:e.statusCode}:{}}:{body:e}}else if(r.from===`variable`){let e=e=>{let t=e.type?Pa[e.type]:void 0;return!!t?.declares&&Da(e.inputs)&&t.declares(e.inputs).includes(r.name)},o=Object.entries(i).find(([,t])=>e(t)),s=o?await n.actionInputs(o[0],t.at):null,c=(Da(s)&&Array.isArray(s.variables)?s.variables:[]).find(e=>Da(e)&&e.name===r.name);(a.variables??={})[r.name]=c?c.value:null}else if(r.from===`item`){let e=await n.actionInputs(r.name,t.at),i=Da(e)&&Array.isArray(e.foreachItems)?e.foreachItems:[];(a.items??={})[r.name]=i[t.at[r.name]??0]??null}let o=Da(t.inputs)?t.inputs:null,s=Da(t.outputs)?t.outputs:null;return{format:Ea,version:1,step:e.name,at:t.startTime,scope:a,request:o?{method:String(o.method??``),uri:String(o.uri??``),body:o.body??null}:null,result:t.error&&!s?{error:t.error}:s?{status:typeof s.statusCode==`number`?s.statusCode:0,body:s.body??null}:null,origin:{kind:`run`,run:t.run,...Object.keys(t.at).length?{iteration:Object.entries(t.at).map(([e,t])=>`${e}[${t}]`).join(`,`)}:{}}}}function za(e){let t=e.origin.kind===`run`?`${(e.origin.run??``).slice(-8)}${e.origin.iteration?`-${e.origin.iteration.replace(/.*\[(\d+)\]$/,`$1`)}`:``}`:new Date().toISOString().replace(/\D/g,``).slice(0,14);return`${e.step}-${t}.json`.replace(/[^A-Za-z0-9._-]/g,`_`)}var Ba=e=>e.from===`trigger`?`trigger`:e.from===`parameter`?``:e.name,Va=e=>{if(typeof e!=`string`)return e;try{return JSON.parse(e)}catch{return e}};function Ha(e,t){let n=[...new Set(t.flatMap(e=>Object.keys(e)))],r=new Set(e.reads.map(Ba).filter(Boolean)),i=n.filter(e=>!r.has(e)&&!(r.has(`trigger`)&&e.startsWith(`trigger.`)));return{records:t.map(t=>{let n=ja(e.name,e.reads);n.origin={kind:`upload`};for(let r of e.reads){let e=Ba(r);if(r.from===`trigger`){let r=Object.keys(t).filter(e=>e.startsWith(`trigger.`)),i=e in t?Va(t[e]):r.length?Object.fromEntries(r.map(e=>[e.slice(8),Va(t[e])])):null;n.scope.trigger={body:i}}else if(e in t){let i=Va(t[e]);r.from===`action`?n.scope.actions[r.name]={body:i}:r.from===`variable`?n.scope.variables[r.name]=i:r.from===`item`&&(n.scope.items[r.name]=i)}}return n}),unmatched:i}}function Ua(e){let t=[],n=[],r=``,i=!1,a=e.replace(/^/,``);for(let e=0;e<a.length;e++){let o=a[e];i?o===`"`&&a[e+1]===`"`?(r+=`"`,e++):o===`"`?i=!1:r+=o:o===`"`?i=!0:o===`,`?(n.push(r),r=``):o===`
8
+ `||o===`\r`?(o===`\r`&&a[e+1]===`
9
+ `&&e++,n.push(r),t.push(n),n=[],r=``):r+=o}(r||n.length)&&(n.push(r),t.push(n));let[o,...s]=t.filter(e=>e.some(e=>e!==``));return o?s.map(e=>Object.fromEntries(o.map((t,n)=>[t.trim(),e[n]??``]))):[]}function Wa(e,t,n){if(!t.request)return{match:null};let r=Da(n)&&Da(n.parameters)?Object.fromEntries(Object.entries(n.parameters).map(([e,t])=>[e,Da(t)?t.defaultValue:void 0])):{},i;try{let n={scope:t.scope,loop:e.loops.at(-1)??null,now:t.at,parameters:r},a=e.template;i={method:V(a.method,n),uri:V(a.uri,n),body:V(a.body??null,n)}}catch(e){return{match:!1,where:e instanceof Error?e.message:String(e)}}let a=Ga(i,t.request,`request`);return a?{match:!1,where:a}:{match:!0}}function Ga(e,t,n){if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return`${n} has ${e.length} entries, production ${t.length}`;for(let r=0;r<e.length;r++){let i=Ga(e[r],t[r],`${n}[${r}]`);if(i)return i}return null}if(Da(e)&&Da(t)){let r=Object.keys(e),i=Object.keys(t);if(r.join()!==i.join())return`${n} has keys ${r.join(`, `)}, production ${i.join(`, `)}`;for(let i of r){let r=Ga(e[i],t[i],`${n}.${i}`);if(r)return r}return null}return JSON.stringify(e)===JSON.stringify(t)?null:`${n}`}var Ka=Object.create(null);Ka.ParseJson={reads:e=>typeof e.content==`string`?e.content:null,schema:e=>e.schema??null};function qa(e,t){for(let[n,r]of Object.entries(La(e))){let e=r.type?Ka[r.type]:void 0,i=e&&Da(r.inputs)?e.reads(r.inputs):null;if(i&&Aa(i).some(e=>e.from===`action`&&e.name===t))return{name:n,expression:i,schema:e.schema&&Da(r.inputs)?e.schema(r.inputs)??null:null}}return null}function Ja(e,t){let n=JSON.stringify(Da(e)?e.actions??{}:{}),r=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`).replace(/'/g,`''`),i=new Set;for(let e of n.matchAll(RegExp(`body\\('${r}'\\)\\??\\['((?:[^']|'')*)'\\]`,`g`)))i.add(e[1].replace(/''/g,`'`));return[...i]}function Ya(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}}function Xa(e,t){let n=K(),r=t.filter(e=>(n.CONNECTION_TYPES[e.type??``]?.answers??[`prompt`]).includes(`request`)),i=(()=>{try{return new URL(e).host}catch{return null}})(),a=r.find(e=>{try{return new URL(n.connectionBase(e)).host===i}catch{return!1}})??r[0];return a?{id:a.id,name:a.name??``}:{id:`http-endpoint`,name:`HTTP endpoint`}}function Za(e,t,n,r){let i=K(),a=n.template,o=String(a.uri??``),s=i.httpApiFor(o),c={type:`httpRequest`,api:s,method:String(a.method??`POST`).toUpperCase(),...Ya(o),body:a.body??null,...i.HTTP_APIS[s].cellOf(a.body??null)},l=qa(t,n.name),u=l?Ja(t,l.name):[],d=[...l?[{type:`is-json`,schema:l.schema?JSON.stringify(l.schema,null,2):``}]:[],...u.length?[{type:`fields-equal-production`,fields:u.join(`
10
+ `)}]:[]],f=Xa(o,r),p=i.withOut({type:`job`,id:i.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:s},...l?.expression?[{type:`readAs`,readAs:l.expression}]:[]]},{kind:`text`,...i.OUTPUT_KINDS.text?.settingDefaults?.()??{},modifiers:i.OUTPUT_KINDS.text?.modifiers?.()??[]});return{version:i.PIPELINE_VERSION,id:i.newId(),name:`${e.name} · ${n.name}`,jobs:[p],targets:[{id:i.newId(),name:`Production`,profile:f,steps:[structuredClone(c)]},{id:i.newId(),name:`Edited`,profile:f,steps:[structuredClone(c)]}],evals:d.length?[i.newEval(`group`,``,{own:{...i.EVAL_TYPES.group.defaults().own,every:d}})]:[],pass:{mode:`all`}}}function Qa(e,t){let n=e.result;if(!n||!(`status`in n))return null;let r=Ia(t).find(t=>t.name===e.step);if(!r)return null;let i=String(r.template.uri??``),a={step:r.name,loop:r.loops.at(-1)??null,api:K().httpApiFor(i),readAs:qa(t,r.name)?.expression??null};try{return K().httpReplyOf(a,{prompt:``},n.body,n.status,{scope:e.scope,now:e.at}).raw}catch{return null}}function $a(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}]}function eo(e,t){let n=[],r=0;for(let{name:i,record:a}of e){let e=Qa(a,t);if(e==null){r++;continue}let o=qa(t,a.step),s=o?Ja(t,o.name):[];n.push({id:i.replace(/\.json$/i,``).replace(/[^A-Za-z0-9._-]/g,`_`),item:i,todo:!0,note:``,metrics:$a(e,s)})}return{cases:n,skipped:r}}async function to(e,t,n,r,i){let a=await e.run(t,n,r),o=La(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 no(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 to(e,t,n,o,a);for(let e of await r.callsOf(i)){let t=ea(await Ra(i,e,r,a)).value,n=Ma(t);if(c.has(n)){u++;continue}c.add(n),l.push(t)}s?.(++d)}return{records:l,skipped:u}}var ro=e=>e.name.toLowerCase().endsWith(`.json`),io=e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result)),r.onerror=()=>n(r.error),r.readAsText(e)}),ao=`evals-lab.flow.importing`;function oo(e){try{return sessionStorage.getItem(e)}catch{return null}}function so(e,t){try{t?sessionStorage.setItem(e,t):sessionStorage.removeItem(e)}catch{}}var co=e=>e instanceof Error?e.message:String(e);function lo({source:e,definition:t,cfg:n}){let r=be(),o=Qe(),c=ne(),[l,d]=(0,Q.useState)(e.files.filter(ro)),[f,p]=(0,Q.useState)({}),[h,g]=(0,Q.useState)(null),[_,x]=(0,Q.useState)(()=>{let t=oo(ao)===e.id;return t&&so(ao,null),t?`import`:null}),[S,C]=(0,Q.useState)(null),T=(0,Q.useMemo)(()=>Ia(t),[t]),[D,O]=(0,Q.useState)(!1),[k,A]=(0,Q.useState)(null),j=(0,Q.useCallback)(async()=>{let t=(await r.source(e.id)).files.filter(ro);d(t);let n=await Promise.all(t.map(async t=>{try{return[t.name,JSON.parse(await io(await r.file(e.id,t.name)))]}catch{return[t.name,null]}}));p(Object.fromEntries(n))},[r,e.id]),M=(0,Q.useCallback)(()=>{A(null),j().then(()=>O(!0),e=>A(co(e)))},[j]);(0,Q.useEffect)(M,[M]);let N=e=>{let n=f[e],r=n?T.find(e=>e.name===n.step):void 0;return n&&r?Wa(r,n,t):null},P=(0,Q.useMemo)(()=>new Set(l.flatMap(e=>f[e.name]?[Ma(f[e.name])]:[])),[l,f]),F=async(t,n=0)=>{let i=0,a=[];for(let n of t)try{await r.upload(e.id,za(n),new Blob([JSON.stringify(n,null,2)],{type:`application/json`})),i++}catch(e){a.push(e instanceof Ae?e.message:co(e))}await j(),g([`Added ${i}`,n?`Skipped ${n}`:``,a.length?`Refused ${a.length}: ${a[0]}`:``].filter(Boolean).join(`, `))},I=async()=>{let{cases:n,skipped:r}=eo(l.flatMap(e=>f[e.name]?[{name:e.name,record:f[e.name]}]:[]),t);if(!n.length)return g(`No record holds a production reply.`);try{let t=await o.create(`${e.name} · production`,{...Le(),source:{id:e.id,name:e.name},cases:n});g([`Made ${t.name}: ${n.length} ${n.length===1?`case`:`cases`}`,r?`Skipped ${r}`:``].filter(Boolean).join(`, `))}catch(e){g(co(e))}},ee=async t=>{try{let{trash:n}=await r.removeFiles(e.id,t);d(e=>e.filter(e=>!t.includes(e.name))),c.offer({label:t.length===1?`Removed ${t[0]}`:`Removed ${t.length} records`,restore:()=>void r.restoreTrash(n).then(j,e=>g(co(e)))})}catch(e){g(co(e))}},L=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)},z=e=>[{label:`View…`,icon:u,onSelect:()=>C(e.name)},{label:`Download`,icon:w,onSelect:()=>void L(e.name).catch(e=>g(co(e)))},{label:`Remove`,icon:m,destructive:!0,onSelect:()=>void ee([e.name])}],B=(0,Q.useCallback)(()=>x(null),[]),V=(0,Q.useCallback)(()=>C(null),[]),te=S?f[S]:null;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(b,{id:`flow-records`,title:`Records`,note:String(l.length),about:`Each is one call of a Power Automate step: what it read, the request it sent and the reply it got. Request says whether the lab rebuilds that request exactly.`,actions:[{label:`Import runs`,icon:s,disabled:!T.length||!n,onSelect:()=>x(`import`)},{label:`Upload…`,icon:U,disabled:!T.length,onSelect:()=>x(`upload`)},{label:`New dataset`,icon:E,disabled:!l.length,onSelect:()=>void I()}],children:[h&&(0,$.jsx)(`p`,{className:`note`,role:`status`,children:h}),D?l.length?(0,$.jsx)(`div`,{className:`sflow`,children:(0,$.jsx)(R,{className:`slist`,label:`Records`,rows:l,rowKey:e=>e.name,select:{noun:`record`,actions:e=>[{label:`Download`,icon:w,onSelect:()=>void(async()=>{for(let t of e)await L(t.name)})().catch(e=>g(co(e)))},{label:`Remove`,icon:m,destructive:!0,onSelect:()=>void ee(e.map(e=>e.name))}]},columns:[{key:`name`,header:`Name`,role:`title`,sort:e=>e.name,cell:e=>(0,$.jsxs)($.Fragment,{children:[e.name,(0,$.jsx)(`span`,{className:`sflow-in`,children:po(f[e.name])})]})},{key:`result`,header:`Result`,sort:e=>mo(f[e.name]),cell:e=>mo(f[e.name])},{key:`request`,header:`Request`,sort:e=>uo(N(e.name)),tdProps:e=>{let t=N(e.name);return t&&t.match===!1?{title:t.where}:{}},cell:e=>uo(N(e.name))},{key:`menu`,header:``,className:`s-actions`,role:`menu`,sort:null,cell:e=>(0,$.jsx)(a,{label:`${e.name} actions`,actions:z(e)})}]})}):(0,$.jsx)(`p`,{className:`note`,children:`No records yet. Import runs, in this group's menu, reads them from the flow's run history.`}):(0,$.jsx)(i,{label:`Records`,error:k,onRetry:M}),(0,$.jsxs)(`button`,{type:`button`,className:`ghost add-btn`,disabled:!T.length,onClick:()=>x(`hand`),children:[(0,$.jsx)(v,{size:14,"aria-hidden":`true`}),` Add record`]})]}),_===`import`&&n&&(0,$.jsx)(_o,{cfg:n,source:e,steps:T,definition:t,held:P,onClose:B,onRead:async(e,t)=>{x(null),await F(e,t)}}),_===`hand`&&(0,$.jsx)(vo,{steps:T,onClose:B,onAdd:async e=>{x(null),await F([e])}}),_===`upload`&&(0,$.jsx)(bo,{steps:T,onClose:B,onRead:async e=>{x(null),await F(e)}}),S&&(0,$.jsx)(y,{title:S,onClose:V,wide:!0,children:(0,$.jsx)(`pre`,{className:`pl-words`,children:te?JSON.stringify(te,null,2):`Unreadable.`})}),(0,$.jsx)(le,{undo:c.undo,onUndo:c.undoNow,onDismiss:c.dismiss})]})}var uo=e=>!e||e.match===null?`—`:e.match?`Match`:`Differs`,fo={run:`Run`,hand:`Hand`,upload:`Upload`},po=e=>e?[e.step,fo[e.origin.kind]??e.origin.kind,e.at?Ji(Date.parse(e.at)/1e3):``].filter(Boolean).join(`, `):`Unreadable`;function mo(e){let t=e?.result;return t?`error`in t?t.error.code||`Error`:String(t.status):`—`}var ho=e=>e.map(e=>({value:e.name,label:e.name})),go=e=>e.from===`trigger`?`Trigger body`:Ba(e);function _o({cfg:e,source:t,steps:n,definition:r,held:a,onClose:o,onRead:s}){let c=(0,Q.useMemo)(()=>Ca(e),[e]),l=t.config??{},[u,d]=(0,Q.useState)(void 0),[f,p]=(0,Q.useState)(n[0]?.name??``),[m,g]=(0,Q.useState)(null),[_,v]=(0,Q.useState)(``),[b,x]=(0,Q.useState)(new Set),[S,C]=(0,Q.useState)(``),[w,T]=(0,Q.useState)(null),[E,D]=(0,Q.useState)(null),[O,k]=(0,Q.useState)(null),[A,j]=(0,Q.useState)(0);(0,Q.useEffect)(()=>{fa(e).then(d,()=>d(null))},[e]),(0,Q.useEffect)(()=>{u&&l.environment&&l.flow&&(k(null),c.runs(l.environment,l.flow).then(g,e=>k(co(e))))},[u,c,l.environment,l.flow,A]);let M=(0,Q.useMemo)(()=>[...new Set((m??[]).map(e=>e.status))].sort(),[m]),N=(0,Q.useMemo)(()=>(m??[]).filter(e=>!_||e.status===_),[m,_]),P=e=>x(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),F=N.length>0&&N.every(e=>b.has(e.id)),I=N.filter(e=>b.has(e.id)).map(e=>e.id),ee=async()=>{let e=n.find(e=>e.name===f);if(!e||!l.environment||!l.flow)return;let t=I;D(null),T(`Reading 0 of ${t.length}`);try{let{records:n,skipped:i}=await no(c,l.environment,l.flow,t,e,r,a,e=>T(`Reading ${e} of ${t.length}`));await s(n,i)}catch(e){D(co(e)),T(null)}};return(0,$.jsxs)(y,{title:`Import runs`,onClose:o,wide:!0,dirty:I.length>0,footer:(0,$.jsxs)(`div`,{className:`sacts`,children:[w&&(0,$.jsx)(`span`,{className:`note`,role:`status`,children:w}),(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:o,children:`Cancel`}),(0,$.jsxs)(`button`,{type:`button`,disabled:!!w||!I.length||!f,"aria-busy":!!w||void 0,onClick:()=>void ee(),children:[w&&(0,$.jsx)(h,{}),`Import `,I.length||``]})]}),children:[u===void 0?(0,$.jsx)(i,{label:`Account`}):u?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(he,{label:`Import`,rows:[{key:`step`,label:`Step`,control:{type:`select`,value:f,options:ho(n),onChange:p}},{key:`latest`,label:`Latest`,control:{type:`text`,value:S,size:`num`,placeholder:`N`,onChange:e=>{C(e);let t=Number.parseInt(e,10);t>0&&x(new Set(N.slice(0,t).map(e=>e.id)))}}}]}),m?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ie,{noun:`runs`,count:{shown:N.length,total:m.length},lead:(0,$.jsx)(`input`,{type:`checkbox`,"aria-label":`Select all shown`,checked:F,disabled:!N.length,onChange:()=>x(F?new Set:new Set(N.map(e=>e.id)))}),filters:[{key:`status`,label:`Status`,value:_,onChange:v,options:[{value:``,label:`All`},...M.map(e=>({value:e,label:e}))]}]}),N.length?(0,$.jsx)(`div`,{className:`sflow`,children:(0,$.jsx)(R,{className:`slist`,label:`Runs`,rows:N,rowKey:e=>e.id,pageSize:20,rowProps:e=>({onClick:()=>P(e.id),"data-selected":b.has(e.id)||void 0}),columns:[{key:`pick`,header:``,sort:null,cell:e=>(0,$.jsx)(`input`,{type:`checkbox`,"aria-label":`Run ${e.id}`,checked:b.has(e.id),onChange:()=>P(e.id),onClick:e=>e.stopPropagation()})},{key:`start`,header:`Started`,sort:e=>e.startTime??``,cell:e=>e.startTime?Ji(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)(i,{label:`Runs`,error:O,onRetry:()=>j(e=>e+1)})]}):(0,$.jsx)(`div`,{className:`sacts`,children:(0,$.jsxs)(`button`,{type:`button`,className:`ghost`,onClick:()=>{so(ao,t.id),ga(e).catch(e=>{so(ao,null),D(co(e))})},children:[(0,$.jsx)(Et,{size:14,"aria-hidden":`true`}),` Sign in with Microsoft`]})}),E&&(0,$.jsx)(`p`,{className:`note bad`,role:`alert`,children:E})]})}function vo({steps:e,onClose:t,onAdd:n}){let[r,i]=(0,Q.useState)(e[0]?.name??``),[a,o]=(0,Q.useState)({}),s=e.find(e=>e.name===r),c=(s?.reads??[]).filter(e=>Ba(e));return(0,$.jsxs)(y,{title:`Add record`,onClose:t,wide:!0,dirty:Object.values(a).some(Boolean),footer:(0,$.jsxs)(`div`,{className:`sacts`,children:[(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:t,children:`Cancel`}),(0,$.jsx)(`button`,{type:`button`,disabled:!s,onClick:()=>{if(!s)return;let e=Object.fromEntries(Object.entries(a).filter(([e,t])=>t!==``&&c.some(t=>Ba(t)===e))),[t]=Ha(s,[e]).records;n({...t,origin:{kind:`hand`}})},children:`Add`})]}),children:[(0,$.jsx)(he,{label:`Record`,rows:[{key:`step`,label:`Step`,control:{type:`select`,value:r,options:ho(e),onChange:e=>{i(e),o({})}}},...c.map(e=>({key:`read-${Ba(e)}`,label:go(e),control:{type:`textarea`,value:a[Ba(e)]??``,onChange:t=>o(n=>({...n,[Ba(e)]:t}))}}))]}),s&&!c.length&&(0,$.jsx)(`p`,{className:`note`,children:`Reads nothing.`})]})}function yo(e,t){if(e.toLowerCase().endsWith(`.csv`))return{rows:Ua(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};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 bo({steps:e,onClose:t,onRead:n}){let r=(0,Q.useRef)(null),[i,a]=(0,Q.useState)(e[0]?.name??``),[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)(null),u=e.find(e=>e.name===i),d=o&&u&&`rows`in o.parsed?Ha(u,o.parsed.rows):null,f=o?`records`in o.parsed?o.parsed.records:d?.records??[]:[],p=async e=>{if(e){l(null);try{s({name:e.name,parsed:yo(e.name,await io(e))})}catch(t){s(null),l(`${e.name}: ${co(t)}`)}}};return(0,$.jsxs)(y,{title:`Upload`,onClose:t,wide:!0,dirty:!!o,footer:(0,$.jsxs)(`div`,{className:`sacts`,children:[(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:t,children:`Cancel`}),(0,$.jsxs)(`button`,{type:`button`,disabled:!f.length,onClick:()=>void n(f),children:[`Add `,f.length||``]})]}),children:[(0,$.jsx)(he,{label:`Upload`,rows:[...o&&`records`in o.parsed?[]:[{key:`step`,label:`Step`,control:{type:`select`,value:i,options:ho(e),onChange:a}}],{key:`file`,label:`File`,control:{type:`static`,text:o?.name??`—`}},...o?[{key:`count`,label:`records`in o.parsed?`Records`:`Rows`,control:{type:`static`,text:String(f.length)}}]:[],...d?.unmatched.length?[{key:`unmatched`,label:`Unmatched`,control:{type:`static`,text:d.unmatched.join(`, `)}}]:[]]}),(0,$.jsxs)(`div`,{className:`sacts`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`ghost`,onClick:()=>r.current?.click(),children:[(0,$.jsx)(U,{size:14,"aria-hidden":`true`}),` Choose file`]}),(0,$.jsx)(`input`,{ref:r,type:`file`,accept:`.json,.csv`,hidden:!0,"aria-hidden":`true`,onChange:e=>{p(e.target.files?.[0]),e.target.value=``}})]}),c&&(0,$.jsx)(`p`,{className:`note bad`,role:`alert`,children:c})]})}function xo({source:e}){let t=be(),r=Sa(),[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)(null),[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(null),m=e.config??{},h=(0,Q.useCallback)(()=>{p(null),t.definition(e.id).then(s,e=>{s(null),p(e instanceof Error?e.message:String(e))})},[t,e.id]);(0,Q.useEffect)(h,[h]);let g=async()=>{if(r&&o&&m.environment&&m.flow){d(!0),l(null);try{if(!await fa(r)){await ga(r);return}let n=await wa(Ca(r),m.environment,m.flow);s(await t.saveDefinition(e.id,o.version,n.definition)),l(`Synced.`)}catch(e){e instanceof Ae&&e.status===409?(h(),l(`It changed since: reloaded.`)):l(e instanceof Error?e.message:String(e))}finally{d(!1)}}},_=(0,Q.useMemo)(()=>So(o?.body),[o]),v=(0,Q.useMemo)(()=>Ia(o?.body),[o]),[y,x]=Pe(`promptlab.workflows`),[S]=Pe(`promptlab.profiles`),C=t=>{let n=v.find(e=>e.name===t);if(!n||!o)return;let r=Za({id:e.id,name:e.name},o.body,n,S.list),i={id:r.id,name:r.name,work:r};x({...y,list:[...y.list,i],at:i.id}),location.hash=`#/runs`};return(0,$.jsxs)(`div`,{className:`sources`,"data-level":`flow`,children:[c&&(0,$.jsx)(`p`,{className:`note`,role:`status`,children:c}),(0,$.jsxs)(b,{id:`flow-source`,title:`Flow`,note:m.displayName,actions:[{label:`Re-sync`,icon:Mt,busy:u,disabled:!r||!o,onSelect:()=>void g()}],children:[(0,$.jsx)(he,{label:`Flow`,rows:[{key:`flow`,label:`Flow`,control:{type:`static`,text:m.displayName||m.flow||`—`}},{key:`env`,label:`Environment`,control:{type:`static`,text:m.environment||`—`}},...o?[{key:`version`,label:`Definition`,control:{type:`static`,text:o.version?`Version ${o.version}${o.at?`, ${Ji(Date.parse(o.at)/1e3)}`:``}`:`None`}}]:[]]}),!o&&(0,$.jsx)(i,{label:`Definition`,error:f,onRetry:h})]}),(0,$.jsx)(lo,{source:e,definition:o?.body??null,cfg:r}),(0,$.jsx)(b,{id:`flow-actions`,title:`Actions`,note:o?String(_.length):void 0,children:o?_.length?(0,$.jsx)(`div`,{className:`sflow`,children:(0,$.jsx)(R,{className:`slist`,label:`Actions`,rows:_,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=>v.some(t=>t.name===e.name)?(0,$.jsx)(a,{label:`${e.name} actions`,actions:[{label:`New pipeline`,icon:n,onSelect:()=>C(e.name)}]}):null}]})}):(0,$.jsx)(`p`,{className:`note`,children:`No actions.`}):(0,$.jsx)(i,{label:`Actions`,error:f,onRetry:h})})]})}function So(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 Co={"power-automate":{Create:Ta,Level:xo}};function wo({sourceId:e=null,onOpen:t,mode:n=`browse`,onPick:o,disabled:s}){let c=be(),l=ne(),[d,p]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(0),[b,x]=(0,Q.useState)(0),[C,T]=(0,Q.useState)(null),[E,D]=(0,Q.useState)(Li),[O,k]=(0,Q.useState)(``),[A,j]=(0,Q.useState)(new Set),[M,N]=(0,Q.useState)(null),[P,F]=(0,Q.useState)(!1),[I,ee]=(0,Q.useState)(!1),[L,z]=(0,Q.useState)(()=>n===`browse`&&Eo()!==null),[V,te]=(0,Q.useState)(null),[H,W]=(0,Q.useState)(null),[re,G]=(0,Q.useState)(!1),[ae,oe]=(0,Q.useState)(``),[q,J]=(0,Q.useState)(()=>n===`browse`&&Eo()||K().DEFAULT_SOURCE_TYPE),[ce,Y]=(0,Q.useState)(``),[ue,X]=(0,Q.useState)(``),[Z,pe]=(0,Q.useState)(null),[me,ge]=(0,Q.useState)([]),[_e,ve]=(0,Q.useState)(!1),[ye,xe]=(0,Q.useState)(!1),[Se,Ce]=(0,Q.useState)(null),[we,Te]=(0,Q.useState)(null),[Ee,De]=(0,Q.useState)(0),[Oe,ke]=(0,Q.useState)(0),je=(0,Q.useRef)(null),Me=(0,Q.useRef)(1),{view:Ne,sort:Pe,dir:Fe}=E,Ie=(0,Q.useCallback)(()=>te(null),[]),Le=(0,Q.useCallback)(()=>z(!1),[]),Re=(0,Q.useCallback)(()=>W(null),[]),ze=(0,Q.useCallback)(()=>G(!1),[]);(0,Q.useEffect)(()=>Ri(E),[E]),(0,Q.useEffect)(()=>{n===`browse`&&Do(L?q:null)},[n,L,q]);let Be=async()=>{try{let e=await c.sources();p(e.sources),g(e.cap),x(e.used)}catch{}};(0,Q.useEffect)(()=>{let e=!0;return c.sources().then(t=>{e&&(p(t.sources),g(t.cap),x(t.used))}).catch(t=>{e&&Ce(Ue(t))}),()=>{e=!1}},[c,Ee]),(0,Q.useEffect)(()=>{j(new Set),ge([]);let t=!0;return Te(null),e?c.source(e).then(e=>{t&&T(e)}).catch(e=>{t&&(T(null),Te(Ue(e)))}):T(null),()=>{t=!1}},[e,Oe]);let Ve=async()=>{if(!e){T(null);return}try{T(await c.source(e))}catch{T(null)}},He=e=>{pe(e),e&&window.setTimeout(()=>pe(null),6e3)},Ue=e=>e instanceof Ae?e.message:`the request failed`,We=Ki(Gi(C?.files??[],Pe,Fe),O),Ge=e=>{j(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},Ke=()=>j(new Set(We.map(e=>e.name))),qe=()=>j(new Set),Je=async e=>{let t=[];try{for(let n of e)t.push((await c.removeSource(n.id)).trash),p(e=>(e??[]).filter(e=>e.id!==n.id))}catch(e){He(Ue(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 Be()}catch(e){He(Ue(e))}})()})},Ye=e=>Je([e]),Xe=async e=>{if(C)try{let{trash:t}=await c.removeFiles(C.id,e),n=new Set(e);T(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)}),j(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);T(e.source)}catch(e){He(Ue(e))}})()})}catch(e){He(Ue(e))}},Ze=(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)},Qe=async e=>{if(!C)return;let t=e.length===1?e[0]:null;xe(!0);try{let n=t?await c.file(C.id,t):await c.zip(C.id,e);Ze(n,t??`${C.name}.zip`)}catch(e){He(Ue(e))}finally{xe(!1)}},$e=async e=>{if(!C||C.system)return;let t=[...e];if(!t.length)return;let n=t.map(e=>({id:Me.current++,file:e,state:`uploading`}));ge(e=>[...e,...n]);for(let e of n)try{await c.upload(C.id,e.file.name,e.file),ge(t=>t.map(t=>t.id===e.id?{...t,state:`done`}:t))}catch(t){ge(n=>n.map(n=>n.id===e.id?{...n,state:`error`,error:Ue(t)}:n))}await Ve()},et=e=>void $e([e.file]),tt=async(e,t)=>{if(C&&H)try{await c.copyFiles(t.id,C.id,H.names,e===`move`),W(null),j(new Set),await Ve(),He(e===`move`?`Moved to ${t.name}.`:`Copied to ${t.name}.`)}catch(e){He(Ue(e)),W(null)}},nt=async()=>{if(C&&ae.trim())try{let e=await c.createSource(ae.trim(),C.type);try{await c.copyFiles(e.id,C.id,[...A],!1)}catch(t){throw await c.removeSource(e.id).catch(()=>{}),t}G(!1),oe(``),j(new Set),await Be(),He(`Made a new Source.`)}catch(e){He(Ue(e))}},rt=async()=>{if(ae.trim())try{await c.createSource(ae.trim(),q),z(!1),oe(``),J(K().DEFAULT_SOURCE_TYPE),await Be()}catch(e){He(Ue(e))}},it=async(e,t)=>{try{let n=await c.renameSource(e.id,t);p(t=>(t??[]).map(t=>t.id===e.id?Yi(n):t)),T(e=>e?.id===n.id?{...e,name:n.name}:e)}catch(e){He(Ue(e))}},at=(e,t=()=>N(e.id),n)=>e.system?[]:[{label:`Rename…`,icon:S,onSelect:t},{label:`Delete`,icon:m,destructive:!0,onSelect:()=>void Ye(e).then(n)}],ot=e=>[{label:`Preview`,icon:u,disabled:!Hi(e.name),onSelect:()=>te(e)},{label:`Download`,icon:w,onSelect:()=>void Qe([e.name])},...C?.system?[]:[{label:`Remove`,icon:m,destructive:!0,onSelect:()=>void Xe([e.name])}]],st=[...C?.system?[]:[{label:`Remove`,icon:m,destructive:!0,onSelect:()=>void Xe([...A])}],{label:`Download`,icon:w,busy:ye,onSelect:()=>void Qe([...A])},...C?.system?[]:[{label:`Move to…`,icon:xt,onSelect:()=>W({kind:`move`,names:[...A]})}],{label:`Copy to…`,icon:_,onSelect:()=>W({kind:`copy`,names:[...A]})},...C?.system?[]:[{label:`New Source from selection…`,icon:St,onSelect:()=>G(!0)}]],ct=e=>{e.preventDefault(),ve(!1),C&&!C.system&&$e(e.dataTransfer.files)},lt=(d??[]).filter(e=>(!ue||e.type===ue)&&e.name.toLowerCase().includes(ce.trim().toLowerCase())),ut=(0,$.jsx)(ie,{noun:`Sources`,search:{label:`Find a Source`,value:ce,placeholder:`Name`,onChange:Y},filters:[{key:`type`,label:`Type`,value:ue,onChange:X,options:[{value:``,label:`All`},...Io()]}],count:{shown:lt.length,total:(d??[]).length}}),dt=()=>(0,$.jsxs)(`div`,{className:`sources`,"data-level":`sources`,children:[Z&&(0,$.jsx)(`p`,{className:`note`,role:`status`,children:Z}),(0,$.jsxs)(`header`,{className:`shead`,children:[(0,$.jsx)(`h2`,{className:`shead-title`,children:`Sources`}),(0,$.jsx)(ko,{view:Ne,onChange:e=>D(t=>({...t,view:e}))})]}),d!==null&&d.length>0&&ut,d===null?(0,$.jsx)(i,{label:`Sources`,error:Se,onRetry:()=>{Ce(null),De(e=>e+1)}}):d.length===0?(0,$.jsx)(`p`,{className:`note`,children:`No Sources on the server yet.`}):Ne===`thumbs`?(0,$.jsx)(`ul`,{className:`sfolders`,children:lt.map(e=>(0,$.jsx)(`li`,{className:`sfolder`,children:(0,$.jsxs)(`button`,{type:`button`,className:`sfolder-open${s?.(e)?` off`:``}`,disabled:s?.(e),onClick:()=>o?.(e),children:[(0,$.jsx)(Mo,{}),(0,$.jsx)(`span`,{className:`sfolder-name`,children:e.name}),(0,$.jsxs)(`span`,{className:`sfolder-meta`,children:[Lo(e),`. `,Ro(e)]})]})},e.id))}):(0,$.jsx)(R,{className:`slist slist-folders`,label:`Sources`,rows:lt,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${s?.(e)?` off`:``}`,disabled:s?.(e),onClick:()=>o?.(e),children:[(0,$.jsx)(Mo,{}),` `,e.name]})},{key:`type`,header:`Type`,sort:e=>Lo(e),cell:e=>Lo(e)},{key:`files`,header:`Items`,className:`num`,cell:e=>e.files},{key:`size`,header:`Size`,className:`num`,sort:e=>e.bytes,cell:e=>qi(e.bytes)}]})]});if(n===`pick`)return dt();if(e){if(!C)return(0,$.jsx)(`div`,{className:`sources`,children:(0,$.jsx)(i,{label:`Files`,error:we,onRetry:()=>ke(e=>e+1)})});let e=Co[C.type]?.Level,n=!e&&!C.system,o=()=>t?.(null),s=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(r,{kind:`Source`,name:C.name,onPick:d?.length?()=>ee(!0):void 0,meta:`${Lo(Yi(C))}. ${[Ro(Yi(C)),qi(C.bytes)].join(`, `)}`,primary:n?{label:`Upload…`,icon:U,onSelect:()=>je.current?.click()}:void 0,actions:at(Yi(C),()=>F(!0),o)}),I&&d&&(0,$.jsx)(se,{kind:`Source`,value:C.id,onPick:e=>t?.(e),onClose:()=>ee(!1),options:d.map(e=>({id:e.id,label:e.name}))}),P&&(0,$.jsx)(fe,{title:`Rename Source`,value:C.name,onCommit:e=>{e&&e!==C.name&&it(C,e)},onClose:()=>F(!1)})]});return e?(0,$.jsxs)(`div`,{className:`sources`,children:[s,(0,$.jsx)(e,{source:C,onBack:o}),(0,$.jsx)(le,{undo:l.undo,onUndo:l.undoNow,onDismiss:l.dismiss})]}):(0,$.jsxs)(`div`,{className:`sources`,"data-level":`files`,children:[s,Z&&(0,$.jsx)(`p`,{className:`note`,role:`status`,children:Z}),(0,$.jsxs)(`header`,{className:`shead`,children:[(0,$.jsx)(ko,{view:Ne,onChange:e=>D(t=>({...t,view:e}))}),(0,$.jsx)(Ao,{sort:Pe,dir:Fe,onChange:(e,t)=>D(n=>({...n,sort:e,dir:t}))}),(0,$.jsxs)(`label`,{className:`sfilter`,children:[(0,$.jsx)(f,{size:14,"aria-hidden":`true`}),(0,$.jsx)(`input`,{type:`search`,"aria-label":`Filter by name`,placeholder:`Filter`,value:O,onChange:e=>k(e.target.value)})]})]}),A.size>0&&(0,$.jsx)(B,{count:A.size,noun:`file`,onClear:qe,actions:Ne===`thumbs`?[{label:`Select all`,icon:ft,disabled:A.size===We.length,onSelect:Ke},...st]:st}),(0,$.jsx)(`div`,{className:`sfiles${_e?` drag`:``}`,onDragOver:e=>{e.preventDefault(),ve(!0)},onDragLeave:()=>ve(!1),onDrop:ct,children:We.length===0?(0,$.jsx)(`p`,{className:`note`,children:O?`No files match that name.`:`No files in this Source yet.`}):Ne===`thumbs`?(0,$.jsx)(`ul`,{className:`stiles`,children:We.map(e=>(0,$.jsx)(`li`,{children:(0,$.jsxs)(`button`,{type:`button`,className:`stile${A.has(e.name)?` sel`:``}`,"aria-pressed":A.has(e.name),"aria-label":e.name,onClick:()=>Ge(e.name),children:[(0,$.jsx)(Oo,{id:C.id,file:e}),(0,$.jsx)(`span`,{className:`stile-name`,children:e.name}),A.has(e.name)&&(0,$.jsx)(`span`,{className:`stile-check`,children:(0,$.jsx)(de,{size:12,"aria-hidden":`true`})})]})},e.name))}):(0,$.jsx)(R,{className:`slist`,label:`${C.name} files`,rows:We,rowKey:e=>e.name,defaultSort:null,select:{noun:`file`,selected:A,onChange:j},rowProps:e=>({onClick:()=>Ge(e.name)}),columns:[{key:`name`,header:`Name`,className:`sfile-name`,role:`title`,cell:e=>e.name},{key:`type`,header:`Type`,className:`stype`,cell:e=>jo(e.name)},{key:`size`,header:`Size`,className:`num`,sort:e=>e.bytes,cell:e=>qi(e.bytes)},{key:`added`,header:`Added`,sort:e=>e.added,cell:e=>e.added?Ji(e.added):`—`},{key:`menu`,header:``,className:`s-actions`,role:`menu`,sort:null,tdProps:()=>({onClick:e=>e.stopPropagation()}),cell:e=>(0,$.jsx)(a,{label:`${e.name} actions`,actions:ot(e)})}]})}),n&&(0,$.jsxs)(`div`,{className:`supload`,children:[(0,$.jsx)(`input`,{ref:je,type:`file`,multiple:!0,hidden:!0,"aria-hidden":`true`,accept:K().sourceTypeOf(C)?.uploads?.join(`,`),onChange:e=>{e.target.files&&$e(e.target.files),e.target.value=``}}),me.length>0&&(0,$.jsx)(`ul`,{className:`suploads`,children:me.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:()=>et(e),children:`Retry`})]})]},e.id))})]}),V&&(0,$.jsxs)(y,{title:V.name,onClose:Ie,children:[Hi(V.name)?(0,$.jsx)(`img`,{className:`spreview-img`,src:Wi(C.id,V),alt:V.name}):null,(0,$.jsx)(`p`,{className:`note`,children:qi(V.bytes)})]}),H&&(0,$.jsx)(y,{title:H.kind===`move`?`Move to…`:`Copy to…`,onClose:Re,children:(0,$.jsx)(wo,{mode:`pick`,disabled:e=>e.id===C.id||e.system||e.type!==C.type,onPick:e=>void tt(H.kind,e)})}),re&&(0,$.jsxs)(y,{title:`New Source from selection`,onClose:ze,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=>oe(e.target.value),onKeyDown:e=>{e.key===`Enter`&&nt()}})]}),(0,$.jsxs)(`div`,{className:`sacts`,children:[(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>G(!1),children:`Cancel`}),(0,$.jsx)(`button`,{type:`button`,disabled:!ae.trim(),onClick:()=>void nt(),children:`Make`})]})]}),(0,$.jsx)(le,{undo:l.undo,onUndo:l.undoNow,onDismiss:l.dismiss})]})}return(0,$.jsxs)(`div`,{className:`sources`,"data-level":`sources`,children:[Z&&(0,$.jsx)(`p`,{className:`note`,role:`status`,children:Z}),(0,$.jsxs)(`header`,{className:`shead`,children:[(0,$.jsx)(`h2`,{className:`shead-title`,children:`Sources`}),(0,$.jsxs)(`p`,{className:`note suste`,children:[`Used `,qi(b),` of `,qi(h)]}),(0,$.jsx)(ko,{view:Ne,onChange:e=>D(t=>({...t,view:e}))})]}),d!==null&&d.length>0&&ut,d===null?(0,$.jsx)(i,{label:`Sources`,error:Se,onRetry:()=>{Ce(null),De(e=>e+1)}}):d.length===0?(0,$.jsx)(`p`,{className:`note`,children:`No Sources yet — Add source below.`}):Ne===`thumbs`?(0,$.jsx)(`ul`,{className:`sfolders`,children:lt.map(e=>(0,$.jsxs)(`li`,{className:`sfolder`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`sfolder-open`,onClick:()=>t?.(e.id),children:[(0,$.jsx)(Mo,{}),(0,$.jsx)(`span`,{className:`sfolder-name`,children:e.name}),(0,$.jsxs)(`span`,{className:`sfolder-meta`,children:[Lo(e),`. `,Ro(e)]}),(0,$.jsx)(Fo,{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:`${No(e.bytes,h)}%`}})})})]}),(0,$.jsx)(`span`,{className:`sfolder-menu`,children:(0,$.jsx)(a,{label:`${e.name} actions`,actions:at(e)})})]},e.id))}):(0,$.jsx)(`div`,{className:`sfiles`,children:(0,$.jsx)(R,{className:`slist slist-folders`,label:`Sources`,rows:lt,rowKey:e=>e.id,rowProps:e=>({"data-open":e.id,onClick:()=>t?.(e.id)}),select:{noun:`Source`,actions:e=>[{label:`Delete`,icon:m,destructive:!0,disabled:e.every(e=>e.system),onSelect:()=>void Je(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)(Mo,{}),` `,e.name]})},{key:`type`,header:`Type`,sort:e=>Lo(e),cell:e=>Lo(e)},{key:`files`,header:`Items`,className:`num`,cell:e=>e.files},{key:`size`,header:`Size`,className:`num`,sort:e=>e.bytes,cell:e=>qi(e.bytes)},{key:`used`,header:`Used`,className:`num`,sort:e=>e.system?null:e.bytes,cell:e=>(0,$.jsx)(Fo,{source:e,cap:h,children:e.system?`—`:`${No(e.bytes,h)}%`})},{key:`menu`,header:``,className:`s-actions`,role:`menu`,sort:null,tdProps:()=>({onClick:e=>e.stopPropagation()}),cell:e=>(0,$.jsx)(a,{label:`${e.name} actions`,actions:at(e)})}]})}),M&&d&&(()=>{let e=d.find(e=>e.id===M);return e?(0,$.jsxs)(`label`,{className:`srename`,children:[(0,$.jsxs)(`span`,{className:`prop-name`,children:[`Rename `,e.name]}),(0,$.jsx)(`input`,{"aria-label":`Rename ${e.name}`,defaultValue:e.name,autoFocus:!0,onKeyDown:t=>{if(t.key===`Enter`){let n=t.target.value.trim();n&&n!==e.name&&it(e,n),N(null)}t.key===`Escape`&&N(null)},onBlur:t=>{let n=t.target.value.trim();n&&n!==e.name&&it(e,n),N(null)}})]}):null})(),(0,$.jsxs)(`button`,{type:`button`,className:`ghost add-btn`,onClick:()=>z(!0),children:[(0,$.jsx)(v,{size:14,"aria-hidden":`true`}),` Add source`]}),L&&(0,$.jsxs)(y,{title:`Add source`,onClose:Le,dirty:!!ae.trim(),children:[(0,$.jsx)(he,{label:`New Source`,rows:[{key:`type`,label:`Type`,hint:K().SOURCE_TYPES[q]?.description,control:{type:`select`,value:q,options:Io(),onChange:J}}]}),(()=>{let e=Co[q]?.Create,t=(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>z(!1),children:`Cancel`});return e?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(e,{onMade:async()=>{z(!1),J(K().DEFAULT_SOURCE_TYPE),await Be()}}),(0,$.jsx)(`div`,{className:`sacts`,children:t})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{className:`prompt`,children:[(0,$.jsx)(`span`,{className:`prop-name`,children:`Name`}),(0,$.jsx)(`input`,{"aria-label":`Source name`,value:ae,autoFocus:!0,onChange:e=>oe(e.target.value),onKeyDown:e=>{e.key===`Enter`&&rt()}})]}),(0,$.jsxs)(`div`,{className:`sacts`,children:[t,(0,$.jsx)(`button`,{type:`button`,disabled:!ae.trim(),onClick:()=>void rt(),children:`Add`})]})]})})()]}),(0,$.jsx)(le,{undo:l.undo,onUndo:l.undoNow,onDismiss:l.dismiss})]})}var To=`evals-lab.sources.adding`;function Eo(){try{return sessionStorage.getItem(To)}catch{return null}}function Do(e){try{e?sessionStorage.setItem(To,e):sessionStorage.removeItem(To)}catch{}}function Oo({id:e,file:t}){let[n,r]=(0,Q.useState)(!1);return!t.thumb||n?(0,$.jsx)(`span`,{className:`stile-type`,children:jo(t.name)||`FILE`}):(0,$.jsx)(`img`,{className:`stile-img`,src:Ui(e,t),alt:``,loading:`lazy`,onError:()=>r(!0)})}function ko({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 Ao({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?ae:Y,{size:14,"aria-hidden":`true`})})]})}function jo(e){let t=e.lastIndexOf(`.`);return t<0?``:e.slice(t+1).toUpperCase()}function Mo(){return(0,$.jsx)(wt,{size:16,"aria-hidden":`true`})}function No(e,t){return t<=0?0:Math.max(0,Math.min(100,Math.round(e/t*100)))}function Po(e,t){return e.system?`Quota: not counted`:`Quota: ${qi(e.bytes)} of ${qi(t)}`}function Fo({source:e,cap:t,children:n}){let r=Po(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 Io=()=>Object.entries(K().SOURCE_TYPES).map(([e,t])=>({value:e,label:t.label})),Lo=e=>K().SOURCE_TYPES[e.type]?.label??e.type,Ro=e=>{let t=K().sourceTypeOf(e)?.noun??`item`;return`${e.files} ${e.files===1?t:`${t}s`}`};function zo({sourceId:e}){let[t,n]=(0,Q.useState)(e);return(0,Q.useEffect)(()=>n(e),[e]),(0,$.jsx)(wo,{sourceId:t,onOpen:e=>{n(e),e?location.hash=`/library/sources/${encodeURIComponent(e)}`:location.hash=`#/library/sources`}})}var Bo=[{id:`datasets`,label:`Evals`,icon:E},{id:`prompts`,label:`Prompts`,icon:c},{id:`sources`,label:`Sources`,icon:d}];function Vo({section:e,sourceId:t,groupId:n}){return(0,$.jsxs)(`div`,{className:`library`,children:[(0,$.jsx)(me,{label:`Library`,level:`section`,className:`lib-sections`,current:e,items:Bo.map(({id:e,label:t,icon:n})=>({key:e,label:t,href:`#/library/${e}`,icon:n}))}),(0,$.jsx)(`section`,{className:`lib-section`,"data-section":e,children:e===`datasets`?(0,$.jsx)(wi,{groupId:n}):e===`prompts`?(0,$.jsx)(Pi,{}):(0,$.jsx)(zo,{sourceId:t})})]})}var Ho=`0.6.0 (2026.10.05-430)`,Uo=3,Wo=3,Go=e=>Mr.find(t=>t.id===e),Ko=e=>Bo.find(t=>t.id===e),qo=e=>new Date(e).toLocaleString(void 0,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`});function Jo(){let e=be(),[t]=Pe(`promptlab.profiles`),[n,r]=Pe(`promptlab.workflows`),i=$e(),a=lt(),{pickDataset:o}=sn(),{openRun:s}=un(),c=Qe(),l=ct(),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)(null),[g,_]=(0,Q.useState)(null),[v,y]=(0,Q.useState)(0),[b,x]=(0,Q.useState)(0),S=e=>e instanceof Error?e.message:String(e);(0,Q.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,Q.useEffect)(()=>{let t=!0;return _(null),e.queue({limit:Wo}).then(e=>{t&&p(e.runs)},e=>{t&&_(S(e))}),()=>{t=!1}},[e,b]);let C=(0,Q.useMemo)(()=>n.list.filter(e=>e.work?.version===13),[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=Go(`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)(Yo,{id:`runs`,icon:Go(`runs`).icon,name:Go(`runs`).label,hub:!0,start:D===`runs`,fact:O(Dn(C.length,`pipeline`),E>0&&`${E} running`),total:C.length,items:C.map(e=>({key:e.id,label:e.name,href:`#/runs`,onPick:()=>r({...n,at:e.id})}))}),(0,$.jsx)(Yo,{id:`history`,icon:Go(`history`).icon,name:Go(`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=cr(e).scenarios.map(e=>e.percent==null?`–`:`${e.percent}%`).join(`, `);return{key:e.id,label:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`code`,{children:En(e.submittedAt)}),e.status!==`done`&&Nn(e.status)]}),sub:O(qo(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)(Yo,{id:`datasets`,to:`library/datasets`,branch:!0,icon:Ko(`datasets`).icon,name:Ko(`datasets`).label,start:D===`datasets`,fact:i.list?O(Dn(w.length,`eval group`),Dn(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:Dn(e.cases,`case`),href:`#/library/datasets/${encodeURIComponent(e.id)}`,onPick:()=>o(e.id)}))}),(0,$.jsx)(Yo,{id:`prompts`,to:`library/prompts`,branch:!0,icon:Ko(`prompts`).icon,name:Ko(`prompts`).label,fact:a.list?O(Dn(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(`
11
+ `)[0]||`Untitled`,sub:e.default?`Default`:void 0,href:`#/library/prompts`}))}),(0,$.jsx)(Yo,{id:`sources`,to:`library/sources`,branch:!0,icon:Ko(`sources`).icon,name:Ko(`sources`).label,fact:u?O(Dn(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:Dn(e.files,`file`),href:`#/library/sources/${encodeURIComponent(e.id)}`}))})]})]}),(0,$.jsx)(Yo,{id:`setup`,icon:Go(`setup`).icon,name:Go(`setup`).label,start:D===`setup`,fact:O(Dn(t.list.length,`profile`)),total:t.list.length,items:t.list.map(e=>({key:e.id,label:e.name||`Untitled`,sub:e.model,href:`#/setup`}))})]})}),(0,$.jsxs)(`p`,{className:`home-version`,children:[`Evals Lab `,Ho]})]})}function Yo({id:e,icon:t,name:n,to:r,fact:a,items:o,total:s=o.length,hub:c,start:l,branch:u,wait:d}){let f=s-Math.min(o.length,Uo);return(0,$.jsxs)(`li`,{className:[`home-stop`,c&&`hub`,l&&`start`,u&&`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:u?15:18})}),n]}),l&&(0,$.jsx)(`span`,{className:`home-start`,children:`Start Here`}),d&&(0,$.jsx)(i,{label:n,error:d.error,onRetry:d.onRetry}),!d&&a&&(0,$.jsx)(`span`,{className:`home-fact`,children:a}),!d&&o.length>0&&(0,$.jsxs)(`ul`,{className:`home-items`,children:[o.slice(0,Uo).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)),f>0&&(0,$.jsx)(`li`,{children:(0,$.jsxs)(`a`,{className:`home-more`,href:`#/${r??e}`,children:[f,` more`]})})]})]})}function Xo({list:e,at:t,canRestore:n,onSelect:i,onNew:a,onClone:o,onRename:c,onDelete:l,onRestore:u,onExport:d,onExportCi:f,onImport:p,used:h={}}){let[g,y]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)(!1),C=e.find(e=>e.id===t),T=[{label:`Rename…`,icon:S,onSelect:()=>y(!0)},{label:`Clone`,icon:_,onSelect:o},{label:`Export YAML`,icon:w,onSelect:d},{label:`Export for CI…`,icon:w,onSelect:f},{label:`Import YAML…`,icon:U,onSelect:p},{label:`Restore…`,icon:s,disabled:!n,onSelect:u},{label:`Delete`,icon:m,destructive:!0,onSelect:l}],E=C?.work.jobs?.length??0,D=C?.work.targets?.length??0;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(r,{kind:`Pipeline`,name:C?.name?.trim()||`Untitled`,onPick:()=>x(!0),meta:`${Qo(E,`job`)}, ${Qo(D,`target`)}`,primary:{label:`New pipeline`,icon:v,onSelect:a},actions:T,docked:!0}),b&&(0,$.jsx)(se,{kind:`Pipeline`,value:t,onPick:i,onClose:()=>x(!1),options:e.map(e=>{let t=h[e.id];return{id:e.id,label:e.name||`Untitled`,used:t?{at:t,label:An(t)}:null}}),recent:e.filter(e=>h[e.id]).sort((e,t)=>h[t.id].localeCompare(h[e.id])).slice(0,Zo).map(e=>e.id)}),g&&(0,$.jsx)(fe,{title:`Rename pipeline`,value:C?.name??``,onCommit:c,onClose:()=>y(!1)})]})}var Zo=5,Qo=(e,t)=>`${e} ${e===1?t:`${t}s`}`;function $o({hasItems:e,onExport:t,onClose:n}){let[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.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)(j,{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:w,busy:a,primary:!0,onSelect:()=>void l()}]})}function es({problems:e,error:t,run:r,submitting:i,onRun:a,onStop:o,onOpen:s}){let c=!!r&&!Kn(r.status),l=r?.progress?.total??0,u=r?.progress?.n??0,d=c&&l?Math.round(u/l*100):null,f=r&&(0,$.jsxs)(`button`,{type:`button`,className:`runbar-open`,title:`Open this run`,onClick:s,children:[(0,$.jsx)(`span`,{className:`runbar-word`,children:Mn(r.status)}),ts(r)&&(0,$.jsx)(`span`,{className:`runbar-detail`,children:ts(r)})]}),p=c?f:e.length?(0,$.jsxs)(`span`,{className:`runbar-why`,children:[is(e[0]),rs(e[0])]}):t?(0,$.jsx)(`span`,{className:`runbar-why bad`,children:is(t)}):f??(0,$.jsx)(`span`,{className:`runbar-word`,children:`Ready to run`});return(0,$.jsx)(ee,{className:`runbar`,primary:{label:`Run`,icon:n,onSelect:a,disabled:e.length>0,busy:i},status:p,secondary:c?{label:`Stop`,icon:g,onSelect:o}:void 0,progress:d,progressLabel:`Run progress`})}function ts(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=In(e.startedAt,e.finishedAt);return t==null?String(e.progress.total):`${e.progress.total} in ${Fn(t)}`}return``}var ns=[[/^Target profile .* not found$/,`#/setup`,`Open\xA0Setup`],[/^Source .* not found$/,`#/library/sources`,`Open\xA0Sources`],[/^Dataset .* not found$/,`#/library/datasets`,`Open\xA0Evals`]];function rs(e){let t=ns.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 is=e=>{let t=e.trim();if(!t)return t;let n=t[0].toUpperCase()+t.slice(1);return/[.!?]$/.test(n)?n:`${n}.`},as=10;function os({onPick:e,onClose:t,used:n}){let{list:r,error:a}=lt(),o=ct(),[s,c]=(0,Q.useState)(``),[l,u]=(0,Q.useState)(`all`),[d,f]=(0,Q.useState)(0),p=r??[],m=p.filter(e=>Oi(e,s,l,n??{byScenario:new Set,byAll:new Set})).sort((e,t)=>Number(t.default)-Number(e.default)),h=Math.ceil(m.length/as),g=Math.min(d,Math.max(0,h-1)),_=m.slice(g*as,(g+1)*as);return(0,$.jsxs)(y,{title:`Select prompt`,onClose:t,className:`sp`,initialFocus:`.sp input[type=search]`,children:[(0,$.jsx)(ie,{noun:`prompts`,search:{label:`Search prompts`,placeholder:`Search prompts`,value:s,onChange:e=>{c(e),f(0)}},filters:[{key:`show`,label:`Show`,value:l,onChange:e=>{u(e),f(0)},options:Ei}],count:{shown:m.length,total:p.length}}),r===null?(0,$.jsx)(i,{label:`Prompts`,error:a,onRetry:()=>void o.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:tt(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 `,ki(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 ss(e){let t=K(),n=e.jobs.at(-1),r=N(t.defaultKind()),i=t.outOf(n),a=t.outOf(r),o=e=>!Z(e.type)||Z(e.type).includes(a.kind),s=i.modifiers.filter(o);return s.length&&(r=t.withOut(r,{...a,modifiers:s})),Hs(e,[...e.jobs.slice(0,-1),t.withOut(n,{...i,modifiers:i.modifiers.filter(e=>!o(e))}),r],()=>({type:`prompt`,prompt:``}))}function cs(e,t){if(e.jobs.length<2)return e;let n=e.jobs.slice();if(t===n.length-1){let e=K(),r=e.outOf(n[t]),i=e.outOf(n[t-1]),a=r.modifiers.filter(e=>!Z(e.type)||Z(e.type).includes(i.kind)),o=[...i.modifiers,...a];n[t-1]=e.withOut(n[t-1],{...i,modifiers:o.length?o:ue(i.kind)})}return n.splice(t,1),{...e,jobs:n,targets:e.targets.map(e=>({...e,steps:e.steps.filter((e,n)=>n!==t)}))}}function ls(e,t){let n={...structuredClone(e.jobs[t]),id:K().newId()};n.name=`${K().jobLabel(e,t)} copy`;let r=[...e.jobs.slice(0,t+1),n,...e.jobs.slice(t+1)],i=e.targets.map(e=>({...e,steps:[...e.steps.slice(0,t+1),structuredClone(e.steps[t]),...e.steps.slice(t+1)]}));return{...e,jobs:r,targets:i}}function us(e,t,n){let r=e.jobs.map((e,r)=>r===t?{...e,name:n.trim()}:e);return{...e,jobs:r}}function ds(e,t,n){let r=K().outOf(e.jobs[t]);if(r.kind===n||!n)return e;let i=t===e.jobs.length-1,a=r.modifiers.filter(e=>!Z(e.type)||Z(e.type).includes(n));return{...e,jobs:e.jobs.map((e,r)=>r===t?K().withOut(e,{kind:n,...re(n),modifiers:i?a.length?a:ue(n):[]}):e)}}var fs=(e,t)=>({...e,evals:[...e.evals,t]}),ps=(e,t)=>({...e,evals:e.evals.filter((e,n)=>n!==t)}),ms=(e,t,n)=>({...e,evals:e.evals.map((e,r)=>r===t?{...e,name:n.trim()}:e)}),hs=(e,t,n)=>({...e,evals:e.evals.map((e,r)=>r===t?n:e)}),gs=(e,t)=>fs(e,K().newLink(t)),_s=(e,t,n)=>({...e,evals:e.evals.map((e,r)=>r===t?{...e,pin:n}:e)}),vs=(e,t,n)=>({...e,evals:e.evals.map((e,r)=>r===t?{id:e.id,name:e.name,continueOnFailure:e.continueOnFailure,type:`group`,group:{id:n.id,name:n.name},pin:null}:e)}),ys=(e,t,n)=>({...e,evals:e.evals.map((e,r)=>r===t&&e.own?{...e,own:{...e.own,cases:[...e.own.cases,...n],casesFrom:null}}:e)}),bs=(e,t)=>({...e,pass:t}),xs=e=>e[0]?{id:e[0].id,name:e[0].name}:{id:``,name:``};function Ss(e,t,n=``){let r=K(),i=!!r.targetEntryOf(e,0,0)?.newStep,a={id:r.newId(),name:``,profile:i?e.targets.at(-1)?.profile??t:t,steps:e.jobs.map((t,i)=>{let a=r.targetStepOf(e,0,i),o=r.STEP_TYPES[r.jobTargetType(e,i)]?.local?`prompt`:r.jobTargetType(e,i);return a&&r.targetEntryOf(e,0,i)?.newStep?.(a)||{type:o,prompt:i===0?n:``}})};return{...e,targets:[...e.targets,a]}}function Cs(e){let t=new Set(e.map(e=>e.trim().toLowerCase())),n=1;for(;t.has(`pipeline ${n}`);)n+=1;return`Pipeline ${n}`}var ws={id:`samples`,name:`Sample library`};function Ts(e,t,n=``){let r=K().withContent({...K().blankPipeline({name:Cs([])}),evals:t?[K().newLink(t)]:[]},{type:`source`,ref:{...ws},first:null,loops:1});if(t){let e=K();r={...r,jobs:[e.withTokens(e.withOut(r.jobs[0],{kind:`list`,...re(`list`),modifiers:[{type:`tidy`},{type:`dedupe`}]}),e.mappingsFor(n))]}}return r=Ss(r,e,n),Ss(r,e,n)}function Es(e,t){let n=e=>!!e.profile&&!e.profile.id;return!t.id||!e.targets.some(n)?e:{...e,targets:e.targets.map(e=>n(e)?{...e,profile:{...t}}:e)}}function Ds(e,t){let n={...structuredClone(e.targets[t]),id:K().newId(),name:`${K().targetLabel(e,t)} copy`};return{...e,targets:[...e.targets.slice(0,t+1),n,...e.targets.slice(t+1)]}}function Os(e,t){return{...e,targets:e.targets.filter((e,n)=>n!==t)}}function ks(e,t,n){return{...e,targets:e.targets.map((e,r)=>r===t?{...e,name:n.trim()}:e)}}function As(e,t,n,r){return n===0?{...e,targets:e.targets.map((e,n)=>n===t?{...e,profile:r??e.profile}:e)}:K().withTarget(e,t,n,e=>{if(r)return{...e,profile:r};let{profile:t,...n}=e;return n})}function js(e,t,n,r){return K().withTarget(e,t,n,{prompt:r})}function Ms(e,t,n,r,i){return K().withTarget(e,t,n,{prompt:r,from:{...i}})}function Ns(e,t){return new Set(e.jobs.flatMap((n,r)=>K().targetStepOf(e,t,r)?.from?.id??[]))}function Ps(e){let t=K().targetsOf(e).length,n=Ns(e,0);for(let r=1;r<t;r++){let t=Ns(e,r);for(let e of[...n])t.has(e)||n.delete(e)}return n}function Fs(e,t,n,r){return Vs(e,t,e=>e.map(e=>e.name===n?{...e,...r}:e))}function Is(e,t,n,r){let i=n.trim();return i?Vs(e,t,e=>e.some(e=>e.name===i)?e:[...e,K().tokenMapping(i,r)]):e}function Ls(e,t,n,r){let i=r.name.trim();return i?Vs(e,t,e=>i!==n&&e.some(e=>e.name===i)?e:e.map(e=>e.name===n?e.type===r.type?{...e,name:i}:K().tokenMapping(i,r.type):e)):e}function Rs(e,t,n){return Vs(e,t,e=>e.filter(e=>e.name!==n))}var zs=/^(?:text|reply|stage[1-9]\d*(?:\..*)?)$/;function Bs(e,t,n,r){let i=n.trim();return i?/[{}\s]/.test(i)?`A name has no braces or spaces.`:zs.test(i)?`{${i}} is filled in by the lab.`:i!==r&&K().tokensOf(e.jobs[t]).some(e=>e.name===i)?`{${i}} is already mapped.`:null:`A mapping needs a name.`}function Vs(e,t,n){let r=K();return{...e,jobs:e.jobs.map((e,i)=>i===t?r.withTokens(e,n(r.tokensOf(e))):e)}}function Hs(e,t,n){let r=t.length,i=e.targets.map(e=>{let t=e.steps.slice(0,r);for(;t.length<r;)t.push(n(t.length));return{...e,steps:t}});return{...e,jobs:t,targets:i}}var Us=(e,t)=>K().targetLabel(e,t);function Ws(e,t){let n=K().STEP_TYPES;return t.includes(n[e]?.asks??`prompt`)?e:Object.entries(n).find(([,e])=>e.slot===`target`&&t.includes(e.asks??`prompt`))?.[0]??e}function Gs(e,t,n,r){if(n.type===r)return n;let i={prompt:n.prompt,...n.profile?{profile:n.profile}:{},...n.from?{from:n.from}:{}},a=K();if(a.STEP_TYPES[r]?.asks!==`request`)return{type:r,...i};let o=a.targetsOf(e).map((n,r)=>a.targetStepOf(e,r,t)).find(e=>e?.type===r);return{type:r,...o?{api:o.api,method:o.method,path:o.path,query:structuredClone(o.query),body:structuredClone(o.body)}:{api:a.flowStepOf(e.jobs[t])?.api??`raw`,method:`POST`,path:`/`,query:{},body:null},...i}}function Ks(e,t,n,r,i){let a=As(e,t,n,r),o=K();return a.jobs.forEach((e,n)=>{let r=o.targetProfileOf(a,t,n),s=r?i(r.id):void 0,c=o.targetStepOf(a,t,n);if(!s||!c)return;let l=Ws(c.type,s);l!==c.type&&(a=o.withTarget(a,t,n,e=>Gs(a,n,e,l)))}),a}var qs=(e,t,n)=>({...e,jobs:e.jobs.map((e,r)=>r===t?K().withImage(e,n):e)});function Js(e,t,n){let r=K();return{...e,jobs:e.jobs.map((e,i)=>{if(i!==t)return e;let a=e.steps.filter(e=>e.type!==`readAs`),o=a.findIndex(e=>r.STEP_TYPES[e.type]?.slot===`responses`);if(n==null)return{...e,steps:a};let s={type:`readAs`,readAs:n};return{...e,steps:o<0?[...a,s]:[...a.slice(0,o),s,...a.slice(o)]}})}}function Ys(e,t){let n=K(),r=n.defaultKind(),i=n.outOf(e.jobs[t]).modifiers.filter(e=>!Z(e.type)||Z(e.type).includes(r));return{...e,jobs:e.jobs.map((e,a)=>a===t?n.withOut(e,{kind:r,...re(r),modifiers:i}):e)}}function Xs(e,t){let n=K().outOf(e.jobs[t]).modifiers.filter(e=>!Z(e.type)||Z(e.type).includes(`text`));return{...e,jobs:e.jobs.map((e,r)=>{if(r!==t)return e;let i=e.steps.filter(e=>e.type!==`readReply`&&e.type!==`modifier`);return{...e,steps:[...i,...n.map(e=>({type:`modifier`,modifier:e}))]}})}}function Zs(e,t){let n=K().withTarget(e,t,0,e=>({type:`echo`,prompt:e.prompt,...e.from?{from:e.from}:{}}));return e.jobs.length===1&&(n={...n,targets:n.targets.map((e,n)=>n===t?{...e,profile:null}:e)}),n}function Qs({k:e,pipeline:t,sources:n,edit:r,offer:i}){let[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(null),l=K(),u=t.jobs[e],d=e===0?l.contentOf(t):null,f=l.flowStepOf(u),p=l.sendsImage(u),m=l.tokensOf(u),h=l.CONTENT_TYPES,g=l.targetsOf(t).some((n,r)=>l.STEP_TYPES[l.targetStepOf(t,r,e)?.type??``]?.asks===`request`)||e===0&&!!h[d?.type??``]?.inline,_=[...e>0?[{kind:`reply`}]:[],...d?[{kind:`attach`}]:[],...f?[{kind:`flow`}]:[],...p?[{kind:`image`}]:[],...m.map(e=>({kind:`mapping`,name:e.name}))],v=(e,n)=>{let a=t;r(n),i({label:e,restore:()=>r(a)})},x=(e,n)=>r(qs(l.withContent(t,e),0,n)),S=[...e===0&&!d?[{label:`Source…`,icon:W.add,onSelect:()=>o(!0)},{label:h.text?.label??`Text`,icon:W.add,onSelect:()=>x({type:`text`,text:``},!1)},{label:h.prompt?.label??`Prompt only`,icon:W.add,onSelect:()=>x({type:`prompt`},!1)}]:[],...!p&&!g?[{label:l.STEP_TYPES.attachImage?.label??`Image`,icon:W.add,onSelect:()=>r(qs(t,e,!0))}]:[],{label:`Token mapping`,icon:W.add,onSelect:()=>c({mode:`add`})}],C=n=>{n.kind===`attach`?v(`Removed the content`,l.withContent(t,null)):n.kind===`image`?v(`Stopped sending the image`,qs(t,e,!1)):n.kind===`mapping`&&v(`Removed {${n.name}}`,Rs(t,e,n.name))},w=s?.mode===`edit`?m.find(e=>e.name===s.name):void 0,T=n=>{let a=t;s?.mode===`add`?r(Is(a,e,n.name,n.type)):w&&(r(Ls(a,e,w.name,n)),n.type!==w.type&&w.value&&i({label:`Changed {${w.name}} to ${l.TOKEN_TYPES[n.type]?.label.toLowerCase()??n.type}`,restore:()=>r(a)})),c(null)},E=(i,a)=>{switch(i.kind){case`reply`:return[{key:`reply`,label:`${l.jobLabel(t,e-1)} reply`,locked:!0,control:{type:`static`,text:`Each target's ${q(l.outOf(t.jobs[e-1]).kind)}`}}];case`attach`:return[d?.type===`text`?{key:`attach`,label:l.STEP_TYPES.attachContent?.label??`Attach Content`,required:!0,actions:a,control:{type:`textarea`,value:d.text,placeholder:`The item every target is sent`,onChange:e=>r(l.withContent(t,{...d,text:e}))}}:{key:`attach`,label:l.STEP_TYPES.attachContent?.label??`Attach Content`,required:!0,actions:a,control:{type:`static`,text:tc(d,n)}}];case`flow`:return[{key:`flow`,label:l.STEP_TYPES.flowStep?.label??`Flow step`,required:!0,actions:a,control:{type:`static`,text:f?.step??``}},{key:`api`,label:`API`,required:!0,control:{type:`select`,value:f?.api??``,onChange:n=>r({...t,jobs:t.jobs.map((t,r)=>r===e?{...t,steps:t.steps.map(e=>e.type===`flowStep`?{...e,api:n}:e)}:t)}),options:Object.entries(l.HTTP_APIS).map(([e,t])=>({value:e,label:t.label}))}}];case`image`:return[{key:`image`,label:l.STEP_TYPES.attachImage?.label??`Attach Image`,required:!0,actions:a,control:{type:`static`,text:`Each item`}}];case`mapping`:{let n=m.find(e=>e.name===i.name),o=l.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(Fs(t,e,n.name,{value:i}))}:{type:`static`,text:o?.label??n.type},...s.includes(`enabled`)?{enabled:{checked:!!n.enabled,onChange:i=>r(Fs(t,e,n.name,{enabled:i}))}}:{},actions:[{label:`Edit…`,icon:W.edit,onSelect:()=>c({mode:`edit`,name:n.name})},...a]}]}}},D=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`,O=_.map(r=>$s[r.kind](t,e,n)).join(`, `)||`none`;return(0,$.jsxs)(b,{id:`job-${e}-content`,title:`Content`,level:3,note:O,children:[(0,$.jsx)(P,{noun:`content`,items:_,onAdd:S,onRemove:e=>C(_[e]),locked:e=>e.kind===`reply`||e.kind===`flow`,extra:e=>e.kind===`attach`?[{label:`Change content`,icon:W.rename,onSelect:()=>o(!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)(he,{label:D(t),rows:E(t,r)})},t.kind===`mapping`?`m-${t.name}`:t.kind)}),s&&(s.mode===`add`||w)&&(0,$.jsx)(X,{title:w?l.TOKEN_TYPES[w.type]?.notation(w.name)??`{${w.name}}`:`New mapping`,initial:w?{name:w.name,type:w.type}:{name:``,type:`value`},problem:n=>Bs(t,e,n,w?.name),onSave:T,onClose:()=>c(null)},s.mode===`edit`?s.name:`add`),a&&(0,$.jsxs)(y,{title:d?`Change content`:`Add content`,onClose:()=>o(!1),children:[(0,$.jsx)(wo,{mode:`pick`,onPick:e=>{x({type:`source`,ref:G(e.id,e.name),first:null,loops:1},l.sourceTypeOf(e)?.sendsImage??!1),o(!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:()=>{x({type:`text`,text:``},!1),o(!1)},children:[(0,$.jsx)(`span`,{children:h.text?.label??`Text`}),h.text?.description&&(0,$.jsx)(`span`,{className:`pick-about`,children:h.text.description})]}),(0,$.jsxs)(`button`,{type:`button`,className:`ghost pick-item`,onClick:()=>{x({type:`prompt`},!1),o(!1)},children:[(0,$.jsx)(`span`,{children:h.prompt?.label??`Prompt only`}),h.prompt?.description&&(0,$.jsx)(`span`,{className:`pick-about`,children:h.prompt.description})]})]})]})]})}var $s={reply:(e,t)=>`${K().jobLabel(e,t-1)}, ${q(K().outOf(e.jobs[t-1]).kind)}`,attach:(e,t,n)=>tc(K().contentOf(e),n),flow:(e,t)=>K().flowStepOf(e.jobs[t])?.step??``,image:()=>`image`,mapping:()=>`token mapping`},ec=(e,t)=>{let n=t.find(t=>t.id===e.ref.id);return n?`${n.name}, ${n.files} ${n.files===1?`file`:`files`}`:`A Source that is gone: ${e.ref.name}`},tc=(e,t)=>e?e.type===`source`?ec(e,t):K().CONTENT_TYPES[e.type]?.label??e.type:`none`;async function nc(e){try{return await navigator.clipboard.writeText(e),!0}catch{}let t=document.createElement(`textarea`);t.value=e,t.style.position=`fixed`,t.style.opacity=`0`,document.body.appendChild(t),t.select();let n=!1;try{n=document.execCommand(`copy`)}catch{n=!1}return t.remove(),n}var rc={prompt:{actions:ac},echo:{actions:ac},httpRequest:{promptLabel:e=>oc(e)?.fields.length?`Prompt`:`Body`,rows:cc,actions:dc}},ic=e=>rc[e??``]??rc.prompt;function ac({pipeline:e,i:t,k:n,onSelectPrompt:r,onClearPrompt:i,defaultPrompt:a,onRevert:o}){let s=K().targetStepOf(e,t,n)?.prompt??``;return[{label:`Select prompt…`,icon:x,onSelect:r},{label:`Clear prompt`,icon:W.clear,disabled:!s,onSelect:i},...o&&a!=null?[{label:`Revert to default`,icon:W.revert,disabled:s===a,onSelect:o}]:[]]}var oc=e=>K().HTTP_APIS[e?.api??``],sc=e=>{let t=Object.entries(e??{}).map(([e,t])=>`${e}=${t}`).join(`&`);return t?`?${t}`:``};function cc(e,t){let n=e,r=[{key:`api`,label:`API`,control:t?{type:`select`,value:n.api,onChange:e=>t({api:e}),options:Object.entries(K().HTTP_APIS).map(([e,t])=>({value:e,label:t.label}))}:{type:`static`,text:oc(e)?.label??n.api}},{key:`request`,label:`Request`,control:{type:`code`,text:`${n.method} ${n.path}${sc(n.query)}`}},{key:`body`,label:`Template`,control:{type:`code`,text:JSON.stringify(n.body,null,2)}}],i=oc(e);if(!i)return r;let a=(n,r,i=!1)=>({key:n,label:r,control:t?i?{type:`textarea`,value:e[n]??``,onChange:e=>t({[n]:e})}:{type:`text`,value:e[n]??``,onChange:e=>t({[n]:e})}:{type:`static`,text:e[n]??`—`}});if(i.fields.includes(`system`)&&r.push(a(`system`,`System`,!0)),i.fields.includes(`model`)&&r.push(a(`model`,`Model`)),i.fields.includes(`settings`))for(let n of i.settings){let i=e.settings?.[n]??``;r.push({key:`setting-${n}`,label:n,control:t?{type:`text`,value:i,size:`num`,onChange:r=>t({settings:{...e.settings,[n]:r}})}:{type:`static`,text:i||`—`}})}return i.fields.includes(`prefill`)&&r.push(a(`prefill`,`Prefill`)),r}function lc(e){return JSON.stringify((oc(e)??K().HTTP_APIS.raw).place(e.body,e),null,2)}function uc(e,t,n){let r=K().targetStepOf(e,t,n);if(!r)return``;let i=oc(r),a=e.jobs[n],o=K().flowStepOf(a),s=K().readAsOf(a),c=K().contentOf(e),l=c?.type===`source`?c.ref.name:null,u=i?.cellOf(r.body),d=u?[`prompt`,`system`,`model`,`prefill`].filter(e=>(r[e]??``)!==(u[e]??``)).concat(Object.keys({...u.settings,...r.settings}).filter(e=>(r.settings?.[e]??``)!==(u.settings?.[e]??``))):[],f=[`In the Power Automate flow${l?` "${l}"`:``}, edit the HTTP action "${o?.step??``}".`,`Replace its Body with the JSON below, exactly as written. Leave its URI, method and headers as they are.`,`Expressions such as @{items('Apply_to_each')} are Power Automate's own; keep them as they are.`];return d.length&&f.push(`What changes from the flow as it is: ${d.join(`, `)} (the lab's target "${Us(e,t)}").`),r.prefill&&f.push(`The body ends with an assistant message, ${JSON.stringify(r.prefill)}, which starts the model's reply. The reply the action returns does not repeat it, so wherever the flow reads the reply`+(s?` (${s})`:``)+` put ${JSON.stringify(r.prefill)} back in front of the text, for example with concat('${r.prefill.replace(/'/g,`''`)}', …).`),f.push(``,`Body:`,"```json",lc(r),"```"),f.join(`
12
+ `)}function dc({pipeline:e,i:t,k:n,say:r}){let i=K().targetStepOf(e,t,n);if(!i)return[];let a=async(e,t)=>r(await nc(e)?`Copied ${t}.`:`Could not copy.`);return[{label:`Copy`,icon:_,onSelect:()=>void a(lc(i),`the body`)},{label:`Copy as AI prompt`,icon:Lt,onSelect:()=>void a(uc(e,t,n),`the AI prompt`)}]}function fc({label:e,profile:t,prompt:n,onPrompt:r,rows:i=[],promptLabel:a=`Prompt`}){return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(he,{label:`${e} setup`,rows:[{key:`profile`,label:`Profile`,control:t},...i]}),(0,$.jsxs)(`label`,{className:`prompt`,children:[(0,$.jsx)(`span`,{className:`prop-name`,children:a}),(0,$.jsx)(`textarea`,{value:n,"aria-label":`${e}, prompt`,rows:8,readOnly:!r,onChange:e=>r?.(e.target.value)})]})]})}function pc({run:e,i:t,onClose:n}){let r=K(),i=r.targetLabel(e,t),a=r.targetsOf(e)[t],o=t=>t&&(e.profiles?.[t.id]?.name||t.name)||`—`,s=e.jobs.length;return(0,$.jsx)(j,{title:i,sections:e.jobs.flatMap((n,i)=>{let a=r.targetStepOf(e,t,i);return a?[{cell:a,k:i}]:[]}).map(({cell:t,k:n})=>({key:`job-${n}`,...s>1?{title:r.jobLabel(e,n)}:{},children:(0,$.jsx)(fc,{label:s>1?`${i}, ${r.jobLabel(e,n)}`:i,profile:{type:`static`,text:n===0?r.STEP_TYPES[t.type]?.local?r.STEP_TYPES[t.type].label??`Echo`:o(a?.profile??void 0):t.profile?o(t.profile):`Same as ${r.jobLabel(e,0)}`},prompt:t.prompt,rows:ic(t.type).rows?.(t)??[],promptLabel:ic(t.type).promptLabel?.(t)??`Prompt`})})),onClose:n})}function mc({index:e}){return(0,$.jsx)(`span`,{className:`target-badge`,"aria-hidden":`true`,children:K().targetLetter(e)})}function hc({k:e,pipeline:t,profiles:n,targetCap:r,onRequestRename:i,onAdd:o,onClone:s,onRemove:c,onProfile:l,onEcho:u,onPrompt:d,onStep:f,onSelectPrompt:p,onClearPrompt:m,defaultPrompt:h,onRevert:g,say:_=()=>{}}){let v=K(),[y]=Pe(`promptlab.versions`),x=e=>y.profile?.[e]?.[0]?.at??null,S=v.targetsOf(t),C=S.length;return(0,$.jsx)(b,{id:`job-${e}-targets`,title:`Targets`,level:3,note:`${C} ${C===1?`target`:`targets`}`,children:(0,$.jsx)(P,{noun:`target`,items:S,min:1,max:r,onAdd:o,onClone:s,onRemove:c,onRename:i,extra:(n,r)=>ic(v.targetStepOf(t,r,e)?.type).actions?.({pipeline:t,i:r,k:e,say:_,onSelectPrompt:()=>p(r),onClearPrompt:()=>m(r),defaultPrompt:h,onRevert:g&&(()=>g(r))})??[],empty:(0,$.jsx)(`p`,{className:`note`,children:`No targets`}),renderItem:(r,i,o)=>{let s=Us(t,i),c=v.targetStepOf(t,i,e)??{type:`prompt`,prompt:``},p=ic(c.type),m=v.STEP_TYPES[c.type],h=e>0&&!!m?.firstJobOnly;return(0,$.jsxs)(`div`,{className:`target`,id:`job-${e}-target-${i}`,children:[(0,$.jsxs)(`div`,{className:`target-head`,children:[(0,$.jsx)(mc,{index:i}),(0,$.jsx)(`h4`,{className:`target-name`,children:s}),h&&(0,$.jsx)(`span`,{className:`target-idle`,children:`Job 1 only`}),(0,$.jsx)(a,{actions:o,label:`${s} actions`})]}),!h&&(0,$.jsx)(fc,{label:s,profile:e===0?{type:`picker`,kind:`Profile`,value:_c(c)?gc:r.profile?.id??``,usedLabel:`Last changed`,...qr(yc(n,r.profile),x,vc()),onChange:e=>e===gc?u(i):l(i,bc(n,e))}:{type:`picker`,kind:`Profile`,value:c.profile?.id??``,usedLabel:`Last changed`,...qr(yc(n,c.profile),x,[{id:``,label:`Same as ${v.jobLabel(t,0)}`}]),onChange:e=>l(i,e?bc(n,e):null)},prompt:c.prompt,onPrompt:e=>d(i,e),rows:p.rows?.(c,e=>f(i,e))??[],promptLabel:p.promptLabel?.(c)??`Prompt`})]},`${i}-${e}`)}})})}var gc=`#echo`,_c=e=>!!K().STEP_TYPES[e.type]?.local,vc=()=>Object.entries(K().STEP_TYPES).filter(([,e])=>e.slot===`target`&&e.local).map(([,e])=>({id:gc,label:e.label??`Echo`})),yc=(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}))],bc=(e,t)=>{let n=e.find(e=>e.id===t);return n?{id:n.id,name:n.name}:null};function xc({pipeline:e,profiles:t,sources:n,targetCap:r,prompt:i=``,defaultPrompt:a,protectedTerms:o,edit:s,offer:c}){let[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(null),h=(t,n)=>{let r=e;s(n),c({label:t,restore:()=>s(r)})},g=e=>{let n=t.find(t=>t.id===e);return n?K().CONNECTION_TYPES[K().typeOf(n)]?.answers??[`prompt`]:void 0},_=!K().targetsOf(e).length;return(0,$.jsxs)(`div`,{className:`jobs`,children:[p&&(0,$.jsx)(`p`,{className:`note`,role:`status`,children:p}),(0,$.jsx)(P,{noun:`job`,items:e.jobs,min:1,addDisabled:_,onAdd:()=>s(ss(e)),onClone:t=>s(ls(e,t)),onRemove:t=>h(`Removed ${K().jobLabel(e,t)}`,cs(e,t)),onRename:e=>u({job:e}),renderItem:(l,d,p)=>{let _=`Job ${d+1}${l.name?.trim()?` - ${l.name.trim()}`:``}`,v=K().flowStepOf(l)?K().readAsOf(l):void 0;return(0,$.jsxs)(Q.Fragment,{children:[d>0&&(0,$.jsxs)(`div`,{className:`job-reply`,"aria-hidden":`true`,children:[(0,$.jsx)(Y,{size:16}),(0,$.jsx)(`span`,{children:`Reply`})]}),(0,$.jsx)(b,{id:`job-${d}`,title:_,level:2,actions:p,note:Sc(e,d),children:(0,$.jsxs)(`div`,{className:`stages`,children:[(0,$.jsx)(Qs,{k:d,pipeline:e,sources:n,edit:s,offer:c}),(0,$.jsx)(hc,{k:d,pipeline:e,profiles:t,targetCap:r,onRequestRename:e=>u({job:d,scenario:e}),onAdd:()=>s(Ss(e,xs(t),i)),onClone:t=>s(Ds(e,t)),onRemove:t=>h(`Removed ${Us(e,t)}`,Os(e,t)),onProfile:(t,n)=>s(Ks(e,t,d,n,g)),onEcho:t=>s(Zs(e,t)),onPrompt:(t,n)=>s(js(e,t,d,n)),onStep:(t,n)=>s(Cc(e,t,d,n)),say:m,onSelectPrompt:e=>f({i:e,k:d}),onClearPrompt:t=>h(`Cleared ${Us(e,t)}'s prompt`,js(e,t,d,``)),...d===0&&a?{defaultPrompt:a.text,onRevert:t=>h(`Reverted ${Us(e,t)} to the default`,Ms(e,t,0,a.text,{id:a.id,name:tt(a)}))}:{}}),(0,$.jsx)(ce,{id:`job-${d}-responses`,out:K().outOf(l),format:!!K().replyOf(l),readAs:v,outputKinds:L(),modifiers:F(),onKind:t=>s(ds(e,d,t)),onSetting:(t,n)=>s(wc(e,d,e=>({...e,[t]:n}))),onAddFormat:()=>s(Ys(e,d)),onRemoveFormat:()=>h(`Removed the format validation`,Xs(e,d)),onReadAs:t=>t==null?h(`Removed Read as`,Js(e,d,null)):s(Js(e,d,t)),...o?{protectedTerms:o}:{},offer:c,onModifier:(t,n)=>s(Tc(e,d,t,n)),onAddModifier:t=>s(wc(e,d,e=>({...e,modifiers:[...e.modifiers,t]}))),onRemoveModifier:t=>h(`Removed a modifier`,wc(e,d,e=>({...e,modifiers:e.modifiers.filter((e,n)=>n!==t)})))})]})})]},l.id||d)}}),_&&(0,$.jsx)(`p`,{className:`note add-why`,children:`Add a target first.`}),l&&`scenario`in l?(0,$.jsx)(fe,{title:`Rename ${Us(e,l.scenario)}`,value:K().targetsOf(e)[l.scenario]?.name??``,onCommit:t=>s(ks(e,l.scenario,t)),onClose:()=>u(null)}):l?(0,$.jsx)(fe,{title:`Rename ${K().jobLabel(e,l.job)}`,value:e.jobs[l.job]?.name??``,onCommit:t=>s(us(e,l.job,t)),onClose:()=>u(null)}):null,d&&(0,$.jsx)(os,{onClose:()=>f(null),used:{byScenario:Ns(e,d.i),byAll:Ps(e)},onPick:t=>{let n=e;s(Ms(n,d.i,d.k,t.text,{id:t.id,name:tt(t)})),f(null),c({label:`Picked ${tt(t)}`,restore:()=>s(n)})}})]})}function Sc(e,t){let n=K(),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 Cc=(e,t,n,r)=>K().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}),wc=(e,t,n)=>({...e,jobs:e.jobs.map((e,r)=>r===t?K().withOut(e,n(K().outOf(e))):e)}),Tc=(e,t,n,r)=>wc(e,t,e=>({...e,modifiers:e.modifiers.map((e,t)=>t===n?r:e)}));function Ec({pipeline:e,edit:t,offer:n,children:r,profiles:i=[],labGrader:o=null}){let s=Qe(),{list:c}=$e(),[l,u]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(null),m=e.evals,h=K().contentOf(e),g=h?.type===`source`?h.ref.id:null,[,_]=(0,Q.useState)(0);(0,Q.useEffect)(()=>s.subscribe(()=>_(e=>e+1)),[s]),(0,Q.useEffect)(()=>{for(let e of m)e.group&&s.load(e.group.id)},[m,s]);let v=(r,i)=>{let a=e;t(r),n({label:i,restore:()=>t(a)})},y=e=>s.entry(e)?.doc?.body??null,x=e=>!!e?.source&&e.source.id!==g,S=new Map((c??[]).map(e=>[e.id,e])),C=new Set(m.flatMap(e=>e.group?[e.group.id]:[])),w=m.flatMap((e,t)=>e.group?[{t:e,j:t}]:[]),T=m.flatMap((e,t)=>e.own?[{t:e,j:t}]:[]),E=({t,j:n})=>{let r=t.group.id,i=S.get(r)?.versions;return[{label:`Open in Library`,icon:d,onSelect:()=>zr(r)},t.pin==null?{label:`Pin`,icon:jt,disabled:i==null,onSelect:()=>v(_s(e,n,i),`Pinned ${t.group.name||r}`)}:{label:`Follow latest`,icon:At,onSelect:()=>v(_s(e,n,null),`${t.group.name||r} follows the latest`)},{label:`Unlink`,icon:Bt,onSelect:()=>v(ps(e,n),`Unlinked ${t.group.name||r}`)}]};return(0,$.jsxs)(b,{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)(Oc,{pass:e.pass,count:m.length,edit:n=>t(bs(e,n))}),w.length>0&&(0,$.jsx)(R,{className:`eg-links`,cards:!0,label:`Linked eval groups`,rows:w,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:()=>zr(e.t.group.id),children:e.t.group.name||e.t.group.id})},{key:`source`,header:`Source`,sort:e=>y(e.t.group.id)?.source?.name??``,tdProps:e=>({"data-state":y(e.t.group.id)?.source?void 0:`none`}),cell:e=>{let t=y(e.t.group.id);return t?t.source?x(t)?(0,$.jsxs)(`span`,{className:`eval-flag`,title:`Grades ${t.source.name}, not this run's content`,children:[(0,$.jsx)(yt,{size:12,"aria-hidden":`true`}),t.source.name]}):t.source.name:`Any`:`…`}},{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)(a,{label:`${e.t.group.name||e.t.group.id} actions`,actions:E(e)})}]}),(0,$.jsxs)(`button`,{type:`button`,className:`ghost eg-add`,onClick:()=>u(!0),children:[(0,$.jsx)(W.add,{size:14,"aria-hidden":`true`}),`Link eval group`]}),r,T.map(({t:n,j:r})=>(0,$.jsx)(Dc,{ev:n,label:K().evalLabel(e,r),renaming:f===r,onRename:()=>p(r),profiles:i,labGrader:o,rawReply:e.jobs.some(e=>K().readAsOf(e)!=null),casesBody:n.own.casesFrom?y(n.own.casesFrom.id):null,loadCases:()=>{n.own.casesFrom&&s.load(n.own.casesFrom.id)},set:n=>t(hs(e,r,n)),undoableSet:(t,n)=>v(hs(e,r,t),n),onCommitName:n=>{t(ms(e,r,n)),p(null)},onCancelName:()=>p(null),onCopyCases:t=>v(ys(e,r,t),`Copied ${K().evalLabel(e,r)}'s cases in`),onMoveToLibrary:async()=>{let t=Ac((n.name||``).trim()||K().evalLabel(e,r),new Set((c??[]).map(e=>e.name))),{casesFrom:i,...a}=n.own,o=await s.create(t,a);v(vs(e,r,{id:o.id,name:o.name}),`Moved ${t} to the Library`)},onRemove:()=>v(ps(e,r),`Removed ${K().evalLabel(e,r)}`)},n.id)),l&&(0,$.jsx)(kc,{list:c??[],linkedIds:C,contentSourceId:g,onLink:n=>{t(gs(e,n)),u(!1)},onNew:async()=>{let n=await s.create(Ac(`Untitled eval group`,new Set((c??[]).map(e=>e.name))));t(gs(e,{id:n.id,name:n.name})),u(!1)},onClose:()=>u(!1)})]})}function Dc({ev:e,label:t,renaming:n,onRename:r,profiles:i,labGrader:a,rawReply:o,casesBody:s,loadCases:c,set:l,undoableSet:u,onCommitName:d,onCancelName:f,onCopyCases:p,onMoveToLibrary:m,onRemove:h}){let g=K(),[_]=Pe(`promptlab.versions`),v=e.own;(0,Q.useEffect)(()=>{v.casesFrom&&c()},[v.casesFrom,c]);let y=g.isWholeRun(g.EVAL_TYPES.group,e),x=y?v.run:v.every,S=t=>l({...e,own:{...v,...t}}),C=t=>({...e,own:{...v,...y?{run:t}:{every:t}}}),w=x.some(e=>g.METRICS[e.type]?.graded),T=i.filter(e=>(g.CONNECTION_TYPES[e.type??``]?.answers??[`prompt`]).includes(`prompt`)),{mode:E,threshold:D}=v.scoring,O=[{label:`Rename…`,icon:W.rename,onSelect:r},...v.casesFrom?[{label:`Copy cases in`,icon:mt,disabled:!s,onSelect:()=>s&&p(s.cases)}]:[],{label:`Move to Library`,icon:Ct,onSelect:()=>void m()},{label:`Remove`,icon:W.remove,destructive:!0,onSelect:h}],k=[{key:`mode`,label:`Scored`,control:{type:`select`,value:E,options:[{value:`all`,label:`All must pass`},{value:`weighted`,label:`Weighted points`}],onChange:e=>S({scoring:{mode:e===`weighted`?`weighted`:`all`,threshold:e===`weighted`?D??1:D}})}},...E===`weighted`?[{key:`threshold`,label:`Pass at`,control:{type:`text`,size:`num`,value:D==null?``:String(D),onChange:e=>S({scoring:{mode:E,threshold:e.trim()?/^-?\d+(\.\d+)?$/.test(e.trim())?Number(e):e:null}})}}]:[],...v.casesFrom?[]:[{key:`over`,label:`Reads`,control:{type:`select`,value:y?`run`:`item`,options:[{value:`item`,label:`Each item`},{value:`run`,label:`Whole run`}],onChange:e=>S(e===`run`?{every:[],run:[...v.every,...v.run]}:{every:[...v.every,...v.run],run:[]})}}],...v.casesFrom?[{key:`cases-from`,label:`Cases from`,control:{type:`static`,text:v.casesFrom.name||v.casesFrom.id}}]:[],...w||v.grader?[{key:`grader`,label:`Grader`,control:{type:`picker`,kind:`Profile`,value:v.grader?.id??``,usedLabel:`Last changed`,...qr(T,e=>_.profile?.[e]?.[0]?.at??null,[{id:``,label:a?`Lab (${a.name})`:`None`}]),onChange:e=>{let t=i.find(t=>t.id===e);S({grader:t?{id:t.id,name:t.name}:null})}}}]:[]];return(0,$.jsxs)(b,{id:`eval-${e.id}`,title:t,level:3,note:g.EVAL_TYPES.group?.label??`Eval group`,about:`A group of this pipeline's own, defined here rather than in the Library.`,actions:O,...n?{rename:{value:e.name||t,onCommit:d,onCancel:f}}:{},children:[(0,$.jsx)(he,{label:t,rows:k}),(0,$.jsx)(Gr,{label:t,metrics:x,over:y?`run`:`item`,rawReply:o,set:e=>l(C(e)),undoable:(e,t)=>u(C(e),t)}),(0,$.jsx)(he,{label:`${t} on failure`,rows:[{key:`continue`,label:`Continue on failure`,control:{type:`checkbox`,checked:e.continueOnFailure,onChange:t=>l({...e,continueOnFailure:t})}}]})]})}function Oc({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`,control:{type:`text`,size:`num`,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)(he,{label:`Pass rule`,rows:i})}function kc({list:e,linkedIds:t,contentSourceId:n,onLink:r,onNew:i,onClose:a}){let o=Qe(),[,s]=(0,Q.useState)(0);(0,Q.useEffect)(()=>o.subscribe(()=>s(e=>e+1)),[o]),(0,Q.useEffect)(()=>{for(let t of e)o.load(t.id)},[e,o]);let c=e=>{let t=o.entry(e)?.doc?.body;return t?!t.source||t.source.id===n:null};return(0,$.jsxs)(y,{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===!1?`Another Source`:i?`Grades this content`:``;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)(W.add,{size:14,"aria-hidden":`true`}),`New eval group…`]})})]})}function Ac(e,t){if(!t.has(e))return e;for(let n=2;;n++)if(!t.has(`${e} ${n}`))return`${e} ${n}`}function jc({pipeline:e,sourceFiles:t,graded:n,openCaseEditor:r}){let[i,a]=(0,Q.useState)({graded:!1,todo:!0,missing:!0});if((K().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)(b,{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=K().contentOf(e),i=r?K().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`${Dn(n.length,`case`)}, ${s} of ${a.length} matched`}}function Mc({pipeline:e,edit:t,comment:n,setComment:r,onClear:i,onCopyFailures:a}){let o=[{label:`Clear comment`,icon:T,destructive:!0,onSelect:i},{label:`Copy last run's failures`,icon:_,onSelect:a}],s=K().contentOf(e),c=s?.type===`source`?[{key:`first`,label:`Run first`,control:{type:`text`,value:s.first==null?``:String(s.first),placeholder:`all`,size:`num`,clearable:!0,onChange:n=>t(K().withContent(e,{...s,first:n.trim()?Nc(n):null}))}},{key:`loops`,label:`Loop`,control:{type:`text`,value:String(s.loops),placeholder:`1`,onChange:n=>t(K().withContent(e,{...s,loops:Math.max(1,Nc(n)??1)}))}}]:[];return(0,$.jsx)(b,{id:`control`,title:`Run settings`,level:2,actions:o,children:(0,$.jsx)(he,{label:`Run settings`,rows:[...c,{key:`comment`,label:`Comment`,control:{type:`text`,value:n,placeholder:`A note to find this run by in History`,onChange:e=>r(e)}}]})})}var Nc=e=>{let t=Number.parseInt(e,10);return Number.isNaN(t)?null:t};function Pc(){let e=Ne(),t=be(),n=ne(),{openRun:r}=un(),{openCaseEditor:a}=li(),[o,s]=Pe(`promptlab.workflows`),[c]=Pe(`promptlab.profiles`),[l,u]=Pe(`promptlab.comment`),[d]=Pe(`promptlab.versions`),[f,p]=(0,Q.useState)([]),{list:m,error:h}=$e(),{list:g,error:_}=lt(),v=g?.find(e=>e.default)??null,b=Qe(),x=(0,Q.useMemo)(()=>(m??[]).map(e=>G(e.id,e.name)),[m]),[S,C]=(0,Q.useState)(4),[w,T]=(0,Q.useState)(void 0),[E,D]=(0,Q.useState)(null),[O,k]=(0,Q.useState)(!1),[A,j]=(0,Q.useState)(!1),[M,N]=(0,Q.useState)(null),P=(0,Q.useRef)(null),[F,I]=(0,Q.useState)(null),[ee,L]=(0,Q.useState)(!1),R=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=!0;return t.sources().then(t=>{e&&p(t.sources)}).catch(()=>{}),t.config().then(t=>{e&&C(t.targetCap)}).catch(()=>{}),()=>{e=!1}},[t]),(0,Q.useEffect)(()=>{let e=!0,n,r=async()=>{let i=5e3;try{let n=(await t.queue({limit:1})).runs[0]??null;if(!e)return;!P.current&&n&&!Kn(n.status)&&(P.current=n.id),n&&n.id===P.current&&(N(n),Kn(n.status)||(i=1e3))}catch{}e&&(n=setTimeout(()=>void r(),i))};return r(),()=>{e=!1,n&&clearTimeout(n)}},[t]);let z=(0,Q.useMemo)(()=>o.list.filter(e=>e.work?.version===13),[o.list]),B=z.find(e=>e.id===o.at)??z[0],V=B?.work,te=B?.id??``,H=V?K().evalsDataset(V)?.id??null:null,U=et(H),W=U?.doc?.body.cases,re=(0,Q.useMemo)(()=>(W??[]).map(e=>({id:e.id??``,item:K().caseItem(e)})),[W]),ie=U?.doc?.body.cases,ae=(0,Q.useMemo)(()=>[...new Set((ie??[]).flatMap(e=>(e.metrics??[]).filter(e=>!e.not&&e.weight!==0&&(e.type===`contains-all`||e.type===`contains-any`)).flatMap(e=>K().metricLines(e.values))))],[ie]),oe=v?.text||V&&K().targetStepOf(V,K().targetsOf(V).length-1,0)?.prompt||``,se=(0,Q.useRef)(c.list);se.current=c.list;let q=z.length?null:m?.[0]??null,J=m!==null||h!==null,ce=g!==null||_!==null,Y=v?.text??``;(0,Q.useEffect)(()=>{if(z.length||!J||!ce)return;let e=Ic(se.current,q?{id:q.id,name:q.name}:void 0,Y);s({list:[e],at:e.id})},[z.length,s,J,ce,q,Y]);let ue=()=>{let e=b.list().list?.[0];return e?{id:e.id,name:e.name}:void 0},X=(0,Q.useRef)(o);X.current=o;let de=(0,Q.useRef)(B);de.current=B;let fe=(0,Q.useRef)(V);fe.current=V;let Z=(0,Q.useRef)(null),pe=(0,Q.useRef)(null),me=(0,Q.useCallback)(()=>{pe.current&&clearTimeout(pe.current);let t=de.current?.id,n=fe.current;t&&n&&(Z.current={id:t,doc:n},pe.current=setTimeout(()=>{let t=Z.current;t&&qe(e,`pipeline`,t.id,t.doc,`idle`)},Ue))},[e]);(0,Q.useEffect)(()=>()=>{pe.current&&clearTimeout(pe.current)},[]);let he=(0,Q.useCallback)(e=>{let t=X.current,n=de.current.id,r={...t,at:n,list:t.list.filter(e=>e.work?.version===13).map(t=>t.id===n?{...t,work:e}:t)};X.current=r,s(r),me(),D(null)},[s,me]),ge=c.list[0]?.id??``;(0,Q.useEffect)(()=>{let e=fe.current,t=de.current?.id;if(!e||!t||!ge)return;let n=Es(e,xs(se.current));if(n===e)return;let r=X.current,i={...r,list:r.list.map(e=>e.id===t?{...e,work:n}:e)};X.current=i,s(i)},[ge,te,s]),(0,Q.useEffect)(()=>{let t=Z.current;t&&t.id!==te&&(qe(e,`pipeline`,t.id,t.doc,`idle`),Z.current=null,pe.current&&=(clearTimeout(pe.current),null))},[te,e]);let _e=V?K().contentOf(V):null,ve=_e?.type===`source`?_e.ref.id:null;(0,Q.useEffect)(()=>{if(ve===null){T(void 0);return}let e=!0;return t.source(ve).then(t=>{e&&T(t.files.map(e=>e.name))}).catch(()=>{}),()=>{e=!1}},[ve,t]);let ye=(0,Q.useCallback)(e=>{let t=f.find(t=>t.id===e);return t?{name:t.name,type:t.type,files:e===ve&&w?w:[]}:null},[f,ve,w]),xe=(0,Q.useMemo)(()=>{let e=c.list.find(e=>e.id===c.grader);return e?{id:e.id,name:e.name}:null},[c]),Se=(0,Q.useMemo)(()=>{if(!V)return[];if(!c.list.length&&K().targetsOf(V).length)return[`add a Target profile first`];let e={profiles:e=>c.list.find(t=>t.id===e)??null,sources:ye,grader:xe,...m?{groups:m}:{}};return K().validatePipeline(V,e)},[V,c.list,ye,m,xe]),Ce=te?d.pipeline?.[te]??[]:[],we=(0,Q.useCallback)(async()=>{let n=fe.current,i=de.current.id;qe(e,`pipeline`,i,n,`run`);let a=K().resolvePipeline(n,{profiles:e=>K().withSlugs(c.list).find(t=>t.id===e)??null,grader:xe,...ve!==null&&w!==void 0?{files:w}:{},comment:l?.text??``});k(!0),D(null);try{let e=await t.submit(a);P.current=e.run.id,N(e.run),r(e.run.id,{at:e.run.submittedAt,from:`runs`})}catch(e){D(e instanceof Error?e.message:String(e)),P.current=null,N(null)}finally{k(!1)}},[t,l,ve,r,c.list,w,e,xe]),Te=(0,Q.useCallback)(async()=>{let e=P.current;if(e)try{N((await t.cancel(e)).run)}catch{}},[t]),Ee=(0,Q.useCallback)(async()=>{try{let e=(await t.queue({limit:1})).runs[0];if(!e)return;let n=(e.results??[]).filter(e=>(e.scenarios??[]).some(e=>Object.values(e?.scores??{}).some(K().failedScore))).map(e=>e.name??`an item`);n.length&&await navigator.clipboard?.writeText(n.join(`
13
+ `))}catch{}},[t]),De=(0,Q.useCallback)(async n=>{let r=fe.current,i=de.current.id;qe(e,`pipeline`,i,r,`run`);let a=K().resolvePipeline(r,{profiles:e=>K().withSlugs(c.list).find(t=>t.id===e)??null,grader:xe,files:[n],comment:l?.text??``}),o=await t.submit(a),s=o.run;for(;s.status===`queued`||s.status===`running`;)await new Promise(e=>setTimeout(e,500)),s=await t.run(o.run.id);return((s.results??[]).find(e=>e.name===n)?.scenarios??[]).map(e=>e.res??null)},[t,l,c.list,e]),Oe=(0,Q.useCallback)(e=>{H&&a(e,{dataset:H,files:w??[],run:De})},[a,w,De,H]),ke=(0,Q.useCallback)(()=>{let e=l?.text??``;u({text:``}),n.offer({label:`Cleared the comment`,restore:()=>u({text:e})})},[l,u,n]),Ae=(0,Q.useCallback)(()=>{let e=K().pipelineToYaml(fe.current,{profiles:se.current});Ir(new Blob([e],{type:`text/yaml`}),Fr(`pipeline`,fe.current.name||`pipeline`,13,`yml`))},[]),je=(0,Q.useCallback)(async e=>{let n=fe.current,r={};for(let e of K().evalsOf(n)){let n=K().casesRef(e)?.id??null;if(n&&!r[n]){let e=await t.dataset(n);r[n]={name:e.name,body:e.body}}}let i=K().exportBundle(n,{profiles:se.current,grader:xe,datasets:r});if(`error`in i)throw Error(i.error);Ir(await t.bundle({files:i.files,source:ve,items:e}),Fr(`ci`,n.name||`pipeline`,13,`zip`))},[t,ve,xe]),Me=(0,Q.useCallback)(async e=>{let n=await t.archivedRules().then(e=>e.rules,()=>({})),r=K().yamlToPipeline(e,{profiles:se.current,profileType:e=>se.current.find(t=>t.id===e)?.type,sources:f,groups:x,rulesFor:e=>n[e]??null});if(`error`in r){I(r);return}let{doc:i,missing:a}=r,o={id:Lc(),name:i.name||`Imported`,work:i},c={...X.current,at:o.id,list:[...z,o]};X.current=c,s(c),I({doc:i,missing:a})},[t,z,s,f,x]);if(!B||!V)return(0,$.jsx)(`div`,{className:`runs`,children:(0,$.jsx)(i,{label:`Pipelines`})});let Fe=t=>{let n=de.current.id;qe(e,`pipeline`,n,fe.current,`restore`),he(t.doc),j(!1)};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Xo,{list:z,at:te,canRestore:Ce.length>0,used:Object.fromEntries(z.map(e=>[e.id,d.pipeline?.[e.id]?.[0]?.at??null])),onSelect:e=>s({...X.current,at:e}),onNew:()=>{let e=Fc(z.map(e=>e.name));if(s({...X.current,list:[...z,e],at:e.id}),l?.text){let e=l.text;u({text:``}),n.offer({label:`Cleared the comment`,restore:()=>u({text:e})})}},onClone:()=>{let e={id:Lc(),name:`${B.name} copy`,work:structuredClone(V)};s({...X.current,list:[...z,e],at:e.id})},onRename:e=>{let t=e.trim(),n=X.current,r=de.current.id,i={...n,at:r,list:n.list.filter(e=>e.work?.version===13).map(e=>e.id===r?{...e,name:t,work:{...e.work,name:t}}:e)};X.current=i,s(i),me()},onDelete:()=>{let e=X.current,t=z.filter(e=>e.id!==te),r=t.length?t:[Ic(c.list,ue(),Y)],i=t.length?t[0].id:r[0].id;s({...X.current,list:r,at:i}),n.offer({label:`Deleted ${B.name||`the pipeline`}`,restore:()=>{X.current=e,s(e)}})},onRestore:()=>j(!0),onExport:Ae,onExportCi:()=>L(!0),onImport:()=>R.current?.click()}),(0,$.jsx)(es,{problems:Se,error:E,run:M,submitting:O,onRun:()=>void we(),onStop:()=>void Te(),onOpen:()=>{M&&r(M.id,{at:M.submittedAt,from:`runs`})}}),(0,$.jsxs)(`div`,{className:`runs`,children:[(0,$.jsx)(`input`,{ref:R,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(Me).catch(()=>I({error:`the file could not be read`}))}}),(0,$.jsx)(Mc,{pipeline:V,edit:he,comment:l?.text??``,setComment:e=>u({text:e}),onClear:ke,onCopyFailures:()=>void Ee()}),(0,$.jsx)(xc,{pipeline:V,profiles:c.list,sources:f,targetCap:S,prompt:oe,...v?{defaultPrompt:v}:{},protectedTerms:ae,edit:he,offer:n.offer}),(0,$.jsx)(Ec,{profiles:c.list,labGrader:xe,pipeline:V,edit:he,offer:n.offer,children:(0,$.jsx)(jc,{pipeline:V,sourceFiles:w,graded:re,openCaseEditor:Oe})}),(0,$.jsx)(le,{undo:n.undo,onUndo:n.undoNow,onDismiss:n.dismiss}),A&&(0,$.jsx)(y,{title:`Restore pipeline`,onClose:()=>j(!1),children:(0,$.jsxs)(`div`,{className:`version-list`,children:[Ce.length===0&&(0,$.jsx)(`p`,{className:`note`,children:`No versions of this pipeline yet.`}),Ce.map((e,t)=>(0,$.jsxs)(`div`,{className:`version-row`,children:[(0,$.jsxs)(`span`,{className:`version-when`,children:[zc(e.at),`, `,Rc(e.reason)]}),(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>Fe(e),children:`Restore`})]},`${e.at}-${t}`))]})}),ee&&(0,$.jsx)($o,{hasItems:ve!==null,onExport:je,onClose:()=>L(!1)}),F&&(`doc`in F?(0,$.jsx)(y,{title:`Imported ${F.doc.name||`Untitled`}`,onClose:()=>I(null),children:F.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 and Target profile rows:`}),(0,$.jsx)(`ul`,{className:`import-missing`,children:F.missing.map(e=>(0,$.jsx)(`li`,{children:e},e))})]}):(0,$.jsx)(`p`,{className:`note`,children:`Ready to run.`})}):(0,$.jsx)(y,{title:`Nothing imported`,onClose:()=>I(null),children:(0,$.jsx)(`p`,{className:`note`,children:F.error})}))]})]})}var Fc=e=>{let t=Cs(e),n=K().blankPipeline({name:t});return{id:Lc(),name:t,work:{...n,jobs:n.jobs.map(e=>({...e,steps:[]}))}}},Ic=(e,t,n)=>({id:Lc(),name:Cs([]),work:Ts(xs(e),t,n)}),Lc=()=>`w${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`,Rc=e=>e===`run`?`before a run`:e===`restore`?`before a restore`:e===`pack`?`before a pack update`:`after editing`,zc=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},Bc=e=>!!e.id&&Kn(e.status),Vc=e=>`Queued ${En(e.submittedAt)}`;async function Hc(e,t){try{(await e.run(t)).status===`queued`&&await e.cancel(t)}catch{}}var Uc=[``,`queued`,`running`,`done`,`cancelled`,`failed`,`incomplete`,`interrupted`],Wc=e=>e.numeric?`hnum num`:void 0,Gc=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)),Kc=e=>e&&{before:e.submittedAt,beforeId:e.id};function qc(){let t=be(),r=ne(),{openRun:o}=un(),[s,c]=Pe(`promptlab.history.columns`),[l,u]=(0,Q.useState)([]),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(``),[g,_]=(0,Q.useState)(new Set),[v,x]=(0,Q.useState)(!1),[S,C]=(0,Q.useState)(null),[E,D]=(0,Q.useState)(null),[O,k]=(0,Q.useState)(null),[A,j]=(0,Q.useState)(null),[M,N]=(0,Q.useState)(!1),[P,F]=(0,Q.useState)(!1),[I,ee]=(0,Q.useState)(!1),[L,z]=(0,Q.useState)(!1),[B,V]=(0,Q.useState)(null),[te,H]=(0,Q.useState)(0),U=(0,Q.useRef)(L);U.current=L;let[W,re]=(0,Q.useState)(null),[G,ae]=(0,Q.useState)(0),oe=(0,Q.useRef)(l);oe.current=l;let se=(0,Q.useMemo)(()=>l.map(e=>kn(cr(e),e)),[l]),q=(0,Q.useMemo)(()=>Xc(s),[s]),J=(0,Q.useCallback)(async(e,n=!1)=>{try{return await t.queue({limit:25,...e,...n?{full:n}:{}})}catch{return null}},[t]),ce=(0,Q.useCallback)(e=>{let t=new Set(e.runs.map(e=>e.id));u(n=>Gc([...n.filter(e=>!t.has(e.id)),...e.runs])),f(e.more)},[]);(0,Q.useEffect)(()=>{let e=!0,t,n=async()=>{let r=await J();e&&(r?(ce(r),z(!0),V(null)):U.current||V(`Runs not loaded: server unreachable.`),oe.current.some(e=>[`queued`,`running`].includes(e.status))&&(t=setTimeout(()=>void n(),3e3)))};return n(),()=>{e=!1,t&&clearTimeout(t)}},[J,ce,te,G]);let Y=(0,Q.useMemo)(()=>se.filter(e=>!p||(e.status||`done`)===p),[se,p]),ue=(e=>({Runs:Vn.filter(t=>e.Runs.has(t.key)),"Run Scenarios":Hn.filter(t=>e[`Run Scenarios`].has(t.key))}))(q),X=(0,Q.useCallback)(e=>{_(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),de=(0,Q.useCallback)((e,t)=>{o(e,{at:t,from:`history`})},[o]),fe=(0,Q.useCallback)(async e=>{try{let n=await t.resume(e),r={runs:[n.run],more:oe.current.length>25};ce(r),de(e,n.run.submittedAt)}catch{}},[t,ce,de]),Z=(0,Q.useCallback)(async e=>{j(null);try{let{run:n}=await t.rerunRun(e);ce({runs:[n],more:oe.current.length>25}),re(n.id),ae(e=>e+1),r.offer({label:Vc(n),restore:()=>void Hc(t,n.id).then(()=>ae(e=>e+1))})}catch(e){j(`Not re-run: ${e instanceof Error?e.message:`server unreachable`}.`)}},[t,ce,r]),me=e=>{let t=e.run?oe.current.find(t=>t.id===e.run):void 0,r=[];return zn(e)&&r.push({label:`Resume`,icon:n,onSelect:()=>void fe(e.run)}),t&&Bc(t)&&r.push({label:`Re-run`,icon:Pt,onSelect:()=>void Z(t.id)}),r},he=(0,Q.useCallback)(async()=>{let e=oe.current;ee(!0);try{await t.clear()}catch{j(`Not cleared: server unreachable.`);return}finally{ee(!1)}u([]),f(!1),r.offer({label:`Cleared ${Dn(e.length,`run`)}`,restore:()=>{for(let n of e)t.submit(K().upgradePipeline(n.snapshot)).catch(()=>{})}})},[t,r]),ge=(0,Q.useCallback)(async()=>{F(!0);let e=[],t=!1,n;for(let r=0;;r++){let i=await J(n,!0);if(!i){t=!0;break}if(e=Gc([...e,...i.runs]),n=Kc(i.runs.at(-1)),!i.more||!n||r>100)break}if(t){let t=new Set(e.map(e=>e.id));e=Gc([...e,...oe.current.filter(e=>!t.has(e.id))])}if(F(!1),!e.length){j(`Nothing to export yet.`);return}Ir(new Blob([JSON.stringify({exported:new Date().toISOString(),runs:e},null,2)],{type:`application/json`}),Fr(`runs`,`all`,13,`json`)),j(t?`Exported ${Dn(e.length,`run`)}. Server unreachable, so only those this browser had.`:`Exported ${Dn(e.length,`run`)}.`)},[t,J]),_e=[{label:`Select Columns`,icon:ht,onSelect:()=>x(!0)},{label:`Export JSON`,icon:w,busy:P,onSelect:()=>void ge()},{label:`Clear`,icon:T,destructive:!0,busy:I,disabled:!L,onSelect:()=>void he()}],ve=(0,Q.useCallback)(e=>{let t=e.target.closest(`[data-openrun]`);if(t){e.stopPropagation();let n=t.closest(`tr[data-run]`),r=n?Y[Number(n.getAttribute(`data-run`))]:null;r?.run&&de(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?Y[Number(t.getAttribute(`data-run`))]:null;r?.run&&D({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?Y[Number(t.getAttribute(`data-run`))]:null,i=n?.run?oe.current.find(e=>e.id===n.run):null;i?.snapshot&&k({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?Y[Number(t.getAttribute(`data-run`))]:null,r=i.getAttribute(`data-prof`);if(n&&r!=null){let e=n.scenarios[Number(r)];C({name:e?.setupProfile?.name??``,settings:bn(n,e??{})})}}},[Y,de]),ye=(0,Q.useCallback)((e,t)=>{u(n=>n.map(n=>n.id===e?{...n,snapshot:{...n.snapshot,comment:t}}:n)),D(null)},[]),xe=(e,t)=>e.image&&wn(t)!==!0?(0,$.jsx)(`span`,{className:`note`,children:`—`}):e.get(t),Se=(e,t,n,r)=>n?e.image&&wn(t)!==!0?(0,$.jsx)(`span`,{className:`note`,children:`—`}):e.get(t,n,r):`—`;return(0,$.jsxs)(`div`,{className:`history`,children:[(0,$.jsxs)(b,{id:`history`,title:`History`,actions:_e,children:[!L&&(0,$.jsx)(i,{label:`Runs`,error:B,onRetry:()=>{V(null),H(e=>e+1)}}),L&&(se.length>0||p)&&(0,$.jsx)(ie,{noun:`runs`,lead:Y.length>0&&(0,$.jsx)(`p`,{className:`note hstatus`,role:`status`,children:Dn(Y.length,`run`)}),filters:[{key:`show`,label:`Show`,value:p,onChange:m,options:Uc.map(e=>({value:e,label:e?Mn(e):`All`}))}]}),A&&(0,$.jsx)(`p`,{className:`note hstatus`,role:`status`,children:A}),L?Y.length?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`scrollx`,onClick:ve,children:(0,$.jsx)(R,{className:`htable`,label:`Runs`,defaultSort:null,rows:Y,rowKey:e=>e.at,rowProps:(e,t)=>({className:`runrow${g.has(e.at)?` open`:``}${e.run&&e.run===W?` fresh`:``}`,"data-run":t}),columns:[{key:`expand`,header:(0,$.jsx)(`span`,{className:`hvh`,children:`Targets`}),label:``,className:`hexpand`,sort:null,cell:(t,n)=>{let r=g.has(t.at);return(0,$.jsx)(`button`,{type:`button`,className:`icon-btn`,"aria-label":r?`Collapse`:`Expand`,"aria-expanded":r,"aria-controls":r?`hscen-${n}`:void 0,onClick:()=>X(t.at),children:(0,$.jsx)(e,{size:16,"aria-hidden":`true`})})}},...ue.Runs.map(e=>({key:e.key,header:e.label,className:Wc(e),sort:e.sort??(t=>pe(e.get(t))),cell:t=>(0,$.jsx)(`span`,{className:`hval`,children:xe(e,t)})})),{key:`actions`,header:(0,$.jsx)(`span`,{className:`hvh`,children:`Actions`}),label:``,className:`hactions`,sort:null,cell:e=>{let t=me(e);return t.length?(0,$.jsx)(a,{actions:t,label:`${En(e.at)} actions`}):null}}],after:(e,t)=>g.has(e.at)&&(0,$.jsx)(`tr`,{className:`scenrows`,id:`hscen-${t}`,"data-run":t,"data-scen":e.at,children:(0,$.jsx)(`td`,{colSpan:ue.Runs.length+2,children:(0,$.jsx)(R,{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:ue[`Run Scenarios`].map(t=>({key:t.key,header:t.label,className:Wc(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 pe(i)},cell:({sc:n,n:r})=>(0,$.jsx)(`span`,{className:`hval`,children:Se(t,e,n,r)})}))})})})})}),d&&(0,$.jsxs)(`button`,{type:`button`,className:`ghost older-btn`,disabled:M,"aria-busy":M||void 0,onClick:async()=>{N(!0);let e=await J(Kc(oe.current.at(-1)));if(N(!1),!e){j(`Server unreachable.`);return}ce(e)},children:[M&&(0,$.jsx)(h,{}),`Older`]})]}):(0,$.jsx)(`p`,{className:`note`,children:A??(se.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)(le,{undo:r.undo,onUndo:r.undoNow,onDismiss:r.dismiss}),v&&(0,$.jsx)(Qc,{cols:q,onSave:e=>{c(Zc(e)),x(!1)},onClose:()=>x(!1)}),O&&(0,$.jsx)(pc,{run:O.run,i:O.i,onClose:()=>k(null)}),S&&(0,$.jsx)(y,{title:S.name||`Settings`,onClose:()=>C(null),children:(0,$.jsx)(Jc,{settings:S.settings})}),E&&(0,$.jsx)(Yc,{runId:E.id,comment:E.comment,onSaved:e=>ye(E.id,e),onClose:()=>D(null)})]})}function Jc({settings:e}){let t=vn.filter(t=>String(e[t]??``)!==``).map(t=>({key:t,label:xn(t),control:{type:`static`,text:Sn(t,e[t])}}));return t.length?(0,$.jsx)(he,{label:`Target profile`,rows:t}):(0,$.jsx)(`p`,{className:`note`,children:`No settings recorded.`})}function Yc({runId:e,comment:t,onSaved:n,onClose:r}){let i=be(),[a,o]=(0,Q.useState)(t),[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(!1);return(0,$.jsx)(j,{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:de,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 Xc(e){let t=()=>({Runs:new Set(Vn.filter(e=>e.on).map(e=>e.key)),"Run Scenarios":new Set(Hn.filter(e=>e.on).map(e=>e.key))});if(!e)return t();let n=t();for(let t of Gn){let r=t[0],i=e[r],a=new Set(t[1].map(e=>e.key)),o=e=>Wn[e]??e,s=new Set(i?.seen?.map(o)??[...a]),c=[...(i?.on??[]).map(o).filter(e=>a.has(e)),...t[1].filter(e=>e.on&&!s.has(e.key)).map(e=>e.key)];c.length&&(n[r]=new Set(c))}return n}function Zc(e){return{Runs:{on:[...e.Runs],seen:Vn.map(e=>e.key)},"Run Scenarios":{on:[...e[`Run Scenarios`]],seen:Hn.map(e=>e.key)}}}function Qc({cols:e,onSave:t,onClose:n}){let[r,i]=(0,Q.useState)(()=>({Runs:new Set(e.Runs),"Run Scenarios":new Set(e[`Run Scenarios`])})),[a,o]=(0,Q.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)(y,{title:`Select Columns`,onClose:n,dirty:c,children:(0,$.jsxs)(`div`,{className:`hcols`,children:[Gn.map(([e,t])=>(0,$.jsxs)(`div`,{className:`groups`,children:[(0,$.jsx)(`h3`,{children:Un[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 $c=e=>!!e&&e.startsWith(`•held:`),el={"promptlab.workflows":{list:[],at:``},"promptlab.profiles":{list:[],at:``},"promptlab.comment":null,"promptlab.versions":tl(),"promptlab.history.columns":null,"promptlab.tokens":null};function tl(){return{pipeline:{},profile:{},dataset:{}}}var nl=[`promptlab.workflows`,`promptlab.profiles`,`promptlab.versions`,`promptlab.tokens`],rl=[`px`,`format`,`quality`],il=[{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`}],al={"image/jpeg":`JPEG`,"image/webp":`WebP`,"image/png":`PNG`},ol=e=>al[e]??e.replace(`image/`,``).toUpperCase(),sl={px:`921600`,quality:`0.92`};function cl(e,t){let n=K().connectionImage({}).format,r=String(e.px??``),i=String(e.format??``),a=String(e.quality??``),o=(il.some(e=>e.value===r)||!r?il:[...il,{value:r,label:K().budgetLabel(r)}]).map(e=>e.value===sl.px?{value:``,label:e.label}:e),s=K().IMAGE_FORMATS.map(e=>e===n?{value:``,label:ol(e)}:{value:e,label:ol(e)}),c=(i||n)===`image/png`,l={type:`text`,value:a,onChange:t(`quality`),size:`num`,...c||a?{}:{placeholder:sl.quality}};return[{key:`px`,label:`Resolution`,control:{type:`select`,value:r===sl.px?``:r,options:o,onChange:t(`px`)}},{key:`format`,label:`Format`,control:{type:`select`,value:i===n?``:i,options:s,onChange:t(`format`)}},{key:`quality`,label:`Quality`,...c?{hint:`Unused for PNG`}:{},control:l}]}function ll(e){let{px:t,format:n,quality:r}=K().connectionImage(e),i=n===`image/png`?``:` q${r??sl.quality}`;return`${K().budgetLabel(t??Number(sl.px))}, ${ol(n)}${i}`}function ul({offer:e}){let t=be(),n=Ne(),r=Qe(),o=ct(),[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(!1),h=(0,Q.useRef)(null),g=e=>u({text:e instanceof Error?e.message:String(e),bad:!0}),_=(0,Q.useCallback)(()=>{f(null),t.packs().then(e=>c(e.packs),e=>f(e instanceof Error?e.message:String(e)))},[t]);(0,Q.useEffect)(_,[_]);let v=async()=>{await Promise.all([n.refresh(),r.refresh(),o.refresh()]),_()},y=async e=>{u({text:`Installing ${e.name}…`,bad:!1}),m(!0);try{let n=await t.installPack(e);await v();let r=(await t.packs()).packs.find(e=>e.id===n.pack),i=r?`${r.name} ${r.version}`:n.pack;u({text:n.installed?`Installed ${i}.`:`${i} is up to date.`,bad:!1})}catch(e){g(e)}finally{m(!1)}},x=async n=>{let r=[];try{for(let e of n)r.push((await t.removePack(e.id)).trash)}catch(e){g(e)}r.length&&(await v(),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 v()})()}}))};return(0,$.jsxs)(b,{id:`setup-packs`,title:`Packs`,note:s?dl(s.length,`pack`):``,actions:[{label:`Install pack…`,icon:U,busy:p,onSelect:()=>h.current?.click()}],children:[s===null&&(0,$.jsx)(i,{label:`Packs`,error:d,onRetry:_}),s&&!s.length&&(0,$.jsx)(`p`,{className:`note`,children:`No packs installed.`}),s&&s.length>0&&(0,$.jsx)(R,{className:`setup-table`,cards:!0,label:`Packs`,rows:s,rowKey:e=>e.id,select:{noun:`pack`,actions:e=>[{label:`Remove`,icon:W.remove,destructive:!0,onSelect:()=>void x(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=>fl(e)},{key:`menu`,header:``,className:`ds-menu`,role:`menu`,sort:null,cell:e=>(0,$.jsx)(a,{label:`${e.name} actions`,actions:[{label:`Remove`,icon:W.remove,destructive:!0,onSelect:()=>void x([e])}]})}]}),l&&(0,$.jsx)(`p`,{className:`note${l.bad?` bad`:``}`,role:l.bad?`alert`:`status`,children:l.text}),(0,$.jsx)(`input`,{ref:h,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&&y(t)}})]})}var dl=(e,t)=>`${e} ${t}${e===1?``:`s`}`,fl=e=>[dl(e.datasets.length,`dataset`),dl(e.pipelines.length,`pipeline`),dl(e.sources.length,`source`),dl(e.presets,`preset`)].join(`, `);function pl({offer:e}){let t=be(),[n,r]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)(null),[u,d]=(0,Q.useState)(!1),f=(0,Q.useRef)(null),p=(0,Q.useCallback)(()=>{l(null),t.plugins().then(e=>r(e.plugins),e=>l(e instanceof Error?e.message:String(e)))},[t]);(0,Q.useEffect)(p,[p]);let m=async e=>{s(null),d(!0);try{let n=await t.installPlugin(e),i=(await t.plugins()).plugins;r(i);let a=i.find(e=>e.id===n.plugin);a&&n.installed&&await Oe(a),s({text:n.installed?Te[n.plugin]?`Installed ${n.plugin}, and it did not load: ${Te[n.plugin]}`:`Installed ${n.plugin}.`:`${n.plugin} is up to date.`,bad:!!Te[n.plugin]})}catch(e){s({text:e instanceof Error?e.message:String(e),bad:!0})}finally{d(!1)}},h=async n=>{let r=[];try{for(let e of n)r.push((await t.removePlugin(e.id)).trash)}catch(e){s({text:e instanceof Error?e.message:String(e),bad:!0})}p(),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(p)}})};return(0,$.jsxs)(b,{id:`setup-plugins`,title:`Plugins`,note:n?`${n.length} ${n.length===1?`plugin`:`plugins`}`:``,actions:[{label:`Install plugin…`,icon:U,busy:u,onSelect:()=>f.current?.click()}],children:[n===null&&(0,$.jsx)(i,{label:`Plugins`,error:c,onRetry:p}),n&&!n.length&&(0,$.jsx)(`p`,{className:`note`,children:`No plugins installed.`}),n&&n.length>0&&(0,$.jsx)(R,{className:`setup-table`,cards:!0,label:`Plugins`,rows:n,rowKey:e=>e.id,select:{noun:`plugin`,actions:e=>[{label:`Remove`,icon:W.remove,destructive:!0,onSelect:()=>void h(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=>ml(e),cell:e=>ml(e)||`—`},{key:`state`,header:`State`,cell:e=>hl(e)},{key:`menu`,header:``,className:`ds-menu`,role:`menu`,sort:null,cell:e=>(0,$.jsx)(a,{label:`${e.id} actions`,actions:[{label:`Remove`,icon:W.remove,destructive:!0,onSelect:()=>void h([e])}]})}]}),o&&(0,$.jsx)(`p`,{className:`note${o.bad?` bad`:``}`,role:o.bad?`alert`:`status`,children:o.text}),(0,$.jsx)(`input`,{ref:f,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&&m(t)}})]})}var ml=e=>[...e.registers.outputKinds??[],...e.registers.modifiers??[],...e.registers.evalTypes??[],...(e.registers.connectionTypes??[]).map(e=>e.id)].join(`, `),hl=e=>Te[e.id]?`Failed: ${Te[e.id]}`:Ee.has(e.id)?`Loaded`:`Not Loaded`,gl={env:`Deployment`,lab:`Own`,default:`Default`};function _l({cfg:e,editable:t,onClose:n}){let r=be(),i=e?.from===`lab`?e:null,[a,o]=(0,Q.useState)(i?.clientId??``),[s,c]=(0,Q.useState)(i?.tenant??``),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(!1),p=a!==(i?.clientId??``)||s!==(i?.tenant??``),m=async()=>{if(!p){n();return}f(!0);try{await r.setMicrosoft(a,s),ba(),n()}catch(e){u(e instanceof Error?e.message:String(e)),f(!1)}},h=e=>t=>{u(null),e(t)},g=!t,_=new URL(`/`,ma()??window.location.href).href,v=[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),size:`wide`,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),size:`wide`,placeholder:`00000000-0000-0000-0000-000000000000`}},{key:`redirect`,label:`Redirect URI`,control:{type:`code`,text:_}},{key:`app`,label:`App`,control:{type:`static`,text:e?.from?gl[e.from]:`None`}}];return(0,$.jsx)(j,{title:`Microsoft 365`,status:l??void 0,statusBad:!!l,focusRow:g?void 0:`client`,sections:[{key:`app`,rows:v}],...g?{}:{onSave:()=>void m(),saving:d,dirty:p},onClose:n})}var vl={env:`Deployment`,lab:`Own`,default:`Default`},yl=`https://console.cloud.google.com/apis/credentials`,bl=[{value:`installed`,label:`Desktop app`},{value:`web`,label:`Web application`}],xl={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.`},Sl=`/api/connections/google/callback`,Cl=()=>/^(localhost|127\.|\[::1\])/.test(window.location.hostname);function wl(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 Tl({onClose:e,onSaved:t}){let n=be(),[r,i]=(0,Q.useState)(void 0),[a,o]=(0,Q.useState)(!0),[s,c]=(0,Q.useState)(``),[l,u]=(0,Q.useState)(``),[d,f]=(0,Q.useState)(``),[p,m]=(0,Q.useState)(Cl()?`installed`:`web`),[h,g]=(0,Q.useState)({clientId:``,apiKey:``,kind:``}),[_,v]=(0,Q.useState)(null),[y,b]=(0,Q.useState)(null),[x,S]=(0,Q.useState)(!1);(0,Q.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??(Cl()?`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=wl(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,M=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:bl.find(e=>e.value===A).label}}]:[{key:`client`,label:`Client ID`,control:{type:`text`,value:s,onChange:T(c),size:`wide`,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),size:`wide`,placeholder:`AIza…`}},{key:`type`,label:`Type`,hint:xl[p],control:{type:`select`,value:p,options:bl,onChange:e=>T(m)(e)}}];return M.push({key:`redirect`,label:`Redirect URI`,control:A===`web`?{type:`code`,text:new URL(Sl,window.location.href).href}:{type:`static`,text:`Not Needed`}},{key:`app`,label:`App`,control:{type:`static`,text:r?.from?vl[r.from]:`None`}}),(0,$.jsx)(j,{title:`Google Drive`,status:_??y??void 0,statusBad:!!_,focusRow:O?void 0:`client`,sections:[{key:`app`,rows:M}],actions:[{label:`Google Cloud`,icon:gt,onSelect:()=>{window.open(yl,`_blank`,`noopener`)}},...O?[]:[{label:`Load client file…`,icon:vt,onSelect:E}]],...O?{}:{onSave:()=>void w(),saving:x,dirty:C},onClose:e})}var El=`microsoft`,Dl=`google`;function Ol(){let e=be(),{cfg:t,editable:n}=xa(),[r,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(void 0),[d,f]=(0,Q.useState)(null),p=(0,Q.useCallback)(()=>{e.connections().then(e=>c(e.connections),()=>c([]))},[e]);(0,Q.useEffect)(p,[p]),(0,Q.useEffect)(()=>{if(!t){u(null);return}fa(t).then(u,()=>u(null))},[t]);let m=[...s??[],...t||n?[{id:El,label:`Microsoft 365`,configured:!!t,signedIn:!!l,account:l??null,problem:null}]:[]],g=async n=>{f(null);try{n.id===El&&t?await ga(t):window.location.assign((await e.signIn(n.id)).url)}catch(e){f(e instanceof Error?e.message:String(e))}},_=async n=>{f(null);try{n.id===El&&t?(await _a(t),u(null)):c((await e.signOut(n.id)).connections)}catch(e){f(e instanceof Error?e.message:String(e))}};if(s===null)return(0,$.jsx)(b,{id:`setup-connections`,title:`Connections`,children:(0,$.jsx)(i,{label:`Connections`})});if(!m.length)return null;let v=m.filter(e=>e.problem);return(0,$.jsxs)(b,{id:`setup-connections`,title:`Connections`,note:`${m.filter(e=>e.signedIn).length} of ${m.length}`,children:[(0,$.jsx)(R,{className:`setup-table`,cards:!0,label:`Connections`,rows:m,rowKey:e=>e.id,columns:[{key:`label`,header:`Connection`,role:`title`,cell:e=>e.label},{key:`status`,header:`Status`,cell:e=>e.id===El&&t&&l===void 0?(0,$.jsxs)(`span`,{className:`loading-status`,children:[(0,$.jsx)(h,{}),`Checking`]}):kl(e)},{key:`account`,header:`Account`,cell:e=>e.account||`—`},{key:`menu`,header:``,className:`ds-menu`,role:`menu`,sort:null,cell:e=>(0,$.jsx)(a,{label:`${e.label} actions`,actions:[e.signedIn?{label:`Sign out`,icon:Dt,onSelect:()=>void _(e)}:{label:`Sign in`,icon:Et,disabled:!e.configured,onSelect:()=>void g(e)},...e.id===El||e.id===Dl?[{label:`Configure…`,icon:Ft,onSelect:()=>o(e.id)}]:[]]})}]}),v.map(e=>(0,$.jsxs)(`p`,{className:`note bad`,role:`alert`,children:[e.label,`: `,e.problem]},e.id)),d&&(0,$.jsx)(`p`,{className:`note bad`,role:`alert`,children:d}),r===El&&t!==void 0&&(0,$.jsx)(_l,{cfg:t,editable:n,onClose:()=>o(null)}),r===Dl&&(0,$.jsx)(Tl,{onClose:()=>o(null),onSaved:p})]})}var kl=e=>e.configured?e.signedIn?`Signed In`:`Signed Out`:`Not Configured`;function Al(){let e=Ne(),t=be(),n=ne(),[r,i]=Pe(`promptlab.profiles`),[a]=Pe(`promptlab.versions`),[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)(null),u=(0,Q.useRef)(c);u.current=c;let[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)({}),[_,y]=(0,Q.useState)(``),[x,S]=(0,Q.useState)(``),[C,w]=(0,Q.useState)(``),[T,E]=(0,Q.useState)({key:`name`,dir:`asc`}),[D,O]=(0,Q.useState)([]),[k,A]=(0,Q.useState)({});(0,Q.useEffect)(()=>{let e=!0;return t.presets().then(t=>{e&&O(t)}).catch(()=>{}),()=>{e=!1}},[t]);let j=(0,Q.useRef)(r);j.current=r;let M=(0,Q.useCallback)(e=>{let t=u.current;return t?.p.id===e?t.p:j.current.list.find(t=>t.id===e)},[]),N=(0,Q.useCallback)(e=>{let t=u.current;if(t?.p.id!==e.id)return;let n={...t,p:e};u.current=n,l(n)},[]),P=(0,Q.useCallback)(()=>{let t=u.current;if(!t)return;let n=j.current,r=t.was?{...n,list:n.list.map(e=>e.id===t.p.id?t.p:e)}:{...n,list:[...n.list,t.p],at:t.p.id};j.current=r,i(r),qe(e,`profile`,t.p.id,t.p,`idle`),l(null),s(null)},[i,e]),F=(0,Q.useCallback)(()=>{l(null),s(null)},[]),I=(0,Q.useCallback)(()=>{let e=Yl(j.current.list);l({p:e,was:null,start:e}),s({id:``,focus:`name`})},[]),ee=(0,Q.useCallback)(e=>{let t=j.current.list.find(t=>t.id===e);if(!t)return;let n=`${t.name||`Profile`} copy`,r={...structuredClone(t),id:ql(),name:n,slug:Jl(n,j.current.list),key:t.key},a={...j.current,list:[...j.current.list,r]};j.current=a,i(a)},[i]),L=(0,Q.useCallback)(e=>{let t=j.current,r=new Set(e),a=t.list.filter(e=>!r.has(e.id));if(!a.length||a.length===t.list.length)return;let o=r.has(t.at)?a[0].id:t.at,c={...t,list:a,at:o,...t.grader&&r.has(t.grader)?{grader:``}:{}};j.current=c,i(c),s(null),l(null);let u=t.list.filter(e=>r.has(e.id));n.offer({label:u.length===1?`Deleted ${u[0].name||`the profile`}`:`Removed ${u.length} profiles`,restore:()=>{j.current=t,i(t)}})},[i,n]),z=(0,Q.useCallback)(e=>L([e]),[L]),B=(0,Q.useCallback)(t=>{let n=t.doc.id,r=j.current.list.find(e=>e.id===n);r&&qe(e,`profile`,n,r,`restore`);let a=j.current,o={...a,list:a.list.map(e=>e.id===n?t.doc:e)};j.current=o,i(o),V()},[e,i]),V=(0,Q.useCallback)(()=>{f(e=>(e?.back&&se(e.id),null))},[]),te=(0,Q.useCallback)(async e=>{let n=M(e);if(!n)return;let r=K().CONNECTION_TYPES[n.type];if(r?.local){g(t=>({...t,[e]:{phase:`connected`,ms:0,lines:[`${r.label} answers each text item with its own text, and sends nothing anywhere.`]}}));return}let i=r?.keyless?``:n.key,a=n.url.trim()||r?.url||`the lab's Ollama`,o=performance.now(),s=()=>Math.round(performance.now()-o),c=[];g(t=>({...t,[e]:{phase:`checking`,lines:[`Checking…`]}}));try{let o=Object.fromEntries((r?.settings??[]).map(e=>[e.key,String(n[e.key]??``)]));if(`testPath`in o&&!o.testPath.trim()){let e=r?.templates?.find(e=>Vl(e.settings.url,n.url));e?.settings.testPath&&(o.testPath=e.settings.testPath)}let l=((await t.models({url:n.url,key:i,type:n.type,settings:o})).data||[]).map(e=>e.id).sort();if(A(t=>({...t,[e]:l})),c.push(`Reached ${a}.`,`${l.length} ${l.length===1?`model`:`models`}: ${l.join(`, `)||`none`}.`),(r?.answers??[`prompt`]).includes(`prompt`)){if(n.model.trim()){let e=K().apiBase(n.url||r?.url||``),a=K().connectionRequest(n,`hi`,null,e,i),o=await t.modelsAsk({url:n.url,key:i,type:n.type,body:a.body}),{raw:s}=K().connectionReply(n,o);c.push(``,`Asked ${n.model} “hi”; it replied:`,s||`(an empty reply)`)}else c.push(``,`No model is picked, so nothing was asked.`)}g(t=>({...t,[e]:{phase:`connected`,lines:c,ms:s()}}))}catch(t){c.push(...c.length?[``]:[],t instanceof Error?t.message:String(t)),g(t=>({...t,[e]:{phase:`error`,lines:c,ms:s()}}))}},[t,M]),H=o?c?.p:void 0,U=H?JSON.stringify([H.id,H.url,H.type,H.key]):``;(0,Q.useEffect)(()=>{if(!H)return;let e=H;if(K().CONNECTION_TYPES[e.type]?.local||K().CONNECTION_TYPES[e.type]?.lists===!1)return;let n=K().CONNECTION_TYPES[e.type]?.keyless,r=!0,i=setTimeout(()=>{t.models({url:e.url,key:n?``:e.key,type:e.type,quiet:!0}).then(t=>{r&&A(n=>({...n,[e.id]:(t.data||[]).map(e=>e.id).sort()}))}).catch(()=>{r&&A(t=>({...t,[e.id]:[]}))})},400);return()=>{r=!1,clearTimeout(i)}},[t,U]);let re=(0,Q.useCallback)((e,t)=>{let n=M(e);if(!n)return;let r={...n};for(let e of Wl(n.type))r[e]=``;for(let[e,n]of Object.entries(t.opts))r[e]=n;N(r)},[M,N]),G=(0,Q.useCallback)(e=>{g(t=>{if(!(e in t))return t;let{[e]:n,...r}=t;return r})},[]),ae=(0,Q.useCallback)((e,t,n)=>{let r=M(e);if(r){if([`url`,`key`,`model`].includes(t)&&G(e),t===`name`){let t=j.current.list.filter(t=>t.id!==e);if(!r.slug||r.slug===Jl(r.name,t)){N({...r,name:n,slug:Jl(n,t)});return}}t===`slug`&&(n=n.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+/,``).slice(0,K().SLUG_MAX)),N({...r,[t]:n})}},[M,N,G]),oe=(0,Q.useCallback)((e,t)=>{let n=M(e);if(!n)return;let r={...n,type:t};G(e),A(t=>({...t,[e]:[]}));let i=K().CONNECTION_TYPES[t];i?.keyless&&(r.key=``),i?.url&&!r.url.trim()&&(r.url=i.url);for(let e of Object.keys(r))[`id`,`name`,`slug`,`url`,`model`,`key`,`temperature`,`type`,...rl].includes(e)||Gl(t).includes(e)||delete r[e];N(r)},[M,N,G]),se=(0,Q.useCallback)((e,t)=>{let n=j.current.list.find(t=>t.id===e);n&&(l({p:structuredClone(n),was:n,start:n}),s(t?{id:e,focus:t}:{id:e}))},[]),q=(0,Q.useCallback)(e=>a.profile?.[e]??[],[a]),J=o?c?.p??null:null,ce=c?c.was?r.list.map(e=>e.id===c.p.id?c.p:e):[...r.list,c.p]:r.list,Y=[...new Set(r.list.map(e=>e.type))],ue=_.trim().toLowerCase(),X=r.list.filter(e=>(!x||e.type===x)&&(!C||C===`set`==!!e.key)&&(!ue||[e.name,e.url,e.model].some(e=>String(e??``).toLowerCase().includes(ue))));return(0,$.jsxs)(`div`,{className:`setup`,children:[(0,$.jsxs)(b,{id:`setup-profiles`,title:`Target profiles`,note:Kl(r.list.length),children:[(0,$.jsx)(`p`,{className:`note`,children:`A profile is how the lab reaches a model or an API: its type, address, key and settings. A target picks one.`}),r.list.length>0&&(0,$.jsx)(ie,{noun:`profiles`,search:{label:`Search profiles`,placeholder:`Name, address or model`,value:_,onChange:y},filters:[{key:`type`,label:`Type`,value:x,onChange:S,options:[{value:``,label:`All`},...Y.map(e=>({value:e,label:K().CONNECTION_TYPES[e]?.label??e}))]},{key:`key`,label:`Key`,value:C,onChange:w,options:[{value:``,label:`All`},{value:`set`,label:`Set`},{value:`unset`,label:`Not set`}]},{key:`sort`,label:`Sort`,value:T?.key??``,neutral:`name`,onChange:e=>E(e?{key:e,dir:`asc`}:null),options:[{value:``,label:`As added`},{value:`name`,label:`Name`},{value:`type`,label:`Type`},{value:`url`,label:`Address`},{value:`model`,label:`Model`}]}],count:{shown:X.length,total:r.list.length}}),r.list.length===0?(0,$.jsx)(`p`,{className:`note`,children:`No profiles yet.`}):X.length===0?(0,$.jsx)(`p`,{className:`note`,children:`No profiles match these filters.`}):(0,$.jsx)(R,{className:`setup-table`,cards:!0,label:`Target profiles`,sort:T,onSort:E,rows:X,rowKey:e=>e.id,select:{noun:`profile`,label:e=>e.name||`Unnamed profile`,actions:e=>[{label:`Remove`,icon:W.remove,destructive:!0,disabled:e.length>=r.list.length,onSelect:()=>L(e.map(e=>e.id))}]},rowProps:e=>({className:`setup-row`,onClick:t=>{t.target.closest(`button, a, .menu`)||se(e.id)}}),columns:jl({tests:h,only:r.list.length===1,grader:r.grader??null,onGrader:e=>{let t=j.current,n={...t,grader:t.grader===e?``:e};j.current=n,i(n)},onOpen:se,onClone:ee,onRemove:z,onTest:te,onResult:e=>m({id:e,back:!1})})}),(0,$.jsxs)(`button`,{type:`button`,className:`ghost add-btn`,onClick:I,children:[(0,$.jsx)(v,{size:14,"aria-hidden":`true`}),`Add profile`]})]}),(0,$.jsx)(Ol,{}),(0,$.jsx)(pl,{offer:n.offer}),(0,$.jsx)(ul,{offer:n.offer}),(0,$.jsx)(le,{undo:n.undo,onUndo:n.undoNow,onDismiss:n.dismiss}),J&&(0,$.jsx)(Ml,{profile:J,slug:K().withSlugs(ce).find(e=>e.id===J.id)?.slug??``,...o?.focus?{focus:o.focus}:{},test:h[J.id],models:k[J.id]??[],presets:D.filter(e=>(e.type??`llama.cpp`)===J.type),canRestore:!!c?.was&&!!q(J.id).length,dirty:!!c&&JSON.stringify(c.p)!==JSON.stringify(c.start),onSave:P,onClose:F,onSetting:ae,onType:oe,onTest:te,onResult:()=>{s(null),m({id:J.id,back:!0})},onRestore:()=>{F(),f({id:J.id,back:!0})},onApplyPreset:e=>re(J.id,e)}),p&&h[p.id]&&(0,$.jsx)(Bl,{test:h[p.id],onClose:()=>{p.back&&u.current?.p.id===p.id&&s({id:p.id}),m(null)}}),d&&(0,$.jsx)(Rl,{versions:q(d.id),onClose:V,onRestore:B})]})}function jl({tests:e,only:t,grader:n,onGrader:r,onOpen:i,onClone:o,onRemove:s,onTest:c,onResult:l}){let u=e=>e.name||`Unnamed profile`,d=a=>[{label:`Edit…`,icon:W.edit,onSelect:()=>i(a.id)},{label:`Rename…`,icon:W.rename,onSelect:()=>i(a.id,`name`)},{label:`Clone`,icon:W.clone,onSelect:()=>o(a.id)},{label:`Test connection`,icon:_e,busy:e[a.id]?.phase===`checking`,onSelect:()=>void c(a.id)},...(K().CONNECTION_TYPES[a.type]?.answers??[`prompt`]).includes(`prompt`)&&!K().CONNECTION_TYPES[a.type]?.local?[{label:n===a.id?`Stop grading`:`Make grader`,icon:Tt,onSelect:()=>r(a.id)}]:[],...t?[]:[{label:`Remove`,icon:W.remove,destructive:!0,onSelect:()=>s(a.id)}]];return[{key:`name`,header:`Profile`,role:`title`,sort:u,cell:t=>{let r=e[t.id];return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,className:`setup-open`,onClick:()=>i(t.id),children:u(t)}),n===t.id&&(0,$.jsx)(`span`,{className:`setup-note`,children:`Grader`}),r&&(0,$.jsx)(`button`,{type:`button`,className:`edit-outcome setup-note${r.phase===`error`?` bad`:``}`,"aria-label":`Test connection: ${zl[r.phase]}`,onClick:()=>l(t.id),children:zl[r.phase]})]})}},{key:`type`,header:`Type`,label:``,sort:e=>K().CONNECTION_TYPES[e.type]?.label??e.type,cell:e=>K().CONNECTION_TYPES[e.type]?.label??e.type},{key:`url`,header:`Address`,sort:e=>e.url.trim(),cell:e=>K().CONNECTION_TYPES[e.type]?.local?(0,$.jsx)(`span`,{className:`setup-unset`,children:`—`}):e.url.trim()||(0,$.jsx)(`span`,{className:`setup-unset`,children:`Default`})},{key:`model`,header:`Model`,sort:e=>e.model.trim(),cell:e=>K().CONNECTION_TYPES[e.type]?.local?(0,$.jsx)(`span`,{className:`setup-unset`,children:`—`}):e.model.trim()||(0,$.jsx)(`span`,{className:`setup-unset`,children:`Not set`})},{key:`key`,header:`Key`,sort:e=>e.key?`Set`:``,cell:e=>K().CONNECTION_TYPES[e.type]?.keyless?(0,$.jsx)(`span`,{className:`setup-unset`,children:`—`}):e.key?`Set`:(0,$.jsx)(`span`,{className:`setup-unset`,children:`Not set`})},{key:`menu`,header:``,label:``,className:`setup-menu`,role:`menu`,sort:null,cell:e=>(0,$.jsx)(a,{actions:d(e),label:`${u(e)} actions`})}]}function Ml({profile:e,slug:t,focus:n,test:r,models:i,presets:a,canRestore:o,dirty:c,onSave:l,onClose:u,onSetting:d,onType:f,onTest:p,onResult:m,onRestore:h,onApplyPreset:g}){let _=K().CONNECTION_TYPES[e.type],v=(_?.answers??[`prompt`]).includes(`prompt`),y=(0,Q.useMemo)(()=>Ll(e),[e]),b=t=>n=>d(e.id,t,n),x=[{key:`name`,label:`Name`,required:!0,control:{type:`text`,value:e.name,onChange:b(`name`)}},{key:`slug`,label:`Slug`,required:!0,...e.slug&&K().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(K().CONNECTION_TYPES).filter(([t,n])=>n.picker!==!1||t===e.type).map(([e,t])=>({value:e,label:t.label}))}},..._?.local?[]:[{key:`url`,label:`Address`,control:{type:`text`,value:e.url,placeholder:_?.url??`the lab's Ollama`,onChange:b(`url`)}},..._?.keyless?[]:[{key:`key`,label:`Key`,control:{type:`secret`,value:$c(e.key)?``:e.key,held:$c(e.key),onChange:b(`key`)}}],...v?[{key:`model`,label:`Model`,control:Ul(e.model,i,b(`model`))}]:[]]],S=(_?.settings??[]).map(t=>Nl(e,t,b(t.key))),C=[{key:`identity`,rows:x},...S.length?[{key:`settings`,title:`Settings`,rows:S}]:[],..._?.local||!v?[]:[{key:`image`,title:`Image`,rows:cl(e,b)},{key:`debug`,title:`Debug`,rows:y,folded:!0}]],w=[{label:`Restore…`,icon:s,disabled:!o,onSelect:h},...a.map(e=>({label:`Apply preset: ${e.label}`,icon:W.preset,onSelect:()=>g(e)})),...(_?.templates??[]).map(t=>({label:`Apply template: ${t.label}`,icon:W.preset,onSelect:()=>g({id:t.id,label:t.label,type:e.type,opts:t.settings})}))];return(0,$.jsx)(j,{title:e.name||`Unnamed profile`,...n?{focusRow:n}:{},sections:C,menu:w,actions:_?.tests===!1?[]:[{label:`Test connection`,icon:_e,busy:r?.phase===`checking`,onSelect:()=>p(e.id),outcome:r?{label:zl[r.phase],bad:r.phase===`error`,onOpen:m}:void 0}],dirty:c,onSave:l,onClose:u})}function Nl(e,t,n){let r=e[t.key]??t.default??``;if(t.control===`select`&&t.choices)return{key:t.key,label:t.label,control:{type:`select`,value:r,options:t.choices,onChange:n}};if(t.key===`grammar`)return{key:t.key,label:t.label,control:{type:`textarea`,value:r,onChange:n}};let i=r?null:Fl(e,t.key),a={type:`text`,value:r,onChange:n,...i?.placeholder?{placeholder:i.placeholder}:{},...i?.numeric?{size:`num`}:{}};return{key:t.key,label:t.label,control:a}}var Pl=`424242`;function Fl(e,t){let n=K().apiBase(e.url),r,i;try{r=Il(K().connectionRequest({...e,[t]:``},`(prompt)`,null,n).body),i=Il(K().connectionRequest({...e,[t]:Pl},`(prompt)`,null,n).body)}catch{return null}let a=Object.keys(i).find(e=>i[e]===Pl||i[e]===JSON.stringify(Pl));if(a===void 0)return null;let o=i[a]===Pl,s=a in r?JSON.parse(r[a]):null;return s===null?{numeric:o}:{placeholder:String(s),numeric:o}}function Il(e,t=``,n={}){if(e&&typeof e==`object`&&!Array.isArray(e))for(let[r,i]of Object.entries(e))Il(i,t?`${t}.${r}`:r,n);else n[t]=JSON.stringify(e)??`null`;return n}function Ll(e){let t=K().apiBase(e.url),n=[];try{let{url:r,body:i}=K().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:ll(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 Rl({versions:e,onClose:t,onRestore:n}){return(0,$.jsx)(y,{title:`Restore profile`,onClose:t,children:(0,$.jsxs)(`div`,{className:`version-list`,children:[e.length===0&&(0,$.jsx)(`p`,{className:`note`,children:`No versions of this profile yet.`}),e.map((e,t)=>(0,$.jsxs)(`div`,{className:`version-row`,children:[(0,$.jsxs)(`span`,{className:`version-when`,children:[Zl(e.at),`, `,Xl(e.reason)]}),(0,$.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>n(e),children:`Restore`})]},`${e.at}-${t}`))]})})}var zl={checking:`Checking…`,connected:`Connected`,error:`Error`};function Bl({test:e,onClose:t}){return(0,$.jsx)(j,{title:`Test connection`,sections:[{key:`result`,rows:[{key:`time`,label:`Time`,required:!0,control:{type:`static`,text:e.ms==null?`—`:Hl(e.ms)}},{key:`result`,label:`Result`,required:!0,control:{type:`textarea`,value:e.lines.join(`
14
+ `)}}]}],onClose:t})}function Vl(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 Hl=e=>e<1e3?`${e} ms`:`${(e/1e3).toFixed(1)}s`;function Ul(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 Wl(e){return K().CONNECTION_TYPES[e]?.settings.map(e=>e.key).filter(e=>e!==`temperature`)??[]}function Gl(e){return K().CONNECTION_TYPES[e]?.settings.map(e=>e.key)??[]}var Kl=e=>e===1?`1 profile`:`${e} profiles`,ql=()=>`p${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`,Jl=(e,t)=>K().uniqueSlug(K().slugOf(e),new Set(K().withSlugs(t).map(e=>e.slug))),Yl=e=>({id:ql(),name:`New profile`,slug:Jl(`New profile`,e),url:``,model:``,key:``,temperature:``,nPredict:``,maxTokens:``,type:`ollama`}),Xl=e=>e===`run`?`before a run`:e===`restore`?`before a restore`:`after editing`,Zl=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},Ql=[];function $l(e,t){let n=be(),[r,i]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(t===null)return;let r=!0,a=Ie(n);return a.runDataset(e).then(n=>{if(n){r&&i({run:e,cases:K().upgradeDatasetBody(n).cases,current:!1});return}return a.dataset(t).then(t=>{r&&i({run:e,cases:K().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:Ql,current:a?.current??!1}}function eu(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=>K().metricLines(e.values)),forbidden:t.filter(e=>e.not&&e.type===`contains`).map(e=>({value:String(e.value??``),except:K().metricLines(e.except)}))}}var tu=e=>e==null?`—`:Fn(e);function nu(e){return e?.transcript||[]}function ru(e,t){return t.flatMap((n,r)=>{let i=nu(e?.scenarios?.[r]?.res);return t.length>1?i.map(e=>({...e,scenario:n.name})):i})}function iu({stages:e}){if(!e.length)return null;let t=!e.some(e=>e.scenario)&&e.length>1?`, ${e.map(e=>tu(e.ms)).join(` + `)}`:``;return(0,$.jsxs)(`div`,{className:`transcript`,children:[(0,$.jsxs)(`div`,{className:`meta`,children:[`Transcript`,t]}),e.map((e,t)=>(0,$.jsxs)(`pre`,{children:[(0,$.jsxs)(`b`,{children:[e.scenario?`${e.scenario}, `:``,`job `,e.n,` `,e.withImage?`(with image)`:`(text only)`,e.kind?`, ${e.kind}`:``,e.conn?`, ${e.conn}`:``,`, `,tu(e.ms),` — sent`]}),`
15
+ `,e.sent,`
16
+ `,(0,$.jsx)(`b`,{children:`— returned`}),`
17
+ `,e.got||(e.error?`(nothing)`:``),e.error?`\n<b className="fault">Error - ${e.error}</b>`:``]},t))]})}function au({text:e,kind:t}){return(0,$.jsx)(`span`,{className:`term${t?` ${t}`:``}`,children:e})}function ou({res:e,kase:t}){let n=e?.dropped||[];if(!n.length)return null;let r=e=>t?eu(t).wanted.some(t=>K().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)(au,{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 su({kase:e}){return(0,$.jsx)($.Fragment,{children:(e.metrics??[]).map((e,t)=>(0,$.jsx)(`div`,{className:`wants${e.weight===0?` watched`:``}`,children:Tr(e)},t))})}var cu=e=>e?.transcript?.at(-1)?.kind===`text`;function lu({res:e}){return e?.error?(0,$.jsx)(`span`,{className:`err`,children:e.error}):cu(e)?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`pre`,{children:e?.transcript?.at(-1)?.got||`(empty)`}),(0,$.jsx)(`div`,{className:`meta`,children:tu(e?.ms)})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`chips`,children:(e?.terms||[]).map((e,t)=>(0,$.jsx)(au,{text:String(e)},t))}),(0,$.jsx)(ou,{res:e,kase:null}),(0,$.jsxs)(`div`,{className:`meta`,children:[(e?.terms||[]).length,` items, `,tu(e?.ms)]})]})}function uu({res:e}){if(e?.error)return(0,$.jsx)(`span`,{className:`err`,children:e.error});let t=e?.transcript?.at(-1)?.got??e?.raw??``;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`pre`,{children:t||`(empty)`}),(0,$.jsxs)(`div`,{className:`meta`,children:[tu(e?.ms),`, `,cu(e)?`answered as text`:`read as ${(e?.terms||[]).length} items`]})]})}function du({tab:e,undo:t}){let r=be(),o=ne(),s=t??o,{setShow:c,openRun:l,closeRun:d}=un(),{openCaseEditor:f}=li(),[p,m]=(0,Q.useState)(null),[v,y]=(0,Q.useState)(!1),[x,S]=(0,Q.useState)(null),[C,w]=(0,Q.useState)(new Set),[T,E]=(0,Q.useState)(!1),[D,O]=(0,Q.useState)(null),[k,A]=(0,Q.useState)(null),[j,M]=(0,Q.useState)(0),[N,P]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{let t=!0,n=!1,i,a=async()=>{try{let o=await r.run(e.id);if(!t)return;n=!0,m(o),A(null),Kn(o.status)||(i=setTimeout(()=>void a(),1e3))}catch(e){if(!t)return;n?i=setTimeout(()=>void a(),1e3):A(e instanceof Ae?e.message:`Run not loaded: server unreachable.`)}};return a(),()=>{t=!1,i&&clearTimeout(i)}},[r,e.id,j]);let F=(0,Q.useMemo)(()=>p?sr(p):null,[p]),I=F?K().evalsDataset(F.snapshot)?.id??null:null,ee=$l(e.id,I),L=(0,Q.useMemo)(()=>new Map(ee.cases.map(e=>[K().caseItem(e),e])),[ee.cases]),z=(0,Q.useCallback)(async()=>{P(null);try{let{run:t}=await r.rerunRun(e.id);l(t.id,{at:t.submittedAt,from:e.from}),s.offer({label:Vc(t),restore:()=>{Hc(r,t.id),d(t.id)}})}catch(e){P(`Not re-run: ${e instanceof Error?e.message:`server unreachable`}.`)}},[r,e.id,e.from,l,d,s]),B=(0,Q.useCallback)(async()=>{y(!0);try{await r.cancel(e.id)}catch{}y(!1)},[r,e.id]);if(!F)return(0,$.jsx)(b,{id:`run-${e.id}`,title:En(e.at)||`Run`,children:(0,$.jsx)(i,{label:`Run`,error:k,onRetry:()=>{A(null),M(e=>e+1)}})});let V=F.progress,te=V.n??V.total??0,H=!Kn(F.status),U=V.total&&te!=null&&H?Math.round(te/V.total*100):null,re=kr(F,ee.cases),G=F.scenarios.map((e,t)=>jr(F,ee.cases,t)),ae=_r(F),oe=(e,t,n)=>{let r=new Set(e);r.has(t)?r.delete(t):r.add(t),n(r)},se=async(e,t,n)=>{let r=Math.max(0,F.scenarios.findIndex((t,n)=>$n(F,e,n))),i=(t.scenarios??[])[r]?.res;i&&await nc(Er(F.snapshot,n,i,r))&&(E(!0),setTimeout(()=>E(!1),1600))},q=async()=>{await nc(re.map(e=>Er(F.snapshot,e.kase,e.res,e.scenarioIndex)).join(`
18
+
19
+ `+`-`.repeat(60)+`
20
+
21
+ `))&&(E(!0),setTimeout(()=>E(!1),1600))},J=[...re.length?[{label:`Copy all failures`,icon:_,onSelect:()=>void q()}]:[],...p&&Bc(p)?[{label:`Re-run`,icon:Pt,onSelect:()=>void z()}]:[]],ce={key:`show`,label:`Show`,value:e.show,onChange:t=>c(e.id,t),options:[{value:`all`,label:`All`},{value:`failed`,label:`Failed`}]},Y=!!I,le=F.evals.find(e=>K().casesRef(e))?.id??null,ue=!!(F.content&&K().CONTENT_TYPES[F.content.type]?.inline),X=e=>{let t=F.results[e]?.name;return t?L.get(t):void 0},de=t=>{let i=F.results[t],a=X(t),o=!!i&&!i.unrun&&Kn(F.status),s=(i?.scenarios??[]).some(e=>e?.res?.transcript?.length),c=[];return s&&c.push({label:`Show details`,icon:u,onSelect:()=>oe(C,t,w)}),o&&i?.name&&a&&c.push({label:`Edit case`,icon:W.edit,onSelect:()=>I&&f(i.name,{dataset:I,resultFor:e=>F.results[t]?.scenarios?.[e]?.res??null,scenarioCount:F.scenarios.length,files:F.results.filter(e=>e.kind!==`text`).map(e=>e.name??``)})}),o&&F.id&&c.push({label:`Re-run row`,icon:n,onSelect:()=>void r.rerun(e.id,t).then(e=>m(e.run)).catch(()=>{})}),o&&a&&fu(F,t)&&c.push({label:`Copy as AI prompt`,icon:_,onSelect:()=>void se(t,i,a)}),c};return(0,$.jsxs)(`div`,{className:`runview`,children:[(0,$.jsxs)(b,{id:`run-${e.id}`,title:F.name||En(e.at),actions:J,children:[(0,$.jsxs)(`div`,{className:`runhead`,children:[ae&&(0,$.jsxs)(`span`,{className:`note run-queue`,children:[(0,$.jsx)(`span`,{className:`run-state`,children:ae.state}),ae.detail&&(0,$.jsx)(`span`,{className:`run-item`,children:ae.detail})]}),H&&(0,$.jsxs)(`button`,{type:`button`,className:`ghost stop-btn`,disabled:v,onClick:()=>void B(),children:[v?(0,$.jsx)(h,{}):(0,$.jsx)(g,{size:14,"aria-hidden":`true`}),`Stop`]})]}),H&&(0,$.jsx)(`div`,{className:`rrbar`,children:U==null?(0,$.jsx)(`span`,{className:`rrprogress`,children:`Waiting`}):(0,$.jsxs)(`div`,{className:`rrmeter`,role:`progressbar`,"aria-valuenow":U,"aria-valuemin":0,"aria-valuemax":100,children:[(0,$.jsx)(`div`,{className:`rrbarfill`,style:{width:`${U}%`}}),(0,$.jsxs)(`span`,{className:`rrpct`,style:{"--pct":`${U}%`},children:[U,`%`]})]})}),p?.rerunOf&&(0,$.jsxs)(`p`,{className:`note rrorigin`,children:[`Re-run of`,` `,p.rerunOfAt?(0,$.jsx)(`a`,{href:`#`,onClick:t=>{t.preventDefault(),l(p.rerunOf,{at:p.rerunOfAt,from:e.from})},children:En(p.rerunOfAt)}):`a cleared run`]}),F.error&&(0,$.jsx)(`p`,{className:`note bad rrstatus`,role:`status`,children:F.error}),N&&(0,$.jsx)(`p`,{className:`note bad rrstatus`,role:`status`,children:N}),(0,$.jsx)(`div`,{id:`run-${e.id}-stats`,className:`runstats`,children:(0,$.jsx)(hn,{label:`Run Statistics`,...fr(F)})}),T&&(0,$.jsx)(`p`,{className:`note`,role:`status`,children:`Copied to clipboard.`})]}),F.evals.length>0&&(0,$.jsx)(mu,{id:`run-${e.id}-evals`,summary:or(F),scenarios:F.scenarios,onScenario:O}),(0,$.jsxs)(b,{id:`run-${e.id}-results`,title:`Results`,children:[(0,$.jsx)(ie,{noun:`results`,filters:[ce],lead:(0,$.jsx)(`p`,{className:`note`,children:Dn(F.items.length,`item`)}),count:{total:F.items.length,shown:e.show===`failed`?F.items.filter((e,t)=>fu(F,t)).length:F.items.length}}),ee.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":F.scenarios.length},children:(0,$.jsx)(R,{className:Y?`rrtable graded`:`rrtable`,defaultSort:null,label:`Results`,rows:F.items.map((e,t)=>t),rowKey:e=>`${F.items[e]}-${e}`,pinned:(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`tr`,{className:`scenstats`,children:[(0,$.jsx)(`td`,{className:`scenstats-label`,children:`Statistics`}),Y&&(0,$.jsx)(`td`,{className:`scenstats-blank`}),F.scenarios.map((e,t)=>(0,$.jsx)(`td`,{className:`scenstat`,"data-label":e.name,children:(0,$.jsx)(hn,{dense:!0,label:`${e.name} statistics`,...mr(F,t)})},e.id))]}),G.some(e=>e.length>0)&&I&&(0,$.jsx)(pu,{from:En(e.at)||F.name,datasetId:I,failing:G,scenarios:F.scenarios,items:F.items.length,graded:Y})]}),rowProps:t=>({"data-item":t,className:C.has(t)?`hasdetail`:void 0,hidden:e.show===`failed`&&!fu(F,t)}),after:t=>C.has(t)&&(0,$.jsx)(`tr`,{className:`rrdetail`,"data-detail":t,hidden:e.show===`failed`&&!fu(F,t),children:(0,$.jsx)(`td`,{colSpan:1+ +!!Y+F.scenarios.length,children:(0,$.jsx)(iu,{stages:ru(F.results[t],F.scenarios)})})}),columns:[{key:`item`,header:ue?`Text`:`Item`,label:``,className:`col-item`,sort:e=>F.items[e]||``,cell:e=>{let t=F.results[e],n=F.items[e];return(0,$.jsxs)($.Fragment,{children:[t?.name&&!ue&&Qr(t.name)?(0,$.jsx)(`button`,{type:`button`,className:`thumb`,"aria-label":`Open ${t.name}`,onClick:()=>S(t.name),children:(0,$.jsx)(`img`,{src:yr(F,t.name),alt:``,loading:`lazy`,"data-name":t.name})}):null,(0,$.jsxs)(`div`,{className:`rritem`,children:[(0,$.jsx)(`div`,{className:`meta`,children:n||``}),(0,$.jsx)(a,{actions:de(e),label:`${n||`row`} actions`})]})]})}},...Y?[{key:`expected`,header:`Expected`,className:`col-expected`,sort:e=>{let t=X(e);return t&&!t.todo?t.metrics?.length??0:null},cell:e=>{let t=X(e);return F.results[e]?t&&!t.todo?(0,$.jsx)(su,{kase:t}):(0,$.jsx)(`span`,{className:`note`,children:`n/a`}):``}}]:[],...F.scenarios.map((e,t)=>({key:`scenario-${t}`,header:e.name,label:e.name,onHeader:()=>O(t),cell:e=>(0,$.jsx)(hu,{item:F.results[e],i:t,readings:(F.outcomes[t]??[]).filter(e=>!e.whole).map(t=>({label:t.label,dataset:t.id===le,score:t.items[e]??null}))})}))]})})]}),D!=null&&(0,$.jsx)(pc,{run:F.snapshot,i:D,onClose:()=>O(null)}),x&&(0,$.jsx)(yu,{src:br(F,x),name:x,onClose:()=>S(null)})]})}var fu=(e,t)=>{let n=e.results[t];return!!n&&(!!n.unrun||(n.scenarios??[]).some((n,r)=>$n(e,t,r)||!!n?.res?.error))};function pu({from:e,datasetId:t,failing:n,scenarios:r,items:i,graded:a}){let{showCases:o}=sn(),{list:s}=$e(),c=s!==null&&!s.some(e=>e.id===t),l=r.length>1;return(0,$.jsxs)(`tr`,{className:`reasons`,children:[(0,$.jsx)(`td`,{className:`scenstats-label`,children:`Reasons`}),a&&(0,$.jsx)(`td`,{className:`scenstats-blank`}),r.map((r,a)=>{let s=r.name,u=n[a]??[];return(0,$.jsx)(`td`,{className:`reasons-cell`,"data-label":s,children:u.length===0?(0,$.jsx)(`span`,{className:`reasons-none`,children:`No failures`}):(0,$.jsx)(`ul`,{className:`reasons-list`,"aria-label":`${s} reasons`,children:u.map(n=>{let r=n.files.length,a=(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(i,1)*100)}%`},children:c?(0,$.jsx)(`span`,{className:`reason`,children:a}):(0,$.jsx)(`a`,{className:`reason`,href:`#/library/datasets`,title:`${n.label}${n.note?` (${n.note})`:``}: open ${Dn(r,`case`)} in the Library`,"aria-label":`${n.label}: open ${Dn(r,`case`)} in the Library`,onClick:r=>{r.preventDefault(),o(t,n.files,`${e}${l?`, ${s}`:``}, ${n.label}`)},children:a})},n.key)})})},r.id)})]})}function mu({id:e,summary:t,scenarios:n,onScenario:r}){let i=[...t.rows.map(e=>({kind:`group`,group:e})),...t.overall?[{kind:`overall`,...t.overall}]:[]],a=(e,t)=>e==null&&t==null?(0,$.jsx)(`span`,{className:`eg-none`,children:`—`}):(0,$.jsxs)(`span`,{className:`eg-cell`,children:[e!=null&&(0,$.jsx)(Tn,{pass:e}),t!=null&&(0,$.jsxs)(`span`,{className:`eg-pct`,children:[t,`%`]})]}),o=t.rows.some(e=>e.version!=null);return(0,$.jsx)(b,{id:e,title:`Evals`,children:(0,$.jsx)(`div`,{className:`scrollx`,style:{"--scenarios":n.length},children:(0,$.jsx)(R,{className:o?`egtable`:`egtable unversioned`,label:`Evals`,rows:i,rowKey:e=>e.kind===`group`?e.group.key:`overall`,defaultSort:null,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,$.jsx)(`span`,{className:`eg-name`,children:e.group.name}):(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})]})},...o?[{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:()=>r(t),cell:e=>{if(e.kind===`overall`)return a(e.pass[t]??null);let n=e.group.cells[t];return n?a(n.pass,n.pct):null}}))]})})})}function hu({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&&!K().isSkipped(e.score)&&e.score.metrics?.length),a=n.length===1&&K().isSkipped(n[0].score),o=(0,$.jsxs)($.Fragment,{children:[(n.length>1||!i&&n.some(e=>e.score))&&(0,$.jsx)(vu,{readings:n}),a&&n.length===1&&(0,$.jsx)(`span`,{className:`verdict skipped`,children:`Skipped`}),(0,$.jsx)(gu,{readings:n})]});return(0,$.jsxs)($.Fragment,{children:[o,e?.kind===`text`?(0,$.jsx)(uu,{res:r}):(0,$.jsx)(lu,{res:r})]})}function gu({readings:e}){let t=e.flatMap(e=>e.score&&!K().isSkipped(e.score)&&e.score.metrics?.length?[{...e,score:e.score}]:[]);return t.length?(0,$.jsx)($.Fragment,{children:t.map((e,t)=>{let n=e.score.metrics.filter(e=>e.weight!==0),r=e.score.metrics.filter(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:_u(e.score.score,!!e.score.points)}),n.length>0&&(0,$.jsx)(`ul`,{children:n.map((e,t)=>(0,$.jsxs)(`li`,{className:e.pass?`pass`:`fail`,children:[(0,$.jsx)(`span`,{className:`eval-name`,children:e.label}),!e.pass&&(0,$.jsxs)($.Fragment,{children:[` `,(0,$.jsx)(`span`,{className:`metric-reason`,children:e.reason})]})]},t))}),r.length>0&&(0,$.jsxs)(`div`,{className:`watched`,children:[(0,$.jsx)(`b`,{children:`Watch`}),(0,$.jsx)(`ul`,{children:r.map((e,t)=>(0,$.jsxs)(`li`,{className:e.pass?`met`:`unmet`,children:[(0,$.jsx)(`span`,{className:`eval-name`,children:e.label}),` `,(0,$.jsx)(`span`,{className:`metric-reason`,children:e.reason})]},t))})]})]},t)})}):null}var _u=(e,t)=>t?`${Math.round(e*100)/100} points`:`${Math.round(e*100)}%`;function vu({readings:e}){return(0,$.jsx)(`ul`,{className:`eval-verdicts`,children:e.map((e,t)=>{let n=e.score?K().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 yu({src:e,name:t,onClose:n}){return(0,$.jsx)(y,{title:t||`Image`,onClose:n,children:(0,$.jsx)(`img`,{className:`lightbox-img`,src:e,alt:t})})}function bu(){let{tabs:e,focusedId:n,closeRun:r,focusRun:i,goBack:a}=un(),o=ne(),s=e.find(e=>e.id===n);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:En(s.at)||`…`}),(0,$.jsx)(`div`,{className:`rtabs`,role:`tablist`,"aria-label":`Open runs`,children:e.map(e=>(0,$.jsxs)(`div`,{className:`rtab${e.id===n?` on`:``}`,children:[(0,$.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":e.id===n,className:`rname`,title:En(e.at)||`run`,onClick:()=>i(e.id),children:En(e.at)||`…`}),(0,$.jsx)(`button`,{type:`button`,className:`rx`,"aria-label":`Close`,onClick:()=>r(e.id),children:(0,$.jsx)(t,{size:14,"aria-hidden":`true`})})]},e.id))})]}),(0,$.jsx)(du,{tab:s,undo:o}),(0,$.jsx)(le,{undo:o.undo,onUndo:o.undoNow,onDismiss:o.dismiss})]}):null}function xu(){let e=Qe(),t=(0,Q.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 Su=`promptlab.theme`,Cu=typeof matchMedia==`function`?matchMedia(`(prefers-color-scheme: light)`):null;function wu(){try{let e=JSON.parse(localStorage.getItem(Su)||`null`)?.choice;return e===`light`||e===`dark`?e:null}catch{return null}}var Tu=()=>wu()??(Cu?.matches?`light`:`dark`),Eu=()=>{let e=Tu();return document.documentElement.setAttribute(`data-theme`,e),e};Eu();function Du(){let[e,t]=(0,Q.useState)(Tu);(0,Q.useEffect)(()=>{let e=()=>t(Eu());return Cu?.addEventListener?.(`change`,e),()=>Cu?.removeEventListener?.(`change`,e)},[]);let n=e===`light`?`dark`:`light`,r=n===`light`?`Light mode`:`Dark mode`;return(0,$.jsx)(`button`,{type:`button`,className:`icon-btn`,title:r,"aria-label":r,onClick:()=>{try{localStorage.setItem(Su,JSON.stringify({choice:n}))}catch{}document.documentElement.setAttribute(`data-theme`,n),t(n)},children:(0,$.jsx)(n===`light`?zt:kt,{size:16,"aria-hidden":`true`})})}var Ou=()=>{let e=decodeURIComponent(location.hash.replace(/^#\/?/,``)),t=e.match(/^(evals|datasets|sources)(\/.*)?$/);t&&(e=`library/${t[1]===`sources`?`sources`:`datasets`}${t[2]??``}`,history.replaceState(null,``,`#/${e.split(`/`).map(encodeURIComponent).join(`/`)}`));let n=e.match(/^library(?:\/(datasets|prompts|sources))?(?:\/(.+))?$/);if(n){let e=n[1]??`datasets`,t=n[2]??null;return{tab:`library`,section:e,src:e===`sources`?t:null,groupId:e===`datasets`?t:null}}return{tab:Mr.find(t=>t.id===e)?.id??`home`,section:`datasets`,src:null,groupId:null}};function ku(){return(0,$.jsx)(M,{children:(0,$.jsx)(Ze,{children:(0,$.jsx)(st,{children:(0,$.jsx)(ln,{children:(0,$.jsx)(on,{children:(0,$.jsx)(ci,{children:(0,$.jsx)(Au,{})})})})})})})}function Au(){let[e,t]=(0,Q.useState)(Ou),{hide:n}=un();(0,Q.useEffect)(()=>{let e=()=>{t(Ou()),n()};return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[n]);let r=Mr.find(t=>t.id===e.tab);return(0,$.jsxs)(`div`,{className:`app`,children:[(0,$.jsxs)(`header`,{className:`app-head`,children:[(0,$.jsx)(`h1`,{children:`Evals Lab`}),(0,$.jsx)(Mu,{}),(0,$.jsx)(xu,{}),(0,$.jsx)(k,{}),(0,$.jsx)(Du,{})]}),(0,$.jsx)(oe,{}),(0,$.jsx)(me,{label:`Lab`,className:`app-tabs`,tablist:!0,current:e.tab,items:Mr.map(e=>({key:e.id,label:e.label,href:`#/${e.id}`,icon:e.icon,id:`tab-${e.id}`,controls:`panel-${e.id}`}))}),(0,$.jsx)(ju,{tab:r,section:e.section,src:e.src,groupId:e.groupId})]})}function ju({tab:e,section:t,src:n,groupId:r}){let{focusedId:i}=un(),a=i?(0,$.jsx)(bu,{}):e.id===`home`?(0,$.jsx)(Jo,{}):e.id===`runs`?(0,$.jsx)(Pc,{}):e.id===`history`?(0,$.jsx)(qc,{}):e.id===`library`?(0,$.jsx)(Vo,{section:t,sourceId:n,groupId:r}):(0,$.jsx)(Al,{});return(0,$.jsx)(`main`,{role:`tabpanel`,id:`panel-${e.id}`,"aria-labelledby":`tab-${e.id}`,"data-tab":e.id,children:a})}function Mu(){let{sync:e,resolve:t}=Fe();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 Nu=`promptlab.sync`,Pu=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Fu=(e,t)=>{let n=el[e];return Pu(n)&&Pu(t)?{...n,...t}:t};function Iu({api:e,storage:t,server:n,pause:r=800}){let i=e=>{try{return t.getItem(e)}catch{return null}},a=new Map,o=(e,n)=>{a.delete(e);try{n==null?t.removeItem(e):t.setItem(e,JSON.stringify(n))}catch{}a.set(e,n??null)},s=e=>{try{return JSON.parse(i(e)??`null`)}catch{return null}},c=(e,t)=>i(e)===(t==null?null:JSON.stringify(t)),l=n!==null,u=s(Nu)??{},d={},f=new Set,p=()=>o(Nu,{versions:d,dirty:[...f]}),m=new Set,h=()=>m.forEach(e=>e()),g=l?{state:`saved`}:{state:`local`},_=null,v=null,y=e=>{g=e,h()};if(n){for(let e of nl){let t=n[e];t&&c(e,t.body)?d[e]=t.version:u.dirty?.includes(e)?(d[e]=u.versions?.[e]??0,f.add(e)):t?(d[e]=t.version,o(e,t.body)):(d[e]=0,i(e)!=null&&f.add(e))}p()}async function b(t=!1){if(!l||g.state===`conflict`)return;if(!f.size){g.state===`saving`&&y({state:`saved`});return}let n=[...f],r=Object.fromEntries(n.map(e=>[e,{version:d[e]??0,body:s(e)}]));y({state:`saving`});try{let{versions:i}=await e.writeState(r,t);Object.assign(d,i);for(let e of n)c(e,r[e].body)&&f.delete(e);if(p(),y({state:`saved`}),f.size)return b(t)}catch(e){if(e instanceof Ae&&e.status===409){let t=e.body?.stale??{};for(let[e,n]of Object.entries(t))d[e]=n.version;let n=Object.keys(t).filter(e=>!c(e,t[e].body));for(let e of Object.keys(t))n.includes(e)||f.delete(e);return p(),n.length?(x=t,y({state:`conflict`,keys:n})):b()}y({state:`offline`,message:e instanceof Error?e.message:String(e)})}}let x={};function S(e=!1){return _&&=(clearTimeout(_),null),v??=b(e).finally(()=>{v=null}),v}return f.size&&(_=setTimeout(()=>{S()},0)),{get(e){return a.has(e)||a.set(e,Fu(e,s(e))),a.get(e)??el[e]},set(e,t){o(e,t),l&&nl.includes(e)&&(f.add(e),p(),_&&clearTimeout(_),_=setTimeout(()=>{S()},r)),h()},subscribe(e){return m.add(e),()=>{m.delete(e)}},sync:()=>g,async resolve(e){if(g.state!==`conflict`)return;let t=g.keys;if(e===`theirs`){for(let e of t)o(e,x[e]?.body??null),f.delete(e);p()}x={},y({state:`saved`}),await S()},flush:S,async refresh(){if(!l)return;await S();let{docs:t}=await e.state(),n=!1;for(let e of nl){let r=t[e];!r||f.has(e)||r.version<=(d[e]??0)||(d[e]=r.version,o(e,r.body),n=!0)}n&&(p(),h())}}}var Lu=e=>[1,2,3,4,5,6,7,8,9,10].includes(e?.version)||K().fatProfileRef(e),Ru=e=>e?.version===1||e?.version===2;function zu(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(Ru).map(e=>e?.tests?.type===`graded`?e.tests.dataset?.id:void 0);return[...new Set(t.filter(e=>!!e))]}function Bu(e,t={}){let n=new Map(e.get(`promptlab.profiles`).list.map(e=>[e.id,e.type])),r={rulesFor:e=>t[e]??null,profileType:e=>n.get(e)},i=e=>K().upgradePipeline(e,r),a=e=>Lu(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)}))]))})}async function Vu(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}}async function Hu(){K();let e=je(),t=()=>{},n=new Promise(e=>{t=e});if(/^#\/?history\/?$/.test(location.hash)&&e.askQueue({limit:25},n),ua())try{let t=(await e.config()).microsoft;t&&await da(t)}catch{}if(ha())try{let t=(await e.config()).microsoft;if(t){await ga(t);return}}catch{}await ke(e),t();let r=Iu({api:e,storage:localStorage,server:await Vu(e)}),i=r.get(`promptlab.profiles`);i.list.some(e=>`profile`in e)&&r.set(`promptlab.profiles`,{...i,list:i.list.map(e=>K().convertProfile(e))});let a=r.get(`promptlab.profiles`),o=e=>K().pinReplyTokens(K().splitOllama(e));a.list.some(e=>o(e)!==e)&&r.set(`promptlab.profiles`,{...a,list:a.list.map(e=>o(e))});let s=r.get(`promptlab.profiles`),c=K().withSlugs(s.list);c!==s.list&&r.set(`promptlab.profiles`,{...s,list:c});let l={};if(zu(r).length)try{l=(await e.archivedRules()).rules}catch{}Bu(r,l),addEventListener(`pagehide`,()=>{r.flush(!0)}),(0,ve.createRoot)(document.getElementById(`root`)).render((0,$.jsx)(Q.StrictMode,{children:(0,$.jsx)(Me.Provider,{value:r,children:(0,$.jsx)(ye.Provider,{value:e,children:(0,$.jsx)(ku,{})})})}))}Hu();