evals-lab 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +66 -0
- package/README.md +17 -9
- package/lab/VERSION +1 -1
- package/lab/demo/datasets/demo-1.json +2187 -1644
- package/lab/demo/datasets/demo-2.json +1870 -1485
- package/lab/demo/manifest.json +2 -2
- package/lab/demo/pipelines/demo-1.json +3 -7
- package/lab/demo/pipelines/demo-2.json +3 -7
- package/lab/evals-core.mjs +429 -434
- package/lab/kinds/list.mjs +1 -1
- package/lab/metrics/builtin.mjs +96 -18
- package/lab/run-evals.js +35 -33
- package/lab/server.py +296 -82
- package/lab/web/dist/assets/{gallery-o7c4lfpn.css → gallery-DFeJkfUw.css} +1 -1
- package/lab/web/dist/assets/gallery-DRBlZ8mP.js +3 -0
- package/lab/web/dist/assets/main-DMpQmW8l.js +21 -0
- package/lab/web/dist/assets/main-wfqC6HcM.css +1 -0
- package/lab/web/dist/assets/tokens-BEn6_hVz.css +1 -0
- package/lab/web/dist/assets/tokens-iGpvbD5R.js +55 -0
- package/lab/web/dist/gallery.html +4 -4
- package/lab/web/dist/index.html +4 -4
- package/package.json +3 -2
- package/lab/web/dist/assets/gallery-DsetJSXv.js +0 -3
- package/lab/web/dist/assets/main-B-VtDGxC.css +0 -1
- package/lab/web/dist/assets/main-ERoD2Kll.js +0 -19
- package/lab/web/dist/assets/tokens-ClRQ7Mui.js +0 -51
- package/lab/web/dist/assets/tokens-D3C8O2Ib.css +0 -1
|
@@ -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,a as O,b as k,c as A,d as j,et as M,f as N,g as P,h as ee,i as F,j as I,k as L,l as te,m as R,o as ne,p as z,q as B,r as V,s as re,t as H,u as ie,v as U,w as ae,x as W,y as G,z as K}from"./tokens-iGpvbD5R.js";var q=e(),J=M(),oe=(0,J.createContext)(null);function Y(){let e=(0,J.useContext)(oe);if(!e)throw Error(`useApi outside an ApiContext: main.tsx mounts one at the root`);return e}var se=`modulepreload`,ce=function(e){return`/`+e},le={},ue=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=ce(t,n),t=s(t),t in le)return;le[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`:se,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)})},X={},de=new Set,fe=e=>`/plugins/${encodeURIComponent(e.id)}/${encodeURIComponent(e.version)}/${e.entry.split(`/`).map(encodeURIComponent).join(`/`)}`;async function pe(e){if(!de.has(e.id))try{let t=await ue(()=>import(fe(e)),[]);if(typeof t.default!=`function`)throw Error(`its entry exports no register function`);await t.default(x().pluginHost(e.id)),de.add(e.id),delete X[e.id]}catch(t){X[e.id]=t instanceof Error?t.message:String(t)}}async function me(e){let t=[];try{t=(await e.plugins()).plugins}catch{return}for(let e of t)await pe(e)}var he=class extends Error{status;body;constructor(e,t,n=null){super(t),this.name=`ApiError`,this.status=e,this.body=n}};function ge(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 he(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:x().upgradePipeline(e.snapshot),results:x().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.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=>x().evalsOf(e.snapshot).some(e=>x().isWholeRun(x().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:{}})),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()},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 _e=(0,J.createContext)(null);function ve(){let e=(0,J.useContext)(_e);if(!e)throw Error(`useStore outside a StoreContext: the app mounts one at its root`);return e}function ye(e){let t=ve();return[(0,J.useSyncExternalStore)(t.subscribe,()=>t.get(e)),(0,J.useCallback)(n=>t.set(e,n),[t,e])]}function be(){let e=ve();return{sync:(0,J.useSyncExternalStore)(e.subscribe,e.sync),resolve:e.resolve}}var xe=e=>e,Se=e=>e?.state===`conflict`?`Not saved: changed in another browser.`:e?.state===`offline`?`Not saved: ${e.message}`:null,Ce=(e,t)=>JSON.stringify(e)===JSON.stringify(t),we=e=>e instanceof Error?e.message:String(e),Te=({body:e,...t})=>t;function Ee({api:e,pause:t=800,idle:n}){let r=xe(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(Te(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(Te(c)),o.has(e))return v(e)}catch(t){let n=a.get(e);if(!n?.doc)return;let r=t instanceof he&&t.status===409?t.body?.current??null:null;if(r){if(Ce(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:we(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:we(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:we(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({...Te(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 De=3e4,Oe=(e,t)=>e.get(`promptlab.versions`)[t]??{};function ke(e,t){return(e.get(`promptlab.versions`).dataset?.[t]??[]).map(e=>({...e,doc:x().upgradeDatasetBody(e?.doc)})).filter(e=>Ae(e.doc))}var Ae=e=>!!e&&typeof e==`object`&&Array.isArray(e.cases);function je(e,t,n,r,i){let a=e.get(`promptlab.versions`),o=Oe(e,t),s=(o[n]??[]).slice(),c=structuredClone(r);s[0]&&Ne(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 Me(e,t,n,r){let i=e.get(`promptlab.versions`),a=(i.dataset?.[t]??[]).slice(),o=structuredClone(n);a[0]&&Ne(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 Ne=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Z=c(),Pe=(0,J.createContext)(null);function Fe({children:e,pause:t}){let n=Y(),r=ve(),i=(0,J.useMemo)(()=>Ee({api:n,...t==null?{}:{pause:t},idle:{ms:De,cut:(e,t)=>Me(r,e,t,`idle`)}}),[n,r,t]);return(0,J.useEffect)(()=>{let e=()=>{i.flush()};return addEventListener(`pagehide`,e),()=>removeEventListener(`pagehide`,e)},[i]),(0,Z.jsx)(Pe.Provider,{value:i,children:e})}function Ie(){let e=(0,J.useContext)(Pe);if(!e)throw Error(`useDatasets outside a DatasetsProvider: the app mounts one at its root`);return e}function Le(){let e=Ie(),t=(0,J.useSyncExternalStore)(e.subscribe,e.list);return(0,J.useEffect)(()=>{e.list().list===null&&e.refresh()},[e]),t}function Re(e){let t=Ie(),n=(0,J.useSyncExternalStore)(t.subscribe,()=>e?t.entry(e):void 0);return(0,J.useEffect)(()=>{e&&t.load(e)},[t,e]),n}var ze=e=>e.name.trim()||e.text.trim().split(`
|
|
2
|
+
`)[0].trim()||`Untitled prompt`,Be=e=>e?.state===`conflict`?`Not saved: changed in another browser.`:e?.state===`offline`?`Not saved: ${e.message}`:null,Ve=e=>e instanceof Error?e.message:String(e),He=({versions:e,uses:t,...n})=>n;function Ue({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(He(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(He(f)),u)return p(t)}catch(e){let n=r.get(t);if(!n?.doc)return;let a=e instanceof he&&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:Ve(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:Ve(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:Ve(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(He(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 We=(0,J.createContext)(null);function Ge({children:e,pause:t}){let n=Y(),r=(0,J.useMemo)(()=>Ue({api:n,...t==null?{}:{pause:t}}),[n,t]);return(0,J.useEffect)(()=>{let e=()=>{r.flush()};return addEventListener(`pagehide`,e),()=>removeEventListener(`pagehide`,e)},[r]),(0,Z.jsx)(We.Provider,{value:r,children:e})}function Ke(){let e=(0,J.useContext)(We);if(!e)throw Error(`usePrompts outside a PromptsProvider: the app mounts one at its root`);return e}function qe(){let e=Ke(),t=(0,J.useSyncExternalStore)(e.subscribe,e.list);return(0,J.useEffect)(()=>{e.refresh()},[e]),t}function Je(e){let t=Ke(),n=(0,J.useSyncExternalStore)(t.subscribe,()=>e?t.entry(e):void 0);return(0,J.useEffect)(()=>{e&&t.load(e)},[t,e]),n}var Ye=S(`ban`,[[`path`,{d:`M4.929 4.929 19.07 19.071`,key:`196cmz`}],[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}]]),Xe=S(`circle-check`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),Ze=S(`circle-stop`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`rect`,{x:`9`,y:`9`,width:`6`,height:`6`,rx:`1`,key:`1ssd4o`}]]),Qe=S(`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`}]]),$e=S(`database`,[[`ellipse`,{cx:`12`,cy:`5`,rx:`9`,ry:`3`,key:`msslwz`}],[`path`,{d:`M3 5V19A9 3 0 0 0 21 19V5`,key:`1wlel7`}],[`path`,{d:`M3 12A9 3 0 0 0 21 12`,key:`mv7ke4`}]]),et=S(`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`}]]),tt=S(`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`}]]),nt=S(`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`}]]),rt=S(`flask-conical`,[[`path`,{d:`M14 2v6a2 2 0 0 0 .245.96l5.51 10.08A2 2 0 0 1 18 22H6a2 2 0 0 1-1.755-2.96l5.51-10.08A2 2 0 0 0 10 8V2`,key:`18mbvz`}],[`path`,{d:`M6.453 15h11.094`,key:`3shlmq`}],[`path`,{d:`M8.5 2h7`,key:`csnxdl`}]]),it=S(`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`}]]),at=S(`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`}]]),ot=S(`folder-open`,[[`path`,{d:`m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2`,key:`usdka0`}]]),st=S(`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=S(`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`}]]),lt=S(`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`}]]),ut=S(`house`,[[`path`,{d:`M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8`,key:`5wwlr5`}],[`path`,{d:`M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z`,key:`r6nss1`}]]),dt=S(`library`,[[`path`,{d:`m16 6 4 14`,key:`ji33uf`}],[`path`,{d:`M12 6v14`,key:`1n7gus`}],[`path`,{d:`M8 8v12`,key:`1gg7y9`}],[`path`,{d:`M4 4v16`,key:`6qkkli`}]]),ft=S(`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`}]]),pt=S(`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`}]]),mt=S(`message-square-text`,[[`path`,{d:`M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z`,key:`18887p`}],[`path`,{d:`M7 11h10`,key:`1twpyw`}],[`path`,{d:`M7 15h6`,key:`d9of3u`}],[`path`,{d:`M7 7h8`,key:`af5zfr`}]]),ht=S(`minus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}]]),gt=S(`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`}]]),_t=S(`play`,[[`path`,{d:`M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z`,key:`10ikf1`}]]),vt=S(`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`}]]),yt=S(`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`}]]),bt=S(`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`}]]),xt=S(`settings`,[[`path`,{d:`M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915`,key:`1i5ecw`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]),St=S(`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`}]]),Ct=S(`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`}]]),wt=S(`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`}]]),Tt=S(`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`}]]),Et=e=>(typeof e.id==`string`?e.id.trim():``)||`item:${x().caseItem(e)}`,Dt=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase(),Ot=e=>Array.isArray(e.metrics)?e.metrics:[],kt=e=>!e.not&&e.weight!==0,At=e=>e.type===`contains`&&e.not===!0&&e.weight!==0,jt=e=>x().metricLines(e);function Mt(e,t){let n=Ot(e);switch(t.type){case`bounds`:{let r=n.findIndex(e=>e.type===`item-count`&&kt(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=>At(e)&&Dt(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`&&kt(e));return i>=0&&jt(n[i].values).some(e=>Dt(e,r))?e:{...e,metrics:i>=0?n.map((e,t)=>t===i?{...e,values:[...jt(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(At(e)&&Dt(String(e.value??``),r))return i=!0,[];if((e.type===`contains-all`||e.type===`contains-any`)&&kt(e)&&jt(e.values).some(e=>Dt(e,r))){i=!0;let t=jt(e.values).filter(e=>!Dt(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 Nt(e,t,n){let r=[];return n.type===`delete`?{next:e.filter(e=>{let n=t.has(Et(e));return n&&r.push(Et(e)),!n}),changed:r}:{next:e.map(e=>{if(!t.has(Et(e)))return e;let i=Mt(e,n);return i!==e&&r.push(Et(e)),i}),changed:r}}function Pt(e,t,n){let r=new Map(e.map(e=>[Et(e),e])),i=new Map(t.map(e=>[Et(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(x().validateEvals({cases:[t]})),s=`${n.id}: `,c=x().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:x().caseItem(n),reasons:c})}return{cases:a}}var Ft={expect:`Expect`,forbid:`Forbid`},It=e=>Ft[e],Lt=e=>`${e} ${e===1?`case`:`cases`}`;function Rt(e,t){let n=Lt(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 ${Ft[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 zt={graded:`Graded`,todo:`To do`,missing:`Missing`};function Bt(e,t){return t&&!t.includes(x().caseItem(e))?`missing`:e.todo?`todo`:`graded`}var Vt={file:``,status:`all`,show:`all`};function Ht(e,t,n,r=null){let i=t.file.trim().toLowerCase();return e.filter(e=>(!i||x().caseItem(e).toLowerCase().includes(i))&&(t.status===`all`||Bt(e,r)===t.status)&&(t.show===`all`||n.has(Et(e))))}var Ut=(0,J.createContext)(null);function Wt({children:e}){let[t,n]=(0,J.useState)(null),[r,i]=(0,J.useState)(new Set),[a,o]=(0,J.useState)(Vt),[s,c]=(0,J.useState)(null),[l,u]=(0,J.useState)(null),d=Re(l?.dataset??null),f=(0,J.useRef)(null),p=(0,J.useCallback)(e=>{e!==f.current&&(f.current=e,n(e),i(new Set),o(Vt),c(null))},[]),m=(0,J.useCallback)(e=>{i(e)},[]),h=(0,J.useCallback)(e=>{o(t=>({...t,...e}))},[]),g=(0,J.useCallback)((e,t,r)=>{f.current=e,n(e),i(new Set),o({...Vt,show:`selected`}),c(null),u({dataset:e,files:t,from:r}),location.hash===`#/library/datasets`?window.dispatchEvent(new HashChangeEvent(`hashchange`)):location.hash=`#/library/datasets`},[]),_=d?.doc?.body??null,v=d?.sync.state===`missing`;(0,J.useEffect)(()=>{if(!l||!_&&!v)return;let e=new Set(l.files),t=(_?.cases??[]).filter(t=>e.has(x().caseItem(t))).map(Et);i(new Set(t)),c({from:l.from,wanted:e.size,found:t.length}),u(null)},[l,_,v]);let y=(0,J.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,Z.jsx)(Ut.Provider,{value:y,children:e})}function Gt(){let e=(0,J.useContext)(Ut);if(!e)throw Error(`useCases outside an CasesProvider: the app mounts one at its root`);return e}var Kt=(0,J.createContext)(null);function qt({children:e}){let[t,n]=(0,J.useState)([]),[r,i]=(0,J.useState)(null),a=(0,J.useRef)(t);a.current=t;let o=(0,J.useRef)(r);o.current=r;let s=(0,J.useRef)(0),c=(0,J.useCallback)((e,t)=>{a.current=e,n(e),o.current=t,i(t)},[]),l=(0,J.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,J.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,J.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,J.useCallback)((e,t)=>{c(a.current.map(n=>n.id===e?{...n,show:t}:n),o.current)},[c]),p=(0,J.useCallback)(()=>{c(a.current,null)},[c]),m=(0,J.useCallback)(()=>{let e=a.current.find(e=>e.id===o.current);window.location.hash=`#/${e?.from??`runs`}`,p()},[p]),h=(0,J.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,Z.jsx)(Kt.Provider,{value:h,children:e})}function Jt(){let e=(0,J.useContext)(Kt);if(!e)throw Error(`useResults outside a ResultsProvider: the app mounts one at its root`);return e}function Yt({n:e,of:t}){return(0,Z.jsxs)(`span`,{className:`fig-part`,children:[e,(0,Z.jsxs)(`span`,{className:`fig-of`,children:[`/`,t]})]})}var Xt=e=>e===`good`?` fig-good`:e===`bad`?` fig-bad`:``;function Zt({fig:e}){return(0,Z.jsx)(`span`,{className:`fig-value${Xt(e.tone)}`,children:e.value??(e.of?(0,Z.jsx)(Yt,{n:e.of[0],of:e.of[1]}):`—`)})}function Qt({fig:e}){return(0,Z.jsxs)(`div`,{className:`fig`,children:[(0,Z.jsx)(`span`,{className:`fig-label`,children:e.label}),(0,Z.jsx)(Zt,{fig:e})]},e.key)}function $t({label:e,lead:t,rest:n,dense:r}){return(0,Z.jsxs)(`div`,{className:`figures${r?` dense`:``}`,role:`group`,"aria-label":e,children:[(0,Z.jsxs)(`div`,{className:`fig fig-lead`,children:[(0,Z.jsx)(`span`,{className:`fig-label`,children:t.label}),(0,Z.jsxs)(`div`,{className:`fig-headline`,children:[(0,Z.jsx)(Zt,{fig:t}),t.under&&(0,Z.jsx)(`span`,{className:`fig-under`,children:(0,Z.jsx)(Yt,{n:t.under[0],of:t.under[1]})})]})]}),!!n.length&&(0,Z.jsx)(`div`,{className:`fig-rest`,children:n.map(e=>(0,Z.jsx)(Qt,{fig:e},e.key))})]})}var en={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`},tn={format:`image/jpeg`,quality:`0.92`,seed:``,nPredict:``,repeatPenalty:``,frequencyPenalty:``,presencePenalty:``,dryMultiplier:``,dryBase:``,dryAllowedLength:``,grammar:``,px:`921600`},nn=[`type`,`profile`,`px`,`format`,`quality`,`seed`,`nPredict`,`repeatPenalty`,`frequencyPenalty`,`presencePenalty`,`dryMultiplier`,`dryBase`,`dryAllowedLength`,`grammar`,`imagePosition`,`cachePrompt`,`thinking`,`rejectLoops`,`url`,`model`,`temperature`];function rn(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 an=(e,t)=>({...tn,...t?.setupProfile?.settings||{}});function on(e){return en[e]??e}function sn(e,t){return e===`type`?cn(String(t)):e===`profile`?t===`speed`?`Speed`:`Quality`:e===`px`?x().budgetLabel(t):e===`format`?String(t).replace(`image/`,``).toUpperCase():String(t)}function cn(e){return x().CONNECTION_TYPES[e]?.label??e}var ln=e=>e.content?e.content!==`text`:null,un=e=>Number(new Date(e)).toString(36).slice(-6).toUpperCase(),dn=(e,t,n=`${t}s`)=>`${e} ${e===1?t:n}`,fn=e=>{let t=e?e.timed??e.ran:0;return t?e.ms/t:null};function pn(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 mn=e=>new Date(e).toLocaleString(void 0,{dateStyle:`medium`,timeStyle:`short`}),hn={queued:`Queued`,running:`Running`,done:`Done`,incomplete:`Incomplete`,cancelled:`Cancelled`,failed:`Failed`,interrupted:`Interrupted`},gn=e=>hn[e]??e;function _n(e){return hn[e]?(0,Z.jsx)(`span`,{className:`rchip ${e}`,children:hn[e]}):null}var vn=e=>e.length?e.reduce((e,t)=>e+t,0)/e.length:null;function yn(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 bn(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 xn=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(fn).filter(e=>e!=null);return{pct:r?Math.round(100*n/r):null,avgScore:i.length?Math.round(vn(i)):null,avgTime:a.length?vn(a):null}},Sn=e=>{let t=xn(e);return{pct:t.pct==null?`—`:`${t.pct}%`,avgScore:t.avgScore==null?`—`:`${t.avgScore}%`,avgTime:t.avgTime==null?`—`:yn(t.avgTime)}},Cn=e=>e.run&&(e.status===`cancelled`||e.status===`interrupted`)?(0,Z.jsx)(`button`,{type:`button`,className:`ghost linkish`,"data-resume":e.run,children:`Resume`}):null,wn=[{key:`runid`,label:`Run ID`,on:!0,sort:e=>e.at,get:e=>(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`code`,{className:`runlink`,"data-openrun":e.run??void 0,children:un(e.at)}),Cn(e)]})},{key:`date`,label:`Date`,on:!0,sort:e=>e.at,get:e=>(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`time`,{dateTime:e.at,title:new Date(e.at).toLocaleString(),children:mn(e.at)}),e.cancelled&&(0,Z.jsx)(`span`,{className:`err`,children:` cancelled`})]})},{key:`state`,label:`State`,on:!0,sort:e=>gn(e.status),get:e=>_n(e.status)},{key:`content`,label:`Content`,on:!0,get:e=>e.content||`—`},{key:`pct`,label:`% Passed Items`,on:!0,numeric:!0,sort:e=>xn(e).pct,get:e=>Sn(e).pct},{key:`avgscore`,label:`Avg Score`,on:!0,numeric:!0,sort:e=>xn(e).avgScore,get:e=>Sn(e).avgScore},{key:`avgtime`,label:`Avg Time`,on:!0,numeric:!0,sort:e=>xn(e).avgTime,get:e=>Sn(e).avgTime},{key:`duration`,label:`Duration`,on:!1,numeric:!0,sort:e=>bn(e.startedAt,e.finishedAt),get:e=>{let t=bn(e.startedAt,e.finishedAt);return t==null?`—`:yn(t)}},{key:`ran`,label:`Ran`,on:!1,numeric:!0,sort:e=>e.done,get:e=>(0,Z.jsx)(Yt,{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,Z.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,Z.jsx)(`span`,{className:`hcomment`,title:e.comment,children:e.comment}):(0,Z.jsx)(`span`,{className:`hcomment empty`,children:`——`})})}],Tn=[{key:`name`,label:`Name`,on:!0,sort:(e,t)=>e?.name||`Target ${t+1}`,get:(e,t,n)=>(0,Z.jsx)(`button`,{type:`button`,className:`ghost linkish`,"data-scenario":n,children:t?.name||`Target ${n+1}`})},{key:`outcome`,label:`Outcome`,on:!0,sort:e=>e.pass,get:(e,t)=>t.pass==null?(0,Z.jsx)(`span`,{className:`note`,children:`—`}):(0,Z.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.evals||`—`},{key:`profile`,label:`Target Profile`,on:!0,sort:e=>e?.setupProfile?.name,get:(e,t,n)=>t?.setupProfile?.name?(0,Z.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,Z.jsx)(Yt,{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=>fn(e),get:(e,t)=>{let n=fn(t);return n==null?`—`:yn(n)}},{key:`total`,label:`Total`,on:!1,numeric:!0,sort:e=>e.ms||null,get:(e,t)=>t.ms?yn(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(x().budgetLabel(an(e,t).px))},{key:`format`,label:`Format`,on:!1,image:!0,get:(e,t)=>String(an(e,t).format).replace(`image/`,``).toUpperCase()},{key:`quality`,label:`Quality`,on:!1,image:!0,get:(e,t)=>an(e,t).format===`image/png`?`—`:String(an(e,t).quality)},{key:`seed`,label:`Seed`,on:!1,get:(e,t)=>String(an(e,t).seed||`1234`)},{key:`predict`,label:`Reply tokens`,on:!1,get:(e,t)=>String(an(e,t).nPredict||an(e,t).maxTokens||`—`)},{key:`penalty`,label:`Repeat penalty`,on:!1,get:(e,t)=>String(an(e,t).repeatPenalty||`—`)},{key:`decoding`,label:`Decoding`,on:!1,get:(e,t)=>rn(an(e,t))||`—`},...Object.entries(x().MODIFIERS).map(([e,t])=>({key:`modifier-${e}`,label:t.label||e,on:!1,get:(t,n)=>n.modifiers?.[e]||`—`}))],En={"Run Scenarios":`Run Targets`},Dn={tests:`evals`},On=[[`Runs`,wn],[`Run Scenarios`,Tn]],kn=e=>![`queued`,`running`].includes(e),An=()=>({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 Mn=(e,t)=>e.filter(e=>!e.whole).map(e=>e.items[t]).filter(e=>!!e&&!x().isSkipped(e)),Nn=e=>Array.isArray(e)?e.length:typeof e==`number`?e:0;function Pn(e,t){let n=t.map(An);return(e||[]).forEach((e,r)=>{e&&!e.unrun&&(e.scenarios||[]).forEach((e,i)=>{let a=n[i];if(!a||!e)return;let o=Mn(t[i],r);if(o.length){a.ran++,o.every(e=>e.pass)&&a.passed++;for(let e of o)a.found+=Nn(e.found),a.of+=Nn(e.found)+Nn(e.missed)+Nn(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 Fn=(e,t,n)=>x().targetsOf(e).map((r,i)=>x().scenarioEvals(e,i,t,kn(n))),In=(e,t,n)=>(e.outcomes[n]??[]).some(e=>!e.whole&&x().failedScore(e.items[t]));function Ln(e){return e.skipped?`Skipped`:e.whole?e.verdict?.ran?e.verdict.pass?`✓`:`✗`:`—`:e.ran?`${e.passed}/${e.ran}`:e.skippedItems?`Skipped`:`—`}var Rn=e=>e.map(e=>`${e.label} ${Ln(e)}`).join(` · `),zn={state:`pending`,value:`—`},Bn={state:`skipped`,value:`Skipped`,note:`an earlier eval failed`};function Vn(e){let t=[];return e.evals.forEach((n,r)=>{let i=e.scenarios.map((t,n)=>e.outcomes[n]?.[r]),a=i.find(Boolean);if(!a)return;let o=x().EVAL_TYPES[n.type]?.label??n.type,s=`dataset`in n&&n.dataset?.name?`${o} · ${n.dataset.name}`:o,c=[],l=(e,t,r,o)=>c.push({key:`${n.id}-${e}`,eval:a.label,type:s,first:!c.length,rule:t,want:r,cells:i.map(e=>e?e.skipped?Bn:o(e):zn)}),u=x().EVAL_TYPES[n.type]?.ruleOf;if(a.rules.length)for(let e of a.rules)l(e.key,e.label,e.want||null,t=>{if(!t.whole&&u){let r=t.items.flatMap(t=>t&&!x().isSkipped(t)?[u(t,e.key,n)]:[]).filter(e=>e!=null);if(!r.length)return zn;let i=r.filter(Boolean).length;return{state:i===r.length?`met`:`not`,value:`${i} of ${r.length}`}}let r=t.verdict?.ran?t.verdict.checks?.find(t=>t.key===e.key):void 0;return r?r.pass?{state:`met`,value:`Met`}:{state:`not`,value:`Not Met`,note:r.note}:zn});a.rules.length&&a.whole||(a.whole?l(`verdict`,`Verdict`,null,e=>e.verdict?.ran?e.verdict.pass?{state:`met`,value:`Pass`}:{state:`not`,value:`Fail`,note:e.verdict.detail}:zn):l(`items`,`Items passed`,null,e=>{if(!e.ran)return e.skippedItems?Bn:zn;let t=e.skippedItems?`${e.skippedItems} skipped`:void 0;return{state:e.passed===e.ran?`met`:`not`,value:`${e.passed} of ${e.ran}`,note:t}})),t.push(...c)}),t}function Hn(e){let t=e.snapshot||{},n=x().contentOf(t),r=!!(n&&x().CONTENT_TYPES[n.type]?.inline),i=x().lastKind(t),a=e.results||[],o=Fn(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:x().targetsOf(t).map((e,n)=>({id:e?.id||`scenario-${n}`,name:x().targetLabel(t,n),kind:i,plain:!(i&&x().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:x().evalsOf(t),snapshot:t,results:a,outcomes:o,tallies:Pn(a,o),startedAt:e.startedAt,finishedAt:e.finishedAt}}function Un(e){let t=e.snapshot||{},n=x().contentOf(t),r=e.results||[],i=x().targetsOf(t),a=t.jobs||[],o=Fn(t,r,e.status),s=Pn(r,o),c=i.map((e,n)=>{let r=s[n]??An(),i=(a.length?x().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=x().scenarioPasses(o[n]??[]);return{name:x().targetLabel(t,n),id:e?.id,model:c,setupProfile:x().scenarioProfile(t,n),modifiers:Object.fromEntries((x().outOf(t.jobs?.at(-1))?.modifiers||[]).map(e=>[e.type,x().modifierSummary(e)])),percent:l,passed:r.passed,cases:r.ran,pass:u,detail:u==null?`not graded`:Rn(o[n]??[]),evals:Rn(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&&x().CONTENT_TYPES[n.type]?.inline?`text`:n?.type===`source`&&(n.ref?.name||n.ref?.id)||``,scenarios:c}}var Wn=e=>({key:`state`,label:`State`,value:gn(e),tone:e===`done`?`good`:[`failed`,`incomplete`,`cancelled`,`interrupted`].includes(e)?`bad`:null}),Gn=e=>e.length?e.reduce((e,t)=>e+t,0)/e.length:null;function Kn(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&&!x().isSkipped(r))for(let e of r.metrics||[])typeof e.asked==`number`&&(t++,n+=e.asked);return{calls:t,ms:n}}function qn(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(Gn(i))}%`:`—`,o=bn(e.startedAt,e.finishedAt),s=Kn(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,J.createElement)(`code`,null,un(e.at)):`—`},Wn(e.status),{key:`score`,label:`Avg Score`,value:a},{key:`duration`,label:`Duration`,value:o==null?`—`:yn(o)},...s.calls?[{key:`grader`,label:`Grader`,value:`${s.calls} ${s.calls===1?`call`:`calls`} · ${yn(s.ms)}`}]:[],...r?[c]:[],{key:`start`,label:`Start Date`,value:e.at?Zn(e.at):`—`},{key:`comment`,label:`Comment`,value:e.snapshot.comment?(0,J.createElement)(`span`,{className:`fig-comment`,title:e.snapshot.comment},e.snapshot.comment):`—`}]}}var Jn=e=>e.evals.length&&kn(e.status)?`No assertions`:`—`;function Yn(e,t){let n=e.tallies[t],r=$n(e,t),i={key:`state`,label:`State`,value:r==null?Jn(e):r?`Pass`:`Fail`,tone:r==null?null:r?`good`:`bad`},a={key:`time`,label:`Avg Time`,value:Xn(n)??`—`},o=e.outcomes[t]??[],s=o.length>1?o.map(e=>({key:`eval-${e.id}`,label:e.label,value:Ln(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 Xn(e){return e?.timed?yn(e.ms/e.timed):null}function Zn(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 Qn(e){let t=gn(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 $n(e,t){return x().scenarioPasses(e.outcomes[t]??[])}function er(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 tr(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 Q=(e,t)=>t==null||t===``?null:`${e}: ${t}`,nr=e=>(e||[]).map(String).join(`, `),rr=e=>e.length?e.every(t=>t===e[0])?String(e[0]):e.join(` → `):``,ir=e=>{let t=x().OUTPUT_KINDS[x().lastKind(e)??x().defaultKind()];return t?!t.terms:!1},ar=e=>{let t=e.metric&&String(e.metric)||x().METRICS[e.type]?.label||e.type,n=x().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 or(e,t,n,r){let i=x().readCase(t,n,ir(e)),{stages:a,connections:o}=x().stagesFor(e,r),s=o.map(e=>x().connectionSettings(e)),c=e=>rr(s.map(e)),l=x().evalsDataset(e);return[`An eval case is failing.`,``,`## The case`,Q(`item`,x().caseItem(t)),Q(`case id`,t.id),Q(`note`,t.note),...(t.metrics||[]).map((e,t)=>Q(`metric ${t+1}`,ar(e))),``,`## What came back`,Q(`verdict`,i.pass?`pass`:`fail`),Q(`score`,i.score==null?`—`:`${Math.round(i.score*100)}%`),Q(`items`,nr(n?.terms)||`(none)`),Q(`missed`,nr((i.missed??[]).map(e=>Array.isArray(e)?e.join(` / `):e))),Q(`invented`,nr(i.invented)),Q(`dropped`,nr((n?.dropped||[]).map(e=>`${e.item} (${e.by})`))),Q(`reasons`,nr(i.reasons)),Q(`error`,n?.error),Q(`took`,n?.ms==null?null:`${n.ms} ms`),``,`## How it was asked`,Q(`scenario`,`${r+1} of ${x().targetsOf(e).length}`),Q(`model`,c(e=>e.model)),Q(`endpoint`,c(e=>e.url||`(the lab's own Ollama)`)),Q(`connection type`,c(e=>cn(String(e.type??``)))),Q(`image`,a[0]?.withImage?sr(s[0]):`no image`),Q(`seed`,c(e=>e.seed||`1234`)),Q(`reply tokens`,c(e=>e.nPredict||e.maxTokens||`not set`)),Q(`repeat penalty`,c(e=>e.repeatPenalty||`(profile default)`)),Q(`other decoding`,cr(s.at(-1))),Q(`modifiers`,(x().outOf(e.jobs.at(-1))?.modifiers||[]).map(e=>`${x().MODIFIERS[e.type]?.label??e.type}: ${x().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 sr(e){let{px:t,format:n}=x().connectionImage(e);return`${t==null?`default budget`:x().budgetLabel(t)} · ${n.replace(`image/`,``).toUpperCase()}`}function cr(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 lr(e,t){let n=[];return!kn(e.status)||!x().evalsDataset(e.snapshot)||(e.results||[]).forEach((r,i)=>{r&&!r.unrun&&(r.scenarios||[]).forEach((a,o)=>{let s=t.find(e=>x().caseItem(e)===r.name);In(e,i,o)&&s&&a.res&&n.push({kase:s,res:a.res,scenarioIndex:o,item:r.name??``})})}),n}var ur=e=>{let t=Math.min(...e),n=Math.max(...e);return t===n?String(t):`${t}–${n}`};function dr(e,t,n){let r=x().evalsDataset(e.snapshot);if(!kn(e.status)||!r)return[];let i=e.outcomes[n]?.find(t=>e.evals.find(e=>e.id===t.id&&`dataset`in e)),a=new Map(t.map(e=>[x().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||x().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?`${ur(r)}, ${e===`over`?`max`:`min`} ${ur(i)}`:null}))}var fr=[{id:`home`,label:`Home`,icon:ut,built:!0},{id:`runs`,label:`Runs`,icon:rt,built:!0},{id:`history`,label:`History`,icon:I,built:!0},{id:`library`,label:`Library`,icon:dt,built:!0},{id:`setup`,label:`Setup`,icon:xt,built:!0}],pr=e=>e.replace(/[^A-Za-z0-9._-]+/g,`-`).replace(/^[-.]+|[-.]+$/g,``);function mr(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 hr(e,t,n,r,i=new Date){return`${e}-${pr(t)||e}-v${n}-${mr(i)}.${r}`}function gr(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)}function _r({name:e,body:t,onSave:n,onClose:r}){let[i,a]=(0,J.useState)(()=>JSON.stringify(t,null,2)),[o,s]=(0,J.useState)(()=>yr(i));(0,J.useEffect)(()=>{let e=setTimeout(()=>s(yr(i)),400);return()=>clearTimeout(e)},[i]);let c=o.problems;return(0,Z.jsxs)(D,{title:`Edit raw… ${e}`,onClose:r,wide:!0,children:[(0,Z.jsx)(`textarea`,{className:`raw-content`,"aria-label":`Dataset JSON`,spellCheck:!1,value:i,onChange:e=>a(e.target.value)}),(0,Z.jsxs)(`div`,{className:`raw-foot`,children:[(0,Z.jsx)(`span`,{className:`note ${c.length?` bad`:``}`,role:c.length?`alert`:void 0,children:c.length?`${c.length} to fix — ${c.join(` · `)}`:`Validated before it is accepted.`}),(0,Z.jsx)(`button`,{type:`button`,className:`run`,onClick:()=>{let e=yr(i);e.body?n(e.body):s(e)},disabled:c.length>0,children:`Save`}),(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,onClick:r,children:`Close`})]})]})}var vr=[`version`,`source`,`cases`];function yr(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))vr.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=x().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=n.source??null;return r.push(...x().validateEvals({version:i,source:a,cases:n.cases})),r.length?{body:null,problems:r}:{body:{version:i,source:a,cases:n.cases},problems:[]}}function br(e){return[e.every&&`Every reply`,e.not&&`Not`,e.of===`said`&&`API text`,e.weight!=null&&`Weight ${e.weight}`,e.metric&&`Group ${e.metric}`].filter(Boolean).join(`, `)}var xr=(e,t)=>({type:e,...x().METRICS[e].defaults(),...t?.weight==null?{}:{weight:t.weight},...t?.not?{not:!0}:{},...t?.metric?{metric:t.metric}:{}});function Sr({label:e,metrics:t,set:n,undoable:r,over:i=`item`}){let a=x(),[o,s]=(0,J.useState)(null),c=(e,r)=>n(t.map((t,n)=>n===e?r:t)),l=e=>{o===`new`?n([...t,xr(e)]):typeof o==`number`&&c(o,xr(e,t[o])),s(null)};return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(R,{noun:`metric`,items:[...t],empty:(0,Z.jsx)(`p`,{className:`note`,children:`No metrics.`}),onAdd:()=>s(`new`),onRemove:e=>r(t.filter((t,n)=>n!==e),`Removed a metric`),extra:(e,t)=>[{label:`Change type…`,icon:St,onSelect:()=>s(t)}],renderItem:(t,n,r)=>{let o=a.METRICS[t.type],s=(t.metric||o?.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||t.metric),d=(o?.options??[]).map(e=>F(e,t,e=>c(n,e)));return(0,Z.jsxs)(U,{id:l,title:s,level:3,actions:r,about:o?.description,children:[d.length>0&&(0,Z.jsx)(N,{label:`${e}, metric ${n+1}`,rows:d}),(0,Z.jsx)(U,{id:`${l}-counts`,title:`How it counts`,level:3,open:u,note:u?br(t):`Defaults`,children:(0,Z.jsx)(N,{label:`${e}, metric ${n+1}, how it counts`,rows:[...i===`run`?[{key:`every`,label:`Every reply`,control:{type:`checkbox`,checked:!!t.every,onChange:e=>{let{every:r,...i}=t;c(n,e?{...i,every:!0}:i)}}}]:[],{key:`not`,label:`Not`,control:{type:`checkbox`,checked:!!t.not,onChange:e=>{let{not:r,...i}=t;c(n,e?{...i,not:!0}:i)}}},{key:`of`,label:`Grades`,control:{type:`select`,value:t.of??`reply`,options:[{value:`reply`,label:`Reply`},{value:`said`,label:`API text`}],onChange:e=>{let{of:r,...i}=t;c(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;c(n,e.trim()?{...i,weight:/^-?\d+(\.\d+)?$/.test(e.trim())?Number(e):e}:i)}}},{key:`metric`,label:`Group`,control:{type:`text`,value:t.metric??``,onChange:e=>{let{metric:r,...i}=t;c(n,e.trim()?{...i,metric:e}:i)}}}]})})]},n)}}),o!==null&&(0,Z.jsx)(Cr,{title:o===`new`?`Add metric`:`Change type`,current:typeof o==`number`?t[o]?.type??null:null,over:i,onPick:l,onClose:()=>s(null)})]})}function Cr({title:e,current:t,over:n,onPick:r,onClose:i}){let[a,o]=(0,J.useState)(``),s=(0,J.useMemo)(()=>{let e=new Map;for(let[t,r]of Object.entries(x().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,Z.jsxs)(D,{title:e,onClose:i,className:`metric-picker`,children:[(0,Z.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,Z.jsx)(`p`,{className:`note`,children:`No metric matches.`}),s.map(([e,n])=>(0,Z.jsxs)(`fieldset`,{className:`mp-family`,children:[(0,Z.jsx)(`legend`,{children:e}),(0,Z.jsx)(`div`,{className:`mp-grid`,children:n.map(e=>(0,Z.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 wr(e,t){return`/api/sources/${encodeURIComponent(e)}/thumbs/${encodeURIComponent(t)}`}function Tr(e){return/\.(?:jpe?g|png|gif|webp|bmp|heic|heif|dng|tiff?)$/i.test(e)}function Er({title:e,action:t,source:n,files:r,taken:i,onPick:a,onClose:o}){let s=(0,J.useMemo)(()=>r.filter(e=>!i.has(e)),[r,i]),[c,l]=(0,J.useState)(``),[u,d]=(0,J.useState)(s[0]??null),f=s.filter(e=>!c.trim()||e.toLowerCase().includes(c.trim().toLowerCase()));return(0,Z.jsxs)(D,{title:e,onClose:o,className:`item-picker`,footer:(0,Z.jsxs)(`div`,{className:`edit-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,onClick:o,children:`Cancel`}),(0,Z.jsx)(`button`,{type:`button`,className:`edit-done`,disabled:!u||!s.includes(u),onClick:()=>{u&&a(u)},children:t})]}),children:[(0,Z.jsxs)(`div`,{className:`prop ip-source`,children:[(0,Z.jsx)(`span`,{className:`prop-name`,children:`Source`}),(0,Z.jsx)(`span`,{className:`prop-value`,children:n.name})]}),(0,Z.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,Z.jsxs)(`fieldset`,{className:`ip-items`,children:[(0,Z.jsxs)(`legend`,{className:`note`,children:[`Items without a case · `,s.length]}),s.length?f.length?f.map(e=>(0,Z.jsxs)(`label`,{className:`ip-item${e===u?` on`:``}`,children:[(0,Z.jsx)(`input`,{type:`radio`,name:`item`,checked:e===u,onChange:()=>d(e)}),Tr(e)?(0,Z.jsx)(`img`,{src:wr(n.id,e),alt:``,loading:`lazy`}):(0,Z.jsx)(`span`,{className:`ip-thumb`,"aria-hidden":`true`}),(0,Z.jsx)(`span`,{className:`ip-name`,children:e})]},e)):(0,Z.jsx)(`p`,{className:`note`,children:`No item matches.`}):(0,Z.jsxs)(`p`,{className:`note`,children:[`Every item of `,n.name,` has a case.`]})]})]})}var Dr=600,Or=2e3,kr=e=>({id:``,item:e,todo:!0,note:``,metrics:[]}),Ar=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 jr({item:e,cases:t,onWrite:n,problem:r,resultFor:i,scenarioCount:a,plain:o=!1,files:s,onFile:c,onClose:u,run:d,source:p=null,sourceFiles:m=null,onRemove:h}){let g=t.find(t=>x().caseItem(t)===e),[_,v]=(0,J.useState)(()=>structuredClone(g??kr(e))),[y,S]=(0,J.useState)(0),[C,w]=(0,J.useState)(null),[T,E]=(0,J.useState)(null),[D,O]=(0,J.useState)(!1),[k,A]=(0,J.useState)(!1),[M,N]=(0,J.useState)(!1),P=(0,J.useRef)(_);P.current=_;let ee=(0,J.useRef)(t);ee.current=t;let F=(0,J.useRef)(null),I=(0,J.useRef)(null),L=t=>ee.current.filter(n=>!(t.id&&n.id===t.id)&&!(!t.id&&x().caseItem(n)===e)).some(e=>x().caseItem(e)===x().caseItem(t))?`${x().caseItem(t)} has a case already`:x().validateEvals({cases:[{...t,id:t.id||`new`}]})[0]?.replace(/^[^:]*: /,``)??null,te=L(_),R=(0,J.useCallback)(()=>{let e=P.current;if(L(e))return!1;e.id||(e={...e,id:Ar(ee.current)},P.current=e,v(e));let t=e;return n(e=>Nr({cases:e},t)),!0},[n,e]),ne=(0,J.useCallback)(()=>{F.current&&clearTimeout(F.current),F.current=setTimeout(()=>{F.current=null,R()&&(A(!0),I.current&&clearTimeout(I.current),I.current=setTimeout(()=>A(!1),Or))},Dr)},[R]);(0,J.useEffect)(()=>()=>{F.current&&clearTimeout(F.current),I.current&&clearTimeout(I.current)},[]);let z=e=>{v(e),ne()},B=e=>{let t=P.current;z({...t,metrics:e,...t.todo&&!(t.metrics??[]).length&&e.length?{todo:!1}:{}})},V=T&&T[y]?T[y]:i(y),re=!V||_.todo||!(_.metrics??[]).length?null:x().readCase(_,V,o),H=async()=>{if(d&&!D){O(!0),w(null);try{let e=await d(x().caseItem(P.current));E(e),w(e.length?null:`No reply to grade.`)}catch(e){w(e instanceof Error?e.message:String(e))}finally{O(!1)}}},ie=s.indexOf(e),U=e=>{let t=ie<0?null:s[ie+e];t&&c(t)};(0,J.useEffect)(()=>{let e=e=>{(e.key===`ArrowLeft`||e.key===`ArrowRight`)&&(e.target?.closest?.(`input, textarea, select, [contenteditable]`)||(e.preventDefault(),U(e.key===`ArrowRight`?1:-1)))};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)});let ae=()=>{F.current&&(clearTimeout(F.current),F.current=null,R()),u()},W=x().caseItem(_),G=new Set(t.filter(t=>!(_.id&&t.id===_.id)&&x().caseItem(t)!==e).map(e=>x().caseItem(e))),K=!!m&&!m.includes(W),q=[{key:`item`,label:`Item`,control:p?{type:`static`,text:K?`${W||`None`} (missing)`:W}:{type:`text`,value:W,onChange:e=>z({...P.current,item:e.trim()})}},{key:`todo`,label:`To do`,control:{type:`checkbox`,checked:!!_.todo,label:`Not graded yet`,onChange:e=>z({...P.current,todo:e})}},{key:`note`,label:`Note`,control:{type:`textarea`,value:_.note??``,onChange:e=>z({...P.current,note:e})}}],oe=[];a>1&&oe.push({key:`scenario`,label:`Show result of`,control:{type:`select`,value:String(y),options:Array.from({length:a},(e,t)=>({value:String(t),label:`Target ${t+1}`})),onChange:e=>S(Number(e))}}),re&&(oe.push({key:`verdict`,label:`Result`,control:{type:`static`,text:re.pass?`Pass`:`Fail`}}),re.watch.length&&oe.push({key:`watch`,label:`Watch`,control:{type:`static`,text:`${re.watch.filter(e=>e.pass).length} of ${re.watch.length}`}}));let Y=p&&W&&Tr(W)&&m?.includes(W)?{src:wr(p.id,W),file:W,source:p.name}:null,se=[...Y?[{key:`preview`,title:`Preview`,children:(0,Z.jsxs)(`div`,{className:`cf-preview`,children:[(0,Z.jsx)(`img`,{src:Y.src,alt:Y.file,loading:`lazy`}),(0,Z.jsxs)(`p`,{className:`note`,children:[Y.file,` in `,Y.source]})]})}]:[],{key:`case`,title:`Case`,rows:q},{key:`metrics`,title:`Metrics`,children:(0,Z.jsx)(Sr,{label:`${W||`Case`} metrics`,metrics:_.metrics??[],set:B,undoable:B})},...oe.length?[{key:`result`,title:`Result`,rows:oe}]:[]],ce=[{label:`Previous`,icon:f,disabled:ie<=0,onSelect:()=>U(-1)},{label:`Next`,icon:l,disabled:ie<0||ie>=s.length-1,onSelect:()=>U(1)},...d?[{label:`Run`,icon:vt,disabled:D,onSelect:()=>void H()}]:[]],le=[...p?[{label:`Change item…`,icon:yt,disabled:!m,onSelect:()=>N(!0)}]:[],...h?[{label:`Remove`,icon:b,destructive:!0,onSelect:()=>{h(x().caseItem(P.current)),u()}}]:[]],ue=C??r??(te?`Not saved: ${te}`:null);return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(j,{title:W||`Case`,status:ue??(D?`Running…`:k?`Saved.`:Mr),...ue?{statusBad:!0}:{},sections:se,...le.length?{menu:le}:{},actions:ce,onClose:ae}),M&&p&&m&&(0,Z.jsx)(Er,{title:`Change item`,action:`Change`,source:p,files:m,taken:new Set([...G,W]),onPick:e=>{N(!1),z({...P.current,item:e})},onClose:()=>N(!1)})]})}var Mr=`Saved to the dataset as you edit.`;function Nr(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 Pr(e,t){return structuredClone(e.cases).filter(e=>x().caseItem(e)!==t)}function Fr(e){let t=Y(),[n,r]=(0,J.useState)(null);return(0,J.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 Ir=(0,J.createContext)(null);function Lr({children:e}){let t=Ie(),[n,r]=(0,J.useState)(null),i=Re(n?.dataset??null),a=(0,J.useCallback)((e,t)=>{r({item:e,...t})},[]),o=(0,J.useCallback)(e=>{r(t=>t&&{...t,item:e})},[]),s=i?.doc?.body.source??null,c=Fr(s?.id),l=n?.dataset??``,u=(0,J.useCallback)(e=>{t.edit(l,t=>({...t,cases:e(t.cases)}))},[t,l]),d=(0,J.useMemo)(()=>({openCaseEditor:a}),[a]),f=i?.doc;return(0,Z.jsxs)(Ir.Provider,{value:d,children:[e,n&&f&&(0,Z.jsx)(jr,{item:n.item,cases:f.body.cases,onWrite:u,problem:Se(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 Rr(){let e=(0,J.useContext)(Ir);if(!e)throw Error(`useCaseEditor outside a CaseEditorProvider: the app mounts one at its root`);return e}function zr({rows:e,shown:t,filters:n,onFilters:r,selected:i,onSelect:a,selectionActions:o,sourceFiles:s,hasSource:c,pageSize:l,onEdit:u,onAdd:d,onRemove:f,loading:p,loadError:m,onRetry:g,children:_}){let v=t.map(Et),y=new Set(v),b=[...i].filter(e=>!y.has(e)).length,x=v.filter(e=>i.has(e)).length,S=x>0&&x===v.length,C=e=>a(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),w=[{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`},...s?[{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 p?(0,Z.jsxs)(`div`,{className:`ds-casebody`,children:[_,(0,Z.jsx)(k,{label:`Cases`,error:m,onRetry:g})]}):(0,Z.jsxs)(`div`,{className:`ds-casebody`,children:[e.length>0&&(0,Z.jsx)(z,{noun:`cases`,search:{label:`Item`,placeholder:`Search items`,value:n.file,onChange:e=>r({file:e})},filters:w,count:{shown:t.length,total:e.length},lead:(0,Z.jsx)(`label`,{className:`ev-check ev-all`,children:(0,Z.jsx)(Br,{all:S,some:x>0,disabled:!t.length,onChange:()=>a(e=>{let t=new Set(e);for(let e of v)S?t.delete(e):t.add(e);return t})})})}),_,e.length===0?(0,Z.jsx)(`p`,{className:`ds-none`,children:c?`No cases.`:`No Source yet.`}):(0,Z.jsxs)(Z.Fragment,{children:[i.size>0&&(0,Z.jsxs)(`div`,{className:`ev-select on`,"data-selected":i.size,children:[(0,Z.jsxs)(`span`,{className:`ev-count`,children:[i.size,` selected`]}),b>0&&(0,Z.jsxs)(`span`,{className:`ev-hidden`,children:[b,` hidden`]}),(0,Z.jsxs)(`span`,{className:`ev-select-acts`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>a(()=>new Set),children:`None`}),(0,Z.jsx)(G,{label:`Selection actions`,actions:o})]})]}),t.length===0?(0,Z.jsx)(`p`,{className:`note`,children:`No cases match these filters.`}):(0,Z.jsx)(`div`,{className:`ds-cases`,children:(0,Z.jsx)(A,{className:`dstable`,label:`Cases`,rows:t,pageSize:l,rowKey:e=>Et(e),rowProps:e=>({"data-selected":i.has(Et(e))||void 0}),columns:Vr(s,i,C,u,f)})})]}),(0,Z.jsxs)(`button`,{type:`button`,className:`ghost ds-add`,onClick:d,disabled:!c||!s,children:[(0,Z.jsx)(h,{size:14,"aria-hidden":`true`}),`Add case`]})]})}function Br({all:e,some:t,disabled:n,onChange:r}){let i=(0,J.useRef)(null);return(0,J.useEffect)(()=>{i.current&&(i.current.indeterminate=t&&!e)},[t,e]),(0,Z.jsx)(`input`,{ref:i,type:`checkbox`,"aria-label":`Select all shown`,checked:e,disabled:n,onChange:r})}function Vr(e,t,n,r,i){let a=t=>Bt(t,e);return[{key:`pick`,header:(0,Z.jsx)(`span`,{className:`ev-vh`,children:`Selected`}),label:``,className:`ev-pick`,sort:null,cell:e=>(0,Z.jsx)(`label`,{className:`ev-check`,children:(0,Z.jsx)(`input`,{type:`checkbox`,checked:t.has(Et(e)),onChange:()=>n(Et(e)),"aria-label":`Select ${e.item}`})})},{key:`item`,header:`Item`,sort:e=>e.item,cell:e=>(0,Z.jsx)(`button`,{type:`button`,className:`ds-file`,onClick:()=>r(e.item),children:e.item})},{key:`status`,header:`Status`,sort:e=>zt[a(e)],tdProps:e=>({"data-state":a(e)}),cell:e=>(0,Z.jsx)(`span`,{className:`ds-status ds-${a(e)}`,children:zt[a(e)]})},{key:`metrics`,header:`Metrics`,sort:e=>Hr(e).length,cell:e=>Hr(e).length},{key:`note`,header:`Note`,sort:e=>e.note??``,tdProps:e=>({"data-state":e.note?.trim()?void 0:`none`}),cell:e=>(0,Z.jsx)(`span`,{className:`ds-note`,children:e.note})},{key:`menu`,header:``,label:``,className:`ds-menu`,sort:null,cell:e=>(0,Z.jsx)(G,{label:`${e.item} actions`,actions:[{label:`Edit`,icon:y.edit,onSelect:()=>r(e.item)},{label:`Remove`,icon:y.remove,destructive:!0,onSelect:()=>i(e.item)}]})}]}var Hr=e=>(e.metrics??[]).filter(e=>e.weight!==0),Ur={bounds:`Set count`,addTerm:`Add term`,removeTerm:`Remove term`,todo:`Mark To do`,graded:`Mark graded`},Wr=[{value:`keep`,label:`Keep`},{value:`set`,label:`Set`},{value:`clear`,label:`Clear`}],Gr=e=>/^\s*\d+\s*$/.test(e)?Number(e):null;function Kr({kind:e,cases:t,keys:n,onApply:r,onClose:i}){let[a,o]=(0,J.useState)(`keep`),[s,c]=(0,J.useState)(`keep`),[l,u]=(0,J.useState)(``),[d,f]=(0,J.useState)(``),[p,m]=(0,J.useState)(`expect`),[h,g]=(0,J.useState)(``),[_,v]=(0,J.useState)(null),y=(0,J.useMemo)(()=>{switch(e){case`bounds`:{let e=a===`set`?Gr(l):null,t=s===`set`?Gr(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]),b=(0,J.useMemo)(()=>{if(typeof y==`string`)return null;let{next:e,changed:r}=Nt(t,n,y);return{changed:r,problems:Pt(t,e,r)}},[y,t,n]),x=_??b?.problems??null,S=!!x&&x.cases.length>0,C=b?.changed.length??0,w=(0,J.useCallback)(()=>{if(typeof y==`string`)return;let e=r(y);e&&v(e)},[y,r]),T=e=>t=>{v(null),e(t)},E=[];return e===`bounds`&&(E.push({key:`min`,label:`Min items`,required:!0,control:{type:`select`,value:a,options:Wr,onChange:T(e=>o(e))}}),a===`set`&&E.push({key:`minN`,label:`Min`,required:!0,control:{type:`text`,value:l,size:`num`,onChange:T(u)}}),E.push({key:`max`,label:`Max items`,required:!0,control:{type:`select`,value:s,options:Wr,onChange:T(e=>c(e))}}),s===`set`&&E.push({key:`maxN`,label:`Max`,required:!0,control:{type:`text`,value:d,size:`num`,onChange:T(f)}})),e===`addTerm`&&E.push({key:`list`,label:`List`,required:!0,control:{type:`select`,value:p,onChange:T(e=>m(e)),options:[`expect`,`forbid`].map(e=>({value:e,label:It(e)}))}}),(e===`addTerm`||e===`removeTerm`)&&E.push({key:`term`,label:`Term`,required:!0,control:{type:`text`,value:h,onChange:T(g)}}),(0,Z.jsxs)(D,{title:Ur[e],onClose:i,className:`ev-bulk`,footer:(0,Z.jsx)(`div`,{className:`edit-actions`,children:(0,Z.jsx)(`button`,{type:`button`,className:`edit-done`,disabled:!C||S,onClick:w,children:`Apply`})}),children:[E.length>0&&(0,Z.jsx)(N,{label:Ur[e],rows:E}),(0,Z.jsx)(`p`,{className:`note ev-changes`,role:`status`,children:typeof y==`string`?y:`Changes ${C} of ${n.size}`}),S&&x&&(0,Z.jsx)(`div`,{className:`ev-refusal`,role:`alert`,children:x.cases.length>0&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`p`,{className:`ev-refusal-head`,children:[x.cases.length,` of `,n.size,` would break`]}),(0,Z.jsx)(`ul`,{children:x.cases.map(e=>(0,Z.jsxs)(`li`,{children:[(0,Z.jsx)(`b`,{children:e.file}),` `,e.reasons.join(`; `)]},e.key))})]})})]})}function qr({pageSize:e=20}){let t=ve(),n=Ie(),r=ne(),{openCaseEditor:i}=Rr(),{list:o}=Le(),{datasetId:s,selected:c,setSelected:l,filters:u,setFilters:d,handedOver:f}=Gt(),[p,m]=(0,J.useState)(null),[h,g]=(0,J.useState)(!1),_=(0,J.useCallback)(()=>m(null),[]),v=o?.find(e=>e.id===s)??o?.[0]??null,b=v?.id??``,S=Re(b||null),C=S?.doc?.body??null,w=C?.cases,T=(0,J.useMemo)(()=>w?x().gradedSetFrom({cases:w}):[],[w]),E=Fr(C?.source?.id),D=(0,J.useMemo)(()=>new Set(T.map(Et)),[T]),k=(0,J.useMemo)(()=>new Set([...c].filter(e=>D.has(e))),[c,D]),A=(0,J.useMemo)(()=>Ht(T,u,k,E),[T,u,k,E]),j=!!C&&!C.source;(0,J.useEffect)(()=>{j&&u.status===`missing`&&d({status:`all`})},[j,u.status,d]);let M=(0,J.useCallback)(()=>n.entry(b)?.doc?.body??null,[n,b]),N=(0,J.useCallback)(e=>{b&&n.edit(b,t=>({...t,cases:e}))},[n,b]),P=e=>{i(e,{dataset:b,files:A.map(e=>e.item),onRemove:F})},ee=e=>{g(!1);let t=M()?.cases??[];N([...t,{id:Ar(t),item:e,todo:!0,note:``,metrics:[]}]),i(e,{dataset:b,files:[...T.map(e=>e.item),e],onRemove:F})};function F(e){let t=M()?.cases??[];N(Pr({cases:t},e)),r.offer({label:`Removed ${e}`,restore:()=>N(t)})}let I=e=>{let i=M();if(!b||!i)return null;let{next:a,changed:o}=Nt(i.cases,k,e);if(!o.length)return m(null),null;if(e.type!==`delete`){let e=Pt(i.cases,a,o);if(e.cases.length)return e}Me(t,b,i,`bulk`);let s=i.cases;if(n.edit(b,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:Rt(e,o.length),restore:()=>n.edit(b,e=>({...e,cases:s}))}),m(null),null},L=k.size===0,te=[{label:`Set count…`,icon:a,disabled:L,onSelect:()=>m(`bounds`)},{label:`Add term…`,icon:y.add,disabled:L,onSelect:()=>m(`addTerm`)},{label:`Remove term…`,icon:ht,disabled:L,onSelect:()=>m(`removeTerm`)},{label:`Mark To do…`,icon:Ye,disabled:L,onSelect:()=>m(`todo`)},{label:`Mark graded…`,icon:Xe,disabled:L,onSelect:()=>m(`graded`)},{label:`Delete`,icon:y.remove,destructive:!0,disabled:L,onSelect:()=>void I({type:`delete`})}];return(0,Z.jsxs)(`div`,{className:`cases`,children:[o?.length?(0,Z.jsx)(zr,{rows:T,shown:A,filters:u,onFilters:d,selected:k,onSelect:l,selectionActions:te,sourceFiles:E,hasSource:!!C?.source,loading:!C,loadError:S?.sync.state===`missing`?S.sync.message:null,onRetry:()=>{b&&n.load(b)},pageSize:e,onEdit:P,onAdd:()=>g(!0),onRemove:F,children:f&&v&&(0,Z.jsxs)(`p`,{className:`note ev-from`,role:`status`,children:[(0,Z.jsxs)(`span`,{children:[`From `,f.from]}),f.found<f.wanted&&(0,Z.jsxs)(`span`,{children:[f.found,` of `,f.wanted,` are in `,v.name,` now`]})]})}):null,h&&C?.source&&E&&(0,Z.jsx)(Er,{title:`Add case`,action:`Add case`,source:C.source,files:E,taken:new Set(T.map(e=>e.item)),onPick:ee,onClose:()=>g(!1)}),p&&C&&(0,Z.jsx)(Kr,{kind:p,cases:C.cases,keys:k,onApply:I,onClose:_}),(0,Z.jsx)(O,{undo:r.undo,onUndo:r.undoNow,onDismiss:r.dismiss})]})}function Jr(){let e=Y(),n=ve(),i=Ie(),a=ne(),{list:o,error:s}=Le(),{datasetId:c,pickDataset:l}=Gt(),[u,d]=(0,J.useState)(!1),[f,p]=(0,J.useState)(!1),[m,_]=(0,J.useState)(null),[v,x]=(0,J.useState)(!1),[S,C]=(0,J.useState)(!1),[w,T]=ie(`dataset-cases`,20),[E,A]=(0,J.useState)(!1),[j,M]=(0,J.useState)(null),N=(0,J.useRef)(null),[F]=ye(`promptlab.versions`),[L,R]=(0,J.useState)(null);(0,J.useEffect)(()=>{let t=!0;return e.sources().then(e=>{t&&R(e.sources)}).catch(()=>{t&&R([])}),()=>{t=!1}},[e]);let z=o?.find(e=>e.id===c)??o?.[0]??null,B=z?.id??``,V=Re(B||null)?.doc??null,H=V?.body??null,ae=(0,J.useMemo)(()=>B?ke(n,B):[],[n,B,F]),W=e=>_({text:e instanceof Error?e.message:String(e),bad:!0}),G=(0,J.useCallback)(()=>i.entry(B)?.doc?.body??null,[i,B]),K=(0,J.useCallback)(e=>{B&&i.edit(B,e)},[i,B]),q=()=>new Set((i.list().list??[]).map(e=>e.name)),oe=async()=>{_(null);try{let e=await i.create(Xr(`Untitled dataset`,q()));l(e.id),d(!0)}catch(e){W(e)}},se=e=>{let t=e.trim();V&&t&&t!==V.name&&(_(null),i.rename(B,t).catch(e=>{e instanceof he&&e.status===409?_({text:`A dataset is already called ${t}.`,bad:!0}):W(e)}))},ce=async()=>{if(V){_(null);try{await i.flush(B);let e=await i.create(Xr(`${V.name} copy`,q()),structuredClone(V.body));l(e.id)}catch(e){W(e)}}},le=async()=>{if(!V)return;_(null);let{name:e}=V,t=o?.findIndex(e=>e.id===B)??-1;try{await i.flush(B);let n=await i.remove(B),r=i.list().list??[];l(r[Math.min(Math.max(t,0),r.length-1)]?.id??null),a.offer({label:`Deleted ${e}`,restore:()=>{i.restore(n).then(t=>{l(t.id),t.name!==e&&_({text:`Restored as ${t.name}.`,bad:!1})}).catch(W)}})}catch(e){W(e)}},ue=async e=>{_(null);let t;try{t=await Yr(e)}catch(e){W(e);return}let n;try{n=JSON.parse(t)}catch(e){_({text:`Not JSON: ${e instanceof Error?e.message:String(e)}`,bad:!0});return}M(`import`);try{let e=await i.importFile(n);e[0]&&l(e[0].id),_({text:`Imported ${e.map(e=>e.name).join(`, `)}.`,bad:!1})}catch(e){W(e)}finally{M(null)}},X=async()=>{B&&(M(`export`),await i.flush(B).catch(()=>{}),await de(i.exportUrl(B),e=>hr(`dataset`,e.dataset?.name??``,e.version,`json`)),M(null))},de=async(e,t)=>{try{let n=await fetch(e);if(!n.ok)throw Error(`the export answered ${n.status}`);let r=await n.json();gr(new Blob([JSON.stringify(r,null,2)+`
|
|
6
|
+
`],{type:`application/json`}),t(r))}catch(e){W(e)}},fe=e=>{let t=G();t&&(Me(n,B,t,`restore`),K(()=>structuredClone(e.doc)),C(!1),a.offer({label:`Restored the dataset`,restore:()=>K(()=>t)}))},pe=!z,me=[{label:`Rename`,icon:t,disabled:!V,onSelect:()=>d(!0)},{label:`Clone`,icon:y.clone,disabled:!V,onSelect:()=>void ce()},{label:`Import JSON…`,icon:r,busy:j===`import`,onSelect:()=>N.current?.click()},{label:`Export JSON`,icon:g,disabled:pe,busy:j===`export`,onSelect:()=>void X()},{label:`Export all`,icon:it,disabled:!o?.length,busy:j===`exportAll`,onSelect:()=>{M(`exportAll`),de(i.exportAllUrl(),e=>hr(`datasets`,`all`,e.version,`json`)).finally(()=>M(null))}},{label:`Restore…`,icon:I,disabled:!ae.length||!V,onSelect:()=>C(!0)},{label:`Edit raw…`,icon:tt,disabled:!V,onSelect:()=>x(!0)},{label:`Delete`,icon:b,destructive:!0,disabled:!V,onSelect:()=>void le()}],ge=H?H.cases.filter(e=>!e.todo).length:0,_e=(0,Z.jsx)(`input`,{ref:N,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&&ue(t)}}),be=H?.source?.name,xe=H?[`${H.cases.length} cases`,`${ge} graded`,...be?[`Source: ${be}`]:[]].join(` · `):void 0;return(0,Z.jsxs)(`div`,{className:`datasets`,children:[(0,Z.jsx)(ee,{kind:`Dataset`,name:V?.name??z?.name??(o===null?`Loading…`:`None`),onPick:o?.length?()=>p(!0):void 0,meta:xe,primary:{label:`New dataset`,icon:h,onSelect:()=>void oe()},actions:me}),m&&(0,Z.jsx)(`p`,{className:`note${m.bad?` bad`:``}`,role:m.bad?`alert`:`status`,children:m.text}),_e,o===null||o.length===0?o===null?(0,Z.jsx)(k,{label:`Datasets`,error:s,onRetry:()=>void i.refresh()}):(0,Z.jsx)(`p`,{className:`note`,children:`No datasets yet.`}):(0,Z.jsxs)(U,{id:`dataset`,title:`Cases`,note:H?String(H.cases.length):void 0,actions:[{label:`Page size`,icon:y.pageSize,onSelect:()=>A(!0)}],children:[H&&(0,Z.jsxs)(`div`,{className:`prop`,"data-control":`select`,children:[(0,Z.jsx)(`span`,{className:`prop-name`,children:`Source`}),(0,Z.jsx)(`span`,{className:`prop-value`,children:(0,Z.jsxs)(`select`,{"aria-label":`Source`,value:H.source?.id??``,onChange:e=>{let t=L?.find(t=>t.id===e.target.value);K(e=>({...e,source:t?{id:t.id,name:t.name}:null}))},children:[(0,Z.jsx)(`option`,{value:``,children:`None`}),H.source&&!L?.some(e=>e.id===H.source.id)&&(0,Z.jsxs)(`option`,{value:H.source.id,children:[H.source.name,` (missing)`]}),(L??[]).map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.name},e.id))]})})]}),(0,Z.jsx)(qr,{pageSize:w})]}),f&&o&&(0,Z.jsx)(P,{kind:`Dataset`,value:B,onClose:()=>p(!1),options:o.map(e=>({id:e.id,label:e.name})),onPick:e=>{l(e),_(null)}}),u&&V&&(0,Z.jsx)(re,{title:`Rename dataset`,value:V.name,onCommit:se,onClose:()=>d(!1)}),E&&(0,Z.jsx)(te,{value:w,onChange:T,onClose:()=>A(!1)}),S&&V&&(0,Z.jsx)(D,{title:`Restore dataset`,onClose:()=>C(!1),children:(0,Z.jsxs)(`div`,{className:`version-list`,children:[ae.length===0&&(0,Z.jsx)(`p`,{className:`note`,children:`No versions of this dataset yet.`}),ae.map((e,t)=>(0,Z.jsxs)(`div`,{className:`version-row`,children:[(0,Z.jsxs)(`span`,{className:`version-when`,children:[Qr(e.at),` · `,Zr(e.reason)]}),(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>fe(e),children:`Restore`})]},`${e.at}-${t}`))]})}),v&&V&&(0,Z.jsx)(_r,{name:V.name,body:V.body,onSave:e=>{K(()=>e),x(!1)},onClose:()=>x(!1)}),(0,Z.jsx)(O,{undo:a.undo,onUndo:a.undoNow,onDismiss:a.dismiss})]})}function Yr(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 Xr=(e,t)=>{if(!t.has(e))return e;for(let n=2;;n++)if(!t.has(`${e} ${n}`))return`${e} ${n}`},Zr=e=>e===`idle`?`after editing`:e===`restore`?`before a restore`:e===`bulk`?`before a bulk edit`:e===`pack`?`before a pack update`:e,Qr=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},$r=[{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 ti(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 ni(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 ri=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()};function ii({id:e,onClose:t,onDuplicate:n,onDelete:r}){let i=Ke(),a=Je(e),{openRun:o}=Jt(),[s,c]=(0,J.useState)(new Set),[l,u]=(0,J.useState)(new Set),[d,f]=(0,J.useState)(null),m=a?.doc;if(!m)return(0,Z.jsx)(j,{title:`Prompt`,sections:[{key:`loading`,children:(0,Z.jsx)(k,{label:`Prompt`,error:a?.sync.state===`missing`?a.sync.message:null,onRetry:()=>i.load(e)})}],onClose:t});let h=(e,t,n)=>{let r=new Set(e);r.has(t)?r.delete(t):r.add(t),n(r)},g=e=>f(e instanceof Error?e.message:String(e)),_=e=>m.versions.find(t=>t.version===e)?.text??``,v=m.uses.some(e=>e.job>0),b=[{key:`version`,header:`Version`,sort:e=>e.version,cell:e=>`v${e.version}${e.version===m.version?` (newest)`:``}`},{key:`created`,header:`Made`,sort:e=>e.created,cell:e=>ri(e.created)},{key:`uses`,header:`Uses`,className:`pl-num`,sort:e=>e.uses,cell:e=>e.uses},{key:`menu`,header:``,label:``,className:`pl-menu`,sort:null,cell:t=>(0,Z.jsx)(G,{label:`v${t.version} actions`,actions:[{label:s.has(t.version)?`Hide words`:`Show words`,icon:p,onSelect:()=>h(s,t.version,c)},{label:`Restore`,icon:ae,disabled:t.version===m.version,onSelect:()=>{f(null),i.restoreVersion(e,t.version).catch(g)}}]})}],x=e=>`${e.runId}:${e.scenarioId}:${e.job}`,S=[{key:`run`,header:`Run`,sort:e=>e.submittedAt,cell:e=>(0,Z.jsx)(`a`,{className:`pl-run`,href:`#/history`,onClick:n=>{n.preventDefault(),t(),o(e.runId,{at:e.submittedAt,from:`history`})},children:un(e.submittedAt)})},{key:`scenario`,header:`Scenario`,sort:e=>e.scenarioName,cell:e=>e.scenarioName},...v?[{key:`job`,header:`Job`,className:`pl-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=>ri(e.submittedAt)},{key:`menu`,header:``,label:``,className:`pl-menu`,sort:null,cell:e=>(0,Z.jsx)(G,{label:`${un(e.submittedAt)} ${e.scenarioName} actions`,actions:[{label:l.has(x(e))?`Hide words`:`Show words`,icon:p,onSelect:()=>h(l,x(e),u)}]})}],C=[{label:`Set as default`,icon:wt,disabled:m.default,onSelect:()=>{f(null),i.setDefault(e).catch(g)}},{label:`Duplicate`,icon:y.clone,onSelect:()=>n(m)},{label:`Delete`,icon:y.remove,destructive:!0,disabled:m.default,onSelect:()=>r(m)}],w=d??Be(a.sync),T=a.sync.state===`conflict`;return(0,Z.jsx)(j,{title:ze(m),status:w??void 0,statusBad:!!w,menu:C,wide:!0,actions:T?[{label:`Take theirs`,onSelect:()=>void i.resolve(e,`theirs`)},{label:`Keep mine`,onSelect:()=>void i.resolve(e,`mine`)}]:[],onClose:()=>{i.flush(e),t()},sections:[{key:`prompt`,rows:[{key:`name`,label:`Name`,control:{type:`text`,value:m.name,placeholder:`First line`,onChange:t=>i.edit(e,{name:t})}},{key:`version`,label:`Version`,required:!0,control:{type:`static`,text:`v${m.version}${m.default?` (Default)`:``}`}},{key:`text`,label:`Prompt`,required:!0,control:{type:`textarea`,value:m.text,placeholder:`None`,onChange:t=>i.edit(e,{text:t})}}]},{key:`versions`,title:`Versions`,children:(0,Z.jsx)(A,{className:`pltable pl-versions`,label:`Versions`,rows:m.versions,rowKey:e=>String(e.version),columns:b,after:e=>s.has(e.version)&&(0,Z.jsx)(`tr`,{className:`pl-words-row`,children:(0,Z.jsx)(`td`,{colSpan:b.length,children:(0,Z.jsx)(`pre`,{className:`pl-words`,children:e.text})})})})},{key:`uses`,title:`Uses`,children:m.uses.length===0?(0,Z.jsx)(`p`,{className:`note`,children:`No uses yet.`}):(0,Z.jsx)(A,{className:`pltable pl-uses`,label:`Uses`,rows:m.uses,rowKey:x,pageSize:10,columns:S,after:e=>l.has(x(e))&&(0,Z.jsx)(`tr`,{className:`pl-words-row`,children:(0,Z.jsx)(`td`,{colSpan:S.length,children:(0,Z.jsx)(`pre`,{className:`pl-words`,children:_(e.version)})})})})}]})}function ai(){let e=Ke(),{list:t,error:n}=qe(),r=ne(),[i,a]=ie(`prompts`,20),[o,s]=(0,J.useState)(!1),[c,l]=(0,J.useState)(``),[u,d]=(0,J.useState)(`all`),[f,p]=(0,J.useState)(null),[m,g]=(0,J.useState)(null),_=t??[],v=_.filter(e=>ti(e,c,u)),b=e=>g(e instanceof Error?e.message:String(e)),x=async()=>{g(null);try{p((await e.create({name:``,text:``})).id)}catch(e){b(e)}},S=async t=>{g(null);try{await e.flush(t.id);let n=await e.create({name:`${ze(t)} copy`,text:e.entry(t.id)?.doc?.text??t.text});p(n.id)}catch(e){b(e)}},C=async t=>{g(null);try{let n=await e.remove(t.id);f===t.id&&p(null),r.offer({label:`Deleted ${ze(t)}`,restore:()=>{e.restore(n).catch(b)}})}catch(e){b(e)}},w=t=>{g(null),e.setDefault(t.id).catch(b)},T=e=>[{label:`Edit`,icon:y.edit,onSelect:()=>p(e.id)},{label:`Set as default`,icon:wt,disabled:e.default,onSelect:()=>w(e)},{label:`Duplicate`,icon:y.clone,onSelect:()=>void S(e)},{label:`Delete`,icon:y.remove,destructive:!0,disabled:e.default,onSelect:()=>void C(e)}];return(0,Z.jsxs)(U,{id:`prompts`,title:`Prompt library`,note:t?`${_.length} ${_.length===1?`prompt`:`prompts`}`:void 0,actions:[{label:`Page size`,icon:y.pageSize,onSelect:()=>s(!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,Z.jsx)(k,{label:`Prompts`,error:n,onRetry:()=>void e.refresh()}):_.length===0?(0,Z.jsx)(`p`,{className:`note`,children:`No prompts yet.`}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(z,{noun:`prompts`,search:{label:`Search prompts`,placeholder:`Search prompts`,value:c,onChange:l},filters:[{key:`show`,label:`Show`,value:u,onChange:e=>d(e),options:$r}],count:{shown:v.length,total:_.length}}),v.length===0?(0,Z.jsx)(`p`,{className:`note`,children:`No prompts match these filters.`}):(0,Z.jsx)(A,{className:`pltable`,label:`Prompts`,rows:v,rowKey:e=>e.id,pageSize:i,rowProps:e=>({"data-default":e.default||void 0}),columns:[{key:`prompt`,header:`Prompt`,sort:e=>ze(e).toLowerCase(),cell:e=>(0,Z.jsxs)(`button`,{type:`button`,className:`pl-open`,onClick:()=>p(e.id),children:[(0,Z.jsxs)(`span`,{className:`pl-title`,children:[ze(e),e.default&&(0,Z.jsx)(`span`,{className:`pl-default`,children:`Default`})]}),e.name.trim()&&e.text.trim()&&(0,Z.jsx)(`span`,{className:`pl-preview`,children:e.text.trim()})]})},{key:`version`,header:`Version`,className:`pl-num`,sort:e=>e.version,cell:e=>`v${e.version}`},{key:`uses`,header:`Uses`,className:`pl-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?ri(e.lastUsed):`—`},{key:`menu`,header:``,label:``,className:`pl-menu`,sort:null,cell:e=>(0,Z.jsx)(G,{label:`${ze(e)} actions`,actions:T(e)})}]})]}),m&&(0,Z.jsx)(`p`,{className:`note bad`,role:`alert`,children:m}),(0,Z.jsxs)(`button`,{type:`button`,className:`ghost pl-add`,onClick:()=>void x(),children:[(0,Z.jsx)(h,{size:14,"aria-hidden":`true`}),`Add prompt`]}),f&&(0,Z.jsx)(ii,{id:f,onClose:()=>p(null),onDuplicate:e=>void S(e),onDelete:e=>void C(e)}),o&&(0,Z.jsx)(te,{value:i,onChange:a,onClose:()=>s(!1)}),(0,Z.jsx)(O,{undo:r.undo,onUndo:r.undoNow,onDismiss:r.dismiss})]})}var oi=`evals-lab.sources`,si={view:`thumbs`,sort:`name`,dir:1};function ci(){try{let e=window.localStorage.getItem(oi);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 si}function li(e){try{window.localStorage.setItem(oi,JSON.stringify(e))}catch{}}var ui=e=>{let t=e.lastIndexOf(`.`);return t<0?``:e.slice(t).toLowerCase()},di=[`.heic`,`.heif`,`.dng`,`.tif`,`.tiff`],fi=[`.jpg`,`.jpeg`,`.png`],pi=e=>fi.includes(ui(e))||di.includes(ui(e)),mi=(e,t)=>`/api/sources/${encodeURIComponent(e)}/thumbs/${encodeURIComponent(t.name)}${t.v?`?v=${t.v}`:``}`,hi=(e,t)=>di.includes(ui(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 _i(e,t){let n=t.trim().toLowerCase();return n?e.filter(e=>e.name.toLowerCase().includes(n)):[...e]}function vi(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 yi(e){return new Date(e*1e3).toLocaleDateString(void 0,{year:`numeric`,month:`short`,day:`numeric`})}function bi(e){return{id:e.id,name:e.name,system:e.system,type:e.type,files:e.files.length,bytes:e.bytes}}var xi=`[redacted]`,Si=/^(?:api[-_]?key|x-api-key|authorization|ocp-apim-subscription-key|password|secret|client[-_]?secret|token|access[-_]?token|refresh[-_]?token|sig)$/i,Ci=/^(?:headers|authentication)$/,wi=[[/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 Ti(e){let t=0,n=e=>{let n=e;for(let[e,r]of wi)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))Ci.test(i)&&a&&typeof a==`object`&&!Array.isArray(a)?n[i]=Object.fromEntries(Object.keys(a).map(e=>(t++,[e,xi]))):Ci.test(i)&&typeof a==`string`||Si.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 Ei=`https://api.flow.microsoft.com/providers/Microsoft.ProcessSimple`,Di=`api-version=2016-11-01`,Oi=/\.powerplatformusercontent\.com$/,ki=4,Ai=4;function ji(e,t=(e,t)=>fetch(e,t)){let n=async n=>{let r=`${Ei}${n}${n.includes(`?`)?`&`:`?`}${Di}`;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(Ei).pathname.length)}${t.search}`},o=(e,t)=>`/environments/${r(e)}/flows/${r(t)}/runs`,s=0,c=[],l=async()=>{if(s<ki){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:`||!Oi.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<Ai){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 Mi=[`https://service.flow.microsoft.com//.default`],Ni=null;function Pi(e){let t=`${e.clientId}/${e.tenant}`;return Ni?.key!==t&&(Ni={key:t,pca:ue(()=>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}),[])}),Ni.pca}var Fi=()=>{let e=new URLSearchParams(window.location.search);return e.has(`state`)&&(e.has(`code`)||e.has(`error`))};async function Ii(e){await Pi(e)}async function Li(e){let t=await Pi(e);return(t.getActiveAccount()??t.getAllAccounts()[0]??null)?.username??null}var Ri=`signin`;function zi(e=window.location.href){let t=new URL(e);return t.hostname===`127.0.0.1`?(t.hostname=`localhost`,t.searchParams.set(Ri,`microsoft`),t.href):null}function Bi(){let e=new URL(window.location.href);return e.searchParams.get(`signin`)===`microsoft`&&(e.searchParams.delete(Ri),window.history.replaceState(window.history.state,``,e.href),!0)}async function Vi(e,t=window.location.href){let n=zi();if(n){window.location.assign(n);return}await(await Pi(e)).loginRedirect({scopes:Mi,prompt:`select_account`,redirectStartPage:t})}async function Hi(e){let t=await Pi(e),n=t.getActiveAccount()??t.getAllAccounts()[0];n&&await t.clearCache({account:n})}async function Ui(e){let t=await Pi(e),n=t.getActiveAccount()??t.getAllAccounts()[0];if(!n)throw Error(`sign in to Microsoft first`);try{return(await t.acquireTokenSilent({scopes:Mi,account:n})).accessToken}catch(e){let{InteractionRequiredAuthError:r}=await ue(async()=>{let{InteractionRequiredAuthError:e}=await import(`./dist-DI3ewZYj.js`);return{InteractionRequiredAuthError:e}},[]);throw e instanceof r&&await t.acquireTokenRedirect({scopes:Mi,account:n,redirectStartPage:window.location.href}),e}}var Wi=new EventTarget,Gi=()=>Wi.dispatchEvent(new Event(`change`));function Ki(){let e=Y(),[t,n]=(0,J.useState)({cfg:void 0,editable:!1});return(0,J.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(),Wi.addEventListener(`change`,r),()=>{t=!1,Wi.removeEventListener(`change`,r)}},[e]),t}var qi=()=>Ki().cfg,Ji=e=>ji(()=>Ui(e));async function Yi(e,t,n){let r=await e.flow(t,n);return{name:r.name,definition:Ti(r.definition).value}}function Xi({onMade:e}){let t=Y(),n=qi(),r=(0,J.useMemo)(()=>n?Ji(n):null,[n]),[i,a]=(0,J.useState)(void 0),[o,s]=(0,J.useState)(null),[c,l]=(0,J.useState)(``),[u,d]=(0,J.useState)(null),[f,p]=(0,J.useState)(``),[m,h]=(0,J.useState)(``),[g,_]=(0,J.useState)(!1),[v,y]=(0,J.useState)(null),b=e=>y(e instanceof Error?e.message:String(e));if((0,J.useEffect)(()=>{n&&Li(n).then(a,()=>a(null))},[n]),(0,J.useEffect)(()=>{r&&i&&r.environments().then(e=>{s(e),l((e.find(e=>e.isDefault)??e[0])?.id??``)},b)},[r,i]),(0,J.useEffect)(()=>{r&&c&&(d(null),p(``),r.flows(c).then(e=>{d(e),p(e[0]?.id??``),h(e[0]?.name??``)},b))},[r,c]),n===void 0||n&&i===void 0)return(0,Z.jsx)(k,{label:`Account`});if(n===null)return(0,Z.jsx)(`p`,{className:`note`,children:`Microsoft: Not Configured`});if(!i)return(0,Z.jsxs)(`div`,{className:`sacts`,children:[(0,Z.jsxs)(`button`,{type:`button`,className:`ghost`,onClick:()=>void Vi(n).catch(b),children:[(0,Z.jsx)(ft,{size:14,"aria-hidden":`true`}),` Sign in with Microsoft`]}),v&&(0,Z.jsx)(`p`,{className:`note bad`,role:`alert`,children:v})]});let x=async()=>{if(!r||!f||!m.trim())return;_(!0),y(null);let n=null;try{let i=u?.find(e=>e.id===f),a=await t.createSource(m.trim(),`power-automate`,{environment:c,flow:f,displayName:i?.name??f});n=a.id;let o=await Yi(r,c,f);await t.saveDefinition(a.id,0,o.definition),await e()}catch(e){n&&await t.removeSource(n).catch(()=>{}),b(e instanceof he?Error(e.message):e)}finally{_(!1)}};return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(N,{label:`Flow`,rows:[{key:`account`,label:`Account`,control:{type:`static`,text:i}},{key:`env`,label:`Environment`,control:o?{type:`select`,value:c,options:o.map(e=>({value:e.id,label:e.name})),onChange:l}:{type:`static`,text:`Loading…`}},{key:`flow`,label:`Flow`,control:u?{type:`select`,value:f,options:u.map(e=>({value:e.id,label:e.name})),onChange:e=>{p(e),h(u.find(t=>t.id===e)?.name??``)}}:{type:`static`,text:c?`Loading…`:`—`}},{key:`name`,label:`Name`,control:{type:`text`,value:m,onChange:h}}]}),u&&!u.length&&(0,Z.jsx)(`p`,{className:`note`,children:`No flows in this environment.`}),v&&(0,Z.jsx)(`p`,{className:`note bad`,role:`alert`,children:v}),(0,Z.jsx)(`div`,{className:`sacts`,children:(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,disabled:g||!f||!m.trim(),onClick:()=>void x(),children:`Add`})})]})}var Zi=`evals-lab/record`,$=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Qi=/\b(triggerBody|triggerOutputs|body|outputs|actions|variables|items|item|parameters)\(\s*(?:'((?:[^']|'')*)')?\s*\)/g;function $i(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)$i(n,t);else if($(e))for(let n of Object.values(e))$i(n,t);return t}function ea(e,t=null){let n=new Map;for(let r of $i(e))for(let e of r.matchAll(Qi)){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 ta(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:Zi,version:1,step:e,at:null,scope:n,request:null,result:null,origin:{kind:`hand`}}}function na(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):$(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 ra=Object.create(null);ra.Http={label:`HTTP`,template:({headers:e,authentication:t,...n})=>n};var ia=Object.create(null);ia.Foreach={loops:!0},ia.Until={loops:!0},ia.InitializeVariable={declares:e=>(Array.isArray(e.variables)?e.variables:[]).flatMap(e=>$(e)&&typeof e.name==`string`?[e.name]:[])};var aa=e=>!!(e&&ia[e]?.loops);function oa(e){let t=[],n=(e,r)=>{for(let[i,a]of Object.entries(e??{})){let e=a.type?ra[a.type]:void 0;if(e&&$(a.inputs)){let n=e.template(a.inputs);t.push({name:i,kind:a.type,loops:r,template:n,reads:ea(n,r.at(-1)??null)})}let o=aa(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($(e)?e.actions:void 0,[]),t}function sa(e){let t={},n=(e,r)=>{for(let[i,a]of Object.entries(e??{})){t[i]={...a,loops:r};let e=aa(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($(e)?e.actions:void 0,[]),t}async function ca(e,t,n,r){let i=sa(r),a={};for(let r of e.reads)if(r.from===`trigger`){let e=await n.triggerOutputs();a.trigger={body:$(e)?e.body:e}}else if(r.from===`action`){let e=await n.actionOutputs(r.name,t.at);(a.actions??={})[r.name]=$(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?ia[e.type]:void 0;return!!t?.declares&&$(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=($(s)&&Array.isArray(s.variables)?s.variables:[]).find(e=>$(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=$(e)&&Array.isArray(e.foreachItems)?e.foreachItems:[];(a.items??={})[r.name]=i[t.at[r.name]??0]??null}let o=$(t.inputs)?t.inputs:null,s=$(t.outputs)?t.outputs:null;return{format:Zi,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 la(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 ua=e=>e.from===`trigger`?`trigger`:e.from===`parameter`?``:e.name,da=e=>{if(typeof e!=`string`)return e;try{return JSON.parse(e)}catch{return e}};function fa(e,t){let n=[...new Set(t.flatMap(e=>Object.keys(e)))],r=new Set(e.reads.map(ua).filter(Boolean)),i=n.filter(e=>!r.has(e)&&!(r.has(`trigger`)&&e.startsWith(`trigger.`)));return{records:t.map(t=>{let n=ta(e.name,e.reads);n.origin={kind:`upload`};for(let r of e.reads){let e=ua(r);if(r.from===`trigger`){let r=Object.keys(t).filter(e=>e.startsWith(`trigger.`)),i=e in t?da(t[e]):r.length?Object.fromEntries(r.map(e=>[e.slice(8),da(t[e])])):null;n.scope.trigger={body:i}}else if(e in t){let i=da(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 pa(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===`
|
|
7
|
+
`||o===`\r`?(o===`\r`&&a[e+1]===`
|
|
8
|
+
`&&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 ma(e,t,n){if(!t.request)return{match:null};let r=$(n)&&$(n.parameters)?Object.fromEntries(Object.entries(n.parameters).map(([e,t])=>[e,$(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:_(a.method,n),uri:_(a.uri,n),body:_(a.body??null,n)}}catch(e){return{match:!1,where:e instanceof Error?e.message:String(e)}}let a=ha(i,t.request,`request`);return a?{match:!1,where:a}:{match:!0}}function ha(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=ha(e[r],t[r],`${n}[${r}]`);if(i)return i}return null}if($(e)&&$(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=ha(e[i],t[i],`${n}.${i}`);if(r)return r}return null}return JSON.stringify(e)===JSON.stringify(t)?null:`${n}`}var ga=Object.create(null);ga.ParseJson={reads:e=>typeof e.content==`string`?e.content:null,schema:e=>e.schema??null};function _a(e,t){for(let[n,r]of Object.entries(sa(e))){let e=r.type?ga[r.type]:void 0,i=e&&$(r.inputs)?e.reads(r.inputs):null;if(i&&ea(i).some(e=>e.from===`action`&&e.name===t))return{name:n,expression:i,schema:e.schema&&$(r.inputs)?e.schema(r.inputs)??null:null}}return null}function va(e,t){let n=JSON.stringify($(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 ba(e,t){let n=x(),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 xa(e,t,n,r){let i=x(),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=_a(t,n.name),u=l?va(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(`
|
|
9
|
+
`)}]:[]],f=ba(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(`metrics`,``,{metrics:d})]:[]}}function Sa(e,t){let n=e.result;if(!n||!(`status`in n))return null;let r=oa(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:x().httpApiFor(i),readAs:_a(t,r.name)?.expression??null};try{return x().httpReplyOf(a,{prompt:``},n.body,n.status,{scope:e.scope,now:e.at}).raw}catch{return null}}function Ca(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 wa(e,t){let n=[],r=0;for(let{name:i,record:a}of e){let e=Sa(a,t);if(e==null){r++;continue}let o=_a(t,a.step),s=o?va(t,o.name):[];n.push({id:i.replace(/\.json$/i,``).replace(/[^A-Za-z0-9._-]/g,`_`),item:i,todo:!0,note:``,metrics:Ca(e,s)})}return{cases:n,skipped:r}}async function Ta(e,t,n,r,i){let a=await e.run(t,n,r),o=sa(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 Ea(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 Ta(e,t,n,o,a);for(let e of await r.callsOf(i)){let t=Ti(await ca(i,e,r,a)).value,n=na(t);if(c.has(n)){u++;continue}c.add(n),l.push(t)}s?.(++d)}return{records:l,skipped:u}}var Da=e=>e.name.toLowerCase().endsWith(`.json`),Oa=e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result)),r.onerror=()=>n(r.error),r.readAsText(e)}),ka=`evals-lab.flow.importing`;function Aa(e){try{return sessionStorage.getItem(e)}catch{return null}}function ja(e,t){try{t?sessionStorage.setItem(e,t):sessionStorage.removeItem(e)}catch{}}var Ma=e=>e instanceof Error?e.message:String(e);function Na({source:e,definition:t,cfg:n}){let i=Y(),a=Ie(),o=ne(),[s,c]=(0,J.useState)(e.files.filter(Da)),[l,u]=(0,J.useState)({}),[d,f]=(0,J.useState)(null),[m,_]=(0,J.useState)(()=>{let t=Aa(ka)===e.id;return t&&ja(ka,null),t?`import`:null}),[v,y]=(0,J.useState)(null),x=(0,J.useMemo)(()=>oa(t),[t]),[S,C]=(0,J.useState)(!1),[w,T]=(0,J.useState)(null),E=(0,J.useCallback)(async()=>{let t=(await i.source(e.id)).files.filter(Da);c(t);let n=await Promise.all(t.map(async t=>{try{return[t.name,JSON.parse(await Oa(await i.file(e.id,t.name)))]}catch{return[t.name,null]}}));u(Object.fromEntries(n))},[i,e.id]),j=(0,J.useCallback)(()=>{T(null),E().then(()=>C(!0),e=>T(Ma(e)))},[E]);(0,J.useEffect)(j,[j]);let M=e=>{let n=l[e],r=n?x.find(e=>e.name===n.step):void 0;return n&&r?ma(r,n,t):null},N=(0,J.useMemo)(()=>new Set(s.flatMap(e=>l[e.name]?[na(l[e.name])]:[])),[s,l]),P=async(t,n=0)=>{let r=0,a=[];for(let n of t)try{await i.upload(e.id,la(n),new Blob([JSON.stringify(n,null,2)],{type:`application/json`})),r++}catch(e){a.push(e instanceof he?e.message:Ma(e))}await E(),f([`Added ${r}`,n?`Skipped ${n}`:``,a.length?`Refused ${a.length}: ${a[0]}`:``].filter(Boolean).join(` · `))},ee=async()=>{let{cases:n,skipped:r}=wa(s.flatMap(e=>l[e.name]?[{name:e.name,record:l[e.name]}]:[]),t);if(!n.length)return f(`No record holds a production reply.`);try{let t=await a.create(`${e.name} · production`,{version:6,source:{id:e.id,name:e.name},cases:n});f([`Made ${t.name}: ${n.length} ${n.length===1?`case`:`cases`}`,r?`Skipped ${r}`:``].filter(Boolean).join(` · `))}catch(e){f(Ma(e))}},F=async t=>{try{let{trash:n}=await i.removeFiles(e.id,t);c(e=>e.filter(e=>!t.includes(e.name))),o.offer({label:`Removed ${t[0]}`,restore:()=>void i.restoreTrash(n).then(E,e=>f(Ma(e)))})}catch(e){f(Ma(e))}},L=async t=>{let n=URL.createObjectURL(await i.file(e.id,t)),r=document.createElement(`a`);r.href=n,r.download=t,document.body.append(r),r.click(),r.remove(),URL.revokeObjectURL(n)},te=e=>[{label:`View`,icon:p,onSelect:()=>y(e.name)},{label:`Download`,icon:g,onSelect:()=>void L(e.name).catch(e=>f(Ma(e)))},{label:`Remove`,icon:b,destructive:!0,onSelect:()=>void F([e.name])}],R=(0,J.useCallback)(()=>_(null),[]),z=(0,J.useCallback)(()=>y(null),[]),B=v?l[v]:null;return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(U,{id:`flow-records`,title:`Records`,note:String(s.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:I,disabled:!x.length||!n,onSelect:()=>_(`import`)},{label:`Upload`,icon:r,disabled:!x.length,onSelect:()=>_(`upload`)},{label:`New dataset`,icon:$e,disabled:!s.length,onSelect:()=>void ee()}],children:[d&&(0,Z.jsx)(`p`,{className:`note`,role:`status`,children:d}),S?s.length?(0,Z.jsx)(`div`,{className:`sflow`,children:(0,Z.jsx)(A,{className:`slist`,label:`Records`,rows:s,rowKey:e=>e.name,columns:[{key:`name`,header:`Name`,sort:e=>e.name,cell:e=>(0,Z.jsxs)(Z.Fragment,{children:[e.name,(0,Z.jsx)(`span`,{className:`sflow-in`,children:Ia(l[e.name])})]})},{key:`result`,header:`Result`,sort:e=>La(l[e.name]),cell:e=>La(l[e.name])},{key:`request`,header:`Request`,sort:e=>Pa(M(e.name)),tdProps:e=>{let t=M(e.name);return t&&t.match===!1?{title:t.where}:{}},cell:e=>Pa(M(e.name))},{key:`menu`,header:``,className:`s-actions`,sort:null,cell:e=>(0,Z.jsx)(G,{label:`${e.name} actions`,actions:te(e)})}]})}):(0,Z.jsx)(`p`,{className:`note`,children:`No records yet. Import runs, in this group's menu, reads them from the flow's run history.`}):(0,Z.jsx)(k,{label:`Records`,error:w,onRetry:j}),(0,Z.jsxs)(`button`,{type:`button`,className:`ghost add-btn`,disabled:!x.length,onClick:()=>_(`hand`),children:[(0,Z.jsx)(h,{size:14,"aria-hidden":`true`}),` Add record`]})]}),m===`import`&&n&&(0,Z.jsx)(Ba,{cfg:n,source:e,steps:x,definition:t,held:N,onClose:R,onRead:async(e,t)=>{_(null),await P(e,t)}}),m===`hand`&&(0,Z.jsx)(Va,{steps:x,onClose:R,onAdd:async e=>{_(null),await P([e])}}),m===`upload`&&(0,Z.jsx)(Ua,{steps:x,onClose:R,onRead:async e=>{_(null),await P(e)}}),v&&(0,Z.jsx)(D,{title:v,onClose:z,wide:!0,children:(0,Z.jsx)(`pre`,{className:`pl-words`,children:B?JSON.stringify(B,null,2):`Unreadable.`})}),(0,Z.jsx)(O,{undo:o.undo,onUndo:o.undoNow,onDismiss:o.dismiss})]})}var Pa=e=>!e||e.match===null?`—`:e.match?`Match`:`Differs`,Fa={run:`Run`,hand:`Hand`,upload:`Upload`},Ia=e=>e?[e.step,Fa[e.origin.kind]??e.origin.kind,e.at?yi(Date.parse(e.at)/1e3):``].filter(Boolean).join(` · `):`Unreadable`;function La(e){let t=e?.result;return t?`error`in t?t.error.code||`Error`:String(t.status):`—`}var Ra=e=>e.map(e=>({value:e.name,label:e.name})),za=e=>e.from===`trigger`?`Trigger body`:ua(e);function Ba({cfg:e,source:t,steps:n,definition:r,held:i,onClose:a,onRead:o}){let s=(0,J.useMemo)(()=>Ji(e),[e]),c=t.config??{},[l,u]=(0,J.useState)(void 0),[d,f]=(0,J.useState)(n[0]?.name??``),[p,m]=(0,J.useState)(null),[h,g]=(0,J.useState)(``),[_,v]=(0,J.useState)(new Set),[y,b]=(0,J.useState)(``),[x,S]=(0,J.useState)(null),[C,w]=(0,J.useState)(null),[T,E]=(0,J.useState)(null),[O,j]=(0,J.useState)(0);(0,J.useEffect)(()=>{Li(e).then(u,()=>u(null))},[e]),(0,J.useEffect)(()=>{l&&c.environment&&c.flow&&(E(null),s.runs(c.environment,c.flow).then(m,e=>E(Ma(e))))},[l,s,c.environment,c.flow,O]);let M=(0,J.useMemo)(()=>[...new Set((p??[]).map(e=>e.status))].sort(),[p]),P=(0,J.useMemo)(()=>(p??[]).filter(e=>!h||e.status===h),[p,h]),ee=e=>v(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),F=P.length>0&&P.every(e=>_.has(e.id)),I=P.filter(e=>_.has(e.id)).map(e=>e.id),L=async()=>{let e=n.find(e=>e.name===d);if(!e||!c.environment||!c.flow)return;let t=I;w(null),S(`Reading 0 of ${t.length}`);try{let{records:n,skipped:a}=await Ea(s,c.environment,c.flow,t,e,r,i,e=>S(`Reading ${e} of ${t.length}`));await o(n,a)}catch(e){w(Ma(e)),S(null)}};return(0,Z.jsxs)(D,{title:`Import runs`,onClose:a,wide:!0,footer:(0,Z.jsxs)(`div`,{className:`sacts`,children:[x&&(0,Z.jsx)(`span`,{className:`note`,role:`status`,children:x}),(0,Z.jsxs)(`button`,{type:`button`,className:`ghost`,disabled:!!x||!I.length||!d,"aria-busy":!!x||void 0,onClick:()=>void L(),children:[x&&(0,Z.jsx)(W,{}),`Import `,I.length||``]})]}),children:[l===void 0?(0,Z.jsx)(k,{label:`Account`}):l?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(N,{label:`Import`,rows:[{key:`step`,label:`Step`,control:{type:`select`,value:d,options:Ra(n),onChange:f}},{key:`latest`,label:`Latest`,control:{type:`text`,value:y,size:`num`,placeholder:`N`,onChange:e=>{b(e);let t=Number.parseInt(e,10);t>0&&v(new Set(P.slice(0,t).map(e=>e.id)))}}}]}),p?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(z,{noun:`runs`,count:{shown:P.length,total:p.length},lead:(0,Z.jsx)(`input`,{type:`checkbox`,"aria-label":`Select all shown`,checked:F,disabled:!P.length,onChange:()=>v(F?new Set:new Set(P.map(e=>e.id)))}),filters:[{key:`status`,label:`Status`,value:h,onChange:g,options:[{value:``,label:`All`},...M.map(e=>({value:e,label:e}))]}]}),P.length?(0,Z.jsx)(`div`,{className:`sflow`,children:(0,Z.jsx)(A,{className:`slist`,label:`Runs`,rows:P,rowKey:e=>e.id,pageSize:20,rowProps:e=>({onClick:()=>ee(e.id),"data-selected":_.has(e.id)||void 0}),columns:[{key:`pick`,header:``,sort:null,cell:e=>(0,Z.jsx)(`input`,{type:`checkbox`,"aria-label":`Run ${e.id}`,checked:_.has(e.id),onChange:()=>ee(e.id),onClick:e=>e.stopPropagation()})},{key:`start`,header:`Started`,sort:e=>e.startTime??``,cell:e=>e.startTime?yi(Date.parse(e.startTime)/1e3):`—`},{key:`status`,header:`Status`,sort:e=>e.status,cell:e=>e.status}]})}):(0,Z.jsx)(`p`,{className:`note`,children:`No runs.`})]}):(0,Z.jsx)(k,{label:`Runs`,error:T,onRetry:()=>j(e=>e+1)})]}):(0,Z.jsx)(`div`,{className:`sacts`,children:(0,Z.jsxs)(`button`,{type:`button`,className:`ghost`,onClick:()=>{ja(ka,t.id),Vi(e).catch(e=>{ja(ka,null),w(Ma(e))})},children:[(0,Z.jsx)(ft,{size:14,"aria-hidden":`true`}),` Sign in with Microsoft`]})}),C&&(0,Z.jsx)(`p`,{className:`note bad`,role:`alert`,children:C})]})}function Va({steps:e,onClose:t,onAdd:n}){let[r,i]=(0,J.useState)(e[0]?.name??``),[a,o]=(0,J.useState)({}),s=e.find(e=>e.name===r),c=(s?.reads??[]).filter(e=>ua(e));return(0,Z.jsxs)(D,{title:`Add record`,onClose:t,wide:!0,footer:(0,Z.jsx)(`div`,{className:`sacts`,children:(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,disabled:!s,onClick:()=>{if(!s)return;let e=Object.fromEntries(Object.entries(a).filter(([e,t])=>t!==``&&c.some(t=>ua(t)===e))),[t]=fa(s,[e]).records;n({...t,origin:{kind:`hand`}})},children:`Add`})}),children:[(0,Z.jsx)(N,{label:`Record`,rows:[{key:`step`,label:`Step`,control:{type:`select`,value:r,options:Ra(e),onChange:e=>{i(e),o({})}}},...c.map(e=>({key:`read-${ua(e)}`,label:za(e),control:{type:`textarea`,value:a[ua(e)]??``,onChange:t=>o(n=>({...n,[ua(e)]:t}))}}))]}),s&&!c.length&&(0,Z.jsx)(`p`,{className:`note`,children:`Reads nothing.`})]})}function Ha(e,t){if(e.toLowerCase().endsWith(`.csv`))return{rows:pa(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 Ua({steps:e,onClose:t,onRead:n}){let i=(0,J.useRef)(null),[a,o]=(0,J.useState)(e[0]?.name??``),[s,c]=(0,J.useState)(null),[l,u]=(0,J.useState)(null),d=e.find(e=>e.name===a),f=s&&d&&`rows`in s.parsed?fa(d,s.parsed.rows):null,p=s?`records`in s.parsed?s.parsed.records:f?.records??[]:[],m=async e=>{if(e){u(null);try{c({name:e.name,parsed:Ha(e.name,await Oa(e))})}catch(t){c(null),u(`${e.name}: ${Ma(t)}`)}}};return(0,Z.jsxs)(D,{title:`Upload`,onClose:t,wide:!0,footer:(0,Z.jsx)(`div`,{className:`sacts`,children:(0,Z.jsxs)(`button`,{type:`button`,className:`ghost`,disabled:!p.length,onClick:()=>void n(p),children:[`Add `,p.length||``]})}),children:[(0,Z.jsx)(N,{label:`Upload`,rows:[...s&&`records`in s.parsed?[]:[{key:`step`,label:`Step`,control:{type:`select`,value:a,options:Ra(e),onChange:o}}],{key:`file`,label:`File`,control:{type:`static`,text:s?.name??`—`}},...s?[{key:`count`,label:`records`in s.parsed?`Records`:`Rows`,control:{type:`static`,text:String(p.length)}}]:[],...f?.unmatched.length?[{key:`unmatched`,label:`Unmatched`,control:{type:`static`,text:f.unmatched.join(`, `)}}]:[]]}),(0,Z.jsxs)(`div`,{className:`sacts`,children:[(0,Z.jsxs)(`button`,{type:`button`,className:`ghost`,onClick:()=>i.current?.click(),children:[(0,Z.jsx)(r,{size:14,"aria-hidden":`true`}),` Choose file`]}),(0,Z.jsx)(`input`,{ref:i,type:`file`,accept:`.json,.csv`,hidden:!0,"aria-hidden":`true`,onChange:e=>{m(e.target.files?.[0]),e.target.value=``}})]}),l&&(0,Z.jsx)(`p`,{className:`note bad`,role:`alert`,children:l})]})}function Wa({source:e}){let t=Y(),n=qi(),[r,i]=(0,J.useState)(null),[a,o]=(0,J.useState)(null),[s,c]=(0,J.useState)(!1),[l,u]=(0,J.useState)(null),d=e.config??{},f=(0,J.useCallback)(()=>{u(null),t.definition(e.id).then(i,e=>{i(null),u(e instanceof Error?e.message:String(e))})},[t,e.id]);(0,J.useEffect)(f,[f]);let p=async()=>{if(n&&r&&d.environment&&d.flow){c(!0),o(null);try{if(!await Li(n)){await Vi(n);return}let a=await Yi(Ji(n),d.environment,d.flow);i(await t.saveDefinition(e.id,r.version,a.definition)),o(`Synced.`)}catch(e){e instanceof he&&e.status===409?(f(),o(`It changed since: reloaded.`)):o(e instanceof Error?e.message:String(e))}finally{c(!1)}}},m=(0,J.useMemo)(()=>Ga(r?.body),[r]),h=(0,J.useMemo)(()=>oa(r?.body),[r]),[g,_]=ye(`promptlab.workflows`),[v]=ye(`promptlab.profiles`),y=t=>{let n=h.find(e=>e.name===t);if(!n||!r)return;let i=xa({id:e.id,name:e.name},r.body,n,v.list),a={id:i.id,name:i.name,work:i};_({...g,list:[...g.list,a],at:a.id}),location.hash=`#/runs`};return(0,Z.jsxs)(`div`,{className:`sources`,"data-level":`flow`,children:[a&&(0,Z.jsx)(`p`,{className:`note`,role:`status`,children:a}),(0,Z.jsxs)(U,{id:`flow-source`,title:`Flow`,note:d.displayName,actions:[{label:`Re-sync`,icon:vt,busy:s,disabled:!n||!r,onSelect:()=>void p()}],children:[(0,Z.jsx)(N,{label:`Flow`,rows:[{key:`flow`,label:`Flow`,control:{type:`static`,text:d.displayName||d.flow||`—`}},{key:`env`,label:`Environment`,control:{type:`static`,text:d.environment||`—`}},...r?[{key:`version`,label:`Definition`,control:{type:`static`,text:r.version?`Version ${r.version}${r.at?` · ${yi(Date.parse(r.at)/1e3)}`:``}`:`None`}}]:[]]}),!r&&(0,Z.jsx)(k,{label:`Definition`,error:l,onRetry:f})]}),(0,Z.jsx)(Na,{source:e,definition:r?.body??null,cfg:n}),(0,Z.jsx)(U,{id:`flow-actions`,title:`Actions`,note:r?String(m.length):void 0,children:r?m.length?(0,Z.jsx)(`div`,{className:`sflow`,children:(0,Z.jsx)(A,{className:`slist`,label:`Actions`,rows:m,rowKey:e=>e.name,columns:[{key:`name`,header:`Name`,sort:e=>e.name,cell:e=>(0,Z.jsxs)(Z.Fragment,{children:[e.name,e.in&&(0,Z.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`,cell:e=>e.calls||`—`},{key:`menu`,header:``,className:`s-actions`,sort:null,cell:e=>h.some(t=>t.name===e.name)?(0,Z.jsx)(G,{label:`${e.name} actions`,actions:[{label:`New pipeline`,icon:_t,onSelect:()=>y(e.name)}]}):null}]})}):(0,Z.jsx)(`p`,{className:`note`,children:`No actions.`}):(0,Z.jsx)(k,{label:`Actions`,error:l,onRetry:f})})]})}function Ga(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 Ka={"power-automate":{Create:Xi,Level:Wa}};function qa({sourceId:e=null,onOpen:n,mode:a=`browse`,onPick:s,disabled:c}){let l=Y(),u=ne(),[d,f]=(0,J.useState)(null),[m,_]=(0,J.useState)(0),[y,S]=(0,J.useState)(0),[C,w]=(0,J.useState)(null),[T,E]=(0,J.useState)(ci),[j,M]=(0,J.useState)(``),[F,I]=(0,J.useState)(new Set),[L,te]=(0,J.useState)(null),[R,B]=(0,J.useState)(!1),[V,H]=(0,J.useState)(!1),[ie,U]=(0,J.useState)(()=>a===`browse`&&Ya()!==null),[ae,W]=(0,J.useState)(null),[K,q]=(0,J.useState)(null),[oe,se]=(0,J.useState)(!1),[ce,le]=(0,J.useState)(``),[ue,X]=(0,J.useState)(()=>a===`browse`&&Ya()||x().DEFAULT_SOURCE_TYPE),[de,fe]=(0,J.useState)(``),[pe,me]=(0,J.useState)(``),[ge,_e]=(0,J.useState)(null),[ve,ye]=(0,J.useState)([]),[be,xe]=(0,J.useState)(!1),[Se,Ce]=(0,J.useState)(!1),[we,Te]=(0,J.useState)(null),[Ee,De]=(0,J.useState)(null),[Oe,ke]=(0,J.useState)(0),[Ae,je]=(0,J.useState)(0),Me=(0,J.useRef)(null),Ne=(0,J.useRef)(1),{view:Pe,sort:Fe,dir:Ie}=T,Le=(0,J.useCallback)(()=>W(null),[]),Re=(0,J.useCallback)(()=>U(!1),[]),ze=(0,J.useCallback)(()=>q(null),[]),Be=(0,J.useCallback)(()=>se(!1),[]);(0,J.useEffect)(()=>li(T),[T]),(0,J.useEffect)(()=>{a===`browse`&&Xa(ie?ue:null)},[a,ie,ue]);let Ve=async()=>{try{let e=await l.sources();f(e.sources),_(e.cap),S(e.used)}catch{}};(0,J.useEffect)(()=>{let e=!0;return l.sources().then(t=>{e&&(f(t.sources),_(t.cap),S(t.used))}).catch(t=>{e&&Te(We(t))}),()=>{e=!1}},[l,Oe]),(0,J.useEffect)(()=>{I(new Set),ye([]);let t=!0;return De(null),e?l.source(e).then(e=>{t&&w(e)}).catch(e=>{t&&(w(null),De(We(e)))}):w(null),()=>{t=!1}},[e,Ae]);let He=async()=>{if(!e){w(null);return}try{w(await l.source(e))}catch{w(null)}},Ue=e=>{_e(e),e&&window.setTimeout(()=>_e(null),6e3)},We=e=>e instanceof he?e.message:`the request failed`,Ge=_i(gi(C?.files??[],Fe,Ie),j),Ke=e=>{I(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},qe=()=>I(new Set(Ge.map(e=>e.name))),Je=()=>I(new Set),Ye=async e=>{try{let{trash:t}=await l.removeSource(e.id);f(t=>(t??[]).filter(t=>t.id!==e.id)),u.offer({label:`Deleted ${e.name}`,restore:()=>void(async()=>{try{await l.restoreTrash(t),await Ve()}catch(e){Ue(We(e))}})()})}catch(e){Ue(We(e))}},Xe=async e=>{if(C)try{let{trash:t}=await l.removeFiles(C.id,e),n=new Set(e);w(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)}),I(e=>new Set([...e].filter(e=>!n.has(e)))),u.offer({label:e.length===1?`Removed ${e[0]}`:`Removed ${e.length} files`,restore:()=>void(async()=>{try{let e=await l.restoreTrash(t);w(e.source)}catch(e){Ue(We(e))}})()})}catch(e){Ue(We(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;Ce(!0);try{let n=t?await l.file(C.id,t):await l.zip(C.id,e);Ze(n,t??`${C.name}.zip`)}catch(e){Ue(We(e))}finally{Ce(!1)}},$e=async e=>{if(!C||C.system)return;let t=[...e];if(!t.length)return;let n=t.map(e=>({id:Ne.current++,file:e,state:`uploading`}));ye(e=>[...e,...n]);for(let e of n)try{await l.upload(C.id,e.file.name,e.file),ye(t=>t.map(t=>t.id===e.id?{...t,state:`done`}:t))}catch(t){ye(n=>n.map(n=>n.id===e.id?{...n,state:`error`,error:We(t)}:n))}await He()},et=e=>void $e([e.file]),tt=async(e,t)=>{if(C&&K)try{await l.copyFiles(t.id,C.id,K.names,e===`move`),q(null),I(new Set),await He(),Ue(e===`move`?`Moved to ${t.name}.`:`Copied to ${t.name}.`)}catch(e){Ue(We(e)),q(null)}},nt=async()=>{if(C&&ce.trim())try{let e=await l.createSource(ce.trim(),C.type);try{await l.copyFiles(e.id,C.id,[...F],!1)}catch(t){throw await l.removeSource(e.id).catch(()=>{}),t}se(!1),le(``),I(new Set),await Ve(),Ue(`Made a new Source.`)}catch(e){Ue(We(e))}},rt=async()=>{if(ce.trim())try{await l.createSource(ce.trim(),ue),U(!1),le(``),X(x().DEFAULT_SOURCE_TYPE),await Ve()}catch(e){Ue(We(e))}},it=async(e,t)=>{try{let n=await l.renameSource(e.id,t);f(t=>(t??[]).map(t=>t.id===e.id?bi(n):t)),w(e=>e?.id===n.id?{...e,name:n.name}:e)}catch(e){Ue(We(e))}},ot=(e,n=()=>te(e.id),r)=>e.system?[]:[{label:`Rename`,icon:t,onSelect:n},{label:`Delete`,icon:b,destructive:!0,onSelect:()=>void Ye(e).then(r)}],ct=e=>[{label:`Preview`,icon:p,disabled:!pi(e.name),onSelect:()=>W(e)},{label:`Download`,icon:g,onSelect:()=>void Qe([e.name])},...C?.system?[]:[{label:`Remove`,icon:b,destructive:!0,onSelect:()=>void Xe([e.name])}]],lt=[...C?.system?[]:[{label:`Remove`,icon:b,destructive:!0,onSelect:()=>void Xe([...F])}],{label:`Download`,icon:g,busy:Se,onSelect:()=>void Qe([...F])},...C?.system?[]:[{label:`Move to…`,icon:at,onSelect:()=>q({kind:`move`,names:[...F]})}],{label:`Copy to…`,icon:o,onSelect:()=>q({kind:`copy`,names:[...F]})},...C?.system?[]:[{label:`New Source from selection`,icon:st,onSelect:()=>se(!0)}]],ut=e=>{e.preventDefault(),xe(!1),C&&!C.system&&$e(e.dataTransfer.files)},dt=(d??[]).filter(e=>(!pe||e.type===pe)&&e.name.toLowerCase().includes(de.trim().toLowerCase())),ft=(0,Z.jsx)(z,{noun:`Sources`,search:{label:`Find a Source`,value:de,placeholder:`Name`,onChange:fe},filters:[{key:`type`,label:`Type`,value:pe,onChange:me,options:[{value:``,label:`All`},...ao()]}],count:{shown:dt.length,total:(d??[]).length}}),pt=()=>(0,Z.jsxs)(`div`,{className:`sources`,"data-level":`sources`,children:[ge&&(0,Z.jsx)(`p`,{className:`note`,role:`status`,children:ge}),(0,Z.jsxs)(`header`,{className:`shead`,children:[(0,Z.jsx)(`h2`,{className:`shead-title`,children:`Sources`}),(0,Z.jsx)(Qa,{view:Pe,onChange:e=>E(t=>({...t,view:e}))})]}),d!==null&&d.length>0&&ft,d===null?(0,Z.jsx)(k,{label:`Sources`,error:we,onRetry:()=>{Te(null),ke(e=>e+1)}}):d.length===0?(0,Z.jsx)(`p`,{className:`note`,children:`No Sources on the server yet.`}):Pe===`thumbs`?(0,Z.jsx)(`ul`,{className:`sfolders`,children:dt.map(e=>(0,Z.jsx)(`li`,{className:`sfolder`,children:(0,Z.jsxs)(`button`,{type:`button`,className:`sfolder-open${c?.(e)?` off`:``}`,disabled:c?.(e),onClick:()=>s?.(e),children:[(0,Z.jsx)(to,{}),(0,Z.jsx)(`span`,{className:`sfolder-name`,children:e.name}),(0,Z.jsxs)(`span`,{className:`sfolder-meta`,children:[oo(e),` · `,so(e)]})]})},e.id))}):(0,Z.jsx)(A,{className:`slist slist-folders`,label:`Sources`,rows:dt,rowKey:e=>e.id,columns:[{key:`name`,header:`Name`,className:`sfile-name`,sort:e=>e.name,cell:e=>(0,Z.jsxs)(`button`,{type:`button`,className:`srow-pick${c?.(e)?` off`:``}`,disabled:c?.(e),onClick:()=>s?.(e),children:[(0,Z.jsx)(to,{}),` `,e.name]})},{key:`type`,header:`Type`,sort:e=>oo(e),cell:e=>oo(e)},{key:`files`,header:`Items`,cell:e=>e.files},{key:`size`,header:`Size`,sort:e=>e.bytes,cell:e=>vi(e.bytes)}]})]});if(a===`pick`)return pt();if(e){if(!C)return(0,Z.jsx)(`div`,{className:`sources`,children:(0,Z.jsx)(k,{label:`Files`,error:Ee,onRetry:()=>je(e=>e+1)})});let e=Ka[C.type]?.Level,t=!e&&!C.system,a=()=>n?.(null),o=(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(ee,{kind:`Source`,name:C.name,crumb:{label:`Sources`,onClick:a},onPick:d?.length?()=>H(!0):void 0,meta:[oo(bi(C)),so(bi(C)),vi(C.bytes)].join(` · `),primary:t?{label:`Upload`,icon:r,onSelect:()=>Me.current?.click()}:void 0,actions:ot(bi(C),()=>B(!0),a)}),V&&d&&(0,Z.jsx)(P,{kind:`Source`,value:C.id,onPick:e=>n?.(e),onClose:()=>H(!1),options:d.map(e=>({id:e.id,label:e.name}))}),R&&(0,Z.jsx)(re,{title:`Rename Source`,value:C.name,onCommit:e=>{e&&e!==C.name&&it(C,e)},onClose:()=>B(!1)})]});return e?(0,Z.jsxs)(`div`,{className:`sources`,children:[o,(0,Z.jsx)(e,{source:C,onBack:a}),(0,Z.jsx)(O,{undo:u.undo,onUndo:u.undoNow,onDismiss:u.dismiss})]}):(0,Z.jsxs)(`div`,{className:`sources`,"data-level":`files`,children:[o,ge&&(0,Z.jsx)(`p`,{className:`note`,role:`status`,children:ge}),(0,Z.jsxs)(`header`,{className:`shead`,children:[(0,Z.jsx)(Qa,{view:Pe,onChange:e=>E(t=>({...t,view:e}))}),(0,Z.jsx)($a,{sort:Fe,dir:Ie,onChange:(e,t)=>E(n=>({...n,sort:e,dir:t}))}),(0,Z.jsxs)(`label`,{className:`sfilter`,children:[(0,Z.jsx)(i,{size:14,"aria-hidden":`true`}),(0,Z.jsx)(`input`,{type:`search`,"aria-label":`Filter by name`,placeholder:`Filter`,value:j,onChange:e=>M(e.target.value)})]})]}),F.size>0&&(0,Z.jsxs)(`div`,{className:`sselect`,"data-selected":F.size,children:[(0,Z.jsxs)(`span`,{className:`sselect-count`,children:[F.size,` selected`]}),(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,onClick:qe,children:`Select all`}),(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,onClick:Je,children:`None`}),(0,Z.jsx)(G,{label:`Selection actions`,actions:lt})]}),(0,Z.jsx)(`div`,{className:`sfiles${be?` drag`:``}`,onDragOver:e=>{e.preventDefault(),xe(!0)},onDragLeave:()=>xe(!1),onDrop:ut,children:Ge.length===0?(0,Z.jsx)(`p`,{className:`note`,children:j?`No files match that name.`:`No files in this Source yet.`}):Pe===`thumbs`?(0,Z.jsx)(`ul`,{className:`stiles`,children:Ge.map(e=>(0,Z.jsx)(`li`,{children:(0,Z.jsxs)(`button`,{type:`button`,className:`stile${F.has(e.name)?` sel`:``}`,"aria-pressed":F.has(e.name),"aria-label":e.name,onClick:()=>Ke(e.name),children:[(0,Z.jsx)(Za,{id:C.id,file:e}),(0,Z.jsx)(`span`,{className:`stile-name`,children:e.name}),F.has(e.name)&&(0,Z.jsx)(`span`,{className:`stile-check`,children:(0,Z.jsx)(v,{size:12,"aria-hidden":`true`})})]})},e.name))}):(0,Z.jsx)(A,{className:`slist`,label:`${C.name} files`,rows:Ge,rowKey:e=>e.name,rowProps:e=>({className:F.has(e.name)?`sel`:void 0,"data-selected":F.has(e.name)||void 0,onClick:()=>Ke(e.name)}),columns:[{key:`name`,header:`Name`,className:`sfile-name`,cell:e=>e.name},{key:`type`,header:`Type`,className:`stype`,cell:e=>eo(e.name)},{key:`size`,header:`Size`,sort:e=>e.bytes,cell:e=>vi(e.bytes)},{key:`added`,header:`Added`,sort:e=>e.added,cell:e=>e.added?yi(e.added):`—`},{key:`menu`,header:``,className:`s-actions`,sort:null,tdProps:()=>({onClick:e=>e.stopPropagation()}),cell:e=>(0,Z.jsx)(G,{label:`${e.name} actions`,actions:ct(e)})}]})}),t&&(0,Z.jsxs)(`div`,{className:`supload`,children:[(0,Z.jsx)(`input`,{ref:Me,type:`file`,multiple:!0,hidden:!0,"aria-hidden":`true`,accept:x().sourceTypeOf(C)?.uploads?.join(`,`),onChange:e=>{e.target.files&&$e(e.target.files),e.target.value=``}}),ve.length>0&&(0,Z.jsx)(`ul`,{className:`suploads`,children:ve.map(e=>(0,Z.jsxs)(`li`,{className:`supload ${e.state}`,children:[(0,Z.jsx)(`span`,{className:`supload-name`,children:e.file.name}),e.state===`uploading`&&(0,Z.jsx)(`span`,{className:`supload-bar`,role:`status`,children:`Uploading…`}),e.state===`done`&&(0,Z.jsx)(`span`,{className:`note`,children:`Uploaded`}),e.state===`error`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`note bad`,children:e.error}),(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>et(e),children:`Retry`})]})]},e.id))})]}),ae&&(0,Z.jsxs)(D,{title:ae.name,onClose:Le,children:[pi(ae.name)?(0,Z.jsx)(`img`,{className:`spreview-img`,src:hi(C.id,ae),alt:ae.name}):null,(0,Z.jsx)(`p`,{className:`note`,children:vi(ae.bytes)})]}),K&&(0,Z.jsx)(D,{title:K.kind===`move`?`Move to…`:`Copy to…`,onClose:ze,children:(0,Z.jsx)(qa,{mode:`pick`,disabled:e=>e.id===C.id||e.system||e.type!==C.type,onPick:e=>void tt(K.kind,e)})}),oe&&(0,Z.jsxs)(D,{title:`New Source from selection`,onClose:Be,children:[(0,Z.jsxs)(`label`,{className:`prompt`,children:[(0,Z.jsx)(`span`,{className:`prop-name`,children:`Name`}),(0,Z.jsx)(`input`,{"aria-label":`New Source name`,value:ce,autoFocus:!0,onChange:e=>le(e.target.value),onKeyDown:e=>{e.key===`Enter`&&nt()}})]}),(0,Z.jsxs)(`div`,{className:`sacts`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,disabled:!ce.trim(),onClick:()=>void nt(),children:`Make`}),(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>se(!1),children:`Close`})]})]}),(0,Z.jsx)(O,{undo:u.undo,onUndo:u.undoNow,onDismiss:u.dismiss})]})}return(0,Z.jsxs)(`div`,{className:`sources`,"data-level":`sources`,children:[ge&&(0,Z.jsx)(`p`,{className:`note`,role:`status`,children:ge}),(0,Z.jsxs)(`header`,{className:`shead`,children:[(0,Z.jsx)(`h2`,{className:`shead-title`,children:`Sources`}),(0,Z.jsxs)(`p`,{className:`note suste`,children:[`Used `,vi(y),` of `,vi(m)]}),(0,Z.jsx)(Qa,{view:Pe,onChange:e=>E(t=>({...t,view:e}))})]}),d!==null&&d.length>0&&ft,d===null?(0,Z.jsx)(k,{label:`Sources`,error:we,onRetry:()=>{Te(null),ke(e=>e+1)}}):d.length===0?(0,Z.jsx)(`p`,{className:`note`,children:`No Sources yet — Add source below.`}):Pe===`thumbs`?(0,Z.jsx)(`ul`,{className:`sfolders`,children:dt.map(e=>(0,Z.jsxs)(`li`,{className:`sfolder`,children:[(0,Z.jsxs)(`button`,{type:`button`,className:`sfolder-open`,onClick:()=>n?.(e.id),children:[(0,Z.jsx)(to,{}),(0,Z.jsx)(`span`,{className:`sfolder-name`,children:e.name}),(0,Z.jsxs)(`span`,{className:`sfolder-meta`,children:[oo(e),` · `,so(e)]}),(0,Z.jsx)(io,{source:e,cap:m,children:e.system?(0,Z.jsx)(`span`,{className:`squota-none`,children:`—`}):(0,Z.jsx)(`span`,{className:`squota-bar`,children:(0,Z.jsx)(`span`,{className:`squota-fill`,style:{width:`${no(e.bytes,m)}%`}})})})]}),(0,Z.jsx)(`span`,{className:`sfolder-menu`,children:(0,Z.jsx)(G,{label:`${e.name} actions`,actions:ot(e)})})]},e.id))}):(0,Z.jsx)(`div`,{className:`sfiles`,children:(0,Z.jsx)(A,{className:`slist slist-folders`,label:`Sources`,rows:dt,rowKey:e=>e.id,rowProps:e=>({"data-open":e.id,onClick:()=>n?.(e.id)}),columns:[{key:`name`,header:`Name`,className:`sfile-name`,sort:e=>e.name,cell:e=>(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(to,{}),` `,e.name]})},{key:`type`,header:`Type`,sort:e=>oo(e),cell:e=>oo(e)},{key:`files`,header:`Items`,cell:e=>e.files},{key:`size`,header:`Size`,sort:e=>e.bytes,cell:e=>vi(e.bytes)},{key:`used`,header:`Used`,sort:e=>e.system?null:e.bytes,cell:e=>(0,Z.jsx)(io,{source:e,cap:m,children:e.system?`—`:`${no(e.bytes,m)}%`})},{key:`menu`,header:``,className:`s-actions`,sort:null,tdProps:()=>({onClick:e=>e.stopPropagation()}),cell:e=>(0,Z.jsx)(G,{label:`${e.name} actions`,actions:ot(e)})}]})}),L&&d&&(()=>{let e=d.find(e=>e.id===L);return e?(0,Z.jsxs)(`label`,{className:`srename`,children:[(0,Z.jsxs)(`span`,{className:`prop-name`,children:[`Rename `,e.name]}),(0,Z.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),te(null)}t.key===`Escape`&&te(null)},onBlur:t=>{let n=t.target.value.trim();n&&n!==e.name&&it(e,n),te(null)}})]}):null})(),(0,Z.jsxs)(`button`,{type:`button`,className:`ghost add-btn`,onClick:()=>U(!0),children:[(0,Z.jsx)(h,{size:14,"aria-hidden":`true`}),` Add source`]}),ie&&(0,Z.jsxs)(D,{title:`Add source`,onClose:Re,children:[(0,Z.jsx)(N,{label:`New Source`,rows:[{key:`type`,label:`Type`,hint:x().SOURCE_TYPES[ue]?.description,control:{type:`select`,value:ue,options:ao(),onChange:X}}]}),(()=>{let e=Ka[ue]?.Create,t=(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>U(!1),children:`Close`});return e?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(e,{onMade:async()=>{U(!1),X(x().DEFAULT_SOURCE_TYPE),await Ve()}}),(0,Z.jsx)(`div`,{className:`sacts`,children:t})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`label`,{className:`prompt`,children:[(0,Z.jsx)(`span`,{className:`prop-name`,children:`Name`}),(0,Z.jsx)(`input`,{"aria-label":`Source name`,value:ce,autoFocus:!0,onChange:e=>le(e.target.value),onKeyDown:e=>{e.key===`Enter`&&rt()}})]}),(0,Z.jsxs)(`div`,{className:`sacts`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,disabled:!ce.trim(),onClick:()=>void rt(),children:`Add`}),t]})]})})()]}),(0,Z.jsx)(O,{undo:u.undo,onUndo:u.undoNow,onDismiss:u.dismiss})]})}var Ja=`evals-lab.sources.adding`;function Ya(){try{return sessionStorage.getItem(Ja)}catch{return null}}function Xa(e){try{e?sessionStorage.setItem(Ja,e):sessionStorage.removeItem(Ja)}catch{}}function Za({id:e,file:t}){let[n,r]=(0,J.useState)(!1);return!t.thumb||n?(0,Z.jsx)(`span`,{className:`stile-type`,children:eo(t.name)||`FILE`}):(0,Z.jsx)(`img`,{className:`stile-img`,src:mi(e,t),alt:``,loading:`lazy`,onError:()=>r(!0)})}function Qa({view:e,onChange:t}){return(0,Z.jsxs)(`div`,{className:`sview`,role:`group`,"aria-label":`View`,children:[(0,Z.jsx)(`button`,{type:`button`,className:e===`thumbs`?`on`:void 0,"aria-pressed":e===`thumbs`,onClick:()=>t(`thumbs`),children:`Thumbnails`}),(0,Z.jsx)(`button`,{type:`button`,className:e===`list`?`on`:void 0,"aria-pressed":e===`list`,onClick:()=>t(`list`),children:`List`})]})}function $a({sort:e,dir:t,onChange:r}){return(0,Z.jsxs)(`div`,{className:`ssort`,role:`group`,"aria-label":`Sort`,children:[(0,Z.jsxs)(`select`,{"aria-label":`Sort by`,value:e,onChange:e=>r(e.target.value,t),children:[(0,Z.jsx)(`option`,{value:`name`,children:`Name`}),(0,Z.jsx)(`option`,{value:`added`,children:`Date added`}),(0,Z.jsx)(`option`,{value:`size`,children:`Size`})]}),(0,Z.jsx)(`button`,{type:`button`,className:`icon-btn`,"aria-label":`Sort ${t===1?`ascending`:`descending`}`,onClick:()=>r(e,t===1?-1:1),children:(0,Z.jsx)(t===1?K:n,{size:14,"aria-hidden":`true`})})]})}function eo(e){let t=e.lastIndexOf(`.`);return t<0?``:e.slice(t+1).toUpperCase()}function to(){return(0,Z.jsx)(ct,{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 ro(e,t){return e.system?`Quota: not counted`:`Quota: ${vi(e.bytes)} of ${vi(t)}`}function io({source:e,cap:t,children:n}){let r=ro(e,t);return(0,Z.jsxs)(`span`,{className:`squota`,role:`img`,"aria-label":r,children:[n,(0,Z.jsx)(`span`,{className:`squota-pop`,"aria-hidden":`true`,children:r})]})}var ao=()=>Object.entries(x().SOURCE_TYPES).map(([e,t])=>({value:e,label:t.label})),oo=e=>x().SOURCE_TYPES[e.type]?.label??e.type,so=e=>{let t=x().sourceTypeOf(e)?.noun??`item`;return`${e.files} ${e.files===1?t:`${t}s`}`};function co({sourceId:e}){let[t,n]=(0,J.useState)(e);return(0,J.useEffect)(()=>n(e),[e]),(0,Z.jsx)(qa,{sourceId:t,onOpen:e=>{n(e),e?location.hash=`/library/sources/${encodeURIComponent(e)}`:location.hash=`#/library/sources`}})}var lo=[{id:`datasets`,label:`Datasets`,icon:$e},{id:`prompts`,label:`Prompts`,icon:mt},{id:`sources`,label:`Sources`,icon:ot}];function uo({section:e,sourceId:t}){return(0,Z.jsxs)(`div`,{className:`library`,children:[(0,Z.jsx)(`nav`,{className:`lib-sections`,"aria-label":`Library`,children:lo.map(({id:t,label:n,icon:r})=>(0,Z.jsxs)(`a`,{href:`#/library/${t}`,...t===e?{"aria-current":`page`}:{},className:t===e?`on`:void 0,children:[(0,Z.jsx)(r,{size:16,"aria-hidden":`true`}),(0,Z.jsx)(`span`,{children:n})]},t))}),(0,Z.jsx)(`section`,{className:`lib-section`,"data-section":e,children:e===`datasets`?(0,Z.jsx)(Jr,{}):e===`prompts`?(0,Z.jsx)(ai,{}):(0,Z.jsx)(co,{sourceId:t})})]})}var fo=`0.3.0 (2026.10.02-355)`,po=3,mo=3,ho=e=>fr.find(t=>t.id===e),go=e=>lo.find(t=>t.id===e),_o=e=>new Date(e).toLocaleString(void 0,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`});function vo(){let e=Y(),[t]=ye(`promptlab.profiles`),[n,r]=ye(`promptlab.workflows`),i=Le(),a=qe(),{pickDataset:o}=Gt(),{openRun:s}=Jt(),c=Ie(),l=Ke(),[u,d]=(0,J.useState)(null),[f,p]=(0,J.useState)(null),[m,h]=(0,J.useState)(null),[g,_]=(0,J.useState)(null),[v,y]=(0,J.useState)(0),[b,x]=(0,J.useState)(0),S=e=>e instanceof Error?e.message:String(e);(0,J.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,J.useEffect)(()=>{let t=!0;return _(null),e.queue({limit:mo}).then(e=>{t&&p(e.runs)},e=>{t&&_(S(e))}),()=>{t=!1}},[e,b]);let C=(0,J.useMemo)(()=>n.list.filter(e=>e.work?.version===12),[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=ho(`library`),A=k.icon;return(0,Z.jsxs)(`div`,{className:`home`,children:[(0,Z.jsxs)(`ol`,{className:`home-line`,"aria-label":`Lab`,children:[(0,Z.jsx)(yo,{id:`runs`,icon:ho(`runs`).icon,name:ho(`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,Z.jsx)(yo,{id:`history`,icon:ho(`history`).icon,name:ho(`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=Un(e).scenarios.map(e=>e.percent==null?`–`:`${e.percent}%`).join(` · `);return{key:e.id,label:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`code`,{children:un(e.submittedAt)}),e.status!==`done`&&_n(e.status)]}),sub:O(_o(e.submittedAt),!!t&&t),href:`#/history`,onOpen:()=>s(e.id,{at:e.submittedAt,from:`home`})}})}),(0,Z.jsxs)(`li`,{className:`home-stop home-fork`,"data-stop":`library`,children:[(0,Z.jsxs)(`a`,{className:`home-name`,href:`#/library`,children:[(0,Z.jsx)(`span`,{className:`home-mark`,"aria-hidden":`true`,children:(0,Z.jsx)(A,{size:18})}),k.label]}),(0,Z.jsxs)(`ol`,{className:`home-branch`,"aria-label":k.label,children:[(0,Z.jsx)(yo,{id:`datasets`,to:`library/datasets`,branch:!0,icon:go(`datasets`).icon,name:go(`datasets`).label,start:D===`datasets`,fact:i.list?O(dn(w.length,`dataset`),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`,onPick:()=>o(e.id)}))}),(0,Z.jsx)(yo,{id:`prompts`,to:`library/prompts`,branch:!0,icon:go(`prompts`).icon,name:go(`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(`
|
|
10
|
+
`)[0]||`Untitled`,sub:e.default?`Default`:void 0,href:`#/library/prompts`}))}),(0,Z.jsx)(yo,{id:`sources`,to:`library/sources`,branch:!0,icon:go(`sources`).icon,name:go(`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,Z.jsx)(yo,{id:`setup`,icon:ho(`setup`).icon,name:ho(`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,Z.jsxs)(`p`,{className:`home-version`,children:[`Evals Lab `,fo]})]})}function yo({id:e,icon:t,name:n,to:r,fact:i,items:a,total:o=a.length,hub:s,start:c,branch:l,wait:u}){let d=o-Math.min(a.length,po);return(0,Z.jsxs)(`li`,{className:[`home-stop`,s&&`hub`,c&&`start`,l&&`branch`].filter(Boolean).join(` `),"data-stop":e,children:[(0,Z.jsxs)(`a`,{className:`home-name`,href:`#/${r??e}`,children:[(0,Z.jsx)(`span`,{className:`home-mark`,"aria-hidden":`true`,children:(0,Z.jsx)(t,{size:l?15:18})}),n]}),c&&(0,Z.jsx)(`span`,{className:`home-start`,children:`Start Here`}),u&&(0,Z.jsx)(k,{label:n,error:u.error,onRetry:u.onRetry}),!u&&i&&(0,Z.jsx)(`span`,{className:`home-fact`,children:i}),!u&&a.length>0&&(0,Z.jsxs)(`ul`,{className:`home-items`,children:[a.slice(0,po).map(e=>(0,Z.jsx)(`li`,{children:(0,Z.jsxs)(`a`,{href:e.href,onClick:t=>{e.onOpen?(t.preventDefault(),e.onOpen()):e.onPick?.()},children:[(0,Z.jsx)(`span`,{className:`home-item`,children:e.label}),e.sub&&(0,Z.jsx)(`span`,{className:`home-sub`,children:e.sub})]})},e.key)),d>0&&(0,Z.jsx)(`li`,{children:(0,Z.jsxs)(`a`,{className:`home-more`,href:`#/${r??e}`,children:[d,` more`]})})]})]})}function bo({list:e,at:n,canRestore:i,onSelect:a,onNew:s,onClone:c,onRename:l,onDelete:u,onRestore:d,onExport:f,onImport:p}){let[m,_]=(0,J.useState)(!1),[v,y]=(0,J.useState)(!1),x=e.find(e=>e.id===n),S=[{label:`Rename`,icon:t,onSelect:()=>_(!0)},{label:`Clone`,icon:o,onSelect:c},{label:`Export YAML`,icon:g,onSelect:f},{label:`Import YAML…`,icon:r,onSelect:p},{label:`Restore…`,icon:I,disabled:!i,onSelect:d},{label:`Delete`,icon:b,destructive:!0,onSelect:u}],C=x?.work.jobs?.length??0,w=x?.work.targets?.length??0;return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(ee,{kind:`Pipeline`,name:x?.name?.trim()||`Untitled`,onPick:()=>y(!0),meta:`${xo(C,`job`)} · ${xo(w,`Target`)}`,primary:{label:`New pipeline`,icon:h,onSelect:s},actions:S}),v&&(0,Z.jsx)(P,{kind:`Pipeline`,value:n,onPick:a,onClose:()=>y(!1),options:e.map(e=>({id:e.id,label:e.name||`Untitled`}))}),m&&(0,Z.jsx)(re,{title:`Rename pipeline`,value:x?.name??``,onCommit:l,onClose:()=>_(!1)})]})}var xo=(e,t)=>`${e} ${e===1?t:`${t}s`}`;function So({problems:e,error:t,run:n,submitting:r,onRun:i,onStop:a,onOpen:o}){let s=!!n&&!kn(n.status),c=n?.progress?.total??0,l=n?.progress?.n??0,u=s&&c?Math.round(l/c*100):null,d=n&&(0,Z.jsxs)(`button`,{type:`button`,className:`runbar-open`,title:`Open this run`,onClick:o,children:[(0,Z.jsx)(`span`,{className:`runbar-word`,children:gn(n.status)}),Co(n)&&(0,Z.jsx)(`span`,{className:`runbar-detail`,children:Co(n)})]}),f=s?d:e.length?(0,Z.jsxs)(`span`,{className:`runbar-why`,children:[Eo(e[0]),To(e[0])]}):t?(0,Z.jsx)(`span`,{className:`runbar-why bad`,children:Eo(t)}):d??(0,Z.jsx)(`span`,{className:`runbar-why`,children:`Ready to run.`});return(0,Z.jsxs)(`div`,{className:`runbar`,children:[(0,Z.jsxs)(`div`,{className:`runbar-row`,children:[(0,Z.jsxs)(`button`,{type:`button`,className:`run`,disabled:e.length>0||r,"aria-busy":r||void 0,onClick:i,children:[r?(0,Z.jsx)(W,{size:16}):(0,Z.jsx)(_t,{size:16,"aria-hidden":`true`}),`Run`]}),(0,Z.jsx)(`span`,{className:`runbar-line`,role:`status`,children:f}),s&&(0,Z.jsxs)(`button`,{type:`button`,className:`ghost runbar-stop`,onClick:a,children:[(0,Z.jsx)(Ze,{size:14,"aria-hidden":`true`}),`Stop`]})]}),u!=null&&(0,Z.jsx)(`div`,{className:`runbar-meter`,role:`progressbar`,"aria-label":`Run progress`,"aria-valuenow":u,"aria-valuemin":0,"aria-valuemax":100,children:(0,Z.jsx)(`div`,{className:`runbar-fill`,style:{width:`${u}%`}})})]})}function Co(e){return e.status===`queued`?e.behind?`behind ${e.behind}`:`next in line`:e.status===`running`&&e.progress?.total?`${e.progress.n} of ${e.progress.total}`:``}var wo=[[/^Target profile .* not found$/,`#/setup`,`Open Setup`],[/^Source .* not found$/,`#/library/sources`,`Open Sources`],[/^Dataset .* not found$/,`#/library/datasets`,`Open Datasets`]];function To(e){let t=wo.find(([t])=>t.test(e.trim()));return t?(0,Z.jsxs)(Z.Fragment,{children:[` `,(0,Z.jsx)(`a`,{className:`runbar-fix`,href:t[1],children:t[2]})]}):null}var Eo=e=>{let t=e.trim();if(!t)return t;let n=t[0].toUpperCase()+t.slice(1);return/[.!?]$/.test(n)?n:`${n}.`},Do=10;function Oo({onPick:e,onClose:t,used:n}){let{list:r,error:i}=qe(),a=Ke(),[o,s]=(0,J.useState)(``),[c,l]=(0,J.useState)(`all`),[u,d]=(0,J.useState)(0),f=r??[],p=f.filter(e=>ni(e,o,c,n??{byScenario:new Set,byAll:new Set})).sort((e,t)=>Number(t.default)-Number(e.default)),m=Math.ceil(p.length/Do),h=Math.min(u,Math.max(0,m-1)),g=p.slice(h*Do,(h+1)*Do);return(0,Z.jsxs)(D,{title:`Select prompt`,onClose:t,className:`sp`,initialFocus:`.sp input[type=search]`,children:[(0,Z.jsx)(z,{noun:`prompts`,search:{label:`Search prompts`,placeholder:`Search prompts`,value:o,onChange:e=>{s(e),d(0)}},filters:[{key:`show`,label:`Show`,value:c,onChange:e=>{l(e),d(0)},options:ei}],count:{shown:p.length,total:f.length}}),r===null?(0,Z.jsx)(k,{label:`Prompts`,error:i,onRetry:()=>void a.refresh()}):f.length===0?(0,Z.jsx)(`p`,{className:`note`,children:`No prompts yet.`}):p.length===0?(0,Z.jsx)(`p`,{className:`note`,children:`No prompts match these filters.`}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`ul`,{className:`sp-list`,"aria-label":`Prompts`,children:g.map(t=>(0,Z.jsx)(`li`,{children:(0,Z.jsxs)(`button`,{type:`button`,className:`sp-pick`,onClick:()=>e(t),children:[(0,Z.jsxs)(`span`,{className:`sp-head`,children:[(0,Z.jsx)(`span`,{className:`sp-title`,children:ze(t)}),t.default&&(0,Z.jsx)(`span`,{className:`pl-default`,children:`Default`})]}),(0,Z.jsx)(`span`,{className:`sp-text`,children:t.text.trim()||`—`}),(0,Z.jsxs)(`span`,{className:`sp-meta`,children:[(0,Z.jsx)(`span`,{children:t.useCount===1?`1 use`:`${t.useCount} uses`}),t.lastUsed&&(0,Z.jsxs)(`span`,{children:[`last `,ri(t.lastUsed)]}),(0,Z.jsxs)(`span`,{children:[`v`,t.version]})]})]})},t.id))}),m>1&&(0,Z.jsxs)(`div`,{className:`sp-pager`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,disabled:h===0,onClick:()=>d(h-1),children:`Back`}),(0,Z.jsxs)(`span`,{className:`sp-page`,children:[h+1,` of `,m]}),(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,disabled:h>=m-1,onClick:()=>d(h+1),children:`Forward`})]})]})]})}function ko(e){let t=x(),n=e.jobs.at(-1),r=s(t.defaultKind()),i=t.outOf(n),a=t.outOf(r),o=e=>!B(e.type)||B(e.type).includes(a.kind),c=i.modifiers.filter(o);return c.length&&(r=t.withOut(r,{...a,modifiers:c})),os(e,[...e.jobs.slice(0,-1),t.withOut(n,{...i,modifiers:i.modifiers.filter(e=>!o(e))}),r],()=>({type:`prompt`,prompt:``}))}function Ao(e,t){if(e.jobs.length<2)return e;let n=e.jobs.slice();if(t===n.length-1){let e=x(),r=e.outOf(n[t]),i=e.outOf(n[t-1]),a=r.modifiers.filter(e=>!B(e.type)||B(e.type).includes(i.kind)),o=[...i.modifiers,...a];n[t-1]=e.withOut(n[t-1],{...i,modifiers:o.length?o:C(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 jo(e,t){let n={...structuredClone(e.jobs[t]),id:x().newId()};n.name=`${x().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 Mo(e,t,n){let r=e.jobs.map((e,r)=>r===t?{...e,name:n.trim()}:e);return{...e,jobs:r}}function No(e,t,n){let r=x().outOf(e.jobs[t]);if(r.kind===n||!n)return e;let i=t===e.jobs.length-1,a=r.modifiers.filter(e=>!B(e.type)||B(e.type).includes(n));return{...e,jobs:e.jobs.map((e,r)=>r===t?x().withOut(e,{kind:n,...d(n),modifiers:i?a.length?a:C(n):[]}):e)}}var Po=(e,t)=>({...e,evals:[...e.evals,t]}),Fo=(e,t)=>({...e,evals:e.evals.filter((e,n)=>n!==t)});function Io(e,t,n){let r=t+n;if(r<0||r>=e.evals.length)return e;let i=e.evals.slice();return[i[t],i[r]]=[i[r],i[t]],{...e,evals:i}}var Lo=(e,t,n)=>({...e,evals:e.evals.map((e,r)=>r===t?{...e,name:n.trim()}:e)}),Ro=(e,t,n)=>({...e,evals:e.evals.map((e,r)=>r===t?n:e)}),zo=e=>e[0]?{id:e[0].id,name:e[0].name}:{id:``,name:``};function Bo(e,t,n=``){let r=x(),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 Vo(e){let t=new Set(e.map(e=>e.trim().toLowerCase())),n=1;for(;t.has(`pipeline ${n}`);)n+=1;return`Pipeline ${n}`}var Ho={id:`samples`,name:`Sample library`};function Uo(e,t,n=``){let r=x().withContent({...x().blankPipeline({name:Vo([])}),evals:t?[x().newEval(`metrics`,``,{dataset:{id:t.id,name:t.name},metrics:[]})]:[]},{type:`source`,ref:{...Ho},first:null,loops:1});if(t){let e=x();r={...r,jobs:[e.withTokens(e.withOut(r.jobs[0],{kind:`list`,...d(`list`),modifiers:[{type:`tidy`},{type:`dedupe`}]}),e.mappingsFor(n))]}}return r=Bo(r,e,n),Bo(r,e,n)}function Wo(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 Go(e,t){let n={...structuredClone(e.targets[t]),id:x().newId(),name:`${x().targetLabel(e,t)} copy`};return{...e,targets:[...e.targets.slice(0,t+1),n,...e.targets.slice(t+1)]}}function Ko(e,t){return{...e,targets:e.targets.filter((e,n)=>n!==t)}}function qo(e,t,n){return{...e,targets:e.targets.map((e,r)=>r===t?{...e,name:n.trim()}:e)}}function Jo(e,t,n,r){return n===0?{...e,targets:e.targets.map((e,n)=>n===t?{...e,profile:r??e.profile}:e)}:x().withTarget(e,t,n,e=>{if(r)return{...e,profile:r};let{profile:t,...n}=e;return n})}function Yo(e,t,n,r){return x().withTarget(e,t,n,{prompt:r})}function Xo(e,t,n,r,i){return x().withTarget(e,t,n,{prompt:r,from:{...i}})}function Zo(e,t){return new Set(e.jobs.flatMap((n,r)=>x().targetStepOf(e,t,r)?.from?.id??[]))}function Qo(e){let t=x().targetsOf(e).length,n=Zo(e,0);for(let r=1;r<t;r++){let t=Zo(e,r);for(let e of[...n])t.has(e)||n.delete(e)}return n}function $o(e,t,n,r){return as(e,t,e=>e.map(e=>e.name===n?{...e,...r}:e))}function es(e,t,n,r){let i=n.trim();return i?as(e,t,e=>e.some(e=>e.name===i)?e:[...e,x().tokenMapping(i,r)]):e}function ts(e,t,n,r){let i=r.name.trim();return i?as(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}:x().tokenMapping(i,r.type):e)):e}function ns(e,t,n){return as(e,t,e=>e.filter(e=>e.name!==n))}var rs=/^(?:text|reply|stage[1-9]\d*(?:\..*)?)$/;function is(e,t,n,r){let i=n.trim();return i?/[{}\s]/.test(i)?`A name has no braces or spaces.`:rs.test(i)?`{${i}} is filled in by the lab.`:i!==r&&x().tokensOf(e.jobs[t]).some(e=>e.name===i)?`{${i}} is already mapped.`:null:`A mapping needs a name.`}function as(e,t,n){let r=x();return{...e,jobs:e.jobs.map((e,i)=>i===t?r.withTokens(e,n(r.tokensOf(e))):e)}}function os(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 ss=(e,t)=>(x().targetsOf(e)[t]?.name||``).trim()||`Target ${t+1}`;function cs(e,t){let n=x().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 ls(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=x();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 us(e,t,n,r,i){let a=Jo(e,t,n,r),o=x();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=cs(c.type,s);l!==c.type&&(a=o.withTarget(a,t,n,e=>ls(a,n,e,l)))}),a}var ds=(e,t,n)=>({...e,jobs:e.jobs.map((e,r)=>r===t?x().withImage(e,n):e)});function fs(e,t,n){let r=x();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 ps(e,t){let n=x(),r=n.defaultKind(),i=n.outOf(e.jobs[t]).modifiers.filter(e=>!B(e.type)||B(e.type).includes(r));return{...e,jobs:e.jobs.map((e,a)=>a===t?n.withOut(e,{kind:r,...d(r),modifiers:i}):e)}}function ms(e,t){let n=x().outOf(e.jobs[t]).modifiers.filter(e=>!B(e.type)||B(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 hs(e,t){let n=x().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 gs({k:e,pipeline:t,sources:n,edit:r,offer:i}){let[a,o]=(0,J.useState)(!1),[s,c]=(0,J.useState)(null),l=x(),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)})},b=(e,n)=>r(ds(l.withContent(t,e),0,n)),S=[...e===0&&!d?[{label:`Source…`,icon:y.add,onSelect:()=>o(!0)},{label:h.text?.label??`Text`,icon:y.add,onSelect:()=>b({type:`text`,text:``},!1)},{label:h.prompt?.label??`Prompt only`,icon:y.add,onSelect:()=>b({type:`prompt`},!1)}]:[],...!p&&!g?[{label:l.STEP_TYPES.attachImage?.label??`Image`,icon:y.add,onSelect:()=>r(ds(t,e,!0))}]:[],{label:`Token mapping`,icon:y.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`,ds(t,e,!1)):n.kind===`mapping`&&v(`Removed {${n.name}}`,ns(t,e,n.name))},T=s?.mode===`edit`?m.find(e=>e.name===s.name):void 0,O=n=>{let a=t;s?.mode===`add`?r(es(a,e,n.name,n.type)):T&&(r(ts(a,e,T.name,n)),n.type!==T.type&&T.value&&i({label:`Changed {${T.name}} to ${l.TOKEN_TYPES[n.type]?.label.toLowerCase()??n.type}`,restore:()=>r(a)})),c(null)},k=(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 ${w(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,hint:h[d?.type??``]?.description,control:{type:`static`,text:ys(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($o(t,e,n.name,{value:i}))}:{type:`static`,text:o?.label??n.type},...s.includes(`enabled`)?{enabled:{checked:!!n.enabled,onChange:i=>r($o(t,e,n.name,{enabled:i}))}}:{},actions:[{label:`Edit`,icon:y.edit,onSelect:()=>c({mode:`edit`,name:n.name})},...a]}]}}},A=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`,j=_.map(r=>_s[r.kind](t,e,n)).join(`, `)||`none`;return(0,Z.jsxs)(U,{id:`job-${e}-content`,title:`Content`,level:3,note:j,children:[(0,Z.jsx)(R,{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:y.rename,onSelect:()=>o(!0)}]:[],empty:(0,Z.jsx)(`p`,{className:`note`,children:`No content`}),renderItem:(t,n,r)=>(0,Z.jsx)(`div`,{className:`stage-row`,id:t.kind===`mapping`?void 0:`job-${e}-${t.kind}`,children:(0,Z.jsx)(N,{label:A(t),rows:k(t,r)})},t.kind===`mapping`?`m-${t.name}`:t.kind)}),s&&(s.mode===`add`||T)&&(0,Z.jsx)(H,{title:T?l.TOKEN_TYPES[T.type]?.notation(T.name)??`{${T.name}}`:`New mapping`,initial:T?{name:T.name,type:T.type}:{name:``,type:`value`},problem:n=>is(t,e,n,T?.name),onSave:O,onClose:()=>c(null)},s.mode===`edit`?s.name:`add`),a&&(0,Z.jsxs)(D,{title:d?`Change content`:`Add content`,onClose:()=>o(!1),children:[(0,Z.jsx)(qa,{mode:`pick`,onPick:e=>{b({type:`source`,ref:E(e.id,e.name),first:null,loops:1},l.sourceTypeOf(e)?.sendsImage??!1),o(!1)}}),(0,Z.jsxs)(`div`,{className:`pick-others`,children:[(0,Z.jsx)(`h2`,{className:`shead-title`,children:`Without a Source`}),(0,Z.jsxs)(`button`,{type:`button`,className:`ghost pick-item`,onClick:()=>{b({type:`text`,text:``},!1),o(!1)},children:[(0,Z.jsx)(`span`,{children:h.text?.label??`Text`}),h.text?.description&&(0,Z.jsx)(`span`,{className:`pick-about`,children:h.text.description})]}),(0,Z.jsxs)(`button`,{type:`button`,className:`ghost pick-item`,onClick:()=>{b({type:`prompt`},!1),o(!1)},children:[(0,Z.jsx)(`span`,{children:h.prompt?.label??`Prompt only`}),h.prompt?.description&&(0,Z.jsx)(`span`,{className:`pick-about`,children:h.prompt.description})]})]})]})]})}var _s={reply:(e,t)=>`${x().jobLabel(e,t-1)} · ${w(x().outOf(e.jobs[t-1]).kind)}`,attach:(e,t,n)=>ys(x().contentOf(e),n),flow:(e,t)=>x().flowStepOf(e.jobs[t])?.step??``,image:()=>`image`,mapping:()=>`token mapping`},vs=(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}`},ys=(e,t)=>e?e.type===`source`?vs(e,t):x().CONTENT_TYPES[e.type]?.label??e.type:`none`;async function bs(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 xs={prompt:{actions:ws,summary:Cs},echo:{actions:ws,summary:()=>`Each item`},httpRequest:{summary:e=>`${e.method} ${e.path}`,promptLabel:e=>Ts(e)?.fields.length?`Prompt`:`Body`,rows:Ds,actions:As}},Ss=e=>xs[e??``]??xs.prompt;function Cs(e){return e.from?.name||e.prompt.split(`
|
|
11
|
+
`).find(e=>e.trim())?.trim()||`No prompt`}function ws({pipeline:e,i:t,k:n,onSelectPrompt:r,onClearPrompt:i,defaultPrompt:a,onRevert:o}){let s=x().targetStepOf(e,t,n)?.prompt??``;return[{label:`Select prompt…`,icon:dt,onSelect:r},{label:`Clear prompt`,icon:y.clear,disabled:!s,onSelect:i},...o&&a!=null?[{label:`Revert to default`,icon:y.revert,disabled:s===a,onSelect:o}]:[]]}var Ts=e=>x().HTTP_APIS[e?.api??``],Es=e=>{let t=Object.entries(e??{}).map(([e,t])=>`${e}=${t}`).join(`&`);return t?`?${t}`:``};function Ds(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(x().HTTP_APIS).map(([e,t])=>({value:e,label:t.label}))}:{type:`static`,text:Ts(e)?.label??n.api}},{key:`request`,label:`Request`,control:{type:`code`,text:`${n.method} ${n.path}${Es(n.query)}`}},{key:`body`,label:`Template`,control:{type:`code`,text:JSON.stringify(n.body,null,2)}}],i=Ts(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 Os(e){return JSON.stringify((Ts(e)??x().HTTP_APIS.raw).place(e.body,e),null,2)}function ks(e,t,n){let r=x().targetStepOf(e,t,n);if(!r)return``;let i=Ts(r),a=e.jobs[n],o=x().flowStepOf(a),s=x().readAsOf(a),c=x().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 "${ss(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",Os(r),"```"),f.join(`
|
|
12
|
+
`)}function As({pipeline:e,i:t,k:n,say:r}){let i=x().targetStepOf(e,t,n);if(!i)return[];let a=async(e,t)=>r(await bs(e)?`Copied ${t}.`:`Could not copy.`);return[{label:`Copy`,icon:o,onSelect:()=>void a(Os(i),`the body`)},{label:`Copy as AI prompt`,icon:Ct,onSelect:()=>void a(ks(e,t,n),`the AI prompt`)}]}function js({label:e,profile:t,prompt:n,onPrompt:r,rows:i=[],promptLabel:a=`Prompt`}){return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(N,{label:`${e} setup`,rows:[{key:`profile`,label:`Target profile`,control:t},...i]}),(0,Z.jsxs)(`label`,{className:`prompt`,children:[(0,Z.jsx)(`span`,{className:`prop-name`,children:a}),(0,Z.jsx)(`textarea`,{value:n,"aria-label":`${e}, prompt`,rows:8,readOnly:!r,onChange:e=>r?.(e.target.value)})]})]})}function Ms({run:e,i:t,onClose:n}){let r=x(),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,Z.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,Z.jsx)(js,{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:Ss(t.type).rows?.(t)??[],promptLabel:Ss(t.type).promptLabel?.(t)??`Prompt`})})),closeLabel:`Close`,onClose:n})}function Ns({index:e}){return(0,Z.jsx)(`span`,{className:`target-badge`,"aria-hidden":`true`,children:String.fromCharCode(65+e)})}function Ps({k:e,pipeline:t,profiles:n,targetCap:r,onRequestRename:i,onAdd:a,onClone:o,onRemove:s,onProfile:c,onEcho:l,onPrompt:u,onStep:d,onSelectPrompt:f,onClearPrompt:p,defaultPrompt:m,onRevert:h,say:g=()=>{}}){let _=x(),v=_.targetsOf(t),y=v.length;return(0,Z.jsx)(U,{id:`job-${e}-targets`,title:`Targets`,level:3,note:`${y} ${y===1?`target`:`targets`}`,children:(0,Z.jsx)(R,{noun:`target`,items:v,min:1,max:r,onAdd:a,onClone:o,onRemove:s,onRename:i,extra:(n,r)=>Ss(_.targetStepOf(t,r,e)?.type).actions?.({pipeline:t,i:r,k:e,say:g,onSelectPrompt:()=>f(r),onClearPrompt:()=>p(r),defaultPrompt:m,onRevert:h&&(()=>h(r))})??[],empty:(0,Z.jsx)(`p`,{className:`note`,children:`No targets`}),renderItem:(r,i,a)=>{let o=ss(t,i),s=_.targetStepOf(t,i,e)??{type:`prompt`,prompt:``},f=Ss(s.type),p=_.STEP_TYPES[s.type],m=e>0&&!!p?.firstJobOnly,h=p?.local?null:s.profile??r.profile,g=h?n.find(e=>e.id===h.id)?.name||h.name||`—`:`No profile`;return(0,Z.jsxs)(`div`,{className:`target`,id:`job-${e}-target-${i}`,children:[(0,Z.jsxs)(`div`,{className:`target-head`,children:[(0,Z.jsx)(Ns,{index:i}),(0,Z.jsxs)(`span`,{className:`target-who`,children:[(0,Z.jsx)(`h4`,{className:`target-name`,children:o}),(0,Z.jsx)(`span`,{className:`target-profile`,children:g})]}),(0,Z.jsxs)(`span`,{className:`target-what`,children:[(0,Z.jsx)(`span`,{className:`target-type`,children:p?.label??s.type}),(0,Z.jsx)(`span`,{className:m?`target-value idle`:`target-value`,children:m?`Job 1 only`:f.summary?.(s)??s.prompt})]}),(0,Z.jsx)(G,{actions:a,label:`${o} actions`})]}),!m&&(0,Z.jsx)(js,{label:o,profile:e===0?{type:`select`,value:Is(s)?Fs:r.profile?.id??``,options:[...Ls(),...Rs(n,r.profile)],onChange:e=>e===Fs?l(i):c(i,zs(n,e))}:{type:`select`,value:s.profile?.id??``,options:[{value:``,label:`Same as ${_.jobLabel(t,0)}`},...Rs(n,s.profile)],onChange:e=>c(i,e?zs(n,e):null)},prompt:s.prompt,onPrompt:e=>u(i,e),rows:f.rows?.(s,e=>d(i,e))??[],promptLabel:f.promptLabel?.(s)??`Prompt`})]},`${i}-${e}`)}})})}var Fs=`#echo`,Is=e=>!!x().STEP_TYPES[e.type]?.local,Ls=()=>Object.entries(x().STEP_TYPES).filter(([,e])=>e.slot===`target`&&e.local).map(([,e])=>({value:Fs,label:e.label??`Echo`})),Rs=(e,t)=>[...t?.id&&!e.some(e=>e.id===t.id)?[{value:t.id,label:`${t.name||t.id} (missing)`}]:[],...e.map(e=>({value:e.id,label:e.name}))],zs=(e,t)=>{let n=e.find(e=>e.id===t);return n?{id:n.id,name:n.name}:null};function Bs({pipeline:e,profiles:t,sources:r,targetCap:i,prompt:a=``,defaultPrompt:o,protectedTerms:s,edit:c,offer:l}){let[d,f]=(0,J.useState)(null),[p,m]=(0,J.useState)(null),[h,g]=(0,J.useState)(null),_=(t,n)=>{let r=e;c(n),l({label:t,restore:()=>c(r)})},v=e=>{let n=t.find(t=>t.id===e);return n?x().CONNECTION_TYPES[x().typeOf(n)]?.answers??[`prompt`]:void 0},y=!x().targetsOf(e).length;return(0,Z.jsxs)(`div`,{className:`jobs`,children:[h&&(0,Z.jsx)(`p`,{className:`note`,role:`status`,children:h}),(0,Z.jsx)(R,{noun:`job`,items:e.jobs,min:1,addDisabled:y,onAdd:()=>c(ko(e)),onClone:t=>c(jo(e,t)),onRemove:t=>_(`Removed ${x().jobLabel(e,t)}`,Ao(e,t)),onRename:e=>f({job:e}),renderItem:(d,p,h)=>{let y=`Job ${p+1}${d.name?.trim()?` - ${d.name.trim()}`:``}`,b=x().flowStepOf(d)?x().readAsOf(d):void 0;return(0,Z.jsxs)(J.Fragment,{children:[p>0&&(0,Z.jsxs)(`div`,{className:`job-reply`,"aria-hidden":`true`,children:[(0,Z.jsx)(n,{size:16}),(0,Z.jsx)(`span`,{children:`Reply`})]}),(0,Z.jsx)(U,{id:`job-${p}`,title:y,level:2,actions:h,note:Vs(e,p),children:(0,Z.jsxs)(`div`,{className:`stages`,children:[(0,Z.jsx)(gs,{k:p,pipeline:e,sources:r,edit:c,offer:l}),(0,Z.jsx)(Ps,{k:p,pipeline:e,profiles:t,targetCap:i,onRequestRename:e=>f({job:p,scenario:e}),onAdd:()=>c(Bo(e,zo(t),a)),onClone:t=>c(Go(e,t)),onRemove:t=>_(`Removed ${ss(e,t)}`,Ko(e,t)),onProfile:(t,n)=>c(us(e,t,p,n,v)),onEcho:t=>c(hs(e,t)),onPrompt:(t,n)=>c(Yo(e,t,p,n)),onStep:(t,n)=>c(Hs(e,t,p,n)),say:g,onSelectPrompt:e=>m({i:e,k:p}),onClearPrompt:t=>_(`Cleared ${ss(e,t)}'s prompt`,Yo(e,t,p,``)),...p===0&&o?{defaultPrompt:o.text,onRevert:t=>_(`Reverted ${ss(e,t)} to the default`,Xo(e,t,0,o.text,{id:o.id,name:ze(o)}))}:{}}),(0,Z.jsx)(V,{id:`job-${p}-responses`,out:x().outOf(d),format:!!x().replyOf(d),readAs:b,outputKinds:T(),modifiers:u(),onKind:t=>c(No(e,p,t)),onSetting:(t,n)=>c(Us(e,p,e=>({...e,[t]:n}))),onAddFormat:()=>c(ps(e,p)),onRemoveFormat:()=>_(`Removed the format validation`,ms(e,p)),onReadAs:t=>t==null?_(`Removed Read as`,fs(e,p,null)):c(fs(e,p,t)),...s?{protectedTerms:s}:{},offer:l,onModifier:(t,n)=>c(Ws(e,p,t,n)),onAddModifier:t=>c(Us(e,p,e=>({...e,modifiers:[...e.modifiers,t]}))),onRemoveModifier:t=>_(`Removed a modifier`,Us(e,p,e=>({...e,modifiers:e.modifiers.filter((e,n)=>n!==t)})))})]})})]},d.id||p)}}),y&&(0,Z.jsx)(`p`,{className:`note add-why`,children:`Add a target first.`}),d&&`scenario`in d?(0,Z.jsx)(re,{title:`Rename ${ss(e,d.scenario)}`,value:x().targetsOf(e)[d.scenario]?.name??``,onCommit:t=>c(qo(e,d.scenario,t)),onClose:()=>f(null)}):d?(0,Z.jsx)(re,{title:`Rename ${x().jobLabel(e,d.job)}`,value:e.jobs[d.job]?.name??``,onCommit:t=>c(Mo(e,d.job,t)),onClose:()=>f(null)}):null,p&&(0,Z.jsx)(Oo,{onClose:()=>m(null),used:{byScenario:Zo(e,p.i),byAll:Qo(e)},onPick:t=>{let n=e;c(Xo(n,p.i,p.k,t.text,{id:t.id,name:ze(t)})),m(null),l({label:`Picked ${ze(t)}`,restore:()=>c(n)})}})]})}function Vs(e,t){let n=x(),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 Hs=(e,t,n,r)=>x().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}),Us=(e,t,n)=>({...e,jobs:e.jobs.map((e,r)=>r===t?x().withOut(e,n(x().outOf(e))):e)}),Ws=(e,t,n,r)=>Us(e,t,e=>({...e,modifiers:e.modifiers.map((e,t)=>t===n?r:e)})),Gs={metrics:{Editor:e=>(0,Z.jsx)(Xs,{...e}),actions:(e,t,n)=>`dataset`in e&&e.dataset&&n.length?[{label:`Edit`,icon:y.edit,onSelect:()=>t(n[0].item)}]:[]}};function Ks({pipeline:e,datasets:t,graded:n,edit:r,offer:i,openCaseEditor:a,children:o,profiles:s=[],labGrader:c=null}){let[l,u]=(0,J.useState)(!1),[d,f]=(0,J.useState)(null),p=e.evals,m=p.findIndex(e=>`dataset`in e&&e.dataset),h=(t,n)=>{let a=e;r(t),i({label:n,restore:()=>r(a)})};return(0,Z.jsxs)(U,{id:`evals`,title:`Evals`,level:2,note:p.length?String(p.length):`None`,children:[(0,Z.jsx)(R,{noun:`eval`,items:p,empty:(0,Z.jsx)(`p`,{className:`note`,children:`No evals — the run is unscored.`}),onAdd:()=>u(!0),onRename:e=>f(e),onRemove:t=>h(Fo(e,t),`Removed ${x().evalLabel(e,t)}`),extra:(t,r)=>[...Gs[t.type]?.actions?.(t,a,n)??[],...x().EVAL_TYPES[t.type]?.toMetrics?[{label:`Convert to Metrics`,icon:y.edit,onSelect:()=>h(Ro(e,r,x().EVAL_TYPES[t.type].toMetrics(t)),`Converted ${x().evalLabel(e,r)} to Metrics`)}]:[],{label:`Move up`,icon:y.moveUp,disabled:r===0,onSelect:()=>h(Io(e,r,-1),`Moved ${x().evalLabel(e,r)} up`)},{label:`Move down`,icon:y.moveDown,disabled:r===p.length-1,onSelect:()=>h(Io(e,r,1),`Moved ${x().evalLabel(e,r)} down`)}],renderItem:(n,i,a)=>{let l=x().evalLabel(e,i),u=t=>r(Ro(e,i,t));return(0,Z.jsxs)(U,{id:`eval-${i}`,title:l,level:3,note:x().EVAL_TYPES[n.type]?.label??n.type,about:x().EVAL_TYPES[n.type]?.description,actions:a,...d===i?{rename:{value:n.name||l,onCommit:t=>{r(Lo(e,i,t)),f(null)},onCancel:()=>f(null)}}:{},children:[(()=>{let r=Gs[n.type]?.Editor;return r?(0,Z.jsx)(r,{ev:n,label:l,set:u,datasets:t,profiles:s,labGrader:c,undoable:(t,n)=>h(Ro(e,i,t),n)}):null})(),(0,Z.jsx)(N,{label:`${l} on failure`,rows:[{key:`continue`,label:`Continue on failure`,control:{type:`checkbox`,checked:n.continueOnFailure,onChange:e=>u({...n,continueOnFailure:e})}}]}),i===m&&o]},n.id)}}),l&&(0,Z.jsx)(Ys,{pipeline:e,datasets:t,onClose:()=>u(!1),onAdd:t=>{r(Po(e,t)),u(!1)}})]})}function qs(e,t,n,r=!1){let i=e&&!t.some(t=>t.id===e.id)?[...t,e]:t;return{key:`dataset`,label:`Dataset`,control:{type:`select`,value:e?.id??``,options:[...r?[{value:``,label:`—`}]:[],...i.map(e=>({value:e.id,label:e.name||e.id}))],onChange:e=>{let r=t.find(t=>t.id===e);n(r?{id:r.id,name:r.name}:null)}}}}function Js(e,t){let n=x().outOf(e.jobs.at(-1)).kind;return Object.entries(x().EVAL_TYPES).flatMap(([e,t])=>{let r=typeof t.accepts==`function`?t.accepts({type:e}):t.accepts,i=t.fields.includes(`dataset`);return r&&!r.includes(n)?[]:[{id:e,label:t.label,dataset:i}]})}function Ys({pipeline:e,datasets:t,onAdd:n,onClose:r}){let i=Js(e,t),[a,o]=(0,J.useState)(i[0]?.id??``),[s,c]=(0,J.useState)(``),l=x().evalsDataset(e),[u,d]=(0,J.useState)(l??null),f=i.find(e=>e.id===a),p=[{key:`type`,label:`Type`,hint:x().EVAL_TYPES[a]?.description,control:{type:`select`,value:a,options:i.map(e=>({value:e.id,label:e.label})),onChange:o}},{key:`name`,label:`Name`,control:{type:`text`,value:s,placeholder:`Eval ${e.evals.length+1}`,onChange:c}},...f?.dataset&&t.length?[qs(u,t,d,!0)]:[]];return(0,Z.jsx)(j,{title:`Add eval`,...i.length?{}:{status:`No eval type reads what the last job answers with.`,statusBad:!0},sections:[{key:`eval`,rows:p}],focusRow:`type`,closeLabel:`Cancel`,actions:[{label:`Add`,icon:y.add,disabled:!f,onSelect:()=>f&&n(x().newEval(f.id,s.trim(),f.dataset&&u?{dataset:{id:u.id,name:u.name},metrics:[]}:{}))}],onClose:r})}function Xs({ev:e,label:t,set:n,undoable:r,profiles:i,datasets:a,labGrader:o}){let s=x(),c=e.metrics.some(e=>s.METRICS[e.type]?.graded),l=i.filter(e=>(s.CONNECTION_TYPES[e.type??``]?.answers??[`prompt`]).includes(`prompt`)),u=[{key:`mode`,label:`Scored`,control:{type:`select`,value:e.mode,options:[{value:`all`,label:`All must pass`},{value:`weighted`,label:`Weighted points`}],onChange:t=>n({...e,mode:t,threshold:t===`weighted`?e.threshold??1:e.threshold})}},...e.mode===`weighted`?[{key:`threshold`,label:`Pass at`,control:{type:`text`,size:`num`,value:e.threshold==null?``:String(e.threshold),onChange:t=>n({...e,threshold:t.trim()?/^-?\d+(\.\d+)?$/.test(t.trim())?Number(t):t:null})}}]:[],{key:`over`,label:`Reads`,control:{type:`select`,value:e.over??`item`,options:[{value:`item`,label:`Each item`},{value:`run`,label:`Whole run`}],onChange:t=>n({...e,over:t===`run`?`run`:`item`})}},{key:`dataset`,label:`Dataset`,control:{type:`select`,value:e.dataset?.id??``,options:[{value:``,label:`—`},...(e.dataset&&!a.some(t=>t.id===e.dataset.id)?[e.dataset]:a).map(e=>({value:e.id,label:e.name||e.id}))],onChange:t=>{let r=a.find(e=>e.id===t);n({...e,dataset:r?{id:r.id,name:r.name}:null})}}},...c||e.grader?[{key:`grader`,label:`Grader`,control:{type:`select`,value:e.grader?.id??``,options:[{value:``,label:o?`Lab (${o.name})`:`—`},...l.map(e=>({value:e.id,label:e.name}))],onChange:t=>{let r=i.find(e=>e.id===t);n({...e,grader:r?{id:r.id,name:r.name}:null})}}}]:[]];return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(N,{label:t,rows:u}),(0,Z.jsx)(Sr,{label:t,metrics:e.metrics,over:e.over??`item`,set:t=>n({...e,metrics:t}),undoable:(t,n)=>r({...e,metrics:t},n)})]})}function Zs({pipeline:e,sourceFiles:t,graded:n,openCaseEditor:r}){let[i,a]=(0,J.useState)({graded:!1,todo:!0,missing:!0});if((x().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)}],u=l[0].files.length,d=l[1].files.length+l[2].files.length,f=l.filter(e=>i[e.key]).flatMap(e=>e.files.map(t=>({file:t,tone:e.tone})));return(0,Z.jsx)(U,{id:`mapping`,title:`Mapping`,level:3,note:p(),about:`Which of the content's items the dataset has a case for, and so which are graded.`,children:o.length?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`p`,{className:`note`,children:[dn(n.length,`case`),` · `,u,` of `,o.length,` content items matched.`]}),(0,Z.jsx)(`div`,{className:`mkey`,children:l.filter(e=>e.files.length).map(e=>(0,Z.jsxs)(`button`,{type:`button`,className:`ghost chip-key${i[e.key]?` on`:``}`,"aria-pressed":i[e.key],onClick:()=>a({...i,[e.key]:!i[e.key]}),children:[e.label,` `,e.files.length]},e.key))}),f.length?(0,Z.jsx)(`div`,{className:`mchips`,children:f.map(({file:e,tone:t})=>(0,Z.jsx)(`button`,{type:`button`,className:`mchip ${t}`,onClick:()=>r(e),children:e},`${t}-${e}`))}):(0,Z.jsx)(`p`,{className:`note`,children:d?`Nothing shown.`:`Every content item is graded.`})]}):(0,Z.jsx)(`p`,{className:`note`,children:`No items in the content to map against.`})});function p(){let r=x().contentOf(e),i=r?x().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 Qs({pipeline:e,edit:t,comment:n,setComment:r,onClear:i,onCopyFailures:a}){let s=[{label:`Clear comment`,icon:m,destructive:!0,onSelect:i},{label:`Copy last run's failures`,icon:o,onSelect:a}],c=x().contentOf(e),l=c?.type===`source`?[{key:`first`,label:`Run first`,control:{type:`text`,value:c.first==null?``:String(c.first),placeholder:`all`,onChange:n=>t(x().withContent(e,{...c,first:n.trim()?$s(n):null}))}},{key:`loops`,label:`Loop`,control:{type:`text`,value:String(c.loops),placeholder:`1`,onChange:n=>t(x().withContent(e,{...c,loops:Math.max(1,$s(n)??1)}))}}]:[];return(0,Z.jsx)(U,{id:`control`,title:`Run settings`,level:2,actions:s,children:(0,Z.jsx)(N,{label:`Run settings`,rows:[...l,{key:`comment`,label:`Comment`,control:{type:`text`,value:n,placeholder:`A note to find this run by in History`,onChange:e=>r(e)}}]})})}var $s=e=>{let t=Number.parseInt(e,10);return Number.isNaN(t)?null:t};function ec(){let e=ve(),t=Y(),n=ne(),{openRun:r}=Jt(),{openCaseEditor:i}=Rr(),[a,o]=ye(`promptlab.workflows`),[s]=ye(`promptlab.profiles`),[c,l]=ye(`promptlab.comment`),[u]=ye(`promptlab.versions`),[d,f]=(0,J.useState)([]),{list:p,error:m}=Le(),{list:h,error:g}=qe(),_=h?.find(e=>e.default)??null,v=Ie(),y=(0,J.useMemo)(()=>(p??[]).map(e=>E(e.id,e.name)),[p]),[b,S]=(0,J.useState)(4),[C,w]=(0,J.useState)(void 0),[T,A]=(0,J.useState)(null),[j,M]=(0,J.useState)(!1),[N,P]=(0,J.useState)(!1),[ee,F]=(0,J.useState)(null),I=(0,J.useRef)(null),[L,te]=(0,J.useState)(null),R=(0,J.useRef)(null);(0,J.useEffect)(()=>{let e=!0;return t.sources().then(t=>{e&&f(t.sources)}).catch(()=>{}),t.config().then(t=>{e&&S(t.targetCap)}).catch(()=>{}),()=>{e=!1}},[t]),(0,J.useEffect)(()=>{let e=!0,n,r=async()=>{let i=5e3;try{let n=(await t.queue({limit:1})).runs[0]??null;if(!e)return;!I.current&&n&&!kn(n.status)&&(I.current=n.id),n&&n.id===I.current&&(F(n),kn(n.status)||(i=1e3))}catch{}e&&(n=setTimeout(()=>void r(),i))};return r(),()=>{e=!1,n&&clearTimeout(n)}},[t]);let z=(0,J.useMemo)(()=>a.list.filter(e=>e.work?.version===12),[a.list]),B=z.find(e=>e.id===a.at)??z[0],V=B?.work,re=B?.id??``,H=V?x().evalsDataset(V)?.id??null:null,ie=Re(H),U=ie?.doc?.body.cases,ae=(0,J.useMemo)(()=>(U??[]).map(e=>({id:e.id??``,item:x().caseItem(e)})),[U]),W=ie?.doc?.body.cases,G=(0,J.useMemo)(()=>[...new Set((W??[]).flatMap(e=>(e.metrics??[]).filter(e=>!e.not&&e.weight!==0&&(e.type===`contains-all`||e.type===`contains-any`)).flatMap(e=>x().metricLines(e.values))))],[W]),K=_?.text||V&&x().targetStepOf(V,x().targetsOf(V).length-1,0)?.prompt||``,q=(0,J.useRef)(s.list);q.current=s.list;let oe=z.length?null:p?.[0]??null,se=p!==null||m!==null,ce=h!==null||g!==null,le=_?.text??``;(0,J.useEffect)(()=>{if(z.length||!se||!ce)return;let e=nc(q.current,oe?{id:oe.id,name:oe.name}:void 0,le);o({list:[e],at:e.id})},[z.length,o,se,ce,oe,le]);let ue=()=>{let e=v.list().list?.[0];return e?{id:e.id,name:e.name}:void 0},X=(0,J.useRef)(a);X.current=a;let de=(0,J.useRef)(B);de.current=B;let fe=(0,J.useRef)(V);fe.current=V;let pe=(0,J.useRef)(null),me=(0,J.useRef)(null),he=(0,J.useCallback)(()=>{me.current&&clearTimeout(me.current);let t=de.current?.id,n=fe.current;t&&n&&(pe.current={id:t,doc:n},me.current=setTimeout(()=>{let t=pe.current;t&&je(e,`pipeline`,t.id,t.doc,`idle`)},De))},[e]);(0,J.useEffect)(()=>()=>{me.current&&clearTimeout(me.current)},[]);let ge=(0,J.useCallback)(e=>{let t=X.current,n=de.current.id,r={...t,at:n,list:t.list.filter(e=>e.work?.version===12).map(t=>t.id===n?{...t,work:e}:t)};X.current=r,o(r),he(),A(null)},[o,he]),_e=s.list[0]?.id??``;(0,J.useEffect)(()=>{let e=fe.current,t=de.current?.id;if(!e||!t||!_e)return;let n=Wo(e,zo(q.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,o(i)},[_e,re,o]),(0,J.useEffect)(()=>{let t=pe.current;t&&t.id!==re&&(je(e,`pipeline`,t.id,t.doc,`idle`),pe.current=null,me.current&&=(clearTimeout(me.current),null))},[re,e]);let be=V?x().contentOf(V):null,xe=be?.type===`source`?be.ref.id:null;(0,J.useEffect)(()=>{if(xe===null){w(void 0);return}let e=!0;return t.source(xe).then(t=>{e&&w(t.files.map(e=>e.name))}).catch(()=>{}),()=>{e=!1}},[xe,t]);let Se=(0,J.useCallback)(e=>{let t=d.find(t=>t.id===e);return t?{name:t.name,type:t.type,files:e===xe&&C?C:[]}:null},[d,xe,C]),Ce=(0,J.useMemo)(()=>{let e=s.list.find(e=>e.id===s.grader);return e?{id:e.id,name:e.name}:null},[s]),we=(0,J.useMemo)(()=>{if(!V)return[];if(!s.list.length&&x().targetsOf(V).length)return[`add a Target profile first`];let e={profiles:e=>s.list.find(t=>t.id===e)??null,sources:Se,grader:Ce,...p?{datasets:p}:{}};return x().validatePipeline(V,e)},[V,s.list,Se,p,Ce]),Te=re?u.pipeline?.[re]??[]:[],Ee=(0,J.useCallback)(async()=>{let n=fe.current,i=de.current.id;je(e,`pipeline`,i,n,`run`);let a=x().resolvePipeline(n,{profiles:e=>s.list.find(t=>t.id===e)??null,grader:Ce,...xe!==null&&C!==void 0?{files:C}:{},comment:c?.text??``});M(!0),A(null);try{let e=await t.submit(a);I.current=e.run.id,F(e.run),r(e.run.id,{at:e.run.submittedAt,from:`runs`})}catch(e){A(e instanceof Error?e.message:String(e)),I.current=null,F(null)}finally{M(!1)}},[t,c,xe,r,s.list,C,e,Ce]),Oe=(0,J.useCallback)(async()=>{let e=I.current;if(e)try{F((await t.cancel(e)).run)}catch{}},[t]),ke=(0,J.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(x().failedScore))).map(e=>e.name??`an item`);n.length&&await navigator.clipboard?.writeText(n.join(`
|
|
13
|
+
`))}catch{}},[t]),Ae=(0,J.useCallback)(async n=>{let r=fe.current,i=de.current.id;je(e,`pipeline`,i,r,`run`);let a=x().resolvePipeline(r,{profiles:e=>s.list.find(t=>t.id===e)??null,grader:Ce,files:[n],comment:c?.text??``}),o=await t.submit(a),l=o.run;for(;l.status===`queued`||l.status===`running`;)await new Promise(e=>setTimeout(e,500)),l=await t.run(o.run.id);return((l.results??[]).find(e=>e.name===n)?.scenarios??[]).map(e=>e.res??null)},[t,c,s.list,e]),Me=(0,J.useCallback)(e=>{H&&i(e,{dataset:H,files:C??[],run:Ae})},[i,C,Ae,H]),Ne=(0,J.useCallback)(()=>{let e=c?.text??``;l({text:``}),n.offer({label:`Cleared the comment`,restore:()=>l({text:e})})},[c,l,n]),Pe=(0,J.useCallback)(()=>{let e=x().pipelineToYaml(fe.current);gr(new Blob([e],{type:`text/yaml`}),hr(`pipeline`,fe.current.name||`pipeline`,12,`yml`))},[]),Fe=(0,J.useCallback)(async e=>{let n=await t.archivedRules().then(e=>e.rules,()=>({})),r=x().yamlToPipeline(e,{profiles:q.current,profileType:e=>q.current.find(t=>t.id===e)?.type,sources:d,datasets:y,rulesFor:e=>n[e]??null});if(`error`in r){te(r);return}let{doc:i,missing:a}=r,s={id:rc(),name:i.name||`Imported`,work:i},c={...X.current,at:s.id,list:[...z,s]};X.current=c,o(c),te({doc:i,missing:a})},[t,z,o,d,y]);if(!B||!V)return(0,Z.jsx)(`div`,{className:`runs`,children:(0,Z.jsx)(k,{label:`Pipelines`})});let ze=t=>{let n=de.current.id;je(e,`pipeline`,n,fe.current,`restore`),ge(t.doc),P(!1)};return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(bo,{list:z,at:re,canRestore:Te.length>0,onSelect:e=>o({...X.current,at:e}),onNew:()=>{let e=tc(z.map(e=>e.name));if(o({...X.current,list:[...z,e],at:e.id}),c?.text){let e=c.text;l({text:``}),n.offer({label:`Cleared the comment`,restore:()=>l({text:e})})}},onClone:()=>{let e={id:rc(),name:`${B.name} copy`,work:structuredClone(V)};o({...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===12).map(e=>e.id===r?{...e,name:t,work:{...e.work,name:t}}:e)};X.current=i,o(i),he()},onDelete:()=>{let e=X.current,t=z.filter(e=>e.id!==re),r=t.length?t:[nc(s.list,ue(),le)],i=t.length?t[0].id:r[0].id;o({...X.current,list:r,at:i}),n.offer({label:`Deleted ${B.name||`the pipeline`}`,restore:()=>{X.current=e,o(e)}})},onRestore:()=>P(!0),onExport:Pe,onImport:()=>R.current?.click()}),(0,Z.jsx)(So,{problems:we,error:T,run:ee,submitting:j,onRun:()=>void Ee(),onStop:()=>void Oe(),onOpen:()=>{ee&&r(ee.id,{at:ee.submittedAt,from:`runs`})}}),(0,Z.jsxs)(`div`,{className:`runs`,children:[(0,Z.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(Fe).catch(()=>te({error:`the file could not be read`}))}}),(0,Z.jsx)(Qs,{pipeline:V,edit:ge,comment:c?.text??``,setComment:e=>l({text:e}),onClear:Ne,onCopyFailures:()=>void ke()}),(0,Z.jsx)(Bs,{pipeline:V,profiles:s.list,sources:d,targetCap:b,prompt:K,..._?{defaultPrompt:_}:{},protectedTerms:G,edit:ge,offer:n.offer}),(0,Z.jsx)(Ks,{profiles:s.list,labGrader:Ce,pipeline:V,datasets:y,graded:ae,edit:ge,offer:n.offer,openCaseEditor:Me,children:(0,Z.jsx)(Zs,{pipeline:V,sourceFiles:C,graded:ae,openCaseEditor:Me})}),(0,Z.jsx)(O,{undo:n.undo,onUndo:n.undoNow,onDismiss:n.dismiss}),N&&(0,Z.jsx)(D,{title:`Restore pipeline`,onClose:()=>P(!1),children:(0,Z.jsxs)(`div`,{className:`version-list`,children:[Te.length===0&&(0,Z.jsx)(`p`,{className:`note`,children:`No versions of this pipeline yet.`}),Te.map((e,t)=>(0,Z.jsxs)(`div`,{className:`version-row`,children:[(0,Z.jsxs)(`span`,{className:`version-when`,children:[ac(e.at),` · `,ic(e.reason)]}),(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>ze(e),children:`Restore`})]},`${e.at}-${t}`))]})}),L&&(`doc`in L?(0,Z.jsx)(D,{title:`Imported ${L.doc.name||`Untitled`}`,onClose:()=>te(null),children:L.missing.length>0?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.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,Z.jsx)(`ul`,{className:`import-missing`,children:L.missing.map(e=>(0,Z.jsx)(`li`,{children:e},e))})]}):(0,Z.jsx)(`p`,{className:`note`,children:`Ready to run.`})}):(0,Z.jsx)(D,{title:`Nothing imported`,onClose:()=>te(null),children:(0,Z.jsx)(`p`,{className:`note`,children:L.error})}))]})]})}var tc=e=>{let t=Vo(e),n=x().blankPipeline({name:t});return{id:rc(),name:t,work:{...n,jobs:n.jobs.map(e=>({...e,steps:[]}))}}},nc=(e,t,n)=>({id:rc(),name:Vo([]),work:Uo(zo(e),t,n)}),rc=()=>`w${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`,ic=e=>e===`run`?`before a run`:e===`restore`?`before a restore`:e===`pack`?`before a pack update`:`after editing`,ac=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},oc=[``,`queued`,`running`,`done`,`cancelled`,`failed`,`incomplete`,`interrupted`],sc=e=>e.numeric?`hnum`:void 0,cc=e=>[...new Map(e.map(e=>[e.id,e])).values()].sort((e,t)=>String(t.submittedAt).localeCompare(String(e.submittedAt)));function lc(){let e=Y(),t=ne(),{openRun:n}=Jt(),[r,i]=ye(`promptlab.history.columns`),[a,o]=(0,J.useState)([]),[s,c]=(0,J.useState)(!1),[u,d]=(0,J.useState)(``),[f,p]=(0,J.useState)(new Set),[h,_]=(0,J.useState)(!1),[v,y]=(0,J.useState)(null),[b,S]=(0,J.useState)(null),[C,w]=(0,J.useState)(null),[T,E]=(0,J.useState)(null),[j,M]=(0,J.useState)(!1),[N,P]=(0,J.useState)(!1),[ee,F]=(0,J.useState)(!1),[I,L]=(0,J.useState)(!1),[te,R]=(0,J.useState)(null),[B,V]=(0,J.useState)(0),re=(0,J.useRef)(I);re.current=I;let H=(0,J.useRef)(a);H.current=a;let ie=(0,J.useMemo)(()=>a.map(e=>pn(Un(e),e)),[a]),ae=(0,J.useMemo)(()=>fc(r),[r]),G=(0,J.useCallback)(async(t,n=!1)=>{try{return await e.queue({limit:25,...t?{before:t}:{},...n?{full:n}:{}})}catch{return null}},[e]),K=(0,J.useCallback)(e=>{let t=new Set(e.runs.map(e=>e.id));o(n=>cc([...n.filter(e=>!t.has(e.id)),...e.runs])),c(e.more)},[]);(0,J.useEffect)(()=>{let e=!0,t,n=async()=>{let r=await G();e&&(r?(K(r),L(!0),R(null)):re.current||R(`Runs not loaded: server unreachable.`),H.current.some(e=>[`queued`,`running`].includes(e.status))&&(t=setTimeout(()=>void n(),3e3)))};return n(),()=>{e=!1,t&&clearTimeout(t)}},[G,K,B]);let q=(0,J.useMemo)(()=>ie.filter(e=>!u||(e.status||`done`)===u),[ie,u]),oe=(e=>({Runs:wn.filter(t=>e.Runs.has(t.key)),"Run Scenarios":Tn.filter(t=>e[`Run Scenarios`].has(t.key))}))(ae),se=(0,J.useCallback)(e=>{p(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),ce=(0,J.useCallback)((e,t)=>{n(e,{at:t,from:`history`})},[n]),le=(0,J.useCallback)(async t=>{try{let n=await e.resume(t),r={runs:[n.run],more:H.current.length>25};K(r),ce(t,n.run.submittedAt)}catch{}},[e,K,ce]),ue=(0,J.useCallback)(async()=>{let n=H.current;F(!0);try{await e.clear()}catch{E(`Not cleared: server unreachable.`);return}finally{F(!1)}o([]),c(!1),t.offer({label:`Cleared ${dn(n.length,`run`)}`,restore:()=>{for(let t of n)e.submit(x().upgradePipeline(t.snapshot)).catch(()=>{})}})},[e,t]),X=(0,J.useCallback)(async()=>{P(!0);let e=[],t=!1,n;for(let r=0;;r++){let i=await G(n,!0);if(!i){t=!0;break}if(e=cc([...e,...i.runs]),n=i.runs.at(-1)?.submittedAt,!i.more||!n||r>100)break}if(t){let t=new Set(e.map(e=>e.id));e=cc([...e,...H.current.filter(e=>!t.has(e.id))])}if(P(!1),!e.length){E(`Nothing to export yet.`);return}gr(new Blob([JSON.stringify({exported:new Date().toISOString(),runs:e},null,2)],{type:`application/json`}),hr(`runs`,`all`,12,`json`)),E(t?`Exported ${dn(e.length,`run`)}. Server unreachable, so only those this browser had.`:`Exported ${dn(e.length,`run`)}.`)},[e,G]),de=[{label:`Select Columns`,icon:Qe,onSelect:()=>_(!0)},{label:`Export JSON`,icon:g,busy:N,onSelect:()=>void X()},{label:`Clear`,icon:m,destructive:!0,busy:ee,disabled:!I,onSelect:()=>void ue()}],fe=(0,J.useCallback)(e=>{let t=e.target.closest(`[data-resume]`);if(t){e.stopPropagation(),le(t.getAttribute(`data-resume`));return}let n=e.target.closest(`[data-openrun]`);if(n){e.stopPropagation();let t=n.closest(`tr[data-run]`),r=t?q[Number(t.getAttribute(`data-run`))]:null;r?.run&&ce(r.run,r.at);return}let r=e.target.closest(`[data-editcomment]`);if(r){e.stopPropagation();let t=r.closest(`tr[data-run]`),n=t?q[Number(t.getAttribute(`data-run`))]:null;n?.run&&S({id:n.run,comment:n.comment});return}let i=e.target.closest(`[data-scenario]`);if(i){e.stopPropagation();let t=i.closest(`tr[data-scen]`)?.previousElementSibling,n=t?q[Number(t.getAttribute(`data-run`))]:null,r=n?.run?H.current.find(e=>e.id===n.run):null;r?.snapshot&&w({run:r.snapshot,i:Number(i.getAttribute(`data-scenario`))});return}let a=e.target.closest(`[data-prof]`);if(a){e.stopPropagation();let t=a.closest(`tr[data-scen]`)?.previousElementSibling,n=t?q[Number(t.getAttribute(`data-run`))]:null,r=a.getAttribute(`data-prof`);if(n&&r!=null){let e=n.scenarios[Number(r)];y({name:e?.setupProfile?.name??``,settings:an(n,e??{})})}}},[q,ce,le]),pe=(0,J.useCallback)((e,t)=>{o(n=>n.map(n=>n.id===e?{...n,snapshot:{...n.snapshot,comment:t}}:n)),S(null)},[]),me=(e,t)=>e.image&&ln(t)!==!0?(0,Z.jsx)(`span`,{className:`note`,children:`—`}):e.get(t),he=(e,t,n,r)=>n?e.image&&ln(t)!==!0?(0,Z.jsx)(`span`,{className:`note`,children:`—`}):e.get(t,n,r):`—`;return(0,Z.jsxs)(`div`,{className:`history`,children:[(0,Z.jsxs)(U,{id:`history`,title:`History`,actions:de,children:[!I&&(0,Z.jsx)(k,{label:`Runs`,error:te,onRetry:()=>{R(null),V(e=>e+1)}}),I&&(ie.length>0||u)&&(0,Z.jsx)(z,{noun:`runs`,lead:q.length>0&&(0,Z.jsx)(`p`,{className:`note hstatus`,role:`status`,children:dn(q.length,`run`)}),filters:[{key:`show`,label:`Show`,value:u,onChange:d,options:oc.map(e=>({value:e,label:e?gn(e):`All`}))}]}),T&&(0,Z.jsx)(`p`,{className:`note hstatus`,role:`status`,children:T}),I?q.length?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`scrollx`,onClick:fe,children:(0,Z.jsx)(A,{className:`htable`,label:`Runs`,rows:q,rowKey:e=>e.at,rowProps:(e,t)=>({className:`runrow${f.has(e.at)?` open`:``}`,"data-run":t}),columns:[{key:`expand`,header:(0,Z.jsx)(`span`,{className:`hvh`,children:`Targets`}),label:``,className:`hexpand`,sort:null,cell:(e,t)=>{let n=f.has(e.at);return(0,Z.jsx)(`button`,{type:`button`,className:`icon-btn`,"aria-label":n?`Collapse`:`Expand`,"aria-expanded":n,"aria-controls":n?`hscen-${t}`:void 0,onClick:()=>se(e.at),children:(0,Z.jsx)(l,{size:16,"aria-hidden":`true`})})}},...oe.Runs.map(e=>({key:e.key,header:e.label,className:sc(e),sort:e.sort??(t=>{let n=e.get(t);return typeof n==`string`?n:null}),cell:t=>(0,Z.jsx)(`span`,{className:`hval`,children:me(e,t)})}))],after:(e,t)=>f.has(e.at)&&(0,Z.jsx)(`tr`,{className:`scenrows`,id:`hscen-${t}`,"data-run":t,"data-scen":e.at,children:(0,Z.jsx)(`td`,{colSpan:oe.Runs.length+1,children:(0,Z.jsx)(A,{className:`scen-table`,label:`Targets`,rows:((e.scenarios||[]).length?e.scenarios:[null]).map((e,t)=>({sc:e,n:t})),rowKey:({sc:e,n:t})=>e?.id??String(t),columns:oe[`Run Scenarios`].map(t=>({key:t.key,header:t.label,className:sc(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 typeof i==`string`?i:null},cell:({sc:n,n:r})=>(0,Z.jsx)(`span`,{className:`hval`,children:he(t,e,n,r)})}))})})})})}),s&&(0,Z.jsxs)(`button`,{type:`button`,className:`ghost older-btn`,disabled:j,"aria-busy":j||void 0,onClick:async()=>{M(!0);let e=await G(H.current.at(-1)?.submittedAt);if(M(!1),!e){E(`Server unreachable.`);return}K(e)},children:[j&&(0,Z.jsx)(W,{}),`Older`]})]}):(0,Z.jsx)(`p`,{className:`note`,children:T??(ie.length?`No runs match this filter.`:(0,Z.jsxs)(Z.Fragment,{children:[`No runs yet. `,(0,Z.jsx)(`a`,{href:`#/runs`,children:`Start one in Runs`})]}))}):null]}),(0,Z.jsx)(O,{undo:t.undo,onUndo:t.undoNow,onDismiss:t.dismiss}),h&&(0,Z.jsx)(mc,{cols:ae,onSave:e=>{i(pc(e)),_(!1)},onClose:()=>_(!1)}),C&&(0,Z.jsx)(Ms,{run:C.run,i:C.i,onClose:()=>w(null)}),v&&(0,Z.jsx)(D,{title:v.name||`Settings`,onClose:()=>y(null),children:(0,Z.jsx)(uc,{settings:v.settings})}),b&&(0,Z.jsx)(dc,{runId:b.id,comment:b.comment,onSaved:e=>pe(b.id,e),onClose:()=>S(null)})]})}function uc({settings:e}){let t=nn.filter(t=>String(e[t]??``)!==``).map(t=>({key:t,label:on(t),control:{type:`static`,text:sn(t,e[t])}}));return t.length?(0,Z.jsx)(N,{label:`Target profile`,rows:t}):(0,Z.jsx)(`p`,{className:`note`,children:`No settings recorded.`})}function dc({runId:e,comment:t,onSaved:n,onClose:r}){let i=Y(),[a,o]=(0,J.useState)(t),[s,c]=(0,J.useState)(null),[l,u]=(0,J.useState)(!1);return(0,Z.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`,icon:v,busy:l,onSelect:async()=>{u(!0),c(null);try{await i.setComment(e,a),n(a)}catch{c(`Not saved: the server is unreachable.`),u(!1)}}}],closeLabel:`Close`,focusRow:`comment`,onClose:r})}function fc(e){let t=()=>({Runs:new Set(wn.filter(e=>e.on).map(e=>e.key)),"Run Scenarios":new Set(Tn.filter(e=>e.on).map(e=>e.key))});if(!e)return t();let n=t();for(let t of On){let r=t[0],i=e[r],a=new Set(t[1].map(e=>e.key)),o=e=>Dn[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 pc(e){return{Runs:{on:[...e.Runs],seen:wn.map(e=>e.key)},"Run Scenarios":{on:[...e[`Run Scenarios`]],seen:Tn.map(e=>e.key)}}}function mc({cols:e,onSave:t,onClose:n}){let[r,i]=(0,J.useState)(()=>({Runs:new Set(e.Runs),"Run Scenarios":new Set(e[`Run Scenarios`])})),[a,o]=(0,J.useState)(null);return(0,Z.jsx)(D,{title:`Select Columns`,onClose:n,children:(0,Z.jsxs)(`div`,{className:`hcols`,children:[On.map(([e,t])=>(0,Z.jsxs)(`div`,{className:`groups`,children:[(0,Z.jsx)(`h3`,{children:En[e]??e}),t.map(t=>(0,Z.jsxs)(`label`,{children:[(0,Z.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,Z.jsx)(`p`,{className:`note bad`,children:a}),(0,Z.jsxs)(`div`,{className:`hcols-actions`,children:[(0,Z.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`}),(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,onClick:n,children:`Close`})]})]})})}var hc=[`px`,`format`,`quality`],gc=[{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`}],_c={"image/jpeg":`JPEG`,"image/webp":`WebP`,"image/png":`PNG`},vc=e=>_c[e]??e.replace(`image/`,``).toUpperCase(),yc={px:`921600`,quality:`0.92`};function bc(e,t){let n=x().connectionImage({}).format,r=String(e.px??``),i=String(e.format??``),a=String(e.quality??``),o=(gc.some(e=>e.value===r)||!r?gc:[...gc,{value:r,label:x().budgetLabel(r)}]).map(e=>e.value===yc.px?{value:``,label:`${e.label} (default)`}:e),s=x().IMAGE_FORMATS.map(e=>e===n?{value:``,label:`${vc(e)} (default)`}:{value:e,label:vc(e)}),c=(i||n)===`image/png`,l={type:`text`,value:a,onChange:t(`quality`),size:`num`,...c?{marker:`unused`}:a?{}:{placeholder:yc.quality,marker:`default`}};return[{key:`px`,label:`Resolution`,control:{type:`select`,value:r===yc.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`,control:l}]}function xc(e){let{px:t,format:n,quality:r}=x().connectionImage(e),i=n===`image/png`?``:` q${r??yc.quality}`;return`${x().budgetLabel(t??Number(yc.px))} · ${vc(n)}${i}`}function Sc({offer:e}){let t=Y(),n=ve(),i=Ie(),a=Ke(),[o,s]=(0,J.useState)(null),[c,l]=(0,J.useState)(null),[u,d]=(0,J.useState)(null),[f,p]=(0,J.useState)(!1),m=(0,J.useRef)(null),h=e=>l({text:e instanceof Error?e.message:String(e),bad:!0}),g=(0,J.useCallback)(()=>{d(null),t.packs().then(e=>s(e.packs),e=>d(e instanceof Error?e.message:String(e)))},[t]);(0,J.useEffect)(g,[g]);let _=async()=>{await Promise.all([n.refresh(),i.refresh(),a.refresh()]),g()},v=async e=>{l({text:`Installing ${e.name}…`,bad:!1}),p(!0);try{let n=await t.installPack(e);await _();let r=(await t.packs()).packs.find(e=>e.id===n.pack),i=r?`${r.name} ${r.version}`:n.pack;l({text:n.installed?`Installed ${i}.`:`${i} is up to date.`,bad:!1})}catch(e){h(e)}finally{p(!1)}},b=async n=>{try{let{trash:r}=await t.removePack(n.id);await _(),e({label:`Removed ${n.name}`,restore:()=>{t.restorePack(r).then(_)}})}catch(e){h(e)}};return(0,Z.jsxs)(U,{id:`setup-packs`,title:`Packs`,note:o?Cc(o.length,`pack`):``,actions:[{label:`Install pack…`,icon:r,busy:f,onSelect:()=>m.current?.click()}],children:[o===null&&(0,Z.jsx)(k,{label:`Packs`,error:u,onRetry:g}),o&&!o.length&&(0,Z.jsx)(`p`,{className:`note`,children:`No packs installed.`}),o&&o.length>0&&(0,Z.jsx)(A,{className:`setup-table`,cards:!0,label:`Packs`,rows:o,rowKey:e=>e.id,columns:[{key:`name`,header:`Pack`,role:`title`,cell:e=>e.name},{key:`version`,header:`Version`,cell:e=>e.version},{key:`made`,header:`Made`,sort:null,cell:e=>wc(e)},{key:`menu`,header:``,className:`ds-menu`,role:`menu`,sort:null,cell:e=>(0,Z.jsx)(G,{label:`${e.name} actions`,actions:[{label:`Remove`,icon:y.remove,destructive:!0,onSelect:()=>void b(e)}]})}]}),c&&(0,Z.jsx)(`p`,{className:`note${c.bad?` bad`:``}`,role:c.bad?`alert`:`status`,children:c.text}),(0,Z.jsx)(`input`,{ref:m,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&&v(t)}})]})}var Cc=(e,t)=>`${e} ${t}${e===1?``:`s`}`,wc=e=>[Cc(e.datasets.length,`dataset`),Cc(e.pipelines.length,`pipeline`),Cc(e.sources.length,`Source`),Cc(e.presets,`preset`)].join(` · `);function Tc({offer:e}){let t=Y(),[n,i]=(0,J.useState)(null),[a,o]=(0,J.useState)(null),[s,c]=(0,J.useState)(null),[l,u]=(0,J.useState)(!1),d=(0,J.useRef)(null),f=(0,J.useCallback)(()=>{c(null),t.plugins().then(e=>i(e.plugins),e=>c(e instanceof Error?e.message:String(e)))},[t]);(0,J.useEffect)(f,[f]);let p=async e=>{o(null),u(!0);try{let n=await t.installPlugin(e),r=(await t.plugins()).plugins;i(r);let a=r.find(e=>e.id===n.plugin);a&&n.installed&&await pe(a),o({text:n.installed?X[n.plugin]?`Installed ${n.plugin}, and it did not load: ${X[n.plugin]}`:`Installed ${n.plugin}.`:`${n.plugin} is up to date.`,bad:!!X[n.plugin]})}catch(e){o({text:e instanceof Error?e.message:String(e),bad:!0})}finally{u(!1)}},m=async n=>{try{let{trash:r}=await t.removePlugin(n.id);f(),e({label:`Removed ${n.id}`,restore:()=>{t.restorePlugin(r).then(f)}})}catch(e){o({text:e instanceof Error?e.message:String(e),bad:!0})}};return(0,Z.jsxs)(U,{id:`setup-plugins`,title:`Plugins`,note:n?`${n.length} ${n.length===1?`plugin`:`plugins`}`:``,actions:[{label:`Install plugin…`,icon:r,busy:l,onSelect:()=>d.current?.click()}],children:[n===null&&(0,Z.jsx)(k,{label:`Plugins`,error:s,onRetry:f}),n&&!n.length&&(0,Z.jsx)(`p`,{className:`note`,children:`No plugins installed.`}),n&&n.length>0&&(0,Z.jsx)(A,{className:`setup-table`,cards:!0,label:`Plugins`,rows:n,rowKey:e=>e.id,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:null,cell:e=>(0,Z.jsx)(`code`,{title:e.sha256,children:e.sha256.slice(0,12)})},{key:`registers`,header:`Registers`,sort:null,cell:e=>Ec(e)||`—`},{key:`state`,header:`State`,cell:e=>Dc(e)},{key:`menu`,header:``,className:`ds-menu`,role:`menu`,sort:null,cell:e=>(0,Z.jsx)(G,{label:`${e.id} actions`,actions:[{label:`Remove`,icon:y.remove,destructive:!0,onSelect:()=>void m(e)}]})}]}),a&&(0,Z.jsx)(`p`,{className:`note${a.bad?` bad`:``}`,role:a.bad?`alert`:`status`,children:a.text}),(0,Z.jsx)(`input`,{ref:d,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&&p(t)}})]})}var Ec=e=>[...e.registers.outputKinds??[],...e.registers.modifiers??[],...e.registers.evalTypes??[],...(e.registers.connectionTypes??[]).map(e=>e.id)].join(`, `),Dc=e=>X[e.id]?`Failed: ${X[e.id]}`:de.has(e.id)?`Loaded`:`Not Loaded`,Oc={env:`Deployment`,lab:`Own`,default:`Default`};function kc({cfg:e,editable:t,onClose:n,onProblem:r}){let i=Y(),a=e?.from===`lab`?e:null,[o,s]=(0,J.useState)(a?.clientId??``),[c,l]=(0,J.useState)(a?.tenant??``),[u,d]=(0,J.useState)(null),f=(0,J.useRef)(null),p=(0,J.useRef)(Promise.resolve()),m=(0,J.useRef)(!0),h=(0,J.useRef)(r);h.current=r;let g=(0,J.useCallback)(e=>{f.current=null,p.current=p.current.then(()=>i.setMicrosoft(e.clientId,e.tenant)).then(()=>{m.current&&d(null),Gi()}).catch(e=>{let t=e instanceof Error?e.message:String(e);m.current?d(t):h.current(`Microsoft 365: ${t}`)})},[i]);(0,J.useEffect)(()=>{if(!f.current)return;let e=setTimeout(()=>{f.current&&g(f.current)},600);return()=>clearTimeout(e)},[g,o,c]),(0,J.useEffect)(()=>(m.current=!0,()=>{m.current=!1,f.current&&g(f.current)}),[g]);let _=(e,t)=>n=>{f.current={clientId:o,tenant:c,...f.current,[e]:n},t(n)},v=!t,y=new URL(`/`,zi()??window.location.href).href,b=[v?{key:`client`,label:`Client ID`,control:{type:`code`,text:e?.clientId??`—`}}:{key:`client`,label:`Client ID`,control:{type:`text`,value:o,onChange:_(`clientId`,s),size:`wide`,placeholder:e?.from==="default"?e.clientId:`00000000-0000-0000-0000-000000000000`}},v?{key:`tenant`,label:`Tenant`,control:{type:`code`,text:e?.tenant??`—`}}:{key:`tenant`,label:`Tenant`,control:{type:`text`,value:c,onChange:_(`tenant`,l),size:`wide`,placeholder:`00000000-0000-0000-0000-000000000000`}},{key:`redirect`,label:`Redirect URI`,control:{type:`code`,text:y}},{key:`app`,label:`App`,control:{type:`static`,text:e?.from?Oc[e.from]:`None`}}];return(0,Z.jsx)(j,{title:`Microsoft 365`,status:u??void 0,statusBad:!!u,focusRow:v?void 0:`client`,sections:[{key:`app`,rows:b}],onClose:n})}var Ac={env:`Deployment`,lab:`Own`,default:`Default`},jc=`https://console.cloud.google.com/apis/credentials`,Mc=[{value:`installed`,label:`Desktop app`},{value:`web`,label:`Web application`}],Nc={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.`},Pc=`/api/connections/google/callback`,Fc=()=>/^(localhost|127\.|\[::1\])/.test(window.location.hostname);function Ic(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 Lc({onClose:e,onProblem:t,onSaved:n}){let r=Y(),[i,a]=(0,J.useState)(void 0),[o,s]=(0,J.useState)(!0),[c,l]=(0,J.useState)(``),[u,d]=(0,J.useState)(``),[f,p]=(0,J.useState)(``),[m,h]=(0,J.useState)(Fc()?`installed`:`web`),[g,_]=(0,J.useState)(null),[v,y]=(0,J.useState)(null);(0,J.useEffect)(()=>{r.google().then(e=>{a(e.google),s(e.editable);let t=e.google?.from===`lab`?e.google:null;t&&(l(t.clientId),p(t.apiKey??``),h(t.clientType))},e=>{a(null),_(e instanceof Error?e.message:String(e))})},[r]);let b=(0,J.useRef)(null),x=(0,J.useRef)(Promise.resolve()),S=(0,J.useRef)(!0),C=(0,J.useRef)({onProblem:t,onSaved:n});C.current={onProblem:t,onSaved:n};let w=(0,J.useCallback)(e=>{b.current=null,x.current=x.current.then(()=>r.setGoogle(e)).then(e=>{S.current&&(_(null),a(e.google)),C.current.onSaved()}).catch(e=>{let t=e instanceof Error?e.message:String(e);S.current?_(t):C.current.onProblem(`Google Drive: ${t}`)})},[r]);(0,J.useEffect)(()=>{if(!b.current)return;let e=setTimeout(()=>{b.current&&w(b.current)},600);return()=>clearTimeout(e)},[w,c,u,f,m]),(0,J.useEffect)(()=>(S.current=!0,()=>{S.current=!1,b.current&&w(b.current)}),[w]);let T=(e,t)=>n=>{b.current={clientId:c,apiKey:f,clientType:m,...u?{clientSecret:u}:{},...b.current,[e]:n},t(n)},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=Ic(await e.text());if(typeof t==`string`){_(t);return}let n={...t,apiKey:f};l(n.clientId),h(n.clientType),d(``),y(`Loaded the client file`),w(n)};if(i===void 0)return null;let O=!o,k=!!i?.hasSecret&&i.from!=="default",A=O?i?.clientType??`web`:m,M=O?[{key:`client`,label:`Client ID`,control:{type:`code`,text:i?.clientId??`—`}},{key:`secret`,label:`Client secret`,control:{type:`static`,text:i?.hasSecret?`Held`:`None`}},{key:`key`,label:`API key`,control:{type:`code`,text:i?.apiKey??`—`}},{key:`type`,label:`Type`,control:{type:`static`,text:Mc.find(e=>e.value===A).label}}]:[{key:`client`,label:`Client ID`,control:{type:`text`,value:c,onChange:T(`clientId`,l),size:`wide`,placeholder:i?.from==="default"?i.clientId:`000000000000-….apps.googleusercontent.com`}},{key:`secret`,label:`Client secret`,control:{type:`secret`,value:u,onChange:T(`clientSecret`,e=>d(e??``)),...k?{placeholder:`Saved`}:{}}},{key:`key`,label:`API key`,control:{type:`text`,value:f,onChange:T(`apiKey`,p),size:`wide`,placeholder:`AIza…`}},{key:`type`,label:`Type`,hint:Nc[m],control:{type:`select`,value:m,options:Mc,onChange:e=>T(`clientType`,h)(e)}}];return M.push({key:`redirect`,label:`Redirect URI`,control:A===`web`?{type:`code`,text:new URL(Pc,window.location.href).href}:{type:`static`,text:`Not Needed`}},{key:`app`,label:`App`,control:{type:`static`,text:i?.from?Ac[i.from]:`None`}}),(0,Z.jsx)(j,{title:`Google Drive`,status:g??v??void 0,statusBad:!!g,focusRow:O?void 0:`client`,sections:[{key:`app`,rows:M}],actions:[{label:`Google Cloud`,icon:et,onSelect:()=>{window.open(jc,`_blank`,`noopener`)}},...O?[]:[{label:`Load client file…`,icon:nt,onSelect:E}]],onClose:e})}var Rc=`microsoft`,zc=`google`;function Bc(){let e=Y(),{cfg:t,editable:n}=Ki(),[r,i]=(0,J.useState)(null),[a,o]=(0,J.useState)(null),[s,c]=(0,J.useState)(void 0),[l,u]=(0,J.useState)(null),d=(0,J.useCallback)(()=>{e.connections().then(e=>o(e.connections),()=>o([]))},[e]);(0,J.useEffect)(d,[d]),(0,J.useEffect)(()=>{if(!t){c(null);return}Li(t).then(c,()=>c(null))},[t]);let f=[...a??[],...t||n?[{id:Rc,label:`Microsoft 365`,configured:!!t,signedIn:!!s,account:s??null,problem:null}]:[]],p=async n=>{u(null);try{n.id===Rc&&t?await Vi(t):window.location.assign((await e.signIn(n.id)).url)}catch(e){u(e instanceof Error?e.message:String(e))}},m=async n=>{u(null);try{n.id===Rc&&t?(await Hi(t),c(null)):o((await e.signOut(n.id)).connections)}catch(e){u(e instanceof Error?e.message:String(e))}};if(a===null)return(0,Z.jsx)(U,{id:`setup-connections`,title:`Connections`,children:(0,Z.jsx)(k,{label:`Connections`})});if(!f.length)return null;let h=f.filter(e=>e.problem);return(0,Z.jsxs)(U,{id:`setup-connections`,title:`Connections`,note:`${f.filter(e=>e.signedIn).length} of ${f.length}`,children:[(0,Z.jsx)(A,{className:`setup-table`,cards:!0,label:`Connections`,rows:f,rowKey:e=>e.id,columns:[{key:`label`,header:`Connection`,role:`title`,cell:e=>e.label},{key:`status`,header:`Status`,cell:e=>e.id===Rc&&t&&s===void 0?(0,Z.jsxs)(`span`,{className:`loading-status`,children:[(0,Z.jsx)(W,{}),`Checking`]}):Vc(e)},{key:`account`,header:`Account`,cell:e=>e.account||`—`},{key:`menu`,header:``,className:`ds-menu`,role:`menu`,sort:null,cell:e=>(0,Z.jsx)(G,{label:`${e.label} actions`,actions:[e.signedIn?{label:`Sign out`,icon:pt,onSelect:()=>void m(e)}:{label:`Sign in`,icon:ft,disabled:!e.configured,onSelect:()=>void p(e)},...e.id===Rc||e.id===zc?[{label:`Configure…`,icon:bt,onSelect:()=>i(e.id)}]:[]]})}]}),h.map(e=>(0,Z.jsxs)(`p`,{className:`note bad`,role:`alert`,children:[e.label,`: `,e.problem]},e.id)),l&&(0,Z.jsx)(`p`,{className:`note bad`,role:`alert`,children:l}),r===Rc&&t!==void 0&&(0,Z.jsx)(kc,{cfg:t,editable:n,onClose:()=>i(null),onProblem:u}),r===zc&&(0,Z.jsx)(Lc,{onClose:()=>i(null),onProblem:u,onSaved:d})]})}var Vc=e=>e.configured?e.signedIn?`Signed In`:`Signed Out`:`Not Configured`;function Hc(){let e=ve(),t=Y(),n=ne(),[r,i]=ye(`promptlab.profiles`),[a]=ye(`promptlab.versions`),[o,s]=(0,J.useState)(null),[c,l]=(0,J.useState)(null),[u,d]=(0,J.useState)(null),[f,p]=(0,J.useState)({}),[m,g]=(0,J.useState)(``),[_,v]=(0,J.useState)(``),[y,b]=(0,J.useState)(``),[S,C]=(0,J.useState)(null),[w,T]=(0,J.useState)([]),[E,D]=(0,J.useState)({});(0,J.useEffect)(()=>{let e=!0;return t.presets().then(t=>{e&&T(t)}).catch(()=>{}),()=>{e=!1}},[t]);let k=(0,J.useRef)(r);k.current=r;let j=(0,J.useCallback)(e=>{let t=k.current,n={...t,list:t.list.map(t=>t.id===e.id?e:t)};k.current=n,i(n),P(e)},[i]),M=(0,J.useRef)(null),N=(0,J.useRef)(null),P=(0,J.useCallback)(t=>{N.current&&clearTimeout(N.current),M.current={p:t},N.current=setTimeout(()=>{let t=M.current;t&&je(e,`profile`,t.p.id,t.p,`idle`)},De)},[e]);(0,J.useEffect)(()=>()=>{N.current&&clearTimeout(N.current)},[]);let ee=(0,J.useCallback)(()=>{let e=ol(),t=k.current,n={...t,list:[...t.list,e],at:e.id};k.current=n,i(n),s({id:e.id,focus:`name`})},[i]),F=(0,J.useCallback)(e=>{let t=k.current.list.find(t=>t.id===e);if(!t)return;let n={...structuredClone(t),id:al(),name:`${t.name||`Profile`} copy`,key:t.key},r={...k.current,list:[...k.current.list,n]};k.current=r,i(r)},[i]),I=(0,J.useCallback)(e=>{let t=k.current,r=t.list.filter(t=>t.id!==e);if(!r.length)return;let a={list:r,at:r[0].id};k.current=a,i(a),s(null);let o=t.list.find(t=>t.id===e);n.offer({label:`Deleted ${o?.name||`the profile`}`,restore:()=>{k.current=t,i(t)}})},[i,n]),L=(0,J.useCallback)(t=>{let n=t.doc.id,r=k.current.list.find(e=>e.id===n);r&&je(e,`profile`,n,r,`restore`);let a=k.current,o={...a,list:a.list.map(e=>e.id===n?t.doc:e)};k.current=o,i(o),te()},[e,i]),te=(0,J.useCallback)(()=>{l(e=>(e?.back&&s({id:e.id}),null))},[]),R=(0,J.useCallback)(async e=>{let n=k.current.list.find(t=>t.id===e);if(!n)return;let r=x().CONNECTION_TYPES[n.type];if(r?.local){p(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=[];p(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=>$c(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(D(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=x().apiBase(n.url||r?.url||``),a=x().connectionRequest(n,`hi`,null,e,i),o=await t.modelsAsk({url:n.url,key:i,type:n.type,body:a.body}),{raw:s}=x().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.`)}p(t=>({...t,[e]:{phase:`connected`,lines:c,ms:s()}}))}catch(t){c.push(...c.length?[``]:[],t instanceof Error?t.message:String(t)),p(t=>({...t,[e]:{phase:`error`,lines:c,ms:s()}}))}},[t]),B=o?r.list.find(e=>e.id===o.id):void 0,V=B?JSON.stringify([B.id,B.url,B.type,B.key]):``;(0,J.useEffect)(()=>{if(!B)return;let e=B;if(x().CONNECTION_TYPES[e.type]?.local||x().CONNECTION_TYPES[e.type]?.lists===!1)return;let n=x().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&&D(n=>({...n,[e.id]:(t.data||[]).map(e=>e.id).sort()}))}).catch(()=>{r&&D(t=>({...t,[e.id]:[]}))})},400);return()=>{r=!1,clearTimeout(i)}},[t,V]);let re=(0,J.useCallback)((e,t)=>{let n=k.current.list.find(t=>t.id===e);if(!n)return;let r={...n};for(let e of nl(n.type))r[e]=``;for(let[e,n]of Object.entries(t.opts))r[e]=n;k.current={...k.current,list:k.current.list.map(t=>t.id===e?r:t)},i(k.current),P(r)},[i,P]),H=(0,J.useCallback)(e=>{p(t=>{if(!(e in t))return t;let{[e]:n,...r}=t;return r})},[]),ie=(0,J.useCallback)((e,t,n)=>{let r=k.current.list.find(t=>t.id===e);r&&([`url`,`key`,`model`].includes(t)&&H(e),j({...r,[t]:n}))},[j,H]),ae=(0,J.useCallback)((e,t)=>{let n=k.current.list.find(t=>t.id===e);if(!n)return;let r={...n,type:t};H(e),D(t=>({...t,[e]:[]}));let i=x().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`,`url`,`model`,`key`,`temperature`,`type`,...hc].includes(e)||rl(t).includes(e)||delete r[e];j(r)},[j,H]),W=(0,J.useCallback)((e,t)=>{s(t?{id:e,focus:t}:{id:e})},[]),G=(0,J.useCallback)(e=>a.profile?.[e]??[],[a]),K=o?r.list.find(e=>e.id===o.id)??null:null,q=[...new Set(r.list.map(e=>e.type))],oe=m.trim().toLowerCase(),se=r.list.filter(e=>(!_||e.type===_)&&(!y||y===`set`==!!e.key)&&(!oe||[e.name,e.url,e.model].some(e=>String(e??``).toLowerCase().includes(oe))));return(0,Z.jsxs)(`div`,{className:`setup`,children:[(0,Z.jsxs)(U,{id:`setup-profiles`,title:`Target profiles`,note:il(r.list.length),children:[(0,Z.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,Z.jsx)(z,{noun:`profiles`,search:{label:`Search profiles`,placeholder:`Name, address or model`,value:m,onChange:g},filters:[{key:`type`,label:`Type`,value:_,onChange:v,options:[{value:``,label:`All`},...q.map(e=>({value:e,label:x().CONNECTION_TYPES[e]?.label??e}))]},{key:`key`,label:`Key`,value:y,onChange:b,options:[{value:``,label:`All`},{value:`set`,label:`Set`},{value:`unset`,label:`Not set`}]},{key:`sort`,label:`Sort`,value:S?.key??``,onChange:e=>C(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:se.length,total:r.list.length}}),r.list.length===0?(0,Z.jsx)(`p`,{className:`note`,children:`No profiles yet.`}):se.length===0?(0,Z.jsx)(`p`,{className:`note`,children:`No profiles match these filters.`}):(0,Z.jsx)(A,{className:`setup-table`,cards:!0,label:`Target profiles`,sort:S,onSort:C,rows:se,rowKey:e=>e.id,rowProps:e=>({className:`setup-row`,onClick:t=>{t.target.closest(`button, a, .menu`)||W(e.id)}}),columns:Uc({tests:f,only:r.list.length===1,grader:r.grader??null,onGrader:e=>{let t=k.current,n={...t,grader:t.grader===e?``:e};k.current=n,i(n)},onOpen:W,onClone:F,onRemove:I,onTest:R,onResult:e=>d({id:e,back:!1})})}),(0,Z.jsxs)(`button`,{type:`button`,className:`ghost add-btn`,onClick:ee,children:[(0,Z.jsx)(h,{size:14,"aria-hidden":`true`}),`Add profile`]})]}),(0,Z.jsx)(Bc,{}),(0,Z.jsx)(Tc,{offer:n.offer}),(0,Z.jsx)(Sc,{offer:n.offer}),(0,Z.jsx)(O,{undo:n.undo,onUndo:n.undoNow,onDismiss:n.dismiss}),K&&(0,Z.jsx)(Wc,{profile:K,...o?.focus?{focus:o.focus}:{},test:f[K.id],models:E[K.id]??[],presets:w.filter(e=>(e.type??`llama.cpp`)===K.type),canRestore:!!G(K.id).length,onClose:()=>s(null),onSetting:ie,onType:ae,onTest:R,onResult:()=>{s(null),d({id:K.id,back:!0})},onRestore:()=>{s(null),l({id:K.id,back:!0})},onApplyPreset:e=>re(K.id,e)}),u&&f[u.id]&&(0,Z.jsx)(Qc,{test:f[u.id],onClose:()=>{u.back&&s({id:u.id}),d(null)}}),c&&(0,Z.jsx)(Xc,{versions:G(c.id),onClose:te,onRestore:L})]})}function Uc({tests:e,only:t,grader:n,onGrader:r,onOpen:i,onClone:a,onRemove:o,onTest:s,onResult:c}){let l=e=>e.name||`Unnamed profile`,u=c=>[{label:`Edit…`,icon:y.edit,onSelect:()=>i(c.id)},{label:`Rename`,icon:y.rename,onSelect:()=>i(c.id,`name`)},{label:`Clone`,icon:y.clone,onSelect:()=>a(c.id)},{label:`Test connection`,icon:L,busy:e[c.id]?.phase===`checking`,onSelect:()=>void s(c.id)},...(x().CONNECTION_TYPES[c.type]?.answers??[`prompt`]).includes(`prompt`)&&!x().CONNECTION_TYPES[c.type]?.local?[{label:n===c.id?`Stop grading`:`Make grader`,icon:lt,onSelect:()=>r(c.id)}]:[],...t?[]:[{label:`Remove`,icon:y.remove,destructive:!0,onSelect:()=>o(c.id)}]];return[{key:`name`,header:`Profile`,role:`title`,sort:l,cell:t=>{let r=e[t.id];return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`button`,{type:`button`,className:`setup-open`,onClick:()=>i(t.id),children:l(t)}),n===t.id&&(0,Z.jsx)(`span`,{className:`setup-note`,children:`Grader`}),r&&(0,Z.jsx)(`button`,{type:`button`,className:`edit-outcome setup-note${r.phase===`error`?` bad`:``}`,"aria-label":`Test connection: ${Zc[r.phase]}`,onClick:()=>c(t.id),children:Zc[r.phase]})]})}},{key:`type`,header:`Type`,label:``,cell:e=>x().CONNECTION_TYPES[e.type]?.label??e.type},{key:`url`,header:`Address`,sort:e=>e.url.trim(),cell:e=>x().CONNECTION_TYPES[e.type]?.local?(0,Z.jsx)(`span`,{className:`setup-unset`,children:`—`}):e.url.trim()||(0,Z.jsx)(`span`,{className:`setup-unset`,children:`(server)`})},{key:`model`,header:`Model`,sort:e=>e.model.trim(),cell:e=>x().CONNECTION_TYPES[e.type]?.local?(0,Z.jsx)(`span`,{className:`setup-unset`,children:`—`}):e.model.trim()||(0,Z.jsx)(`span`,{className:`setup-unset`,children:`Not set`})},{key:`key`,header:`Key`,sort:e=>e.key?`Set`:``,cell:e=>x().CONNECTION_TYPES[e.type]?.keyless?(0,Z.jsx)(`span`,{className:`setup-unset`,children:`—`}):e.key?`Set`:(0,Z.jsx)(`span`,{className:`setup-unset`,children:`Not set`})},{key:`menu`,header:``,label:``,className:`setup-menu`,role:`menu`,sort:null,cell:e=>(0,Z.jsx)(G,{actions:u(e),label:`${l(e)} actions`})}]}function Wc({profile:e,focus:t,test:n,models:r,presets:i,canRestore:a,onClose:o,onSetting:s,onType:c,onTest:l,onResult:u,onRestore:d,onApplyPreset:f}){let p=x().CONNECTION_TYPES[e.type],m=(p?.answers??[`prompt`]).includes(`prompt`),h=(0,J.useMemo)(()=>Yc(e),[e]),g=t=>n=>s(e.id,t,n),_=[{key:`name`,label:`Name`,required:!0,control:{type:`text`,value:e.name,onChange:g(`name`)}},{key:`type`,label:`Type`,required:!0,hint:p?.description,control:{type:`select`,value:e.type,onChange:t=>c(e.id,t),options:Object.entries(x().CONNECTION_TYPES).filter(([t,n])=>n.picker!==!1||t===e.type).map(([e,t])=>({value:e,label:t.label}))}},...p?.local?[]:[{key:`url`,label:`Address`,control:{type:`text`,value:e.url,placeholder:p?.url??`the lab's Ollama`,onChange:g(`url`)}},...p?.keyless?[]:[{key:`key`,label:`Key`,control:{type:`secret`,value:e.key,onChange:g(`key`)}}],...m?[{key:`model`,label:`Model`,control:tl(e.model,r,g(`model`))}]:[]]],v=(p?.settings??[]).map(t=>Gc(e,t,g(t.key))),b=[{key:`identity`,rows:_},...v.length?[{key:`settings`,title:`Settings`,rows:v}]:[],...p?.local||!m?[]:[{key:`image`,title:`Image`,rows:bc(e,g)},{key:`debug`,title:`Debug`,rows:h,folded:!0}]],S=[{label:`Restore…`,icon:I,disabled:!a,onSelect:d},...i.map(e=>({label:`Apply preset: ${e.label}`,icon:y.preset,onSelect:()=>f(e)})),...(p?.templates??[]).map(t=>({label:`Apply template: ${t.label}`,icon:y.preset,onSelect:()=>f({id:t.id,label:t.label,type:e.type,opts:t.settings})}))];return(0,Z.jsx)(j,{title:e.name||`Unnamed profile`,...t?{focusRow:t}:{},sections:b,menu:S,actions:p?.tests===!1?[]:[{label:`Test connection`,icon:L,busy:n?.phase===`checking`,onSelect:()=>l(e.id),outcome:n?{label:Zc[n.phase],bad:n.phase===`error`,onOpen:u}:void 0}],onClose:o})}function Gc(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:qc(e,t.key),a={type:`text`,value:r,onChange:n,...i?.placeholder?{placeholder:i.placeholder}:{},...i?{marker:i.marker}:{},...i?.numeric?{size:`num`}:{}};return{key:t.key,label:t.label,control:a}}var Kc=`424242`;function qc(e,t){let n=x().apiBase(e.url),r,i;try{r=Jc(x().connectionRequest({...e,[t]:``},`(prompt)`,null,n).body),i=Jc(x().connectionRequest({...e,[t]:Kc},`(prompt)`,null,n).body)}catch{return null}let a=Object.keys(i).find(e=>i[e]===Kc||i[e]===JSON.stringify(Kc));if(a===void 0)return null;let o=i[a]===Kc,s=a in r?JSON.parse(r[a]):null;return s===null?{marker:`server`,numeric:o}:{placeholder:String(s),marker:`default`,numeric:o}}function Jc(e,t=``,n={}){if(e&&typeof e==`object`&&!Array.isArray(e))for(let[r,i]of Object.entries(e))Jc(i,t?`${t}.${r}`:r,n);else n[t]=JSON.stringify(e)??`null`;return n}function Yc(e){let t=x().apiBase(e.url),n=[];try{let{url:r,body:i}=x().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:xc(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 Xc({versions:e,onClose:t,onRestore:n}){return(0,Z.jsx)(D,{title:`Restore profile`,onClose:t,children:(0,Z.jsxs)(`div`,{className:`version-list`,children:[e.length===0&&(0,Z.jsx)(`p`,{className:`note`,children:`No versions of this profile yet.`}),e.map((e,t)=>(0,Z.jsxs)(`div`,{className:`version-row`,children:[(0,Z.jsxs)(`span`,{className:`version-when`,children:[cl(e.at),` · `,sl(e.reason)]}),(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>n(e),children:`Restore`})]},`${e.at}-${t}`))]})})}var Zc={checking:`Checking…`,connected:`Connected`,error:`Error`};function Qc({test:e,onClose:t}){return(0,Z.jsx)(j,{title:`Test connection`,sections:[{key:`result`,rows:[{key:`time`,label:`Time`,required:!0,control:{type:`static`,text:e.ms==null?`—`:el(e.ms)}},{key:`result`,label:`Result`,required:!0,control:{type:`textarea`,value:e.lines.join(`
|
|
14
|
+
`)}}]}],closeLabel:`Close`,onClose:t})}function $c(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 el=e=>e<1e3?`${e} ms`:`${(e/1e3).toFixed(1)}s`;function tl(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 nl(e){return x().CONNECTION_TYPES[e]?.settings.map(e=>e.key).filter(e=>e!==`temperature`)??[]}function rl(e){return x().CONNECTION_TYPES[e]?.settings.map(e=>e.key)??[]}var il=e=>e===1?`1 profile`:`${e} profiles`,al=()=>`p${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`,ol=()=>({id:al(),name:`New profile`,url:``,model:``,key:``,temperature:``,nPredict:``,maxTokens:``,type:`ollama`}),sl=e=>e===`run`?`before a run`:e===`restore`?`before a restore`:`after editing`,cl=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},ll=[];function ul(e,t){let n=Y(),[r,i]=(0,J.useState)(null);(0,J.useEffect)(()=>{if(t===null)return;let r=!0,a=xe(n);return a.runDataset(e).then(n=>{if(n){r&&i({run:e,cases:x().upgradeDatasetBody(n).cases,current:!1});return}return a.dataset(t).then(t=>{r&&i({run:e,cases:x().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:ll,current:a?.current??!1}}function dl(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=>x().metricLines(e.values)),forbidden:t.filter(e=>e.not&&e.type===`contains`).map(e=>({value:String(e.value??``),except:x().metricLines(e.except)}))}}var fl=e=>e==null?`—`:yn(e);function pl(e){return e?.transcript||[]}function ml(e,t){return t.flatMap((n,r)=>{let i=pl(e?.scenarios?.[r]?.res);return t.length>1?i.map(e=>({...e,scenario:n.name})):i})}function hl({stages:e}){if(!e.length)return null;let t=!e.some(e=>e.scenario)&&e.length>1?` · ${e.map(e=>fl(e.ms)).join(` + `)}`:``;return(0,Z.jsxs)(`div`,{className:`transcript`,children:[(0,Z.jsxs)(`div`,{className:`meta`,children:[`Transcript`,t]}),e.map((e,t)=>(0,Z.jsxs)(`pre`,{children:[(0,Z.jsxs)(`b`,{children:[e.scenario?`${e.scenario} · `:``,`job `,e.n,` `,e.withImage?`(with image)`:`(text only)`,e.kind?` · ${e.kind}`:``,e.conn?` · ${e.conn}`:``,` · `,fl(e.ms),` — sent`]}),`
|
|
15
|
+
`,e.sent,`
|
|
16
|
+
`,(0,Z.jsx)(`b`,{children:`— returned`}),`
|
|
17
|
+
`,e.got||(e.error?`(nothing)`:``),e.error?`\n<b className="fault">Error - ${e.error}</b>`:``]},t))]})}function gl({text:e,kind:t}){return(0,Z.jsx)(`span`,{className:`term${t?` ${t}`:``}`,children:e})}function _l({res:e,kase:t}){let n=e?.dropped||[];if(!n.length)return null;let r=e=>t?dl(t).wanted.some(t=>x().termIn([e],t)):!1;return(0,Z.jsxs)(`details`,{className:`dropped`,children:[(0,Z.jsxs)(`summary`,{children:[`Dropped `,n.length]}),n.map((e,t)=>(0,Z.jsxs)(`div`,{className:`droppedrow`,children:[(0,Z.jsx)(gl,{text:e.item,kind:`no`}),(0,Z.jsxs)(`span`,{className:`note`,children:[e.by,r(e.item)&&(0,Z.jsx)(`b`,{className:`fault`,children:` · wanted`})]})]},t))]})}function vl({kase:e}){return(0,Z.jsx)(Z.Fragment,{children:(e.metrics??[]).map((e,t)=>(0,Z.jsx)(`div`,{className:`wants${e.weight===0?` watched`:``}`,children:ar(e)},t))})}var yl=e=>e?.transcript?.at(-1)?.kind===`text`;function bl({res:e}){return e?.error?(0,Z.jsx)(`span`,{className:`err`,children:e.error}):yl(e)?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`pre`,{children:e?.transcript?.at(-1)?.got||`(empty)`}),(0,Z.jsx)(`div`,{className:`meta`,children:fl(e?.ms)})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`chips`,children:(e?.terms||[]).map((e,t)=>(0,Z.jsx)(gl,{text:String(e)},t))}),(0,Z.jsx)(_l,{res:e,kase:null}),(0,Z.jsxs)(`div`,{className:`meta`,children:[(e?.terms||[]).length,` items · `,fl(e?.ms)]})]})}function xl({res:e}){if(e?.error)return(0,Z.jsx)(`span`,{className:`err`,children:e.error});let t=e?.transcript?.at(-1)?.got??e?.raw??``;return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`pre`,{children:t||`(empty)`}),(0,Z.jsxs)(`div`,{className:`meta`,children:[fl(e?.ms),` · `,yl(e)?`answered as text`:`read as ${(e?.terms||[]).length} items`]})]})}function Sl({tab:e}){let t=Y(),{setShow:n}=Jt(),{openCaseEditor:r}=Rr(),[i,a]=(0,J.useState)(null),[s,c]=(0,J.useState)(!1),[l,u]=(0,J.useState)(null),[d,f]=(0,J.useState)(new Set),[m,h]=(0,J.useState)(!1),[g,_]=(0,J.useState)(null),[v,b]=(0,J.useState)(null),[S,C]=(0,J.useState)(0);(0,J.useEffect)(()=>{let n=!0,r=!1,i,o=async()=>{try{let s=await t.run(e.id);if(!n)return;r=!0,a(s),b(null),kn(s.status)||(i=setTimeout(()=>void o(),1e3))}catch(e){if(!n)return;r?i=setTimeout(()=>void o(),1e3):b(e instanceof he?e.message:`Run not loaded: server unreachable.`)}};return o(),()=>{n=!1,i&&clearTimeout(i)}},[t,e.id,S]);let w=(0,J.useMemo)(()=>i?Hn(i):null,[i]),T=w?x().evalsDataset(w.snapshot)?.id??null:null,E=ul(e.id,T),D=(0,J.useMemo)(()=>new Map(E.cases.map(e=>[x().caseItem(e),e])),[E.cases]),O=(0,J.useCallback)(async()=>{c(!0);try{await t.cancel(e.id)}catch{}c(!1)},[t,e.id]);if(!w)return(0,Z.jsx)(U,{id:`run-${e.id}`,title:un(e.at)||`Run`,children:(0,Z.jsx)(k,{label:`Run`,error:v,onRetry:()=>{b(null),C(e=>e+1)}})});let j=w.progress,M=j.n??j.total??0,N=!kn(w.status),P=j.total&&M!=null&&N?Math.round(M/j.total*100):null,ee=lr(w,E.cases),F=w.scenarios.map((e,t)=>dr(w,E.cases,t)),I=Qn(w),L=(e,t,n)=>{let r=new Set(e);r.has(t)?r.delete(t):r.add(t),n(r)},te=async(e,t,n)=>{let r=Math.max(0,w.scenarios.findIndex((t,n)=>In(w,e,n))),i=(t.scenarios??[])[r]?.res;i&&await bs(or(w.snapshot,n,i,r))&&(h(!0),setTimeout(()=>h(!1),1600))},R=async()=>{await bs(ee.map(e=>or(w.snapshot,e.kase,e.res,e.scenarioIndex)).join(`
|
|
18
|
+
|
|
19
|
+
`+`-`.repeat(60)+`
|
|
20
|
+
|
|
21
|
+
`))&&(h(!0),setTimeout(()=>h(!1),1600))},ne=ee.length?[{label:`Copy all failures`,icon:o,onSelect:()=>void R()}]:[],B={key:`show`,label:`Show`,value:e.show,onChange:t=>n(e.id,t),options:[{value:`all`,label:`All`},{value:`failed`,label:`Failed`}]},V=!!T,re=w.evals.find(e=>`dataset`in e&&e.dataset)?.id??null,H=!!(w.content&&x().CONTENT_TYPES[w.content.type]?.inline),ie=e=>{let t=w.results[e]?.name;return t?D.get(t):void 0},ae=n=>{let i=w.results[n],s=ie(n),c=!!i&&!i.unrun&&kn(w.status),l=(i?.scenarios??[]).some(e=>e?.res?.transcript?.length),u=[];return l&&u.push({label:`Show details`,icon:p,onSelect:()=>L(d,n,f)}),c&&i?.name&&s&&u.push({label:`Edit case`,icon:y.edit,onSelect:()=>T&&r(i.name,{dataset:T,resultFor:e=>w.results[n]?.scenarios?.[e]?.res??null,scenarioCount:w.scenarios.length,files:w.results.filter(e=>e.kind!==`text`).map(e=>e.name??``)})}),c&&w.id&&u.push({label:`Re-run row`,icon:_t,onSelect:()=>void t.rerun(e.id,n).then(e=>a(e.run)).catch(()=>{})}),c&&s&&Cl(w,n)&&u.push({label:`Copy as AI prompt`,icon:o,onSelect:()=>void te(n,i,s)}),u};return(0,Z.jsxs)(`div`,{className:`runview`,children:[(0,Z.jsxs)(U,{id:`run-${e.id}`,title:w.name||un(e.at),actions:ne,children:[(0,Z.jsxs)(`div`,{className:`runhead`,children:[I&&(0,Z.jsxs)(`span`,{className:`note run-queue`,children:[(0,Z.jsx)(`span`,{className:`run-state`,children:I.state}),I.detail&&(0,Z.jsx)(`span`,{className:`run-item`,children:I.detail})]}),N&&(0,Z.jsxs)(`button`,{type:`button`,className:`ghost stop-btn`,disabled:s,onClick:()=>void O(),children:[s?(0,Z.jsx)(W,{}):(0,Z.jsx)(Ze,{size:14,"aria-hidden":`true`}),`Stop`]})]}),N&&(0,Z.jsx)(`div`,{className:`rrbar`,children:P==null?(0,Z.jsx)(`span`,{className:`rrprogress`,children:`Waiting`}):(0,Z.jsxs)(`div`,{className:`rrmeter`,role:`progressbar`,"aria-valuenow":P,"aria-valuemin":0,"aria-valuemax":100,children:[(0,Z.jsx)(`div`,{className:`rrbarfill`,style:{width:`${P}%`}}),(0,Z.jsxs)(`span`,{className:`rrpct`,style:{"--pct":`${P}%`},children:[P,`%`]})]})}),w.error&&(0,Z.jsx)(`p`,{className:`note bad rrstatus`,role:`status`,children:w.error}),(0,Z.jsx)(`div`,{id:`run-${e.id}-stats`,className:`runstats`,children:(0,Z.jsx)($t,{label:`Run Statistics`,...qn(w)})}),w.evals.length>0&&(0,Z.jsx)(Tl,{id:`run-${e.id}-evals`,rows:Vn(w),scenarios:w.scenarios,onScenario:_}),(0,Z.jsxs)(U,{id:`run-${e.id}-results`,title:`Results`,level:3,children:[(0,Z.jsx)(z,{noun:`results`,filters:[B],lead:(0,Z.jsx)(`p`,{className:`note`,children:dn(w.items.length,`item`)}),count:{total:w.items.length,shown:e.show===`failed`?w.items.filter((e,t)=>Cl(w,t)).length:w.items.length}}),E.current&&(0,Z.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,Z.jsx)(`div`,{className:`scrollx`,style:{"--scenarios":w.scenarios.length},children:(0,Z.jsx)(A,{className:V?`rrtable graded`:`rrtable`,label:`Results`,rows:w.items.map((e,t)=>t),rowKey:e=>`${w.items[e]}-${e}`,pinned:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`tr`,{className:`scenstats`,children:[(0,Z.jsx)(`td`,{className:`scenstats-label`,children:`Statistics`}),V&&(0,Z.jsx)(`td`,{className:`scenstats-blank`}),w.scenarios.map((e,t)=>(0,Z.jsx)(`td`,{className:`scenstat`,"data-label":e.name,children:(0,Z.jsx)($t,{dense:!0,label:`${e.name} statistics`,...Yn(w,t)})},e.id))]}),F.some(e=>e.length>0)&&T&&(0,Z.jsx)(wl,{from:un(e.at)||w.name,datasetId:T,failing:F,scenarios:w.scenarios,items:w.items.length,graded:V})]}),rowProps:t=>({"data-item":t,className:d.has(t)?`hasdetail`:void 0,hidden:e.show===`failed`&&!Cl(w,t)}),after:t=>d.has(t)&&(0,Z.jsx)(`tr`,{className:`rrdetail`,"data-detail":t,hidden:e.show===`failed`&&!Cl(w,t),children:(0,Z.jsx)(`td`,{colSpan:1+ +!!V+w.scenarios.length,children:(0,Z.jsx)(hl,{stages:ml(w.results[t],w.scenarios)})})}),columns:[{key:`item`,header:H?`Text`:`Item`,label:``,className:`col-item`,sort:e=>w.items[e]||``,cell:e=>{let t=w.results[e],n=w.items[e];return(0,Z.jsxs)(Z.Fragment,{children:[t?.name&&!H&&Tr(t.name)?(0,Z.jsx)(`button`,{type:`button`,className:`thumb`,"aria-label":`Open ${t.name}`,onClick:()=>u(t.name),children:(0,Z.jsx)(`img`,{src:er(w,t.name),alt:``,loading:`lazy`,"data-name":t.name})}):null,(0,Z.jsxs)(`div`,{className:`rritem`,children:[(0,Z.jsx)(`div`,{className:`meta`,children:n||``}),(0,Z.jsx)(G,{actions:ae(e),label:`${n||`row`} actions`})]})]})}},...V?[{key:`expected`,header:`Expected`,className:`col-expected`,sort:e=>{let t=ie(e);return t&&!t.todo?t.metrics?.length??0:null},cell:e=>{let t=ie(e);return w.results[e]?t&&!t.todo?(0,Z.jsx)(vl,{kase:t}):(0,Z.jsx)(`span`,{className:`note`,children:`n/a`}):``}}]:[],...w.scenarios.map((e,t)=>({key:`scenario-${t}`,header:e.name,label:e.name,onHeader:()=>_(t),cell:e=>(0,Z.jsx)(El,{item:w.results[e],i:t,readings:(w.outcomes[t]??[]).filter(e=>!e.whole).map(t=>({label:t.label,dataset:t.id===re,score:t.items[e]??null}))})}))]})})]}),m&&(0,Z.jsx)(`p`,{className:`note`,role:`status`,children:`Copied to clipboard.`})]}),g!=null&&(0,Z.jsx)(Ms,{run:w.snapshot,i:g,onClose:()=>_(null)}),l&&(0,Z.jsx)(Al,{src:tr(w,l),name:l,onClose:()=>u(null)})]})}var Cl=(e,t)=>{let n=e.results[t];return!!n&&(!!n.unrun||(n.scenarios??[]).some((n,r)=>In(e,t,r)||!!n?.res?.error))};function wl({from:e,datasetId:t,failing:n,scenarios:r,items:i,graded:a}){let{showCases:o}=Gt(),{list:s}=Le(),c=s!==null&&!s.some(e=>e.id===t),l=r.length>1;return(0,Z.jsxs)(`tr`,{className:`reasons`,children:[(0,Z.jsx)(`td`,{className:`scenstats-label`,children:`Reasons`}),a&&(0,Z.jsx)(`td`,{className:`scenstats-blank`}),r.map((r,a)=>{let s=r.name,u=n[a]??[];return(0,Z.jsx)(`td`,{className:`reasons-cell`,"data-label":s,children:u.length===0?(0,Z.jsx)(`span`,{className:`reasons-none`,children:`No failures`}):(0,Z.jsx)(`ul`,{className:`reasons-list`,"aria-label":`${s} reasons`,children:u.map(n=>{let r=n.files.length,a=(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`reason-n`,children:r}),(0,Z.jsxs)(`span`,{className:`reason-t`,children:[n.label,n.note&&(0,Z.jsxs)(`span`,{className:`reason-note`,children:[` `,n.note]})]})]});return(0,Z.jsx)(`li`,{"data-group":n.key,style:{"--share":`${Math.round(r/Math.max(i,1)*100)}%`},children:c?(0,Z.jsx)(`span`,{className:`reason`,children:a}):(0,Z.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 Tl({id:e,rows:t,scenarios:n,onScenario:r}){return(0,Z.jsx)(U,{id:e,title:`Evals`,level:3,children:(0,Z.jsx)(`div`,{className:`scrollx`,style:{"--scenarios":n.length},children:(0,Z.jsx)(A,{className:`ruletable`,label:`Evals`,rows:t,rowKey:e=>e.key,rowProps:e=>({className:e.first?`rule-first`:void 0,"data-rule":e.key}),columns:[{key:`eval`,header:`Eval`,label:``,sort:null,className:`col-eval rule-eval`,cell:e=>e.first&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`rule-eval-name`,children:e.eval}),` `,(0,Z.jsx)(`span`,{className:`rule-type`,children:e.type})]})},{key:`rule`,header:`Rule`,label:``,sort:null,className:`col-rule`,cell:e=>(0,Z.jsxs)(Z.Fragment,{children:[e.rule,e.want!=null&&(0,Z.jsxs)(Z.Fragment,{children:[` `,(0,Z.jsx)(`code`,{className:`rule-want`,children:e.want})]})]})},...n.map((e,t)=>({key:`scenario-${t}`,header:e.name,label:e.name,sort:null,onHeader:()=>r(t),cell:e=>{let n=e.cells[t];if(!n)return null;let r=n.state===`met`?`✓ `:n.state===`not`?`✗ `:``;return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`span`,{className:`rule-state ${n.state}`,children:[r,n.value]}),n.note&&(0,Z.jsx)(`span`,{className:`rule-note`,children:n.note})]})}}))]})})})}function El({item:e,i:t,readings:n}){let r=e?.scenarios?.[t]?.res;if(e?.unrun)return(0,Z.jsx)(`span`,{className:`err`,children:e.unrun});if(!r)return(0,Z.jsx)(`span`,{className:`spin`,"aria-hidden":`true`});let i=n.some(e=>e.score&&!x().isSkipped(e.score)&&e.score.metrics?.length),a=n.length===1&&x().isSkipped(n[0].score),o=(0,Z.jsxs)(Z.Fragment,{children:[(n.length>1||!i&&n.some(e=>e.score))&&(0,Z.jsx)(kl,{readings:n}),a&&n.length===1&&(0,Z.jsx)(`span`,{className:`verdict skipped`,children:`Skipped`}),(0,Z.jsx)(Dl,{readings:n})]});return(0,Z.jsxs)(Z.Fragment,{children:[o,e?.kind===`text`?(0,Z.jsx)(xl,{res:r}):(0,Z.jsx)(bl,{res:r})]})}function Dl({readings:e}){let t=e.flatMap(e=>e.score&&!x().isSkipped(e.score)&&e.score.metrics?.length?[{...e,score:e.score}]:[]);return t.length?(0,Z.jsx)(Z.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,Z.jsxs)(`div`,{className:`metric-readings`,children:[(0,Z.jsx)(`span`,{className:`verdict ${e.score.pass?`pass`:`fail`}`,children:e.score.pass?`Pass`:`Fail`}),e.score.score!=null&&(0,Z.jsx)(`span`,{className:`metric-score`,children:Ol(e.score.score,!!e.score.points)}),n.length>0&&(0,Z.jsx)(`ul`,{children:n.map((e,t)=>(0,Z.jsxs)(`li`,{className:e.pass?`pass`:`fail`,children:[(0,Z.jsx)(`span`,{className:`eval-name`,children:e.label}),!e.pass&&(0,Z.jsxs)(Z.Fragment,{children:[` `,(0,Z.jsx)(`span`,{className:`metric-reason`,children:e.reason})]})]},t))}),r.length>0&&(0,Z.jsxs)(`div`,{className:`watched`,children:[(0,Z.jsx)(`b`,{children:`Watch`}),(0,Z.jsx)(`ul`,{children:r.map((e,t)=>(0,Z.jsxs)(`li`,{className:e.pass?`met`:`unmet`,children:[(0,Z.jsx)(`span`,{className:`eval-name`,children:e.label}),` `,(0,Z.jsx)(`span`,{className:`metric-reason`,children:e.reason})]},t))})]})]},t)})}):null}var Ol=(e,t)=>t?`${Math.round(e*100)/100} points`:`${Math.round(e*100)}%`;function kl({readings:e}){return(0,Z.jsx)(`ul`,{className:`eval-verdicts`,children:e.map((e,t)=>{let n=e.score?x().isSkipped(e.score)?`Skipped`:e.score.pass?`Pass`:`Fail`:null;return n&&(0,Z.jsxs)(`li`,{children:[(0,Z.jsx)(`span`,{className:`eval-name`,children:e.label}),(0,Z.jsx)(`span`,{className:`verdict ${n.toLowerCase()}`,children:n})]},t)})})}function Al({src:e,name:t,onClose:n}){return(0,Z.jsx)(D,{title:t||`Image`,onClose:n,children:(0,Z.jsx)(`img`,{className:`lightbox-img`,src:e,alt:t})})}function jl(){let{tabs:e,focusedId:t,closeRun:n,focusRun:r,goBack:i}=Jt(),a=e.find(e=>e.id===t);return a?(0,Z.jsxs)(`div`,{className:`results`,role:`region`,"aria-label":`Open runs`,children:[(0,Z.jsxs)(`div`,{className:`results-bar`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`ghost icon-btn rrback`,onClick:i,"aria-label":`Back`,children:(0,Z.jsx)(f,{size:18,"aria-hidden":`true`})}),(0,Z.jsx)(`code`,{className:`rrcode`,children:un(a.at)||`…`}),(0,Z.jsx)(`div`,{className:`rtabs`,role:`tablist`,"aria-label":`Open runs`,children:e.map(e=>(0,Z.jsxs)(`div`,{className:`rtab${e.id===t?` on`:``}`,children:[(0,Z.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":e.id===t,className:`rname`,title:un(e.at)||`run`,onClick:()=>r(e.id),children:un(e.at)||`…`}),(0,Z.jsx)(`button`,{type:`button`,className:`rx`,"aria-label":`Close`,onClick:()=>n(e.id),children:`×`})]},e.id))})]}),(0,Z.jsx)(Sl,{tab:a})]}):null}function Ml(){let e=Ie(),t=(0,J.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,Z.jsxs)(Z.Fragment,{children:[n.map(t=>(0,Z.jsxs)(`div`,{className:`sync bad`,role:`alert`,children:[(0,Z.jsxs)(`span`,{children:[t.doc?.name??t.id,` changed in another browser.`]}),(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>void e.resolve(t.id,`theirs`),children:`Use theirs`}),(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>void e.resolve(t.id,`mine`),children:`Keep mine`})]},t.id)),r.map(t=>(0,Z.jsxs)(`div`,{className:`sync bad`,role:`status`,children:[(0,Z.jsxs)(`span`,{children:[t.doc?.name??t.id,` not saved: `,t.sync.state===`offline`?t.sync.message.replace(/\.$/,``):``,`.`]}),(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>void e.flush(t.id),children:`Retry`})]},t.id))]})}var Nl=`promptlab.theme`,Pl=typeof matchMedia==`function`?matchMedia(`(prefers-color-scheme: light)`):null;function Fl(){try{let e=JSON.parse(localStorage.getItem(Nl)||`null`)?.choice;return e===`light`||e===`dark`?e:null}catch{return null}}var Il=()=>Fl()??(Pl?.matches?`light`:`dark`),Ll=()=>{let e=Il();return document.documentElement.setAttribute(`data-theme`,e),e};Ll();function Rl(){let[e,t]=(0,J.useState)(Il);(0,J.useEffect)(()=>{let e=()=>t(Ll());return Pl?.addEventListener?.(`change`,e),()=>Pl?.removeEventListener?.(`change`,e)},[]);let n=e===`light`?`dark`:`light`,r=n===`light`?`Light mode`:`Dark mode`;return(0,Z.jsx)(`button`,{type:`button`,className:`icon-btn`,title:r,"aria-label":r,onClick:()=>{try{localStorage.setItem(Nl,JSON.stringify({choice:n}))}catch{}document.documentElement.setAttribute(`data-theme`,n),t(n)},children:(0,Z.jsx)(n===`light`?Tt:gt,{size:16,"aria-hidden":`true`})})}var zl=()=>{let e=decodeURIComponent(location.hash.replace(/^#\/?/,``)),t=e.match(/^(evals|datasets|sources)(\/.*)?$/);t&&(e=`library/${t[1]===`sources`?`sources`:`datasets`}${t[1]===`sources`?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`;return{tab:`library`,section:e,src:e===`sources`?n[2]??null:null}}return{tab:fr.find(t=>t.id===e)?.id??`home`,section:`datasets`,src:null}};function Bl(){return(0,Z.jsx)(Fe,{children:(0,Z.jsx)(Ge,{children:(0,Z.jsx)(qt,{children:(0,Z.jsx)(Wt,{children:(0,Z.jsx)(Lr,{children:(0,Z.jsx)(Vl,{})})})})})})}function Vl(){let[e,t]=(0,J.useState)(zl),{hide:n}=Jt();(0,J.useEffect)(()=>{let e=()=>{t(zl()),n()};return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[n]);let r=fr.find(t=>t.id===e.tab);return(0,Z.jsxs)(`div`,{className:`app`,children:[(0,Z.jsxs)(`header`,{className:`app-head`,children:[(0,Z.jsx)(`h1`,{children:`Evals Lab`}),(0,Z.jsx)(Ul,{}),(0,Z.jsx)(Ml,{}),(0,Z.jsx)(Rl,{})]}),(0,Z.jsx)(`nav`,{className:`app-tabs`,role:`tablist`,"aria-label":`Lab`,children:fr.map(t=>(0,Z.jsxs)(`a`,{role:`tab`,id:`tab-${t.id}`,href:`#/${t.id}`,"aria-selected":t.id===e.tab,"aria-controls":`panel-${t.id}`,className:t.id===e.tab?`on`:void 0,children:[(0,Z.jsx)(t.icon,{size:18,"aria-hidden":`true`,className:`tab-icon`}),(0,Z.jsx)(`span`,{className:`tab-word`,children:t.label})]},t.id))}),(0,Z.jsx)(Hl,{tab:r,section:e.section,src:e.src})]})}function Hl({tab:e,section:t,src:n}){let{focusedId:r}=Jt(),i=r?(0,Z.jsx)(jl,{}):e.id===`home`?(0,Z.jsx)(vo,{}):e.id===`runs`?(0,Z.jsx)(ec,{}):e.id===`history`?(0,Z.jsx)(lc,{}):e.id===`library`?(0,Z.jsx)(uo,{section:t,sourceId:n}):(0,Z.jsx)(Hc,{});return(0,Z.jsx)(`main`,{role:`tabpanel`,id:`panel-${e.id}`,"aria-labelledby":`tab-${e.id}`,"data-tab":e.id,children:i})}function Ul(){let{sync:e,resolve:t}=be();return e.state===`offline`?(0,Z.jsxs)(`p`,{className:`sync bad`,role:`status`,children:[`Not saved to the server: `,e.message,`. Kept in this browser.`]}):e.state===`conflict`?(0,Z.jsxs)(`div`,{className:`sync bad`,role:`alert`,children:[(0,Z.jsx)(`span`,{children:`Changed on another device.`}),(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>void t(`theirs`),children:`Use theirs`}),(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>void t(`mine`),children:`Keep mine`})]}):null}var Wl={"promptlab.workflows":{list:[],at:``},"promptlab.profiles":{list:[],at:``},"promptlab.comment":null,"promptlab.versions":Gl(),"promptlab.history.columns":null,"promptlab.tokens":null};function Gl(){return{pipeline:{},profile:{},dataset:{}}}var Kl=[`promptlab.workflows`,`promptlab.profiles`,`promptlab.versions`,`promptlab.tokens`],ql=`promptlab.sync`,Jl=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Yl=(e,t)=>{let n=Wl[e];return Jl(n)&&Jl(t)?{...n,...t}:t};function Xl({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(ql)??{},d={},f=new Set,p=()=>o(ql,{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 Kl){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 he&&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,Yl(e,s(e))),a.get(e)??Wl[e]},set(e,t){o(e,t),l&&Kl.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 Kl){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 Zl=e=>[1,2,3,4,5,6,7,8,9,10].includes(e?.version)||x().fatProfileRef(e),Ql=e=>e?.version===1||e?.version===2;function $l(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(Ql).map(e=>e?.tests?.type===`graded`?e.tests.dataset?.id:void 0);return[...new Set(t.filter(e=>!!e))]}function eu(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=>x().upgradePipeline(e,r),a=e=>Zl(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 tu(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 nu(){x();let e=ge(),t=()=>{},n=new Promise(e=>{t=e});if(/^#\/?history\/?$/.test(location.hash)&&e.askQueue({limit:25},n),Fi())try{let t=(await e.config()).microsoft;t&&await Ii(t)}catch{}if(Bi())try{let t=(await e.config()).microsoft;if(t){await Vi(t);return}}catch{}await me(e),t();let r=Xl({api:e,storage:localStorage,server:await tu(e)}),i=r.get(`promptlab.profiles`);i.list.some(e=>`profile`in e)&&r.set(`promptlab.profiles`,{...i,list:i.list.map(e=>x().convertProfile(e))});let a=r.get(`promptlab.profiles`),o=e=>x().pinReplyTokens(x().splitOllama(e));a.list.some(e=>o(e)!==e)&&r.set(`promptlab.profiles`,{...a,list:a.list.map(e=>o(e))});let s={};if($l(r).length)try{s=(await e.archivedRules()).rules}catch{}eu(r,s),addEventListener(`pagehide`,()=>{r.flush(!0)}),(0,q.createRoot)(document.getElementById(`root`)).render((0,Z.jsx)(J.StrictMode,{children:(0,Z.jsx)(_e.Provider,{value:r,children:(0,Z.jsx)(oe.Provider,{value:e,children:(0,Z.jsx)(Bl,{})})})}))}nu();
|