openpond 0.0.34 → 0.0.35

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.
Files changed (172) hide show
  1. package/dist/chunks/{app-layer-UQQNF5VZ.js → app-layer-GUF2CKYH.js} +3 -3
  2. package/dist/chunks/{apps-7NSC56K5.js → apps-DIVHAUOV.js} +3 -3
  3. package/dist/chunks/{chunk-MMDKFTJB.js → chunk-2GV3QBBZ.js} +1 -1
  4. package/dist/chunks/{chunk-BZPAW4JY.js → chunk-2I5TZW66.js} +918 -527
  5. package/dist/chunks/{chunk-TF234YN4.js → chunk-4Y25BACE.js} +1 -1
  6. package/dist/chunks/{chunk-ZRNFOHFH.js → chunk-CRFB72X2.js} +3 -3
  7. package/dist/chunks/{chunk-ZDEBKTWR.js → chunk-EY52SLOQ.js} +1 -1
  8. package/dist/chunks/{chunk-EBCLEJRO.js → chunk-FRPL5XPX.js} +1 -1
  9. package/dist/chunks/{chunk-UASXM3RR.js → chunk-GUGFYXFS.js} +4 -4
  10. package/dist/chunks/{chunk-5MM3P5KY.js → chunk-II2ERA2H.js} +2 -2
  11. package/dist/chunks/{chunk-V7SHAMUN.js → chunk-LUA5QGQP.js} +33 -33
  12. package/dist/chunks/{chunk-E3RLJ5XT.js → chunk-NTRTK6C6.js} +2 -2
  13. package/dist/chunks/{chunk-F6FFL3AA.js → chunk-RLQGMSW7.js} +2 -2
  14. package/dist/chunks/{chunk-JVTACGKD.js → chunk-S3VA47DG.js} +3 -3
  15. package/dist/chunks/{chunk-G7XOSECC.js → chunk-SECNDLPQ.js} +966 -528
  16. package/dist/chunks/{chunk-2GCNPJMD.js → chunk-TXJ4TIDO.js} +1 -1
  17. package/dist/chunks/{chunk-B5CFIWWU.js → chunk-XIF53VR3.js} +1 -1
  18. package/dist/chunks/{chunk-U4TUOBXO.js → chunk-YPK2W34Z.js} +1 -1
  19. package/dist/chunks/{chunk-HGZ3O4TS.js → chunk-ZZOTKXRD.js} +2 -2
  20. package/dist/chunks/{cli-VEDK2B42.js → cli-3AEIYSMD.js} +6 -6
  21. package/dist/chunks/{cli-4ETE5RS2.js → cli-HUVI6ELM.js} +4 -4
  22. package/dist/chunks/{core-commands-J3IQGQOL.js → core-commands-2HUTKFHQ.js} +4 -4
  23. package/dist/chunks/{extend-3F3LLDOF.js → extend-PAJMXYKV.js} +9 -9
  24. package/dist/chunks/{harness-JER7P6MJ.js → harness-UWAS2VAN.js} +3 -3
  25. package/dist/chunks/{help-75NFCYJ4.js → help-M7D2XAOX.js} +1 -1
  26. package/dist/chunks/{opchat-UT5V7MR2.js → opchat-FQ2CJVM6.js} +5 -5
  27. package/dist/chunks/{organizations-ERKRLVNQ.js → organizations-L5N6LJ7O.js} +4 -4
  28. package/dist/chunks/{profile-A3CUSDIF.js → profile-KH5IKVNY.js} +7 -7
  29. package/dist/chunks/{project-agent-FCV5HPYT.js → project-agent-F4NHVRGY.js} +6 -6
  30. package/dist/chunks/{sandbox-command-L2QPIWZ5.js → sandbox-command-DDXRQNB6.js} +4 -4
  31. package/dist/chunks/{sandbox-template-XOIWROEK.js → sandbox-template-5EEEQKR5.js} +5 -5
  32. package/dist/chunks/{src-V4FUQNHR.js → src-34FV42HE.js} +27227 -24056
  33. package/dist/chunks/{src-ENVQ7ARM.js → src-LHZWUSD7.js} +2 -2
  34. package/dist/chunks/{teams-bot-OR3ZJHQ5.js → teams-bot-HFWO5GOV.js} +3 -3
  35. package/dist/chunks/{workspaces-L73SRLPA.js → workspaces-LO44JAC2.js} +2 -2
  36. package/dist/cli.js +10 -10
  37. package/dist/web/assets/AppDialog-T3j6O3yg.js +1 -0
  38. package/dist/web/assets/{AppsView-CLjjVkjr.js → AppsView-70Qqf9eJ.js} +1 -1
  39. package/dist/web/assets/{BrowserSidebar-CkNO8723.js → BrowserSidebar-CdBLHdNW.js} +1 -1
  40. package/dist/web/assets/CloudWorkView-C5-jvlOo.js +1 -0
  41. package/dist/web/assets/{CommandMenu-DWtdkvmq.js → CommandMenu-B3Y4MvmT.js} +1 -1
  42. package/dist/web/assets/CommunityView-BHUJ9Hun.js +1 -0
  43. package/dist/web/assets/ComposerCreateImproveStrip-DeRI5XEO.js +1 -0
  44. package/dist/web/assets/GetStartedView-CIXScviw.js +1 -0
  45. package/dist/web/assets/GetStartedView-DBLdduwr.css +1 -0
  46. package/dist/web/assets/LabsRoute-Cs_R1fuu.js +3 -0
  47. package/dist/web/assets/MainChatThread-h7VSA_Rc.js +2 -0
  48. package/dist/web/assets/MakeAgentTutorialLearningPanel-r7jyZVc0.js +2 -0
  49. package/dist/web/assets/MarkdownText-E35C404I.js +7 -0
  50. package/dist/web/assets/Messages-BANZuAnA.js +10 -0
  51. package/dist/web/assets/NativeSkillSidebar-Qgccncuc.js +1 -0
  52. package/dist/web/assets/NativeSkillSidebar-T8KXjnUH.css +1 -0
  53. package/dist/web/assets/{NewProjectDialog-PrbA4fL6.js → NewProjectDialog-BowacUmA.js} +1 -1
  54. package/dist/web/assets/PostTrainingLearningPanel-oJu5qaHK.js +2 -0
  55. package/dist/web/assets/PostTrainingStatusPill-B9Eoc4s0.js +1 -0
  56. package/dist/web/assets/{ProfileSettingsSection-CqnfjiCl.css → ProfileSettingsSection-Cg4tKO-C.css} +1 -1
  57. package/dist/web/assets/ProfileSettingsSection-Dnh92gDH.js +1 -0
  58. package/dist/web/assets/RightChatPanelStack-pGwbt6Wy.js +1 -0
  59. package/dist/web/assets/SettingsView-Bjehxwt1.js +6 -0
  60. package/dist/web/assets/SettingsView-uHhQnazW.css +1 -0
  61. package/dist/web/assets/TeamChatView-Tn4X5cuY.js +3 -0
  62. package/dist/web/assets/{TerminalOverlay-DaGfEprz.js → TerminalOverlay-DoX5LYzK.js} +11 -11
  63. package/dist/web/assets/TrainingCreationPanel-BLSf1Bnp.js +1 -0
  64. package/dist/web/assets/{TrainingDraftPanel-BX5CCqlO.js → TrainingDraftPanel-Da6uGu9y.js} +1 -1
  65. package/dist/web/assets/UsageSettingsSection-DKky0p47.js +59 -0
  66. package/dist/web/assets/UsageSettingsSection-O8VK0qBL.css +1 -0
  67. package/dist/web/assets/WorkspaceDiffPanel-DTRtW9n8.js +14 -0
  68. package/dist/web/assets/WorkspaceEnvironmentMenu-Ba4M8z1N.js +32 -0
  69. package/dist/web/assets/WorkspaceGitDialogs-CSepNOb8.js +1 -0
  70. package/dist/web/assets/{WorkspaceMonacoEditor-C0fDue2d.js → WorkspaceMonacoEditor-LhFdzCRs.js} +3 -3
  71. package/dist/web/assets/activity-bW02ZsBD.js +1 -0
  72. package/dist/web/assets/{boxes-CXLqRF98.js → boxes-B1dRA1pi.js} +1 -1
  73. package/dist/web/assets/chevron-up-CySy6WNq.js +1 -0
  74. package/dist/web/assets/circle-alert-DMHz5tj_.js +1 -0
  75. package/dist/web/assets/circle-x-DY8vKAKi.js +1 -0
  76. package/dist/web/assets/copy-DuHI1UZ_.js +1 -0
  77. package/dist/web/assets/{create-pipeline-request-C26NOc7v.js → create-pipeline-request-CGBcdK9r.js} +2 -2
  78. package/dist/web/assets/credit-card-Bot0OuTl.js +1 -0
  79. package/dist/web/assets/{cssMode-DmtwKUVm.js → cssMode-BIjAothW.js} +1 -1
  80. package/dist/web/assets/git-branch-Cm02aNWq.js +1 -0
  81. package/dist/web/assets/{git-commit-horizontal-CDDZl4iA.js → git-commit-horizontal-FYILXW0v.js} +1 -1
  82. package/dist/web/assets/{htmlMode-Box0EOm1.js → htmlMode-zO2xLLgL.js} +1 -1
  83. package/dist/web/assets/index-B5AN29EO.js +177 -0
  84. package/dist/web/assets/index-BnwYyUgT.js +1 -0
  85. package/dist/web/assets/index-COGlKIJ4.css +1 -0
  86. package/dist/web/assets/{info-4Iy6BKvT.js → info-DeuEU_RO.js} +1 -1
  87. package/dist/web/assets/{jsonMode-g7t_3HFv.js → jsonMode-D2A3mj4n.js} +1 -1
  88. package/dist/web/assets/{lspLanguageFeatures-CwhFOYc9.js → lspLanguageFeatures-aPSqvscU.js} +1 -1
  89. package/dist/web/assets/make-agent-tutorial-A2W9Ajwv.js +2 -0
  90. package/dist/web/assets/{monaco.contribution-CW2ctrTm.js → monaco.contribution-CHVe9CQ9.js} +2 -2
  91. package/dist/web/assets/{monaco.contribution-DGZAePHI.js → monaco.contribution-DAq6Jihl.js} +2 -2
  92. package/dist/web/assets/{monaco.contribution-CwMt3eHi.js → monaco.contribution-Do3Jjslo.js} +2 -2
  93. package/dist/web/assets/{monaco.contribution-B-QC_ls9.js → monaco.contribution-KqCt1n9-.js} +2 -2
  94. package/dist/web/assets/{monitor-DOVjBLkr.js → monitor-DXvHWFeW.js} +1 -1
  95. package/dist/web/assets/{play-DLCuESeG.js → play-BIHyH-Yu.js} +1 -1
  96. package/dist/web/assets/{python-DRNmHcYd.js → python-g3mtmU2J.js} +1 -1
  97. package/dist/web/assets/{refresh-cw-JNUovwk4.js → refresh-cw-Daz0oqwK.js} +1 -1
  98. package/dist/web/assets/{reply-D4QvJyzE.js → reply-wu9DIBuK.js} +1 -1
  99. package/dist/web/assets/rotate-cw-D7q9GgNc.js +1 -0
  100. package/dist/web/assets/{save-BR4O4UDP.js → save-BVFY6VTI.js} +1 -1
  101. package/dist/web/assets/{toggleHighContrast-CrfdWIsV.js → toggleHighContrast-D9C_WUDu.js} +1 -1
  102. package/dist/web/assets/training-1du5QD-P.css +1 -0
  103. package/dist/web/assets/{tsMode-ZuV9go1B.js → tsMode-B4lEUN5X.js} +1 -1
  104. package/dist/web/assets/upload-DNbYB4Rl.js +1 -0
  105. package/dist/web/assets/{wifi-off-XFVqsf4c.js → wifi-off-C5QLifIJ.js} +1 -1
  106. package/dist/web/assets/{workers-CJpO1Wzj.js → workers-CV4BZb_x.js} +1 -1
  107. package/dist/web/assets/{yaml-AQ4ok5ED.js → yaml-3ah8oX43.js} +1 -1
  108. package/dist/web/courses/post-training/01-how-post-training-works-poster.webp +0 -0
  109. package/dist/web/courses/post-training/01-how-post-training-works.vtt +25 -0
  110. package/dist/web/courses/post-training/02-definitions-poster.webp +0 -0
  111. package/dist/web/courses/post-training/02-definitions.vtt +117 -0
  112. package/dist/web/courses/post-training/03-on-policy-off-policy-poster.webp +0 -0
  113. package/dist/web/courses/post-training/03-on-policy-off-policy.vtt +29 -0
  114. package/dist/web/courses/post-training/04-rewards-credit-assignment-poster.webp +0 -0
  115. package/dist/web/courses/post-training/04-rewards-credit-assignment.vtt +65 -0
  116. package/dist/web/courses/post-training/05-verifiable-rewards-rlvr-poster.webp +0 -0
  117. package/dist/web/courses/post-training/05-verifiable-rewards-rlvr.vtt +69 -0
  118. package/dist/web/courses/post-training/06-ppo-grpo-poster.webp +0 -0
  119. package/dist/web/courses/post-training/06-ppo-grpo.vtt +65 -0
  120. package/dist/web/courses/post-training/07-distillation-poster.webp +0 -0
  121. package/dist/web/courses/post-training/07-distillation.vtt +53 -0
  122. package/dist/web/courses/post-training/08-opsd-sdft-sdpo-poster.webp +0 -0
  123. package/dist/web/courses/post-training/08-opsd-sdft-sdpo.vtt +61 -0
  124. package/dist/web/courses/post-training/09-credible-experiments-poster.webp +0 -0
  125. package/dist/web/courses/post-training/09-credible-experiments.vtt +69 -0
  126. package/dist/web/courses/post-training/10-technical-appendix-poster.webp +0 -0
  127. package/dist/web/courses/post-training/10-technical-appendix.vtt +69 -0
  128. package/dist/web/courses/post-training/full-course-poster.webp +0 -0
  129. package/dist/web/courses/post-training/full-course.vtt +623 -0
  130. package/dist/web/courses/post-training/scripts/script_01.md +31 -0
  131. package/dist/web/courses/post-training/scripts/script_02.md +49 -0
  132. package/dist/web/courses/post-training/scripts/script_03.md +35 -0
  133. package/dist/web/courses/post-training/scripts/script_04.md +43 -0
  134. package/dist/web/courses/post-training/scripts/script_05.md +43 -0
  135. package/dist/web/courses/post-training/scripts/script_06.md +41 -0
  136. package/dist/web/courses/post-training/scripts/script_07.md +37 -0
  137. package/dist/web/courses/post-training/scripts/script_08.md +37 -0
  138. package/dist/web/courses/post-training/scripts/script_09.md +45 -0
  139. package/dist/web/courses/post-training/scripts/script_10.md +47 -0
  140. package/dist/web/index.html +2 -2
  141. package/dist/web/tutorials/how-to-make-an-agent-create-poster.png +0 -0
  142. package/dist/web/tutorials/how-to-make-an-agent-create.vtt +49 -0
  143. package/dist/web/tutorials/how-to-make-an-agent-improve-poster.png +0 -0
  144. package/dist/web/tutorials/how-to-make-an-agent-improve.vtt +45 -0
  145. package/dist/web/tutorials/how-to-make-an-agent-poster.png +0 -0
  146. package/dist/web/tutorials/how-to-make-an-agent-use-poster.png +0 -0
  147. package/dist/web/tutorials/how-to-make-an-agent-use.vtt +33 -0
  148. package/dist/web/tutorials/how-to-make-an-agent.vtt +125 -0
  149. package/dist/web/tutorials/what-is-an-openpond-agent-poster.png +0 -0
  150. package/dist/web/tutorials/what-is-an-openpond-agent.vtt +25 -0
  151. package/package.json +1 -1
  152. package/dist/web/assets/CloudWorkView-Cu_VqkaD.js +0 -1
  153. package/dist/web/assets/CommunityView-f03qOTER.js +0 -1
  154. package/dist/web/assets/ComposerCreateImproveStrip-CZpiQJsJ.js +0 -1
  155. package/dist/web/assets/GetStartedView-C3ZrnEz5.css +0 -1
  156. package/dist/web/assets/GetStartedView-CLMmryTG.js +0 -1
  157. package/dist/web/assets/LabsRoute-BwR2g71k.js +0 -4
  158. package/dist/web/assets/ProfileSettingsSection-CD_x_V8d.js +0 -1
  159. package/dist/web/assets/SettingsView-BMmlKvlB.js +0 -63
  160. package/dist/web/assets/SettingsView-CAPf81v3.css +0 -1
  161. package/dist/web/assets/TeamChatView-B5SlhDso.js +0 -3
  162. package/dist/web/assets/TrainingComputeDialog-BFY6E0yU.js +0 -1
  163. package/dist/web/assets/TrainingCreationPanel-Cp66gMed.js +0 -1
  164. package/dist/web/assets/WorkspaceDiffPanel-D7ZEbryF.js +0 -14
  165. package/dist/web/assets/WorkspaceEnvironmentMenu-D4DmAJaS.js +0 -32
  166. package/dist/web/assets/WorkspaceGitDialogs-DHOfJxbL.js +0 -1
  167. package/dist/web/assets/index-8H-GDlM5.css +0 -1
  168. package/dist/web/assets/index-BUyeKpY6.js +0 -1
  169. package/dist/web/assets/index-CKmte5ok.js +0 -192
  170. package/dist/web/assets/training-DeVTd0m8.css +0 -1
  171. package/dist/web/assets/useComputeSettings-DUNS6uOl.js +0 -1
  172. package/dist/web/assets/useComputeSettings-R2Sw621I.css +0 -1
