openpond 0.0.63 → 0.0.64
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{app-layer-TUAFALOE.js → app-layer-NCSTDSNQ.js} +2 -2
- package/dist/chunks/{app-server-runtime-O26LVUYH.js → app-server-runtime-XWIG4OWY.js} +6 -6
- package/dist/chunks/{apps-KSZRA7Y2.js → apps-HEG7FEEV.js} +2 -2
- package/dist/chunks/{chunk-66KQLYSH.js → chunk-57XKCMOZ.js} +1 -1
- package/dist/chunks/{chunk-JTFDOA2P.js → chunk-6FZNXLVN.js} +17 -5
- package/dist/chunks/{chunk-IXA5PMXC.js → chunk-BRLUAT6S.js} +1 -1
- package/dist/chunks/{chunk-7IFPXSSJ.js → chunk-C7TOCBGY.js} +1 -1
- package/dist/chunks/{chunk-6FKBOGA4.js → chunk-EWP6VGHP.js} +1 -1
- package/dist/chunks/{chunk-V2CTXKS2.js → chunk-HM6Z3PEC.js} +19 -16
- package/dist/chunks/{chunk-KGU437HZ.js → chunk-JMHOO2IG.js} +2 -2
- package/dist/chunks/{chunk-7UVEB2AZ.js → chunk-THYIAXOB.js} +2 -2
- package/dist/chunks/{chunk-LEL5AQJU.js → chunk-U345JN44.js} +1 -1
- package/dist/chunks/{chunk-YDH34BGG.js → chunk-WT3THPTX.js} +32 -32
- package/dist/chunks/{cli-LPFU4ULD.js → cli-3BI2QBI2.js} +5 -5
- package/dist/chunks/{core-commands-OEOBYFIW.js → core-commands-Y4ZMQXO4.js} +3 -3
- package/dist/chunks/{desktop-test-BRLZF3O7.js → desktop-test-YRFKONLO.js} +2 -2
- package/dist/chunks/{extension-5BUCIDKG.js → extension-4MFKIC6Q.js} +2 -2
- package/dist/chunks/{help-MT6VPW4X.js → help-STXVR4NO.js} +1 -1
- package/dist/chunks/{opchat-O4DVKNFW.js → opchat-CCVKI5GH.js} +2 -2
- package/dist/chunks/{organizations-ACNOJ57Q.js → organizations-AS76SGLP.js} +4 -4
- package/dist/chunks/{profile-7LLWXAJE.js → profile-QNWDNZY3.js} +2 -2
- package/dist/chunks/{project-agent-RVYQYTU2.js → project-agent-GPZL7KAL.js} +2 -2
- package/dist/chunks/{sandbox-command-QST23BX5.js → sandbox-command-LC63MMAA.js} +2 -2
- package/dist/chunks/{sandbox-template-N7UG3P6V.js → sandbox-template-FPQLZ4IP.js} +3 -3
- package/dist/chunks/{src-CPM5Q7T5.js → src-6NIBZPH2.js} +3 -3
- package/dist/chunks/{src-M37V6NVU.js → src-DQFVZZUR.js} +7 -7
- package/dist/chunks/{teams-bot-ITTI47XS.js → teams-bot-YTX7IC2J.js} +2 -2
- package/dist/chunks/{workspaces-CYBR37US.js → workspaces-IXF7MIQV.js} +2 -2
- package/dist/cli.js +13 -13
- package/dist/web/assets/{AppDialog-wIb8mGQ0.js → AppDialog-DacC7BcY.js} +1 -1
- package/dist/web/assets/{AppsView-D097dPIV.js → AppsView-mkeAkrvr.js} +1 -1
- package/dist/web/assets/{BrowserSidebar-DrD-o_yB.js → BrowserSidebar-1aEC6gsF.js} +1 -1
- package/dist/web/assets/{CommandMenu-L5LelA2h.js → CommandMenu-BN6J3ecV.js} +1 -1
- package/dist/web/assets/{CommunityView-DUJ8NryS.js → CommunityView-B2v9Q4cw.js} +1 -1
- package/dist/web/assets/{ComposerCreateImproveStrip-BP-7DmQG.js → ComposerCreateImproveStrip-BH8Ath1h.js} +1 -1
- package/dist/web/assets/{GetStartedView-B7gB6Hii.js → GetStartedView-B-R-KSva.js} +1 -1
- package/dist/web/assets/{LabModelVersionDetailPage-CNDz2a6I.js → LabModelVersionDetailPage-Bhfa7T00.js} +1 -1
- package/dist/web/assets/{LabSkillSidebar-BImOQcjk.js → LabSkillSidebar-CbYdG0RN.js} +1 -1
- package/dist/web/assets/{LabsRoute-BauSK1is.js → LabsRoute-DFV5vV6Z.js} +3 -3
- package/dist/web/assets/{MainChatThread-BZvAqQO6.js → MainChatThread-COiXI7ri.js} +2 -2
- package/dist/web/assets/MainPane-CQCLhV5C.js +6 -0
- package/dist/web/assets/MarkdownText-R3MC5S30.js +9 -0
- package/dist/web/assets/{Messages-DijmQL-z.js → Messages-DpZ8mIz8.js} +1 -1
- package/dist/web/assets/{NativeSkillSidebar-aCkrdGa0.js → NativeSkillSidebar-BfcMqLHA.js} +1 -1
- package/dist/web/assets/{NewProjectDialog-D98WIQzr.js → NewProjectDialog-DqTX1Eeo.js} +1 -1
- package/dist/web/assets/{OutputsPage-BA0c6cfy.js → OutputsPage-DfZYswx2.js} +1 -1
- package/dist/web/assets/{RightChatPanelStack-DKDEmrEH.js → RightChatPanelStack-DH8QjiDY.js} +1 -1
- package/dist/web/assets/{ScheduledWorkPage-DeHi99mv.js → ScheduledWorkPage-DkaVUnwj.js} +1 -1
- package/dist/web/assets/SettingsView-BRPrJuP5.css +1 -0
- package/dist/web/assets/SettingsView-StVFsSJ6.js +6 -0
- package/dist/web/assets/{TeamChatView-D2mCoLZ3.js → TeamChatView-CqZOnQh2.js} +1 -1
- package/dist/web/assets/{TerminalOverlay-BHMsVp4L.js → TerminalOverlay-CnFv6FZT.js} +1 -1
- package/dist/web/assets/{TrainingCreationPanel-CPnMWgkt.js → TrainingCreationPanel-CWzyzmyT.js} +1 -1
- package/dist/web/assets/{TrainingDraftPanel-0scEtzSW.js → TrainingDraftPanel-BVHx0HZ0.js} +1 -1
- package/dist/web/assets/{UsageSettingsSection-COoCLLg6.js → UsageSettingsSection-Bdvm66WK.js} +1 -1
- package/dist/web/assets/{WorkspaceDiffPanel-BFTwZ_dB.js → WorkspaceDiffPanel-DUCjD1GA.js} +5 -5
- package/dist/web/assets/{WorkspaceEnvironmentMenu-DFlkdd9T.js → WorkspaceEnvironmentMenu-DHGrt_ie.js} +1 -1
- package/dist/web/assets/{WorkspaceGitDialogs-Dt3LO27Z.js → WorkspaceGitDialogs-hI57yjPL.js} +1 -1
- package/dist/web/assets/{WorkspaceMonacoEditor-3g05teoR.js → WorkspaceMonacoEditor-DPv-1uO6.js} +3 -3
- package/dist/web/assets/{arrow-up-right-DYGSWA2J.js → arrow-up-right-BDcNd1rt.js} +1 -1
- package/dist/web/assets/{chevron-up-4qfvI9iW.js → chevron-up-XTMMnfnf.js} +1 -1
- package/dist/web/assets/{cloud-upload-COReKxOy.js → cloud-upload-D6bS8rS2.js} +1 -1
- package/dist/web/assets/{cssMode-BbH67BYF.js → cssMode-CvN9o8bP.js} +1 -1
- package/dist/web/assets/{folder-open-9OjGqNgP.js → folder-open-8C5l7A93.js} +1 -1
- package/dist/web/assets/{folder-plus-DF5E6zr3.js → folder-plus-B9Wqb9yd.js} +1 -1
- package/dist/web/assets/{git-branch-eCwyZXMl.js → git-branch-C45ve7zh.js} +1 -1
- package/dist/web/assets/{git-commit-horizontal-cPm51DqY.js → git-commit-horizontal-CGoLIyKK.js} +1 -1
- package/dist/web/assets/{htmlMode-DD6Oge4x.js → htmlMode-DxLP6j5r.js} +1 -1
- package/dist/web/assets/index-BYgrO3wt.js +1 -0
- package/dist/web/assets/index-CHqMtVfF.css +1 -0
- package/dist/web/assets/{index-BO2W2U23.js → index-LrGasYyx.js} +29 -29
- package/dist/web/assets/{info-p1mFpqBI.js → info-DTObFlHw.js} +1 -1
- package/dist/web/assets/{jsonMode-C2Xd56A_.js → jsonMode-C3_fOSJu.js} +1 -1
- package/dist/web/assets/{lspLanguageFeatures-BjYEk4gJ.js → lspLanguageFeatures-0c-UKStE.js} +1 -1
- package/dist/web/assets/{monaco.contribution-quEPEMQZ.js → monaco.contribution-CF1DgPPC.js} +2 -2
- package/dist/web/assets/{monaco.contribution-C7WMqwmc.js → monaco.contribution-CFLEc9Ly.js} +2 -2
- package/dist/web/assets/{monaco.contribution-Bo-5m7yy.js → monaco.contribution-Cb7KlQ6G.js} +2 -2
- package/dist/web/assets/{monaco.contribution-DzWlEgU1.js → monaco.contribution-Dsug_FPj.js} +2 -2
- package/dist/web/assets/{play-Ctx-iMqd.js → play-Cbsyrwkw.js} +1 -1
- package/dist/web/assets/{python-Cm64qCpk.js → python-DVcVB2lF.js} +1 -1
- package/dist/web/assets/{refresh-cw-Bn28jIl0.js → refresh-cw-ChUK_QfF.js} +1 -1
- package/dist/web/assets/{save-BM5IQX65.js → save-Doep-KC7.js} +1 -1
- package/dist/web/assets/{square-DAGpFfSr.js → square-B5q2aneb.js} +1 -1
- package/dist/web/assets/{toggleHighContrast-DLW8Fnck.js → toggleHighContrast-CTZp7RE7.js} +1 -1
- package/dist/web/assets/{tsMode-BleUN_8S.js → tsMode-GfNadOOB.js} +1 -1
- package/dist/web/assets/{upload-vaAKFfxi.js → upload-DcewuCTa.js} +1 -1
- package/dist/web/assets/{useLocalAgentSchedules-Ccenbqf6.js → useLocalAgentSchedules-BwltnId8.js} +1 -1
- package/dist/web/assets/{wifi-off-DJA9KReb.js → wifi-off-cXPyKIzd.js} +1 -1
- package/dist/web/assets/{workers-CFG-afha.js → workers-CP6kCS63.js} +1 -1
- package/dist/web/assets/{yaml-Cs8iZKVC.js → yaml-w0GP6yKf.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/web/assets/MainPane-CuhwxMxg.js +0 -6
- package/dist/web/assets/MarkdownText-gwAue4u5.js +0 -9
- package/dist/web/assets/SettingsView--fL3Ecuy.js +0 -6
- package/dist/web/assets/SettingsView-BS5m5vdt.css +0 -1
- package/dist/web/assets/index-BRLugX1S.js +0 -1
- package/dist/web/assets/index-Y7IoiSlQ.css +0 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./LabModelVersionDetailPage-
|
|
2
|
-
import{r as c,b9 as oa,j as e,X as Me,A as An,aS as dt,ba as ra,a2 as wn,bN as Ft,p as lt,bO as st,bP as je,bQ as Tn,P as da,bR as ca,L as _n,u as $n,aV as zt,au as ua,aL as ot,as as ha,_ as ma,bS as pa,bT as Vt,ar as Pn,M as En,a as ba,bU as kt,bV as ga,bW as fa,bX as xa,bY as ja,aA as va,aG as ya,ay as Zt,bZ as en,b_ as St,b$ as ka}from"./index-BO2W2U23.js";import{C as Sa}from"./cloud-upload-COReKxOy.js";import{C as Na}from"./MainPane-CuhwxMxg.js";import{A as _e}from"./AppDialog-wIb8mGQ0.js";import{c as Ca,s as Se,f as $e,e as Oe,j as Ln,g as Ra}from"./training-model-data-V8276E5q.js";import{D as De}from"./MarkdownText-gwAue4u5.js";import{ComposerCreateImproveStrip as Ia}from"./ComposerCreateImproveStrip-BP-7DmQG.js";/* empty css */import{UsageSettingsSection as Ma}from"./UsageSettingsSection-COoCLLg6.js";const Nt=8,tn=24,Aa=2;function wa(t){const n=_a(t);if(n.length){const l=tn+n.reduce((i,r)=>i+Nt+Ke(r.content),0),o=n.filter(i=>i.role==="assistant").map(i=>Nt+Ke(i.content));return{renderedTokens:l,maximumAssistantTargetTokens:Math.max(0,...o),assistantTargetCount:o.length}}const a=Pa(t.input),s=Ea(t.expectedOutput);return{renderedTokens:tn+Ke(a)+Ke(s),maximumAssistantTargetTokens:Nt+Ke(s),assistantTargetCount:s?1:0}}function Ta(t,n={}){const a=n.minimum??64,s=n.maximum??4096,l=t.tasks.filter(o=>o.split==="train").reduce((o,i)=>Math.max(o,wa(i).renderedTokens),0);return l<=a?a:Math.min(s,2**Math.ceil(Math.log2(l)))}function _a(t){const n=[...nn(t.input.messages),...nn(t.expectedOutput?.messages)],a=[],s=new Map,l=o=>{const i=typeof o=="string"&&o?o:`missing_${s.size+1}`;return s.has(i)||s.set(i,`call_${s.size+1}`),s.get(i)};for(const o of n){if(!it(o))continue;const i=o.role,r=o.content;if(i==="tool"){a.push({role:"user",content:rt({content:typeof r=="string"?r:"",tool_call_id:l(o.tool_call_id),type:"tool_result"})});continue}if(i==="assistant"&&Array.isArray(o.tool_calls)&&o.tool_calls.length){for(const u of o.tool_calls)!it(u)||!it(u.function)||(a.push({role:"assistant",content:rt({arguments:$a(u.function.arguments),name:u.function.name??null,type:"tool_call"})}),l(u.id));typeof r=="string"&&r&&a.push({role:"assistant",content:r});continue}(i==="system"||i==="user"||i==="assistant")&&typeof r=="string"&&r&&a.push({role:i,content:r})}return a}function nn(t){return Array.isArray(t)?t:[]}function $a(t){if(typeof t!="string")return{};try{return JSON.parse(t)}catch{return{malformed_arguments:t}}}function rt(t){return JSON.stringify(wt(t))}function wt(t){return Array.isArray(t)?t.map(wt):it(t)?Object.fromEntries(Object.keys(t).sort().map(n=>[n,wt(t[n])])):t}function Pa(t){return typeof t.prompt=="string"?t.prompt:rt(t)}function Ea(t){return t?typeof t.text=="string"?t.text:rt(t):""}function Ke(t){return Math.ceil(t.length/Aa)}function it(t){return!!(t&&typeof t=="object"&&!Array.isArray(t))}const an=[{id:"build",title:"Build",description:"Create from a purpose, conversations, or both.",icon:oa,available:!0},{id:"huggingface",title:"Hugging Face",description:"Import task data from a Dataset URL or repository ID.",icon:Na,available:!0},{id:"upload",title:"Upload file",description:"JSON, JSONL, CSV, and Parquet import is coming next.",icon:Sa,available:!1}];function La({onClose:t,onSelect:n}){const[a,s]=c.useState(null),l=an.find(o=>o.id===a)??null;return e.jsxs(_e,{ariaLabel:"New Taskset",className:"training-dialog training-run-dialog training-run-start-step",onClose:t,children:[e.jsxs("div",{className:"training-dialog-header",children:[e.jsx("h2",{children:"New Taskset"}),e.jsx("button",{"aria-label":"Close",className:"training-icon-button",type:"button",onClick:t,children:e.jsx(Me,{size:16})})]}),e.jsxs("div",{className:"training-run-step-heading",children:[e.jsx("h3",{children:"Choose a source"}),e.jsx("p",{children:"Every source becomes an immutable OpenPond Taskset with Parquet-backed Data."})]}),e.jsx("div",{"aria-label":"How to create a Taskset",className:"training-method-options training-start-mode-options",role:"radiogroup",children:an.map(o=>{const i=o.icon;return e.jsxs("button",{"aria-describedby":o.available?void 0:`${o.id}-availability`,"aria-checked":a===o.id,className:a===o.id?"selected":void 0,disabled:!o.available,role:"radio",type:"button",onClick:()=>s(o.id),children:[e.jsx("span",{className:"training-start-mode-icon","aria-hidden":"true",children:e.jsx(i,{size:18})}),e.jsxs("span",{className:"training-start-mode-copy",children:[e.jsxs("strong",{children:[o.title,o.available?null:e.jsx("span",{className:"dataset-source-availability",id:`${o.id}-availability`,children:"Coming next"})]}),e.jsx("small",{children:o.description})]})]},o.id)})}),e.jsxs("div",{className:"training-dialog-actions",children:[e.jsx("button",{className:"training-button secondary",type:"button",onClick:t,children:"Cancel"}),e.jsx("button",{className:"training-button",disabled:!l,type:"button",onClick:()=>{l&&n(l.id)},children:a==="build"?"Create":"Continue"})]})]})}const Da=["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"],Oa=["visible","privileged","metadata"];function Ba({onBack:t,onClose:n,onImported:a,onOpenDatasetStorageSettings:s,training:l}){const[o,i]=c.useState(""),[r,u]=c.useState(null),[h,d]=c.useState(null),[j,b]=c.useState(""),[g,C]=c.useState(""),[k,f]=c.useState(!1),[S,y]=c.useState(null),w=c.useRef(null),p=l.payload?.datasetImports.find(M=>M.id===r?.id)??r,_=p?.inspection??null,x=!!(p&&["inspecting","materializing","validating","cancelling"].includes(p.status)),m=!_?.declaredLicense||["unknown","other"].includes(_.declaredLicense.toLowerCase()),T=c.useMemo(()=>_?.sourceFiles.reduce((M,H)=>M===null||H.sizeBytes===null?null:M+H.sizeBytes,0)??null,[_]);c.useEffect(()=>{!p||p.status!=="ready"||!p.tasksetId||w.current!==p.id&&(w.current=p.id,a(p.tasksetId))},[p,a]);async function V(){if(!o.trim())return;y(null);const M=await l.actions.inspectHuggingFaceDataset(o);if(!M){y(l.error??"OpenPond could not inspect this Dataset.");return}u(M),M.inspection&&M.mapping&&E(M)}function E(M){d(M.mapping),b(M.inspection?.title??M.locator?.repositoryId.split("/").at(-1)??"Imported Dataset"),C(M.inspection?.description?.trim().slice(0,2e3)||`Train and evaluate tasks from ${M.locator?.repositoryId??"this Dataset"}.`)}function $(M,H){d(B=>B&&{...B,bindings:B.bindings.map((G,de)=>de===M?{...G,...H}:G)})}async function Z(){if(!p||!h||!j.trim()||!g.trim())return;y(null);const M=await l.actions.materializeDatasetImport(p.id,{name:j.trim(),objective:g.trim(),mapping:h,targetStorageRoot:null,licenseApproved:k});if(!M){y(l.error??"OpenPond could not start Dataset materialization.");return}u(M)}async function K(){if(!p)return;const M=await l.actions.cancelDatasetImport(p.id);M&&u(M)}const ee=!!(_&&h)&&!["materializing","validating","ready","cancelling","cancelled"].includes(p?.status??"");return e.jsxs(_e,{ariaLabel:"Import Hugging Face data",className:"training-dialog training-run-dialog training-run-workflow-step dataset-import-dialog",dismissDisabled:x,initialFocusKey:_?"review":"locator",onClose:n,children:[e.jsxs("div",{className:"training-dialog-header",children:[e.jsxs("div",{className:"training-run-dialog-title",children:[e.jsx("button",{"aria-label":"Back to Taskset sources",className:"training-icon-button",type:"button",onClick:t,children:e.jsx(An,{size:16})}),e.jsx("h2",{children:"Import from Hugging Face"})]}),e.jsx("button",{"aria-label":"Close",className:"training-icon-button",type:"button",onClick:n,children:e.jsx(Me,{size:16})})]}),_?ee?e.jsxs("div",{className:"training-dialog-scroll-body dataset-import-review",children:[e.jsx(Ua,{job:p,sourceBytes:T}),e.jsxs("label",{className:"training-objective-field",children:[e.jsx("span",{children:"Taskset name"}),e.jsx("input",{value:j,onChange:M=>b(M.target.value)})]}),e.jsxs("label",{className:"training-objective-field",children:[e.jsx("span",{children:"Purpose"}),e.jsx("textarea",{value:g,onChange:M=>C(M.target.value)})]}),e.jsxs("div",{className:"dataset-import-mapping",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Semantic mapping"}),e.jsx("small",{children:"Review which fields the policy can see and which stay privileged for grading."})]}),e.jsx("div",{className:"dataset-import-mapping-table",children:h.bindings.map((M,H)=>e.jsxs("div",{children:[e.jsx("code",{children:M.sourcePath}),e.jsx("select",{"aria-label":`Target for ${M.sourcePath}`,value:M.target,onChange:B=>$(H,{target:B.target.value}),children:Da.map(B=>e.jsx("option",{value:B,children:Tt(B)},B))}),e.jsx("select",{"aria-label":`Policy for ${M.sourcePath}`,value:M.policy,onChange:B=>$(H,{policy:B.target.value}),children:Oa.map(B=>e.jsx("option",{value:B,children:Tt(B)},B))})]},`${M.sourcePath}:${H}`))})]}),m?e.jsxs("label",{className:"dataset-import-license-review",children:[e.jsx("input",{checked:k,type:"checkbox",onChange:M=>f(M.target.checked)}),e.jsx("span",{children:"I reviewed the repository license and approve importing this Dataset."})]}):null,p?.status==="failed"&&p.error?e.jsx("div",{className:"training-banner error",role:"alert",children:p.error}):null]}):e.jsx(Fa,{job:p}):e.jsxs("div",{className:"training-dialog-scroll-body dataset-import-locator",children:[e.jsxs("div",{className:"training-run-step-heading",children:[e.jsx("h3",{children:"Paste a Dataset URL"}),e.jsx("p",{children:"OpenPond inspects the public repository, pins its exact commit, and shows the fields before downloading any rows."})]}),e.jsxs("label",{className:"training-objective-field",children:[e.jsx("span",{children:"Hugging Face URL or repository ID"}),e.jsx("input",{"data-autofocus":!0,disabled:x,placeholder:"BytedTsinghua-SIA/DAPO-Math-17k",value:o,onChange:M=>i(M.target.value)})]}),p?.status==="failed"&&p.error?e.jsx("div",{className:"training-banner error",role:"alert",children:p.error}):null]}),S?e.jsx("div",{className:"training-banner error",role:"alert",children:S}):null,e.jsx("div",{className:"training-dialog-actions",children:_?ee?e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"training-button secondary",type:"button",onClick:s,children:"Dataset storage"}),e.jsx("button",{className:"training-button",disabled:!j.trim()||!g.trim()||!h||m&&!k,type:"button",onClick:()=>{Z()},children:"Import and save"})]}):x?e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"training-button secondary",type:"button",onClick:n,children:"Run in background"}),e.jsx("button",{className:"training-button",disabled:p?.status==="cancelling",type:"button",onClick:()=>{K()},children:"Cancel import"})]}):e.jsx("button",{className:"training-button",type:"button",onClick:n,children:"Close"}):e.jsxs("button",{className:"training-button",disabled:!o.trim()||x,type:"button",onClick:()=>{V()},children:[x?e.jsx(dt,{className:"spin",size:14}):null,"Inspect Dataset"]})})]})}function Ua({job:t,sourceBytes:n}){const a=t.inspection,s=a.splits.reduce((l,o)=>l===null||o.rowCount===null?null:l+o.rowCount,0);return e.jsxs("div",{className:"dataset-import-summary",children:[e.jsxs("div",{children:[e.jsx("strong",{children:a.title}),e.jsxs("a",{href:a.locator.repositoryUrl,rel:"noreferrer",target:"_blank",children:["Open on Hugging Face ",e.jsx(ra,{size:12})]})]}),e.jsxs("dl",{children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Revision"}),e.jsx("dd",{children:e.jsx("code",{children:a.resolvedRevision.slice(0,12)})})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Rows"}),e.jsx("dd",{children:s===null?"Unknown":s.toLocaleString()})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Source size"}),e.jsx("dd",{children:n===null?"Unknown":_t(n)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"License"}),e.jsx("dd",{children:a.declaredLicense??"Review required"})]})]}),e.jsx("p",{children:a.splits.map(l=>`${l.configuration}/${l.split}: ${l.rowCount?.toLocaleString()??"unknown"} rows`).join(" · ")})]})}function Fa({job:t}){const n=t.progress,a=n.totalBytes&&n.totalBytes>0?Math.min(100,n.completedBytes/n.totalBytes*100):null,l=(n.totalRows&&n.totalRows>0?Math.min(100,n.completedRows/n.totalRows*100):null)??a;return e.jsxs("div",{className:"training-dialog-scroll-body dataset-import-progress",role:"status",children:[e.jsx(dt,{className:t.status==="ready"?"":"spin",size:22}),e.jsx("h3",{children:t.status==="ready"?"Taskset saved":"Importing data"}),e.jsx("p",{children:t.progress.message}),e.jsx("div",{className:"dataset-import-progress-track",children:e.jsx("span",{style:{width:`${l??8}%`}})}),e.jsx("small",{children:n.completedRows?`${n.completedRows.toLocaleString()}${n.totalRows?` of ${n.totalRows.toLocaleString()}`:""} rows`:n.completedBytes?`${_t(n.completedBytes)}${n.totalBytes?` of ${_t(n.totalBytes)}`:""}`:Tt(n.phase)}),t.error?e.jsx("div",{className:"training-banner error",children:t.error}):null]})}function Tt(t){return t.replaceAll("_"," ").replace(/^./,n=>n.toUpperCase())}function _t(t){const n=["B","KB","MB","GB","TB"];let a=t,s=0;for(;a>=1024&&s<n.length-1;)a/=1024,s+=1;return`${a>=10?a.toFixed(0):a.toFixed(1)} ${n[s]}`}function Dn({lineage:t,taskset:n,training:a,onChat:s,onClose:l}){const o=!!a.busyAction;function i(){s(Ft({modelId:t.id,taskset:n})),l()}return e.jsxs(_e,{ariaLabel:`Use ${n.name}`,className:"training-dialog training-model-use-dialog",dismissDisabled:o,onClose:l,children:[e.jsxs("div",{className:"training-dialog-header",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Use model"}),e.jsx("p",{children:n.name})]}),e.jsx("button",{"aria-label":"Close model use",disabled:o,type:"button",onClick:l,children:e.jsx(Me,{size:16})})]}),t.promotable?null:e.jsx("p",{className:"training-model-use-warning",children:"This run did not pass its frozen Eval. Chat is available for inspection, but the model cannot be promoted."}),e.jsx("p",{className:"training-model-use-note",children:"Open a chat with this trained version. OpenPond selects its managed or Local runtime from the recorded model lineage."}),e.jsxs("div",{className:"training-dialog-actions",children:[e.jsx("button",{className:"training-button secondary",disabled:o,type:"button",onClick:l,children:"Cancel"}),e.jsxs("button",{className:"training-button",disabled:o,type:"button",onClick:i,children:[e.jsx(wn,{size:14}),"Chat now"]})]})]})}const za=new Set(["planning","awaiting_questions","awaiting_plan_approval","paused","applying_source","running_checks","evaluating","awaiting_promotion","opening_pull_request","pull_request_open","reconciling_release","pushing_hosted","running_hosted_checks"]);function Va(t){const{connection:n,profileId:a}=t,[s,l]=c.useState([]),[o,i]=c.useState(!1),[r,u]=c.useState(null),h=c.useRef(null),d=c.useCallback(()=>{if(!n)return Promise.resolve(null);if(h.current)return h.current;i(!0);const b=lt.listCreateImproveRuns(n,{profileId:a,limit:500}).then(g=>(l(g.runs),u(null),g.runs)).catch(g=>(u(g instanceof Error?g.message:String(g)),null)).finally(()=>{h.current===b&&(h.current=null),i(!1)});return h.current=b,b},[n,a]);c.useEffect(()=>{if(!n){l([]),u(null);return}d()},[n,a,d]);const j=c.useMemo(()=>s.some(b=>za.has(b.state)),[s]);return c.useEffect(()=>{if(!n)return;let b=!0,g=null;const C=async()=>{await d(),b&&(g=window.setTimeout(()=>{C()},j?1e3:15e3))};return g=window.setTimeout(()=>{C()},j?1e3:15e3),()=>{b=!1,g!==null&&window.clearTimeout(g)}},[n,j,d]),{runs:s,loading:o,error:r,refresh:d}}function be({title:t,actions:n,children:a}){return e.jsxs("section",{className:"training-detail-section",children:[e.jsxs("div",{className:"training-detail-section-heading",children:[e.jsx("h2",{children:t}),n?e.jsx("div",{children:n}):null]}),e.jsx("div",{className:"training-detail-section-panel",children:a})]})}const qa=new Set(["released","rejected","ready","ready_local","published_hosted","cancelled"]);function On(t){const n=new Map,a=new Set((t.training?.modelProjects??[]).map(i=>i.id)),s=new Map,l=new Map((t.training?.plans??[]).map(i=>[i.id,i.modelId]));for(const i of t.training?.jobs??[]){const r=l.get(i.planId);if(!r)continue;const u=s.get(r)??new Set;u.add(i.id),s.set(r,u)}for(const i of t.runs){if(i.target.kind!=="model"||!i.target.id||!i.target.trainingPlanId)continue;const r=s.get(i.target.id)??new Set;for(const u of t.training?.jobs??[])u.planId===i.target.trainingPlanId&&r.add(u.id);s.set(i.target.id,r)}const o=new Date(0).toISOString();for(const i of t.profile?.agents??[]){const r=Ie("agent",i.id),u=t.profile?.actionCatalog.find(h=>h.agentId===i.id&&h.sourceActionId==="chat"&&h.visibility!=="internal"&&h.visibility!=="debug")??null;n.set(r,{key:r,kind:"agent",id:i.id,ownerProfileId:t.profile?.activeProfile??null,name:i.name||i.id,description:i.enabled?"Enabled Profile Agent":"Disabled Profile Agent",status:i.enabled?"Ready":"Disabled",updatedAt:t.profile?.lastCheck?.checkedAt??o,path:i.path,enabled:i.enabled,runIds:[],conversationId:null,tasksetId:null,trainingRunCount:0,evaluationStatus:"not_run",useActionId:u?.id??null})}for(const i of t.profile?.skills??[]){const r=Ie("skill",i.name);n.set(r,{key:r,kind:"skill",id:i.name,ownerProfileId:t.profile?.activeProfile??null,name:i.name,description:i.description,status:i.validationStatus==="valid"?"Ready":i.validationStatus,updatedAt:o,path:i.path,enabled:i.enabled,runIds:[],conversationId:null,tasksetId:null,trainingRunCount:0,evaluationStatus:"not_run",useActionId:null,skillSource:"profile",skillValidationStatus:i.validationStatus,skillValidationMessages:i.validationMessages,skillSourceHash:i.sourceHash,skillCharCount:i.charCount,skillResourceFiles:i.resourceFiles})}for(const i of t.training?.modelProjects??[]){const u=(t.training?.modelRunDrafts??[]).filter(k=>k.modelId===i.id&&(k.status==="draft"||k.status==="ready_to_run"))[0]??null,h=(t.training?.modelRuns??[]).filter(k=>k.modelId===i.id).sort((k,f)=>f.updatedAt.localeCompare(k.updatedAt)),d=new Set(h.map(k=>k.id)),j=[...s.get(i.id)??[]].filter(k=>{const f=t.training?.jobs.find(y=>y.id===k),S=typeof f?.metadata.modelRunId=="string"?f.metadata.modelRunId:null;return!S||!d.has(S)}).length,b=h[0]??null,g=(t.training?.modelVersions??[]).find(k=>k.modelId===i.id&&k.kind==="base_reference"&&k.version===0)??null,C=Ie("model",i.id);n.set(C,{key:C,kind:"model",id:i.id,ownerProfileId:i.profileId,name:st(i.name,"Untitled Model"),description:i.objective??"No description",status:b?Ha(b.status):u?.status==="ready_to_run"?"Ready to run":u?"Draft":g?"Base ready":"Ready",updatedAt:b?.updatedAt??u?.updatedAt??i.updatedAt,path:b?`tasksets/${b.taskset.id}`:u?.tasksetRef?`tasksets/${u.tasksetRef.id}`:g?`tasksets/${g.taskset.id}`:null,enabled:g?!1:null,runIds:[],conversationId:null,tasksetId:b?.taskset.id??u?.tasksetRef?.id??g?.taskset.id??null,trainingRunCount:h.length+j,evaluationStatus:"not_run",useActionId:null})}for(const i of Ca(t.training)){if(i.taskset.metadata.resourceIntent==="dataset"&&!i.latestPlan&&!i.localModel)continue;const r=t.runs.filter(f=>f.target.kind==="model"&&(i.latestPlan&&f.target.trainingPlanId===i.latestPlan.id||!i.latestPlan&&i.localModel&&f.target.trainingJobId===i.localModel.jobId)).sort((f,S)=>S.updatedAt.localeCompare(f.updatedAt))[0]??null,u=r?.target.kind==="model"&&r.target.id?r.target.id:i.latestPlan?.modelId??i.localModel?.modelId??null;if(!u)continue;const h=Ie("model",u),d=n.get(h),j=r?.target.kind==="model"?r.target.trainingPlanId:null,b=new Set((t.training?.plans??[]).filter(f=>f.modelId===u||j!=null&&f.id===j).map(f=>f.id)),g=(t.training?.jobs??[]).filter(f=>b.has(f.planId)).sort((f,S)=>S.createdAt.localeCompare(f.createdAt)),C=g[0]??null,k=C?t.training?.models.find(f=>f.jobId===C.id)??null:null;n.set(h,{key:h,kind:"model",id:u,ownerProfileId:d?.ownerProfileId??i.taskset.profileId,name:st(d?.name??r?.target.displayName??i.name,"New model"),description:d?.description??i.taskset.objective,status:C?Se(C.status):i.status,updatedAt:C?.updatedAt??i.updatedAt,path:`tasksets/${i.taskset.id}`,enabled:i.localModel?i.localModel.status==="imported"&&!!je(i.localModel):null,runIds:r?[...new Set([...d?.runIds??[],r.id])]:d?.runIds??[],conversationId:null,tasksetId:i.taskset.id,trainingRunCount:Math.max(d?.trainingRunCount??0,g.length),evaluationStatus:Xa(C,k),useActionId:null})}for(const i of t.runs){if(i.target.kind==="configuration"||i.target.kind==="unselected"||i.target.kind==="model"&&!i.tasksetRef&&["cancelled","failed","rejected"].includes(i.state)||i.target.kind==="model"&&!i.target.id)continue;const r=i.target.kind,u=i.target.kind==="model"?i.target.id:i.target.id??i.id,h=Ie(r,u),d=n.get(h),j=r==="agent"?Ja(i,d?.name??null):r==="model"&&a.has(u)?d?.name??i.target.displayName??ln(i):i.target.displayName??d?.name??ln(i),b=r==="model"?st(j,"New model"):j;n.set(h,{key:h,kind:r,id:u,ownerProfileId:d?.ownerProfileId??i.scope.profileId,name:b,description:d?.description??i.objective,status:Wa(i),updatedAt:Ya(d?.updatedAt,i.updatedAt),path:d?.path??i.plan?.sourcePlan[0]?.path??null,enabled:d?.enabled??null,runIds:[...new Set([...d?.runIds??[],i.id])],conversationId:i.scope.conversationId??d?.conversationId??null,tasksetId:i.target.kind==="model"?i.tasksetRef?.id??d?.tasksetId??null:null,trainingRunCount:r==="model"?Math.max(d?.trainingRunCount??0,s.get(u)?.size??0):d?.trainingRunCount??0,evaluationStatus:Qa(i)??d?.evaluationStatus??"not_run",useActionId:d?.useActionId??null})}return[...n.values()].sort((i,r)=>{const u=Number(sn(i,t.runs))-Number(sn(r,t.runs));return u!==0?-u:r.updatedAt.localeCompare(i.updatedAt)||i.name.localeCompare(r.name)})}function Ha(t){return t==="prepared"?"Prepared":t==="running"?"Running":t==="succeeded"?"Rollout complete":t==="failed"?"Failed":"Cancelled"}function Ie(t,n){return`${t}:${n}`}function Ka(t){return t==="agent"?"Agents":t==="skill"?"Skills":t==="extension"?"Extensions":"Models"}function Ga(t,n){const a=new Set(t.runIds);return n.filter(s=>a.has(s.id)).sort((s,l)=>l.updatedAt.localeCompare(s.updatedAt))}function sn(t,n){const a=new Set(t.runIds);return n.some(s=>a.has(s.id)&&!qa.has(s.state))}function ln(t){return`${t.operation==="improve"?"Improve":"Create"} ${t.target.kind}`}function Ja(t,n){const a=on(t.target.displayName);if(a)return a;const s=on(n);if(s)return s;const l=t.objective.replace(/^(?:please\s+)?(?:create|make|build|improve)\s+(?:an?\s+)?agent\s+(?:that\s+|to\s+)?/i,"").trim(),o=st(l,"New agent");return o==="New agent"?o:`Agent for ${o}`}function on(t){const n=t?.trim();if(!n)return null;const a=n.toLowerCase().replace(/\s+/g," ");return/^(?:create|creating|improve|improving|new) (?:an )?agent$/.test(a)?null:n}function Wa(t){return t.state.replaceAll("_"," ")}function Qa(t){const n=t.evaluationReceipts.filter(a=>a.subject==="candidate"||a.subject==="post_release");return n.length?n.some(a=>a.status==="failed"||a.status==="blocked"||a.publishGate==="failed")?"failed":n.every(a=>a.status==="passed"&&a.publishGate!=="failed")?"passed":null:null}function Xa(t,n){return!t||!(!!(n&&je(n))||t.metadata.frozenEvaluationComplete===!0||!!n?.frozenEvaluationArtifactId||!!n?.managedServing?.customerBindingAllowed)?"not_run":!!(n&&(je(n)||Tn(n)))?"passed":"failed"}function Ya(t,n){return t&&t.localeCompare(n)>=0?t:n}function Za({agentId:t,evals:n,onAttach:a,onCreate:s}){const l=c.useMemo(()=>n.filter(r=>r.agentId===null||r.agentId===t),[t,n]),[o,i]=c.useState(l[0]?.id??"");return c.useEffect(()=>{l.some(r=>r.id===o)||i(l[0]?.id??"")},[l,o]),e.jsxs("div",{className:"labs-eval-actions",children:[e.jsxs("button",{className:"training-button secondary",type:"button",onClick:s,children:[e.jsx(da,{size:13}),"Create Eval"]}),l.length?e.jsxs(e.Fragment,{children:[e.jsx(De,{compact:!0,searchable:!0,label:"Existing Eval",options:l.map(r=>({value:r.id,label:r.name,shortLabel:r.name,description:r.path})),value:o,onChange:i}),e.jsx("button",{className:"training-button secondary",disabled:!o,type:"button",onClick:()=>a(o),children:"Add Eval"})]}):null]})}function re({label:t,value:n=t}){return e.jsx("span",{className:`labs-status-badge ${Bn(n)}`,children:t})}function Bn(t){const n=t.trim().toLowerCase().replaceAll("_"," ");return n.includes("ready")||n.includes("passed")||n.includes("succeeded")||n.includes("published")||n.includes("released")||n.includes("merged")||n.includes("imported")?"positive":n.includes("planning")||n.includes("applying")||n.includes("running")||n.includes("evaluating")||n.includes("pushing")?"info":n.includes("awaiting")||n.includes("paused")||n.includes("pr open")||n.includes("blocked")||n.includes("review")||n.includes("dirty")||n.includes("pending")?"warning":n.includes("failed")||n.includes("rejected")||n.includes("closed")||n.includes("error")||n.includes("disabled")?"negative":"neutral"}function $t({decorative:t=!1,label:n,size:a="default",tone:s,value:l=n}){return e.jsx("span",{"aria-hidden":t||void 0,"aria-label":t?void 0:n,className:`labs-status-dot ${s??Bn(l)} ${a}`,role:t?void 0:"status",title:n})}function es({candidate:t,diff:n,error:a,run:s,onApplyCandidate:l,onOpenFiles:o,onRejectCandidate:i}){const[r,u]=c.useState(null),d=c.useMemo(()=>s.evaluationReceipts.filter(f=>f.candidateId===t.id),[t.id,s.evaluationReceipts]).filter(f=>f.subject==="candidate"),b=d.length>0&&d.every(f=>f.status==="passed"&&f.publishGate!=="failed")&&(s.state==="awaiting_promotion"||s.state==="blocked"&&!!s.localProfileCommit),g=s.state==="reconciling_release",C=n?.filesChanged??t.git?.changedPaths.length??0;async function k(f,S){if(!r){u(f);try{await S()}finally{u(null)}}}return e.jsxs("div",{className:"labs-change-page",children:[s.blockedReason?e.jsx("div",{className:"labs-change-message negative",children:s.blockedReason}):null,e.jsxs("div",{className:"labs-change-timeline",children:[e.jsx("article",{className:"labs-change-timeline-item",children:e.jsxs("div",{className:"labs-change-card",children:[e.jsx("header",{className:"labs-change-card-header",children:e.jsx("span",{className:"labs-change-timeline-label",children:"Request"})}),e.jsxs("div",{className:"labs-change-card-body",children:[e.jsx("h3",{children:s.objective}),e.jsx("p",{children:"This is the behavior the Agent update should improve."})]})]})}),e.jsx("article",{className:"labs-change-timeline-item",children:e.jsxs("div",{className:"labs-change-card",children:[e.jsxs("header",{className:"labs-change-card-header",children:[e.jsx("span",{className:"labs-change-timeline-label",children:"Changes"}),e.jsx("span",{children:Pt(C)})]}),e.jsxs("div",{className:"labs-change-card-body",children:[e.jsx("h3",{children:"Drafted update"}),e.jsx("p",{children:ts(t,n,a)})]}),e.jsx("footer",{className:"labs-change-card-footer end",children:e.jsx("button",{className:"training-button secondary",disabled:!!a,title:a??void 0,type:"button",onClick:o,children:a?"Files unavailable":`Files${C?` (${C})`:""}`})})]})}),e.jsx("article",{className:"labs-change-timeline-item",children:e.jsxs("div",{className:"labs-change-card",children:[e.jsxs("header",{className:"labs-change-card-header",children:[e.jsx("span",{className:"labs-change-timeline-label",children:"Evals"}),e.jsx("span",{children:ns(d)})]}),e.jsx("div",{className:"labs-change-evals",children:d.length?d.map(f=>e.jsxs("div",{className:"labs-change-eval",children:[e.jsxs("div",{children:[e.jsx("strong",{children:f.summary??"Agent Evals"}),e.jsx("span",{children:f.summaryCounts?`${f.summaryCounts.passed}/${f.summaryCounts.total} passed`:f.status})]}),e.jsx(re,{label:f.status,value:f.status})]},f.id)):e.jsx("div",{className:"labs-change-empty",children:"Agent Evals have not finished yet."})})]})}),e.jsx("article",{className:"labs-change-timeline-item",children:e.jsxs("div",{className:"labs-change-card",children:[e.jsx("header",{className:"labs-change-card-header",children:e.jsx("span",{className:"labs-change-timeline-label",children:"Apply"})}),e.jsxs("div",{className:"labs-change-card-body",children:[e.jsx("h3",{children:"Save this Agent update"}),e.jsx("p",{children:"Applying the update changes the Agent in your Profile, then runs its Evals again."})]}),e.jsxs("footer",{className:"labs-change-card-footer",children:[e.jsxs("span",{className:"labs-change-footer-status",children:[e.jsx($t,{label:rn(s),value:s.state}),rn(s)]}),e.jsxs("div",{className:"labs-change-actions",children:[e.jsx("button",{className:"training-button secondary",disabled:!!r||g||s.state!=="awaiting_promotion",type:"button",onClick:()=>{k("reject",()=>i(s,t.id))},children:r==="reject"?"Keeping current version":"Keep current version"}),e.jsx("button",{className:"training-button",disabled:!b||!!r||g,type:"button",onClick:()=>{k("apply",()=>l(s,t.id))},children:g||r==="apply"?"Applying":s.state==="blocked"?"Re-run Evals":"Apply update"})]})]})]})})]})]})}function Pt(t){return`${t} ${t===1?"file":"files"}`}function ts(t,n,a){if(a)return a;const s=n?.filesChanged??t.git?.changedPaths.length??0;return s?n?`${Pt(s)} drafted · +${n.additions} −${n.deletions}`:`${Pt(s)} drafted for this Agent. Open Files to review the changes.`:"The drafted Agent update is ready, but no file summary is available yet."}function ns(t){if(!t.length)return"Waiting for Agent Evals";const n=t.reduce((s,l)=>({passed:s.passed+(l.summaryCounts?.passed??0),tests:s.tests+(l.summaryCounts?.total??0)}),{passed:0,tests:0});return n.tests>0?`${n.passed}/${n.tests} Evals passed`:`${t.filter(s=>s.status==="passed").length}/${t.length} Eval results passed`}function rn(t){return t.state==="awaiting_promotion"?"Ready to apply":t.state==="reconciling_release"?"Applying update":t.state==="released"?"Update applied":t.state==="rejected"?"Current version kept":t.state==="blocked"?t.localProfileCommit?"Needs verification":"Blocked":t.state.replaceAll("_"," ")}function as({runs:t,onReview:n}){return t.length?e.jsx("div",{className:"training-table-wrap",children:e.jsxs("table",{className:"training-data-table labs-agent-change-history",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Change"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Evals"}),e.jsx("th",{children:"Updated"})]})}),e.jsx("tbody",{children:t.map(a=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("button",{type:"button",onClick:()=>n(a),children:[e.jsx("strong",{children:a.objective}),e.jsx("span",{children:is(a)})]})}),e.jsx("td",{children:e.jsx(re,{label:ls(a),value:a.state})}),e.jsx("td",{children:ss(a)}),e.jsx("td",{children:$e(a.updatedAt)})]},a.id))})]})}):e.jsx("div",{className:"training-run-placeholder",children:"No changes yet."})}function ss(t){const n=[...t.candidates].reverse().find(l=>l.target.kind===t.target.kind);if(!n)return"—";const a=t.evaluationReceipts.filter(l=>l.candidateId===n.id&&l.subject==="candidate"),s=a.reduce((l,o)=>({passed:l.passed+(o.summaryCounts?.passed??0),tests:l.tests+(o.summaryCounts?.total??0)}),{passed:0,tests:0});return s.tests>0?`${s.passed}/${s.tests} passed`:a[0]?.status??"Not run"}function is(t){return`${`${t.target.kind[0].toUpperCase()}${t.target.kind.slice(1)}`} ${t.operation==="improve"?"improvement":"creation"}`}function ls(t){const n=t.state;return t.state==="planning"?"Planning":t.state==="awaiting_questions"?"Waiting for input":t.state==="awaiting_plan_approval"?"Plan ready":t.state==="applying_source"?"Saving Agent":t.state==="running_checks"||t.state==="evaluating"?"Running Evals":t.state==="awaiting_promotion"?"Update ready":t.state==="opening_pull_request"?"Preparing review":t.state==="pull_request_open"?"Review open":t.state==="reconciling_release"?"Applying update":t.state==="released"?"Updated":t.state==="rejected"?"Current version kept":t.state==="paused"?"Paused":t.state==="ready"||t.state==="ready_local"?"Ready":t.state==="pushing_hosted"?"Saving to hosted Profile":t.state==="running_hosted_checks"?"Running hosted Evals":t.state==="published_hosted"?"Published":t.state==="cancelled"?"Cancelled":t.state==="blocked"?"Blocked":t.state==="failed"?"Failed":n.replaceAll("_"," ")}function Un({series:t}){const n=Math.max(1,...t.map(a=>a.tokens));return e.jsxs("div",{className:"labs-evaluation-comparison","aria-label":"Evaluation comparison",children:[e.jsx(dn,{title:"Foreground tokens",description:"Provider-reported input and output tokens for evaluated tasks.",direction:"Lower is better",series:t.map(a=>({id:a.id,label:a.label,value:a.tokens,display:a.tokens.toLocaleString(),ratio:a.tokens/n}))}),e.jsx(dn,{title:"Quality",description:"Share of evaluated tasks that passed the pinned graders.",direction:"Higher is better",series:t.map(a=>({id:a.id,label:a.label,value:a.passRate,display:`${Math.round(a.passRate*100)}%`,ratio:a.passRate}))}),e.jsx(os,{series:t})]})}function os({series:t}){return e.jsxs("section",{className:"labs-evaluation-chart",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("h4",{children:"Token mix"}),e.jsx("p",{children:"Input and output tokens inside each measured foreground total."})]}),e.jsxs("div",{className:"labs-evaluation-token-legend","aria-label":"Token legend",children:[e.jsx("span",{children:"Input"}),e.jsx("span",{children:"Output"})]})]}),e.jsx("div",{className:"labs-evaluation-token-mix",children:t.map((n,a)=>{const s=Math.max(1,n.inputTokens+n.outputTokens);return e.jsxs("div",{"data-series-index":a,children:[e.jsxs("div",{className:"labs-evaluation-token-label",children:[e.jsx("span",{children:n.label}),e.jsx("strong",{children:n.tokens.toLocaleString()})]}),e.jsxs("div",{className:"labs-evaluation-token-stack","aria-hidden":"true",children:[e.jsx("span",{style:{width:`${n.inputTokens/s*100}%`}}),e.jsx("span",{style:{width:`${n.outputTokens/s*100}%`}})]}),e.jsxs("small",{children:[n.inputTokens.toLocaleString()," input · ",n.outputTokens.toLocaleString()," output"]})]},n.id)})})]})}function dn({title:t,description:n,direction:a,series:s}){return e.jsxs("section",{className:"labs-evaluation-chart",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("h4",{children:t}),e.jsx("p",{children:n})]}),e.jsx("span",{className:"labs-evaluation-direction",children:a})]}),e.jsx("div",{className:"labs-evaluation-chart-series",children:s.map((l,o)=>e.jsxs("div",{className:"labs-evaluation-chart-row","data-series-index":o,children:[e.jsxs("div",{className:"labs-evaluation-chart-label",children:[e.jsx("span",{children:l.label}),e.jsx("strong",{children:l.display})]}),e.jsx("div",{className:"labs-evaluation-chart-track","aria-hidden":"true",children:e.jsx("span",{style:{width:`${Math.max(2,Math.min(100,l.ratio*100))}%`}})})]},l.id))})]})}const rs=["baseline","adaptation","candidate_adaptation","candidate"];function Fn(t){const n=new Map;for(const a of t){const s=`${a.phase}\0${a.taskId}`,l=n.get(s);(!l||a.startedAt>l.startedAt||a.startedAt===l.startedAt&&a.attemptId>l.attemptId)&&n.set(s,a)}return[...n.values()]}function zn(t){const n=Fn(t.attempts);return Object.fromEntries(rs.map(a=>{const s=n.filter(o=>o.phase===a),l=s.map(o=>o.costUsd).filter(o=>o!==null);return[a,{inputTokens:s.reduce((o,i)=>o+i.inputTokens,0),outputTokens:s.reduce((o,i)=>o+i.outputTokens,0),totalTokens:s.reduce((o,i)=>o+i.totalTokens,0),costUsd:l.length?l.reduce((o,i)=>o+i,0):null}]}))}function Be(t){const n=Fn(t.attempts??[]),{summary:a,pairs:s}=ca({attempts:n});return{...a,pairs:s,baselinePassedCount:s.filter(l=>l.baseline.passed).length,refinedPassedCount:s.filter(l=>l.refined.passed).length,cohorts:{adaptation:a.cohorts.adaptation,held_out:a.cohorts.heldOut}}}function ds({workproduct:t,training:n,readOnly:a,defaultModel:s,initialModel:l,providerSettings:o,onClose:i,onOpenEntry:r,onToast:u}){const[h,d]=c.useState("high"),[j,b]=c.useState(l??s),[g,C]=c.useState(!1),f=c.useMemo(()=>(n.payload?.modelRuns??[]).filter(m=>m.modelId===t.id&&m.kind==="evaluation"&&m.evaluation?.benchmarkId==="harness-refiner").sort((m,T)=>T.updatedAt.localeCompare(m.updatedAt)),[n.payload?.modelRuns,t.id])[0]??null,S=us(f?.receipt??null),y=S?zn(S):null,w=S?Be(S):null,R=cs(f?.receipt??null),p=(n.payload?.tasksets??[]).find(m=>m.benchmark?.definitionId==="harness-refiner"),_=c.useMemo(()=>hs(o,j),[j,o]);async function x(){C(!0);try{const m=await n.actions.startHarnessRefinerBenchmark(t.id,j,h);if(!m)throw new Error("Benchmark start returned no Model Run.");r(`model-run:${m.id}`)}catch(m){u(m instanceof Error?m.message:String(m),"error")}finally{C(!1)}}return e.jsxs(_e,{ariaLabel:`Benchmark ${t.name}`,backdropClassName:"labs-rename-backdrop",className:"labs-rename-dialog labs-model-benchmark-dialog",dismissDisabled:g,onClose:i,children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Benchmark model"}),e.jsx("p",{children:"Run a controlled evaluation and save it in this Model's history."})]}),e.jsx("button",{"aria-label":"Close benchmark setup",disabled:g,type:"button",onClick:i,children:e.jsx(Me,{size:16})})]}),e.jsx("div",{className:"labs-model-benchmark-dialog-body",children:e.jsxs("article",{className:"labs-model-benchmark-card",children:[e.jsxs("div",{className:"labs-model-benchmark-heading",children:[e.jsxs("div",{children:[e.jsx("h3",{children:"Harness Refiner 08112026"}),e.jsx("p",{children:"Tests whether every task uses fewer foreground tokens after an evidence-driven Harness update. Quality is measured separately. Each run is watched to terminal state with a $10 maximum provider spend."})]}),f?e.jsx(re,{label:S?cn(S):R?"Inconclusive":Se(f.status),value:S?w?.passed?"succeeded":"failed":R?.terminalClassification??f.status}):e.jsx(re,{label:"Not run",value:"not_run"})]}),S?e.jsxs(e.Fragment,{children:[e.jsx(Un,{series:[{id:"baseline",label:"Baseline",inputTokens:y.baseline.inputTokens,outputTokens:y.baseline.outputTokens,tokens:y.baseline.totalTokens,passRate:S.quality.baselinePassRate,costUsd:y.baseline.costUsd},{id:"candidate",label:"Candidate Harness",inputTokens:y.candidate.inputTokens,outputTokens:y.candidate.outputTokens,tokens:y.candidate.totalTokens,passRate:S.quality.candidatePassRate,costUsd:y.candidate.costUsd}]}),e.jsxs("div",{className:"labs-model-benchmark-result-row",children:[e.jsx("span",{children:cn(S)}),e.jsx("strong",{children:ps(S)}),e.jsx("button",{className:"training-button secondary labs-compact-button",type:"button",onClick:()=>f&&r(`model-run:${f.id}`),children:"View run"})]})]}):R?e.jsxs("div",{className:"labs-model-benchmark-result-row",children:[e.jsx("span",{children:"Inconclusive · candidate replay skipped"}),e.jsxs("strong",{children:[R.attempts.length," attempts · $",R.budget.observedSpendUsd.toFixed(4)]}),e.jsx("button",{className:"training-button secondary labs-compact-button",type:"button",onClick:()=>f&&r(`model-run:${f.id}`),children:"View run"})]}):f?e.jsxs("button",{className:"labs-model-benchmark-running",type:"button",onClick:()=>r(`model-run:${f.id}`),children:[e.jsx("span",{children:f.failure??(f.evaluationProgress?`${f.evaluationProgress.stage.replaceAll("_"," ")} · ${f.evaluationProgress.completedAttempts}/${f.evaluationProgress.totalAttempts} attempts`:"The benchmark is running through its pinned stages.")}),e.jsx("strong",{children:$e(f.updatedAt)})]}):e.jsx("p",{className:"labs-model-benchmark-empty",children:p?"No result yet. The shipped 20-case Taskset is ready.":"The built-in Harness Refiner Taskset is loading."}),a?null:e.jsxs("div",{className:"labs-model-benchmark-controls",children:[e.jsxs("label",{className:"labs-model-benchmark-model",children:[e.jsx("span",{children:"Model"}),e.jsx("select",{"aria-label":"Benchmark model",value:Et(j),onChange:m=>{const T=ms(m.target.value);T&&b(T)},children:_.map(m=>e.jsx("optgroup",{label:m.label,children:m.models.map(T=>e.jsx("option",{value:T.value,children:T.label},T.value))},m.providerId))})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Effort"}),e.jsxs("select",{value:h,onChange:m=>d(m.target.value),children:[e.jsx("option",{value:"low",children:"Low"}),e.jsx("option",{value:"medium",children:"Medium"}),e.jsx("option",{value:"high",children:"High"})]})]}),e.jsx("button",{className:"training-button primary",disabled:g||f?.status==="running",type:"button",onClick:()=>{x()},children:g?"Starting…":"Run Refiner Benchmark"})]})]})})]})}function cs(t){return t&&typeof t=="object"&&"schemaVersion"in t&&t.schemaVersion==="openpond.modelEvaluationStopReceipt.v1"?t:null}function us(t){return t&&typeof t=="object"&&"schemaVersion"in t&&t.schemaVersion==="openpond.modelEvaluationReceipt.v1"?t:null}function hs(t,n){const a=_n(t,{includeUnavailable:!1}).flatMap(l=>{const o=$n(l.value,t).map(i=>({value:Et({providerId:l.value,modelId:i.value}),label:i.label}));return o.length?[{providerId:l.value,label:l.label,models:o}]:[]}),s=Et(n);return a.some(l=>l.models.some(o=>o.value===s))?a:[{providerId:n.providerId,label:n.providerId,models:[{value:s,label:zt(n.modelId,t,n.providerId)}]},...a]}function Et(t){return JSON.stringify([t.providerId,t.modelId])}function ms(t){try{const n=JSON.parse(t);return!Array.isArray(n)||n.length!==2||typeof n[0]!="string"||typeof n[1]!="string"?null:{providerId:n[0],modelId:n[1]}}catch{return null}}function ps(t){const n=Be(t),a=n.tokenDelta>0?"+":"",s=n.tokenDeltaPercent===null?"":` · ${a}${n.tokenDeltaPercent.toFixed(1)}%`;return`${a}${n.tokenDelta.toLocaleString()} tokens${s}`}function cn(t){const n=Be(t);return`${n.passedTaskCount}/${n.comparedTaskCount} efficiency passes`}function qt(t){if(!t)return[];const n=new Map;for(const a of[...t.modelTasksets??[],...t.tasksets??[]])n.set(`${a.id}:${a.revision}:${a.contentHash}`,a);return[...n.values()]}function ct(t,n){return(n?.modelRuns??[]).filter(a=>a.modelId===t.id).sort((a,s)=>s.updatedAt.localeCompare(a.updatedAt))??[]}function ut(t,n,a){if(!a)return[];const s=n.filter(i=>i.target.kind==="model"&&i.target.id===t.id),l=new Set(s.flatMap(i=>i.target.kind==="model"&&i.target.trainingPlanId?[i.target.trainingPlanId]:[])),o=new Set(s.flatMap(i=>i.tasksetRef?[i.tasksetRef.id]:[]));return t.tasksetId&&o.add(t.tasksetId),a.plans.filter(i=>i.modelId===t.id||l.has(i.id)||i.modelId===null&&o.has(i.tasksetId)).sort((i,r)=>r.createdAt.localeCompare(i.createdAt))}function We(t,n,a){if(!a)return[];const s=new Set(ut(t,n,a).map(o=>o.id)),l=new Set(ct(t,a).map(o=>o.id));return a.jobs.filter(o=>s.has(o.planId)||typeof o.metadata.modelRunId=="string"&&l.has(o.metadata.modelRunId)).sort((o,i)=>i.createdAt.localeCompare(o.createdAt))}function bs(t,n,a){if(!a)return[];const s=new Set(ut(t,n,a).map(l=>l.tasksetId));for(const l of n)l.target.kind==="model"&&l.target.id===t.id&&l.tasksetRef&&s.add(l.tasksetRef.id);return t.tasksetId&&s.add(t.tasksetId),qt(a).filter(l=>s.has(l.id))}function Qe(t,n,a){if(!a)return[];const s=ut(t,n,a),l=new Map(s.map(d=>[d.id,d])),o=We(t,n,a),i=new Map(o.map(d=>[d.id,d])),r=Vn(t,n,a),u=new Set(o.map(d=>d.id));return a.models.filter(d=>d.modelId===t.id||u.has(d.jobId)).sort((d,j)=>d.importedAt.localeCompare(j.importedAt)).map((d,j)=>{const b=i.get(d.jobId)??null;return{lineage:d,number:j+1,job:b,plan:b?l.get(b.planId)??null:null,taskset:qt(a).find(g=>g.id===d.tasksetId)??null,current:r?.modelArtifactLineageId===d.id}}).sort((d,j)=>j.number-d.number)}function Vn(t,n,a){if(!a)return null;const s=new Set(We(t,n,a).map(i=>i.id)),l=new Set(a.models.filter(i=>i.modelId===t.id||s.has(i.jobId)).map(i=>i.id)),o=new Set(n.flatMap(i=>i.target.kind==="model"&&i.target.id===t.id&&i.tasksetRef?[i.tasksetRef.id]:[]));return t.tasksetId&&o.add(t.tasksetId),a.modelBindings.filter(i=>i.status==="active"&&i.role==="chat_manual"&&(i.roleTargetId===t.id||o.has(i.roleTargetId)||i.roleTargetId==="default"&&l.has(i.modelArtifactLineageId))).sort((i,r)=>r.promotedAt.localeCompare(i.promotedAt))[0]??null}function gs({workproduct:t,runs:n,training:a,onOpenDataset:s,onOpenEntry:l,onResumeDraft:o,readOnly:i=!1}){const r=a.payload,u=c.useMemo(()=>We(t,n,r),[n,r,t]),h=c.useMemo(()=>Qe(t,n,r),[n,r,t]),d=c.useMemo(()=>ut(t,n,r),[n,r,t]),j=c.useMemo(()=>new Map(d.map(x=>[x.id,x])),[d]),b=ct(t,r),g=qt(r),C=c.useMemo(()=>(r?.modelRunDrafts??[]).filter(x=>x.modelId===t.id&&(x.status==="draft"||x.status==="ready_to_run")).sort((x,m)=>m.updatedAt.localeCompare(x.updatedAt)),[r?.modelRunDrafts,t.id]),k=c.useMemo(()=>Ht(u,h,b,i?[]:C),[C,u,b,i,h]),[f,S]=c.useState(!1),y=f?k:k.slice(0,5),w=k.filter(x=>!x.draft).length,R=k.length-w,p=c.useMemo(()=>{let x=w;const m=new Map;for(const T of k)T.draft||(m.set(T.key,x),x-=1);return m},[k,w]);function _(x){if(x.draft){o(x.draft.id);return}l(x.key)}return e.jsxs("section",{className:"labs-model-version-index","aria-label":"Model runs",children:[e.jsxs("header",{className:"labs-model-section-intro",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Recent runs"}),e.jsx("p",{children:"Training and evaluation history, including unfinished drafts."})]}),e.jsxs("span",{children:[w," ",w===1?"run":"runs",R?` · ${R} ${R===1?"draft":"drafts"}`:""]})]}),e.jsx("div",{className:"training-table-wrap",children:e.jsxs("table",{className:"training-data-table labs-model-runs-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Run or draft"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Method"}),e.jsx("th",{children:"Dataset"}),e.jsx("th",{children:"Result"}),e.jsx("th",{children:"Updated"})]})}),e.jsxs("tbody",{children:[k.length?null:e.jsx("tr",{children:e.jsx("td",{colSpan:6,children:e.jsx("div",{className:"training-run-placeholder",children:"No runs or drafts yet."})})}),y.map(x=>{const m=p.get(x.key)??null,T=x.version?.plan??(x.job?j.get(x.job.planId)??null:null),V=x.version?.taskset??g.find($=>$.id===(x.draft?.tasksetRef?.id??x.lifecycleRun?.taskset.id??T?.tasksetId))??null,E=x.version;return e.jsxs("tr",{className:x.draft?"labs-model-run-draft":void 0,onClick:()=>_(x),children:[e.jsx("td",{children:e.jsxs("button",{className:"labs-version-row-button",type:"button",onClick:$=>{$.stopPropagation(),_(x)},children:[e.jsx("strong",{children:x.draft?x.draft.title||"Run draft":`Run ${m}`}),e.jsx("small",{children:x.draft?x.draft.status==="ready_to_run"?"Review and run":"Resume draft":E?`Created Version ${E.number}`:x.lifecycleRun?.kind==="evaluation"?"Evaluation":x.lifecycleRun?.kind==="rollout_smoke"?"Preflight rollout":"Training"})]})}),e.jsx("td",{children:e.jsx(re,{label:x.draft?x.draft.status==="ready_to_run"?"Ready to run":"Draft":x.lifecycleRun?Se(x.lifecycleRun.status):x.job?Se(x.job.status):"Not started",value:x.draft?.status??x.lifecycleRun?.status??x.job?.status??"not_run"})}),e.jsx("td",{children:x.lifecycleRun?.kind==="evaluation"?"Evaluation":Oe(x.draft?.method??x.lifecycleRun?.method??T?.recipe.method)}),e.jsx("td",{children:V?e.jsx("button",{className:"labs-version-dataset-link",type:"button",onClick:$=>{$.stopPropagation(),s(V.id)},children:V.name}):"Unavailable"}),e.jsx("td",{children:xs(x)}),e.jsx("td",{children:$e(x.lifecycleRun?.updatedAt??x.draft?.updatedAt??E?.lineage.importedAt??x.job?.updatedAt??"")})]},x.key)})]})]})}),k.length>5?e.jsx("div",{className:"labs-model-run-list-actions",children:e.jsx("button",{className:"training-button secondary labs-compact-button",type:"button",onClick:()=>S(x=>!x),children:f?"Show latest 5":`Show all ${k.length} activities`})}):null]})}function fs({workproduct:t,runs:n,training:a,onOpenDataset:s,onOpenEntry:l,onToast:o,readOnly:i=!1}){const r=a.payload,u=c.useMemo(()=>Qe(t,n,r),[n,r,t]),h=Vn(t,n,r);async function d(b){if(i)return;const g=u.find(k=>k.lineage.id===b);if(!g||!je(g.lineage)||!window.confirm(`Set Version ${g.number} as active for ${t.name}?`))return;const C=await a.actions.bindModel(g.lineage.id,"chat_manual",t.id);o(C?`Version ${g.number} is now active.`:"The active Version could not be changed.",C?"success":"error")}async function j(b,g){if(i)return;const C=await a.actions.setModelPinned(b,g);o(C?g?"Version pinned.":"Version unpinned.":"Version pin could not be changed.",C?"success":"error")}return e.jsxs("section",{className:"labs-model-version-index","aria-label":"Model versions",children:[e.jsxs("header",{className:"labs-model-section-intro",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Versions"}),e.jsx("p",{children:"Trained outputs that can be evaluated, activated, and downloaded."})]}),e.jsxs("span",{children:[u.length," trained"]})]}),e.jsx("div",{className:"training-table-wrap",children:e.jsxs("table",{className:"training-data-table labs-model-versions-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Version"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Training"}),e.jsx("th",{children:"Dataset"}),e.jsx("th",{children:"Evaluation"}),e.jsx("th",{children:"Created"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsxs("tbody",{children:[u.length?null:e.jsx("tr",{children:e.jsx("td",{colSpan:7,children:e.jsx("div",{className:"training-run-placeholder",children:"No trained Versions yet. A successful run will appear here."})})}),u.map(b=>{const g=h?.modelArtifactLineageId===b.lineage.id;return e.jsxs("tr",{onClick:()=>l(b.job?`job:${b.job.id}`:`version:${b.lineage.id}`),children:[e.jsx("td",{children:e.jsxs("button",{className:"labs-version-row-button",type:"button",onClick:()=>l(b.job?`job:${b.job.id}`:`version:${b.lineage.id}`),children:[e.jsxs("strong",{children:["Version ",b.number]}),e.jsx("small",{children:ys(b.lineage.id)})]})}),e.jsx("td",{children:e.jsx(vs,{job:b.job,version:b})}),e.jsx("td",{children:Oe(b.plan?.recipe.method)}),e.jsx("td",{children:b.taskset?e.jsx("button",{className:"labs-version-dataset-link",type:"button",onClick:C=>{C.stopPropagation(),s(b.taskset.id)},children:b.taskset.name}):"Unavailable"}),e.jsx("td",{children:e.jsx(js,{job:b.job,version:b})}),e.jsx("td",{children:$e(b.lineage.importedAt)}),e.jsx("td",{children:e.jsxs("div",{className:"training-table-actions",children:[e.jsx("button",{"aria-pressed":b.lineage.pinned||g,className:"labs-version-icon-button",disabled:i||g,title:g?"The active Version stays pinned":b.lineage.pinned?"Unpin Version":"Pin Version",type:"button",onClick:C=>{C.stopPropagation(),j(b.lineage.id,!b.lineage.pinned)},children:e.jsx(ua,{size:14})}),b.current?null:e.jsx("button",{className:"training-button secondary",disabled:i||!je(b.lineage),type:"button",onClick:C=>{C.stopPropagation(),d(b.lineage.id)},children:"Activate"}),e.jsx("button",{"aria-label":`Download Version ${b.number}`,className:"labs-version-icon-button",type:"button",onClick:C=>{C.stopPropagation(),a.actions.downloadModelPackage(b.lineage.id)},children:e.jsx(ot,{size:14})})]})})]},b.lineage.id)})]})]})})]})}function Tl(t,n,a=[]){const s=new Map(n.flatMap(i=>i.job?[[i.job.id,i]]:[])),l=t.map(i=>({key:`job:${i.id}`,job:i,version:s.get(i.id)??null,draft:null})),o=new Set(t.map(i=>i.id));for(const i of n)i.job&&o.has(i.job.id)||l.push({key:`version:${i.lineage.id}`,job:i.job,version:i,draft:null});for(const i of a)l.push({key:`draft:${i.id}`,job:null,version:null,draft:i});return l.sort((i,r)=>un(r).localeCompare(un(i)))}function Ht(t,n,a,s=[]){const l=new Map(t.flatMap(h=>typeof h.metadata.modelRunId=="string"?[[h.metadata.modelRunId,h]]:[])),o=new Map(n.flatMap(h=>h.job?[[h.job.id,h]]:[])),i=new Map(n.map(h=>[h.lineage.id,h])),r=new Set,u=a.map(h=>{const d=l.get(h.id)??t.find(j=>j.id===h.id)??null;return d&&r.add(d.id),{key:`model-run:${h.id}`,job:d,lifecycleRun:h,version:(d?o.get(d.id)??null:null)??(h.adapterArtifactLineageId?i.get(h.adapterArtifactLineageId)??null:null),draft:null}});for(const h of t)r.has(h.id)||u.push({key:`job:${h.id}`,job:h,lifecycleRun:null,version:o.get(h.id)??null,draft:null});for(const h of s)u.push({key:`draft:${h.id}`,job:null,lifecycleRun:null,version:null,draft:h});return u.sort((h,d)=>hn(d).localeCompare(hn(h)))}function un(t){return t.version?.lineage.importedAt??t.draft?.updatedAt??t.job?.updatedAt??t.job?.createdAt??""}function hn(t){return t.draft?.updatedAt??t.lifecycleRun?.updatedAt??t.job?.updatedAt??t.job?.createdAt??""}function xs(t){if(t.draft)return t.draft.status==="ready_to_run"?"Review and run":"Resume draft";if(t.version)return`Version ${t.version.number}`;if(t.lifecycleRun?.kind==="evaluation"&&t.lifecycleRun.receipt?.schemaVersion==="openpond.modelEvaluationReceipt.v1"){const n=t.lifecycleRun.receipt.foregroundTokenDelta;return`${n>0?"+":""}${n.toLocaleString()} tokens`}return t.lifecycleRun?.reward?`Reward ${t.lifecycleRun.reward.raw.toFixed(3)}`:t.lifecycleRun?.status==="failed"||t.job?.status==="failed"?"Failed":t.lifecycleRun?.status==="succeeded"||t.job?.status==="succeeded"?"Completed":"No output"}function js({job:t,version:n}){const a=n?!!je(n.lineage)||t?.metadata.frozenEvaluationComplete===!0||!!n.lineage.frozenEvaluationArtifactId||!!n.lineage.managedServing?.customerBindingAllowed:!1,s=n?!!je(n.lineage)||Tn(n.lineage):!1,l=n?a?s?"Passed":"Failed":"Not run":t&&["queued","starting","running","cancelling","reconciling"].includes(t.status)?"Pending":"Not run",o=n?s?"passed":a?"failed":"not_run":"not_run";return e.jsx(re,{label:l,value:o})}function vs({job:t,version:n}){const a=!!(t&&["queued","starting","running","cancelling","reconciling"].includes(t.status));return e.jsx(re,{label:n?n.current?"Active":"Available":a?"Pending":"Not created",value:n?n.current?"current":"ready":a?"running":"not_run"})}function ys(t){const n=t.replace(/^baseline_run_/,"").replace(/^(?:training_job_|lineage_)(?:artifact_)?/,"").replace(/^model_run_/,"");return n.length<=12?n:n.slice(-8)}function ks({run:t,onAnswerQuestion:n,onApplyCandidate:a,onApprove:s,onCancel:l,onOpenPullRequest:o,onPause:i,onOpenConversation:r,onReconcilePullRequest:u,onRejectCandidate:h,onRetry:d,onResume:j,onRevise:b}){const g=t.state==="blocked"?"Review blocker":t.state==="failed"?"Review failure":"View progress",C=t.target.kind==="agent"&&["blocked","failed","cancelled"].includes(t.state);return e.jsxs("div",{className:"labs-run-decision",children:[e.jsx(Ia,{runtime:{run:t,onAnswerQuestion:n,onApplyCandidate:a,onApprove:s,onCancel:l,onOpenPullRequest:o,onPause:i,onReconcilePullRequest:u,onRejectCandidate:h,onResume:j,onRevise:b}}),t.scope.conversationId||C?e.jsxs("div",{className:"labs-run-decision-actions",children:[t.scope.conversationId?e.jsx("button",{className:"training-button secondary",type:"button",onClick:()=>r(t.scope.conversationId),children:g}):null,C?e.jsx("button",{className:"training-button",type:"button",onClick:d,children:"Try again"}):null]}):null]})}function Ss(t,n){const a=new Blob([`${JSON.stringify(n,null,2)}
|
|
3
|
-
`],{type:"application/json"}),s=URL.createObjectURL(a),l=document.createElement("a");l.href=s,l.download=t,l.click(),URL.revokeObjectURL(s)}const Ns=new Set(["released","rejected","ready","ready_local","published_hosted","blocked","failed","cancelled"]),qn=new Set(["queued","starting","running","cancelling","reconciling"]);function Cs(t){const n=t.runs[0]??null,a=n?.state==="blocked"&&n.candidates.some(l=>!!l.git?.worktreePath&&["draft","checking"].includes(l.status))?n:null,s=t.runs.find(l=>!Ns.has(l.state))??null;if(t.workproduct.kind==="model"&&t.taskset){const l=Ln(t.training,t.taskset.id)[0]??null;if(l&&qn.has(l.status))return mn({taskset:t.taskset,training:t.training,latestRun:n,fallbackStatus:t.workproduct.status})}return a?Ct(a):s?Ct(s):t.workproduct.kind==="model"?!t.taskset&&n&&["failed","blocked","cancelled"].includes(n.state)?Ct(n):mn({taskset:t.taskset,training:t.training,latestRun:n,fallbackStatus:t.workproduct.status}):t.workproduct.kind==="agent"?{statusLabel:t.workproduct.status,statusValue:t.workproduct.status,action:{kind:"start_agent_change",label:"Improve agent"},runId:n?.id??null,conversationId:n?.scope.conversationId??null}:n?.scope.conversationId?{statusLabel:t.workproduct.status,statusValue:t.workproduct.status,action:{kind:"open_conversation",label:"Open chat"},runId:n.id,conversationId:n.scope.conversationId}:{statusLabel:t.workproduct.status,statusValue:t.workproduct.status,action:null,runId:n?.id??null,conversationId:n?.scope.conversationId??null}}function Ct(t){const n={statusLabel:Rs(t),statusValue:t.state,runId:t.id,conversationId:t.scope.conversationId};if(t.state==="awaiting_questions")return{...n,action:{kind:"review_run",label:"Review questions"}};if(t.state==="awaiting_plan_approval")return{...n,action:{kind:"review_run",label:"Review plan"}};if(t.state==="awaiting_promotion")return{...n,action:{kind:"review_run",label:t.target.kind==="agent"?"Review update":"Review candidate"}};if(t.state==="pull_request_open")return{...n,action:{kind:"review_run",label:"Review change"}};if(t.state==="paused")return{...n,action:{kind:"resume_run",label:"Resume"}};if(t.state==="blocked"){const a=t.candidates.some(s=>!!s.git?.worktreePath&&["draft","checking"].includes(s.status));return{...n,action:a?{kind:"resume_run",label:t.target.kind==="agent"?"Continue update":"Continue candidate"}:t.target.kind==="agent"?{kind:"start_agent_change",label:"Try again"}:t.scope.conversationId?{kind:"open_conversation",label:"Review blocker"}:null}}return t.state==="failed"?{...n,action:t.scope.conversationId?{kind:"open_conversation",label:"Review failure"}:null}:{...n,action:t.scope.conversationId?{kind:"open_conversation",label:"View progress"}:null}}function mn(t){const n=t.latestRun?.scope.conversationId??null;if(!t.taskset)return{statusLabel:"Not hosted",statusValue:"not_run",action:n?{kind:"open_conversation",label:"View progress"}:null,runId:t.latestRun?.id??null,conversationId:n};const s=Ln(t.training,t.taskset.id)[0]??null,l=s?t.training?.models.find(o=>o.jobId===s.id&&o.status==="imported")??null:null;if(s&&qn.has(s.status))return{statusLabel:Se(s.status),statusValue:s.status,action:{kind:"open_training",label:"View run"},runId:t.latestRun?.id??null,conversationId:n};if(s?.status==="failed")return{statusLabel:"Training failed",statusValue:"failed",action:{kind:"open_training",label:"Review failure"},runId:t.latestRun?.id??null,conversationId:n};if(s?.status==="succeeded"){const o=s.metadata.frozenEvaluationComplete===!0||!!l?.frozenEvaluationArtifactId,i=typeof s.metadata.frozenEvaluationThresholdPassed=="boolean"?s.metadata.frozenEvaluationThresholdPassed:l?.promotable===!0;return o&&!i?{statusLabel:"Evaluation failed",statusValue:"failed",action:{kind:"open_training",label:"Review results"},runId:t.latestRun?.id??null,conversationId:n}:o&&i?{statusLabel:l?.promotable?"Model ready":"Evaluation passed",statusValue:l?.promotable?"ready":"passed",action:{kind:"open_training",label:"Review results"},runId:t.latestRun?.id??null,conversationId:n}:{statusLabel:l?"Evaluation pending":"Collecting model",statusValue:"running",action:{kind:"open_training",label:"Review results"},runId:t.latestRun?.id??null,conversationId:n}}return t.taskset.readiness?.ready?{statusLabel:"Ready to train",statusValue:"ready",action:{kind:"start_training",label:"Start training"},runId:t.latestRun?.id??null,conversationId:n}:{statusLabel:"Needs review",statusValue:"needs_review",action:{kind:"open_data",label:"Review data"},runId:t.latestRun?.id??null,conversationId:n}}function Rs(t){const n=t.state,a=t.target.kind==="agent";return{planning:"Planning",awaiting_questions:"Needs answers",awaiting_plan_approval:"Plan ready",paused:"Paused",applying_source:a?"Saving Agent":"Applying changes",running_checks:a?"Running Evals":"Running checks",evaluating:a?"Running Evals":"Evaluating",awaiting_promotion:a?"Update ready":"Candidate ready",opening_pull_request:"Opening review",pull_request_open:"Review open",reconciling_release:a?"Saving update":"Merging change",released:"Released",rejected:"Rejected",ready:"Ready",ready_local:"Ready",pushing_hosted:"Syncing",running_hosted_checks:"Verifying hosted",published_hosted:"Published",blocked:"Blocked",failed:"Failed",cancelled:"Cancelled"}[n]}const pn={chat_manual:"Default chat model",agent:"Agent runtime",extension:"Extension runtime",authoring_optimizer:"Authoring / optimizer"};function Is({lineage:t,state:n,training:a,onToast:s}){const[l,o]=c.useState("chat_manual"),[i,r]=c.useState("default"),[u,h]=c.useState(null),[d,j]=c.useState(""),b=c.useMemo(()=>n?.modelBindings.find(m=>m.status==="active"&&m.role===l&&m.roleTargetId===i.trim())??null,[l,i,n?.modelBindings]),g=b?n?.models.find(m=>m.id===b.modelArtifactLineageId)??null:null,k=(t?.frozenEvaluationArtifactId?n?.artifacts.find(m=>m.id===t.frozenEvaluationArtifactId)??null:null)?.metadata.evaluationComplete===!1;if(!t)return e.jsx("div",{className:"training-run-placeholder",children:"Promotion is available after a verified artifact is imported."});const f=t,S=je(f),y=!!a.busyAction,w=f.status==="imported"&&!!S&&!!i.trim(),R=b?.modelArtifactLineageId===f.id;async function p(){const m=await a.actions.bindModel(f.id,l,i.trim());h(null),s(m?"Model binding activated.":"Couldn’t activate Model binding.",m?"success":"error")}async function _(){const m=d.trim();if(!m)return;const T=await a.actions.rejectModel(f.id,m);h(null),s(T?"Model candidate rejected.":"Couldn’t reject Model candidate.",T?"success":"error")}async function x(){if(!b)return;const m=await a.actions.rollbackModelBinding(b.id);s(m?"Model binding rolled back.":"Couldn’t roll back Model binding.",m?"success":"error")}return e.jsxs("div",{className:"training-promotion",children:[e.jsxs("div",{className:"training-promotion-status",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Promotion gate"}),e.jsx("strong",{children:S?"Passed":"Blocked"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Selected role"}),e.jsx("strong",{children:g?Rt(g.id):"No active binding"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Rollback target"}),e.jsx("strong",{children:b?.rollbackTargetBindingId?Rt(b.rollbackTargetBindingId):"None"})]})]}),e.jsxs("div",{className:"training-promotion-controls",children:[e.jsxs("label",{children:[e.jsx("span",{children:"Role"}),e.jsx("select",{value:l,onChange:m=>{const T=m.target.value;o(T),r(T==="chat_manual"?"default":"")},children:Object.entries(pn).map(([m,T])=>e.jsx("option",{value:m,children:T},m))})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Role target"}),e.jsx("input",{value:i,placeholder:l==="agent"?"agent id":l==="extension"?"extension id":"default",onChange:m=>r(m.target.value)})]}),e.jsxs("div",{className:"training-promotion-actions",children:[R?e.jsx("button",{className:"training-button secondary",type:"button",disabled:y,onClick:()=>{x()},children:"Roll back"}):e.jsx("button",{className:"training-button",type:"button",disabled:y||!w,onClick:()=>h("bind"),children:b?"Replace binding":"Bind model"}),e.jsx("button",{className:"training-button danger",type:"button",disabled:y||t.status==="rejected"||R,onClick:()=>h("reject"),children:"Reject"})]})]}),S?null:e.jsx("p",{className:"training-promotion-note",children:k?"The artifact remains inspectable. Its prior evaluation was blocked by provider infrastructure and recorded no quality result.":"The artifact remains inspectable, but it cannot be bound until its frozen-evaluation threshold passes."}),u?e.jsx("div",{className:"training-dialog-backdrop",role:"presentation",onMouseDown:()=>!y&&h(null),children:e.jsxs("section",{className:"training-dialog training-promotion-dialog",role:"dialog","aria-modal":"true","aria-label":u==="bind"?"Confirm Model binding":"Reject Model candidate",onMouseDown:m=>m.stopPropagation(),children:[e.jsx("div",{className:"training-dialog-header",children:e.jsxs("div",{children:[e.jsx("h2",{children:u==="bind"?"Activate this Model binding?":"Reject this Model candidate?"}),e.jsx("p",{children:u==="bind"?`${pn[l]} · ${i.trim()}`:"The artifact and evaluation evidence are retained."})]})}),u==="bind"?e.jsx("p",{children:b?`The current binding ${Rt(b.modelArtifactLineageId)} becomes the recorded rollback target.`:"This is an explicit activation; training success alone never changes runtime selection."}):e.jsxs("label",{className:"training-promotion-reason",children:[e.jsx("span",{children:"Reason"}),e.jsx("textarea",{autoFocus:!0,value:d,onChange:m=>j(m.target.value)})]}),e.jsxs("div",{className:"training-dialog-actions",children:[e.jsx("button",{className:"training-button secondary",type:"button",disabled:y,onClick:()=>h(null),children:"Cancel"}),e.jsx("button",{className:`training-button ${u==="reject"?"danger":""}`,type:"button",disabled:y||u==="reject"&&!d.trim(),onClick:()=>{u==="bind"?p():_()},children:y?"Applying…":u==="bind"?"Activate binding":"Reject candidate"})]})]})}):null]})}function Rt(t){return t.replace(/^lineage_/,"").replace(/^model_binding_/,"").slice(0,16)}function Ms(t){return[...t.candidates].reverse().find(n=>!!n.git?.headCommit)??null}function As(t){return t?t.state==="released"?"positive":t.state==="blocked"||t.state==="failed"||t.state==="rejected"?"negative":t.state==="reconciling_release"?"info":"warning":"neutral"}function ws({workproduct:t,profile:n}){if(t.kind==="agent"){const a=n?.agents.find(s=>s.id===t.id)??null;return e.jsx(be,{title:"Agent",children:e.jsxs("dl",{className:"training-configuration-list",children:[e.jsx(ie,{label:"Enabled",value:a?.enabled?"Yes":"No"}),e.jsx(ie,{label:"Source",value:a?.path??t.path??"Draft"}),e.jsx(ie,{label:"Default action",value:`${t.id}.chat`}),e.jsx(ie,{label:"Profile checks",value:n?.lastCheck?.status??"Not run"})]})})}if(t.kind==="skill"){const a=t.skillSource==="codex"?null:n?.skills.find(i=>i.name===t.id)??null,s=t.skillValidationStatus??a?.validationStatus??"error",l=t.skillValidationMessages??a?.validationMessages??[],o=t.skillResourceFiles??[];return e.jsxs(be,{title:"Skill",children:[e.jsxs("dl",{className:"training-configuration-list",children:[e.jsx(ie,{label:"Scope",value:t.skillSource==="codex"?"Codex personal":"OpenPond profile"}),e.jsx(ie,{label:"Enabled",value:t.enabled?"Yes":"No"}),e.jsx(ie,{label:"Validation",value:s}),e.jsx(ie,{label:"Source",value:t.path??"Not available"}),e.jsx(ie,{label:"Source hash",value:t.skillSourceHash??a?.sourceHash??"Not available"}),e.jsx(ie,{label:"Characters",value:String(t.skillCharCount??a?.charCount??"Not available")}),t.skillSource==="codex"?e.jsx(ie,{label:"Packaged resources",value:String(o.length)}):null]}),o.length?e.jsxs("div",{className:"labs-source-evals",children:[e.jsx("strong",{children:"Packaged resources"}),e.jsx("ul",{children:o.map(i=>e.jsx("li",{children:e.jsx("code",{children:i})},i))})]}):null,l.length?e.jsx("ul",{className:"labs-validation-list",children:l.map(i=>e.jsx("li",{children:i},i))}):null]})}return t.kind==="extension"?e.jsx(be,{title:"Extension",children:e.jsx("div",{className:"training-run-placeholder",children:"Runtime bindings arrive with the Extension phase."})}):t.kind==="model"?e.jsx(be,{title:"Model",children:e.jsxs("dl",{className:"training-configuration-list",children:[e.jsx(ie,{label:"Stable Model ID",value:t.id}),e.jsx(ie,{label:"Taskset",value:t.tasksetId??"Select one in Build"}),e.jsx(ie,{label:"Training runs",value:String(t.trainingRunCount)}),e.jsx(ie,{label:"Status",value:t.status})]})}):null}function Ts({runs:t,selectedRun:n,onSelectedRunIdChange:a}){return e.jsx(be,{title:"Activity",children:t.length?e.jsx("div",{className:"training-table-wrap",children:e.jsxs("table",{className:"training-data-table labs-activity-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Run"}),e.jsx("th",{children:"Operation"}),e.jsx("th",{children:"State"}),e.jsx("th",{children:"Revision"}),e.jsx("th",{children:"Updated"})]})}),e.jsx("tbody",{children:t.map(s=>e.jsxs("tr",{className:s.id===n?.id?"selected":void 0,onClick:()=>a(s.id),children:[e.jsx("td",{children:ht(s.id)}),e.jsx("td",{children:s.operation}),e.jsx("td",{children:e.jsx(re,{label:s.state.replaceAll("_"," "),value:s.state})}),e.jsx("td",{children:s.revision}),e.jsx("td",{children:$e(s.updatedAt)})]},s.id))})]})}):e.jsx("div",{className:"training-run-placeholder",children:"No Create/Improve activity yet."})})}function _s({profileEvals:t,run:n,workproduct:a}){const s=n?.evaluationReceipts??[],l=[...new Set([...n?.context.evalRefs??[],...s.flatMap(r=>r.evalRefs)])],o=a.kind==="agent"?t.filter(r=>r.agentId===null||r.agentId===a.id):[],i=a.kind==="agent";return!s.length&&!o.length&&!l.length?e.jsx("div",{className:"training-run-placeholder",children:"No Eval receipts yet."}):e.jsxs("div",{className:"labs-eval-summary",children:[o.length?e.jsxs("div",{className:"labs-source-evals",children:[e.jsx("strong",{children:"Available Evals"}),e.jsx("ul",{children:o.map(r=>e.jsxs("li",{children:[e.jsx("span",{children:r.name}),i?null:e.jsx("code",{children:r.path})]},r.id))})]}):null,l.length?e.jsxs("div",{className:"labs-source-evals",children:[e.jsx("strong",{children:i?"Included in this update":"Used for this change"}),e.jsx("ul",{children:i?e.jsx("li",{children:e.jsxs("span",{children:[l.length," Eval set",l.length===1?"":"s"]})}):l.map(r=>e.jsx("li",{children:e.jsx("code",{children:r})},r))})]}):null,s.length?e.jsxs("div",{className:"labs-eval-receipts",children:[e.jsx("strong",{children:i?"Check results":"Eval receipts"}),e.jsx("div",{className:"training-table-wrap",children:e.jsxs("table",{className:"training-data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[i?null:e.jsx("th",{children:"Receipt"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Evals"}),e.jsx("th",{children:"Summary"})]})}),e.jsx("tbody",{children:s.map(r=>e.jsxs("tr",{children:[i?null:e.jsx("td",{children:ht(r.id)}),e.jsx("td",{children:e.jsx(re,{label:r.status})}),e.jsx("td",{children:r.evalRefs.length}),e.jsx("td",{children:i?$s(r):r.summary??"No summary"})]},r.id))})]})})]}):null]})}function $s(t){return t.summaryCounts?`${t.summaryCounts.passed} of ${t.summaryCounts.total} Evals passed.`:t.status==="passed"?"Agent behavior Evals passed.":t.status==="failed"?"One or more Agent behavior Evals failed.":"Agent behavior Evals are still running."}function Ps({runs:t,selectedRun:n,taskset:a,training:s,trainingState:l,onToast:o}){const i=(a?l?.models.filter(d=>d.tasksetId===a.id)??[]:[]).sort((d,j)=>j.importedAt.localeCompare(d.importedAt)),r=new Map(l?.jobs.map(d=>[d.id,d])??[]),u=new Map(l?.plans.map(d=>[d.id,d])??[]),h=new Map(l?.artifacts.map(d=>[d.id,d])??[]);return e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"labs-detail-copy labs-version-storage-copy",children:"OpenPond automatically saves provider weights in app-managed local storage. Download LoRA creates a portable copy for moving or sharing the adapter."}),e.jsxs("dl",{className:"labs-inline-facts",children:[e.jsx(ke,{label:"Create/Improve runs",value:String(t.length)}),e.jsx(ke,{label:"Candidates",value:String(n?.candidates.length??0)}),e.jsx(ke,{label:"Profile commit",value:n?.localProfileCommit??"Not released"}),e.jsx(ke,{label:"Model artifacts",value:String(i.length)})]}),i.length?e.jsx("div",{className:"training-table-wrap",children:e.jsxs("table",{className:"training-data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Version"}),e.jsx("th",{children:"Method"}),e.jsx("th",{children:"Storage"}),e.jsx("th",{children:"Frozen Eval"}),e.jsx("th",{children:"Imported"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Download"})})]})}),e.jsx("tbody",{children:i.map((d,j)=>{const b=r.get(d.jobId),g=b?u.get(b.planId):null,C=h.get(d.artifactId)??null,k=C?Es(C.path):null;return e.jsxs("tr",{children:[e.jsxs("td",{className:"labs-version-name",children:[e.jsx("strong",{children:j===0?"Latest":`Prior ${j}`}),e.jsx("small",{children:ht(d.id)})]}),e.jsx("td",{children:Oe(g?.recipe.method)}),e.jsxs("td",{className:"labs-version-storage",children:[e.jsx("strong",{children:k?"Saved locally":"Unavailable"}),k?e.jsx("code",{title:C?.path,children:k}):null]}),e.jsx("td",{children:d.promotable?"Passed":d.frozenEvaluationArtifactId?"Failed":"Not run"}),e.jsx("td",{children:$e(d.importedAt)}),e.jsx("td",{children:e.jsxs("button",{className:"training-button secondary",type:"button",onClick:()=>{s.actions.downloadModelPackage(d.id)},children:[e.jsx(ot,{size:14}),"Download LoRA"]})})]},d.id)})})]})}):e.jsx("div",{className:"training-run-placeholder",children:"Model versions appear after the first adapter is imported."}),i[0]?e.jsxs("div",{className:"labs-version-promotion",children:[e.jsx("h3",{children:"Promotion & bindings"}),e.jsx(Is,{lineage:i[0],state:l,training:s,onToast:o})]}):null]})}function Es(t){return t.replace(/[/\\][^/\\]+$/,"").replace(/^\/home\/[^/]+/,"~")}function ke({label:t,value:n}){return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsx("dd",{children:n})]})}function ie({label:t,value:n}){return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsx("dd",{children:n})]})}function ht(t){return t.replace(/^(create_improve|training_job|agent_candidate|model_candidate)_/,"").slice(0,14)}function Hn(t){return t&&`${t[0].toUpperCase()}${t.slice(1).replaceAll("_"," ")}`}function Ls(t,n,a,s=!1){return t==="changes"?n?["Changes",a?`Change ${a.slice(0,8)}`:`Change ${ht(n)}`]:["Changes"]:[Hn(t)]}function Ds(t,n,a){const s=a.git?.changedPaths??[],l=s[0]??null,o=t.path?.trim().replace(/^\.\/+|\/+$/g,"")??"";if(!o)return{fileRootPath:null,initialPath:l};const i=o.split("/").filter(Boolean);i.at(-1)?.includes(".")&&i.pop();const r=i.join("/");if(!r)return{fileRootPath:null,initialPath:l};const u=r.startsWith("profiles/")?r:`profiles/${n?.activeProfile??"default"}/${r}`,h=s.find(d=>d===u||d.startsWith(`${u}/`))??null;return h?{fileRootPath:u,initialPath:h}:{fileRootPath:null,initialPath:l}}function Os(t){return t?t.state==="planning"?"Planning update":t.state==="awaiting_questions"?"Waiting for input":t.state==="awaiting_plan_approval"?"Plan ready":t.state==="applying_source"?"Saving Agent":t.state==="running_checks"||t.state==="evaluating"?"Running Evals":t.state==="awaiting_promotion"?"Update ready to apply":t.state==="opening_pull_request"||t.state==="pull_request_open"?"Update review open":t.state==="reconciling_release"?"Applying update":t.state==="released"?"Update applied":t.state==="rejected"?"Current version kept":t.state==="ready"||t.state==="ready_local"?"Agent ready":t.state==="published_hosted"?"Agent published":t.state==="paused"?"Update paused":t.state==="cancelled"?"Update cancelled":t.state==="blocked"?"Update blocked":t.state==="failed"?"Update failed":`Change ${t.state.replaceAll("_"," ")}`:"No change status"}const Bs=c.lazy(()=>ma(()=>import("./LabModelVersionDetailPage-CNDz2a6I.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]),import.meta.url).then(t=>({default:t.LabModelVersionDetailPage})));function Us({workproduct:t,runs:n,profile:a,training:s,connection:l,onOpenConversation:o,onClose:i,onLocationChange:r,onRenameAgent:u,onStartAgentChange:h,onOpenDataset:d,onToast:j,onAnswerQuestion:b,candidateReview:g,onApprove:C,onCancel:k,onChatWithModel:f,onApplyCandidate:S,onCandidateReviewChange:y,onOpenCandidateFiles:w,onOpenPullRequest:R,onPause:p,onReconcilePullRequest:_,onRejectCandidate:x,onResume:m,onRevise:T,renderModelRunEditor:V,benchmarkDefaultModel:E,benchmarkProviderSettings:$,initialBenchmarkModel:Z=null,initialBenchmarkOpen:K=!1,onInitialBenchmarkOpenConsumed:ee}){const M=c.useMemo(()=>Ga(t,n),[n,t]),[H,B]=c.useState(M[0]?.id??""),[G,de]=c.useState(null),[F,ne]=c.useState("overview"),[J,ae]=c.useState(null),[X,N]=c.useState("run"),q=c.useRef("runs"),[D,te]=c.useState(null),[Q,le]=c.useState(null),[Ae,fe]=c.useState(K);c.useEffect(()=>{K&&(fe(!0),ee?.())},[K,ee]);const ue=M.find(A=>A.id===H)??M[0]??null,I=G?M.find(A=>A.id===G)??null:null,L=I?Ms(I):null,he=Ka(t.kind),oe=t.kind==="model"&&!!(t.ownerProfileId&&t.ownerProfileId!==a?.activeProfile),me=c.useMemo(()=>t.kind==="model"?Qe(t,n,s.payload):[],[n,s.payload,t]),v=c.useMemo(()=>t.kind==="model"?We(t,n,s.payload):[],[n,s.payload,t]),O=c.useMemo(()=>t.kind==="model"?ct(t,s.payload):[],[s.payload,t]),W=D?.startsWith("job:")?v.find(A=>A.id===D.slice(4))??null:null,pe=D?.startsWith("model-run:")?O.find(A=>A.id===D.slice(10))??null:W?.metadata.modelRunId?O.find(A=>A.id===W.metadata.modelRunId)??null:null,se=(D?.startsWith("version:")?me.find(A=>A.lineage.id===D.slice(8))??null:null)??(W?me.find(A=>A.job?.id===W.id)??null:null)??(pe?.adapterArtifactLineageId?me.find(A=>A.lineage.id===pe.adapterArtifactLineageId)??null:null),ve=c.useMemo(()=>Ht(v,me,O),[v,O,me]),we=ve.findIndex(A=>A.key===D||W!==null&&A.job?.id===W.id||pe!==null&&A.lifecycleRun?.id===pe.id),Pe=we<0?null:ve.length-we,Te=L?.git?.headCommit??null,Xe=c.useMemo(()=>t.kind==="model"?J?[{label:"Runs",onSelect:()=>U("runs")},{label:J==="new"?"New run":"Resume draft"},...X==="dataset"?[{label:"New Taskset"}]:[]]:D?[{label:D.startsWith("version:")?"Versions":"Runs",onSelect:()=>{te(null)}},{label:D.startsWith("version:")&&se?`Version ${se.number}`:Pe?`Run ${Pe}`:D.startsWith("version:")?"Version details":"Run details"}]:[]:Ls(F==="runs"?"overview":F,G,Te,t.kind==="agent").map(A=>({label:A})),[F,X,J,Te,G,D,Pe,se,t.kind]),Ue=t.tasksetId?[...s.payload?.tasksets??[],...s.payload?.modelTasksets??[]].find(A=>A.id===t.tasksetId)??null:null,mt=t.kind==="agent"?a?.agents.some(A=>A.id===t.id)??!1:!1,Ee=Cs({workproduct:t,runs:M,taskset:Ue,training:s.payload}),Ne=t.kind==="model"?me.find(A=>A.current)??null:null,Ye=t.kind==="model"?Ne?{label:"Hosted",value:"ready"}:{label:"Not hosted",value:"not_run"}:{label:Ee.statusLabel,value:Ee.statusValue},Fe=Ee.runId??M[0]?.id??"",Ze=M.some(A=>A.id===H),Ce=G?M.some(A=>A.id===G):!0,ze=[["overview","Overview"],["changes","Changes"],["evals","Evals"],["versions","Versions"],["configuration","Configuration"]];c.useEffect(()=>{y(null),B(Fe),de(null),te(null),ne("overview"),ae(null),N("run")},[t.key]),c.useEffect(()=>{H&&Ze||B(Fe)},[Fe,Ze,H]),c.useEffect(()=>{Ce||de(null)},[Ce]),c.useEffect(()=>{if(F==="changes"&&I&&L){const A=Ds(t,a,L);y({run:I,candidate:L,fileRootPath:A.fileRootPath,initialPath:A.initialPath});return}y(null)},[F,y,a,L,I,t]),c.useEffect(()=>{r({kind:t.kind,kindLabel:he,kindOnSelect:t.kind==="model"?()=>{if(J){U("collection");return}i()}:void 0,workproductLabel:t.name,workproductOnSelect:t.kind==="model"?()=>{if(J){U("overview");return}ae(null),te(null),ne("overview")}:void 0,segments:Xe})},[he,Xe,i,r,t.kind,t.name]),c.useEffect(()=>()=>y(null),[y]);function Ve(A){if(oe)return;const ge=me.find(Re=>Re.lineage.id===A);ge?.taskset&&f(Ft({modelId:A,taskset:ge.taskset}))}function U(A){q.current=A,document.getElementById("model-run-editor-cancel")?.click()}return t.kind==="model"&&J?V({initialTasksetId:Ue?.id??null,draftId:J==="new"?null:J,modelId:t.id,modelName:t.name,onCancel:()=>{const A=q.current;if(ae(null),N("run"),A==="collection"){i();return}ne(A)},onFinished:async()=>{ae(null),N("run"),ne("runs")},onSectionChange:N}):e.jsxs("div",{className:"training-model-detail labs-workproduct-detail",children:[e.jsxs("header",{className:"training-model-detail-header labs-workproduct-detail-header",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"labs-workproduct-name-row",children:[e.jsx("h1",{children:t.name}),e.jsx($t,{label:Ye.label,value:Ye.value})]}),t.description&&t.description!=="No description"?e.jsx("p",{className:"labs-workproduct-description",children:t.description}):null]}),t.kind==="model"?e.jsxs("div",{className:"labs-workproduct-header-actions",children:[se?.taskset?e.jsxs("button",{className:"training-button secondary",disabled:oe||!je(se.lineage),title:je(se.lineage)?"Chat with this Version":"Chat is unavailable because this Version did not pass evaluation.",type:"button",onClick:()=>Ve(se.lineage.id),children:[e.jsx(wn,{size:14}),"Chat"]}):null,se?e.jsxs("button",{className:"training-button secondary",type:"button",onClick:()=>{s.actions.downloadModelPackage(se.lineage.id)},children:[e.jsx(ot,{size:14}),"Download LoRA"]}):null,pe?.receipt?e.jsxs("button",{className:"training-button secondary",type:"button",onClick:()=>Ss(`${pe.id}-receipt.json`,pe.receipt),children:[e.jsx(ot,{size:14}),"Download receipt"]}):null,e.jsx("button",{className:"training-button secondary",type:"button",onClick:()=>fe(!0),children:"Benchmark"}),oe?null:e.jsx("button",{className:"training-button",type:"button",onClick:()=>ae("new"),children:"New run"})]}):t.kind==="agent"?e.jsxs("div",{className:"labs-workproduct-header-actions",children:[e.jsx("button",{className:"training-button",type:"button",onClick:()=>h(t.id),children:"Improve agent"}),mt?e.jsxs("button",{className:"training-button secondary labs-compact-button",type:"button",onClick:u,children:[e.jsx(ha,{size:14}),e.jsx("span",{children:"Rename"})]}):null]}):null]}),t.kind==="model"||D?null:e.jsx("div",{className:"training-detail-tabs",role:"tablist","aria-label":"Workproduct detail",children:ze.map(([A,ge])=>e.jsxs("button",{className:F===A?"active":void 0,"aria-selected":F===A,role:"tab",type:"button",onClick:()=>{ne(A),A==="changes"&&de(null)},children:[ge,A==="changes"?e.jsx($t,{decorative:!0,label:Os(M[0]??null),size:"small",tone:As(M[0]??null)}):null]},A))}),e.jsx("div",{className:"training-detail-sections",children:t.kind==="model"&&D?e.jsx(c.Suspense,{fallback:e.jsx("div",{className:"training-run-placeholder",children:"Loading run details…"}),children:e.jsx(Bs,{connection:l,runs:n,selectedEntryKey:D,training:s,workproduct:t,onOpenDataset:d,onOpenConversation:o})}):t.kind==="model"?e.jsxs(e.Fragment,{children:[e.jsx(gs,{runs:n,training:s,workproduct:t,readOnly:oe,onOpenDataset:d,onOpenEntry:te,onResumeDraft:ae}),e.jsx(fs,{runs:n,training:s,workproduct:t,readOnly:oe,onOpenDataset:d,onOpenEntry:te,onToast:j})]}):F==="overview"?e.jsxs(be,{title:"Overview",children:[e.jsxs("dl",{className:"labs-inline-facts",children:[e.jsx(ke,{label:"Type",value:Hn(t.kind)}),e.jsx(ke,{label:"Status",value:Ee.statusLabel}),t.kind==="agent"?e.jsx(ke,{label:"Profile",value:"Saved in your Profile"}):e.jsxs(e.Fragment,{children:[e.jsx(ke,{label:"ID",value:t.id}),e.jsx(ke,{label:"Path",value:t.path??"Managed artifact"})]})]}),e.jsx("p",{className:"labs-detail-copy",children:t.description})]}):F==="changes"&&!I?e.jsx("div",{className:"labs-change-index",children:e.jsx(as,{runs:M,onReview:A=>{B(A.id),de(A.id)}})}):F==="changes"&&I&&L?e.jsx(es,{candidate:L,diff:g.diff,error:g.error,run:I,onApplyCandidate:(A,ge)=>S({run:A},ge),onOpenFiles:w,onRejectCandidate:(A,ge)=>x({run:A},ge)}):F==="changes"&&I?e.jsxs("div",{className:"labs-change-run-detail",children:[e.jsxs("article",{className:"labs-change-card",children:[e.jsxs("header",{className:"labs-change-card-header",children:[e.jsx("span",{className:"labs-change-timeline-label",children:"Request"}),e.jsx(re,{label:I.state.replaceAll("_"," "),value:I.state})]}),e.jsx("div",{className:"labs-change-card-body",children:e.jsx("h3",{children:I.objective})})]}),e.jsx(ks,{run:I,onAnswerQuestion:b,onApplyCandidate:S,onApprove:C,onCancel:k,onOpenConversation:o,onOpenPullRequest:R,onPause:p,onReconcilePullRequest:_,onRejectCandidate:x,onResume:m,onRetry:()=>h(t.id,I.objective),onRevise:T})]}):F==="evals"?e.jsx(be,{title:"Evals",actions:t.kind==="agent"?e.jsx(Za,{agentId:t.id,evals:a?.evals??[],onCreate:()=>h(t.id,`Create an Eval for ${t.name}. Describe the behavior this Eval should specify: `),onAttach:A=>h(t.id,`--eval ${JSON.stringify(A)} Improve ${t.name} using this existing Eval: `)}):null,children:e.jsx(_s,{profileEvals:a?.evals??[],run:ue,workproduct:t})}):F==="versions"?e.jsxs(e.Fragment,{children:[e.jsx(be,{title:"Versions",children:e.jsx(Ps,{runs:M,selectedRun:ue,taskset:Ue,training:s,trainingState:s.payload,onToast:j})}),e.jsx(Ts,{runs:M,selectedRun:ue,onSelectedRunIdChange:B})]}):e.jsxs(e.Fragment,{children:[e.jsx(be,{title:"Connections",children:e.jsxs("dl",{className:"training-configuration-list",children:[e.jsx(ie,{label:"Profile",value:a?.activeProfile??"default"}),e.jsx(ie,{label:"Conversation",value:ue?.scope.conversationId??"Not linked"}),e.jsx(ie,{label:"Project",value:ue?.scope.projectId??"Not linked"}),e.jsx(ie,{label:"Source authority",value:ue?.adapter.sourceAuthority??"Profile"})]})}),e.jsx(ws,{workproduct:t,profile:a})]})}),t.kind==="model"&&Ae?e.jsx(ds,{workproduct:t,training:s,readOnly:!1,defaultModel:E,initialModel:Z,providerSettings:$,onClose:()=>fe(!1),onOpenEntry:A=>{fe(!1),te(A)},onToast:j}):null,Q?(()=>{const A=me.find(ge=>ge.lineage.id===Q);return A?.taskset?e.jsx(Dn,{lineage:A.lineage,taskset:A.taskset,training:s,onChat:f,onClose:()=>le(null)}):null})():null]})}function Fs({activeTab:t,children:n,showHeader:a=!0,onCreateDataset:s,onCreateModel:l}){return e.jsxs("section",{className:"labs-route","aria-label":"Models",children:[a?e.jsx("header",{className:"labs-header",children:e.jsx("div",{className:"labs-header-actions",children:t==="models"?e.jsx("button",{className:"labs-create-button",type:"button",onClick:l,children:e.jsx("span",{children:"New model"})}):t==="tasksets"?e.jsx("button",{className:"labs-create-button",type:"button",onClick:s,children:e.jsx("span",{children:"New Taskset"})}):null})}):null,e.jsx("div",{className:"labs-panel",children:n})]})}function zs({taskset:t,busyAction:n,onPreview:a,onApprove:s,onToast:l}){const[o,i]=c.useState(null),[r,u]=c.useState(!1),h=qs(t),d=t.learningSignals.demonstrations.filter(k=>k.approved&&k.metadata.exampleOrigin==="expert_authored").length,j=n==="preview-expert-bootstrap",b=n==="approve-expert-bootstrap";async function g(){u(!0);const k=await a();if(k){i(k);return}u(!1),l("Couldn’t load the expert trajectories.","error")}async function C(){if(!o)return;const k=await s(o.previewHash);if(!k){l("The expert trajectories were not approved.","error");return}u(!1),l(`${k.approval.trajectoryCount} expert trajectories approved by ${k.approval.approvedBy}.`,"success")}return e.jsxs(e.Fragment,{children:[e.jsx(be,{title:"SFT bootstrap data",actions:e.jsx("button",{className:"training-button secondary",disabled:j||b,type:"button",onClick:()=>{g()},children:h?"Review trajectories":j?"Loading…":"Review expert trajectories"}),children:e.jsxs("div",{className:"labs-expert-bootstrap-summary",children:[e.jsxs("div",{children:[e.jsx(re,{label:h?"Approved":"Review required",value:h?"ready":"needs_review"}),e.jsx("p",{children:h?`${d} deterministic train-split trajectories are approved for the optional SFT bootstrap.`:"Five deterministic train-split trajectories are available. Failed model outputs remain excluded."})]}),h?e.jsxs("dl",{className:"labs-inline-facts",children:[e.jsx(Ge,{label:"Approved by",value:h.approvedBy}),e.jsx(Ge,{label:"Taskset revision",value:String(t.revision)})]}):null]})}),r?e.jsx(Vs,{approving:b,loading:j,preview:o,onApprove:()=>{C()},onClose:()=>{b||u(!1)}}):null]})}function Vs({preview:t,loading:n,approving:a,onApprove:s,onClose:l}){return e.jsxs(_e,{ariaLabel:"Review expert trajectories",className:"training-dialog labs-expert-bootstrap-dialog",dismissDisabled:a,onClose:l,children:[e.jsxs("div",{className:"training-dialog-header",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Review expert trajectories"}),e.jsx("p",{children:"These examples were executed in the deterministic synthetic environment and passed the exact verifier. Approval is bound to the signed-in OpenPond account."})]}),e.jsx("button",{"aria-label":"Close",disabled:a,type:"button",onClick:l,children:"×"})]}),e.jsx("div",{className:"training-dialog-scroll-body labs-expert-trajectory-list",children:n||!t?e.jsx("div",{className:"training-run-placeholder",children:"Generating and verifying the review set…"}):e.jsxs(e.Fragment,{children:[e.jsxs("dl",{className:"labs-inline-facts labs-expert-preview-facts",children:[e.jsx(Ge,{label:"Taskset revision",value:String(t.tasksetRevision)}),e.jsx(Ge,{label:"Trajectories",value:String(t.tasks.length)}),e.jsx(Ge,{label:"Review state",value:t.status==="approved"?"Approved":"Pending"})]}),t.tasks.map(o=>e.jsxs("details",{className:"labs-expert-trajectory",children:[e.jsxs("summary",{children:[e.jsxs("span",{children:[e.jsx("strong",{children:Hs(o.family)}),e.jsxs("small",{children:[o.toolCallCount," tool calls · exact reward ",o.reward.toFixed(3)]})]}),e.jsx("span",{"aria-hidden":"true",children:"›"})]}),e.jsxs("div",{className:"labs-expert-trajectory-body",children:[e.jsxs("section",{children:[e.jsx("h3",{children:"Prompt"}),e.jsx("p",{children:o.prompt})]}),e.jsxs("section",{children:[e.jsx("h3",{children:"Tool sequence"}),e.jsx("div",{className:"training-pills",children:o.toolNames.map((i,r)=>e.jsx("span",{children:i},`${o.trajectoryId}-${i}-${r}`))})]}),e.jsxs("section",{children:[e.jsx("h3",{children:"Verified answer"}),e.jsx("pre",{children:o.finalAnswer})]}),e.jsxs("details",{className:"labs-expert-messages",children:[e.jsxs("summary",{children:["View ",o.messageCount," training messages"]}),e.jsx("pre",{children:JSON.stringify(o.messages,null,2)})]})]})]},o.trajectoryId))]})}),e.jsxs("div",{className:"training-dialog-actions",children:[e.jsx("span",{className:"labs-expert-approval-note",children:"Train split only · failed policy outputs excluded"}),e.jsx("button",{className:"training-button secondary",disabled:a,type:"button",onClick:l,children:"Close"}),t?.status!=="approved"?e.jsx("button",{className:"training-button",disabled:!t||n||a,type:"button",onClick:s,children:a?"Approving…":`Approve ${t?.tasks.length??0} trajectories`}):null]})]})}function qs(t){const n=bn(t.metadata.expertBootstrap),a=bn(n.approval);return a.status!=="approved"||typeof a.approvedBy!="string"||typeof a.approvedAt!="string"||typeof a.previewHash!="string"||typeof a.trajectoryCount!="number"?null:a}function Ge({label:t,value:n}){return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsx("dd",{children:n})]})}function Hs(t){return t.split("_").map(n=>`${n.slice(0,1).toUpperCase()}${n.slice(1)}`).join(" ")}function bn(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}const Ks=[{id:"train",label:"Training"},{id:"validation",label:"Validation"},{id:"frozen_eval",label:"Frozen Eval"}],Le=10;function Gs({artifact:t,defaultModel:n,tab:a="overview",taskset:s,onOpenFiles:l,onToast:o,training:i}){const r=c.useMemo(()=>t?new Map(Object.entries(t.splitCounts)):si(s.tasks.map(N=>N.split)),[t,s.tasks]),u=r.get("train")?"train":r.get("validation")?"validation":r.get("frozen_eval")?"frozen_eval":s.tasks[0]?.split??"train",[h,d]=c.useState(u==="test"?"frozen_eval":u),[j,b]=c.useState(1),[g,C]=c.useState([]),[k,f]=c.useState(null),[S,y]=c.useState([]),[w,R]=c.useState(null),[p,_]=c.useState(!1),[x,m]=c.useState(null),[T,V]=c.useState(null),E=c.useMemo(()=>new Map(s.sourceRefs.map(N=>[N.id,N])),[s.sourceRefs]);c.useEffect(()=>{if(a!=="cases"||!t)return;let N=!1;return _(!0),m(null),i.actions.datasetRows(s.id,{split:h,cursor:k,limit:Le}).then(q=>{N||!q||(C(q.rows.map(D=>pa.parse(D))),R(q.nextCursor))}).catch(q=>{N||(C([]),R(null),m(q instanceof Error?q.message:String(q)))}).finally(()=>{N||_(!1)}),()=>{N=!0}},[t,k,h,a,s.id,i.actions]);const $=t?g:s.tasks.filter(N=>N.split===h),Z=Math.max(1,Math.ceil($.length/Le)),K=t?$:$.slice((j-1)*Le,j*Le),ee=t?S.length*Le:(j-1)*Le,M=s.sourceRefs.filter(Kt).length,H=s.sourceRefs.filter(N=>Vt(N)&&N.turnIds.length>0).length,B=s.sourceRefs.filter(N=>N.metadata.containsCustomerData===!0).length,G=s.learningSignals.demonstrations.filter(N=>N.approved).length,de=s.learningSignals.preferences.filter(N=>N.approved).length,F=s.learningSignals.rewards.filter(N=>N.approved).length,ne=s.learningSignals.labels.filter(N=>N.approved&&N.labelKind==="rubric").length,J=s.graders.some(N=>N.kind==="model_judge"),ae=s.environment.kind==="work"?s.tasks.find(N=>N.split!=="frozen_eval")??null:null;async function X(N,q){if(V(null),!await q()){V(`${N} did not complete. Check the latest error and try again.`);return}V(`${N} started or completed successfully.`),o(`${N} started or completed successfully.`,"success")}return a==="overview"?e.jsxs(be,{title:"Taskset",children:[e.jsx("p",{className:"labs-detail-copy labs-dataset-summary",children:Ws({syntheticSources:M,chatSources:H,customerSources:B,sourceCount:s.sourceRefs.length})}),e.jsxs("dl",{className:"labs-inline-facts",children:[e.jsx(ce,{label:"Training",value:String(r.get("train")??0)}),e.jsx(ce,{label:"Validation",value:String(r.get("validation")??0)}),e.jsx(ce,{label:"Frozen Eval",value:String(r.get("frozen_eval")??0)}),e.jsx(ce,{label:"Demonstrations",value:String(G)}),e.jsx(ce,{label:"Preference pairs",value:String(de)}),e.jsx(ce,{label:"Reward specs",value:String(F)}),e.jsx(ce,{label:"Rubrics",value:String(ne)})]}),s.purpose==="benchmark"&&s.benchmark?e.jsxs("div",{className:"labs-dataset-method-readiness",children:[e.jsx("strong",{children:"Benchmark protocol"}),e.jsxs("div",{className:"training-pills",children:[e.jsx("span",{children:xe(s.benchmark.primaryMetric.replaceAll("_"," "))}),e.jsx("span",{children:xe(s.benchmark.qualityGate.replaceAll("_"," "))}),e.jsx("span",{children:"Immutable release"})]}),e.jsxs("p",{className:"labs-detail-copy",children:["Adapt on ",xe(s.benchmark.adaptationSplit)," cases and compare paired ",xe(s.benchmark.evaluationSplit.replaceAll("_"," "))," runs."]})]}):e.jsxs("div",{className:"labs-dataset-method-readiness",children:[e.jsx("strong",{children:"Training compatibility"}),e.jsx("div",{className:"training-pills",children:s.readiness?.methodReadiness.length?s.readiness.methodReadiness.map(N=>e.jsxs("span",{title:N.reasons.join(" "),children:[N.method.toUpperCase()," · ",xe(N.status)]},N.method)):s.capabilities.compatibleMethods.filter(N=>!["none","retrieval"].includes(N)).map(N=>e.jsx("span",{children:N.toUpperCase()},N))}),s.readiness?.methodReadiness.some(N=>N.reasons.length)?e.jsx("ul",{children:s.readiness.methodReadiness.flatMap(N=>N.reasons.map(q=>e.jsxs("li",{children:[e.jsxs("strong",{children:[N.method.toUpperCase(),":"]})," ",q]},`${N.method}:${q}`)))}):null]}),e.jsxs("details",{className:"labs-dataset-advanced-details",children:[e.jsx("summary",{children:"Technical details"}),e.jsxs("dl",{className:"training-configuration-list",children:[e.jsx(ce,{label:"Taskset ID",value:s.id}),e.jsx(ce,{label:"Revision",value:String(s.revision)}),e.jsx(ce,{label:"Format",value:t?.format.toUpperCase()??"Inline Taskset"}),e.jsx(ce,{label:"Rows",value:String(t?.rowCount??s.tasks.length)}),e.jsx(ce,{label:"Storage",value:t?ii(t.sizeBytes):"Managed inline"}),e.jsx(ce,{label:"Availability",value:t?.available===!1?t.unavailableReason??"Unavailable":"Available"}),e.jsx(ce,{label:"Content hash",value:t?.contentHash??s.contentHash})]}),e.jsx("button",{className:"training-button secondary",type:"button",onClick:l,children:"Open files"})]})]}):a==="scoring"?e.jsxs(e.Fragment,{children:[s.purpose==="benchmark"?e.jsx(be,{title:"Benchmark runs",children:e.jsxs("p",{className:"labs-detail-copy",children:["Harness Refiner runs start from a Model so the selected Model, effort, full protocol, result charts, and Git-backed receipt stay together in one evaluation run. Open a Model and choose",e.jsx("strong",{children:" Run Refiner Benchmark"}),"."]})}):null,e.jsxs(be,{title:"Taskset checks",children:[e.jsx("p",{className:"labs-detail-copy",children:"Audit the reward and graders before creating a Model run."}),e.jsxs("div",{className:"labs-dataset-detail-actions",children:[ae?e.jsx("button",{className:"training-button secondary",disabled:i.busyAction!==null,type:"button",onClick:()=>{X("Work attempt",()=>i.actions.executeTasksetAttempt(s.id,ae.id,n))},children:"Run Work attempt"}):null,e.jsx("button",{className:"training-button secondary",disabled:i.busyAction!==null,type:"button",onClick:()=>{X("Grader audit",()=>i.actions.auditGraders(s.id))},children:"Audit graders"}),J?e.jsx("button",{className:"training-button secondary",disabled:i.busyAction!==null,type:"button",onClick:()=>{X("Judge calibration",()=>i.actions.calibrateJudges(s.id))},children:"Calibrate judges"}):null,e.jsx("button",{className:"training-button secondary",disabled:i.busyAction!==null,type:"button",onClick:()=>{X("Readiness check",()=>i.actions.readiness(s.id))},children:"Refresh readiness"})]}),T?e.jsx("p",{className:"labs-detail-copy",role:"status",children:T}):null,s.readiness?.blockers.length?e.jsxs("div",{className:"training-banner warning",children:[e.jsx("strong",{children:"Readiness blockers"}),e.jsx("ul",{children:s.readiness.blockers.map(N=>e.jsx("li",{children:N.message},`${N.code}:${N.path??""}`))})]}):null]}),e.jsx(be,{title:"Graders",children:e.jsx("div",{className:"labs-dataset-grader-list",children:s.graders.map(N=>e.jsxs("div",{children:[e.jsx("strong",{children:N.label}),e.jsx("small",{children:xe(N.kind)})]},N.id))})})]}):e.jsxs(be,{title:"Cases",children:[e.jsx("div",{className:"labs-method-tabs labs-dataset-tabs",role:"tablist","aria-label":"Taskset splits",children:Ks.map(N=>e.jsxs("button",{"aria-selected":h===N.id,className:h===N.id?"active":"",role:"tab",type:"button",onClick:()=>{d(N.id),b(1),f(null),y([])},children:[N.label,e.jsx("span",{children:r.get(N.id)??0})]},N.id))}),e.jsxs("div",{className:"labs-dataset-examples",children:[K.map((N,q)=>e.jsx(Js,{index:ee+q,source:N.sourceRefs.map(D=>E.get(D)).find(Boolean)??null,task:N},N.id)),t?e.jsxs("nav",{className:"labs-pagination","aria-label":"Task data pages",children:[e.jsx("button",{type:"button",disabled:!S.length||p,onClick:()=>{const N=S.at(-1)??null;y(q=>q.slice(0,-1)),f(N||null)},children:"Previous"}),e.jsx("span",{children:p?"Loading…":`Page ${S.length+1} · ${g.length.toLocaleString()} rows`}),e.jsx("button",{type:"button",disabled:!w||p,onClick:()=>{y(N=>[...N,k??""]),f(w)},children:"Next"})]}):Z>1?e.jsxs("nav",{className:"labs-pagination","aria-label":"Task data pages",children:[e.jsx("button",{type:"button",disabled:j<=1,onClick:()=>b(N=>Math.max(1,N-1)),children:"Previous"}),e.jsxs("span",{children:[j," of ",Z]}),e.jsx("button",{type:"button",disabled:j>=Z,onClick:()=>b(N=>Math.min(Z,N+1)),children:"Next"})]}):null,x?e.jsx("div",{className:"training-banner error",role:"alert",children:x}):null]})]})}function Js({index:t,source:n,task:a}){const s=Qs(a),l=Ys(a),o=Xs(a),i=n?ti(n):"Source unavailable",r=Zs(a,n),u=ei(a,n);return e.jsxs("details",{className:"labs-dataset-example",children:[e.jsxs("summary",{children:[e.jsx("span",{className:"labs-dataset-example-index",children:String(t+1).padStart(2,"0")}),e.jsxs("span",{className:"labs-dataset-example-title",children:[e.jsx("strong",{children:s}),e.jsx("small",{children:[r,u,i].filter(Boolean).join(" · ")})]}),e.jsx(re,{label:ai(a.split),value:a.split})]}),e.jsxs("div",{className:"labs-dataset-example-body",children:[e.jsxs("section",{children:[e.jsx("h3",{children:"Prompt"}),e.jsx("p",{children:s})]}),e.jsxs("section",{children:[e.jsx("h3",{children:a.split==="frozen_eval"?"Expected result":"Approved answer"}),a.split==="frozen_eval"?e.jsx("p",{children:"The answer stays held out and is only opened by the Eval runner."}):e.jsx("pre",{children:o??"No approved answer is attached."})]}),l.length?e.jsxs("section",{children:[e.jsx("h3",{children:"Tool trajectory"}),e.jsx("div",{className:"training-pills",children:l.map((h,d)=>e.jsx("span",{children:h},`${h}:${d}`))})]}):null,e.jsxs("section",{children:[e.jsx("h3",{children:"Source"}),e.jsxs("p",{children:[e.jsx("strong",{children:n?.title??"Source unavailable"})," — ",ni(n)]})]}),e.jsxs("details",{className:"labs-dataset-example-advanced",children:[e.jsx("summary",{children:"Technical details"}),e.jsxs("dl",{className:"training-configuration-list",children:[e.jsx(ce,{label:"Task",value:a.id}),e.jsx(ce,{label:"Source",value:n?.id??"Unavailable"}),e.jsx(ce,{label:"Cluster",value:a.clusterKey})]})]})]})]})}function Ws(t){if(t.sourceCount>0&&t.syntheticSources===t.sourceCount&&t.chatSources===0&&t.customerSources===0)return`This dataset contains ${t.sourceCount} generated scenarios. It uses no raw chats or customer data.`;const n=[`${t.sourceCount} source${t.sourceCount===1?"":"s"}`,`${t.chatSources} chat${t.chatSources===1?"":"s"}`,`${t.syntheticSources} generated scenario${t.syntheticSources===1?"":"s"}`];return t.customerSources===0?n.push("no sources marked as customer data"):n.push(`${t.customerSources} source${t.customerSources===1?"":"s"} marked as customer data`),`This dataset contains ${n.join(", ")}.`}function Qs(t){return typeof t.input.prompt=="string"?t.input.prompt:"Untitled dataset example"}function Xs(t){if(!t.expectedOutput)return null;if(typeof t.expectedOutput.text=="string")return t.expectedOutput.text;const n=Array.isArray(t.expectedOutput.messages)?t.expectedOutput.messages:[];for(const a of[...n].reverse())if(a&&typeof a=="object"&&"content"in a&&typeof a.content=="string")return a.content;return null}function Ys(t){if(!t.expectedOutput||!Array.isArray(t.expectedOutput.messages))return[];const n=[];for(const a of t.expectedOutput.messages){if(!a||typeof a!="object"||!("tool_calls"in a))continue;const s=Array.isArray(a.tool_calls)?a.tool_calls:[];for(const l of s){if(!l||typeof l!="object"||!("function"in l))continue;const o=l.function;o&&typeof o=="object"&&"name"in o&&typeof o.name=="string"&&n.push(o.name)}}return n}function Zs(t,n){const a=n?.metadata.crossSystemOperations;if(a&&typeof a=="object"&&"taskFamily"in a){const l=a.taskFamily;if(typeof l=="string")return xe(l)}const s=t.tags.find(l=>!["synthetic","structured-tool-trajectory"].includes(l));return s?xe(s):null}function ei(t,n){const a=n?.metadata.crossSystemOperations;if(a&&typeof a=="object"&&"worldDifficulty"in a){const s=a.worldDifficulty;if(typeof s=="string")return xe(s)}return t.clusterKey.match(/_(easy|medium|hard)$/)?.[1]??null}function Kt(t){return t.schemaVersion==="openpond.generatedDatasetSource.v1"||t.metadata.syntheticSpecification===!0}function ti(t){return Kt(t)?"Generated scenario":Vt(t)&&t.turnIds.length>0?"Chat":t.schemaVersion==="openpond.huggingFaceDatasetSource.v1"?"Hugging Face":t.schemaVersion==="openpond.uploadedFileDatasetSource.v1"?"Uploaded file":"Imported source"}function ni(t){return t?Kt(t)&&t.metadata.containsCustomerData===!1?"generated locally from a deterministic specification; no customer content is attached.":Vt(t)&&t.turnIds.length>0?`${t.turnIds.length} approved chat turn${t.turnIds.length===1?"":"s"} are attached.`:t.schemaVersion==="openpond.huggingFaceDatasetSource.v1"?`${t.repositoryId}@${t.revision.slice(0,12)} is attached.`:"an approved imported source is attached.":"The referenced source could not be loaded."}function ai(t){return t==="frozen_eval"?"Frozen Eval":xe(t)}function xe(t){return t.replaceAll("-"," ").replaceAll("_"," ").replace(/\b\w/g,n=>n.toUpperCase())}function si(t){const n=new Map;for(const a of t)n.set(a,(n.get(a)??0)+1);return n}function ii(t){return t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(1)} KB`:t<1073741824?`${(t/1048576).toFixed(1)} MB`:`${(t/1073741824).toFixed(1)} GB`}function ce({label:t,value:n}){return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsx("dd",{children:n})]})}const Lt=10,li=[{id:"overview",label:"Overview"},{id:"cases",label:"Cases"},{id:"scoring",label:"Scoring"},{id:"history",label:"History"}];function oi({state:t,runs:n,selectedId:a,onSelectedIdChange:s,defaultModel:l,onImproveInChat:o,onTrainModel:i,onOpenFiles:r,training:u,onToast:h}){const[d,j]=c.useState(""),[b,g]=c.useState(1),[C,k]=c.useState("overview"),f=t?.tasksets??[],S=[...f,...t?.modelTasksets??[]].find(m=>m.id===a)??null,y=!!(S&&S.profileId!==t?.profileId),w=S?.benchmark?.source==="builtin",R=S?.datasetArtifact?t?.datasetArtifacts.find(m=>m.tasksetId===a&&m.tasksetRevision===S.revision)??null:null,p=c.useMemo(()=>{const m=d.trim().toLowerCase();return m?f.filter(T=>[T.name,T.objective,T.id].some(V=>V.toLowerCase().includes(m))):f},[d,f]),_=p.slice((b-1)*Lt,b*Lt),x=c.useMemo(()=>{const m=new Map;if(!t)return m;const T=On({profile:null,training:t,runs:n}).filter(V=>V.kind==="model");for(const V of T)for(const E of bs(V,n,t))m.set(E.id,(m.get(E.id)??0)+1);return m},[n,t]);return c.useEffect(()=>{k("overview")},[a]),S?e.jsxs("div",{className:"labs-flat-body labs-datasets-page",children:[e.jsxs("div",{className:"labs-dataset-detail-heading",children:[e.jsx("button",{"aria-label":"Back to Tasksets",className:"labs-back-button",type:"button",onClick:()=>s(null),children:e.jsx(An,{size:15})}),e.jsxs("div",{children:[e.jsx("h1",{children:S.name}),e.jsx("p",{children:S.objective})]}),e.jsxs("div",{className:"labs-dataset-detail-actions",children:[y?e.jsx(re,{label:`Profile: ${S.profileId}`,value:"available"}):null,w?null:e.jsx("button",{className:"training-button secondary",disabled:y,title:y?"Switch to this Taskset's Profile to modify it.":"Improve this Taskset in Chat.",type:"button",onClick:()=>o(S),children:"Improve in Chat"}),S.purpose==="benchmark"?e.jsx("button",{className:"training-button",disabled:y,type:"button",onClick:()=>k("scoring"),children:"Run Benchmark"}):e.jsx("button",{className:"training-button",disabled:y||!S.readiness?.ready,title:y?"Switch to this Taskset's Profile before launching a Model run.":S.readiness?.ready?"Create a Model run from this ready Taskset.":S.readiness?.blockers[0]?.message??"Run Taskset checks before training.",type:"button",onClick:()=>i(S.id),children:"Train Model"}),e.jsx(re,{label:di(S),value:S.status})]})]}),e.jsx("div",{className:"training-detail-tabs",role:"tablist","aria-label":"Taskset detail",children:li.map(m=>e.jsx("button",{"aria-selected":C===m.id,className:C===m.id?"active":void 0,role:"tab",type:"button",onClick:()=>k(m.id),children:m.label},m.id))}),C==="history"?e.jsx(ri,{state:t,taskset:S}):e.jsxs(e.Fragment,{children:[e.jsx(Gs,{artifact:R,defaultModel:l,tab:C,taskset:S,onOpenFiles:()=>r(S.id),onToast:h,training:u}),C==="scoring"&&S.metadata.flagship==="cross-system-operations"?e.jsx(zs,{busyAction:u.busyAction,taskset:S,onApprove:m=>u.actions.approveExpertBootstrap(S.id,m),onPreview:()=>u.actions.previewExpertBootstrap(S.id),onToast:h}):null]})]}):e.jsxs("div",{className:"labs-flat-body labs-datasets-page",children:[e.jsx("div",{className:"labs-workproduct-toolbar",children:e.jsxs("label",{className:"labs-search",children:[e.jsx(Pn,{size:14}),e.jsx("input",{"aria-label":"Search Tasksets",placeholder:"Search Tasksets",value:d,onChange:m=>{j(m.target.value),g(1)}})]})}),e.jsx("div",{className:"training-table-wrap",children:e.jsxs("table",{className:"training-data-table labs-datasets-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Taskset"}),e.jsx("th",{children:"Training"}),e.jsx("th",{children:"Validation"}),e.jsx("th",{children:"Frozen Eval"}),e.jsx("th",{children:"Graders"}),e.jsx("th",{children:"Activity"}),e.jsx("th",{children:"Updated"})]})}),e.jsx("tbody",{children:_.map(m=>{const T=x.get(m.id)??0,V=(t?.benchmarkRuns??[]).filter(E=>E.metadata.sourceTasksetId===m.id).length;return e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("button",{className:"labs-workproduct-link",type:"button",onClick:()=>s(m.id),children:[e.jsx("strong",{children:m.name}),e.jsx("span",{children:m.objective})]})}),e.jsx("td",{children:It(m,t,"train")}),e.jsx("td",{children:It(m,t,"validation")}),e.jsx("td",{children:It(m,t,"frozen_eval")}),e.jsx("td",{children:m.graders.length}),e.jsx("td",{children:m.purpose==="benchmark"?V?`${V} run${V===1?"":"s"}`:"Not run":T?`${T} model${T===1?"":"s"}`:"—"}),e.jsx("td",{children:Dt(m.updatedAt)})]},m.id)})})]})}),_.length?null:e.jsx("div",{className:"labs-table-empty",children:"No Tasksets match this view."}),e.jsx(ci,{page:b,total:p.length,onChange:g})]})}function ri({state:t,taskset:n}){const[a,s]=c.useState(!1),l=(t?.modelRuns??[]).filter(r=>r.taskset.id===n.id).sort((r,u)=>u.updatedAt.localeCompare(r.updatedAt)),o=a?l:l.slice(0,10),i=new Map((t?.modelProjects??[]).map(r=>[r.id,r.name]));if(n.purpose==="benchmark"){const r=l.filter(u=>u.kind==="evaluation");return r.length?e.jsx("div",{className:"training-table-wrap",children:e.jsxs("table",{className:"training-data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Model"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Quality"}),e.jsx("th",{children:"Token delta"}),e.jsx("th",{children:"Mode"}),e.jsx("th",{children:"Updated"})]})}),e.jsx("tbody",{children:r.map(u=>{const h=u.receipt?.schemaVersion==="openpond.modelEvaluationReceipt.v1"?u.receipt:null,d=u.receipt?.schemaVersion==="openpond.modelEvaluationStopReceipt.v1"?u.receipt:null,j=h?.foregroundTokenDelta??null;return e.jsxs("tr",{children:[e.jsx("td",{children:i.get(u.modelId)??u.modelId}),e.jsx("td",{children:d?"inconclusive":u.status}),e.jsx("td",{children:h?`${Math.round(h.quality.candidatePassRate*100)}% candidate`:d?"Candidate skipped":"Pending"}),e.jsx("td",{children:j===null?"—":`${j>0?"+":""}${j.toLocaleString()}`}),e.jsx("td",{children:u.evaluation?`${u.evaluation.attemptPlan.reduce((b,g)=>b+g.attemptCount,0)} attempts`:"—"}),e.jsx("td",{children:Dt(u.updatedAt)})]},u.id)})})]})}):e.jsx("div",{className:"labs-table-empty",children:"This benchmark has not been run yet."})}return l.length?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"training-table-wrap",children:e.jsxs("table",{className:"training-data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Model"}),e.jsx("th",{children:"Run"}),e.jsx("th",{children:"Method"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Updated"})]})}),e.jsx("tbody",{children:o.map(r=>e.jsxs("tr",{children:[e.jsx("td",{children:i.get(r.modelId)??r.modelId}),e.jsx("td",{children:Se(r.kind)}),e.jsx("td",{children:Oe(r.method)}),e.jsx("td",{children:e.jsx(re,{label:Se(r.status),value:r.status})}),e.jsx("td",{children:Dt(r.updatedAt)})]},r.id))})]})}),l.length>10?e.jsx("div",{className:"labs-model-run-list-actions",children:e.jsx("button",{className:"training-button secondary labs-compact-button",type:"button",onClick:()=>s(r=>!r),children:a?"Show latest 10":`Show all ${l.length} runs`})}):null]}):e.jsx("div",{className:"labs-table-empty",children:"This Taskset has not been used in a submitted run yet."})}function It(t,n,a){const s=t.datasetArtifact?n?.datasetArtifacts.find(l=>l.tasksetId===t.id&&l.tasksetRevision===t.revision):null;return s?s.splitCounts[a]??0:t.tasks.filter(l=>l.split===a).length}function di(t){return t.readiness?.ready?"Ready":t.status==="ready"?"Needs Evals":t.status.replaceAll("_"," ").replace(/^./,n=>n.toUpperCase())}function Dt(t){const n=new Date(t);return Number.isFinite(n.getTime())?n.toLocaleDateString(void 0,{month:"short",day:"numeric"}):"—"}function ci({page:t,total:n,onChange:a}){const s=Math.max(1,Math.ceil(n/Lt));return s===1?null:e.jsxs("nav",{className:"labs-pagination","aria-label":"Taskset pages",children:[e.jsx("button",{type:"button",disabled:t<=1,onClick:()=>a(t-1),children:"Previous"}),e.jsxs("span",{children:[t," of ",s]}),e.jsx("button",{type:"button",disabled:t>=s,onClick:()=>a(t+1),children:"Next"})]})}function ui({baseModelCandidates:t,busy:n,defaultBenchmarkModel:a,initialName:s,onClose:l,onCreate:o,onManageModels:i,providerSettings:r}){const u=c.useMemo(()=>pi(t),[t]),[h,d]=c.useState(s),[j,b]=c.useState(""),[g,C]=c.useState(""),[k,f]=c.useState("train"),S=c.useMemo(()=>hi(r,a),[a,r]),[y,w]=c.useState(Ot(a)),[R,p]=c.useState(null),_=h.trim().replace(/\s+/g," ");async function x(m){if(m.preventDefault(),!_||n)return;p(null);const T=u.find(E=>E.selectionKey===g)??null;await o({name:_,description:j.trim()||null,defaultBaseModel:T?.preference??null,benchmarkModel:k==="benchmark"?mi(y):null,purpose:k})||p("OpenPond could not create the Model. Review the latest error and try again.")}return e.jsxs(_e,{ariaLabel:"New model",backdropClassName:"labs-rename-backdrop",className:"labs-rename-dialog labs-model-create-dialog",dismissDisabled:n,initialFocusKey:s,onClose:l,children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("h2",{children:"New model"}),e.jsx("p",{children:"Create the Model now. Tasksets, runs, and releases can be added later."})]}),e.jsx("button",{"aria-label":"Close new model",disabled:n,type:"button",onClick:l,children:e.jsx(Me,{size:16})})]}),e.jsxs("form",{onSubmit:m=>{x(m)},children:[e.jsxs("fieldset",{className:"labs-model-create-purpose",children:[e.jsx("legend",{children:"What do you want to do?"}),e.jsxs("button",{className:k==="train"?"selected":void 0,type:"button",onClick:()=>f("train"),children:[e.jsx("strong",{children:"Train a model"}),e.jsx("small",{children:"Create runs and trained Versions from your Tasksets."})]}),e.jsxs("button",{className:k==="benchmark"?"selected":void 0,type:"button",onClick:()=>f("benchmark"),children:[e.jsx("strong",{children:"Benchmark a model"}),e.jsx("small",{children:"Create the Model, then configure a controlled evaluation."})]})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Name"}),e.jsx("input",{"data-autofocus":!0,maxLength:200,required:!0,value:h,onChange:m=>d(m.currentTarget.value)})]}),e.jsxs("label",{children:[e.jsxs("span",{children:["Description ",e.jsx("small",{children:"Optional"})]}),e.jsx("textarea",{maxLength:5e3,rows:3,value:j,onChange:m=>b(m.currentTarget.value)})]}),k==="benchmark"?e.jsxs("label",{className:"labs-model-create-field",children:[e.jsx("span",{children:"Model to benchmark"}),e.jsx("select",{"aria-label":"Model to benchmark",value:y,onChange:m=>w(m.target.value),children:S.map(m=>e.jsx("optgroup",{label:m.providerLabel,children:m.models.map(T=>e.jsx("option",{value:T.value,children:T.label},T.value))},m.providerId))}),e.jsx("small",{children:"Uses the same chat-provider catalog as the composer. The choice is pinned in the saved benchmark receipt."})]}):e.jsxs("div",{className:"labs-model-create-field",children:[e.jsxs("span",{children:["Starting model ",e.jsx("small",{children:"Optional"})]}),e.jsxs("div",{className:"labs-model-create-select-row",children:[e.jsx(De,{label:"Starting model",value:g,options:[{value:"",label:"Choose later"},...u.map(m=>({value:m.selectionKey,label:`${m.label} · ${m.sourceLabel}${m.available?"":" · Unavailable"}`,disabled:!m.available}))],onChange:C}),e.jsx("button",{"aria-label":"Add starting model",className:"labs-model-create-add",disabled:n,title:"Manage models in Compute settings",type:"button",onClick:i,children:"+"})]})]}),R?e.jsx("div",{className:"labs-rename-error",role:"alert",children:R}):null,e.jsxs("footer",{children:[e.jsx("button",{disabled:n,type:"button",onClick:l,children:"Cancel"}),e.jsx("button",{disabled:!_||n,type:"submit",children:n?"Creating…":k==="benchmark"?"Create and benchmark":"Create model"})]})]})]})}function hi(t,n){const s=_n(t,{includeUnavailable:!1}).flatMap(o=>{const i=$n(o.value,t).map(r=>({label:r.label,value:Ot({providerId:o.value,modelId:r.value})}));return i.length?[{providerId:o.value,providerLabel:o.label,models:i}]:[]}),l=Ot(n);return s.some(o=>o.models.some(i=>i.value===l))?s:[{providerId:n.providerId,providerLabel:En(n.providerId,t),models:[{label:n.modelId,value:l}]},...s]}function Ot(t){return JSON.stringify([t.providerId,t.modelId])}function mi(t){try{const n=JSON.parse(t);return!Array.isArray(n)||n.length!==2||typeof n[0]!="string"||typeof n[1]!="string"?null:{providerId:n[0],modelId:n[1]}}catch{return null}}function pi(t){return t.filter(n=>!(n.preference.source==="builtin"&&n.nonProduction))}const bi=10;new Date(0).toISOString();function gi({items:t,loading:n,runs:a,state:s,emptyMessage:l="No Models yet.",onSelect:o,onUseModel:i}){return n?e.jsxs("div",{className:"labs-table-empty",children:[e.jsx(dt,{className:"spin",size:16})," Loading Models…"]}):t.length?e.jsx("div",{className:"training-table-wrap",children:e.jsxs("table",{className:"training-data-table labs-models-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Model"}),e.jsx("th",{children:"Availability"}),e.jsx("th",{children:"Recent run"}),e.jsx("th",{children:"Updated"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(r=>{const u=Qe(r,a,s),h=u.find(g=>g.current)??null,j=Ht(We(r,a,s),u,ct(r,s))[0]??null,b=j?.lifecycleRun?.status??j?.job?.status??"not_run";return e.jsxs("tr",{onClick:()=>o(r.key),children:[e.jsx("td",{children:e.jsxs("button",{className:"labs-workproduct-link",type:"button",onClick:()=>o(r.key),children:[e.jsx("strong",{children:r.name}),e.jsx("span",{children:r.description})]})}),e.jsx("td",{children:e.jsxs("div",{className:"labs-model-table-summary",children:[e.jsx(re,{label:h?"Hosted":"Not hosted",value:h?"ready":"not_run"}),e.jsx("span",{children:h?`Release ${h.number}`:"No active release"})]})}),e.jsx("td",{children:e.jsxs("div",{className:"labs-model-table-summary",children:[e.jsx(re,{label:Se(b),value:b}),e.jsx("span",{children:fi(j?.lifecycleRun??null,r.trainingRunCount)})]})}),e.jsx("td",{children:xi(r.updatedAt)}),e.jsx("td",{children:e.jsxs("div",{className:"labs-workproduct-actions",children:[e.jsx("button",{className:"training-button secondary labs-compact-button labs-workproduct-use",disabled:!h,title:h?"Chat with the active Version":"Set a passing Version active before Chat",type:"button",onClick:g=>{g.stopPropagation(),i(r.id)},children:"Chat"}),e.jsx(ba,{size:15})]})})]},r.key)})})]})}):e.jsx("div",{className:"labs-table-empty",children:l})}function fi(t,n){if(t?.kind==="evaluation"){const a=t.evaluation?.benchmarkId==="harness-refiner"?"Harness Refiner 08112026":"Benchmark",s=t.receipt?.schemaVersion==="openpond.modelEvaluationReceipt.v1"?t.receipt.attempts?.length?(()=>{const l=Be(t.receipt);return`${l.passedTaskCount}/${l.comparedTaskCount} passed`})():gn(t.receipt.terminalClassification.replaceAll("_"," ")):t.receipt?.schemaVersion==="openpond.modelEvaluationStopReceipt.v1"?"Inconclusive":t.evaluationProgress?`${gn(t.evaluationProgress.stage)} ${t.evaluationProgress.completedAttempts}/${t.evaluationProgress.totalAttempts}`:Se(t.status);return`${a} · ${s}`}return`${n} ${n===1?"run":"runs"}`}function xi(t){const n=new Date(t),a=new Date;return n.toDateString()===a.toDateString()?new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"}).format(n):new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",...n.getFullYear()===a.getFullYear()?{}:{year:"2-digit"}}).format(n)}function ji({page:t,total:n,onChange:a}){const s=Math.max(1,Math.ceil(n/bi));return s<=1?null:e.jsxs("nav",{className:"labs-pagination","aria-label":"Pagination",children:[e.jsx("button",{type:"button",disabled:t<=1,onClick:()=>a(t-1),children:"Previous"}),e.jsxs("span",{children:[t," of ",s]}),e.jsx("button",{type:"button",disabled:t>=s,onClick:()=>a(t+1),children:"Next"})]})}function gn(t){return t&&`${t[0].toUpperCase()}${t.slice(1).replaceAll("_"," ")}`}function vi(t){return t?[...t.jobs.map(n=>`job:${n.id}:${n.status}`),...t.models.map(n=>`model:${n.id}:${n.status}:${n.artifactId}:${n.jobId}`)].sort().join("|"):""}function yi({items:t,providerSettings:n,state:a,onClose:s,onOpenModel:l}){const o=c.useMemo(()=>Si(t,a),[t,a]),[i,r]=c.useState(o[0]?.run.id??""),[u,h]=c.useState(o[1]?.run.id??o[0]?.run.id??""),d=o.find(g=>g.run.id===i)??o[0]??null,j=o.find(g=>g.run.id===u)??o[1]??o[0]??null,b=d&&j?[d,j]:[];return e.jsxs(_e,{ariaLabel:"Compare benchmark runs",backdropClassName:"labs-rename-backdrop",className:"labs-rename-dialog labs-model-compare-dialog",onClose:s,children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Compare benchmark runs"}),e.jsx("p",{children:"Compare persisted results across models or across runs of one model."})]}),e.jsx("button",{"aria-label":"Close comparison",type:"button",onClick:s,children:e.jsx(Me,{size:16})})]}),e.jsx("div",{className:"labs-model-compare-body",children:o.length?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"labs-model-compare-selectors",children:[e.jsx(fn,{label:"First run",runs:o,value:d?.run.id??"",providerSettings:n,onChange:r}),e.jsx(fn,{label:"Second run",runs:o,value:j?.run.id??"",providerSettings:n,onChange:h})]}),b.length===2?e.jsxs(e.Fragment,{children:[e.jsx(Un,{series:b.map(g=>{const C=zn(g.receipt).candidate;return{id:g.run.id,label:Ci(g,n),inputTokens:C.inputTokens,outputTokens:C.outputTokens,tokens:C.totalTokens,passRate:g.receipt.quality.candidatePassRate,costUsd:C.costUsd}})}),e.jsx("div",{className:"labs-model-compare-facts",children:b.map(g=>e.jsxs("article",{children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("strong",{children:g.item.name}),e.jsx("span",{children:Kn(g.run,n)})]}),e.jsx("button",{className:"training-button secondary labs-compact-button",type:"button",onClick:()=>l(g.item.key),children:"View model"})]}),e.jsxs("dl",{children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Result"}),e.jsx("dd",{children:ki(g.receipt)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Quality"}),e.jsxs("dd",{children:[xn(g.receipt.quality.baselinePassRate)," → ",xn(g.receipt.quality.candidatePassRate)]})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"All-task token change"}),e.jsx("dd",{children:Ri(Be(g.receipt).tokenDeltaPercent)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Harness"}),e.jsx("dd",{children:g.receipt.stages.baseline.contentHash===g.receipt.stages.candidate.contentHash?"Unchanged":"Updated"})]})]})]},g.run.id))})]}):null]}):e.jsx("p",{className:"labs-model-benchmark-empty",children:"Complete a benchmark to make its saved result available here."})})]})}function ki(t){const n=Be(t);return`${n.passedTaskCount}/${n.comparedTaskCount} passed`}function fn({label:t,runs:n,value:a,providerSettings:s,onChange:l}){return e.jsxs("label",{children:[e.jsx("span",{children:t}),e.jsx("select",{value:a,onChange:o=>l(o.target.value),children:n.map(o=>e.jsxs("option",{value:o.run.id,children:[o.item.name," · ",Kn(o.run,s)," · ",$e(o.run.updatedAt)]},o.run.id))})]})}function Si(t,n){const a=new Map(t.map(s=>[s.id,s]));return n.modelRuns.flatMap(s=>{const l=a.get(s.modelId),o=Ni(s);return l&&o?[{item:l,receipt:o,run:s}]:[]}).sort((s,l)=>l.run.updatedAt.localeCompare(s.run.updatedAt))}function Ni(t){return t.receipt?.schemaVersion==="openpond.modelEvaluationReceipt.v1"?t.receipt:null}function Ci(t,n){return`${zt(t.run.evaluation?.model.modelId??"Unknown model",n,t.run.evaluation?.model.providerId)} · ${Ii(t.run.updatedAt)}`}function Kn(t,n){const a=t.evaluation?.model;return a?`${En(a.providerId,n)} / ${zt(a.modelId,n,a.providerId)}`:"Unknown model"}function xn(t){return`${Math.round(t*100)}%`}function Ri(t){return t===null?"Not comparable":`${t>0?"+":""}${t.toFixed(1)}%`}function Ii(t){return new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"}).format(new Date(t))}const jn=10;function Mi({activeProfileId:t,items:n,loading:a,providerSettings:s,runs:l,state:o,onSelect:i,onUseModel:r}){const[u,h]=c.useState("all"),[d,j]=c.useState(""),[b,g]=c.useState(1),[C,k]=c.useState(!1),f=o?.modelRuns.filter(p=>p.receipt?.schemaVersion==="openpond.modelEvaluationReceipt.v1").length??0,S=c.useMemo(()=>[...new Set(n.flatMap(p=>p.ownerProfileId?[p.ownerProfileId]:[]))].sort((p,_)=>p===t?-1:_===t?1:p.localeCompare(_)),[t,n]),y=c.useMemo(()=>{const p=d.trim().toLowerCase();return n.filter(_=>u!=="all"&&_.ownerProfileId!==u?!1:!p||[_.name,_.description,_.id,_.ownerProfileId??""].some(x=>x.toLowerCase().includes(p))).sort((_,x)=>x.updatedAt.localeCompare(_.updatedAt))},[n,u,d]),w=y.slice((b-1)*jn,b*jn),R=n.length?"No Models match this Profile or search.":"No Models exist in this workspace yet.";return e.jsxs("div",{className:"labs-flat-body labs-models-page",children:[e.jsxs("div",{className:"labs-workproduct-toolbar",children:[e.jsxs("label",{className:"labs-search",children:[e.jsx(Pn,{size:14}),e.jsx("input",{"aria-label":"Search Models",placeholder:"Search Models",value:d,onChange:p=>{j(p.target.value),g(1)}})]}),e.jsxs("div",{className:"labs-model-toolbar-actions",children:[e.jsx(De,{className:"labs-model-profile-filter",label:"Filter Models by Profile",value:u,options:[{value:"all",label:"All profiles"},...S.map(p=>({value:p,label:`${p}${p===t?" (active)":""}`}))],onChange:p=>{h(p),g(1)}}),e.jsx("button",{className:"training-button secondary",disabled:f<1,type:"button",onClick:()=>k(!0),children:"Compare runs"})]})]}),e.jsx(gi,{emptyMessage:R,items:w,loading:a,runs:l,state:o,onSelect:i,onUseModel:r}),e.jsx(ji,{page:b,total:y.length,onChange:g}),C&&o?e.jsx(yi,{items:n,providerSettings:s,state:o,onClose:()=>k(!1),onOpenModel:p=>{k(!1),i(p)}}):null]})}function Ai({state:t}){if(!t)return e.jsxs("div",{className:"labs-table-empty",children:[e.jsx(dt,{className:"spin",size:16})," Loading serving state…"]});const n=wi(t);return e.jsx("div",{className:"labs-flat-body labs-serving-page",children:e.jsxs("section",{className:"labs-operational-section","aria-labelledby":"managed-serving-title",children:[e.jsx("header",{children:e.jsxs("div",{children:[e.jsx("h2",{id:"managed-serving-title",children:"Managed serving"}),e.jsx("p",{children:"Durable adapter publication and binding state synchronized from OpenPond Managed training."})]})}),n.length?e.jsx("div",{className:"training-table-wrap",children:e.jsxs("table",{className:"training-data-table labs-managed-serving-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Model"}),e.jsx("th",{children:"Synchronization"}),e.jsx("th",{children:"Artifact"}),e.jsx("th",{children:"Deployment"}),e.jsx("th",{children:"Admission"}),e.jsx("th",{children:"Updated"})]})}),e.jsx("tbody",{children:n.map(a=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("span",{className:"labs-serving-model",children:[e.jsx("strong",{children:a.modelName}),e.jsx("span",{children:a.versionLabel})]})}),e.jsx("td",{children:e.jsx(re,{label:Mt(a.managed.state),value:a.managed.state})}),e.jsx("td",{children:Mt(a.managed.canonicalArtifactState)}),e.jsx("td",{children:Mt(a.managed.canonicalDeploymentState)}),e.jsx("td",{children:a.managed.customerBindingAllowed?"Allowed":"Pending"}),e.jsx("td",{children:Ti(a.updatedAt)})]},a.lineageId))})]})}):e.jsx("div",{className:"labs-table-empty",children:"No managed serving bindings are synchronized."})]})})}function wi(t){const n=new Map(t.modelProjects.map(s=>[s.id,s])),a=new Map(t.modelVersions.flatMap(s=>s.artifactLineageId?[[s.artifactLineageId,s]]:[]));return t.models.flatMap(s=>{if(!s.managedServing)return[];const l=a.get(s.id)??null,o=n.get(s.modelId)??null;return[{lineageId:s.id,modelName:o?.name??s.modelId,versionLabel:l?`Version ${l.version}`:s.id,managed:s.managedServing,updatedAt:s.managedServing.lastSyncedAt}]}).sort((s,l)=>l.updatedAt.localeCompare(s.updatedAt))}function Mt(t){return t?t.replaceAll("_"," ").replace(/^./,n=>n.toUpperCase()):"Pending"}function Ti(t){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(t))}function _i({account:t,connection:n,onError:a,onOpenSourceSession:s}){return e.jsxs("div",{className:"labs-flat-body labs-usage-page",children:[e.jsxs("header",{className:"labs-operational-header",children:[e.jsx("h2",{children:"Model usage"}),e.jsx("p",{children:"All recorded model calls for this account. Narrow the projection by provider, model, status, visibility, or time range."})]}),e.jsx(Ma,{account:t,connection:n,enabled:!0,modelFocused:!0,onError:a,onOpenSourceSession:s})]})}function $i({project:t,persisted:n,busy:a,dirty:s,canRun:l,pageReason:o,actionLabel:i,onProjectChange:r,onCancel:u,onSave:h,onLaunch:d}){const[j,b]=c.useState(!1),g=c.useRef(t.name);return e.jsxs("header",{className:"model-build-header",children:[e.jsx("div",{children:n?e.jsxs(e.Fragment,{children:[e.jsx("h1",{className:"model-build-name",children:"New run"}),e.jsx("p",{children:t.name})]}):j?e.jsx("input",{"aria-label":"Model name",autoFocus:!0,className:"model-build-name model-build-name-input",value:t.name,onBlur:()=>{r({...t,name:t.name.trim()||g.current,updatedAt:new Date().toISOString()}),b(!1)},onChange:C=>r({...t,name:C.target.value,updatedAt:new Date().toISOString()}),onKeyDown:C=>{C.key==="Enter"&&C.currentTarget.blur(),C.key==="Escape"&&(r({...t,name:g.current,updatedAt:new Date().toISOString()}),b(!1))}}):e.jsx("button",{"aria-label":`Rename ${t.name}`,className:"model-build-name model-build-name-button",type:"button",onClick:()=>{g.current=t.name,b(!0)},children:t.name})}),e.jsxs("div",{className:"model-build-actions",children:[e.jsx("button",{id:"model-run-editor-cancel",className:"training-button secondary",type:"button",disabled:a,onClick:u,children:"Cancel"}),e.jsx("button",{className:"training-button secondary",type:"button",disabled:a||!s||!t.name.trim(),onClick:h,children:"Save"}),e.jsx("span",{className:"model-build-run-control",title:o??i,children:e.jsx("button",{className:"training-button",type:"button",disabled:!l,onClick:d,children:i})})]})]})}function Pi(t){return t==="gspo-token"?"GSPO-token":t.toUpperCase()}function Bt(t){return t==="openpond/tiny-cpu-gpt2-fixture"?.01:2e-4}function Ei(t){const n=t.metadata.trainingMethod;if(typeof n=="string"&&n!=="none")return n;const a=t.readiness?.recommendedMethod;return a&&a!=="none"?a:"sft"}function Li(t){const n=new Set;for(const a of t.capabilities.compatibleMethods)(a==="sft"||a==="dpo"||a==="grpo"||a==="ppo")&&n.add(a);return t.readiness?.trainingPath?.bootstrap?.method==="sft"&&n.add("sft"),t.readiness?.trainingPath?.primaryMethod==="grpo"&&n.add("grpo"),t.readiness?.trainingPath?.primaryMethod==="ppo"&&n.add("ppo"),["sft","dpo","grpo","ppo"].filter(a=>n.has(a)).length>0?["sft","dpo","grpo","ppo"].filter(a=>n.has(a)):["sft"]}function Gn(t,n){return t.datasetArtifact?.splitCounts[n]??t.tasks.filter(a=>a.split===n).length}function Je(t){return t.replaceAll("_"," ").replace(/\b\w/g,n=>n.toUpperCase())}function Di(t,n){return n?t.find(a=>a.preference.modelId===n.modelId&&a.preference.source===n.source&&a.preference.revision===n.revision&&a.preference.modelAssetId===n.modelAssetId)??t.find(a=>a.preference.modelId===n.modelId)??null:null}function Oi(t,n,a){return t.find(s=>s.executionOptions.some(l=>l.destinationId===n&&l.available&&l.methods.includes(a)))??null}function Jn(t){return(t.split("/").at(-1)??t).replaceAll("-"," ").replace(/\b\w/g,a=>a.toUpperCase())}function vn(t){return{ready:"Ready",model_download_required:"Model download required",compute_setup_required:"Compute setup required",provider_managed:"Provider managed",unsupported:"Unsupported"}[t]??"Unsupported"}function Gt(t){return t==null?"size unknown":t<1024?`${t} B`:t<1024**2?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(0)} MB`}function Bi({busy:t,catalog:n,catalogError:a,selectedComputeTarget:s,modelSearch:l,onModelSearchChange:o,baseModelKey:i,baseModelCandidates:r,destinationId:u,method:h,onBaseModelChange:d,visibleCatalogModels:j,selectedCatalogCompatibility:b,selectedCatalogModel:g,configurationContent:C,inlineProviderApproval:k}){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"training-start-fields",children:e.jsxs("section",{className:"training-catalog-setup","aria-label":"Training compute and Model catalog",children:[e.jsxs("div",{className:"training-catalog-field",children:[e.jsx("span",{children:"Compute"}),e.jsx("strong",{children:n?"Automatic":"Resolving…"}),e.jsx("small",{children:s?.description??"The backend selects the available provider, device, runtime, and engine."})]}),a?e.jsx("p",{className:"training-catalog-error",children:a}):null,e.jsxs("label",{className:"training-catalog-field",children:[e.jsx("span",{children:"Base model"}),e.jsx("input",{"aria-label":"Search Model catalog",placeholder:"Search all known Models",type:"search",value:l,disabled:t||!n,onChange:f=>o(f.target.value)})]}),n?e.jsxs("div",{className:"training-model-catalog",role:"listbox","aria-label":"Available base Models",children:[j.map(f=>{const S=f.compatibilities.find(p=>p.targetId===s?.id&&p.methods.includes(h)),y=S?.state??"unsupported",w=S?.reason??`This target does not support ${h.toUpperCase()} for this Model.`,R=y!=="unsupported";return e.jsxs("button",{"aria-selected":f.selectionKey===i,className:`${f.selectionKey===i?"selected ":""}${R?"":"unsupported"}`,disabled:t||!R,role:"option",title:w,type:"button",onClick:()=>d(f.selectionKey,f.modelId),children:[e.jsxs("span",{children:[e.jsx("strong",{children:f.label}),e.jsxs("small",{children:[f.modelId," · ",f.source]})]}),e.jsx("span",{className:`training-preparation-state ${y}`,children:vn(y)}),w?e.jsx("small",{children:w}):null]},f.selectionKey)}),j.length===0?e.jsx("p",{children:"No Models match this search. Clear the search to see the full catalog."}):null]}):e.jsx("label",{className:"training-catalog-field",children:e.jsxs("select",{"aria-label":"Available base Models",value:i,disabled:t,onChange:f=>{const S=f.target.value,y=r.find(w=>w.selectionKey===S)?.preference.modelId??"";d(S,y)},children:[e.jsx("option",{value:"",disabled:!0,children:"Choose starting weights"}),r.map(f=>{const S=f.executionOptions.find(y=>y.destinationId===u&&y.methods.includes(h));return e.jsxs("option",{disabled:!S?.available,value:f.selectionKey,children:[f.label," · ",f.sourceLabel,S?.available?"":` — ${S?.unavailableReason??"Unsupported"}`]},f.selectionKey)})]})}),e.jsx("div",{className:"training-start-fields training-resolved-device",children:e.jsxs("label",{children:[e.jsx("span",{children:"Training engine"}),e.jsx("input",{readOnly:!0,value:s?.engineAdapterId??"Resolving…"})]})}),e.jsx("p",{className:"training-start-note",children:"The backend can change providers as availability changes. The exact provider and spend are shown before launch."})]})}),C,k,e.jsxs("section",{className:"training-preparation-summary","aria-label":"Preparation summary",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Preparation"}),e.jsx("span",{children:vn(b?.state??g?.preparationState??"unsupported")})]}),e.jsxs("dl",{className:"training-start-summary",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Model weights / cache"}),e.jsx("dd",{children:g?.cached?"Pinned revision is cached":g?.expectedBytes!=null?`${Gt(g.expectedBytes)} download after Run review`:"Resolved during Run review"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Worker image"}),e.jsx("dd",{children:"Backend-pinned immutable image"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Harness runtime"}),e.jsx("dd",{children:s?.runtimeAdapterId??"Resolving…"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Data movement"}),e.jsx("dd",{children:"Exact upload and artifact return shown before approval"})]})]}),e.jsx("p",{children:"Selection starts no download, connection, upload, provisioning, or spend. The top-level Run review shows exact actions and approvals."})]})]})}function Ui({open:t,busy:n,destinationId:a,baseModelId:s,approvalFields:l,prepared:o,preparedQuote:i,compatible:r,actionLabel:u,onClose:h,onConfirm:d}){return t?e.jsx("div",{className:"training-dialog-backdrop",role:"presentation",onMouseDown:n?void 0:h,children:e.jsxs("section",{"aria-label":"Review provider approval","aria-modal":"true",className:"training-dialog training-provider-approval-dialog",role:"dialog",onMouseDown:j=>j.stopPropagation(),children:[e.jsxs("div",{className:"training-dialog-header",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Review and run"}),e.jsxs("p",{children:[Je(a)," · ",Jn(s)]})]}),e.jsx("button",{"aria-label":"Close provider approval",disabled:n,type:"button",onClick:h,children:e.jsx(Me,{size:16})})]}),l,o?e.jsxs("dl",{className:"training-start-summary",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Exact quote"}),e.jsx("dd",{children:i==null?"Unavailable":`$${i.toFixed(2)}`})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Prepared data"}),e.jsxs("dd",{children:[Gt(o.bundle.totalSizeBytes)," · verified"]})]})]}):null,e.jsxs("div",{className:"training-dialog-actions",children:[e.jsx("button",{className:"training-button secondary",type:"button",disabled:n,onClick:h,children:"Cancel"}),e.jsx("button",{className:"training-button",type:"button",disabled:n||!r,onClick:d,children:u})]})]})}):null}function Fi({approvalPolicy:t,providerLabel:n,method:a,busy:s,exportApproved:l,maximumCostUsd:o,retentionDays:i,onManageProvider:r,onExportApprovedChange:u,onMaximumCostChange:h,onRetentionDaysChange:d}){return e.jsxs("fieldset",{className:"training-provider-approval",children:[e.jsx("legend",{children:"Provider approval"}),r?e.jsx("button",{className:"training-text-button",type:"button",disabled:s,onClick:r,children:t.settingsActionLabel??`Manage ${n}`}):null,e.jsxs("label",{className:"training-provider-consent",children:[e.jsx("input",{type:"checkbox",checked:l,disabled:s,onChange:j=>u(j.target.checked)}),e.jsx("span",{children:t.exportDescription??`Export only the approved train split to ${n}.`})]}),e.jsxs("div",{className:"training-start-fields",children:[e.jsxs("label",{children:[e.jsx("span",{children:"Maximum provider spend (USD)"}),e.jsx("input",{"aria-label":"Maximum provider spend (USD)",type:"number",min:t.minimumSpendUsd,max:t.maximumSpendUsd,step:.01,value:o??"",disabled:s,onChange:j=>h(j.target.valueAsNumber)})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Retention record (days)"}),e.jsx("input",{"aria-label":"Retention record (days)",type:"number",min:t.minimumRetentionDays,max:t.maximumRetentionDays,step:1,value:i,disabled:s,onChange:j=>d(j.target.valueAsNumber)})]})]}),e.jsx("p",{className:"training-start-note",children:"Approval is bound server-side to the signed-in OpenPond account at launch."}),a==="grpo"?e.jsx("p",{className:"training-start-note",children:t.methodRequirement}):null]})}function zi({busy:t,method:n,options:a,onSelect:s}){return e.jsx("div",{className:"training-method-tabs",role:"tablist","aria-label":"Training method",children:a.map(l=>e.jsxs("button",{"aria-selected":l===n,className:l===n?"active":"",disabled:t,role:"tab",type:"button",onClick:()=>s(l),children:[e.jsx("span",{children:Ra(l)}),e.jsx("strong",{children:Oe(l)})]},l))})}function Vi({method:t,trainingExamples:n,availableTrainExamples:a,approvedExamples:s,evaluationExamples:l,preparedQuote:o,selectedComputeTarget:i,approvalPresentation:r,maximumCostUsd:u,providerManaged:h,storagePath:d}){const j=i?.approvalPolicy??null,b=t==="grpo"||t==="ppo"?`${Math.min(n,a)} of ${a} approved train prompts`:t==="dpo"?`${Math.min(n,s)} of ${s} approved preference pairs`:`${Math.min(n,s||a)} approved example${n===1?"":"s"}`,g=j?r==="dialog"?"Reviewed when you Run":o==null?`Prepare a provider-validated quote · hard cap $${u!=null&&Number.isFinite(u)?u.toFixed(2):"—"}`:`$${o.toFixed(2)} · hard cap $${(u??0).toFixed(2)}`:"Provided before approval";return e.jsxs("dl",{className:"training-start-summary",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Training data"}),e.jsx("dd",{children:b})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Evaluation"}),e.jsxs("dd",{children:[l," test example",l===1?"":"s"]})]}),e.jsxs("div",{children:[e.jsx("dt",{children:o==null?"Estimate":"Exact quote"}),e.jsx("dd",{children:g})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Storage"}),e.jsx("dd",{children:h?"Portable output imported into app-managed storage":d??"App-managed storage"})]})]})}function qi({prepared:t,preparedQuote:n,maximumCostUsd:a}){const s=t.plan.recipe,l=s.method==="dpo"?s.policyModel.id:s.method==="ppo"?s.policyOptimization.policyModel.id:s.method==="sft"||s.method==="grpo"?s.baseModel.id:"",o=s.method==="grpo"?`RFT · ${Pi(s.loss.method)}`:`${Oe(s.method)} · ${s.parameterization.toUpperCase()}`;return e.jsxs("section",{className:"training-prepared-confirmation","aria-label":"Confirm paid training launch",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Ready to launch"}),e.jsx("span",{children:"The quote and prepared data are fixed to this confirmation."})]}),e.jsxs("dl",{className:"training-start-summary",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Account"}),e.jsx("dd",{children:t.approvalActor??"Local user"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Provider"}),e.jsx("dd",{children:Je(t.plan.destinationId)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Model"}),e.jsx("dd",{children:Jn(l)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Method"}),e.jsx("dd",{children:o})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Quote"}),e.jsx("dd",{children:n==null?"Unavailable":`$${n.toFixed(2)}`})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Maximum"}),e.jsx("dd",{children:a==null?"Unavailable":`$${a.toFixed(2)}`})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Retention"}),e.jsxs("dd",{children:[t.plan.dataPolicy.retentionDays," days"]})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Prepared data"}),e.jsxs("dd",{children:[Gt(t.bundle.totalSizeBytes)," · verified"]})]})]}),e.jsx("p",{children:"No provider dataset or job exists until you launch."})]})}function Hi({method:t,trainingExamples:n,maximumTrainingExamples:a,maxSteps:s,sequenceLength:l,maximumSequenceLength:o,rolloutMaxOutputTokens:i,maximumOutputTokens:r,defaultRolloutOutputTokens:u,rank:h,learningRate:d,rftLossMethod:j,rolloutGroupSize:b,rolloutConcurrency:g,onTrainingExamplesChange:C,onMaxStepsChange:k,onSequenceLengthChange:f,onRolloutMaxOutputTokensChange:S,onRankChange:y,onLearningRateChange:w,onRftLossMethodChange:R,onRolloutGroupSizeChange:p,onRolloutConcurrencyChange:_}){return e.jsxs("details",{className:"training-start-advanced",children:[e.jsx("summary",{children:"Advanced settings"}),e.jsxs("div",{className:"training-start-fields",children:[e.jsxs("label",{children:[e.jsx("span",{children:"Training examples"}),e.jsx("input",{type:"number",min:1,max:a,value:n,onChange:x=>C(Math.max(1,Math.min(a,x.target.valueAsNumber||1)))})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Optimizer steps"}),e.jsx("input",{type:"number",min:1,max:1e3,value:s,onChange:x=>k(x.target.valueAsNumber||1)})]}),e.jsxs("label",{children:[e.jsx("span",{children:t==="grpo"?"Prompt length":"Sequence length"}),e.jsx("input",{type:"number",min:16,max:o,value:l,onChange:x=>f(x.target.valueAsNumber||64)})]}),t==="grpo"?e.jsxs("label",{children:[e.jsx("span",{children:"Maximum output"}),e.jsx("input",{type:"number",min:16,max:r,value:i,onChange:x=>S(Math.max(16,Math.min(r,x.target.valueAsNumber||u)))})]}):null,e.jsxs("label",{children:[e.jsx("span",{children:"LoRA rank"}),e.jsx("input",{type:"number",min:1,max:256,value:h,onChange:x=>y(x.target.valueAsNumber||2)})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Learning rate"}),e.jsx("input",{type:"number",min:1e-6,max:.1,step:1e-4,value:d,onChange:x=>{const m=x.target.valueAsNumber;Number.isFinite(m)&&w(m)}})]}),t==="grpo"?e.jsxs(e.Fragment,{children:[e.jsxs("label",{children:[e.jsx("span",{children:"RL loss"}),e.jsxs("select",{"aria-label":"RL loss",value:j,onChange:x=>R(x.target.value),children:[e.jsx("option",{value:"dapo",children:"DAPO"}),e.jsx("option",{value:"grpo",children:"GRPO"}),e.jsx("option",{value:"gspo-token",children:"GSPO-token"})]})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Rollouts per prompt"}),e.jsx("input",{type:"number",min:2,max:16,value:b,onChange:x=>p(x.target.valueAsNumber||8)})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Concurrent rollouts"}),e.jsx("input",{type:"number",min:1,max:16,value:g,onChange:x=>_(x.target.valueAsNumber||4)})]})]}):null]})]})}const Ki=64,Gi=4096;function Ut(t,n=Gi){return Ta(t,{minimum:Ki,maximum:n})}function Ji(t){if(t.method!=="grpo"||t.destinationId!=="openpond_managed"||t.executionMode!=="provider_native")throw new Error("This Model improvement path requires OpenPond Managed GRPO.");const n=t.taskset.metadata.toolContractHash===kt||t.taskset.environment.metadata.toolContractHash===kt,a=t.taskset.graders.find(l=>l.rewardEligible),s=4;return{schemaVersion:"openpond.rftRecipe.v1",method:"grpo",parameterization:"lora",baseModel:Wi(t),dataset:{trainSplit:"train",validationSplit:"frozen_eval",maxPromptTokens:4096,maxExamples:t.trainingExamples,selectionStrategy:t.taskset.datasetArtifact?"rft_easy_curriculum_v1":"stable_hash_top_n"},lora:{rank:16},rollout:{groupSize:s,concurrency:4,maxTurns:n?15:1,maxOutputTokens:512,temperature:.8,topP:.95,seed:17},optimizer:{learningRate:1e-5,maxSteps:t.maxSteps},loss:{method:t.rftLossMethod??Wn(t.taskset),klBeta:null},reward:n?{graderId:"cross-system-exact-verifier",graderHash:"server-derived-grader-hash",environmentId:"cross-system-operations",environmentVersion:ga,toolContractHash:kt}:{graderId:a?.id??"math_final_answer",graderHash:"server-derived-grader-hash",environmentId:ja,environmentVersion:xa,toolContractHash:fa},resourceLimits:{wallTimeMs:18e5,maxRollouts:Math.max(s,t.maxSteps*s),maxPayloadBytes:1e6},policyOptimization:null}}function Wn(t){return t.sourceRefs.some(a=>{const s=a.metadata;return("repositoryId"in a?String(a.repositoryId):"").toLowerCase().includes("dapo-math")||a.title.toLowerCase().includes("dapo-math")||String(s.datasetName??"").toLowerCase().includes("dapo-math")})?"dapo":"grpo"}function yn(t,n,a,s){return t.find(o=>o.selectionKey===n)?.executionOptions.some(o=>o.destinationId===a&&o.methods.includes(s))?n:""}function Wi(t){return{id:t.baseModelId,revision:t.catalogModel?.revision??"provider-managed-model-resource-v1",tokenizerRevision:t.catalogModel?.tokenizerRevision??"provider-managed-tokenizer-v1",chatTemplateHash:t.catalogModel?.chatTemplateHash??"provider-managed-chat-template-v1"}}const Qi=4096,Xi=4096,Yi=64;function Zi(t){const[n,a]=c.useState(null),[s,l]=c.useState(null),[o,i]=c.useState(""),r=c.useMemo(()=>{if(n?.targets)return n.targets;const d=t.destinations.find(j=>j.destinationId===t.initialDestination)??t.destinations.find(j=>j.available);return d?[{id:"automatic",label:"Automatic",description:d.unavailableReason??"Server-reported training destination.",destinationId:d.destinationId,computeAdapterId:d.destinationId,runtimeAdapterId:"resolving",engineAdapterId:"resolving",methods:d.methods,capabilityPills:[Je(d.destinationId)],executionMode:"local_worker",approvalPolicy:null,limits:{maximumSequenceLength:Qi,maximumOutputTokens:Xi,maximumTrainingExamples:null},defaults:{loraRank:2,maxSteps:8,rolloutGroupSize:4,rolloutConcurrency:1,rolloutOutputTokens:Yi},available:d.available,unavailableReason:d.unavailableReason}]:[]},[n?.targets,t.destinations,t.initialDestination]),u=c.useMemo(()=>{const d=n?.models??[],j=o.trim().toLowerCase();return j?d.filter(b=>`${b.label} ${b.modelId} ${b.source}`.toLowerCase().includes(j)):d.filter(b=>b.source!=="search")},[n?.models,o]),h=r[0]?.id??"automatic";return c.useEffect(()=>{if(!t.connection)return;let d=!0;const j=o.trim().length>=2?o.trim():"",b=window.setTimeout(()=>{lt.portableTrainingCatalog(t.connection,j,t.method).then(g=>{d&&(a(g),l(null))}).catch(g=>{d&&l(g instanceof Error?g.message:"The Model registry search could not be completed.")})},j?250:0);return()=>{d=!1,window.clearTimeout(b)}},[t.connection,t.method,o]),{catalog:n,catalogError:s,catalogTargets:r,visibleCatalogModels:u,computeTargetId:h,modelSearch:o,setModelSearch:i}}const el=64;function tl(t){const n=t.taskset.readiness?.trainingPath??null,a=n?.primaryMethod??Ei(t.taskset),s=n?.bootstrap??null,l=Li(t.taskset),o=t.initialMethod&&l.includes(t.initialMethod)?t.initialMethod:a==="grpo"?"grpo":a==="dpo"?"dpo":a==="ppo"?"ppo":"sft",i=t.runPreset==="small"||t.runPreset==="small_experiment",r=Di(t.baseModelCandidates,t.preferredBaseModel),u=r?.executionOptions.find(Q=>Q.available&&Q.methods.includes(o))??null,h=u?.destinationId??t.destinations.find(Q=>Q.available)?.destinationId??"openpond_managed",d=u?r:Oi(t.baseModelCandidates,h,o),j=Gn(t.taskset,"train"),[b,g]=c.useState(h),[C,k]=c.useState(d?.selectionKey??""),[f,S]=c.useState(()=>i&&o!=="grpo"?1:o==="grpo"?t.runPreset==="standard"?50:8:o==="dpo"?t.runPreset==="standard"?100:4:o==="ppo"?t.runPreset==="standard"?20:2:t.runPreset==="standard"?100:2),[y,w]=c.useState(()=>Math.max(1,Math.min(j,o==="dpo"?i?2:t.taskset.learningSignals.preferences.filter(Q=>Q.approved).length:o==="ppo"?i?2:t.runPreset==="standard"?16:4:o==="grpo"&&t.taskset.datasetArtifact?t.runPreset==="standard"?32:16:i?4:1e3))),[R,p]=c.useState(()=>Ut(t.taskset)),[_,x]=c.useState(2),[m,T]=c.useState(()=>Bt(d?.preference.modelId??"")),[V,E]=c.useState(!1),[$,Z]=c.useState(null),[K,ee]=c.useState(7),[M,H]=c.useState(8),[B,G]=c.useState(4),[de,F]=c.useState(el),[ne,J]=c.useState(()=>Wn(t.taskset)),[ae,X]=c.useState(o),[N,q]=c.useState(null),[D,te]=c.useState(!1);return{primaryMethod:a,bootstrap:s,methodOptions:l,quickTest:i,initialDestination:h,availableTrainExamples:j,destinationId:b,setDestinationId:g,baseModelKey:C,setBaseModelKey:k,maxSteps:f,setMaxSteps:S,trainingExamples:y,setTrainingExamples:w,sequenceLength:R,setSequenceLength:p,rank:_,setRank:x,learningRate:m,setLearningRate:T,exportApproved:V,setExportApproved:E,maximumCostUsd:$,setMaximumCostUsd:Z,retentionDays:K,setRetentionDays:ee,rolloutGroupSize:M,setRolloutGroupSize:H,rolloutConcurrency:B,setRolloutConcurrency:G,rolloutMaxOutputTokens:de,setRolloutMaxOutputTokens:F,rftLossMethod:ne,setRftLossMethod:J,method:ae,setMethod:X,prepared:N,setPrepared:q,providerApprovalOpen:D,setProviderApprovalOpen:te}}const kn=4096,nl=4096,Sn=64;function al({baseModelCandidates:t,connection:n,taskset:a,modelId:s=null,destinations:l,initialMethod:o,preferredBaseModel:i=null,busy:r,onClose:u,onStart:h,onPrepare:d,onConfirmPrepared:j,onOpenProviderSettings:b,presentation:g="dialog",runControlId:C,hideActions:k=!1,onReadinessChange:f,onConfigurationChange:S,runPreset:y="custom",hideMethodTabs:w=!1,approvalPresentation:R="inline",configurationContent:p}){const{primaryMethod:_,bootstrap:x,methodOptions:m,quickTest:T,initialDestination:V,availableTrainExamples:E,destinationId:$,setDestinationId:Z,baseModelKey:K,setBaseModelKey:ee,maxSteps:M,setMaxSteps:H,trainingExamples:B,setTrainingExamples:G,sequenceLength:de,setSequenceLength:F,rank:ne,setRank:J,learningRate:ae,setLearningRate:X,exportApproved:N,setExportApproved:q,maximumCostUsd:D,setMaximumCostUsd:te,retentionDays:Q,setRetentionDays:le,rolloutGroupSize:Ae,setRolloutGroupSize:fe,rolloutConcurrency:ue,setRolloutConcurrency:I,rolloutMaxOutputTokens:L,setRolloutMaxOutputTokens:he,rftLossMethod:oe,setRftLossMethod:me,method:v,setMethod:O,prepared:W,setPrepared:pe,providerApprovalOpen:se,setProviderApprovalOpen:ve}=tl({baseModelCandidates:t,preferredBaseModel:i,destinations:l,taskset:a,initialMethod:o,runPreset:y}),{catalog:we,catalogError:Pe,catalogTargets:Te,visibleCatalogModels:Xe,computeTargetId:Ue,modelSearch:mt,setModelSearch:Ee}=Zi({connection:n,destinations:l,initialDestination:V,method:v}),Ne=l.find(P=>P.destinationId===$)??null,Ye=v==="sft"&&_!=="sft"&&x?.method==="sft",Fe=v==="dpo"?a.learningSignals.preferences.filter(P=>P.approved).length:a.learningSignals.demonstrations.filter(P=>P.approved).length,Ze=Gn(a,"frozen_eval"),Ce=t.find(P=>P.selectionKey===K)??null,ze=Ce?.executionOptions.find(P=>P.destinationId===$&&P.methods.includes(v))??null,Ve=Ce?.preference.modelId??"",U=Te.find(P=>P.id===Ue)??null,A=c.useRef(null),ge=we?.models.find(P=>P.selectionKey===K)??null,Re=ge?.compatibilities.find(P=>P.targetId===U?.id&&P.methods.includes(v))??null,z=U?.approvalPolicy??null,pt=U?.executionMode==="provider_native",bt=z?.providerLabel??"provider";c.useEffect(()=>{if(!U||U.destinationId!==$)return;const P=JSON.stringify({destinationId:U.destinationId,defaults:U.defaults,approvalPolicy:U.approvalPolicy});A.current!==P&&(A.current=P,J(U.defaults.loraRank),fe(U.defaults.rolloutGroupSize),I(U.defaults.rolloutConcurrency),he(U.defaults.rolloutOutputTokens),H(U.defaults.maxSteps),te(U.approvalPolicy?.defaultMaximumSpendUsd??null),le(U.approvalPolicy?.defaultRetentionDays??7),U.destinationId==="openpond_managed"&&(X(1e-5),F(4096)))},[$,U,X,H,te,J,le,I,fe,he,F]);const Zn=U?.limits.maximumSequenceLength??kn,ea=U?.limits.maximumOutputTokens??nl,ta=v==="dpo"?Math.max(1,a.learningSignals.preferences.filter(P=>P.approved).length):v==="ppo"?Math.max(1,Math.min(1e3,E)):v==="grpo"&&pt&&a.datasetArtifact?Math.max(1,Math.min(U?.limits.maximumTrainingExamples??E,E)):Math.max(1,Math.min(1e5,E)),na=!z||(!z.exportApprovalRequired||N)&&D!=null&&D>=z.minimumSpendUsd&&D<=z.maximumSpendUsd&&Number.isInteger(Q)&&Q>=z.minimumRetentionDays&&Q<=z.maximumRetentionDays,Jt=U?.methods.includes(v)??Ne?.methods.includes(v)??!1,aa=a.capabilities.compatibleMethods.includes(v)||x?.method===v,gt=!!(a.readiness?.ready&&Jt&&Ne?.available&&Ne.methods.includes(v)&&aa&&ze?.available&&Re?.state!=="unsupported"&&Re?.state!=="compute_setup_required"&&Ce?.preference.source!=="local"),et=gt&&na,tt=a.readiness?.ready?Jt?Re?.state==="unsupported"||Re?.state==="compute_setup_required"?Re.reason??"The selected Model and compute target are not ready.":Ce?ze?.available?Ne?.methods.includes(v)?Ne?.unavailableReason??null:`${Je($)} does not execute ${v.toUpperCase()}.`:ze?.unavailableReason??"The selected base model cannot run on this compute destination.":`Choose starting weights compatible with ${Je($)} and ${v.toUpperCase()}.`:`${v.toUpperCase()} is the primary recommendation but no compatible execution backend is available here.${x?" Choose the optional SFT trajectory bootstrap to run the local precursor.":""}`:"The Taskset must pass environment, grader, and data readiness before training.",ft=tt??(z?.exportApprovalRequired&&!N?`Approve the bounded train-split export before launching ${bt}.`:z&&(D==null||D<z.minimumSpendUsd||D>z.maximumSpendUsd)?`Set a ${bt} cap from $${z.minimumSpendUsd.toFixed(2)} through $${z.maximumSpendUsd.toFixed(2)}.`:z&&(!Number.isInteger(Q)||Q<z.minimumRetentionDays||Q>z.maximumRetentionDays)?"Choose a provider retention record from 1 through 30 days.":null),nt=Ji({method:v,taskset:a,destinationId:$,baseModelId:Ve,maxSteps:M,trainingExamples:B,rftLossMethod:oe,executionMode:U?.executionMode,catalogModel:ge}),at={exportApproved:z?N:!0,maximumCostUsd:z?D:0,retentionDays:z?Q:null,region:null},xt=JSON.stringify({modelId:s,destinationId:$,recipe:nt,approval:at}),ye=W?.configurationKey===xt?W.value:null;async function Wt(){if(!et)return;if(z?.preparationRequired&&!ye){const Y=await d($,nt,at);Y&&pe({configurationKey:xt,value:Y});return}(z?.preparationRequired&&ye?await j(ye,D??0):await h($,nt,at))&&(ve(!1),u())}async function Qt(){if(gt){if(z&&R==="dialog"){ve(!0);return}await Wt()}}function sa(P,Y=Te.find(yt=>yt.destinationId===P)){Z(P),ee(yt=>yn(t,yt,P,v)),J(Y?.defaults.loraRank??2),fe(Y?.defaults.rolloutGroupSize??4),I(Y?.defaults.rolloutConcurrency??1),he(Y?.defaults.rolloutOutputTokens??Sn),X(P==="openpond_managed"?1e-5:Bt(Ve)),te(Y?.approvalPolicy?.defaultMaximumSpendUsd??null),le(Y?.approvalPolicy?.defaultRetentionDays??7),q(!1),v==="grpo"?(H(Y?.defaults.maxSteps??8),a.datasetArtifact&&Y?.executionMode==="provider_native"&&G(Math.max(1,Math.min(E,Y.limits.maximumTrainingExamples??16))),F(Math.min(Y?.limits.maximumSequenceLength??kn,Math.max(512,Ut(a,Y?.limits.maximumSequenceLength))))):F(Ut(a,Y?.limits.maximumSequenceLength))}function ia(P){if(O(P),pe(null),ee(Y=>yn(t,Y,$,P)),P==="grpo"){H(8),pt&&a.datasetArtifact&&F(Y=>Math.max(512,Y)),G(Math.max(1,Math.min(E,a.datasetArtifact?16:1e3)));return}if(H(T?1:P==="dpo"?4:2),P==="dpo"){G(Math.max(1,Math.min(a.learningSignals.preferences.filter(Y=>Y.approved).length,T?2:64)));return}if(P==="ppo"){G(Math.max(1,Math.min(E,T?2:4)));return}G(Math.max(1,Math.min(E,T?4:32)))}const qe=ye?.plan.estimatedCostUsd??null,jt=r?ye?"Launching…":z?.preparationRequired?"Preparing…":"Starting…":ye&&qe!=null?`Launch $${qe.toFixed(2)} job`:z?.preparationRequired?"Prepare exact quote":"Start training",He=R==="dialog"&&z?gt:et,vt=R==="dialog"&&z?"Run":jt;c.useEffect(()=>{U&&sa(U.destinationId,U)},[U?.id,U?.destinationId]),c.useEffect(()=>{f?.({ready:He,reason:He?null:R==="dialog"&&z?tt??"This setup is unavailable.":ft??"This setup is unavailable.",actionLabel:vt})},[R,tt,z,ft,f,vt,He]),c.useEffect(()=>{S?.({baseModel:Ce?.preference??null,method:v,destinationId:$,recipe:nt,approval:at})},[xt,S]);const Xt=z?e.jsx(Fi,{approvalPolicy:z,providerLabel:bt,method:v,busy:r,exportApproved:N,maximumCostUsd:D,retentionDays:Q,onManageProvider:b?()=>{R==="dialog"?ve(!1):u(),b()}:void 0,onExportApprovedChange:q,onMaximumCostChange:te,onRetentionDaysChange:le}):null,Yt=e.jsxs("section",{className:`training-dialog training-start-dialog${g==="embedded"?" embedded":""}${w?" hide-method-tabs":""}`,role:g==="dialog"?"dialog":"region","aria-modal":g==="dialog"?"true":void 0,"aria-label":"Start training",onMouseDown:P=>P.stopPropagation(),children:[g==="dialog"?e.jsxs("div",{className:"training-dialog-header",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Start training"}),e.jsx("p",{children:a.name})]}),e.jsx("button",{type:"button","aria-label":"Close start training",disabled:r,onClick:u,children:e.jsx(Me,{size:16})})]}):null,w?null:e.jsx(zi,{busy:r,method:v,options:m,onSelect:ia}),e.jsx(Bi,{busy:r,catalog:we,catalogError:Pe,selectedComputeTarget:U,modelSearch:mt,onModelSearchChange:Ee,baseModelKey:K,baseModelCandidates:t,destinationId:$,method:v,onBaseModelChange:(P,Y)=>{ee(P),X(Bt(Y))},visibleCatalogModels:Xe,selectedCatalogCompatibility:Re,selectedCatalogModel:ge,configurationContent:p,inlineProviderApproval:R==="inline"?Xt:null}),e.jsx(Vi,{method:v,trainingExamples:B,availableTrainExamples:E,approvedExamples:Fe,evaluationExamples:Ze,preparedQuote:qe,selectedComputeTarget:U,approvalPresentation:R,maximumCostUsd:D,providerManaged:pt,storagePath:null}),R==="inline"&&ye?e.jsx(qi,{prepared:ye,preparedQuote:qe,maximumCostUsd:D}):null,Ye&&x?e.jsxs("div",{className:"training-bootstrap-limitations",children:[e.jsx("strong",{children:"Supervised precursor"}),e.jsx("p",{children:"This SFT run teaches the approved tool trajectories. It does not replace reinforcement training."}),e.jsx("ul",{children:x.limitations.map(P=>e.jsx("li",{children:P},P))})]}):null,e.jsx(Hi,{method:v,trainingExamples:B,maximumTrainingExamples:ta,maxSteps:M,sequenceLength:de,maximumSequenceLength:Zn,rolloutMaxOutputTokens:L,maximumOutputTokens:ea,defaultRolloutOutputTokens:U?.defaults.rolloutOutputTokens??Sn,rank:ne,learningRate:ae,rftLossMethod:oe,rolloutGroupSize:Ae,rolloutConcurrency:ue,onTrainingExamplesChange:G,onMaxStepsChange:H,onSequenceLengthChange:F,onRolloutMaxOutputTokensChange:he,onRankChange:J,onLearningRateChange:X,onRftLossMethodChange:me,onRolloutGroupSizeChange:fe,onRolloutConcurrencyChange:I}),He?Ne?.nonProduction?e.jsx("p",{className:"training-start-note",children:"This local worker is an experimental correctness run. It does not claim useful model quality."}):null:e.jsx("div",{className:"training-banner error training-dialog-error",children:R==="dialog"&&z?tt??"This setup is unavailable.":ft??"This setup is unavailable."}),k?e.jsx("button",{id:C,hidden:!0,type:"button",disabled:r||!He,onClick:()=>{Qt()},children:vt}):e.jsxs("div",{className:"training-dialog-actions",children:[e.jsx("button",{className:"training-button secondary",type:"button",disabled:r,onClick:u,children:"Cancel"}),e.jsx("button",{id:C,className:"training-button",type:"button",disabled:r||!et,onClick:()=>{Qt()},children:jt})]})]}),la=e.jsx(Ui,{open:R==="dialog"&&!!z&&se,busy:r,destinationId:$,baseModelId:Ve,approvalFields:Xt,prepared:ye,preparedQuote:qe,compatible:et,actionLabel:jt,onClose:()=>ve(!1),onConfirm:()=>{Wt()}});return g==="embedded"?e.jsxs(e.Fragment,{children:[Yt,la]}):e.jsx("div",{className:"training-dialog-backdrop",role:"presentation",onMouseDown:r?void 0:u,children:Yt})}const sl=[{id:"dataset",label:"Taskset"},{id:"method",label:"Training method"},{id:"configuration",label:"Model and compute"}];function il({activeStep:t,steps:n,onStepChange:a}){return e.jsx("ol",{className:"model-setup-step-list","aria-label":"Run setup progress",children:n.map((s,l)=>e.jsx("li",{className:[t===s.id?"active":"",s.complete?"complete":""].filter(Boolean).join(" "),children:e.jsxs("button",{"aria-current":t===s.id?"step":void 0,type:"button",onClick:()=>a(s.id),children:[e.jsxs("span",{className:"model-setup-step-label",children:[l+1,". ",s.label]}),e.jsx("span",{className:"model-setup-step-segment","aria-hidden":"true"})]})},s.id))})}const ll=["sft","dpo","grpo","ppo"];function Qn(t,n,a,s){const l=new Date().toISOString(),o=crypto.randomUUID();return{schemaVersion:"openpond.modelProject.v1",id:a??`model_${o}`,profileId:t,name:s?.trim()||"Model #1",objective:n,defaultBaseModel:null,defaultDestinationId:null,createdAt:l,updatedAt:l}}function ol(t){return t.tasksetRef?t.method?"configuration":"method":"dataset"}function rl(t,n,a,s){return t==="dataset"?!!a:t==="method"?!!n.method:s}function Xn(t){let n=t.length;for(const a of t){const s=/^Model #(\d+)$/.exec(a.name.trim());s&&(n=Math.max(n,Number(s[1])))}return`Model #${n+1}`}function dl(t,n){const a=new Date().toISOString();return{schemaVersion:"openpond.modelRunDraft.v1",id:`run_draft_${crypto.randomUUID()}`,profileId:t,modelId:n,status:"draft",title:"Run draft",datasetMode:null,tasksetRef:null,datasetCreationId:null,buildIntent:null,buildSpecification:null,baseModel:null,method:null,destinationId:null,managedRolloutPlacement:"local",runPreset:null,recipe:null,createdAt:a,updatedAt:a}}function Nn(t,n){return{...t,datasetMode:"existing",tasksetRef:{id:n.id,revision:n.revision,contentHash:n.contentHash},buildIntent:t.buildIntent??ul(n),updatedAt:new Date().toISOString()}}function cl(t){const n=new Date().toISOString();return{...t,id:`run_draft_${crypto.randomUUID()}`,status:"draft",title:"Run draft",createdAt:n,updatedAt:n}}function ul(t){return t.capabilities.supportedSignals.includes("preference")||t.capabilities.compatibleMethods.includes("dpo")?"preferences":t.capabilities.supportedSignals.includes("reward")||t.capabilities.compatibleMethods.includes("grpo")||t.capabilities.compatibleMethods.includes("ppo")?"verifiable_reward":t.capabilities.supportedSignals.includes("label")?"rubric":"demonstrations"}function At(t,n){const{updatedAt:a,...s}=t,{updatedAt:l,status:o,...i}=n;return JSON.stringify({project:s,draft:i})}function hl(t,n,a,s){if(!t.name.trim())return"Name this Model.";if(!n.datasetMode)return"Choose a Taskset.";if(!a)return"Choose a Taskset to enable Run.";if(!n.method)return"Choose a training method.";const l=a.readiness?.methodReadiness.find(o=>o.method===n.method);return l?.status==="needs_dataset_work"?l.reasons[0]??"Resolve Taskset readiness for this method.":n.runPreset?n.baseModel?n.destinationId?s.ready?null:s.reason??"Complete the launch checks.":"Choose a compatible destination.":"Choose a base model.":n.method==="grpo"||n.method==="ppo"?"Choose an experiment size.":"Choose a run size."}function ml(t){const n=t.downloads.length?t.downloads.map(l=>`${l.label}: ${Rn(l.diskImpactBytes)} (${l.state})`).join("; "):"No downloads",a=t.dataMovement.length?t.dataMovement.map(l=>`${l.label}: ${l.direction}${l.bytes==null?"":` ${Rn(l.bytes)}`}`).join("; "):"No remote data movement",s=t.quoteUsd==null?"No provider spend quoted":`Quote $${t.quoteUsd.toFixed(2)}; maximum $${t.maximumSpendUsd?.toFixed(2)??"not set"}`;return[`${xl(t.state)}${t.reason?` — ${t.reason}`:""}.`,`Downloads: ${n}.`,`Data: ${a}.`,`${s}. Retention: ${t.retentionDays==null?"local policy":`${t.retentionDays} days`}.`,"No side effects have started. Confirming may begin downloads, connections, uploads, provisioning, or spend."].join(" ")}function pl(t,n){return ll.map(a=>{const s=t?.readiness?.methodReadiness.find(u=>u.method===a),l=!!(t&&(t.capabilities.compatibleMethods.includes(a)||t.readiness?.trainingPath?.bootstrap?.method===a)),o=n.some(u=>u.available&&u.methods.includes(a)),i=s?.status==="needs_dataset_work"?"Needs Taskset work":l?o?s?.status==="recommended"?"Recommended":"Compatible":"Destination unavailable":"Incompatible Taskset",r=s?.reasons[0]??(l?o?fl(a):`No configured destination currently executes ${a.toUpperCase()}.`:`This Taskset revision does not contain the evidence required for ${a.toUpperCase()}.`);return{method:a,state:i,reason:r,executionTargets:bl(a,n),available:l&&s?.status!=="needs_dataset_work"&&o}})}function bl(t,n){return[gl(t,"openpond_managed","OpenPond Managed",n)]}function gl(t,n,a,s){const l=s.find(r=>r.destinationId===n),o="OpenPond Managed",i=!!l?.methods.includes(t);return{id:n,label:a,available:!!(l?.available&&i),reason:l?i?l.unavailableReason??`${o} is not available in this environment.`:`${o} does not execute ${t.toUpperCase()}.`:`${o} capabilities have not loaded.`}}function fl(t){return t==="sft"?"Imitate approved responses with assistant-only loss.":t==="dpo"?"Increase the margin between chosen and rejected responses.":t==="grpo"?"Sample grouped responses and optimize executable rewards.":"Optimize a policy with a separately tracked value model."}function Yn(t){return t==="grpo"||t==="ppo"?[{id:"small_experiment",label:"Quick test",description:"Bound prompts, rollouts, output tokens, steps, time, and spend."},{id:"standard",label:"Recommended",description:"Use the Taskset-aware recommended online budgets."},{id:"custom",label:"Custom",description:"Set each rollout and optimizer limit explicitly."}]:[{id:"small",label:"Quick test",description:"A bounded LoRA experiment with independent frozen evaluation."},{id:"standard",label:"Recommended",description:"Use Taskset-aware recommended examples and optimizer limits."},{id:"custom",label:"Custom",description:"Set examples, steps, sequence length, rank, time, and spend."}]}function Cn(t,n){return Yn(t).find(a=>a.id===(n??"standard"))}function xl(t){return t.replaceAll("_"," ").replace(/^\w/,n=>n.toUpperCase())}function Rn(t){return t<1024?`${t} B`:t<1024**2?`${(t/1024).toFixed(1)} KB`:t<1024**3?`${(t/1024**2).toFixed(1)} MB`:`${(t/1024**3).toFixed(1)} GB`}const jl="model-build-run-control";function vl({activeStep:t,onStepChange:n,draft:a,setDraft:s,selectedTaskset:l,methodCards:o,tasksets:i,baseModelCandidates:r,destinations:u,connection:h,training:d,canRun:j,onSelectTaskset:b,onOpenDatasetBuilder:g,onLaunchStateChange:C,onConfigurationChange:k,onOpenProviderSettings:f,onFinished:S}){return e.jsxs(e.Fragment,{children:[e.jsx(il,{activeStep:t,steps:sl.map(y=>({...y,complete:rl(y.id,a,l,j)})),onStepChange:n}),t==="dataset"?e.jsxs("section",{className:"model-build-section",children:[e.jsx("div",{className:"model-build-section-heading",children:e.jsxs("div",{children:[e.jsx("h2",{children:"Choose a Taskset"}),e.jsx("p",{children:"Use a ready Taskset, or create one conversationally in Chat."})]})}),e.jsx("div",{className:"model-build-dataset-step",children:e.jsxs("div",{className:"model-build-existing-dataset",children:[e.jsxs("div",{className:"model-build-field",children:[e.jsx("span",{children:"Taskset revision"}),e.jsx(De,{label:"Taskset revision",value:l?.id??"",options:[{value:"",label:i.length?"Select a Taskset":"No Tasksets yet",disabled:i.length===0},...i.map(y=>({value:y.id,label:`${y.name} · r${y.revision} · ${y.readiness?.ready?"ready":"needs work"}`}))],onChange:y=>{const w=i.find(R=>R.id===y);w&&b(w)}})]}),e.jsx("button",{className:"training-button secondary",type:"button",onClick:g,children:a.datasetMode==="build"?"Continue building Taskset":"Build a Taskset"})]})})]}):t==="method"?e.jsxs("section",{className:"model-build-section",children:[e.jsx("div",{className:"model-build-section-heading",children:e.jsx("h2",{children:"Choose a training method"})}),e.jsx("div",{className:"model-build-method-grid",children:o.map(y=>e.jsxs("button",{className:a.method===y.method?"model-build-method selected":"model-build-method",type:"button",disabled:!y.available,title:y.available?void 0:y.reason,onClick:()=>{s(w=>({...w,method:y.method,runPreset:"standard",recipe:null,updatedAt:new Date().toISOString()})),n("configuration")},children:[e.jsxs("span",{children:[e.jsx("strong",{children:y.method.toUpperCase()}),e.jsx("em",{children:y.state})]}),e.jsx("small",{children:y.reason}),e.jsx("span",{className:"model-build-method-targets","aria-label":"Execution targets",children:y.executionTargets.map(w=>e.jsx("span",{"aria-label":`${w.label}: ${w.available?"available":w.reason}`,className:w.available?"model-build-target-pill available":"model-build-target-pill unavailable",title:w.available?void 0:w.reason,children:w.label},w.id))}),e.jsx("span",{className:"training-choice-indicator","aria-hidden":"true"})]},y.method))})]}):e.jsxs("section",{className:"model-build-section",children:[e.jsx("div",{className:"model-build-section-heading",children:e.jsxs("div",{children:[e.jsx("h2",{children:"Choose a model"}),e.jsx("p",{children:"Select the starting model and where it will train."})]})}),l&&(a.method==="sft"||a.method==="dpo"||a.method==="grpo"||a.method==="ppo")?e.jsx(al,{baseModelCandidates:r,connection:h,taskset:l,modelId:a.modelId,destinations:u,initialMethod:a.method,preferredBaseModel:a.baseModel,busy:["prepare-training","prepare-model-run","start-prepared-training","start-training","start-model-run"].includes(d.busyAction??""),busyAction:d.busyAction,presentation:"embedded",hideActions:!0,runControlId:jl,runPreset:a.runPreset??"standard",hideMethodTabs:!0,approvalPresentation:"dialog",configurationContent:e.jsxs("details",{className:"model-run-options",children:[e.jsxs("summary",{children:[e.jsx("span",{children:"Training configuration"}),e.jsx("strong",{children:Cn(a.method,a.runPreset)?.label??"Recommended"})]}),e.jsxs("div",{className:"model-build-field",children:[e.jsx("span",{children:"Training budget"}),e.jsx(De,{label:"Training budget",value:a.runPreset??"standard",options:Yn(a.method).map(y=>({value:y.id,label:y.label})),onChange:y=>s(w=>({...w,runPreset:y,recipe:null,updatedAt:new Date().toISOString()}))}),e.jsx("small",{children:Cn(a.method,a.runPreset)?.description??"Use Taskset-aware recommended limits."})]}),a.destinationId==="openpond_managed"?e.jsxs("div",{className:"model-build-field",children:[e.jsx("span",{children:"Rollout execution"}),e.jsx(De,{label:"Rollout execution",value:a.managedRolloutPlacement??"local",options:[{value:"local",label:"This desktop"},{value:"remote",label:"Hosted Sandboxes"}],onChange:y=>s(w=>({...w,managedRolloutPlacement:y==="remote"?"remote":"local",updatedAt:new Date().toISOString()}))}),e.jsx("small",{children:"This desktop keeps local integrations and provider credentials on this device. Hosted Sandboxes can run unattended."})]}):null]}),onReadinessChange:C,onConfigurationChange:k,onClose:()=>{},onOpenProviderSettings:f,onPrepare:(y,w,R)=>d.actions.prepareTraining({modelId:a.modelId,tasksetId:l.id,destinationId:y,recipe:w,exportApproved:R.exportApproved,retentionDays:R.retentionDays,region:R.region}),onConfirmPrepared:async(y,w)=>await d.actions.startPreparedTraining({planId:y.plan.id,bundleId:y.bundle.id,maximumCostUsd:w})?(await d.actions.saveModelRunDraft({...a,status:"launched",updatedAt:new Date().toISOString()}),await S(a.modelId,l.id),!0):!1,onStart:async(y,w,R)=>await d.actions.startTraining({modelId:a.modelId,tasksetId:l.id,destinationId:y,recipe:w,...R})?(await d.actions.saveModelRunDraft({...a,status:"launched",updatedAt:new Date().toISOString()}),await S(a.modelId,l.id),!0):!1},`${l.id}:${l.revision}:${a.method}:${a.runPreset}`):e.jsx("div",{className:"model-build-empty",children:"Choose a Taskset and training method to select a model."})]})]})}function In({connection:t,initialObjective:n,initialModelId:a,initialName:s,initialDraftId:l,initialTasksetId:o,profileId:i,training:r,onCancel:u,onFinished:h,onNameChange:d,onSectionChange:j,onSaved:b,renderDatasetBuilder:g,onOpenProviderSettings:C}){const k=r.payload,f=c.useMemo(()=>k?.modelRunDrafts.find(I=>(I.status==="draft"||I.status==="ready_to_run")&&I.id===l)??null,[l,k?.modelRunDrafts]),S=k?.modelProjects.find(I=>I.id===a)??null,y=k?.tasksets.find(I=>I.id===o)??null,w=c.useMemo(()=>!a||l?null:[...k?.modelRunDrafts??[]].filter(I=>I.modelId===a&&I.status==="launched"&&k?.tasksets.some(L=>L.id===I.tasksetRef?.id&&L.revision===I.tasksetRef.revision&&L.contentHash===I.tasksetRef.contentHash)).sort((I,L)=>L.updatedAt.localeCompare(I.updatedAt))[0]??null,[l,a,k?.modelRunDrafts,k?.tasksets]),R=c.useRef(null);R.current||(R.current=S??Qn(i,n,a,s??Xn(k?.modelProjects??[])));const[p,_]=c.useState(R.current),x=c.useRef(null);if(!x.current){const I=f??(w?cl(w):dl(i,R.current.id));x.current=y?Nn(I,y):I}const[m,T]=c.useState(x.current),[V,E]=c.useState(()=>ol(x.current)),[$,Z]=c.useState(x.current.datasetMode==="build"&&!x.current.tasksetRef),[K,ee]=c.useState(f&&S?At(S,f):""),{confirmAction:M,confirmDialog:H,resolveConfirmDialog:B}=va(),[G,de]=c.useState({ready:!1,reason:"Select a Taskset.",actionLabel:"Run"}),[F,ne]=c.useState({exportApproved:!0,maximumCostUsd:0,retentionDays:null,region:null}),J=k?.tasksets.find(I=>I.id===m.tasksetRef?.id&&I.revision===m.tasksetRef.revision&&I.contentHash===m.tasksetRef.contentHash)??null,ae=c.useMemo(()=>pl(J,k?.destinations??[]),[J,k?.destinations]),X=At(p,m)!==K,N=!!r.busyAction,q=hl(p,m,J,G),D=!N&&q===null;c.useEffect(()=>{j?.($?"dataset":"run")},[$,j]),c.useEffect(()=>{d?.(p.name)},[d,p.name]),c.useEffect(()=>{if(!X)return;const I=L=>{L.preventDefault(),L.returnValue=""};return window.addEventListener("beforeunload",I),()=>window.removeEventListener("beforeunload",I)},[X]),c.useEffect(()=>{!m.method||ae.find(L=>L.method===m.method)?.available||T(L=>({...L,method:null,recipe:null,runPreset:null,baseModel:null,destinationId:null,updatedAt:new Date().toISOString()}))},[m.method,ae]),c.useEffect(()=>{!m.method||m.runPreset||T(I=>({...I,runPreset:"standard",updatedAt:new Date().toISOString()}))},[m.method,m.runPreset]);const te=c.useCallback(I=>{ne(I.approval),T(L=>({...L,baseModel:I.baseModel,method:L.method??I.method,destinationId:I.destinationId,recipe:I.recipe,updatedAt:new Date().toISOString()}))},[]),Q=c.useCallback(I=>de(I),[]);async function le(I=!0){const L=new Date().toISOString(),he={...p,updatedAt:L},oe=await r.actions.saveModelProject(he);if(!oe)return null;const me={...m,status:q===null?"ready_to_run":"draft",updatedAt:L},v=await r.actions.saveModelRunDraft(me);return v?(_(oe),T(v),ee(At(oe,v)),I&&await b?.(v.modelId),v):null}async function Ae(){X&&!await M({title:"Discard run setup?",body:"Your Model and run setup changes will be discarded.",confirmLabel:"Discard",cancelLabel:"Keep editing",tone:"danger"})||u()}async function fe(){if(!D||!J)return;const I=await le(!1);if(!I)return;const L=await r.actions.prepareModelRun(I.id,{maximumSpendUsd:F.maximumCostUsd,retentionDays:F.retentionDays});!L||!await M({title:"Review and start training",body:ml(L),confirmLabel:L.quoteUsd?`Approve up to $${(L.maximumSpendUsd??L.quoteUsd).toFixed(2)} and run`:"Start exact run",cancelLabel:"Back"})||!await r.actions.startModelRun(I.id,{maximumSpendUsd:F.maximumCostUsd,retentionDays:F.retentionDays,exportApproved:F.exportApproved})||await h(I.modelId,J.id)}function ue(I){Z(!1),E("method"),T(L=>Nn(L,I))}return $?e.jsxs("main",{className:"model-build-page model-build-dataset-page","aria-label":"New Taskset",children:[e.jsxs("header",{className:"model-build-header",children:[e.jsx("div",{children:e.jsx("h1",{children:"New Taskset"})}),e.jsx("button",{className:"training-button secondary",type:"button",onClick:()=>{Z(!1),T(I=>({...I,datasetMode:null,updatedAt:new Date().toISOString()}))},children:"Back to run setup"})]}),g(I=>{const L=k?.tasksets.find(he=>he.id===I);L?ue(L):r.refresh().then(he=>{const oe=he?.tasksets.find(me=>me.id===I);oe&&ue(oe)})},()=>{Z(!1),T(I=>({...I,datasetMode:"existing",tasksetRef:null,updatedAt:new Date().toISOString()}))})]}):e.jsxs(e.Fragment,{children:[e.jsxs("main",{className:"model-build-page","aria-label":"Run setup",children:[e.jsx($i,{project:p,persisted:!!S,busy:N,dirty:X,canRun:D,pageReason:q,actionLabel:G.actionLabel,onProjectChange:_,onCancel:()=>{Ae()},onSave:()=>{le()},onLaunch:()=>{fe()}}),e.jsx(vl,{activeStep:V,onStepChange:E,draft:m,setDraft:T,selectedTaskset:J,methodCards:ae,tasksets:k?.tasksets??[],baseModelCandidates:k?.baseModelCandidates??[],destinations:k?.destinations??[],connection:t,training:r,canRun:D,onSelectTaskset:ue,onOpenDatasetBuilder:()=>{T(I=>({...I,datasetMode:"build",tasksetRef:null,updatedAt:new Date().toISOString()})),Z(!0)},onLaunchStateChange:Q,onConfigurationChange:te,onOpenProviderSettings:C,onFinished:h})]}),e.jsx(ya,{state:H,onResolve:B})]})}function yl({account:t,closeDetailKind:n,closeDetailRequestId:a,onAnswerQuestion:s,onApplyCandidate:l,onApprove:o,onCancel:i,candidateReview:r,onCandidateReviewChange:u,onDetailOpenChange:h,onSkillSelectionChange:d,onNewModel:j,onOpenPullRequest:b,onOpenCandidateFiles:g,onOpenRunConversation:C,onPause:k,onReconcilePullRequest:f,onRejectCandidate:S,onResume:y,onRevise:w,profileView:R,training:p}){const _=R.payload?.profile??null,x=_?.activeProfile??"default",m=Va({connection:R.connection,profileId:x});Zt(m.error),Zt(p.training.error);const T=c.useMemo(()=>vi(p.training.payload),[p.training.payload]),V=c.useMemo(()=>m.runs.filter(v=>v.target.kind==="agent"&&["ready_local","released","published_hosted"].includes(v.state)).map(v=>`${v.id}:${v.revision}:${v.state}`).sort().join("|"),[m.runs]),[E,$]=c.useState(()=>typeof window>"u"?"models":en(window.location.search)),[Z,K]=c.useState(null),[ee,M]=c.useState(null),[H,B]=c.useState(!1),[G,de]=c.useState(null),[F,ne]=c.useState(null),[J,ae]=c.useState("run"),[X,N]=c.useState(null),[q,D]=c.useState(null),te=c.useMemo(()=>On({profile:_,training:p.training.payload,runs:m.runs}),[m.runs,_,p.training.payload]),Q=c.useMemo(()=>te.filter(v=>v.kind==="model"),[te]),le=Q.find(v=>v.key===Z)??null;c.useEffect(()=>{if(!R.connection)return;let v=!1;return lt.bootstrap(R.connection).then(O=>{v||R.onPayload(O)}).catch(O=>{v||R.onError(O instanceof Error?O.message:String(O))}),()=>{v=!0}},[R.connection,R.onError,R.onPayload]),c.useEffect(()=>{const v=()=>{K(null),M(null),$(en(window.location.search))};return window.addEventListener("popstate",v),window.addEventListener(St,v),()=>{window.removeEventListener("popstate",v),window.removeEventListener(St,v)}},[]),c.useEffect(()=>{const v=ka(window.location.search,E),O=`${window.location.pathname}${v}${window.location.hash}`,W=`${window.location.pathname}${window.location.search}${window.location.hash}`;O!==W&&(window.history.replaceState(window.history.state,"",O),window.dispatchEvent(new Event(St)))},[E]),c.useEffect(()=>{T&&m.refresh()},[m.refresh,T]),c.useEffect(()=>{if(!V||!R.connection)return;let v=!1;return lt.bootstrap(R.connection).then(O=>{v||R.onPayload(O)}).catch(O=>{v||R.onError(O instanceof Error?O.message:String(O))}),()=>{v=!0}},[V,R.connection,R.onError,R.onPayload]),c.useEffect(()=>{Z&&!te.some(v=>v.key===Z)&&K(null)},[Z,te]),c.useEffect(()=>{d(null)},[d]),c.useEffect(()=>{if(!(a<=0)){if(K(null),M(null),n==="dataset"){$("tasksets");return}$("models")}},[n,a]),c.useEffect(()=>{N(null)},[p.launchRequest?.id]),c.useEffect(()=>{if(p.launchRequest){h({kind:"model",kindLabel:"Models",kindOnSelect:()=>document.getElementById("model-run-editor-cancel")?.click(),workproductLabel:null,segments:[{label:X??"Model"},...J==="dataset"?[{label:"New Taskset"}]:[]]});return}if(E==="tasksets"){h(ee?{kind:"dataset",kindLabel:"Tasksets",workproductLabel:[...p.training.payload?.tasksets??[],...p.training.payload?.modelTasksets??[]].find(v=>v.id===ee)?.name??"Taskset",segments:[]}:null);return}if(E!=="models"){h(null);return}le||h(null)},[E,h,le,ee,J,X,p.launchRequest,p.training.payload?.modelTasksets,p.training.payload?.tasksets]),c.useEffect(()=>()=>h(null),[h]);function Ae(v){const O=te.find(se=>se.kind==="model"&&se.id===v);if(!O)return;const W=Qe(O,m.runs,p.training.payload),pe=W.find(se=>se.current)??W.find(se=>se.lineage.promotable)??null;pe?.taskset&&p.onChatWithModel(Ft({modelId:pe.lineage.id,taskset:pe.taskset}))}function fe(){ne("source"),M(null),$("tasksets")}function ue(){ne(null)}function I(v){const O=v?`Help me improve the ${v.name} Taskset.`:"Help me create a Taskset.";R.onSkillCommand?.(`$openpond-taskset-authoring ${O}`,"openpond"),ue()}function L(v){ne(null),K(null),$("tasksets"),M(v)}function he(v){ae("run"),K(null),M(null),$("models"),j(v)}async function oe(v){const O={...Qn(x,v.description,void 0,v.name),defaultBaseModel:v.defaultBaseModel},W=await p.training.actions.saveModelProject(O);return W?(B(!1),$("models"),K(Ie("model",W.id)),v.purpose==="benchmark"&&de({modelId:W.id,model:v.benchmarkModel??p.defaultModel}),R.onToast?.(`${W.name} created.`,"success"),!0):!1}const me=c.useCallback(()=>K(null),[]);return e.jsxs(Fs,{activeTab:E,showHeader:!p.launchRequest&&!le&&!ee,onCreateDataset:fe,onCreateModel:()=>B(!0),children:[E==="tasksets"?e.jsx(oi,{defaultModel:p.defaultModel,runs:m.runs,selectedId:ee,state:p.training.payload,training:p.training,onToast:(v,O)=>R.onToast?.(v,O)??0,onSelectedIdChange:M,onImproveInChat:v=>I(v),onTrainModel:he,onOpenFiles:v=>{p.onSelectedTasksetIdChange(v),p.onOpenTasksetFiles()}}):E==="serving"?e.jsx(Ai,{state:p.training.payload}):E==="usage"?e.jsx(_i,{account:t,connection:R.connection,onError:R.onError,onOpenSourceSession:C}):p.launchRequest&&p.training.payload?e.jsx(In,{connection:R.connection,initialObjective:p.launchRequest.objective,initialTasksetId:p.launchRequest.initialTasksetId,profileId:x,training:p.training,onCancel:()=>{p.onLaunchHandled(p.launchRequest.id)},onFinished:async(v,O)=>{p.onSelectedTasksetIdChange(O),p.onDetailTasksetIdChange(O),p.onLaunchHandled(p.launchRequest.id),K(Ie("model",v)),$("models"),await m.refresh()},onNameChange:N,onSectionChange:ae,onSaved:async v=>{p.onLaunchHandled(p.launchRequest.id),K(Ie("model",v)),$("models")},onOpenProviderSettings:p.onOpenProviderSettings,renderDatasetBuilder:(v,O)=>e.jsx(Mn,{onOpenChat:()=>I(),onUseExistingDataset:O})}):le?e.jsx(Us,{connection:R.connection,profile:_,runs:m.runs,training:p.training,workproduct:le,onAnswerQuestion:s,onApplyCandidate:l,onApprove:o,onCancel:i,candidateReview:r,onCandidateReviewChange:u,onChatWithModel:p.onChatWithModel,onOpenPullRequest:b,onOpenCandidateFiles:g,onOpenConversation:C,onClose:me,onLocationChange:h,onRenameAgent:()=>{},onOpenDataset:v=>{K(null),M(v),$("tasksets")},onPause:k,onReconcilePullRequest:f,onRejectCandidate:S,onResume:y,onRevise:w,renderModelRunEditor:({initialTasksetId:v,draftId:O,modelId:W,modelName:pe,onCancel:se,onFinished:ve,onSectionChange:we})=>e.jsx(In,{connection:R.connection,initialModelId:W,initialName:pe,initialDraftId:O??void 0,initialObjective:le.description,initialTasksetId:v??void 0,profileId:x,training:p.training,onCancel:se,onFinished:async()=>{await m.refresh(),await ve()},onSectionChange:we,onOpenProviderSettings:p.onOpenProviderSettings,renderDatasetBuilder:(Pe,Te)=>e.jsx(Mn,{onOpenChat:()=>I(),onUseExistingDataset:Te})}),onStartAgentChange:()=>{},onToast:p.onToast,benchmarkDefaultModel:p.defaultModel,benchmarkProviderSettings:p.providerSettings,initialBenchmarkModel:G?.modelId===le.id?G.model:null,initialBenchmarkOpen:G?.modelId===le.id,onInitialBenchmarkOpenConsumed:()=>de(null)}):e.jsx(Mi,{activeProfileId:x,items:Q,loading:p.training.loading&&!Q.length,providerSettings:p.providerSettings,runs:m.runs,state:p.training.payload,onSelect:K,onUseModel:Ae}),H?e.jsx(ui,{baseModelCandidates:p.training.payload?.baseModelCandidates??[],busy:p.training.busyAction==="save-model-project",defaultBenchmarkModel:p.defaultModel,initialName:Xn(p.training.payload?.modelProjects??[]),onClose:()=>B(!1),onCreate:oe,onManageModels:()=>{B(!1),p.onOpenTrainingSettings()},providerSettings:p.providerSettings}):null,F==="source"?e.jsx(La,{onClose:ue,onSelect:v=>{if(v==="build"){I();return}ne(v)}}):null,F==="huggingface"?e.jsx(Ba,{onBack:()=>ne("source"),onClose:ue,onImported:async v=>{await p.training.refresh(),L(v)},onOpenDatasetStorageSettings:()=>{ne(null),p.onOpenDatasetStorageSettings()},training:p.training}):null,q?(()=>{const v=p.training.payload?.models.find(W=>W.id===q),O=p.training.payload?.tasksets.find(W=>W.id===v?.tasksetId);return!v||!O?null:e.jsx(Dn,{lineage:v,taskset:O,training:p.training,onChat:p.onChatWithModel,onClose:()=>D(null)})})():null]})}function Mn({onOpenChat:t,onUseExistingDataset:n}){return e.jsxs("section",{className:"training-run-placeholder",children:[e.jsx("h3",{children:"Build the Taskset in full Chat"}),e.jsx("p",{children:"The Taskset authoring Skill gathers tasks and data conversationally, then uses typed actions to materialize graders, evaluations, and the executable Taskset. No training starts from this flow."}),e.jsxs("div",{className:"labs-dataset-detail-actions",children:[e.jsx("button",{className:"training-button",type:"button",onClick:t,children:"Open Taskset Builder"}),n?e.jsx("button",{className:"training-button secondary",type:"button",onClick:n,children:"Use existing Taskset"}):null]})]})}const _l=Object.freeze(Object.defineProperty({__proto__:null,LabsRoute:yl},Symbol.toStringTag,{value:"Module"}));export{Un as E,re as L,Fn as a,Be as b,Qe as c,ct as d,ut as e,Ht as f,qt as g,zn as h,_l as i,We as l,Tl as m};
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./LabModelVersionDetailPage-Bhfa7T00.js","./index-LrGasYyx.js","./index-CHqMtVfF.css","./training-model-data-V8276E5q.js","./cloud-upload-D6bS8rS2.js","./MainPane-CQCLhV5C.js","./arrow-up-right-BDcNd1rt.js","./MarkdownText-R3MC5S30.js","./square-B5q2aneb.js","./folder-open-8C5l7A93.js","./MainPane-BfVDe9f7.css","./AppDialog-DacC7BcY.js","./ComposerCreateImproveStrip-BH8Ath1h.js","./play-Cbsyrwkw.js","./refresh-cw-ChUK_QfF.js","./UsageSettingsSection-Bdvm66WK.js","./index-BYgrO3wt.js","./UsageSettingsSection-O8VK0qBL.css","./training-BQVNUTZA.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as c,b9 as oa,j as e,X as Me,A as An,aS as dt,ba as ra,a2 as wn,bN as Ft,p as lt,bO as st,bP as je,bQ as Tn,P as da,bR as ca,L as _n,u as $n,aV as zt,au as ua,aL as ot,as as ha,_ as ma,bS as pa,bT as Vt,ar as Pn,M as En,a as ba,bU as kt,bV as ga,bW as fa,bX as xa,bY as ja,aA as va,aG as ya,ay as Zt,bZ as en,b_ as St,b$ as ka}from"./index-LrGasYyx.js";import{C as Sa}from"./cloud-upload-D6bS8rS2.js";import{C as Na}from"./MainPane-CQCLhV5C.js";import{A as _e}from"./AppDialog-DacC7BcY.js";import{c as Ca,s as Se,f as $e,e as Oe,j as Ln,g as Ra}from"./training-model-data-V8276E5q.js";import{D as De}from"./MarkdownText-R3MC5S30.js";import{ComposerCreateImproveStrip as Ia}from"./ComposerCreateImproveStrip-BH8Ath1h.js";/* empty css */import{UsageSettingsSection as Ma}from"./UsageSettingsSection-Bdvm66WK.js";const Nt=8,tn=24,Aa=2;function wa(t){const n=_a(t);if(n.length){const l=tn+n.reduce((i,r)=>i+Nt+Ke(r.content),0),o=n.filter(i=>i.role==="assistant").map(i=>Nt+Ke(i.content));return{renderedTokens:l,maximumAssistantTargetTokens:Math.max(0,...o),assistantTargetCount:o.length}}const a=Pa(t.input),s=Ea(t.expectedOutput);return{renderedTokens:tn+Ke(a)+Ke(s),maximumAssistantTargetTokens:Nt+Ke(s),assistantTargetCount:s?1:0}}function Ta(t,n={}){const a=n.minimum??64,s=n.maximum??4096,l=t.tasks.filter(o=>o.split==="train").reduce((o,i)=>Math.max(o,wa(i).renderedTokens),0);return l<=a?a:Math.min(s,2**Math.ceil(Math.log2(l)))}function _a(t){const n=[...nn(t.input.messages),...nn(t.expectedOutput?.messages)],a=[],s=new Map,l=o=>{const i=typeof o=="string"&&o?o:`missing_${s.size+1}`;return s.has(i)||s.set(i,`call_${s.size+1}`),s.get(i)};for(const o of n){if(!it(o))continue;const i=o.role,r=o.content;if(i==="tool"){a.push({role:"user",content:rt({content:typeof r=="string"?r:"",tool_call_id:l(o.tool_call_id),type:"tool_result"})});continue}if(i==="assistant"&&Array.isArray(o.tool_calls)&&o.tool_calls.length){for(const u of o.tool_calls)!it(u)||!it(u.function)||(a.push({role:"assistant",content:rt({arguments:$a(u.function.arguments),name:u.function.name??null,type:"tool_call"})}),l(u.id));typeof r=="string"&&r&&a.push({role:"assistant",content:r});continue}(i==="system"||i==="user"||i==="assistant")&&typeof r=="string"&&r&&a.push({role:i,content:r})}return a}function nn(t){return Array.isArray(t)?t:[]}function $a(t){if(typeof t!="string")return{};try{return JSON.parse(t)}catch{return{malformed_arguments:t}}}function rt(t){return JSON.stringify(wt(t))}function wt(t){return Array.isArray(t)?t.map(wt):it(t)?Object.fromEntries(Object.keys(t).sort().map(n=>[n,wt(t[n])])):t}function Pa(t){return typeof t.prompt=="string"?t.prompt:rt(t)}function Ea(t){return t?typeof t.text=="string"?t.text:rt(t):""}function Ke(t){return Math.ceil(t.length/Aa)}function it(t){return!!(t&&typeof t=="object"&&!Array.isArray(t))}const an=[{id:"build",title:"Build",description:"Create from a purpose, conversations, or both.",icon:oa,available:!0},{id:"huggingface",title:"Hugging Face",description:"Import task data from a Dataset URL or repository ID.",icon:Na,available:!0},{id:"upload",title:"Upload file",description:"JSON, JSONL, CSV, and Parquet import is coming next.",icon:Sa,available:!1}];function La({onClose:t,onSelect:n}){const[a,s]=c.useState(null),l=an.find(o=>o.id===a)??null;return e.jsxs(_e,{ariaLabel:"New Taskset",className:"training-dialog training-run-dialog training-run-start-step",onClose:t,children:[e.jsxs("div",{className:"training-dialog-header",children:[e.jsx("h2",{children:"New Taskset"}),e.jsx("button",{"aria-label":"Close",className:"training-icon-button",type:"button",onClick:t,children:e.jsx(Me,{size:16})})]}),e.jsxs("div",{className:"training-run-step-heading",children:[e.jsx("h3",{children:"Choose a source"}),e.jsx("p",{children:"Every source becomes an immutable OpenPond Taskset with Parquet-backed Data."})]}),e.jsx("div",{"aria-label":"How to create a Taskset",className:"training-method-options training-start-mode-options",role:"radiogroup",children:an.map(o=>{const i=o.icon;return e.jsxs("button",{"aria-describedby":o.available?void 0:`${o.id}-availability`,"aria-checked":a===o.id,className:a===o.id?"selected":void 0,disabled:!o.available,role:"radio",type:"button",onClick:()=>s(o.id),children:[e.jsx("span",{className:"training-start-mode-icon","aria-hidden":"true",children:e.jsx(i,{size:18})}),e.jsxs("span",{className:"training-start-mode-copy",children:[e.jsxs("strong",{children:[o.title,o.available?null:e.jsx("span",{className:"dataset-source-availability",id:`${o.id}-availability`,children:"Coming next"})]}),e.jsx("small",{children:o.description})]})]},o.id)})}),e.jsxs("div",{className:"training-dialog-actions",children:[e.jsx("button",{className:"training-button secondary",type:"button",onClick:t,children:"Cancel"}),e.jsx("button",{className:"training-button",disabled:!l,type:"button",onClick:()=>{l&&n(l.id)},children:a==="build"?"Create":"Continue"})]})]})}const Da=["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"],Oa=["visible","privileged","metadata"];function Ba({onBack:t,onClose:n,onImported:a,onOpenDatasetStorageSettings:s,training:l}){const[o,i]=c.useState(""),[r,u]=c.useState(null),[h,d]=c.useState(null),[j,b]=c.useState(""),[g,C]=c.useState(""),[k,f]=c.useState(!1),[S,y]=c.useState(null),w=c.useRef(null),p=l.payload?.datasetImports.find(M=>M.id===r?.id)??r,_=p?.inspection??null,x=!!(p&&["inspecting","materializing","validating","cancelling"].includes(p.status)),m=!_?.declaredLicense||["unknown","other"].includes(_.declaredLicense.toLowerCase()),T=c.useMemo(()=>_?.sourceFiles.reduce((M,H)=>M===null||H.sizeBytes===null?null:M+H.sizeBytes,0)??null,[_]);c.useEffect(()=>{!p||p.status!=="ready"||!p.tasksetId||w.current!==p.id&&(w.current=p.id,a(p.tasksetId))},[p,a]);async function V(){if(!o.trim())return;y(null);const M=await l.actions.inspectHuggingFaceDataset(o);if(!M){y(l.error??"OpenPond could not inspect this Dataset.");return}u(M),M.inspection&&M.mapping&&E(M)}function E(M){d(M.mapping),b(M.inspection?.title??M.locator?.repositoryId.split("/").at(-1)??"Imported Dataset"),C(M.inspection?.description?.trim().slice(0,2e3)||`Train and evaluate tasks from ${M.locator?.repositoryId??"this Dataset"}.`)}function $(M,H){d(B=>B&&{...B,bindings:B.bindings.map((G,de)=>de===M?{...G,...H}:G)})}async function Z(){if(!p||!h||!j.trim()||!g.trim())return;y(null);const M=await l.actions.materializeDatasetImport(p.id,{name:j.trim(),objective:g.trim(),mapping:h,targetStorageRoot:null,licenseApproved:k});if(!M){y(l.error??"OpenPond could not start Dataset materialization.");return}u(M)}async function K(){if(!p)return;const M=await l.actions.cancelDatasetImport(p.id);M&&u(M)}const ee=!!(_&&h)&&!["materializing","validating","ready","cancelling","cancelled"].includes(p?.status??"");return e.jsxs(_e,{ariaLabel:"Import Hugging Face data",className:"training-dialog training-run-dialog training-run-workflow-step dataset-import-dialog",dismissDisabled:x,initialFocusKey:_?"review":"locator",onClose:n,children:[e.jsxs("div",{className:"training-dialog-header",children:[e.jsxs("div",{className:"training-run-dialog-title",children:[e.jsx("button",{"aria-label":"Back to Taskset sources",className:"training-icon-button",type:"button",onClick:t,children:e.jsx(An,{size:16})}),e.jsx("h2",{children:"Import from Hugging Face"})]}),e.jsx("button",{"aria-label":"Close",className:"training-icon-button",type:"button",onClick:n,children:e.jsx(Me,{size:16})})]}),_?ee?e.jsxs("div",{className:"training-dialog-scroll-body dataset-import-review",children:[e.jsx(Ua,{job:p,sourceBytes:T}),e.jsxs("label",{className:"training-objective-field",children:[e.jsx("span",{children:"Taskset name"}),e.jsx("input",{value:j,onChange:M=>b(M.target.value)})]}),e.jsxs("label",{className:"training-objective-field",children:[e.jsx("span",{children:"Purpose"}),e.jsx("textarea",{value:g,onChange:M=>C(M.target.value)})]}),e.jsxs("div",{className:"dataset-import-mapping",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Semantic mapping"}),e.jsx("small",{children:"Review which fields the policy can see and which stay privileged for grading."})]}),e.jsx("div",{className:"dataset-import-mapping-table",children:h.bindings.map((M,H)=>e.jsxs("div",{children:[e.jsx("code",{children:M.sourcePath}),e.jsx("select",{"aria-label":`Target for ${M.sourcePath}`,value:M.target,onChange:B=>$(H,{target:B.target.value}),children:Da.map(B=>e.jsx("option",{value:B,children:Tt(B)},B))}),e.jsx("select",{"aria-label":`Policy for ${M.sourcePath}`,value:M.policy,onChange:B=>$(H,{policy:B.target.value}),children:Oa.map(B=>e.jsx("option",{value:B,children:Tt(B)},B))})]},`${M.sourcePath}:${H}`))})]}),m?e.jsxs("label",{className:"dataset-import-license-review",children:[e.jsx("input",{checked:k,type:"checkbox",onChange:M=>f(M.target.checked)}),e.jsx("span",{children:"I reviewed the repository license and approve importing this Dataset."})]}):null,p?.status==="failed"&&p.error?e.jsx("div",{className:"training-banner error",role:"alert",children:p.error}):null]}):e.jsx(Fa,{job:p}):e.jsxs("div",{className:"training-dialog-scroll-body dataset-import-locator",children:[e.jsxs("div",{className:"training-run-step-heading",children:[e.jsx("h3",{children:"Paste a Dataset URL"}),e.jsx("p",{children:"OpenPond inspects the public repository, pins its exact commit, and shows the fields before downloading any rows."})]}),e.jsxs("label",{className:"training-objective-field",children:[e.jsx("span",{children:"Hugging Face URL or repository ID"}),e.jsx("input",{"data-autofocus":!0,disabled:x,placeholder:"BytedTsinghua-SIA/DAPO-Math-17k",value:o,onChange:M=>i(M.target.value)})]}),p?.status==="failed"&&p.error?e.jsx("div",{className:"training-banner error",role:"alert",children:p.error}):null]}),S?e.jsx("div",{className:"training-banner error",role:"alert",children:S}):null,e.jsx("div",{className:"training-dialog-actions",children:_?ee?e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"training-button secondary",type:"button",onClick:s,children:"Dataset storage"}),e.jsx("button",{className:"training-button",disabled:!j.trim()||!g.trim()||!h||m&&!k,type:"button",onClick:()=>{Z()},children:"Import and save"})]}):x?e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"training-button secondary",type:"button",onClick:n,children:"Run in background"}),e.jsx("button",{className:"training-button",disabled:p?.status==="cancelling",type:"button",onClick:()=>{K()},children:"Cancel import"})]}):e.jsx("button",{className:"training-button",type:"button",onClick:n,children:"Close"}):e.jsxs("button",{className:"training-button",disabled:!o.trim()||x,type:"button",onClick:()=>{V()},children:[x?e.jsx(dt,{className:"spin",size:14}):null,"Inspect Dataset"]})})]})}function Ua({job:t,sourceBytes:n}){const a=t.inspection,s=a.splits.reduce((l,o)=>l===null||o.rowCount===null?null:l+o.rowCount,0);return e.jsxs("div",{className:"dataset-import-summary",children:[e.jsxs("div",{children:[e.jsx("strong",{children:a.title}),e.jsxs("a",{href:a.locator.repositoryUrl,rel:"noreferrer",target:"_blank",children:["Open on Hugging Face ",e.jsx(ra,{size:12})]})]}),e.jsxs("dl",{children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Revision"}),e.jsx("dd",{children:e.jsx("code",{children:a.resolvedRevision.slice(0,12)})})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Rows"}),e.jsx("dd",{children:s===null?"Unknown":s.toLocaleString()})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Source size"}),e.jsx("dd",{children:n===null?"Unknown":_t(n)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"License"}),e.jsx("dd",{children:a.declaredLicense??"Review required"})]})]}),e.jsx("p",{children:a.splits.map(l=>`${l.configuration}/${l.split}: ${l.rowCount?.toLocaleString()??"unknown"} rows`).join(" · ")})]})}function Fa({job:t}){const n=t.progress,a=n.totalBytes&&n.totalBytes>0?Math.min(100,n.completedBytes/n.totalBytes*100):null,l=(n.totalRows&&n.totalRows>0?Math.min(100,n.completedRows/n.totalRows*100):null)??a;return e.jsxs("div",{className:"training-dialog-scroll-body dataset-import-progress",role:"status",children:[e.jsx(dt,{className:t.status==="ready"?"":"spin",size:22}),e.jsx("h3",{children:t.status==="ready"?"Taskset saved":"Importing data"}),e.jsx("p",{children:t.progress.message}),e.jsx("div",{className:"dataset-import-progress-track",children:e.jsx("span",{style:{width:`${l??8}%`}})}),e.jsx("small",{children:n.completedRows?`${n.completedRows.toLocaleString()}${n.totalRows?` of ${n.totalRows.toLocaleString()}`:""} rows`:n.completedBytes?`${_t(n.completedBytes)}${n.totalBytes?` of ${_t(n.totalBytes)}`:""}`:Tt(n.phase)}),t.error?e.jsx("div",{className:"training-banner error",children:t.error}):null]})}function Tt(t){return t.replaceAll("_"," ").replace(/^./,n=>n.toUpperCase())}function _t(t){const n=["B","KB","MB","GB","TB"];let a=t,s=0;for(;a>=1024&&s<n.length-1;)a/=1024,s+=1;return`${a>=10?a.toFixed(0):a.toFixed(1)} ${n[s]}`}function Dn({lineage:t,taskset:n,training:a,onChat:s,onClose:l}){const o=!!a.busyAction;function i(){s(Ft({modelId:t.id,taskset:n})),l()}return e.jsxs(_e,{ariaLabel:`Use ${n.name}`,className:"training-dialog training-model-use-dialog",dismissDisabled:o,onClose:l,children:[e.jsxs("div",{className:"training-dialog-header",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Use model"}),e.jsx("p",{children:n.name})]}),e.jsx("button",{"aria-label":"Close model use",disabled:o,type:"button",onClick:l,children:e.jsx(Me,{size:16})})]}),t.promotable?null:e.jsx("p",{className:"training-model-use-warning",children:"This run did not pass its frozen Eval. Chat is available for inspection, but the model cannot be promoted."}),e.jsx("p",{className:"training-model-use-note",children:"Open a chat with this trained version. OpenPond selects its managed or Local runtime from the recorded model lineage."}),e.jsxs("div",{className:"training-dialog-actions",children:[e.jsx("button",{className:"training-button secondary",disabled:o,type:"button",onClick:l,children:"Cancel"}),e.jsxs("button",{className:"training-button",disabled:o,type:"button",onClick:i,children:[e.jsx(wn,{size:14}),"Chat now"]})]})]})}const za=new Set(["planning","awaiting_questions","awaiting_plan_approval","paused","applying_source","running_checks","evaluating","awaiting_promotion","opening_pull_request","pull_request_open","reconciling_release","pushing_hosted","running_hosted_checks"]);function Va(t){const{connection:n,profileId:a}=t,[s,l]=c.useState([]),[o,i]=c.useState(!1),[r,u]=c.useState(null),h=c.useRef(null),d=c.useCallback(()=>{if(!n)return Promise.resolve(null);if(h.current)return h.current;i(!0);const b=lt.listCreateImproveRuns(n,{profileId:a,limit:500}).then(g=>(l(g.runs),u(null),g.runs)).catch(g=>(u(g instanceof Error?g.message:String(g)),null)).finally(()=>{h.current===b&&(h.current=null),i(!1)});return h.current=b,b},[n,a]);c.useEffect(()=>{if(!n){l([]),u(null);return}d()},[n,a,d]);const j=c.useMemo(()=>s.some(b=>za.has(b.state)),[s]);return c.useEffect(()=>{if(!n)return;let b=!0,g=null;const C=async()=>{await d(),b&&(g=window.setTimeout(()=>{C()},j?1e3:15e3))};return g=window.setTimeout(()=>{C()},j?1e3:15e3),()=>{b=!1,g!==null&&window.clearTimeout(g)}},[n,j,d]),{runs:s,loading:o,error:r,refresh:d}}function be({title:t,actions:n,children:a}){return e.jsxs("section",{className:"training-detail-section",children:[e.jsxs("div",{className:"training-detail-section-heading",children:[e.jsx("h2",{children:t}),n?e.jsx("div",{children:n}):null]}),e.jsx("div",{className:"training-detail-section-panel",children:a})]})}const qa=new Set(["released","rejected","ready","ready_local","published_hosted","cancelled"]);function On(t){const n=new Map,a=new Set((t.training?.modelProjects??[]).map(i=>i.id)),s=new Map,l=new Map((t.training?.plans??[]).map(i=>[i.id,i.modelId]));for(const i of t.training?.jobs??[]){const r=l.get(i.planId);if(!r)continue;const u=s.get(r)??new Set;u.add(i.id),s.set(r,u)}for(const i of t.runs){if(i.target.kind!=="model"||!i.target.id||!i.target.trainingPlanId)continue;const r=s.get(i.target.id)??new Set;for(const u of t.training?.jobs??[])u.planId===i.target.trainingPlanId&&r.add(u.id);s.set(i.target.id,r)}const o=new Date(0).toISOString();for(const i of t.profile?.agents??[]){const r=Ie("agent",i.id),u=t.profile?.actionCatalog.find(h=>h.agentId===i.id&&h.sourceActionId==="chat"&&h.visibility!=="internal"&&h.visibility!=="debug")??null;n.set(r,{key:r,kind:"agent",id:i.id,ownerProfileId:t.profile?.activeProfile??null,name:i.name||i.id,description:i.enabled?"Enabled Profile Agent":"Disabled Profile Agent",status:i.enabled?"Ready":"Disabled",updatedAt:t.profile?.lastCheck?.checkedAt??o,path:i.path,enabled:i.enabled,runIds:[],conversationId:null,tasksetId:null,trainingRunCount:0,evaluationStatus:"not_run",useActionId:u?.id??null})}for(const i of t.profile?.skills??[]){const r=Ie("skill",i.name);n.set(r,{key:r,kind:"skill",id:i.name,ownerProfileId:t.profile?.activeProfile??null,name:i.name,description:i.description,status:i.validationStatus==="valid"?"Ready":i.validationStatus,updatedAt:o,path:i.path,enabled:i.enabled,runIds:[],conversationId:null,tasksetId:null,trainingRunCount:0,evaluationStatus:"not_run",useActionId:null,skillSource:"profile",skillValidationStatus:i.validationStatus,skillValidationMessages:i.validationMessages,skillSourceHash:i.sourceHash,skillCharCount:i.charCount,skillResourceFiles:i.resourceFiles})}for(const i of t.training?.modelProjects??[]){const u=(t.training?.modelRunDrafts??[]).filter(k=>k.modelId===i.id&&(k.status==="draft"||k.status==="ready_to_run"))[0]??null,h=(t.training?.modelRuns??[]).filter(k=>k.modelId===i.id).sort((k,f)=>f.updatedAt.localeCompare(k.updatedAt)),d=new Set(h.map(k=>k.id)),j=[...s.get(i.id)??[]].filter(k=>{const f=t.training?.jobs.find(y=>y.id===k),S=typeof f?.metadata.modelRunId=="string"?f.metadata.modelRunId:null;return!S||!d.has(S)}).length,b=h[0]??null,g=(t.training?.modelVersions??[]).find(k=>k.modelId===i.id&&k.kind==="base_reference"&&k.version===0)??null,C=Ie("model",i.id);n.set(C,{key:C,kind:"model",id:i.id,ownerProfileId:i.profileId,name:st(i.name,"Untitled Model"),description:i.objective??"No description",status:b?Ha(b.status):u?.status==="ready_to_run"?"Ready to run":u?"Draft":g?"Base ready":"Ready",updatedAt:b?.updatedAt??u?.updatedAt??i.updatedAt,path:b?`tasksets/${b.taskset.id}`:u?.tasksetRef?`tasksets/${u.tasksetRef.id}`:g?`tasksets/${g.taskset.id}`:null,enabled:g?!1:null,runIds:[],conversationId:null,tasksetId:b?.taskset.id??u?.tasksetRef?.id??g?.taskset.id??null,trainingRunCount:h.length+j,evaluationStatus:"not_run",useActionId:null})}for(const i of Ca(t.training)){if(i.taskset.metadata.resourceIntent==="dataset"&&!i.latestPlan&&!i.localModel)continue;const r=t.runs.filter(f=>f.target.kind==="model"&&(i.latestPlan&&f.target.trainingPlanId===i.latestPlan.id||!i.latestPlan&&i.localModel&&f.target.trainingJobId===i.localModel.jobId)).sort((f,S)=>S.updatedAt.localeCompare(f.updatedAt))[0]??null,u=r?.target.kind==="model"&&r.target.id?r.target.id:i.latestPlan?.modelId??i.localModel?.modelId??null;if(!u)continue;const h=Ie("model",u),d=n.get(h),j=r?.target.kind==="model"?r.target.trainingPlanId:null,b=new Set((t.training?.plans??[]).filter(f=>f.modelId===u||j!=null&&f.id===j).map(f=>f.id)),g=(t.training?.jobs??[]).filter(f=>b.has(f.planId)).sort((f,S)=>S.createdAt.localeCompare(f.createdAt)),C=g[0]??null,k=C?t.training?.models.find(f=>f.jobId===C.id)??null:null;n.set(h,{key:h,kind:"model",id:u,ownerProfileId:d?.ownerProfileId??i.taskset.profileId,name:st(d?.name??r?.target.displayName??i.name,"New model"),description:d?.description??i.taskset.objective,status:C?Se(C.status):i.status,updatedAt:C?.updatedAt??i.updatedAt,path:`tasksets/${i.taskset.id}`,enabled:i.localModel?i.localModel.status==="imported"&&!!je(i.localModel):null,runIds:r?[...new Set([...d?.runIds??[],r.id])]:d?.runIds??[],conversationId:null,tasksetId:i.taskset.id,trainingRunCount:Math.max(d?.trainingRunCount??0,g.length),evaluationStatus:Xa(C,k),useActionId:null})}for(const i of t.runs){if(i.target.kind==="configuration"||i.target.kind==="unselected"||i.target.kind==="model"&&!i.tasksetRef&&["cancelled","failed","rejected"].includes(i.state)||i.target.kind==="model"&&!i.target.id)continue;const r=i.target.kind,u=i.target.kind==="model"?i.target.id:i.target.id??i.id,h=Ie(r,u),d=n.get(h),j=r==="agent"?Ja(i,d?.name??null):r==="model"&&a.has(u)?d?.name??i.target.displayName??ln(i):i.target.displayName??d?.name??ln(i),b=r==="model"?st(j,"New model"):j;n.set(h,{key:h,kind:r,id:u,ownerProfileId:d?.ownerProfileId??i.scope.profileId,name:b,description:d?.description??i.objective,status:Wa(i),updatedAt:Ya(d?.updatedAt,i.updatedAt),path:d?.path??i.plan?.sourcePlan[0]?.path??null,enabled:d?.enabled??null,runIds:[...new Set([...d?.runIds??[],i.id])],conversationId:i.scope.conversationId??d?.conversationId??null,tasksetId:i.target.kind==="model"?i.tasksetRef?.id??d?.tasksetId??null:null,trainingRunCount:r==="model"?Math.max(d?.trainingRunCount??0,s.get(u)?.size??0):d?.trainingRunCount??0,evaluationStatus:Qa(i)??d?.evaluationStatus??"not_run",useActionId:d?.useActionId??null})}return[...n.values()].sort((i,r)=>{const u=Number(sn(i,t.runs))-Number(sn(r,t.runs));return u!==0?-u:r.updatedAt.localeCompare(i.updatedAt)||i.name.localeCompare(r.name)})}function Ha(t){return t==="prepared"?"Prepared":t==="running"?"Running":t==="succeeded"?"Rollout complete":t==="failed"?"Failed":"Cancelled"}function Ie(t,n){return`${t}:${n}`}function Ka(t){return t==="agent"?"Agents":t==="skill"?"Skills":t==="extension"?"Extensions":"Models"}function Ga(t,n){const a=new Set(t.runIds);return n.filter(s=>a.has(s.id)).sort((s,l)=>l.updatedAt.localeCompare(s.updatedAt))}function sn(t,n){const a=new Set(t.runIds);return n.some(s=>a.has(s.id)&&!qa.has(s.state))}function ln(t){return`${t.operation==="improve"?"Improve":"Create"} ${t.target.kind}`}function Ja(t,n){const a=on(t.target.displayName);if(a)return a;const s=on(n);if(s)return s;const l=t.objective.replace(/^(?:please\s+)?(?:create|make|build|improve)\s+(?:an?\s+)?agent\s+(?:that\s+|to\s+)?/i,"").trim(),o=st(l,"New agent");return o==="New agent"?o:`Agent for ${o}`}function on(t){const n=t?.trim();if(!n)return null;const a=n.toLowerCase().replace(/\s+/g," ");return/^(?:create|creating|improve|improving|new) (?:an )?agent$/.test(a)?null:n}function Wa(t){return t.state.replaceAll("_"," ")}function Qa(t){const n=t.evaluationReceipts.filter(a=>a.subject==="candidate"||a.subject==="post_release");return n.length?n.some(a=>a.status==="failed"||a.status==="blocked"||a.publishGate==="failed")?"failed":n.every(a=>a.status==="passed"&&a.publishGate!=="failed")?"passed":null:null}function Xa(t,n){return!t||!(!!(n&&je(n))||t.metadata.frozenEvaluationComplete===!0||!!n?.frozenEvaluationArtifactId||!!n?.managedServing?.customerBindingAllowed)?"not_run":!!(n&&(je(n)||Tn(n)))?"passed":"failed"}function Ya(t,n){return t&&t.localeCompare(n)>=0?t:n}function Za({agentId:t,evals:n,onAttach:a,onCreate:s}){const l=c.useMemo(()=>n.filter(r=>r.agentId===null||r.agentId===t),[t,n]),[o,i]=c.useState(l[0]?.id??"");return c.useEffect(()=>{l.some(r=>r.id===o)||i(l[0]?.id??"")},[l,o]),e.jsxs("div",{className:"labs-eval-actions",children:[e.jsxs("button",{className:"training-button secondary",type:"button",onClick:s,children:[e.jsx(da,{size:13}),"Create Eval"]}),l.length?e.jsxs(e.Fragment,{children:[e.jsx(De,{compact:!0,searchable:!0,label:"Existing Eval",options:l.map(r=>({value:r.id,label:r.name,shortLabel:r.name,description:r.path})),value:o,onChange:i}),e.jsx("button",{className:"training-button secondary",disabled:!o,type:"button",onClick:()=>a(o),children:"Add Eval"})]}):null]})}function re({label:t,value:n=t}){return e.jsx("span",{className:`labs-status-badge ${Bn(n)}`,children:t})}function Bn(t){const n=t.trim().toLowerCase().replaceAll("_"," ");return n.includes("ready")||n.includes("passed")||n.includes("succeeded")||n.includes("published")||n.includes("released")||n.includes("merged")||n.includes("imported")?"positive":n.includes("planning")||n.includes("applying")||n.includes("running")||n.includes("evaluating")||n.includes("pushing")?"info":n.includes("awaiting")||n.includes("paused")||n.includes("pr open")||n.includes("blocked")||n.includes("review")||n.includes("dirty")||n.includes("pending")?"warning":n.includes("failed")||n.includes("rejected")||n.includes("closed")||n.includes("error")||n.includes("disabled")?"negative":"neutral"}function $t({decorative:t=!1,label:n,size:a="default",tone:s,value:l=n}){return e.jsx("span",{"aria-hidden":t||void 0,"aria-label":t?void 0:n,className:`labs-status-dot ${s??Bn(l)} ${a}`,role:t?void 0:"status",title:n})}function es({candidate:t,diff:n,error:a,run:s,onApplyCandidate:l,onOpenFiles:o,onRejectCandidate:i}){const[r,u]=c.useState(null),d=c.useMemo(()=>s.evaluationReceipts.filter(f=>f.candidateId===t.id),[t.id,s.evaluationReceipts]).filter(f=>f.subject==="candidate"),b=d.length>0&&d.every(f=>f.status==="passed"&&f.publishGate!=="failed")&&(s.state==="awaiting_promotion"||s.state==="blocked"&&!!s.localProfileCommit),g=s.state==="reconciling_release",C=n?.filesChanged??t.git?.changedPaths.length??0;async function k(f,S){if(!r){u(f);try{await S()}finally{u(null)}}}return e.jsxs("div",{className:"labs-change-page",children:[s.blockedReason?e.jsx("div",{className:"labs-change-message negative",children:s.blockedReason}):null,e.jsxs("div",{className:"labs-change-timeline",children:[e.jsx("article",{className:"labs-change-timeline-item",children:e.jsxs("div",{className:"labs-change-card",children:[e.jsx("header",{className:"labs-change-card-header",children:e.jsx("span",{className:"labs-change-timeline-label",children:"Request"})}),e.jsxs("div",{className:"labs-change-card-body",children:[e.jsx("h3",{children:s.objective}),e.jsx("p",{children:"This is the behavior the Agent update should improve."})]})]})}),e.jsx("article",{className:"labs-change-timeline-item",children:e.jsxs("div",{className:"labs-change-card",children:[e.jsxs("header",{className:"labs-change-card-header",children:[e.jsx("span",{className:"labs-change-timeline-label",children:"Changes"}),e.jsx("span",{children:Pt(C)})]}),e.jsxs("div",{className:"labs-change-card-body",children:[e.jsx("h3",{children:"Drafted update"}),e.jsx("p",{children:ts(t,n,a)})]}),e.jsx("footer",{className:"labs-change-card-footer end",children:e.jsx("button",{className:"training-button secondary",disabled:!!a,title:a??void 0,type:"button",onClick:o,children:a?"Files unavailable":`Files${C?` (${C})`:""}`})})]})}),e.jsx("article",{className:"labs-change-timeline-item",children:e.jsxs("div",{className:"labs-change-card",children:[e.jsxs("header",{className:"labs-change-card-header",children:[e.jsx("span",{className:"labs-change-timeline-label",children:"Evals"}),e.jsx("span",{children:ns(d)})]}),e.jsx("div",{className:"labs-change-evals",children:d.length?d.map(f=>e.jsxs("div",{className:"labs-change-eval",children:[e.jsxs("div",{children:[e.jsx("strong",{children:f.summary??"Agent Evals"}),e.jsx("span",{children:f.summaryCounts?`${f.summaryCounts.passed}/${f.summaryCounts.total} passed`:f.status})]}),e.jsx(re,{label:f.status,value:f.status})]},f.id)):e.jsx("div",{className:"labs-change-empty",children:"Agent Evals have not finished yet."})})]})}),e.jsx("article",{className:"labs-change-timeline-item",children:e.jsxs("div",{className:"labs-change-card",children:[e.jsx("header",{className:"labs-change-card-header",children:e.jsx("span",{className:"labs-change-timeline-label",children:"Apply"})}),e.jsxs("div",{className:"labs-change-card-body",children:[e.jsx("h3",{children:"Save this Agent update"}),e.jsx("p",{children:"Applying the update changes the Agent in your Profile, then runs its Evals again."})]}),e.jsxs("footer",{className:"labs-change-card-footer",children:[e.jsxs("span",{className:"labs-change-footer-status",children:[e.jsx($t,{label:rn(s),value:s.state}),rn(s)]}),e.jsxs("div",{className:"labs-change-actions",children:[e.jsx("button",{className:"training-button secondary",disabled:!!r||g||s.state!=="awaiting_promotion",type:"button",onClick:()=>{k("reject",()=>i(s,t.id))},children:r==="reject"?"Keeping current version":"Keep current version"}),e.jsx("button",{className:"training-button",disabled:!b||!!r||g,type:"button",onClick:()=>{k("apply",()=>l(s,t.id))},children:g||r==="apply"?"Applying":s.state==="blocked"?"Re-run Evals":"Apply update"})]})]})]})})]})]})}function Pt(t){return`${t} ${t===1?"file":"files"}`}function ts(t,n,a){if(a)return a;const s=n?.filesChanged??t.git?.changedPaths.length??0;return s?n?`${Pt(s)} drafted · +${n.additions} −${n.deletions}`:`${Pt(s)} drafted for this Agent. Open Files to review the changes.`:"The drafted Agent update is ready, but no file summary is available yet."}function ns(t){if(!t.length)return"Waiting for Agent Evals";const n=t.reduce((s,l)=>({passed:s.passed+(l.summaryCounts?.passed??0),tests:s.tests+(l.summaryCounts?.total??0)}),{passed:0,tests:0});return n.tests>0?`${n.passed}/${n.tests} Evals passed`:`${t.filter(s=>s.status==="passed").length}/${t.length} Eval results passed`}function rn(t){return t.state==="awaiting_promotion"?"Ready to apply":t.state==="reconciling_release"?"Applying update":t.state==="released"?"Update applied":t.state==="rejected"?"Current version kept":t.state==="blocked"?t.localProfileCommit?"Needs verification":"Blocked":t.state.replaceAll("_"," ")}function as({runs:t,onReview:n}){return t.length?e.jsx("div",{className:"training-table-wrap",children:e.jsxs("table",{className:"training-data-table labs-agent-change-history",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Change"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Evals"}),e.jsx("th",{children:"Updated"})]})}),e.jsx("tbody",{children:t.map(a=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("button",{type:"button",onClick:()=>n(a),children:[e.jsx("strong",{children:a.objective}),e.jsx("span",{children:is(a)})]})}),e.jsx("td",{children:e.jsx(re,{label:ls(a),value:a.state})}),e.jsx("td",{children:ss(a)}),e.jsx("td",{children:$e(a.updatedAt)})]},a.id))})]})}):e.jsx("div",{className:"training-run-placeholder",children:"No changes yet."})}function ss(t){const n=[...t.candidates].reverse().find(l=>l.target.kind===t.target.kind);if(!n)return"—";const a=t.evaluationReceipts.filter(l=>l.candidateId===n.id&&l.subject==="candidate"),s=a.reduce((l,o)=>({passed:l.passed+(o.summaryCounts?.passed??0),tests:l.tests+(o.summaryCounts?.total??0)}),{passed:0,tests:0});return s.tests>0?`${s.passed}/${s.tests} passed`:a[0]?.status??"Not run"}function is(t){return`${`${t.target.kind[0].toUpperCase()}${t.target.kind.slice(1)}`} ${t.operation==="improve"?"improvement":"creation"}`}function ls(t){const n=t.state;return t.state==="planning"?"Planning":t.state==="awaiting_questions"?"Waiting for input":t.state==="awaiting_plan_approval"?"Plan ready":t.state==="applying_source"?"Saving Agent":t.state==="running_checks"||t.state==="evaluating"?"Running Evals":t.state==="awaiting_promotion"?"Update ready":t.state==="opening_pull_request"?"Preparing review":t.state==="pull_request_open"?"Review open":t.state==="reconciling_release"?"Applying update":t.state==="released"?"Updated":t.state==="rejected"?"Current version kept":t.state==="paused"?"Paused":t.state==="ready"||t.state==="ready_local"?"Ready":t.state==="pushing_hosted"?"Saving to hosted Profile":t.state==="running_hosted_checks"?"Running hosted Evals":t.state==="published_hosted"?"Published":t.state==="cancelled"?"Cancelled":t.state==="blocked"?"Blocked":t.state==="failed"?"Failed":n.replaceAll("_"," ")}function Un({series:t}){const n=Math.max(1,...t.map(a=>a.tokens));return e.jsxs("div",{className:"labs-evaluation-comparison","aria-label":"Evaluation comparison",children:[e.jsx(dn,{title:"Foreground tokens",description:"Provider-reported input and output tokens for evaluated tasks.",direction:"Lower is better",series:t.map(a=>({id:a.id,label:a.label,value:a.tokens,display:a.tokens.toLocaleString(),ratio:a.tokens/n}))}),e.jsx(dn,{title:"Quality",description:"Share of evaluated tasks that passed the pinned graders.",direction:"Higher is better",series:t.map(a=>({id:a.id,label:a.label,value:a.passRate,display:`${Math.round(a.passRate*100)}%`,ratio:a.passRate}))}),e.jsx(os,{series:t})]})}function os({series:t}){return e.jsxs("section",{className:"labs-evaluation-chart",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("h4",{children:"Token mix"}),e.jsx("p",{children:"Input and output tokens inside each measured foreground total."})]}),e.jsxs("div",{className:"labs-evaluation-token-legend","aria-label":"Token legend",children:[e.jsx("span",{children:"Input"}),e.jsx("span",{children:"Output"})]})]}),e.jsx("div",{className:"labs-evaluation-token-mix",children:t.map((n,a)=>{const s=Math.max(1,n.inputTokens+n.outputTokens);return e.jsxs("div",{"data-series-index":a,children:[e.jsxs("div",{className:"labs-evaluation-token-label",children:[e.jsx("span",{children:n.label}),e.jsx("strong",{children:n.tokens.toLocaleString()})]}),e.jsxs("div",{className:"labs-evaluation-token-stack","aria-hidden":"true",children:[e.jsx("span",{style:{width:`${n.inputTokens/s*100}%`}}),e.jsx("span",{style:{width:`${n.outputTokens/s*100}%`}})]}),e.jsxs("small",{children:[n.inputTokens.toLocaleString()," input · ",n.outputTokens.toLocaleString()," output"]})]},n.id)})})]})}function dn({title:t,description:n,direction:a,series:s}){return e.jsxs("section",{className:"labs-evaluation-chart",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("h4",{children:t}),e.jsx("p",{children:n})]}),e.jsx("span",{className:"labs-evaluation-direction",children:a})]}),e.jsx("div",{className:"labs-evaluation-chart-series",children:s.map((l,o)=>e.jsxs("div",{className:"labs-evaluation-chart-row","data-series-index":o,children:[e.jsxs("div",{className:"labs-evaluation-chart-label",children:[e.jsx("span",{children:l.label}),e.jsx("strong",{children:l.display})]}),e.jsx("div",{className:"labs-evaluation-chart-track","aria-hidden":"true",children:e.jsx("span",{style:{width:`${Math.max(2,Math.min(100,l.ratio*100))}%`}})})]},l.id))})]})}const rs=["baseline","adaptation","candidate_adaptation","candidate"];function Fn(t){const n=new Map;for(const a of t){const s=`${a.phase}\0${a.taskId}`,l=n.get(s);(!l||a.startedAt>l.startedAt||a.startedAt===l.startedAt&&a.attemptId>l.attemptId)&&n.set(s,a)}return[...n.values()]}function zn(t){const n=Fn(t.attempts);return Object.fromEntries(rs.map(a=>{const s=n.filter(o=>o.phase===a),l=s.map(o=>o.costUsd).filter(o=>o!==null);return[a,{inputTokens:s.reduce((o,i)=>o+i.inputTokens,0),outputTokens:s.reduce((o,i)=>o+i.outputTokens,0),totalTokens:s.reduce((o,i)=>o+i.totalTokens,0),costUsd:l.length?l.reduce((o,i)=>o+i,0):null}]}))}function Be(t){const n=Fn(t.attempts??[]),{summary:a,pairs:s}=ca({attempts:n});return{...a,pairs:s,baselinePassedCount:s.filter(l=>l.baseline.passed).length,refinedPassedCount:s.filter(l=>l.refined.passed).length,cohorts:{adaptation:a.cohorts.adaptation,held_out:a.cohorts.heldOut}}}function ds({workproduct:t,training:n,readOnly:a,defaultModel:s,initialModel:l,providerSettings:o,onClose:i,onOpenEntry:r,onToast:u}){const[h,d]=c.useState("high"),[j,b]=c.useState(l??s),[g,C]=c.useState(!1),f=c.useMemo(()=>(n.payload?.modelRuns??[]).filter(m=>m.modelId===t.id&&m.kind==="evaluation"&&m.evaluation?.benchmarkId==="harness-refiner").sort((m,T)=>T.updatedAt.localeCompare(m.updatedAt)),[n.payload?.modelRuns,t.id])[0]??null,S=us(f?.receipt??null),y=S?zn(S):null,w=S?Be(S):null,R=cs(f?.receipt??null),p=(n.payload?.tasksets??[]).find(m=>m.benchmark?.definitionId==="harness-refiner"),_=c.useMemo(()=>hs(o,j),[j,o]);async function x(){C(!0);try{const m=await n.actions.startHarnessRefinerBenchmark(t.id,j,h);if(!m)throw new Error("Benchmark start returned no Model Run.");r(`model-run:${m.id}`)}catch(m){u(m instanceof Error?m.message:String(m),"error")}finally{C(!1)}}return e.jsxs(_e,{ariaLabel:`Benchmark ${t.name}`,backdropClassName:"labs-rename-backdrop",className:"labs-rename-dialog labs-model-benchmark-dialog",dismissDisabled:g,onClose:i,children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Benchmark model"}),e.jsx("p",{children:"Run a controlled evaluation and save it in this Model's history."})]}),e.jsx("button",{"aria-label":"Close benchmark setup",disabled:g,type:"button",onClick:i,children:e.jsx(Me,{size:16})})]}),e.jsx("div",{className:"labs-model-benchmark-dialog-body",children:e.jsxs("article",{className:"labs-model-benchmark-card",children:[e.jsxs("div",{className:"labs-model-benchmark-heading",children:[e.jsxs("div",{children:[e.jsx("h3",{children:"Harness Refiner 08112026"}),e.jsx("p",{children:"Tests whether every task uses fewer foreground tokens after an evidence-driven Harness update. Quality is measured separately. Each run is watched to terminal state with a $10 maximum provider spend."})]}),f?e.jsx(re,{label:S?cn(S):R?"Inconclusive":Se(f.status),value:S?w?.passed?"succeeded":"failed":R?.terminalClassification??f.status}):e.jsx(re,{label:"Not run",value:"not_run"})]}),S?e.jsxs(e.Fragment,{children:[e.jsx(Un,{series:[{id:"baseline",label:"Baseline",inputTokens:y.baseline.inputTokens,outputTokens:y.baseline.outputTokens,tokens:y.baseline.totalTokens,passRate:S.quality.baselinePassRate,costUsd:y.baseline.costUsd},{id:"candidate",label:"Candidate Harness",inputTokens:y.candidate.inputTokens,outputTokens:y.candidate.outputTokens,tokens:y.candidate.totalTokens,passRate:S.quality.candidatePassRate,costUsd:y.candidate.costUsd}]}),e.jsxs("div",{className:"labs-model-benchmark-result-row",children:[e.jsx("span",{children:cn(S)}),e.jsx("strong",{children:ps(S)}),e.jsx("button",{className:"training-button secondary labs-compact-button",type:"button",onClick:()=>f&&r(`model-run:${f.id}`),children:"View run"})]})]}):R?e.jsxs("div",{className:"labs-model-benchmark-result-row",children:[e.jsx("span",{children:"Inconclusive · candidate replay skipped"}),e.jsxs("strong",{children:[R.attempts.length," attempts · $",R.budget.observedSpendUsd.toFixed(4)]}),e.jsx("button",{className:"training-button secondary labs-compact-button",type:"button",onClick:()=>f&&r(`model-run:${f.id}`),children:"View run"})]}):f?e.jsxs("button",{className:"labs-model-benchmark-running",type:"button",onClick:()=>r(`model-run:${f.id}`),children:[e.jsx("span",{children:f.failure??(f.evaluationProgress?`${f.evaluationProgress.stage.replaceAll("_"," ")} · ${f.evaluationProgress.completedAttempts}/${f.evaluationProgress.totalAttempts} attempts`:"The benchmark is running through its pinned stages.")}),e.jsx("strong",{children:$e(f.updatedAt)})]}):e.jsx("p",{className:"labs-model-benchmark-empty",children:p?"No result yet. The shipped 20-case Taskset is ready.":"The built-in Harness Refiner Taskset is loading."}),a?null:e.jsxs("div",{className:"labs-model-benchmark-controls",children:[e.jsxs("label",{className:"labs-model-benchmark-model",children:[e.jsx("span",{children:"Model"}),e.jsx("select",{"aria-label":"Benchmark model",value:Et(j),onChange:m=>{const T=ms(m.target.value);T&&b(T)},children:_.map(m=>e.jsx("optgroup",{label:m.label,children:m.models.map(T=>e.jsx("option",{value:T.value,children:T.label},T.value))},m.providerId))})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Effort"}),e.jsxs("select",{value:h,onChange:m=>d(m.target.value),children:[e.jsx("option",{value:"low",children:"Low"}),e.jsx("option",{value:"medium",children:"Medium"}),e.jsx("option",{value:"high",children:"High"})]})]}),e.jsx("button",{className:"training-button primary",disabled:g||f?.status==="running",type:"button",onClick:()=>{x()},children:g?"Starting…":"Run Refiner Benchmark"})]})]})})]})}function cs(t){return t&&typeof t=="object"&&"schemaVersion"in t&&t.schemaVersion==="openpond.modelEvaluationStopReceipt.v1"?t:null}function us(t){return t&&typeof t=="object"&&"schemaVersion"in t&&t.schemaVersion==="openpond.modelEvaluationReceipt.v1"?t:null}function hs(t,n){const a=_n(t,{includeUnavailable:!1}).flatMap(l=>{const o=$n(l.value,t).map(i=>({value:Et({providerId:l.value,modelId:i.value}),label:i.label}));return o.length?[{providerId:l.value,label:l.label,models:o}]:[]}),s=Et(n);return a.some(l=>l.models.some(o=>o.value===s))?a:[{providerId:n.providerId,label:n.providerId,models:[{value:s,label:zt(n.modelId,t,n.providerId)}]},...a]}function Et(t){return JSON.stringify([t.providerId,t.modelId])}function ms(t){try{const n=JSON.parse(t);return!Array.isArray(n)||n.length!==2||typeof n[0]!="string"||typeof n[1]!="string"?null:{providerId:n[0],modelId:n[1]}}catch{return null}}function ps(t){const n=Be(t),a=n.tokenDelta>0?"+":"",s=n.tokenDeltaPercent===null?"":` · ${a}${n.tokenDeltaPercent.toFixed(1)}%`;return`${a}${n.tokenDelta.toLocaleString()} tokens${s}`}function cn(t){const n=Be(t);return`${n.passedTaskCount}/${n.comparedTaskCount} efficiency passes`}function qt(t){if(!t)return[];const n=new Map;for(const a of[...t.modelTasksets??[],...t.tasksets??[]])n.set(`${a.id}:${a.revision}:${a.contentHash}`,a);return[...n.values()]}function ct(t,n){return(n?.modelRuns??[]).filter(a=>a.modelId===t.id).sort((a,s)=>s.updatedAt.localeCompare(a.updatedAt))??[]}function ut(t,n,a){if(!a)return[];const s=n.filter(i=>i.target.kind==="model"&&i.target.id===t.id),l=new Set(s.flatMap(i=>i.target.kind==="model"&&i.target.trainingPlanId?[i.target.trainingPlanId]:[])),o=new Set(s.flatMap(i=>i.tasksetRef?[i.tasksetRef.id]:[]));return t.tasksetId&&o.add(t.tasksetId),a.plans.filter(i=>i.modelId===t.id||l.has(i.id)||i.modelId===null&&o.has(i.tasksetId)).sort((i,r)=>r.createdAt.localeCompare(i.createdAt))}function We(t,n,a){if(!a)return[];const s=new Set(ut(t,n,a).map(o=>o.id)),l=new Set(ct(t,a).map(o=>o.id));return a.jobs.filter(o=>s.has(o.planId)||typeof o.metadata.modelRunId=="string"&&l.has(o.metadata.modelRunId)).sort((o,i)=>i.createdAt.localeCompare(o.createdAt))}function bs(t,n,a){if(!a)return[];const s=new Set(ut(t,n,a).map(l=>l.tasksetId));for(const l of n)l.target.kind==="model"&&l.target.id===t.id&&l.tasksetRef&&s.add(l.tasksetRef.id);return t.tasksetId&&s.add(t.tasksetId),qt(a).filter(l=>s.has(l.id))}function Qe(t,n,a){if(!a)return[];const s=ut(t,n,a),l=new Map(s.map(d=>[d.id,d])),o=We(t,n,a),i=new Map(o.map(d=>[d.id,d])),r=Vn(t,n,a),u=new Set(o.map(d=>d.id));return a.models.filter(d=>d.modelId===t.id||u.has(d.jobId)).sort((d,j)=>d.importedAt.localeCompare(j.importedAt)).map((d,j)=>{const b=i.get(d.jobId)??null;return{lineage:d,number:j+1,job:b,plan:b?l.get(b.planId)??null:null,taskset:qt(a).find(g=>g.id===d.tasksetId)??null,current:r?.modelArtifactLineageId===d.id}}).sort((d,j)=>j.number-d.number)}function Vn(t,n,a){if(!a)return null;const s=new Set(We(t,n,a).map(i=>i.id)),l=new Set(a.models.filter(i=>i.modelId===t.id||s.has(i.jobId)).map(i=>i.id)),o=new Set(n.flatMap(i=>i.target.kind==="model"&&i.target.id===t.id&&i.tasksetRef?[i.tasksetRef.id]:[]));return t.tasksetId&&o.add(t.tasksetId),a.modelBindings.filter(i=>i.status==="active"&&i.role==="chat_manual"&&(i.roleTargetId===t.id||o.has(i.roleTargetId)||i.roleTargetId==="default"&&l.has(i.modelArtifactLineageId))).sort((i,r)=>r.promotedAt.localeCompare(i.promotedAt))[0]??null}function gs({workproduct:t,runs:n,training:a,onOpenDataset:s,onOpenEntry:l,onResumeDraft:o,readOnly:i=!1}){const r=a.payload,u=c.useMemo(()=>We(t,n,r),[n,r,t]),h=c.useMemo(()=>Qe(t,n,r),[n,r,t]),d=c.useMemo(()=>ut(t,n,r),[n,r,t]),j=c.useMemo(()=>new Map(d.map(x=>[x.id,x])),[d]),b=ct(t,r),g=qt(r),C=c.useMemo(()=>(r?.modelRunDrafts??[]).filter(x=>x.modelId===t.id&&(x.status==="draft"||x.status==="ready_to_run")).sort((x,m)=>m.updatedAt.localeCompare(x.updatedAt)),[r?.modelRunDrafts,t.id]),k=c.useMemo(()=>Ht(u,h,b,i?[]:C),[C,u,b,i,h]),[f,S]=c.useState(!1),y=f?k:k.slice(0,5),w=k.filter(x=>!x.draft).length,R=k.length-w,p=c.useMemo(()=>{let x=w;const m=new Map;for(const T of k)T.draft||(m.set(T.key,x),x-=1);return m},[k,w]);function _(x){if(x.draft){o(x.draft.id);return}l(x.key)}return e.jsxs("section",{className:"labs-model-version-index","aria-label":"Model runs",children:[e.jsxs("header",{className:"labs-model-section-intro",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Recent runs"}),e.jsx("p",{children:"Training and evaluation history, including unfinished drafts."})]}),e.jsxs("span",{children:[w," ",w===1?"run":"runs",R?` · ${R} ${R===1?"draft":"drafts"}`:""]})]}),e.jsx("div",{className:"training-table-wrap",children:e.jsxs("table",{className:"training-data-table labs-model-runs-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Run or draft"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Method"}),e.jsx("th",{children:"Dataset"}),e.jsx("th",{children:"Result"}),e.jsx("th",{children:"Updated"})]})}),e.jsxs("tbody",{children:[k.length?null:e.jsx("tr",{children:e.jsx("td",{colSpan:6,children:e.jsx("div",{className:"training-run-placeholder",children:"No runs or drafts yet."})})}),y.map(x=>{const m=p.get(x.key)??null,T=x.version?.plan??(x.job?j.get(x.job.planId)??null:null),V=x.version?.taskset??g.find($=>$.id===(x.draft?.tasksetRef?.id??x.lifecycleRun?.taskset.id??T?.tasksetId))??null,E=x.version;return e.jsxs("tr",{className:x.draft?"labs-model-run-draft":void 0,onClick:()=>_(x),children:[e.jsx("td",{children:e.jsxs("button",{className:"labs-version-row-button",type:"button",onClick:$=>{$.stopPropagation(),_(x)},children:[e.jsx("strong",{children:x.draft?x.draft.title||"Run draft":`Run ${m}`}),e.jsx("small",{children:x.draft?x.draft.status==="ready_to_run"?"Review and run":"Resume draft":E?`Created Version ${E.number}`:x.lifecycleRun?.kind==="evaluation"?"Evaluation":x.lifecycleRun?.kind==="rollout_smoke"?"Preflight rollout":"Training"})]})}),e.jsx("td",{children:e.jsx(re,{label:x.draft?x.draft.status==="ready_to_run"?"Ready to run":"Draft":x.lifecycleRun?Se(x.lifecycleRun.status):x.job?Se(x.job.status):"Not started",value:x.draft?.status??x.lifecycleRun?.status??x.job?.status??"not_run"})}),e.jsx("td",{children:x.lifecycleRun?.kind==="evaluation"?"Evaluation":Oe(x.draft?.method??x.lifecycleRun?.method??T?.recipe.method)}),e.jsx("td",{children:V?e.jsx("button",{className:"labs-version-dataset-link",type:"button",onClick:$=>{$.stopPropagation(),s(V.id)},children:V.name}):"Unavailable"}),e.jsx("td",{children:xs(x)}),e.jsx("td",{children:$e(x.lifecycleRun?.updatedAt??x.draft?.updatedAt??E?.lineage.importedAt??x.job?.updatedAt??"")})]},x.key)})]})]})}),k.length>5?e.jsx("div",{className:"labs-model-run-list-actions",children:e.jsx("button",{className:"training-button secondary labs-compact-button",type:"button",onClick:()=>S(x=>!x),children:f?"Show latest 5":`Show all ${k.length} activities`})}):null]})}function fs({workproduct:t,runs:n,training:a,onOpenDataset:s,onOpenEntry:l,onToast:o,readOnly:i=!1}){const r=a.payload,u=c.useMemo(()=>Qe(t,n,r),[n,r,t]),h=Vn(t,n,r);async function d(b){if(i)return;const g=u.find(k=>k.lineage.id===b);if(!g||!je(g.lineage)||!window.confirm(`Set Version ${g.number} as active for ${t.name}?`))return;const C=await a.actions.bindModel(g.lineage.id,"chat_manual",t.id);o(C?`Version ${g.number} is now active.`:"The active Version could not be changed.",C?"success":"error")}async function j(b,g){if(i)return;const C=await a.actions.setModelPinned(b,g);o(C?g?"Version pinned.":"Version unpinned.":"Version pin could not be changed.",C?"success":"error")}return e.jsxs("section",{className:"labs-model-version-index","aria-label":"Model versions",children:[e.jsxs("header",{className:"labs-model-section-intro",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Versions"}),e.jsx("p",{children:"Trained outputs that can be evaluated, activated, and downloaded."})]}),e.jsxs("span",{children:[u.length," trained"]})]}),e.jsx("div",{className:"training-table-wrap",children:e.jsxs("table",{className:"training-data-table labs-model-versions-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Version"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Training"}),e.jsx("th",{children:"Dataset"}),e.jsx("th",{children:"Evaluation"}),e.jsx("th",{children:"Created"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsxs("tbody",{children:[u.length?null:e.jsx("tr",{children:e.jsx("td",{colSpan:7,children:e.jsx("div",{className:"training-run-placeholder",children:"No trained Versions yet. A successful run will appear here."})})}),u.map(b=>{const g=h?.modelArtifactLineageId===b.lineage.id;return e.jsxs("tr",{onClick:()=>l(b.job?`job:${b.job.id}`:`version:${b.lineage.id}`),children:[e.jsx("td",{children:e.jsxs("button",{className:"labs-version-row-button",type:"button",onClick:()=>l(b.job?`job:${b.job.id}`:`version:${b.lineage.id}`),children:[e.jsxs("strong",{children:["Version ",b.number]}),e.jsx("small",{children:ys(b.lineage.id)})]})}),e.jsx("td",{children:e.jsx(vs,{job:b.job,version:b})}),e.jsx("td",{children:Oe(b.plan?.recipe.method)}),e.jsx("td",{children:b.taskset?e.jsx("button",{className:"labs-version-dataset-link",type:"button",onClick:C=>{C.stopPropagation(),s(b.taskset.id)},children:b.taskset.name}):"Unavailable"}),e.jsx("td",{children:e.jsx(js,{job:b.job,version:b})}),e.jsx("td",{children:$e(b.lineage.importedAt)}),e.jsx("td",{children:e.jsxs("div",{className:"training-table-actions",children:[e.jsx("button",{"aria-pressed":b.lineage.pinned||g,className:"labs-version-icon-button",disabled:i||g,title:g?"The active Version stays pinned":b.lineage.pinned?"Unpin Version":"Pin Version",type:"button",onClick:C=>{C.stopPropagation(),j(b.lineage.id,!b.lineage.pinned)},children:e.jsx(ua,{size:14})}),b.current?null:e.jsx("button",{className:"training-button secondary",disabled:i||!je(b.lineage),type:"button",onClick:C=>{C.stopPropagation(),d(b.lineage.id)},children:"Activate"}),e.jsx("button",{"aria-label":`Download Version ${b.number}`,className:"labs-version-icon-button",type:"button",onClick:C=>{C.stopPropagation(),a.actions.downloadModelPackage(b.lineage.id)},children:e.jsx(ot,{size:14})})]})})]},b.lineage.id)})]})]})})]})}function Tl(t,n,a=[]){const s=new Map(n.flatMap(i=>i.job?[[i.job.id,i]]:[])),l=t.map(i=>({key:`job:${i.id}`,job:i,version:s.get(i.id)??null,draft:null})),o=new Set(t.map(i=>i.id));for(const i of n)i.job&&o.has(i.job.id)||l.push({key:`version:${i.lineage.id}`,job:i.job,version:i,draft:null});for(const i of a)l.push({key:`draft:${i.id}`,job:null,version:null,draft:i});return l.sort((i,r)=>un(r).localeCompare(un(i)))}function Ht(t,n,a,s=[]){const l=new Map(t.flatMap(h=>typeof h.metadata.modelRunId=="string"?[[h.metadata.modelRunId,h]]:[])),o=new Map(n.flatMap(h=>h.job?[[h.job.id,h]]:[])),i=new Map(n.map(h=>[h.lineage.id,h])),r=new Set,u=a.map(h=>{const d=l.get(h.id)??t.find(j=>j.id===h.id)??null;return d&&r.add(d.id),{key:`model-run:${h.id}`,job:d,lifecycleRun:h,version:(d?o.get(d.id)??null:null)??(h.adapterArtifactLineageId?i.get(h.adapterArtifactLineageId)??null:null),draft:null}});for(const h of t)r.has(h.id)||u.push({key:`job:${h.id}`,job:h,lifecycleRun:null,version:o.get(h.id)??null,draft:null});for(const h of s)u.push({key:`draft:${h.id}`,job:null,lifecycleRun:null,version:null,draft:h});return u.sort((h,d)=>hn(d).localeCompare(hn(h)))}function un(t){return t.version?.lineage.importedAt??t.draft?.updatedAt??t.job?.updatedAt??t.job?.createdAt??""}function hn(t){return t.draft?.updatedAt??t.lifecycleRun?.updatedAt??t.job?.updatedAt??t.job?.createdAt??""}function xs(t){if(t.draft)return t.draft.status==="ready_to_run"?"Review and run":"Resume draft";if(t.version)return`Version ${t.version.number}`;if(t.lifecycleRun?.kind==="evaluation"&&t.lifecycleRun.receipt?.schemaVersion==="openpond.modelEvaluationReceipt.v1"){const n=t.lifecycleRun.receipt.foregroundTokenDelta;return`${n>0?"+":""}${n.toLocaleString()} tokens`}return t.lifecycleRun?.reward?`Reward ${t.lifecycleRun.reward.raw.toFixed(3)}`:t.lifecycleRun?.status==="failed"||t.job?.status==="failed"?"Failed":t.lifecycleRun?.status==="succeeded"||t.job?.status==="succeeded"?"Completed":"No output"}function js({job:t,version:n}){const a=n?!!je(n.lineage)||t?.metadata.frozenEvaluationComplete===!0||!!n.lineage.frozenEvaluationArtifactId||!!n.lineage.managedServing?.customerBindingAllowed:!1,s=n?!!je(n.lineage)||Tn(n.lineage):!1,l=n?a?s?"Passed":"Failed":"Not run":t&&["queued","starting","running","cancelling","reconciling"].includes(t.status)?"Pending":"Not run",o=n?s?"passed":a?"failed":"not_run":"not_run";return e.jsx(re,{label:l,value:o})}function vs({job:t,version:n}){const a=!!(t&&["queued","starting","running","cancelling","reconciling"].includes(t.status));return e.jsx(re,{label:n?n.current?"Active":"Available":a?"Pending":"Not created",value:n?n.current?"current":"ready":a?"running":"not_run"})}function ys(t){const n=t.replace(/^baseline_run_/,"").replace(/^(?:training_job_|lineage_)(?:artifact_)?/,"").replace(/^model_run_/,"");return n.length<=12?n:n.slice(-8)}function ks({run:t,onAnswerQuestion:n,onApplyCandidate:a,onApprove:s,onCancel:l,onOpenPullRequest:o,onPause:i,onOpenConversation:r,onReconcilePullRequest:u,onRejectCandidate:h,onRetry:d,onResume:j,onRevise:b}){const g=t.state==="blocked"?"Review blocker":t.state==="failed"?"Review failure":"View progress",C=t.target.kind==="agent"&&["blocked","failed","cancelled"].includes(t.state);return e.jsxs("div",{className:"labs-run-decision",children:[e.jsx(Ia,{runtime:{run:t,onAnswerQuestion:n,onApplyCandidate:a,onApprove:s,onCancel:l,onOpenPullRequest:o,onPause:i,onReconcilePullRequest:u,onRejectCandidate:h,onResume:j,onRevise:b}}),t.scope.conversationId||C?e.jsxs("div",{className:"labs-run-decision-actions",children:[t.scope.conversationId?e.jsx("button",{className:"training-button secondary",type:"button",onClick:()=>r(t.scope.conversationId),children:g}):null,C?e.jsx("button",{className:"training-button",type:"button",onClick:d,children:"Try again"}):null]}):null]})}function Ss(t,n){const a=new Blob([`${JSON.stringify(n,null,2)}
|
|
3
|
+
`],{type:"application/json"}),s=URL.createObjectURL(a),l=document.createElement("a");l.href=s,l.download=t,l.click(),URL.revokeObjectURL(s)}const Ns=new Set(["released","rejected","ready","ready_local","published_hosted","blocked","failed","cancelled"]),qn=new Set(["queued","starting","running","cancelling","reconciling"]);function Cs(t){const n=t.runs[0]??null,a=n?.state==="blocked"&&n.candidates.some(l=>!!l.git?.worktreePath&&["draft","checking"].includes(l.status))?n:null,s=t.runs.find(l=>!Ns.has(l.state))??null;if(t.workproduct.kind==="model"&&t.taskset){const l=Ln(t.training,t.taskset.id)[0]??null;if(l&&qn.has(l.status))return mn({taskset:t.taskset,training:t.training,latestRun:n,fallbackStatus:t.workproduct.status})}return a?Ct(a):s?Ct(s):t.workproduct.kind==="model"?!t.taskset&&n&&["failed","blocked","cancelled"].includes(n.state)?Ct(n):mn({taskset:t.taskset,training:t.training,latestRun:n,fallbackStatus:t.workproduct.status}):t.workproduct.kind==="agent"?{statusLabel:t.workproduct.status,statusValue:t.workproduct.status,action:{kind:"start_agent_change",label:"Improve agent"},runId:n?.id??null,conversationId:n?.scope.conversationId??null}:n?.scope.conversationId?{statusLabel:t.workproduct.status,statusValue:t.workproduct.status,action:{kind:"open_conversation",label:"Open chat"},runId:n.id,conversationId:n.scope.conversationId}:{statusLabel:t.workproduct.status,statusValue:t.workproduct.status,action:null,runId:n?.id??null,conversationId:n?.scope.conversationId??null}}function Ct(t){const n={statusLabel:Rs(t),statusValue:t.state,runId:t.id,conversationId:t.scope.conversationId};if(t.state==="awaiting_questions")return{...n,action:{kind:"review_run",label:"Review questions"}};if(t.state==="awaiting_plan_approval")return{...n,action:{kind:"review_run",label:"Review plan"}};if(t.state==="awaiting_promotion")return{...n,action:{kind:"review_run",label:t.target.kind==="agent"?"Review update":"Review candidate"}};if(t.state==="pull_request_open")return{...n,action:{kind:"review_run",label:"Review change"}};if(t.state==="paused")return{...n,action:{kind:"resume_run",label:"Resume"}};if(t.state==="blocked"){const a=t.candidates.some(s=>!!s.git?.worktreePath&&["draft","checking"].includes(s.status));return{...n,action:a?{kind:"resume_run",label:t.target.kind==="agent"?"Continue update":"Continue candidate"}:t.target.kind==="agent"?{kind:"start_agent_change",label:"Try again"}:t.scope.conversationId?{kind:"open_conversation",label:"Review blocker"}:null}}return t.state==="failed"?{...n,action:t.scope.conversationId?{kind:"open_conversation",label:"Review failure"}:null}:{...n,action:t.scope.conversationId?{kind:"open_conversation",label:"View progress"}:null}}function mn(t){const n=t.latestRun?.scope.conversationId??null;if(!t.taskset)return{statusLabel:"Not hosted",statusValue:"not_run",action:n?{kind:"open_conversation",label:"View progress"}:null,runId:t.latestRun?.id??null,conversationId:n};const s=Ln(t.training,t.taskset.id)[0]??null,l=s?t.training?.models.find(o=>o.jobId===s.id&&o.status==="imported")??null:null;if(s&&qn.has(s.status))return{statusLabel:Se(s.status),statusValue:s.status,action:{kind:"open_training",label:"View run"},runId:t.latestRun?.id??null,conversationId:n};if(s?.status==="failed")return{statusLabel:"Training failed",statusValue:"failed",action:{kind:"open_training",label:"Review failure"},runId:t.latestRun?.id??null,conversationId:n};if(s?.status==="succeeded"){const o=s.metadata.frozenEvaluationComplete===!0||!!l?.frozenEvaluationArtifactId,i=typeof s.metadata.frozenEvaluationThresholdPassed=="boolean"?s.metadata.frozenEvaluationThresholdPassed:l?.promotable===!0;return o&&!i?{statusLabel:"Evaluation failed",statusValue:"failed",action:{kind:"open_training",label:"Review results"},runId:t.latestRun?.id??null,conversationId:n}:o&&i?{statusLabel:l?.promotable?"Model ready":"Evaluation passed",statusValue:l?.promotable?"ready":"passed",action:{kind:"open_training",label:"Review results"},runId:t.latestRun?.id??null,conversationId:n}:{statusLabel:l?"Evaluation pending":"Collecting model",statusValue:"running",action:{kind:"open_training",label:"Review results"},runId:t.latestRun?.id??null,conversationId:n}}return t.taskset.readiness?.ready?{statusLabel:"Ready to train",statusValue:"ready",action:{kind:"start_training",label:"Start training"},runId:t.latestRun?.id??null,conversationId:n}:{statusLabel:"Needs review",statusValue:"needs_review",action:{kind:"open_data",label:"Review data"},runId:t.latestRun?.id??null,conversationId:n}}function Rs(t){const n=t.state,a=t.target.kind==="agent";return{planning:"Planning",awaiting_questions:"Needs answers",awaiting_plan_approval:"Plan ready",paused:"Paused",applying_source:a?"Saving Agent":"Applying changes",running_checks:a?"Running Evals":"Running checks",evaluating:a?"Running Evals":"Evaluating",awaiting_promotion:a?"Update ready":"Candidate ready",opening_pull_request:"Opening review",pull_request_open:"Review open",reconciling_release:a?"Saving update":"Merging change",released:"Released",rejected:"Rejected",ready:"Ready",ready_local:"Ready",pushing_hosted:"Syncing",running_hosted_checks:"Verifying hosted",published_hosted:"Published",blocked:"Blocked",failed:"Failed",cancelled:"Cancelled"}[n]}const pn={chat_manual:"Default chat model",agent:"Agent runtime",extension:"Extension runtime",authoring_optimizer:"Authoring / optimizer"};function Is({lineage:t,state:n,training:a,onToast:s}){const[l,o]=c.useState("chat_manual"),[i,r]=c.useState("default"),[u,h]=c.useState(null),[d,j]=c.useState(""),b=c.useMemo(()=>n?.modelBindings.find(m=>m.status==="active"&&m.role===l&&m.roleTargetId===i.trim())??null,[l,i,n?.modelBindings]),g=b?n?.models.find(m=>m.id===b.modelArtifactLineageId)??null:null,k=(t?.frozenEvaluationArtifactId?n?.artifacts.find(m=>m.id===t.frozenEvaluationArtifactId)??null:null)?.metadata.evaluationComplete===!1;if(!t)return e.jsx("div",{className:"training-run-placeholder",children:"Promotion is available after a verified artifact is imported."});const f=t,S=je(f),y=!!a.busyAction,w=f.status==="imported"&&!!S&&!!i.trim(),R=b?.modelArtifactLineageId===f.id;async function p(){const m=await a.actions.bindModel(f.id,l,i.trim());h(null),s(m?"Model binding activated.":"Couldn’t activate Model binding.",m?"success":"error")}async function _(){const m=d.trim();if(!m)return;const T=await a.actions.rejectModel(f.id,m);h(null),s(T?"Model candidate rejected.":"Couldn’t reject Model candidate.",T?"success":"error")}async function x(){if(!b)return;const m=await a.actions.rollbackModelBinding(b.id);s(m?"Model binding rolled back.":"Couldn’t roll back Model binding.",m?"success":"error")}return e.jsxs("div",{className:"training-promotion",children:[e.jsxs("div",{className:"training-promotion-status",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Promotion gate"}),e.jsx("strong",{children:S?"Passed":"Blocked"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Selected role"}),e.jsx("strong",{children:g?Rt(g.id):"No active binding"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Rollback target"}),e.jsx("strong",{children:b?.rollbackTargetBindingId?Rt(b.rollbackTargetBindingId):"None"})]})]}),e.jsxs("div",{className:"training-promotion-controls",children:[e.jsxs("label",{children:[e.jsx("span",{children:"Role"}),e.jsx("select",{value:l,onChange:m=>{const T=m.target.value;o(T),r(T==="chat_manual"?"default":"")},children:Object.entries(pn).map(([m,T])=>e.jsx("option",{value:m,children:T},m))})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Role target"}),e.jsx("input",{value:i,placeholder:l==="agent"?"agent id":l==="extension"?"extension id":"default",onChange:m=>r(m.target.value)})]}),e.jsxs("div",{className:"training-promotion-actions",children:[R?e.jsx("button",{className:"training-button secondary",type:"button",disabled:y,onClick:()=>{x()},children:"Roll back"}):e.jsx("button",{className:"training-button",type:"button",disabled:y||!w,onClick:()=>h("bind"),children:b?"Replace binding":"Bind model"}),e.jsx("button",{className:"training-button danger",type:"button",disabled:y||t.status==="rejected"||R,onClick:()=>h("reject"),children:"Reject"})]})]}),S?null:e.jsx("p",{className:"training-promotion-note",children:k?"The artifact remains inspectable. Its prior evaluation was blocked by provider infrastructure and recorded no quality result.":"The artifact remains inspectable, but it cannot be bound until its frozen-evaluation threshold passes."}),u?e.jsx("div",{className:"training-dialog-backdrop",role:"presentation",onMouseDown:()=>!y&&h(null),children:e.jsxs("section",{className:"training-dialog training-promotion-dialog",role:"dialog","aria-modal":"true","aria-label":u==="bind"?"Confirm Model binding":"Reject Model candidate",onMouseDown:m=>m.stopPropagation(),children:[e.jsx("div",{className:"training-dialog-header",children:e.jsxs("div",{children:[e.jsx("h2",{children:u==="bind"?"Activate this Model binding?":"Reject this Model candidate?"}),e.jsx("p",{children:u==="bind"?`${pn[l]} · ${i.trim()}`:"The artifact and evaluation evidence are retained."})]})}),u==="bind"?e.jsx("p",{children:b?`The current binding ${Rt(b.modelArtifactLineageId)} becomes the recorded rollback target.`:"This is an explicit activation; training success alone never changes runtime selection."}):e.jsxs("label",{className:"training-promotion-reason",children:[e.jsx("span",{children:"Reason"}),e.jsx("textarea",{autoFocus:!0,value:d,onChange:m=>j(m.target.value)})]}),e.jsxs("div",{className:"training-dialog-actions",children:[e.jsx("button",{className:"training-button secondary",type:"button",disabled:y,onClick:()=>h(null),children:"Cancel"}),e.jsx("button",{className:`training-button ${u==="reject"?"danger":""}`,type:"button",disabled:y||u==="reject"&&!d.trim(),onClick:()=>{u==="bind"?p():_()},children:y?"Applying…":u==="bind"?"Activate binding":"Reject candidate"})]})]})}):null]})}function Rt(t){return t.replace(/^lineage_/,"").replace(/^model_binding_/,"").slice(0,16)}function Ms(t){return[...t.candidates].reverse().find(n=>!!n.git?.headCommit)??null}function As(t){return t?t.state==="released"?"positive":t.state==="blocked"||t.state==="failed"||t.state==="rejected"?"negative":t.state==="reconciling_release"?"info":"warning":"neutral"}function ws({workproduct:t,profile:n}){if(t.kind==="agent"){const a=n?.agents.find(s=>s.id===t.id)??null;return e.jsx(be,{title:"Agent",children:e.jsxs("dl",{className:"training-configuration-list",children:[e.jsx(ie,{label:"Enabled",value:a?.enabled?"Yes":"No"}),e.jsx(ie,{label:"Source",value:a?.path??t.path??"Draft"}),e.jsx(ie,{label:"Default action",value:`${t.id}.chat`}),e.jsx(ie,{label:"Profile checks",value:n?.lastCheck?.status??"Not run"})]})})}if(t.kind==="skill"){const a=t.skillSource==="codex"?null:n?.skills.find(i=>i.name===t.id)??null,s=t.skillValidationStatus??a?.validationStatus??"error",l=t.skillValidationMessages??a?.validationMessages??[],o=t.skillResourceFiles??[];return e.jsxs(be,{title:"Skill",children:[e.jsxs("dl",{className:"training-configuration-list",children:[e.jsx(ie,{label:"Scope",value:t.skillSource==="codex"?"Codex personal":"OpenPond profile"}),e.jsx(ie,{label:"Enabled",value:t.enabled?"Yes":"No"}),e.jsx(ie,{label:"Validation",value:s}),e.jsx(ie,{label:"Source",value:t.path??"Not available"}),e.jsx(ie,{label:"Source hash",value:t.skillSourceHash??a?.sourceHash??"Not available"}),e.jsx(ie,{label:"Characters",value:String(t.skillCharCount??a?.charCount??"Not available")}),t.skillSource==="codex"?e.jsx(ie,{label:"Packaged resources",value:String(o.length)}):null]}),o.length?e.jsxs("div",{className:"labs-source-evals",children:[e.jsx("strong",{children:"Packaged resources"}),e.jsx("ul",{children:o.map(i=>e.jsx("li",{children:e.jsx("code",{children:i})},i))})]}):null,l.length?e.jsx("ul",{className:"labs-validation-list",children:l.map(i=>e.jsx("li",{children:i},i))}):null]})}return t.kind==="extension"?e.jsx(be,{title:"Extension",children:e.jsx("div",{className:"training-run-placeholder",children:"Runtime bindings arrive with the Extension phase."})}):t.kind==="model"?e.jsx(be,{title:"Model",children:e.jsxs("dl",{className:"training-configuration-list",children:[e.jsx(ie,{label:"Stable Model ID",value:t.id}),e.jsx(ie,{label:"Taskset",value:t.tasksetId??"Select one in Build"}),e.jsx(ie,{label:"Training runs",value:String(t.trainingRunCount)}),e.jsx(ie,{label:"Status",value:t.status})]})}):null}function Ts({runs:t,selectedRun:n,onSelectedRunIdChange:a}){return e.jsx(be,{title:"Activity",children:t.length?e.jsx("div",{className:"training-table-wrap",children:e.jsxs("table",{className:"training-data-table labs-activity-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Run"}),e.jsx("th",{children:"Operation"}),e.jsx("th",{children:"State"}),e.jsx("th",{children:"Revision"}),e.jsx("th",{children:"Updated"})]})}),e.jsx("tbody",{children:t.map(s=>e.jsxs("tr",{className:s.id===n?.id?"selected":void 0,onClick:()=>a(s.id),children:[e.jsx("td",{children:ht(s.id)}),e.jsx("td",{children:s.operation}),e.jsx("td",{children:e.jsx(re,{label:s.state.replaceAll("_"," "),value:s.state})}),e.jsx("td",{children:s.revision}),e.jsx("td",{children:$e(s.updatedAt)})]},s.id))})]})}):e.jsx("div",{className:"training-run-placeholder",children:"No Create/Improve activity yet."})})}function _s({profileEvals:t,run:n,workproduct:a}){const s=n?.evaluationReceipts??[],l=[...new Set([...n?.context.evalRefs??[],...s.flatMap(r=>r.evalRefs)])],o=a.kind==="agent"?t.filter(r=>r.agentId===null||r.agentId===a.id):[],i=a.kind==="agent";return!s.length&&!o.length&&!l.length?e.jsx("div",{className:"training-run-placeholder",children:"No Eval receipts yet."}):e.jsxs("div",{className:"labs-eval-summary",children:[o.length?e.jsxs("div",{className:"labs-source-evals",children:[e.jsx("strong",{children:"Available Evals"}),e.jsx("ul",{children:o.map(r=>e.jsxs("li",{children:[e.jsx("span",{children:r.name}),i?null:e.jsx("code",{children:r.path})]},r.id))})]}):null,l.length?e.jsxs("div",{className:"labs-source-evals",children:[e.jsx("strong",{children:i?"Included in this update":"Used for this change"}),e.jsx("ul",{children:i?e.jsx("li",{children:e.jsxs("span",{children:[l.length," Eval set",l.length===1?"":"s"]})}):l.map(r=>e.jsx("li",{children:e.jsx("code",{children:r})},r))})]}):null,s.length?e.jsxs("div",{className:"labs-eval-receipts",children:[e.jsx("strong",{children:i?"Check results":"Eval receipts"}),e.jsx("div",{className:"training-table-wrap",children:e.jsxs("table",{className:"training-data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[i?null:e.jsx("th",{children:"Receipt"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Evals"}),e.jsx("th",{children:"Summary"})]})}),e.jsx("tbody",{children:s.map(r=>e.jsxs("tr",{children:[i?null:e.jsx("td",{children:ht(r.id)}),e.jsx("td",{children:e.jsx(re,{label:r.status})}),e.jsx("td",{children:r.evalRefs.length}),e.jsx("td",{children:i?$s(r):r.summary??"No summary"})]},r.id))})]})})]}):null]})}function $s(t){return t.summaryCounts?`${t.summaryCounts.passed} of ${t.summaryCounts.total} Evals passed.`:t.status==="passed"?"Agent behavior Evals passed.":t.status==="failed"?"One or more Agent behavior Evals failed.":"Agent behavior Evals are still running."}function Ps({runs:t,selectedRun:n,taskset:a,training:s,trainingState:l,onToast:o}){const i=(a?l?.models.filter(d=>d.tasksetId===a.id)??[]:[]).sort((d,j)=>j.importedAt.localeCompare(d.importedAt)),r=new Map(l?.jobs.map(d=>[d.id,d])??[]),u=new Map(l?.plans.map(d=>[d.id,d])??[]),h=new Map(l?.artifacts.map(d=>[d.id,d])??[]);return e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"labs-detail-copy labs-version-storage-copy",children:"OpenPond automatically saves provider weights in app-managed local storage. Download LoRA creates a portable copy for moving or sharing the adapter."}),e.jsxs("dl",{className:"labs-inline-facts",children:[e.jsx(ke,{label:"Create/Improve runs",value:String(t.length)}),e.jsx(ke,{label:"Candidates",value:String(n?.candidates.length??0)}),e.jsx(ke,{label:"Profile commit",value:n?.localProfileCommit??"Not released"}),e.jsx(ke,{label:"Model artifacts",value:String(i.length)})]}),i.length?e.jsx("div",{className:"training-table-wrap",children:e.jsxs("table",{className:"training-data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Version"}),e.jsx("th",{children:"Method"}),e.jsx("th",{children:"Storage"}),e.jsx("th",{children:"Frozen Eval"}),e.jsx("th",{children:"Imported"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Download"})})]})}),e.jsx("tbody",{children:i.map((d,j)=>{const b=r.get(d.jobId),g=b?u.get(b.planId):null,C=h.get(d.artifactId)??null,k=C?Es(C.path):null;return e.jsxs("tr",{children:[e.jsxs("td",{className:"labs-version-name",children:[e.jsx("strong",{children:j===0?"Latest":`Prior ${j}`}),e.jsx("small",{children:ht(d.id)})]}),e.jsx("td",{children:Oe(g?.recipe.method)}),e.jsxs("td",{className:"labs-version-storage",children:[e.jsx("strong",{children:k?"Saved locally":"Unavailable"}),k?e.jsx("code",{title:C?.path,children:k}):null]}),e.jsx("td",{children:d.promotable?"Passed":d.frozenEvaluationArtifactId?"Failed":"Not run"}),e.jsx("td",{children:$e(d.importedAt)}),e.jsx("td",{children:e.jsxs("button",{className:"training-button secondary",type:"button",onClick:()=>{s.actions.downloadModelPackage(d.id)},children:[e.jsx(ot,{size:14}),"Download LoRA"]})})]},d.id)})})]})}):e.jsx("div",{className:"training-run-placeholder",children:"Model versions appear after the first adapter is imported."}),i[0]?e.jsxs("div",{className:"labs-version-promotion",children:[e.jsx("h3",{children:"Promotion & bindings"}),e.jsx(Is,{lineage:i[0],state:l,training:s,onToast:o})]}):null]})}function Es(t){return t.replace(/[/\\][^/\\]+$/,"").replace(/^\/home\/[^/]+/,"~")}function ke({label:t,value:n}){return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsx("dd",{children:n})]})}function ie({label:t,value:n}){return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsx("dd",{children:n})]})}function ht(t){return t.replace(/^(create_improve|training_job|agent_candidate|model_candidate)_/,"").slice(0,14)}function Hn(t){return t&&`${t[0].toUpperCase()}${t.slice(1).replaceAll("_"," ")}`}function Ls(t,n,a,s=!1){return t==="changes"?n?["Changes",a?`Change ${a.slice(0,8)}`:`Change ${ht(n)}`]:["Changes"]:[Hn(t)]}function Ds(t,n,a){const s=a.git?.changedPaths??[],l=s[0]??null,o=t.path?.trim().replace(/^\.\/+|\/+$/g,"")??"";if(!o)return{fileRootPath:null,initialPath:l};const i=o.split("/").filter(Boolean);i.at(-1)?.includes(".")&&i.pop();const r=i.join("/");if(!r)return{fileRootPath:null,initialPath:l};const u=r.startsWith("profiles/")?r:`profiles/${n?.activeProfile??"default"}/${r}`,h=s.find(d=>d===u||d.startsWith(`${u}/`))??null;return h?{fileRootPath:u,initialPath:h}:{fileRootPath:null,initialPath:l}}function Os(t){return t?t.state==="planning"?"Planning update":t.state==="awaiting_questions"?"Waiting for input":t.state==="awaiting_plan_approval"?"Plan ready":t.state==="applying_source"?"Saving Agent":t.state==="running_checks"||t.state==="evaluating"?"Running Evals":t.state==="awaiting_promotion"?"Update ready to apply":t.state==="opening_pull_request"||t.state==="pull_request_open"?"Update review open":t.state==="reconciling_release"?"Applying update":t.state==="released"?"Update applied":t.state==="rejected"?"Current version kept":t.state==="ready"||t.state==="ready_local"?"Agent ready":t.state==="published_hosted"?"Agent published":t.state==="paused"?"Update paused":t.state==="cancelled"?"Update cancelled":t.state==="blocked"?"Update blocked":t.state==="failed"?"Update failed":`Change ${t.state.replaceAll("_"," ")}`:"No change status"}const Bs=c.lazy(()=>ma(()=>import("./LabModelVersionDetailPage-Bhfa7T00.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]),import.meta.url).then(t=>({default:t.LabModelVersionDetailPage})));function Us({workproduct:t,runs:n,profile:a,training:s,connection:l,onOpenConversation:o,onClose:i,onLocationChange:r,onRenameAgent:u,onStartAgentChange:h,onOpenDataset:d,onToast:j,onAnswerQuestion:b,candidateReview:g,onApprove:C,onCancel:k,onChatWithModel:f,onApplyCandidate:S,onCandidateReviewChange:y,onOpenCandidateFiles:w,onOpenPullRequest:R,onPause:p,onReconcilePullRequest:_,onRejectCandidate:x,onResume:m,onRevise:T,renderModelRunEditor:V,benchmarkDefaultModel:E,benchmarkProviderSettings:$,initialBenchmarkModel:Z=null,initialBenchmarkOpen:K=!1,onInitialBenchmarkOpenConsumed:ee}){const M=c.useMemo(()=>Ga(t,n),[n,t]),[H,B]=c.useState(M[0]?.id??""),[G,de]=c.useState(null),[F,ne]=c.useState("overview"),[J,ae]=c.useState(null),[X,N]=c.useState("run"),q=c.useRef("runs"),[D,te]=c.useState(null),[Q,le]=c.useState(null),[Ae,fe]=c.useState(K);c.useEffect(()=>{K&&(fe(!0),ee?.())},[K,ee]);const ue=M.find(A=>A.id===H)??M[0]??null,I=G?M.find(A=>A.id===G)??null:null,L=I?Ms(I):null,he=Ka(t.kind),oe=t.kind==="model"&&!!(t.ownerProfileId&&t.ownerProfileId!==a?.activeProfile),me=c.useMemo(()=>t.kind==="model"?Qe(t,n,s.payload):[],[n,s.payload,t]),v=c.useMemo(()=>t.kind==="model"?We(t,n,s.payload):[],[n,s.payload,t]),O=c.useMemo(()=>t.kind==="model"?ct(t,s.payload):[],[s.payload,t]),W=D?.startsWith("job:")?v.find(A=>A.id===D.slice(4))??null:null,pe=D?.startsWith("model-run:")?O.find(A=>A.id===D.slice(10))??null:W?.metadata.modelRunId?O.find(A=>A.id===W.metadata.modelRunId)??null:null,se=(D?.startsWith("version:")?me.find(A=>A.lineage.id===D.slice(8))??null:null)??(W?me.find(A=>A.job?.id===W.id)??null:null)??(pe?.adapterArtifactLineageId?me.find(A=>A.lineage.id===pe.adapterArtifactLineageId)??null:null),ve=c.useMemo(()=>Ht(v,me,O),[v,O,me]),we=ve.findIndex(A=>A.key===D||W!==null&&A.job?.id===W.id||pe!==null&&A.lifecycleRun?.id===pe.id),Pe=we<0?null:ve.length-we,Te=L?.git?.headCommit??null,Xe=c.useMemo(()=>t.kind==="model"?J?[{label:"Runs",onSelect:()=>U("runs")},{label:J==="new"?"New run":"Resume draft"},...X==="dataset"?[{label:"New Taskset"}]:[]]:D?[{label:D.startsWith("version:")?"Versions":"Runs",onSelect:()=>{te(null)}},{label:D.startsWith("version:")&&se?`Version ${se.number}`:Pe?`Run ${Pe}`:D.startsWith("version:")?"Version details":"Run details"}]:[]:Ls(F==="runs"?"overview":F,G,Te,t.kind==="agent").map(A=>({label:A})),[F,X,J,Te,G,D,Pe,se,t.kind]),Ue=t.tasksetId?[...s.payload?.tasksets??[],...s.payload?.modelTasksets??[]].find(A=>A.id===t.tasksetId)??null:null,mt=t.kind==="agent"?a?.agents.some(A=>A.id===t.id)??!1:!1,Ee=Cs({workproduct:t,runs:M,taskset:Ue,training:s.payload}),Ne=t.kind==="model"?me.find(A=>A.current)??null:null,Ye=t.kind==="model"?Ne?{label:"Hosted",value:"ready"}:{label:"Not hosted",value:"not_run"}:{label:Ee.statusLabel,value:Ee.statusValue},Fe=Ee.runId??M[0]?.id??"",Ze=M.some(A=>A.id===H),Ce=G?M.some(A=>A.id===G):!0,ze=[["overview","Overview"],["changes","Changes"],["evals","Evals"],["versions","Versions"],["configuration","Configuration"]];c.useEffect(()=>{y(null),B(Fe),de(null),te(null),ne("overview"),ae(null),N("run")},[t.key]),c.useEffect(()=>{H&&Ze||B(Fe)},[Fe,Ze,H]),c.useEffect(()=>{Ce||de(null)},[Ce]),c.useEffect(()=>{if(F==="changes"&&I&&L){const A=Ds(t,a,L);y({run:I,candidate:L,fileRootPath:A.fileRootPath,initialPath:A.initialPath});return}y(null)},[F,y,a,L,I,t]),c.useEffect(()=>{r({kind:t.kind,kindLabel:he,kindOnSelect:t.kind==="model"?()=>{if(J){U("collection");return}i()}:void 0,workproductLabel:t.name,workproductOnSelect:t.kind==="model"?()=>{if(J){U("overview");return}ae(null),te(null),ne("overview")}:void 0,segments:Xe})},[he,Xe,i,r,t.kind,t.name]),c.useEffect(()=>()=>y(null),[y]);function Ve(A){if(oe)return;const ge=me.find(Re=>Re.lineage.id===A);ge?.taskset&&f(Ft({modelId:A,taskset:ge.taskset}))}function U(A){q.current=A,document.getElementById("model-run-editor-cancel")?.click()}return t.kind==="model"&&J?V({initialTasksetId:Ue?.id??null,draftId:J==="new"?null:J,modelId:t.id,modelName:t.name,onCancel:()=>{const A=q.current;if(ae(null),N("run"),A==="collection"){i();return}ne(A)},onFinished:async()=>{ae(null),N("run"),ne("runs")},onSectionChange:N}):e.jsxs("div",{className:"training-model-detail labs-workproduct-detail",children:[e.jsxs("header",{className:"training-model-detail-header labs-workproduct-detail-header",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"labs-workproduct-name-row",children:[e.jsx("h1",{children:t.name}),e.jsx($t,{label:Ye.label,value:Ye.value})]}),t.description&&t.description!=="No description"?e.jsx("p",{className:"labs-workproduct-description",children:t.description}):null]}),t.kind==="model"?e.jsxs("div",{className:"labs-workproduct-header-actions",children:[se?.taskset?e.jsxs("button",{className:"training-button secondary",disabled:oe||!je(se.lineage),title:je(se.lineage)?"Chat with this Version":"Chat is unavailable because this Version did not pass evaluation.",type:"button",onClick:()=>Ve(se.lineage.id),children:[e.jsx(wn,{size:14}),"Chat"]}):null,se?e.jsxs("button",{className:"training-button secondary",type:"button",onClick:()=>{s.actions.downloadModelPackage(se.lineage.id)},children:[e.jsx(ot,{size:14}),"Download LoRA"]}):null,pe?.receipt?e.jsxs("button",{className:"training-button secondary",type:"button",onClick:()=>Ss(`${pe.id}-receipt.json`,pe.receipt),children:[e.jsx(ot,{size:14}),"Download receipt"]}):null,e.jsx("button",{className:"training-button secondary",type:"button",onClick:()=>fe(!0),children:"Benchmark"}),oe?null:e.jsx("button",{className:"training-button",type:"button",onClick:()=>ae("new"),children:"New run"})]}):t.kind==="agent"?e.jsxs("div",{className:"labs-workproduct-header-actions",children:[e.jsx("button",{className:"training-button",type:"button",onClick:()=>h(t.id),children:"Improve agent"}),mt?e.jsxs("button",{className:"training-button secondary labs-compact-button",type:"button",onClick:u,children:[e.jsx(ha,{size:14}),e.jsx("span",{children:"Rename"})]}):null]}):null]}),t.kind==="model"||D?null:e.jsx("div",{className:"training-detail-tabs",role:"tablist","aria-label":"Workproduct detail",children:ze.map(([A,ge])=>e.jsxs("button",{className:F===A?"active":void 0,"aria-selected":F===A,role:"tab",type:"button",onClick:()=>{ne(A),A==="changes"&&de(null)},children:[ge,A==="changes"?e.jsx($t,{decorative:!0,label:Os(M[0]??null),size:"small",tone:As(M[0]??null)}):null]},A))}),e.jsx("div",{className:"training-detail-sections",children:t.kind==="model"&&D?e.jsx(c.Suspense,{fallback:e.jsx("div",{className:"training-run-placeholder",children:"Loading run details…"}),children:e.jsx(Bs,{connection:l,runs:n,selectedEntryKey:D,training:s,workproduct:t,onOpenDataset:d,onOpenConversation:o})}):t.kind==="model"?e.jsxs(e.Fragment,{children:[e.jsx(gs,{runs:n,training:s,workproduct:t,readOnly:oe,onOpenDataset:d,onOpenEntry:te,onResumeDraft:ae}),e.jsx(fs,{runs:n,training:s,workproduct:t,readOnly:oe,onOpenDataset:d,onOpenEntry:te,onToast:j})]}):F==="overview"?e.jsxs(be,{title:"Overview",children:[e.jsxs("dl",{className:"labs-inline-facts",children:[e.jsx(ke,{label:"Type",value:Hn(t.kind)}),e.jsx(ke,{label:"Status",value:Ee.statusLabel}),t.kind==="agent"?e.jsx(ke,{label:"Profile",value:"Saved in your Profile"}):e.jsxs(e.Fragment,{children:[e.jsx(ke,{label:"ID",value:t.id}),e.jsx(ke,{label:"Path",value:t.path??"Managed artifact"})]})]}),e.jsx("p",{className:"labs-detail-copy",children:t.description})]}):F==="changes"&&!I?e.jsx("div",{className:"labs-change-index",children:e.jsx(as,{runs:M,onReview:A=>{B(A.id),de(A.id)}})}):F==="changes"&&I&&L?e.jsx(es,{candidate:L,diff:g.diff,error:g.error,run:I,onApplyCandidate:(A,ge)=>S({run:A},ge),onOpenFiles:w,onRejectCandidate:(A,ge)=>x({run:A},ge)}):F==="changes"&&I?e.jsxs("div",{className:"labs-change-run-detail",children:[e.jsxs("article",{className:"labs-change-card",children:[e.jsxs("header",{className:"labs-change-card-header",children:[e.jsx("span",{className:"labs-change-timeline-label",children:"Request"}),e.jsx(re,{label:I.state.replaceAll("_"," "),value:I.state})]}),e.jsx("div",{className:"labs-change-card-body",children:e.jsx("h3",{children:I.objective})})]}),e.jsx(ks,{run:I,onAnswerQuestion:b,onApplyCandidate:S,onApprove:C,onCancel:k,onOpenConversation:o,onOpenPullRequest:R,onPause:p,onReconcilePullRequest:_,onRejectCandidate:x,onResume:m,onRetry:()=>h(t.id,I.objective),onRevise:T})]}):F==="evals"?e.jsx(be,{title:"Evals",actions:t.kind==="agent"?e.jsx(Za,{agentId:t.id,evals:a?.evals??[],onCreate:()=>h(t.id,`Create an Eval for ${t.name}. Describe the behavior this Eval should specify: `),onAttach:A=>h(t.id,`--eval ${JSON.stringify(A)} Improve ${t.name} using this existing Eval: `)}):null,children:e.jsx(_s,{profileEvals:a?.evals??[],run:ue,workproduct:t})}):F==="versions"?e.jsxs(e.Fragment,{children:[e.jsx(be,{title:"Versions",children:e.jsx(Ps,{runs:M,selectedRun:ue,taskset:Ue,training:s,trainingState:s.payload,onToast:j})}),e.jsx(Ts,{runs:M,selectedRun:ue,onSelectedRunIdChange:B})]}):e.jsxs(e.Fragment,{children:[e.jsx(be,{title:"Connections",children:e.jsxs("dl",{className:"training-configuration-list",children:[e.jsx(ie,{label:"Profile",value:a?.activeProfile??"default"}),e.jsx(ie,{label:"Conversation",value:ue?.scope.conversationId??"Not linked"}),e.jsx(ie,{label:"Project",value:ue?.scope.projectId??"Not linked"}),e.jsx(ie,{label:"Source authority",value:ue?.adapter.sourceAuthority??"Profile"})]})}),e.jsx(ws,{workproduct:t,profile:a})]})}),t.kind==="model"&&Ae?e.jsx(ds,{workproduct:t,training:s,readOnly:!1,defaultModel:E,initialModel:Z,providerSettings:$,onClose:()=>fe(!1),onOpenEntry:A=>{fe(!1),te(A)},onToast:j}):null,Q?(()=>{const A=me.find(ge=>ge.lineage.id===Q);return A?.taskset?e.jsx(Dn,{lineage:A.lineage,taskset:A.taskset,training:s,onChat:f,onClose:()=>le(null)}):null})():null]})}function Fs({activeTab:t,children:n,showHeader:a=!0,onCreateDataset:s,onCreateModel:l}){return e.jsxs("section",{className:"labs-route","aria-label":"Models",children:[a?e.jsx("header",{className:"labs-header",children:e.jsx("div",{className:"labs-header-actions",children:t==="models"?e.jsx("button",{className:"labs-create-button",type:"button",onClick:l,children:e.jsx("span",{children:"New model"})}):t==="tasksets"?e.jsx("button",{className:"labs-create-button",type:"button",onClick:s,children:e.jsx("span",{children:"New Taskset"})}):null})}):null,e.jsx("div",{className:"labs-panel",children:n})]})}function zs({taskset:t,busyAction:n,onPreview:a,onApprove:s,onToast:l}){const[o,i]=c.useState(null),[r,u]=c.useState(!1),h=qs(t),d=t.learningSignals.demonstrations.filter(k=>k.approved&&k.metadata.exampleOrigin==="expert_authored").length,j=n==="preview-expert-bootstrap",b=n==="approve-expert-bootstrap";async function g(){u(!0);const k=await a();if(k){i(k);return}u(!1),l("Couldn’t load the expert trajectories.","error")}async function C(){if(!o)return;const k=await s(o.previewHash);if(!k){l("The expert trajectories were not approved.","error");return}u(!1),l(`${k.approval.trajectoryCount} expert trajectories approved by ${k.approval.approvedBy}.`,"success")}return e.jsxs(e.Fragment,{children:[e.jsx(be,{title:"SFT bootstrap data",actions:e.jsx("button",{className:"training-button secondary",disabled:j||b,type:"button",onClick:()=>{g()},children:h?"Review trajectories":j?"Loading…":"Review expert trajectories"}),children:e.jsxs("div",{className:"labs-expert-bootstrap-summary",children:[e.jsxs("div",{children:[e.jsx(re,{label:h?"Approved":"Review required",value:h?"ready":"needs_review"}),e.jsx("p",{children:h?`${d} deterministic train-split trajectories are approved for the optional SFT bootstrap.`:"Five deterministic train-split trajectories are available. Failed model outputs remain excluded."})]}),h?e.jsxs("dl",{className:"labs-inline-facts",children:[e.jsx(Ge,{label:"Approved by",value:h.approvedBy}),e.jsx(Ge,{label:"Taskset revision",value:String(t.revision)})]}):null]})}),r?e.jsx(Vs,{approving:b,loading:j,preview:o,onApprove:()=>{C()},onClose:()=>{b||u(!1)}}):null]})}function Vs({preview:t,loading:n,approving:a,onApprove:s,onClose:l}){return e.jsxs(_e,{ariaLabel:"Review expert trajectories",className:"training-dialog labs-expert-bootstrap-dialog",dismissDisabled:a,onClose:l,children:[e.jsxs("div",{className:"training-dialog-header",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Review expert trajectories"}),e.jsx("p",{children:"These examples were executed in the deterministic synthetic environment and passed the exact verifier. Approval is bound to the signed-in OpenPond account."})]}),e.jsx("button",{"aria-label":"Close",disabled:a,type:"button",onClick:l,children:"×"})]}),e.jsx("div",{className:"training-dialog-scroll-body labs-expert-trajectory-list",children:n||!t?e.jsx("div",{className:"training-run-placeholder",children:"Generating and verifying the review set…"}):e.jsxs(e.Fragment,{children:[e.jsxs("dl",{className:"labs-inline-facts labs-expert-preview-facts",children:[e.jsx(Ge,{label:"Taskset revision",value:String(t.tasksetRevision)}),e.jsx(Ge,{label:"Trajectories",value:String(t.tasks.length)}),e.jsx(Ge,{label:"Review state",value:t.status==="approved"?"Approved":"Pending"})]}),t.tasks.map(o=>e.jsxs("details",{className:"labs-expert-trajectory",children:[e.jsxs("summary",{children:[e.jsxs("span",{children:[e.jsx("strong",{children:Hs(o.family)}),e.jsxs("small",{children:[o.toolCallCount," tool calls · exact reward ",o.reward.toFixed(3)]})]}),e.jsx("span",{"aria-hidden":"true",children:"›"})]}),e.jsxs("div",{className:"labs-expert-trajectory-body",children:[e.jsxs("section",{children:[e.jsx("h3",{children:"Prompt"}),e.jsx("p",{children:o.prompt})]}),e.jsxs("section",{children:[e.jsx("h3",{children:"Tool sequence"}),e.jsx("div",{className:"training-pills",children:o.toolNames.map((i,r)=>e.jsx("span",{children:i},`${o.trajectoryId}-${i}-${r}`))})]}),e.jsxs("section",{children:[e.jsx("h3",{children:"Verified answer"}),e.jsx("pre",{children:o.finalAnswer})]}),e.jsxs("details",{className:"labs-expert-messages",children:[e.jsxs("summary",{children:["View ",o.messageCount," training messages"]}),e.jsx("pre",{children:JSON.stringify(o.messages,null,2)})]})]})]},o.trajectoryId))]})}),e.jsxs("div",{className:"training-dialog-actions",children:[e.jsx("span",{className:"labs-expert-approval-note",children:"Train split only · failed policy outputs excluded"}),e.jsx("button",{className:"training-button secondary",disabled:a,type:"button",onClick:l,children:"Close"}),t?.status!=="approved"?e.jsx("button",{className:"training-button",disabled:!t||n||a,type:"button",onClick:s,children:a?"Approving…":`Approve ${t?.tasks.length??0} trajectories`}):null]})]})}function qs(t){const n=bn(t.metadata.expertBootstrap),a=bn(n.approval);return a.status!=="approved"||typeof a.approvedBy!="string"||typeof a.approvedAt!="string"||typeof a.previewHash!="string"||typeof a.trajectoryCount!="number"?null:a}function Ge({label:t,value:n}){return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsx("dd",{children:n})]})}function Hs(t){return t.split("_").map(n=>`${n.slice(0,1).toUpperCase()}${n.slice(1)}`).join(" ")}function bn(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}const Ks=[{id:"train",label:"Training"},{id:"validation",label:"Validation"},{id:"frozen_eval",label:"Frozen Eval"}],Le=10;function Gs({artifact:t,defaultModel:n,tab:a="overview",taskset:s,onOpenFiles:l,onToast:o,training:i}){const r=c.useMemo(()=>t?new Map(Object.entries(t.splitCounts)):si(s.tasks.map(N=>N.split)),[t,s.tasks]),u=r.get("train")?"train":r.get("validation")?"validation":r.get("frozen_eval")?"frozen_eval":s.tasks[0]?.split??"train",[h,d]=c.useState(u==="test"?"frozen_eval":u),[j,b]=c.useState(1),[g,C]=c.useState([]),[k,f]=c.useState(null),[S,y]=c.useState([]),[w,R]=c.useState(null),[p,_]=c.useState(!1),[x,m]=c.useState(null),[T,V]=c.useState(null),E=c.useMemo(()=>new Map(s.sourceRefs.map(N=>[N.id,N])),[s.sourceRefs]);c.useEffect(()=>{if(a!=="cases"||!t)return;let N=!1;return _(!0),m(null),i.actions.datasetRows(s.id,{split:h,cursor:k,limit:Le}).then(q=>{N||!q||(C(q.rows.map(D=>pa.parse(D))),R(q.nextCursor))}).catch(q=>{N||(C([]),R(null),m(q instanceof Error?q.message:String(q)))}).finally(()=>{N||_(!1)}),()=>{N=!0}},[t,k,h,a,s.id,i.actions]);const $=t?g:s.tasks.filter(N=>N.split===h),Z=Math.max(1,Math.ceil($.length/Le)),K=t?$:$.slice((j-1)*Le,j*Le),ee=t?S.length*Le:(j-1)*Le,M=s.sourceRefs.filter(Kt).length,H=s.sourceRefs.filter(N=>Vt(N)&&N.turnIds.length>0).length,B=s.sourceRefs.filter(N=>N.metadata.containsCustomerData===!0).length,G=s.learningSignals.demonstrations.filter(N=>N.approved).length,de=s.learningSignals.preferences.filter(N=>N.approved).length,F=s.learningSignals.rewards.filter(N=>N.approved).length,ne=s.learningSignals.labels.filter(N=>N.approved&&N.labelKind==="rubric").length,J=s.graders.some(N=>N.kind==="model_judge"),ae=s.environment.kind==="work"?s.tasks.find(N=>N.split!=="frozen_eval")??null:null;async function X(N,q){if(V(null),!await q()){V(`${N} did not complete. Check the latest error and try again.`);return}V(`${N} started or completed successfully.`),o(`${N} started or completed successfully.`,"success")}return a==="overview"?e.jsxs(be,{title:"Taskset",children:[e.jsx("p",{className:"labs-detail-copy labs-dataset-summary",children:Ws({syntheticSources:M,chatSources:H,customerSources:B,sourceCount:s.sourceRefs.length})}),e.jsxs("dl",{className:"labs-inline-facts",children:[e.jsx(ce,{label:"Training",value:String(r.get("train")??0)}),e.jsx(ce,{label:"Validation",value:String(r.get("validation")??0)}),e.jsx(ce,{label:"Frozen Eval",value:String(r.get("frozen_eval")??0)}),e.jsx(ce,{label:"Demonstrations",value:String(G)}),e.jsx(ce,{label:"Preference pairs",value:String(de)}),e.jsx(ce,{label:"Reward specs",value:String(F)}),e.jsx(ce,{label:"Rubrics",value:String(ne)})]}),s.purpose==="benchmark"&&s.benchmark?e.jsxs("div",{className:"labs-dataset-method-readiness",children:[e.jsx("strong",{children:"Benchmark protocol"}),e.jsxs("div",{className:"training-pills",children:[e.jsx("span",{children:xe(s.benchmark.primaryMetric.replaceAll("_"," "))}),e.jsx("span",{children:xe(s.benchmark.qualityGate.replaceAll("_"," "))}),e.jsx("span",{children:"Immutable release"})]}),e.jsxs("p",{className:"labs-detail-copy",children:["Adapt on ",xe(s.benchmark.adaptationSplit)," cases and compare paired ",xe(s.benchmark.evaluationSplit.replaceAll("_"," "))," runs."]})]}):e.jsxs("div",{className:"labs-dataset-method-readiness",children:[e.jsx("strong",{children:"Training compatibility"}),e.jsx("div",{className:"training-pills",children:s.readiness?.methodReadiness.length?s.readiness.methodReadiness.map(N=>e.jsxs("span",{title:N.reasons.join(" "),children:[N.method.toUpperCase()," · ",xe(N.status)]},N.method)):s.capabilities.compatibleMethods.filter(N=>!["none","retrieval"].includes(N)).map(N=>e.jsx("span",{children:N.toUpperCase()},N))}),s.readiness?.methodReadiness.some(N=>N.reasons.length)?e.jsx("ul",{children:s.readiness.methodReadiness.flatMap(N=>N.reasons.map(q=>e.jsxs("li",{children:[e.jsxs("strong",{children:[N.method.toUpperCase(),":"]})," ",q]},`${N.method}:${q}`)))}):null]}),e.jsxs("details",{className:"labs-dataset-advanced-details",children:[e.jsx("summary",{children:"Technical details"}),e.jsxs("dl",{className:"training-configuration-list",children:[e.jsx(ce,{label:"Taskset ID",value:s.id}),e.jsx(ce,{label:"Revision",value:String(s.revision)}),e.jsx(ce,{label:"Format",value:t?.format.toUpperCase()??"Inline Taskset"}),e.jsx(ce,{label:"Rows",value:String(t?.rowCount??s.tasks.length)}),e.jsx(ce,{label:"Storage",value:t?ii(t.sizeBytes):"Managed inline"}),e.jsx(ce,{label:"Availability",value:t?.available===!1?t.unavailableReason??"Unavailable":"Available"}),e.jsx(ce,{label:"Content hash",value:t?.contentHash??s.contentHash})]}),e.jsx("button",{className:"training-button secondary",type:"button",onClick:l,children:"Open files"})]})]}):a==="scoring"?e.jsxs(e.Fragment,{children:[s.purpose==="benchmark"?e.jsx(be,{title:"Benchmark runs",children:e.jsxs("p",{className:"labs-detail-copy",children:["Harness Refiner runs start from a Model so the selected Model, effort, full protocol, result charts, and Git-backed receipt stay together in one evaluation run. Open a Model and choose",e.jsx("strong",{children:" Run Refiner Benchmark"}),"."]})}):null,e.jsxs(be,{title:"Taskset checks",children:[e.jsx("p",{className:"labs-detail-copy",children:"Audit the reward and graders before creating a Model run."}),e.jsxs("div",{className:"labs-dataset-detail-actions",children:[ae?e.jsx("button",{className:"training-button secondary",disabled:i.busyAction!==null,type:"button",onClick:()=>{X("Work attempt",()=>i.actions.executeTasksetAttempt(s.id,ae.id,n))},children:"Run Work attempt"}):null,e.jsx("button",{className:"training-button secondary",disabled:i.busyAction!==null,type:"button",onClick:()=>{X("Grader audit",()=>i.actions.auditGraders(s.id))},children:"Audit graders"}),J?e.jsx("button",{className:"training-button secondary",disabled:i.busyAction!==null,type:"button",onClick:()=>{X("Judge calibration",()=>i.actions.calibrateJudges(s.id))},children:"Calibrate judges"}):null,e.jsx("button",{className:"training-button secondary",disabled:i.busyAction!==null,type:"button",onClick:()=>{X("Readiness check",()=>i.actions.readiness(s.id))},children:"Refresh readiness"})]}),T?e.jsx("p",{className:"labs-detail-copy",role:"status",children:T}):null,s.readiness?.blockers.length?e.jsxs("div",{className:"training-banner warning",children:[e.jsx("strong",{children:"Readiness blockers"}),e.jsx("ul",{children:s.readiness.blockers.map(N=>e.jsx("li",{children:N.message},`${N.code}:${N.path??""}`))})]}):null]}),e.jsx(be,{title:"Graders",children:e.jsx("div",{className:"labs-dataset-grader-list",children:s.graders.map(N=>e.jsxs("div",{children:[e.jsx("strong",{children:N.label}),e.jsx("small",{children:xe(N.kind)})]},N.id))})})]}):e.jsxs(be,{title:"Cases",children:[e.jsx("div",{className:"labs-method-tabs labs-dataset-tabs",role:"tablist","aria-label":"Taskset splits",children:Ks.map(N=>e.jsxs("button",{"aria-selected":h===N.id,className:h===N.id?"active":"",role:"tab",type:"button",onClick:()=>{d(N.id),b(1),f(null),y([])},children:[N.label,e.jsx("span",{children:r.get(N.id)??0})]},N.id))}),e.jsxs("div",{className:"labs-dataset-examples",children:[K.map((N,q)=>e.jsx(Js,{index:ee+q,source:N.sourceRefs.map(D=>E.get(D)).find(Boolean)??null,task:N},N.id)),t?e.jsxs("nav",{className:"labs-pagination","aria-label":"Task data pages",children:[e.jsx("button",{type:"button",disabled:!S.length||p,onClick:()=>{const N=S.at(-1)??null;y(q=>q.slice(0,-1)),f(N||null)},children:"Previous"}),e.jsx("span",{children:p?"Loading…":`Page ${S.length+1} · ${g.length.toLocaleString()} rows`}),e.jsx("button",{type:"button",disabled:!w||p,onClick:()=>{y(N=>[...N,k??""]),f(w)},children:"Next"})]}):Z>1?e.jsxs("nav",{className:"labs-pagination","aria-label":"Task data pages",children:[e.jsx("button",{type:"button",disabled:j<=1,onClick:()=>b(N=>Math.max(1,N-1)),children:"Previous"}),e.jsxs("span",{children:[j," of ",Z]}),e.jsx("button",{type:"button",disabled:j>=Z,onClick:()=>b(N=>Math.min(Z,N+1)),children:"Next"})]}):null,x?e.jsx("div",{className:"training-banner error",role:"alert",children:x}):null]})]})}function Js({index:t,source:n,task:a}){const s=Qs(a),l=Ys(a),o=Xs(a),i=n?ti(n):"Source unavailable",r=Zs(a,n),u=ei(a,n);return e.jsxs("details",{className:"labs-dataset-example",children:[e.jsxs("summary",{children:[e.jsx("span",{className:"labs-dataset-example-index",children:String(t+1).padStart(2,"0")}),e.jsxs("span",{className:"labs-dataset-example-title",children:[e.jsx("strong",{children:s}),e.jsx("small",{children:[r,u,i].filter(Boolean).join(" · ")})]}),e.jsx(re,{label:ai(a.split),value:a.split})]}),e.jsxs("div",{className:"labs-dataset-example-body",children:[e.jsxs("section",{children:[e.jsx("h3",{children:"Prompt"}),e.jsx("p",{children:s})]}),e.jsxs("section",{children:[e.jsx("h3",{children:a.split==="frozen_eval"?"Expected result":"Approved answer"}),a.split==="frozen_eval"?e.jsx("p",{children:"The answer stays held out and is only opened by the Eval runner."}):e.jsx("pre",{children:o??"No approved answer is attached."})]}),l.length?e.jsxs("section",{children:[e.jsx("h3",{children:"Tool trajectory"}),e.jsx("div",{className:"training-pills",children:l.map((h,d)=>e.jsx("span",{children:h},`${h}:${d}`))})]}):null,e.jsxs("section",{children:[e.jsx("h3",{children:"Source"}),e.jsxs("p",{children:[e.jsx("strong",{children:n?.title??"Source unavailable"})," — ",ni(n)]})]}),e.jsxs("details",{className:"labs-dataset-example-advanced",children:[e.jsx("summary",{children:"Technical details"}),e.jsxs("dl",{className:"training-configuration-list",children:[e.jsx(ce,{label:"Task",value:a.id}),e.jsx(ce,{label:"Source",value:n?.id??"Unavailable"}),e.jsx(ce,{label:"Cluster",value:a.clusterKey})]})]})]})]})}function Ws(t){if(t.sourceCount>0&&t.syntheticSources===t.sourceCount&&t.chatSources===0&&t.customerSources===0)return`This dataset contains ${t.sourceCount} generated scenarios. It uses no raw chats or customer data.`;const n=[`${t.sourceCount} source${t.sourceCount===1?"":"s"}`,`${t.chatSources} chat${t.chatSources===1?"":"s"}`,`${t.syntheticSources} generated scenario${t.syntheticSources===1?"":"s"}`];return t.customerSources===0?n.push("no sources marked as customer data"):n.push(`${t.customerSources} source${t.customerSources===1?"":"s"} marked as customer data`),`This dataset contains ${n.join(", ")}.`}function Qs(t){return typeof t.input.prompt=="string"?t.input.prompt:"Untitled dataset example"}function Xs(t){if(!t.expectedOutput)return null;if(typeof t.expectedOutput.text=="string")return t.expectedOutput.text;const n=Array.isArray(t.expectedOutput.messages)?t.expectedOutput.messages:[];for(const a of[...n].reverse())if(a&&typeof a=="object"&&"content"in a&&typeof a.content=="string")return a.content;return null}function Ys(t){if(!t.expectedOutput||!Array.isArray(t.expectedOutput.messages))return[];const n=[];for(const a of t.expectedOutput.messages){if(!a||typeof a!="object"||!("tool_calls"in a))continue;const s=Array.isArray(a.tool_calls)?a.tool_calls:[];for(const l of s){if(!l||typeof l!="object"||!("function"in l))continue;const o=l.function;o&&typeof o=="object"&&"name"in o&&typeof o.name=="string"&&n.push(o.name)}}return n}function Zs(t,n){const a=n?.metadata.crossSystemOperations;if(a&&typeof a=="object"&&"taskFamily"in a){const l=a.taskFamily;if(typeof l=="string")return xe(l)}const s=t.tags.find(l=>!["synthetic","structured-tool-trajectory"].includes(l));return s?xe(s):null}function ei(t,n){const a=n?.metadata.crossSystemOperations;if(a&&typeof a=="object"&&"worldDifficulty"in a){const s=a.worldDifficulty;if(typeof s=="string")return xe(s)}return t.clusterKey.match(/_(easy|medium|hard)$/)?.[1]??null}function Kt(t){return t.schemaVersion==="openpond.generatedDatasetSource.v1"||t.metadata.syntheticSpecification===!0}function ti(t){return Kt(t)?"Generated scenario":Vt(t)&&t.turnIds.length>0?"Chat":t.schemaVersion==="openpond.huggingFaceDatasetSource.v1"?"Hugging Face":t.schemaVersion==="openpond.uploadedFileDatasetSource.v1"?"Uploaded file":"Imported source"}function ni(t){return t?Kt(t)&&t.metadata.containsCustomerData===!1?"generated locally from a deterministic specification; no customer content is attached.":Vt(t)&&t.turnIds.length>0?`${t.turnIds.length} approved chat turn${t.turnIds.length===1?"":"s"} are attached.`:t.schemaVersion==="openpond.huggingFaceDatasetSource.v1"?`${t.repositoryId}@${t.revision.slice(0,12)} is attached.`:"an approved imported source is attached.":"The referenced source could not be loaded."}function ai(t){return t==="frozen_eval"?"Frozen Eval":xe(t)}function xe(t){return t.replaceAll("-"," ").replaceAll("_"," ").replace(/\b\w/g,n=>n.toUpperCase())}function si(t){const n=new Map;for(const a of t)n.set(a,(n.get(a)??0)+1);return n}function ii(t){return t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(1)} KB`:t<1073741824?`${(t/1048576).toFixed(1)} MB`:`${(t/1073741824).toFixed(1)} GB`}function ce({label:t,value:n}){return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsx("dd",{children:n})]})}const Lt=10,li=[{id:"overview",label:"Overview"},{id:"cases",label:"Cases"},{id:"scoring",label:"Scoring"},{id:"history",label:"History"}];function oi({state:t,runs:n,selectedId:a,onSelectedIdChange:s,defaultModel:l,onImproveInChat:o,onTrainModel:i,onOpenFiles:r,training:u,onToast:h}){const[d,j]=c.useState(""),[b,g]=c.useState(1),[C,k]=c.useState("overview"),f=t?.tasksets??[],S=[...f,...t?.modelTasksets??[]].find(m=>m.id===a)??null,y=!!(S&&S.profileId!==t?.profileId),w=S?.benchmark?.source==="builtin",R=S?.datasetArtifact?t?.datasetArtifacts.find(m=>m.tasksetId===a&&m.tasksetRevision===S.revision)??null:null,p=c.useMemo(()=>{const m=d.trim().toLowerCase();return m?f.filter(T=>[T.name,T.objective,T.id].some(V=>V.toLowerCase().includes(m))):f},[d,f]),_=p.slice((b-1)*Lt,b*Lt),x=c.useMemo(()=>{const m=new Map;if(!t)return m;const T=On({profile:null,training:t,runs:n}).filter(V=>V.kind==="model");for(const V of T)for(const E of bs(V,n,t))m.set(E.id,(m.get(E.id)??0)+1);return m},[n,t]);return c.useEffect(()=>{k("overview")},[a]),S?e.jsxs("div",{className:"labs-flat-body labs-datasets-page",children:[e.jsxs("div",{className:"labs-dataset-detail-heading",children:[e.jsx("button",{"aria-label":"Back to Tasksets",className:"labs-back-button",type:"button",onClick:()=>s(null),children:e.jsx(An,{size:15})}),e.jsxs("div",{children:[e.jsx("h1",{children:S.name}),e.jsx("p",{children:S.objective})]}),e.jsxs("div",{className:"labs-dataset-detail-actions",children:[y?e.jsx(re,{label:`Profile: ${S.profileId}`,value:"available"}):null,w?null:e.jsx("button",{className:"training-button secondary",disabled:y,title:y?"Switch to this Taskset's Profile to modify it.":"Improve this Taskset in Chat.",type:"button",onClick:()=>o(S),children:"Improve in Chat"}),S.purpose==="benchmark"?e.jsx("button",{className:"training-button",disabled:y,type:"button",onClick:()=>k("scoring"),children:"Run Benchmark"}):e.jsx("button",{className:"training-button",disabled:y||!S.readiness?.ready,title:y?"Switch to this Taskset's Profile before launching a Model run.":S.readiness?.ready?"Create a Model run from this ready Taskset.":S.readiness?.blockers[0]?.message??"Run Taskset checks before training.",type:"button",onClick:()=>i(S.id),children:"Train Model"}),e.jsx(re,{label:di(S),value:S.status})]})]}),e.jsx("div",{className:"training-detail-tabs",role:"tablist","aria-label":"Taskset detail",children:li.map(m=>e.jsx("button",{"aria-selected":C===m.id,className:C===m.id?"active":void 0,role:"tab",type:"button",onClick:()=>k(m.id),children:m.label},m.id))}),C==="history"?e.jsx(ri,{state:t,taskset:S}):e.jsxs(e.Fragment,{children:[e.jsx(Gs,{artifact:R,defaultModel:l,tab:C,taskset:S,onOpenFiles:()=>r(S.id),onToast:h,training:u}),C==="scoring"&&S.metadata.flagship==="cross-system-operations"?e.jsx(zs,{busyAction:u.busyAction,taskset:S,onApprove:m=>u.actions.approveExpertBootstrap(S.id,m),onPreview:()=>u.actions.previewExpertBootstrap(S.id),onToast:h}):null]})]}):e.jsxs("div",{className:"labs-flat-body labs-datasets-page",children:[e.jsx("div",{className:"labs-workproduct-toolbar",children:e.jsxs("label",{className:"labs-search",children:[e.jsx(Pn,{size:14}),e.jsx("input",{"aria-label":"Search Tasksets",placeholder:"Search Tasksets",value:d,onChange:m=>{j(m.target.value),g(1)}})]})}),e.jsx("div",{className:"training-table-wrap",children:e.jsxs("table",{className:"training-data-table labs-datasets-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Taskset"}),e.jsx("th",{children:"Training"}),e.jsx("th",{children:"Validation"}),e.jsx("th",{children:"Frozen Eval"}),e.jsx("th",{children:"Graders"}),e.jsx("th",{children:"Activity"}),e.jsx("th",{children:"Updated"})]})}),e.jsx("tbody",{children:_.map(m=>{const T=x.get(m.id)??0,V=(t?.benchmarkRuns??[]).filter(E=>E.metadata.sourceTasksetId===m.id).length;return e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("button",{className:"labs-workproduct-link",type:"button",onClick:()=>s(m.id),children:[e.jsx("strong",{children:m.name}),e.jsx("span",{children:m.objective})]})}),e.jsx("td",{children:It(m,t,"train")}),e.jsx("td",{children:It(m,t,"validation")}),e.jsx("td",{children:It(m,t,"frozen_eval")}),e.jsx("td",{children:m.graders.length}),e.jsx("td",{children:m.purpose==="benchmark"?V?`${V} run${V===1?"":"s"}`:"Not run":T?`${T} model${T===1?"":"s"}`:"—"}),e.jsx("td",{children:Dt(m.updatedAt)})]},m.id)})})]})}),_.length?null:e.jsx("div",{className:"labs-table-empty",children:"No Tasksets match this view."}),e.jsx(ci,{page:b,total:p.length,onChange:g})]})}function ri({state:t,taskset:n}){const[a,s]=c.useState(!1),l=(t?.modelRuns??[]).filter(r=>r.taskset.id===n.id).sort((r,u)=>u.updatedAt.localeCompare(r.updatedAt)),o=a?l:l.slice(0,10),i=new Map((t?.modelProjects??[]).map(r=>[r.id,r.name]));if(n.purpose==="benchmark"){const r=l.filter(u=>u.kind==="evaluation");return r.length?e.jsx("div",{className:"training-table-wrap",children:e.jsxs("table",{className:"training-data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Model"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Quality"}),e.jsx("th",{children:"Token delta"}),e.jsx("th",{children:"Mode"}),e.jsx("th",{children:"Updated"})]})}),e.jsx("tbody",{children:r.map(u=>{const h=u.receipt?.schemaVersion==="openpond.modelEvaluationReceipt.v1"?u.receipt:null,d=u.receipt?.schemaVersion==="openpond.modelEvaluationStopReceipt.v1"?u.receipt:null,j=h?.foregroundTokenDelta??null;return e.jsxs("tr",{children:[e.jsx("td",{children:i.get(u.modelId)??u.modelId}),e.jsx("td",{children:d?"inconclusive":u.status}),e.jsx("td",{children:h?`${Math.round(h.quality.candidatePassRate*100)}% candidate`:d?"Candidate skipped":"Pending"}),e.jsx("td",{children:j===null?"—":`${j>0?"+":""}${j.toLocaleString()}`}),e.jsx("td",{children:u.evaluation?`${u.evaluation.attemptPlan.reduce((b,g)=>b+g.attemptCount,0)} attempts`:"—"}),e.jsx("td",{children:Dt(u.updatedAt)})]},u.id)})})]})}):e.jsx("div",{className:"labs-table-empty",children:"This benchmark has not been run yet."})}return l.length?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"training-table-wrap",children:e.jsxs("table",{className:"training-data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Model"}),e.jsx("th",{children:"Run"}),e.jsx("th",{children:"Method"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Updated"})]})}),e.jsx("tbody",{children:o.map(r=>e.jsxs("tr",{children:[e.jsx("td",{children:i.get(r.modelId)??r.modelId}),e.jsx("td",{children:Se(r.kind)}),e.jsx("td",{children:Oe(r.method)}),e.jsx("td",{children:e.jsx(re,{label:Se(r.status),value:r.status})}),e.jsx("td",{children:Dt(r.updatedAt)})]},r.id))})]})}),l.length>10?e.jsx("div",{className:"labs-model-run-list-actions",children:e.jsx("button",{className:"training-button secondary labs-compact-button",type:"button",onClick:()=>s(r=>!r),children:a?"Show latest 10":`Show all ${l.length} runs`})}):null]}):e.jsx("div",{className:"labs-table-empty",children:"This Taskset has not been used in a submitted run yet."})}function It(t,n,a){const s=t.datasetArtifact?n?.datasetArtifacts.find(l=>l.tasksetId===t.id&&l.tasksetRevision===t.revision):null;return s?s.splitCounts[a]??0:t.tasks.filter(l=>l.split===a).length}function di(t){return t.readiness?.ready?"Ready":t.status==="ready"?"Needs Evals":t.status.replaceAll("_"," ").replace(/^./,n=>n.toUpperCase())}function Dt(t){const n=new Date(t);return Number.isFinite(n.getTime())?n.toLocaleDateString(void 0,{month:"short",day:"numeric"}):"—"}function ci({page:t,total:n,onChange:a}){const s=Math.max(1,Math.ceil(n/Lt));return s===1?null:e.jsxs("nav",{className:"labs-pagination","aria-label":"Taskset pages",children:[e.jsx("button",{type:"button",disabled:t<=1,onClick:()=>a(t-1),children:"Previous"}),e.jsxs("span",{children:[t," of ",s]}),e.jsx("button",{type:"button",disabled:t>=s,onClick:()=>a(t+1),children:"Next"})]})}function ui({baseModelCandidates:t,busy:n,defaultBenchmarkModel:a,initialName:s,onClose:l,onCreate:o,onManageModels:i,providerSettings:r}){const u=c.useMemo(()=>pi(t),[t]),[h,d]=c.useState(s),[j,b]=c.useState(""),[g,C]=c.useState(""),[k,f]=c.useState("train"),S=c.useMemo(()=>hi(r,a),[a,r]),[y,w]=c.useState(Ot(a)),[R,p]=c.useState(null),_=h.trim().replace(/\s+/g," ");async function x(m){if(m.preventDefault(),!_||n)return;p(null);const T=u.find(E=>E.selectionKey===g)??null;await o({name:_,description:j.trim()||null,defaultBaseModel:T?.preference??null,benchmarkModel:k==="benchmark"?mi(y):null,purpose:k})||p("OpenPond could not create the Model. Review the latest error and try again.")}return e.jsxs(_e,{ariaLabel:"New model",backdropClassName:"labs-rename-backdrop",className:"labs-rename-dialog labs-model-create-dialog",dismissDisabled:n,initialFocusKey:s,onClose:l,children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("h2",{children:"New model"}),e.jsx("p",{children:"Create the Model now. Tasksets, runs, and releases can be added later."})]}),e.jsx("button",{"aria-label":"Close new model",disabled:n,type:"button",onClick:l,children:e.jsx(Me,{size:16})})]}),e.jsxs("form",{onSubmit:m=>{x(m)},children:[e.jsxs("fieldset",{className:"labs-model-create-purpose",children:[e.jsx("legend",{children:"What do you want to do?"}),e.jsxs("button",{className:k==="train"?"selected":void 0,type:"button",onClick:()=>f("train"),children:[e.jsx("strong",{children:"Train a model"}),e.jsx("small",{children:"Create runs and trained Versions from your Tasksets."})]}),e.jsxs("button",{className:k==="benchmark"?"selected":void 0,type:"button",onClick:()=>f("benchmark"),children:[e.jsx("strong",{children:"Benchmark a model"}),e.jsx("small",{children:"Create the Model, then configure a controlled evaluation."})]})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Name"}),e.jsx("input",{"data-autofocus":!0,maxLength:200,required:!0,value:h,onChange:m=>d(m.currentTarget.value)})]}),e.jsxs("label",{children:[e.jsxs("span",{children:["Description ",e.jsx("small",{children:"Optional"})]}),e.jsx("textarea",{maxLength:5e3,rows:3,value:j,onChange:m=>b(m.currentTarget.value)})]}),k==="benchmark"?e.jsxs("label",{className:"labs-model-create-field",children:[e.jsx("span",{children:"Model to benchmark"}),e.jsx("select",{"aria-label":"Model to benchmark",value:y,onChange:m=>w(m.target.value),children:S.map(m=>e.jsx("optgroup",{label:m.providerLabel,children:m.models.map(T=>e.jsx("option",{value:T.value,children:T.label},T.value))},m.providerId))}),e.jsx("small",{children:"Uses the same chat-provider catalog as the composer. The choice is pinned in the saved benchmark receipt."})]}):e.jsxs("div",{className:"labs-model-create-field",children:[e.jsxs("span",{children:["Starting model ",e.jsx("small",{children:"Optional"})]}),e.jsxs("div",{className:"labs-model-create-select-row",children:[e.jsx(De,{label:"Starting model",value:g,options:[{value:"",label:"Choose later"},...u.map(m=>({value:m.selectionKey,label:`${m.label} · ${m.sourceLabel}${m.available?"":" · Unavailable"}`,disabled:!m.available}))],onChange:C}),e.jsx("button",{"aria-label":"Add starting model",className:"labs-model-create-add",disabled:n,title:"Manage models in Compute settings",type:"button",onClick:i,children:"+"})]})]}),R?e.jsx("div",{className:"labs-rename-error",role:"alert",children:R}):null,e.jsxs("footer",{children:[e.jsx("button",{disabled:n,type:"button",onClick:l,children:"Cancel"}),e.jsx("button",{disabled:!_||n,type:"submit",children:n?"Creating…":k==="benchmark"?"Create and benchmark":"Create model"})]})]})]})}function hi(t,n){const s=_n(t,{includeUnavailable:!1}).flatMap(o=>{const i=$n(o.value,t).map(r=>({label:r.label,value:Ot({providerId:o.value,modelId:r.value})}));return i.length?[{providerId:o.value,providerLabel:o.label,models:i}]:[]}),l=Ot(n);return s.some(o=>o.models.some(i=>i.value===l))?s:[{providerId:n.providerId,providerLabel:En(n.providerId,t),models:[{label:n.modelId,value:l}]},...s]}function Ot(t){return JSON.stringify([t.providerId,t.modelId])}function mi(t){try{const n=JSON.parse(t);return!Array.isArray(n)||n.length!==2||typeof n[0]!="string"||typeof n[1]!="string"?null:{providerId:n[0],modelId:n[1]}}catch{return null}}function pi(t){return t.filter(n=>!(n.preference.source==="builtin"&&n.nonProduction))}const bi=10;new Date(0).toISOString();function gi({items:t,loading:n,runs:a,state:s,emptyMessage:l="No Models yet.",onSelect:o,onUseModel:i}){return n?e.jsxs("div",{className:"labs-table-empty",children:[e.jsx(dt,{className:"spin",size:16})," Loading Models…"]}):t.length?e.jsx("div",{className:"training-table-wrap",children:e.jsxs("table",{className:"training-data-table labs-models-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Model"}),e.jsx("th",{children:"Availability"}),e.jsx("th",{children:"Recent run"}),e.jsx("th",{children:"Updated"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(r=>{const u=Qe(r,a,s),h=u.find(g=>g.current)??null,j=Ht(We(r,a,s),u,ct(r,s))[0]??null,b=j?.lifecycleRun?.status??j?.job?.status??"not_run";return e.jsxs("tr",{onClick:()=>o(r.key),children:[e.jsx("td",{children:e.jsxs("button",{className:"labs-workproduct-link",type:"button",onClick:()=>o(r.key),children:[e.jsx("strong",{children:r.name}),e.jsx("span",{children:r.description})]})}),e.jsx("td",{children:e.jsxs("div",{className:"labs-model-table-summary",children:[e.jsx(re,{label:h?"Hosted":"Not hosted",value:h?"ready":"not_run"}),e.jsx("span",{children:h?`Release ${h.number}`:"No active release"})]})}),e.jsx("td",{children:e.jsxs("div",{className:"labs-model-table-summary",children:[e.jsx(re,{label:Se(b),value:b}),e.jsx("span",{children:fi(j?.lifecycleRun??null,r.trainingRunCount)})]})}),e.jsx("td",{children:xi(r.updatedAt)}),e.jsx("td",{children:e.jsxs("div",{className:"labs-workproduct-actions",children:[e.jsx("button",{className:"training-button secondary labs-compact-button labs-workproduct-use",disabled:!h,title:h?"Chat with the active Version":"Set a passing Version active before Chat",type:"button",onClick:g=>{g.stopPropagation(),i(r.id)},children:"Chat"}),e.jsx(ba,{size:15})]})})]},r.key)})})]})}):e.jsx("div",{className:"labs-table-empty",children:l})}function fi(t,n){if(t?.kind==="evaluation"){const a=t.evaluation?.benchmarkId==="harness-refiner"?"Harness Refiner 08112026":"Benchmark",s=t.receipt?.schemaVersion==="openpond.modelEvaluationReceipt.v1"?t.receipt.attempts?.length?(()=>{const l=Be(t.receipt);return`${l.passedTaskCount}/${l.comparedTaskCount} passed`})():gn(t.receipt.terminalClassification.replaceAll("_"," ")):t.receipt?.schemaVersion==="openpond.modelEvaluationStopReceipt.v1"?"Inconclusive":t.evaluationProgress?`${gn(t.evaluationProgress.stage)} ${t.evaluationProgress.completedAttempts}/${t.evaluationProgress.totalAttempts}`:Se(t.status);return`${a} · ${s}`}return`${n} ${n===1?"run":"runs"}`}function xi(t){const n=new Date(t),a=new Date;return n.toDateString()===a.toDateString()?new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"}).format(n):new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",...n.getFullYear()===a.getFullYear()?{}:{year:"2-digit"}}).format(n)}function ji({page:t,total:n,onChange:a}){const s=Math.max(1,Math.ceil(n/bi));return s<=1?null:e.jsxs("nav",{className:"labs-pagination","aria-label":"Pagination",children:[e.jsx("button",{type:"button",disabled:t<=1,onClick:()=>a(t-1),children:"Previous"}),e.jsxs("span",{children:[t," of ",s]}),e.jsx("button",{type:"button",disabled:t>=s,onClick:()=>a(t+1),children:"Next"})]})}function gn(t){return t&&`${t[0].toUpperCase()}${t.slice(1).replaceAll("_"," ")}`}function vi(t){return t?[...t.jobs.map(n=>`job:${n.id}:${n.status}`),...t.models.map(n=>`model:${n.id}:${n.status}:${n.artifactId}:${n.jobId}`)].sort().join("|"):""}function yi({items:t,providerSettings:n,state:a,onClose:s,onOpenModel:l}){const o=c.useMemo(()=>Si(t,a),[t,a]),[i,r]=c.useState(o[0]?.run.id??""),[u,h]=c.useState(o[1]?.run.id??o[0]?.run.id??""),d=o.find(g=>g.run.id===i)??o[0]??null,j=o.find(g=>g.run.id===u)??o[1]??o[0]??null,b=d&&j?[d,j]:[];return e.jsxs(_e,{ariaLabel:"Compare benchmark runs",backdropClassName:"labs-rename-backdrop",className:"labs-rename-dialog labs-model-compare-dialog",onClose:s,children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Compare benchmark runs"}),e.jsx("p",{children:"Compare persisted results across models or across runs of one model."})]}),e.jsx("button",{"aria-label":"Close comparison",type:"button",onClick:s,children:e.jsx(Me,{size:16})})]}),e.jsx("div",{className:"labs-model-compare-body",children:o.length?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"labs-model-compare-selectors",children:[e.jsx(fn,{label:"First run",runs:o,value:d?.run.id??"",providerSettings:n,onChange:r}),e.jsx(fn,{label:"Second run",runs:o,value:j?.run.id??"",providerSettings:n,onChange:h})]}),b.length===2?e.jsxs(e.Fragment,{children:[e.jsx(Un,{series:b.map(g=>{const C=zn(g.receipt).candidate;return{id:g.run.id,label:Ci(g,n),inputTokens:C.inputTokens,outputTokens:C.outputTokens,tokens:C.totalTokens,passRate:g.receipt.quality.candidatePassRate,costUsd:C.costUsd}})}),e.jsx("div",{className:"labs-model-compare-facts",children:b.map(g=>e.jsxs("article",{children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("strong",{children:g.item.name}),e.jsx("span",{children:Kn(g.run,n)})]}),e.jsx("button",{className:"training-button secondary labs-compact-button",type:"button",onClick:()=>l(g.item.key),children:"View model"})]}),e.jsxs("dl",{children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Result"}),e.jsx("dd",{children:ki(g.receipt)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Quality"}),e.jsxs("dd",{children:[xn(g.receipt.quality.baselinePassRate)," → ",xn(g.receipt.quality.candidatePassRate)]})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"All-task token change"}),e.jsx("dd",{children:Ri(Be(g.receipt).tokenDeltaPercent)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Harness"}),e.jsx("dd",{children:g.receipt.stages.baseline.contentHash===g.receipt.stages.candidate.contentHash?"Unchanged":"Updated"})]})]})]},g.run.id))})]}):null]}):e.jsx("p",{className:"labs-model-benchmark-empty",children:"Complete a benchmark to make its saved result available here."})})]})}function ki(t){const n=Be(t);return`${n.passedTaskCount}/${n.comparedTaskCount} passed`}function fn({label:t,runs:n,value:a,providerSettings:s,onChange:l}){return e.jsxs("label",{children:[e.jsx("span",{children:t}),e.jsx("select",{value:a,onChange:o=>l(o.target.value),children:n.map(o=>e.jsxs("option",{value:o.run.id,children:[o.item.name," · ",Kn(o.run,s)," · ",$e(o.run.updatedAt)]},o.run.id))})]})}function Si(t,n){const a=new Map(t.map(s=>[s.id,s]));return n.modelRuns.flatMap(s=>{const l=a.get(s.modelId),o=Ni(s);return l&&o?[{item:l,receipt:o,run:s}]:[]}).sort((s,l)=>l.run.updatedAt.localeCompare(s.run.updatedAt))}function Ni(t){return t.receipt?.schemaVersion==="openpond.modelEvaluationReceipt.v1"?t.receipt:null}function Ci(t,n){return`${zt(t.run.evaluation?.model.modelId??"Unknown model",n,t.run.evaluation?.model.providerId)} · ${Ii(t.run.updatedAt)}`}function Kn(t,n){const a=t.evaluation?.model;return a?`${En(a.providerId,n)} / ${zt(a.modelId,n,a.providerId)}`:"Unknown model"}function xn(t){return`${Math.round(t*100)}%`}function Ri(t){return t===null?"Not comparable":`${t>0?"+":""}${t.toFixed(1)}%`}function Ii(t){return new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"}).format(new Date(t))}const jn=10;function Mi({activeProfileId:t,items:n,loading:a,providerSettings:s,runs:l,state:o,onSelect:i,onUseModel:r}){const[u,h]=c.useState("all"),[d,j]=c.useState(""),[b,g]=c.useState(1),[C,k]=c.useState(!1),f=o?.modelRuns.filter(p=>p.receipt?.schemaVersion==="openpond.modelEvaluationReceipt.v1").length??0,S=c.useMemo(()=>[...new Set(n.flatMap(p=>p.ownerProfileId?[p.ownerProfileId]:[]))].sort((p,_)=>p===t?-1:_===t?1:p.localeCompare(_)),[t,n]),y=c.useMemo(()=>{const p=d.trim().toLowerCase();return n.filter(_=>u!=="all"&&_.ownerProfileId!==u?!1:!p||[_.name,_.description,_.id,_.ownerProfileId??""].some(x=>x.toLowerCase().includes(p))).sort((_,x)=>x.updatedAt.localeCompare(_.updatedAt))},[n,u,d]),w=y.slice((b-1)*jn,b*jn),R=n.length?"No Models match this Profile or search.":"No Models exist in this workspace yet.";return e.jsxs("div",{className:"labs-flat-body labs-models-page",children:[e.jsxs("div",{className:"labs-workproduct-toolbar",children:[e.jsxs("label",{className:"labs-search",children:[e.jsx(Pn,{size:14}),e.jsx("input",{"aria-label":"Search Models",placeholder:"Search Models",value:d,onChange:p=>{j(p.target.value),g(1)}})]}),e.jsxs("div",{className:"labs-model-toolbar-actions",children:[e.jsx(De,{className:"labs-model-profile-filter",label:"Filter Models by Profile",value:u,options:[{value:"all",label:"All profiles"},...S.map(p=>({value:p,label:`${p}${p===t?" (active)":""}`}))],onChange:p=>{h(p),g(1)}}),e.jsx("button",{className:"training-button secondary",disabled:f<1,type:"button",onClick:()=>k(!0),children:"Compare runs"})]})]}),e.jsx(gi,{emptyMessage:R,items:w,loading:a,runs:l,state:o,onSelect:i,onUseModel:r}),e.jsx(ji,{page:b,total:y.length,onChange:g}),C&&o?e.jsx(yi,{items:n,providerSettings:s,state:o,onClose:()=>k(!1),onOpenModel:p=>{k(!1),i(p)}}):null]})}function Ai({state:t}){if(!t)return e.jsxs("div",{className:"labs-table-empty",children:[e.jsx(dt,{className:"spin",size:16})," Loading serving state…"]});const n=wi(t);return e.jsx("div",{className:"labs-flat-body labs-serving-page",children:e.jsxs("section",{className:"labs-operational-section","aria-labelledby":"managed-serving-title",children:[e.jsx("header",{children:e.jsxs("div",{children:[e.jsx("h2",{id:"managed-serving-title",children:"Managed serving"}),e.jsx("p",{children:"Durable adapter publication and binding state synchronized from OpenPond Managed training."})]})}),n.length?e.jsx("div",{className:"training-table-wrap",children:e.jsxs("table",{className:"training-data-table labs-managed-serving-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Model"}),e.jsx("th",{children:"Synchronization"}),e.jsx("th",{children:"Artifact"}),e.jsx("th",{children:"Deployment"}),e.jsx("th",{children:"Admission"}),e.jsx("th",{children:"Updated"})]})}),e.jsx("tbody",{children:n.map(a=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("span",{className:"labs-serving-model",children:[e.jsx("strong",{children:a.modelName}),e.jsx("span",{children:a.versionLabel})]})}),e.jsx("td",{children:e.jsx(re,{label:Mt(a.managed.state),value:a.managed.state})}),e.jsx("td",{children:Mt(a.managed.canonicalArtifactState)}),e.jsx("td",{children:Mt(a.managed.canonicalDeploymentState)}),e.jsx("td",{children:a.managed.customerBindingAllowed?"Allowed":"Pending"}),e.jsx("td",{children:Ti(a.updatedAt)})]},a.lineageId))})]})}):e.jsx("div",{className:"labs-table-empty",children:"No managed serving bindings are synchronized."})]})})}function wi(t){const n=new Map(t.modelProjects.map(s=>[s.id,s])),a=new Map(t.modelVersions.flatMap(s=>s.artifactLineageId?[[s.artifactLineageId,s]]:[]));return t.models.flatMap(s=>{if(!s.managedServing)return[];const l=a.get(s.id)??null,o=n.get(s.modelId)??null;return[{lineageId:s.id,modelName:o?.name??s.modelId,versionLabel:l?`Version ${l.version}`:s.id,managed:s.managedServing,updatedAt:s.managedServing.lastSyncedAt}]}).sort((s,l)=>l.updatedAt.localeCompare(s.updatedAt))}function Mt(t){return t?t.replaceAll("_"," ").replace(/^./,n=>n.toUpperCase()):"Pending"}function Ti(t){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(t))}function _i({account:t,connection:n,onError:a,onOpenSourceSession:s}){return e.jsxs("div",{className:"labs-flat-body labs-usage-page",children:[e.jsxs("header",{className:"labs-operational-header",children:[e.jsx("h2",{children:"Model usage"}),e.jsx("p",{children:"All recorded model calls for this account. Narrow the projection by provider, model, status, visibility, or time range."})]}),e.jsx(Ma,{account:t,connection:n,enabled:!0,modelFocused:!0,onError:a,onOpenSourceSession:s})]})}function $i({project:t,persisted:n,busy:a,dirty:s,canRun:l,pageReason:o,actionLabel:i,onProjectChange:r,onCancel:u,onSave:h,onLaunch:d}){const[j,b]=c.useState(!1),g=c.useRef(t.name);return e.jsxs("header",{className:"model-build-header",children:[e.jsx("div",{children:n?e.jsxs(e.Fragment,{children:[e.jsx("h1",{className:"model-build-name",children:"New run"}),e.jsx("p",{children:t.name})]}):j?e.jsx("input",{"aria-label":"Model name",autoFocus:!0,className:"model-build-name model-build-name-input",value:t.name,onBlur:()=>{r({...t,name:t.name.trim()||g.current,updatedAt:new Date().toISOString()}),b(!1)},onChange:C=>r({...t,name:C.target.value,updatedAt:new Date().toISOString()}),onKeyDown:C=>{C.key==="Enter"&&C.currentTarget.blur(),C.key==="Escape"&&(r({...t,name:g.current,updatedAt:new Date().toISOString()}),b(!1))}}):e.jsx("button",{"aria-label":`Rename ${t.name}`,className:"model-build-name model-build-name-button",type:"button",onClick:()=>{g.current=t.name,b(!0)},children:t.name})}),e.jsxs("div",{className:"model-build-actions",children:[e.jsx("button",{id:"model-run-editor-cancel",className:"training-button secondary",type:"button",disabled:a,onClick:u,children:"Cancel"}),e.jsx("button",{className:"training-button secondary",type:"button",disabled:a||!s||!t.name.trim(),onClick:h,children:"Save"}),e.jsx("span",{className:"model-build-run-control",title:o??i,children:e.jsx("button",{className:"training-button",type:"button",disabled:!l,onClick:d,children:i})})]})]})}function Pi(t){return t==="gspo-token"?"GSPO-token":t.toUpperCase()}function Bt(t){return t==="openpond/tiny-cpu-gpt2-fixture"?.01:2e-4}function Ei(t){const n=t.metadata.trainingMethod;if(typeof n=="string"&&n!=="none")return n;const a=t.readiness?.recommendedMethod;return a&&a!=="none"?a:"sft"}function Li(t){const n=new Set;for(const a of t.capabilities.compatibleMethods)(a==="sft"||a==="dpo"||a==="grpo"||a==="ppo")&&n.add(a);return t.readiness?.trainingPath?.bootstrap?.method==="sft"&&n.add("sft"),t.readiness?.trainingPath?.primaryMethod==="grpo"&&n.add("grpo"),t.readiness?.trainingPath?.primaryMethod==="ppo"&&n.add("ppo"),["sft","dpo","grpo","ppo"].filter(a=>n.has(a)).length>0?["sft","dpo","grpo","ppo"].filter(a=>n.has(a)):["sft"]}function Gn(t,n){return t.datasetArtifact?.splitCounts[n]??t.tasks.filter(a=>a.split===n).length}function Je(t){return t.replaceAll("_"," ").replace(/\b\w/g,n=>n.toUpperCase())}function Di(t,n){return n?t.find(a=>a.preference.modelId===n.modelId&&a.preference.source===n.source&&a.preference.revision===n.revision&&a.preference.modelAssetId===n.modelAssetId)??t.find(a=>a.preference.modelId===n.modelId)??null:null}function Oi(t,n,a){return t.find(s=>s.executionOptions.some(l=>l.destinationId===n&&l.available&&l.methods.includes(a)))??null}function Jn(t){return(t.split("/").at(-1)??t).replaceAll("-"," ").replace(/\b\w/g,a=>a.toUpperCase())}function vn(t){return{ready:"Ready",model_download_required:"Model download required",compute_setup_required:"Compute setup required",provider_managed:"Provider managed",unsupported:"Unsupported"}[t]??"Unsupported"}function Gt(t){return t==null?"size unknown":t<1024?`${t} B`:t<1024**2?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(0)} MB`}function Bi({busy:t,catalog:n,catalogError:a,selectedComputeTarget:s,modelSearch:l,onModelSearchChange:o,baseModelKey:i,baseModelCandidates:r,destinationId:u,method:h,onBaseModelChange:d,visibleCatalogModels:j,selectedCatalogCompatibility:b,selectedCatalogModel:g,configurationContent:C,inlineProviderApproval:k}){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"training-start-fields",children:e.jsxs("section",{className:"training-catalog-setup","aria-label":"Training compute and Model catalog",children:[e.jsxs("div",{className:"training-catalog-field",children:[e.jsx("span",{children:"Compute"}),e.jsx("strong",{children:n?"Automatic":"Resolving…"}),e.jsx("small",{children:s?.description??"The backend selects the available provider, device, runtime, and engine."})]}),a?e.jsx("p",{className:"training-catalog-error",children:a}):null,e.jsxs("label",{className:"training-catalog-field",children:[e.jsx("span",{children:"Base model"}),e.jsx("input",{"aria-label":"Search Model catalog",placeholder:"Search all known Models",type:"search",value:l,disabled:t||!n,onChange:f=>o(f.target.value)})]}),n?e.jsxs("div",{className:"training-model-catalog",role:"listbox","aria-label":"Available base Models",children:[j.map(f=>{const S=f.compatibilities.find(p=>p.targetId===s?.id&&p.methods.includes(h)),y=S?.state??"unsupported",w=S?.reason??`This target does not support ${h.toUpperCase()} for this Model.`,R=y!=="unsupported";return e.jsxs("button",{"aria-selected":f.selectionKey===i,className:`${f.selectionKey===i?"selected ":""}${R?"":"unsupported"}`,disabled:t||!R,role:"option",title:w,type:"button",onClick:()=>d(f.selectionKey,f.modelId),children:[e.jsxs("span",{children:[e.jsx("strong",{children:f.label}),e.jsxs("small",{children:[f.modelId," · ",f.source]})]}),e.jsx("span",{className:`training-preparation-state ${y}`,children:vn(y)}),w?e.jsx("small",{children:w}):null]},f.selectionKey)}),j.length===0?e.jsx("p",{children:"No Models match this search. Clear the search to see the full catalog."}):null]}):e.jsx("label",{className:"training-catalog-field",children:e.jsxs("select",{"aria-label":"Available base Models",value:i,disabled:t,onChange:f=>{const S=f.target.value,y=r.find(w=>w.selectionKey===S)?.preference.modelId??"";d(S,y)},children:[e.jsx("option",{value:"",disabled:!0,children:"Choose starting weights"}),r.map(f=>{const S=f.executionOptions.find(y=>y.destinationId===u&&y.methods.includes(h));return e.jsxs("option",{disabled:!S?.available,value:f.selectionKey,children:[f.label," · ",f.sourceLabel,S?.available?"":` — ${S?.unavailableReason??"Unsupported"}`]},f.selectionKey)})]})}),e.jsx("div",{className:"training-start-fields training-resolved-device",children:e.jsxs("label",{children:[e.jsx("span",{children:"Training engine"}),e.jsx("input",{readOnly:!0,value:s?.engineAdapterId??"Resolving…"})]})}),e.jsx("p",{className:"training-start-note",children:"The backend can change providers as availability changes. The exact provider and spend are shown before launch."})]})}),C,k,e.jsxs("section",{className:"training-preparation-summary","aria-label":"Preparation summary",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Preparation"}),e.jsx("span",{children:vn(b?.state??g?.preparationState??"unsupported")})]}),e.jsxs("dl",{className:"training-start-summary",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Model weights / cache"}),e.jsx("dd",{children:g?.cached?"Pinned revision is cached":g?.expectedBytes!=null?`${Gt(g.expectedBytes)} download after Run review`:"Resolved during Run review"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Worker image"}),e.jsx("dd",{children:"Backend-pinned immutable image"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Harness runtime"}),e.jsx("dd",{children:s?.runtimeAdapterId??"Resolving…"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Data movement"}),e.jsx("dd",{children:"Exact upload and artifact return shown before approval"})]})]}),e.jsx("p",{children:"Selection starts no download, connection, upload, provisioning, or spend. The top-level Run review shows exact actions and approvals."})]})]})}function Ui({open:t,busy:n,destinationId:a,baseModelId:s,approvalFields:l,prepared:o,preparedQuote:i,compatible:r,actionLabel:u,onClose:h,onConfirm:d}){return t?e.jsx("div",{className:"training-dialog-backdrop",role:"presentation",onMouseDown:n?void 0:h,children:e.jsxs("section",{"aria-label":"Review provider approval","aria-modal":"true",className:"training-dialog training-provider-approval-dialog",role:"dialog",onMouseDown:j=>j.stopPropagation(),children:[e.jsxs("div",{className:"training-dialog-header",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Review and run"}),e.jsxs("p",{children:[Je(a)," · ",Jn(s)]})]}),e.jsx("button",{"aria-label":"Close provider approval",disabled:n,type:"button",onClick:h,children:e.jsx(Me,{size:16})})]}),l,o?e.jsxs("dl",{className:"training-start-summary",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Exact quote"}),e.jsx("dd",{children:i==null?"Unavailable":`$${i.toFixed(2)}`})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Prepared data"}),e.jsxs("dd",{children:[Gt(o.bundle.totalSizeBytes)," · verified"]})]})]}):null,e.jsxs("div",{className:"training-dialog-actions",children:[e.jsx("button",{className:"training-button secondary",type:"button",disabled:n,onClick:h,children:"Cancel"}),e.jsx("button",{className:"training-button",type:"button",disabled:n||!r,onClick:d,children:u})]})]})}):null}function Fi({approvalPolicy:t,providerLabel:n,method:a,busy:s,exportApproved:l,maximumCostUsd:o,retentionDays:i,onManageProvider:r,onExportApprovedChange:u,onMaximumCostChange:h,onRetentionDaysChange:d}){return e.jsxs("fieldset",{className:"training-provider-approval",children:[e.jsx("legend",{children:"Provider approval"}),r?e.jsx("button",{className:"training-text-button",type:"button",disabled:s,onClick:r,children:t.settingsActionLabel??`Manage ${n}`}):null,e.jsxs("label",{className:"training-provider-consent",children:[e.jsx("input",{type:"checkbox",checked:l,disabled:s,onChange:j=>u(j.target.checked)}),e.jsx("span",{children:t.exportDescription??`Export only the approved train split to ${n}.`})]}),e.jsxs("div",{className:"training-start-fields",children:[e.jsxs("label",{children:[e.jsx("span",{children:"Maximum provider spend (USD)"}),e.jsx("input",{"aria-label":"Maximum provider spend (USD)",type:"number",min:t.minimumSpendUsd,max:t.maximumSpendUsd,step:.01,value:o??"",disabled:s,onChange:j=>h(j.target.valueAsNumber)})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Retention record (days)"}),e.jsx("input",{"aria-label":"Retention record (days)",type:"number",min:t.minimumRetentionDays,max:t.maximumRetentionDays,step:1,value:i,disabled:s,onChange:j=>d(j.target.valueAsNumber)})]})]}),e.jsx("p",{className:"training-start-note",children:"Approval is bound server-side to the signed-in OpenPond account at launch."}),a==="grpo"?e.jsx("p",{className:"training-start-note",children:t.methodRequirement}):null]})}function zi({busy:t,method:n,options:a,onSelect:s}){return e.jsx("div",{className:"training-method-tabs",role:"tablist","aria-label":"Training method",children:a.map(l=>e.jsxs("button",{"aria-selected":l===n,className:l===n?"active":"",disabled:t,role:"tab",type:"button",onClick:()=>s(l),children:[e.jsx("span",{children:Ra(l)}),e.jsx("strong",{children:Oe(l)})]},l))})}function Vi({method:t,trainingExamples:n,availableTrainExamples:a,approvedExamples:s,evaluationExamples:l,preparedQuote:o,selectedComputeTarget:i,approvalPresentation:r,maximumCostUsd:u,providerManaged:h,storagePath:d}){const j=i?.approvalPolicy??null,b=t==="grpo"||t==="ppo"?`${Math.min(n,a)} of ${a} approved train prompts`:t==="dpo"?`${Math.min(n,s)} of ${s} approved preference pairs`:`${Math.min(n,s||a)} approved example${n===1?"":"s"}`,g=j?r==="dialog"?"Reviewed when you Run":o==null?`Prepare a provider-validated quote · hard cap $${u!=null&&Number.isFinite(u)?u.toFixed(2):"—"}`:`$${o.toFixed(2)} · hard cap $${(u??0).toFixed(2)}`:"Provided before approval";return e.jsxs("dl",{className:"training-start-summary",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Training data"}),e.jsx("dd",{children:b})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Evaluation"}),e.jsxs("dd",{children:[l," test example",l===1?"":"s"]})]}),e.jsxs("div",{children:[e.jsx("dt",{children:o==null?"Estimate":"Exact quote"}),e.jsx("dd",{children:g})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Storage"}),e.jsx("dd",{children:h?"Portable output imported into app-managed storage":d??"App-managed storage"})]})]})}function qi({prepared:t,preparedQuote:n,maximumCostUsd:a}){const s=t.plan.recipe,l=s.method==="dpo"?s.policyModel.id:s.method==="ppo"?s.policyOptimization.policyModel.id:s.method==="sft"||s.method==="grpo"?s.baseModel.id:"",o=s.method==="grpo"?`RFT · ${Pi(s.loss.method)}`:`${Oe(s.method)} · ${s.parameterization.toUpperCase()}`;return e.jsxs("section",{className:"training-prepared-confirmation","aria-label":"Confirm paid training launch",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Ready to launch"}),e.jsx("span",{children:"The quote and prepared data are fixed to this confirmation."})]}),e.jsxs("dl",{className:"training-start-summary",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Account"}),e.jsx("dd",{children:t.approvalActor??"Local user"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Provider"}),e.jsx("dd",{children:Je(t.plan.destinationId)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Model"}),e.jsx("dd",{children:Jn(l)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Method"}),e.jsx("dd",{children:o})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Quote"}),e.jsx("dd",{children:n==null?"Unavailable":`$${n.toFixed(2)}`})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Maximum"}),e.jsx("dd",{children:a==null?"Unavailable":`$${a.toFixed(2)}`})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Retention"}),e.jsxs("dd",{children:[t.plan.dataPolicy.retentionDays," days"]})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Prepared data"}),e.jsxs("dd",{children:[Gt(t.bundle.totalSizeBytes)," · verified"]})]})]}),e.jsx("p",{children:"No provider dataset or job exists until you launch."})]})}function Hi({method:t,trainingExamples:n,maximumTrainingExamples:a,maxSteps:s,sequenceLength:l,maximumSequenceLength:o,rolloutMaxOutputTokens:i,maximumOutputTokens:r,defaultRolloutOutputTokens:u,rank:h,learningRate:d,rftLossMethod:j,rolloutGroupSize:b,rolloutConcurrency:g,onTrainingExamplesChange:C,onMaxStepsChange:k,onSequenceLengthChange:f,onRolloutMaxOutputTokensChange:S,onRankChange:y,onLearningRateChange:w,onRftLossMethodChange:R,onRolloutGroupSizeChange:p,onRolloutConcurrencyChange:_}){return e.jsxs("details",{className:"training-start-advanced",children:[e.jsx("summary",{children:"Advanced settings"}),e.jsxs("div",{className:"training-start-fields",children:[e.jsxs("label",{children:[e.jsx("span",{children:"Training examples"}),e.jsx("input",{type:"number",min:1,max:a,value:n,onChange:x=>C(Math.max(1,Math.min(a,x.target.valueAsNumber||1)))})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Optimizer steps"}),e.jsx("input",{type:"number",min:1,max:1e3,value:s,onChange:x=>k(x.target.valueAsNumber||1)})]}),e.jsxs("label",{children:[e.jsx("span",{children:t==="grpo"?"Prompt length":"Sequence length"}),e.jsx("input",{type:"number",min:16,max:o,value:l,onChange:x=>f(x.target.valueAsNumber||64)})]}),t==="grpo"?e.jsxs("label",{children:[e.jsx("span",{children:"Maximum output"}),e.jsx("input",{type:"number",min:16,max:r,value:i,onChange:x=>S(Math.max(16,Math.min(r,x.target.valueAsNumber||u)))})]}):null,e.jsxs("label",{children:[e.jsx("span",{children:"LoRA rank"}),e.jsx("input",{type:"number",min:1,max:256,value:h,onChange:x=>y(x.target.valueAsNumber||2)})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Learning rate"}),e.jsx("input",{type:"number",min:1e-6,max:.1,step:1e-4,value:d,onChange:x=>{const m=x.target.valueAsNumber;Number.isFinite(m)&&w(m)}})]}),t==="grpo"?e.jsxs(e.Fragment,{children:[e.jsxs("label",{children:[e.jsx("span",{children:"RL loss"}),e.jsxs("select",{"aria-label":"RL loss",value:j,onChange:x=>R(x.target.value),children:[e.jsx("option",{value:"dapo",children:"DAPO"}),e.jsx("option",{value:"grpo",children:"GRPO"}),e.jsx("option",{value:"gspo-token",children:"GSPO-token"})]})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Rollouts per prompt"}),e.jsx("input",{type:"number",min:2,max:16,value:b,onChange:x=>p(x.target.valueAsNumber||8)})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Concurrent rollouts"}),e.jsx("input",{type:"number",min:1,max:16,value:g,onChange:x=>_(x.target.valueAsNumber||4)})]})]}):null]})]})}const Ki=64,Gi=4096;function Ut(t,n=Gi){return Ta(t,{minimum:Ki,maximum:n})}function Ji(t){if(t.method!=="grpo"||t.destinationId!=="openpond_managed"||t.executionMode!=="provider_native")throw new Error("This Model improvement path requires OpenPond Managed GRPO.");const n=t.taskset.metadata.toolContractHash===kt||t.taskset.environment.metadata.toolContractHash===kt,a=t.taskset.graders.find(l=>l.rewardEligible),s=4;return{schemaVersion:"openpond.rftRecipe.v1",method:"grpo",parameterization:"lora",baseModel:Wi(t),dataset:{trainSplit:"train",validationSplit:"frozen_eval",maxPromptTokens:4096,maxExamples:t.trainingExamples,selectionStrategy:t.taskset.datasetArtifact?"rft_easy_curriculum_v1":"stable_hash_top_n"},lora:{rank:16},rollout:{groupSize:s,concurrency:4,maxTurns:n?15:1,maxOutputTokens:512,temperature:.8,topP:.95,seed:17},optimizer:{learningRate:1e-5,maxSteps:t.maxSteps},loss:{method:t.rftLossMethod??Wn(t.taskset),klBeta:null},reward:n?{graderId:"cross-system-exact-verifier",graderHash:"server-derived-grader-hash",environmentId:"cross-system-operations",environmentVersion:ga,toolContractHash:kt}:{graderId:a?.id??"math_final_answer",graderHash:"server-derived-grader-hash",environmentId:ja,environmentVersion:xa,toolContractHash:fa},resourceLimits:{wallTimeMs:18e5,maxRollouts:Math.max(s,t.maxSteps*s),maxPayloadBytes:1e6},policyOptimization:null}}function Wn(t){return t.sourceRefs.some(a=>{const s=a.metadata;return("repositoryId"in a?String(a.repositoryId):"").toLowerCase().includes("dapo-math")||a.title.toLowerCase().includes("dapo-math")||String(s.datasetName??"").toLowerCase().includes("dapo-math")})?"dapo":"grpo"}function yn(t,n,a,s){return t.find(o=>o.selectionKey===n)?.executionOptions.some(o=>o.destinationId===a&&o.methods.includes(s))?n:""}function Wi(t){return{id:t.baseModelId,revision:t.catalogModel?.revision??"provider-managed-model-resource-v1",tokenizerRevision:t.catalogModel?.tokenizerRevision??"provider-managed-tokenizer-v1",chatTemplateHash:t.catalogModel?.chatTemplateHash??"provider-managed-chat-template-v1"}}const Qi=4096,Xi=4096,Yi=64;function Zi(t){const[n,a]=c.useState(null),[s,l]=c.useState(null),[o,i]=c.useState(""),r=c.useMemo(()=>{if(n?.targets)return n.targets;const d=t.destinations.find(j=>j.destinationId===t.initialDestination)??t.destinations.find(j=>j.available);return d?[{id:"automatic",label:"Automatic",description:d.unavailableReason??"Server-reported training destination.",destinationId:d.destinationId,computeAdapterId:d.destinationId,runtimeAdapterId:"resolving",engineAdapterId:"resolving",methods:d.methods,capabilityPills:[Je(d.destinationId)],executionMode:"local_worker",approvalPolicy:null,limits:{maximumSequenceLength:Qi,maximumOutputTokens:Xi,maximumTrainingExamples:null},defaults:{loraRank:2,maxSteps:8,rolloutGroupSize:4,rolloutConcurrency:1,rolloutOutputTokens:Yi},available:d.available,unavailableReason:d.unavailableReason}]:[]},[n?.targets,t.destinations,t.initialDestination]),u=c.useMemo(()=>{const d=n?.models??[],j=o.trim().toLowerCase();return j?d.filter(b=>`${b.label} ${b.modelId} ${b.source}`.toLowerCase().includes(j)):d.filter(b=>b.source!=="search")},[n?.models,o]),h=r[0]?.id??"automatic";return c.useEffect(()=>{if(!t.connection)return;let d=!0;const j=o.trim().length>=2?o.trim():"",b=window.setTimeout(()=>{lt.portableTrainingCatalog(t.connection,j,t.method).then(g=>{d&&(a(g),l(null))}).catch(g=>{d&&l(g instanceof Error?g.message:"The Model registry search could not be completed.")})},j?250:0);return()=>{d=!1,window.clearTimeout(b)}},[t.connection,t.method,o]),{catalog:n,catalogError:s,catalogTargets:r,visibleCatalogModels:u,computeTargetId:h,modelSearch:o,setModelSearch:i}}const el=64;function tl(t){const n=t.taskset.readiness?.trainingPath??null,a=n?.primaryMethod??Ei(t.taskset),s=n?.bootstrap??null,l=Li(t.taskset),o=t.initialMethod&&l.includes(t.initialMethod)?t.initialMethod:a==="grpo"?"grpo":a==="dpo"?"dpo":a==="ppo"?"ppo":"sft",i=t.runPreset==="small"||t.runPreset==="small_experiment",r=Di(t.baseModelCandidates,t.preferredBaseModel),u=r?.executionOptions.find(Q=>Q.available&&Q.methods.includes(o))??null,h=u?.destinationId??t.destinations.find(Q=>Q.available)?.destinationId??"openpond_managed",d=u?r:Oi(t.baseModelCandidates,h,o),j=Gn(t.taskset,"train"),[b,g]=c.useState(h),[C,k]=c.useState(d?.selectionKey??""),[f,S]=c.useState(()=>i&&o!=="grpo"?1:o==="grpo"?t.runPreset==="standard"?50:8:o==="dpo"?t.runPreset==="standard"?100:4:o==="ppo"?t.runPreset==="standard"?20:2:t.runPreset==="standard"?100:2),[y,w]=c.useState(()=>Math.max(1,Math.min(j,o==="dpo"?i?2:t.taskset.learningSignals.preferences.filter(Q=>Q.approved).length:o==="ppo"?i?2:t.runPreset==="standard"?16:4:o==="grpo"&&t.taskset.datasetArtifact?t.runPreset==="standard"?32:16:i?4:1e3))),[R,p]=c.useState(()=>Ut(t.taskset)),[_,x]=c.useState(2),[m,T]=c.useState(()=>Bt(d?.preference.modelId??"")),[V,E]=c.useState(!1),[$,Z]=c.useState(null),[K,ee]=c.useState(7),[M,H]=c.useState(8),[B,G]=c.useState(4),[de,F]=c.useState(el),[ne,J]=c.useState(()=>Wn(t.taskset)),[ae,X]=c.useState(o),[N,q]=c.useState(null),[D,te]=c.useState(!1);return{primaryMethod:a,bootstrap:s,methodOptions:l,quickTest:i,initialDestination:h,availableTrainExamples:j,destinationId:b,setDestinationId:g,baseModelKey:C,setBaseModelKey:k,maxSteps:f,setMaxSteps:S,trainingExamples:y,setTrainingExamples:w,sequenceLength:R,setSequenceLength:p,rank:_,setRank:x,learningRate:m,setLearningRate:T,exportApproved:V,setExportApproved:E,maximumCostUsd:$,setMaximumCostUsd:Z,retentionDays:K,setRetentionDays:ee,rolloutGroupSize:M,setRolloutGroupSize:H,rolloutConcurrency:B,setRolloutConcurrency:G,rolloutMaxOutputTokens:de,setRolloutMaxOutputTokens:F,rftLossMethod:ne,setRftLossMethod:J,method:ae,setMethod:X,prepared:N,setPrepared:q,providerApprovalOpen:D,setProviderApprovalOpen:te}}const kn=4096,nl=4096,Sn=64;function al({baseModelCandidates:t,connection:n,taskset:a,modelId:s=null,destinations:l,initialMethod:o,preferredBaseModel:i=null,busy:r,onClose:u,onStart:h,onPrepare:d,onConfirmPrepared:j,onOpenProviderSettings:b,presentation:g="dialog",runControlId:C,hideActions:k=!1,onReadinessChange:f,onConfigurationChange:S,runPreset:y="custom",hideMethodTabs:w=!1,approvalPresentation:R="inline",configurationContent:p}){const{primaryMethod:_,bootstrap:x,methodOptions:m,quickTest:T,initialDestination:V,availableTrainExamples:E,destinationId:$,setDestinationId:Z,baseModelKey:K,setBaseModelKey:ee,maxSteps:M,setMaxSteps:H,trainingExamples:B,setTrainingExamples:G,sequenceLength:de,setSequenceLength:F,rank:ne,setRank:J,learningRate:ae,setLearningRate:X,exportApproved:N,setExportApproved:q,maximumCostUsd:D,setMaximumCostUsd:te,retentionDays:Q,setRetentionDays:le,rolloutGroupSize:Ae,setRolloutGroupSize:fe,rolloutConcurrency:ue,setRolloutConcurrency:I,rolloutMaxOutputTokens:L,setRolloutMaxOutputTokens:he,rftLossMethod:oe,setRftLossMethod:me,method:v,setMethod:O,prepared:W,setPrepared:pe,providerApprovalOpen:se,setProviderApprovalOpen:ve}=tl({baseModelCandidates:t,preferredBaseModel:i,destinations:l,taskset:a,initialMethod:o,runPreset:y}),{catalog:we,catalogError:Pe,catalogTargets:Te,visibleCatalogModels:Xe,computeTargetId:Ue,modelSearch:mt,setModelSearch:Ee}=Zi({connection:n,destinations:l,initialDestination:V,method:v}),Ne=l.find(P=>P.destinationId===$)??null,Ye=v==="sft"&&_!=="sft"&&x?.method==="sft",Fe=v==="dpo"?a.learningSignals.preferences.filter(P=>P.approved).length:a.learningSignals.demonstrations.filter(P=>P.approved).length,Ze=Gn(a,"frozen_eval"),Ce=t.find(P=>P.selectionKey===K)??null,ze=Ce?.executionOptions.find(P=>P.destinationId===$&&P.methods.includes(v))??null,Ve=Ce?.preference.modelId??"",U=Te.find(P=>P.id===Ue)??null,A=c.useRef(null),ge=we?.models.find(P=>P.selectionKey===K)??null,Re=ge?.compatibilities.find(P=>P.targetId===U?.id&&P.methods.includes(v))??null,z=U?.approvalPolicy??null,pt=U?.executionMode==="provider_native",bt=z?.providerLabel??"provider";c.useEffect(()=>{if(!U||U.destinationId!==$)return;const P=JSON.stringify({destinationId:U.destinationId,defaults:U.defaults,approvalPolicy:U.approvalPolicy});A.current!==P&&(A.current=P,J(U.defaults.loraRank),fe(U.defaults.rolloutGroupSize),I(U.defaults.rolloutConcurrency),he(U.defaults.rolloutOutputTokens),H(U.defaults.maxSteps),te(U.approvalPolicy?.defaultMaximumSpendUsd??null),le(U.approvalPolicy?.defaultRetentionDays??7),U.destinationId==="openpond_managed"&&(X(1e-5),F(4096)))},[$,U,X,H,te,J,le,I,fe,he,F]);const Zn=U?.limits.maximumSequenceLength??kn,ea=U?.limits.maximumOutputTokens??nl,ta=v==="dpo"?Math.max(1,a.learningSignals.preferences.filter(P=>P.approved).length):v==="ppo"?Math.max(1,Math.min(1e3,E)):v==="grpo"&&pt&&a.datasetArtifact?Math.max(1,Math.min(U?.limits.maximumTrainingExamples??E,E)):Math.max(1,Math.min(1e5,E)),na=!z||(!z.exportApprovalRequired||N)&&D!=null&&D>=z.minimumSpendUsd&&D<=z.maximumSpendUsd&&Number.isInteger(Q)&&Q>=z.minimumRetentionDays&&Q<=z.maximumRetentionDays,Jt=U?.methods.includes(v)??Ne?.methods.includes(v)??!1,aa=a.capabilities.compatibleMethods.includes(v)||x?.method===v,gt=!!(a.readiness?.ready&&Jt&&Ne?.available&&Ne.methods.includes(v)&&aa&&ze?.available&&Re?.state!=="unsupported"&&Re?.state!=="compute_setup_required"&&Ce?.preference.source!=="local"),et=gt&&na,tt=a.readiness?.ready?Jt?Re?.state==="unsupported"||Re?.state==="compute_setup_required"?Re.reason??"The selected Model and compute target are not ready.":Ce?ze?.available?Ne?.methods.includes(v)?Ne?.unavailableReason??null:`${Je($)} does not execute ${v.toUpperCase()}.`:ze?.unavailableReason??"The selected base model cannot run on this compute destination.":`Choose starting weights compatible with ${Je($)} and ${v.toUpperCase()}.`:`${v.toUpperCase()} is the primary recommendation but no compatible execution backend is available here.${x?" Choose the optional SFT trajectory bootstrap to run the local precursor.":""}`:"The Taskset must pass environment, grader, and data readiness before training.",ft=tt??(z?.exportApprovalRequired&&!N?`Approve the bounded train-split export before launching ${bt}.`:z&&(D==null||D<z.minimumSpendUsd||D>z.maximumSpendUsd)?`Set a ${bt} cap from $${z.minimumSpendUsd.toFixed(2)} through $${z.maximumSpendUsd.toFixed(2)}.`:z&&(!Number.isInteger(Q)||Q<z.minimumRetentionDays||Q>z.maximumRetentionDays)?"Choose a provider retention record from 1 through 30 days.":null),nt=Ji({method:v,taskset:a,destinationId:$,baseModelId:Ve,maxSteps:M,trainingExamples:B,rftLossMethod:oe,executionMode:U?.executionMode,catalogModel:ge}),at={exportApproved:z?N:!0,maximumCostUsd:z?D:0,retentionDays:z?Q:null,region:null},xt=JSON.stringify({modelId:s,destinationId:$,recipe:nt,approval:at}),ye=W?.configurationKey===xt?W.value:null;async function Wt(){if(!et)return;if(z?.preparationRequired&&!ye){const Y=await d($,nt,at);Y&&pe({configurationKey:xt,value:Y});return}(z?.preparationRequired&&ye?await j(ye,D??0):await h($,nt,at))&&(ve(!1),u())}async function Qt(){if(gt){if(z&&R==="dialog"){ve(!0);return}await Wt()}}function sa(P,Y=Te.find(yt=>yt.destinationId===P)){Z(P),ee(yt=>yn(t,yt,P,v)),J(Y?.defaults.loraRank??2),fe(Y?.defaults.rolloutGroupSize??4),I(Y?.defaults.rolloutConcurrency??1),he(Y?.defaults.rolloutOutputTokens??Sn),X(P==="openpond_managed"?1e-5:Bt(Ve)),te(Y?.approvalPolicy?.defaultMaximumSpendUsd??null),le(Y?.approvalPolicy?.defaultRetentionDays??7),q(!1),v==="grpo"?(H(Y?.defaults.maxSteps??8),a.datasetArtifact&&Y?.executionMode==="provider_native"&&G(Math.max(1,Math.min(E,Y.limits.maximumTrainingExamples??16))),F(Math.min(Y?.limits.maximumSequenceLength??kn,Math.max(512,Ut(a,Y?.limits.maximumSequenceLength))))):F(Ut(a,Y?.limits.maximumSequenceLength))}function ia(P){if(O(P),pe(null),ee(Y=>yn(t,Y,$,P)),P==="grpo"){H(8),pt&&a.datasetArtifact&&F(Y=>Math.max(512,Y)),G(Math.max(1,Math.min(E,a.datasetArtifact?16:1e3)));return}if(H(T?1:P==="dpo"?4:2),P==="dpo"){G(Math.max(1,Math.min(a.learningSignals.preferences.filter(Y=>Y.approved).length,T?2:64)));return}if(P==="ppo"){G(Math.max(1,Math.min(E,T?2:4)));return}G(Math.max(1,Math.min(E,T?4:32)))}const qe=ye?.plan.estimatedCostUsd??null,jt=r?ye?"Launching…":z?.preparationRequired?"Preparing…":"Starting…":ye&&qe!=null?`Launch $${qe.toFixed(2)} job`:z?.preparationRequired?"Prepare exact quote":"Start training",He=R==="dialog"&&z?gt:et,vt=R==="dialog"&&z?"Run":jt;c.useEffect(()=>{U&&sa(U.destinationId,U)},[U?.id,U?.destinationId]),c.useEffect(()=>{f?.({ready:He,reason:He?null:R==="dialog"&&z?tt??"This setup is unavailable.":ft??"This setup is unavailable.",actionLabel:vt})},[R,tt,z,ft,f,vt,He]),c.useEffect(()=>{S?.({baseModel:Ce?.preference??null,method:v,destinationId:$,recipe:nt,approval:at})},[xt,S]);const Xt=z?e.jsx(Fi,{approvalPolicy:z,providerLabel:bt,method:v,busy:r,exportApproved:N,maximumCostUsd:D,retentionDays:Q,onManageProvider:b?()=>{R==="dialog"?ve(!1):u(),b()}:void 0,onExportApprovedChange:q,onMaximumCostChange:te,onRetentionDaysChange:le}):null,Yt=e.jsxs("section",{className:`training-dialog training-start-dialog${g==="embedded"?" embedded":""}${w?" hide-method-tabs":""}`,role:g==="dialog"?"dialog":"region","aria-modal":g==="dialog"?"true":void 0,"aria-label":"Start training",onMouseDown:P=>P.stopPropagation(),children:[g==="dialog"?e.jsxs("div",{className:"training-dialog-header",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Start training"}),e.jsx("p",{children:a.name})]}),e.jsx("button",{type:"button","aria-label":"Close start training",disabled:r,onClick:u,children:e.jsx(Me,{size:16})})]}):null,w?null:e.jsx(zi,{busy:r,method:v,options:m,onSelect:ia}),e.jsx(Bi,{busy:r,catalog:we,catalogError:Pe,selectedComputeTarget:U,modelSearch:mt,onModelSearchChange:Ee,baseModelKey:K,baseModelCandidates:t,destinationId:$,method:v,onBaseModelChange:(P,Y)=>{ee(P),X(Bt(Y))},visibleCatalogModels:Xe,selectedCatalogCompatibility:Re,selectedCatalogModel:ge,configurationContent:p,inlineProviderApproval:R==="inline"?Xt:null}),e.jsx(Vi,{method:v,trainingExamples:B,availableTrainExamples:E,approvedExamples:Fe,evaluationExamples:Ze,preparedQuote:qe,selectedComputeTarget:U,approvalPresentation:R,maximumCostUsd:D,providerManaged:pt,storagePath:null}),R==="inline"&&ye?e.jsx(qi,{prepared:ye,preparedQuote:qe,maximumCostUsd:D}):null,Ye&&x?e.jsxs("div",{className:"training-bootstrap-limitations",children:[e.jsx("strong",{children:"Supervised precursor"}),e.jsx("p",{children:"This SFT run teaches the approved tool trajectories. It does not replace reinforcement training."}),e.jsx("ul",{children:x.limitations.map(P=>e.jsx("li",{children:P},P))})]}):null,e.jsx(Hi,{method:v,trainingExamples:B,maximumTrainingExamples:ta,maxSteps:M,sequenceLength:de,maximumSequenceLength:Zn,rolloutMaxOutputTokens:L,maximumOutputTokens:ea,defaultRolloutOutputTokens:U?.defaults.rolloutOutputTokens??Sn,rank:ne,learningRate:ae,rftLossMethod:oe,rolloutGroupSize:Ae,rolloutConcurrency:ue,onTrainingExamplesChange:G,onMaxStepsChange:H,onSequenceLengthChange:F,onRolloutMaxOutputTokensChange:he,onRankChange:J,onLearningRateChange:X,onRftLossMethodChange:me,onRolloutGroupSizeChange:fe,onRolloutConcurrencyChange:I}),He?Ne?.nonProduction?e.jsx("p",{className:"training-start-note",children:"This local worker is an experimental correctness run. It does not claim useful model quality."}):null:e.jsx("div",{className:"training-banner error training-dialog-error",children:R==="dialog"&&z?tt??"This setup is unavailable.":ft??"This setup is unavailable."}),k?e.jsx("button",{id:C,hidden:!0,type:"button",disabled:r||!He,onClick:()=>{Qt()},children:vt}):e.jsxs("div",{className:"training-dialog-actions",children:[e.jsx("button",{className:"training-button secondary",type:"button",disabled:r,onClick:u,children:"Cancel"}),e.jsx("button",{id:C,className:"training-button",type:"button",disabled:r||!et,onClick:()=>{Qt()},children:jt})]})]}),la=e.jsx(Ui,{open:R==="dialog"&&!!z&&se,busy:r,destinationId:$,baseModelId:Ve,approvalFields:Xt,prepared:ye,preparedQuote:qe,compatible:et,actionLabel:jt,onClose:()=>ve(!1),onConfirm:()=>{Wt()}});return g==="embedded"?e.jsxs(e.Fragment,{children:[Yt,la]}):e.jsx("div",{className:"training-dialog-backdrop",role:"presentation",onMouseDown:r?void 0:u,children:Yt})}const sl=[{id:"dataset",label:"Taskset"},{id:"method",label:"Training method"},{id:"configuration",label:"Model and compute"}];function il({activeStep:t,steps:n,onStepChange:a}){return e.jsx("ol",{className:"model-setup-step-list","aria-label":"Run setup progress",children:n.map((s,l)=>e.jsx("li",{className:[t===s.id?"active":"",s.complete?"complete":""].filter(Boolean).join(" "),children:e.jsxs("button",{"aria-current":t===s.id?"step":void 0,type:"button",onClick:()=>a(s.id),children:[e.jsxs("span",{className:"model-setup-step-label",children:[l+1,". ",s.label]}),e.jsx("span",{className:"model-setup-step-segment","aria-hidden":"true"})]})},s.id))})}const ll=["sft","dpo","grpo","ppo"];function Qn(t,n,a,s){const l=new Date().toISOString(),o=crypto.randomUUID();return{schemaVersion:"openpond.modelProject.v1",id:a??`model_${o}`,profileId:t,name:s?.trim()||"Model #1",objective:n,defaultBaseModel:null,defaultDestinationId:null,createdAt:l,updatedAt:l}}function ol(t){return t.tasksetRef?t.method?"configuration":"method":"dataset"}function rl(t,n,a,s){return t==="dataset"?!!a:t==="method"?!!n.method:s}function Xn(t){let n=t.length;for(const a of t){const s=/^Model #(\d+)$/.exec(a.name.trim());s&&(n=Math.max(n,Number(s[1])))}return`Model #${n+1}`}function dl(t,n){const a=new Date().toISOString();return{schemaVersion:"openpond.modelRunDraft.v1",id:`run_draft_${crypto.randomUUID()}`,profileId:t,modelId:n,status:"draft",title:"Run draft",datasetMode:null,tasksetRef:null,datasetCreationId:null,buildIntent:null,buildSpecification:null,baseModel:null,method:null,destinationId:null,managedRolloutPlacement:"local",runPreset:null,recipe:null,createdAt:a,updatedAt:a}}function Nn(t,n){return{...t,datasetMode:"existing",tasksetRef:{id:n.id,revision:n.revision,contentHash:n.contentHash},buildIntent:t.buildIntent??ul(n),updatedAt:new Date().toISOString()}}function cl(t){const n=new Date().toISOString();return{...t,id:`run_draft_${crypto.randomUUID()}`,status:"draft",title:"Run draft",createdAt:n,updatedAt:n}}function ul(t){return t.capabilities.supportedSignals.includes("preference")||t.capabilities.compatibleMethods.includes("dpo")?"preferences":t.capabilities.supportedSignals.includes("reward")||t.capabilities.compatibleMethods.includes("grpo")||t.capabilities.compatibleMethods.includes("ppo")?"verifiable_reward":t.capabilities.supportedSignals.includes("label")?"rubric":"demonstrations"}function At(t,n){const{updatedAt:a,...s}=t,{updatedAt:l,status:o,...i}=n;return JSON.stringify({project:s,draft:i})}function hl(t,n,a,s){if(!t.name.trim())return"Name this Model.";if(!n.datasetMode)return"Choose a Taskset.";if(!a)return"Choose a Taskset to enable Run.";if(!n.method)return"Choose a training method.";const l=a.readiness?.methodReadiness.find(o=>o.method===n.method);return l?.status==="needs_dataset_work"?l.reasons[0]??"Resolve Taskset readiness for this method.":n.runPreset?n.baseModel?n.destinationId?s.ready?null:s.reason??"Complete the launch checks.":"Choose a compatible destination.":"Choose a base model.":n.method==="grpo"||n.method==="ppo"?"Choose an experiment size.":"Choose a run size."}function ml(t){const n=t.downloads.length?t.downloads.map(l=>`${l.label}: ${Rn(l.diskImpactBytes)} (${l.state})`).join("; "):"No downloads",a=t.dataMovement.length?t.dataMovement.map(l=>`${l.label}: ${l.direction}${l.bytes==null?"":` ${Rn(l.bytes)}`}`).join("; "):"No remote data movement",s=t.quoteUsd==null?"No provider spend quoted":`Quote $${t.quoteUsd.toFixed(2)}; maximum $${t.maximumSpendUsd?.toFixed(2)??"not set"}`;return[`${xl(t.state)}${t.reason?` — ${t.reason}`:""}.`,`Downloads: ${n}.`,`Data: ${a}.`,`${s}. Retention: ${t.retentionDays==null?"local policy":`${t.retentionDays} days`}.`,"No side effects have started. Confirming may begin downloads, connections, uploads, provisioning, or spend."].join(" ")}function pl(t,n){return ll.map(a=>{const s=t?.readiness?.methodReadiness.find(u=>u.method===a),l=!!(t&&(t.capabilities.compatibleMethods.includes(a)||t.readiness?.trainingPath?.bootstrap?.method===a)),o=n.some(u=>u.available&&u.methods.includes(a)),i=s?.status==="needs_dataset_work"?"Needs Taskset work":l?o?s?.status==="recommended"?"Recommended":"Compatible":"Destination unavailable":"Incompatible Taskset",r=s?.reasons[0]??(l?o?fl(a):`No configured destination currently executes ${a.toUpperCase()}.`:`This Taskset revision does not contain the evidence required for ${a.toUpperCase()}.`);return{method:a,state:i,reason:r,executionTargets:bl(a,n),available:l&&s?.status!=="needs_dataset_work"&&o}})}function bl(t,n){return[gl(t,"openpond_managed","OpenPond Managed",n)]}function gl(t,n,a,s){const l=s.find(r=>r.destinationId===n),o="OpenPond Managed",i=!!l?.methods.includes(t);return{id:n,label:a,available:!!(l?.available&&i),reason:l?i?l.unavailableReason??`${o} is not available in this environment.`:`${o} does not execute ${t.toUpperCase()}.`:`${o} capabilities have not loaded.`}}function fl(t){return t==="sft"?"Imitate approved responses with assistant-only loss.":t==="dpo"?"Increase the margin between chosen and rejected responses.":t==="grpo"?"Sample grouped responses and optimize executable rewards.":"Optimize a policy with a separately tracked value model."}function Yn(t){return t==="grpo"||t==="ppo"?[{id:"small_experiment",label:"Quick test",description:"Bound prompts, rollouts, output tokens, steps, time, and spend."},{id:"standard",label:"Recommended",description:"Use the Taskset-aware recommended online budgets."},{id:"custom",label:"Custom",description:"Set each rollout and optimizer limit explicitly."}]:[{id:"small",label:"Quick test",description:"A bounded LoRA experiment with independent frozen evaluation."},{id:"standard",label:"Recommended",description:"Use Taskset-aware recommended examples and optimizer limits."},{id:"custom",label:"Custom",description:"Set examples, steps, sequence length, rank, time, and spend."}]}function Cn(t,n){return Yn(t).find(a=>a.id===(n??"standard"))}function xl(t){return t.replaceAll("_"," ").replace(/^\w/,n=>n.toUpperCase())}function Rn(t){return t<1024?`${t} B`:t<1024**2?`${(t/1024).toFixed(1)} KB`:t<1024**3?`${(t/1024**2).toFixed(1)} MB`:`${(t/1024**3).toFixed(1)} GB`}const jl="model-build-run-control";function vl({activeStep:t,onStepChange:n,draft:a,setDraft:s,selectedTaskset:l,methodCards:o,tasksets:i,baseModelCandidates:r,destinations:u,connection:h,training:d,canRun:j,onSelectTaskset:b,onOpenDatasetBuilder:g,onLaunchStateChange:C,onConfigurationChange:k,onOpenProviderSettings:f,onFinished:S}){return e.jsxs(e.Fragment,{children:[e.jsx(il,{activeStep:t,steps:sl.map(y=>({...y,complete:rl(y.id,a,l,j)})),onStepChange:n}),t==="dataset"?e.jsxs("section",{className:"model-build-section",children:[e.jsx("div",{className:"model-build-section-heading",children:e.jsxs("div",{children:[e.jsx("h2",{children:"Choose a Taskset"}),e.jsx("p",{children:"Use a ready Taskset, or create one conversationally in Chat."})]})}),e.jsx("div",{className:"model-build-dataset-step",children:e.jsxs("div",{className:"model-build-existing-dataset",children:[e.jsxs("div",{className:"model-build-field",children:[e.jsx("span",{children:"Taskset revision"}),e.jsx(De,{label:"Taskset revision",value:l?.id??"",options:[{value:"",label:i.length?"Select a Taskset":"No Tasksets yet",disabled:i.length===0},...i.map(y=>({value:y.id,label:`${y.name} · r${y.revision} · ${y.readiness?.ready?"ready":"needs work"}`}))],onChange:y=>{const w=i.find(R=>R.id===y);w&&b(w)}})]}),e.jsx("button",{className:"training-button secondary",type:"button",onClick:g,children:a.datasetMode==="build"?"Continue building Taskset":"Build a Taskset"})]})})]}):t==="method"?e.jsxs("section",{className:"model-build-section",children:[e.jsx("div",{className:"model-build-section-heading",children:e.jsx("h2",{children:"Choose a training method"})}),e.jsx("div",{className:"model-build-method-grid",children:o.map(y=>e.jsxs("button",{className:a.method===y.method?"model-build-method selected":"model-build-method",type:"button",disabled:!y.available,title:y.available?void 0:y.reason,onClick:()=>{s(w=>({...w,method:y.method,runPreset:"standard",recipe:null,updatedAt:new Date().toISOString()})),n("configuration")},children:[e.jsxs("span",{children:[e.jsx("strong",{children:y.method.toUpperCase()}),e.jsx("em",{children:y.state})]}),e.jsx("small",{children:y.reason}),e.jsx("span",{className:"model-build-method-targets","aria-label":"Execution targets",children:y.executionTargets.map(w=>e.jsx("span",{"aria-label":`${w.label}: ${w.available?"available":w.reason}`,className:w.available?"model-build-target-pill available":"model-build-target-pill unavailable",title:w.available?void 0:w.reason,children:w.label},w.id))}),e.jsx("span",{className:"training-choice-indicator","aria-hidden":"true"})]},y.method))})]}):e.jsxs("section",{className:"model-build-section",children:[e.jsx("div",{className:"model-build-section-heading",children:e.jsxs("div",{children:[e.jsx("h2",{children:"Choose a model"}),e.jsx("p",{children:"Select the starting model and where it will train."})]})}),l&&(a.method==="sft"||a.method==="dpo"||a.method==="grpo"||a.method==="ppo")?e.jsx(al,{baseModelCandidates:r,connection:h,taskset:l,modelId:a.modelId,destinations:u,initialMethod:a.method,preferredBaseModel:a.baseModel,busy:["prepare-training","prepare-model-run","start-prepared-training","start-training","start-model-run"].includes(d.busyAction??""),busyAction:d.busyAction,presentation:"embedded",hideActions:!0,runControlId:jl,runPreset:a.runPreset??"standard",hideMethodTabs:!0,approvalPresentation:"dialog",configurationContent:e.jsxs("details",{className:"model-run-options",children:[e.jsxs("summary",{children:[e.jsx("span",{children:"Training configuration"}),e.jsx("strong",{children:Cn(a.method,a.runPreset)?.label??"Recommended"})]}),e.jsxs("div",{className:"model-build-field",children:[e.jsx("span",{children:"Training budget"}),e.jsx(De,{label:"Training budget",value:a.runPreset??"standard",options:Yn(a.method).map(y=>({value:y.id,label:y.label})),onChange:y=>s(w=>({...w,runPreset:y,recipe:null,updatedAt:new Date().toISOString()}))}),e.jsx("small",{children:Cn(a.method,a.runPreset)?.description??"Use Taskset-aware recommended limits."})]}),a.destinationId==="openpond_managed"?e.jsxs("div",{className:"model-build-field",children:[e.jsx("span",{children:"Rollout execution"}),e.jsx(De,{label:"Rollout execution",value:a.managedRolloutPlacement??"local",options:[{value:"local",label:"This desktop"},{value:"remote",label:"Hosted Sandboxes"}],onChange:y=>s(w=>({...w,managedRolloutPlacement:y==="remote"?"remote":"local",updatedAt:new Date().toISOString()}))}),e.jsx("small",{children:"This desktop keeps local integrations and provider credentials on this device. Hosted Sandboxes can run unattended."})]}):null]}),onReadinessChange:C,onConfigurationChange:k,onClose:()=>{},onOpenProviderSettings:f,onPrepare:(y,w,R)=>d.actions.prepareTraining({modelId:a.modelId,tasksetId:l.id,destinationId:y,recipe:w,exportApproved:R.exportApproved,retentionDays:R.retentionDays,region:R.region}),onConfirmPrepared:async(y,w)=>await d.actions.startPreparedTraining({planId:y.plan.id,bundleId:y.bundle.id,maximumCostUsd:w})?(await d.actions.saveModelRunDraft({...a,status:"launched",updatedAt:new Date().toISOString()}),await S(a.modelId,l.id),!0):!1,onStart:async(y,w,R)=>await d.actions.startTraining({modelId:a.modelId,tasksetId:l.id,destinationId:y,recipe:w,...R})?(await d.actions.saveModelRunDraft({...a,status:"launched",updatedAt:new Date().toISOString()}),await S(a.modelId,l.id),!0):!1},`${l.id}:${l.revision}:${a.method}:${a.runPreset}`):e.jsx("div",{className:"model-build-empty",children:"Choose a Taskset and training method to select a model."})]})]})}function In({connection:t,initialObjective:n,initialModelId:a,initialName:s,initialDraftId:l,initialTasksetId:o,profileId:i,training:r,onCancel:u,onFinished:h,onNameChange:d,onSectionChange:j,onSaved:b,renderDatasetBuilder:g,onOpenProviderSettings:C}){const k=r.payload,f=c.useMemo(()=>k?.modelRunDrafts.find(I=>(I.status==="draft"||I.status==="ready_to_run")&&I.id===l)??null,[l,k?.modelRunDrafts]),S=k?.modelProjects.find(I=>I.id===a)??null,y=k?.tasksets.find(I=>I.id===o)??null,w=c.useMemo(()=>!a||l?null:[...k?.modelRunDrafts??[]].filter(I=>I.modelId===a&&I.status==="launched"&&k?.tasksets.some(L=>L.id===I.tasksetRef?.id&&L.revision===I.tasksetRef.revision&&L.contentHash===I.tasksetRef.contentHash)).sort((I,L)=>L.updatedAt.localeCompare(I.updatedAt))[0]??null,[l,a,k?.modelRunDrafts,k?.tasksets]),R=c.useRef(null);R.current||(R.current=S??Qn(i,n,a,s??Xn(k?.modelProjects??[])));const[p,_]=c.useState(R.current),x=c.useRef(null);if(!x.current){const I=f??(w?cl(w):dl(i,R.current.id));x.current=y?Nn(I,y):I}const[m,T]=c.useState(x.current),[V,E]=c.useState(()=>ol(x.current)),[$,Z]=c.useState(x.current.datasetMode==="build"&&!x.current.tasksetRef),[K,ee]=c.useState(f&&S?At(S,f):""),{confirmAction:M,confirmDialog:H,resolveConfirmDialog:B}=va(),[G,de]=c.useState({ready:!1,reason:"Select a Taskset.",actionLabel:"Run"}),[F,ne]=c.useState({exportApproved:!0,maximumCostUsd:0,retentionDays:null,region:null}),J=k?.tasksets.find(I=>I.id===m.tasksetRef?.id&&I.revision===m.tasksetRef.revision&&I.contentHash===m.tasksetRef.contentHash)??null,ae=c.useMemo(()=>pl(J,k?.destinations??[]),[J,k?.destinations]),X=At(p,m)!==K,N=!!r.busyAction,q=hl(p,m,J,G),D=!N&&q===null;c.useEffect(()=>{j?.($?"dataset":"run")},[$,j]),c.useEffect(()=>{d?.(p.name)},[d,p.name]),c.useEffect(()=>{if(!X)return;const I=L=>{L.preventDefault(),L.returnValue=""};return window.addEventListener("beforeunload",I),()=>window.removeEventListener("beforeunload",I)},[X]),c.useEffect(()=>{!m.method||ae.find(L=>L.method===m.method)?.available||T(L=>({...L,method:null,recipe:null,runPreset:null,baseModel:null,destinationId:null,updatedAt:new Date().toISOString()}))},[m.method,ae]),c.useEffect(()=>{!m.method||m.runPreset||T(I=>({...I,runPreset:"standard",updatedAt:new Date().toISOString()}))},[m.method,m.runPreset]);const te=c.useCallback(I=>{ne(I.approval),T(L=>({...L,baseModel:I.baseModel,method:L.method??I.method,destinationId:I.destinationId,recipe:I.recipe,updatedAt:new Date().toISOString()}))},[]),Q=c.useCallback(I=>de(I),[]);async function le(I=!0){const L=new Date().toISOString(),he={...p,updatedAt:L},oe=await r.actions.saveModelProject(he);if(!oe)return null;const me={...m,status:q===null?"ready_to_run":"draft",updatedAt:L},v=await r.actions.saveModelRunDraft(me);return v?(_(oe),T(v),ee(At(oe,v)),I&&await b?.(v.modelId),v):null}async function Ae(){X&&!await M({title:"Discard run setup?",body:"Your Model and run setup changes will be discarded.",confirmLabel:"Discard",cancelLabel:"Keep editing",tone:"danger"})||u()}async function fe(){if(!D||!J)return;const I=await le(!1);if(!I)return;const L=await r.actions.prepareModelRun(I.id,{maximumSpendUsd:F.maximumCostUsd,retentionDays:F.retentionDays});!L||!await M({title:"Review and start training",body:ml(L),confirmLabel:L.quoteUsd?`Approve up to $${(L.maximumSpendUsd??L.quoteUsd).toFixed(2)} and run`:"Start exact run",cancelLabel:"Back"})||!await r.actions.startModelRun(I.id,{maximumSpendUsd:F.maximumCostUsd,retentionDays:F.retentionDays,exportApproved:F.exportApproved})||await h(I.modelId,J.id)}function ue(I){Z(!1),E("method"),T(L=>Nn(L,I))}return $?e.jsxs("main",{className:"model-build-page model-build-dataset-page","aria-label":"New Taskset",children:[e.jsxs("header",{className:"model-build-header",children:[e.jsx("div",{children:e.jsx("h1",{children:"New Taskset"})}),e.jsx("button",{className:"training-button secondary",type:"button",onClick:()=>{Z(!1),T(I=>({...I,datasetMode:null,updatedAt:new Date().toISOString()}))},children:"Back to run setup"})]}),g(I=>{const L=k?.tasksets.find(he=>he.id===I);L?ue(L):r.refresh().then(he=>{const oe=he?.tasksets.find(me=>me.id===I);oe&&ue(oe)})},()=>{Z(!1),T(I=>({...I,datasetMode:"existing",tasksetRef:null,updatedAt:new Date().toISOString()}))})]}):e.jsxs(e.Fragment,{children:[e.jsxs("main",{className:"model-build-page","aria-label":"Run setup",children:[e.jsx($i,{project:p,persisted:!!S,busy:N,dirty:X,canRun:D,pageReason:q,actionLabel:G.actionLabel,onProjectChange:_,onCancel:()=>{Ae()},onSave:()=>{le()},onLaunch:()=>{fe()}}),e.jsx(vl,{activeStep:V,onStepChange:E,draft:m,setDraft:T,selectedTaskset:J,methodCards:ae,tasksets:k?.tasksets??[],baseModelCandidates:k?.baseModelCandidates??[],destinations:k?.destinations??[],connection:t,training:r,canRun:D,onSelectTaskset:ue,onOpenDatasetBuilder:()=>{T(I=>({...I,datasetMode:"build",tasksetRef:null,updatedAt:new Date().toISOString()})),Z(!0)},onLaunchStateChange:Q,onConfigurationChange:te,onOpenProviderSettings:C,onFinished:h})]}),e.jsx(ya,{state:H,onResolve:B})]})}function yl({account:t,closeDetailKind:n,closeDetailRequestId:a,onAnswerQuestion:s,onApplyCandidate:l,onApprove:o,onCancel:i,candidateReview:r,onCandidateReviewChange:u,onDetailOpenChange:h,onSkillSelectionChange:d,onNewModel:j,onOpenPullRequest:b,onOpenCandidateFiles:g,onOpenRunConversation:C,onPause:k,onReconcilePullRequest:f,onRejectCandidate:S,onResume:y,onRevise:w,profileView:R,training:p}){const _=R.payload?.profile??null,x=_?.activeProfile??"default",m=Va({connection:R.connection,profileId:x});Zt(m.error),Zt(p.training.error);const T=c.useMemo(()=>vi(p.training.payload),[p.training.payload]),V=c.useMemo(()=>m.runs.filter(v=>v.target.kind==="agent"&&["ready_local","released","published_hosted"].includes(v.state)).map(v=>`${v.id}:${v.revision}:${v.state}`).sort().join("|"),[m.runs]),[E,$]=c.useState(()=>typeof window>"u"?"models":en(window.location.search)),[Z,K]=c.useState(null),[ee,M]=c.useState(null),[H,B]=c.useState(!1),[G,de]=c.useState(null),[F,ne]=c.useState(null),[J,ae]=c.useState("run"),[X,N]=c.useState(null),[q,D]=c.useState(null),te=c.useMemo(()=>On({profile:_,training:p.training.payload,runs:m.runs}),[m.runs,_,p.training.payload]),Q=c.useMemo(()=>te.filter(v=>v.kind==="model"),[te]),le=Q.find(v=>v.key===Z)??null;c.useEffect(()=>{if(!R.connection)return;let v=!1;return lt.bootstrap(R.connection).then(O=>{v||R.onPayload(O)}).catch(O=>{v||R.onError(O instanceof Error?O.message:String(O))}),()=>{v=!0}},[R.connection,R.onError,R.onPayload]),c.useEffect(()=>{const v=()=>{K(null),M(null),$(en(window.location.search))};return window.addEventListener("popstate",v),window.addEventListener(St,v),()=>{window.removeEventListener("popstate",v),window.removeEventListener(St,v)}},[]),c.useEffect(()=>{const v=ka(window.location.search,E),O=`${window.location.pathname}${v}${window.location.hash}`,W=`${window.location.pathname}${window.location.search}${window.location.hash}`;O!==W&&(window.history.replaceState(window.history.state,"",O),window.dispatchEvent(new Event(St)))},[E]),c.useEffect(()=>{T&&m.refresh()},[m.refresh,T]),c.useEffect(()=>{if(!V||!R.connection)return;let v=!1;return lt.bootstrap(R.connection).then(O=>{v||R.onPayload(O)}).catch(O=>{v||R.onError(O instanceof Error?O.message:String(O))}),()=>{v=!0}},[V,R.connection,R.onError,R.onPayload]),c.useEffect(()=>{Z&&!te.some(v=>v.key===Z)&&K(null)},[Z,te]),c.useEffect(()=>{d(null)},[d]),c.useEffect(()=>{if(!(a<=0)){if(K(null),M(null),n==="dataset"){$("tasksets");return}$("models")}},[n,a]),c.useEffect(()=>{N(null)},[p.launchRequest?.id]),c.useEffect(()=>{if(p.launchRequest){h({kind:"model",kindLabel:"Models",kindOnSelect:()=>document.getElementById("model-run-editor-cancel")?.click(),workproductLabel:null,segments:[{label:X??"Model"},...J==="dataset"?[{label:"New Taskset"}]:[]]});return}if(E==="tasksets"){h(ee?{kind:"dataset",kindLabel:"Tasksets",workproductLabel:[...p.training.payload?.tasksets??[],...p.training.payload?.modelTasksets??[]].find(v=>v.id===ee)?.name??"Taskset",segments:[]}:null);return}if(E!=="models"){h(null);return}le||h(null)},[E,h,le,ee,J,X,p.launchRequest,p.training.payload?.modelTasksets,p.training.payload?.tasksets]),c.useEffect(()=>()=>h(null),[h]);function Ae(v){const O=te.find(se=>se.kind==="model"&&se.id===v);if(!O)return;const W=Qe(O,m.runs,p.training.payload),pe=W.find(se=>se.current)??W.find(se=>se.lineage.promotable)??null;pe?.taskset&&p.onChatWithModel(Ft({modelId:pe.lineage.id,taskset:pe.taskset}))}function fe(){ne("source"),M(null),$("tasksets")}function ue(){ne(null)}function I(v){const O=v?`Help me improve the ${v.name} Taskset.`:"Help me create a Taskset.";R.onSkillCommand?.(`$openpond-taskset-authoring ${O}`,"openpond"),ue()}function L(v){ne(null),K(null),$("tasksets"),M(v)}function he(v){ae("run"),K(null),M(null),$("models"),j(v)}async function oe(v){const O={...Qn(x,v.description,void 0,v.name),defaultBaseModel:v.defaultBaseModel},W=await p.training.actions.saveModelProject(O);return W?(B(!1),$("models"),K(Ie("model",W.id)),v.purpose==="benchmark"&&de({modelId:W.id,model:v.benchmarkModel??p.defaultModel}),R.onToast?.(`${W.name} created.`,"success"),!0):!1}const me=c.useCallback(()=>K(null),[]);return e.jsxs(Fs,{activeTab:E,showHeader:!p.launchRequest&&!le&&!ee,onCreateDataset:fe,onCreateModel:()=>B(!0),children:[E==="tasksets"?e.jsx(oi,{defaultModel:p.defaultModel,runs:m.runs,selectedId:ee,state:p.training.payload,training:p.training,onToast:(v,O)=>R.onToast?.(v,O)??0,onSelectedIdChange:M,onImproveInChat:v=>I(v),onTrainModel:he,onOpenFiles:v=>{p.onSelectedTasksetIdChange(v),p.onOpenTasksetFiles()}}):E==="serving"?e.jsx(Ai,{state:p.training.payload}):E==="usage"?e.jsx(_i,{account:t,connection:R.connection,onError:R.onError,onOpenSourceSession:C}):p.launchRequest&&p.training.payload?e.jsx(In,{connection:R.connection,initialObjective:p.launchRequest.objective,initialTasksetId:p.launchRequest.initialTasksetId,profileId:x,training:p.training,onCancel:()=>{p.onLaunchHandled(p.launchRequest.id)},onFinished:async(v,O)=>{p.onSelectedTasksetIdChange(O),p.onDetailTasksetIdChange(O),p.onLaunchHandled(p.launchRequest.id),K(Ie("model",v)),$("models"),await m.refresh()},onNameChange:N,onSectionChange:ae,onSaved:async v=>{p.onLaunchHandled(p.launchRequest.id),K(Ie("model",v)),$("models")},onOpenProviderSettings:p.onOpenProviderSettings,renderDatasetBuilder:(v,O)=>e.jsx(Mn,{onOpenChat:()=>I(),onUseExistingDataset:O})}):le?e.jsx(Us,{connection:R.connection,profile:_,runs:m.runs,training:p.training,workproduct:le,onAnswerQuestion:s,onApplyCandidate:l,onApprove:o,onCancel:i,candidateReview:r,onCandidateReviewChange:u,onChatWithModel:p.onChatWithModel,onOpenPullRequest:b,onOpenCandidateFiles:g,onOpenConversation:C,onClose:me,onLocationChange:h,onRenameAgent:()=>{},onOpenDataset:v=>{K(null),M(v),$("tasksets")},onPause:k,onReconcilePullRequest:f,onRejectCandidate:S,onResume:y,onRevise:w,renderModelRunEditor:({initialTasksetId:v,draftId:O,modelId:W,modelName:pe,onCancel:se,onFinished:ve,onSectionChange:we})=>e.jsx(In,{connection:R.connection,initialModelId:W,initialName:pe,initialDraftId:O??void 0,initialObjective:le.description,initialTasksetId:v??void 0,profileId:x,training:p.training,onCancel:se,onFinished:async()=>{await m.refresh(),await ve()},onSectionChange:we,onOpenProviderSettings:p.onOpenProviderSettings,renderDatasetBuilder:(Pe,Te)=>e.jsx(Mn,{onOpenChat:()=>I(),onUseExistingDataset:Te})}),onStartAgentChange:()=>{},onToast:p.onToast,benchmarkDefaultModel:p.defaultModel,benchmarkProviderSettings:p.providerSettings,initialBenchmarkModel:G?.modelId===le.id?G.model:null,initialBenchmarkOpen:G?.modelId===le.id,onInitialBenchmarkOpenConsumed:()=>de(null)}):e.jsx(Mi,{activeProfileId:x,items:Q,loading:p.training.loading&&!Q.length,providerSettings:p.providerSettings,runs:m.runs,state:p.training.payload,onSelect:K,onUseModel:Ae}),H?e.jsx(ui,{baseModelCandidates:p.training.payload?.baseModelCandidates??[],busy:p.training.busyAction==="save-model-project",defaultBenchmarkModel:p.defaultModel,initialName:Xn(p.training.payload?.modelProjects??[]),onClose:()=>B(!1),onCreate:oe,onManageModels:()=>{B(!1),p.onOpenTrainingSettings()},providerSettings:p.providerSettings}):null,F==="source"?e.jsx(La,{onClose:ue,onSelect:v=>{if(v==="build"){I();return}ne(v)}}):null,F==="huggingface"?e.jsx(Ba,{onBack:()=>ne("source"),onClose:ue,onImported:async v=>{await p.training.refresh(),L(v)},onOpenDatasetStorageSettings:()=>{ne(null),p.onOpenDatasetStorageSettings()},training:p.training}):null,q?(()=>{const v=p.training.payload?.models.find(W=>W.id===q),O=p.training.payload?.tasksets.find(W=>W.id===v?.tasksetId);return!v||!O?null:e.jsx(Dn,{lineage:v,taskset:O,training:p.training,onChat:p.onChatWithModel,onClose:()=>D(null)})})():null]})}function Mn({onOpenChat:t,onUseExistingDataset:n}){return e.jsxs("section",{className:"training-run-placeholder",children:[e.jsx("h3",{children:"Build the Taskset in full Chat"}),e.jsx("p",{children:"The Taskset authoring Skill gathers tasks and data conversationally, then uses typed actions to materialize graders, evaluations, and the executable Taskset. No training starts from this flow."}),e.jsxs("div",{className:"labs-dataset-detail-actions",children:[e.jsx("button",{className:"training-button",type:"button",onClick:t,children:"Open Taskset Builder"}),n?e.jsx("button",{className:"training-button secondary",type:"button",onClick:n,children:"Use existing Taskset"}):null]})]})}const _l=Object.freeze(Object.defineProperty({__proto__:null,LabsRoute:yl},Symbol.toStringTag,{value:"Module"}));export{Un as E,re as L,Fn as a,Be as b,Qe as c,ct as d,ut as e,Ht as f,qt as g,zn as h,_l as i,We as l,Tl as m};
|