evals-lab 0.2.0 → 0.4.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.
@@ -1,19 +0,0 @@
1
- import{A as e,B as t,C as n,D as r,E as i,F as a,G as o,H as s,I as c,J as l,K as u,L as d,M as f,N as p,O as m,P as h,R as g,S as _,T as v,U as y,V as b,W as x,X as S,Y as C,_ as w,a as T,b as E,c as D,d as O,f as k,g as A,h as j,i as M,j as N,k as P,l as F,m as I,o as ee,p as L,q as R,r as z,s as B,t as V,u as H,v as U,w as W,x as G,y as K,z as q}from"./tokens-ClRQ7Mui.js";var te=C(),J=S(),ne=(0,J.createContext)(null);function Y(){let e=(0,J.useContext)(ne);if(!e)throw Error(`useApi outside an ApiContext: main.tsx mounts one at the root`);return e}var re=`modulepreload`,ie=function(e){return`/`+e},ae={},oe=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=ie(t,n),t=s(t),t in ae)return;ae[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`:re,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)})},se={},ce=new Set,le=e=>`/plugins/${encodeURIComponent(e.id)}/${encodeURIComponent(e.version)}/${e.entry.split(`/`).map(encodeURIComponent).join(`/`)}`;async function X(e){if(!ce.has(e.id))try{let t=await oe(()=>import(le(e)),[]);if(typeof t.default!=`function`)throw Error(`its entry exports no register function`);await t.default(q().pluginHost(e.id)),ce.add(e.id),delete se[e.id]}catch(t){se[e.id]=t instanceof Error?t.message:String(t)}}async function ue(e){let t=[];try{t=(await e.plugins()).plugins}catch{return}for(let e of t)await X(e)}var de=class extends Error{status;body;constructor(e,t,n=null){super(t),this.name=`ApiError`,this.status=e,this.body=n}};function fe(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 de(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:q().upgradePipeline(e.snapshot),results:q().upgradeResults(e.results)}),i=async e=>{let t=await e;return{...t,run:r(t.run)}};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=new URLSearchParams;return e.limit&&t.set(`limit`,String(e.limit)),e.before&&t.set(`before`,e.before),n(`/api/queue${t.size?`?${t}`:``}`).then(e=>({...e,runs:e.runs.map(r)}))},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=>i(n(`/api/queue`,{body:e})),cancel:e=>i(n(`/api/queue/${encodeURIComponent(e)}/cancel`,{body:{}})),resume:e=>i(n(`/api/queue/${encodeURIComponent(e)}/resume`,{body:{}})),rerun:(e,t)=>i(n(`/api/queue/${encodeURIComponent(e)}/items/${t}`,{body:{}})),rescore:(e,t)=>i(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 pe=(0,J.createContext)(null);function me(){let e=(0,J.useContext)(pe);if(!e)throw Error(`useStore outside a StoreContext: the app mounts one at its root`);return e}function he(e){let t=me();return[(0,J.useSyncExternalStore)(t.subscribe,()=>t.get(e)),(0,J.useCallback)(n=>t.set(e,n),[t,e])]}function ge(){let e=me();return{sync:(0,J.useSyncExternalStore)(e.subscribe,e.sync),resolve:e.resolve}}var _e=e=>e,ve=e=>e?.state===`conflict`?`Not saved: changed in another browser.`:e?.state===`offline`?`Not saved: ${e.message}`:null,ye=(e,t)=>JSON.stringify(e)===JSON.stringify(t),be=e=>e instanceof Error?e.message:String(e),xe=({body:e,...t})=>t;function Se({api:e,pause:t=800,idle:n}){let r=_e(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(xe(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(xe(c)),o.has(e))return v(e)}catch(t){let n=a.get(e);if(!n?.doc)return;let r=t instanceof de&&t.status===409?t.body?.current??null:null;if(r){if(ye(r.body,n.doc.body)){o.delete(e),p(e,{doc:{...n.doc,version:r.version},sync:{state:`saved`}});return}p(e,{sync:{state:`conflict`,theirs:r}});return}p(e,{sync:{state:`offline`,message:be(t)}})}}function y(e){let t=s.get(e);t&&(clearTimeout(t),s.delete(e));let n=l.get(e);return n||(n=v(e).finally(()=>l.delete(e)),l.set(e,n)),n}return{list:()=>i,entry:e=>a.get(e),held:()=>d??=[...a.values()],async refresh(){try{let e=(await r.datasets()).datasets;m(e);for(let t of e){let e=a.get(t.id);e?.doc&&!o.has(t.id)&&t.version>e.doc.version&&r.dataset(t.id).then(e=>{a.has(t.id)&&!o.has(t.id)&&_(e)},()=>{})}}catch(e){i={list:i.list,error:be(e)},f()}},load(e){a.has(e)||(p(e,{sync:{state:`loading`}}),r.dataset(e).then(t=>{a.has(e)&&p(e,{doc:t,sync:{state:`saved`}})},t=>{a.has(e)&&p(e,{sync:{state:`missing`,message:be(t)}})}))},edit(e,r){let i=a.get(e);if(!i?.doc)return;let l=r(i.doc.body);if(l===i.doc.body)return;p(e,{doc:{...i.doc,body:l,cases:l.cases.length}}),o.add(e);let u=s.get(e);if(u&&clearTimeout(u),s.set(e,setTimeout(()=>{s.delete(e),y(e)},t)),n){let t=c.get(e);t&&clearTimeout(t),c.set(e,setTimeout(()=>{c.delete(e);let t=a.get(e)?.doc;t&&n.cut(e,t.body)},n.ms))}},async flush(e){await Promise.all((e?[e]:[...o]).map(y))},async resolve(e,t){let n=a.get(e);if(!n?.doc||n.sync.state!==`conflict`)return;let r=n.sync.theirs;if(t===`theirs`){o.delete(e),_(r);return}p(e,{doc:{...n.doc,version:r.version},sync:{state:`saved`}}),o.add(e),await y(e)},async create(e,t){let n=await r.createDataset(t?{name:e,body:t}:{name:e});return _(n),n},async rename(e,t){let n=await r.renameDataset(e,t),i=a.get(e)?.doc;i&&p(e,{doc:{...i,name:n.name,version:n.version,updated:n.updated}}),h({...xe(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 Ce=3e4,we=(e,t)=>e.get(`promptlab.versions`)[t]??{};function Te(e,t){return(e.get(`promptlab.versions`).dataset?.[t]??[]).map(e=>({...e,doc:q().upgradeDatasetBody(e?.doc)})).filter(e=>Ee(e.doc))}var Ee=e=>!!e&&typeof e==`object`&&Array.isArray(e.cases);function De(e,t,n,r,i){let a=e.get(`promptlab.versions`),o=we(e,t),s=(o[n]??[]).slice(),c=structuredClone(r);s[0]&&ke(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 Oe(e,t,n,r){let i=e.get(`promptlab.versions`),a=(i.dataset?.[t]??[]).slice(),o=structuredClone(n);a[0]&&ke(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 ke=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Z=g(),Ae=(0,J.createContext)(null);function je({children:e,pause:t}){let n=Y(),r=me(),i=(0,J.useMemo)(()=>Se({api:n,...t==null?{}:{pause:t},idle:{ms:Ce,cut:(e,t)=>Oe(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)(Ae.Provider,{value:i,children:e})}function Me(){let e=(0,J.useContext)(Ae);if(!e)throw Error(`useDatasets outside a DatasetsProvider: the app mounts one at its root`);return e}function Ne(){let e=Me(),t=(0,J.useSyncExternalStore)(e.subscribe,e.list);return(0,J.useEffect)(()=>{e.list().list===null&&e.refresh()},[e]),t}function Pe(e){let t=Me(),n=(0,J.useSyncExternalStore)(t.subscribe,()=>e?t.entry(e):void 0);return(0,J.useEffect)(()=>{e&&t.load(e)},[t,e]),n}var Fe=e=>e.name.trim()||e.text.trim().split(`
2
- `)[0].trim()||`Untitled prompt`,Ie=e=>e?.state===`conflict`?`Not saved: changed in another browser.`:e?.state===`offline`?`Not saved: ${e.message}`:null,Le=e=>e instanceof Error?e.message:String(e),Re=({versions:e,uses:t,...n})=>n;function ze({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(Re(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(Re(f)),u)return p(t)}catch(e){let n=r.get(t);if(!n?.doc)return;let a=e instanceof de&&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:Le(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(){try{u((await e.prompts()).prompts)}catch(e){n={list:n.list,error:Le(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:Le(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(Re(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 Be=(0,J.createContext)(null);function Ve({children:e,pause:t}){let n=Y(),r=(0,J.useMemo)(()=>ze({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)(Be.Provider,{value:r,children:e})}function He(){let e=(0,J.useContext)(Be);if(!e)throw Error(`usePrompts outside a PromptsProvider: the app mounts one at its root`);return e}function Ue(){let e=He(),t=(0,J.useSyncExternalStore)(e.subscribe,e.list);return(0,J.useEffect)(()=>{e.refresh()},[e]),t}function We(e){let t=He(),n=(0,J.useSyncExternalStore)(t.subscribe,()=>e?t.entry(e):void 0);return(0,J.useEffect)(()=>{e&&t.load(e)},[t,e]),n}var Ge=e=>(typeof e.id==`string`?e.id.trim():``)||`file:${q().caseFile(e)}`,Ke=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();function qe(e,t){switch(t.type){case`bounds`:{let n=(e,t)=>e.kind===`keep`?t??null:e.kind===`clear`?null:e.n,r=n(t.min,e.minCount),i=n(t.max,e.maxCount);return r===(e.minCount??null)&&i===(e.maxCount??null)?e:{...e,minCount:r,maxCount:i}}case`addTerm`:{let n=t.term.trim(),r=e[t.list]??[];return!n||r.some(e=>Ke(e,n))?e:{...e,[t.list]:[...r,n]}}case`removeTerm`:{let n=t.term.trim();if(!n)return e;let r=e=>(e??[]).filter(e=>!Ke(e,n)),i=r(e.expect),a=r(e.forbid),o=r(e.allow),s=(e.anyOf??[]).map(r).filter(e=>e.length);return i.length===(e.expect??[]).length&&a.length===(e.forbid??[]).length&&o.length===(e.allow??[]).length&&JSON.stringify(s)===JSON.stringify(e.anyOf??[])?e:{...e,...e.expect?{expect:i}:{},...e.forbid?{forbid:a}:{},...e.allow?{allow:o}:{},...e.anyOf?{anyOf:s}:{}}}case`status`:return!!e.todo===t.todo?e:{...e,todo:t.todo}}}function Je(e,t,n){let r=[];return n.type===`delete`?{next:e.filter(e=>{let n=t.has(Ge(e));return n&&r.push(Ge(e)),!n}),changed:r}:{next:e.map(e=>{if(!t.has(Ge(e)))return e;let i=qe(e,n);return i!==e&&r.push(Ge(e)),i}),changed:r}}function Ye(e,t,n){let r=new Map(e.map(e=>[Ge(e),e])),i=new Map(t.map(e=>[Ge(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(q().validateEvals({cases:[t]})),s=`${n.id}: `,c=q().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:q().caseFile(n),reasons:c})}return{cases:a}}var Xe={expect:`Expect`,forbid:`Forbid`,allow:`Except`},Ze=e=>Xe[e],Qe=e=>`${e} ${e===1?`case`:`cases`}`;function $e(e,t){let n=Qe(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 ${Xe[e.list]} on ${n}`;case`removeTerm`:return`Removed ${e.term.trim()} from ${n}`;case`status`:return`Marked ${n} ${e.todo?`Todo`:`graded`}`;case`delete`:return`Deleted ${n}`}}var et={file:``,status:`all`,show:`all`};function tt(e,t,n){let r=t.file.trim().toLowerCase();return e.filter(e=>(!r||q().caseFile(e).toLowerCase().includes(r))&&(t.status===`all`||t.status===`todo`==!!e.todo)&&(t.show===`all`||n.has(Ge(e))))}var nt=(0,J.createContext)(null);function rt({children:e}){let[t,n]=(0,J.useState)(null),[r,i]=(0,J.useState)(new Set),[a,o]=(0,J.useState)(et),[s,c]=(0,J.useState)(null),[l,u]=(0,J.useState)(null),d=Pe(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(et),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({...et,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(q().caseFile(t))).map(Ge);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)(nt.Provider,{value:y,children:e})}function it(){let e=(0,J.useContext)(nt);if(!e)throw Error(`useEvals outside an EvalsProvider: the app mounts one at its root`);return e}var at=(0,J.createContext)(null);function ot({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)(at.Provider,{value:h,children:e})}function st(){let e=(0,J.useContext)(at);if(!e)throw Error(`useResults outside a ResultsProvider: the app mounts one at its root`);return e}function ct({n:e,of:t}){return(0,Z.jsxs)(`span`,{className:`fig-part`,children:[e,(0,Z.jsxs)(`span`,{className:`fig-of`,children:[`/`,t]})]})}var lt=e=>e===`good`?` fig-good`:e===`bad`?` fig-bad`:``;function ut({fig:e}){return(0,Z.jsx)(`span`,{className:`fig-value${lt(e.tone)}`,children:e.value??(e.of?(0,Z.jsx)(ct,{n:e.of[0],of:e.of[1]}):`—`)})}function dt({fig:e}){return(0,Z.jsxs)(`div`,{className:`fig`,children:[(0,Z.jsx)(`span`,{className:`fig-label`,children:e.label}),(0,Z.jsx)(ut,{fig:e})]},e.key)}function ft({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)(ut,{fig:t}),t.under&&(0,Z.jsx)(`span`,{className:`fig-under`,children:(0,Z.jsx)(ct,{n:t.under[0],of:t.under[1]})})]})]}),!!n.length&&(0,Z.jsx)(`div`,{className:`fig-rest`,children:n.map(e=>(0,Z.jsx)(dt,{fig:e},e.key))})]})}var pt={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`},mt={format:`image/jpeg`,quality:`0.92`,seed:``,nPredict:``,repeatPenalty:``,frequencyPenalty:``,presencePenalty:``,dryMultiplier:``,dryBase:``,dryAllowedLength:``,grammar:``,px:`921600`},ht=[`type`,`profile`,`px`,`format`,`quality`,`seed`,`nPredict`,`repeatPenalty`,`frequencyPenalty`,`presencePenalty`,`dryMultiplier`,`dryBase`,`dryAllowedLength`,`grammar`,`imagePosition`,`cachePrompt`,`thinking`,`rejectLoops`,`url`,`model`,`temperature`];function gt(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 _t=(e,t)=>({...mt,...t?.setupProfile?.settings||{}});function vt(e){return pt[e]??e}function yt(e,t){return e===`type`?bt(String(t)):e===`profile`?t===`speed`?`Speed`:`Quality`:e===`px`?q().budgetLabel(t):e===`format`?String(t).replace(`image/`,``).toUpperCase():String(t)}function bt(e){return q().CONNECTION_TYPES[e]?.label??e}var xt=e=>e.content?e.content!==`text`:null,St=e=>Number(new Date(e)).toString(36).slice(-6).toUpperCase(),Ct=(e,t,n=`${t}s`)=>`${e} ${e===1?t:n}`,wt=e=>{let t=e?e.timed??e.ran:0;return t?e.ms/t:null};function Tt(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 Et=e=>new Date(e).toLocaleString(void 0,{dateStyle:`medium`,timeStyle:`short`}),Dt={queued:`Queued`,running:`Running`,done:`Done`,incomplete:`Incomplete`,cancelled:`Cancelled`,failed:`Failed`,interrupted:`Interrupted`},Ot=e=>Dt[e]??e;function kt(e){return Dt[e]?(0,Z.jsx)(`span`,{className:`rchip ${e}`,children:Dt[e]}):null}var At=e=>e.length?e.reduce((e,t)=>e+t,0)/e.length:null;function jt(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 Mt(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 Nt=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(wt).filter(e=>e!=null);return{pct:r?Math.round(100*n/r):null,avgScore:i.length?Math.round(At(i)):null,avgTime:a.length?At(a):null}},Pt=e=>{let t=Nt(e);return{pct:t.pct==null?`—`:`${t.pct}%`,avgScore:t.avgScore==null?`—`:`${t.avgScore}%`,avgTime:t.avgTime==null?`—`:jt(t.avgTime)}},Ft=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,It=[{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:St(e.at)}),Ft(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:Et(e.at)}),e.cancelled&&(0,Z.jsx)(`span`,{className:`err`,children:` cancelled`})]})},{key:`state`,label:`State`,on:!0,sort:e=>Ot(e.status),get:e=>kt(e.status)},{key:`content`,label:`Content`,on:!0,get:e=>e.content||`—`},{key:`pct`,label:`% Passed Items`,on:!0,numeric:!0,sort:e=>Nt(e).pct,get:e=>Pt(e).pct},{key:`avgscore`,label:`Avg Score`,on:!0,numeric:!0,sort:e=>Nt(e).avgScore,get:e=>Pt(e).avgScore},{key:`avgtime`,label:`Avg Time`,on:!0,numeric:!0,sort:e=>Nt(e).avgTime,get:e=>Pt(e).avgTime},{key:`duration`,label:`Duration`,on:!1,numeric:!0,sort:e=>Mt(e.startedAt,e.finishedAt),get:e=>{let t=Mt(e.startedAt,e.finishedAt);return t==null?`—`:jt(t)}},{key:`ran`,label:`Ran`,on:!1,numeric:!0,sort:e=>e.done,get:e=>(0,Z.jsx)(ct,{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:`——`})})}],Lt=[{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:`tests`,label:`Tests`,on:!0,sort:e=>e.tests||null,get:(e,t)=>t.tests||`—`},{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)(ct,{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=>wt(e),get:(e,t)=>{let n=wt(t);return n==null?`—`:jt(n)}},{key:`total`,label:`Total`,on:!1,numeric:!0,sort:e=>e.ms||null,get:(e,t)=>t.ms?jt(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(q().budgetLabel(_t(e,t).px))},{key:`format`,label:`Format`,on:!1,image:!0,get:(e,t)=>String(_t(e,t).format).replace(`image/`,``).toUpperCase()},{key:`quality`,label:`Quality`,on:!1,image:!0,get:(e,t)=>_t(e,t).format===`image/png`?`—`:String(_t(e,t).quality)},{key:`seed`,label:`Seed`,on:!1,get:(e,t)=>String(_t(e,t).seed||`1234`)},{key:`predict`,label:`Reply tokens`,on:!1,get:(e,t)=>String(_t(e,t).nPredict||_t(e,t).maxTokens||`—`)},{key:`penalty`,label:`Repeat penalty`,on:!1,get:(e,t)=>String(_t(e,t).repeatPenalty||`—`)},{key:`decoding`,label:`Decoding`,on:!1,get:(e,t)=>gt(_t(e,t))||`—`},...Object.entries(q().MODIFIERS).map(([e,t])=>({key:`modifier-${e}`,label:t.label||e,on:!1,get:(t,n)=>n.modifiers?.[e]||`—`}))],Rt={"Run Scenarios":`Run Targets`},zt=[[`Runs`,It],[`Run Scenarios`,Lt]],Bt=e=>![`queued`,`running`].includes(e),Vt=()=>({ran:0,passed:0,found:0,of:0,ms:0,timed:0,share:0,shared:0});function Ht(e){return e.of?Math.round(100*e.found/e.of):e.shared?Math.round(100*e.share/e.shared):null}var Ut=(e,t)=>e.filter(e=>!e.whole).map(e=>e.items[t]).filter(e=>!!e&&!q().isSkipped(e));function Wt(e,t){let n=t.map(Vt);return(e||[]).forEach((e,r)=>{e&&!e.unrun&&(e.scenarios||[]).forEach((e,i)=>{let a=n[i];if(!a||!e)return;let o=Ut(t[i],r);if(o.length){a.ran++,o.every(e=>e.pass)&&a.passed++;for(let e of o)a.found+=(e.found||[]).length,a.of+=(e.found||[]).length+(e.missed||[]).length+(e.invented||[]).length,!e.found&&!e.missed&&typeof e.score==`number`&&!e.points&&(a.share+=e.score,a.shared++)}e.res&&(a.timed++,a.ms+=e.res.ms||0)})}),n}var Gt=(e,t,n)=>q().targetsOf(e).map((r,i)=>q().scenarioTests(e,i,t,Bt(n))),Kt=(e,t,n)=>(e.outcomes[n]??[]).some(e=>!e.whole&&q().failedScore(e.items[t]));function qt(e){return e.skipped?`Skipped`:e.whole?e.verdict?.ran?e.verdict.pass?`✓`:`✗`:`—`:e.ran?`${e.passed}/${e.ran}`:e.skippedItems?`Skipped`:`—`}var Jt=e=>e.map(e=>`${e.label} ${qt(e)}`).join(` · `),Yt={state:`pending`,value:`—`},Xt={state:`skipped`,value:`Skipped`,note:`an earlier test failed`};function Zt(e){let t=[];return e.tests.forEach((n,r)=>{let i=e.scenarios.map((t,n)=>e.outcomes[n]?.[r]),a=i.find(Boolean);if(!a)return;let o=q().TEST_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}`,test:a.label,type:s,first:!c.length,rule:t,want:r,cells:i.map(e=>e?e.skipped?Xt:o(e):Yt)}),u=q().TEST_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&&!q().isSkipped(t)?[u(t,e.key,n)]:[]).filter(e=>e!=null);if(!r.length)return Yt;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}:Yt});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}:Yt):l(`items`,`Items passed`,null,e=>{if(!e.ran)return e.skippedItems?Xt:Yt;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 Qt(e){let t=e.snapshot||{},n=q().contentOf(t),r=!!(n&&q().CONTENT_TYPES[n.type]?.inline),i=q().lastKind(t),a=e.results||[],o=Gt(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:q().targetsOf(t).map((e,n)=>({id:e?.id||`scenario-${n}`,name:q().targetLabel(t,n),kind:i,plain:!(i&&q().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??``},tests:q().testsOf(t),snapshot:t,results:a,outcomes:o,tallies:Wt(a,o),startedAt:e.startedAt,finishedAt:e.finishedAt}}function $t(e){let t=e.snapshot||{},n=q().contentOf(t),r=e.results||[],i=q().targetsOf(t),a=t.jobs||[],o=Gt(t,r,e.status),s=Wt(r,o),c=i.map((e,n)=>{let r=s[n]??Vt(),i=(a.length?q().stagesFor(t,n).connections:[]).map(e=>String(e.model||``)),c=i[0]?new Set(i).size===1?i[0]:i.join(` → `):``,l=Ht(r),u=q().scenarioPasses(o[n]??[]);return{name:q().targetLabel(t,n),id:e?.id,model:c,setupProfile:q().scenarioProfile(t,n),modifiers:Object.fromEntries((q().outOf(t.jobs?.at(-1))?.modifiers||[]).map(e=>[e.type,q().modifierSummary(e)])),percent:l,passed:r.passed,cases:r.ran,pass:u,detail:u==null?`not graded`:Jt(o[n]??[]),tests:Jt(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&&q().CONTENT_TYPES[n.type]?.inline?`text`:n?.type===`source`&&(n.ref?.name||n.ref?.id)||``,scenarios:c}}var en=e=>({key:`state`,label:`State`,value:Ot(e),tone:e===`done`?`good`:[`failed`,`incomplete`,`cancelled`,`interrupted`].includes(e)?`bad`:null}),tn=e=>e.length?e.reduce((e,t)=>e+t,0)/e.length:null;function nn(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&&!q().isSkipped(r))for(let e of r.metrics||[])typeof e.asked==`number`&&(t++,n+=e.asked);return{calls:t,ms:n}}function rn(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(Ht).filter(e=>e!=null),a=i.length?`${Math.round(tn(i))}%`:`—`,o=Mt(e.startedAt,e.finishedAt),s=nn(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,St(e.at)):`—`},en(e.status),{key:`score`,label:`Avg Score`,value:a},{key:`duration`,label:`Duration`,value:o==null?`—`:jt(o)},...s.calls?[{key:`grader`,label:`Grader`,value:`${s.calls} ${s.calls===1?`call`:`calls`} · ${jt(s.ms)}`}]:[],...r?[c]:[],{key:`start`,label:`Start Date`,value:e.at?cn(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 an=e=>e.tests.length&&Bt(e.status)?`No assertions`:`—`;function on(e,t){let n=e.tallies[t],r=un(e,t),i={key:`state`,label:`State`,value:r==null?an(e):r?`Pass`:`Fail`,tone:r==null?null:r?`good`:`bad`},a={key:`time`,label:`Avg Time`,value:sn(n)??`—`},o=e.outcomes[t]??[],s=o.length>1?o.map(e=>({key:`test-${e.id}`,label:e.label,value:qt(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:Ht(n)==null?`—`:`${Ht(n)}%`},a]}:{lead:i,rest:[...s,a]}}function sn(e){return e?.timed?jt(e.ms/e.timed):null}function cn(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 ln(e){let t=Ot(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 un(e,t){return q().scenarioPasses(e.outcomes[t]??[])}function dn(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 fn(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}`,pn=e=>(e||[]).map(String).join(`, `),mn=e=>e.length?e.every(t=>t===e[0])?String(e[0]):e.join(` → `):``;function hn(e,t,n,r){let i=q().scoreCase(t,n),{stages:a,connections:o}=q().stagesFor(e,r),s=o.map(e=>q().connectionSettings(e)),c=e=>mn(s.map(e)),l=q().testsDataset(e);return[`An eval case is failing.`,``,`## The case`,Q(`file`,q().caseFile(t)),Q(`case id`,t.id),Q(`why it is graded`,t.why),Q(`expected, all of`,pn(t.expect)),...(t.anyOf||[]).map((e,t)=>Q(`expected, any of group ${t+1}`,pn(e))),Q(`forbidden`,pn(t.forbid)),Q(`allowed despite a forbidden word`,pn(t.allow)),Q(`watch for, not scored`,pn(t.watch)),``,`## What came back`,Q(`verdict`,i.pass?`pass`:`fail`),Q(`score`,i.score==null?`—`:`${Math.round(i.score*100)}%`),Q(`items`,pn(n?.terms)||`(none)`),Q(`missed`,pn(i.missed.map(e=>Array.isArray(e)?e.join(` / `):e))),Q(`invented`,pn(i.invented)),Q(`dropped`,pn((n?.dropped||[]).map(e=>`${e.item} (${e.by})`))),Q(`reasons`,pn(i.reasons)),Q(`error`,n?.error),Q(`took`,n?.ms==null?null:`${n.ms} ms`),``,`## How it was asked`,Q(`scenario`,`${r+1} of ${q().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=>bt(String(e.type??``)))),Q(`image`,a[0]?.withImage?gn(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`,_n(s.at(-1))),Q(`modifiers`,(q().outOf(e.jobs.at(-1))?.modifiers||[]).map(e=>`${q().MODIFIERS[e.type]?.label??e.type}: ${q().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(`
3
- `)}function gn(e){let{px:t,format:n}=q().connectionImage(e);return`${t==null?`default budget`:q().budgetLabel(t)} · ${n.replace(`image/`,``).toUpperCase()}`}function _n(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 vn(e,t){let n=[];return!Bt(e.status)||!q().testsDataset(e.snapshot)||(e.results||[]).forEach((r,i)=>{r&&!r.unrun&&(r.scenarios||[]).forEach((a,o)=>{let s=t.find(e=>q().caseFile(e)===r.name);Kt(e,i,o)&&s&&a.res&&n.push({kase:s,res:a.res,scenarioIndex:o,item:r.name??``})})}),n}var yn=e=>{let t=Math.min(...e),n=Math.max(...e);return t===n?String(t):`${t}–${n}`};function bn(e,t,n){let r=q().testsDataset(e.snapshot);if(!Bt(e.status)||!r)return[];let i=e.outcomes[n]?.find(t=>e.tests.find(e=>e.id===t.id&&`dataset`in e)),a=new Map(t.map(e=>[q().caseFile(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;if(!r||r.todo||!o||q().isSkipped(i?.items[t]))return;let c=q().scoreCase(r,o);if(c.pass)return;let l=e.name;if(c.discarded){s(`error`,6,`Error`,l);return}c.over&&s(`over`,0,`Too many items`,l,c.count,r.maxCount),c.under&&s(`under`,1,`Too few items`,l,c.count,r.minCount);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?`${yn(r)}, ${e===`over`?`max`:`min`} ${yn(i)}`:null}))}var xn=d(`ban`,[[`path`,{d:`M4.929 4.929 19.07 19.071`,key:`196cmz`}],[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}]]),Sn=d(`circle-check`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),Cn=d(`circle-stop`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`rect`,{x:`9`,y:`9`,width:`6`,height:`6`,rx:`1`,key:`1ssd4o`}]]),wn=d(`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`}]]),Tn=d(`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`}]]),En=d(`external-link`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`M10 14 21 3`,key:`gplh6r`}],[`path`,{d:`M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`,key:`a6xqqp`}]]),Dn=d(`file-code-corner`,[[`path`,{d:`M4 12.15V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2h-3.35`,key:`1wthlu`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`m5 16-3 3 3 3`,key:`331omg`}],[`path`,{d:`m9 22 3-3-3-3`,key:`lsp7cz`}]]),On=d(`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`}]]),kn=d(`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`}]]),An=d(`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`}]]),jn=d(`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`}]]),Mn=d(`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`}]]),Nn=d(`folder-plus`,[[`path`,{d:`M12 10v6`,key:`1bos4e`}],[`path`,{d:`M9 13h6`,key:`1uhe8q`}],[`path`,{d:`M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z`,key:`1kt360`}]]),Pn=d(`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`}]]),Fn=d(`gavel`,[[`path`,{d:`m14 13-8.381 8.38a1 1 0 0 1-3.001-3l8.384-8.381`,key:`pgg06f`}],[`path`,{d:`m16 16 6-6`,key:`vzrcl6`}],[`path`,{d:`m21.5 10.5-8-8`,key:`a17d9x`}],[`path`,{d:`m8 8 6-6`,key:`18bi4p`}],[`path`,{d:`m8.5 7.5 8 8`,key:`1oyaui`}]]),In=d(`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`}]]),Ln=d(`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`}]]),Rn=d(`link-2`,[[`path`,{d:`M9 17H7A5 5 0 0 1 7 7h2`,key:`8i5ue5`}],[`path`,{d:`M15 7h2a5 5 0 1 1 0 10h-2`,key:`1b9ql8`}],[`line`,{x1:`8`,x2:`16`,y1:`12`,y2:`12`,key:`1jonct`}]]),zn=d(`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`}]]),Bn=d(`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`}]]),Vn=d(`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`}]]),Hn=d(`minus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}]]),Un=d(`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`}]]),Wn=d(`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`}]]),Gn=d(`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`}]]),Kn=d(`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`}]]),qn=d(`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`}]]),Jn=d(`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`}]]),Yn=d(`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`}]]),Xn=d(`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`}]]),Zn=d(`waypoints`,[[`circle`,{cx:`12`,cy:`4.5`,r:`2.5`,key:`r5ysbb`}],[`path`,{d:`m10.2 6.3-3.9 3.9`,key:`1nzqf6`}],[`circle`,{cx:`4.5`,cy:`12`,r:`2.5`,key:`jydg6v`}],[`path`,{d:`M7 12h10`,key:`b7w52i`}],[`circle`,{cx:`19.5`,cy:`12`,r:`2.5`,key:`1piiel`}],[`path`,{d:`m13.8 17.7 3.9-3.9`,key:`1wyg1y`}],[`circle`,{cx:`12`,cy:`19.5`,r:`2.5`,key:`13o1pw`}]]),Qn=[{id:`home`,label:`Home`,icon:In,built:!0},{id:`runs`,label:`Runs`,icon:kn,built:!0},{id:`history`,label:`History`,icon:r,built:!0},{id:`library`,label:`Library`,icon:Ln,built:!0},{id:`setup`,label:`Setup`,icon:qn,built:!0}],$n=e=>e.replace(/[^A-Za-z0-9._-]+/g,`-`).replace(/^[-.]+|[-.]+$/g,``);function er(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 tr(e,t,n,r,i=new Date){return`${e}-${$n(t)||e}-v${n}-${er(i)}.${r}`}function nr(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 rr({name:e,body:t,onSave:n,onClose:r}){let[i,a]=(0,J.useState)(()=>JSON.stringify(t,null,2)),[o,s]=(0,J.useState)(()=>ar(i));(0,J.useEffect)(()=>{let e=setTimeout(()=>s(ar(i)),400);return()=>clearTimeout(e)},[i]);let c=o.problems;return(0,Z.jsxs)(L,{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=ar(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 ir=[`cases`];function ar(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))ir.includes(e)||r.push(`${e} is not part of a dataset`);return Array.isArray(n.cases)||r.push(`cases has to be a list`),r.length||(r.push(...q().validateEvals({cases:n.cases})),r.length)?{body:null,problems:r}:{body:{cases:n.cases},problems:[]}}function or(){let t=me(),n=Me(),a=ee(),{list:o,error:s}=Ne(),{datasetId:c,pickDataset:l}=it(),[u,d]=(0,J.useState)(!1),[f,p]=(0,J.useState)(null),[m,h]=(0,J.useState)(!1),[g,_]=(0,J.useState)(!1),v=(0,J.useRef)(null),[y]=he(`promptlab.versions`),b=o?.find(e=>e.id===c)??o?.[0]??null,x=b?.id??``,S=Pe(x||null),C=S?.doc??null;C?.body;let w=(0,J.useMemo)(()=>x?Te(t,x):[],[t,x,y]),E=e=>p({text:e instanceof Error?e.message:String(e),bad:!0}),D=(0,J.useCallback)(()=>n.entry(x)?.doc?.body??null,[n,x]),O=(0,J.useCallback)(e=>{x&&n.edit(x,e)},[n,x]),k=()=>new Set((n.list().list??[]).map(e=>e.name)),j=async()=>{p(null);try{let e=await n.create(cr(`Untitled dataset`,k()));l(e.id),d(!0)}catch(e){E(e)}},M=e=>{d(!1);let t=e.trim();C&&t&&t!==C.name&&(p(null),n.rename(x,t).catch(e=>{e instanceof de&&e.status===409?p({text:`A dataset is already called ${t}.`,bad:!0}):E(e)}))},N=async()=>{if(C){p(null);try{await n.flush(x);let e=await n.create(cr(`${C.name} copy`,k()),structuredClone(C.body));l(e.id)}catch(e){E(e)}}},P=async()=>{if(!C)return;p(null);let{name:e}=C,t=o?.findIndex(e=>e.id===x)??-1;try{await n.flush(x);let r=await n.remove(x),i=n.list().list??[];l(i[Math.min(Math.max(t,0),i.length-1)]?.id??null),a.offer({label:`Deleted ${e}`,restore:()=>{n.restore(r).then(t=>{l(t.id),t.name!==e&&p({text:`Restored as ${t.name}.`,bad:!1})}).catch(E)}})}catch(e){E(e)}},F=async e=>{p(null);let t;try{t=await sr(e)}catch(e){E(e);return}let r;try{r=JSON.parse(t)}catch(e){p({text:`Not JSON: ${e instanceof Error?e.message:String(e)}`,bad:!0});return}try{let e=await n.importFile(r);e[0]&&l(e[0].id),p({text:`Imported ${e.map(e=>e.name).join(`, `)}.`,bad:!1})}catch(e){E(e)}},I=async()=>{x&&(await n.flush(x).catch(()=>{}),await R(n.exportUrl(x),e=>tr(`dataset`,e.dataset?.name??``,e.version,`json`)))},R=async(e,t)=>{try{let n=await fetch(e);if(!n.ok)throw Error(`the export answered ${n.status}`);let r=await n.json();nr(new Blob([JSON.stringify(r,null,2)+`
4
- `],{type:`application/json`}),t(r))}catch(e){E(e)}},z=e=>{let n=D();n&&(Oe(t,x,n,`restore`),O(()=>structuredClone(e.doc)),_(!1),a.offer({label:`Restored the dataset`,restore:()=>O(()=>n)}))},B=!b,V=[{label:`New dataset`,icon:W,onSelect:()=>void j()},{label:`Rename`,icon:i,disabled:!C,onSelect:()=>d(!0)},{label:`Clone`,icon:U.clone,disabled:!C,onSelect:()=>void N()},{label:`Import JSON…`,icon:K,onSelect:()=>v.current?.click()},{label:`Export JSON`,icon:e,disabled:B,onSelect:()=>void I()},{label:`Export all`,icon:An,disabled:!o?.length,onSelect:()=>void R(n.exportAllUrl(),e=>tr(`datasets`,`all`,e.version,`json`))},{label:`Restore…`,icon:r,disabled:!w.length||!C,onSelect:()=>_(!0)},{label:`Edit raw…`,icon:Dn,disabled:!C,onSelect:()=>h(!0)},{label:`Delete`,icon:G,destructive:!0,disabled:!C,onSelect:()=>void P()}];return(0,Z.jsxs)(`div`,{className:`datasets`,children:[(0,Z.jsxs)(A,{id:`datasets`,title:`Datasets`,actions:V,about:`Answers fixed in advance: a case for each item, saying what a reply to it should hold. A test grades against one.`,children:[o===null?(0,Z.jsx)(`p`,{className:`note${s?` bad`:``}`,role:s?`alert`:void 0,children:s??`Loading…`}):o.length===0?(0,Z.jsxs)(`div`,{className:`ds-empty`,children:[(0,Z.jsx)(`p`,{className:`note`,children:`No datasets yet.`}),(0,Z.jsxs)(`div`,{className:`ds-empty-actions`,children:[(0,Z.jsxs)(`button`,{type:`button`,className:`ghost ds-add`,onClick:()=>void j(),children:[(0,Z.jsx)(W,{size:14,"aria-hidden":`true`}),`New dataset`]}),(0,Z.jsxs)(`button`,{type:`button`,className:`ghost ds-add`,onClick:()=>v.current?.click(),children:[(0,Z.jsx)(K,{size:14,"aria-hidden":`true`}),`Import JSON…`]})]})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`prop`,"data-control":u?`text`:`select`,children:[(0,Z.jsx)(`span`,{className:`prop-name`,children:`Dataset`}),(0,Z.jsx)(`span`,{className:`prop-value`,children:u&&C?(0,Z.jsx)(`input`,{type:`text`,"aria-label":`Name`,defaultValue:C.name,autoFocus:!0,onFocus:e=>e.currentTarget.select(),onKeyDown:e=>{e.key===`Enter`?M(e.currentTarget.value):e.key===`Escape`&&d(!1)},onBlur:e=>{u&&M(e.currentTarget.value)}}):(0,Z.jsx)(`select`,{"aria-label":`Dataset`,value:x,onChange:e=>{l(e.target.value),p(null)},children:o.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.name},e.id))})})]}),b&&(0,Z.jsxs)(`p`,{className:`ds-meta note`,children:[(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`b`,{children:b.cases}),` cases`]}),b.updated&&(0,Z.jsxs)(`span`,{children:[`updated `,(0,Z.jsx)(`b`,{children:ur(b.updated)})]})]})]}),f&&(0,Z.jsx)(`p`,{className:`note${f.bad?` bad`:``}`,role:f.bad?`alert`:`status`,children:f.text}),S?.sync.state===`missing`&&(0,Z.jsx)(`p`,{className:`note bad`,role:`alert`,children:S.sync.message}),(0,Z.jsx)(`input`,{ref:v,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&&F(t)}})]}),g&&C&&(0,Z.jsx)(L,{title:`Restore dataset`,onClose:()=>_(!1),children:(0,Z.jsxs)(`div`,{className:`version-list`,children:[w.length===0&&(0,Z.jsx)(`p`,{className:`note`,children:`No versions of this dataset yet.`}),w.map((e,t)=>(0,Z.jsxs)(`div`,{className:`version-row`,children:[(0,Z.jsxs)(`span`,{className:`version-when`,children:[ur(e.at),` · `,lr(e.reason)]}),(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>z(e),children:`Restore`})]},`${e.at}-${t}`))]})}),m&&C&&(0,Z.jsx)(rr,{name:C.name,body:C.body,onSave:e=>{O(()=>e),h(!1)},onClose:()=>h(!1)}),(0,Z.jsx)(T,{undo:a.undo,onUndo:a.undoNow,onDismiss:a.dismiss})]})}function sr(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 cr=(e,t)=>{if(!t.has(e))return e;for(let n=2;;n++)if(!t.has(`${e} ${n}`))return`${e} ${n}`},lr=e=>e===`idle`?`after editing`:e===`restore`?`before a restore`:e===`bulk`?`before a bulk edit`:e===`pack`?`before a pack update`:e,ur=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},dr={"promptlab.workflows":{list:[],at:``},"promptlab.profiles":{list:[],at:``},"promptlab.comment":null,"promptlab.versions":fr(),"promptlab.history.columns":null,"promptlab.tokens":null,"promptlab.mappings":pr()};function fr(){return{pipeline:{},profile:{},dataset:{}}}function pr(){return{datasets:{}}}var mr=[`promptlab.workflows`,`promptlab.profiles`,`promptlab.versions`,`promptlab.tokens`,`promptlab.mappings`],hr=16;function gr(e,t){if(!e)return null;let n=t.find(t=>t===e);if(n)return n;let r=e.toLowerCase();return t.find(e=>e.toLowerCase()===r)??null}function _r(e,t){return`/api/sources/${encodeURIComponent(e)}/thumbs/${encodeURIComponent(t)}`}function vr(e){return/\.(?:jpe?g|png|gif|webp|bmp|heic|heif|dng|tiff?)$/i.test(e)}function yr(e){return e?e.file?`mapped`:`nomatch`:`none`}async function br(e,t,n,r){let i=new Date().toISOString(),a={id:n.id,name:n.name},o={},s=e.length;r?.(0,s);for(let n=0;n<s;n+=hr){for(let r of e.slice(n,n+hr))o[r]={source:a,at:i,file:gr(r,t)};r?.(Math.min(n+hr,s),s),await new Promise(e=>{setTimeout(e,0)})}return o}async function xr(e,t,n,r,i,a){let o=await br(i,(await e.source(r.id)).files.map(e=>e.name),r,a);return wr(t,n,r,o),o}function Sr(e,t){let n=e.get(`promptlab.mappings`).datasets?.[t];return{recents:n?.recents??[],cases:n?.cases??{}}}function Cr(e,t){return e.cases[t]??null}function wr(e,t,n,r){let i=e.get(`promptlab.mappings`),a=i.datasets??pr().datasets,o=a[t]??{recents:[],cases:{}},s=[{id:n.id,name:n.name,at:new Date().toISOString()},...o.recents.filter(e=>e.id!==n.id)].slice(0,5);e.set(`promptlab.mappings`,{...i,datasets:{...a,[t]:{recents:s,cases:{...o.cases,...r}}}})}function Tr(e,t,n){let r=e.get(`promptlab.mappings`),i=r.datasets??pr().datasets,a=i[t];if(!a||!(n in a.cases))return;let o={...a.cases};delete o[n],e.set(`promptlab.mappings`,{...r,datasets:{...i,[t]:{...a,cases:o}}})}function Er(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function Dr(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(`, `)}function Or({label:e,metrics:t,set:n,undoable:r,over:i=`item`}){let a=q(),o=Object.entries(a.METRICS).map(([e,t])=>({value:e,label:t.label})),s=(e,r)=>n(t.map((t,n)=>n===e?r:t));return(0,Z.jsx)(j,{noun:`metric`,items:[...t],empty:(0,Z.jsx)(`p`,{className:`note`,children:`No metrics.`}),onAdd:()=>n([...t,{type:`contains`,...a.METRICS.contains.defaults()}]),onRemove:e=>r(t.filter((t,n)=>n!==e),`Removed a metric`),renderItem:(t,n,r)=>{let c=a.METRICS[t.type],l=(t.metric||c?.label||t.type)+(t.not?` (not)`:``),u=`${e.replace(/\W+/g,`-`).toLowerCase()}-metric-${n}`,d=!!(t.every||t.not||t.of||t.weight!=null||t.metric);return(0,Z.jsxs)(A,{id:u,title:l,level:3,actions:r,about:c?.description,children:[(0,Z.jsx)(k,{label:`${e}, metric ${n+1}`,rows:[{key:`type`,label:`Type`,control:{type:`select`,value:t.type,options:o,onChange:e=>s(n,{type:e,...a.METRICS[e].defaults(),...t.weight==null?{}:{weight:t.weight},...t.not?{not:!0}:{}})}},...(c?.options??[]).map(e=>M(e,t,e=>s(n,e)))]}),(0,Z.jsx)(A,{id:`${u}-counts`,title:`How it counts`,level:3,open:d,note:d?Dr(t):`Defaults`,children:(0,Z.jsx)(k,{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;s(n,e?{...i,every:!0}:i)}}}]:[],{key:`not`,label:`Not`,control:{type:`checkbox`,checked:!!t.not,onChange:e=>{let{not:r,...i}=t;s(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;s(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;s(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;s(n,e.trim()?{...i,metric:e}:i)}}}]})})]},n)}})}var kr=[`expect`,`anyOf`,`forbid`,`allow`,`watch`],Ar={expect:`Expect`,anyOf:`Any of`,forbid:`Forbid`,allow:`Except`,minCount:`Min items`,maxCount:`Max items`,watch:`Watch for`,traits:`Traits`,discarded:`Discarded`,todo:`Todo`,why:`Why`},jr=600,Mr=2e3,Nr=e=>({id:``,filename:e,todo:!0,traits:[],why:``,expect:[],anyOf:[],forbid:[],allow:[],minCount:null,maxCount:null,watch:[]}),Pr=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 Fr({filename:e,cases:t,onWrite:n,problem:r,resultFor:i,scenarioCount:a,files:o,onFile:s,onClose:c,run:l,preview:u,onRemove:d}){let m=t.findIndex(t=>q().caseFile(t)===e),h=m>=0?t[m]:Nr(e),[g,_]=(0,J.useState)(()=>structuredClone(h)),[v,y]=(0,J.useState)(0),[b,x]=(0,J.useState)(null),[S,C]=(0,J.useState)(null),[w,T]=(0,J.useState)(!1),[E,D]=(0,J.useState)(!1),k=(0,J.useRef)(g);k.current=g;let A=(0,J.useRef)(t);A.current=t;let j=(0,J.useRef)(null),M=(0,J.useRef)(null),N=(0,J.useCallback)(()=>{let t=k.current;A.current.findIndex(t=>q().caseFile(t)===e)<0&&!t.id&&(t={...t,id:Pr(A.current)},k.current=t,_(t));let r=t;n(t=>Br({cases:t},e,r))},[n,e]),P=(0,J.useCallback)(()=>{j.current&&clearTimeout(j.current),j.current=setTimeout(()=>{N(),D(!0),M.current&&clearTimeout(M.current),M.current=setTimeout(()=>D(!1),Mr)},jr)},[N]);(0,J.useEffect)(()=>()=>{j.current&&clearTimeout(j.current),M.current&&clearTimeout(M.current)},[]);let F=e=>{_(e),P()},I=(e,t,n)=>{let r=t.trim();if(!r)return;let i=structuredClone(k.current);if(e===`anyOf`){let e=n??i.anyOf.length;(i.anyOf[e]||=[]).push(r)}else{let t=i[e];t&&!t.includes(r)&&(i[e]=[...t,r])}i.todo&&(e===`expect`||e===`anyOf`)&&(i.todo=!1),F(i)},ee=(e,t,n)=>{let r=structuredClone(k.current);if(e===`anyOf`){let e=r.anyOf[n];e&&(e.splice(t,1),e.length||r.anyOf.splice(n,1))}else r[e].splice(t,1);F(r)},L=e=>g[e]??[],R=S&&S[v]?S[v]:i(v),z=!R||g.todo||R.error&&!g.discarded?null:q().scoreCase(g,R).pass,B=async()=>{if(l&&!w){T(!0),x(null);try{let t=await l(e);C(t),x(t.length?null:`No reply to grade.`)}catch(e){x(e instanceof Error?e.message:String(e))}finally{T(!1)}}},V=o.indexOf(e),H=e=>{let t=V<0?null:o[V+e];t&&s(t)};(0,J.useEffect)(()=>{let e=e=>{(e.key===`ArrowLeft`||e.key===`ArrowRight`)&&(e.target?.closest?.(`input, textarea, select, [contenteditable]`)||(e.preventDefault(),H(e.key===`ArrowRight`?1:-1)))};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)});let U=()=>{j.current&&(clearTimeout(j.current),j.current=null,N()),c()},W=[{key:`minCount`,label:Ar.minCount,control:{type:`text`,value:g.minCount==null?``:String(g.minCount),size:`num`,onChange:e=>F({...k.current,minCount:Lr(e)})}},{key:`maxCount`,label:Ar.maxCount,control:{type:`text`,value:g.maxCount==null?``:String(g.maxCount),size:`num`,onChange:e=>F({...k.current,maxCount:Lr(e)})}},{key:`discarded`,label:Ar.discarded,control:{type:`checkbox`,checked:!!g.discarded,label:`Expected`,onChange:e=>{let{discarded:t,...n}=k.current;F(e?{...n,discarded:!0}:n)}}},{key:`todo`,label:Ar.todo,control:{type:`checkbox`,checked:!!g.todo,label:`Not graded yet`,onChange:e=>F({...k.current,todo:e})}},{key:`why`,label:Ar.why,control:{type:`textarea`,value:g.why??``,onChange:e=>F({...k.current,why:e})}}],K=[];a>1&&K.push({key:`scenario`,label:`Show result of`,control:{type:`select`,value:String(v),options:Array.from({length:a},(e,t)=>({value:String(t),label:`Target ${t+1}`})),onChange:e=>y(Number(e))}}),z!=null&&K.push({key:`verdict`,label:`Result`,control:{type:`static`,text:z?`Pass`:`Fail`}});let te=[...u?[{key:`preview`,title:`Preview`,children:(0,Z.jsxs)(`div`,{className:`cf-preview`,children:[(0,Z.jsx)(`img`,{src:u.src,alt:u.file,loading:`lazy`}),(0,Z.jsxs)(`p`,{className:`note`,children:[u.file,` in `,u.source]})]})}]:[],{key:`terms`,title:`Expectations`,children:(0,Z.jsx)(`div`,{className:`caseform`,children:kr.map(e=>{let t=Ar[e];if(e===`anyOf`){let n=g.anyOf;return(0,Z.jsxs)(`div`,{className:`cfrow`,children:[(0,Z.jsx)(`span`,{className:`cflabel`,children:t}),(0,Z.jsx)(`div`,{className:`cfgroups`,children:[...n??[],[]].map((t,r)=>(0,Z.jsx)(Rr,{label:r===n?.length?`New group`:``,terms:t,stateFor:t=>zr(g,e,t,r,R),onAdd:t=>I(e,t,r),onDrop:t=>ee(e,t,r)},r))})]},e)}return(0,Z.jsxs)(`div`,{className:`cfrow`,children:[(0,Z.jsx)(`span`,{className:`cflabel`,children:t}),(0,Z.jsx)(Rr,{terms:L(e),stateFor:t=>zr(g,e,t,void 0,R),onAdd:t=>I(e,t),onDrop:t=>ee(e,t)})]},e)})})},{key:`metrics`,title:`Metrics`,children:(0,Z.jsx)(Or,{label:`${e} metrics`,metrics:g.metrics??[],set:e=>{let{metrics:t,...n}=k.current;F(e.length?{...n,metrics:e}:n)},undoable:e=>{let{metrics:t,...n}=k.current;F(e.length?{...n,metrics:e}:n)}})},{key:`limits`,title:`Limits`,rows:W},...K.length?[{key:`result`,title:`Result`,rows:K}]:[]],ne=[{label:`Previous`,icon:p,disabled:V<=0,onSelect:()=>H(-1)},{label:`Next`,icon:f,disabled:V<0||V>=o.length-1,onSelect:()=>H(1)},...l?[{label:`Run`,icon:Gn,disabled:w,onSelect:()=>void B()}]:[]],Y=d?[{label:`Remove`,icon:G,destructive:!0,onSelect:()=>{d(e),c()}}]:[],re=b??r??null;return(0,Z.jsx)(O,{title:e||`Case`,status:re??(w?`Running…`:E?`Saved.`:Ir),...re?{statusBad:!0}:{},sections:te,...Y.length?{menu:Y}:{},actions:ne,onClose:U})}var Ir=`Saved to the dataset as you edit.`,Lr=e=>{let t=e.trim();if(!t)return null;let n=Number(t);return Number.isInteger(n)&&n>0?n:null};function Rr({terms:e,stateFor:t,onAdd:n,onDrop:r,label:i}){let[a,o]=(0,J.useState)(``);return(0,Z.jsxs)(`div`,{className:`cfchips`,children:[i&&(0,Z.jsx)(`span`,{className:`cf-group-note`,children:i}),e.map((e,n)=>(0,Z.jsxs)(`span`,{className:`chip${t(e)?` ${t(e)}`:``}`,children:[e,(0,Z.jsx)(`button`,{type:`button`,className:`chipx`,"aria-label":`Remove ${e}`,onClick:()=>r(n),children:`×`})]},n)),(0,Z.jsxs)(`form`,{className:`cfadd`,onSubmit:e=>{e.preventDefault(),n(a),o(``)},children:[(0,Z.jsx)(`input`,{type:`text`,value:a,"aria-label":i||`Add`,placeholder:i||`Add`,autoComplete:`off`,spellCheck:!1,onChange:e=>o(e.target.value)}),(0,Z.jsx)(`button`,{type:`submit`,className:`ghost`,"aria-label":`Add`,children:`+`})]})]})}function zr(e,t,n,r,i){if(!i||i.error)return``;let a=i.terms||[];return t===`expect`||t===`watch`?q().termIn(a,n)?`met`:`unmet`:t===`forbid`?q().forbiddenIn(a,n,e.allow||[])?`unmet`:`met`:t===`anyOf`?q().termIn(a,n)?`met`:(e.anyOf?.[r??0]||[]).some(e=>q().termIn(a,e))?``:`unmet`:``}function Br(e,t,n){let r=e.cases.findIndex(e=>q().caseFile(e)===t),i=structuredClone(e.cases);return r>=0?i[r]=structuredClone(n):i.push(structuredClone(n)),i}function Vr(e,t){return structuredClone(e.cases).filter(e=>q().caseFile(e)!==t)}var Hr=(0,J.createContext)(null);function Ur({children:e}){let t=Me(),[n,r]=(0,J.useState)(null),i=Pe(n?.dataset??null),a=(0,J.useCallback)((e,t)=>{r({filename:e,...t})},[]),o=(0,J.useCallback)(e=>{r(t=>t&&{...t,filename:e})},[]),s=me(),[c]=he(`promptlab.mappings`),l=(0,J.useMemo)(()=>{if(!n)return;let e=Cr(Sr(s,n.dataset),n.filename);return e?.file&&vr(e.file)?{src:_r(e.source.id,e.file),file:e.file,source:e.source.name}:void 0},[s,n,c]),u=n?.dataset??``,d=(0,J.useCallback)(e=>{t.edit(u,t=>({...t,cases:e(t.cases)}))},[t,u]),f=(0,J.useMemo)(()=>({openCaseEditor:a}),[a]),p=i?.doc;return(0,Z.jsxs)(Hr.Provider,{value:f,children:[e,n&&p&&(0,Z.jsx)(Fr,{filename:n.filename,cases:p.body.cases,onWrite:d,problem:ve(i.sync),resultFor:n.resultFor??(()=>null),scenarioCount:n.scenarioCount??0,files:n.files??[],onFile:o,...n.run?{run:n.run}:{},...l?{preview:l}:{},...n.onRemove?{onRemove:n.onRemove}:{},onClose:()=>r(null)},n.filename)]})}function Wr(){let e=(0,J.useContext)(Hr);if(!e)throw Error(`useCaseEditor outside a CaseEditorProvider: the app mounts one at its root`);return e}function Gr({sources:e,recents:t,onPick:n,onClose:r}){let i=t.find(t=>e.some(e=>e.id===t.id))?.id??e[0]?.id??``,[a,o]=(0,J.useState)(i);(0,J.useEffect)(()=>{o(e=>e||i)},[i]);let s=t.filter(t=>e.some(e=>e.id===t.id));return(0,Z.jsx)(L,{title:`Map against Source`,onClose:r,children:e.length===0?(0,Z.jsx)(`p`,{className:`note`,children:`The lab holds no Sources to map against.`}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`prop`,children:[(0,Z.jsx)(`span`,{className:`prop-name`,children:`Source`}),(0,Z.jsx)(`span`,{className:`prop-value`,children:(0,Z.jsx)(`select`,{"aria-label":`Source`,value:a,onChange:e=>o(e.target.value),children:e.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.name},e.id))})})]}),s.length>0&&(0,Z.jsxs)(`div`,{className:`ds-recents`,children:[(0,Z.jsx)(`h3`,{className:`edit-section-title`,children:`Recent`}),(0,Z.jsx)(`div`,{className:`ds-recent-list`,children:s.map(e=>(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>n({id:e.id,name:e.name}),children:e.name},e.id))})]}),(0,Z.jsx)(`div`,{className:`ds-picker-actions`,children:(0,Z.jsx)(`button`,{type:`button`,className:`edit-done`,onClick:()=>{let t=e.find(e=>e.id===a);t&&n({id:t.id,name:t.name})},disabled:!a,children:`Map`})})]})})}function Kr({filename:e,mapped:t,onClose:n}){let r=[{key:`source`,label:`Source`,required:!0,control:{type:`static`,text:t.source.name}},{key:`when`,label:`Mapped`,required:!0,control:{type:`static`,text:Er(t.at)}},{key:`file`,label:`File`,required:!0,control:{type:`code`,text:t.file??``}}];return(0,Z.jsx)(O,{title:e,sections:[{key:`mapping`,title:`Mapping`,rows:r}],onClose:n})}function qr({rows:e,shown:t,filters:n,onFilters:r,selected:i,onSelect:a,selectionActions:o,mapping:s,onEdit:c,onAdd:l,onRemove:u,onMap:d,progress:f,onMapDetails:p,children:m}){let[h,g]=H(`dataset-cases`,20),[_,v]=(0,J.useState)(!1),y=e.filter(e=>!e.todo).length,b=[{label:`Map against Source…`,icon:Zn,disabled:!!f,onSelect:d},{label:`Page size`,icon:U.pageSize,onSelect:()=>v(!0)}],x=t.map(Ge),S=new Set(x),C=[...i].filter(e=>!S.has(e)).length,T=x.filter(e=>i.has(e)).length,E=T>0&&T===x.length,O=e=>a(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),k=[{key:`status`,label:`Status`,value:n.status,onChange:e=>r({status:e}),options:[{value:`all`,label:`All`},{value:`graded`,label:`Graded`},{value:`todo`,label:`Todo`}]},{key:`show`,label:`Show`,value:n.show,onChange:e=>r({show:e}),options:[{value:`all`,label:`All`},{value:`selected`,label:`Selected`}]}];return(0,Z.jsxs)(A,{id:`cases`,title:`Cases`,note:`${y} graded · ${e.length-y} todo`,actions:b,children:[(0,Z.jsx)(I,{noun:`cases`,search:{label:`File`,placeholder:`Search files`,value:n.file,onChange:e=>r({file:e})},filters:k,count:{shown:t.length,total:e.length},lead:e.length>0&&(0,Z.jsx)(`label`,{className:`ev-check ev-all`,children:(0,Z.jsx)(Jr,{all:E,some:T>0,disabled:!t.length,onChange:()=>a(e=>{let t=new Set(e);for(let e of x)E?t.delete(e):t.add(e);return t})})})}),m,f&&(0,Z.jsxs)(`p`,{className:`note ds-progress`,role:`status`,children:[`Mapping against `,f.source,`… `,f.done,` of `,f.total]}),e.length===0?(0,Z.jsx)(`p`,{className:`note`,children:`No cases 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`]}),C>0&&(0,Z.jsxs)(`span`,{className:`ev-hidden`,children:[C,` 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)(w,{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)(D,{className:`dstable`,label:`Cases`,rows:t,pageSize:h,rowKey:e=>Ge(e),rowProps:e=>({"data-selected":i.has(Ge(e))||void 0}),columns:Yr(s,i,O,c,u,p)})})]}),(0,Z.jsxs)(`button`,{type:`button`,className:`ghost ds-add`,onClick:l,children:[(0,Z.jsx)(W,{size:14,"aria-hidden":`true`}),`Add case`]}),_&&(0,Z.jsx)(F,{value:h,onChange:g,onClose:()=>v(!1)})]})}function Jr({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 Yr(e,t,n,r,i,a){let o=t=>yr(e.cases[t.filename]??null),s=Object.values(e.cases).some(e=>yr(e??null)!==`none`),c=[{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(Ge(e)),onChange:()=>n(Ge(e)),"aria-label":`Select ${e.filename}`})})},{key:`file`,header:`File`,sort:e=>e.filename,cell:e=>(0,Z.jsx)(`button`,{type:`button`,className:`ds-file`,onClick:()=>r(e.filename),children:e.filename})},{key:`expectations`,header:`Expectations`,cell:e=>Xr(e)},{key:`bounds`,header:`Count`,sort:e=>e.maxCount??e.minCount??null,tdProps:e=>({"data-state":Zr(e)?void 0:`none`}),cell:e=>Zr(e)??`—`},{key:`status`,header:`Status`,sort:e=>e.todo?`Todo`:`Graded`,cell:e=>(0,Z.jsx)(`span`,{className:e.todo?`ds-todo`:void 0,children:e.todo?`Todo`:`Graded`})},{key:`map`,header:`Map`,sort:e=>({nomatch:`No match`,mapped:`Mapped`})[o(e)]??null,tdProps:e=>({"data-state":o(e)}),cell:e=>{let t=o(e);return t===`nomatch`?(0,Z.jsx)(`span`,{className:`ds-nomatch`,children:`No match`}):t===`mapped`?(0,Z.jsx)(`button`,{type:`button`,className:`ds-mapped`,onClick:()=>a(e.filename),children:`Mapped`}):null}},{key:`menu`,header:``,label:``,className:`ds-menu`,sort:null,cell:e=>(0,Z.jsx)(w,{label:`${e.filename} actions`,actions:[{label:`Edit`,icon:U.edit,onSelect:()=>r(e.filename)},{label:`Remove`,icon:U.remove,destructive:!0,onSelect:()=>i(e.filename)}]})}];return s?c:c.filter(e=>e.key!==`map`)}var Xr=e=>(e.expect??[]).length+(e.anyOf??[]).length+(e.metrics??[]).length,Zr=e=>{let t=e.minCount??null,n=e.maxCount??null;return t!=null&&n!=null?`${t}–${n}`:t==null?n==null?null:`≤${n}`:`≥${t}`},Qr={bounds:`Set count`,addTerm:`Add term`,removeTerm:`Remove term`,todo:`Mark Todo`,graded:`Mark graded`},$r=[{value:`keep`,label:`Keep`},{value:`set`,label:`Set`},{value:`clear`,label:`Clear`}],ei=e=>/^\s*\d+\s*$/.test(e)?Number(e):null;function ti({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`?ei(l):null,t=s===`set`?ei(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}=Je(t,n,y);return{changed:r,problems:Ye(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:$r,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:$r,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`,`allow`].map(e=>({value:e,label:Ze(e)}))}}),(e===`addTerm`||e===`removeTerm`)&&E.push({key:`term`,label:`Term`,required:!0,control:{type:`text`,value:h,onChange:T(g)}}),(0,Z.jsxs)(L,{title:Qr[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)(k,{label:Qr[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 ni(){let e=Y(),t=me(),n=Me(),r=ee(),{openCaseEditor:i}=Wr(),{list:a}=Ne(),{datasetId:o,selected:s,setSelected:c,filters:l,setFilters:u,handedOver:d}=it(),[f,p]=(0,J.useState)([]),[m,h]=(0,J.useState)(!1),[g,v]=(0,J.useState)(null),[y,b]=(0,J.useState)(null),[x,S]=(0,J.useState)(null),[C,w]=(0,J.useState)(null),E=(0,J.useCallback)(()=>w(null),[]),[D]=he(`promptlab.mappings`);(0,J.useEffect)(()=>{let t=!0;return e.sources().then(e=>{t&&p(e.sources)}).catch(()=>{}),()=>{t=!1}},[e]);let O=a?.find(e=>e.id===o)??a?.[0]??null,k=O?.id??``,A=Pe(k||null),j=A?.doc?.body??null,M=j?.cases,N=(0,J.useMemo)(()=>M?q().gradedSetFrom({cases:M}):[],[M]),P=(0,J.useMemo)(()=>Sr(t,k),[t,k,D]),F=(0,J.useMemo)(()=>new Set(N.map(Ge)),[N]),I=(0,J.useMemo)(()=>new Set([...s].filter(e=>F.has(e))),[s,F]),L=(0,J.useMemo)(()=>tt(N,l,I),[N,l,I]),R=(0,J.useCallback)(()=>n.entry(k)?.doc?.body??null,[n,k]),z=(0,J.useCallback)(e=>{k&&n.edit(k,t=>({...t,cases:e}))},[n,k]),B=e=>{i(e,{dataset:k,files:L.map(e=>e.filename),onRemove:H})},V=()=>{let e=R()?.cases??[],t=ri(e);z([...e,{id:Pr(e),filename:t,todo:!0,traits:[],why:``,expect:[],anyOf:[],forbid:[],allow:[],minCount:null,maxCount:null,watch:[]}]),i(t,{dataset:k,files:[...N.map(e=>e.filename),t],onRemove:H})};function H(e){let n=R()?.cases??[];z(Vr({cases:n},e)),k&&Tr(t,k,e),r.offer({label:`Removed ${e}`,restore:()=>z(n)})}let W=e=>{let i=R();if(!k||!i)return null;let{next:a,changed:o}=Je(i.cases,I,e);if(!o.length)return w(null),null;if(e.type!==`delete`){let e=Ye(i.cases,a,o);if(e.cases.length)return e}Oe(t,k,i,`bulk`);let s=i.cases;if(n.edit(k,e=>({...e,cases:a})),e.type===`delete`){let e=new Set(o);for(let n of s)e.has(Ge(n))&&Tr(t,k,q().caseFile(n));c(t=>new Set([...t].filter(t=>!e.has(t))))}return r.offer({label:$e(e,o.length),restore:()=>n.edit(k,e=>({...e,cases:s}))}),w(null),null},G=I.size===0,K=[{label:`Set count…`,icon:_,disabled:G,onSelect:()=>w(`bounds`)},{label:`Add term…`,icon:U.add,disabled:G,onSelect:()=>w(`addTerm`)},{label:`Remove term…`,icon:Hn,disabled:G,onSelect:()=>w(`removeTerm`)},{label:`Mark Todo…`,icon:xn,disabled:G,onSelect:()=>w(`todo`)},{label:`Mark graded…`,icon:Sn,disabled:G,onSelect:()=>w(`graded`)},{label:`Delete`,icon:U.remove,destructive:!0,disabled:G,onSelect:()=>void W({type:`delete`})}],te=async n=>{h(!1),S(null),b({done:0,total:N.length,source:n.name});try{await xr(e,t,k,n,N.map(e=>e.filename),(e,t)=>b({done:e,total:t,source:n.name}))}catch(e){S(e instanceof Error?e.message:String(e))}finally{b(null)}};return(0,Z.jsxs)(`div`,{className:`evals`,children:[a?.length?(0,Z.jsxs)(qr,{rows:N,shown:L,filters:l,onFilters:u,selected:I,onSelect:c,selectionActions:K,mapping:P,onEdit:B,onAdd:V,onRemove:H,onMap:()=>h(!0),...y?{progress:y}:{},onMapDetails:v,children:[d&&O&&(0,Z.jsxs)(`p`,{className:`note ev-from`,role:`status`,children:[(0,Z.jsxs)(`span`,{children:[`From `,d.from]}),d.found<d.wanted&&(0,Z.jsxs)(`span`,{children:[d.found,` of `,d.wanted,` are in `,O.name,` now`]})]}),A?.sync.state===`missing`&&(0,Z.jsx)(`p`,{className:`note bad`,role:`alert`,children:A.sync.message}),x&&(0,Z.jsx)(`p`,{className:`note bad ds-map-say`,role:`alert`,children:x})]}):null,C&&j&&(0,Z.jsx)(ti,{kind:C,cases:j.cases,keys:I,onApply:W,onClose:E}),m&&(0,Z.jsx)(Gr,{sources:f,recents:P.recents,onPick:e=>void te(e),onClose:()=>h(!1)}),g&&P.cases[g]&&(0,Z.jsx)(Kr,{filename:g,mapped:P.cases[g],onClose:()=>v(null)}),(0,Z.jsx)(T,{undo:r.undo,onUndo:r.undoNow,onDismiss:r.dismiss})]})}var ri=e=>{let t=new Set(e.map(e=>q().caseFile(e)));for(let e=1;;e++){let n=e===1?`untitled`:`untitled-${e}`;if(!t.has(n))return n}},ii=[{value:`all`,label:`All`},{value:`used`,label:`Used`},{value:`unused`,label:`Unused`}],ai=[{value:`all`,label:`All`},{value:`scenario`,label:`Used by this target`},{value:`scenarios`,label:`Used by all targets`}];function oi(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 si(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 ci=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()};function li({id:e,onClose:t,onDuplicate:n,onDelete:r}){let i=He(),a=We(e),{openRun:o}=st(),[s,c]=(0,J.useState)(new Set),[l,u]=(0,J.useState)(new Set),[d,f]=(0,J.useState)(null),p=a?.doc;if(!p)return(0,Z.jsx)(O,{title:`Prompt`,status:a?.sync.state===`missing`?a.sync.message:`Loading…`,statusBad:a?.sync.state===`missing`,sections:[],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=>p.versions.find(t=>t.version===e)?.text??``,v=p.uses.some(e=>e.job>0),y=[{key:`version`,header:`Version`,sort:e=>e.version,cell:e=>`v${e.version}${e.version===p.version?` (newest)`:``}`},{key:`created`,header:`Made`,sort:e=>e.created,cell:e=>ci(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)(w,{label:`v${t.version} actions`,actions:[{label:s.has(t.version)?`Hide words`:`Show words`,icon:m,onSelect:()=>h(s,t.version,c)},{label:`Restore`,icon:E,disabled:t.version===p.version,onSelect:()=>{f(null),i.restoreVersion(e,t.version).catch(g)}}]})}],b=e=>`${e.runId}:${e.scenarioId}:${e.job}`,x=[{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:St(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=>ci(e.submittedAt)},{key:`menu`,header:``,label:``,className:`pl-menu`,sort:null,cell:e=>(0,Z.jsx)(w,{label:`${St(e.submittedAt)} ${e.scenarioName} actions`,actions:[{label:l.has(b(e))?`Hide words`:`Show words`,icon:m,onSelect:()=>h(l,b(e),u)}]})}],S=[{label:`Set as default`,icon:Yn,disabled:p.default,onSelect:()=>{f(null),i.setDefault(e).catch(g)}},{label:`Duplicate`,icon:U.clone,onSelect:()=>n(p)},{label:`Delete`,icon:U.remove,destructive:!0,disabled:p.default,onSelect:()=>r(p)}],C=d??Ie(a.sync),T=a.sync.state===`conflict`;return(0,Z.jsx)(O,{title:Fe(p),status:C??void 0,statusBad:!!C,menu:S,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:p.name,placeholder:`First line`,onChange:t=>i.edit(e,{name:t})}},{key:`version`,label:`Version`,required:!0,control:{type:`static`,text:`v${p.version}${p.default?` (Default)`:``}`}},{key:`text`,label:`Prompt`,required:!0,control:{type:`textarea`,value:p.text,placeholder:`None`,onChange:t=>i.edit(e,{text:t})}}]},{key:`versions`,title:`Versions`,children:(0,Z.jsx)(D,{className:`pltable pl-versions`,label:`Versions`,rows:p.versions,rowKey:e=>String(e.version),columns:y,after:e=>s.has(e.version)&&(0,Z.jsx)(`tr`,{className:`pl-words-row`,children:(0,Z.jsx)(`td`,{colSpan:y.length,children:(0,Z.jsx)(`pre`,{className:`pl-words`,children:e.text})})})})},{key:`uses`,title:`Uses`,children:p.uses.length===0?(0,Z.jsx)(`p`,{className:`note`,children:`No uses yet.`}):(0,Z.jsx)(D,{className:`pltable pl-uses`,label:`Uses`,rows:p.uses,rowKey:b,pageSize:10,columns:x,after:e=>l.has(b(e))&&(0,Z.jsx)(`tr`,{className:`pl-words-row`,children:(0,Z.jsx)(`td`,{colSpan:x.length,children:(0,Z.jsx)(`pre`,{className:`pl-words`,children:_(e.version)})})})})}]})}function ui(){let e=He(),{list:t,error:n}=Ue(),r=ee(),[i,a]=H(`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,h]=(0,J.useState)(null),g=t??[],_=g.filter(e=>oi(e,c,u)),v=e=>h(e instanceof Error?e.message:String(e)),y=async()=>{h(null);try{p((await e.create({name:``,text:``})).id)}catch(e){v(e)}},b=async t=>{h(null);try{await e.flush(t.id);let n=await e.create({name:`${Fe(t)} copy`,text:e.entry(t.id)?.doc?.text??t.text});p(n.id)}catch(e){v(e)}},x=async t=>{h(null);try{let n=await e.remove(t.id);f===t.id&&p(null),r.offer({label:`Deleted ${Fe(t)}`,restore:()=>{e.restore(n).catch(v)}})}catch(e){v(e)}},S=t=>{h(null),e.setDefault(t.id).catch(v)},C=e=>[{label:`Edit`,icon:U.edit,onSelect:()=>p(e.id)},{label:`Set as default`,icon:Yn,disabled:e.default,onSelect:()=>S(e)},{label:`Duplicate`,icon:U.clone,onSelect:()=>void b(e)},{label:`Delete`,icon:U.remove,destructive:!0,disabled:e.default,onSelect:()=>void x(e)}];return(0,Z.jsxs)(A,{id:`prompts`,title:`Prompt library`,note:t?`${g.length} ${g.length===1?`prompt`:`prompts`}`:void 0,actions:[{label:`Page size`,icon:U.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)(`p`,{className:`note${n?` bad`:``}`,role:n?`alert`:void 0,children:n??`Loading…`}):g.length===0?(0,Z.jsx)(`p`,{className:`note`,children:`No prompts yet.`}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(I,{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:ii}],count:{shown:_.length,total:g.length}}),_.length===0?(0,Z.jsx)(`p`,{className:`note`,children:`No prompts match these filters.`}):(0,Z.jsx)(D,{className:`pltable`,label:`Prompts`,rows:_,rowKey:e=>e.id,pageSize:i,rowProps:e=>({"data-default":e.default||void 0}),columns:[{key:`prompt`,header:`Prompt`,sort:e=>Fe(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:[Fe(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?ci(e.lastUsed):`—`},{key:`menu`,header:``,label:``,className:`pl-menu`,sort:null,cell:e=>(0,Z.jsx)(w,{label:`${Fe(e)} actions`,actions:C(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 y(),children:[(0,Z.jsx)(W,{size:14,"aria-hidden":`true`}),`Add prompt`]}),f&&(0,Z.jsx)(li,{id:f,onClose:()=>p(null),onDuplicate:e=>void b(e),onDelete:e=>void x(e)}),o&&(0,Z.jsx)(F,{value:i,onChange:a,onClose:()=>s(!1)}),(0,Z.jsx)(T,{undo:r.undo,onUndo:r.undoNow,onDismiss:r.dismiss})]})}var di=`evals-lab.sources`,fi={view:`thumbs`,sort:`name`,dir:1};function pi(){try{let e=window.localStorage.getItem(di);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 fi}function mi(e){try{window.localStorage.setItem(di,JSON.stringify(e))}catch{}}var hi=e=>{let t=e.lastIndexOf(`.`);return t<0?``:e.slice(t).toLowerCase()},gi=[`.heic`,`.heif`,`.dng`,`.tif`,`.tiff`],_i=[`.jpg`,`.jpeg`,`.png`],vi=e=>_i.includes(hi(e))||gi.includes(hi(e)),yi=(e,t)=>`/api/sources/${encodeURIComponent(e)}/thumbs/${encodeURIComponent(t.name)}${t.v?`?v=${t.v}`:``}`,bi=(e,t)=>gi.includes(hi(t.name))?`/api/sources/${encodeURIComponent(e)}/zoom/${encodeURIComponent(t.name)}`:`/api/sources/${encodeURIComponent(e)}/files/${encodeURIComponent(t.name)}`;function xi(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 Si(e,t){let n=t.trim().toLowerCase();return n?e.filter(e=>e.name.toLowerCase().includes(n)):[...e]}function Ci(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 wi(e){return new Date(e*1e3).toLocaleDateString(void 0,{year:`numeric`,month:`short`,day:`numeric`})}function Ti(e){return{id:e.id,name:e.name,system:e.system,type:e.type,files:e.files.length,bytes:e.bytes}}var Ei=`[redacted]`,Di=/^(?:api[-_]?key|x-api-key|authorization|ocp-apim-subscription-key|password|secret|client[-_]?secret|token|access[-_]?token|refresh[-_]?token|sig)$/i,Oi=/^(?:headers|authentication)$/,ki=[[/sk-ant-[A-Za-z0-9_-]+/g,Ei],[/sk-[A-Za-z0-9_-]{20,}/g,Ei],[/Bearer\s+[A-Za-z0-9._~+/=-]+/g,`Bearer ${Ei}`],[/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,Ei],[/([?&](?:sig|code)=)[^&"\s]+/g,`$1${Ei}`]];function Ai(e){let t=0,n=e=>{let n=e;for(let[e,r]of ki)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))Oi.test(i)&&a&&typeof a==`object`&&!Array.isArray(a)?n[i]=Object.fromEntries(Object.keys(a).map(e=>(t++,[e,Ei]))):Oi.test(i)&&typeof a==`string`||Di.test(i)&&a!=null&&typeof a!=`object`?(t++,n[i]=Ei):n[i]=r(a);return n}return typeof e==`string`?n(e):e};return{value:r(e),count:t}}var ji=`https://api.flow.microsoft.com/providers/Microsoft.ProcessSimple`,Mi=`api-version=2016-11-01`,Ni=/\.powerplatformusercontent\.com$/,Pi=4,Fi=4;function Ii(e,t=(e,t)=>fetch(e,t)){let n=async n=>{let r=`${ji}${n}${n.includes(`?`)?`&`:`?`}${Mi}`;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(ji).pathname.length)}${t.search}`},o=(e,t)=>`/environments/${r(e)}/flows/${r(t)}/runs`,s=0,c=[],l=async()=>{if(s<Pi){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:`||!Ni.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<Fi){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 Li=[`https://service.flow.microsoft.com//.default`],Ri=null;function zi(e){let t=`${e.clientId}/${e.tenant}`;return Ri?.key!==t&&(Ri={key:t,pca:oe(()=>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}),[])}),Ri.pca}var Bi=()=>{let e=new URLSearchParams(window.location.search);return e.has(`state`)&&(e.has(`code`)||e.has(`error`))};async function Vi(e){await zi(e)}async function Hi(e){let t=await zi(e);return(t.getActiveAccount()??t.getAllAccounts()[0]??null)?.username??null}var Ui=`signin`;function Wi(e=window.location.href){let t=new URL(e);return t.hostname===`127.0.0.1`?(t.hostname=`localhost`,t.searchParams.set(Ui,`microsoft`),t.href):null}function Gi(){let e=new URL(window.location.href);return e.searchParams.get(`signin`)===`microsoft`&&(e.searchParams.delete(Ui),window.history.replaceState(window.history.state,``,e.href),!0)}async function Ki(e,t=window.location.href){let n=Wi();if(n){window.location.assign(n);return}await(await zi(e)).loginRedirect({scopes:Li,prompt:`select_account`,redirectStartPage:t})}async function qi(e){let t=await zi(e),n=t.getActiveAccount()??t.getAllAccounts()[0];n&&await t.clearCache({account:n})}async function Ji(e){let t=await zi(e),n=t.getActiveAccount()??t.getAllAccounts()[0];if(!n)throw Error(`sign in to Microsoft first`);try{return(await t.acquireTokenSilent({scopes:Li,account:n})).accessToken}catch(e){let{InteractionRequiredAuthError:r}=await oe(async()=>{let{InteractionRequiredAuthError:e}=await import(`./dist-DI3ewZYj.js`);return{InteractionRequiredAuthError:e}},[]);throw e instanceof r&&await t.acquireTokenRedirect({scopes:Li,account:n,redirectStartPage:window.location.href}),e}}var Yi=new EventTarget,Xi=()=>Yi.dispatchEvent(new Event(`change`));function Zi(){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(),Yi.addEventListener(`change`,r),()=>{t=!1,Yi.removeEventListener(`change`,r)}},[e]),t}var Qi=()=>Zi().cfg,$i=e=>Ii(()=>Ji(e));async function ea(e,t,n){let r=await e.flow(t,n);return{name:r.name,definition:Ai(r.definition).value}}function ta({onMade:e}){let t=Y(),n=Qi(),r=(0,J.useMemo)(()=>n?$i(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&&Hi(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)(`p`,{className:`note`,children:`Loading…`});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 Ki(n).catch(b),children:[(0,Z.jsx)(zn,{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 ea(r,c,f);await t.saveDefinition(a.id,0,o.definition),await e()}catch(e){n&&await t.removeSource(n).catch(()=>{}),b(e instanceof de?Error(e.message):e)}finally{_(!1)}};return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(k,{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 na=`evals-lab/record`,$=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ra=/\b(triggerBody|triggerOutputs|body|outputs|actions|variables|items|item|parameters)\(\s*(?:'((?:[^']|'')*)')?\s*\)/g;function ia(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)ia(n,t);else if($(e))for(let n of Object.values(e))ia(n,t);return t}function aa(e,t=null){let n=new Map;for(let r of ia(e))for(let e of r.matchAll(ra)){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 oa(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:na,version:1,step:e,at:null,scope:n,request:null,result:null,origin:{kind:`hand`}}}function sa(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 ca=Object.create(null);ca.Http={label:`HTTP`,template:({headers:e,authentication:t,...n})=>n};var la=Object.create(null);la.Foreach={loops:!0},la.Until={loops:!0},la.InitializeVariable={declares:e=>(Array.isArray(e.variables)?e.variables:[]).flatMap(e=>$(e)&&typeof e.name==`string`?[e.name]:[])};var ua=e=>!!(e&&la[e]?.loops);function da(e){let t=[],n=(e,r)=>{for(let[i,a]of Object.entries(e??{})){let e=a.type?ca[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:aa(n,r.at(-1)??null)})}let o=ua(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 fa(e){let t={},n=(e,r)=>{for(let[i,a]of Object.entries(e??{})){t[i]={...a,loops:r};let e=ua(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 pa(e,t,n,r){let i=fa(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?la[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:na,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 ma(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 ha=e=>e.from===`trigger`?`trigger`:e.from===`parameter`?``:e.name,ga=e=>{if(typeof e!=`string`)return e;try{return JSON.parse(e)}catch{return e}};function _a(e,t){let n=[...new Set(t.flatMap(e=>Object.keys(e)))],r=new Set(e.reads.map(ha).filter(Boolean)),i=n.filter(e=>!r.has(e)&&!(r.has(`trigger`)&&e.startsWith(`trigger.`)));return{records:t.map(t=>{let n=oa(e.name,e.reads);n.origin={kind:`upload`};for(let r of e.reads){let e=ha(r);if(r.from===`trigger`){let r=Object.keys(t).filter(e=>e.startsWith(`trigger.`)),i=e in t?ga(t[e]):r.length?Object.fromEntries(r.map(e=>[e.slice(8),ga(t[e])])):null;n.scope.trigger={body:i}}else if(e in t){let i=ga(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 va(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===`
5
- `||o===`\r`?(o===`\r`&&a[e+1]===`
6
- `&&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 ya(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:l(a.method,n),uri:l(a.uri,n),body:l(a.body??null,n)}}catch(e){return{match:!1,where:e instanceof Error?e.message:String(e)}}let a=ba(i,t.request,`request`);return a?{match:!1,where:a}:{match:!0}}function ba(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=ba(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=ba(e[i],t[i],`${n}.${i}`);if(r)return r}return null}return JSON.stringify(e)===JSON.stringify(t)?null:`${n}`}var xa=Object.create(null);xa.ParseJson={reads:e=>typeof e.content==`string`?e.content:null,schema:e=>e.schema??null};function Sa(e,t){for(let[n,r]of Object.entries(fa(e))){let e=r.type?xa[r.type]:void 0,i=e&&$(r.inputs)?e.reads(r.inputs):null;if(i&&aa(i).some(e=>e.from===`action`&&e.name===t))return{name:n,expression:i,schema:e.schema&&$(r.inputs)?e.schema(r.inputs)??null:null}}return null}function Ca(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 wa(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 Ta(e,t){let n=q(),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 Ea(e,t,n,r){let i=q(),a=n.template,o=String(a.uri??``),s=i.httpApiFor(o),c={type:`httpRequest`,api:s,method:String(a.method??`POST`).toUpperCase(),...wa(o),body:a.body??null,...i.HTTP_APIS[s].cellOf(a.body??null)},l=Sa(t,n.name),u=l?Ca(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(`
7
- `)}]:[]],f=Ta(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)]}],tests:d.length?[i.newTest(`metrics`,``,{metrics:d})]:[]}}function Da(e,t){let n=e.result;if(!n||!(`status`in n))return null;let r=da(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:q().httpApiFor(i),readAs:Sa(t,r.name)?.expression??null};try{return q().httpReplyOf(a,{prompt:``},n.body,n.status,{scope:e.scope,now:e.at}).raw}catch{return null}}function Oa(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 ka(e,t){let n=[],r=0;for(let{name:i,record:a}of e){let e=Da(a,t);if(e==null){r++;continue}let o=Sa(t,a.step),s=o?Ca(t,o.name):[];n.push({id:i.replace(/\.json$/i,``).replace(/[^A-Za-z0-9._-]/g,`_`),filename:i,todo:!0,metrics:Oa(e,s)})}return{cases:n,skipped:r}}async function Aa(e,t,n,r,i){let a=await e.run(t,n,r),o=fa(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 ja(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 Aa(e,t,n,o,a);for(let e of await r.callsOf(i)){let t=Ai(await pa(i,e,r,a)).value,n=sa(t);if(c.has(n)){u++;continue}c.add(n),l.push(t)}s?.(++d)}return{records:l,skipped:u}}var Ma=e=>e.name.toLowerCase().endsWith(`.json`),Na=e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result)),r.onerror=()=>n(r.error),r.readAsText(e)}),Pa=`evals-lab.flow.importing`;function Fa(e){try{return sessionStorage.getItem(e)}catch{return null}}function Ia(e,t){try{t?sessionStorage.setItem(e,t):sessionStorage.removeItem(e)}catch{}}var La=e=>e instanceof Error?e.message:String(e);function Ra({source:t,definition:n,cfg:i}){let a=Y(),o=Me(),s=ee(),[c,l]=(0,J.useState)(t.files.filter(Ma)),[u,d]=(0,J.useState)({}),[f,p]=(0,J.useState)(null),[h,g]=(0,J.useState)(()=>{let e=Fa(Pa)===t.id;return e&&Ia(Pa,null),e?`import`:null}),[_,v]=(0,J.useState)(null),y=(0,J.useMemo)(()=>da(n),[n]),b=(0,J.useCallback)(async()=>{let e=(await a.source(t.id)).files.filter(Ma);l(e);let n=await Promise.all(e.map(async e=>{try{return[e.name,JSON.parse(await Na(await a.file(t.id,e.name)))]}catch{return[e.name,null]}}));d(Object.fromEntries(n))},[a,t.id]);(0,J.useEffect)(()=>{b().catch(e=>p(La(e)))},[b]);let x=e=>{let t=u[e],r=t?y.find(e=>e.name===t.step):void 0;return t&&r?ya(r,t,n):null},S=(0,J.useMemo)(()=>new Set(c.flatMap(e=>u[e.name]?[sa(u[e.name])]:[])),[c,u]),C=async(e,n=0)=>{let r=0,i=[];for(let n of e)try{await a.upload(t.id,ma(n),new Blob([JSON.stringify(n,null,2)],{type:`application/json`})),r++}catch(e){i.push(e instanceof de?e.message:La(e))}await b(),p([`Added ${r}`,n?`Skipped ${n}`:``,i.length?`Refused ${i.length}: ${i[0]}`:``].filter(Boolean).join(` · `))},E=async()=>{let{cases:e,skipped:r}=ka(c.flatMap(e=>u[e.name]?[{name:e.name,record:u[e.name]}]:[]),n);if(!e.length)return p(`No record holds a production reply.`);try{let n=await o.create(`${t.name} · production`,{cases:e});p([`Made ${n.name}: ${e.length} ${e.length===1?`case`:`cases`}`,r?`Skipped ${r}`:``].filter(Boolean).join(` · `))}catch(e){p(La(e))}},O=async e=>{try{let{trash:n}=await a.removeFiles(t.id,e);l(t=>t.filter(t=>!e.includes(t.name))),s.offer({label:`Removed ${e[0]}`,restore:()=>void a.restoreTrash(n).then(b,e=>p(La(e)))})}catch(e){p(La(e))}},k=async e=>{let n=URL.createObjectURL(await a.file(t.id,e)),r=document.createElement(`a`);r.href=n,r.download=e,document.body.append(r),r.click(),r.remove(),URL.revokeObjectURL(n)},j=t=>[{label:`View`,icon:m,onSelect:()=>v(t.name)},{label:`Download`,icon:e,onSelect:()=>void k(t.name).catch(e=>p(La(e)))},{label:`Remove`,icon:G,destructive:!0,onSelect:()=>void O([t.name])}],M=(0,J.useCallback)(()=>g(null),[]),N=(0,J.useCallback)(()=>v(null),[]),P=_?u[_]:null;return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(A,{id:`flow-records`,title:`Records`,note:String(c.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:r,disabled:!y.length||!i,onSelect:()=>g(`import`)},{label:`Upload`,icon:K,disabled:!y.length,onSelect:()=>g(`upload`)},{label:`New dataset`,icon:Tn,disabled:!c.length,onSelect:()=>void E()}],children:[f&&(0,Z.jsx)(`p`,{className:`note`,role:`status`,children:f}),c.length?(0,Z.jsx)(`div`,{className:`sflow`,children:(0,Z.jsx)(D,{className:`slist`,label:`Records`,rows:c,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:Va(u[e.name])})]})},{key:`result`,header:`Result`,sort:e=>Ha(u[e.name]),cell:e=>Ha(u[e.name])},{key:`request`,header:`Request`,sort:e=>za(x(e.name)),tdProps:e=>{let t=x(e.name);return t&&t.match===!1?{title:t.where}:{}},cell:e=>za(x(e.name))},{key:`menu`,header:``,className:`s-actions`,sort:null,cell:e=>(0,Z.jsx)(w,{label:`${e.name} actions`,actions:j(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.jsxs)(`button`,{type:`button`,className:`ghost add-btn`,disabled:!y.length,onClick:()=>g(`hand`),children:[(0,Z.jsx)(W,{size:14,"aria-hidden":`true`}),` Add record`]})]}),h===`import`&&i&&(0,Z.jsx)(Ga,{cfg:i,source:t,steps:y,definition:n,held:S,onClose:M,onRead:async(e,t)=>{g(null),await C(e,t)}}),h===`hand`&&(0,Z.jsx)(Ka,{steps:y,onClose:M,onAdd:async e=>{g(null),await C([e])}}),h===`upload`&&(0,Z.jsx)(Ja,{steps:y,onClose:M,onRead:async e=>{g(null),await C(e)}}),_&&(0,Z.jsx)(L,{title:_,onClose:N,wide:!0,children:(0,Z.jsx)(`pre`,{className:`pl-words`,children:P?JSON.stringify(P,null,2):`Unreadable.`})}),(0,Z.jsx)(T,{undo:s.undo,onUndo:s.undoNow,onDismiss:s.dismiss})]})}var za=e=>!e||e.match===null?`—`:e.match?`Match`:`Differs`,Ba={run:`Run`,hand:`Hand`,upload:`Upload`},Va=e=>e?[e.step,Ba[e.origin.kind]??e.origin.kind,e.at?wi(Date.parse(e.at)/1e3):``].filter(Boolean).join(` · `):`Unreadable`;function Ha(e){let t=e?.result;return t?`error`in t?t.error.code||`Error`:String(t.status):`—`}var Ua=e=>e.map(e=>({value:e.name,label:e.name})),Wa=e=>e.from===`trigger`?`Trigger body`:ha(e);function Ga({cfg:e,source:t,steps:n,definition:r,held:i,onClose:a,onRead:o}){let s=(0,J.useMemo)(()=>$i(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);(0,J.useEffect)(()=>{Hi(e).then(u,()=>u(null))},[e]),(0,J.useEffect)(()=>{l&&c.environment&&c.flow&&s.runs(c.environment,c.flow).then(m,e=>w(La(e)))},[l,s,c.environment,c.flow]);let T=(0,J.useMemo)(()=>[...new Set((p??[]).map(e=>e.status))].sort(),[p]),E=(0,J.useMemo)(()=>(p??[]).filter(e=>!h||e.status===h),[p,h]),O=e=>v(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),A=E.length>0&&E.every(e=>_.has(e.id)),j=E.filter(e=>_.has(e.id)).map(e=>e.id),M=async()=>{let e=n.find(e=>e.name===d);if(!e||!c.environment||!c.flow)return;let t=j;w(null),S(`Reading 0 of ${t.length}`);try{let{records:n,skipped:a}=await ja(s,c.environment,c.flow,t,e,r,i,e=>S(`Reading ${e} of ${t.length}`));await o(n,a)}catch(e){w(La(e)),S(null)}};return(0,Z.jsxs)(L,{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||!j.length||!d,onClick:()=>void M(),children:[`Import `,j.length||``]})]}),children:[l===void 0?(0,Z.jsx)(`p`,{className:`note`,children:`Loading…`}):l?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(k,{label:`Import`,rows:[{key:`step`,label:`Step`,control:{type:`select`,value:d,options:Ua(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(E.slice(0,t).map(e=>e.id)))}}}]}),p?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(I,{noun:`runs`,count:{shown:E.length,total:p.length},lead:(0,Z.jsx)(`input`,{type:`checkbox`,"aria-label":`Select all shown`,checked:A,disabled:!E.length,onChange:()=>v(A?new Set:new Set(E.map(e=>e.id)))}),filters:[{key:`status`,label:`Status`,value:h,onChange:g,options:[{value:``,label:`All`},...T.map(e=>({value:e,label:e}))]}]}),E.length?(0,Z.jsx)(`div`,{className:`sflow`,children:(0,Z.jsx)(D,{className:`slist`,label:`Runs`,rows:E,rowKey:e=>e.id,pageSize:20,rowProps:e=>({onClick:()=>O(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:()=>O(e.id),onClick:e=>e.stopPropagation()})},{key:`start`,header:`Started`,sort:e=>e.startTime??``,cell:e=>e.startTime?wi(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)(`p`,{className:`note`,children:`Loading…`})]}):(0,Z.jsx)(`div`,{className:`sacts`,children:(0,Z.jsxs)(`button`,{type:`button`,className:`ghost`,onClick:()=>{Ia(Pa,t.id),Ki(e).catch(e=>{Ia(Pa,null),w(La(e))})},children:[(0,Z.jsx)(zn,{size:14,"aria-hidden":`true`}),` Sign in with Microsoft`]})}),C&&(0,Z.jsx)(`p`,{className:`note bad`,role:`alert`,children:C})]})}function Ka({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=>ha(e));return(0,Z.jsxs)(L,{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=>ha(t)===e))),[t]=_a(s,[e]).records;n({...t,origin:{kind:`hand`}})},children:`Add`})}),children:[(0,Z.jsx)(k,{label:`Record`,rows:[{key:`step`,label:`Step`,control:{type:`select`,value:r,options:Ua(e),onChange:e=>{i(e),o({})}}},...c.map(e=>({key:`read-${ha(e)}`,label:Wa(e),control:{type:`textarea`,value:a[ha(e)]??``,onChange:t=>o(n=>({...n,[ha(e)]:t}))}}))]}),s&&!c.length&&(0,Z.jsx)(`p`,{className:`note`,children:`Reads nothing.`})]})}function qa(e,t){if(e.toLowerCase().endsWith(`.csv`))return{rows:va(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 Ja({steps:e,onClose:t,onRead:n}){let r=(0,J.useRef)(null),[i,a]=(0,J.useState)(e[0]?.name??``),[o,s]=(0,J.useState)(null),[c,l]=(0,J.useState)(null),u=e.find(e=>e.name===i),d=o&&u&&`rows`in o.parsed?_a(u,o.parsed.rows):null,f=o?`records`in o.parsed?o.parsed.records:d?.records??[]:[],p=async e=>{if(e){l(null);try{s({name:e.name,parsed:qa(e.name,await Na(e))})}catch(t){s(null),l(`${e.name}: ${La(t)}`)}}};return(0,Z.jsxs)(L,{title:`Upload`,onClose:t,wide:!0,footer:(0,Z.jsx)(`div`,{className:`sacts`,children:(0,Z.jsxs)(`button`,{type:`button`,className:`ghost`,disabled:!f.length,onClick:()=>void n(f),children:[`Add `,f.length||``]})}),children:[(0,Z.jsx)(k,{label:`Upload`,rows:[...o&&`records`in o.parsed?[]:[{key:`step`,label:`Step`,control:{type:`select`,value:i,options:Ua(e),onChange:a}}],{key:`file`,label:`File`,control:{type:`static`,text:o?.name??`—`}},...o?[{key:`count`,label:`records`in o.parsed?`Records`:`Rows`,control:{type:`static`,text:String(f.length)}}]:[],...d?.unmatched.length?[{key:`unmatched`,label:`Unmatched`,control:{type:`static`,text:d.unmatched.join(`, `)}}]:[]]}),(0,Z.jsxs)(`div`,{className:`sacts`,children:[(0,Z.jsxs)(`button`,{type:`button`,className:`ghost`,onClick:()=>r.current?.click(),children:[(0,Z.jsx)(K,{size:14,"aria-hidden":`true`}),` Choose file`]}),(0,Z.jsx)(`input`,{ref:r,type:`file`,accept:`.json,.csv`,hidden:!0,"aria-hidden":`true`,onChange:e=>{p(e.target.files?.[0]),e.target.value=``}})]}),c&&(0,Z.jsx)(`p`,{className:`note bad`,role:`alert`,children:c})]})}function Ya({source:e,onBack:t}){let n=Y(),r=Qi(),[i,a]=(0,J.useState)(null),[o,s]=(0,J.useState)(null),[c,l]=(0,J.useState)(!1),u=e.config??{},d=(0,J.useCallback)(()=>{n.definition(e.id).then(a,()=>a(null))},[n,e.id]);(0,J.useEffect)(d,[d]);let f=async()=>{if(r&&i&&u.environment&&u.flow){l(!0),s(null);try{if(!await Hi(r)){await Ki(r);return}let t=await ea($i(r),u.environment,u.flow);a(await n.saveDefinition(e.id,i.version,t.definition)),s(`Synced.`)}catch(e){e instanceof de&&e.status===409?(d(),s(`It changed since: reloaded.`)):s(e instanceof Error?e.message:String(e))}finally{l(!1)}}},p=(0,J.useMemo)(()=>Xa(i?.body),[i]),m=(0,J.useMemo)(()=>da(i?.body),[i]),[h,g]=he(`promptlab.workflows`),[_]=he(`promptlab.profiles`),v=t=>{let n=m.find(e=>e.name===t);if(!n||!i)return;let r=Ea({id:e.id,name:e.name},i.body,n,_.list),a={id:r.id,name:r.name,work:r};g({...h,list:[...h.list,a],at:a.id}),location.hash=`#/runs`};return(0,Z.jsxs)(`div`,{className:`sources`,"data-level":`flow`,children:[(0,Z.jsx)(`header`,{className:`shead`,children:(0,Z.jsxs)(`nav`,{className:`scrumb`,"aria-label":`Breadcrumb`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`ghost crumb`,onClick:t,children:`Sources`}),(0,Z.jsxs)(`span`,{className:`crumb-cur`,"aria-current":`page`,children:[`› `,e.name]})]})}),o&&(0,Z.jsx)(`p`,{className:`note`,role:`status`,children:o}),(0,Z.jsx)(A,{id:`flow-source`,title:`Flow`,note:u.displayName,actions:[{label:`Re-sync`,icon:Gn,disabled:c||!r||!i,onSelect:()=>void f()}],children:(0,Z.jsx)(k,{label:`Flow`,rows:[{key:`flow`,label:`Flow`,control:{type:`static`,text:u.displayName||u.flow||`—`}},{key:`env`,label:`Environment`,control:{type:`static`,text:u.environment||`—`}},{key:`version`,label:`Definition`,control:{type:`static`,text:i?i.version?`Version ${i.version}${i.at?` · ${wi(Date.parse(i.at)/1e3)}`:``}`:`None`:`Loading…`}}]})}),(0,Z.jsx)(Ra,{source:e,definition:i?.body??null,cfg:r}),(0,Z.jsx)(A,{id:`flow-actions`,title:`Actions`,note:i?String(p.length):void 0,children:i&&!p.length?(0,Z.jsx)(`p`,{className:`note`,children:`No actions.`}):(0,Z.jsx)(`div`,{className:`sflow`,children:(0,Z.jsx)(D,{className:`slist`,label:`Actions`,rows:p,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=>m.some(t=>t.name===e.name)?(0,Z.jsx)(w,{label:`${e.name} actions`,actions:[{label:`New pipeline`,icon:Wn,onSelect:()=>v(e.name)}]}):null}]})})})]})}function Xa(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 Za={"power-automate":{Create:ta,Level:Ya}};function Qa({sourceId:t=null,onOpen:r,mode:a=`browse`,onPick:o,disabled:s}){let c=Y(),l=ee(),[u,d]=(0,J.useState)(null),[f,p]=(0,J.useState)(0),[g,_]=(0,J.useState)(0),[v,y]=(0,J.useState)(null),[b,x]=(0,J.useState)(pi),[S,C]=(0,J.useState)(``),[E,O]=(0,J.useState)(new Set),[A,j]=(0,J.useState)(null),[M,P]=(0,J.useState)(()=>a===`browse`&&eo()!==null),[F,R]=(0,J.useState)(null),[z,B]=(0,J.useState)(null),[V,H]=(0,J.useState)(!1),[U,K]=(0,J.useState)(``),[te,ne]=(0,J.useState)(()=>a===`browse`&&eo()||q().DEFAULT_SOURCE_TYPE),[re,ie]=(0,J.useState)(``),[ae,oe]=(0,J.useState)(``),[se,ce]=(0,J.useState)(null),[le,X]=(0,J.useState)([]),[ue,fe]=(0,J.useState)(!1),[pe,me]=(0,J.useState)(!1),he=(0,J.useRef)(null),ge=(0,J.useRef)(1),{view:_e,sort:ve,dir:ye}=b,be=(0,J.useCallback)(()=>R(null),[]),xe=(0,J.useCallback)(()=>P(!1),[]),Se=(0,J.useCallback)(()=>B(null),[]),Ce=(0,J.useCallback)(()=>H(!1),[]);(0,J.useEffect)(()=>mi(b),[b]),(0,J.useEffect)(()=>{a===`browse`&&to(M?te:null)},[a,M,te]);let we=async()=>{try{let e=await c.sources();d(e.sources),p(e.cap),_(e.used)}catch{}};(0,J.useEffect)(()=>{let e=!0;return c.sources().then(t=>{e&&(d(t.sources),p(t.cap),_(t.used))}).catch(()=>{}),()=>{e=!1}},[c]),(0,J.useEffect)(()=>{O(new Set),X([]);let e=!0;return t?c.source(t).then(t=>{e&&y(t)}).catch(()=>{e&&y(null)}):y(null),()=>{e=!1}},[t]);let Te=async()=>{if(!t){y(null);return}try{y(await c.source(t))}catch{y(null)}},Ee=e=>{ce(e),e&&window.setTimeout(()=>ce(null),6e3)},De=e=>e instanceof de?e.message:`the request failed`,Oe=Si(xi(v?.files??[],ve,ye),S),ke=e=>{O(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},Ae=()=>O(new Set(Oe.map(e=>e.name))),je=()=>O(new Set),Me=async e=>{try{let{trash:t}=await c.removeSource(e.id);d(t=>(t??[]).filter(t=>t.id!==e.id)),l.offer({label:`Deleted ${e.name}`,restore:()=>void(async()=>{try{await c.restoreTrash(t),await we()}catch(e){Ee(De(e))}})()})}catch(e){Ee(De(e))}},Ne=async e=>{if(v)try{let{trash:t}=await c.removeFiles(v.id,e),n=new Set(e);y(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)}),O(e=>new Set([...e].filter(e=>!n.has(e)))),l.offer({label:e.length===1?`Removed ${e[0]}`:`Removed ${e.length} files`,restore:()=>void(async()=>{try{let e=await c.restoreTrash(t);y(e.source)}catch(e){Ee(De(e))}})()})}catch(e){Ee(De(e))}},Pe=(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)},Fe=async e=>{if(!v)return;let t=e.length===1?e[0]:null;me(!0);try{let n=t?await c.file(v.id,t):await c.zip(v.id,e);Pe(n,t??`${v.name}.zip`)}catch(e){Ee(De(e))}finally{me(!1)}},Ie=async e=>{if(!v||v.system)return;let t=[...e];if(!t.length)return;let n=t.map(e=>({id:ge.current++,file:e,state:`uploading`}));X(e=>[...e,...n]);for(let e of n)try{await c.upload(v.id,e.file.name,e.file),X(t=>t.map(t=>t.id===e.id?{...t,state:`done`}:t))}catch(t){X(n=>n.map(n=>n.id===e.id?{...n,state:`error`,error:De(t)}:n))}await Te()},Le=e=>void Ie([e.file]),Re=async(e,t)=>{if(v&&z)try{await c.copyFiles(t.id,v.id,z.names,e===`move`),B(null),O(new Set),await Te(),Ee(e===`move`?`Moved to ${t.name}.`:`Copied to ${t.name}.`)}catch(e){Ee(De(e)),B(null)}},ze=async()=>{if(v&&U.trim())try{let e=await c.createSource(U.trim(),v.type);try{await c.copyFiles(e.id,v.id,[...E],!1)}catch(t){throw await c.removeSource(e.id).catch(()=>{}),t}H(!1),K(``),O(new Set),await we(),Ee(`Made a new Source.`)}catch(e){Ee(De(e))}},Be=async()=>{if(U.trim())try{await c.createSource(U.trim(),te),P(!1),K(``),ne(q().DEFAULT_SOURCE_TYPE),await we()}catch(e){Ee(De(e))}},Ve=async(e,t)=>{try{let n=await c.renameSource(e.id,t);d(t=>(t??[]).map(t=>t.id===e.id?Ti(n):t))}catch(e){Ee(De(e))}},He=e=>e.system?[]:[{label:`Rename`,icon:i,onSelect:()=>j(e.id)},{label:`Delete`,icon:G,destructive:!0,onSelect:()=>void Me(e)}],Ue=t=>[{label:`Preview`,icon:m,disabled:!vi(t.name),onSelect:()=>R(t)},{label:`Download`,icon:e,onSelect:()=>void Fe([t.name])},...v?.system?[]:[{label:`Remove`,icon:G,destructive:!0,onSelect:()=>void Ne([t.name])}]],We=[...v?.system?[]:[{label:`Remove`,icon:G,destructive:!0,onSelect:()=>void Ne([...E])}],{label:`Download`,icon:e,disabled:pe,onSelect:()=>void Fe([...E])},...v?.system?[]:[{label:`Move to…`,icon:jn,onSelect:()=>B({kind:`move`,names:[...E]})}],{label:`Copy to…`,icon:N,onSelect:()=>B({kind:`copy`,names:[...E]})},...v?.system?[]:[{label:`New Source from selection`,icon:Nn,onSelect:()=>H(!0)}]],Ge=e=>{e.preventDefault(),fe(!1),v&&!v.system&&Ie(e.dataTransfer.files)},Ke=(u??[]).filter(e=>(!ae||e.type===ae)&&e.name.toLowerCase().includes(re.trim().toLowerCase())),qe=(0,Z.jsx)(I,{noun:`Sources`,search:{label:`Find a Source`,value:re,placeholder:`Name`,onChange:ie},filters:[{key:`type`,label:`Type`,value:ae,onChange:oe,options:[{value:``,label:`All`},...uo()]}],count:{shown:Ke.length,total:(u??[]).length}}),Je=()=>(0,Z.jsxs)(`div`,{className:`sources`,"data-level":`sources`,children:[se&&(0,Z.jsx)(`p`,{className:`note`,role:`status`,children:se}),(0,Z.jsxs)(`header`,{className:`shead`,children:[(0,Z.jsx)(`h2`,{className:`shead-title`,children:`Sources`}),(0,Z.jsx)(ro,{view:_e,onChange:e=>x(t=>({...t,view:e}))})]}),u!==null&&u.length>0&&qe,u===null?(0,Z.jsx)(`p`,{className:`note`,children:`Loading…`}):u.length===0?(0,Z.jsx)(`p`,{className:`note`,children:`No Sources on the server yet.`}):_e===`thumbs`?(0,Z.jsx)(`ul`,{className:`sfolders`,children:Ke.map(e=>(0,Z.jsx)(`li`,{className:`sfolder`,children:(0,Z.jsxs)(`button`,{type:`button`,className:`sfolder-open${s?.(e)?` off`:``}`,disabled:s?.(e),onClick:()=>o?.(e),children:[(0,Z.jsx)(oo,{}),(0,Z.jsx)(`span`,{className:`sfolder-name`,children:e.name}),(0,Z.jsxs)(`span`,{className:`sfolder-meta`,children:[fo(e),` · `,po(e)]})]})},e.id))}):(0,Z.jsx)(D,{className:`slist slist-folders`,label:`Sources`,rows:Ke,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${s?.(e)?` off`:``}`,disabled:s?.(e),onClick:()=>o?.(e),children:[(0,Z.jsx)(oo,{}),` `,e.name]})},{key:`type`,header:`Type`,sort:e=>fo(e),cell:e=>fo(e)},{key:`files`,header:`Items`,cell:e=>e.files},{key:`size`,header:`Size`,sort:e=>e.bytes,cell:e=>Ci(e.bytes)}]})]});if(a===`pick`)return Je();if(t){if(!v)return(0,Z.jsx)(`div`,{className:`sources`,children:(0,Z.jsx)(`p`,{className:`note`,children:`Loading…`})});let e=Za[v.type]?.Level;return e?(0,Z.jsx)(e,{source:v,onBack:()=>r?.(null)}):(0,Z.jsxs)(`div`,{className:`sources`,"data-level":`files`,children:[se&&(0,Z.jsx)(`p`,{className:`note`,role:`status`,children:se}),(0,Z.jsxs)(`header`,{className:`shead`,children:[(0,Z.jsxs)(`nav`,{className:`scrumb`,"aria-label":`Breadcrumb`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`ghost crumb`,onClick:()=>r?.(null),children:`Sources`}),(0,Z.jsxs)(`span`,{className:`crumb-cur`,"aria-current":`page`,children:[`› `,v.name]})]}),(0,Z.jsx)(ro,{view:_e,onChange:e=>x(t=>({...t,view:e}))}),(0,Z.jsx)(io,{sort:ve,dir:ye,onChange:(e,t)=>x(n=>({...n,sort:e,dir:t}))}),(0,Z.jsxs)(`label`,{className:`sfilter`,children:[(0,Z.jsx)(n,{size:14,"aria-hidden":`true`}),(0,Z.jsx)(`input`,{type:`search`,"aria-label":`Filter by name`,placeholder:`Filter`,value:S,onChange:e=>C(e.target.value)})]})]}),E.size>0&&(0,Z.jsxs)(`div`,{className:`sselect`,"data-selected":E.size,children:[(0,Z.jsxs)(`span`,{className:`sselect-count`,children:[E.size,` selected`]}),(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,onClick:Ae,children:`Select all`}),(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,onClick:je,children:`None`}),(0,Z.jsx)(w,{label:`Selection actions`,actions:We})]}),(0,Z.jsx)(`div`,{className:`sfiles${ue?` drag`:``}`,onDragOver:e=>{e.preventDefault(),fe(!0)},onDragLeave:()=>fe(!1),onDrop:Ge,children:Oe.length===0?(0,Z.jsx)(`p`,{className:`note`,children:S?`No files match that name.`:`No files in this Source yet.`}):_e===`thumbs`?(0,Z.jsx)(`ul`,{className:`stiles`,children:Oe.map(e=>(0,Z.jsx)(`li`,{children:(0,Z.jsxs)(`button`,{type:`button`,className:`stile${E.has(e.name)?` sel`:``}`,"aria-pressed":E.has(e.name),"aria-label":e.name,onClick:()=>ke(e.name),children:[(0,Z.jsx)(no,{id:v.id,file:e}),(0,Z.jsx)(`span`,{className:`stile-name`,children:e.name}),E.has(e.name)&&(0,Z.jsx)(`span`,{className:`stile-check`,children:(0,Z.jsx)(h,{size:12,"aria-hidden":`true`})})]})},e.name))}):(0,Z.jsx)(D,{className:`slist`,label:`${v.name} files`,rows:Oe,rowKey:e=>e.name,rowProps:e=>({className:E.has(e.name)?`sel`:void 0,"data-selected":E.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=>ao(e.name)},{key:`size`,header:`Size`,sort:e=>e.bytes,cell:e=>Ci(e.bytes)},{key:`added`,header:`Added`,sort:e=>e.added,cell:e=>e.added?wi(e.added):`—`},{key:`menu`,header:``,className:`s-actions`,sort:null,tdProps:()=>({onClick:e=>e.stopPropagation()}),cell:e=>(0,Z.jsx)(w,{label:`${e.name} actions`,actions:Ue(e)})}]})}),!v.system&&(0,Z.jsxs)(`div`,{className:`supload`,children:[(0,Z.jsxs)(`button`,{type:`button`,className:`ghost add-btn`,onClick:()=>he.current?.click(),children:[(0,Z.jsx)(W,{size:14,"aria-hidden":`true`}),` Add files`]}),(0,Z.jsx)(`input`,{ref:he,type:`file`,multiple:!0,hidden:!0,"aria-hidden":`true`,accept:q().sourceTypeOf(v)?.uploads?.join(`,`),onChange:e=>{e.target.files&&Ie(e.target.files),e.target.value=``}}),le.length>0&&(0,Z.jsx)(`ul`,{className:`suploads`,children:le.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:()=>Le(e),children:`Retry`})]})]},e.id))}),(0,Z.jsx)(`p`,{className:`note sudrop`,children:`…or drop them onto the Source.`})]}),F&&(0,Z.jsxs)(L,{title:F.name,onClose:be,children:[vi(F.name)?(0,Z.jsx)(`img`,{className:`spreview-img`,src:bi(v.id,F),alt:F.name}):null,(0,Z.jsx)(`p`,{className:`note`,children:Ci(F.bytes)})]}),z&&(0,Z.jsx)(L,{title:z.kind===`move`?`Move to…`:`Copy to…`,onClose:Se,children:(0,Z.jsx)(Qa,{mode:`pick`,disabled:e=>e.id===v.id||e.system||e.type!==v.type,onPick:e=>void Re(z.kind,e)})}),V&&(0,Z.jsxs)(L,{title:`New Source from selection`,onClose:Ce,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:U,autoFocus:!0,onChange:e=>K(e.target.value),onKeyDown:e=>{e.key===`Enter`&&ze()}})]}),(0,Z.jsxs)(`div`,{className:`sacts`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,disabled:!U.trim(),onClick:()=>void ze(),children:`Make`}),(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>H(!1),children:`Close`})]})]}),(0,Z.jsx)(T,{undo:l.undo,onUndo:l.undoNow,onDismiss:l.dismiss})]})}return(0,Z.jsxs)(`div`,{className:`sources`,"data-level":`sources`,children:[se&&(0,Z.jsx)(`p`,{className:`note`,role:`status`,children:se}),(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 `,Ci(g),` of `,Ci(f)]}),(0,Z.jsx)(ro,{view:_e,onChange:e=>x(t=>({...t,view:e}))})]}),u!==null&&u.length>0&&qe,u===null?(0,Z.jsx)(`p`,{className:`note`,children:`Loading…`}):u.length===0?(0,Z.jsx)(`p`,{className:`note`,children:`No Sources yet — Add source below.`}):_e===`thumbs`?(0,Z.jsx)(`ul`,{className:`sfolders`,children:Ke.map(e=>(0,Z.jsxs)(`li`,{className:`sfolder`,children:[(0,Z.jsxs)(`button`,{type:`button`,className:`sfolder-open`,onClick:()=>r?.(e.id),children:[(0,Z.jsx)(oo,{}),(0,Z.jsx)(`span`,{className:`sfolder-name`,children:e.name}),(0,Z.jsxs)(`span`,{className:`sfolder-meta`,children:[fo(e),` · `,po(e)]}),(0,Z.jsx)(lo,{source:e,cap:f,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:`${so(e.bytes,f)}%`}})})})]}),(0,Z.jsx)(`span`,{className:`sfolder-menu`,children:(0,Z.jsx)(w,{label:`${e.name} actions`,actions:He(e)})})]},e.id))}):(0,Z.jsx)(`div`,{className:`sfiles`,children:(0,Z.jsx)(D,{className:`slist slist-folders`,label:`Sources`,rows:Ke,rowKey:e=>e.id,rowProps:e=>({"data-open":e.id,onClick:()=>r?.(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)(oo,{}),` `,e.name]})},{key:`type`,header:`Type`,sort:e=>fo(e),cell:e=>fo(e)},{key:`files`,header:`Items`,cell:e=>e.files},{key:`size`,header:`Size`,sort:e=>e.bytes,cell:e=>Ci(e.bytes)},{key:`used`,header:`Used`,sort:e=>e.system?null:e.bytes,cell:e=>(0,Z.jsx)(lo,{source:e,cap:f,children:e.system?`—`:`${so(e.bytes,f)}%`})},{key:`menu`,header:``,className:`s-actions`,sort:null,tdProps:()=>({onClick:e=>e.stopPropagation()}),cell:e=>(0,Z.jsx)(w,{label:`${e.name} actions`,actions:He(e)})}]})}),A&&u&&(()=>{let e=u.find(e=>e.id===A);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&&Ve(e,n),j(null)}t.key===`Escape`&&j(null)},onBlur:t=>{let n=t.target.value.trim();n&&n!==e.name&&Ve(e,n),j(null)}})]}):null})(),(0,Z.jsxs)(`button`,{type:`button`,className:`ghost add-btn`,onClick:()=>P(!0),children:[(0,Z.jsx)(W,{size:14,"aria-hidden":`true`}),` Add source`]}),M&&(0,Z.jsxs)(L,{title:`Add source`,onClose:xe,children:[(0,Z.jsx)(k,{label:`New Source`,rows:[{key:`type`,label:`Type`,hint:q().SOURCE_TYPES[te]?.description,control:{type:`select`,value:te,options:uo(),onChange:ne}}]}),(()=>{let e=Za[te]?.Create,t=(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>P(!1),children:`Close`});return e?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(e,{onMade:async()=>{P(!1),ne(q().DEFAULT_SOURCE_TYPE),await we()}}),(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:U,autoFocus:!0,onChange:e=>K(e.target.value),onKeyDown:e=>{e.key===`Enter`&&Be()}})]}),(0,Z.jsxs)(`div`,{className:`sacts`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,disabled:!U.trim(),onClick:()=>void Be(),children:`Add`}),t]})]})})()]}),(0,Z.jsx)(T,{undo:l.undo,onUndo:l.undoNow,onDismiss:l.dismiss})]})}var $a=`evals-lab.sources.adding`;function eo(){try{return sessionStorage.getItem($a)}catch{return null}}function to(e){try{e?sessionStorage.setItem($a,e):sessionStorage.removeItem($a)}catch{}}function no({id:e,file:t}){let[n,r]=(0,J.useState)(!1);return!t.thumb||n?(0,Z.jsx)(`span`,{className:`stile-type`,children:ao(t.name)||`FILE`}):(0,Z.jsx)(`img`,{className:`stile-img`,src:yi(e,t),alt:``,loading:`lazy`,onError:()=>r(!0)})}function ro({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 io({sort:e,dir:t,onChange:n}){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=>n(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:()=>n(e,t===1?-1:1),children:(0,Z.jsx)(t===1?a:c,{size:14,"aria-hidden":`true`})})]})}function ao(e){let t=e.lastIndexOf(`.`);return t<0?``:e.slice(t+1).toUpperCase()}function oo(){return(0,Z.jsx)(Pn,{size:16,"aria-hidden":`true`})}function so(e,t){return t<=0?0:Math.max(0,Math.min(100,Math.round(e/t*100)))}function co(e,t){return e.system?`Quota: not counted`:`Quota: ${Ci(e.bytes)} of ${Ci(t)}`}function lo({source:e,cap:t,children:n}){let r=co(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 uo=()=>Object.entries(q().SOURCE_TYPES).map(([e,t])=>({value:e,label:t.label})),fo=e=>q().SOURCE_TYPES[e.type]?.label??e.type,po=e=>{let t=q().sourceTypeOf(e)?.noun??`item`;return`${e.files} ${e.files===1?t:`${t}s`}`};function mo({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 ho=[{id:`datasets`,label:`Datasets`,icon:Tn},{id:`prompts`,label:`Prompts`,icon:Vn},{id:`sources`,label:`Sources`,icon:Mn}];function go({section:e,sourceId:t}){return(0,Z.jsxs)(`div`,{className:`library`,children:[(0,Z.jsx)(`nav`,{className:`lib-sections`,"aria-label":`Library`,children:ho.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.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(or,{}),(0,Z.jsx)(ni,{})]}):e===`prompts`?(0,Z.jsx)(ui,{}):(0,Z.jsx)(mo,{sourceId:t})})]})}var _o=`0.2.0 (2026.10.02-323)`,vo=3,yo=3,bo=e=>Qn.find(t=>t.id===e),xo=e=>ho.find(t=>t.id===e),So=e=>new Date(e).toLocaleString(void 0,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`});function Co(){let e=Y(),[t]=he(`promptlab.profiles`),[n,r]=he(`promptlab.workflows`),i=Ne(),a=Ue(),{pickDataset:o}=it(),{openRun:s}=st(),[c,l]=(0,J.useState)(null),[u,d]=(0,J.useState)(null);(0,J.useEffect)(()=>{let t=!0;return e.sources().then(e=>{t&&l(e.sources)},()=>{t&&l([])}),e.queue({limit:yo}).then(e=>{t&&d(e.runs)},()=>{t&&d([])}),()=>{t=!1}},[e]);let f=(0,J.useMemo)(()=>n.list.filter(e=>e.work?.version===10),[n.list]),p=i.list??[],m=p.reduce((e,t)=>e+t.cases,0),h=(u??[]).filter(e=>e.status===`queued`||e.status===`running`).length,g=t.list.length===0?`setup`:i.list===null?null:p.length===0||m===0?`datasets`:u!==null&&u.length===0?`runs`:null,_=(...e)=>e.filter(Boolean).join(` · `)||void 0,v=bo(`library`),y=v.icon;return(0,Z.jsxs)(`div`,{className:`home`,children:[(0,Z.jsxs)(`ol`,{className:`home-line`,"aria-label":`Lab`,children:[(0,Z.jsx)(wo,{id:`runs`,icon:bo(`runs`).icon,name:bo(`runs`).label,hub:!0,start:g===`runs`,fact:_(Ct(f.length,`pipeline`),h>0&&`${h} running`),total:f.length,items:f.map(e=>({key:e.id,label:e.name,href:`#/runs`,onPick:()=>r({...n,at:e.id})}))}),(0,Z.jsx)(wo,{id:`history`,icon:bo(`history`).icon,name:bo(`history`).label,fact:u&&u.length===0?`No runs yet`:void 0,items:(u??[]).map(e=>{let t=$t(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:St(e.submittedAt)}),e.status!==`done`&&kt(e.status)]}),sub:_(So(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)(y,{size:18})}),v.label]}),(0,Z.jsxs)(`ol`,{className:`home-branch`,"aria-label":v.label,children:[(0,Z.jsx)(wo,{id:`datasets`,to:`library/datasets`,branch:!0,icon:xo(`datasets`).icon,name:xo(`datasets`).label,start:g===`datasets`,fact:i.list?_(Ct(p.length,`dataset`),Ct(m,`case`)):void 0,total:p.length,items:p.map(e=>({key:e.id,label:e.name,sub:Ct(e.cases,`case`),href:`#/library/datasets`,onPick:()=>o(e.id)}))}),(0,Z.jsx)(wo,{id:`prompts`,to:`library/prompts`,branch:!0,icon:xo(`prompts`).icon,name:xo(`prompts`).label,fact:a.list?_(Ct(a.list.length,`prompt`)):void 0,total:a.list?.length??0,items:(a.list??[]).map(e=>({key:e.id,label:e.name||e.text.split(`
8
- `)[0]||`Untitled`,sub:e.default?`Default`:void 0,href:`#/library/prompts`}))}),(0,Z.jsx)(wo,{id:`sources`,to:`library/sources`,branch:!0,icon:xo(`sources`).icon,name:xo(`sources`).label,fact:c?_(Ct(c.length,`source`)):void 0,total:c?.length??0,items:(c??[]).map(e=>({key:e.id,label:e.name,sub:Ct(e.files,`file`),href:`#/library/sources/${encodeURIComponent(e.id)}`}))})]})]}),(0,Z.jsx)(wo,{id:`setup`,icon:bo(`setup`).icon,name:bo(`setup`).label,start:g===`setup`,fact:_(Ct(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 `,_o]})]})}function wo({id:e,icon:t,name:n,to:r,fact:i,items:a,total:o=a.length,hub:s,start:c,branch:l}){let u=o-Math.min(a.length,vo);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`}),i&&(0,Z.jsx)(`span`,{className:`home-fact`,children:i}),a.length>0&&(0,Z.jsxs)(`ul`,{className:`home-items`,children:[a.slice(0,vo).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)),u>0&&(0,Z.jsx)(`li`,{children:(0,Z.jsxs)(`a`,{className:`home-more`,href:`#/${r??e}`,children:[u,` more`]})})]})]})}function To({list:t,at:n,canRestore:a,onSelect:o,onNew:s,onClone:c,onRename:l,onDelete:u,onRestore:d,onExport:f,onImport:p}){let[m,h]=(0,J.useState)(!1),g=t.find(e=>e.id===n),_=`Pipeline - ${g?.name?.trim()||`Untitled`}`;return(0,Z.jsxs)(A,{id:`pipelines`,title:_,actions:[{label:`Rename`,icon:i,onSelect:()=>h(!0)},{label:`Clone`,icon:N,onSelect:c},{label:`Export YAML`,icon:e,onSelect:f},{label:`Import YAML…`,icon:K,onSelect:p},{label:`Restore…`,icon:r,disabled:!a,onSelect:d},{label:`Delete`,icon:G,destructive:!0,onSelect:u}],children:[(0,Z.jsxs)(`div`,{className:`prop`,children:[(0,Z.jsx)(`span`,{className:`prop-name`,children:`Pipeline`}),(0,Z.jsx)(`span`,{className:`prop-value`,children:(0,Z.jsx)(`select`,{"aria-label":`Pipeline`,value:n,onChange:e=>o(e.target.value),children:t.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.name||`Untitled`},e.id))})})]}),(0,Z.jsxs)(`button`,{type:`button`,className:`ghost add-btn`,onClick:s,children:[(0,Z.jsx)(W,{size:14,"aria-hidden":`true`}),`New pipeline`]}),m&&(0,Z.jsx)(B,{title:`Rename pipeline`,value:g?.name??``,onCommit:l,onClose:()=>h(!1)})]})}function Eo({problems:e,error:t,run:n,submitting:r,onRun:i,onStop:a,onOpen:o}){let s=!!n&&!Bt(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:Ot(n.status)}),Do(n)&&(0,Z.jsx)(`span`,{className:`runbar-detail`,children:Do(n)})]}),f=s?d:e.length?(0,Z.jsxs)(`span`,{className:`runbar-why`,children:[Ao(e[0]),ko(e[0])]}):t?(0,Z.jsx)(`span`,{className:`runbar-why bad`,children:Ao(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,onClick:i,children:[(0,Z.jsx)(Wn,{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)(Cn,{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 Do(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 Oo=[[/^Target profile .* not found$/,`#/setup`,`Open Setup`],[/^Source .* not found$/,`#/library/sources`,`Open Sources`],[/^Dataset .* not found$/,`#/library/datasets`,`Open Datasets`]];function ko(e){let t=Oo.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 Ao=e=>{let t=e.trim();if(!t)return t;let n=t[0].toUpperCase()+t.slice(1);return/[.!?]$/.test(n)?n:`${n}.`},jo=10;function Mo({onPick:e,onClose:t,used:n}){let{list:r,error:i}=Ue(),[a,o]=(0,J.useState)(``),[s,c]=(0,J.useState)(`all`),[l,u]=(0,J.useState)(0),d=r??[],f=d.filter(e=>si(e,a,s,n??{byScenario:new Set,byAll:new Set})).sort((e,t)=>Number(t.default)-Number(e.default)),p=Math.ceil(f.length/jo),m=Math.min(l,Math.max(0,p-1)),h=f.slice(m*jo,(m+1)*jo);return(0,Z.jsxs)(L,{title:`Select prompt`,onClose:t,className:`sp`,initialFocus:`.sp input[type=search]`,children:[(0,Z.jsx)(I,{noun:`prompts`,search:{label:`Search prompts`,placeholder:`Search prompts`,value:a,onChange:e=>{o(e),u(0)}},filters:[{key:`show`,label:`Show`,value:s,onChange:e=>{c(e),u(0)},options:ai}],count:{shown:f.length,total:d.length}}),r===null?(0,Z.jsx)(`p`,{className:`note${i?` bad`:``}`,role:i?`alert`:void 0,children:i??`Loading…`}):d.length===0?(0,Z.jsx)(`p`,{className:`note`,children:`No prompts yet.`}):f.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:h.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:Fe(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 `,ci(t.lastUsed)]}),(0,Z.jsxs)(`span`,{children:[`v`,t.version]})]})]})},t.id))}),p>1&&(0,Z.jsxs)(`div`,{className:`sp-pager`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,disabled:m===0,onClick:()=>u(m-1),children:`Back`}),(0,Z.jsxs)(`span`,{className:`sp-page`,children:[m+1,` of `,p]}),(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,disabled:m>=p-1,onClick:()=>u(m+1),children:`Forward`})]})]})]})}function No(e){let t=q(),n=e.jobs.at(-1),r=b(t.defaultKind()),i=t.outOf(n),a=t.outOf(r),o=e=>!y(e.type)||y(e.type).includes(a.kind),s=i.modifiers.filter(o);return s.length&&(r=t.withOut(r,{...a,modifiers:s})),us(e,[...e.jobs.slice(0,-1),t.withOut(n,{...i,modifiers:i.modifiers.filter(e=>!o(e))}),r],()=>({type:`prompt`,prompt:``}))}function Po(e,n){if(e.jobs.length<2)return e;let r=e.jobs.slice();if(n===r.length-1){let e=q(),i=e.outOf(r[n]),a=e.outOf(r[n-1]),o=i.modifiers.filter(e=>!y(e.type)||y(e.type).includes(a.kind)),s=[...a.modifiers,...o];r[n-1]=e.withOut(r[n-1],{...a,modifiers:s.length?s:t(a.kind)})}return r.splice(n,1),{...e,jobs:r,targets:e.targets.map(e=>({...e,steps:e.steps.filter((e,t)=>t!==n)}))}}function Fo(e,t){let n={...structuredClone(e.jobs[t]),id:q().newId()};n.name=`${q().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 Io(e,t,n){let r=e.jobs.map((e,r)=>r===t?{...e,name:n.trim()}:e);return{...e,jobs:r}}function Lo(e,n,r){let i=q().outOf(e.jobs[n]);if(i.kind===r||!r)return e;let a=n===e.jobs.length-1,o=i.modifiers.filter(e=>!y(e.type)||y(e.type).includes(r));return{...e,jobs:e.jobs.map((e,i)=>i===n?q().withOut(e,{kind:r,...s(r),modifiers:a?o.length?o:t(r):[]}):e)}}var Ro=(e,t)=>({...e,tests:[...e.tests,t]}),zo=(e,t)=>({...e,tests:e.tests.filter((e,n)=>n!==t)});function Bo(e,t,n){let r=t+n;if(r<0||r>=e.tests.length)return e;let i=e.tests.slice();return[i[t],i[r]]=[i[r],i[t]],{...e,tests:i}}var Vo=(e,t,n)=>({...e,tests:e.tests.map((e,r)=>r===t?{...e,name:n.trim()}:e)}),Ho=(e,t,n)=>({...e,tests:e.tests.map((e,r)=>r===t?n:e)}),Uo=e=>e[0]?{id:e[0].id,name:e[0].name}:{id:``,name:``};function Wo(e,t,n=``){let r=q(),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 Go(e){let t=new Set(e.map(e=>e.trim().toLowerCase())),n=1;for(;t.has(`pipeline ${n}`);)n+=1;return`Pipeline ${n}`}var Ko={id:`samples`,name:`Sample library`};function qo(e,t,n=``){let r=q().withContent({...q().blankPipeline({name:`Evals`}),tests:t?[q().newTest(`metrics`,``,{dataset:{id:t.id,name:t.name},metrics:[{type:`case`}]})]:[]},{type:`source`,ref:{...Ko},first:null,loops:1});if(t){let e=q();r={...r,jobs:[e.withTokens(e.withOut(r.jobs[0],{kind:`list`,...s(`list`),modifiers:[{type:`tidy`},{type:`dedupe`}]}),e.mappingsFor(n))]}}return r=Wo(r,e,n),Wo(r,e,n)}function Jo(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 Yo(e,t){let n={...structuredClone(e.targets[t]),id:q().newId(),name:`${q().targetLabel(e,t)} copy`};return{...e,targets:[...e.targets.slice(0,t+1),n,...e.targets.slice(t+1)]}}function Xo(e,t){return{...e,targets:e.targets.filter((e,n)=>n!==t)}}function Zo(e,t,n){return{...e,targets:e.targets.map((e,r)=>r===t?{...e,name:n.trim()}:e)}}function Qo(e,t,n,r){return n===0?{...e,targets:e.targets.map((e,n)=>n===t?{...e,profile:r??e.profile}:e)}:q().withTarget(e,t,n,e=>{if(r)return{...e,profile:r};let{profile:t,...n}=e;return n})}function $o(e,t,n,r){return q().withTarget(e,t,n,{prompt:r})}function es(e,t,n,r,i){return q().withTarget(e,t,n,{prompt:r,from:{...i}})}function ts(e,t){return new Set(e.jobs.flatMap((n,r)=>q().targetStepOf(e,t,r)?.from?.id??[]))}function ns(e){let t=q().targetsOf(e).length,n=ts(e,0);for(let r=1;r<t;r++){let t=ts(e,r);for(let e of[...n])t.has(e)||n.delete(e)}return n}function rs(e,t,n,r){return ls(e,t,e=>e.map(e=>e.name===n?{...e,...r}:e))}function is(e,t,n,r){let i=n.trim();return i?ls(e,t,e=>e.some(e=>e.name===i)?e:[...e,q().tokenMapping(i,r)]):e}function as(e,t,n,r){let i=r.name.trim();return i?ls(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}:q().tokenMapping(i,r.type):e)):e}function os(e,t,n){return ls(e,t,e=>e.filter(e=>e.name!==n))}var ss=/^(?:text|reply|stage[1-9]\d*(?:\..*)?)$/;function cs(e,t,n,r){let i=n.trim();return i?/[{}\s]/.test(i)?`A name has no braces or spaces.`:ss.test(i)?`{${i}} is filled in by the lab.`:i!==r&&q().tokensOf(e.jobs[t]).some(e=>e.name===i)?`{${i}} is already mapped.`:null:`A mapping needs a name.`}function ls(e,t,n){let r=q();return{...e,jobs:e.jobs.map((e,i)=>i===t?r.withTokens(e,n(r.tokensOf(e))):e)}}function us(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 ds=(e,t)=>(q().targetsOf(e)[t]?.name||``).trim()||`Target ${t+1}`;function fs(e,t){let n=q().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 ps(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=q();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 ms(e,t,n,r,i){let a=Qo(e,t,n,r),o=q();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=fs(c.type,s);l!==c.type&&(a=o.withTarget(a,t,n,e=>ps(a,n,e,l)))}),a}var hs=(e,t,n)=>({...e,jobs:e.jobs.map((e,r)=>r===t?q().withImage(e,n):e)});function gs(e,t,n){let r=q();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 _s(e,t){let n=q(),r=n.defaultKind(),i=n.outOf(e.jobs[t]).modifiers.filter(e=>!y(e.type)||y(e.type).includes(r));return{...e,jobs:e.jobs.map((e,a)=>a===t?n.withOut(e,{kind:r,...s(r),modifiers:i}):e)}}function vs(e,t){let n=q().outOf(e.jobs[t]).modifiers.filter(e=>!y(e.type)||y(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 ys(e,t){let n=q().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 bs({k:e,pipeline:t,sources:n,edit:r,offer:i}){let[a,o]=(0,J.useState)(!1),[s,c]=(0,J.useState)(null),l=q(),d=t.jobs[e],f=e===0?l.contentOf(t):null,p=l.flowStepOf(d),m=l.sendsImage(d),h=l.tokensOf(d),g=l.CONTENT_TYPES,_=l.targetsOf(t).some((n,r)=>l.STEP_TYPES[l.targetStepOf(t,r,e)?.type??``]?.asks===`request`)||e===0&&!!g[f?.type??``]?.inline,v=[...e>0?[{kind:`reply`}]:[],...f?[{kind:`attach`}]:[],...p?[{kind:`flow`}]:[],...m?[{kind:`image`}]:[],...h.map(e=>({kind:`mapping`,name:e.name}))],y=(e,n)=>{let a=t;r(n),i({label:e,restore:()=>r(a)})},b=(e,n)=>r(hs(l.withContent(t,e),0,n)),x=[...e===0&&!f?[{label:`Source…`,icon:U.add,onSelect:()=>o(!0)},{label:g.text?.label??`Text`,icon:U.add,onSelect:()=>b({type:`text`,text:``},!1)},{label:g.prompt?.label??`Prompt only`,icon:U.add,onSelect:()=>b({type:`prompt`},!1)}]:[],...!m&&!_?[{label:l.STEP_TYPES.attachImage?.label??`Image`,icon:U.add,onSelect:()=>r(hs(t,e,!0))}]:[],{label:`Token mapping`,icon:U.add,onSelect:()=>c({mode:`add`})}],S=n=>{n.kind===`attach`?y(`Removed the content`,l.withContent(t,null)):n.kind===`image`?y(`Stopped sending the image`,hs(t,e,!1)):n.kind===`mapping`&&y(`Removed {${n.name}}`,os(t,e,n.name))},C=s?.mode===`edit`?h.find(e=>e.name===s.name):void 0,w=n=>{let a=t;s?.mode===`add`?r(is(a,e,n.name,n.type)):C&&(r(as(a,e,C.name,n)),n.type!==C.type&&C.value&&i({label:`Changed {${C.name}} to ${l.TOKEN_TYPES[n.type]?.label.toLowerCase()??n.type}`,restore:()=>r(a)})),c(null)},T=(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 ${u(l.outOf(t.jobs[e-1]).kind)}`}}];case`attach`:return[f?.type===`text`?{key:`attach`,label:l.STEP_TYPES.attachContent?.label??`Attach Content`,required:!0,actions:a,control:{type:`textarea`,value:f.text,placeholder:`The item every target is sent`,onChange:e=>r(l.withContent(t,{...f,text:e}))}}:{key:`attach`,label:l.STEP_TYPES.attachContent?.label??`Attach Content`,required:!0,actions:a,hint:g[f?.type??``]?.description,control:{type:`static`,text:Cs(f,n)}}];case`flow`:return[{key:`flow`,label:l.STEP_TYPES.flowStep?.label??`Flow step`,required:!0,actions:a,control:{type:`static`,text:p?.step??``}},{key:`api`,label:`API`,required:!0,control:{type:`select`,value:p?.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=h.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(rs(t,e,n.name,{value:i}))}:{type:`static`,text:o?.label??n.type},...s.includes(`enabled`)?{enabled:{checked:!!n.enabled,onChange:i=>r(rs(t,e,n.name,{enabled:i}))}}:{},actions:[{label:`Edit`,icon:U.edit,onSelect:()=>c({mode:`edit`,name:n.name})},...a]}]}}},E=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`,D=v.map(r=>xs[r.kind](t,e,n)).join(`, `)||`none`;return(0,Z.jsxs)(A,{id:`job-${e}-content`,title:`Content`,level:3,note:D,children:[(0,Z.jsx)(j,{noun:`content`,items:v,onAdd:x,onRemove:e=>S(v[e]),locked:e=>e.kind===`reply`||e.kind===`flow`,extra:e=>e.kind===`attach`?[{label:`Change content`,icon:U.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)(k,{label:E(t),rows:T(t,r)})},t.kind===`mapping`?`m-${t.name}`:t.kind)}),s&&(s.mode===`add`||C)&&(0,Z.jsx)(V,{title:C?l.TOKEN_TYPES[C.type]?.notation(C.name)??`{${C.name}}`:`New mapping`,initial:C?{name:C.name,type:C.type}:{name:``,type:`value`},problem:n=>cs(t,e,n,C?.name),onSave:w,onClose:()=>c(null)},s.mode===`edit`?s.name:`add`),a&&(0,Z.jsxs)(L,{title:f?`Change content`:`Add content`,onClose:()=>o(!1),children:[(0,Z.jsx)(Qa,{mode:`pick`,onPick:e=>{b({type:`source`,ref:R(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:g.text?.label??`Text`}),g.text?.description&&(0,Z.jsx)(`span`,{className:`pick-about`,children:g.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:g.prompt?.label??`Prompt only`}),g.prompt?.description&&(0,Z.jsx)(`span`,{className:`pick-about`,children:g.prompt.description})]})]})]})]})}var xs={reply:(e,t)=>`${q().jobLabel(e,t-1)} · ${u(q().outOf(e.jobs[t-1]).kind)}`,attach:(e,t,n)=>Cs(q().contentOf(e),n),flow:(e,t)=>q().flowStepOf(e.jobs[t])?.step??``,image:()=>`image`,mapping:()=>`token mapping`},Ss=(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}`},Cs=(e,t)=>e?e.type===`source`?Ss(e,t):q().CONTENT_TYPES[e.type]?.label??e.type:`none`;async function ws(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 Ts={prompt:{actions:Os,summary:Ds},echo:{actions:Os,summary:()=>`Each item`},httpRequest:{summary:e=>`${e.method} ${e.path}`,promptLabel:e=>ks(e)?.fields.length?`Prompt`:`Body`,rows:js,actions:Ps}},Es=e=>Ts[e??``]??Ts.prompt;function Ds(e){return e.from?.name||e.prompt.split(`
9
- `).find(e=>e.trim())?.trim()||`No prompt`}function Os({pipeline:e,i:t,k:n,onSelectPrompt:r,onClearPrompt:i,defaultPrompt:a,onRevert:o}){let s=q().targetStepOf(e,t,n)?.prompt??``;return[{label:`Select prompt…`,icon:Ln,onSelect:r},{label:`Clear prompt`,icon:U.clear,disabled:!s,onSelect:i},...o&&a!=null?[{label:`Revert to default`,icon:U.revert,disabled:s===a,onSelect:o}]:[]]}var ks=e=>q().HTTP_APIS[e?.api??``],As=e=>{let t=Object.entries(e??{}).map(([e,t])=>`${e}=${t}`).join(`&`);return t?`?${t}`:``};function js(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(q().HTTP_APIS).map(([e,t])=>({value:e,label:t.label}))}:{type:`static`,text:ks(e)?.label??n.api}},{key:`request`,label:`Request`,control:{type:`code`,text:`${n.method} ${n.path}${As(n.query)}`}},{key:`body`,label:`Template`,control:{type:`code`,text:JSON.stringify(n.body,null,2)}}],i=ks(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 Ms(e){return JSON.stringify((ks(e)??q().HTTP_APIS.raw).place(e.body,e),null,2)}function Ns(e,t,n){let r=q().targetStepOf(e,t,n);if(!r)return``;let i=ks(r),a=e.jobs[n],o=q().flowStepOf(a),s=q().readAsOf(a),c=q().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 "${ds(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",Ms(r),"```"),f.join(`
10
- `)}function Ps({pipeline:e,i:t,k:n,say:r}){let i=q().targetStepOf(e,t,n);if(!i)return[];let a=async(e,t)=>r(await ws(e)?`Copied ${t}.`:`Could not copy.`);return[{label:`Copy`,icon:N,onSelect:()=>void a(Ms(i),`the body`)},{label:`Copy as AI prompt`,icon:Jn,onSelect:()=>void a(Ns(e,t,n),`the AI prompt`)}]}function Fs({label:e,profile:t,prompt:n,onPrompt:r,rows:i=[],promptLabel:a=`Prompt`}){return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(k,{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 Is({run:e,i:t,onClose:n}){let r=q(),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)(O,{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)(Fs,{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:Es(t.type).rows?.(t)??[],promptLabel:Es(t.type).promptLabel?.(t)??`Prompt`})})),closeLabel:`Close`,onClose:n})}function Ls({index:e}){return(0,Z.jsx)(`span`,{className:`target-badge`,"aria-hidden":`true`,children:String.fromCharCode(65+e)})}function Rs({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 _=q(),v=_.targetsOf(t),y=v.length;return(0,Z.jsx)(A,{id:`job-${e}-targets`,title:`Targets`,level:3,note:`${y} ${y===1?`target`:`targets`}`,children:(0,Z.jsx)(j,{noun:`target`,items:v,min:1,max:r,onAdd:a,onClone:o,onRemove:s,onRename:i,extra:(n,r)=>Es(_.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=ds(t,i),s=_.targetStepOf(t,i,e)??{type:`prompt`,prompt:``},f=Es(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)(Ls,{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)(w,{actions:a,label:`${o} actions`})]}),!m&&(0,Z.jsx)(Fs,{label:o,profile:e===0?{type:`select`,value:Bs(s)?zs:r.profile?.id??``,options:[...Vs(),...Hs(n,r.profile)],onChange:e=>e===zs?l(i):c(i,Us(n,e))}:{type:`select`,value:s.profile?.id??``,options:[{value:``,label:`Same as ${_.jobLabel(t,0)}`},...Hs(n,s.profile)],onChange:e=>c(i,e?Us(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 zs=`#echo`,Bs=e=>!!q().STEP_TYPES[e.type]?.local,Vs=()=>Object.entries(q().STEP_TYPES).filter(([,e])=>e.slot===`target`&&e.local).map(([,e])=>({value:zs,label:e.label??`Echo`})),Hs=(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}))],Us=(e,t)=>{let n=e.find(e=>e.id===t);return n?{id:n.id,name:n.name}:null};function Ws({pipeline:e,profiles:t,sources:n,targetCap:r,prompt:i=``,defaultPrompt:a,protectedTerms:s,edit:l,offer:u}){let[d,f]=(0,J.useState)(null),[p,m]=(0,J.useState)(null),[h,g]=(0,J.useState)(null),_=(t,n)=>{let r=e;l(n),u({label:t,restore:()=>l(r)})},v=e=>{let n=t.find(t=>t.id===e);return n?q().CONNECTION_TYPES[q().typeOf(n)]?.answers??[`prompt`]:void 0},y=!q().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)(j,{noun:`job`,items:e.jobs,min:1,addDisabled:y,onAdd:()=>l(No(e)),onClone:t=>l(Fo(e,t)),onRemove:t=>_(`Removed ${q().jobLabel(e,t)}`,Po(e,t)),onRename:e=>f({job:e}),renderItem:(d,p,h)=>{let y=`Job ${p+1}${d.name?.trim()?` - ${d.name.trim()}`:``}`,b=q().flowStepOf(d)?q().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)(c,{size:16}),(0,Z.jsx)(`span`,{children:`Reply`})]}),(0,Z.jsx)(A,{id:`job-${p}`,title:y,level:2,actions:h,note:Gs(e,p),children:(0,Z.jsxs)(`div`,{className:`stages`,children:[(0,Z.jsx)(bs,{k:p,pipeline:e,sources:n,edit:l,offer:u}),(0,Z.jsx)(Rs,{k:p,pipeline:e,profiles:t,targetCap:r,onRequestRename:e=>f({job:p,scenario:e}),onAdd:()=>l(Wo(e,Uo(t),i)),onClone:t=>l(Yo(e,t)),onRemove:t=>_(`Removed ${ds(e,t)}`,Xo(e,t)),onProfile:(t,n)=>l(ms(e,t,p,n,v)),onEcho:t=>l(ys(e,t)),onPrompt:(t,n)=>l($o(e,t,p,n)),onStep:(t,n)=>l(Ks(e,t,p,n)),say:g,onSelectPrompt:e=>m({i:e,k:p}),onClearPrompt:t=>_(`Cleared ${ds(e,t)}'s prompt`,$o(e,t,p,``)),...p===0&&a?{defaultPrompt:a.text,onRevert:t=>_(`Reverted ${ds(e,t)} to the default`,es(e,t,0,a.text,{id:a.id,name:Fe(a)}))}:{}}),(0,Z.jsx)(z,{id:`job-${p}-responses`,out:q().outOf(d),format:!!q().replyOf(d),readAs:b,outputKinds:o(),modifiers:x(),onKind:t=>l(Lo(e,p,t)),onSetting:(t,n)=>l(qs(e,p,e=>({...e,[t]:n}))),onAddFormat:()=>l(_s(e,p)),onRemoveFormat:()=>_(`Removed the format validation`,vs(e,p)),onReadAs:t=>t==null?_(`Removed Read as`,gs(e,p,null)):l(gs(e,p,t)),...s?{protectedTerms:s}:{},offer:u,onModifier:(t,n)=>l(Js(e,p,t,n)),onAddModifier:t=>l(qs(e,p,e=>({...e,modifiers:[...e.modifiers,t]}))),onRemoveModifier:t=>_(`Removed a modifier`,qs(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)(B,{title:`Rename ${ds(e,d.scenario)}`,value:q().targetsOf(e)[d.scenario]?.name??``,onCommit:t=>l(Zo(e,d.scenario,t)),onClose:()=>f(null)}):d?(0,Z.jsx)(B,{title:`Rename ${q().jobLabel(e,d.job)}`,value:e.jobs[d.job]?.name??``,onCommit:t=>l(Io(e,d.job,t)),onClose:()=>f(null)}):null,p&&(0,Z.jsx)(Mo,{onClose:()=>m(null),used:{byScenario:ts(e,p.i),byAll:ns(e)},onPick:t=>{let n=e;l(es(n,p.i,p.k,t.text,{id:t.id,name:Fe(t)})),m(null),u({label:`Picked ${Fe(t)}`,restore:()=>l(n)})}})]})}function Gs(e,t){let n=q(),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 Ks=(e,t,n,r)=>q().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}),qs=(e,t,n)=>({...e,jobs:e.jobs.map((e,r)=>r===t?q().withOut(e,n(q().outOf(e))):e)}),Js=(e,t,n,r)=>qs(e,t,e=>({...e,modifiers:e.modifiers.map((e,t)=>t===n?r:e)})),Ys={metrics:{Editor:e=>(0,Z.jsx)(ec,{...e}),actions:(e,t,n)=>`dataset`in e&&e.dataset&&n.length?[{label:`Edit`,icon:U.edit,onSelect:()=>t(n[0].filename)}]:[]}};function Xs({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.tests,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)(A,{id:`tests`,title:`Tests`,level:2,note:p.length?String(p.length):`None`,children:[(0,Z.jsx)(j,{noun:`test`,items:p,empty:(0,Z.jsx)(`p`,{className:`note`,children:`No tests — the run is unscored.`}),onAdd:()=>u(!0),onRename:e=>f(e),onRemove:t=>h(zo(e,t),`Removed ${q().testLabel(e,t)}`),extra:(t,r)=>[...Ys[t.type]?.actions?.(t,a,n)??[],...q().TEST_TYPES[t.type]?.toMetrics?[{label:`Convert to Metrics`,icon:U.edit,onSelect:()=>h(Ho(e,r,q().TEST_TYPES[t.type].toMetrics(t)),`Converted ${q().testLabel(e,r)} to Metrics`)}]:[],{label:`Move up`,icon:U.moveUp,disabled:r===0,onSelect:()=>h(Bo(e,r,-1),`Moved ${q().testLabel(e,r)} up`)},{label:`Move down`,icon:U.moveDown,disabled:r===p.length-1,onSelect:()=>h(Bo(e,r,1),`Moved ${q().testLabel(e,r)} down`)}],renderItem:(n,i,a)=>{let l=q().testLabel(e,i),u=t=>r(Ho(e,i,t));return(0,Z.jsxs)(A,{id:`test-${i}`,title:l,level:3,note:q().TEST_TYPES[n.type]?.label??n.type,about:q().TEST_TYPES[n.type]?.description,actions:a,...d===i?{rename:{value:n.name||l,onCommit:t=>{r(Vo(e,i,t)),f(null)},onCancel:()=>f(null)}}:{},children:[(()=>{let r=Ys[n.type]?.Editor;return r?(0,Z.jsx)(r,{test:n,label:l,set:u,datasets:t,profiles:s,labGrader:c,undoable:(t,n)=>h(Ho(e,i,t),n)}):null})(),(0,Z.jsx)(k,{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)($s,{pipeline:e,datasets:t,onClose:()=>u(!1),onAdd:t=>{r(Ro(e,t)),u(!1)}})]})}function Zs(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 Qs(e,t){let n=q().outOf(e.jobs.at(-1)).kind;return Object.entries(q().TEST_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 $s({pipeline:e,datasets:t,onAdd:n,onClose:r}){let i=Qs(e,t),[a,o]=(0,J.useState)(i[0]?.id??``),[s,c]=(0,J.useState)(``),l=q().testsDataset(e),[u,d]=(0,J.useState)(l??null),f=i.find(e=>e.id===a),p=[{key:`type`,label:`Type`,hint:q().TEST_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:`Test ${e.tests.length+1}`,onChange:c}},...f?.dataset&&t.length?[Zs(u,t,d,!0)]:[]];return(0,Z.jsx)(O,{title:`Add test`,...i.length?{}:{status:`No test type reads what the last job answers with.`,statusBad:!0},sections:[{key:`test`,rows:p}],focusRow:`type`,closeLabel:`Cancel`,actions:[{label:`Add`,icon:U.add,disabled:!f,onSelect:()=>f&&n(q().newTest(f.id,s.trim(),f.dataset&&u?{dataset:{id:u.id,name:u.name},metrics:[{type:`case`}]}:{}))}],onClose:r})}function ec({test:e,label:t,set:n,undoable:r,profiles:i,datasets:a,labGrader:o}){let s=q(),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)(k,{label:t,rows:u}),(0,Z.jsx)(Or,{label:t,metrics:e.metrics,over:e.over??`item`,set:t=>n({...e,metrics:t}),undoable:(t,n)=>r({...e,metrics:t},n)})]})}function tc({pipeline:e,sourceFiles:t,graded:n,sources:r,openCaseEditor:i}){let a=Y(),o=me(),[s]=he(`promptlab.mappings`),[c,l]=(0,J.useState)({graded:!1,todo:!0,missing:!0}),[u,d]=(0,J.useState)(!1),[f,p]=(0,J.useState)(null),[m,h]=(0,J.useState)(null),g=q().testsDataset(e)?.id??null,_=(0,J.useMemo)(()=>g?Sr(o,g):null,[o,g,s]);if(g===null)return null;let v=t??[],y=new Set(n.map(e=>e.filename)),b=new Set(v),x=[{key:`graded`,label:`Graded`,tone:`ok`,files:v.filter(e=>y.has(e))},{key:`todo`,label:`Todo`,tone:`todo`,files:v.filter(e=>!y.has(e))},{key:`missing`,label:`Missing`,tone:`missing`,files:n.filter(e=>!b.has(e.filename)).map(e=>e.filename)}],S=x[0].files.length,C=x[1].files.length+x[2].files.length,w=x.filter(e=>c[e.key]).flatMap(e=>e.files.map(t=>({file:t,tone:e.tone}))),T=async e=>{if(g){d(!1),h(null),p({done:0,total:n.length,source:e.name});try{await xr(a,o,g,e,n.map(e=>e.filename),(t,n)=>p({done:t,total:n,source:e.name}))}catch(e){h(e instanceof Error?e.message:String(e))}finally{p(null)}}},E=_?.recents[0]??null,D=_?n.map(e=>Cr(_,e.filename)).filter(e=>e!==null):[],O=D.filter(e=>e.file!==null).length,k=[{label:`Map against Source…`,icon:Zn,disabled:!!f||!r.length||!n.length,onSelect:()=>d(!0)}];return(0,Z.jsxs)(A,{id:`mapping`,title:`Mapping`,level:3,note:j(),actions:k,about:`Which of the content's files the dataset has a case for, and so which are graded.`,children:[f&&(0,Z.jsxs)(`p`,{className:`note`,role:`status`,children:[`Mapping against `,f.source,`… `,f.done,` of `,f.total]}),m&&(0,Z.jsx)(`p`,{className:`note fault`,role:`alert`,children:m}),E&&!f&&(0,Z.jsxs)(`p`,{className:`note mapped-line`,children:[`Mapped against `,E.name,`, `,Er(E.at),`: `,O,` matched, `,D.length-O,` with no match.`]}),v.length?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`p`,{className:`note`,children:[n.length,` expectations · `,S,` of `,v.length,` content files matched.`]}),(0,Z.jsx)(`div`,{className:`mkey`,children:x.filter(e=>e.files.length).map(e=>(0,Z.jsxs)(`button`,{type:`button`,className:`ghost chip-key${c[e.key]?` on`:``}`,"aria-pressed":c[e.key],onClick:()=>l({...c,[e.key]:!c[e.key]}),children:[e.label,` `,e.files.length]},e.key))}),w.length?(0,Z.jsx)(`div`,{className:`mchips`,children:w.map(({file:e,tone:t})=>{let n=_?Cr(_,e):null,r=!!n?.file;return(0,Z.jsxs)(`button`,{type:`button`,className:`mchip ${t}${r?` linked`:``}`,...r?{title:`Mapped to ${n.file} in ${n.source.name}`}:{},onClick:()=>i(e),children:[r&&(0,Z.jsx)(Rn,{size:12,"aria-label":`Mapped`}),e]},`${t}-${e}`)})}):(0,Z.jsx)(`p`,{className:`note`,children:C?`Nothing shown.`:`Every content file is graded.`})]}):(0,Z.jsx)(`p`,{className:`note`,children:`No files in the content to map against.`}),u&&g&&(0,Z.jsx)(Gr,{sources:r,recents:_?.recents??[],onPick:e=>void T(e),onClose:()=>d(!1)})]});function j(){let r=q().contentOf(e),i=r?q().CONTENT_TYPES[r.type]:void 0;if(i?.inline)return i.label;let a=t??[],o=new Set(n.map(e=>e.filename)),s=a.filter(e=>o.has(e)).length;return`${n.length} expectations · ${s} of ${a.length} matched`}}function nc({pipeline:e,edit:t,comment:n,setComment:r,onClear:i,onCopyFailures:a}){let o=[{label:`Clear comment`,icon:P,destructive:!0,onSelect:i},{label:`Copy last run's failures`,icon:N,onSelect:a}],s=q().contentOf(e),c=s?.type===`source`?[{key:`first`,label:`Run first`,control:{type:`text`,value:s.first==null?``:String(s.first),placeholder:`all`,onChange:n=>t(q().withContent(e,{...s,first:n.trim()?rc(n):null}))}},{key:`loops`,label:`Loop`,control:{type:`text`,value:String(s.loops),placeholder:`1`,onChange:n=>t(q().withContent(e,{...s,loops:Math.max(1,rc(n)??1)}))}}]:[];return(0,Z.jsx)(A,{id:`control`,title:`Run settings`,level:2,actions:o,children:(0,Z.jsx)(k,{label:`Run settings`,rows:[...c,{key:`comment`,label:`Comment`,control:{type:`text`,value:n,placeholder:`A note to find this run by in History`,onChange:e=>r(e)}}]})})}var rc=e=>{let t=Number.parseInt(e,10);return Number.isNaN(t)?null:t};function ic(){let e=me(),t=Y(),n=ee(),{openRun:r}=st(),{openCaseEditor:i}=Wr(),[a,o]=he(`promptlab.workflows`),[s]=he(`promptlab.profiles`),[c,l]=he(`promptlab.comment`),[u]=he(`promptlab.versions`),[d,f]=(0,J.useState)([]),{list:p,error:m}=Ne(),{list:h,error:g}=Ue(),_=h?.find(e=>e.default)??null,v=Me(),y=(0,J.useMemo)(()=>(p??[]).map(e=>R(e.id,e.name)),[p]),[b,x]=(0,J.useState)(4),[S,C]=(0,J.useState)(void 0),[w,E]=(0,J.useState)(null),[D,O]=(0,J.useState)(!1),[k,A]=(0,J.useState)(!1),[j,M]=(0,J.useState)(null),N=(0,J.useRef)(null),[P,F]=(0,J.useState)(null),I=(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&&x(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;!N.current&&n&&!Bt(n.status)&&(N.current=n.id),n&&n.id===N.current&&(M(n),Bt(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===10),[a.list]),B=z.find(e=>e.id===a.at)??z[0],V=B?.work,H=B?.id??``,U=V?q().testsDataset(V)?.id??null:null,W=Pe(U),G=W?.doc?.body.cases,K=(0,J.useMemo)(()=>(G??[]).map(e=>({id:e.id??``,filename:q().caseFile(e)})),[G]),te=W?.doc?.body.cases,ne=(0,J.useMemo)(()=>[...new Set((te??[]).flatMap(e=>[...e.expect??[],...(e.anyOf??[]).flat()]))],[te]),re=_?.text||V&&q().targetStepOf(V,q().targetsOf(V).length-1,0)?.prompt||``,ie=(0,J.useRef)(s.list);ie.current=s.list;let ae=z.length?null:p?.[0]??null,oe=p!==null||m!==null,se=h!==null||g!==null,ce=_?.text??``;(0,J.useEffect)(()=>{if(z.length||!oe||!se)return;let e=oc(ie.current,ae?{id:ae.id,name:ae.name}:void 0,ce);o({list:[e],at:e.id})},[z.length,o,oe,se,ae,ce]);let le=()=>{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 ue=(0,J.useRef)(B);ue.current=B;let de=(0,J.useRef)(V);de.current=V;let fe=(0,J.useRef)(null),pe=(0,J.useRef)(null),ge=(0,J.useCallback)(()=>{pe.current&&clearTimeout(pe.current);let t=ue.current?.id,n=de.current;t&&n&&(fe.current={id:t,doc:n},pe.current=setTimeout(()=>{let t=fe.current;t&&De(e,`pipeline`,t.id,t.doc,`idle`)},Ce))},[e]);(0,J.useEffect)(()=>()=>{pe.current&&clearTimeout(pe.current)},[]);let _e=(0,J.useCallback)(e=>{let t=X.current,n=ue.current.id,r={...t,at:n,list:t.list.filter(e=>e.work?.version===10).map(t=>t.id===n?{...t,work:e}:t)};X.current=r,o(r),ge(),E(null)},[o,ge]),ve=s.list[0]?.id??``;(0,J.useEffect)(()=>{let e=de.current,t=ue.current?.id;if(!e||!t||!ve)return;let n=Jo(e,Uo(ie.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)},[ve,H,o]),(0,J.useEffect)(()=>{let t=fe.current;t&&t.id!==H&&(De(e,`pipeline`,t.id,t.doc,`idle`),fe.current=null,pe.current&&=(clearTimeout(pe.current),null))},[H,e]);let ye=V?q().contentOf(V):null,be=ye?.type===`source`?ye.ref.id:null;(0,J.useEffect)(()=>{if(be===null){C(void 0);return}let e=!0;return t.source(be).then(t=>{e&&C(t.files.map(e=>e.name))}).catch(()=>{}),()=>{e=!1}},[be,t]);let xe=(0,J.useCallback)(e=>{let t=d.find(t=>t.id===e);return t?{name:t.name,type:t.type,files:e===be&&S?S:[]}:null},[d,be,S]),Se=(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&&q().targetsOf(V).length)return[`add a Target profile first`];let e={profiles:e=>s.list.find(t=>t.id===e)??null,sources:xe,grader:Se,...p?{datasets:p}:{}};return q().validatePipeline(V,e)},[V,s.list,xe,p,Se]),Te=H?u.pipeline?.[H]??[]:[],Ee=(0,J.useCallback)(async()=>{let n=de.current,i=ue.current.id;De(e,`pipeline`,i,n,`run`);let a=q().resolvePipeline(n,{profiles:e=>s.list.find(t=>t.id===e)??null,grader:Se,...be!==null&&S!==void 0?{files:S}:{},comment:c?.text??``});O(!0),E(null);try{let e=await t.submit(a);N.current=e.run.id,M(e.run),r(e.run.id,{at:e.run.submittedAt,from:`runs`})}catch(e){E(e instanceof Error?e.message:String(e)),N.current=null,M(null)}finally{O(!1)}},[t,c,be,r,s.list,S,e,Se]),Oe=(0,J.useCallback)(async()=>{let e=N.current;if(e)try{M((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(q().failedScore))).map(e=>e.name??`an item`);n.length&&await navigator.clipboard?.writeText(n.join(`
11
- `))}catch{}},[t]),Ae=(0,J.useCallback)(async n=>{let r=de.current,i=ue.current.id;De(e,`pipeline`,i,r,`run`);let a=q().resolvePipeline(r,{profiles:e=>s.list.find(t=>t.id===e)??null,grader:Se,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]),je=(0,J.useCallback)(e=>{U&&i(e,{dataset:U,files:S??[],run:Ae})},[i,S,Ae,U]),Fe=(0,J.useCallback)(()=>{let e=c?.text??``;l({text:``}),n.offer({label:`Cleared the comment`,restore:()=>l({text:e})})},[c,l,n]),Ie=(0,J.useCallback)(()=>{let e=q().pipelineToYaml(de.current);nr(new Blob([e],{type:`text/yaml`}),tr(`pipeline`,de.current.name||`pipeline`,10,`yml`))},[]),Le=(0,J.useCallback)(async e=>{let n=await t.archivedRules().then(e=>e.rules,()=>({})),r=q().yamlToPipeline(e,{profiles:ie.current,profileType:e=>ie.current.find(t=>t.id===e)?.type,sources:d,datasets:y,rulesFor:e=>n[e]??null});if(`error`in r){F(r);return}let{doc:i,missing:a}=r,s={id:sc(),name:i.name||`Imported`,work:i},c={...X.current,at:s.id,list:[...z,s]};X.current=c,o(c),F({doc:i,missing:a})},[t,z,o,d,y]);if(!B||!V)return null;let Re=t=>{let n=ue.current.id;De(e,`pipeline`,n,de.current,`restore`),_e(t.doc),A(!1)};return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Eo,{problems:we,error:w,run:j,submitting:D,onRun:()=>void Ee(),onStop:()=>void Oe(),onOpen:()=>{j&&r(j.id,{at:j.submittedAt,from:`runs`})}}),(0,Z.jsxs)(`div`,{className:`runs`,children:[(0,Z.jsx)(To,{list:z,at:H,canRestore:Te.length>0,onSelect:e=>o({...X.current,at:e}),onNew:()=>{let e=ac(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:sc(),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=ue.current.id,i={...n,at:r,list:n.list.filter(e=>e.work?.version===10).map(e=>e.id===r?{...e,name:t,work:{...e.work,name:t}}:e)};X.current=i,o(i),ge()},onDelete:()=>{let e=X.current,t=z.filter(e=>e.id!==H),r=t.length?t:[oc(s.list,le(),ce)],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:()=>A(!0),onExport:Ie,onImport:()=>I.current?.click()}),(0,Z.jsx)(`input`,{ref:I,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(Le).catch(()=>F({error:`the file could not be read`}))}}),(0,Z.jsx)(nc,{pipeline:V,edit:_e,comment:c?.text??``,setComment:e=>l({text:e}),onClear:Fe,onCopyFailures:()=>void ke()}),(0,Z.jsx)(Ws,{pipeline:V,profiles:s.list,sources:d,targetCap:b,prompt:re,..._?{defaultPrompt:_}:{},protectedTerms:ne,edit:_e,offer:n.offer}),(0,Z.jsx)(Xs,{profiles:s.list,labGrader:Se,pipeline:V,datasets:y,graded:K,edit:_e,offer:n.offer,openCaseEditor:je,children:(0,Z.jsx)(tc,{pipeline:V,sourceFiles:S,graded:K,sources:d,openCaseEditor:je})}),(0,Z.jsx)(T,{undo:n.undo,onUndo:n.undoNow,onDismiss:n.dismiss}),k&&(0,Z.jsx)(L,{title:`Restore pipeline`,onClose:()=>A(!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:[lc(e.at),` · `,cc(e.reason)]}),(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>Re(e),children:`Restore`})]},`${e.at}-${t}`))]})}),P&&(`doc`in P?(0,Z.jsx)(L,{title:`Imported ${P.doc.name||`Untitled`}`,onClose:()=>F(null),children:P.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:P.missing.map(e=>(0,Z.jsx)(`li`,{children:e},e))})]}):(0,Z.jsx)(`p`,{className:`note`,children:`Ready to run.`})}):(0,Z.jsx)(L,{title:`Nothing imported`,onClose:()=>F(null),children:(0,Z.jsx)(`p`,{className:`note`,children:P.error})}))]})]})}var ac=e=>{let t=Go(e),n=q().blankPipeline({name:t});return{id:sc(),name:t,work:{...n,jobs:n.jobs.map(e=>({...e,steps:[]}))}}},oc=(e,t,n)=>({id:sc(),name:`Evals`,work:qo(Uo(e),t,n)}),sc=()=>`w${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`,cc=e=>e===`run`?`before a run`:e===`restore`?`before a restore`:e===`pack`?`before a pack update`:`after editing`,lc=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},uc=25,dc=[``,`queued`,`running`,`done`,`cancelled`,`failed`,`incomplete`,`interrupted`],fc=e=>e.numeric?`hnum`:void 0,pc=e=>[...new Map(e.map(e=>[e.submittedAt,e])).values()].sort((e,t)=>String(t.submittedAt).localeCompare(String(e.submittedAt)));function mc(){let t=Y(),n=ee(),{openRun:r}=st(),[i,a]=he(`promptlab.history.columns`),[o,s]=(0,J.useState)([]),[c,l]=(0,J.useState)(!1),[u,d]=(0,J.useState)(``),[p,m]=(0,J.useState)(new Set),[h,g]=(0,J.useState)(!1),[_,v]=(0,J.useState)(null),[y,b]=(0,J.useState)(null),[x,S]=(0,J.useState)(null),[C,w]=(0,J.useState)(null),[E,O]=(0,J.useState)(!1),k=(0,J.useRef)(o);k.current=o;let j=(0,J.useMemo)(()=>o.map(e=>Tt($t(e),e)),[o]),M=(0,J.useMemo)(()=>_c(i),[i]),N=(0,J.useCallback)(async e=>{try{return await t.queue(e?{limit:uc,before:e}:{limit:uc})}catch{return null}},[t]),F=(0,J.useCallback)(e=>{let t=new Set(e.runs.map(e=>e.submittedAt));s(n=>pc([...n.filter(e=>!t.has(e.submittedAt)),...e.runs])),l(e.more)},[]);(0,J.useEffect)(()=>{let e=!0,t,n=async()=>{let r=await N();e&&(r&&F(r),k.current.some(e=>[`queued`,`running`].includes(e.status))&&(t=setTimeout(()=>void n(),3e3)))};return n(),()=>{e=!1,t&&clearTimeout(t)}},[N,F]);let R=(0,J.useMemo)(()=>j.filter(e=>!u||(e.status||`done`)===u),[j,u]),z=(e=>({Runs:It.filter(t=>e.Runs.has(t.key)),"Run Scenarios":Lt.filter(t=>e[`Run Scenarios`].has(t.key))}))(M),B=(0,J.useCallback)(e=>{m(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),V=(0,J.useCallback)((e,t)=>{r(e,{at:t,from:`history`})},[r]),H=(0,J.useCallback)(async e=>{try{let n=await t.resume(e),r={runs:[n.run],more:k.current.length>uc};F(r),V(e,n.run.submittedAt)}catch{}},[t,F,V]),U=(0,J.useCallback)(async()=>{let e=k.current;try{await t.clear()}catch{w(`Not cleared: server unreachable.`);return}s([]),l(!1),n.offer({label:`Cleared ${Ct(e.length,`run`)}`,restore:()=>{for(let n of e)t.submit(q().upgradePipeline(n.snapshot)).catch(()=>{})}})},[t,n]),W=(0,J.useCallback)(async()=>{O(!0);let e=[...k.current],t=!1,n;for(let r=0;;r++){let i=await N(n);if(!i){t=!0;break}if(e=pc([...e,...i.runs]),n=i.runs.at(-1)?.submittedAt,!i.more||!n||r>100)break}if(O(!1),!e.length){w(`Nothing to export yet.`);return}nr(new Blob([JSON.stringify({exported:new Date().toISOString(),runs:e},null,2)],{type:`application/json`}),tr(`runs`,`all`,10,`json`)),w(t?`Exported ${Ct(e.length,`run`)}. Server unreachable, so only those this browser had.`:`Exported ${Ct(e.length,`run`)}.`)},[t,N]),G=[{label:`Select Columns`,icon:wn,onSelect:()=>g(!0)},{label:`Export JSON`,icon:e,onSelect:()=>void W()},{label:`Clear`,icon:P,destructive:!0,onSelect:()=>void U()}],K=(0,J.useCallback)(e=>{let t=e.target.closest(`[data-resume]`);if(t){e.stopPropagation(),H(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?R[Number(t.getAttribute(`data-run`))]:null;r?.run&&V(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?R[Number(t.getAttribute(`data-run`))]:null;n?.run&&b({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?R[Number(t.getAttribute(`data-run`))]:null,r=n?.run?k.current.find(e=>e.id===n.run):null;r?.snapshot&&S({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?R[Number(t.getAttribute(`data-run`))]:null,r=a.getAttribute(`data-prof`);if(n&&r!=null){let e=n.scenarios[Number(r)];v({name:e?.setupProfile?.name??``,settings:_t(n,e??{})})}}},[R,V,H]),te=(0,J.useCallback)((e,t)=>{s(n=>n.map(n=>n.id===e?{...n,snapshot:{...n.snapshot,comment:t}}:n)),b(null)},[]),ne=(e,t)=>e.image&&xt(t)!==!0?(0,Z.jsx)(`span`,{className:`note`,children:`—`}):e.get(t),re=(e,t,n,r)=>n?e.image&&xt(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)(A,{id:`history`,title:`History`,actions:G,children:[(j.length>0||u)&&(0,Z.jsx)(I,{noun:`runs`,lead:R.length>0&&(0,Z.jsx)(`p`,{className:`note hstatus`,role:`status`,children:Ct(R.length,`run`)}),filters:[{key:`show`,label:`Show`,value:u,onChange:d,options:dc.map(e=>({value:e,label:e?Ot(e):`All`}))}]}),C&&(0,Z.jsx)(`p`,{className:`note hstatus`,role:`status`,children:C}),R.length?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`scrollx`,onClick:K,children:(0,Z.jsx)(D,{className:`htable`,label:`Runs`,rows:R,rowKey:e=>e.at,rowProps:(e,t)=>({className:`runrow${p.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=p.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:()=>B(e.at),children:(0,Z.jsx)(f,{size:16,"aria-hidden":`true`})})}},...z.Runs.map(e=>({key:e.key,header:e.label,className:fc(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:ne(e,t)})}))],after:(e,t)=>p.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:z.Runs.length+1,children:(0,Z.jsx)(D,{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:z[`Run Scenarios`].map(t=>({key:t.key,header:t.label,className:fc(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:re(t,e,n,r)})}))})})})})}),c&&(0,Z.jsx)(`button`,{type:`button`,className:`ghost older-btn`,disabled:E,onClick:async()=>{O(!0);let e=await N(k.current.at(-1)?.submittedAt);if(O(!1),!e){w(`Server unreachable.`);return}F(e)},children:`Older`})]}):(0,Z.jsx)(`p`,{className:`note`,children:C??(j.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`})]}))})]}),(0,Z.jsx)(T,{undo:n.undo,onUndo:n.undoNow,onDismiss:n.dismiss}),h&&(0,Z.jsx)(yc,{cols:M,onSave:e=>{a(vc(e)),g(!1)},onClose:()=>g(!1)}),x&&(0,Z.jsx)(Is,{run:x.run,i:x.i,onClose:()=>S(null)}),_&&(0,Z.jsx)(L,{title:_.name||`Settings`,onClose:()=>v(null),children:(0,Z.jsx)(hc,{settings:_.settings})}),y&&(0,Z.jsx)(gc,{runId:y.id,comment:y.comment,onSaved:e=>te(y.id,e),onClose:()=>b(null)})]})}function hc({settings:e}){let t=ht.filter(t=>String(e[t]??``)!==``).map(t=>({key:t,label:vt(t),control:{type:`static`,text:yt(t,e[t])}}));return t.length?(0,Z.jsx)(k,{label:`Target profile`,rows:t}):(0,Z.jsx)(`p`,{className:`note`,children:`No settings recorded.`})}function gc({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)(O,{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:h,disabled: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 _c(e){let t=()=>({Runs:new Set(It.filter(e=>e.on).map(e=>e.key)),"Run Scenarios":new Set(Lt.filter(e=>e.on).map(e=>e.key))});if(!e)return t();let n=t();for(let t of zt){let r=t[0],i=e[r],a=new Set(t[1].map(e=>e.key)),o=new Set(i?.seen??[...a]),s=[...(i?.on??[]).filter(e=>a.has(e)),...t[1].filter(e=>e.on&&!o.has(e.key)).map(e=>e.key)];s.length&&(n[r]=new Set(s))}return n}function vc(e){return{Runs:{on:[...e.Runs],seen:It.map(e=>e.key)},"Run Scenarios":{on:[...e[`Run Scenarios`]],seen:Lt.map(e=>e.key)}}}function yc({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)(L,{title:`Select Columns`,onClose:n,children:(0,Z.jsxs)(`div`,{className:`hcols`,children:[zt.map(([e,t])=>(0,Z.jsxs)(`div`,{className:`groups`,children:[(0,Z.jsx)(`h3`,{children:Rt[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 bc=[`px`,`format`,`quality`],xc=[{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`}],Sc={"image/jpeg":`JPEG`,"image/webp":`WebP`,"image/png":`PNG`},Cc=e=>Sc[e]??e.replace(`image/`,``).toUpperCase(),wc={px:`921600`,quality:`0.92`};function Tc(e,t){let n=q().connectionImage({}).format,r=String(e.px??``),i=String(e.format??``),a=String(e.quality??``),o=(xc.some(e=>e.value===r)||!r?xc:[...xc,{value:r,label:q().budgetLabel(r)}]).map(e=>e.value===wc.px?{value:``,label:`${e.label} (default)`}:e),s=q().IMAGE_FORMATS.map(e=>e===n?{value:``,label:`${Cc(e)} (default)`}:{value:e,label:Cc(e)}),c=(i||n)===`image/png`,l={type:`text`,value:a,onChange:t(`quality`),size:`num`,...c?{marker:`unused`}:a?{}:{placeholder:wc.quality,marker:`default`}};return[{key:`px`,label:`Resolution`,control:{type:`select`,value:r===wc.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 Ec(e){let{px:t,format:n,quality:r}=q().connectionImage(e),i=n===`image/png`?``:` q${r??wc.quality}`;return`${q().budgetLabel(t??Number(wc.px))} · ${Cc(n)}${i}`}function Dc({offer:e}){let t=Y(),n=me(),r=Me(),i=He(),[a,o]=(0,J.useState)(null),[s,c]=(0,J.useState)(null),l=(0,J.useRef)(null),u=e=>c({text:e instanceof Error?e.message:String(e),bad:!0}),d=(0,J.useCallback)(()=>{t.packs().then(e=>o(e.packs),u)},[t]);(0,J.useEffect)(d,[d]);let f=async()=>{await Promise.all([n.refresh(),r.refresh(),i.refresh()]),d()},p=async e=>{c({text:`Installing ${e.name}…`,bad:!1});try{let n=await t.installPack(e);await f();let r=(await t.packs()).packs.find(e=>e.id===n.pack),i=r?`${r.name} ${r.version}`:n.pack;c({text:n.installed?`Installed ${i}.`:`${i} is up to date.`,bad:!1})}catch(e){u(e)}},m=async n=>{try{let{trash:r}=await t.removePack(n.id);await f(),e({label:`Removed ${n.name}`,restore:()=>{t.restorePack(r).then(f)}})}catch(e){u(e)}};return a===null&&!s?null:(0,Z.jsxs)(A,{id:`setup-packs`,title:`Packs`,note:a?Oc(a.length,`pack`):``,actions:[{label:`Install pack…`,icon:K,onSelect:()=>l.current?.click()}],children:[a&&!a.length&&(0,Z.jsx)(`p`,{className:`note`,children:`No packs installed.`}),a&&a.length>0&&(0,Z.jsx)(D,{className:`setup-table`,cards:!0,label:`Packs`,rows:a,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=>kc(e)},{key:`menu`,header:``,className:`ds-menu`,role:`menu`,sort:null,cell:e=>(0,Z.jsx)(w,{label:`${e.name} actions`,actions:[{label:`Remove`,icon:U.remove,destructive:!0,onSelect:()=>void m(e)}]})}]}),s&&(0,Z.jsx)(`p`,{className:`note${s.bad?` bad`:``}`,role:s.bad?`alert`:`status`,children:s.text}),(0,Z.jsx)(`input`,{ref:l,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&&p(t)}})]})}var Oc=(e,t)=>`${e} ${t}${e===1?``:`s`}`,kc=e=>[Oc(e.datasets.length,`dataset`),Oc(e.pipelines.length,`pipeline`),Oc(e.sources.length,`Source`),Oc(e.presets,`preset`)].join(` · `);function Ac({offer:e}){let t=Y(),[n,r]=(0,J.useState)(null),[i,a]=(0,J.useState)(null),o=(0,J.useRef)(null),s=(0,J.useCallback)(()=>{t.plugins().then(e=>r(e.plugins),e=>a({text:e instanceof Error?e.message:String(e),bad:!0}))},[t]);(0,J.useEffect)(s,[s]);let c=async e=>{a(null);try{let n=await t.installPlugin(e),i=(await t.plugins()).plugins;r(i);let o=i.find(e=>e.id===n.plugin);o&&n.installed&&await X(o),a({text:n.installed?se[n.plugin]?`Installed ${n.plugin}, and it did not load: ${se[n.plugin]}`:`Installed ${n.plugin}.`:`${n.plugin} is up to date.`,bad:!!se[n.plugin]})}catch(e){a({text:e instanceof Error?e.message:String(e),bad:!0})}},l=async n=>{try{let{trash:r}=await t.removePlugin(n.id);s(),e({label:`Removed ${n.id}`,restore:()=>{t.restorePlugin(r).then(s)}})}catch(e){a({text:e instanceof Error?e.message:String(e),bad:!0})}};return n===null&&!i?null:(0,Z.jsxs)(A,{id:`setup-plugins`,title:`Plugins`,note:n?`${n.length} ${n.length===1?`plugin`:`plugins`}`:``,actions:[{label:`Install plugin…`,icon:K,onSelect:()=>o.current?.click()}],children:[n&&!n.length&&(0,Z.jsx)(`p`,{className:`note`,children:`No plugins installed.`}),n&&n.length>0&&(0,Z.jsx)(D,{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=>jc(e)||`—`},{key:`state`,header:`State`,cell:e=>Mc(e)},{key:`menu`,header:``,className:`ds-menu`,role:`menu`,sort:null,cell:e=>(0,Z.jsx)(w,{label:`${e.id} actions`,actions:[{label:`Remove`,icon:U.remove,destructive:!0,onSelect:()=>void l(e)}]})}]}),i&&(0,Z.jsx)(`p`,{className:`note${i.bad?` bad`:``}`,role:i.bad?`alert`:`status`,children:i.text}),(0,Z.jsx)(`input`,{ref:o,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&&c(t)}})]})}var jc=e=>[...e.registers.outputKinds??[],...e.registers.modifiers??[],...e.registers.testTypes??[],...(e.registers.connectionTypes??[]).map(e=>e.id)].join(`, `),Mc=e=>se[e.id]?`Failed: ${se[e.id]}`:ce.has(e.id)?`Loaded`:`Not Loaded`,Nc={env:`Deployment`,lab:`Own`,default:`Default`};function Pc({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),Xi()}).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(`/`,Wi()??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?Nc[e.from]:`None`}}];return(0,Z.jsx)(O,{title:`Microsoft 365`,status:u??void 0,statusBad:!!u,focusRow:v?void 0:`client`,sections:[{key:`app`,rows:b}],onClose:n})}var Fc={env:`Deployment`,lab:`Own`,default:`Default`},Ic=`https://console.cloud.google.com/apis/credentials`,Lc=[{value:`installed`,label:`Desktop app`},{value:`web`,label:`Web application`}],Rc={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.`},zc=`/api/connections/google/callback`,Bc=()=>/^(localhost|127\.|\[::1\])/.test(window.location.hostname);function Vc(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 Hc({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)(Bc()?`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=Vc(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 k=!o,A=!!i?.hasSecret&&i.from!=="default",j=k?i?.clientType??`web`:m,M=k?[{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:Lc.find(e=>e.value===j).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??``)),...A?{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:Rc[m],control:{type:`select`,value:m,options:Lc,onChange:e=>T(`clientType`,h)(e)}}];return M.push({key:`redirect`,label:`Redirect URI`,control:j===`web`?{type:`code`,text:new URL(zc,window.location.href).href}:{type:`static`,text:`Not Needed`}},{key:`app`,label:`App`,control:{type:`static`,text:i?.from?Fc[i.from]:`None`}}),(0,Z.jsx)(O,{title:`Google Drive`,status:g??v??void 0,statusBad:!!g,focusRow:k?void 0:`client`,sections:[{key:`app`,rows:M}],actions:[{label:`Google Cloud`,icon:En,onSelect:()=>{window.open(Ic,`_blank`,`noopener`)}},...k?[]:[{label:`Load client file…`,icon:On,onSelect:E}]],onClose:e})}var Uc=`microsoft`,Wc=`google`;function Gc(){let e=Y(),{cfg:t,editable:n}=Zi(),[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}Hi(t).then(c,()=>c(null))},[t]);let f=[...a??[],...t||n?[{id:Uc,label:`Microsoft 365`,configured:!!t,signedIn:!!s,account:s??null,problem:null}]:[]],p=async n=>{u(null);try{n.id===Uc&&t?await Ki(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===Uc&&t?(await qi(t),c(null)):o((await e.signOut(n.id)).connections)}catch(e){u(e instanceof Error?e.message:String(e))}};if(!f.length)return null;let h=f.filter(e=>e.problem);return(0,Z.jsxs)(A,{id:`setup-connections`,title:`Connections`,note:`${f.filter(e=>e.signedIn).length} of ${f.length}`,children:[(0,Z.jsx)(D,{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=>Kc(e)},{key:`account`,header:`Account`,cell:e=>e.account||`—`},{key:`menu`,header:``,className:`ds-menu`,role:`menu`,sort:null,cell:e=>(0,Z.jsx)(w,{label:`${e.label} actions`,actions:[e.signedIn?{label:`Sign out`,icon:Bn,onSelect:()=>void m(e)}:{label:`Sign in`,icon:zn,disabled:!e.configured,onSelect:()=>void p(e)},...e.id===Uc||e.id===Wc?[{label:`Configure…`,icon:Kn,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===Uc&&t!==void 0&&(0,Z.jsx)(Pc,{cfg:t,editable:n,onClose:()=>i(null),onProblem:u}),r===Wc&&(0,Z.jsx)(Hc,{onClose:()=>i(null),onProblem:u,onSaved:d})]})}var Kc=e=>e.configured?e.signedIn?`Signed In`:`Signed Out`:`Not Configured`;function qc(){let e=me(),t=Y(),n=ee(),[r,i]=he(`promptlab.profiles`),[a]=he(`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,h]=(0,J.useState)(``),[g,_]=(0,J.useState)(``),[v,y]=(0,J.useState)(``),[b,x]=(0,J.useState)(null),[S,C]=(0,J.useState)([]),[w,E]=(0,J.useState)({});(0,J.useEffect)(()=>{let e=!0;return t.presets().then(t=>{e&&C(t)}).catch(()=>{}),()=>{e=!1}},[t]);let O=(0,J.useRef)(r);O.current=r;let k=(0,J.useCallback)(e=>{let t=O.current,n={...t,list:t.list.map(t=>t.id===e.id?e:t)};O.current=n,i(n),N(e)},[i]),j=(0,J.useRef)(null),M=(0,J.useRef)(null),N=(0,J.useCallback)(t=>{M.current&&clearTimeout(M.current),j.current={p:t},M.current=setTimeout(()=>{let t=j.current;t&&De(e,`profile`,t.p.id,t.p,`idle`)},Ce)},[e]);(0,J.useEffect)(()=>()=>{M.current&&clearTimeout(M.current)},[]);let P=(0,J.useCallback)(()=>{let e=dl(),t=O.current,n={...t,list:[...t.list,e],at:e.id};O.current=n,i(n),s({id:e.id,focus:`name`})},[i]),F=(0,J.useCallback)(e=>{let t=O.current.list.find(t=>t.id===e);if(!t)return;let n={...structuredClone(t),id:ul(),name:`${t.name||`Profile`} copy`,key:t.key},r={...O.current,list:[...O.current.list,n]};O.current=r,i(r)},[i]),L=(0,J.useCallback)(e=>{let t=O.current,r=t.list.filter(t=>t.id!==e);if(!r.length)return;let a={list:r,at:r[0].id};O.current=a,i(a),s(null);let o=t.list.find(t=>t.id===e);n.offer({label:`Deleted ${o?.name||`the profile`}`,restore:()=>{O.current=t,i(t)}})},[i,n]),R=(0,J.useCallback)(t=>{let n=t.doc.id,r=O.current.list.find(e=>e.id===n);r&&De(e,`profile`,n,r,`restore`);let a=O.current,o={...a,list:a.list.map(e=>e.id===n?t.doc:e)};O.current=o,i(o),z()},[e,i]),z=(0,J.useCallback)(()=>{l(e=>(e?.back&&s({id:e.id}),null))},[]),B=(0,J.useCallback)(async e=>{let n=O.current.list.find(t=>t.id===e);if(!n)return;let r=q().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=>il(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(E(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=q().apiBase(n.url||r?.url||``),a=q().connectionRequest(n,`hi`,null,e,i),o=await t.modelsAsk({url:n.url,key:i,type:n.type,body:a.body}),{raw:s}=q().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]),V=o?r.list.find(e=>e.id===o.id):void 0,H=V?JSON.stringify([V.id,V.url,V.type,V.key]):``;(0,J.useEffect)(()=>{if(!V)return;let e=V;if(q().CONNECTION_TYPES[e.type]?.local||q().CONNECTION_TYPES[e.type]?.lists===!1)return;let n=q().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&&E(n=>({...n,[e.id]:(t.data||[]).map(e=>e.id).sort()}))}).catch(()=>{r&&E(t=>({...t,[e.id]:[]}))})},400);return()=>{r=!1,clearTimeout(i)}},[t,H]);let U=(0,J.useCallback)((e,t)=>{let n=O.current.list.find(t=>t.id===e);if(!n)return;let r={...n};for(let e of sl(n.type))r[e]=``;for(let[e,n]of Object.entries(t.opts))r[e]=n;O.current={...O.current,list:O.current.list.map(t=>t.id===e?r:t)},i(O.current),N(r)},[i,N]),G=(0,J.useCallback)(e=>{p(t=>{if(!(e in t))return t;let{[e]:n,...r}=t;return r})},[]),K=(0,J.useCallback)((e,t,n)=>{let r=O.current.list.find(t=>t.id===e);r&&([`url`,`key`,`model`].includes(t)&&G(e),k({...r,[t]:n}))},[k,G]),te=(0,J.useCallback)((e,t)=>{let n=O.current.list.find(t=>t.id===e);if(!n)return;let r={...n,type:t};G(e),E(t=>({...t,[e]:[]}));let i=q().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`,...bc].includes(e)||cl(t).includes(e)||delete r[e];k(r)},[k,G]),ne=(0,J.useCallback)((e,t)=>{s(t?{id:e,focus:t}:{id:e})},[]),re=(0,J.useCallback)(e=>a.profile?.[e]??[],[a]),ie=o?r.list.find(e=>e.id===o.id)??null:null,ae=[...new Set(r.list.map(e=>e.type))],oe=m.trim().toLowerCase(),se=r.list.filter(e=>(!g||e.type===g)&&(!v||v===`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)(A,{id:`setup-profiles`,title:`Target profiles`,note:ll(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)(I,{noun:`profiles`,search:{label:`Search profiles`,placeholder:`Name, address or model`,value:m,onChange:h},filters:[{key:`type`,label:`Type`,value:g,onChange:_,options:[{value:``,label:`All`},...ae.map(e=>({value:e,label:q().CONNECTION_TYPES[e]?.label??e}))]},{key:`key`,label:`Key`,value:v,onChange:y,options:[{value:``,label:`All`},{value:`set`,label:`Set`},{value:`unset`,label:`Not set`}]},{key:`sort`,label:`Sort`,value:b?.key??``,onChange:e=>x(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)(D,{className:`setup-table`,cards:!0,label:`Target profiles`,sort:b,onSort:x,rows:se,rowKey:e=>e.id,rowProps:e=>({className:`setup-row`,onClick:t=>{t.target.closest(`button, a, .menu`)||ne(e.id)}}),columns:Jc({tests:f,only:r.list.length===1,grader:r.grader??null,onGrader:e=>{let t=O.current,n={...t,grader:t.grader===e?``:e};O.current=n,i(n)},onOpen:ne,onClone:F,onRemove:L,onTest:B,onResult:e=>d({id:e,back:!1})})}),(0,Z.jsxs)(`button`,{type:`button`,className:`ghost add-btn`,onClick:P,children:[(0,Z.jsx)(W,{size:14,"aria-hidden":`true`}),`Add profile`]})]}),(0,Z.jsx)(Gc,{}),(0,Z.jsx)(Ac,{offer:n.offer}),(0,Z.jsx)(Dc,{offer:n.offer}),(0,Z.jsx)(T,{undo:n.undo,onUndo:n.undoNow,onDismiss:n.dismiss}),ie&&(0,Z.jsx)(Yc,{profile:ie,...o?.focus?{focus:o.focus}:{},test:f[ie.id],models:w[ie.id]??[],presets:S.filter(e=>(e.type??`llama.cpp`)===ie.type),canRestore:!!re(ie.id).length,onClose:()=>s(null),onSetting:K,onType:te,onTest:B,onResult:()=>{s(null),d({id:ie.id,back:!0})},onRestore:()=>{s(null),l({id:ie.id,back:!0})},onApplyPreset:e=>U(ie.id,e)}),u&&f[u.id]&&(0,Z.jsx)(rl,{test:f[u.id],onClose:()=>{u.back&&s({id:u.id}),d(null)}}),c&&(0,Z.jsx)(tl,{versions:re(c.id),onClose:z,onRestore:R})]})}function Jc({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=e=>[{label:`Edit…`,icon:U.edit,onSelect:()=>i(e.id)},{label:`Rename`,icon:U.rename,onSelect:()=>i(e.id,`name`)},{label:`Clone`,icon:U.clone,onSelect:()=>a(e.id)},{label:`Test connection`,icon:v,onSelect:()=>void s(e.id)},...(q().CONNECTION_TYPES[e.type]?.answers??[`prompt`]).includes(`prompt`)&&!q().CONNECTION_TYPES[e.type]?.local?[{label:n===e.id?`Stop grading`:`Make grader`,icon:Fn,onSelect:()=>r(e.id)}]:[],...t?[]:[{label:`Remove`,icon:U.remove,destructive:!0,onSelect:()=>o(e.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: ${nl[r.phase]}`,onClick:()=>c(t.id),children:nl[r.phase]})]})}},{key:`type`,header:`Type`,label:``,cell:e=>q().CONNECTION_TYPES[e.type]?.label??e.type},{key:`url`,header:`Address`,sort:e=>e.url.trim(),cell:e=>q().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=>q().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=>q().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)(w,{actions:u(e),label:`${l(e)} actions`})}]}function Yc({profile:e,focus:t,test:n,models:i,presets:a,canRestore:o,onClose:s,onSetting:c,onType:l,onTest:u,onResult:d,onRestore:f,onApplyPreset:p}){let m=q().CONNECTION_TYPES[e.type],h=(m?.answers??[`prompt`]).includes(`prompt`),g=(0,J.useMemo)(()=>el(e),[e]),_=t=>n=>c(e.id,t,n),y=[{key:`name`,label:`Name`,required:!0,control:{type:`text`,value:e.name,onChange:_(`name`)}},{key:`type`,label:`Type`,required:!0,hint:m?.description,control:{type:`select`,value:e.type,onChange:t=>l(e.id,t),options:Object.entries(q().CONNECTION_TYPES).filter(([t,n])=>n.picker!==!1||t===e.type).map(([e,t])=>({value:e,label:t.label}))}},...m?.local?[]:[{key:`url`,label:`Address`,control:{type:`text`,value:e.url,placeholder:m?.url??`the lab's Ollama`,onChange:_(`url`)}},...m?.keyless?[]:[{key:`key`,label:`Key`,control:{type:`secret`,value:e.key,onChange:_(`key`)}}],...h?[{key:`model`,label:`Model`,control:ol(e.model,i,_(`model`))}]:[]]],b=(m?.settings??[]).map(t=>Xc(e,t,_(t.key))),x=[{key:`identity`,rows:y},...b.length?[{key:`settings`,title:`Settings`,rows:b}]:[],...m?.local||!h?[]:[{key:`image`,title:`Image`,rows:Tc(e,_)},{key:`debug`,title:`Debug`,rows:g,folded:!0}]],S=[{label:`Restore…`,icon:r,disabled:!o,onSelect:f},...a.map(e=>({label:`Apply preset: ${e.label}`,icon:U.preset,onSelect:()=>p(e)})),...(m?.templates??[]).map(t=>({label:`Apply template: ${t.label}`,icon:U.preset,onSelect:()=>p({id:t.id,label:t.label,type:e.type,opts:t.settings})}))];return(0,Z.jsx)(O,{title:e.name||`Unnamed profile`,...t?{focusRow:t}:{},sections:x,menu:S,actions:m?.tests===!1?[]:[{label:`Test connection`,icon:v,onSelect:()=>u(e.id),outcome:n?{label:nl[n.phase],bad:n.phase===`error`,onOpen:d}:void 0}],onClose:s})}function Xc(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 Zc=`424242`;function Qc(e,t){let n=q().apiBase(e.url),r,i;try{r=$c(q().connectionRequest({...e,[t]:``},`(prompt)`,null,n).body),i=$c(q().connectionRequest({...e,[t]:Zc},`(prompt)`,null,n).body)}catch{return null}let a=Object.keys(i).find(e=>i[e]===Zc||i[e]===JSON.stringify(Zc));if(a===void 0)return null;let o=i[a]===Zc,s=a in r?JSON.parse(r[a]):null;return s===null?{marker:`server`,numeric:o}:{placeholder:String(s),marker:`default`,numeric:o}}function $c(e,t=``,n={}){if(e&&typeof e==`object`&&!Array.isArray(e))for(let[r,i]of Object.entries(e))$c(i,t?`${t}.${r}`:r,n);else n[t]=JSON.stringify(e)??`null`;return n}function el(e){let t=q().apiBase(e.url),n=[];try{let{url:r,body:i}=q().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:Ec(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 tl({versions:e,onClose:t,onRestore:n}){return(0,Z.jsx)(L,{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:[pl(e.at),` · `,fl(e.reason)]}),(0,Z.jsx)(`button`,{type:`button`,className:`ghost`,onClick:()=>n(e),children:`Restore`})]},`${e.at}-${t}`))]})})}var nl={checking:`Checking…`,connected:`Connected`,error:`Error`};function rl({test:e,onClose:t}){return(0,Z.jsx)(O,{title:`Test connection`,sections:[{key:`result`,rows:[{key:`time`,label:`Time`,required:!0,control:{type:`static`,text:e.ms==null?`—`:al(e.ms)}},{key:`result`,label:`Result`,required:!0,control:{type:`textarea`,value:e.lines.join(`
12
- `)}}]}],closeLabel:`Close`,onClose:t})}function il(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 al=e=>e<1e3?`${e} ms`:`${(e/1e3).toFixed(1)}s`;function ol(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 sl(e){return q().CONNECTION_TYPES[e]?.settings.map(e=>e.key).filter(e=>e!==`temperature`)??[]}function cl(e){return q().CONNECTION_TYPES[e]?.settings.map(e=>e.key)??[]}var ll=e=>e===1?`1 profile`:`${e} profiles`,ul=()=>`p${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`,dl=()=>({id:ul(),name:`New profile`,url:``,model:``,key:``,temperature:``,nPredict:``,maxTokens:``,type:`ollama`}),fl=e=>e===`run`?`before a run`:e===`restore`?`before a restore`:`after editing`,pl=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},ml=[];function hl(e,t){let n=Y(),[r,i]=(0,J.useState)(null);(0,J.useEffect)(()=>{if(t===null)return;let r=!0,a=_e(n);return a.runDataset(e).then(n=>{if(n){r&&i({run:e,cases:n.cases,current:!1});return}return a.dataset(t).then(t=>{r&&i({run:e,cases: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:ml,current:a?.current??!1}}var gl=e=>e==null?`—`:jt(e);function _l(e){return e?.transcript||[]}function vl(e,t){return t.flatMap((n,r)=>{let i=_l(e?.scenarios?.[r]?.res);return t.length>1?i.map(e=>({...e,scenario:n.name})):i})}function yl({stages:e}){if(!e.length)return null;let t=!e.some(e=>e.scenario)&&e.length>1?` · ${e.map(e=>gl(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}`:``,` · `,gl(e.ms),` — sent`]}),`
13
- `,e.sent,`
14
- `,(0,Z.jsx)(`b`,{children:`— returned`}),`
15
- `,e.got||(e.error?`(nothing)`:``),e.error?`\n<b className="fault">Error - ${e.error}</b>`:``]},t))]})}function bl({text:e,kind:t}){return(0,Z.jsx)(`span`,{className:`term${t?` ${t}`:``}`,children:e})}function xl({res:e,kase:t}){let n=e?.dropped||[];if(!n.length)return null;let r=e=>t?[...t.expect||[],...(t.anyOf||[]).flat()].some(t=>q().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)(bl,{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 Sl({kase:e}){let t=(e,t,n)=>t?.length?(0,Z.jsxs)(`div`,{className:`wants`,children:[(0,Z.jsx)(`b`,{children:e}),t.map((e,t)=>(0,Z.jsx)(bl,{text:e,kind:n},t))]}):null,n=e.minCount!=null||e.maxCount!=null?[e.minCount,e.maxCount].filter(e=>e!=null).map(String).join(`–`):``;return(0,Z.jsxs)(Z.Fragment,{children:[t(`All of`,e.expect),(e.anyOf||[]).map((e,n)=>t(`Any of`,e,`any`)),t(`None of`,e.forbid,`no`),t(`Except`,e.allow),n&&t(`Count`,[n]),e.discarded&&t(`Discarded`,[`expected`]),t(`Watch for`,e.watch||[],`txt`),(e.metrics??[]).map((e,t)=>(0,Z.jsxs)(`div`,{className:`wants`,children:[(0,Z.jsx)(`b`,{children:q().METRICS[e.type]?.label??e.type}),`${e.not?`not `:``}${q().metricSummary(e)}`]},`m${t}`))]})}function Cl({kase:e,res:t}){if(!e.watch?.length)return null;let n=q().scoreCase(e,t);if(!n.watchTotal)return null;let r=e=>n.discarded?`txt`:n.watchFound.includes(e)?`met`:`unmet`;return(0,Z.jsxs)(`div`,{className:`wants`,children:[(0,Z.jsxs)(`b`,{children:[`Watch for, `,n.watchFound.length,` of `,n.watchTotal,` found`]}),e.watch.map((e,t)=>(0,Z.jsx)(bl,{text:e,kind:r(e)},t)),(0,Z.jsx)(`span`,{className:`note`,children:`Not scored`})]})}function wl({kase:e,res:t,scenarioIndex:n}){let r=q().scoreCase(e,t),i=t=>{if((e.expect||[]).some(e=>q().termIn([t],e))||(e.anyOf||[]).some(e=>e.some(e=>q().termIn([t],e))))return` met`;let n=n=>(e.allow||[]).some(e=>q().termIn([e],n)&&q().termIn([t],e));return(e.forbid||[]).some(e=>q().termIn([t],e)&&!n(e))?` unmet`:``},a=(t?.terms||[]).length,o=r.discarded?`${a} items, none kept`:`${a} items`;return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`verdict ${r.pass?`pass`:`fail`}`,children:r.pass?`pass`:`fail`}),(0,Z.jsx)(`span`,{className:`pct`,children:r.score==null?`—`:Math.round(r.score*100)+`%`}),r.reasons.length?(0,Z.jsx)(`div`,{className:`reasons fault`,children:r.reasons.map((e,t)=>(0,Z.jsx)(`div`,{children:e},t))}):(0,Z.jsx)(`div`,{className:`reasons hit`,children:`All matched`}),(0,Z.jsxs)(`div`,{className:`meta`,children:[o,` · `,gl(t?.ms)]}),(0,Z.jsx)(`div`,{className:`chips`,children:(t?.terms||[]).map((e,t)=>(0,Z.jsx)(bl,{text:String(e),kind:r.discarded?`drop`:i(String(e))},t))}),(0,Z.jsx)(xl,{res:t,kase:e})]})}var Tl=e=>e?.transcript?.at(-1)?.kind===`text`;function El({res:e}){return e?.error?(0,Z.jsx)(`span`,{className:`err`,children:e.error}):Tl(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:gl(e?.ms)})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`chips`,children:(e?.terms||[]).map((e,t)=>(0,Z.jsx)(bl,{text:String(e)},t))}),(0,Z.jsx)(xl,{res:e,kase:null}),(0,Z.jsxs)(`div`,{className:`meta`,children:[(e?.terms||[]).length,` items · `,gl(e?.ms)]})]})}function Dl({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:[gl(e?.ms),` · `,Tl(e)?`answered as text`:`read as ${(e?.terms||[]).length} items`]})]})}function Ol({tab:e}){let t=Y(),{setShow:n}=st(),{openCaseEditor:r}=Wr(),[i,a]=(0,J.useState)(null),[o,s]=(0,J.useState)(!1),[c,l]=(0,J.useState)(null),[u,d]=(0,J.useState)(new Set),[f,p]=(0,J.useState)(new Set),[h,g]=(0,J.useState)(!1),[_,v]=(0,J.useState)(null);(0,J.useEffect)(()=>{let n=!0,r,i=async()=>{try{let o=await t.run(e.id);if(!n)return;a(o),Bt(o.status)||(r=setTimeout(()=>void i(),1e3))}catch{n&&(r=setTimeout(()=>void i(),1e3))}};return i(),()=>{n=!1,r&&clearTimeout(r)}},[t,e.id]);let y=(0,J.useMemo)(()=>i?Qt(i):null,[i]),b=y?q().testsDataset(y.snapshot)?.id??null:null,x=hl(e.id,b),S=(0,J.useMemo)(()=>new Map(x.cases.map(e=>[q().caseFile(e),e])),[x.cases]),C=(0,J.useCallback)(async()=>{s(!0);try{await t.cancel(e.id)}catch{}s(!1)},[t,e.id]);if(!y)return(0,Z.jsx)(A,{id:`run-${e.id}`,title:St(e.at)||`Run`,children:(0,Z.jsx)(`p`,{className:`note`,children:`Loading…`})});let T=y.progress,E=T.n??T.total??0,O=!Bt(y.status),k=T.total&&E!=null&&O?Math.round(E/T.total*100):null,j=vn(y,x.cases),M=y.scenarios.map((e,t)=>bn(y,x.cases,t)),P=ln(y),F=(e,t,n)=>{let r=new Set(e);r.has(t)?r.delete(t):r.add(t),n(r)},ee=async(e,t,n)=>{let r=Math.max(0,y.scenarios.findIndex((t,n)=>Kt(y,e,n))),i=(t.scenarios??[])[r]?.res;i&&await ws(hn(y.snapshot,n,i,r))&&(g(!0),setTimeout(()=>g(!1),1600))},L=async()=>{await ws(j.map(e=>hn(y.snapshot,e.kase,e.res,e.scenarioIndex)).join(`
16
-
17
- `+`-`.repeat(60)+`
18
-
19
- `))&&(g(!0),setTimeout(()=>g(!1),1600))},R=j.length?[{label:`Copy all failures`,icon:N,onSelect:()=>void L()}]:[],z={key:`show`,label:`Show`,value:e.show,onChange:t=>n(e.id,t),options:[{value:`all`,label:`All`},{value:`failed`,label:`Failed`}]},B=!!b,V=y.tests.find(e=>`dataset`in e&&e.dataset)?.id??null,H=!!(y.content&&q().CONTENT_TYPES[y.content.type]?.inline),W=e=>{let t=y.results[e]?.name;return t?S.get(t):void 0},G=n=>{let i=y.results[n],o=W(n),s=!!i&&!i.unrun&&Bt(y.status),c=(i?.scenarios??[]).some(e=>e?.res?.transcript?.length),l=[];return c&&l.push({label:`Show details`,icon:m,onSelect:()=>F(u,n,d)}),o?.watch?.length&&l.push({label:`Watch for`,icon:m,onSelect:()=>F(f,n,p)}),s&&i?.name&&o&&l.push({label:`Edit case`,icon:U.edit,onSelect:()=>b&&r(i.name,{dataset:b,resultFor:e=>y.results[n]?.scenarios?.[e]?.res??null,scenarioCount:y.scenarios.length,files:y.results.filter(e=>e.kind!==`text`).map(e=>e.name??``)})}),s&&y.id&&l.push({label:`Re-run row`,icon:Wn,onSelect:()=>void t.rerun(e.id,n).then(e=>a(e.run)).catch(()=>{})}),s&&o&&kl(y,n)&&l.push({label:`Copy as AI prompt`,icon:N,onSelect:()=>void ee(n,i,o)}),l};return(0,Z.jsxs)(`div`,{className:`runview`,children:[(0,Z.jsxs)(A,{id:`run-${e.id}`,title:y.name||St(e.at),actions:R,children:[(0,Z.jsxs)(`div`,{className:`runhead`,children:[P&&(0,Z.jsxs)(`span`,{className:`note run-queue`,children:[(0,Z.jsx)(`span`,{className:`run-state`,children:P.state}),P.detail&&(0,Z.jsx)(`span`,{className:`run-item`,children:P.detail})]}),O&&(0,Z.jsxs)(`button`,{type:`button`,className:`ghost stop-btn`,disabled:o,onClick:()=>void C(),children:[(0,Z.jsx)(Cn,{size:14,"aria-hidden":`true`}),`Stop`]})]}),O&&(0,Z.jsx)(`div`,{className:`rrbar`,children:k==null?(0,Z.jsx)(`span`,{className:`rrprogress`,children:`Waiting`}):(0,Z.jsxs)(`div`,{className:`rrmeter`,role:`progressbar`,"aria-valuenow":k,"aria-valuemin":0,"aria-valuemax":100,children:[(0,Z.jsx)(`div`,{className:`rrbarfill`,style:{width:`${k}%`}}),(0,Z.jsxs)(`span`,{className:`rrpct`,style:{"--pct":`${k}%`},children:[k,`%`]})]})}),y.error&&(0,Z.jsx)(`p`,{className:`note bad rrstatus`,role:`status`,children:y.error}),(0,Z.jsx)(`div`,{id:`run-${e.id}-stats`,className:`runstats`,children:(0,Z.jsx)(ft,{label:`Run Statistics`,...rn(y)})}),y.tests.length>0&&(0,Z.jsx)(jl,{id:`run-${e.id}-tests`,rows:Zt(y),scenarios:y.scenarios,onScenario:v}),(0,Z.jsxs)(A,{id:`run-${e.id}-results`,title:`Results`,level:3,children:[(0,Z.jsx)(I,{noun:`results`,filters:[z],lead:(0,Z.jsx)(`p`,{className:`note`,children:Ct(y.items.length,`item`)}),count:{total:y.items.length,shown:e.show===`failed`?y.items.filter((e,t)=>kl(y,t)).length:y.items.length}}),x.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":y.scenarios.length},children:(0,Z.jsx)(D,{className:B?`rrtable graded`:`rrtable`,label:`Results`,rows:y.items.map((e,t)=>t),rowKey:e=>`${y.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`}),B&&(0,Z.jsx)(`td`,{className:`scenstats-blank`}),y.scenarios.map((e,t)=>(0,Z.jsx)(`td`,{className:`scenstat`,"data-label":e.name,children:(0,Z.jsx)(ft,{dense:!0,label:`${e.name} statistics`,...on(y,t)})},e.id))]}),M.some(e=>e.length>0)&&b&&(0,Z.jsx)(Al,{from:St(e.at)||y.name,datasetId:b,failing:M,scenarios:y.scenarios,items:y.items.length,graded:B})]}),rowProps:t=>({"data-item":t,className:u.has(t)?`hasdetail`:void 0,hidden:e.show===`failed`&&!kl(y,t)}),after:t=>u.has(t)&&(0,Z.jsx)(`tr`,{className:`rrdetail`,"data-detail":t,hidden:e.show===`failed`&&!kl(y,t),children:(0,Z.jsx)(`td`,{colSpan:1+ +!!B+y.scenarios.length,children:(0,Z.jsx)(yl,{stages:vl(y.results[t],y.scenarios)})})}),columns:[{key:`item`,header:H?`Text`:`Item`,label:``,className:`col-item`,sort:e=>y.items[e]||``,cell:e=>{let t=y.results[e],n=y.items[e];return(0,Z.jsxs)(Z.Fragment,{children:[t?.name&&!H&&vr(t.name)?(0,Z.jsx)(`button`,{type:`button`,className:`thumb`,"aria-label":`Open ${t.name}`,onClick:()=>l(t.name),children:(0,Z.jsx)(`img`,{src:dn(y,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)(w,{actions:G(e),label:`${n||`row`} actions`})]})]})}},...B?[{key:`expected`,header:`Expected`,className:`col-expected`,sort:e=>{let t=W(e);return t&&!t.todo?(t.expect??[]).length+(t.anyOf??[]).length+(t.metrics?.length??0):null},cell:e=>{let t=W(e);return y.results[e]?t&&!t.todo?(0,Z.jsx)(Sl,{kase:t}):(0,Z.jsx)(`span`,{className:`note`,children:`n/a`}):``}}]:[],...y.scenarios.map((e,t)=>({key:`scenario-${t}`,header:e.name,label:e.name,onHeader:()=>v(t),cell:e=>(0,Z.jsx)(Ml,{item:y.results[e],i:t,graded:B,cases:S,watched:f.has(e),readings:(y.outcomes[t]??[]).filter(e=>!e.whole).map(t=>({label:t.label,dataset:t.id===V,score:t.items[e]??null}))})}))]})})]}),h&&(0,Z.jsx)(`p`,{className:`note`,role:`status`,children:`Copied to clipboard.`})]}),_!=null&&(0,Z.jsx)(Is,{run:y.snapshot,i:_,onClose:()=>v(null)}),c&&(0,Z.jsx)(Rl,{src:fn(y,c),name:c,onClose:()=>l(null)})]})}var kl=(e,t)=>{let n=e.results[t];return!!n&&(!!n.unrun||(n.scenarios??[]).some((n,r)=>Kt(e,t,r)||!!n?.res?.error))};function Al({from:e,datasetId:t,failing:n,scenarios:r,items:i,graded:a}){let{showCases:o}=it(),{list:s}=Ne(),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 ${Ct(r,`case`)} in the Library`,"aria-label":`${n.label}: open ${Ct(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 jl({id:e,rows:t,scenarios:n,onScenario:r}){return(0,Z.jsx)(A,{id:e,title:`Tests`,level:3,children:(0,Z.jsx)(`div`,{className:`scrollx`,style:{"--scenarios":n.length},children:(0,Z.jsx)(D,{className:`ruletable`,label:`Tests`,rows:t,rowKey:e=>e.key,rowProps:e=>({className:e.first?`rule-first`:void 0,"data-rule":e.key}),columns:[{key:`test`,header:`Test`,label:``,sort:null,className:`col-test rule-test`,cell:e=>e.first&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`rule-test-name`,children:e.test}),` `,(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 Ml({item:e,i:t,graded:n,cases:r,watched:i,readings:a}){let o=e?.scenarios?.[t]?.res;if(e?.unrun)return(0,Z.jsx)(`span`,{className:`err`,children:e.unrun});if(!o)return(0,Z.jsx)(`span`,{className:`spin`,"aria-hidden":`true`});let s=e?.name?r.get(e.name):void 0,c=n&&!!s&&!s.todo&&e?.kind!==`text`&&Nl(s),l=a.map(e=>!c||!e.score||q().isSkipped(e.score)||!e.score.metrics?e:{...e,score:{...e.score,metrics:e.score.metrics.filter(e=>!e.found&&!e.missed&&!e.invented)}}),u=l.some(e=>e.score&&!q().isSkipped(e.score)&&e.score.metrics?.length),d=a.length>1||u?(0,Z.jsxs)(Z.Fragment,{children:[a.length>1&&(0,Z.jsx)(Il,{readings:a}),(0,Z.jsx)(Pl,{readings:l})]}):null;if(e?.kind===`text`)return(0,Z.jsxs)(Z.Fragment,{children:[d,(0,Z.jsx)(Dl,{res:o})]});let f=q().isSkipped(a.find(e=>e.dataset)?.score);return!c||f?(0,Z.jsxs)(Z.Fragment,{children:[f&&!d&&(0,Z.jsx)(`span`,{className:`verdict skipped`,children:`Skipped`}),d,(0,Z.jsx)(El,{res:o})]}):(0,Z.jsxs)(Z.Fragment,{children:[d,(0,Z.jsx)(wl,{kase:s,res:o,scenarioIndex:t}),i&&(0,Z.jsx)(Ll,{kase:s,res:o})]})}var Nl=e=>!!(e.expect?.length||e.anyOf?.length||e.forbid?.length||e.minCount!=null||e.maxCount!=null||e.discarded);function Pl({readings:e}){let t=e.flatMap(e=>e.score&&!q().isSkipped(e.score)&&e.score.metrics?.length?[{...e,score:e.score}]:[]);return t.length?(0,Z.jsx)(Z.Fragment,{children:t.map((e,t)=>(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:Fl(e.score.score,!!e.score.points)}),(0,Z.jsx)(`ul`,{children:e.score.metrics.map((e,t)=>(0,Z.jsxs)(`li`,{className:e.pass?`pass`:`fail`,children:[(0,Z.jsx)(`span`,{className:`test-name`,children:e.label}),` `,(0,Z.jsx)(`span`,{className:`metric-reason`,children:e.reason})]},t))})]},t))}):null}var Fl=(e,t)=>t?`${Math.round(e*100)/100} points`:`${Math.round(e*100)}%`;function Il({readings:e}){return(0,Z.jsx)(`ul`,{className:`test-verdicts`,children:e.map((e,t)=>{let n=e.score?q().isSkipped(e.score)?`Skipped`:e.score.pass?`Pass`:`Fail`:null;return n&&(0,Z.jsxs)(`li`,{children:[(0,Z.jsx)(`span`,{className:`test-name`,children:e.label}),(0,Z.jsx)(`span`,{className:`verdict ${n.toLowerCase()}`,children:n})]},t)})})}function Ll({kase:e,res:t}){return(0,Z.jsx)(Cl,{kase:e,res:t})}function Rl({src:e,name:t,onClose:n}){return(0,Z.jsx)(L,{title:t||`Image`,onClose:n,children:(0,Z.jsx)(`img`,{className:`lightbox-img`,src:e,alt:t})})}function zl(){let{tabs:e,focusedId:t,closeRun:n,focusRun:r,goBack:i}=st(),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)(p,{size:18,"aria-hidden":`true`})}),(0,Z.jsx)(`code`,{className:`rrcode`,children:St(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:St(e.at)||`run`,onClick:()=>r(e.id),children:St(e.at)||`…`}),(0,Z.jsx)(`button`,{type:`button`,className:`rx`,"aria-label":`Close`,onClick:()=>n(e.id),children:`×`})]},e.id))})]}),(0,Z.jsx)(Ol,{tab:a})]}):null}function Bl(){let e=Me(),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 Vl=`promptlab.theme`,Hl=typeof matchMedia==`function`?matchMedia(`(prefers-color-scheme: light)`):null;function Ul(){try{let e=JSON.parse(localStorage.getItem(Vl)||`null`)?.choice;return e===`light`||e===`dark`?e:null}catch{return null}}var Wl=()=>Ul()??(Hl?.matches?`light`:`dark`),Gl=()=>{let e=Wl();return document.documentElement.setAttribute(`data-theme`,e),e};Gl();function Kl(){let[e,t]=(0,J.useState)(Wl);(0,J.useEffect)(()=>{let e=()=>t(Gl());return Hl?.addEventListener?.(`change`,e),()=>Hl?.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(Vl,JSON.stringify({choice:n}))}catch{}document.documentElement.setAttribute(`data-theme`,n),t(n)},children:(0,Z.jsx)(n===`light`?Xn:Un,{size:16,"aria-hidden":`true`})})}var ql=()=>{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:Qn.find(t=>t.id===e)?.id??`home`,section:`datasets`,src:null}};function Jl(){return(0,Z.jsx)(je,{children:(0,Z.jsx)(Ve,{children:(0,Z.jsx)(ot,{children:(0,Z.jsx)(rt,{children:(0,Z.jsx)(Ur,{children:(0,Z.jsx)(Yl,{})})})})})})}function Yl(){let[e,t]=(0,J.useState)(ql),{hide:n}=st();(0,J.useEffect)(()=>{let e=()=>{t(ql()),n()};return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[n]);let r=Qn.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)(Zl,{}),(0,Z.jsx)(Bl,{}),(0,Z.jsx)(Kl,{})]}),(0,Z.jsx)(`nav`,{className:`app-tabs`,role:`tablist`,"aria-label":`Lab`,children:Qn.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)(Xl,{tab:r,section:e.section,src:e.src})]})}function Xl({tab:e,section:t,src:n}){let{focusedId:r}=st(),i=r?(0,Z.jsx)(zl,{}):e.id===`home`?(0,Z.jsx)(Co,{}):e.id===`runs`?(0,Z.jsx)(ic,{}):e.id===`history`?(0,Z.jsx)(mc,{}):e.id===`library`?(0,Z.jsx)(go,{section:t,sourceId:n}):(0,Z.jsx)(qc,{});return(0,Z.jsx)(`main`,{role:`tabpanel`,id:`panel-${e.id}`,"aria-labelledby":`tab-${e.id}`,"data-tab":e.id,children:i})}function Zl(){let{sync:e,resolve:t}=ge();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 Ql=`promptlab.sync`,$l=e=>typeof e==`object`&&!!e&&!Array.isArray(e),eu=(e,t)=>{let n=dr[e];return $l(n)&&$l(t)?{...n,...t}:t};function tu({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 mr){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 de&&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,eu(e,s(e))),a.get(e)??dr[e]},set(e,t){o(e,t),l&&mr.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 mr){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 nu=e=>[1,2,3,4,5,6,7,8,9].includes(e?.version)||q().fatProfileRef(e),ru=e=>e?.version===1||e?.version===2;function iu(e){let t=[...e.get(`promptlab.workflows`).list.map(e=>e.work),...Object.values(e.get(`promptlab.versions`).pipeline??{}).flat().map(e=>e.doc)].filter(ru).map(e=>e?.tests?.type===`graded`?e.tests.dataset?.id:void 0);return[...new Set(t.filter(e=>!!e))]}function au(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=>q().upgradePipeline(e,r),a=e=>nu(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 ou(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 su(){q();let e=fe();if(Bi())try{let t=(await e.config()).microsoft;t&&await Vi(t)}catch{}if(Gi())try{let t=(await e.config()).microsoft;if(t){await Ki(t);return}}catch{}await ue(e);let t=tu({api:e,storage:localStorage,server:await ou(e)}),n=t.get(`promptlab.profiles`);n.list.some(e=>`profile`in e)&&t.set(`promptlab.profiles`,{...n,list:n.list.map(e=>q().convertProfile(e))});let r=t.get(`promptlab.profiles`),i=e=>q().pinReplyTokens(q().splitOllama(e));r.list.some(e=>i(e)!==e)&&t.set(`promptlab.profiles`,{...r,list:r.list.map(e=>i(e))});let a={};if(iu(t).length)try{a=(await e.archivedRules()).rules}catch{}au(t,a),addEventListener(`pagehide`,()=>{t.flush(!0)}),(0,te.createRoot)(document.getElementById(`root`)).render((0,Z.jsx)(J.StrictMode,{children:(0,Z.jsx)(pe.Provider,{value:t,children:(0,Z.jsx)(ne.Provider,{value:e,children:(0,Z.jsx)(Jl,{})})})}))}su();