@@ -0,0 +1,3 @@
1
+ import{j as e,S as os,K as we,r as c,bj as Lt,y as Ks,z as Hs,a2 as Gs,bk as Rn,D as on,bl as Ws,M as Bt,a as dn,bm as ds,u as Qe,bn as Js,R as xn,X as Xe,a6 as Qs,bo as Xs,ae as Ys,E as Zs,bp as Ot,n as ut,bq as Qt,br as ea,bs as ta,bt as na,bu as sa,k as cs,v as bn,P as aa,bv as ia,V as us,Y as ra,aC as la,U as hs,bw as oa,bx as jn,Q as ps,a1 as ms}from"./index-B5AN29EO.js";import{P as da}from"./ProfileSettingsSection-Dnh92gDH.js";import{A as it}from"./AppDialog-T3j6O3yg.js";import{B as pt}from"./boxes-B1dRA1pi.js";import{R as gs}from"./refresh-cw-Daz0oqwK.js";import{c as ca,e as at,g as ua,f as qt,s as vn,d as An,b as Mn,j as fs}from"./training-model-data-BXUCzS0p.js";import{ComposerCreateImproveStrip as ha}from"./ComposerCreateImproveStrip-DeRI5XEO.js";/* empty css */import{C as pa,a as ma}from"./circle-x-DY8vKAKi.js";import"./git-commit-horizontal-FYILXW0v.js";import"./play-BIHyH-Yu.js";/* empty css */import"./circle-alert-DMHz5tj_.js";function ga(t,n){let s=null;for(const a of t)fa(a,n)&&(!s||xa(a,s))&&(s=a);return s}function fa(t,n){const s=t.scope;return!!(s&&t.rftSignal&&s.split===n.split&&s.taskCount===n.taskCount&&s.attemptsPerTask===n.attemptsPerTask&&s.selectionSeed===n.selectionSeed&&s.selectionStrategy===n.selectionStrategy&&s.model.providerId===n.model.providerId&&s.model.modelId===n.model.modelId&&s.sampling.maxOutputTokens===n.sampling.maxOutputTokens&&s.sampling.temperature===n.sampling.temperature&&s.sampling.topP===n.sampling.topP)}function xa(t,n){const s=t.rftSignal?.passed===!0,a=n.rftSignal?.passed===!0;return s!==a?s:t.createdAt>n.createdAt}const Xt=8,_n=24,ba=2;function ja(t){const n=ya(t);if(n.length){const i=_n+n.reduce((l,o)=>l+Xt+vt(o.content),0),r=n.filter(l=>l.role==="assistant").map(l=>Xt+vt(l.content));return{renderedTokens:i,maximumAssistantTargetTokens:Math.max(0,...r),assistantTargetCount:r.length}}const s=ka(t.input),a=Sa(t.expectedOutput);return{renderedTokens:_n+vt(s)+vt(a),maximumAssistantTargetTokens:Xt+vt(a),assistantTargetCount:a?1:0}}function va(t,n={}){const s=n.minimum??64,a=n.maximum??4096,i=t.tasks.filter(r=>r.split==="train").reduce((r,l)=>Math.max(r,ja(l).renderedTokens),0);return i<=s?s:Math.min(a,2**Math.ceil(Math.log2(i)))}function ya(t){const n=[...Tn(t.input.messages),...Tn(t.expectedOutput?.messages)],s=[],a=new Map,i=r=>{const l=typeof r=="string"&&r?r:`missing_${a.size+1}`;return a.has(l)||a.set(l,`call_${a.size+1}`),a.get(l)};for(const r of n){if(!$t(r))continue;const l=r.role,o=r.content;if(l==="tool"){s.push({role:"user",content:Ft({content:typeof o=="string"?o:"",tool_call_id:i(r.tool_call_id),type:"tool_result"})});continue}if(l==="assistant"&&Array.isArray(r.tool_calls)&&r.tool_calls.length){for(const u of r.tool_calls)!$t(u)||!$t(u.function)||(s.push({role:"assistant",content:Ft({arguments:Na(u.function.arguments),name:u.function.name??null,type:"tool_call"})}),i(u.id));typeof o=="string"&&o&&s.push({role:"assistant",content:o});continue}(l==="system"||l==="user"||l==="assistant")&&typeof o=="string"&&o&&s.push({role:l,content:o})}return s}function Tn(t){return Array.isArray(t)?t:[]}function Na(t){if(typeof t!="string")return{};try{return JSON.parse(t)}catch{return{malformed_arguments:t}}}function Ft(t){return JSON.stringify(cn(t))}function cn(t){return Array.isArray(t)?t.map(cn):$t(t)?Object.fromEntries(Object.keys(t).sort().map(n=>[n,cn(t[n])])):t}function ka(t){return typeof t.prompt=="string"?t.prompt:Ft(t)}function Sa(t){return t?typeof t.text=="string"?t.text:Ft(t):""}function vt(t){return Math.ceil(t.length/ba)}function $t(t){return!!(t&&typeof t=="object"&&!Array.isArray(t))}function Ca({section:t="all",payload:n,connection:s,onPayload:a,onError:i,onToast:r,onSkillCommand:l,overviewContent:o}){return e.jsx("section",{className:"profile-view","aria-label":t==="agents"?"Agents":"Profile",children:e.jsx(da,{section:t,payload:n,connection:s,onPayload:a,onError:i,onToast:r,onSkillCommand:l,overviewContent:o})})}function wa({candidates:t,onRescan:n,onSelect:s}){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"training-dialog-scroll-body",children:[e.jsxs("div",{className:"training-run-step-heading",children:[e.jsx("h3",{children:t.length?"Review repeated workflows":"No repeated workflows found"}),e.jsx("p",{children:t.length?"Choose a candidate to review its supporting chats before anything is disclosed.":"Nothing met the current recurrence and evidence thresholds. No empty model was created."})]}),t.length?e.jsx("div",{className:"training-candidate-options",children:t.map(a=>e.jsxs("button",{type:"button",onClick:()=>s(a),children:[e.jsxs("span",{children:[e.jsx("strong",{children:a.title}),e.jsx("small",{children:a.summary})]}),e.jsxs("dl",{children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Supporting chats"}),e.jsx("dd",{children:a.evidence.length})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Confidence"}),e.jsxs("dd",{children:[Math.round(a.scorecard.overall*100),"%"]})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Preliminary"}),e.jsx("dd",{children:a.recommendation.tactic.replaceAll("_"," ")})]})]})]},a.id))}):null]}),e.jsx("div",{className:"training-dialog-actions",children:e.jsx("button",{className:"training-button secondary",type:"button",onClick:n,children:t.length?"Scan again":"Change scan"})})]})}function un({disabled:t=!1,estimatesBySessionId:n,matchingSessionCount:s,onLoadMore:a,onSearchChange:i,onToggleSession:r,onToggleVisible:l,reviewOnly:o=!1,search:u,searchError:h,searchHasMore:d,searchIndexedChats:m,searchIndexing:x,searchLoading:j,searchTotalChats:N,selectedEntries:S,selectedSessionIds:v,visibleSessions:y}){const g=y.length>0&&y.every(C=>v.has(C.sessionId)),k=y.filter(C=>!v.has(C.sessionId));return e.jsxs("fieldset",{className:"training-chat-picker",disabled:t,children:[o?null:e.jsxs("div",{className:"training-source-toolbar",children:[e.jsxs("label",{className:"training-search",children:[e.jsx(os,{size:14}),e.jsx("input",{value:u,onChange:C=>i(C.target.value),placeholder:"Search chats"})]}),e.jsx("button",{className:"training-text-button",type:"button",disabled:!y.length,onClick:l,children:g?"Clear visible":"Select visible"})]}),e.jsxs("div",{className:"training-source-result-count",children:[e.jsx("span",{children:o?`${S.length} selected chat${S.length===1?"":"s"}`:`Showing ${y.length} of ${s} matching chats`}),!o&&x?e.jsxs("span",{children:["Indexing messages ",m," of ",N]}):null]}),e.jsxs("div",{className:"training-source-options",onScroll:C=>{const M=C.currentTarget;d&&!j&&M.scrollHeight-M.scrollTop-M.clientHeight<72&&a()},children:[S.length?e.jsx("div",{className:"training-selected-chat-group",children:S.map(C=>e.jsx(En,{checked:!0,entry:C,estimatesBySessionId:n,onToggleSession:r,showSnippet:o||!!u.trim()},C.sessionId))}):null,o?null:k.map(C=>e.jsx(En,{checked:!1,entry:C,estimatesBySessionId:n,onToggleSession:r,showSnippet:!!u.trim()},C.sessionId)),!o&&j?e.jsxs("div",{className:"training-chat-search-state",children:[e.jsx(we,{className:"spin",size:15}),e.jsx("span",{children:y.length?"Loading more chats…":"Searching chats…"})]}):null,!o&&h?e.jsx("p",{className:"training-empty",children:"Chat search is unavailable. Try again."}):null,!o&&!j&&!h&&!y.length?e.jsx("p",{className:"training-empty",children:x?"No matches yet. Message indexing is still running.":"No completed chats match this search."}):null]})]})}function En({checked:t,entry:n,estimatesBySessionId:s,onToggleSession:a,showSnippet:i}){return e.jsxs("label",{children:[e.jsx("input",{className:"training-chat-checkbox",type:"checkbox",checked:t,onChange:r=>a(n.sessionId,r.target.checked)}),e.jsxs("span",{children:[e.jsx("strong",{children:n.title}),i&&n.snippet?e.jsx("span",{className:"training-chat-search-snippet",children:n.snippet}):null,e.jsxs("small",{children:[new Date(n.updatedAt).toLocaleString(),e.jsx(Ia,{estimate:s[n.sessionId]})]})]})]})}function Ia({estimate:t}){return t?e.jsxs("span",{className:"training-chat-estimate",children:[e.jsxs("span",{children:[t.messageCount," messages"]}),e.jsxs("span",{children:["About ",ct(t.estimatedTokens)," tokens"]})]}):e.jsx("span",{className:"training-chat-estimate",children:e.jsx("span",{children:"Estimating…"})})}function ct(t){return t<1e3?String(t):t<1e6?`${(t/1e3).toFixed(t>=1e4?0:1)}K`:`${(t/1e6).toFixed(t>=1e7?0:1)}M`}function Ra({config:t,estimatesBySessionId:n,estimate:s,matchingSessionCount:a,onCancel:i,onConfigChange:r,onLoadMore:l,onScan:o,onSearchChange:u,onToggleSession:h,onToggleVisible:d,run:m,scanning:x,search:j,searchError:N,searchHasMore:S,searchIndexedChats:v,searchIndexing:y,searchLoading:g,searchTotalChats:k,selectedEntries:C,selectedSessionIds:M,targetLabel:R,visibleSessions:w}){const p=M.size,B=s.measuredChats===p,D=Aa(R);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"training-dialog-scroll-body",children:[e.jsxs("div",{className:"training-run-step-heading",children:[e.jsx("h3",{children:"Choose chats to inspect"}),e.jsx("p",{children:D.description})]}),e.jsx(un,{disabled:x,estimatesBySessionId:n,matchingSessionCount:a,onLoadMore:l,onSearchChange:u,onToggleSession:h,onToggleVisible:d,search:j,searchError:N,searchHasMore:S,searchIndexedChats:v,searchIndexing:y,searchLoading:g,searchTotalChats:k,selectedEntries:C,selectedSessionIds:M,visibleSessions:w}),e.jsx("p",{className:"training-local-scope-note",children:"The scan reads only the selected chats and runs locally. Nothing is sent to an authoring model until you choose a recommendation and approve its supporting chats."}),e.jsxs("details",{className:"training-automatic-options",children:[e.jsx("summary",{children:"Discovery options"}),e.jsxs("div",{children:[e.jsxs("label",{children:["Look back ",e.jsx("input",{type:"number",min:1,max:365,value:t.observationWindowDays,onChange:$=>r({...t,observationWindowDays:Number($.target.value)})})," days"]}),e.jsxs("label",{children:["Minimum recurrence ",e.jsx("input",{type:"number",min:2,max:100,value:t.minimumRecurrence,onChange:$=>r({...t,minimumRecurrence:Number($.target.value)})})]})]})]}),m&&["queued","running","cancelling"].includes(m.status)?e.jsxs("div",{className:"training-miner-progress",role:"status",children:[e.jsxs("div",{children:[e.jsx("strong",{children:Ma(m)}),e.jsxs("span",{children:[m.progress.processedSources," of ",m.progress.totalSources||p," chats · ",m.progress.candidatesFound," candidates",m.progress.skippedSources?` · ${m.progress.skippedSources} skipped`:""]})]}),e.jsx("progress",{max:Math.max(1,m.progress.totalSources||p),value:m.progress.processedSources})]}):null,m?.status==="failed"?e.jsxs("p",{className:"training-empty",children:["Scan failed: ",m.error]}):null,m?.status==="cancelled"?e.jsx("p",{className:"training-empty",children:"The scan was cancelled. No recommendation was selected."}):null]}),e.jsxs("div",{className:"training-dialog-actions",children:[e.jsx("span",{className:"training-selection-count",children:p===0?"Select one or more chats":B?e.jsxs(e.Fragment,{children:[e.jsxs("span",{children:[p," chat",p===1?"":"s"]}),e.jsxs("span",{children:[s.messageCount," messages"]}),e.jsxs("span",{children:["About ",ct(s.estimatedTokens)," tokens"]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{children:[p," chat",p===1?"":"s"]}),e.jsx("span",{children:"Estimating…"})]})}),x?e.jsx("button",{className:"training-button secondary",type:"button",disabled:m?.status==="cancelling",onClick:i,children:m?.status==="cancelling"?"Cancelling…":"Cancel scan"}):null,e.jsxs("button",{className:"training-button",type:"button",disabled:x||p===0,onClick:o,children:[x?e.jsx(we,{className:"spin",size:14}):null,x?D.scanningLabel:D.actionLabel]})]})]})}function Aa(t){return t==="agent"?{actionLabel:"Find Agent opportunities",description:"Select completed chats that may contain repeated work worth turning into an Agent. OpenPond will compare only the chats you choose.",scanningLabel:"Finding Agent opportunities…"}:t==="dataset"?{actionLabel:"Find Dataset opportunities",description:"Select completed chats that may contain repeated work worth capturing in a reusable Dataset. OpenPond will compare only the chats you choose.",scanningLabel:"Finding Dataset opportunities…"}:t==="model"?{actionLabel:"Find training opportunities",description:"Select completed chats that may contain repeated work worth training into a Model. OpenPond will compare only the chats you choose.",scanningLabel:"Finding training opportunities…"}:{actionLabel:"Find repeated work",description:`Select completed chats that may contain repeated work worth turning into a ${t}. OpenPond will compare only the chats you choose.`,scanningLabel:"Finding repeated work…"}}function Ma(t){return t.status==="queued"?"Preparing scan":t.status==="cancelling"?"Cancelling scan":t.progress.stage==="ingesting"?"Preparing local evidence":t.progress.stage==="clustering"?"Clustering repeated work":t.progress.stage==="persisting"?"Saving recommendations":"Scanning local evidence"}function _a({busy:t,candidates:n,value:s,onChange:a,onContinue:i,onManage:r,onScan:l}){const o=n.find(d=>d.selectionKey===s&&d.available)??null,u=Ea(n),h=s??n.find(d=>d.available)?.selectionKey??null;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{"aria-label":"Starting-weight choices",className:"training-dialog-scroll-body training-base-model-scroll",role:"region",tabIndex:0,children:[e.jsxs("div",{className:"training-run-step-heading",children:[e.jsx("h3",{children:"Choose starting weights"}),e.jsx("p",{children:"Choose the model this Model should start from. Compute, provider, export, and spend are confirmed separately for each Version."})]}),e.jsx("div",{"aria-label":"Available base models",className:"training-base-model-groups",role:"radiogroup",children:u.map(d=>e.jsxs("section",{className:"training-base-model-group",children:[e.jsxs("div",{className:"training-base-model-group-heading",children:[e.jsx("strong",{children:d.label}),e.jsx("small",{children:d.description})]}),e.jsx("div",{className:"training-method-options training-base-model-options",children:d.candidates.map(m=>e.jsx(Ta,{candidate:m,selected:m.selectionKey===s,autofocus:m.selectionKey===h,onChange:a,onContinue:i},m.selectionKey))})]},d.label))}),n.length?null:e.jsx("div",{className:"training-banner",children:"No training base models were found. Scan this machine, or manage local models to configure storage and download supported weights."}),e.jsx("p",{className:"training-start-note",children:"This preference can be overridden for a Version, but OpenPond will not silently switch its base model or provider."})]}),e.jsxs("div",{className:"training-dialog-actions training-base-model-actions",children:[e.jsxs("button",{className:"training-button secondary",type:"button",onClick:r,children:[e.jsx(pt,{size:14}),"Manage local models"]}),e.jsxs("button",{className:"training-button secondary",type:"button",disabled:t,onClick:l,children:[t?e.jsx(we,{className:"spin",size:14}):e.jsx(gs,{size:14}),t?"Scanning":"Scan this machine"]}),e.jsx("button",{className:"training-button",type:"button",disabled:!o,onClick:i,children:"Continue"})]})]})}function Ta({candidate:t,selected:n,autofocus:s,onChange:a,onContinue:i}){const r=!t.available;return e.jsxs("button",{"aria-checked":n,"aria-disabled":r,className:`${n?"selected":""}${r?" unavailable":""}`,"data-autofocus":!r&&s?!0:void 0,disabled:r,role:"radio",type:"button",onClick:()=>a(t.selectionKey),onDoubleClick:r?void 0:i,children:[e.jsx("span",{className:"training-base-model-icon","aria-hidden":"true",children:e.jsx(pt,{size:18})}),e.jsxs("span",{className:"training-base-model-copy",children:[e.jsx("strong",{children:t.label}),e.jsx("small",{children:t.preference.modelId}),t.preference.revision?e.jsxs("small",{children:["Revision ",Pa(t.preference.revision)]}):null,t.available?null:e.jsx("small",{className:"training-base-model-reason",children:t.unavailableReason})]}),e.jsxs("span",{className:"training-base-model-tags","aria-hidden":"true",children:[e.jsx("small",{children:t.sourceLabel}),t.methods.map(l=>e.jsx("small",{children:l==="grpo"?"RFT":l.toUpperCase()},l)),e.jsx("small",{children:"LoRA"}),t.nonProduction?e.jsx("small",{children:"Non-production"}):null,t.available?null:e.jsx("small",{children:"Unavailable"})]}),e.jsx("span",{className:"training-choice-indicator","aria-hidden":"true"})]})}function Ea(t){const n=t.filter(a=>a.available);return[{label:"Managed",description:"Hosted training catalogs",candidates:n.filter(a=>a.preference.source==="managed")},{label:"This machine",description:"Verified local weights",candidates:n.filter(a=>a.preference.source!=="managed")},{label:"Unavailable",description:"Known choices that cannot run yet",candidates:t.filter(a=>!a.available)}].filter(a=>a.candidates.length>0)}function Pa(t){return t.length>18?`${t.slice(0,18)}…`:t}function $a({state:t,selectedTasksetId:n,busy:s,onChange:a,onCreate:i}){const r=La(t),l=r.find(o=>o.id===n)??null;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"training-dialog-scroll-body",children:[e.jsxs("div",{className:"training-run-step-heading",children:[e.jsx("h3",{children:"Choose a Dataset"}),e.jsx("p",{children:"Use an approved Dataset as the immutable training and Eval boundary for this Model."})]}),e.jsxs("div",{className:"training-existing-dataset-list",role:"radiogroup","aria-label":"Available Datasets",children:[r.map(o=>{const u=o.id===n;return e.jsxs("button",{"aria-checked":u,className:u?"selected":void 0,role:"radio",type:"button",onClick:()=>a(o.id),children:[e.jsx("span",{className:"training-existing-dataset-icon",children:e.jsx(pt,{size:17})}),e.jsxs("span",{children:[e.jsx("strong",{children:o.name}),e.jsx("small",{children:o.objective})]}),e.jsx(Da,{taskset:o}),e.jsx("span",{className:"training-choice-indicator","aria-hidden":"true"})]},o.id)}),r.length?null:e.jsx("div",{className:"training-empty training-existing-dataset-empty",children:"No reusable Datasets are ready yet. Create a Dataset from the Lab menu, then return here."})]}),l?e.jsx("p",{className:"training-existing-dataset-note",children:"The Dataset remains reusable and unchanged. Creating the Model stores the preferred base Model on the Model draft."}):null]}),e.jsx("div",{className:"training-dialog-actions",children:e.jsx("button",{className:"training-button",disabled:!l||s,type:"button",onClick:i,children:"Create model"})})]})}function Da({taskset:t}){return e.jsxs("span",{className:"training-existing-dataset-splits",children:[e.jsxs("span",{children:[Yt(t,"train")," train"]}),e.jsxs("span",{children:[Yt(t,"validation")," validation"]}),e.jsxs("span",{children:[Yt(t,"frozen_eval")," frozen Eval"]})]})}function Yt(t,n){return t.tasks.filter(s=>s.split===n).length}function La(t){return t?t.tasksets.filter(n=>n.readiness?.ready).sort((n,s)=>s.updatedAt.localeCompare(n.updatedAt)||n.name.localeCompare(s.name)):[]}function Ba({creation:t,onCreationChange:n,sources:s,training:a}){const[i,r]=c.useState(""),l=t.proposal;if(!l)return null;const o=new Set(t.request.sourceIds),u=s.filter(N=>o.has(N.id)),h=l.diagnosis.stableBehavior.length>0?l.diagnosis.stableBehavior:[l.diagnosis.summary],d=[...l.diagnosis.changingKnowledge,...l.diagnosis.requiredContext],m=l.proposedExamples.filter(N=>N.split!=="train"),x=t.request.targetIntent.operation==="improve"?"Improvement":"New Agent";async function j(){const N=i.trim();if(!N)return;const S=await a.actions.chatCreation(t.id,N);S&&(r(""),n(S))}return e.jsxs("div",{className:"training-recommendation-review agent-recommendation-review",children:[e.jsxs("section",{className:"training-setup-section training-setup-model",children:[e.jsxs("div",{className:"training-setup-section-heading",children:[e.jsx("span",{className:"training-setup-step-number",children:"1"}),e.jsx("strong",{children:"Purpose"}),e.jsx("small",{children:x})]}),e.jsx("div",{className:"training-recommendation-detail-body",children:e.jsx("p",{className:"training-recommendation-objective",children:t.request.objective??l.objective})})]}),e.jsxs("details",{className:"training-setup-section",open:!0,children:[e.jsxs("summary",{children:[e.jsx("span",{className:"training-setup-step-number",children:"2"}),e.jsx("strong",{children:"What the Agent should do"}),e.jsxs("small",{children:[h.length," expected behavior",h.length===1?"":"s"]})]}),e.jsxs("div",{className:"training-recommendation-detail-body",children:[e.jsx("ul",{children:h.map(N=>e.jsx("li",{children:N},N))}),d.length>0?e.jsxs(e.Fragment,{children:[e.jsx("h4",{children:"Information it should use at run time"}),e.jsx("ul",{children:d.map(N=>e.jsx("li",{children:N},N))})]}):null]})]}),e.jsxs("details",{className:"training-setup-section",children:[e.jsxs("summary",{children:[e.jsx("span",{className:"training-setup-step-number",children:"3"}),e.jsx("strong",{children:"Supporting chats"}),e.jsxs("small",{children:[u.length," selected"]})]}),e.jsx("div",{className:"training-recommendation-detail-body",children:u.length>0?e.jsx("ul",{children:u.map(N=>e.jsx("li",{children:N.title},N.id))}):e.jsx("p",{children:"No chats are attached. OpenPond will build from the purpose above."})})]}),e.jsxs("details",{className:"training-setup-section",children:[e.jsxs("summary",{children:[e.jsx("span",{className:"training-setup-step-number",children:"4"}),e.jsx("strong",{children:"Evals"}),e.jsxs("small",{children:[m.length," Eval scenario",m.length===1?"":"s"]})]}),e.jsxs("div",{className:"training-recommendation-detail-body",children:[e.jsx("p",{children:"OpenPond will evaluate the Agent against scenarios derived from the approved chats before it can be released."}),m.length>0?e.jsx("ul",{children:m.map(N=>e.jsx("li",{children:N.inputPrompt},N.id))}):e.jsx("p",{children:"Add another supporting chat so OpenPond can keep a separate Eval scenario."})]})]}),e.jsxs("details",{className:"training-setup-section",children:[e.jsxs("summary",{children:[e.jsx("span",{className:"training-setup-step-number",children:"5"}),e.jsx("strong",{children:"Change this review"}),e.jsx("small",{children:"Optional"})]}),e.jsxs("div",{className:"training-recommendation-detail-body training-recommendation-revision",children:[e.jsx("textarea",{"aria-label":"Changes to the Agent review",onChange:N=>r(N.target.value),placeholder:"Explain what the Agent should do differently",value:i}),e.jsx("button",{className:"training-button secondary",disabled:!i.trim()||!!a.busyAction,onClick:()=>{j()},type:"button",children:"Update review"})]})]}),t.state==="recommendation_ready"?e.jsxs("div",{className:"training-recommendation-guidance",children:[e.jsx("strong",{children:"Add another example before continuing"}),e.jsx("p",{children:"OpenPond needs enough independent examples to evaluate the Agent without reusing the same conversation it learned from."})]}):null]})}function Oa({creation:t,resourceIntent:n="workproduct",sources:s,training:a,onCreationChange:i}){const[r,l]=c.useState(""),o=t.proposal,[u,h]=c.useState(o?.name??"");if(c.useEffect(()=>h(o?.name??""),[o?.name]),!o)return null;const d=o.diagnosis,m=n==="dataset"?"dataset":Fa(t),x=new Map(s.map(k=>[k.id,k])),j=o.proposedExamples.filter(k=>k.split==="train"),N=o.proposedExamples.filter(k=>k.split!=="train"),S=t.materializedTasksetId?a.payload?.graderAuditReports.find(k=>k.tasksetId===t.materializedTasksetId)??null:null,v=o.trainingPath?.primaryMethod??o.proposedMethod;async function y(){const k=r.trim();if(!k)return;const C=await a.actions.chatCreation(t.id,k);C&&(l(""),i(C))}async function g(){if(!o)return;const k=Lt(u,o.name);if(!k||k===o.name)return;const C=await a.actions.renameCreation(t.id,k);C&&(h(C.proposal?.name??k),i(C))}return e.jsxs("div",{className:"training-recommendation-review",children:[e.jsxs("section",{className:"training-setup-section training-setup-model",children:[e.jsxs("div",{className:"training-setup-section-heading",children:[e.jsx("span",{className:"training-setup-step-number",children:"1"}),e.jsx("strong",{children:m==="dataset"?"Dataset":"Model"}),e.jsxs("small",{children:[Dt(m)," · ",za(d.intervention)]})]}),e.jsxs("label",{className:"training-recommendation-name",children:[e.jsx("span",{children:m==="dataset"?"Dataset name":m==="model"?"Model name":"Workproduct name"}),e.jsx("input",{value:u,maxLength:100,onChange:k=>h(k.target.value),onBlur:()=>{g()},onKeyDown:k=>{k.key==="Enter"&&(k.preventDefault(),g())}}),e.jsx("small",{children:"Five words maximum. The full capability stays in the description."})]}),e.jsx("p",{className:"training-recommendation-objective",children:o.objective}),m==="model"&&t.request.preferredBaseModelId?e.jsxs("p",{className:"training-recommendation-base-model",children:[e.jsx("span",{children:"Preferred base"}),e.jsx("strong",{children:Ua(t.request.preferredBaseModelId)})]}):null]}),e.jsxs("details",{className:"training-setup-section",children:[e.jsxs("summary",{children:[e.jsx("span",{className:"training-setup-step-number",children:"2"}),e.jsx("strong",{children:"Dataset & Evals"}),e.jsxs("small",{children:[j.length," train · ",N.length," eval · ",o.proposedGraders.length," grader",o.proposedGraders.length===1?"":"s"]})]}),e.jsxs("div",{className:"training-recommendation-detail-body",children:[e.jsxs("dl",{className:"training-recommendation-facts",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Chat seeds"}),e.jsx("dd",{children:t.request.sourceIds.length})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Training examples"}),e.jsx("dd",{children:j.length})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Evaluation examples"}),e.jsx("dd",{children:N.length})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Grader"}),e.jsx("dd",{children:S?S.passed?"Passed":"Failed":o.proposedGraders.length?"Runs after creation":"Not proposed"})]})]}),o.proposedExamples.length?e.jsx("div",{className:"training-proposed-examples",children:o.proposedExamples.map(k=>e.jsxs("article",{children:[e.jsxs("div",{children:[e.jsx("strong",{children:k.split==="frozen_eval"?"Evaluation":k.split==="train"?"Training":Dt(k.split)}),e.jsx("span",{children:Dt(k.origin.replaceAll("_"," "))})]}),e.jsx("p",{children:k.inputPrompt}),e.jsx("small",{children:x.get(k.sourceId)?.title??"Selected chat"})]},k.id))}):e.jsx("p",{children:"No training examples are proposed for this recommendation."}),o.proposedGraders.length?e.jsxs("div",{className:"training-proposed-evaluation",children:[e.jsx("strong",{children:"Grader summary"}),e.jsxs("p",{children:[o.proposedGraders.map(k=>k.label).join(", ")," · ",S?S.passed?"executed successfully":"execution failed":"execution pending Taskset creation"]})]}):null,o.warnings.length&&t.state!=="recommendation_ready"?e.jsx("ul",{className:"training-recommendation-warnings",children:o.warnings.map(k=>e.jsx("li",{children:k},k))}):null]})]}),e.jsxs("details",{className:"training-setup-section",open:!0,children:[e.jsxs("summary",{children:[e.jsx("span",{className:"training-setup-step-number",children:"3"}),e.jsx("strong",{children:"Recommended training"}),e.jsx("small",{children:Pn(v)})]}),e.jsxs("div",{className:"training-recommendation-detail-body training-path-review",children:[e.jsxs("div",{children:[e.jsxs("strong",{children:["Primary · ",Pn(v)]}),e.jsx("p",{children:d.rationale.join(" ")||d.summary})]}),o.trainingPath?.bootstrap?e.jsxs("div",{children:[e.jsx("strong",{children:"Optional precursor · Supervised / SFT"}),e.jsxs("p",{children:[o.trainingPath.bootstrap.demonstrationRefs.length," reviewed demonstration",o.trainingPath.bootstrap.demonstrationRefs.length===1?"":"s",". ",o.trainingPath.bootstrap.limitations.join(" ")]})]}):null,e.jsx("p",{className:"training-setup-spend-note",children:"Creating the model saves this Dataset and recommendation locally. Paid provider training starts later from the model’s Training page, where method, budget, and export are reviewed explicitly."})]})]}),e.jsxs("details",{className:"training-setup-section",children:[e.jsxs("summary",{children:[e.jsx("span",{className:"training-setup-step-number",children:"4"}),e.jsx("strong",{children:"Behavior & context"}),e.jsxs("small",{children:[d.stableBehavior.length," stable behavior",d.stableBehavior.length===1?"":"s"]})]}),e.jsxs("div",{className:"training-recommendation-detail-body",children:[e.jsx("h4",{children:"What it should learn"}),d.stableBehavior.length?e.jsx("ul",{children:d.stableBehavior.map(k=>e.jsx("li",{children:k},k))}):e.jsx("p",{children:d.summary}),d.changingKnowledge.length||d.requiredContext.length?e.jsxs(e.Fragment,{children:[e.jsx("h4",{children:"Keep in context"}),e.jsx("ul",{children:[...d.changingKnowledge,...d.requiredContext].map(k=>e.jsx("li",{children:k},k))})]}):null]})]}),e.jsxs("details",{className:"training-setup-section",children:[e.jsxs("summary",{children:[e.jsx("span",{className:"training-setup-step-number",children:"5"}),e.jsx("strong",{children:"Advanced"}),e.jsx("small",{children:"Technical method · revise"})]}),e.jsxs("div",{className:"training-recommendation-detail-body training-recommendation-revision",children:[e.jsxs("p",{children:["Technical method: ",qa(v)]}),t.state==="recommendation_ready"||!d.trainingEligible?e.jsxs("div",{className:"training-recommendation-guidance",children:[e.jsx("strong",{children:"Why this is not ready for a Dataset"}),e.jsx("ul",{children:o.warnings.map(k=>e.jsx("li",{children:k},k))})]}):null,e.jsx("textarea",{value:r,onChange:k=>l(k.target.value),placeholder:"Explain what should change"}),e.jsx("button",{className:"training-button secondary",type:"button",disabled:!r.trim()||!!a.busyAction,onClick:()=>{y()},children:"Revise"})]})]})]})}function Fa(t){return t.request.targetIntent.kind?t.request.targetIntent.kind:t.proposal?.diagnosis.trainingEligible?"model":t.proposal?.diagnosis.intervention==="retrieval"?"configuration":"agent"}function za(t){return{no_training:"No training",prompting:"Prompt or agent instructions",retrieval:"Retrieval",sft:"SFT",preference:"Preference tuning",grpo_rft:"RFT",sdft_opsd:"Distillation",sdpo:"SDPO",agentic_rl:"Agentic RL"}[t]}function Dt(t){return t&&`${t[0].toUpperCase()}${t.slice(1)}`}function Pn(t){return t==="grpo"?"Reinforcement / RFT":t==="sft"?"Supervised / SFT":t==="preference"?"Preference":Dt(t.replaceAll("_"," "))}function qa(t){return t==="grpo"?"GRPO optimizer":t==="sft"?"SFT":t.toUpperCase()}function Ua(t){return t.split("/").filter(Boolean).at(-1)??t}function Va({busy:t,createLabel:n,creation:s,editDataLabel:a="Add chats",onAddChats:i,onClose:r,onCreateTaskset:l,onCreationChange:o,resourceIntent:u="workproduct",sources:h,training:d}){const m=s.state==="awaiting_materialization_approval",x=s.state==="recommendation_ready"&&s.proposal?.diagnosis.trainingEligible===!0,j=s.request.targetIntent.kind==="agent",N=n??(j?s.request.targetIntent.operation==="improve"?"Continue to improvement plan":"Continue to Agent plan":"Create Taskset");return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"training-dialog-scroll-body",children:j?e.jsx(Ba,{creation:s,onCreationChange:o,sources:h,training:d}):e.jsx(Oa,{creation:s,resourceIntent:u,sources:h,training:d,onCreationChange:o})}),e.jsxs("div",{className:"training-dialog-actions",children:[x?e.jsx("button",{className:"training-button secondary",type:"button",disabled:t,onClick:i,children:a}):null,e.jsx("button",{className:"training-button secondary",type:"button",onClick:r,children:m?"Cancel":"Done"}),m?e.jsxs("button",{className:"training-button",type:"button",disabled:t,onClick:l,children:[t?e.jsx(we,{className:"spin",size:14}):null,N]}):null]})]})}function Ka({authoringModel:t,authoringProvider:n,authoringReasoningEffort:s,busy:a,disclosurePending:i,estimatesBySessionId:r,matchingSessionCount:l,mode:o,objective:u,onObjectiveChange:h,onAnalyze:d,onApproveDisclosure:m,onAuthoringModelChange:x,onAuthoringProviderChange:j,onAuthoringReasoningEffortChange:N,onDeclineDisclosure:S,onDiscoverFromConversations:v,onSearchChange:y,onLoadMore:g,onReturnToRecommendation:k,onToggleSession:C,onToggleVisible:M,providerSettings:R,recommendationAvailable:w,search:p,searchError:B,searchHasMore:D,searchIndexedChats:$,searchIndexing:Y,searchLoading:ne,searchTotalChats:_,selectedEntries:E,selectedEstimate:T,selectedSessionIds:z,targetLabel:U="model",targetOperation:je="create",visibleSessions:ue}){const V=c.useMemo(()=>Ks(R,{enabledOnly:!0}),[R]),ie=c.useMemo(()=>Hs(n,R),[n,R]),he=Gs(n,t,R),Z=z.size,ee=o==="from_prompt",me=o==="from_chats",O=o==="manual"||ee||me,pe=!ee,le=me?!!u.trim()&&Z>0:o==="manual"||ee?!!u.trim():Z>0,de=T.measuredChats===Z,ye=Z>0&&de&&T.estimatedTokens>Rn,W=U==="dataset",Ne=U==="model",q=U==="agent",ge=q?ie.map(se=>se.value.startsWith("openpond-scripted-")?{...se,label:"OpenPond Chat",shortLabel:"OpenPond Chat",description:void 0}:se):ie,Q=ge.find(se=>se.value===t)?.label??t,Re=V.find(se=>se.value===n)?.label??n,be=Ne||W,Ae=i&&q?"Review chats for the Agent plan":W||Ne?"Build the Dataset":ee?"Describe the Agent":"Add purpose and supporting chats",fe=i&&q?"Approve the selected chat excerpts so OpenPond can turn their goals, decisions, and answer patterns into the first Agent plan.":o==="automated"?be?"Confirm the chats that demonstrate this repeated workflow. Only selected chats seed the Dataset.":"Confirm the chats that support this repeated workflow.":W?"Define what this Dataset should contain and be useful for. Supporting chats are optional.":U==="agent"?me?"Define the Agent's purpose and choose at least one chat that demonstrates the work or desired outcome.":"Define the Agent's purpose. This path does not attach or search your chats.":"Define the capability the Model should learn. Supporting chats are optional.",A=W?"Dataset purpose":U==="agent"?je==="improve"?"Improvement goal":"Agent purpose":"Capability",J=W?"Describe what this Dataset should contain and be useful for":U==="agent"?"Describe the work this Agent should handle reliably":`Describe what this ${U} should do reliably`;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"training-dialog-scroll-body",children:[e.jsxs("div",{className:"training-run-step-heading",children:[e.jsx("h3",{children:Ae}),e.jsx("p",{children:fe})]}),O?e.jsxs("label",{className:"training-objective-field training-dataset-capability",children:[e.jsx("span",{children:A}),e.jsx("textarea",{"data-autofocus":!0,required:!0,value:u,disabled:a||i,placeholder:J,onChange:se=>h(se.target.value)})]}):u?e.jsxs("div",{className:"training-evidence-objective",children:[e.jsx("span",{children:A}),e.jsx("strong",{children:u})]}):null,e.jsxs("fieldset",{className:"training-evidence-fields",disabled:a||i,children:[pe?o==="manual"?e.jsxs("details",{className:"training-manual-chat-seeds",children:[e.jsxs("summary",{children:[e.jsx("span",{children:"Add supporting chats"}),e.jsx("small",{children:Z?`${Z} selected`:"Optional"})]}),e.jsxs("div",{className:"training-manual-chat-seeds-body",children:[e.jsx("p",{children:"Choose successful examples, corrections, or outcome-bearing chats that clarify the purpose above."}),e.jsx(un,{estimatesBySessionId:r,matchingSessionCount:l,onLoadMore:g,onSearchChange:y,onToggleSession:C,onToggleVisible:M,reviewOnly:i,search:p,searchError:B,searchHasMore:D,searchIndexedChats:$,searchIndexing:Y,searchLoading:ne,searchTotalChats:_,selectedEntries:E,selectedSessionIds:z,visibleSessions:ue})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"training-dataset-source-heading",children:e.jsx("span",{children:be?"Chat seeds":"Supporting chats"})}),e.jsx(un,{estimatesBySessionId:r,matchingSessionCount:l,onLoadMore:g,onSearchChange:y,onToggleSession:C,onToggleVisible:M,reviewOnly:i,search:p,searchError:B,searchHasMore:D,searchIndexedChats:$,searchIndexing:Y,searchLoading:ne,searchTotalChats:_,selectedEntries:E,selectedSessionIds:z,visibleSessions:ue})]}):null,e.jsxs("div",{className:"training-authoring-row",children:[e.jsx("span",{children:q?"Build with":"Analyzed with"}),e.jsxs("div",{className:"training-authoring-controls","aria-label":"Analysis model",children:[e.jsx(on,{compact:!0,placement:"bottom",label:"Provider",value:n,options:V,disabled:a,onChange:se=>j(se)}),he?e.jsx(Ws,{disabled:a,model:t,modelOptions:ge,placement:"bottom",reasoningEffort:s,onModelChange:x,onReasoningEffortChange:N}):e.jsx(on,{compact:!0,placement:"bottom",label:"Model",value:t,options:ge,disabled:a,onChange:x})]})]})]}),i?e.jsxs("div",{className:"training-disclosure-review",role:"status",children:[e.jsx("strong",{children:q?"How the chats build the plan":"Approve evidence disclosure"}),e.jsxs("p",{children:[e.jsxs("b",{children:[Re," / ",Q]})," will analyze excerpts from ",Z," selected chat",Z===1?"":"s",", ",T.messageCount," messages, and approximately ",ct(T.estimatedTokens)," tokens. ",q?"OpenPond uses the recurring goals, decisions, corrections, and answer patterns to draft the Agent's purpose, behavior, actions, outputs, and Evals.":""]})]}):null,ye?e.jsxs("div",{className:"training-banner error",role:"alert",children:["Selected evidence is about ",ct(T.estimatedTokens)," tokens. Hosted Taskset authoring accepts up to ",ct(Rn)," raw-evidence tokens; choose fewer chats or selected turns."]}):null]}),e.jsxs("div",{className:"training-dialog-actions",children:[e.jsx("span",{className:"training-selection-count",children:ee?"No chats will be attached":Z===0?o==="manual"?"Supporting chats are optional":"Select at least one supporting chat":T.measuredChats===Z?e.jsxs(e.Fragment,{children:[e.jsxs("span",{children:[Z," chat",Z===1?"":"s"]}),e.jsxs("span",{children:[T.messageCount," messages"]}),e.jsxs("span",{children:["About ",ct(T.estimatedTokens)," tokens"]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{children:[Z," chat",Z===1?"":"s"]}),e.jsx("span",{children:"Estimating…"})]})}),i?e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"training-button secondary",type:"button",disabled:a,onClick:S,children:q?"Change chats":"Change evidence"}),e.jsxs("button",{className:"training-button",type:"button",disabled:a||!de||ye,onClick:m,children:[a?e.jsx(we,{className:"spin",size:14}):null,q?"Approve chats and build plan":"Approve and analyze"]})]}):w?e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"training-button secondary",type:"button",disabled:a,onClick:d,children:"Reanalyze changes"}),e.jsx("button",{className:"training-button",type:"button",onClick:k,children:"Return to recommendation"})]}):e.jsxs(e.Fragment,{children:[W&&o==="manual"&&v?e.jsx("button",{className:"training-button secondary",type:"button",disabled:a,onClick:v,children:"Discover from conversations"}):null,e.jsxs("button",{className:"training-button",type:"button",disabled:!le||a||ye||Z>0&&!de,onClick:d,children:[a?e.jsx(we,{className:"spin",size:14}):null,Z>0?q?"Review chats for plan":"Review data access":q&&ee?"Continue":be?"Build Dataset":"Review setup"]})]})]})]})}function Ha({mode:t,allowExistingDataset:n=!1,operation:s="create",targetLabel:a="model",onChange:i,onContinue:r}){const l=a==="agent",o=Ga(a),u=[{id:"automated",title:"Automatic",description:o.automaticDescription,icon:Bt},{id:"manual",title:"Manual",description:o.manualDescription,icon:dn},{id:"existing_dataset",title:"Existing Dataset",description:"Create the Model from a reviewed Dataset without changing its tasks, graders, or held-out Evals.",icon:pt}],d=l?[{id:"from_prompt",title:"From prompt",description:s==="improve"?"Describe the improvement you want without attaching chat evidence.":"Describe the Agent's purpose without attaching supporting chats.",icon:dn},{id:"from_chats",title:"From chats",description:s==="improve"?"Describe the improvement and attach chats that show the correction or desired outcome.":"Describe the Agent's purpose and attach chats that show the work it should handle.",icon:Bt}]:n?u:u.filter(m=>m.id!=="existing_dataset");return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"training-run-step-heading",children:[e.jsx("h3",{children:"Choose a setup"}),e.jsx("p",{children:o.introduction})]}),e.jsx("div",{"aria-label":l?`How to ${s} an agent`:`How to start a new ${a}`,className:"training-method-options training-start-mode-options",role:"radiogroup",children:d.map(m=>{const x=m.icon,j=m.id===t;return e.jsxs("button",{type:"button",role:"radio","aria-checked":j,className:j?"selected":"",onClick:()=>i(m.id),onDoubleClick:r,children:[e.jsx("span",{className:"training-start-mode-icon","aria-hidden":"true",children:e.jsx(x,{size:18})}),e.jsxs("span",{className:"training-start-mode-copy",children:[e.jsx("strong",{children:m.title}),e.jsx("small",{children:m.description})]}),e.jsx("span",{className:"training-choice-indicator","aria-hidden":"true"})]},m.id)})}),e.jsx("div",{className:"training-dialog-actions",children:e.jsx("button",{className:"training-button",type:"button",disabled:!t,onClick:r,children:"Continue"})})]})}function Ga(t){return t==="agent"?{automaticDescription:"Choose chats that support the Agent's purpose.",introduction:"Describe what the Agent should do, with or without examples from your chats.",manualDescription:"Describe the Agent's purpose without supporting chats."}:t==="dataset"?{automaticDescription:"Choose chats to inspect for repeated work worth capturing in a Dataset.",introduction:"Let OpenPond find a Dataset opportunity in selected chats, or define the Dataset you already need.",manualDescription:"Define the Dataset's purpose yourself, with optional supporting chats."}:t==="model"?{automaticDescription:"Choose chats to inspect for repeated work that may be worth training into a Model.",introduction:"Let OpenPond find a training opportunity in selected chats, define the capability yourself, or start from an existing Dataset.",manualDescription:"Define the capability the Model should learn, with optional supporting chats."}:{automaticDescription:`Choose chats to inspect for repeated work that could become a ${t}.`,introduction:`Let OpenPond find an opportunity in selected chats, or describe the ${t} you already want.`,manualDescription:`Describe the ${t}'s purpose yourself, with optional supporting chats.`}}const Wa=new Set(["cancelled","failed","ready"]);function $n(t){return!!(t&&!Wa.has(t.state))}function Ja(t){return t?t.state==="awaiting_disclosure_approval"?"evidence":"recommendation":"start"}function Dn(t,n,s){if(n){const i=t.find(r=>r.preference.modelId===n.modelId&&r.preference.source===n.source&&r.preference.revision===n.revision&&r.preference.modelAssetId===n.modelAssetId);if(i)return i}const a=n?.modelId??s;return a?t.find(i=>i.preference.modelId===a)??null:null}function Qa(t){return t?t.trim().toLowerCase()==="terminated"?"OpenPond Chat closed the Taskset authoring stream before a proposal was returned. No Taskset was created.":t:"The authoring model did not return a proposal."}function Ln(t,n){return n==="dataset"?"New Dataset":t.kind==="agent"?t.operation==="improve"?`Improve ${t.displayName??"agent"}`:"New agent":t.kind==="model"?"New model":"New change"}function Zt(t,n){return n==="dataset"?"dataset":t.kind==="agent"?"agent":t.kind==="model"?"model":"workproduct"}function Xa(t,n){return n==="dataset"?"Review Dataset":t.kind==="model"?"Review model":t.kind==="agent"?t.operation==="improve"?"Review agent change":"Review agent":"Review change"}function Ya(t,n){let s=0,a=0,i=0;for(const r of t){const l=n[r];l&&(i+=1,s+=l.messageCount,a+=l.estimatedTokens)}return{messageCount:s,estimatedTokens:a,measuredChats:i}}function Za(t,n,s){return t==="base_model"?"Back to setup":t==="existing_dataset"?"Back to base model":t==="automatic_scope"?n?"Back to base model":"Back to setup":t==="automatic_candidates"?"Back to scan scope":t==="evidence"?s==="automated"?"Back to repeated workflows":n?"Back to base model":"Back to setup":"Back to Dataset"}function ei(){return{schemaVersion:"openpond.taskMinerConfig.v1",enabled:!1,localOnly:!0,observationWindowDays:30,minimumRecurrence:3,clustering:"hybrid_deterministic_first",consentRequired:!0}}const Bn=20;function yt({datasetBuildMode:t=!1,defaultModel:n,initialCreation:s=null,initialObjective:a,initialSessionIds:i=[],onClose:r,onAgentPromptSubmitted:l,onBackToDatasetSources:o,onOpenComputeSettings:u,onModelCreatedFromTaskset:h,onTasksetCreated:d,preferences:m,providerSettings:x,reasoningEffort:j,resourceIntent:N="workproduct",sessions:S,sources:v,training:y,targetIntent:g={kind:"model",id:null,displayName:null,operation:"create"}}){const k=ds(m,n),C=y.payload?.baseModelCandidates??[],M=v.filter(b=>s?.request.sourceIds.includes(b.id)).map(b=>b.sessionId),[R,w]=c.useState(()=>s?Ja(s):t?"evidence":"start"),p=N==="workproduct"&&g.kind==="agent",[B,D]=c.useState(()=>s&&p?s.request.sourceIds.length>0?"from_chats":"from_prompt":s?.request.entryMode??(t?"manual":null)),$=B==="automated"||B==="manual"?B:null,Y=B==="from_prompt"||B==="from_chats"?B:null,[ne,_]=c.useState(s?.request.objective??a??""),[E,T]=c.useState(()=>Dn(C,s?.request.preferredBaseModel??null,s?.request.preferredBaseModelId??null)?.selectionKey??null),[z,U]=c.useState(null),[je,ue]=c.useState(s?.request.candidateId??null),[V,ie]=c.useState(s?.request.analysisModel?.providerId??k.providerId),[he,Z]=c.useState(s?.request.analysisModel?.modelId??k.modelId),[ee,me]=c.useState(s?.request.analysisReasoningEffort??j),[O,pe]=c.useState(""),[le,de]=c.useState([]),[ye,W]=c.useState(0),[Ne,q]=c.useState(!1),[ge,Q]=c.useState(!1),[Re,be]=c.useState(null),[Ae,fe]=c.useState(!1),[A,J]=c.useState(0),[se,K]=c.useState(0),[I,F]=c.useState(0),X=c.useRef(0),oe=c.useRef(!1),[Me,ke]=c.useState(()=>new Set([...i,...M])),[Ve,wt]=c.useState({}),[G,Ke]=c.useState(s),[De,Se]=c.useState(!1),[Le,Ie]=c.useState(!1),[ce,_e]=c.useState(null);Qe(Re,{prefix:"Chat search"}),Qe(ce);const[Je,mt]=c.useState(!1),[Te,gt]=c.useState(null),[ft,xt]=c.useState([]),[ae,Ye]=c.useState(()=>y.payload?.minerConfig??ei()),Ee=c.useMemo(()=>new Set(v.filter(b=>{const L=b.metadata.workflowSignature;return b.metadata.frontierBaseline===!0||L==="cross-system-operations"||typeof L=="string"&&L.startsWith("baseline:")||!!b.metadata.crossSystemOperations}).map(b=>b.sessionId)),[v]),rt=c.useMemo(()=>S.filter(b=>!b.systemKind&&!b.hiddenFromDefaultSidebar&&b.status!=="active"&&!Ee.has(b.id)),[Ee,S]),bt=c.useMemo(()=>new Map(S.map(b=>[b.id,b])),[S]),Be=c.useMemo(()=>new Map(v.map(b=>[b.sessionId,b])),[v]),Ze=c.useMemo(()=>rt.slice(0,500).map(b=>({sessionId:b.id,title:b.title,updatedAt:b.updatedAt})),[rt]),et=c.useMemo(()=>[...Me].flatMap(b=>{const L=le.find(tt=>tt.sessionId===b);if(L)return[L];const P=bt.get(b);if(P)return[{sessionId:b,title:P.title,updatedAt:P.updatedAt,snippet:null}];const H=Be.get(b);return H?[{sessionId:b,title:H.title,updatedAt:H.occurredAt,snippet:null}]:[]}),[le,Me,bt,Be]),jt=c.useMemo(()=>[...new Set([...et,...le].map(b=>b.sessionId))].filter(b=>!Ve[b]).join(`
2
+ `),[Ve,le,et]),He=c.useMemo(()=>y.payload?.minerRuns.find(b=>b.id===Te)??null,[Te,y.payload?.minerRuns]),Vt=Je||!!(He&&["queued","running","cancelling"].includes(He.status)),Ge=Le||Je||!!y.busyAction,Oe=R==="automatic_scope"||R==="evidence"&&B!=="from_prompt",$e=N==="workproduct"&&g.kind==="model",lt=c.useMemo(()=>C.find(b=>b.selectionKey===E)??null,[C,E]),ot=lt?.preference??null;c.useEffect(()=>(oe.current=!1,()=>{oe.current=!0,X.current+=1}),[]),c.useEffect(()=>_(s?.request.objective??a??""),[s?.id,a]),c.useEffect(()=>{if(E||!s)return;const b=Dn(C,s.request.preferredBaseModel,s.request.preferredBaseModelId);b&&T(b.selectionKey)},[C,s,E]),c.useEffect(()=>{if(R!=="automatic_scope"||Te)return;const b=y.payload?.minerRuns.find(L=>["queued","running","cancelling"].includes(L.status));b&&gt(b.id)},[Te,R,y.payload?.minerRuns]),c.useEffect(()=>{if(!Js(R,He))return;const b=new Set(He.candidateIds);xt(y.payload?.candidates.filter(L=>b.has(L.id))??[]),w("automatic_candidates")},[He,R,y.payload?.candidates]),c.useEffect(()=>{Oe&&(de([]),W(0),q(!1),be(null))},[O,Oe]),c.useEffect(()=>{if(!Oe)return;const b=X.current+1;X.current=b,Q(!0),be(null);const L=window.setTimeout(()=>{y.actions.searchChats(O,Ze,0,Bn).then(P=>{X.current===b&&(de(P.entries),W(P.total),q(P.hasMore),fe(P.indexing),J(P.indexedChats),K(P.totalChats))}).catch(P=>{X.current===b&&(de([]),W(0),q(!1),fe(!1),be(P instanceof Error?P.message:String(P)))}).finally(()=>{X.current===b&&Q(!1)})},220);return()=>window.clearTimeout(L)},[Ze,O,I,Oe,y.actions]),c.useEffect(()=>{if(!Oe||!O.trim()||!Ae)return;const b=window.setTimeout(()=>F(L=>L+1),1500);return()=>window.clearTimeout(b)},[O,Ae,Oe]);const re=c.useCallback(async()=>{if(ge||!Ne)return;const b=X.current,L=le.length;Q(!0);try{const P=await y.actions.searchChats(O,Ze,L,Bn);if(X.current!==b)return;de(H=>{const tt=new Set(H.map(Jt=>Jt.sessionId));return[...H,...P.entries.filter(Jt=>!tt.has(Jt.sessionId))]}),W(P.total),q(P.hasMore),fe(P.indexing),J(P.indexedChats),K(P.totalChats)}catch(P){X.current===b&&be(P instanceof Error?P.message:String(P))}finally{X.current===b&&Q(!1)}},[Ze,O,le.length,Ne,ge,y.actions]);c.useEffect(()=>{const b=Object.fromEntries(v.flatMap(L=>{const P=typeof L.metadata.messageCount=="number"?L.metadata.messageCount:null,H=typeof L.metadata.estimatedTokens=="number"?L.metadata.estimatedTokens:null;return P===null||H===null?[]:[[L.sessionId,{messageCount:P,estimatedTokens:H}]]}));Object.keys(b).length&&wt(L=>({...b,...L}))},[v]),c.useEffect(()=>{if(!Oe||!jt)return;let b=!1;const L=window.setTimeout(()=>{y.actions.estimateSources(jt.split(`
3
+ `)).then(P=>{b||wt(H=>({...H,...Object.fromEntries(P.map(tt=>[tt.sessionId,{messageCount:tt.messageCount,estimatedTokens:tt.estimatedTokens}]))}))}).catch(()=>{})},200);return()=>{b=!0,window.clearTimeout(L)}},[Oe,y.actions,jt]);const It=c.useMemo(()=>Ya([...Me],Ve),[Ve,Me]);function Kt(b){b!==B&&B!==null&&Se(!0),D(b)}function Ht(){if($e){w("base_model");return}Fe()}function Fe(){if(!($e&&!lt?.available)){if(B==="existing_dataset"){w("existing_dataset");return}if(Y){w("evidence");return}$==="automated"&&w("automatic_scope"),$==="manual"&&w("evidence")}}async function Gt(){if(!(!z||!h||!ot)){Ie(!0),_e(null);try{const b=await y.actions.createModelFromTaskset(z,ot);if(!b)throw new Error(y.error??"OpenPond could not create the Model from this Dataset.");const L=y.payload?.tasksets.find(P=>P.id===z);if(!L)throw new Error("The selected Dataset could not be reloaded.");await h(L,b)}catch(b){_e(b instanceof Error?b.message:String(b))}finally{Ie(!1)}}}function f(b){b!==ne&&Se(!0),_(b)}function te(b){Se(!0),ie(b),Z(L=>Qs(b,L,x))}function dt(b){Se(!0),Z(b)}function Wt(b){Se(!0),me(b)}function Cn(){Se(!0),ke(b=>{const L=new Set(b),P=le.length>0&&le.every(H=>L.has(H.sessionId));for(const H of le)P?L.delete(H.sessionId):L.add(H.sessionId);return L})}function wn(b,L){Se(!0),ke(P=>{const H=new Set(P);return L?H.add(b):H.delete(b),H})}async function $s(){const b=[],L=[];for(const P of Me){const H=Be.get(P);H?b.push(H):L.push(P)}if(L.length){const P=await y.actions.addSources(L);if(!P)throw new Error("OpenPond could not attach the selected evidence. Review the training error and try again.");b.push(...P)}if(b.length!==Me.size)throw new Error("Some selected evidence could not be resolved. Reselect the chats before continuing.");return b}async function Ds(){const b=[...Me];if(b.length){mt(!0);try{const L={...ae,enabled:!0},P=await y.actions.runMiner([],b,L);P&&gt(P.id)}finally{mt(!1)}}}async function Ls(){Te&&await y.actions.cancelMinerRun(Te)}function Bs(b){const L=new Set(b.evidence.flatMap(H=>H.sourceRefIds)),P=v.filter(H=>L.has(H.id)).map(H=>H.sessionId);ke(new Set(P)),ue(b.id),_(b.title),Se(!0),w("evidence")}async function Os(){Ie(!0),_e(null);try{if(p&&Y==="from_prompt"){if(!l)throw new Error("OpenPond could not continue from the Agent purpose.");await l({analysisModel:{providerId:V,modelId:he},objective:ne.trim()});return}const b=await $s(),L=G?.request.sourceIds.length===0?G.request.createImproveRunId:null;if(G&&!L&&De&&!["cancelled","failed","ready"].includes(G.state)){const H=G;await y.actions.cancelCreation(H.id)}const P=await y.actions.startCreation(b.map(H=>H.id),{surface:$==="automated"?"task_candidate":"training_page",mode:"defaults",entryMode:$??"manual",resourceIntent:N,objective:ne.trim()||void 0,methodHint:null,preferredBaseModel:$e?ot:null,candidateId:je,analysisModel:{providerId:V,modelId:he},analysisReasoningEffort:ee,createImproveRunId:L,targetIntent:g});if(!P)throw new Error(p?"OpenPond could not prepare the Agent review.":"OpenPond could not start Taskset authoring.");if(oe.current){$n(P)&&await y.actions.cancelCreation(P.id);return}Ke(P),Se(!1),P.state!=="awaiting_disclosure_approval"&&w("recommendation")}catch(b){oe.current||_e(b instanceof Error?b.message:String(b))}finally{oe.current||Ie(!1)}}async function Fs(){if(!(!G||G.state!=="awaiting_disclosure_approval")){Ie(!0);try{const b=await y.actions.approveDisclosure(G.id,!0);if(!b)return;Ke(b),w("recommendation")}finally{Ie(!1)}}}async function zs(){if(!(!G||G.state!=="failed")){Ie(!0),_e(null);try{const b=await y.actions.retryCreation(G.id);if(!b)throw new Error(y.error??(p?"OpenPond could not retry the Agent review.":"OpenPond could not retry Taskset authoring."));Ke(b),w("recommendation")}catch(b){_e(b instanceof Error?b.message:String(b))}finally{Ie(!1)}}}async function In(){G?.state==="awaiting_disclosure_approval"&&await y.actions.approveDisclosure(G.id,!1),Ke(null),Se(!0)}function qs(){if(R==="base_model")w("start");else if(R==="existing_dataset")w("base_model");else if(R==="automatic_scope")w(t?"evidence":$e?"base_model":"start");else if(R==="automatic_candidates")w("automatic_scope");else if(R==="evidence"){if(G?.state==="awaiting_disclosure_approval"&&In(),t&&o){o();return}w($==="automated"?"automatic_candidates":$e?"base_model":"start")}else R==="recommendation"&&w("evidence")}async function Rt(){if(oe.current)return;oe.current=!0,X.current+=1;const b=G;try{$n(b)&&await y.actions.cancelCreation(b.id)}finally{r()}}async function Us(){await Rt(),u()}async function Vs(){if(!(!G||G.state!=="awaiting_materialization_approval")){_e(null);try{const b=await y.actions.materialize(G.id,!0);if(!b)throw new Error(p?"OpenPond could not continue from the approved Agent review.":"OpenPond could not materialize the approved Taskset.");if(b.state==="ready"){await d(b);return}Ke(b)}catch(b){_e(b instanceof Error?b.message:String(b))}}}return e.jsxs(it,{ariaLabel:Ln(g,N),className:`training-dialog training-run-dialog ${R==="start"?"training-run-start-step":"training-run-workflow-step"}`,initialFocusKey:R,onClose:()=>{Rt()},children:[e.jsxs("div",{className:"training-dialog-header",children:[e.jsxs("div",{className:"training-run-dialog-title",children:[R!=="start"?e.jsx("button",{className:"training-icon-button",type:"button","aria-label":t&&R==="evidence"?"Back to Dataset sources":Za(R,$e,$),onClick:qs,children:e.jsx(xn,{size:16})}):null,e.jsx("h2",{children:R==="recommendation"?Xa(g,N):Ln(g,N)})]}),e.jsx("button",{className:"training-icon-button",type:"button","aria-label":"Close",onClick:()=>{Rt()},children:e.jsx(Xe,{size:16})})]}),R==="start"?e.jsx(Ha,{allowExistingDataset:$e&&!!h,mode:B,operation:g.operation,targetLabel:Zt(g,N),onChange:Kt,onContinue:Ht}):R==="base_model"?e.jsx(_a,{busy:y.busyAction==="scan-base-models",candidates:C,value:E,onChange:T,onContinue:Fe,onManage:()=>{Us()},onScan:()=>{y.actions.scanBaseModels()}}):R==="existing_dataset"?e.jsx($a,{busy:Ge,selectedTasksetId:z,state:y.payload,onChange:U,onCreate:()=>{Gt()}}):R==="automatic_scope"?e.jsx(Ra,{config:ae,estimatesBySessionId:Ve,estimate:It,matchingSessionCount:ye,onCancel:()=>{Ls()},onConfigChange:Ye,onLoadMore:()=>{re()},onScan:()=>{Ds()},onSearchChange:pe,onToggleSession:wn,onToggleVisible:Cn,run:He,scanning:Vt,search:O,searchError:Re,searchHasMore:Ne,searchIndexedChats:A,searchIndexing:Ae,searchLoading:ge,searchTotalChats:se,selectedEntries:et,selectedSessionIds:Me,targetLabel:Zt(g,N),visibleSessions:le}):R==="automatic_candidates"?e.jsx(wa,{candidates:ft,onRescan:()=>{gt(null),w("automatic_scope")},onSelect:Bs}):R==="evidence"&&($||Y)?e.jsx(Ka,{authoringModel:he,authoringProvider:V,authoringReasoningEffort:ee,busy:Ge,disclosurePending:G?.state==="awaiting_disclosure_approval",estimatesBySessionId:Ve,matchingSessionCount:ye,mode:Y??$,objective:ne,onObjectiveChange:f,onAnalyze:()=>{Os()},onApproveDisclosure:()=>{Fs()},onAuthoringModelChange:dt,onAuthoringProviderChange:te,onAuthoringReasoningEffortChange:Wt,onDeclineDisclosure:()=>{In()},onDiscoverFromConversations:t?()=>w("automatic_scope"):void 0,onSearchChange:pe,onLoadMore:()=>{re()},onReturnToRecommendation:()=>w("recommendation"),onToggleSession:wn,onToggleVisible:Cn,providerSettings:x,recommendationAvailable:!!G?.proposal&&!De,search:O,searchError:Re,searchHasMore:Ne,searchIndexedChats:A,searchIndexing:Ae,searchLoading:ge,searchTotalChats:se,selectedEntries:et,selectedEstimate:It,selectedSessionIds:Me,targetLabel:Zt(g,N),targetOperation:g.operation,visibleSessions:le}):R==="recommendation"&&G?.proposal?e.jsx(Va,{busy:Ge,creation:G,onAddChats:()=>w("evidence"),onClose:()=>{Rt()},onCreateTaskset:()=>{Vs()},onCreationChange:Ke,sources:v,training:y,createLabel:N==="dataset"?"Create Dataset":g.kind==="model"?"Create model":void 0,editDataLabel:N==="dataset"?"Edit sources":g.kind==="model"?"Edit Dataset":void 0,resourceIntent:N}):R==="recommendation"&&G?.state==="awaiting_questions"?e.jsxs("div",{className:"training-evidence-required",children:[e.jsx("div",{className:"training-dialog-scroll-body",children:e.jsxs("div",{className:"training-run-step-heading",children:[e.jsx("h3",{children:"More evidence is needed"}),e.jsx("p",{children:G.blockingQuestions[0]?.prompt??G.blockedReason??"Add supporting evidence before authoring continues."})]})}),e.jsx("div",{className:"training-dialog-actions",children:e.jsx("button",{className:"training-button",type:"button",onClick:()=>w("evidence"),children:N==="dataset"?"Edit sources":g.kind==="model"?"Edit Dataset":"Add chats"})})]}):R==="recommendation"&&G?.state==="failed"?e.jsxs("div",{className:"training-evidence-required",children:[e.jsxs("div",{className:"training-dialog-scroll-body",children:[e.jsxs("div",{className:"training-run-step-heading",children:[e.jsx("h3",{children:"Analysis failed"}),e.jsx("p",{children:Qa(G.blockedReason)})]}),ne?e.jsxs("div",{className:"training-evidence-objective",children:[e.jsx("span",{children:p?"Agent purpose":"Capability"}),e.jsx("strong",{children:ne})]}):null,e.jsx("p",{className:"training-empty",children:p?"Retry uses the same approved chats and model. Change chats starts a new review when the selection is no longer right for this Agent.":"Retry keeps the exact approved evidence, model, and disclosure receipt. Change evidence starts a new review if the selection is too large or no longer representative."})]}),e.jsxs("div",{className:"training-dialog-actions",children:[e.jsx("button",{className:"training-button secondary",type:"button",disabled:Ge,onClick:()=>w("evidence"),children:p?"Change chats":"Change evidence"}),e.jsxs("button",{className:"training-button",type:"button",disabled:Ge,onClick:()=>{zs()},children:[Le?e.jsx(we,{className:"spin",size:14}):null,"Retry approved evidence"]})]})]}):e.jsx("div",{className:"training-recommendation-loading",children:G?.state==="failed"?e.jsxs(e.Fragment,{children:[e.jsx("h3",{children:"Analysis failed"}),e.jsx("p",{children:G.blockedReason})]}):e.jsxs(e.Fragment,{children:[e.jsx(we,{className:"spin",size:18}),e.jsx("p",{children:p?"Preparing the Agent review…":"Preparing the recommendation…"})]})})]})}const ti=[{id:"build",title:"Build",description:"Create from a purpose, conversations, or both.",icon:pt,available:!0},{id:"huggingface",title:"Hugging Face",description:"Paste a Dataset URL or repository ID.",icon:Xs,available:!0},{id:"upload",title:"Upload file",description:"JSON, JSONL, CSV, and Parquet import is coming next.",icon:Ys,available:!1}];function ni({onClose:t,onSelect:n}){return e.jsxs(it,{ariaLabel:"New Dataset",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 Dataset"}),e.jsx("button",{"aria-label":"Close",className:"training-icon-button",type:"button",onClick:t,children:e.jsx(Xe,{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 the same immutable, Parquet-backed OpenPond Dataset."})]}),e.jsx("div",{"aria-label":"How to create a Dataset",className:"training-method-options training-start-mode-options",role:"list",children:ti.map(s=>{const a=s.icon;return e.jsxs("button",{"aria-describedby":s.available?void 0:`${s.id}-availability`,disabled:!s.available,type:"button",onClick:()=>n(s.id),children:[e.jsx("span",{className:"training-start-mode-icon","aria-hidden":"true",children:e.jsx(a,{size:18})}),e.jsxs("span",{className:"training-start-mode-copy",children:[e.jsxs("strong",{children:[s.title,s.available?null:e.jsx("span",{className:"dataset-source-availability",id:`${s.id}-availability`,children:"Coming next"})]}),e.jsx("small",{children:s.description})]})]},s.id)})})]})}const si=["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"],ai=["visible","privileged","metadata"];function ii({onBack:t,onClose:n,onImported:s,onOpenDatasetStorageSettings:a,training:i}){const[r,l]=c.useState(""),[o,u]=c.useState(null),[h,d]=c.useState(null),[m,x]=c.useState(""),[j,N]=c.useState(""),[S,v]=c.useState(!1),[y,g]=c.useState(null),k=c.useRef(null),M=i.payload?.datasetImports.find(T=>T.id===o?.id)??o,R=M?.inspection??null,w=!!(M&&["inspecting","materializing","validating","cancelling"].includes(M.status)),p=!R?.declaredLicense||["unknown","other"].includes(R.declaredLicense.toLowerCase()),B=c.useMemo(()=>R?.sourceFiles.reduce((T,z)=>T===null||z.sizeBytes===null?null:T+z.sizeBytes,0)??null,[R]);c.useEffect(()=>{!M||M.status!=="ready"||!M.tasksetId||k.current!==M.id&&(k.current=M.id,s(M.tasksetId))},[M,s]);async function D(){if(!r.trim())return;g(null);const T=await i.actions.inspectHuggingFaceDataset(r);if(!T){g(i.error??"OpenPond could not inspect this Dataset.");return}u(T),T.inspection&&T.mapping&&$(T)}function $(T){d(T.mapping),x(T.inspection?.title??T.locator?.repositoryId.split("/").at(-1)??"Imported Dataset"),N(T.inspection?.description?.trim().slice(0,2e3)||`Train and evaluate tasks from ${T.locator?.repositoryId??"this Dataset"}.`)}function Y(T,z){d(U=>U&&{...U,bindings:U.bindings.map((je,ue)=>ue===T?{...je,...z}:je)})}async function ne(){if(!M||!h||!m.trim()||!j.trim())return;g(null);const T=await i.actions.materializeDatasetImport(M.id,{name:m.trim(),objective:j.trim(),mapping:h,targetStorageRoot:null,licenseApproved:S});if(!T){g(i.error??"OpenPond could not start Dataset materialization.");return}u(T)}async function _(){if(!M)return;const T=await i.actions.cancelDatasetImport(M.id);T&&u(T)}const E=!!(R&&h)&&!["materializing","validating","ready","cancelling","cancelled"].includes(M?.status??"");return e.jsxs(it,{ariaLabel:"Import Hugging Face Dataset",className:"training-dialog training-run-dialog training-run-workflow-step dataset-import-dialog",dismissDisabled:w,initialFocusKey:R?"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 Dataset sources",className:"training-icon-button",type:"button",onClick:t,children:e.jsx(xn,{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(Xe,{size:16})})]}),R?E?e.jsxs("div",{className:"training-dialog-scroll-body dataset-import-review",children:[e.jsx(ri,{job:M,sourceBytes:B}),e.jsxs("label",{className:"training-objective-field",children:[e.jsx("span",{children:"Dataset name"}),e.jsx("input",{value:m,onChange:T=>x(T.target.value)})]}),e.jsxs("label",{className:"training-objective-field",children:[e.jsx("span",{children:"Purpose"}),e.jsx("textarea",{value:j,onChange:T=>N(T.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((T,z)=>e.jsxs("div",{children:[e.jsx("code",{children:T.sourcePath}),e.jsx("select",{"aria-label":`Target for ${T.sourcePath}`,value:T.target,onChange:U=>Y(z,{target:U.target.value}),children:si.map(U=>e.jsx("option",{value:U,children:hn(U)},U))}),e.jsx("select",{"aria-label":`Policy for ${T.sourcePath}`,value:T.policy,onChange:U=>Y(z,{policy:U.target.value}),children:ai.map(U=>e.jsx("option",{value:U,children:hn(U)},U))})]},`${T.sourcePath}:${z}`))})]}),p?e.jsxs("label",{className:"dataset-import-license-review",children:[e.jsx("input",{checked:S,type:"checkbox",onChange:T=>v(T.target.checked)}),e.jsx("span",{children:"I reviewed the repository license and approve importing this Dataset."})]}):null,M?.status==="failed"&&M.error?e.jsx("div",{className:"training-banner error",role:"alert",children:M.error}):null]}):e.jsx(li,{job:M}):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:w,placeholder:"BytedTsinghua-SIA/DAPO-Math-17k",value:r,onChange:T=>l(T.target.value)})]}),M?.status==="failed"&&M.error?e.jsx("div",{className:"training-banner error",role:"alert",children:M.error}):null]}),y?e.jsx("div",{className:"training-banner error",role:"alert",children:y}):null,e.jsx("div",{className:"training-dialog-actions",children:R?E?e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"training-button secondary",type:"button",onClick:a,children:"Dataset storage"}),e.jsx("button",{className:"training-button",disabled:!m.trim()||!j.trim()||!h||p&&!S,type:"button",onClick:()=>{ne()},children:"Import and save"})]}):w?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:M?.status==="cancelling",type:"button",onClick:()=>{_()},children:"Cancel import"})]}):e.jsx("button",{className:"training-button",type:"button",onClick:n,children:"Close"}):e.jsxs("button",{className:"training-button",disabled:!r.trim()||w,type:"button",onClick:()=>{D()},children:[w?e.jsx(we,{className:"spin",size:14}):null,"Inspect Dataset"]})})]})}function ri({job:t,sourceBytes:n}){const s=t.inspection,a=s.splits.reduce((i,r)=>i===null||r.rowCount===null?null:i+r.rowCount,0);return e.jsxs("div",{className:"dataset-import-summary",children:[e.jsxs("div",{children:[e.jsx("strong",{children:s.title}),e.jsxs("a",{href:s.locator.repositoryUrl,rel:"noreferrer",target:"_blank",children:["Open on Hugging Face ",e.jsx(Zs,{size:12})]})]}),e.jsxs("dl",{children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Revision"}),e.jsx("dd",{children:e.jsx("code",{children:s.resolvedRevision.slice(0,12)})})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Rows"}),e.jsx("dd",{children:a===null?"Unknown":a.toLocaleString()})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Source size"}),e.jsx("dd",{children:n===null?"Unknown":pn(n)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"License"}),e.jsx("dd",{children:s.declaredLicense??"Review required"})]})]}),e.jsx("p",{children:s.splits.map(i=>`${i.configuration}/${i.split}: ${i.rowCount?.toLocaleString()??"unknown"} rows`).join(" · ")})]})}function li({job:t}){const n=t.progress,s=n.totalBytes&&n.totalBytes>0?Math.min(100,n.completedBytes/n.totalBytes*100):null,i=(n.totalRows&&n.totalRows>0?Math.min(100,n.completedRows/n.totalRows*100):null)??s;return e.jsxs("div",{className:"training-dialog-scroll-body dataset-import-progress",role:"status",children:[e.jsx(we,{className:t.status==="ready"?"":"spin",size:22}),e.jsx("h3",{children:t.status==="ready"?"Dataset saved":"Importing Dataset"}),e.jsx("p",{children:t.progress.message}),e.jsx("div",{className:"dataset-import-progress-track",children:e.jsx("span",{style:{width:`${i??8}%`}})}),e.jsx("small",{children:n.completedRows?`${n.completedRows.toLocaleString()}${n.totalRows?` of ${n.totalRows.toLocaleString()}`:""} rows`:n.completedBytes?`${pn(n.completedBytes)}${n.totalBytes?` of ${pn(n.totalBytes)}`:""}`:hn(n.phase)}),t.error?e.jsx("div",{className:"training-banner error",children:t.error}):null]})}function hn(t){return t.replaceAll("_"," ").replace(/^./,n=>n.toUpperCase())}function pn(t){const n=["B","KB","MB","GB","TB"];let s=t,a=0;for(;s>=1024&&a<n.length-1;)s/=1024,a+=1;return`${s>=10?s.toFixed(0):s.toFixed(1)} ${n[a]}`}function xs({lineage:t,taskset:n,training:s,onChat:a,onClose:i}){Qe(s.error);const[r,l]=c.useState(!1),u=c.useMemo(()=>(s.payload?.servingSessions??[]).filter(N=>N.modelArtifactLineageId===t.id).sort((N,S)=>S.updatedAt.localeCompare(N.updatedAt)),[t.id,s.payload?.servingSessions])[0]??null,h=u&&["starting","ready","stopping"].includes(u.state)?u:null,d=!!s.busyAction;c.useEffect(()=>{!r||u?.state!=="ready"||(a(Ot({modelId:t.id,taskset:n})),i())},[t.id,a,i,u?.state,r,n]);async function m(){l(!0),await s.actions.startModelServing(t.id)||l(!1)}async function x(N){l(!1),await s.actions.stopModelServing(N.id)}function j(){a(Ot({modelId:t.id,taskset:n})),i()}return e.jsxs(it,{ariaLabel:`Use ${n.name}`,className:"training-dialog training-model-use-dialog",dismissDisabled:d,onClose:i,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:d,type:"button",onClick:i,children:e.jsx(Xe,{size:16})})]}),e.jsxs("div",{className:"training-model-use-summary",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Compute"}),e.jsx("strong",{children:"1× H100"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Rate"}),e.jsx("strong",{children:"$7.00/hour"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Idle stop"}),e.jsx("strong",{children:"5 minutes"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Hard stop"}),e.jsx("strong",{children:"10 minutes · $1.17 max"})]})]}),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."}),u?e.jsx(oi,{session:u}):e.jsx("p",{className:"training-model-use-note",children:"Start a temporary Fireworks deployment, attach this LoRA, then open a chat. OpenPond tears it down on idle, at the hard limit, or when you press Stop."}),e.jsxs("div",{className:"training-dialog-actions",children:[h?e.jsx("button",{className:"training-button secondary",disabled:d||h.state==="stopping",type:"button",onClick:()=>{x(h)},children:h.state==="stopping"?"Stopping…":"Stop serving"}):e.jsx("button",{className:"training-button secondary",disabled:d,type:"button",onClick:i,children:"Cancel"}),u?.state==="ready"?e.jsxs("button",{className:"training-button",disabled:d,type:"button",onClick:j,children:[e.jsx(Bt,{size:14}),"Chat now"]}):h?.state==="starting"?e.jsxs("button",{className:"training-button",disabled:!0,type:"button",children:[e.jsx(we,{className:"spin",size:14}),"Starting…"]}):e.jsxs("button",{className:"training-button",disabled:d,type:"button",onClick:()=>{m()},children:[d&&r?e.jsx(we,{className:"spin",size:14}):null,"Start & chat"]})]})]})}function oi({session:t}){const n=t.state==="starting"?"Starting Fireworks serving":t.state==="ready"?"Ready to chat":t.state==="stopping"?"Stopping Fireworks serving":t.state==="stopped"?"Serving stopped":"Serving failed",s=`$${t.estimatedCostUsd.toFixed(4)}`;return e.jsxs("div",{className:`training-model-serving-status ${t.state}`,children:[e.jsxs("div",{children:[e.jsx("strong",{children:n}),e.jsxs("span",{children:["Estimated serving cost ",s]})]}),t.state==="starting"||t.state==="stopping"?e.jsx("div",{className:"training-model-serving-progress","aria-label":n,children:e.jsx("span",{})}):null,t.stoppedAt?e.jsxs("small",{children:["Stopped ",new Date(t.stoppedAt).toLocaleString(),t.stopReason?` · ${di(t.stopReason)}`:""]}):null,t.error?e.jsx("small",{className:"error",children:t.error}):null]})}function di(t){return t==="idle"?"idle limit":t==="duration"?"10-minute limit":t==="budget"?"cost limit":t==="restart_cleanup"?"app restart cleanup":t==="startup_error"?"startup error":t==="shutdown"?"app shutdown":"stopped by user"}const ci=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 ui(t){const{connection:n,profileId:s}=t,[a,i]=c.useState([]),[r,l]=c.useState(!1),[o,u]=c.useState(null),h=c.useRef(null),d=c.useCallback(()=>{if(!n)return Promise.resolve(null);if(h.current)return h.current;l(!0);const x=ut.listCreateImproveRuns(n,{profileId:s,limit:500}).then(j=>(i(j.runs),u(null),j.runs)).catch(j=>(u(j instanceof Error?j.message:String(j)),null)).finally(()=>{h.current===x&&(h.current=null),l(!1)});return h.current=x,x},[n,s]);c.useEffect(()=>{if(!n){i([]),u(null);return}d()},[n,s,d]);const m=c.useMemo(()=>a.some(x=>ci.has(x.state)),[a]);return c.useEffect(()=>{if(!n)return;let x=!0,j=null;const N=async()=>{await d(),x&&(j=window.setTimeout(()=>{N()},m?1e3:15e3))};return j=window.setTimeout(()=>{N()},m?1e3:15e3),()=>{x=!1,j!==null&&window.clearTimeout(j)}},[n,m,d]),{runs:a,loading:r,error:o,refresh:d}}function xe({title:t,actions:n,children:s}){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:s})]})}const hi=64,pi=4096;function en(t,n=pi){return va(t,{minimum:hi,maximum:n})}const On=["q_proj","k_proj","v_proj","o_proj","gate_proj","up_proj","down_proj"],mi="accounts/fireworks/models/qwen3-8b",Nt=3,At=9.99,tn=32768,Fn=2048,zn=8192;function gi({baseModelCandidates:t,connection:n,taskset:s,modelId:a=null,destinations:i,initialMethod:r,preferredBaseModel:l=null,busy:o,busyAction:u=null,onClose:h,onStart:d,onPrepare:m,onConfirmPrepared:x,onOpenProviderSettings:j,onRunBaseline:N,baselineReports:S=[],baselineRuns:v=[]}){const y=s.readiness?.trainingPath??null,g=y?.primaryMethod??ji(s),k=y?.bootstrap??null,C=vi(s),M=r&&C.includes(r)?r:g==="grpo"?"grpo":"sft",R=yi(t,l),w=R?.executionOptions.find(f=>f.available&&f.methods.includes(M))??null,p=i.find(f=>f.destinationId==="fireworks"&&f.available&&f.methods.includes(M)),B=w?.destinationId??p?.destinationId??i.find(f=>f.destinationId==="local_cpu_fixture"&&f.available)?.destinationId??i.find(f=>f.available&&f.destinationId!=="export")?.destinationId??"local_cpu_fixture",[D,$]=c.useState(B),[Y,ne]=c.useState(null),_=w?R:Ni(t,B,M),[E,T]=c.useState(_?.selectionKey??""),[z,U]=c.useState("automatic"),[je,ue]=c.useState(()=>M==="grpo"?8:2),V=Vn(s,"train"),[ie,he]=c.useState(()=>Math.max(1,Math.min(V,M==="grpo"&&s.datasetArtifact?16:1e3))),[Z,ee]=c.useState(()=>{const f=en(s,B==="fireworks"?tn:void 0);return M==="grpo"&&s.datasetArtifact&&B==="fireworks"?Math.max(512,f):f}),[me,O]=c.useState(B==="fireworks"?8:2),[pe,le]=c.useState(()=>Un(_?.preference.modelId??"")),[de,ye]=c.useState(!1),[W,Ne]=c.useState(Nt),[q,ge]=c.useState(7),[Q,Re]=c.useState(8),[be,Ae]=c.useState(4),[fe,A]=c.useState(Fn),[J,se]=c.useState(()=>bs(s)),[K,I]=c.useState(M),[F,X]=c.useState(null),oe=i.find(f=>f.destinationId===D)??null,Me=K==="sft"&&g!=="sft"&&k?.method==="sft",ke=s.learningSignals.demonstrations.filter(f=>f.approved).length,Ve=Vn(s,"frozen_eval"),wt=c.useMemo(()=>Y?.inventory?.devices.filter(f=>f.available)??[],[Y?.inventory?.devices]),G=c.useMemo(()=>Y?.inventory?.models.filter(f=>f.trainingCompatible&&f.modelId&&f.revision&&f.tokenizerRevision&&f.chatTemplateHash)??[],[Y?.inventory?.models]),Ke=c.useMemo(()=>t.filter(f=>f.executionOptions.some(te=>te.destinationId===D&&te.methods.includes(K))),[t,D,K]),De=Ke.find(f=>f.selectionKey===E)??null,Se=De?.executionOptions.find(f=>f.destinationId===D&&f.methods.includes(K))??null,Le=De?.preference.modelId??"",Ie=De?.preference.modelAssetId?G.find(f=>f.id===De.preference.modelAssetId)??null:G.find(f=>f.modelId===Le)??null,ce=D==="fireworks",_e=s.datasetArtifact?"rft_easy_curriculum_v1":"stable_hash_top_n",Je={maxOutputTokens:fe,temperature:.8,topP:.95},mt=ga(S,{split:"train",taskCount:ie,attemptsPerTask:Q,selectionSeed:17,selectionStrategy:_e,model:{providerId:"fireworks",modelId:Le},sampling:Je}),Te=v.find(f=>f.tasksetHash===s.contentHash&&f.configuration.split==="train"&&f.configuration.taskLimit===ie&&f.configuration.attemptsPerTask===Q&&f.configuration.selectionSeed===17&&f.configuration.selectionStrategy===_e&&f.configuration.model.providerId==="fireworks"&&f.configuration.model.modelId===Le&&f.configuration.sampling.maxOutputTokens===Je.maxOutputTokens&&f.configuration.sampling.temperature===Je.temperature&&f.configuration.sampling.topP===Je.topP)??null,gt=Te?["queued","preparing","running","cancelling"].includes(Te.status):!1,ft=Te?.status==="failed",xt=u==="baseline"||gt,ae=s.datasetArtifact?mt:S.find(f=>f.id===s.readiness?.baselineReportId)??null,Ye=s.readiness?.baselineReward??null,Ee=K!=="grpo"||(s.datasetArtifact?mt?.rftSignal?.passed===!0:!!(s.readiness?.baselineReportId&&Ye&&Ye.count>=2&&(Ye.variance??0)>0&&(Ye.mean??0)>.05&&(Ye.mean??0)<.95)),rt=ae?Object.entries(ae.failureClusters).filter(([f])=>f==="infrastructure_failure").reduce((f,[,te])=>f+te,0):0,bt=ae?.attemptRefs.length??0,Be=!!(ae&&ae.reward.count===0&&rt>0),Ze=!!(ae?.rftSignal&&!ae.rftSignal.passed&&!Be),et=K==="grpo"&&ce&&s.datasetArtifact?Math.max(1,Math.min(32,V)):Math.max(1,Math.min(1e5,V)),jt=!ce||de&&W>=Nt&&W<=At&&Number.isInteger(q)&&q>=1&&q<=30,He=K==="sft"||K==="grpo"&&ce,Vt=s.capabilities.compatibleMethods.includes(K)||k?.method===K,Ge=!!(s.readiness?.ready&&Ee&&He&&oe?.available&&oe.methods.includes(K)&&Vt&&Se?.available&&(De?.preference.source!=="local"||Ie)&&jt),Oe=s.readiness?.ready?Ee?He?De?Se?.available?De.preference.source==="local"&&!Ie?"The selected local model is no longer present in the verified compute inventory. Scan Compute and select it again.":oe?.methods.includes(K)?oe?.unavailableReason??(ce&&!de?"Approve the bounded train-split export before launching Fireworks.":ce&&(W<Nt||W>At)?`Set a Fireworks cap from $${Nt.toFixed(2)} through $${At.toFixed(2)}.`:ce&&(!Number.isInteger(q)||q<1||q>30)?"Choose a provider retention record from 1 through 30 days.":null):`${Mt(D)} does not execute ${K.toUpperCase()}.`:Se?.unavailableReason??"The selected base model cannot run on this compute destination.":`Choose starting weights compatible with ${Mt(D)} and ${K.toUpperCase()}.`:`${K.toUpperCase()} is the primary recommendation but no compatible execution backend is available here.${k?" Choose the optional SFT trajectory bootstrap to run the local precursor.":""}`:"Verify mixed rewards on the selected train prompts before preparing a paid training quote.":"The Taskset must pass environment, grader, and data readiness before training.",$e=xi({method:K,taskset:s,destinationId:D,baseModelId:Le,maxSteps:je,sequenceLength:Z,rank:me,learningRate:pe,model:Ie,rolloutGroupSize:Q,rolloutConcurrency:be,rolloutMaxOutputTokens:fe,trainingExamples:ie,rftLossMethod:J}),lt={exportApproved:ce?de:!0,maximumCostUsd:ce?W:0,retentionDays:ce?q:null,region:null},ot=JSON.stringify({modelId:a,destinationId:D,recipe:$e,approval:lt}),re=F?.configurationKey===ot?F.value:null;c.useEffect(()=>{if(!n)return;let f=!0;return ut.computeState(n).then(te=>{f&&(ne(te),U(te.settings.defaultDeviceIds[0]??"automatic"))}).catch(()=>{}),()=>{f=!1}},[n]);async function It(){if(!Ge)return;if(ce&&!re){const te=await m(D,$e,lt);te&&X({configurationKey:ot,value:te});return}(ce&&re?await x(re,W):await d(D,$e,lt))&&h()}function Kt(f){if($(f),T(te=>qn(t,te,f,K)),f==="fireworks"){O(8),K==="grpo"&&(ue(8),s.datasetArtifact&&he(Math.max(1,Math.min(V,16)))),ee(Math.max(512,en(s,tn)));return}O(2),ee(en(s))}function Ht(f){if(I(f),X(null),T(te=>qn(t,te,D,f)),f==="grpo"){ue(8),D==="fireworks"&&s.datasetArtifact&&ee(te=>Math.max(512,te)),he(Math.max(1,Math.min(V,s.datasetArtifact?16:1e3)));return}ue(2)}const Fe=re?.plan.estimatedCostUsd??null,Gt=o?u==="baseline"?"Base-model test running":re?"Launching…":ce?"Preparing…":"Starting…":re&&Fe!=null?`Launch $${Fe.toFixed(2)} job`:ce?"Prepare exact quote":"Start training";return e.jsx("div",{className:"training-dialog-backdrop",role:"presentation",onMouseDown:o?void 0:h,children:e.jsxs("section",{className:"training-dialog training-start-dialog",role:"dialog","aria-modal":"true","aria-label":"Start training",onMouseDown:f=>f.stopPropagation(),children:[e.jsxs("div",{className:"training-dialog-header",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Start training"}),e.jsx("p",{children:s.name})]}),e.jsx("button",{type:"button","aria-label":"Close start training",disabled:o,onClick:h,children:e.jsx(Xe,{size:16})})]}),e.jsx("div",{className:"training-method-tabs",role:"tablist","aria-label":"Training method",children:C.map(f=>e.jsxs("button",{"aria-selected":f===K,className:f===K?"active":"",disabled:o,role:"tab",type:"button",onClick:()=>Ht(f),children:[e.jsx("span",{children:ca(f)}),e.jsx("strong",{children:at(f)})]},f))}),e.jsxs("div",{className:"training-start-fields",children:[e.jsxs("label",{children:[e.jsx("span",{children:"Base model"}),e.jsxs("select",{value:E,disabled:o,onChange:f=>{const te=f.target.value,dt=t.find(Wt=>Wt.selectionKey===te);T(te),le(Un(dt?.preference.modelId??""))},children:[e.jsx("option",{value:"",disabled:!0,children:"Choose compatible starting weights"}),Ke.map(f=>{const te=f.executionOptions.find(dt=>dt.destinationId===D&&dt.methods.includes(K));return e.jsxs("option",{value:f.selectionKey,disabled:!te?.available,children:[f.label," · ",f.sourceLabel,te?.available?"":` — ${te?.unavailableReason??"Unavailable"}`]},f.selectionKey)})]})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Compute"}),e.jsx("select",{value:D,disabled:o,onChange:f=>Kt(f.target.value),children:i.filter(f=>!["custom","runpod_byoc","export"].includes(f.destinationId)).map(f=>e.jsxs("option",{value:f.destinationId,disabled:!f.available,children:[Mt(f.destinationId),f.available?"":` — ${f.unavailableReason??"Unavailable"}`]},f.destinationId))})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Device"}),e.jsxs("select",{value:z,disabled:o||D!=="local_cpu_fixture",onChange:f=>U(f.target.value),children:[e.jsx("option",{value:"automatic",children:"Automatic"}),wt.map(f=>e.jsx("option",{value:f.id,children:f.name},f.id))]})]})]}),ce?e.jsxs("fieldset",{className:"training-provider-approval",children:[e.jsx("legend",{children:"Provider approval"}),j?e.jsx("button",{className:"training-text-button",type:"button",disabled:o,onClick:()=>{h(),j()},children:"Manage Fireworks provider"}):null,e.jsxs("label",{className:"training-provider-consent",children:[e.jsx("input",{type:"checkbox",checked:de,disabled:o,onChange:f=>ye(f.target.checked)}),e.jsx("span",{children:"Export only the approved train split to Fireworks. Frozen Eval cases and grader secrets stay in OpenPond."})]}),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:Nt,max:At,step:.01,value:W,disabled:o,onChange:f=>Ne(f.target.valueAsNumber)})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Retention record (days)"}),e.jsx("input",{"aria-label":"Retention record (days)",type:"number",min:1,max:30,step:1,value:q,disabled:o,onChange:f=>ge(f.target.valueAsNumber)})]})]}),e.jsx("p",{className:"training-start-note",children:"Approval is bound server-side to the signed-in OpenPond account at launch."}),K==="grpo"?e.jsxs("p",{className:"training-start-note",children:["RFT requires a public HTTPS callback ending in ",e.jsx("code",{children:"/v1/training/fireworks/rft"}),". Launch fails closed before provider upload when it is missing or invalid."]}):null]}):null,e.jsxs("dl",{className:"training-start-summary",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Training data"}),e.jsx("dd",{children:K==="grpo"?`${Math.min(ie,V)} of ${V} approved train prompts`:`${Math.min(ie,ke||V)} approved example${ie===1?"":"s"}`})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Evaluation"}),e.jsxs("dd",{children:[Ve," test example",Ve===1?"":"s"]})]}),e.jsxs("div",{children:[e.jsx("dt",{children:Fe==null?"Estimate":"Exact quote"}),e.jsx("dd",{children:D==="local_cpu_fixture"?Ie?`$0 · ${je} steps × ${Z} tokens · 15-minute hard stop`:"$0 · 2-minute hard stop":ce?Fe==null?`Prepare a provider-validated quote · hard cap $${Number.isFinite(W)?W.toFixed(2):"—"}`:`$${Fe.toFixed(2)} · hard cap $${W.toFixed(2)}`:"Provided before approval"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Storage"}),e.jsx("dd",{children:ce?"Portable output imported into app-managed storage":Y?.settings.modelStorePath??"App-managed local storage"})]})]}),re?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:re.approvalActor??"Local user"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Provider"}),e.jsx("dd",{children:Mt(re.plan.destinationId)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Model"}),e.jsx("dd",{children:ki(re.plan.recipe.method==="sft"||re.plan.recipe.method==="grpo"?re.plan.recipe.baseModel.id:"")})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Method"}),e.jsx("dd",{children:re.plan.recipe.method==="grpo"?`RFT · ${bi(re.plan.recipe.loss.method)}`:`${at(re.plan.recipe.method)} · ${re.plan.recipe.parameterization.toUpperCase()}`})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Quote"}),e.jsx("dd",{children:Fe==null?"Unavailable":`$${Fe.toFixed(2)}`})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Maximum"}),e.jsxs("dd",{children:["$",W.toFixed(2)]})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Retention"}),e.jsxs("dd",{children:[re.plan.dataPolicy.retentionDays," days"]})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Prepared data"}),e.jsxs("dd",{children:[Si(re.bundle.totalSizeBytes)," · verified"]})]}),re.plan.rftSignalGate?e.jsxs("div",{children:[e.jsx("dt",{children:"Train signal"}),e.jsxs("dd",{children:[re.plan.rftSignalGate.signal.mixedRewardGroups," mixed groups · verified"]})]}):null]}),e.jsx("p",{children:"No Fireworks dataset or job exists until you launch."})]}):null,K==="grpo"&&ce?e.jsxs("section",{className:"training-prepared-confirmation","aria-label":s.datasetArtifact?"Train-signal check":"Base-model test",children:[e.jsxs("div",{children:[e.jsx("strong",{children:s.datasetArtifact?Ee?"Train signal verified":Be||ft?"Train-signal check failed":ae?.rftSignal?.parseableAttempts===0?"No final answers returned":Ze?"Not enough train signal":"Check train signal":Ee?"Base-model test complete":Be?"Base-model test failed":"Test the base model"}),e.jsx("span",{children:s.datasetArtifact?Ee&&ae?`${ae.rftSignal?.mixedRewardGroups??0} of ${ae.scope?.taskCount??ie} prompts produced both correct and incorrect rewards · ${ae.rftSignal?.correctAttempts??0} of ${ae.rftSignal?.eligibleAttempts??0} answers correct · $${(ae.totalCostUsd??0).toFixed(2)} recorded cost.`:ft?`${Te?.error??"The train-signal check failed before it completed."} No training job was started.`:Be?`${rt} of ${bt} attempts failed before grading. No training job was started.`:ae?.rftSignal?.parseableAttempts===0?`All ${ae.rftSignal.eligibleAttempts} requests completed, but none returned a parseable final answer. No training job was started.`:Ze?`${ae?.rftSignal?.mixedRewardGroups??0} of ${ie} prompts produced mixed rewards; ${ae?.rftSignal?.requiredMixedRewardGroups??4} are required. No training job was started.`:`Run ${ie} selected train prompts with ${Q} candidates each. At least 4 prompts must produce both correct and incorrect rewards before training can launch.`:Ee&&ae?`${ae.reward.count} graded attempts · ${(100*(ae.reward.mean??0)).toFixed(0)}% correct · $${(ae.totalCostUsd??0).toFixed(2)} recorded cost.`:Be?`${rt} of ${bt} attempts failed before grading. No training job was started.`:"Run 8 held-back prompts with 4 attempts each before training. Answers and grading stay inside OpenPond."}),Ee?null:e.jsxs("span",{children:[s.datasetArtifact?"The check":"The test"," may start one temporary Fireworks deployment, capped at 10 minutes (up to $1.17), and removes it when finished."]})]}),Ee?null:e.jsx("button",{className:"training-button secondary",type:"button",disabled:xt||!Le||!N,onClick:()=>{!N||!Le||N({providerId:"fireworks",modelId:Le},{targetModelId:a,taskLimit:s.datasetArtifact?ie:8,attemptsPerTask:s.datasetArtifact?Q:4,selectionSeed:17,split:s.datasetArtifact?"train":"frozen_eval",selectionStrategy:_e,sampling:Je})},children:s.datasetArtifact?xt?fi(Te):ae||ft?"Retry train-signal check":"Run train-signal check":xt?"Testing base model…":Be?"Retry base-model test":"Test base model"})]}):null,Me&&k?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:k.limitations.map(f=>e.jsx("li",{children:f},f))})]}):null,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:et,value:ie,onChange:f=>he(Math.max(1,Math.min(et,f.target.valueAsNumber||1)))})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Optimizer steps"}),e.jsx("input",{type:"number",min:1,max:1e3,value:je,onChange:f=>ue(f.target.valueAsNumber||1)})]}),e.jsxs("label",{children:[e.jsx("span",{children:K==="grpo"?"Prompt length":"Sequence length"}),e.jsx("input",{type:"number",min:16,max:ce?tn:4096,value:Z,onChange:f=>ee(f.target.valueAsNumber||64)})]}),K==="grpo"?e.jsxs("label",{children:[e.jsx("span",{children:"Maximum output"}),e.jsx("input",{type:"number",min:16,max:zn,value:fe,onChange:f=>A(Math.max(16,Math.min(zn,f.target.valueAsNumber||Fn)))})]}):null,e.jsxs("label",{children:[e.jsx("span",{children:"LoRA rank"}),e.jsx("input",{type:"number",min:1,max:256,value:me,onChange:f=>O(f.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:pe,onChange:f=>{const te=f.target.valueAsNumber;Number.isFinite(te)&&le(te)}})]}),K==="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:f=>se(f.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:Q,onChange:f=>Re(f.target.valueAsNumber||8)})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Concurrent rollouts"}),e.jsx("input",{type:"number",min:1,max:16,value:be,onChange:f=>Ae(f.target.valueAsNumber||4)})]})]}):null]})]}),!Ge&&(Ee||K!=="grpo"||!ce)?e.jsx("div",{className:"training-banner error training-dialog-error",children:Oe??"This setup is unavailable."}):oe?.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.jsxs("div",{className:"training-dialog-actions",children:[e.jsx("button",{className:"training-button secondary",type:"button",disabled:o,onClick:h,children:"Cancel"}),e.jsx("button",{className:"training-button",type:"button",disabled:o||!Ge,onClick:()=>{It()},children:Gt})]})]})})}function fi(t){return t?t.status==="cancelling"?"Cancelling train-signal check…":t.progress.stage==="provisioning"?"Preparing Fireworks capacity…":t.progress.stage==="running"?`Checking train signal… ${t.progress.completedAttempts}/${t.progress.totalAttempts}`:t.progress.stage==="cleaning_up"?"Removing temporary deployment…":"Checking train signal…":"Starting train-signal check…"}function xi(t){if(t.method==="grpo"&&t.destinationId==="fireworks"){const n=t.taskset.metadata.toolContractHash===Qt||t.taskset.environment.metadata.toolContractHash===Qt,s=t.taskset.graders.find(a=>a.rewardEligible);return{schemaVersion:"openpond.rftRecipe.v1",method:"grpo",parameterization:"lora",baseModel:{id:t.baseModelId,revision:"fireworks-managed-model-resource-v1",tokenizerRevision:"fireworks-provider-managed",chatTemplateHash:"fireworks-qwen3-chat-v1"},dataset:{trainSplit:"train",validationSplit:"frozen_eval",maxPromptTokens:t.sequenceLength,maxExamples:t.trainingExamples,selectionStrategy:t.taskset.datasetArtifact?"rft_easy_curriculum_v1":"stable_hash_top_n"},lora:{rank:t.rank},rollout:{groupSize:t.rolloutGroupSize,concurrency:t.rolloutConcurrency,maxTurns:n?15:1,maxOutputTokens:t.rolloutMaxOutputTokens,temperature:.8,topP:.95,seed:17},optimizer:{learningRate:t.learningRate,maxSteps:t.maxSteps},loss:{method:t.rftLossMethod??bs(t.taskset),klBeta:null},reward:n?{graderId:"cross-system-exact-verifier",graderHash:"server-derived-grader-hash",environmentId:"cross-system-operations",environmentVersion:ea,toolContractHash:Qt}:{graderId:s?.id??"math_final_answer",graderHash:"server-derived-grader-hash",environmentId:sa,environmentVersion:na,toolContractHash:ta},resourceLimits:{wallTimeMs:18e4,maxRollouts:Math.max(t.rolloutGroupSize,t.trainingExamples*t.rolloutGroupSize),maxPayloadBytes:1e6}}}return t.destinationId==="fireworks"?{schemaVersion:"openpond.sftRecipe.v1",method:"sft",parameterization:"lora",baseModel:{id:t.baseModelId,revision:"fireworks-managed-model-resource-v1",tokenizerRevision:"fireworks-provider-managed",chatTemplateHash:"fireworks-qwen3-chat-v1"},dataset:{trainSplit:"train",validationSplit:"frozen_eval",completionOnly:!0,maxSequenceLength:t.sequenceLength,maxExamples:t.trainingExamples},lora:{rank:t.rank,alpha:t.rank*2,dropout:.05,targetModules:On},optimizer:{learningRate:t.learningRate,epochs:1,maxSteps:t.maxSteps,batchSize:1,gradientAccumulationSteps:1,seed:17},resourceLimits:{cpuThreads:1,memoryBytes:1e9,wallTimeMs:36e5}}:!t.model?.modelId||!t.model.revision||!t.model.tokenizerRevision||!t.model.chatTemplateHash?{schemaVersion:"openpond.sftRecipe.v1",method:"sft",parameterization:"lora",baseModel:{id:"openpond/tiny-cpu-gpt2-fixture",revision:"architecture-v2-seed-17-context-512",tokenizerRevision:"wordlevel-v1",chatTemplateHash:"fixture00000000"},dataset:{trainSplit:"train",validationSplit:"frozen_eval",completionOnly:!0,maxSequenceLength:t.sequenceLength,maxExamples:t.trainingExamples},lora:{rank:t.rank,alpha:t.rank*2,dropout:0,targetModules:["c_attn"]},optimizer:{learningRate:t.learningRate,epochs:1,maxSteps:t.maxSteps,batchSize:1,gradientAccumulationSteps:1,seed:17},resourceLimits:{cpuThreads:4,memoryBytes:2e9,wallTimeMs:12e4}}:{schemaVersion:"openpond.sftRecipe.v1",method:"sft",parameterization:"lora",baseModel:{id:t.model.modelId,revision:t.model.revision,tokenizerRevision:t.model.tokenizerRevision,chatTemplateHash:t.model.chatTemplateHash},dataset:{trainSplit:"train",validationSplit:"frozen_eval",completionOnly:!0,maxSequenceLength:t.sequenceLength,maxExamples:t.trainingExamples},lora:{rank:t.rank,alpha:t.rank*2,dropout:.05,targetModules:On},optimizer:{learningRate:t.learningRate,epochs:1,maxSteps:t.maxSteps,batchSize:1,gradientAccumulationSteps:1,seed:17},resourceLimits:{cpuThreads:4,memoryBytes:8e9,wallTimeMs:9e5}}}function bs(t){return t.sourceRefs.some(s=>{const a=s.metadata;return("repositoryId"in s?String(s.repositoryId):"").toLowerCase().includes("dapo-math")||s.title.toLowerCase().includes("dapo-math")||String(a.datasetName??"").toLowerCase().includes("dapo-math")})?"dapo":"grpo"}function bi(t){return t==="gspo-token"?"GSPO-token":t.toUpperCase()}function qn(t,n,s,a){return t.find(r=>r.selectionKey===n)?.executionOptions.some(r=>r.destinationId===s&&r.methods.includes(a))?n:""}function Un(t){return t==="openpond/tiny-cpu-gpt2-fixture"?.01:2e-4}function ji(t){const n=t.metadata.trainingMethod;return typeof n=="string"&&n!=="none"?n:t.readiness?.recommendedMethod&&t.readiness.recommendedMethod!=="none"?t.readiness.recommendedMethod:"sft"}function vi(t){const n=new Set;for(const a of t.capabilities.compatibleMethods)(a==="sft"||a==="grpo")&&n.add(a);t.readiness?.trainingPath?.bootstrap?.method==="sft"&&n.add("sft"),t.readiness?.trainingPath?.primaryMethod==="grpo"&&n.add("grpo");const s=[];return n.has("sft")&&s.push("sft"),n.has("grpo")&&s.push("grpo"),s.length?s:["sft"]}function Vn(t,n){return t.datasetArtifact?.splitCounts[n]??t.tasks.filter(s=>s.split===n).length}function Mt(t){return{export:"Export only",local_cpu_fixture:"Local CPU",local_cuda:"Local NVIDIA GPU",local_mlx:"Apple Silicon",ssh_gpu:"SSH GPU",prime_hosted:"Prime hosted",fireworks:"Fireworks",openpond_managed:"OpenPond managed"}[t]??t.replaceAll("_"," ")}function yi(t,n){return n?t.find(s=>s.preference.modelId===n.modelId&&s.preference.source===n.source&&s.preference.revision===n.revision&&s.preference.modelAssetId===n.modelAssetId)??t.find(s=>s.preference.modelId===n.modelId)??null:null}function Ni(t,n,s){const a=t.filter(i=>i.executionOptions.some(r=>r.destinationId===n&&r.available&&r.methods.includes(s)));return n==="fireworks"?a.find(i=>i.preference.modelId===mi)??a[0]??null:a[0]??null}function ki(t){return t==="accounts/fireworks/models/qwen3-8b"?"Qwen3 8B · Fireworks managed LoRA":t==="accounts/fireworks/models/qwen3-0p6b"?"Qwen3 0.6B · Fireworks managed LoRA":t.split("/").at(-1)??t}function Si(t){return t==null?"size unknown":t<1024?`${t} B`:t<1024**2?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(0)} MB`}const Ci=new Set(["released","rejected","ready","ready_local","published_hosted","cancelled"]);function js(t){const n=new Map,s=wi(t.runs,t.training),a=new Date(0).toISOString();for(const i of t.profile?.agents??[]){const r=Ue("agent",i.id),l=t.profile?.actionCatalog.find(o=>o.agentId===i.id&&o.sourceActionId==="chat"&&o.visibility!=="internal"&&o.visibility!=="debug")??null;n.set(r,{key:r,kind:"agent",id:i.id,name:i.name||i.id,description:i.enabled?"Enabled Profile Agent":"Disabled Profile Agent",status:i.enabled?"Ready":"Disabled",updatedAt:t.profile?.lastCheck?.checkedAt??a,path:i.path,enabled:i.enabled,runIds:[],conversationId:null,tasksetId:null,frontierBaselineRunId:null,trainingRunCount:0,evaluationStatus:"not_run",useActionId:l?.id??null})}for(const i of t.profile?.skills??[]){const r=Ue("skill",i.name);n.set(r,{key:r,kind:"skill",id:i.name,name:i.name,description:i.description,status:i.validationStatus==="valid"?"Ready":i.validationStatus,updatedAt:a,path:i.path,enabled:i.enabled,runIds:[],conversationId:null,tasksetId:null,frontierBaselineRunId:null,trainingRunCount:0,evaluationStatus:"not_run",useActionId:null})}for(const i of ua(t.training)){if(i.taskset.metadata.resourceIntent==="dataset"&&!i.latestPlan&&!i.localModel)continue;const r=t.runs.filter(h=>h.target.kind==="model"&&h.tasksetRef?.id===i.taskset.id).sort((h,d)=>d.updatedAt.localeCompare(h.updatedAt))[0]??null,l=r?.target.kind==="model"?s.get(r.id)??r.target.id??r.id:i.latestPlan?.modelId??i.taskset.id,o=Ue("model",l),u=n.get(o);n.set(o,{key:o,kind:"model",id:l,name:Lt(r?.target.displayName??i.name,"New model"),description:i.taskset.objective,status:i.status,updatedAt:i.updatedAt,path:`tasksets/${i.taskset.id}`,enabled:i.localModel?i.localModel.status==="imported"&&i.localModel.promotable:null,runIds:r?[...new Set([...u?.runIds??[],r.id])]:u?.runIds??[],conversationId:null,tasksetId:i.taskset.id,frontierBaselineRunId:null,trainingRunCount:Math.max(u?.trainingRunCount??0,i.runCount),evaluationStatus:i.latestJob?.metadata.frozenEvaluationComplete===!0?i.latestJob.metadata.frozenEvaluationThresholdPassed===!0?"passed":"failed":"not_run",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))continue;const r=i.target.kind,l=i.target.kind==="model"?s.get(i.id)??i.target.id??i.id:i.target.id??i.id,o=Ue(r,l),u=n.get(o),h=r==="agent"?_i(i,u?.name??null):i.target.displayName??u?.name??Mi(i),d=r==="model"?Lt(h,"New model"):h;n.set(o,{key:o,kind:r,id:l,name:d,description:u?.description??i.objective,status:Ei(i),updatedAt:Gn(u?.updatedAt,i.updatedAt),path:u?.path??i.plan?.sourcePlan[0]?.path??null,enabled:u?.enabled??null,runIds:[...new Set([...u?.runIds??[],i.id])],conversationId:i.scope.conversationId??u?.conversationId??null,tasksetId:i.target.kind==="model"?i.tasksetRef?.id??u?.tasksetId??null:null,frontierBaselineRunId:u?.frontierBaselineRunId??null,trainingRunCount:u?.trainingRunCount??0,evaluationStatus:Pi(i)??u?.evaluationStatus??"not_run",useActionId:u?.useActionId??null})}for(const i of t.training?.frontierBaselineRuns??[]){const r=Ri(i,t.runs);if(!r)continue;const l=[...n.values()].find(h=>h.runIds.includes(r));if(!l)continue;const o=l.tasksetId?t.training?.tasksets.find(h=>h.id===l.tasksetId)??null:null;if(o&&!Ii(i,o))continue;const u=l.frontierBaselineRunId?t.training?.frontierBaselineRuns.find(h=>h.id===l.frontierBaselineRunId)??null:null;u&&u.updatedAt>=i.updatedAt||n.set(l.key,{...l,updatedAt:Gn(l.updatedAt,i.updatedAt),frontierBaselineRunId:i.id})}return[...n.values()].sort((i,r)=>{const l=Number(Kn(i,t.runs))-Number(Kn(r,t.runs));return l!==0?-l:r.updatedAt.localeCompare(i.updatedAt)||i.name.localeCompare(r.name)})}function wi(t,n){const s=new Map,a=n?.plans??[],i=n?.jobs??[],r=n?.models??[],l=new Map(a.map(h=>[h.id,h])),o=new Map(i.map(h=>[h.id,h])),u=new Map;for(const h of t){if(h.target.kind!=="model"||!h.tasksetRef)continue;const d=u.get(h.tasksetRef.id)??[];d.push(h),u.set(h.tasksetRef.id,d)}for(const[h,d]of u){const m=new Set;for(const S of a)S.tasksetId===h&&S.modelId&&m.add(S.modelId);for(const S of r)S.tasksetId===h&&S.modelId&&m.add(S.modelId);if(m.size>1)continue;const x=d.filter(S=>S.target.kind!=="model"?!1:S.target.trainingPlanId||S.target.trainingJobId||S.target.artifactId?!0:a.some(v=>v.tasksetId===h&&v.modelId===(S.target.id??S.id)));if(!x.length)continue;const N=[...m][0]??null??[...x].sort((S,v)=>v.updatedAt.localeCompare(S.updatedAt))[0].target.id??x[0].id;for(const S of x){if(S.target.kind!=="model")continue;const v=(S.target.trainingPlanId?l.get(S.target.trainingPlanId):null)??(S.target.trainingJobId?l.get(o.get(S.target.trainingJobId)?.planId??""):null);v?.modelId&&v.modelId!==N||s.set(S.id,N)}}return s}function Ii(t,n){if(["queued","running","cancelling"].includes(t.status))return!0;const s=new Set(n.sourceRefs.map(a=>a.id));return t.sourceIds.length===s.size&&t.sourceIds.every(a=>s.has(a))}function Ri(t,n){if(t.createImproveRunId&&n.some(a=>a.id===t.createImproveRunId&&a.target.kind==="model"))return t.createImproveRunId;if(t.sourceIds.length===0)return null;const s=new Set(t.sourceIds);return n.find(a=>a.target.kind==="model"&&[...s].every(i=>a.sourceRefs.includes(i)))?.id??null}function Ue(t,n){return`${t}:${n}`}function Ai(t){return t==="agent"?"Agents":t==="skill"?"Skills":t==="extension"?"Extensions":"Models"}function vs(t,n){const s=new Set(t.runIds);return n.filter(a=>s.has(a.id)).sort((a,i)=>i.updatedAt.localeCompare(a.updatedAt))}function Kn(t,n){const s=new Set(t.runIds);return n.some(a=>s.has(a.id)&&!Ci.has(a.state))}function Mi(t){return`${t.operation==="improve"?"Improve":"Create"} ${t.target.kind}`}function _i(t,n){const s=Hn(t.target.displayName);if(s)return s;const a=Hn(n);if(a)return a;const i=t.objective.split(/[.!?\n]|[,;](?=\s)/,1)[0]?.replace(/^(?:please\s+)?(?:create|make|build|improve)\s+(?:an?\s+)?agent\s+(?:that\s+|to\s+)?/i,"").trim();return`${Lt(i,"New agent")} · ${Ti(t.id)}`}function Ti(t){return(t.split(/[^a-z0-9]+/i).filter(Boolean).at(-1)??t).slice(-6).toUpperCase().padStart(4,"0")}function Hn(t){const n=t?.trim()??"";if(!n)return null;const s=n.toLowerCase().replace(/[^a-z0-9]+/g," ").trim();return/^(?:create|creating|improve|improving|new) (?:an )?agent$/.test(s)?null:n}function Ei(t){return t.state.replaceAll("_"," ")}function Pi(t){const n=t.evaluationReceipts.filter(s=>s.subject==="candidate"||s.subject==="post_release");return n.length?n.some(s=>s.status==="failed"||s.status==="blocked"||s.publishGate==="failed")?"failed":n.every(s=>s.status==="passed"&&s.publishGate!=="failed")?"passed":null:null}function Gn(t,n){return t&&t.localeCompare(n)>=0?t:n}function $i({agentId:t,evals:n,onAttach:s,onCreate:a}){const i=c.useMemo(()=>n.filter(o=>o.agentId===null||o.agentId===t),[t,n]),[r,l]=c.useState(i[0]?.id??"");return c.useEffect(()=>{i.some(o=>o.id===r)||l(i[0]?.id??"")},[i,r]),e.jsxs("div",{className:"labs-eval-actions",children:[e.jsxs("button",{className:"training-button secondary",type:"button",onClick:a,children:[e.jsx(cs,{size:13}),"Create Eval"]}),i.length?e.jsxs(e.Fragment,{children:[e.jsx(on,{compact:!0,searchable:!0,label:"Existing Eval",options:i.map(o=>({value:o.id,label:o.name,shortLabel:o.name,description:o.path})),value:r,onChange:l}),e.jsx("button",{className:"training-button secondary",disabled:!r,type:"button",onClick:()=>s(r),children:"Add Eval"})]}):null]})}function ve({label:t,value:n=t}){return e.jsx("span",{className:`labs-status-badge ${ys(n)}`,children:t})}function ys(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 mn({decorative:t=!1,label:n,size:s="default",tone:a,value:i=n}){return e.jsx("span",{"aria-hidden":t||void 0,"aria-label":t?void 0:n,className:`labs-status-dot ${a??ys(i)} ${s}`,role:t?void 0:"status",title:n})}function Di({candidate:t,diff:n,error:s,run:a,onApplyCandidate:i,onOpenFiles:r,onRejectCandidate:l}){const[o,u]=c.useState(null),d=c.useMemo(()=>a.evaluationReceipts.filter(v=>v.candidateId===t.id),[t.id,a.evaluationReceipts]).filter(v=>v.subject==="candidate"),x=d.length>0&&d.every(v=>v.status==="passed"&&v.publishGate!=="failed")&&(a.state==="awaiting_promotion"||a.state==="blocked"&&!!a.localProfileCommit),j=a.state==="reconciling_release",N=n?.filesChanged??t.git?.changedPaths.length??0;async function S(v,y){if(!o){u(v);try{await y()}finally{u(null)}}}return e.jsxs("div",{className:"labs-change-page",children:[a.blockedReason?e.jsx("div",{className:"labs-change-message negative",children:a.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:a.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:gn(N)})]}),e.jsxs("div",{className:"labs-change-card-body",children:[e.jsx("h3",{children:"Drafted update"}),e.jsx("p",{children:Li(t,n,s)})]}),e.jsx("footer",{className:"labs-change-card-footer end",children:e.jsx("button",{className:"training-button secondary",disabled:!!s,title:s??void 0,type:"button",onClick:r,children:s?"Files unavailable":`Files${N?` (${N})`:""}`})})]})}),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:Bi(d)})]}),e.jsx("div",{className:"labs-change-evals",children:d.length?d.map(v=>e.jsxs("div",{className:"labs-change-eval",children:[e.jsxs("div",{children:[e.jsx("strong",{children:v.summary??"Agent Evals"}),e.jsx("span",{children:v.summaryCounts?`${v.summaryCounts.passed}/${v.summaryCounts.total} passed`:v.status})]}),e.jsx(ve,{label:v.status,value:v.status})]},v.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(mn,{label:Wn(a),value:a.state}),Wn(a)]}),e.jsxs("div",{className:"labs-change-actions",children:[e.jsx("button",{className:"training-button secondary",disabled:!!o||j||a.state!=="awaiting_promotion",type:"button",onClick:()=>{S("reject",()=>l(a,t.id))},children:o==="reject"?"Keeping current version":"Keep current version"}),e.jsx("button",{className:"training-button",disabled:!x||!!o||j,type:"button",onClick:()=>{S("apply",()=>i(a,t.id))},children:j||o==="apply"?"Applying":a.state==="blocked"?"Re-run Evals":"Apply update"})]})]})]})})]})]})}function gn(t){return`${t} ${t===1?"file":"files"}`}function Li(t,n,s){if(s)return s;const a=n?.filesChanged??t.git?.changedPaths.length??0;return a?n?`${gn(a)} drafted · +${n.additions} −${n.deletions}`:`${gn(a)} drafted for this Agent. Open Files to review the changes.`:"The drafted Agent update is ready, but no file summary is available yet."}function Bi(t){if(!t.length)return"Waiting for Agent Evals";const n=t.reduce((a,i)=>({passed:a.passed+(i.summaryCounts?.passed??0),tests:a.tests+(i.summaryCounts?.total??0)}),{passed:0,tests:0});return n.tests>0?`${n.passed}/${n.tests} Evals passed`:`${t.filter(a=>a.status==="passed").length}/${t.length} Eval results passed`}function Wn(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 Oi({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(s=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("button",{type:"button",onClick:()=>n(s),children:[e.jsx("strong",{children:s.objective}),e.jsx("span",{children:zi(s)})]})}),e.jsx("td",{children:e.jsx(ve,{label:qi(s),value:s.state})}),e.jsx("td",{children:Fi(s)}),e.jsx("td",{children:qt(s.updatedAt)})]},s.id))})]})}):e.jsx("div",{className:"training-run-placeholder",children:"No changes yet."})}function Fi(t){const n=[...t.candidates].reverse().find(i=>i.target.kind===t.target.kind);if(!n)return"—";const s=t.evaluationReceipts.filter(i=>i.candidateId===n.id&&i.subject==="candidate"),a=s.reduce((i,r)=>({passed:i.passed+(r.summaryCounts?.passed??0),tests:i.tests+(r.summaryCounts?.total??0)}),{passed:0,tests:0});return a.tests>0?`${a.passed}/${a.tests} passed`:s[0]?.status??"Not run"}function zi(t){return`${`${t.target.kind[0].toUpperCase()}${t.target.kind.slice(1)}`} ${t.operation==="improve"?"improvement":"creation"}`}function qi(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 Ui({receipts:t}){const[n,s]=c.useState(!1);if(!t.length)return e.jsx("div",{className:"training-run-placeholder",children:"No on-policy rollout receipts were recorded for this run."});const a=[...t].sort((r,l)=>l.updatedAt.localeCompare(r.updatedAt)),i=n?a:a.slice(0,24);return e.jsxs("div",{className:"training-rollout-receipts",children:[t.length>24?e.jsxs("div",{className:"training-rollout-receipt-controls",children:[e.jsx("span",{children:n?`Showing all ${t.length} receipts`:`Showing latest ${i.length} of ${t.length} receipts`}),e.jsx("button",{className:"training-text-button",type:"button",onClick:()=>s(r=>!r),children:n?"Show latest 24":`Show all ${t.length}`})]}):null,i.map(r=>e.jsxs("details",{children:[e.jsxs("summary",{children:[e.jsx("span",{children:Vi(r.providerTrace.rolloutId)}),e.jsx("strong",{children:r.status}),e.jsx("em",{children:r.reward.eligible&&r.reward.raw!=null?r.reward.raw.toFixed(3):r.failureClass??"not reward eligible"})]}),e.jsxs("dl",{className:"training-configuration-list",children:[e.jsx(ze,{label:"Correlation",value:r.correlationId}),e.jsx(ze,{label:"Task",value:r.taskId}),e.jsx(ze,{label:"Policy",value:r.policy.modelId}),e.jsx(ze,{label:"Checkpoint",value:r.policy.checkpointId??"Provider initial policy"}),e.jsx(ze,{label:"Environment",value:`${r.environment.id}@${r.environment.version}`}),e.jsx(ze,{label:"World",value:`${r.environment.worldId} · ${r.environment.worldHash}`}),e.jsx(ze,{label:"Raw reward",value:r.reward.raw==null?"Not eligible":String(r.reward.raw)}),e.jsx(ze,{label:"Components",value:JSON.stringify(r.reward.components)}),e.jsx(ze,{label:"Outcome",value:r.verifier?.outcome??r.failureClass??"Pending"}),e.jsx(ze,{label:"Trace",value:`${r.providerTrace.experimentId}/${r.providerTrace.rolloutId}`})]})]},r.id))]})}function ze({label:t,value:n}){return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsx("dd",{children:n})]})}function Vi(t){return t.replace(/^lineage_/,"").slice(0,18)}function Ki({detail:t,loading:n}){if(n&&!t)return e.jsx("div",{className:"training-run-placeholder",children:"Loading evaluation results…"});const s=t?.evaluation;return s?e.jsxs("div",{className:"training-run-evaluation",children:[e.jsxs("div",{className:"training-metric-summary",children:[e.jsx(_t,{label:"Base score",value:Jn(s.base.meanScore)}),e.jsx(_t,{label:"Trained score",value:Jn(s.trained.meanScore)}),e.jsx(_t,{label:"Score change",value:Wi(s.meanScoreDelta)}),e.jsx(_t,{label:"Trained pass rate",value:Gi(s.trained.passRate)})]}),s.base.count===0?e.jsx("p",{className:"training-muted",children:"Base-model scoring was not imported for this earlier run. New runs retain both base and trained evaluations."}):null,s.trained.count>0&&s.trained.scoredCount===0?e.jsx("p",{className:"training-muted",children:"Outputs were captured, but the grader was unavailable, so this run has no evaluation score."}):null,e.jsx("div",{className:"training-table-wrap",children:e.jsxs("table",{className:"training-data-table training-evaluation-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Test example"}),e.jsx("th",{children:"Base"}),e.jsx("th",{children:"Trained"}),e.jsx("th",{children:"Result"})]})}),e.jsx("tbody",{children:s.examples.map(a=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("details",{children:[e.jsx("summary",{children:a.taskId}),e.jsx(Hi,{input:a.input,baseOutput:a.baseOutput,trainedOutput:a.trainedOutput,baseGrade:a.baseGrade,trainedGrade:a.trainedGrade})]})}),e.jsx("td",{children:Qn(a.baseGrade)}),e.jsx("td",{children:Qn(a.trainedGrade)}),e.jsx("td",{children:Ji(a.baseGrade,a.trainedGrade)})]},a.taskId))})]})})]}):e.jsx("div",{className:"training-run-placeholder",children:"No scored evaluation results are available for this run."})}function Hi({input:t,baseOutput:n,trainedOutput:s,baseGrade:a,trainedGrade:i}){const r=[...new Set([...a?.feedback??[],...i?.feedback??[]])];return e.jsxs("div",{className:"training-evaluation-output",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Input"}),e.jsx("pre",{children:JSON.stringify(t,null,2)})]}),n?e.jsxs("div",{children:[e.jsx("span",{children:"Base output"}),e.jsx("pre",{children:JSON.stringify(n,null,2)})]}):null,s?e.jsxs("div",{children:[e.jsx("span",{children:"Trained output"}),e.jsx("pre",{children:JSON.stringify(s,null,2)})]}):null,r.length?e.jsxs("div",{children:[e.jsx("span",{children:"Grader feedback"}),e.jsx("p",{children:r.join(" ")})]}):null]})}function _t({label:t,value:n}){return e.jsxs("div",{children:[e.jsx("span",{children:t}),e.jsx("strong",{children:n})]})}function Jn(t){return t==null?"Not recorded":t.toFixed(3)}function Gi(t){return t==null?"Not recorded":`${Math.round(t*100)}%`}function Wi(t){return t==null?"Not comparable":`${t>=0?"+":""}${t.toFixed(3)}`}function Qn(t){return t?.status==="unavailable"?"Unavailable":t?.score==null?"Not scored":t.score.toFixed(3)}function Ji(t,n){if(!n)return"Not evaluated";if(n.status==="unavailable")return"Unavailable";if(!t||t.score==null||n.score==null)return n.passed?"Passed":"Failed";const s=n.score-t.score;return Math.abs(s)<5e-4?"No change":s>0?`Improved ${s.toFixed(3)}`:`Regressed ${Math.abs(s).toFixed(3)}`}const Xn=[{key:"loss",label:"Loss",format:qe},{key:"reward",label:"Reward",format:qe},{key:"policyLoss",label:"Policy loss",format:qe},{key:"advantageLoss",label:"Advantage loss",format:qe},{key:"learningRate",label:"Learning rate",format:sr},{key:"gradientNorm",label:"Gradient norm",format:qe},{key:"meanTokenAccuracy",label:"Token accuracy",format:ar},{key:"entropy",label:"Entropy",format:qe},{key:"memoryBytes",label:"Memory",format:Ns}];function Qi({detail:t,loading:n,error:s}){Qe(s,{prefix:"Training metrics"});const a=c.useMemo(()=>tr(t?.stepMetrics??[]),[t?.stepMetrics]),i=c.useMemo(()=>Xn.filter(j=>a.some(N=>N[j.key]!=null)),[a]),[r,l]=c.useState("loss"),o=i.find(j=>j.key===r)??i[0]??Xn[0],u=a.flatMap(j=>j[o.key]==null?[]:[{step:j.step,value:j[o.key]}]),h=t?Yi(t):{};if(n&&!t)return e.jsx("div",{className:"training-run-placeholder",children:"Loading training metrics…"});if(s&&!t)return e.jsx("div",{className:"training-run-placeholder",children:"Training metrics are unavailable."});if(!t)return e.jsx("div",{className:"training-run-placeholder",children:"Select a training run to inspect its metrics."});const d=t.job.metadata.trainingMethod==="grpo",m=a.flatMap(j=>j.reward==null?[]:[j.reward]),x=a.flatMap(j=>j.loss==null?[]:[j.loss]);return e.jsxs("div",{className:"training-run-metrics",children:[e.jsxs("div",{className:"training-metric-summary",children:[e.jsx(nt,{label:d?"Optimizer updates":"Steps",value:d?er(t,a):h.steps??Zi(a)}),d?e.jsxs(e.Fragment,{children:[e.jsx(nt,{label:"Latest reward",value:m.length?qe(m.at(-1)):null}),e.jsx(nt,{label:"Best reward",value:m.length?qe(Math.max(...m)):null}),e.jsx(nt,{label:"Recorded points",value:m.length||null})]}):e.jsxs(e.Fragment,{children:[e.jsx(nt,{label:"Final loss",value:h.trainLoss==null?x.at(-1)==null?null:qe(x.at(-1)):qe(h.trainLoss)}),e.jsx(nt,{label:"Peak memory",value:nr(t.stepMetrics)}),e.jsx(nt,{label:"Adapter parameters",value:h.adapterParameterCount==null?null:h.adapterParameterCount.toLocaleString()})]})]}),i.length?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"training-metric-tabs",role:"tablist","aria-label":"Training metrics",children:i.map(j=>e.jsx("button",{type:"button",role:"tab","aria-selected":j.key===o.key,className:j.key===o.key?"active":"",onClick:()=>l(j.key),children:j.label},j.key))}),e.jsx(Xi,{label:o.label,points:u,format:o.format})]}):e.jsx("div",{className:"training-run-placeholder",children:"This earlier run recorded its final result but not per-step Trainer logs."})]})}function Xi({label:t,points:n,format:s}){const r={top:20,right:20,bottom:58,left:64},l=n.map(g=>g.value),o=Math.min(...l),u=Math.max(...l),h=u-o||Math.max(Math.abs(u)*.1,1e-9),d=o-h*.08,m=u+h*.08,x=n[0]?.step??0,j=n.at(-1)?.step??x+1,N=Math.max(1,j-x),S=g=>r.left+(g-x)/N*(760-r.left-r.right),v=g=>r.top+(m-g)/(m-d)*(270-r.top-r.bottom),y=n.map((g,k)=>`${k?"L":"M"}${S(g.step).toFixed(2)},${v(g.value).toFixed(2)}`).join(" ");return e.jsx("figure",{className:"training-line-chart","aria-label":`${t} by optimizer step`,children:e.jsxs("svg",{viewBox:"0 0 760 270",role:"img","aria-labelledby":`metric-${t.replaceAll(" ","-")}`,children:[e.jsx("title",{id:`metric-${t.replaceAll(" ","-")}`,children:`${t} by optimizer step`}),[0,.25,.5,.75,1].map(g=>{const k=r.top+g*(270-r.top-r.bottom),C=m-g*(m-d);return e.jsxs("g",{children:[e.jsx("line",{className:"training-chart-grid",x1:r.left,x2:760-r.right,y1:k,y2:k}),e.jsx("text",{className:"training-chart-label",x:r.left-10,y:k+4,textAnchor:"end",children:s(C)})]},g)}),e.jsx("line",{className:"training-chart-axis",x1:r.left,x2:760-r.right,y1:270-r.bottom,y2:270-r.bottom}),e.jsx("path",{className:"training-chart-line",d:y}),n.map(g=>e.jsx("circle",{className:"training-chart-point",cx:S(g.step),cy:v(g.value),r:"3",children:e.jsx("title",{children:`Step ${g.step}: ${s(g.value)}`})},`${g.step}-${g.value}`)),e.jsx("text",{className:"training-chart-label",x:r.left,y:236,textAnchor:"middle",children:x}),e.jsx("text",{className:"training-chart-label",x:760-r.right,y:236,textAnchor:"middle",children:j}),e.jsx("text",{className:"training-chart-label axis-title",x:(r.left+760-r.right)/2,y:261,textAnchor:"middle",children:"Optimizer step"})]})})}function nt({label:t,value:n}){return e.jsxs("div",{children:[e.jsx("span",{children:t}),e.jsx("strong",{children:n??"Not recorded"})]})}function Yi(t){const n=[...t.events].reverse().find(s=>s.type==="metric"&&s.payload.metricKind!=="sft_step"&&(typeof s.payload.trainLoss=="number"||typeof s.payload.steps=="number"));return Object.fromEntries(Object.entries(n?.payload??{}).filter(s=>typeof s[1]=="number"))}function Zi(t){const n=t.at(-1);return n?`${n.step} of ${n.maxSteps}`:null}function er(t,n){const s=t.job.metadata.optimizerUpdatesObserved;return typeof s=="number"&&Number.isFinite(s)?Math.max(0,s):(n.at(-1)?.step??0)||null}function tr(t){const n=new Map;for(const s of t)n.set(s.step,s);return[...n.values()].sort((s,a)=>s.step-a.step)}function nr(t){const n=t.flatMap(s=>s.memoryBytes==null?[]:[s.memoryBytes]);return n.length?Ns(Math.max(...n)):null}function qe(t){return new Intl.NumberFormat(void 0,{maximumFractionDigits:4}).format(t)}function sr(t){return t===0?"0":t.toExponential(2)}function ar(t){return`${(t*100).toFixed(1)}%`}function Ns(t){return`${(t/1024**3).toFixed(2)} GB`}const ir=new Set(["queued","starting","running","cancelling","reconciling"]);function rr(t,n,s){const[a,i]=c.useState(null),[r,l]=c.useState(!1),[o,u]=c.useState(null),h=c.useCallback(async()=>{if(!t||!n)return null;l(!0);try{const d=await ut.trainingRunDetail(t,n);return i(d),u(null),d}catch(d){return u(d instanceof Error?d.message:String(d)),null}finally{l(!1)}},[t,n]);return c.useEffect(()=>{i(null),u(null),!(!t||!n)&&h()},[t,n,h]),c.useEffect(()=>{if(!t||!n||!s||!ir.has(s))return;const d=window.setInterval(()=>{h()},2e3);return()=>window.clearInterval(d)},[t,n,s,h]),{detail:a,error:o,loading:r,refresh:h}}function Ct(t,n,s){if(!s)return[];const a=n.filter(l=>l.target.kind==="model"&&l.target.id===t.id),i=new Set(a.flatMap(l=>l.target.kind==="model"&&l.target.trainingPlanId?[l.target.trainingPlanId]:[])),r=new Set(a.flatMap(l=>l.tasksetRef?[l.tasksetRef.id]:[]));return t.tasksetId&&r.add(t.tasksetId),s.plans.filter(l=>l.modelId===t.id||i.has(l.id)||l.modelId===null&&r.has(l.tasksetId)).sort((l,o)=>o.createdAt.localeCompare(l.createdAt))}function yn(t,n,s){if(!s)return[];const a=new Set(Ct(t,n,s).map(i=>i.id));return s.jobs.filter(i=>a.has(i.planId)).sort((i,r)=>r.createdAt.localeCompare(i.createdAt))}function ks(t,n,s){if(!s)return[];const a=new Set(Ct(t,n,s).map(i=>i.tasksetId));for(const i of n)i.target.kind==="model"&&i.target.id===t.id&&i.tasksetRef&&a.add(i.tasksetRef.id);return t.tasksetId&&a.add(t.tasksetId),s.tasksets.filter(i=>a.has(i.id))}function Ss(t,n,s){if(!s)return[];const a=new Set(ks(t,n,s).map(i=>i.id));return(s.baselineRuns??[]).filter(i=>i.targetModelId?i.targetModelId===t.id:a.has(i.tasksetId)).sort((i,r)=>r.updatedAt.localeCompare(i.updatedAt))}function ht(t,n,s){if(!s)return[];const a=Ct(t,n,s),i=new Map(a.map(d=>[d.id,d])),r=yn(t,n,s),l=new Map(r.map(d=>[d.id,d])),o=Cs(t,n,s),u=new Set(r.map(d=>d.id));return s.models.filter(d=>d.modelId===t.id||u.has(d.jobId)).sort((d,m)=>d.importedAt.localeCompare(m.importedAt)).map((d,m)=>{const x=l.get(d.jobId)??null;return{lineage:d,number:m+1,job:x,plan:x?i.get(x.planId)??null:null,taskset:s.tasksets.find(j=>j.id===d.tasksetId)??null,current:o?.modelArtifactLineageId===d.id}}).sort((d,m)=>m.number-d.number)}function Cs(t,n,s){if(!s)return null;const a=new Set(n.flatMap(i=>i.target.kind==="model"&&i.target.id===t.id&&i.tasksetRef?[i.tasksetRef.id]:[]));return t.tasksetId&&a.add(t.tasksetId),s.modelBindings.filter(i=>i.status==="active"&&i.role==="chat_manual"&&(i.roleTargetId===t.id||a.has(i.roleTargetId))).sort((i,r)=>r.promotedAt.localeCompare(i.promotedAt))[0]??null}function lr({workproduct:t,runs:n,training:s,onOpenDataset:a,onOpenEntry:i,onToast:r}){const l=s.payload,o=c.useMemo(()=>yn(t,n,l),[n,l,t]),u=c.useMemo(()=>ht(t,n,l),[n,l,t]),h=c.useMemo(()=>Ss(t,n,l),[n,l,t]),d=c.useMemo(()=>Ct(t,n,l),[n,l,t]),m=c.useMemo(()=>new Map(d.map(v=>[v.id,v])),[d]),x=c.useMemo(()=>ws(o,u,h),[h,o,u]),j=Cs(t,n,l);async function N(v){const y=u.find(k=>k.lineage.id===v);if(!y?.lineage.promotable||!window.confirm(`Set Version ${y.number} as active for ${t.name}?`))return;const g=await s.actions.bindModel(y.lineage.id,"chat_manual",t.id);r(g?`Version ${y.number} is now active.`:"The active Version could not be changed.",g?"success":"error")}async function S(v,y){const g=await s.actions.setModelPinned(v,y);r(g?y?"Version pinned.":"Version unpinned.":"Version pin could not be changed.",g?"success":"error")}return e.jsx("section",{className:"labs-model-version-index","aria-label":"Versions",children: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:"Training"}),e.jsx("th",{children:"Dataset"}),e.jsx("th",{children:"Training status"}),e.jsx("th",{children:"Evaluation"}),e.jsx("th",{children:"Version status"}),e.jsx("th",{children:"Updated"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsxs("tbody",{children:[x.length?null:e.jsx("tr",{children:e.jsx("td",{colSpan:8,children:e.jsx("div",{className:"training-run-placeholder",children:"No training attempts yet. Create the first Version and finish its Dataset checks."})})}),x.map(v=>{const y=v.baselineRun,g=v.version?.plan??(v.job?m.get(v.job.planId)??null:null),k=v.version?.taskset??l?.tasksets.find(R=>R.id===(y?.tasksetId??g?.tasksetId))??null,C=v.version,M=C&&j?.modelArtifactLineageId===C.lineage.id;return e.jsxs("tr",{onClick:()=>i(v.key),children:[e.jsx("td",{children:e.jsxs("button",{className:"labs-version-row-button",type:"button",onClick:()=>i(v.key),children:[e.jsx("strong",{children:C?`Version ${C.number}`:"No output"}),e.jsx("small",{children:mr(C?.lineage.id??v.job?.id??y?.id??v.key)})]})}),e.jsx("td",{children:y?y.configuration.split==="train"?"Train-signal check":"Base-model check":at(g?.recipe.method)}),e.jsx("td",{children:k?e.jsx("button",{className:"labs-version-dataset-link",type:"button",onClick:R=>{R.stopPropagation(),a(k.id)},children:k.name}):"Unavailable"}),e.jsx("td",{children:e.jsx(ve,{label:y?Is(y):v.job?vn(v.job.status):"Imported",value:y?.status??v.job?.status??"completed"})}),e.jsx("td",{children:y?e.jsx(dr,{run:y}):e.jsx(cr,{version:C})}),e.jsx("td",{children:e.jsx(ur,{version:C})}),e.jsx("td",{children:qt(C?.lineage.importedAt??y?.updatedAt??v.job?.updatedAt??"")}),e.jsx("td",{children:y&&Nn(y)?e.jsx("button",{className:"training-button secondary",type:"button",onClick:R=>{R.stopPropagation(),s.actions.cancelBaselineRun(y.id)},children:"Cancel"}):C?e.jsxs("div",{className:"training-table-actions",children:[e.jsx("button",{"aria-pressed":C.lineage.pinned||!!M,className:"labs-version-icon-button",disabled:!!M,title:M?"The active Version stays pinned":C.lineage.pinned?"Unpin Version":"Pin Version",type:"button",onClick:R=>{R.stopPropagation(),S(C.lineage.id,!C.lineage.pinned)},children:e.jsx(aa,{size:14})}),C.current?null:e.jsx("button",{className:"training-button secondary",disabled:!C.lineage.promotable,type:"button",onClick:R=>{R.stopPropagation(),N(C.lineage.id)},children:"Activate"}),e.jsx("button",{"aria-label":`Download Version ${C.number}`,className:"labs-version-icon-button",type:"button",onClick:R=>{R.stopPropagation(),s.actions.downloadModelPackage(C.lineage.id)},children:e.jsx(bn,{size:14})})]}):null})]},v.key)})]})]})})})}function or({connection:t,selectedEntryKey:n,workproduct:s,runs:a,training:i,onBack:r,onOpenDataset:l,onUseVersion:o}){const u=i.payload,h=c.useMemo(()=>yn(s,a,u),[a,u,s]),d=c.useMemo(()=>ht(s,a,u),[a,u,s]),m=c.useMemo(()=>Ss(s,a,u),[a,u,s]),x=c.useMemo(()=>Ct(s,a,u),[a,u,s]),j=c.useMemo(()=>new Map(x.map(w=>[w.id,w])),[x]),S=c.useMemo(()=>ws(h,d,m),[m,h,d]).find(w=>w.key===n)??null,v=S?.job??null,y=S?.version??null,g=S?.baselineRun??null,k=y?.plan??(v?j.get(v.planId)??null:null),C=y?.taskset??u?.tasksets.find(w=>w.id===(g?.tasksetId??k?.tasksetId))??null,M=rr(t,v?.id??null,v?.status??null),R=v?u?.rolloutReceipts.filter(w=>w.jobId===v.id)??[]:[];return S?e.jsxs("div",{className:"labs-model-version-detail",children:[e.jsx("button",{className:"settings-secondary compact labs-model-version-back",type:"button",onClick:r,children:"Back to versions"}),e.jsxs(xe,{title:g?g.configuration.split==="train"?"Train-signal check":"Base-model check":y?`Version ${y.number}`:`${at(k?.recipe.method)} attempt`,actions:g&&Nn(g)?e.jsx("button",{className:"training-button secondary",type:"button",onClick:()=>{i.actions.cancelBaselineRun(g.id)},children:"Cancel check"}):y?e.jsxs("div",{className:"training-table-actions",children:[C?e.jsxs("button",{className:"training-button secondary",disabled:!y.lineage.promotable,title:y.lineage.promotable?"Chat with this Version":"Chat is unavailable because this Version did not pass evaluation.",type:"button",onClick:()=>o(y.lineage.id),children:[e.jsx(Bt,{size:14}),"Chat"]}):null,e.jsxs("button",{className:"training-button secondary",type:"button",onClick:()=>{i.actions.downloadModelPackage(y.lineage.id)},children:[e.jsx(bn,{size:14}),"Download LoRA"]})]}):null,children:[e.jsxs("dl",{className:"labs-inline-facts",children:[e.jsx(Ce,{label:g?"Check status":"Training status",value:g?Is(g):v?vn(v.status):"Imported"}),e.jsx(Ce,{label:"Version status",value:y?y.current?"Active":"Available":"Not created"}),e.jsx(Ce,{label:"Training",value:g?"RFT readiness check":at(k?.recipe.method)}),e.jsx(Ce,{label:"Base model",value:g?pr(g.configuration.model.modelId):hr(k)}),e.jsx(Ce,{label:"Dataset",value:C?.name??"Unavailable"}),e.jsx(Ce,{label:"Compute",value:g?"Fireworks":k?An(k.destinationId):v?An(v.destinationId):"Not recorded"}),e.jsx(Ce,{label:"Duration",value:g?Mn(g.startedAt,g.completedAt):v?Mn(v.startedAt,v.completedAt):"Not recorded"}),e.jsx(Ce,{label:"Output",value:y?`Version ${y.number}`:g?.reportId?"Check report":"No Version"})]}),C?e.jsxs("button",{className:"labs-version-dataset-link labs-version-detail-dataset",type:"button",onClick:()=>l(C.id),children:["Open ",C.name]}):null,g?.error||v?.error?e.jsx("p",{className:"labs-training-error",children:g?.error??v?.error}):null]}),v?e.jsxs(e.Fragment,{children:[e.jsx(xe,{title:k?.recipe.method==="grpo"?"Rollout scores":"Training metrics",children:e.jsx(Qi,{detail:M.detail,error:M.error,loading:M.loading})}),e.jsx(xe,{title:"Evaluation",children:e.jsx(Ki,{detail:M.detail,loading:M.loading})}),k?.recipe.method==="grpo"?e.jsx(xe,{title:"Rollout traces",children:e.jsx(Ui,{receipts:R})}):null]}):null,e.jsx(xe,{title:"Configuration",children:e.jsxs("dl",{className:"training-configuration-list",children:[e.jsx(Ce,{label:g?"Check run":"Training attempt",value:g?.id??v?.id??"Provider import"}),e.jsx(Ce,{label:"Dataset",value:C?.name??"Unavailable"}),e.jsx(Ce,{label:g?"Selection":"Prepared data",value:g?`${g.configuration.taskLimit} prompts × ${g.configuration.attemptsPerTask} attempts`:v?.bundleHash??"Provider managed"}),e.jsx(Ce,{label:g?"Provider deployment":"Version ID",value:g?g.provider?.deploymentId??"Not provisioned":y?.lineage.id??"No Version created"}),g?e.jsx(Ce,{label:"Attempt progress",value:`${g.progress.completedAttempts} of ${g.progress.totalAttempts}`}):null,g?.provider?.statusCode?e.jsx(Ce,{label:"Provider status",value:g.provider.statusCode}):null]})})]}):e.jsxs("div",{className:"labs-model-version-detail",children:[e.jsx("button",{className:"settings-secondary compact",type:"button",onClick:r,children:"Back to versions"}),e.jsx("div",{className:"training-run-placeholder",children:"This training attempt is no longer available."})]})}function ws(t,n,s){const a=new Map(n.flatMap(l=>l.job?[[l.job.id,l]]:[])),i=t.map(l=>({key:`job:${l.id}`,job:l,version:a.get(l.id)??null,baselineRun:null})),r=new Set(t.map(l=>l.id));for(const l of n)l.job&&r.has(l.job.id)||i.push({key:`version:${l.lineage.id}`,job:l.job,version:l,baselineRun:null});for(const l of s)i.push({key:`baseline:${l.id}`,job:null,version:null,baselineRun:l});return i.sort((l,o)=>Yn(o).localeCompare(Yn(l)))}function Yn(t){return t.version?.lineage.importedAt??t.baselineRun?.updatedAt??t.job?.updatedAt??t.job?.createdAt??""}function Is(t){switch(t.status){case"queued":return"Check queued";case"preparing":return"Preparing check";case"running":return"Check running";case"cancelling":return"Cancelling check";case"cancelled":return"Check cancelled";case"succeeded":return"Check passed";case"failed":return"Check failed"}}function Nn(t){return["queued","preparing","running","cancelling"].includes(t.status)}function dr({run:t}){const n=`${t.progress.completedAttempts} / ${t.progress.totalAttempts}`,s=t.reportId?"Recorded":t.progress.completedAttempts?n:"No attempts";return e.jsx(ve,{label:s,value:t.reportId?"passed":Nn(t)?"running":t.status})}function cr({version:t}){const n=t?t.lineage.promotable?"Passed":t.lineage.frozenEvaluationArtifactId?"Failed":"Not run":"No output",s=t?t.lineage.promotable?"passed":t.lineage.frozenEvaluationArtifactId?"failed":"not_run":"not_run";return e.jsx(ve,{label:n,value:s})}function ur({version:t}){return e.jsx(ve,{label:t?t.current?"Active":"Available":"Not created",value:t?t.current?"current":"ready":"not_run"})}function hr(t){return!t||t.recipe.method!=="sft"&&t.recipe.method!=="grpo"?"Not recorded":t.recipe.baseModel.id.split("/").at(-1)??t.recipe.baseModel.id}function pr(t){return t.split("/").at(-1)??t}function mr(t){return t.replace(/^baseline_run_/,"").replace(/^(?:training_job_|lineage_)(?:fireworks_)?(?:artifact_)?/,"").slice(0,12)}function Ce({label:t,value:n}){return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsx("dd",{children:n})]})}function gr({state:t,initialTasksetId:n,checking:s,onClose:a,onCheck:i,onContinue:r,onReview:l}){const o=c.useMemo(()=>(t?.tasksets??[]).sort((x,j)=>x.id===n?-1:j.id===n?1:j.updatedAt.localeCompare(x.updatedAt)),[n,t?.tasksets]),[u,h]=c.useState(n&&o.some(x=>x.id===n)?n:o[0]?.id??""),d=o.find(x=>x.id===u)??null,m=d?.readiness?.ready===!0;return e.jsxs(it,{ariaLabel:"New version",className:"training-dialog labs-new-version-dialog",dismissDisabled:s,onClose:a,children:[e.jsxs("div",{className:"training-dialog-header",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"New version"}),e.jsx("p",{children:"Choose the immutable Dataset revision. Training setup comes next."})]}),e.jsx("button",{"aria-label":"Close New version",type:"button",onClick:a,children:e.jsx(Xe,{size:16})})]}),e.jsxs("div",{className:"labs-new-version-step",children:[e.jsx("span",{className:"labs-new-version-step-number",children:"1"}),e.jsxs("div",{children:[e.jsx("strong",{children:"Dataset"}),e.jsx("p",{children:"Every run keeps the exact selected revision and Eval boundary."})]})]}),e.jsxs("label",{className:"labs-new-version-select",children:[e.jsx("span",{children:"Dataset revision"}),e.jsx("select",{value:u,onChange:x=>h(x.target.value),children:o.map(x=>e.jsxs("option",{value:x.id,children:[x.name," · revision ",x.revision,x.readiness?.ready?"":" · needs review"]},x.id))})]}),d?e.jsxs("dl",{className:"labs-inline-facts labs-new-version-dataset-facts",children:[e.jsx(Tt,{label:"Training",value:String(nn(d,"train"))}),e.jsx(Tt,{label:"Validation",value:String(nn(d,"validation"))}),e.jsx(Tt,{label:"Frozen Eval",value:String(nn(d,"frozen_eval"))}),e.jsx(Tt,{label:"Graders",value:String(d.graders.length)})]}):e.jsx("div",{className:"training-run-placeholder",children:"No Dataset is available. Create a Dataset first."}),d&&!m?e.jsxs("div",{className:"training-banner warning labs-new-version-readiness",children:[e.jsx("strong",{children:"This Dataset needs its local checks before training."}),e.jsx("p",{children:"OpenPond verifies the grader, split boundary, and immutable artifact before it can prepare a provider export."}),e.jsxs("div",{className:"training-dialog-actions",children:[e.jsx("button",{className:"training-text-button",type:"button",onClick:()=>{a(),l(d.id)},children:"Review Dataset"}),e.jsx("button",{className:"training-button secondary",disabled:s,type:"button",onClick:()=>{i(d.id)},children:s?"Checking…":"Run Dataset checks"})]})]}):null,e.jsxs("div",{className:"training-dialog-actions",children:[e.jsx("button",{className:"training-button secondary",type:"button",onClick:a,children:"Cancel"}),e.jsx("button",{className:"training-button",disabled:!m,type:"button",onClick:()=>{m&&d&&r({taskset:d})},children:"Configure training"})]})]})}function nn(t,n){return t.datasetArtifact?t.datasetArtifact.splitCounts[n]??0:t.tasks.filter(s=>s.split===n).length}function Tt({label:t,value:n}){return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsx("dd",{children:n})]})}function fr({run:t,onAnswerQuestion:n,onApplyCandidate:s,onApprove:a,onCancel:i,onOpenPullRequest:r,onPause:l,onOpenConversation:o,onReconcilePullRequest:u,onRejectCandidate:h,onRetry:d,onResume:m,onRevise:x}){const j=t.state==="blocked"?"Review blocker":t.state==="failed"?"Review failure":"View progress",N=t.target.kind==="agent"&&["blocked","failed","cancelled"].includes(t.state);return e.jsxs("div",{className:"labs-run-decision",children:[e.jsx(ha,{runtime:{run:t,onAnswerQuestion:n,onApplyCandidate:s,onApprove:a,onCancel:i,onOpenPullRequest:r,onPause:l,onReconcilePullRequest:u,onRejectCandidate:h,onResume:m,onRevise:x}}),t.scope.conversationId||N?e.jsxs("div",{className:"labs-run-decision-actions",children:[t.scope.conversationId?e.jsx("button",{className:"training-button secondary",type:"button",onClick:()=>o(t.scope.conversationId),children:j}):null,N?e.jsx("button",{className:"training-button",type:"button",onClick:d,children:"Try again"}):null]}):null]})}function xr({run:t,showOutcomes:n=!0}){const{completedTasks:s,currentTask:a,totalTasks:i}=t.progress,r=a?`${Zn(a.family)} · ${a.worldId}`:t.progress.stage==="complete"?"Baseline complete":Zn(t.progress.stage);return e.jsxs("div",{className:"labs-training-run-progress-wrap","aria-live":jr(t)?"polite":"off",children:[e.jsxs("div",{className:"labs-training-run-progress",children:[e.jsxs("progress",{max:Math.max(1,i),value:s,children:[s," of ",i," tasks"]}),e.jsxs("small",{children:[s," / ",i," · ",r]})]}),n?e.jsxs("span",{className:"labs-training-run-verdicts",children:[t.progress.outcomes.correct," exact · ",t.progress.outcomes.incorrect," incorrect ·"," ",t.progress.outcomes.parseFailure," format ·"," ",t.progress.outcomes.infrastructureFailure," infrastructure"]}):null]})}function br(t){return t.status==="queued"?"Queued":t.status==="cancelling"?"Cancelling":t.status==="cancelled"?"Cancelled":t.status==="succeeded"?"Baseline ready":t.status==="failed"?"Baseline failed":t.progress.stage==="preparing"?"Preparing baseline":t.progress.stage==="persisting"?"Saving baseline":"Running baseline"}function jr(t){return["queued","running","cancelling"].includes(t.status)}function Zn(t){return t.replaceAll("_"," ").replace(/\b\w/g,n=>n.toUpperCase())}const vr=new Set(["released","rejected","ready","ready_local","published_hosted","blocked","failed","cancelled"]),Rs=new Set(["queued","starting","running","cancelling","reconciling"]);function As(t){const n=t.runs[0]??null,s=n?.state==="blocked"&&n.candidates.some(i=>!!i.git?.worktreePath&&["draft","checking"].includes(i.status))?n:null,a=t.runs.find(i=>!vr.has(i.state))??null;if(t.workproduct.kind==="model"&&t.taskset){const i=fs(t.training,t.taskset.id)[0]??null;if(i&&Rs.has(i.status))return es({taskset:t.taskset,training:t.training,latestRun:n,fallbackStatus:t.workproduct.status})}if(s)return sn(s);if(a)return sn(a);if(t.workproduct.kind==="model"){const i=t.workproduct.frontierBaselineRunId?t.training?.frontierBaselineRuns.find(r=>r.id===t.workproduct.frontierBaselineRunId)??null:null;return i?yr(i):!t.taskset&&n&&["failed","blocked","cancelled"].includes(n.state)?sn(n):es({taskset:t.taskset,training:t.training,latestRun:n,fallbackStatus:t.workproduct.status})}return 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 yr(t){return{statusLabel:br(t),statusValue:t.status,action:{kind:t.status==="succeeded"?"open_data":"open_evals",label:t.status==="succeeded"?"Review data":"View baseline"},runId:null,conversationId:null}}function sn(t){const n={statusLabel:Nr(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 s=t.candidates.some(a=>!!a.git?.worktreePath&&["draft","checking"].includes(a.status));return{...n,action:s?{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 es(t){const n=t.latestRun?.scope.conversationId??null;if(!t.taskset)return{statusLabel:"Creating data",statusValue:"planning",action:n?{kind:"open_conversation",label:"View progress"}:null,runId:t.latestRun?.id??null,conversationId:n};const a=fs(t.training,t.taskset.id)[0]??null,i=t.training?.models.find(l=>l.tasksetId===t.taskset.id&&l.status==="imported")??null;if(a&&Rs.has(a.status))return{statusLabel:vn(a.status),statusValue:a.status,action:{kind:"open_training",label:"View run"},runId:t.latestRun?.id??null,conversationId:n};if(a?.status==="failed")return{statusLabel:"Training failed",statusValue:"failed",action:{kind:"open_training",label:"Review failure"},runId:t.latestRun?.id??null,conversationId:n};if(a?.status==="succeeded")return a.metadata.frozenEvaluationComplete===!0&&a.metadata.frozenEvaluationThresholdPassed!==!0?{statusLabel:"Evaluation failed",statusValue:"failed",action:{kind:"open_training",label:"Review results"},runId:t.latestRun?.id??null,conversationId:n}:{statusLabel:i?a.metadata.frozenEvaluationThresholdPassed===!0?"Model ready":"Evaluation pending":"Collecting model",statusValue:i&&a.metadata.frozenEvaluationThresholdPassed===!0?"ready":"running",action:{kind:"open_training",label:"Review results"},runId:t.latestRun?.id??null,conversationId:n};if(!t.taskset.readiness?.ready)return{statusLabel:"Needs review",statusValue:"needs_review",action:{kind:"open_data",label:"Review data"},runId:t.latestRun?.id??null,conversationId:n};const r=t.taskset.readiness.baselineReward;return t.taskset.readiness.recommendedMethod==="grpo"&&!(t.taskset.readiness.baselineReportId&&r&&r.count>=2&&(r.variance??0)>0&&(r.mean??0)>.05&&(r.mean??0)<.95)?{statusLabel:"Test base model",statusValue:"needs_review",action:{kind:"start_training",label:"Configure training"},runId:t.latestRun?.id??null,conversationId:n}:{statusLabel:"Ready to train",statusValue:"ready",action:{kind:"start_training",label:"Start training"},runId:t.latestRun?.id??null,conversationId:n}}function Nr(t){const n=t.state,s=t.target.kind==="agent";return{planning:"Planning",awaiting_questions:"Needs answers",awaiting_plan_approval:"Plan ready",paused:"Paused",applying_source:s?"Saving Agent":"Applying changes",running_checks:s?"Running Evals":"Running checks",evaluating:s?"Running Evals":"Evaluating",awaiting_promotion:s?"Update ready":"Candidate ready",opening_pull_request:"Opening review",pull_request_open:"Review open",reconciling_release:s?"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 ts={chat_manual:"Default chat model",agent:"Agent runtime",extension:"Extension runtime",authoring_optimizer:"Authoring / optimizer"};function kr({lineage:t,state:n,training:s,onToast:a}){const[i,r]=c.useState("chat_manual"),[l,o]=c.useState("default"),[u,h]=c.useState(null),[d,m]=c.useState(""),x=c.useMemo(()=>n?.modelBindings.find(p=>p.status==="active"&&p.role===i&&p.roleTargetId===l.trim())??null,[i,l,n?.modelBindings]),j=x?n?.models.find(p=>p.id===x.modelArtifactLineageId)??null:null,S=(t?.frozenEvaluationArtifactId?n?.artifacts.find(p=>p.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 v=t,y=!!s.busyAction,g=v.status==="imported"&&v.promotable&&!!l.trim(),k=x?.modelArtifactLineageId===v.id;async function C(){const p=await s.actions.bindModel(v.id,i,l.trim());h(null),a(p?"Model binding activated.":"Couldn’t activate Model binding.",p?"success":"error")}async function M(){const p=d.trim();if(!p)return;const B=await s.actions.rejectModel(v.id,p);h(null),a(B?"Model candidate rejected.":"Couldn’t reject Model candidate.",B?"success":"error")}async function R(){const p=await s.actions.evaluateJob(v.jobId);h(null),a(p?"Frozen evaluation completed.":"Couldn’t complete frozen evaluation.",p?"success":"error")}async function w(){if(!x)return;const p=await s.actions.rollbackModelBinding(x.id);a(p?"Model binding rolled back.":"Couldn’t roll back Model binding.",p?"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:t.promotable?"Passed":"Blocked"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Selected role"}),e.jsx("strong",{children:j?an(j.id):"No active binding"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Rollback target"}),e.jsx("strong",{children:x?.rollbackTargetBindingId?an(x.rollbackTargetBindingId):"None"})]})]}),e.jsxs("div",{className:"training-promotion-controls",children:[e.jsxs("label",{children:[e.jsx("span",{children:"Role"}),e.jsx("select",{value:i,onChange:p=>{const B=p.target.value;r(B),o(B==="chat_manual"?"default":"")},children:Object.entries(ts).map(([p,B])=>e.jsx("option",{value:p,children:B},p))})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Role target"}),e.jsx("input",{value:l,placeholder:i==="agent"?"agent id":i==="extension"?"extension id":"default",onChange:p=>o(p.target.value)})]}),e.jsxs("div",{className:"training-promotion-actions",children:[S?e.jsx("button",{className:"training-button secondary",type:"button",disabled:y,onClick:()=>h("evaluate"),children:"Run evaluation"}):null,k?e.jsx("button",{className:"training-button secondary",type:"button",disabled:y,onClick:()=>{w()},children:"Roll back"}):e.jsx("button",{className:"training-button",type:"button",disabled:y||!g,onClick:()=>h("bind"),children:x?"Replace binding":"Bind model"}),e.jsx("button",{className:"training-button danger",type:"button",disabled:y||t.status==="rejected"||k,onClick:()=>h("reject"),children:"Reject"})]})]}),t.promotable?null:e.jsx("p",{className:"training-promotion-note",children:S?"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":u==="evaluate"?"Run frozen evaluation":"Reject Model candidate",onMouseDown:p=>p.stopPropagation(),children:[e.jsx("div",{className:"training-dialog-header",children:e.jsxs("div",{children:[e.jsx("h2",{children:u==="bind"?"Activate this Model binding?":u==="evaluate"?"Run frozen evaluation?":"Reject this Model candidate?"}),e.jsx("p",{children:u==="bind"?`${ts[i]} · ${l.trim()}`:u==="evaluate"?"Temporary Fireworks deployments are deleted after the base and trained runs.":"The artifact and evaluation evidence are retained."})]})}),u==="bind"?e.jsx("p",{children:x?`The current binding ${an(x.modelArtifactLineageId)} becomes the recorded rollback target.`:"This is an explicit activation; training success alone never changes runtime selection."}):u==="reject"?e.jsxs("label",{className:"training-promotion-reason",children:[e.jsx("span",{children:"Reason"}),e.jsx("textarea",{autoFocus:!0,value:d,onChange:p=>m(p.target.value)})]}):e.jsx("p",{children:"OpenPond first validates both deployment shapes without spending, then runs the approved frozen Taskset through the stateful tool harness. Runtime is capped at 10 minutes and the conservative deployment ceiling is $1.17 within the existing training approval."}),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"?C():u==="evaluate"?R():M()},children:y?"Applying…":u==="bind"?"Activate binding":u==="evaluate"?"Run evaluation":"Reject candidate"})]})]})}):null]})}function an(t){return t.replace(/^lineage_/,"").replace(/^model_binding_/,"").slice(0,16)}function Sr(t){for(const n of t){const s=ia.safeParse(n.metadata.preferredBaseModel);if(s.success)return s.data;const a=n.metadata.preferredBaseModelId;if(typeof a=="string"&&a.trim())return{schemaVersion:"openpond.baseModelPreference.v1",modelId:a.trim(),revision:null,tokenizerRevision:null,chatTemplateHash:null,modelAssetId:null,source:"managed"}}return null}function Cr(t){return[...t.candidates].reverse().find(n=>!!n.git?.headCommit)??null}function wr(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 Ir({workproduct:t,profile:n}){if(t.kind==="agent"){const s=n?.agents.find(a=>a.id===t.id)??null;return e.jsx(xe,{title:"Agent",children:e.jsxs("dl",{className:"training-configuration-list",children:[e.jsx(Pe,{label:"Enabled",value:s?.enabled?"Yes":"No"}),e.jsx(Pe,{label:"Source",value:s?.path??t.path??"Draft"}),e.jsx(Pe,{label:"Default action",value:`${t.id}.chat`}),e.jsx(Pe,{label:"Profile checks",value:n?.lastCheck?.status??"Not run"})]})})}if(t.kind==="skill"){const s=n?.skills.find(a=>a.name===t.id)??null;return e.jsxs(xe,{title:"Skill",children:[e.jsxs("dl",{className:"training-configuration-list",children:[e.jsx(Pe,{label:"Enabled",value:s?.enabled?"Yes":"No"}),e.jsx(Pe,{label:"Validation",value:s?.validationStatus??"Draft"}),e.jsx(Pe,{label:"Source hash",value:s?.sourceHash??"Not available"}),e.jsx(Pe,{label:"Characters",value:s?String(s.charCount):"Not available"})]}),s?.validationMessages.length?e.jsx("ul",{className:"labs-validation-list",children:s.validationMessages.map(a=>e.jsx("li",{children:a},a))}):null]})}return t.kind==="extension"?e.jsx(xe,{title:"Extension",children:e.jsx("div",{className:"training-run-placeholder",children:"Runtime bindings arrive with the Extension phase."})}):null}function Rr({runs:t,selectedRun:n,onSelectedRunIdChange:s}){return e.jsx(xe,{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(a=>e.jsxs("tr",{className:a.id===n?.id?"selected":void 0,onClick:()=>s(a.id),children:[e.jsx("td",{children:Ut(a.id)}),e.jsx("td",{children:a.operation}),e.jsx("td",{children:e.jsx(ve,{label:a.state.replaceAll("_"," "),value:a.state})}),e.jsx("td",{children:a.revision}),e.jsx("td",{children:qt(a.updatedAt)})]},a.id))})]})}):e.jsx("div",{className:"training-run-placeholder",children:"No Create/Improve activity yet."})})}function Ar({profileEvals:t,run:n,workproduct:s}){const a=n?.evaluationReceipts??[],i=[...new Set([...n?.context.evalRefs??[],...a.flatMap(o=>o.evalRefs)])],r=s.kind==="agent"?t.filter(o=>o.agentId===null||o.agentId===s.id):[],l=s.kind==="agent";return!a.length&&!r.length&&!i.length?e.jsx("div",{className:"training-run-placeholder",children:"No Eval receipts yet."}):e.jsxs("div",{className:"labs-eval-summary",children:[r.length?e.jsxs("div",{className:"labs-source-evals",children:[e.jsx("strong",{children:"Available Evals"}),e.jsx("ul",{children:r.map(o=>e.jsxs("li",{children:[e.jsx("span",{children:o.name}),l?null:e.jsx("code",{children:o.path})]},o.id))})]}):null,i.length?e.jsxs("div",{className:"labs-source-evals",children:[e.jsx("strong",{children:l?"Included in this update":"Used for this change"}),e.jsx("ul",{children:l?e.jsx("li",{children:e.jsxs("span",{children:[i.length," Eval set",i.length===1?"":"s"]})}):i.map(o=>e.jsx("li",{children:e.jsx("code",{children:o})},o))})]}):null,a.length?e.jsxs("div",{className:"labs-eval-receipts",children:[e.jsx("strong",{children:l?"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:[l?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:a.map(o=>e.jsxs("tr",{children:[l?null:e.jsx("td",{children:Ut(o.id)}),e.jsx("td",{children:e.jsx(ve,{label:o.status})}),e.jsx("td",{children:o.evalRefs.length}),e.jsx("td",{children:l?Mr(o):o.summary??"No summary"})]},o.id))})]})})]}):null]})}function Mr(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 _r({runs:t,selectedRun:n,taskset:s,training:a,trainingState:i,onToast:r}){const l=(s?i?.models.filter(d=>d.tasksetId===s.id)??[]:[]).sort((d,m)=>m.importedAt.localeCompare(d.importedAt)),o=new Map(i?.jobs.map(d=>[d.id,d])??[]),u=new Map(i?.plans.map(d=>[d.id,d])??[]),h=new Map(i?.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(We,{label:"Create/Improve runs",value:String(t.length)}),e.jsx(We,{label:"Candidates",value:String(n?.candidates.length??0)}),e.jsx(We,{label:"Profile commit",value:n?.localProfileCommit??"Not released"}),e.jsx(We,{label:"Model artifacts",value:String(l.length)})]}),l.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:l.map((d,m)=>{const x=o.get(d.jobId),j=x?u.get(x.planId):null,N=h.get(d.artifactId)??null,S=N?Tr(N.path):null;return e.jsxs("tr",{children:[e.jsxs("td",{className:"labs-version-name",children:[e.jsx("strong",{children:m===0?"Latest":`Prior ${m}`}),e.jsx("small",{children:Ut(d.id)})]}),e.jsx("td",{children:at(j?.recipe.method)}),e.jsxs("td",{className:"labs-version-storage",children:[e.jsx("strong",{children:S?"Saved locally":"Unavailable"}),S?e.jsx("code",{title:N?.path,children:S}):null]}),e.jsx("td",{children:d.promotable?"Passed":d.frozenEvaluationArtifactId?"Failed":"Not run"}),e.jsx("td",{children:qt(d.importedAt)}),e.jsx("td",{children:e.jsxs("button",{className:"training-button secondary",type:"button",onClick:()=>{a.actions.downloadModelPackage(d.id)},children:[e.jsx(bn,{size:14}),"Download LoRA"]})})]},d.id)})})]})}):e.jsx("div",{className:"training-run-placeholder",children:"Model versions appear after the first adapter is imported."}),l[0]?e.jsxs("div",{className:"labs-version-promotion",children:[e.jsx("h3",{children:"Promotion & bindings"}),e.jsx(kr,{lineage:l[0],state:i,training:a,onToast:r})]}):null]})}function Tr(t){return t.replace(/[/\\][^/\\]+$/,"").replace(/^\/home\/[^/]+/,"~")}function We({label:t,value:n}){return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsx("dd",{children:n})]})}function Pe({label:t,value:n}){return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsx("dd",{children:n})]})}function Ut(t){return t.replace(/^(create_improve|training_job|agent_candidate|model_candidate)_/,"").slice(0,14)}function Ms(t){return t&&`${t[0].toUpperCase()}${t.slice(1).replaceAll("_"," ")}`}function Er(t,n,s,a=!1){return t==="changes"?n?["Changes",s?`Change ${s.slice(0,8)}`:`Change ${Ut(n)}`]:["Changes"]:[Ms(t)]}function Pr(t,n,s){const a=s.git?.changedPaths??[],i=a[0]??null,r=t.path?.trim().replace(/^\.\/+|\/+$/g,"")??"";if(!r)return{fileRootPath:null,initialPath:i};const l=r.split("/").filter(Boolean);l.at(-1)?.includes(".")&&l.pop();const o=l.join("/");if(!o)return{fileRootPath:null,initialPath:i};const u=o.startsWith("profiles/")?o:`profiles/${n?.activeProfile??"default"}/${o}`,h=a.find(d=>d===u||d.startsWith(`${u}/`))??null;return h?{fileRootPath:u,initialPath:h}:{fileRootPath:null,initialPath:i}}function $r(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"}function Dr({workproduct:t,runs:n,profile:s,training:a,connection:i,onOpenConversation:r,onLocationChange:l,onRenameAgent:o,onStartAgentChange:u,onOpenDataset:h,onOpenProviderSettings:d,onToast:m,onAnswerQuestion:x,candidateReview:j,onApprove:N,onCancel:S,onChatWithModel:v,onApplyCandidate:y,onCandidateReviewChange:g,onOpenCandidateFiles:k,onOpenPullRequest:C,onPause:M,onReconcilePullRequest:R,onRejectCandidate:w,onResume:p,onRevise:B}){const D=c.useMemo(()=>vs(t,n),[n,t]),[$,Y]=c.useState(D[0]?.id??""),[ne,_]=c.useState(null),[E,T]=c.useState("overview"),[z,U]=c.useState(null),[je,ue]=c.useState(!1),[V,ie]=c.useState(null),[he,Z]=c.useState(null),ee=he?a.payload?.tasksets.find(A=>A.id===he.id)??he:null,me=D.find(A=>A.id===$)??D[0]??null,O=ne?D.find(A=>A.id===ne)??null:null,pe=O?Cr(O):null,le=Ai(t.kind),de=pe?.git?.headCommit??null,ye=c.useMemo(()=>t.kind==="model"?z?["Version details"]:[]:Er(E,ne,de,t.kind==="agent"),[E,de,ne,z,t.kind]),W=t.tasksetId?a.payload?.tasksets.find(A=>A.id===t.tasksetId)??null:null,Ne=t.kind==="agent"?s?.agents.some(A=>A.id===t.id)??!1:!1,q=As({workproduct:t,runs:D,taskset:W,training:a.payload}),ge=q.runId??D[0]?.id??"",Q=D.some(A=>A.id===$),Re=ne?D.some(A=>A.id===ne):!0,be=[["overview","Overview"],["changes","Changes"],["evals","Evals"],["versions","Versions"],["configuration","Configuration"]];c.useEffect(()=>{g(null),Y(ge),_(null),U(null),T("overview")},[t.key]),c.useEffect(()=>{$&&Q||Y(ge)},[ge,Q,$]),c.useEffect(()=>{Re||_(null)},[Re]),c.useEffect(()=>{if(E==="changes"&&O&&pe){const A=Pr(t,s,pe);g({run:O,candidate:pe,fileRootPath:A.fileRootPath,initialPath:A.initialPath});return}g(null)},[E,g,s,pe,O,t]),c.useEffect(()=>{l({kind:t.kind,kindLabel:le,workproductLabel:t.name,sectionLabels:ye})},[le,ye,l,t.kind,t.name]),c.useEffect(()=>()=>g(null),[g]);function Ae(A){const J=ht(t,n,a.payload).find(se=>se.lineage.id===A);if(J?.taskset){if(J.job?.destinationId==="fireworks"){ie(A);return}v(Ot({modelId:A,taskset:J.taskset}))}}async function fe(A){(await a.actions.auditGraders(A))?.passed&&await a.actions.readiness(A)}return 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.jsx("div",{children:e.jsxs("div",{className:"labs-workproduct-name-row",children:[e.jsx("h1",{children:t.name}),e.jsx(mn,{label:q.statusLabel,value:q.statusValue})]})}),t.kind==="model"?e.jsx("div",{className:"labs-workproduct-header-actions",children:e.jsx("button",{className:"training-button",type:"button",onClick:()=>ue(!0),children:"New version"})}):t.kind==="agent"?e.jsxs("div",{className:"labs-workproduct-header-actions",children:[e.jsx("button",{className:"training-button",type:"button",onClick:()=>u(t.id),children:"Improve agent"}),Ne?e.jsxs("button",{className:"settings-secondary compact",type:"button",onClick:o,children:[e.jsx(dn,{size:14}),e.jsx("span",{children:"Rename"})]}):null]}):null]}),t.kind!=="model"?e.jsx("div",{className:"training-detail-tabs",role:"tablist","aria-label":"Workproduct detail",children:be.map(([A,J])=>e.jsxs("button",{className:E===A?"active":void 0,"aria-selected":E===A,role:"tab",type:"button",onClick:()=>{T(A),A==="changes"&&_(null)},children:[J,A==="changes"?e.jsx(mn,{decorative:!0,label:$r(D[0]??null),size:"small",tone:wr(D[0]??null)}):null]},A))}):null,e.jsx("div",{className:"training-detail-sections",children:t.kind==="model"?z?e.jsx(or,{connection:i,runs:n,selectedEntryKey:z,training:a,workproduct:t,onBack:()=>U(null),onOpenDataset:h,onUseVersion:Ae}):e.jsx(lr,{runs:n,training:a,workproduct:t,onOpenDataset:h,onOpenEntry:U,onToast:m}):E==="overview"?e.jsxs(xe,{title:"Overview",children:[e.jsxs("dl",{className:"labs-inline-facts",children:[e.jsx(We,{label:"Type",value:Ms(t.kind)}),e.jsx(We,{label:"Status",value:q.statusLabel}),t.kind==="agent"?e.jsx(We,{label:"Profile",value:"Saved in your Profile"}):e.jsxs(e.Fragment,{children:[e.jsx(We,{label:"ID",value:t.id}),e.jsx(We,{label:"Path",value:t.path??"Managed artifact"})]})]}),e.jsx("p",{className:"labs-detail-copy",children:t.description})]}):E==="changes"&&!O?e.jsx("div",{className:"labs-change-index",children:e.jsx(Oi,{runs:D,onReview:A=>{Y(A.id),_(A.id)}})}):E==="changes"&&O&&pe?e.jsx(Di,{candidate:pe,diff:j.diff,error:j.error,run:O,onApplyCandidate:(A,J)=>y({run:A},J),onOpenFiles:k,onRejectCandidate:(A,J)=>w({run:A},J)}):E==="changes"&&O?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(ve,{label:O.state.replaceAll("_"," "),value:O.state})]}),e.jsx("div",{className:"labs-change-card-body",children:e.jsx("h3",{children:O.objective})})]}),e.jsx(fr,{run:O,onAnswerQuestion:x,onApplyCandidate:y,onApprove:N,onCancel:S,onOpenConversation:r,onOpenPullRequest:C,onPause:M,onReconcilePullRequest:R,onRejectCandidate:w,onResume:p,onRetry:()=>u(t.id,O.objective),onRevise:B})]}):E==="evals"?e.jsx(xe,{title:"Evals",actions:t.kind==="agent"?e.jsx($i,{agentId:t.id,evals:s?.evals??[],onCreate:()=>u(t.id,`Create an Eval for ${t.name}. Describe the behavior this Eval should specify: `),onAttach:A=>u(t.id,`--eval ${JSON.stringify(A)} Improve ${t.name} using this existing Eval: `)}):null,children:e.jsx(Ar,{profileEvals:s?.evals??[],run:me,workproduct:t})}):E==="versions"?e.jsxs(e.Fragment,{children:[e.jsx(xe,{title:"Versions",children:e.jsx(_r,{runs:D,selectedRun:me,taskset:W,training:a,trainingState:a.payload,onToast:m})}),e.jsx(Rr,{runs:D,selectedRun:me,onSelectedRunIdChange:Y})]}):e.jsxs(e.Fragment,{children:[e.jsx(xe,{title:"Connections",children:e.jsxs("dl",{className:"training-configuration-list",children:[e.jsx(Pe,{label:"Profile",value:s?.activeProfile??"default"}),e.jsx(Pe,{label:"Conversation",value:me?.scope.conversationId??"Not linked"}),e.jsx(Pe,{label:"Project",value:me?.scope.projectId??"Not linked"}),e.jsx(Pe,{label:"Source authority",value:me?.adapter.sourceAuthority??"Profile"})]})}),e.jsx(Ir,{workproduct:t,profile:s})]})}),je?e.jsx(gr,{checking:["audit-graders","readiness"].includes(a.busyAction??""),initialTasksetId:W?.id??null,state:a.payload,onClose:()=>ue(!1),onCheck:fe,onContinue:({taskset:A})=>{ue(!1),Z(A)},onReview:A=>h(A)}):null,ee?e.jsx(gi,{busy:["prepare-training","start-prepared-training","start-training","baseline"].includes(a.busyAction??""),busyAction:a.busyAction,connection:i,baseModelCandidates:a.payload?.baseModelCandidates??[],destinations:a.payload?.destinations??[],modelId:t.id,preferredBaseModel:Sr(D),taskset:ee,baselineReports:a.payload?.baselineReports.filter(A=>A.tasksetId===ee.id&&A.tasksetHash===ee.contentHash)??[],baselineRuns:a.payload?.baselineRuns.filter(A=>A.tasksetId===ee.id)??[],onClose:()=>Z(null),onOpenProviderSettings:d,onRunBaseline:async(A,J)=>!!await a.actions.baseline(ee.id,A,J),onPrepare:(A,J,se)=>a.actions.prepareTraining({modelId:t.id,tasksetId:ee.id,destinationId:A,recipe:J,exportApproved:se.exportApproved,retentionDays:se.retentionDays,region:se.region}),onConfirmPrepared:async(A,J)=>!!await a.actions.startPreparedTraining({planId:A.plan.id,bundleId:A.bundle.id,maximumCostUsd:J}),onStart:async(A,J,se)=>!!await a.actions.startTraining({modelId:t.id,tasksetId:ee.id,destinationId:A,recipe:J,...se})}):null,V?(()=>{const A=ht(t,n,a.payload).find(J=>J.lineage.id===V);return A?.taskset?e.jsx(xs,{lineage:A.lineage,taskset:A.taskset,training:a,onChat:v,onClose:()=>ie(null)}):null})():null]})}function Lr({activeTab:t,children:n,suggestionCount:s,showHeader:a=!0,onTabChange:i,onCreateAgent:r,onCreateDataset:l,onCreateModel:o}){const[u,h]=c.useState(!1),d=c.useRef(null);return c.useEffect(()=>{if(!u)return;function m(j){d.current?.contains(j.target)||h(!1)}function x(j){j.key==="Escape"&&h(!1)}return document.addEventListener("pointerdown",m),document.addEventListener("keydown",x),()=>{document.removeEventListener("pointerdown",m),document.removeEventListener("keydown",x)}},[u]),e.jsxs("section",{className:"labs-route","aria-label":"Lab",children:[a?e.jsxs("header",{className:"labs-header",children:[e.jsx("div",{className:"labs-header-navigation",children:e.jsxs("nav",{className:"labs-primary-tabs",role:"tablist","aria-label":"Lab sections",children:[e.jsx("button",{"aria-selected":t==="workproducts",className:t==="workproducts"?"active":void 0,role:"tab",type:"button",onClick:()=>i("workproducts"),children:"Home"}),e.jsx("button",{"aria-selected":t==="datasets",className:t==="datasets"?"active":void 0,role:"tab",type:"button",onClick:()=>i("datasets"),children:"Datasets"}),e.jsxs("button",{"aria-selected":t==="suggestions",className:t==="suggestions"?"active":void 0,role:"tab",type:"button",onClick:()=>i("suggestions"),children:["Suggestions",s>0?e.jsx("span",{children:s}):null]})]})}),e.jsx("div",{className:"labs-header-actions",children:e.jsxs("div",{className:"labs-create-anchor",ref:d,children:[e.jsx("button",{className:"labs-create-button",type:"button","aria-expanded":u,"aria-haspopup":"menu","aria-label":"Create workproduct",title:"Create workproduct",onClick:()=>h(m=>!m),children:e.jsx(cs,{size:15})}),u?e.jsxs("div",{className:"labs-create-menu",role:"menu",children:[e.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{h(!1),r()},children:[e.jsx(us,{size:15}),e.jsxs("span",{children:[e.jsx("strong",{children:"New agent"}),e.jsx("small",{children:"Describe the agent in the shared Create flow."})]})]}),e.jsxs("button",{disabled:!0,type:"button",role:"menuitem",children:[e.jsx(ra,{size:15}),e.jsxs("span",{children:[e.jsx("strong",{children:"New skill"}),e.jsx("small",{children:"Coming soon"})]})]}),e.jsxs("button",{disabled:!0,type:"button",role:"menuitem",children:[e.jsx(la,{size:15}),e.jsxs("span",{children:[e.jsx("strong",{children:"New extension"}),e.jsx("small",{children:"Coming soon"})]})]}),e.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{h(!1),o()},children:[e.jsx(hs,{size:15}),e.jsxs("span",{children:[e.jsx("strong",{children:"New model"}),e.jsx("small",{children:"Build the data and Evals, then choose training."})]})]}),e.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{h(!1),l()},children:[e.jsx(pt,{size:15}),e.jsxs("span",{children:[e.jsx("strong",{children:"New Dataset"}),e.jsx("small",{children:"Create a reusable Taskset without creating a Model."})]})]})]}):null]})})]}):null,e.jsx("div",{className:"labs-panel",children:n})]})}function Br({agentId:t,currentName:n,onClose:s,onRename:a}){const[i,r]=c.useState(n),[l,o]=c.useState(!1),[u,h]=c.useState(null);Qe(u);const d=i.trim().replace(/\s+/g," "),m=d===n.trim().replace(/\s+/g," ");c.useEffect(()=>{r(n),o(!1),h(null)},[t,n]);async function x(j){if(j.preventDefault(),!(!d||m||l)){o(!0),h(null);try{await a(d),s()}catch(N){h(N instanceof Error?N.message:String(N))}finally{o(!1)}}}return e.jsxs(it,{ariaLabel:`Rename ${n}`,backdropClassName:"labs-rename-backdrop",className:"labs-rename-dialog",dismissDisabled:l,initialFocusKey:t,onClose:s,children:[e.jsxs("header",{children:[e.jsx("span",{className:"labs-rename-dialog-icon",children:e.jsx(us,{size:16})}),e.jsxs("div",{children:[e.jsx("h2",{children:"Rename agent"}),e.jsx("p",{children:"Change the display name without changing the stable agent ID."})]}),e.jsx("button",{"aria-label":"Close rename agent",disabled:l,type:"button",onClick:s,children:e.jsx(Xe,{size:16})})]}),e.jsxs("form",{onSubmit:j=>{x(j)},children:[e.jsxs("label",{children:[e.jsx("span",{children:"Display name"}),e.jsx("input",{"data-autofocus":!0,maxLength:80,value:i,onChange:j=>r(j.currentTarget.value)})]}),e.jsxs("div",{className:"labs-rename-agent-id",children:[e.jsx("span",{children:"Agent ID"}),e.jsx("code",{children:t})]}),e.jsxs("footer",{children:[e.jsx("button",{disabled:l,type:"button",onClick:s,children:"Cancel"}),e.jsx("button",{disabled:!d||m||l,type:"submit",children:l?"Renaming…":"Rename"})]})]})]})}function Or({taskset:t,busyAction:n,onPreview:s,onApprove:a,onToast:i}){const[r,l]=c.useState(null),[o,u]=c.useState(!1),h=zr(t),d=t.learningSignals.demonstrations.filter(S=>S.approved&&S.metadata.exampleOrigin==="expert_authored").length,m=n==="preview-expert-bootstrap",x=n==="approve-expert-bootstrap";async function j(){u(!0);const S=await s();if(S){l(S);return}u(!1),i("Couldn’t load the expert trajectories.","error")}async function N(){if(!r)return;const S=await a(r.previewHash);if(!S){i("The expert trajectories were not approved.","error");return}u(!1),i(`${S.approval.trajectoryCount} expert trajectories approved by ${S.approval.approvedBy}.`,"success")}return e.jsxs(e.Fragment,{children:[e.jsx(xe,{title:"SFT bootstrap data",actions:e.jsx("button",{className:"training-button secondary",disabled:m||x,type:"button",onClick:()=>{j()},children:h?"Review trajectories":m?"Loading…":"Review expert trajectories"}),children:e.jsxs("div",{className:"labs-expert-bootstrap-summary",children:[e.jsxs("div",{children:[e.jsx(ve,{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(St,{label:"Approved by",value:h.approvedBy}),e.jsx(St,{label:"Taskset revision",value:String(t.revision)})]}):null]})}),o?e.jsx(Fr,{approving:x,loading:m,preview:r,onApprove:()=>{N()},onClose:()=>{x||u(!1)}}):null]})}function Fr({preview:t,loading:n,approving:s,onApprove:a,onClose:i}){return e.jsxs(it,{ariaLabel:"Review expert trajectories",className:"training-dialog labs-expert-bootstrap-dialog",dismissDisabled:s,onClose:i,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:s,type:"button",onClick:i,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(St,{label:"Taskset revision",value:String(t.tasksetRevision)}),e.jsx(St,{label:"Trajectories",value:String(t.tasks.length)}),e.jsx(St,{label:"Review state",value:t.status==="approved"?"Approved":"Pending"})]}),t.tasks.map(r=>e.jsxs("details",{className:"labs-expert-trajectory",children:[e.jsxs("summary",{children:[e.jsxs("span",{children:[e.jsx("strong",{children:qr(r.family)}),e.jsxs("small",{children:[r.toolCallCount," tool calls · exact reward ",r.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:r.prompt})]}),e.jsxs("section",{children:[e.jsx("h3",{children:"Tool sequence"}),e.jsx("div",{className:"training-pills",children:r.toolNames.map((l,o)=>e.jsx("span",{children:l},`${r.trajectoryId}-${l}-${o}`))})]}),e.jsxs("section",{children:[e.jsx("h3",{children:"Verified answer"}),e.jsx("pre",{children:r.finalAnswer})]}),e.jsxs("details",{className:"labs-expert-messages",children:[e.jsxs("summary",{children:["View ",r.messageCount," training messages"]}),e.jsx("pre",{children:JSON.stringify(r.messages,null,2)})]})]})]},r.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:s,type:"button",onClick:i,children:"Close"}),t?.status!=="approved"?e.jsx("button",{className:"training-button",disabled:!t||n||s,type:"button",onClick:a,children:s?"Approving…":`Approve ${t?.tasks.length??0} trajectories`}):null]})]})}function zr(t){const n=ns(t.metadata.expertBootstrap),s=ns(n.approval);return s.status!=="approved"||typeof s.approvedBy!="string"||typeof s.approvedAt!="string"||typeof s.previewHash!="string"||typeof s.trajectoryCount!="number"?null:s}function St({label:t,value:n}){return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsx("dd",{children:n})]})}function qr(t){return t.split("_").map(n=>`${n.slice(0,1).toUpperCase()}${n.slice(1)}`).join(" ")}function ns(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}const Ur=new Set(["queued","preparing","running","cancelling"]);function Vr({runs:t,taskset:n,onCancel:s}){return e.jsx(xe,{title:"Checks",children:t.length?e.jsx("div",{className:"training-table-wrap",children:e.jsxs("table",{className:"training-data-table","aria-label":"Dataset checks",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Check"}),e.jsx("th",{children:"Version"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Progress"}),e.jsx("th",{children:"Provider"}),e.jsx("th",{children:"Updated"}),e.jsx("th",{"aria-label":"Actions"})]})}),e.jsx("tbody",{children:t.map(a=>{const i=Ur.has(a.status);return e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:a.configuration.split==="train"?"Train signal":"Baseline"}),e.jsxs("span",{children:[a.configuration.taskLimit," prompts × ",a.configuration.attemptsPerTask]}),a.error?e.jsx("span",{className:"training-field-error",role:"alert",children:a.error}):null]}),e.jsx("td",{children:a.tasksetHash===n.contentHash?"Current":"Earlier"}),e.jsx("td",{children:e.jsx(ve,{label:a.status.replaceAll("_"," "),value:a.status})}),e.jsx("td",{children:Kr(a)}),e.jsx("td",{children:Hr(a)}),e.jsx("td",{children:Gr(a.updatedAt)}),e.jsx("td",{children:i?e.jsx("button",{className:"training-button secondary",disabled:a.status==="cancelling",type:"button",onClick:()=>{s(a.id)},children:a.status==="cancelling"?"Cancelling…":"Cancel"}):null})]},a.id)})})]})}):e.jsx("div",{className:"training-run-placeholder",children:"No checks have been run for this Dataset yet."})})}function Kr(t){const{completedAttempts:n,totalAttempts:s,stage:a}=t.progress;return t.status==="succeeded"?`${n}/${s} complete`:t.status==="failed"||t.status==="cancelled"?n?`${n}/${s} before ${t.status}`:a.replaceAll("_"," "):a==="running"?`${n}/${s}`:a.replaceAll("_"," ")}function Hr(t){return t.provider?t.provider.statusCode?t.provider.statusCode:t.provider.state?t.provider.state:t.provider.phase.replaceAll("_"," "):"Not started"}function Gr(t){const n=new Date(t);return Number.isFinite(n.getTime())?n.toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):"—"}const Wr=[{id:"train",label:"Training"},{id:"validation",label:"Validation"},{id:"frozen_eval",label:"Frozen Eval"}],rn=10;function Jr({artifact:t,taskset:n,onOpenFiles:s,training:a}){const i=c.useMemo(()=>t?new Map(Object.entries(t.splitCounts)):rl(n.tasks.map(_=>_.split)),[t,n.tasks]),r=i.get("train")?"train":i.get("validation")?"validation":i.get("frozen_eval")?"frozen_eval":n.tasks[0]?.split??"train",[l,o]=c.useState(r==="test"?"frozen_eval":r),[u,h]=c.useState(!1),[d,m]=c.useState([]),[x,j]=c.useState(null),[N,S]=c.useState([]),[v,y]=c.useState(null),[g,k]=c.useState(!1),[C,M]=c.useState(null),R=c.useMemo(()=>new Map(n.sourceRefs.map(_=>[_.id,_])),[n.sourceRefs]);c.useEffect(()=>{if(!t)return;let _=!1;return k(!0),M(null),a.actions.datasetRows(n.id,{split:l,cursor:x,limit:25}).then(E=>{_||!E||(m(E.rows.map(T=>oa.parse(T))),y(E.nextCursor))}).catch(E=>{_||(m([]),y(null),M(E instanceof Error?E.message:String(E)))}).finally(()=>{_||k(!1)}),()=>{_=!0}},[t,x,l,n.id,a.actions]);const w=t?d:n.tasks.filter(_=>_.split===l),p=u?w:w.slice(0,rn),B=n.sourceRefs.filter(kn).length,D=n.sourceRefs.filter(_=>jn(_)&&_.turnIds.length>0).length,$=n.sourceRefs.filter(_=>_.metadata.containsCustomerData===!0).length,Y=n.learningSignals.demonstrations.filter(_=>_.approved).length,ne=a.payload?.baselineRuns.filter(_=>_.tasksetId===n.id)??[];return e.jsxs(e.Fragment,{children:[e.jsxs(xe,{title:"Dataset",actions:e.jsx("button",{className:"training-button secondary",type:"button",onClick:s,children:"Open files"}),children:[e.jsx("p",{className:"labs-detail-copy labs-dataset-summary",children:Xr({syntheticSources:B,chatSources:D,customerSources:$,sourceCount:n.sourceRefs.length})}),e.jsxs("dl",{className:"labs-inline-facts",children:[e.jsx(st,{label:"Training",value:String(i.get("train")??0)}),e.jsx(st,{label:"Validation",value:String(i.get("validation")??0)}),e.jsx(st,{label:"Frozen Eval",value:String(i.get("frozen_eval")??0)}),e.jsx(st,{label:"Approved demonstrations",value:String(Y)})]})]}),e.jsx(Vr,{runs:ne,taskset:n,onCancel:a.actions.cancelBaselineRun}),e.jsxs(xe,{title:"Examples",children:[e.jsx("div",{className:"labs-method-tabs labs-dataset-tabs",role:"tablist","aria-label":"Dataset splits",children:Wr.map(_=>e.jsxs("button",{"aria-selected":l===_.id,className:l===_.id?"active":"",role:"tab",type:"button",onClick:()=>{o(_.id),h(!1),j(null),S([])},children:[_.label,e.jsx("span",{children:i.get(_.id)??0})]},_.id))}),e.jsxs("div",{className:"labs-dataset-examples",children:[p.map((_,E)=>e.jsx(Qr,{index:E,source:_.sourceRefs.map(T=>R.get(T)).find(Boolean)??null,task:_},_.id)),w.length>rn?e.jsx("button",{className:"training-button secondary labs-dataset-show-all",type:"button",onClick:()=>h(_=>!_),children:u?`Show first ${rn}`:`Show all ${w.length}`}):null,t?e.jsxs("div",{className:"labs-pagination","aria-label":"Dataset example pages",children:[e.jsx("button",{type:"button",disabled:!N.length||g,onClick:()=>{const _=N.at(-1)??null;S(E=>E.slice(0,-1)),j(_||null)},children:"Previous"}),e.jsx("span",{children:g?"Loading…":`${d.length.toLocaleString()} rows on this page`}),e.jsx("button",{type:"button",disabled:!v||g,onClick:()=>{S(_=>[..._,x??""]),j(v)},children:"Next"})]}):null,C?e.jsx("div",{className:"training-banner error",role:"alert",children:C}):null]})]})]})}function Qr({index:t,source:n,task:s}){const a=Yr(s),i=el(s),r=Zr(s),l=n?sl(n):"Source unavailable",o=tl(s,n),u=nl(s,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:a}),e.jsx("small",{children:[o,u,l].filter(Boolean).join(" · ")})]}),e.jsx(ve,{label:il(s.split),value:s.split})]}),e.jsxs("div",{className:"labs-dataset-example-body",children:[e.jsxs("section",{children:[e.jsx("h3",{children:"Prompt"}),e.jsx("p",{children:a})]}),e.jsxs("section",{children:[e.jsx("h3",{children:s.split==="frozen_eval"?"Expected result":"Approved answer"}),s.split==="frozen_eval"?e.jsx("p",{children:"The answer stays held out and is only opened by the Eval runner."}):e.jsx("pre",{children:r??"No approved answer is attached."})]}),i.length?e.jsxs("section",{children:[e.jsx("h3",{children:"Tool trajectory"}),e.jsx("div",{className:"training-pills",children:i.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"})," — ",al(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(st,{label:"Task",value:s.id}),e.jsx(st,{label:"Source",value:n?.id??"Unavailable"}),e.jsx(st,{label:"Cluster",value:s.clusterKey})]})]})]})]})}function Xr(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 Yr(t){return typeof t.input.prompt=="string"?t.input.prompt:"Untitled dataset example"}function Zr(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 s of[...n].reverse())if(s&&typeof s=="object"&&"content"in s&&typeof s.content=="string")return s.content;return null}function el(t){if(!t.expectedOutput||!Array.isArray(t.expectedOutput.messages))return[];const n=[];for(const s of t.expectedOutput.messages){if(!s||typeof s!="object"||!("tool_calls"in s))continue;const a=Array.isArray(s.tool_calls)?s.tool_calls:[];for(const i of a){if(!i||typeof i!="object"||!("function"in i))continue;const r=i.function;r&&typeof r=="object"&&"name"in r&&typeof r.name=="string"&&n.push(r.name)}}return n}function tl(t,n){const s=n?.metadata.crossSystemOperations;if(s&&typeof s=="object"&&"taskFamily"in s){const i=s.taskFamily;if(typeof i=="string")return zt(i)}const a=t.tags.find(i=>!["synthetic","structured-tool-trajectory"].includes(i));return a?zt(a):null}function nl(t,n){const s=n?.metadata.crossSystemOperations;if(s&&typeof s=="object"&&"worldDifficulty"in s){const a=s.worldDifficulty;if(typeof a=="string")return zt(a)}return t.clusterKey.match(/_(easy|medium|hard)$/)?.[1]??null}function kn(t){return t.schemaVersion==="openpond.generatedDatasetSource.v1"||t.metadata.syntheticSpecification===!0}function sl(t){return kn(t)?"Generated scenario":jn(t)&&t.turnIds.length>0?"Chat":t.schemaVersion==="openpond.huggingFaceDatasetSource.v1"?"Hugging Face":t.schemaVersion==="openpond.uploadedFileDatasetSource.v1"?"Uploaded file":"Imported source"}function al(t){return t?kn(t)&&t.metadata.containsCustomerData===!1?"generated locally from a deterministic specification; no customer content is attached.":jn(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 il(t){return t==="frozen_eval"?"Frozen Eval":zt(t)}function zt(t){return t.replaceAll("-"," ").replaceAll("_"," ").replace(/\b\w/g,n=>n.toUpperCase())}function rl(t){const n=new Map;for(const s of t)n.set(s,(n.get(s)??0)+1);return n}function st({label:t,value:n}){return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsx("dd",{children:n})]})}const fn=10;function ll({state:t,runs:n,selectedId:s,onSelectedIdChange:a,onCreate:i,onOpenFiles:r,training:l,onToast:o}){const[u,h]=c.useState(""),[d,m]=c.useState(1),x=t?.tasksets??[],j=x.find(g=>g.id===s)??null,N=t?.datasetArtifacts.find(g=>g.tasksetId===s)??null,S=c.useMemo(()=>{const g=u.trim().toLowerCase();return g?x.filter(k=>[k.name,k.objective,k.id].some(C=>C.toLowerCase().includes(g))):x},[u,x]),v=S.slice((d-1)*fn,d*fn),y=c.useMemo(()=>{const g=new Map;if(!t)return g;const k=js({profile:null,training:t,runs:n}).filter(C=>C.kind==="model");for(const C of k)for(const M of ks(C,n,t))g.set(M.id,(g.get(M.id)??0)+1);return g},[n,t]);return j?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 Datasets",className:"labs-back-button",type:"button",onClick:()=>a(null),children:e.jsx(xn,{size:15})}),e.jsxs("div",{children:[e.jsx("h1",{children:j.name}),e.jsx("p",{children:j.objective})]}),e.jsx(ve,{label:ol(j),value:j.status})]}),e.jsx(Jr,{artifact:N,taskset:j,onOpenFiles:()=>r(j.id),training:l}),j.metadata.flagship==="cross-system-operations"?e.jsx(Or,{busyAction:l.busyAction,taskset:j,onApprove:g=>l.actions.approveExpertBootstrap(j.id,g),onPreview:()=>l.actions.previewExpertBootstrap(j.id),onToast:o}):null]}):e.jsxs("div",{className:"labs-flat-body labs-datasets-page",children:[e.jsx("div",{className:"labs-resource-actions",children:e.jsx("button",{className:"training-button",type:"button",onClick:i,children:"Create Dataset"})}),e.jsx("div",{className:"labs-workproduct-toolbar",children:e.jsxs("label",{className:"labs-search",children:[e.jsx(os,{size:14}),e.jsx("input",{"aria-label":"Search Datasets",placeholder:"Search Datasets",value:u,onChange:g=>{h(g.target.value),m(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:"Dataset"}),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:"Models"}),e.jsx("th",{children:"Updated"})]})}),e.jsx("tbody",{children:v.map(g=>{const k=y.get(g.id)??0;return e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("button",{className:"labs-workproduct-link",type:"button",onClick:()=>a(g.id),children:[e.jsx("strong",{children:g.name}),e.jsx("span",{children:g.objective})]})}),e.jsx("td",{children:ln(g,t,"train")}),e.jsx("td",{children:ln(g,t,"validation")}),e.jsx("td",{children:ln(g,t,"frozen_eval")}),e.jsx("td",{children:g.graders.length}),e.jsx("td",{children:k||"—"}),e.jsx("td",{children:dl(g.updatedAt)})]},g.id)})})]})}),v.length?null:e.jsx("div",{className:"labs-table-empty",children:"No Datasets match this view."}),e.jsx(cl,{page:d,total:S.length,onChange:m})]})}function ln(t,n,s){const a=n?.datasetArtifacts.find(i=>i.tasksetId===t.id);return a?a.splitCounts[s]??0:t.tasks.filter(i=>i.split===s).length}function ol(t){return t.readiness?.ready?"Ready":t.status==="ready"?"Needs Evals":t.status.replaceAll("_"," ").replace(/^./,n=>n.toUpperCase())}function dl(t){const n=new Date(t);return Number.isFinite(n.getTime())?n.toLocaleDateString(void 0,{month:"short",day:"numeric"}):"—"}function cl({page:t,total:n,onChange:s}){const a=Math.max(1,Math.ceil(n/fn));return a===1?null:e.jsxs("nav",{className:"labs-pagination","aria-label":"Dataset pages",children:[e.jsx("button",{type:"button",disabled:t<=1,onClick:()=>s(t-1),children:"Previous"}),e.jsxs("span",{children:[t," of ",a]}),e.jsx("button",{type:"button",disabled:t>=a,onClick:()=>s(t+1),children:"Next"})]})}function ul({enabled:t,items:n,runs:s,nextScanAt:a,scanRunning:i,scanStartedAt:r,scanning:l,savingEnabled:o,error:u,onEnabledChange:h,onPatchStatus:d,onOpenSession:m}){Qe(u);const[x,j]=c.useState("all"),[N,S]=c.useState("all"),[v,y]=c.useState("all"),[g,k]=c.useState("all"),[C,M]=c.useState("all"),[R,w]=c.useState(()=>Date.now());c.useEffect(()=>{const z=window.setInterval(()=>w(Date.now()),1e3);return()=>window.clearInterval(z)},[]);const p=c.useMemo(()=>n.filter(z=>!(x!=="all"&&z.status!==x||N!=="all"&&z.severity!==N||v!=="all"&&Es(z)!==v)),[n,N,v,x]),B=c.useMemo(()=>s.filter(z=>!(g!=="all"&&z.status!==g||C!=="all"&&z.trigger!==C||v!=="all"&&!z.evidenceSources.includes(v))),[g,C,s,v]),D=c.useMemo(()=>p.filter(z=>z.status==="active"),[p]),$=c.useMemo(()=>p.filter(z=>z.status!=="active"),[p]),Y=x==="all"||x==="active",ne=x==="all"||x!=="active",_=l||i,E=`${x}:${N}:${v}`,T=`${g}:${C}:${v}`;return e.jsxs("section",{className:"insights-view","aria-label":"Insights",children:[e.jsxs("section",{className:"insights-scan-preference","aria-label":"Observation scanning",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Observation scanning"}),e.jsx("span",{children:"Periodically review selected work, failures, and corrections for signals. It stays off until you turn it on."})]}),e.jsxs("div",{className:"insights-scan-controls",children:[e.jsxs("span",{className:`insights-scan-countdown ${_?"running":""}`,children:[e.jsx("span",{className:"insights-scan-dot","aria-hidden":"true"}),t?jl(a,R,_):"Scanning is off"]}),e.jsx("button",{"aria-pressed":t,className:t?"active":void 0,disabled:o||_,type:"button",onClick:()=>{h(!t)},children:o?"Saving":t?"On":"Turn on"})]})]}),e.jsxs("div",{className:"insights-filters","aria-label":"Insight filters",children:[e.jsx(kt,{label:"Observation status",options:hl,value:x,onChange:j}),e.jsx(kt,{label:"Severity",options:pl,value:N,onChange:S}),e.jsx(kt,{label:"Source",options:ml,value:v,onChange:y}),e.jsx(kt,{label:"Run status",options:gl,value:g,onChange:k}),e.jsx(kt,{label:"Run trigger",options:fl,value:C,onChange:M})]}),_?e.jsxs("div",{className:"insights-active-scan",role:"status",children:[e.jsx("span",{className:"insights-scan-dot","aria-hidden":"true"}),e.jsxs("div",{children:[e.jsx("strong",{children:"Active scan"}),e.jsx("span",{children:r?`Started ${Sn(r)}`:"Scanning insights now"})]})]}):null,e.jsx(xl,{runs:B,paginationKey:T,onOpenSession:m}),Y?e.jsx(ss,{title:"Active",emptyText:"No active Create/Improve insights match the filters.",items:D,paginationKey:E,onPatchStatus:d,onOpenSession:m}):null,ne?e.jsx(ss,{title:"Recent",emptyText:"No resolved or dismissed insights match the filters.",items:$,paginationKey:E,onPatchStatus:d,onOpenSession:m}):null]})}const hl=[{value:"all",label:"All"},{value:"active",label:"Active"},{value:"resolved",label:"Resolved"},{value:"dismissed",label:"Dismissed"}],pl=[{value:"all",label:"All"},{value:"blocker",label:"Blocker"},{value:"concern",label:"Concern"},{value:"nit",label:"Nit"}],ml=[{value:"all",label:"All"},{value:"create_edit",label:"Create/Improve"},{value:"stuck_turn",label:"Stuck turns"},{value:"tool_failure",label:"Tools"},{value:"abandoned_goal",label:"Goals"},{value:"user_correction",label:"Corrections"},{value:"unresolved_conversation",label:"Unresolved"},{value:"usage_anomaly",label:"Usage"}],gl=[{value:"all",label:"All"},{value:"running",label:"Running"},{value:"completed",label:"Completed"},{value:"failed",label:"Failed"},{value:"skipped",label:"Skipped"}],fl=[{value:"all",label:"All"},{value:"manual",label:"Manual"},{value:"interval",label:"Interval"},{value:"startup",label:"Startup"},{value:"slash_command",label:"Slash"}];function kt({label:t,options:n,value:s,onChange:a}){return e.jsxs("label",{className:"insights-filter-group",children:[e.jsx("span",{children:t}),e.jsx("select",{value:s,onChange:i=>a(i.target.value),children:n.map(i=>e.jsx("option",{value:i.value,children:i.label},i.value))})]})}function ss({title:t,emptyText:n,items:s,paginationKey:a,onPatchStatus:i,onOpenSession:r}){const l=_s(s,a);return e.jsxs("section",{className:"insights-section",children:[e.jsx("h2",{children:t}),s.length===0?e.jsx("p",{className:"insights-empty",children:n}):e.jsxs("div",{className:"insights-table-frame",children:[e.jsx("div",{className:"insights-table-scroll",children:e.jsxs("table",{className:"insights-table insights-observations-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Severity"}),e.jsx("th",{scope:"col",children:"Status"}),e.jsx("th",{scope:"col",children:"Observation"}),e.jsx("th",{scope:"col",children:"Updated"}),e.jsx("th",{scope:"col",children:"Actions"})]})}),e.jsx("tbody",{children:l.pageItems.map(o=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("span",{className:`insights-severity ${o.severity}`,children:bl(o.severity)})}),e.jsx("td",{children:e.jsxs("div",{className:"insights-status-stack",children:[e.jsx("span",{children:o.status}),e.jsx("small",{children:Nl(Es(o))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"insights-copy",children:[e.jsx("strong",{children:o.title}),e.jsx("span",{children:o.summary})]})}),e.jsx("td",{className:"insights-time",children:Sn(o.updatedAt)}),e.jsx("td",{children:e.jsxs("div",{className:"insights-actions",children:[as(o.payload.sessionId)?e.jsx("button",{type:"button",className:"insights-text-action",onClick:()=>r(as(o.payload.sessionId)),children:"Source"}):null,o.lastRunSessionId?e.jsx("button",{type:"button",className:"insights-text-action",onClick:()=>r(o.lastRunSessionId),children:"Run"}):null,o.status==="active"?e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",title:"Resolve observation","aria-label":"Resolve observation",onClick:()=>{i(o.id,"resolved")},children:e.jsx(ps,{size:15})}),e.jsx("button",{type:"button",title:"Dismiss observation","aria-label":"Dismiss observation",onClick:()=>{i(o.id,"dismissed")},children:e.jsx(Xe,{size:15})})]}):e.jsx("button",{type:"button",title:"Reopen observation","aria-label":"Reopen observation",onClick:()=>{i(o.id,"active")},children:e.jsx(gs,{size:15})})]})})]},o.id))})]})}),e.jsx(Ts,{label:t,...l})]})]})}function xl({runs:t,paginationKey:n,onOpenSession:s}){const a=_s(t,n);return e.jsxs("section",{className:"insights-section",children:[e.jsx("h2",{children:"Runs"}),t.length===0?e.jsx("p",{className:"insights-empty",children:"No Insights runs yet."}):e.jsxs("div",{className:"insights-table-frame",children:[e.jsx("div",{className:"insights-table-scroll",children:e.jsxs("table",{className:"insights-table insights-runs-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Trigger"}),e.jsx("th",{scope:"col",children:"Status"}),e.jsx("th",{scope:"col",children:"Model"}),e.jsx("th",{scope:"col",children:"Summary"}),e.jsx("th",{scope:"col",children:"Completed"}),e.jsx("th",{scope:"col",children:"Actions"})]})}),e.jsx("tbody",{children:a.pageItems.map(i=>e.jsxs("tr",{children:[e.jsx("td",{children:vl(i.trigger)}),e.jsx("td",{className:"insights-status",children:i.status}),e.jsx("td",{className:"insights-status",children:yl(i)}),e.jsx("td",{children:e.jsxs("div",{className:"insights-copy",children:[e.jsx("strong",{children:i.summary??`${i.findingCount} finding${i.findingCount===1?"":"s"}`}),e.jsxs("span",{children:[i.createdCount," new / ",i.updatedCount," updated / ",i.resolvedCount," resolved"]})]})}),e.jsx("td",{className:"insights-time",children:Sn(i.completedAt??i.startedAt)}),e.jsx("td",{children:e.jsx("div",{className:"insights-actions",children:e.jsx("button",{type:"button",className:"insights-text-action",onClick:()=>s(i.sessionId),children:"Open run"})})})]},i.turnId))})]})}),e.jsx(Ts,{label:"Runs",...a})]})]})}const Et=10;function _s(t,n){const[s,a]=c.useState(0);c.useEffect(()=>a(0),[n]);const i=Math.max(1,Math.ceil(t.length/Et)),r=Math.min(s,i-1),l=r*Et;return{pageItems:t.slice(l,l+Et),pageIndex:r,pageCount:i,pageStart:l,pageSize:Et,totalItems:t.length,onPageChange:a}}function Ts({label:t,pageIndex:n,pageCount:s,pageStart:a,pageSize:i,totalItems:r,onPageChange:l}){return e.jsxs("nav",{className:"insights-pagination","aria-label":`${t} pagination`,children:[e.jsxs("span",{children:[a+1,"–",Math.min(a+i,r)," of ",r]}),e.jsxs("div",{children:[e.jsx("button",{type:"button",disabled:n===0,onClick:()=>l(n-1),children:"Previous"}),e.jsxs("span",{children:["Page ",n+1," of ",s]}),e.jsx("button",{type:"button",disabled:n>=s-1,onClick:()=>l(n+1),children:"Next"})]})]})}function bl(t){return t==="blocker"?"Blocker":t==="concern"?"Concern":"Nit"}function jl(t,n,s){if(s)return"Scanning now";if(!t)return"Next scan not scheduled";const a=new Date(t).getTime();if(Number.isNaN(a))return"Next scan not scheduled";const i=a-n;if(i<=0)return"Next scan starting soon";const r=Math.ceil(i/6e4);return`${r} minute${r===1?"":"s"} till next scan`}function vl(t){return t==="slash_command"?"Slash command":t==="startup"?"Startup":t==="interval"?"Interval":"Manual"}function yl(t){return t.modelRef?`${t.modelRef.providerId} / ${t.modelRef.modelId}`:"Default"}function Es(t){const n=t.payload.evidenceSource;return n==="create_edit"||n==="stuck_turn"||n==="tool_failure"||n==="abandoned_goal"||n==="user_correction"||n==="unresolved_conversation"||n==="usage_anomaly"?n:"create_edit"}function Nl(t){return t==="stuck_turn"?"Stuck turn":t==="tool_failure"?"Tool failures":t==="abandoned_goal"?"Abandoned goal":t==="user_correction"?"Corrections":t==="unresolved_conversation"?"Unresolved chat":t==="usage_anomaly"?"Usage":"Create/Improve"}function as(t){return typeof t=="string"&&t.trim()?t:null}function Sn(t){const n=new Date(t);return Number.isNaN(n.getTime())?t:new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(n)}function kl({training:t,defaultModel:n,preferences:s,reasoningEffort:a,onPlanStarted:i}){const r=t.payload?.candidates??[];return e.jsxs("section",{className:"training-page-body training-suggestions",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"AI suggestions"}),e.jsx("p",{children:"Review repeated work found by the local Task Miner before creating a training plan."})]}),r.length?e.jsx("div",{className:"training-card-grid",children:r.map(l=>e.jsx(Sl,{candidate:l,candidates:r,training:t,defaultModel:n,preferences:s,reasoningEffort:a,onPlanStarted:i},l.id))}):e.jsx("div",{className:"training-empty training-suggestions-empty",children:"No AI suggestions yet. Start New model with Automatic to scan selected chats for repeated, verifiable work."})]})}function Sl({candidate:t,candidates:n,training:s,defaultModel:a,preferences:i,reasoningEffort:r,onPlanStarted:l}){const[o,u]=c.useState(""),h=n.filter(m=>m.id!==t.id&&m.status!=="retired");async function d(){const m=await s.actions.createCandidate(t.id,i.creationMode,ds(i,a),r);m&&(m.state==="awaiting_disclosure_approval"&&i.autoApproveEvidence&&await s.actions.approveDisclosure(m.id,!0),l())}return e.jsxs("article",{className:"training-card",children:[e.jsxs("div",{className:"training-card-heading",children:[e.jsx("strong",{children:t.title}),e.jsx("span",{className:"training-pill",children:t.recommendation.tactic.replaceAll("_"," ")})]}),e.jsx("p",{children:t.summary}),e.jsxs("dl",{children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Frequency"}),e.jsx("dd",{children:Pt(t.scorecard.frequency)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Verifiable"}),e.jsx("dd",{children:Pt(t.scorecard.verifiability)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Signal"}),e.jsx("dd",{children:Pt(t.scorecard.signalQuality)})]})]}),e.jsxs("details",{className:"training-evidence",children:[e.jsx("summary",{children:"Evidence and recommendation"}),e.jsx("p",{children:t.recommendation.reasons.join(" ")}),t.recommendation.blockers.map(m=>e.jsx("p",{className:"training-draft-warning",children:m},m)),e.jsx("ul",{children:t.evidence.map(m=>e.jsxs("li",{children:[e.jsx("strong",{children:m.kind.replaceAll("_"," ")})," — ",m.summary," (",Pt(m.confidence),")"]},m.id))})]}),e.jsxs("div",{className:"training-inline-actions",children:[e.jsx("button",{className:"training-button",type:"button",disabled:!!s.busyAction,onClick:()=>{d()},children:"Create plan"}),e.jsx("button",{className:"training-text-button",type:"button",onClick:()=>{s.actions.patchCandidate(t.id,{status:"rejected"})},children:"Reject"}),e.jsx("button",{className:"training-text-button",type:"button",onClick:()=>{s.actions.patchCandidate(t.id,{status:"dismissed"})},children:"Dismiss"})]}),h.length?e.jsxs("div",{className:"training-merge-row",children:[e.jsxs("select",{"aria-label":`Merge ${t.title} into`,value:o,onChange:m=>u(m.target.value),children:[e.jsx("option",{value:"",children:"Merge into…"}),h.map(m=>e.jsx("option",{value:m.id,children:m.title},m.id))]}),e.jsx("button",{className:"training-text-button",type:"button",disabled:!o,onClick:()=>{s.actions.patchCandidate(t.id,{mergeIntoId:o})},children:"Merge"})]}):null]})}function Pt(t){return`${Math.round(t*100)}%`}const Cl=10,wl=new Date(0).toISOString();function Il({insights:t,suggestionsView:n,training:s,onSuggestionsViewChange:a,onPlanStarted:i}){return e.jsxs("section",{className:"labs-suggestions-page","aria-label":"Suggestions",children:[e.jsxs("div",{className:"labs-subtabs",role:"tablist","aria-label":"Suggestion types",children:[e.jsxs("button",{"aria-selected":n==="observations",className:n==="observations"?"active":void 0,role:"tab",type:"button",onClick:()=>a("observations"),children:["Observations"," ",e.jsx("span",{children:t.items.filter(r=>r.status==="active").length})]}),e.jsxs("button",{"aria-selected":n==="suggestions",className:n==="suggestions"?"active":void 0,role:"tab",type:"button",onClick:()=>a("suggestions"),children:["AI suggestions"," ",e.jsx("span",{children:s.training.payload?.candidates.length??0})]})]}),e.jsx("div",{className:"labs-suggestions-body",children:n==="observations"?e.jsx(ul,{...t}):e.jsx(kl,{training:s.training,defaultModel:s.defaultModel,preferences:s.preferences,reasoningEffort:s.reasoningEffort,onPlanStarted:i})})]})}function Rl({frontierBaselineRuns:t,items:n,loading:s,progressionByKey:a,showType:i,onSelect:r,onUseAgent:l,onUseModel:o,onUseSkill:u}){if(s)return e.jsxs("div",{className:"labs-table-empty",children:[e.jsx(we,{className:"spin",size:16})," Loading workproducts…"]});if(!n.length)return e.jsx("div",{className:"labs-table-empty",children:"No workproducts match this view."});const h=new Map(t.map(d=>[d.id,d]));return e.jsx("div",{className:"training-table-wrap",children:e.jsxs("table",{className:`training-data-table labs-workproducts-table${i?"":" models-only"}`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[i?e.jsx("th",{children:"Type"}):null,e.jsx("th",{children:"Name"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Training"}),e.jsx("th",{children:"Evals"}),e.jsx("th",{children:"Updated"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Open"})})]})}),e.jsx("tbody",{children:n.map(d=>{const m=a.get(d.key),x=d.frontierBaselineRunId?h.get(d.frontierBaselineRunId)??null:null;return e.jsxs("tr",{onClick:()=>r(d.key),children:[i?e.jsx("td",{className:"labs-workproduct-type",children:El(d.kind)}):null,e.jsx("td",{children:e.jsxs("button",{className:x?"labs-workproduct-link labs-training-run-name":"labs-workproduct-link",type:"button",onClick:()=>r(d.key),children:[e.jsx("strong",{children:d.name}),e.jsx("span",{children:d.description}),x?e.jsx(xr,{run:x,showOutcomes:!1}):null]})}),e.jsx("td",{children:e.jsx(ve,{label:m?.statusLabel??d.status,value:m?.statusValue??d.status})}),e.jsx("td",{className:"labs-workproduct-training",children:Ml(d)}),e.jsx("td",{className:"labs-workproduct-evals",children:_l(d)}),e.jsx("td",{className:"labs-workproduct-updated",children:d.updatedAt===wl?"—":Ps(d.updatedAt)}),e.jsx("td",{children:e.jsxs("div",{className:"labs-workproduct-actions",children:[d.kind==="skill"?e.jsx("button",{className:"settings-secondary compact labs-workproduct-use",type:"button",onClick:j=>{j.stopPropagation(),u(d.name)},children:"Use"}):d.kind==="agent"&&d.useActionId?e.jsx("button",{className:"settings-secondary compact labs-workproduct-use",type:"button",onClick:j=>{j.stopPropagation(),l(d.useActionId,d.name)},children:"Use"}):d.kind==="model"&&d.enabled!==null?e.jsx("button",{className:"settings-secondary compact labs-workproduct-use",type:"button",disabled:!d.enabled,title:d.enabled?"Start a bounded chat session with this model":"Chat is available after a version passes frozen evaluation",onClick:j=>{j.stopPropagation(),o(d.id)},children:"Chat"}):null,e.jsx(ms,{size:15})]})})]},d.key)})})]})})}function Al({items:t,loading:n,runs:s,state:a,onSelect:i,onUseModel:r}){return n?e.jsxs("div",{className:"labs-table-empty",children:[e.jsx(we,{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:"Active"}),e.jsx("th",{children:"Eval"}),e.jsx("th",{children:"Versions"}),e.jsx("th",{children:"Updated"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(l=>{const o=ht(l,s,a),u=o.find(d=>d.current)??null,h=o[0]??null;return e.jsxs("tr",{onClick:()=>i(l.key),children:[e.jsx("td",{children:e.jsxs("button",{className:"labs-workproduct-link",type:"button",onClick:()=>i(l.key),children:[e.jsx("strong",{children:l.name}),e.jsx("span",{children:l.description})]})}),e.jsx("td",{children:u?`Version ${u.number} · ${at(u.plan?.recipe.method)}`:"Not selected"}),e.jsx("td",{children:e.jsx(ve,{label:h?h.lineage.promotable?"Passed":h.lineage.frozenEvaluationArtifactId?"Failed":"Not run":"Not run",value:h?.lineage.promotable?"passed":h?.lineage.frozenEvaluationArtifactId?"failed":"not_run"})}),e.jsx("td",{children:o.length}),e.jsx("td",{children:Ps(l.updatedAt)}),e.jsx("td",{children:e.jsxs("div",{className:"labs-workproduct-actions",children:[e.jsx("button",{className:"settings-secondary compact labs-workproduct-use",disabled:!u,title:u?"Chat with the active Version":"Set a passing Version active before Chat",type:"button",onClick:d=>{d.stopPropagation(),r(l.id)},children:"Chat"}),e.jsx(ms,{size:15})]})})]},l.key)})})]})}):e.jsx("div",{className:"labs-table-empty",children:"No Models yet."})}function Ml(t){if(t.kind!=="model")return e.jsx("span",{className:"labs-workproduct-na",title:"Training not applicable",children:"—"});const n=`${t.trainingRunCount} training ${t.trainingRunCount===1?"run":"runs"}`;return e.jsxs("span",{className:`labs-workproduct-indicator${t.trainingRunCount>0?" active":""}`,title:n,children:[e.jsx(hs,{"aria-hidden":"true",size:15}),e.jsx("strong",{"aria-hidden":"true",children:t.trainingRunCount}),e.jsx("span",{className:"sr-only",children:n})]})}function _l(t){const n=t.evaluationStatus==="passed"?{icon:e.jsx(ps,{"aria-hidden":"true",size:16}),label:"Evals passed",tone:"positive"}:t.evaluationStatus==="failed"?{icon:e.jsx(pa,{"aria-hidden":"true",size:16}),label:"Evals failed",tone:"negative"}:{icon:e.jsx(ma,{"aria-hidden":"true",size:16}),label:"Evals not run",tone:"neutral"};return e.jsxs("span",{className:`labs-workproduct-indicator ${n.tone}`,title:n.label,children:[n.icon,e.jsx("span",{className:"sr-only",children:n.label})]})}function Ps(t){const n=new Date(t),s=new Date;return n.toDateString()===s.toDateString()?new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"}).format(n):new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",...n.getFullYear()===s.getFullYear()?{}:{year:"2-digit"}}).format(n)}function Tl({page:t,total:n,onChange:s}){const a=Math.max(1,Math.ceil(n/Cl));return a<=1?null:e.jsxs("nav",{className:"labs-pagination","aria-label":"Pagination",children:[e.jsx("button",{type:"button",disabled:t<=1,onClick:()=>s(t-1),children:"Previous"}),e.jsxs("span",{children:[t," of ",a]}),e.jsx("button",{type:"button",disabled:t>=a,onClick:()=>s(t+1),children:"Next"})]})}async function is(t,n,s,a){if(n.onLaunchHandled(n.launchRequest?.id??0),!t.materializedTasksetId)return;n.onSelectedTasksetIdChange(t.materializedTasksetId),n.onDetailTasksetIdChange(t.materializedTasksetId);const r=(await s())?.find(l=>l.id===t.request.createImproveRunId);a(Ue("model",r?.target.kind==="model"?r.target.id??r.id:t.materializedTasksetId))}function rs(t,n){return t.request.objective?.trim()||t.proposal?.objective.trim()||t.proposal?.name.trim()||n}function El(t){return t&&`${t[0].toUpperCase()}${t.slice(1).replaceAll("_"," ")}`}function Pl(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("|"):""}const ls=10;function Wl({closeDetailKind:t,closeDetailRequestId:n,insights:s,onAnswerQuestion:a,onApplyCandidate:i,onApprove:r,onCancel:l,candidateReview:o,onCandidateReviewChange:u,onCreateAgent:h,onDetailOpenChange:d,onImproveAgent:m,onNewModel:x,onOpenPullRequest:j,onOpenCandidateFiles:N,onOpenRunConversation:S,onPause:v,onReconcilePullRequest:y,onRejectCandidate:g,onResume:k,onRevise:C,onUseAgent:M,openSuggestionsRequestId:R,profileView:w,training:p}){const B=w.payload?.profile??null,D=B?.activeProfile??"default",$=ui({connection:w.connection,profileId:D});Qe($.error),Qe(p.training.error);const Y=c.useMemo(()=>Pl(p.training.payload),[p.training.payload]),ne=c.useMemo(()=>$.runs.filter(I=>I.target.kind==="agent"&&["ready_local","released","published_hosted"].includes(I.state)).map(I=>`${I.id}:${I.revision}:${I.state}`).sort().join("|"),[$.runs]),[_,E]=c.useState("workproducts"),[T,z]=c.useState("observations"),[U,je]=c.useState(1),[ue,V]=c.useState(null),[ie,he]=c.useState(null),[Z,ee]=c.useState(!1),[me,O]=c.useState(null),[pe,le]=c.useState(null),[de,ye]=c.useState(null),[W,Ne]=c.useState(null),[q,ge]=c.useState(null),Q=c.useMemo(()=>js({profile:B,training:p.training.payload,runs:$.runs}),[$.runs,B,p.training.payload]),Re=c.useMemo(()=>{const I=new Map((p.training.payload?.tasksets??[]).map(F=>[F.id,F]));return new Map(Q.map(F=>[F.key,As({workproduct:F,runs:vs(F,$.runs),taskset:F.tasksetId?I.get(F.tasksetId)??null:null,training:p.training.payload})]))},[$.runs,p.training.payload,Q]),be=c.useMemo(()=>Q.filter(I=>I.kind!=="model"),[Q]),Ae=c.useMemo(()=>Q.filter(I=>I.kind==="model"),[Q]),fe=Q.find(I=>I.key===ue)??null,A=s.items.filter(I=>I.status==="active").length+(p.training.payload?.candidates.length??0);c.useEffect(()=>{Y&&$.refresh()},[$.refresh,Y]),c.useEffect(()=>{if(!ne||!w.connection)return;let I=!1;return ut.bootstrap(w.connection).then(F=>{I||w.onPayload(F)}).catch(F=>{I||w.onError(F instanceof Error?F.message:String(F))}),()=>{I=!0}},[ne,w.connection,w.onError,w.onPayload]),c.useEffect(()=>{R<=0||(z("observations"),E("suggestions"))},[R]),c.useEffect(()=>{ue&&!Q.some(I=>I.key===ue)&&V(null)},[ue,Q]),c.useEffect(()=>{if(!(n<=0)){if(V(null),t==="dataset"){he(null),E("datasets");return}E("workproducts")}},[t,n]),c.useEffect(()=>{if(_==="datasets"){d(ie?{kind:"dataset",kindLabel:"Datasets",workproductLabel:p.training.payload?.tasksets.find(I=>I.id===ie)?.name??"Dataset",sectionLabels:[]}:null);return}if(_!=="workproducts"){d(null);return}fe||d(null)},[_,d,fe,ie,p.training.payload?.tasksets]),c.useEffect(()=>()=>d(null),[d]);function J(I){V(null),je(1),he(null),E(I)}function se(I,F=""){const X=Q.find(oe=>oe.kind==="agent"&&oe.id===I);ge({agentId:I,agentName:X?.name??I,initialObjective:F.trim()})}function K(I){const F=Q.find(ke=>ke.kind==="model"&&ke.id===I);if(!F)return;const X=ht(F,$.runs,p.training.payload),oe=X.find(ke=>ke.current)??X.find(ke=>ke.lineage.promotable)??null;if(!oe?.taskset)return;if(p.training.payload?.jobs.find(ke=>ke.id===oe.lineage.jobId)?.destinationId==="fireworks"){Ne(oe.lineage.id);return}p.onChatWithModel(Ot({modelId:oe.lineage.id,taskset:oe.taskset}))}return e.jsxs(Lr,{activeTab:_,showHeader:!fe&&!ie,suggestionCount:A,onTabChange:J,onCreateAgent:()=>ee(!0),onCreateDataset:()=>O("source"),onCreateModel:x,children:[_==="suggestions"?e.jsx(Il,{insights:s,suggestionsView:T,training:p,onSuggestionsViewChange:z,onPlanStarted:()=>E("workproducts")}):_==="datasets"?e.jsx(ll,{runs:$.runs,selectedId:ie,state:p.training.payload,training:p.training,onToast:(I,F)=>w.onToast?.(I,F)??0,onSelectedIdChange:he,onCreate:()=>O("source"),onOpenFiles:I=>{p.onSelectedTasksetIdChange(I),p.onOpenTasksetFiles()}}):fe?e.jsx(Dr,{connection:w.connection,profile:B,runs:$.runs,training:p.training,workproduct:fe,onAnswerQuestion:a,onApplyCandidate:i,onApprove:r,onCancel:l,candidateReview:o,onCandidateReviewChange:u,onChatWithModel:p.onChatWithModel,onOpenPullRequest:j,onOpenCandidateFiles:N,onOpenConversation:S,onLocationChange:d,onRenameAgent:()=>le({id:fe.id,name:fe.name}),onOpenDataset:I=>{V(null),he(I),E("datasets")},onOpenProviderSettings:p.onOpenProviderSettings,onPause:v,onReconcilePullRequest:y,onRejectCandidate:g,onResume:k,onRevise:C,onStartAgentChange:(I,F)=>se(I,F??""),onToast:p.onToast}):e.jsxs("div",{className:"labs-flat-body",children:[_==="workproducts"?e.jsx("div",{className:"labs-home-profile-controls",children:e.jsx(Ca,{...w,section:"controls"})}):null,e.jsx(Rl,{frontierBaselineRuns:p.training.payload?.frontierBaselineRuns??[],loading:$.loading&&!Q.length,items:be.slice((U-1)*ls,U*ls),progressionByKey:Re,showType:!0,onSelect:V,onUseAgent:M,onUseModel:K,onUseSkill:I=>w.onSkillCommand?.(`$${I} `)}),e.jsx(Tl,{page:U,total:be.length,onChange:je}),_==="workproducts"?e.jsxs("section",{className:"labs-home-models",children:[e.jsx("div",{className:"labs-section-heading",children:e.jsx("h2",{children:"Models"})}),e.jsx(Al,{loading:!1,items:Ae.slice(0,10),runs:$.runs,state:p.training.payload,onSelect:V,onUseModel:K})]}):null]}),p.launchRequest&&p.training.payload?e.jsx(yt,{defaultModel:p.defaultModel,initialObjective:p.launchRequest.objective,initialSessionIds:p.launchRequest.initialSessionIds??[],localProjects:p.localProjects??[],onClose:()=>p.onLaunchHandled(p.launchRequest.id),onOpenComputeSettings:p.onOpenComputeSettings,onModelCreatedFromTaskset:async(I,F)=>{p.onLaunchHandled(p.launchRequest.id),p.onSelectedTasksetIdChange(I.id),p.onDetailTasksetIdChange(I.id),V(Ue("model",F.target.id??F.id)),E("workproducts"),await $.refresh()},onTasksetCreated:async I=>{await is(I,p,$.refresh,V),E("workproducts")},preferences:p.preferences,providerSettings:p.providerSettings,reasoningEffort:p.reasoningEffort,sessions:p.sessions,sources:p.training.payload.sources,training:p.training}):null,Z?e.jsx(yt,{defaultModel:p.defaultModel,initialObjective:null,localProjects:p.localProjects??[],onClose:()=>ee(!1),onAgentPromptSubmitted:async({analysisModel:I,objective:F})=>{const X=await h(F,null,I);await $.refresh(),E("workproducts"),V(Ue("agent",X.target.id??X.id)),ee(!1)},onOpenComputeSettings:p.onOpenComputeSettings,onTasksetCreated:async I=>{const F=rs(I,"Create a useful Agent from the approved Taskset."),X=await h(F,I.request.createImproveRunId,I.request.analysisModel);await $.refresh(),E("workproducts"),V(Ue("agent",X.target.id??X.id)),ee(!1)},preferences:p.preferences,providerSettings:p.providerSettings,reasoningEffort:p.reasoningEffort,sessions:p.sessions,sources:p.training.payload?.sources??[],targetIntent:{kind:"agent",id:null,displayName:null,operation:"create"},training:p.training}):null,me==="source"?e.jsx(ni,{onClose:()=>O(null),onSelect:O}):null,me==="build"?e.jsx(yt,{datasetBuildMode:!0,defaultModel:p.defaultModel,initialObjective:null,localProjects:p.localProjects??[],onBackToDatasetSources:()=>O("source"),onClose:()=>O(null),onOpenComputeSettings:p.onOpenComputeSettings,onTasksetCreated:async I=>{O(null),V(null),E("datasets"),he(I.materializedTasksetId),await $.refresh()},preferences:p.preferences,providerSettings:p.providerSettings,reasoningEffort:p.reasoningEffort,resourceIntent:"dataset",sessions:p.sessions,sources:p.training.payload?.sources??[],targetIntent:{kind:null,id:null,displayName:null,operation:"create"},training:p.training}):null,me==="huggingface"?e.jsx(ii,{onBack:()=>O("source"),onClose:()=>O(null),onImported:async I=>{O(null),V(null),E("datasets"),he(I),await p.training.refresh()},onOpenDatasetStorageSettings:()=>{O(null),p.onOpenDatasetStorageSettings()},training:p.training}):null,q?e.jsx(yt,{defaultModel:p.defaultModel,initialObjective:q.initialObjective,localProjects:p.localProjects??[],onClose:()=>ge(null),onAgentPromptSubmitted:async({analysisModel:I,objective:F})=>{await m(q.agentId,F,q.agentName,null,I),await $.refresh(),E("workproducts"),V(Ue("agent",q.agentId)),ge(null)},onOpenComputeSettings:p.onOpenComputeSettings,onTasksetCreated:async I=>{const F=rs(I,q.initialObjective);await m(q.agentId,F,q.agentName,I.request.createImproveRunId,I.request.analysisModel),await $.refresh(),E("workproducts"),V(Ue("agent",q.agentId)),ge(null)},preferences:p.preferences,providerSettings:p.providerSettings,reasoningEffort:p.reasoningEffort,sessions:p.sessions,sources:p.training.payload?.sources??[],targetIntent:{kind:"agent",id:q.agentId,displayName:q.agentName,operation:"improve"},training:p.training}):null,de?e.jsx(yt,{defaultModel:p.defaultModel,initialCreation:de,initialObjective:de.request.objective,localProjects:p.localProjects??[],onClose:()=>ye(null),onOpenComputeSettings:p.onOpenComputeSettings,onTasksetCreated:async I=>{await is(I,p,$.refresh,V),E("workproducts"),ye(null)},preferences:p.preferences,providerSettings:p.providerSettings,reasoningEffort:p.reasoningEffort,sessions:p.sessions,sources:p.training.payload?.sources??[],targetIntent:de.request.targetIntent,training:p.training}):null,W?(()=>{const I=p.training.payload?.models.find(X=>X.id===W),F=p.training.payload?.tasksets.find(X=>X.id===I?.tasksetId);return!I||!F?null:e.jsx(xs,{lineage:I,taskset:F,training:p.training,onChat:p.onChatWithModel,onClose:()=>Ne(null)})})():null,pe?e.jsx(Br,{agentId:pe.id,currentName:pe.name,onClose:()=>le(null),onRename:async I=>{if(!w.connection)throw new Error("Connect OpenPond before renaming an agent.");w.onError(null),await ut.profileAgentRename(w.connection,pe.id,{name:I}),w.onPayload(await ut.bootstrap(w.connection)),w.onToast?.(`Renamed agent to ${I}.`,"success")}}):null]})}export{Wl as LabsRoute};