openpond 0.0.38 → 0.0.39

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 (212) hide show
  1. package/README.md +3 -4
  2. package/dist/api/core.d.ts +6 -0
  3. package/dist/api/vercel-protection.d.ts +1 -0
  4. package/dist/chunks/{app-layer-DPUJRNO2.js → app-layer-LTBWNA2F.js} +32 -10
  5. package/dist/chunks/app-server-runtime-VYYJ2AWX.js +18 -0
  6. package/dist/chunks/{apps-AKBI6AS7.js → apps-CZAJBGE3.js} +6 -4
  7. package/dist/chunks/{chunk-LZZM3IHS.js → chunk-2SF6HLT7.js} +5899 -5939
  8. package/dist/chunks/{chunk-XCATKTK3.js → chunk-3CDPPVLE.js} +108 -66
  9. package/dist/chunks/{chunk-JWF37O5E.js → chunk-3HW6OSHP.js} +1 -3
  10. package/dist/chunks/{chunk-43YI36NA.js → chunk-3KLQ52B2.js} +228 -5
  11. package/dist/chunks/chunk-4HIWFIMN.js +37172 -0
  12. package/dist/chunks/{chunk-AHPQTEIJ.js → chunk-4N6E3OVF.js} +4 -4
  13. package/dist/chunks/{chunk-YTJL6XPU.js → chunk-6V7MJVRO.js} +56 -11
  14. package/dist/chunks/{chunk-QRM7XMAO.js → chunk-BQQZNGI6.js} +152 -161
  15. package/dist/chunks/chunk-DBHSOTYZ.js +1552 -0
  16. package/dist/chunks/{chunk-275WCETC.js → chunk-FCVVOMIP.js} +145 -5
  17. package/dist/chunks/{chunk-GB6VUZUA.js → chunk-JIEUB6OS.js} +1 -1
  18. package/dist/chunks/{chunk-HS2AGRDV.js → chunk-JJPAMKXZ.js} +1 -1
  19. package/dist/chunks/{chunk-GDZYDLEL.js → chunk-JRROTGQT.js} +1 -110
  20. package/dist/chunks/chunk-KHNHUA2H.js +1737 -0
  21. package/dist/chunks/{chunk-AHNFNWUN.js → chunk-L6XH4ZGZ.js} +1 -1
  22. package/dist/chunks/chunk-M2NXTLH2.js +4054 -0
  23. package/dist/chunks/{chunk-SLMP353Q.js → chunk-MIZHCABO.js} +2 -195
  24. package/dist/chunks/chunk-SMNFI2FU.js +113 -0
  25. package/dist/chunks/chunk-VCVQLECH.js +675 -0
  26. package/dist/chunks/{chunk-V35STJF4.js → chunk-ZJBJQCQZ.js} +179 -52
  27. package/dist/chunks/{cli-7BKDWFNU.js → cli-JS76LCW2.js} +9 -5
  28. package/dist/chunks/{core-commands-YN4RMWA3.js → core-commands-4MRJQZJV.js} +7 -5
  29. package/dist/chunks/{harness-BHQRMXJR.js → desktop-test-RNMWLOVU.js} +15 -14
  30. package/dist/chunks/{chunk-XERQHYBO.js → extension-GDRW22N3.js} +5868 -3580
  31. package/dist/chunks/{help-VREQNA4I.js → help-LWNREJ7U.js} +1 -1
  32. package/dist/chunks/{opchat-D63YTNSX.js → opchat-2K2JIGK3.js} +9 -10
  33. package/dist/chunks/{organizations-I46KG7TC.js → organizations-Z5HVD2E7.js} +11 -9
  34. package/dist/chunks/{profile-WKZJHEPG.js → profile-QNECVVGN.js} +12 -38
  35. package/dist/chunks/{project-agent-ZUC3YMCT.js → project-agent-W3V75WBR.js} +9 -411
  36. package/dist/chunks/{sandbox-command-AAOPFTI5.js → sandbox-command-X3FO74NX.js} +7 -5
  37. package/dist/chunks/{sandbox-template-GKNVR4C5.js → sandbox-template-5B4T4BGU.js} +8 -6
  38. package/dist/chunks/{src-RPW5TOPI.js → src-ESAILPUH.js} +32 -30
  39. package/dist/chunks/src-IC5RX4L6.js +63517 -0
  40. package/dist/chunks/{teams-bot-PSL3ZO6Z.js → teams-bot-NTQ6VFFL.js} +6 -4
  41. package/dist/chunks/training-BR5A7SPU.js +320 -0
  42. package/dist/chunks/{workspaces-BPXC2DHT.js → workspaces-XC3QBD2Y.js} +2 -2
  43. package/dist/cli.js +24 -12
  44. package/dist/config.d.ts +9 -3
  45. package/dist/index.js +1300 -1045
  46. package/dist/profile/local-profile-types.d.ts +16 -0
  47. package/dist/profile/local-profile.d.ts +50 -4
  48. package/dist/sandbox/client-handles.d.ts +33 -46
  49. package/dist/sandbox/client.d.ts +4 -26
  50. package/dist/sandbox/sandbox-instance-client.d.ts +5 -5
  51. package/dist/sandbox/types/client.d.ts +1 -2
  52. package/dist/sandbox/types/core.d.ts +0 -1
  53. package/dist/sandbox/types/org-project-agent.d.ts +3 -89
  54. package/dist/sandbox/types/record.d.ts +1 -2
  55. package/dist/sandbox/types/runtime-profiles.d.ts +2 -2
  56. package/dist/sandbox-template/manifest.d.ts +1 -1
  57. package/dist/skills/openpond-agent-authoring/SKILL.md +40 -0
  58. package/dist/skills/openpond-agent-authoring/references/action-and-chat-design.md +13 -0
  59. package/dist/skills/openpond-agent-authoring/references/integrations-and-setup.md +13 -0
  60. package/dist/skills/openpond-agent-authoring/references/profile-layout.md +29 -0
  61. package/dist/skills/openpond-agent-authoring/references/validation-and-repair.md +14 -0
  62. package/dist/skills/openpond-desktop-harness/SKILL.md +1 -1
  63. package/dist/skills/openpond-skill-authoring/SKILL.md +44 -0
  64. package/dist/skills/openpond-skill-authoring/references/copying-and-adaptation.md +16 -0
  65. package/dist/skills/openpond-skill-authoring/references/skill-package-layout.md +38 -0
  66. package/dist/skills/openpond-skill-authoring/references/validation-and-repair.md +24 -0
  67. package/dist/skills/openpond-skill-authoring/scripts/validate-skill.mjs +102 -0
  68. package/dist/skills/openpond-taskset-authoring/SKILL.md +64 -22
  69. package/dist/skills/openpond-taskset-authoring/artifact.json +39 -0
  70. package/dist/skills/openpond-taskset-authoring/references/graders-and-rewards.md +3 -0
  71. package/dist/skills/openpond-taskset-authoring/references/method-selection.md +1 -1
  72. package/dist/skills/openpond-taskset-authoring/references/privacy-and-provenance.md +2 -0
  73. package/dist/skills/openpond-taskset-authoring/references/task-design.md +32 -0
  74. package/dist/web/assets/{AppDialog-DrwJb_wG.js → AppDialog-Bua3f-6v.js} +1 -1
  75. package/dist/web/assets/{AppsView-DPagLMsc.js → AppsView-DrJkHeSO.js} +1 -1
  76. package/dist/web/assets/BrowserSidebar-Bf-4Vozm.js +1 -0
  77. package/dist/web/assets/CommandMenu-DDZlGQiB.js +1 -0
  78. package/dist/web/assets/CommunityView-BtcCrba7.js +1 -0
  79. package/dist/web/assets/ComposerCreateImproveStrip-DOe5Otg6.js +1 -0
  80. package/dist/web/assets/GetStartedView-CG4z0Dtw.js +1 -0
  81. package/dist/web/assets/GetStartedView-yVmnGZPw.css +1 -0
  82. package/dist/web/assets/LabModelVersionDetailPage-BEkmSKuv.js +1 -0
  83. package/dist/web/assets/LabSkillSidebar-BIotN_RB.js +1 -0
  84. package/dist/web/assets/LabsRoute-CfOe0Zt5.js +3 -0
  85. package/dist/web/assets/LabsRoute-CoSPO4HR.css +1 -0
  86. package/dist/web/assets/MainChatThread-C0-l1mHt.js +2 -0
  87. package/dist/web/assets/MainPane-Bky_Rqcx.css +1 -0
  88. package/dist/web/assets/MainPane-aOVlVyRK.js +6 -0
  89. package/dist/web/assets/MarkdownText-D7DT1k1k.js +9 -0
  90. package/dist/web/assets/Messages-CBIXruA9.js +9 -0
  91. package/dist/web/assets/NativeSkillSidebar-C4t69Y7B.js +1 -0
  92. package/dist/web/assets/NewProjectDialog-Bat65tYD.js +1 -0
  93. package/dist/web/assets/OutputsPage-C58n39Db.js +1 -0
  94. package/dist/web/assets/RightChatPanelStack-Bp7nZxQ0.js +1 -0
  95. package/dist/web/assets/ScheduledWorkPage-BXP0j_c_.js +1 -0
  96. package/dist/web/assets/SettingsView-CtWK_aQ0.css +1 -0
  97. package/dist/web/assets/SettingsView-DOOfhO9a.js +6 -0
  98. package/dist/web/assets/TeamChatView-Cgxm-pKA.css +1 -0
  99. package/dist/web/assets/TeamChatView-De2wdqyY.js +3 -0
  100. package/dist/web/assets/{TerminalOverlay-BKl0p8pa.js → TerminalOverlay-BsuCH3NX.js} +1 -1
  101. package/dist/web/assets/TrainingCreationPanel-D2OFWyQ-.js +1 -0
  102. package/dist/web/assets/TrainingDraftPanel-DBpulXTz.js +1 -0
  103. package/dist/web/assets/{UsageSettingsSection-zDAwzTGl.js → UsageSettingsSection-DzMLUXAO.js} +37 -37
  104. package/dist/web/assets/WorkspaceDiffPanel-B7yIhjNF.js +14 -0
  105. package/dist/web/assets/WorkspaceEnvironmentMenu-B6jXM9xG.js +32 -0
  106. package/dist/web/assets/WorkspaceGitDialogs-CQ0fl9Qk.js +1 -0
  107. package/dist/web/assets/{WorkspaceMonacoEditor-DPGcG8fy.js → WorkspaceMonacoEditor-C2ctzITz.js} +3 -3
  108. package/dist/web/assets/arrow-up-right-ecwcx3xt.js +1 -0
  109. package/dist/web/assets/chevron-up-DP8PPfWd.js +1 -0
  110. package/dist/web/assets/circle-alert-envg1D6O.js +1 -0
  111. package/dist/web/assets/cloud-upload-5MGPLnaA.js +1 -0
  112. package/dist/web/assets/{cssMode-CKN9CcfG.js → cssMode-CFifcEfw.js} +1 -1
  113. package/dist/web/assets/folder-open-Dq3ZjeEP.js +1 -0
  114. package/dist/web/assets/folder-plus-EiZ5wbv_.js +1 -0
  115. package/dist/web/assets/git-branch-w29jmQ-X.js +1 -0
  116. package/dist/web/assets/{git-commit-horizontal-Bxi8YPep.js → git-commit-horizontal-CGZM0PZo.js} +1 -1
  117. package/dist/web/assets/{htmlMode-CeUcNhBZ.js → htmlMode-Ct1P-_lf.js} +1 -1
  118. package/dist/web/assets/index-ByIQyiUl.js +178 -0
  119. package/dist/web/assets/index-D4uCeiep.js +1 -0
  120. package/dist/web/assets/index-D9jTe16Q.css +1 -0
  121. package/dist/web/assets/info-Cd2HkIeb.js +1 -0
  122. package/dist/web/assets/{jsonMode-97z0Yz9u.js → jsonMode-BAUNCNAX.js} +1 -1
  123. package/dist/web/assets/{lspLanguageFeatures-D4Tp-JmI.js → lspLanguageFeatures-fucFYI1A.js} +1 -1
  124. package/dist/web/assets/monaco.contribution-Ce4v5kei.js +2 -0
  125. package/dist/web/assets/monaco.contribution-DLLMi4cB.js +2 -0
  126. package/dist/web/assets/monaco.contribution-g9QiIm1d.js +2 -0
  127. package/dist/web/assets/monaco.contribution-nG-5Cyjz.js +2 -0
  128. package/dist/web/assets/monitor-DgHCnCKl.js +1 -0
  129. package/dist/web/assets/{play-C-37dnR1.js → play-Be0XDHBu.js} +1 -1
  130. package/dist/web/assets/{python-CGpDXY7_.js → python-CEhEiPo7.js} +1 -1
  131. package/dist/web/assets/{refresh-cw-BAaaPCXl.js → refresh-cw-DH0KLbdD.js} +1 -1
  132. package/dist/web/assets/reply-D1TK2yV8.js +1 -0
  133. package/dist/web/assets/{save-Cvxs3XyC.js → save-C1MSeBnQ.js} +1 -1
  134. package/dist/web/assets/square-CemI-0g5.js +1 -0
  135. package/dist/web/assets/square-pen-CqfsvR_n.js +1 -0
  136. package/dist/web/assets/{toggleHighContrast-CD42jH4g.js → toggleHighContrast-DrdQN3Rl.js} +1 -1
  137. package/dist/web/assets/training-BQVNUTZA.css +1 -0
  138. package/dist/web/assets/training-model-data-B7-1Bxil.js +1 -0
  139. package/dist/web/assets/{tsMode-ZROIxEjv.js → tsMode-CKB5oOUU.js} +1 -1
  140. package/dist/web/assets/{upload-DvCSGERK.js → upload-t751LLqP.js} +1 -1
  141. package/dist/web/assets/useLocalAgentSchedules-CzC3wfIP.js +1 -0
  142. package/dist/web/assets/{wifi-off-BIb94PkS.js → wifi-off-CxTHH3JU.js} +1 -1
  143. package/dist/web/assets/{workers-oYqbrVYG.js → workers-CqYddzCd.js} +1 -1
  144. package/dist/web/assets/{yaml-WqBjNgOO.js → yaml-e5wBkc-C.js} +1 -1
  145. package/dist/web/index.html +2 -2
  146. package/docs/command-reference.md +75 -40
  147. package/package.json +3 -1
  148. package/dist/chunks/chunk-FWLOFUPU.js +0 -864
  149. package/dist/chunks/chunk-HLCTINEP.js +0 -224
  150. package/dist/chunks/chunk-MPGSHXGF.js +0 -3896
  151. package/dist/chunks/chunk-T4QXKU5Y.js +0 -1
  152. package/dist/chunks/chunk-XEJ7XXUQ.js +0 -1301
  153. package/dist/chunks/chunk-ZI4GDAUB.js +0 -3522
  154. package/dist/chunks/cli-2KBVNDRY.js +0 -23
  155. package/dist/chunks/extend-REGNTBK3.js +0 -89
  156. package/dist/chunks/extension-7K77DAVL.js +0 -121
  157. package/dist/chunks/fileFromPath-DHCRY3BD.js +0 -2151
  158. package/dist/chunks/src-MWDIK56B.js +0 -105881
  159. package/dist/web/assets/BrowserSidebar-DMn2V8RV.js +0 -1
  160. package/dist/web/assets/CloudWorkView-Cl_7mM3c.js +0 -1
  161. package/dist/web/assets/CloudWorkView-DNoPIlMj.css +0 -1
  162. package/dist/web/assets/CommandMenu-CHMQLez_.js +0 -1
  163. package/dist/web/assets/CommunityView-DcHVDUk0.js +0 -1
  164. package/dist/web/assets/ComposerCreateImproveStrip-BZ3Dgzmo.js +0 -1
  165. package/dist/web/assets/GetStartedView-DBLdduwr.css +0 -1
  166. package/dist/web/assets/GetStartedView-DTRotFqz.js +0 -1
  167. package/dist/web/assets/LabSkillSidebar-D-PqFe1T.js +0 -1
  168. package/dist/web/assets/LabsRoute-BrJkBNig.css +0 -1
  169. package/dist/web/assets/LabsRoute-Dew1BwK5.js +0 -3
  170. package/dist/web/assets/MainChatThread-BaPxxzrw.js +0 -2
  171. package/dist/web/assets/MakeAgentTutorialLearningPanel-CBsfnONQ.js +0 -2
  172. package/dist/web/assets/MarkdownText-DGLfAM_Z.js +0 -7
  173. package/dist/web/assets/Messages-CIX9uTjX.js +0 -10
  174. package/dist/web/assets/NativeSkillSidebar-AP_uHn6g.js +0 -1
  175. package/dist/web/assets/NewProjectDialog-C6lHkafU.js +0 -1
  176. package/dist/web/assets/PostTrainingLearningPanel-CZEgPc8O.js +0 -2
  177. package/dist/web/assets/PostTrainingStatusPill-CeEpwUDB.js +0 -1
  178. package/dist/web/assets/ProfileSettingsSection-Cg4tKO-C.css +0 -1
  179. package/dist/web/assets/ProfileSettingsSection-EumMLlEp.js +0 -1
  180. package/dist/web/assets/RightChatPanelStack-MXBcx3zO.js +0 -1
  181. package/dist/web/assets/SettingsView-Caljbns2.css +0 -1
  182. package/dist/web/assets/SettingsView-DyURG_Uh.js +0 -6
  183. package/dist/web/assets/TeamChatView-Bx44q3WV.css +0 -1
  184. package/dist/web/assets/TeamChatView-D3v6aqJ3.js +0 -3
  185. package/dist/web/assets/TrainingCreationPanel-CfZQTuT5.js +0 -1
  186. package/dist/web/assets/TrainingDraftPanel-DslRPSDW.js +0 -1
  187. package/dist/web/assets/WorkspaceDiffPanel-C_MZPPlL.js +0 -14
  188. package/dist/web/assets/WorkspaceEnvironmentMenu-BUAnn80j.js +0 -32
  189. package/dist/web/assets/WorkspaceGitDialogs-Drbf4ujA.js +0 -1
  190. package/dist/web/assets/activity-Dnr3jqb3.js +0 -1
  191. package/dist/web/assets/boxes-BinC8UPn.js +0 -1
  192. package/dist/web/assets/chevron-up-Bjp_-_Cb.js +0 -1
  193. package/dist/web/assets/circle-x-ubnvEYuE.js +0 -1
  194. package/dist/web/assets/copy-B_ZCCUMz.js +0 -1
  195. package/dist/web/assets/create-pipeline-request-D6uLUxe9.js +0 -4
  196. package/dist/web/assets/file-8HAMlTmQ.js +0 -1
  197. package/dist/web/assets/git-branch-l2Zih3Bv.js +0 -1
  198. package/dist/web/assets/index-BMFyOFRU.css +0 -1
  199. package/dist/web/assets/index-BzwcDzbT.js +0 -1
  200. package/dist/web/assets/index-KoQSSt_f.js +0 -177
  201. package/dist/web/assets/info-JTbDQxHx.js +0 -1
  202. package/dist/web/assets/make-agent-tutorial-D6nBCgv-.js +0 -2
  203. package/dist/web/assets/monaco.contribution-B3j6oown.js +0 -2
  204. package/dist/web/assets/monaco.contribution-BXHxPPWL.js +0 -2
  205. package/dist/web/assets/monaco.contribution-C2P5zIzh.js +0 -2
  206. package/dist/web/assets/monaco.contribution-C8c6OtGi.js +0 -2
  207. package/dist/web/assets/monitor-kzHtxHnA.js +0 -1
  208. package/dist/web/assets/reply-9rehU13k.js +0 -1
  209. package/dist/web/assets/rotate-cw-C1Z_Xs23.js +0 -1
  210. package/dist/web/assets/training-BN8CALIc.css +0 -1
  211. package/dist/web/assets/training-model-data-BXUCzS0p.js +0 -1
  212. package/docs/agent-edit-check-status-json.md +0 -132
@@ -1,3 +0,0 @@
1
- import{j as e,S as cs,O as Me,k as vn,r as c,bo as Ft,z as Xs,A as Ys,a5 as Zs,bp as Mn,D as un,bq as ea,M as zt,a as hn,V as qt,X as Xe,br as us,u as Qe,bs as ta,a7 as na,bt as sa,ag as aa,E as ia,bu as Ut,n as st,bv as Yt,bw as ra,bx as la,by as oa,bz as da,w as yn,P as ca,bA as ua,Y as hs,W as ps,_ as ha,aD as pa,bB as ma,bC as Kt,T as ms,a2 as gs}from"./index-KoQSSt_f.js";import{P as ga}from"./ProfileSettingsSection-EumMLlEp.js";import{B as ht}from"./boxes-BinC8UPn.js";import{R as fs}from"./refresh-cw-BAaaPCXl.js";import{A as it}from"./AppDialog-DrwJb_wG.js";import{c as fa,e as at,g as xa,f as Ht,s as Nn,d as _n,b as Tn,j as xs}from"./training-model-data-BXUCzS0p.js";import{ComposerCreateImproveStrip as ba}from"./ComposerCreateImproveStrip-BZ3Dgzmo.js";/* empty css */import{C as ja,a as va}from"./circle-x-ubnvEYuE.js";import"./git-commit-horizontal-Bxi8YPep.js";import"./play-C-37dnR1.js";/* empty css */function ya(t,n){let s=null;for(const a of t)Na(a,n)&&(!s||Sa(a,s))&&(s=a);return s}function Na(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 Sa(t,n){const s=t.rftSignal?.passed===!0,a=n.rftSignal?.passed===!0;return s!==a?s:t.createdAt>n.createdAt}const Zt=8,En=24,ka=2;function Ca(t){const n=Ia(t);if(n.length){const i=En+n.reduce((l,o)=>l+Zt+jt(o.content),0),r=n.filter(l=>l.role==="assistant").map(l=>Zt+jt(l.content));return{renderedTokens:i,maximumAssistantTargetTokens:Math.max(0,...r),assistantTargetCount:r.length}}const s=Aa(t.input),a=Ma(t.expectedOutput);return{renderedTokens:En+jt(s)+jt(a),maximumAssistantTargetTokens:Zt+jt(a),assistantTargetCount:a?1:0}}function wa(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,Ca(l).renderedTokens),0);return i<=s?s:Math.min(a,2**Math.ceil(Math.log2(i)))}function Ia(t){const n=[...Pn(t.input.messages),...Pn(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(!Lt(r))continue;const l=r.role,o=r.content;if(l==="tool"){s.push({role:"user",content:Vt({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)!Lt(u)||!Lt(u.function)||(s.push({role:"assistant",content:Vt({arguments:Ra(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 Pn(t){return Array.isArray(t)?t:[]}function Ra(t){if(typeof t!="string")return{};try{return JSON.parse(t)}catch{return{malformed_arguments:t}}}function Vt(t){return JSON.stringify(pn(t))}function pn(t){return Array.isArray(t)?t.map(pn):Lt(t)?Object.fromEntries(Object.keys(t).sort().map(n=>[n,pn(t[n])])):t}function Aa(t){return typeof t.prompt=="string"?t.prompt:Vt(t)}function Ma(t){return t?typeof t.text=="string"?t.text:Vt(t):""}function jt(t){return Math.ceil(t.length/ka)}function Lt(t){return!!(t&&typeof t=="object"&&!Array.isArray(t))}function _a({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(ga,{section:t,payload:n,connection:s,onPayload:a,onError:i,onToast:r,onSkillCommand:l,overviewContent:o})})}function Ta({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 mn({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:p,searchIndexing:m,searchLoading:b,searchTotalChats:k,selectedEntries:w,selectedSessionIds:j,visibleSessions:v}){const N=v.length>0&&v.every(y=>j.has(y.sessionId)),S=v.filter(y=>!j.has(y.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(cs,{size:14}),e.jsx("input",{value:u,onChange:y=>i(y.target.value),placeholder:"Search chats"})]}),e.jsx("button",{className:"training-text-button",type:"button",disabled:!v.length,onClick:l,children:N?"Clear visible":"Select visible"})]}),e.jsxs("div",{className:"training-source-result-count",children:[e.jsx("span",{children:o?`${w.length} selected chat${w.length===1?"":"s"}`:`Showing ${v.length} of ${s} matching chats`}),!o&&m?e.jsxs("span",{children:["Indexing messages ",p," of ",k]}):null]}),e.jsxs("div",{className:"training-source-options",onScroll:y=>{const M=y.currentTarget;d&&!b&&M.scrollHeight-M.scrollTop-M.clientHeight<72&&a()},children:[w.length?e.jsx("div",{className:"training-selected-chat-group",children:w.map(y=>e.jsx(Dn,{checked:!0,entry:y,estimatesBySessionId:n,onToggleSession:r,showSnippet:o||!!u.trim()},y.sessionId))}):null,o?null:S.map(y=>e.jsx(Dn,{checked:!1,entry:y,estimatesBySessionId:n,onToggleSession:r,showSnippet:!!u.trim()},y.sessionId)),!o&&b?e.jsxs("div",{className:"training-chat-search-state",children:[e.jsx(Me,{className:"spin",size:15}),e.jsx("span",{children:v.length?"Loading more chats…":"Searching chats…"})]}):null,!o&&h?e.jsx("p",{className:"training-empty",children:"Chat search is unavailable. Try again."}):null,!o&&!b&&!h&&!v.length?e.jsx("p",{className:"training-empty",children:m?"No matches yet. Message indexing is still running.":"No completed chats match this search."}):null]})]})}function Dn({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(Ea,{estimate:s[n.sessionId]})]})]})]})}function Ea({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 Pa({config:t,estimatesBySessionId:n,estimate:s,matchingSessionCount:a,onCancel:i,onConfigChange:r,onLoadMore:l,onScan:o,onSearchChange:u,onToggleSession:h,onToggleVisible:d,run:p,scanning:m,search:b,searchError:k,searchHasMore:w,searchIndexedChats:j,searchIndexing:v,searchLoading:N,searchTotalChats:S,selectedEntries:y,selectedSessionIds:M,targetLabel:E,visibleSessions:$}){const C=M.size,x=s.measuredChats===C,D=Da(E);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(mn,{disabled:m,estimatesBySessionId:n,matchingSessionCount:a,onLoadMore:l,onSearchChange:u,onToggleSession:h,onToggleVisible:d,search:b,searchError:k,searchHasMore:w,searchIndexedChats:j,searchIndexing:v,searchLoading:N,searchTotalChats:S,selectedEntries:y,selectedSessionIds:M,visibleSessions:$}),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:ae=>r({...t,observationWindowDays:Number(ae.target.value)})})," days"]}),e.jsxs("label",{children:["Minimum recurrence ",e.jsx("input",{type:"number",min:2,max:100,value:t.minimumRecurrence,onChange:ae=>r({...t,minimumRecurrence:Number(ae.target.value)})})]})]})]}),p&&["queued","running","cancelling"].includes(p.status)?e.jsxs("div",{className:"training-miner-progress",role:"status",children:[e.jsxs("div",{children:[e.jsx("strong",{children:$a(p)}),e.jsxs("span",{children:[p.progress.processedSources," of ",p.progress.totalSources||C," chats · ",p.progress.candidatesFound," candidates",p.progress.skippedSources?` · ${p.progress.skippedSources} skipped`:""]})]}),e.jsx("progress",{max:Math.max(1,p.progress.totalSources||C),value:p.progress.processedSources})]}):null,p?.status==="failed"?e.jsxs("p",{className:"training-empty",children:["Scan failed: ",p.error]}):null,p?.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:C===0?"Select one or more chats":x?e.jsxs(e.Fragment,{children:[e.jsxs("span",{children:[C," chat",C===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:[C," chat",C===1?"":"s"]}),e.jsx("span",{children:"Estimating…"})]})}),m?e.jsx("button",{className:"training-button secondary",type:"button",disabled:p?.status==="cancelling",onClick:i,children:p?.status==="cancelling"?"Cancelling…":"Cancel scan"}):null,e.jsxs("button",{className:"training-button",type:"button",disabled:m||C===0,onClick:o,children:[m?e.jsx(Me,{className:"spin",size:14}):null,m?D.scanningLabel:D.actionLabel]})]})]})}function Da(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 $a(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 Ba({busy:t,candidates:n,continueLabel:s="Continue",value:a,onChange:i,onContinue:r,onManage:l,onScan:o}){const u=n.find(p=>p.selectionKey===a&&p.available)??null,h=Oa(n),d=a??n.find(p=>p.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:h.map(p=>e.jsxs("section",{className:"training-base-model-group",children:[e.jsxs("div",{className:"training-base-model-group-heading",children:[e.jsx("strong",{children:p.label}),e.jsx("small",{children:p.description})]}),e.jsx("div",{className:"training-method-options training-base-model-options",children:p.candidates.map(m=>e.jsx(La,{candidate:m,selected:m.selectionKey===a,autofocus:m.selectionKey===d,onChange:i,onContinue:r},m.selectionKey))})]},p.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:l,children:[e.jsx(ht,{size:14}),"Manage local models"]}),e.jsxs("button",{className:"training-button secondary",type:"button",disabled:t,onClick:o,children:[t?e.jsx(Me,{className:"spin",size:14}):e.jsx(fs,{size:14}),t?"Scanning":"Scan this machine"]}),e.jsx("button",{className:"training-button",type:"button",disabled:!u,onClick:r,children:s})]})]})}function La({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(ht,{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 ",Fa(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 Oa(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 Fa(t){return t.length>18?`${t.slice(0,18)}…`:t}function za({state:t,selectedTasksetId:n,busy:s,onChange:a,onContinue:i,onCreateDataset:r}){const l=Ua(t),o=l.find(u=>u.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:[l.map(u=>{const h=u.id===n;return e.jsxs("button",{"aria-checked":h,className:h?"selected":void 0,role:"radio",type:"button",onClick:()=>a(u.id),children:[e.jsx("span",{className:"training-existing-dataset-icon",children:e.jsx(ht,{size:17})}),e.jsxs("span",{children:[e.jsx("strong",{children:u.name}),e.jsx("small",{children:u.objective})]}),e.jsx(qa,{state:t,taskset:u}),e.jsx("span",{className:"training-choice-indicator","aria-hidden":"true"})]},u.id)}),l.length?null:e.jsxs("div",{className:"training-empty training-existing-dataset-empty",children:[e.jsx("strong",{children:"No reusable Datasets are ready yet."}),e.jsx("span",{children:"Create a Dataset, then return here to configure the Model."})]})]}),o?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.jsxs("div",{className:"training-dialog-actions",children:[r?e.jsxs("button",{className:"training-button secondary",type:"button",onClick:r,children:[e.jsx(vn,{size:14}),"Create new Dataset"]}):null,e.jsx("button",{className:"training-button",disabled:!o||s,type:"button",onClick:i,children:"Continue"})]})]})}function qa({state:t,taskset:n}){return e.jsxs("span",{className:"training-existing-dataset-splits",children:[e.jsxs("span",{children:[en(t,n,"train")," train"]}),e.jsxs("span",{children:[en(t,n,"validation")," validation"]}),e.jsxs("span",{children:[en(t,n,"frozen_eval")," frozen Eval"]})]})}function en(t,n,s){const a=n.datasetArtifact?t?.datasetArtifacts?.find(i=>i.tasksetId===n.id&&i.tasksetRevision===n.revision):null;return a?a.splitCounts[s]??0:n.tasks.filter(i=>i.split===s).length}function Ua(t){return t?t.tasksets.filter(n=>n.readiness?.ready).sort((n,s)=>s.updatedAt.localeCompare(n.updatedAt)||n.name.localeCompare(s.name)):[]}function Va({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(k=>o.has(k.id)),h=l.diagnosis.stableBehavior.length>0?l.diagnosis.stableBehavior:[l.diagnosis.summary],d=[...l.diagnosis.changingKnowledge,...l.diagnosis.requiredContext],p=l.proposedExamples.filter(k=>k.split!=="train"),m=t.request.targetIntent.operation==="improve"?"Improvement":"New Agent";async function b(){const k=i.trim();if(!k)return;const w=await a.actions.chatCreation(t.id,k);w&&(r(""),n(w))}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:m})]}),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(k=>e.jsx("li",{children:k},k))}),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(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:"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(k=>e.jsx("li",{children:k.title},k.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:[p.length," Eval scenario",p.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."}),p.length>0?e.jsx("ul",{children:p.map(k=>e.jsx("li",{children:k.inputPrompt},k.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:k=>r(k.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:()=>{b()},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 Ka({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,p=n==="dataset"?"dataset":Ha(t),m=new Map(s.map(S=>[S.id,S])),b=o.proposedExamples.filter(S=>S.split==="train"),k=o.proposedExamples.filter(S=>S.split!=="train"),w=t.materializedTasksetId?a.payload?.graderAuditReports.find(S=>S.tasksetId===t.materializedTasksetId)??null:null,j=o.trainingPath?.primaryMethod??o.proposedMethod;async function v(){const S=r.trim();if(!S)return;const y=await a.actions.chatCreation(t.id,S);y&&(l(""),i(y))}async function N(){if(!o)return;const S=Ft(u,o.name);if(!S||S===o.name)return;const y=await a.actions.renameCreation(t.id,S);y&&(h(y.proposal?.name??S),i(y))}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:p==="dataset"?"Dataset":"Model"}),e.jsxs("small",{children:[Ot(p)," · ",Ga(d.intervention)]})]}),e.jsxs("label",{className:"training-recommendation-name",children:[e.jsx("span",{children:p==="dataset"?"Dataset name":p==="model"?"Model name":"Workproduct name"}),e.jsx("input",{value:u,maxLength:100,onChange:S=>h(S.target.value),onBlur:()=>{N()},onKeyDown:S=>{S.key==="Enter"&&(S.preventDefault(),N())}}),e.jsx("small",{children:"Five words maximum. The full capability stays in the description."})]}),e.jsx("p",{className:"training-recommendation-objective",children:o.objective}),p==="model"&&t.request.preferredBaseModelId?e.jsxs("p",{className:"training-recommendation-base-model",children:[e.jsx("span",{children:"Preferred base"}),e.jsx("strong",{children:Ja(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:[b.length," train · ",k.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:b.length})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Evaluation examples"}),e.jsx("dd",{children:k.length})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Grader"}),e.jsx("dd",{children:w?w.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(S=>e.jsxs("article",{children:[e.jsxs("div",{children:[e.jsx("strong",{children:S.split==="frozen_eval"?"Evaluation":S.split==="train"?"Training":Ot(S.split)}),e.jsx("span",{children:Ot(S.origin.replaceAll("_"," "))})]}),e.jsx("p",{children:S.inputPrompt}),e.jsx("small",{children:m.get(S.sourceId)?.title??"Selected chat"})]},S.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(S=>S.label).join(", ")," · ",w?w.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(S=>e.jsx("li",{children:S},S))}):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:$n(j)})]}),e.jsxs("div",{className:"training-recommendation-detail-body training-path-review",children:[e.jsxs("div",{children:[e.jsxs("strong",{children:["Primary · ",$n(j)]}),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(S=>e.jsx("li",{children:S},S))}):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(S=>e.jsx("li",{children:S},S))})]}):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: ",Wa(j)]}),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(S=>e.jsx("li",{children:S},S))})]}):null,e.jsx("textarea",{value:r,onChange:S=>l(S.target.value),placeholder:"Explain what should change"}),e.jsx("button",{className:"training-button secondary",type:"button",disabled:!r.trim()||!!a.busyAction,onClick:()=>{v()},children:"Revise"})]})]})]})}function Ha(t){return t.request.targetIntent.kind?t.request.targetIntent.kind:t.proposal?.diagnosis.trainingEligible?"model":t.proposal?.diagnosis.intervention==="retrieval"?"configuration":"agent"}function Ga(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 Ot(t){return t&&`${t[0].toUpperCase()}${t.slice(1)}`}function $n(t){return t==="grpo"?"Reinforcement / RFT":t==="sft"?"Supervised / SFT":t==="preference"?"Preference":Ot(t.replaceAll("_"," "))}function Wa(t){return t==="grpo"?"GRPO optimizer":t==="sft"?"SFT":t.toUpperCase()}function Ja(t){return t.split("/").filter(Boolean).at(-1)??t}function Qa({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 p=s.state==="awaiting_materialization_approval",m=s.state==="recommendation_ready"&&s.proposal?.diagnosis.trainingEligible===!0,b=s.request.targetIntent.kind==="agent",k=n??(b?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:b?e.jsx(Va,{creation:s,onCreationChange:o,sources:h,training:d}):e.jsx(Ka,{creation:s,resourceIntent:u,sources:h,training:d,onCreationChange:o})}),e.jsxs("div",{className:"training-dialog-actions",children:[m?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:p?"Cancel":"Done"}),p?e.jsxs("button",{className:"training-button",type:"button",disabled:t,onClick:l,children:[t?e.jsx(Me,{className:"spin",size:14}):null,k]}):null]})]})}function Xa({authoringModel:t,authoringProvider:n,authoringReasoningEffort:s,busy:a,disclosurePending:i,estimatesBySessionId:r,matchingSessionCount:l,mode:o,objective:u,onObjectiveChange:h,onAnalyze:d,onApproveDisclosure:p,onAuthoringModelChange:m,onAuthoringProviderChange:b,onAuthoringReasoningEffortChange:k,onDeclineDisclosure:w,onDiscoverFromConversations:j,onSearchChange:v,onLoadMore:N,onReturnToRecommendation:S,onToggleSession:y,onToggleVisible:M,providerSettings:E,recommendationAvailable:$,search:C,searchError:x,searchHasMore:D,searchIndexedChats:ae,searchIndexing:P,searchLoading:F,searchTotalChats:G,selectedEntries:T,selectedEstimate:I,selectedSessionIds:O,targetLabel:z="model",targetOperation:ce="create",visibleSessions:ie}){const re=c.useMemo(()=>Xs(E,{enabledOnly:!0}),[E]),K=c.useMemo(()=>Ys(n,E),[n,E]),ue=Zs(n,t,E),Q=O.size,se=o==="from_prompt",le=o==="from_chats",Y=o==="manual"||se||le,ne=!se,ke=le?!!u.trim()&&Q>0:o==="manual"||se?!!u.trim():Q>0,he=I.measuredChats===Q,Ce=Q>0&&he&&I.estimatedTokens>Mn,H=z==="dataset",Le=z==="model",U=z==="agent",oe=U?K.map(V=>V.value.startsWith("openpond-scripted-")?{...V,label:"OpenPond Chat",shortLabel:"OpenPond Chat",description:void 0}:V):K,pe=oe.find(V=>V.value===t)?.label??t,fe=re.find(V=>V.value===n)?.label??n,xe=Le||H,_e=i&&U?"Review chats for the Agent plan":H||Le?"Build the Dataset":se?"Describe the Agent":"Add purpose and supporting chats",je=i&&U?"Approve the selected chat excerpts so OpenPond can turn their goals, decisions, and answer patterns into the first Agent plan.":o==="automated"?xe?"Confirm the chats that demonstrate this repeated workflow. Only selected chats seed the Dataset.":"Confirm the chats that support this repeated workflow.":H?"Define what this Dataset should contain and be useful for. Supporting chats are optional.":z==="agent"?le?"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=H?"Dataset purpose":z==="agent"?ce==="improve"?"Improvement goal":"Agent purpose":"Capability",J=H?"Describe what this Dataset should contain and be useful for":z==="agent"?"Describe the work this Agent should handle reliably":`Describe what this ${z} 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:_e}),e.jsx("p",{children:je})]}),Y?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:V=>h(V.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:[ne?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:Q?`${Q} 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(mn,{estimatesBySessionId:r,matchingSessionCount:l,onLoadMore:N,onSearchChange:v,onToggleSession:y,onToggleVisible:M,reviewOnly:i,search:C,searchError:x,searchHasMore:D,searchIndexedChats:ae,searchIndexing:P,searchLoading:F,searchTotalChats:G,selectedEntries:T,selectedSessionIds:O,visibleSessions:ie})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"training-dataset-source-heading",children:e.jsx("span",{children:xe?"Chat seeds":"Supporting chats"})}),e.jsx(mn,{estimatesBySessionId:r,matchingSessionCount:l,onLoadMore:N,onSearchChange:v,onToggleSession:y,onToggleVisible:M,reviewOnly:i,search:C,searchError:x,searchHasMore:D,searchIndexedChats:ae,searchIndexing:P,searchLoading:F,searchTotalChats:G,selectedEntries:T,selectedSessionIds:O,visibleSessions:ie})]}):null,e.jsxs("div",{className:"training-authoring-row",children:[e.jsx("span",{children:U?"Build with":"Analyzed with"}),e.jsxs("div",{className:"training-authoring-controls","aria-label":"Analysis model",children:[e.jsx(un,{compact:!0,placement:"bottom",label:"Provider",value:n,options:re,disabled:a,onChange:V=>b(V)}),ue?e.jsx(ea,{disabled:a,model:t,modelOptions:oe,placement:"bottom",reasoningEffort:s,onModelChange:m,onReasoningEffortChange:k}):e.jsx(un,{compact:!0,placement:"bottom",label:"Model",value:t,options:oe,disabled:a,onChange:m})]})]})]}),i?e.jsxs("div",{className:"training-disclosure-review",role:"status",children:[e.jsx("strong",{children:U?"How the chats build the plan":"Approve evidence disclosure"}),e.jsxs("p",{children:[e.jsxs("b",{children:[fe," / ",pe]})," will analyze excerpts from ",Q," selected chat",Q===1?"":"s",", ",I.messageCount," messages, and approximately ",ct(I.estimatedTokens)," tokens. ",U?"OpenPond uses the recurring goals, decisions, corrections, and answer patterns to draft the Agent's purpose, behavior, actions, outputs, and Evals.":""]})]}):null,Ce?e.jsxs("div",{className:"training-banner error",role:"alert",children:["Selected evidence is about ",ct(I.estimatedTokens)," tokens. Hosted Taskset authoring accepts up to ",ct(Mn)," 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:se?"No chats will be attached":Q===0?o==="manual"?"Supporting chats are optional":"Select at least one supporting chat":I.measuredChats===Q?e.jsxs(e.Fragment,{children:[e.jsxs("span",{children:[Q," chat",Q===1?"":"s"]}),e.jsxs("span",{children:[I.messageCount," messages"]}),e.jsxs("span",{children:["About ",ct(I.estimatedTokens)," tokens"]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{children:[Q," chat",Q===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:w,children:U?"Change chats":"Change evidence"}),e.jsxs("button",{className:"training-button",type:"button",disabled:a||!he||Ce,onClick:p,children:[a?e.jsx(Me,{className:"spin",size:14}):null,U?"Approve chats and build plan":"Approve and analyze"]})]}):$?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:S,children:"Return to recommendation"})]}):e.jsxs(e.Fragment,{children:[H&&o==="manual"&&j?e.jsx("button",{className:"training-button secondary",type:"button",disabled:a,onClick:j,children:"Discover from conversations"}):null,e.jsxs("button",{className:"training-button",type:"button",disabled:!ke||a||Ce||Q>0&&!he,onClick:d,children:[a?e.jsx(Me,{className:"spin",size:14}):null,Q>0?U?"Review chats for plan":"Review data access":U&&se?"Continue":xe?"Build Dataset":"Review setup"]})]})]})]})}function Ya({mode:t,allowExistingDataset:n=!1,operation:s="create",targetLabel:a="model",onChange:i,onContinue:r}){const l=a==="agent",o=Za(a),u=[{id:"automated",title:"Automatic",description:o.automaticDescription,icon:zt},{id:"manual",title:"Manual",description:o.manualDescription,icon:hn},{id:"existing_dataset",title:"Existing Dataset",description:"Create the Model from a reviewed Dataset without changing its tasks, graders, or held-out Evals.",icon:ht}],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:hn},{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:zt}]:n?u:u.filter(p=>p.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(p=>{const m=p.icon,b=p.id===t;return e.jsxs("button",{type:"button",role:"radio","aria-checked":b,className:b?"selected":"",onClick:()=>i(p.id),onDoubleClick:r,children:[e.jsx("span",{className:"training-start-mode-icon","aria-hidden":"true",children:e.jsx(m,{size:18})}),e.jsxs("span",{className:"training-start-mode-copy",children:[e.jsx("strong",{children:p.title}),e.jsx("small",{children:p.description})]}),e.jsx("span",{className:"training-choice-indicator","aria-hidden":"true"})]},p.id)})}),e.jsx("div",{className:"training-dialog-actions",children:e.jsx("button",{className:"training-button",type:"button",disabled:!t,onClick:r,children:"Continue"})})]})}function Za(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 ei=new Set(["cancelled","failed","ready"]);function tn(t){return!!(t&&!ei.has(t.state))}function ti({ariaLabel:t,backAriaLabel:n,children:s,presentation:a,showBack:i,step:r,title:l,onBack:o,onClose:u}){return a==="embedded"?e.jsxs("section",{className:"labs-dataset-build-editor","aria-label":t,children:[i?e.jsxs("button",{className:"training-text-button labs-dataset-build-back",type:"button",onClick:o,children:[e.jsx(qt,{size:14}),n]}):null,e.jsx("div",{className:"labs-dataset-builder-workspace",children:s})]}):e.jsxs(it,{ariaLabel:t,className:`training-dialog training-run-dialog ${r==="start"?"training-run-start-step":"training-run-workflow-step"}`,initialFocusKey:r,onClose:u,children:[e.jsxs("div",{className:"training-dialog-header",children:[e.jsxs("div",{className:"training-run-dialog-title",children:[i?e.jsx("button",{className:"training-icon-button",type:"button","aria-label":n,onClick:o,children:e.jsx(qt,{size:16})}):null,e.jsx("h2",{children:l})]}),e.jsx("button",{className:"training-icon-button",type:"button","aria-label":"Close",onClick:u,children:e.jsx(Xe,{size:16})})]}),s]})}function ni(t){return t?t.state==="awaiting_disclosure_approval"?"evidence":"recommendation":"start"}function Bn(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 si(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 nn(t,n){return n==="dataset"?"dataset":t.kind==="agent"?"agent":t.kind==="model"?"model":"workproduct"}function ai(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 ii(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 ri(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 li(){return{schemaVersion:"openpond.taskMinerConfig.v1",enabled:!1,localOnly:!0,observationWindowDays:30,minimumRecurrence:3,clustering:"hybrid_deterministic_first",consentRequired:!0}}const On=20;function Nt({datasetBuildMode:t=!1,defaultModel:n,datasetBuildBackLabel:s="Back to Dataset sources",initialCreation:a=null,initialExistingTasksetId:i=null,initialObjective:r,initialSessionIds:l=[],onClose:o,onAgentPromptSubmitted:u,onBackToDatasetSources:h,onOpenComputeSettings:d,onCreateDataset:p,onModelCreatedFromTaskset:m,onTasksetCreated:b,preferences:k,providerSettings:w,reasoningEffort:j,resourceIntent:v="workproduct",sessions:N,sources:S,training:y,targetIntent:M={kind:"model",id:null,displayName:null,operation:"create"},presentation:E="dialog"}){const $=us(k,n),C=y.payload?.baseModelCandidates??[],x=v==="workproduct"&&M.kind==="agent",D=v==="workproduct"&&M.kind==="model",ae=S.filter(f=>a?.request.sourceIds.includes(f.id)).map(f=>f.sessionId),[P,F]=c.useState(()=>a?ni(a):t?"evidence":D?"existing_dataset":"start"),[G,T]=c.useState(()=>a&&x?a.request.sourceIds.length>0?"from_chats":"from_prompt":a?.request.entryMode??(t?"manual":D?"existing_dataset":null)),I=G==="automated"||G==="manual"?G:null,O=G==="from_prompt"||G==="from_chats"?G:null,[z,ce]=c.useState(a?.request.objective??r??""),[ie,re]=c.useState(()=>Bn(C,a?.request.preferredBaseModel??null,a?.request.preferredBaseModelId??null)?.selectionKey??null),[K,ue]=c.useState(i),[Q,se]=c.useState(a?.request.candidateId??null),[le,Y]=c.useState(a?.request.analysisModel?.providerId??$.providerId),[ne,ke]=c.useState(a?.request.analysisModel?.modelId??$.modelId),[he,Ce]=c.useState(a?.request.analysisReasoningEffort??j),[H,Le]=c.useState(""),[U,oe]=c.useState([]),[pe,fe]=c.useState(0),[xe,_e]=c.useState(!1),[je,A]=c.useState(!1),[J,V]=c.useState(null),[W,We]=c.useState(!1),[Ye,ve]=c.useState(0),[Oe,rt]=c.useState(0),[pt,lt]=c.useState(0),be=c.useRef(0),Te=c.useRef(!1),[me,Ee]=c.useState(()=>new Set([...l,...ae])),[Pe,R]=c.useState({}),[_,q]=c.useState(a),[ye,ge]=c.useState(!1),[we,Ie]=c.useState(!1),[Wt,$e]=c.useState(null);Qe(J,{prefix:"Chat search"}),Qe(Wt);const[ot,ee]=c.useState(!1),[Be,De]=c.useState(null),[mt,wt]=c.useState([]),[He,It]=c.useState(()=>y.payload?.minerConfig??li()),gt=c.useMemo(()=>new Set(S.filter(f=>{const L=f.metadata.workflowSignature;return f.metadata.frontierBaseline===!0||L==="cross-system-operations"||typeof L=="string"&&L.startsWith("baseline:")||!!f.metadata.crossSystemOperations}).map(f=>f.sessionId)),[S]),Rt=c.useMemo(()=>N.filter(f=>!f.systemKind&&!f.hiddenFromDefaultSidebar&&f.status!=="active"&&!gt.has(f.id)),[gt,N]),ft=c.useMemo(()=>new Map(N.map(f=>[f.id,f])),[N]),xt=c.useMemo(()=>new Map(S.map(f=>[f.sessionId,f])),[S]),Je=c.useMemo(()=>Rt.slice(0,500).map(f=>({sessionId:f.id,title:f.title,updatedAt:f.updatedAt})),[Rt]),dt=c.useMemo(()=>[...me].flatMap(f=>{const L=U.find(tt=>tt.sessionId===f);if(L)return[L];const B=ft.get(f);if(B)return[{sessionId:f,title:B.title,updatedAt:B.updatedAt,snippet:null}];const X=xt.get(f);return X?[{sessionId:f,title:X.title,updatedAt:X.occurredAt,snippet:null}]:[]}),[U,me,ft,xt]),Ze=c.useMemo(()=>[...new Set([...dt,...U].map(f=>f.sessionId))].filter(f=>!Pe[f]).join(`
2
- `),[Pe,U,dt]),Fe=c.useMemo(()=>y.payload?.minerRuns.find(f=>f.id===Be)??null,[Be,y.payload?.minerRuns]),At=ot||!!(Fe&&["queued","running","cancelling"].includes(Fe.status)),te=we||ot||!!y.busyAction,ze=P==="automatic_scope"||P==="evidence"&&G!=="from_prompt",Mt=c.useMemo(()=>C.find(f=>f.selectionKey===ie)??null,[C,ie]),bt=Mt?.preference??null;c.useEffect(()=>(Te.current=!1,()=>{Te.current=!0,be.current+=1}),[]),c.useEffect(()=>ce(a?.request.objective??r??""),[a?.id,r]),c.useEffect(()=>{if(ie||!a)return;const f=Bn(C,a.request.preferredBaseModel,a.request.preferredBaseModelId);f&&re(f.selectionKey)},[C,a,ie]),c.useEffect(()=>{if(P!=="automatic_scope"||Be)return;const f=y.payload?.minerRuns.find(L=>["queued","running","cancelling"].includes(L.status));f&&De(f.id)},[Be,P,y.payload?.minerRuns]),c.useEffect(()=>{if(!ta(P,Fe))return;const f=new Set(Fe.candidateIds);wt(y.payload?.candidates.filter(L=>f.has(L.id))??[]),F("automatic_candidates")},[Fe,P,y.payload?.candidates]),c.useEffect(()=>{ze&&(oe([]),fe(0),_e(!1),V(null))},[H,ze]),c.useEffect(()=>{if(!ze)return;const f=be.current+1;be.current=f,A(!0),V(null);const L=window.setTimeout(()=>{y.actions.searchChats(H,Je,0,On).then(B=>{be.current===f&&(oe(B.entries),fe(B.total),_e(B.hasMore),We(B.indexing),ve(B.indexedChats),rt(B.totalChats))}).catch(B=>{be.current===f&&(oe([]),fe(0),_e(!1),We(!1),V(B instanceof Error?B.message:String(B)))}).finally(()=>{be.current===f&&A(!1)})},220);return()=>window.clearTimeout(L)},[Je,H,pt,ze,y.actions]),c.useEffect(()=>{if(!ze||!H.trim()||!W)return;const f=window.setTimeout(()=>lt(L=>L+1),1500);return()=>window.clearTimeout(f)},[H,W,ze]);const qe=c.useCallback(async()=>{if(je||!xe)return;const f=be.current,L=U.length;A(!0);try{const B=await y.actions.searchChats(H,Je,L,On);if(be.current!==f)return;oe(X=>{const tt=new Set(X.map(Xt=>Xt.sessionId));return[...X,...B.entries.filter(Xt=>!tt.has(Xt.sessionId))]}),fe(B.total),_e(B.hasMore),We(B.indexing),ve(B.indexedChats),rt(B.totalChats)}catch(B){be.current===f&&V(B instanceof Error?B.message:String(B))}finally{be.current===f&&A(!1)}},[Je,H,U.length,xe,je,y.actions]);c.useEffect(()=>{const f=Object.fromEntries(S.flatMap(L=>{const B=typeof L.metadata.messageCount=="number"?L.metadata.messageCount:null,X=typeof L.metadata.estimatedTokens=="number"?L.metadata.estimatedTokens:null;return B===null||X===null?[]:[[L.sessionId,{messageCount:B,estimatedTokens:X}]]}));Object.keys(f).length&&R(L=>({...f,...L}))},[S]),c.useEffect(()=>{if(!ze||!Ze)return;let f=!1;const L=window.setTimeout(()=>{y.actions.estimateSources(Ze.split(`
3
- `)).then(B=>{f||R(X=>({...X,...Object.fromEntries(B.map(tt=>[tt.sessionId,{messageCount:tt.messageCount,estimatedTokens:tt.estimatedTokens}]))}))}).catch(()=>{})},200);return()=>{f=!0,window.clearTimeout(L)}},[ze,y.actions,Ze]);const _t=c.useMemo(()=>ii([...me],Pe),[Pe,me]);function g(f){f!==G&&G!==null&&ge(!0),T(f)}function Z(){if(D){F("base_model");return}et()}function et(){if(!(D&&!Mt?.available)){if(G==="existing_dataset"){Jt();return}if(O){F("evidence");return}I==="automated"&&F("automatic_scope"),I==="manual"&&F("evidence")}}async function Jt(){if(!(!K||!m||!bt)){Ie(!0),$e(null);try{const f=await y.actions.createModelFromTaskset(K,bt);if(!f)throw new Error(y.error??"OpenPond could not create the Model from this Dataset.");const L=y.payload?.tasksets.find(B=>B.id===K);if(!L)throw new Error("The selected Dataset could not be reloaded.");await m(L,f)}catch(f){$e(f instanceof Error?f.message:String(f))}finally{Ie(!1)}}}function $s(f){f!==z&&ge(!0),ce(f)}function Bs(f){ge(!0),Y(f),ke(L=>na(f,L,w))}function Ls(f){ge(!0),ke(f)}function Os(f){ge(!0),Ce(f)}function In(){ge(!0),Ee(f=>{const L=new Set(f),B=U.length>0&&U.every(X=>L.has(X.sessionId));for(const X of U)B?L.delete(X.sessionId):L.add(X.sessionId);return L})}function Rn(f,L){ge(!0),Ee(B=>{const X=new Set(B);return L?X.add(f):X.delete(f),X})}async function Fs(){const f=[],L=[];for(const B of me){const X=xt.get(B);X?f.push(X):L.push(B)}if(L.length){const B=await y.actions.addSources(L);if(!B)throw new Error("OpenPond could not attach the selected evidence. Review the training error and try again.");f.push(...B)}if(f.length!==me.size)throw new Error("Some selected evidence could not be resolved. Reselect the chats before continuing.");return f}async function zs(){const f=[...me];if(f.length){ee(!0);try{const L={...He,enabled:!0},B=await y.actions.runMiner([],f,L);B&&De(B.id)}finally{ee(!1)}}}async function qs(){Be&&await y.actions.cancelMinerRun(Be)}function Us(f){const L=new Set(f.evidence.flatMap(X=>X.sourceRefIds)),B=S.filter(X=>L.has(X.id)).map(X=>X.sessionId);Ee(new Set(B)),se(f.id),ce(f.title),ge(!0),F("evidence")}async function Vs(){Ie(!0),$e(null);try{if(x&&O==="from_prompt"){if(!u)throw new Error("OpenPond could not continue from the Agent purpose.");await u({analysisModel:{providerId:le,modelId:ne},objective:z.trim()});return}const f=await Fs(),L=_?.request.sourceIds.length===0?_.request.createImproveRunId:null;if(_&&!L&&ye&&!["cancelled","failed","ready"].includes(_.state)){const X=_;await y.actions.cancelCreation(X.id)}const B=await y.actions.startCreation(f.map(X=>X.id),{surface:I==="automated"?"task_candidate":"training_page",mode:"defaults",entryMode:I??"manual",resourceIntent:v,objective:z.trim()||void 0,methodHint:null,preferredBaseModel:D?bt:null,candidateId:Q,analysisModel:{providerId:le,modelId:ne},analysisReasoningEffort:he,createImproveRunId:L,targetIntent:M});if(!B)throw new Error(x?"OpenPond could not prepare the Agent review.":"OpenPond could not start Taskset authoring.");if(Te.current){tn(B)&&await y.actions.cancelCreation(B.id);return}q(B),ge(!1),B.state!=="awaiting_disclosure_approval"&&F("recommendation")}catch(f){Te.current||$e(f instanceof Error?f.message:String(f))}finally{Te.current||Ie(!1)}}async function Ks(){if(!(!_||_.state!=="awaiting_disclosure_approval")){Ie(!0);try{const f=await y.actions.approveDisclosure(_.id,!0);if(!f)return;q(f),F("recommendation")}finally{Ie(!1)}}}async function Hs(){if(!(!_||_.state!=="failed")){Ie(!0),$e(null);try{const f=await y.actions.retryCreation(_.id);if(!f)throw new Error(y.error??(x?"OpenPond could not retry the Agent review.":"OpenPond could not retry Taskset authoring."));q(f),F("recommendation")}catch(f){$e(f instanceof Error?f.message:String(f))}finally{Ie(!1)}}}async function An(){_?.state==="awaiting_disclosure_approval"&&await y.actions.approveDisclosure(_.id,!1),q(null),ge(!0)}async function Gs(){const f=_;try{tn(f)&&await y.actions.cancelCreation(f.id)}finally{h?.()}}function Ws(){if(P==="base_model")F(G==="existing_dataset"?"existing_dataset":"start");else if(P==="existing_dataset")F("base_model");else if(P==="automatic_scope")F(t?"evidence":D?"base_model":"start");else if(P==="automatic_candidates")F("automatic_scope");else if(P==="evidence"){if(t&&h){Gs();return}_?.state==="awaiting_disclosure_approval"&&An(),F(I==="automated"?"automatic_candidates":D?"base_model":"start")}else P==="recommendation"&&F("evidence")}async function Qt(){if(Te.current)return;Te.current=!0,be.current+=1;const f=_;try{tn(f)&&await y.actions.cancelCreation(f.id)}finally{o()}}async function Js(){await Qt(),d()}async function Qs(){if(!(!_||_.state!=="awaiting_materialization_approval")){$e(null);try{const f=await y.actions.materialize(_.id,!0);if(!f)throw new Error(x?"OpenPond could not continue from the approved Agent review.":"OpenPond could not materialize the approved Taskset.");if(f.state==="ready"){await b(f);return}q(f)}catch(f){$e(f instanceof Error?f.message:String(f))}}}return e.jsx(ti,{ariaLabel:Ln(M,v),backAriaLabel:t&&P==="evidence"?s:t&&(P==="automatic_scope"||P==="recommendation")?"Back to Dataset build":ri(P,D,I),presentation:E,showBack:P!=="start"&&P!=="existing_dataset",step:P,title:P==="recommendation"?ai(M,v):Ln(M,v),onBack:Ws,onClose:()=>{Qt()},children:P==="start"?e.jsx(Ya,{allowExistingDataset:D&&!!m,mode:G,operation:M.operation,targetLabel:nn(M,v),onChange:g,onContinue:Z}):P==="base_model"?e.jsx(Ba,{busy:y.busyAction==="scan-base-models",candidates:C,continueLabel:G==="existing_dataset"?"Create model":"Continue",value:ie,onChange:re,onContinue:et,onManage:()=>{Js()},onScan:()=>{y.actions.scanBaseModels()}}):P==="existing_dataset"?e.jsx(za,{busy:te,selectedTasksetId:K,state:y.payload,onChange:ue,onContinue:()=>F("base_model"),onCreateDataset:p}):P==="automatic_scope"?e.jsx(Pa,{config:He,estimatesBySessionId:Pe,estimate:_t,matchingSessionCount:pe,onCancel:()=>{qs()},onConfigChange:It,onLoadMore:()=>{qe()},onScan:()=>{zs()},onSearchChange:Le,onToggleSession:Rn,onToggleVisible:In,run:Fe,scanning:At,search:H,searchError:J,searchHasMore:xe,searchIndexedChats:Ye,searchIndexing:W,searchLoading:je,searchTotalChats:Oe,selectedEntries:dt,selectedSessionIds:me,targetLabel:nn(M,v),visibleSessions:U}):P==="automatic_candidates"?e.jsx(Ta,{candidates:mt,onRescan:()=>{De(null),F("automatic_scope")},onSelect:Us}):P==="evidence"&&(I||O)?e.jsx(Xa,{authoringModel:ne,authoringProvider:le,authoringReasoningEffort:he,busy:te,disclosurePending:_?.state==="awaiting_disclosure_approval",estimatesBySessionId:Pe,matchingSessionCount:pe,mode:O??I,objective:z,onObjectiveChange:$s,onAnalyze:()=>{Vs()},onApproveDisclosure:()=>{Ks()},onAuthoringModelChange:Ls,onAuthoringProviderChange:Bs,onAuthoringReasoningEffortChange:Os,onDeclineDisclosure:()=>{An()},onDiscoverFromConversations:t?()=>F("automatic_scope"):void 0,onSearchChange:Le,onLoadMore:()=>{qe()},onReturnToRecommendation:()=>F("recommendation"),onToggleSession:Rn,onToggleVisible:In,providerSettings:w,recommendationAvailable:!!_?.proposal&&!ye,search:H,searchError:J,searchHasMore:xe,searchIndexedChats:Ye,searchIndexing:W,searchLoading:je,searchTotalChats:Oe,selectedEntries:dt,selectedEstimate:_t,selectedSessionIds:me,targetLabel:nn(M,v),targetOperation:M.operation,visibleSessions:U}):P==="recommendation"&&_?.proposal?e.jsx(Qa,{busy:te,creation:_,onAddChats:()=>F("evidence"),onClose:()=>{Qt()},onCreateTaskset:()=>{Qs()},onCreationChange:q,sources:S,training:y,createLabel:v==="dataset"?"Create Dataset":M.kind==="model"?"Create model":void 0,editDataLabel:v==="dataset"?"Edit sources":M.kind==="model"?"Edit Dataset":void 0,resourceIntent:v}):P==="recommendation"&&_?.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:_.blockingQuestions[0]?.prompt??_.blockedReason??"Add supporting evidence before authoring continues."})]})}),e.jsx("div",{className:"training-dialog-actions",children:e.jsx("button",{className:"training-button",type:"button",onClick:()=>F("evidence"),children:v==="dataset"?"Edit sources":M.kind==="model"?"Edit Dataset":"Add chats"})})]}):P==="recommendation"&&_?.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:si(_.blockedReason)})]}),z?e.jsxs("div",{className:"training-evidence-objective",children:[e.jsx("span",{children:x?"Agent purpose":"Capability"}),e.jsx("strong",{children:z})]}):null,e.jsx("p",{className:"training-empty",children:x?"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:te,onClick:()=>F("evidence"),children:x?"Change chats":"Change evidence"}),e.jsxs("button",{className:"training-button",type:"button",disabled:te,onClick:()=>{Hs()},children:[we?e.jsx(Me,{className:"spin",size:14}):null,"Retry approved evidence"]})]})]}):e.jsx("div",{className:"training-recommendation-loading",children:_?.state==="failed"?e.jsxs(e.Fragment,{children:[e.jsx("h3",{children:"Analysis failed"}),e.jsx("p",{children:_.blockedReason})]}):e.jsxs(e.Fragment,{children:[e.jsx(Me,{className:"spin",size:18}),e.jsx("p",{children:x?"Preparing the Agent review…":"Preparing the recommendation…"})]})})})}const Fn=[{id:"build",title:"Build",description:"Create from a purpose, conversations, or both.",icon:ht,available:!0},{id:"huggingface",title:"Hugging Face",description:"Paste a Dataset URL or repository ID.",icon:sa,available:!0},{id:"upload",title:"Upload file",description:"JSON, JSONL, CSV, and Parquet import is coming next.",icon:aa,available:!1}];function oi({onClose:t,onSelect:n}){const[s,a]=c.useState(null),i=Fn.find(r=>r.id===s)??null;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:"radiogroup",children:Fn.map(r=>{const l=r.icon;return e.jsxs("button",{"aria-describedby":r.available?void 0:`${r.id}-availability`,"aria-checked":s===r.id,className:s===r.id?"selected":void 0,disabled:!r.available,role:"radio",type:"button",onClick:()=>a(r.id),children:[e.jsx("span",{className:"training-start-mode-icon","aria-hidden":"true",children:e.jsx(l,{size:18})}),e.jsxs("span",{className:"training-start-mode-copy",children:[e.jsxs("strong",{children:[r.title,r.available?null:e.jsx("span",{className:"dataset-source-availability",id:`${r.id}-availability`,children:"Coming next"})]}),e.jsx("small",{children:r.description})]})]},r.id)})}),e.jsxs("div",{className:"training-dialog-actions",children:[e.jsx("button",{className:"training-button secondary",type:"button",onClick:t,children:"Cancel"}),e.jsx("button",{className:"training-button",disabled:!i,type:"button",onClick:()=>{i&&n(i.id)},children:s==="build"?"Create":"Continue"})]})]})}const di=["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"],ci=["visible","privileged","metadata"];function ui({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),[p,m]=c.useState(""),[b,k]=c.useState(""),[w,j]=c.useState(!1),[v,N]=c.useState(null),S=c.useRef(null),M=i.payload?.datasetImports.find(I=>I.id===o?.id)??o,E=M?.inspection??null,$=!!(M&&["inspecting","materializing","validating","cancelling"].includes(M.status)),C=!E?.declaredLicense||["unknown","other"].includes(E.declaredLicense.toLowerCase()),x=c.useMemo(()=>E?.sourceFiles.reduce((I,O)=>I===null||O.sizeBytes===null?null:I+O.sizeBytes,0)??null,[E]);c.useEffect(()=>{!M||M.status!=="ready"||!M.tasksetId||S.current!==M.id&&(S.current=M.id,s(M.tasksetId))},[M,s]);async function D(){if(!r.trim())return;N(null);const I=await i.actions.inspectHuggingFaceDataset(r);if(!I){N(i.error??"OpenPond could not inspect this Dataset.");return}u(I),I.inspection&&I.mapping&&ae(I)}function ae(I){d(I.mapping),m(I.inspection?.title??I.locator?.repositoryId.split("/").at(-1)??"Imported Dataset"),k(I.inspection?.description?.trim().slice(0,2e3)||`Train and evaluate tasks from ${I.locator?.repositoryId??"this Dataset"}.`)}function P(I,O){d(z=>z&&{...z,bindings:z.bindings.map((ce,ie)=>ie===I?{...ce,...O}:ce)})}async function F(){if(!M||!h||!p.trim()||!b.trim())return;N(null);const I=await i.actions.materializeDatasetImport(M.id,{name:p.trim(),objective:b.trim(),mapping:h,targetStorageRoot:null,licenseApproved:w});if(!I){N(i.error??"OpenPond could not start Dataset materialization.");return}u(I)}async function G(){if(!M)return;const I=await i.actions.cancelDatasetImport(M.id);I&&u(I)}const T=!!(E&&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:$,initialFocusKey:E?"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(qt,{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})})]}),E?T?e.jsxs("div",{className:"training-dialog-scroll-body dataset-import-review",children:[e.jsx(hi,{job:M,sourceBytes:x}),e.jsxs("label",{className:"training-objective-field",children:[e.jsx("span",{children:"Dataset name"}),e.jsx("input",{value:p,onChange:I=>m(I.target.value)})]}),e.jsxs("label",{className:"training-objective-field",children:[e.jsx("span",{children:"Purpose"}),e.jsx("textarea",{value:b,onChange:I=>k(I.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((I,O)=>e.jsxs("div",{children:[e.jsx("code",{children:I.sourcePath}),e.jsx("select",{"aria-label":`Target for ${I.sourcePath}`,value:I.target,onChange:z=>P(O,{target:z.target.value}),children:di.map(z=>e.jsx("option",{value:z,children:gn(z)},z))}),e.jsx("select",{"aria-label":`Policy for ${I.sourcePath}`,value:I.policy,onChange:z=>P(O,{policy:z.target.value}),children:ci.map(z=>e.jsx("option",{value:z,children:gn(z)},z))})]},`${I.sourcePath}:${O}`))})]}),C?e.jsxs("label",{className:"dataset-import-license-review",children:[e.jsx("input",{checked:w,type:"checkbox",onChange:I=>j(I.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(pi,{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:$,placeholder:"BytedTsinghua-SIA/DAPO-Math-17k",value:r,onChange:I=>l(I.target.value)})]}),M?.status==="failed"&&M.error?e.jsx("div",{className:"training-banner error",role:"alert",children:M.error}):null]}),v?e.jsx("div",{className:"training-banner error",role:"alert",children:v}):null,e.jsx("div",{className:"training-dialog-actions",children:E?T?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:!p.trim()||!b.trim()||!h||C&&!w,type:"button",onClick:()=>{F()},children:"Import and save"})]}):$?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:()=>{G()},children:"Cancel import"})]}):e.jsx("button",{className:"training-button",type:"button",onClick:n,children:"Close"}):e.jsxs("button",{className:"training-button",disabled:!r.trim()||$,type:"button",onClick:()=>{D()},children:[$?e.jsx(Me,{className:"spin",size:14}):null,"Inspect Dataset"]})})]})}function hi({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(ia,{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":fn(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 pi({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(Me,{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?`${fn(n.completedBytes)}${n.totalBytes?` of ${fn(n.totalBytes)}`:""}`:gn(n.phase)}),t.error?e.jsx("div",{className:"training-banner error",children:t.error}):null]})}function gn(t){return t.replaceAll("_"," ").replace(/^./,n=>n.toUpperCase())}function fn(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 bs({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(k=>k.modelArtifactLineageId===t.id).sort((k,w)=>w.updatedAt.localeCompare(k.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(Ut({modelId:t.id,taskset:n})),i())},[t.id,a,i,u?.state,r,n]);async function p(){l(!0),await s.actions.startModelServing(t.id)||l(!1)}async function m(k){l(!1),await s.actions.stopModelServing(k.id)}function b(){a(Ut({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(mi,{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:()=>{m(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:b,children:[e.jsx(zt,{size:14}),"Chat now"]}):h?.state==="starting"?e.jsxs("button",{className:"training-button",disabled:!0,type:"button",children:[e.jsx(Me,{className:"spin",size:14}),"Starting…"]}):e.jsxs("button",{className:"training-button",disabled:d,type:"button",onClick:()=>{p()},children:[d&&r?e.jsx(Me,{className:"spin",size:14}):null,"Start & chat"]})]})]})}function mi({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?` · ${gi(t.stopReason)}`:""]}):null,t.error?e.jsx("small",{className:"error",children:t.error}):null]})}function gi(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 fi=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 xi(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 m=st.listCreateImproveRuns(n,{profileId:s,limit:500}).then(b=>(i(b.runs),u(null),b.runs)).catch(b=>(u(b instanceof Error?b.message:String(b)),null)).finally(()=>{h.current===m&&(h.current=null),l(!1)});return h.current=m,m},[n,s]);c.useEffect(()=>{if(!n){i([]),u(null);return}d()},[n,s,d]);const p=c.useMemo(()=>a.some(m=>fi.has(m.state)),[a]);return c.useEffect(()=>{if(!n)return;let m=!0,b=null;const k=async()=>{await d(),m&&(b=window.setTimeout(()=>{k()},p?1e3:15e3))};return b=window.setTimeout(()=>{k()},p?1e3:15e3),()=>{m=!1,b!==null&&window.clearTimeout(b)}},[n,p,d]),{runs:a,loading:r,error:o,refresh:d}}function de({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 bi=64,ji=4096;function sn(t,n=ji){return wa(t,{minimum:bi,maximum:n})}const zn=["q_proj","k_proj","v_proj","o_proj","gate_proj","up_proj","down_proj"],vi="accounts/fireworks/models/qwen3-8b",vt=3,Tt=9.99,an=32768,qn=2048,Un=8192;function yi({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:p,onConfirmPrepared:m,onOpenProviderSettings:b,onRunBaseline:k,baselineReports:w=[],baselineRuns:j=[]}){const v=s.readiness?.trainingPath??null,N=v?.primaryMethod??Ci(s),S=v?.bootstrap??null,y=wi(s),M=r&&y.includes(r)?r:N==="grpo"?"grpo":"sft",E=Ii(t,l),$=E?.executionOptions.find(g=>g.available&&g.methods.includes(M))??null,C=i.find(g=>g.destinationId==="fireworks"&&g.available&&g.methods.includes(M)),x=$?.destinationId??C?.destinationId??i.find(g=>g.destinationId==="local_cpu_fixture"&&g.available)?.destinationId??i.find(g=>g.available&&g.destinationId!=="export")?.destinationId??"local_cpu_fixture",[D,ae]=c.useState(x),[P,F]=c.useState(null),G=$?E:Ri(t,x,M),[T,I]=c.useState(G?.selectionKey??""),[O,z]=c.useState("automatic"),[ce,ie]=c.useState(()=>M==="grpo"?8:2),re=Hn(s,"train"),[K,ue]=c.useState(()=>Math.max(1,Math.min(re,M==="grpo"&&s.datasetArtifact?16:1e3))),[Q,se]=c.useState(()=>{const g=sn(s,x==="fireworks"?an:void 0);return M==="grpo"&&s.datasetArtifact&&x==="fireworks"?Math.max(512,g):g}),[le,Y]=c.useState(x==="fireworks"?8:2),[ne,ke]=c.useState(()=>Kn(G?.preference.modelId??"")),[he,Ce]=c.useState(!1),[H,Le]=c.useState(vt),[U,oe]=c.useState(7),[pe,fe]=c.useState(8),[xe,_e]=c.useState(4),[je,A]=c.useState(qn),[J,V]=c.useState(()=>js(s)),[W,We]=c.useState(M),[Ye,ve]=c.useState(null),Oe=i.find(g=>g.destinationId===D)??null,rt=W==="sft"&&N!=="sft"&&S?.method==="sft",pt=s.learningSignals.demonstrations.filter(g=>g.approved).length,lt=Hn(s,"frozen_eval"),be=c.useMemo(()=>P?.inventory?.devices.filter(g=>g.available)??[],[P?.inventory?.devices]),Te=c.useMemo(()=>P?.inventory?.models.filter(g=>g.trainingCompatible&&g.modelId&&g.revision&&g.tokenizerRevision&&g.chatTemplateHash)??[],[P?.inventory?.models]),me=c.useMemo(()=>t.filter(g=>g.executionOptions.some(Z=>Z.destinationId===D&&Z.methods.includes(W))),[t,D,W]),Ee=me.find(g=>g.selectionKey===T)??null,Pe=Ee?.executionOptions.find(g=>g.destinationId===D&&g.methods.includes(W))??null,R=Ee?.preference.modelId??"",_=Ee?.preference.modelAssetId?Te.find(g=>g.id===Ee.preference.modelAssetId)??null:Te.find(g=>g.modelId===R)??null,q=D==="fireworks",ye=s.datasetArtifact?"rft_easy_curriculum_v1":"stable_hash_top_n",ge={maxOutputTokens:je,temperature:.8,topP:.95},we=ya(w,{split:"train",taskCount:K,attemptsPerTask:pe,selectionSeed:17,selectionStrategy:ye,model:{providerId:"fireworks",modelId:R},sampling:ge}),Ie=j.find(g=>g.tasksetHash===s.contentHash&&g.configuration.split==="train"&&g.configuration.taskLimit===K&&g.configuration.attemptsPerTask===pe&&g.configuration.selectionSeed===17&&g.configuration.selectionStrategy===ye&&g.configuration.model.providerId==="fireworks"&&g.configuration.model.modelId===R&&g.configuration.sampling.maxOutputTokens===ge.maxOutputTokens&&g.configuration.sampling.temperature===ge.temperature&&g.configuration.sampling.topP===ge.topP)??null,Wt=Ie?["queued","preparing","running","cancelling"].includes(Ie.status):!1,$e=Ie?.status==="failed",ot=u==="baseline"||Wt,ee=s.datasetArtifact?we:w.find(g=>g.id===s.readiness?.baselineReportId)??null,Be=s.readiness?.baselineReward??null,De=W!=="grpo"||(s.datasetArtifact?we?.rftSignal?.passed===!0:!!(s.readiness?.baselineReportId&&Be&&Be.count>=2&&(Be.variance??0)>0&&(Be.mean??0)>.05&&(Be.mean??0)<.95)),mt=ee?Object.entries(ee.failureClusters).filter(([g])=>g==="infrastructure_failure").reduce((g,[,Z])=>g+Z,0):0,wt=ee?.attemptRefs.length??0,He=!!(ee&&ee.reward.count===0&&mt>0),It=!!(ee?.rftSignal&&!ee.rftSignal.passed&&!He),gt=W==="grpo"&&q&&s.datasetArtifact?Math.max(1,Math.min(32,re)):Math.max(1,Math.min(1e5,re)),Rt=!q||he&&H>=vt&&H<=Tt&&Number.isInteger(U)&&U>=1&&U<=30,ft=W==="sft"||W==="grpo"&&q,xt=s.capabilities.compatibleMethods.includes(W)||S?.method===W,Je=!!(s.readiness?.ready&&De&&ft&&Oe?.available&&Oe.methods.includes(W)&&xt&&Pe?.available&&(Ee?.preference.source!=="local"||_)&&Rt),dt=s.readiness?.ready?De?ft?Ee?Pe?.available?Ee.preference.source==="local"&&!_?"The selected local model is no longer present in the verified compute inventory. Scan Compute and select it again.":Oe?.methods.includes(W)?Oe?.unavailableReason??(q&&!he?"Approve the bounded train-split export before launching Fireworks.":q&&(H<vt||H>Tt)?`Set a Fireworks cap from $${vt.toFixed(2)} through $${Tt.toFixed(2)}.`:q&&(!Number.isInteger(U)||U<1||U>30)?"Choose a provider retention record from 1 through 30 days.":null):`${Et(D)} does not execute ${W.toUpperCase()}.`:Pe?.unavailableReason??"The selected base model cannot run on this compute destination.":`Choose starting weights compatible with ${Et(D)} and ${W.toUpperCase()}.`:`${W.toUpperCase()} is the primary recommendation but no compatible execution backend is available here.${S?" 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.",Ze=Si({method:W,taskset:s,destinationId:D,baseModelId:R,maxSteps:ce,sequenceLength:Q,rank:le,learningRate:ne,model:_,rolloutGroupSize:pe,rolloutConcurrency:xe,rolloutMaxOutputTokens:je,trainingExamples:K,rftLossMethod:J}),Fe={exportApproved:q?he:!0,maximumCostUsd:q?H:0,retentionDays:q?U:null,region:null},At=JSON.stringify({modelId:a,destinationId:D,recipe:Ze,approval:Fe}),te=Ye?.configurationKey===At?Ye.value:null;c.useEffect(()=>{if(!n)return;let g=!0;return st.computeState(n).then(Z=>{g&&(F(Z),z(Z.settings.defaultDeviceIds[0]??"automatic"))}).catch(()=>{}),()=>{g=!1}},[n]);async function ze(){if(!Je)return;if(q&&!te){const Z=await p(D,Ze,Fe);Z&&ve({configurationKey:At,value:Z});return}(q&&te?await m(te,H):await d(D,Ze,Fe))&&h()}function Mt(g){if(ae(g),I(Z=>Vn(t,Z,g,W)),g==="fireworks"){Y(8),W==="grpo"&&(ie(8),s.datasetArtifact&&ue(Math.max(1,Math.min(re,16)))),se(Math.max(512,sn(s,an)));return}Y(2),se(sn(s))}function bt(g){if(We(g),ve(null),I(Z=>Vn(t,Z,D,g)),g==="grpo"){ie(8),D==="fireworks"&&s.datasetArtifact&&se(Z=>Math.max(512,Z)),ue(Math.max(1,Math.min(re,s.datasetArtifact?16:1e3)));return}ie(2)}const qe=te?.plan.estimatedCostUsd??null,_t=o?u==="baseline"?"Base-model test running":te?"Launching…":q?"Preparing…":"Starting…":te&&qe!=null?`Launch $${qe.toFixed(2)} job`:q?"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:g=>g.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:y.map(g=>e.jsxs("button",{"aria-selected":g===W,className:g===W?"active":"",disabled:o,role:"tab",type:"button",onClick:()=>bt(g),children:[e.jsx("span",{children:fa(g)}),e.jsx("strong",{children:at(g)})]},g))}),e.jsxs("div",{className:"training-start-fields",children:[e.jsxs("label",{children:[e.jsx("span",{children:"Base model"}),e.jsxs("select",{value:T,disabled:o,onChange:g=>{const Z=g.target.value,et=t.find(Jt=>Jt.selectionKey===Z);I(Z),ke(Kn(et?.preference.modelId??""))},children:[e.jsx("option",{value:"",disabled:!0,children:"Choose compatible starting weights"}),me.map(g=>{const Z=g.executionOptions.find(et=>et.destinationId===D&&et.methods.includes(W));return e.jsxs("option",{value:g.selectionKey,disabled:!Z?.available,children:[g.label," · ",g.sourceLabel,Z?.available?"":` — ${Z?.unavailableReason??"Unavailable"}`]},g.selectionKey)})]})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Compute"}),e.jsx("select",{value:D,disabled:o,onChange:g=>Mt(g.target.value),children:i.filter(g=>!["custom","runpod_byoc","export"].includes(g.destinationId)).map(g=>e.jsxs("option",{value:g.destinationId,disabled:!g.available,children:[Et(g.destinationId),g.available?"":` — ${g.unavailableReason??"Unavailable"}`]},g.destinationId))})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Device"}),e.jsxs("select",{value:O,disabled:o||D!=="local_cpu_fixture",onChange:g=>z(g.target.value),children:[e.jsx("option",{value:"automatic",children:"Automatic"}),be.map(g=>e.jsx("option",{value:g.id,children:g.name},g.id))]})]})]}),q?e.jsxs("fieldset",{className:"training-provider-approval",children:[e.jsx("legend",{children:"Provider approval"}),b?e.jsx("button",{className:"training-text-button",type:"button",disabled:o,onClick:()=>{h(),b()},children:"Manage Fireworks provider"}):null,e.jsxs("label",{className:"training-provider-consent",children:[e.jsx("input",{type:"checkbox",checked:he,disabled:o,onChange:g=>Ce(g.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:vt,max:Tt,step:.01,value:H,disabled:o,onChange:g=>Le(g.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:U,disabled:o,onChange:g=>oe(g.target.valueAsNumber)})]})]}),e.jsx("p",{className:"training-start-note",children:"Approval is bound server-side to the signed-in OpenPond account at launch."}),W==="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:W==="grpo"?`${Math.min(K,re)} of ${re} approved train prompts`:`${Math.min(K,pt||re)} approved example${K===1?"":"s"}`})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Evaluation"}),e.jsxs("dd",{children:[lt," test example",lt===1?"":"s"]})]}),e.jsxs("div",{children:[e.jsx("dt",{children:qe==null?"Estimate":"Exact quote"}),e.jsx("dd",{children:D==="local_cpu_fixture"?_?`$0 · ${ce} steps × ${Q} tokens · 15-minute hard stop`:"$0 · 2-minute hard stop":q?qe==null?`Prepare a provider-validated quote · hard cap $${Number.isFinite(H)?H.toFixed(2):"—"}`:`$${qe.toFixed(2)} · hard cap $${H.toFixed(2)}`:"Provided before approval"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Storage"}),e.jsx("dd",{children:q?"Portable output imported into app-managed storage":P?.settings.modelStorePath??"App-managed local storage"})]})]}),te?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:te.approvalActor??"Local user"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Provider"}),e.jsx("dd",{children:Et(te.plan.destinationId)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Model"}),e.jsx("dd",{children:Ai(te.plan.recipe.method==="sft"||te.plan.recipe.method==="grpo"?te.plan.recipe.baseModel.id:"")})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Method"}),e.jsx("dd",{children:te.plan.recipe.method==="grpo"?`RFT · ${ki(te.plan.recipe.loss.method)}`:`${at(te.plan.recipe.method)} · ${te.plan.recipe.parameterization.toUpperCase()}`})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Quote"}),e.jsx("dd",{children:qe==null?"Unavailable":`$${qe.toFixed(2)}`})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Maximum"}),e.jsxs("dd",{children:["$",H.toFixed(2)]})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Retention"}),e.jsxs("dd",{children:[te.plan.dataPolicy.retentionDays," days"]})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Prepared data"}),e.jsxs("dd",{children:[Mi(te.bundle.totalSizeBytes)," · verified"]})]}),te.plan.rftSignalGate?e.jsxs("div",{children:[e.jsx("dt",{children:"Train signal"}),e.jsxs("dd",{children:[te.plan.rftSignalGate.signal.mixedRewardGroups," mixed groups · verified"]})]}):null]}),e.jsx("p",{children:"No Fireworks dataset or job exists until you launch."})]}):null,W==="grpo"&&q?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?De?"Train signal verified":He||$e?"Train-signal check failed":ee?.rftSignal?.parseableAttempts===0?"No final answers returned":It?"Not enough train signal":"Check train signal":De?"Base-model test complete":He?"Base-model test failed":"Test the base model"}),e.jsx("span",{children:s.datasetArtifact?De&&ee?`${ee.rftSignal?.mixedRewardGroups??0} of ${ee.scope?.taskCount??K} prompts produced both correct and incorrect rewards · ${ee.rftSignal?.correctAttempts??0} of ${ee.rftSignal?.eligibleAttempts??0} answers correct · $${(ee.totalCostUsd??0).toFixed(2)} recorded cost.`:$e?`${Ie?.error??"The train-signal check failed before it completed."} No training job was started.`:He?`${mt} of ${wt} attempts failed before grading. No training job was started.`:ee?.rftSignal?.parseableAttempts===0?`All ${ee.rftSignal.eligibleAttempts} requests completed, but none returned a parseable final answer. No training job was started.`:It?`${ee?.rftSignal?.mixedRewardGroups??0} of ${K} prompts produced mixed rewards; ${ee?.rftSignal?.requiredMixedRewardGroups??4} are required. No training job was started.`:`Run ${K} selected train prompts with ${pe} candidates each. At least 4 prompts must produce both correct and incorrect rewards before training can launch.`:De&&ee?`${ee.reward.count} graded attempts · ${(100*(ee.reward.mean??0)).toFixed(0)}% correct · $${(ee.totalCostUsd??0).toFixed(2)} recorded cost.`:He?`${mt} of ${wt} 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."}),De?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."]})]}),De?null:e.jsx("button",{className:"training-button secondary",type:"button",disabled:ot||!R||!k,onClick:()=>{!k||!R||k({providerId:"fireworks",modelId:R},{targetModelId:a,taskLimit:s.datasetArtifact?K:8,attemptsPerTask:s.datasetArtifact?pe:4,selectionSeed:17,split:s.datasetArtifact?"train":"frozen_eval",selectionStrategy:ye,sampling:ge})},children:s.datasetArtifact?ot?Ni(Ie):ee||$e?"Retry train-signal check":"Run train-signal check":ot?"Testing base model…":He?"Retry base-model test":"Test base model"})]}):null,rt&&S?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:S.limitations.map(g=>e.jsx("li",{children:g},g))})]}):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:gt,value:K,onChange:g=>ue(Math.max(1,Math.min(gt,g.target.valueAsNumber||1)))})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Optimizer steps"}),e.jsx("input",{type:"number",min:1,max:1e3,value:ce,onChange:g=>ie(g.target.valueAsNumber||1)})]}),e.jsxs("label",{children:[e.jsx("span",{children:W==="grpo"?"Prompt length":"Sequence length"}),e.jsx("input",{type:"number",min:16,max:q?an:4096,value:Q,onChange:g=>se(g.target.valueAsNumber||64)})]}),W==="grpo"?e.jsxs("label",{children:[e.jsx("span",{children:"Maximum output"}),e.jsx("input",{type:"number",min:16,max:Un,value:je,onChange:g=>A(Math.max(16,Math.min(Un,g.target.valueAsNumber||qn)))})]}):null,e.jsxs("label",{children:[e.jsx("span",{children:"LoRA rank"}),e.jsx("input",{type:"number",min:1,max:256,value:le,onChange:g=>Y(g.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:ne,onChange:g=>{const Z=g.target.valueAsNumber;Number.isFinite(Z)&&ke(Z)}})]}),W==="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:g=>V(g.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:pe,onChange:g=>fe(g.target.valueAsNumber||8)})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Concurrent rollouts"}),e.jsx("input",{type:"number",min:1,max:16,value:xe,onChange:g=>_e(g.target.valueAsNumber||4)})]})]}):null]})]}),!Je&&(De||W!=="grpo"||!q)?e.jsx("div",{className:"training-banner error training-dialog-error",children:dt??"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||!Je,onClick:()=>{ze()},children:_t})]})]})})}function Ni(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 Si(t){if(t.method==="grpo"&&t.destinationId==="fireworks"){const n=t.taskset.metadata.toolContractHash===Yt||t.taskset.environment.metadata.toolContractHash===Yt,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??js(t.taskset),klBeta:null},reward:n?{graderId:"cross-system-exact-verifier",graderHash:"server-derived-grader-hash",environmentId:"cross-system-operations",environmentVersion:ra,toolContractHash:Yt}:{graderId:s?.id??"math_final_answer",graderHash:"server-derived-grader-hash",environmentId:da,environmentVersion:oa,toolContractHash:la},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:zn},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:zn},optimizer:{learningRate:t.learningRate,epochs:1,maxSteps:t.maxSteps,batchSize:1,gradientAccumulationSteps:1,seed:17},resourceLimits:{cpuThreads:4,memoryBytes:8e9,wallTimeMs:9e5}}}function js(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 ki(t){return t==="gspo-token"?"GSPO-token":t.toUpperCase()}function Vn(t,n,s,a){return t.find(r=>r.selectionKey===n)?.executionOptions.some(r=>r.destinationId===s&&r.methods.includes(a))?n:""}function Kn(t){return t==="openpond/tiny-cpu-gpt2-fixture"?.01:2e-4}function Ci(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 wi(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 Hn(t,n){return t.datasetArtifact?.splitCounts[n]??t.tasks.filter(s=>s.split===n).length}function Et(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 Ii(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 Ri(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===vi)??a[0]??null:a[0]??null}function Ai(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 Mi(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 _i=new Set(["released","rejected","ready","ready_local","published_hosted","cancelled"]);function vs(t){const n=new Map,s=Ti(t.runs,t.training),a=new Date(0).toISOString();for(const i of t.profile?.agents??[]){const r=Ke("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=Ke("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,skillSource:"profile",skillValidationStatus:i.validationStatus,skillValidationMessages:i.validationMessages,skillSourceHash:i.sourceHash,skillCharCount:i.charCount,skillResourceFiles:i.resourceFiles})}for(const i of xa(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=Ke("model",l),u=n.get(o);n.set(o,{key:o,kind:"model",id:l,name:Ft(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=Ke(r,l),u=n.get(o),h=r==="agent"?Bi(i,u?.name??null):i.target.displayName??u?.name??$i(i),d=r==="model"?Ft(h,"New model"):h;n.set(o,{key:o,kind:r,id:l,name:d,description:u?.description??i.objective,status:Oi(i),updatedAt:Jn(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:Fi(i)??u?.evaluationStatus??"not_run",useActionId:u?.useActionId??null})}for(const i of t.training?.frontierBaselineRuns??[]){const r=Pi(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&&!Ei(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:Jn(l.updatedAt,i.updatedAt),frontierBaselineRunId:i.id})}return[...n.values()].sort((i,r)=>{const l=Number(Gn(i,t.runs))-Number(Gn(r,t.runs));return l!==0?-l:r.updatedAt.localeCompare(i.updatedAt)||i.name.localeCompare(r.name)})}function Ti(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 p=new Set;for(const w of a)w.tasksetId===h&&w.modelId&&p.add(w.modelId);for(const w of r)w.tasksetId===h&&w.modelId&&p.add(w.modelId);if(p.size>1)continue;const m=d.filter(w=>w.target.kind!=="model"?!1:w.target.trainingPlanId||w.target.trainingJobId||w.target.artifactId?!0:a.some(j=>j.tasksetId===h&&j.modelId===(w.target.id??w.id)));if(!m.length)continue;const k=[...p][0]??null??[...m].sort((w,j)=>j.updatedAt.localeCompare(w.updatedAt))[0].target.id??m[0].id;for(const w of m){if(w.target.kind!=="model")continue;const j=(w.target.trainingPlanId?l.get(w.target.trainingPlanId):null)??(w.target.trainingJobId?l.get(o.get(w.target.trainingJobId)?.planId??""):null);j?.modelId&&j.modelId!==k||s.set(w.id,k)}}return s}function Ei(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 Pi(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 Ke(t,n){return`${t}:${n}`}function Di(t){return t==="agent"?"Agents":t==="skill"?"Skills":t==="extension"?"Extensions":"Models"}function ys(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 Gn(t,n){const s=new Set(t.runIds);return n.some(a=>s.has(a.id)&&!_i.has(a.state))}function $i(t){return`${t.operation==="improve"?"Improve":"Create"} ${t.target.kind}`}function Bi(t,n){const s=Wn(t.target.displayName);if(s)return s;const a=Wn(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`${Ft(i,"New agent")} · ${Li(t.id)}`}function Li(t){return(t.split(/[^a-z0-9]+/i).filter(Boolean).at(-1)??t).slice(-6).toUpperCase().padStart(4,"0")}function Wn(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 Oi(t){return t.state.replaceAll("_"," ")}function Fi(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 Jn(t,n){return t&&t.localeCompare(n)>=0?t:n}function zi({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(vn,{size:13}),"Create Eval"]}),i.length?e.jsxs(e.Fragment,{children:[e.jsx(un,{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 Se({label:t,value:n=t}){return e.jsx("span",{className:`labs-status-badge ${Ns(n)}`,children:t})}function Ns(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 xn({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??Ns(i)} ${s}`,role:t?void 0:"status",title:n})}function qi({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(j=>j.candidateId===t.id),[t.id,a.evaluationReceipts]).filter(j=>j.subject==="candidate"),m=d.length>0&&d.every(j=>j.status==="passed"&&j.publishGate!=="failed")&&(a.state==="awaiting_promotion"||a.state==="blocked"&&!!a.localProfileCommit),b=a.state==="reconciling_release",k=n?.filesChanged??t.git?.changedPaths.length??0;async function w(j,v){if(!o){u(j);try{await v()}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:bn(k)})]}),e.jsxs("div",{className:"labs-change-card-body",children:[e.jsx("h3",{children:"Drafted update"}),e.jsx("p",{children:Ui(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${k?` (${k})`:""}`})})]})}),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:Vi(d)})]}),e.jsx("div",{className:"labs-change-evals",children:d.length?d.map(j=>e.jsxs("div",{className:"labs-change-eval",children:[e.jsxs("div",{children:[e.jsx("strong",{children:j.summary??"Agent Evals"}),e.jsx("span",{children:j.summaryCounts?`${j.summaryCounts.passed}/${j.summaryCounts.total} passed`:j.status})]}),e.jsx(Se,{label:j.status,value:j.status})]},j.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(xn,{label:Qn(a),value:a.state}),Qn(a)]}),e.jsxs("div",{className:"labs-change-actions",children:[e.jsx("button",{className:"training-button secondary",disabled:!!o||b||a.state!=="awaiting_promotion",type:"button",onClick:()=>{w("reject",()=>l(a,t.id))},children:o==="reject"?"Keeping current version":"Keep current version"}),e.jsx("button",{className:"training-button",disabled:!m||!!o||b,type:"button",onClick:()=>{w("apply",()=>i(a,t.id))},children:b||o==="apply"?"Applying":a.state==="blocked"?"Re-run Evals":"Apply update"})]})]})]})})]})]})}function bn(t){return`${t} ${t===1?"file":"files"}`}function Ui(t,n,s){if(s)return s;const a=n?.filesChanged??t.git?.changedPaths.length??0;return a?n?`${bn(a)} drafted · +${n.additions} −${n.deletions}`:`${bn(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 Vi(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 Qn(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 Ki({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:Gi(s)})]})}),e.jsx("td",{children:e.jsx(Se,{label:Wi(s),value:s.state})}),e.jsx("td",{children:Hi(s)}),e.jsx("td",{children:Ht(s.updatedAt)})]},s.id))})]})}):e.jsx("div",{className:"training-run-placeholder",children:"No changes yet."})}function Hi(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 Gi(t){return`${`${t.target.kind[0].toUpperCase()}${t.target.kind.slice(1)}`} ${t.operation==="improve"?"improvement":"creation"}`}function Wi(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 Ji({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:Qi(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(Ue,{label:"Correlation",value:r.correlationId}),e.jsx(Ue,{label:"Task",value:r.taskId}),e.jsx(Ue,{label:"Policy",value:r.policy.modelId}),e.jsx(Ue,{label:"Checkpoint",value:r.policy.checkpointId??"Provider initial policy"}),e.jsx(Ue,{label:"Environment",value:`${r.environment.id}@${r.environment.version}`}),e.jsx(Ue,{label:"World",value:`${r.environment.worldId} · ${r.environment.worldHash}`}),e.jsx(Ue,{label:"Raw reward",value:r.reward.raw==null?"Not eligible":String(r.reward.raw)}),e.jsx(Ue,{label:"Components",value:JSON.stringify(r.reward.components)}),e.jsx(Ue,{label:"Outcome",value:r.verifier?.outcome??r.failureClass??"Pending"}),e.jsx(Ue,{label:"Trace",value:`${r.providerTrace.experimentId}/${r.providerTrace.rolloutId}`})]})]},r.id))]})}function Ue({label:t,value:n}){return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsx("dd",{children:n})]})}function Qi(t){return t.replace(/^lineage_/,"").slice(0,18)}function Xi({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(Pt,{label:"Base score",value:Xn(s.base.meanScore)}),e.jsx(Pt,{label:"Trained score",value:Xn(s.trained.meanScore)}),e.jsx(Pt,{label:"Score change",value:er(s.meanScoreDelta)}),e.jsx(Pt,{label:"Trained pass rate",value:Zi(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(Yi,{input:a.input,baseOutput:a.baseOutput,trainedOutput:a.trainedOutput,baseGrade:a.baseGrade,trainedGrade:a.trainedGrade})]})}),e.jsx("td",{children:Yn(a.baseGrade)}),e.jsx("td",{children:Yn(a.trainedGrade)}),e.jsx("td",{children:tr(a.baseGrade,a.trainedGrade)})]},a.taskId))})]})})]}):e.jsx("div",{className:"training-run-placeholder",children:"No scored evaluation results are available for this run."})}function Yi({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 Pt({label:t,value:n}){return e.jsxs("div",{children:[e.jsx("span",{children:t}),e.jsx("strong",{children:n})]})}function Xn(t){return t==null?"Not recorded":t.toFixed(3)}function Zi(t){return t==null?"Not recorded":`${Math.round(t*100)}%`}function er(t){return t==null?"Not comparable":`${t>=0?"+":""}${t.toFixed(3)}`}function Yn(t){return t?.status==="unavailable"?"Unavailable":t?.score==null?"Not scored":t.score.toFixed(3)}function tr(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 Zn=[{key:"loss",label:"Loss",format:Ve},{key:"reward",label:"Reward",format:Ve},{key:"policyLoss",label:"Policy loss",format:Ve},{key:"advantageLoss",label:"Advantage loss",format:Ve},{key:"learningRate",label:"Learning rate",format:dr},{key:"gradientNorm",label:"Gradient norm",format:Ve},{key:"meanTokenAccuracy",label:"Token accuracy",format:cr},{key:"entropy",label:"Entropy",format:Ve},{key:"memoryBytes",label:"Memory",format:Ss}];function nr({detail:t,loading:n,error:s}){Qe(s,{prefix:"Training metrics"});const a=c.useMemo(()=>lr(t?.stepMetrics??[]),[t?.stepMetrics]),i=c.useMemo(()=>Zn.filter(b=>a.some(k=>k[b.key]!=null)),[a]),[r,l]=c.useState("loss"),o=i.find(b=>b.key===r)??i[0]??Zn[0],u=a.flatMap(b=>b[o.key]==null?[]:[{step:b.step,value:b[o.key]}]),h=t?ar(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",p=a.flatMap(b=>b.reward==null?[]:[b.reward]),m=a.flatMap(b=>b.loss==null?[]:[b.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?rr(t,a):h.steps??ir(a)}),d?e.jsxs(e.Fragment,{children:[e.jsx(nt,{label:"Latest reward",value:p.length?Ve(p.at(-1)):null}),e.jsx(nt,{label:"Best reward",value:p.length?Ve(Math.max(...p)):null}),e.jsx(nt,{label:"Recorded points",value:p.length||null})]}):e.jsxs(e.Fragment,{children:[e.jsx(nt,{label:"Final loss",value:h.trainLoss==null?m.at(-1)==null?null:Ve(m.at(-1)):Ve(h.trainLoss)}),e.jsx(nt,{label:"Peak memory",value:or(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(b=>e.jsx("button",{type:"button",role:"tab","aria-selected":b.key===o.key,className:b.key===o.key?"active":"",onClick:()=>l(b.key),children:b.label},b.key))}),e.jsx(sr,{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 sr({label:t,points:n,format:s}){const r={top:20,right:20,bottom:58,left:64},l=n.map(N=>N.value),o=Math.min(...l),u=Math.max(...l),h=u-o||Math.max(Math.abs(u)*.1,1e-9),d=o-h*.08,p=u+h*.08,m=n[0]?.step??0,b=n.at(-1)?.step??m+1,k=Math.max(1,b-m),w=N=>r.left+(N-m)/k*(760-r.left-r.right),j=N=>r.top+(p-N)/(p-d)*(270-r.top-r.bottom),v=n.map((N,S)=>`${S?"L":"M"}${w(N.step).toFixed(2)},${j(N.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(N=>{const S=r.top+N*(270-r.top-r.bottom),y=p-N*(p-d);return e.jsxs("g",{children:[e.jsx("line",{className:"training-chart-grid",x1:r.left,x2:760-r.right,y1:S,y2:S}),e.jsx("text",{className:"training-chart-label",x:r.left-10,y:S+4,textAnchor:"end",children:s(y)})]},N)}),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:v}),n.map(N=>e.jsx("circle",{className:"training-chart-point",cx:w(N.step),cy:j(N.value),r:"3",children:e.jsx("title",{children:`Step ${N.step}: ${s(N.value)}`})},`${N.step}-${N.value}`)),e.jsx("text",{className:"training-chart-label",x:r.left,y:236,textAnchor:"middle",children:m}),e.jsx("text",{className:"training-chart-label",x:760-r.right,y:236,textAnchor:"middle",children:b}),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 ar(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 ir(t){const n=t.at(-1);return n?`${n.step} of ${n.maxSteps}`:null}function rr(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 lr(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 or(t){const n=t.flatMap(s=>s.memoryBytes==null?[]:[s.memoryBytes]);return n.length?Ss(Math.max(...n)):null}function Ve(t){return new Intl.NumberFormat(void 0,{maximumFractionDigits:4}).format(t)}function dr(t){return t===0?"0":t.toExponential(2)}function cr(t){return`${(t*100).toFixed(1)}%`}function Ss(t){return`${(t/1024**3).toFixed(2)} GB`}const ur=new Set(["queued","starting","running","cancelling","reconciling"]);function hr(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 st.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||!ur.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 Sn(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 Cs(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 ut(t,n,s){if(!s)return[];const a=Ct(t,n,s),i=new Map(a.map(d=>[d.id,d])),r=Sn(t,n,s),l=new Map(r.map(d=>[d.id,d])),o=ws(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,p)=>d.importedAt.localeCompare(p.importedAt)).map((d,p)=>{const m=l.get(d.jobId)??null;return{lineage:d,number:p+1,job:m,plan:m?i.get(m.planId)??null:null,taskset:s.tasksets.find(b=>b.id===d.tasksetId)??null,current:o?.modelArtifactLineageId===d.id}}).sort((d,p)=>p.number-d.number)}function ws(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 pr({workproduct:t,runs:n,training:s,onOpenDataset:a,onOpenEntry:i,onToast:r}){const l=s.payload,o=c.useMemo(()=>Sn(t,n,l),[n,l,t]),u=c.useMemo(()=>ut(t,n,l),[n,l,t]),h=c.useMemo(()=>Cs(t,n,l),[n,l,t]),d=c.useMemo(()=>Ct(t,n,l),[n,l,t]),p=c.useMemo(()=>new Map(d.map(j=>[j.id,j])),[d]),m=c.useMemo(()=>Is(o,u,h),[h,o,u]),b=ws(t,n,l);async function k(j){const v=u.find(S=>S.lineage.id===j);if(!v?.lineage.promotable||!window.confirm(`Set Version ${v.number} as active for ${t.name}?`))return;const N=await s.actions.bindModel(v.lineage.id,"chat_manual",t.id);r(N?`Version ${v.number} is now active.`:"The active Version could not be changed.",N?"success":"error")}async function w(j,v){const N=await s.actions.setModelPinned(j,v);r(N?v?"Version pinned.":"Version unpinned.":"Version pin could not be changed.",N?"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:[m.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."})})}),m.map(j=>{const v=j.baselineRun,N=j.version?.plan??(j.job?p.get(j.job.planId)??null:null),S=j.version?.taskset??l?.tasksets.find(E=>E.id===(v?.tasksetId??N?.tasksetId))??null,y=j.version,M=y&&b?.modelArtifactLineageId===y.lineage.id;return e.jsxs("tr",{onClick:()=>i(j.key),children:[e.jsx("td",{children:e.jsxs("button",{className:"labs-version-row-button",type:"button",onClick:()=>i(j.key),children:[e.jsx("strong",{children:y?`Version ${y.number}`:"No output"}),e.jsx("small",{children:vr(y?.lineage.id??j.job?.id??v?.id??j.key)})]})}),e.jsx("td",{children:v?v.configuration.split==="train"?"Train-signal check":"Base-model check":at(N?.recipe.method)}),e.jsx("td",{children:S?e.jsx("button",{className:"labs-version-dataset-link",type:"button",onClick:E=>{E.stopPropagation(),a(S.id)},children:S.name}):"Unavailable"}),e.jsx("td",{children:e.jsx(Se,{label:v?Rs(v):j.job?Nn(j.job.status):"Imported",value:v?.status??j.job?.status??"completed"})}),e.jsx("td",{children:v?e.jsx(gr,{run:v}):e.jsx(fr,{version:y})}),e.jsx("td",{children:e.jsx(xr,{version:y})}),e.jsx("td",{children:Ht(y?.lineage.importedAt??v?.updatedAt??j.job?.updatedAt??"")}),e.jsx("td",{children:v&&kn(v)?e.jsx("button",{className:"training-button secondary",type:"button",onClick:E=>{E.stopPropagation(),s.actions.cancelBaselineRun(v.id)},children:"Cancel"}):y?e.jsxs("div",{className:"training-table-actions",children:[e.jsx("button",{"aria-pressed":y.lineage.pinned||!!M,className:"labs-version-icon-button",disabled:!!M,title:M?"The active Version stays pinned":y.lineage.pinned?"Unpin Version":"Pin Version",type:"button",onClick:E=>{E.stopPropagation(),w(y.lineage.id,!y.lineage.pinned)},children:e.jsx(ca,{size:14})}),y.current?null:e.jsx("button",{className:"training-button secondary",disabled:!y.lineage.promotable,type:"button",onClick:E=>{E.stopPropagation(),k(y.lineage.id)},children:"Activate"}),e.jsx("button",{"aria-label":`Download Version ${y.number}`,className:"labs-version-icon-button",type:"button",onClick:E=>{E.stopPropagation(),s.actions.downloadModelPackage(y.lineage.id)},children:e.jsx(yn,{size:14})})]}):null})]},j.key)})]})]})})})}function mr({connection:t,selectedEntryKey:n,workproduct:s,runs:a,training:i,onBack:r,onOpenDataset:l,onUseVersion:o}){const u=i.payload,h=c.useMemo(()=>Sn(s,a,u),[a,u,s]),d=c.useMemo(()=>ut(s,a,u),[a,u,s]),p=c.useMemo(()=>Cs(s,a,u),[a,u,s]),m=c.useMemo(()=>Ct(s,a,u),[a,u,s]),b=c.useMemo(()=>new Map(m.map($=>[$.id,$])),[m]),w=c.useMemo(()=>Is(h,d,p),[p,h,d]).find($=>$.key===n)??null,j=w?.job??null,v=w?.version??null,N=w?.baselineRun??null,S=v?.plan??(j?b.get(j.planId)??null:null),y=v?.taskset??u?.tasksets.find($=>$.id===(N?.tasksetId??S?.tasksetId))??null,M=hr(t,j?.id??null,j?.status??null),E=j?u?.rolloutReceipts.filter($=>$.jobId===j.id)??[]:[];return w?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(de,{title:N?N.configuration.split==="train"?"Train-signal check":"Base-model check":v?`Version ${v.number}`:`${at(S?.recipe.method)} attempt`,actions:N&&kn(N)?e.jsx("button",{className:"training-button secondary",type:"button",onClick:()=>{i.actions.cancelBaselineRun(N.id)},children:"Cancel check"}):v?e.jsxs("div",{className:"training-table-actions",children:[y?e.jsxs("button",{className:"training-button secondary",disabled:!v.lineage.promotable,title:v.lineage.promotable?"Chat with this Version":"Chat is unavailable because this Version did not pass evaluation.",type:"button",onClick:()=>o(v.lineage.id),children:[e.jsx(zt,{size:14}),"Chat"]}):null,e.jsxs("button",{className:"training-button secondary",type:"button",onClick:()=>{i.actions.downloadModelPackage(v.lineage.id)},children:[e.jsx(yn,{size:14}),"Download LoRA"]})]}):null,children:[e.jsxs("dl",{className:"labs-inline-facts",children:[e.jsx(Re,{label:N?"Check status":"Training status",value:N?Rs(N):j?Nn(j.status):"Imported"}),e.jsx(Re,{label:"Version status",value:v?v.current?"Active":"Available":"Not created"}),e.jsx(Re,{label:"Training",value:N?"RFT readiness check":at(S?.recipe.method)}),e.jsx(Re,{label:"Base model",value:N?jr(N.configuration.model.modelId):br(S)}),e.jsx(Re,{label:"Dataset",value:y?.name??"Unavailable"}),e.jsx(Re,{label:"Compute",value:N?"Fireworks":S?_n(S.destinationId):j?_n(j.destinationId):"Not recorded"}),e.jsx(Re,{label:"Duration",value:N?Tn(N.startedAt,N.completedAt):j?Tn(j.startedAt,j.completedAt):"Not recorded"}),e.jsx(Re,{label:"Output",value:v?`Version ${v.number}`:N?.reportId?"Check report":"No Version"})]}),y?e.jsxs("button",{className:"labs-version-dataset-link labs-version-detail-dataset",type:"button",onClick:()=>l(y.id),children:["Open ",y.name]}):null,N?.error||j?.error?e.jsx("p",{className:"labs-training-error",children:N?.error??j?.error}):null]}),j?e.jsxs(e.Fragment,{children:[e.jsx(de,{title:S?.recipe.method==="grpo"?"Rollout scores":"Training metrics",children:e.jsx(nr,{detail:M.detail,error:M.error,loading:M.loading})}),e.jsx(de,{title:"Evaluation",children:e.jsx(Xi,{detail:M.detail,loading:M.loading})}),S?.recipe.method==="grpo"?e.jsx(de,{title:"Rollout traces",children:e.jsx(Ji,{receipts:E})}):null]}):null,e.jsx(de,{title:"Configuration",children:e.jsxs("dl",{className:"training-configuration-list",children:[e.jsx(Re,{label:N?"Check run":"Training attempt",value:N?.id??j?.id??"Provider import"}),e.jsx(Re,{label:"Dataset",value:y?.name??"Unavailable"}),e.jsx(Re,{label:N?"Selection":"Prepared data",value:N?`${N.configuration.taskLimit} prompts × ${N.configuration.attemptsPerTask} attempts`:j?.bundleHash??"Provider managed"}),e.jsx(Re,{label:N?"Provider deployment":"Version ID",value:N?N.provider?.deploymentId??"Not provisioned":v?.lineage.id??"No Version created"}),N?e.jsx(Re,{label:"Attempt progress",value:`${N.progress.completedAttempts} of ${N.progress.totalAttempts}`}):null,N?.provider?.statusCode?e.jsx(Re,{label:"Provider status",value:N.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 Is(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)=>es(o).localeCompare(es(l)))}function es(t){return t.version?.lineage.importedAt??t.baselineRun?.updatedAt??t.job?.updatedAt??t.job?.createdAt??""}function Rs(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 kn(t){return["queued","preparing","running","cancelling"].includes(t.status)}function gr({run:t}){const n=`${t.progress.completedAttempts} / ${t.progress.totalAttempts}`,s=t.reportId?"Recorded":t.progress.completedAttempts?n:"No attempts";return e.jsx(Se,{label:s,value:t.reportId?"passed":kn(t)?"running":t.status})}function fr({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(Se,{label:n,value:s})}function xr({version:t}){return e.jsx(Se,{label:t?t.current?"Active":"Available":"Not created",value:t?t.current?"current":"ready":"not_run"})}function br(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 jr(t){return t.split("/").at(-1)??t}function vr(t){return t.replace(/^baseline_run_/,"").replace(/^(?:training_job_|lineage_)(?:fireworks_)?(?:artifact_)?/,"").slice(0,12)}function Re({label:t,value:n}){return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsx("dd",{children:n})]})}function yr({state:t,initialTasksetId:n,checking:s,onClose:a,onCheck:i,onContinue:r,onReview:l}){const o=c.useMemo(()=>(t?.tasksets??[]).sort((m,b)=>m.id===n?-1:b.id===n?1:b.updatedAt.localeCompare(m.updatedAt)),[n,t?.tasksets]),[u,h]=c.useState(n&&o.some(m=>m.id===n)?n:o[0]?.id??""),d=o.find(m=>m.id===u)??null,p=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:m=>h(m.target.value),children:o.map(m=>e.jsxs("option",{value:m.id,children:[m.name," · revision ",m.revision,m.readiness?.ready?"":" · needs review"]},m.id))})]}),d?e.jsxs("dl",{className:"labs-inline-facts labs-new-version-dataset-facts",children:[e.jsx(Dt,{label:"Training",value:String(rn(d,"train"))}),e.jsx(Dt,{label:"Validation",value:String(rn(d,"validation"))}),e.jsx(Dt,{label:"Frozen Eval",value:String(rn(d,"frozen_eval"))}),e.jsx(Dt,{label:"Graders",value:String(d.graders.length)})]}):e.jsx("div",{className:"training-run-placeholder",children:"No Dataset is available. Create a Dataset first."}),d&&!p?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:!p,type:"button",onClick:()=>{p&&d&&r({taskset:d})},children:"Configure training"})]})]})}function rn(t,n){return t.datasetArtifact?t.datasetArtifact.splitCounts[n]??0:t.tasks.filter(s=>s.split===n).length}function Dt({label:t,value:n}){return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsx("dd",{children:n})]})}function Nr({run:t,onAnswerQuestion:n,onApplyCandidate:s,onApprove:a,onCancel:i,onOpenPullRequest:r,onPause:l,onOpenConversation:o,onReconcilePullRequest:u,onRejectCandidate:h,onRetry:d,onResume:p,onRevise:m}){const b=t.state==="blocked"?"Review blocker":t.state==="failed"?"Review failure":"View progress",k=t.target.kind==="agent"&&["blocked","failed","cancelled"].includes(t.state);return e.jsxs("div",{className:"labs-run-decision",children:[e.jsx(ba,{runtime:{run:t,onAnswerQuestion:n,onApplyCandidate:s,onApprove:a,onCancel:i,onOpenPullRequest:r,onPause:l,onReconcilePullRequest:u,onRejectCandidate:h,onResume:p,onRevise:m}}),t.scope.conversationId||k?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:b}):null,k?e.jsx("button",{className:"training-button",type:"button",onClick:d,children:"Try again"}):null]}):null]})}function Sr({run:t,showOutcomes:n=!0}){const{completedTasks:s,currentTask:a,totalTasks:i}=t.progress,r=a?`${ts(a.family)} · ${a.worldId}`:t.progress.stage==="complete"?"Baseline complete":ts(t.progress.stage);return e.jsxs("div",{className:"labs-training-run-progress-wrap","aria-live":Cr(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 kr(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 Cr(t){return["queued","running","cancelling"].includes(t.status)}function ts(t){return t.replaceAll("_"," ").replace(/\b\w/g,n=>n.toUpperCase())}const wr=new Set(["released","rejected","ready","ready_local","published_hosted","blocked","failed","cancelled"]),As=new Set(["queued","starting","running","cancelling","reconciling"]);function Ms(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=>!wr.has(i.state))??null;if(t.workproduct.kind==="model"&&t.taskset){const i=xs(t.training,t.taskset.id)[0]??null;if(i&&As.has(i.status))return ns({taskset:t.taskset,training:t.training,latestRun:n,fallbackStatus:t.workproduct.status})}if(s)return ln(s);if(a)return ln(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?Ir(i):!t.taskset&&n&&["failed","blocked","cancelled"].includes(n.state)?ln(n):ns({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 Ir(t){return{statusLabel:kr(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 ln(t){const n={statusLabel:Rr(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 ns(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=xs(t.training,t.taskset.id)[0]??null,i=t.training?.models.find(l=>l.tasksetId===t.taskset.id&&l.status==="imported")??null;if(a&&As.has(a.status))return{statusLabel:Nn(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 Rr(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 ss={chat_manual:"Default chat model",agent:"Agent runtime",extension:"Extension runtime",authoring_optimizer:"Authoring / optimizer"};function Ar({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,p]=c.useState(""),m=c.useMemo(()=>n?.modelBindings.find(C=>C.status==="active"&&C.role===i&&C.roleTargetId===l.trim())??null,[i,l,n?.modelBindings]),b=m?n?.models.find(C=>C.id===m.modelArtifactLineageId)??null:null,w=(t?.frozenEvaluationArtifactId?n?.artifacts.find(C=>C.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 j=t,v=!!s.busyAction,N=j.status==="imported"&&j.promotable&&!!l.trim(),S=m?.modelArtifactLineageId===j.id;async function y(){const C=await s.actions.bindModel(j.id,i,l.trim());h(null),a(C?"Model binding activated.":"Couldn’t activate Model binding.",C?"success":"error")}async function M(){const C=d.trim();if(!C)return;const x=await s.actions.rejectModel(j.id,C);h(null),a(x?"Model candidate rejected.":"Couldn’t reject Model candidate.",x?"success":"error")}async function E(){const C=await s.actions.evaluateJob(j.jobId);h(null),a(C?"Frozen evaluation completed.":"Couldn’t complete frozen evaluation.",C?"success":"error")}async function $(){if(!m)return;const C=await s.actions.rollbackModelBinding(m.id);a(C?"Model binding rolled back.":"Couldn’t roll back Model binding.",C?"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:b?on(b.id):"No active binding"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Rollback target"}),e.jsx("strong",{children:m?.rollbackTargetBindingId?on(m.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:C=>{const x=C.target.value;r(x),o(x==="chat_manual"?"default":"")},children:Object.entries(ss).map(([C,x])=>e.jsx("option",{value:C,children:x},C))})]}),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:C=>o(C.target.value)})]}),e.jsxs("div",{className:"training-promotion-actions",children:[w?e.jsx("button",{className:"training-button secondary",type:"button",disabled:v,onClick:()=>h("evaluate"),children:"Run evaluation"}):null,S?e.jsx("button",{className:"training-button secondary",type:"button",disabled:v,onClick:()=>{$()},children:"Roll back"}):e.jsx("button",{className:"training-button",type:"button",disabled:v||!N,onClick:()=>h("bind"),children:m?"Replace binding":"Bind model"}),e.jsx("button",{className:"training-button danger",type:"button",disabled:v||t.status==="rejected"||S,onClick:()=>h("reject"),children:"Reject"})]})]}),t.promotable?null:e.jsx("p",{className:"training-promotion-note",children:w?"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:()=>!v&&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:C=>C.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"?`${ss[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:m?`The current binding ${on(m.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:C=>p(C.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:v,onClick:()=>h(null),children:"Cancel"}),e.jsx("button",{className:`training-button ${u==="reject"?"danger":""}`,type:"button",disabled:v||u==="reject"&&!d.trim(),onClick:()=>{u==="bind"?y():u==="evaluate"?E():M()},children:v?"Applying…":u==="bind"?"Activate binding":u==="evaluate"?"Run evaluation":"Reject candidate"})]})]})}):null]})}function on(t){return t.replace(/^lineage_/,"").replace(/^model_binding_/,"").slice(0,16)}function Mr(t){for(const n of t){const s=ua.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 _r(t){return[...t.candidates].reverse().find(n=>!!n.git?.headCommit)??null}function Tr(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 Er({workproduct:t,profile:n}){if(t.kind==="agent"){const s=n?.agents.find(a=>a.id===t.id)??null;return e.jsx(de,{title:"Agent",children:e.jsxs("dl",{className:"training-configuration-list",children:[e.jsx(Ne,{label:"Enabled",value:s?.enabled?"Yes":"No"}),e.jsx(Ne,{label:"Source",value:s?.path??t.path??"Draft"}),e.jsx(Ne,{label:"Default action",value:`${t.id}.chat`}),e.jsx(Ne,{label:"Profile checks",value:n?.lastCheck?.status??"Not run"})]})})}if(t.kind==="skill"){const s=t.skillSource==="codex"?null:n?.skills.find(l=>l.name===t.id)??null,a=t.skillValidationStatus??s?.validationStatus??"error",i=t.skillValidationMessages??s?.validationMessages??[],r=t.skillResourceFiles??[];return e.jsxs(de,{title:"Skill",children:[e.jsxs("dl",{className:"training-configuration-list",children:[e.jsx(Ne,{label:"Scope",value:t.skillSource==="codex"?"Codex personal":"OpenPond profile"}),e.jsx(Ne,{label:"Enabled",value:t.enabled?"Yes":"No"}),e.jsx(Ne,{label:"Validation",value:a}),e.jsx(Ne,{label:"Source",value:t.path??"Not available"}),e.jsx(Ne,{label:"Source hash",value:t.skillSourceHash??s?.sourceHash??"Not available"}),e.jsx(Ne,{label:"Characters",value:String(t.skillCharCount??s?.charCount??"Not available")}),t.skillSource==="codex"?e.jsx(Ne,{label:"Packaged resources",value:String(r.length)}):null]}),r.length?e.jsxs("div",{className:"labs-source-evals",children:[e.jsx("strong",{children:"Packaged resources"}),e.jsx("ul",{children:r.map(l=>e.jsx("li",{children:e.jsx("code",{children:l})},l))})]}):null,i.length?e.jsx("ul",{className:"labs-validation-list",children:i.map(l=>e.jsx("li",{children:l},l))}):null]})}return t.kind==="extension"?e.jsx(de,{title:"Extension",children:e.jsx("div",{className:"training-run-placeholder",children:"Runtime bindings arrive with the Extension phase."})}):null}function Pr({runs:t,selectedRun:n,onSelectedRunIdChange:s}){return e.jsx(de,{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:Gt(a.id)}),e.jsx("td",{children:a.operation}),e.jsx("td",{children:e.jsx(Se,{label:a.state.replaceAll("_"," "),value:a.state})}),e.jsx("td",{children:a.revision}),e.jsx("td",{children:Ht(a.updatedAt)})]},a.id))})]})}):e.jsx("div",{className:"training-run-placeholder",children:"No Create/Improve activity yet."})})}function Dr({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:Gt(o.id)}),e.jsx("td",{children:e.jsx(Se,{label:o.status})}),e.jsx("td",{children:o.evalRefs.length}),e.jsx("td",{children:l?$r(o):o.summary??"No summary"})]},o.id))})]})})]}):null]})}function $r(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 Br({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,p)=>p.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(Ge,{label:"Create/Improve runs",value:String(t.length)}),e.jsx(Ge,{label:"Candidates",value:String(n?.candidates.length??0)}),e.jsx(Ge,{label:"Profile commit",value:n?.localProfileCommit??"Not released"}),e.jsx(Ge,{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,p)=>{const m=o.get(d.jobId),b=m?u.get(m.planId):null,k=h.get(d.artifactId)??null,w=k?Lr(k.path):null;return e.jsxs("tr",{children:[e.jsxs("td",{className:"labs-version-name",children:[e.jsx("strong",{children:p===0?"Latest":`Prior ${p}`}),e.jsx("small",{children:Gt(d.id)})]}),e.jsx("td",{children:at(b?.recipe.method)}),e.jsxs("td",{className:"labs-version-storage",children:[e.jsx("strong",{children:w?"Saved locally":"Unavailable"}),w?e.jsx("code",{title:k?.path,children:w}):null]}),e.jsx("td",{children:d.promotable?"Passed":d.frozenEvaluationArtifactId?"Failed":"Not run"}),e.jsx("td",{children:Ht(d.importedAt)}),e.jsx("td",{children:e.jsxs("button",{className:"training-button secondary",type:"button",onClick:()=>{a.actions.downloadModelPackage(d.id)},children:[e.jsx(yn,{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(Ar,{lineage:l[0],state:i,training:a,onToast:r})]}):null]})}function Lr(t){return t.replace(/[/\\][^/\\]+$/,"").replace(/^\/home\/[^/]+/,"~")}function Ge({label:t,value:n}){return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsx("dd",{children:n})]})}function Ne({label:t,value:n}){return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsx("dd",{children:n})]})}function Gt(t){return t.replace(/^(create_improve|training_job|agent_candidate|model_candidate)_/,"").slice(0,14)}function _s(t){return t&&`${t[0].toUpperCase()}${t.slice(1).replaceAll("_"," ")}`}function Or(t,n,s,a=!1){return t==="changes"?n?["Changes",s?`Change ${s.slice(0,8)}`:`Change ${Gt(n)}`]:["Changes"]:[_s(t)]}function Fr(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 zr(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 qr({workproduct:t,runs:n,profile:s,training:a,connection:i,onOpenConversation:r,onLocationChange:l,onRenameAgent:o,onStartAgentChange:u,onOpenDataset:h,onOpenProviderSettings:d,onToast:p,onAnswerQuestion:m,candidateReview:b,onApprove:k,onCancel:w,onChatWithModel:j,onApplyCandidate:v,onCandidateReviewChange:N,onOpenCandidateFiles:S,onOpenPullRequest:y,onPause:M,onReconcilePullRequest:E,onRejectCandidate:$,onResume:C,onRevise:x}){const D=c.useMemo(()=>ys(t,n),[n,t]),[ae,P]=c.useState(D[0]?.id??""),[F,G]=c.useState(null),[T,I]=c.useState("overview"),[O,z]=c.useState(null),[ce,ie]=c.useState(!1),[re,K]=c.useState(null),[ue,Q]=c.useState(null),se=ue?a.payload?.tasksets.find(A=>A.id===ue.id)??ue:null,le=D.find(A=>A.id===ae)??D[0]??null,Y=F?D.find(A=>A.id===F)??null:null,ne=Y?_r(Y):null,ke=Di(t.kind),he=ne?.git?.headCommit??null,Ce=c.useMemo(()=>t.kind==="model"?O?["Version details"]:[]:Or(T,F,he,t.kind==="agent"),[T,he,F,O,t.kind]),H=t.tasksetId?a.payload?.tasksets.find(A=>A.id===t.tasksetId)??null:null,Le=t.kind==="agent"?s?.agents.some(A=>A.id===t.id)??!1:!1,U=Ms({workproduct:t,runs:D,taskset:H,training:a.payload}),oe=U.runId??D[0]?.id??"",pe=D.some(A=>A.id===ae),fe=F?D.some(A=>A.id===F):!0,xe=[["overview","Overview"],["changes","Changes"],["evals","Evals"],["versions","Versions"],["configuration","Configuration"]];c.useEffect(()=>{N(null),P(oe),G(null),z(null),I("overview")},[t.key]),c.useEffect(()=>{ae&&pe||P(oe)},[oe,pe,ae]),c.useEffect(()=>{fe||G(null)},[fe]),c.useEffect(()=>{if(T==="changes"&&Y&&ne){const A=Fr(t,s,ne);N({run:Y,candidate:ne,fileRootPath:A.fileRootPath,initialPath:A.initialPath});return}N(null)},[T,N,s,ne,Y,t]),c.useEffect(()=>{l({kind:t.kind,kindLabel:ke,workproductLabel:t.name,sectionLabels:Ce})},[ke,Ce,l,t.kind,t.name]),c.useEffect(()=>()=>N(null),[N]);function _e(A){const J=ut(t,n,a.payload).find(V=>V.lineage.id===A);if(J?.taskset){if(J.job?.destinationId==="fireworks"){K(A);return}j(Ut({modelId:A,taskset:J.taskset}))}}async function je(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(xn,{label:U.statusLabel,value:U.statusValue})]})}),t.kind==="model"?e.jsx("div",{className:"labs-workproduct-header-actions",children:e.jsx("button",{className:"training-button",type:"button",onClick:()=>ie(!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"}),Le?e.jsxs("button",{className:"settings-secondary compact",type:"button",onClick:o,children:[e.jsx(hn,{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:xe.map(([A,J])=>e.jsxs("button",{className:T===A?"active":void 0,"aria-selected":T===A,role:"tab",type:"button",onClick:()=>{I(A),A==="changes"&&G(null)},children:[J,A==="changes"?e.jsx(xn,{decorative:!0,label:zr(D[0]??null),size:"small",tone:Tr(D[0]??null)}):null]},A))}):null,e.jsx("div",{className:"training-detail-sections",children:t.kind==="model"?O?e.jsx(mr,{connection:i,runs:n,selectedEntryKey:O,training:a,workproduct:t,onBack:()=>z(null),onOpenDataset:h,onUseVersion:_e}):e.jsx(pr,{runs:n,training:a,workproduct:t,onOpenDataset:h,onOpenEntry:z,onToast:p}):T==="overview"?e.jsxs(de,{title:"Overview",children:[e.jsxs("dl",{className:"labs-inline-facts",children:[e.jsx(Ge,{label:"Type",value:_s(t.kind)}),e.jsx(Ge,{label:"Status",value:U.statusLabel}),t.kind==="agent"?e.jsx(Ge,{label:"Profile",value:"Saved in your Profile"}):e.jsxs(e.Fragment,{children:[e.jsx(Ge,{label:"ID",value:t.id}),e.jsx(Ge,{label:"Path",value:t.path??"Managed artifact"})]})]}),e.jsx("p",{className:"labs-detail-copy",children:t.description})]}):T==="changes"&&!Y?e.jsx("div",{className:"labs-change-index",children:e.jsx(Ki,{runs:D,onReview:A=>{P(A.id),G(A.id)}})}):T==="changes"&&Y&&ne?e.jsx(qi,{candidate:ne,diff:b.diff,error:b.error,run:Y,onApplyCandidate:(A,J)=>v({run:A},J),onOpenFiles:S,onRejectCandidate:(A,J)=>$({run:A},J)}):T==="changes"&&Y?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(Se,{label:Y.state.replaceAll("_"," "),value:Y.state})]}),e.jsx("div",{className:"labs-change-card-body",children:e.jsx("h3",{children:Y.objective})})]}),e.jsx(Nr,{run:Y,onAnswerQuestion:m,onApplyCandidate:v,onApprove:k,onCancel:w,onOpenConversation:r,onOpenPullRequest:y,onPause:M,onReconcilePullRequest:E,onRejectCandidate:$,onResume:C,onRetry:()=>u(t.id,Y.objective),onRevise:x})]}):T==="evals"?e.jsx(de,{title:"Evals",actions:t.kind==="agent"?e.jsx(zi,{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(Dr,{profileEvals:s?.evals??[],run:le,workproduct:t})}):T==="versions"?e.jsxs(e.Fragment,{children:[e.jsx(de,{title:"Versions",children:e.jsx(Br,{runs:D,selectedRun:le,taskset:H,training:a,trainingState:a.payload,onToast:p})}),e.jsx(Pr,{runs:D,selectedRun:le,onSelectedRunIdChange:P})]}):e.jsxs(e.Fragment,{children:[e.jsx(de,{title:"Connections",children:e.jsxs("dl",{className:"training-configuration-list",children:[e.jsx(Ne,{label:"Profile",value:s?.activeProfile??"default"}),e.jsx(Ne,{label:"Conversation",value:le?.scope.conversationId??"Not linked"}),e.jsx(Ne,{label:"Project",value:le?.scope.projectId??"Not linked"}),e.jsx(Ne,{label:"Source authority",value:le?.adapter.sourceAuthority??"Profile"})]})}),e.jsx(Er,{workproduct:t,profile:s})]})}),ce?e.jsx(yr,{checking:["audit-graders","readiness"].includes(a.busyAction??""),initialTasksetId:H?.id??null,state:a.payload,onClose:()=>ie(!1),onCheck:je,onContinue:({taskset:A})=>{ie(!1),Q(A)},onReview:A=>h(A)}):null,se?e.jsx(yi,{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:Mr(D),taskset:se,baselineReports:a.payload?.baselineReports.filter(A=>A.tasksetId===se.id&&A.tasksetHash===se.contentHash)??[],baselineRuns:a.payload?.baselineRuns.filter(A=>A.tasksetId===se.id)??[],onClose:()=>Q(null),onOpenProviderSettings:d,onRunBaseline:async(A,J)=>!!await a.actions.baseline(se.id,A,J),onPrepare:(A,J,V)=>a.actions.prepareTraining({modelId:t.id,tasksetId:se.id,destinationId:A,recipe:J,exportApproved:V.exportApproved,retentionDays:V.retentionDays,region:V.region}),onConfirmPrepared:async(A,J)=>!!await a.actions.startPreparedTraining({planId:A.plan.id,bundleId:A.bundle.id,maximumCostUsd:J}),onStart:async(A,J,V)=>!!await a.actions.startTraining({modelId:t.id,tasksetId:se.id,destinationId:A,recipe:J,...V})}):null,re?(()=>{const A=ut(t,n,a.payload).find(J=>J.lineage.id===re);return A?.taskset?e.jsx(bs,{lineage:A.lineage,taskset:A.taskset,training:a,onChat:j,onClose:()=>K(null)}):null})():null]})}function Ur(t){return t?.kind!=="skill"||!t.skillSource?null:{name:t.name,description:t.description,scope:t.skillSource,packagePath:t.path??t.name,files:["SKILL.md",...new Set(t.skillResourceFiles??[])]}}function Vr({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 p(b){d.current?.contains(b.target)||h(!1)}function m(b){b.key==="Escape"&&h(!1)}return document.addEventListener("pointerdown",p),document.addEventListener("keydown",m),()=>{document.removeEventListener("pointerdown",p),document.removeEventListener("keydown",m)}},[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.jsxs("button",{className:"labs-create-button",type:"button","aria-expanded":u,"aria-haspopup":"menu","aria-label":"Create",title:"Create",onClick:()=>h(p=>!p),children:[e.jsx(vn,{size:13}),e.jsx("span",{children:"Create"})]}),u?e.jsxs("div",{className:"labs-create-menu",role:"menu",children:[t!=="datasets"?e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{h(!1),r()},children:[e.jsx(hs,{size:13}),e.jsxs("span",{children:[e.jsx("strong",{children:"Agent"}),e.jsx("small",{children:"Describe the agent in the shared Create flow."})]})]}),e.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{h(!1),o()},children:[e.jsx(ps,{size:13}),e.jsxs("span",{children:[e.jsx("strong",{children:"Model"}),e.jsx("small",{children:"Build the data and Evals, then choose training."})]})]})]}):null,e.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{h(!1),l()},children:[e.jsx(ht,{size:13}),e.jsxs("span",{children:[e.jsx("strong",{children:"Dataset"}),e.jsx("small",{children:"Create a reusable Taskset without creating a Model."})]})]}),t!=="datasets"?e.jsxs(e.Fragment,{children:[e.jsxs("button",{disabled:!0,type:"button",role:"menuitem",children:[e.jsx(ha,{size:13}),e.jsxs("span",{children:[e.jsx("strong",{children:"Skill"}),e.jsx("small",{children:"Coming soon"})]})]}),e.jsxs("button",{disabled:!0,type:"button",role:"menuitem",children:[e.jsx(pa,{size:13}),e.jsxs("span",{children:[e.jsx("strong",{children:"Extension"}),e.jsx("small",{children:"Coming soon"})]})]})]}):null]}):null]})})]}):null,e.jsx("div",{className:"labs-panel",children:n})]})}function Kr({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," "),p=d===n.trim().replace(/\s+/g," ");c.useEffect(()=>{r(n),o(!1),h(null)},[t,n]);async function m(b){if(b.preventDefault(),!(!d||p||l)){o(!0),h(null);try{await a(d),s()}catch(k){h(k instanceof Error?k.message:String(k))}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(hs,{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:b=>{m(b)},children:[e.jsxs("label",{children:[e.jsx("span",{children:"Display name"}),e.jsx("input",{"data-autofocus":!0,maxLength:80,value:i,onChange:b=>r(b.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||p||l,type:"submit",children:l?"Renaming…":"Rename"})]})]})]})}function Hr({taskset:t,busyAction:n,onPreview:s,onApprove:a,onToast:i}){const[r,l]=c.useState(null),[o,u]=c.useState(!1),h=Wr(t),d=t.learningSignals.demonstrations.filter(w=>w.approved&&w.metadata.exampleOrigin==="expert_authored").length,p=n==="preview-expert-bootstrap",m=n==="approve-expert-bootstrap";async function b(){u(!0);const w=await s();if(w){l(w);return}u(!1),i("Couldn’t load the expert trajectories.","error")}async function k(){if(!r)return;const w=await a(r.previewHash);if(!w){i("The expert trajectories were not approved.","error");return}u(!1),i(`${w.approval.trajectoryCount} expert trajectories approved by ${w.approval.approvedBy}.`,"success")}return e.jsxs(e.Fragment,{children:[e.jsx(de,{title:"SFT bootstrap data",actions:e.jsx("button",{className:"training-button secondary",disabled:p||m,type:"button",onClick:()=>{b()},children:h?"Review trajectories":p?"Loading…":"Review expert trajectories"}),children:e.jsxs("div",{className:"labs-expert-bootstrap-summary",children:[e.jsxs("div",{children:[e.jsx(Se,{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(Gr,{approving:m,loading:p,preview:r,onApprove:()=>{k()},onClose:()=>{m||u(!1)}}):null]})}function Gr({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:Jr(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 Wr(t){const n=as(t.metadata.expertBootstrap),s=as(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 Jr(t){return t.split("_").map(n=>`${n.slice(0,1).toUpperCase()}${n.slice(1)}`).join(" ")}function as(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}const Qr=new Set(["queued","preparing","running","cancelling"]);function Xr({runs:t,taskset:n,onCancel:s}){return e.jsx(de,{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=Qr.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(Se,{label:a.status.replaceAll("_"," "),value:a.status})}),e.jsx("td",{children:Yr(a)}),e.jsx("td",{children:Zr(a)}),e.jsx("td",{children:el(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 Yr(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 Zr(t){return t.provider?t.provider.statusCode?t.provider.statusCode:t.provider.state?t.provider.state:t.provider.phase.replaceAll("_"," "):"Not started"}function el(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 tl=[{id:"train",label:"Training"},{id:"validation",label:"Validation"},{id:"frozen_eval",label:"Frozen Eval"}],dn=10;function nl({artifact:t,tab:n="overview",taskset:s,onOpenFiles:a,training:i}){const r=c.useMemo(()=>t?new Map(Object.entries(t.splitCounts)):pl(s.tasks.map(T=>T.split)),[t,s.tasks]),l=r.get("train")?"train":r.get("validation")?"validation":r.get("frozen_eval")?"frozen_eval":s.tasks[0]?.split??"train",[o,u]=c.useState(l==="test"?"frozen_eval":l),[h,d]=c.useState(!1),[p,m]=c.useState([]),[b,k]=c.useState(null),[w,j]=c.useState([]),[v,N]=c.useState(null),[S,y]=c.useState(!1),[M,E]=c.useState(null),$=c.useMemo(()=>new Map(s.sourceRefs.map(T=>[T.id,T])),[s.sourceRefs]);c.useEffect(()=>{if(n!=="data"||!t)return;let T=!1;return y(!0),E(null),i.actions.datasetRows(s.id,{split:o,cursor:b,limit:25}).then(I=>{T||!I||(m(I.rows.map(O=>ma.parse(O))),N(I.nextCursor))}).catch(I=>{T||(m([]),N(null),E(I instanceof Error?I.message:String(I)))}).finally(()=>{T||y(!1)}),()=>{T=!0}},[t,b,o,n,s.id,i.actions]);const C=t?p:s.tasks.filter(T=>T.split===o),x=h?C:C.slice(0,dn),D=s.sourceRefs.filter(Cn).length,ae=s.sourceRefs.filter(T=>Kt(T)&&T.turnIds.length>0).length,P=s.sourceRefs.filter(T=>T.metadata.containsCustomerData===!0).length,F=s.learningSignals.demonstrations.filter(T=>T.approved).length,G=i.payload?.baselineRuns.filter(T=>T.tasksetId===s.id)??[];return n==="overview"?e.jsxs(de,{title:"Dataset",children:[e.jsx("p",{className:"labs-detail-copy labs-dataset-summary",children:al({syntheticSources:D,chatSources:ae,customerSources:P,sourceCount:s.sourceRefs.length})}),e.jsxs("dl",{className:"labs-inline-facts",children:[e.jsx(Ae,{label:"Training",value:String(r.get("train")??0)}),e.jsx(Ae,{label:"Validation",value:String(r.get("validation")??0)}),e.jsx(Ae,{label:"Frozen Eval",value:String(r.get("frozen_eval")??0)}),e.jsx(Ae,{label:"Approved demonstrations",value:String(F)})]})]}):n==="evals"?e.jsxs(e.Fragment,{children:[e.jsx(Xr,{runs:G,taskset:s,onCancel:i.actions.cancelBaselineRun}),e.jsx(de,{title:"Graders",children:e.jsx("div",{className:"labs-dataset-grader-list",children:s.graders.map(T=>e.jsxs("div",{children:[e.jsx("strong",{children:T.label}),e.jsx("small",{children:kt(T.kind)})]},T.id))})})]}):n==="configuration"?e.jsx(de,{title:"Configuration",actions:e.jsx("button",{className:"training-button secondary",type:"button",onClick:a,children:"Open files"}),children:e.jsxs("dl",{className:"training-configuration-list",children:[e.jsx(Ae,{label:"Dataset ID",value:s.id}),e.jsx(Ae,{label:"Revision",value:String(s.revision)}),e.jsx(Ae,{label:"Format",value:t?.format.toUpperCase()??"Inline Taskset"}),e.jsx(Ae,{label:"Rows",value:String(t?.rowCount??s.tasks.length)}),e.jsx(Ae,{label:"Storage",value:t?ml(t.sizeBytes):"Managed inline"}),e.jsx(Ae,{label:"Availability",value:t?.available===!1?t.unavailableReason??"Unavailable":"Available"}),e.jsx(Ae,{label:"Content hash",value:t?.contentHash??s.contentHash})]})}):e.jsxs(de,{title:"Examples",children:[e.jsx("div",{className:"labs-method-tabs labs-dataset-tabs",role:"tablist","aria-label":"Dataset splits",children:tl.map(T=>e.jsxs("button",{"aria-selected":o===T.id,className:o===T.id?"active":"",role:"tab",type:"button",onClick:()=>{u(T.id),d(!1),k(null),j([])},children:[T.label,e.jsx("span",{children:r.get(T.id)??0})]},T.id))}),e.jsxs("div",{className:"labs-dataset-examples",children:[x.map((T,I)=>e.jsx(sl,{index:I,source:T.sourceRefs.map(O=>$.get(O)).find(Boolean)??null,task:T},T.id)),C.length>dn?e.jsx("button",{className:"training-button secondary labs-dataset-show-all",type:"button",onClick:()=>d(T=>!T),children:h?`Show first ${dn}`:`Show all ${C.length}`}):null,t?e.jsxs("div",{className:"labs-pagination","aria-label":"Dataset example pages",children:[e.jsx("button",{type:"button",disabled:!w.length||S,onClick:()=>{const T=w.at(-1)??null;j(I=>I.slice(0,-1)),k(T||null)},children:"Previous"}),e.jsx("span",{children:S?"Loading…":`${p.length.toLocaleString()} rows on this page`}),e.jsx("button",{type:"button",disabled:!v||S,onClick:()=>{j(T=>[...T,b??""]),k(v)},children:"Next"})]}):null,M?e.jsx("div",{className:"training-banner error",role:"alert",children:M}):null]})]})}function sl({index:t,source:n,task:s}){const a=il(s),i=ll(s),r=rl(s),l=n?cl(n):"Source unavailable",o=ol(s,n),u=dl(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(Se,{label:hl(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"})," — ",ul(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(Ae,{label:"Task",value:s.id}),e.jsx(Ae,{label:"Source",value:n?.id??"Unavailable"}),e.jsx(Ae,{label:"Cluster",value:s.clusterKey})]})]})]})]})}function al(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 il(t){return typeof t.input.prompt=="string"?t.input.prompt:"Untitled dataset example"}function rl(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 ll(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 ol(t,n){const s=n?.metadata.crossSystemOperations;if(s&&typeof s=="object"&&"taskFamily"in s){const i=s.taskFamily;if(typeof i=="string")return kt(i)}const a=t.tags.find(i=>!["synthetic","structured-tool-trajectory"].includes(i));return a?kt(a):null}function dl(t,n){const s=n?.metadata.crossSystemOperations;if(s&&typeof s=="object"&&"worldDifficulty"in s){const a=s.worldDifficulty;if(typeof a=="string")return kt(a)}return t.clusterKey.match(/_(easy|medium|hard)$/)?.[1]??null}function Cn(t){return t.schemaVersion==="openpond.generatedDatasetSource.v1"||t.metadata.syntheticSpecification===!0}function cl(t){return Cn(t)?"Generated scenario":Kt(t)&&t.turnIds.length>0?"Chat":t.schemaVersion==="openpond.huggingFaceDatasetSource.v1"?"Hugging Face":t.schemaVersion==="openpond.uploadedFileDatasetSource.v1"?"Uploaded file":"Imported source"}function ul(t){return t?Cn(t)&&t.metadata.containsCustomerData===!1?"generated locally from a deterministic specification; no customer content is attached.":Kt(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 hl(t){return t==="frozen_eval"?"Frozen Eval":kt(t)}function kt(t){return t.replaceAll("-"," ").replaceAll("_"," ").replace(/\b\w/g,n=>n.toUpperCase())}function pl(t){const n=new Map;for(const s of t)n.set(s,(n.get(s)??0)+1);return n}function ml(t){return t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(1)} KB`:t<1073741824?`${(t/1048576).toFixed(1)} MB`:`${(t/1073741824).toFixed(1)} GB`}function Ae({label:t,value:n}){return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsx("dd",{children:n})]})}const jn=10,gl=[{id:"build",label:"Build"},{id:"overview",label:"Overview"},{id:"data",label:"Data"},{id:"evals",label:"Evals"},{id:"configuration",label:"Configuration"}];function fl({state:t,runs:n,selectedId:s,onSelectedIdChange:a,building:i=!1,buildContent:r=null,onBuild:l,onOpenFiles:o,training:u,onToast:h}){const[d,p]=c.useState(""),[m,b]=c.useState(1),[k,w]=c.useState(()=>i?"build":"overview"),j=t?.tasksets??[],v=j.find(E=>E.id===s)??null,N=v?.datasetArtifact?t?.datasetArtifacts.find(E=>E.tasksetId===s&&E.tasksetRevision===v.revision)??null:null,S=c.useMemo(()=>{const E=d.trim().toLowerCase();return E?j.filter($=>[$.name,$.objective,$.id].some(C=>C.toLowerCase().includes(E))):j},[d,j]),y=S.slice((m-1)*jn,m*jn),M=c.useMemo(()=>{const E=new Map;if(!t)return E;const $=vs({profile:null,training:t,runs:n}).filter(C=>C.kind==="model");for(const C of $)for(const x of ks(C,n,t))E.set(x.id,(E.get(x.id)??0)+1);return E},[n,t]);if(c.useEffect(()=>{w(i?"build":"overview")},[i,s]),v||i){const E=!v;return e.jsxs("div",{className:"labs-flat-body labs-datasets-page",children:[e.jsxs("div",{className:"labs-dataset-detail-heading",children:[i?e.jsx("span",{"aria-hidden":"true",className:"labs-dataset-heading-spacer"}):e.jsx("button",{"aria-label":"Back to Datasets",className:"labs-back-button",type:"button",onClick:()=>a(null),children:e.jsx(qt,{size:15})}),e.jsxs("div",{children:[e.jsx("h1",{children:v?.name??"New Dataset"}),e.jsx("p",{children:v?.objective??"Define the Dataset, review its tasks and Evals, then save an immutable first version."})]}),e.jsx(Se,{label:v?xl(v):"Draft",value:v?.status??"planning"})]}),e.jsx("div",{className:"training-detail-tabs",role:"tablist","aria-label":"Dataset detail",children:gl.map($=>e.jsx("button",{"aria-selected":k===$.id,className:k===$.id?"active":void 0,disabled:E&&$.id!=="build",role:"tab",type:"button",onClick:()=>{w($.id),$.id==="build"&&v&&!i&&l(v.id)},children:$.label},$.id))}),r?e.jsx("div",{hidden:k!=="build",children:r}):k==="build"?e.jsx("div",{className:"training-empty",children:"Preparing the Dataset builder…"}):null,v&&k!=="build"?e.jsx(nl,{artifact:N,tab:k,taskset:v,onOpenFiles:()=>o(v.id),training:u}):null,v&&k==="evals"&&v.metadata.flagship==="cross-system-operations"?e.jsx(Hr,{busyAction:u.busyAction,taskset:v,onApprove:$=>u.actions.approveExpertBootstrap(v.id,$),onPreview:()=>u.actions.previewExpertBootstrap(v.id),onToast:h}):null]})}return e.jsxs("div",{className:"labs-flat-body labs-datasets-page",children:[e.jsx("div",{className:"labs-workproduct-toolbar",children:e.jsxs("label",{className:"labs-search",children:[e.jsx(cs,{size:14}),e.jsx("input",{"aria-label":"Search Datasets",placeholder:"Search Datasets",value:d,onChange:E=>{p(E.target.value),b(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:y.map(E=>{const $=M.get(E.id)??0;return e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("button",{className:"labs-workproduct-link",type:"button",onClick:()=>a(E.id),children:[e.jsx("strong",{children:E.name}),e.jsx("span",{children:E.objective})]})}),e.jsx("td",{children:cn(E,t,"train")}),e.jsx("td",{children:cn(E,t,"validation")}),e.jsx("td",{children:cn(E,t,"frozen_eval")}),e.jsx("td",{children:E.graders.length}),e.jsx("td",{children:$||"—"}),e.jsx("td",{children:bl(E.updatedAt)})]},E.id)})})]})}),y.length?null:e.jsx("div",{className:"labs-table-empty",children:"No Datasets match this view."}),e.jsx(jl,{page:m,total:S.length,onChange:b})]})}function cn(t,n,s){const a=t.datasetArtifact?n?.datasetArtifacts.find(i=>i.tasksetId===t.id&&i.tasksetRevision===t.revision):null;return a?a.splitCounts[s]??0:t.tasks.filter(i=>i.split===s).length}function xl(t){return t.readiness?.ready?"Ready":t.status==="ready"?"Needs Evals":t.status.replaceAll("_"," ").replace(/^./,n=>n.toUpperCase())}function bl(t){const n=new Date(t);return Number.isFinite(n.getTime())?n.toLocaleDateString(void 0,{month:"short",day:"numeric"}):"—"}function jl({page:t,total:n,onChange:s}){const a=Math.max(1,Math.ceil(n/jn));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 vl({enabled:t,items:n,runs:s,nextScanAt:a,scanRunning:i,scanStartedAt:r,scanning:l,savingEnabled:o,error:u,onEnabledChange:h,onPatchStatus:d,onOpenSession:p}){Qe(u);const[m,b]=c.useState("all"),[k,w]=c.useState("all"),[j,v]=c.useState("all"),[N,S]=c.useState("all"),[y,M]=c.useState("all"),[E,$]=c.useState(()=>Date.now());c.useEffect(()=>{const O=window.setInterval(()=>$(Date.now()),1e3);return()=>window.clearInterval(O)},[]);const C=c.useMemo(()=>n.filter(O=>!(m!=="all"&&O.status!==m||k!=="all"&&O.severity!==k||j!=="all"&&Ps(O)!==j)),[n,k,j,m]),x=c.useMemo(()=>s.filter(O=>!(N!=="all"&&O.status!==N||y!=="all"&&O.trigger!==y||j!=="all"&&!O.evidenceSources.includes(j))),[N,y,s,j]),D=c.useMemo(()=>C.filter(O=>O.status==="active"),[C]),ae=c.useMemo(()=>C.filter(O=>O.status!=="active"),[C]),P=m==="all"||m==="active",F=m==="all"||m!=="active",G=l||i,T=`${m}:${k}:${j}`,I=`${N}:${y}:${j}`;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 ${G?"running":""}`,children:[e.jsx("span",{className:"insights-scan-dot","aria-hidden":"true"}),t?Rl(a,E,G):"Scanning is off"]}),e.jsx("button",{"aria-pressed":t,className:t?"active":void 0,disabled:o||G,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(yt,{label:"Observation status",options:yl,value:m,onChange:b}),e.jsx(yt,{label:"Severity",options:Nl,value:k,onChange:w}),e.jsx(yt,{label:"Source",options:Sl,value:j,onChange:v}),e.jsx(yt,{label:"Run status",options:kl,value:N,onChange:S}),e.jsx(yt,{label:"Run trigger",options:Cl,value:y,onChange:M})]}),G?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 ${wn(r)}`:"Scanning insights now"})]})]}):null,e.jsx(wl,{runs:x,paginationKey:I,onOpenSession:p}),P?e.jsx(is,{title:"Active",emptyText:"No active Create/Improve insights match the filters.",items:D,paginationKey:T,onPatchStatus:d,onOpenSession:p}):null,F?e.jsx(is,{title:"Recent",emptyText:"No resolved or dismissed insights match the filters.",items:ae,paginationKey:T,onPatchStatus:d,onOpenSession:p}):null]})}const yl=[{value:"all",label:"All"},{value:"active",label:"Active"},{value:"resolved",label:"Resolved"},{value:"dismissed",label:"Dismissed"}],Nl=[{value:"all",label:"All"},{value:"blocker",label:"Blocker"},{value:"concern",label:"Concern"},{value:"nit",label:"Nit"}],Sl=[{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"}],kl=[{value:"all",label:"All"},{value:"running",label:"Running"},{value:"completed",label:"Completed"},{value:"failed",label:"Failed"},{value:"skipped",label:"Skipped"}],Cl=[{value:"all",label:"All"},{value:"manual",label:"Manual"},{value:"interval",label:"Interval"},{value:"startup",label:"Startup"},{value:"slash_command",label:"Slash"}];function yt({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 is({title:t,emptyText:n,items:s,paginationKey:a,onPatchStatus:i,onOpenSession:r}){const l=Ts(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:Il(o.severity)})}),e.jsx("td",{children:e.jsxs("div",{className:"insights-status-stack",children:[e.jsx("span",{children:o.status}),e.jsx("small",{children:_l(Ps(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:wn(o.updatedAt)}),e.jsx("td",{children:e.jsxs("div",{className:"insights-actions",children:[rs(o.payload.sessionId)?e.jsx("button",{type:"button",className:"insights-text-action",onClick:()=>r(rs(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(ms,{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(fs,{size:15})})]})})]},o.id))})]})}),e.jsx(Es,{label:t,...l})]})]})}function wl({runs:t,paginationKey:n,onOpenSession:s}){const a=Ts(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:Al(i.trigger)}),e.jsx("td",{className:"insights-status",children:i.status}),e.jsx("td",{className:"insights-status",children:Ml(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:wn(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(Es,{label:"Runs",...a})]})]})}const $t=10;function Ts(t,n){const[s,a]=c.useState(0);c.useEffect(()=>a(0),[n]);const i=Math.max(1,Math.ceil(t.length/$t)),r=Math.min(s,i-1),l=r*$t;return{pageItems:t.slice(l,l+$t),pageIndex:r,pageCount:i,pageStart:l,pageSize:$t,totalItems:t.length,onPageChange:a}}function Es({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 Il(t){return t==="blocker"?"Blocker":t==="concern"?"Concern":"Nit"}function Rl(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 Al(t){return t==="slash_command"?"Slash command":t==="startup"?"Startup":t==="interval"?"Interval":"Manual"}function Ml(t){return t.modelRef?`${t.modelRef.providerId} / ${t.modelRef.modelId}`:"Default"}function Ps(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 _l(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 rs(t){return typeof t=="string"&&t.trim()?t:null}function wn(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 Tl({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(El,{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 El({candidate:t,candidates:n,training:s,defaultModel:a,preferences:i,reasoningEffort:r,onPlanStarted:l}){const[o,u]=c.useState(""),h=n.filter(p=>p.id!==t.id&&p.status!=="retired");async function d(){const p=await s.actions.createCandidate(t.id,i.creationMode,us(i,a),r);p&&(p.state==="awaiting_disclosure_approval"&&i.autoApproveEvidence&&await s.actions.approveDisclosure(p.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:Bt(t.scorecard.frequency)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Verifiable"}),e.jsx("dd",{children:Bt(t.scorecard.verifiability)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Signal"}),e.jsx("dd",{children:Bt(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(p=>e.jsx("p",{className:"training-draft-warning",children:p},p)),e.jsx("ul",{children:t.evidence.map(p=>e.jsxs("li",{children:[e.jsx("strong",{children:p.kind.replaceAll("_"," ")})," — ",p.summary," (",Bt(p.confidence),")"]},p.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:p=>u(p.target.value),children:[e.jsx("option",{value:"",children:"Merge into…"}),h.map(p=>e.jsx("option",{value:p.id,children:p.title},p.id))]}),e.jsx("button",{className:"training-text-button",type:"button",disabled:!o,onClick:()=>{s.actions.patchCandidate(t.id,{mergeIntoId:o})},children:"Merge"})]}):null]})}function Bt(t){return`${Math.round(t*100)}%`}const Pl=10,Dl=new Date(0).toISOString();function $l({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(vl,{...t}):e.jsx(Tl,{training:s.training,defaultModel:s.defaultModel,preferences:s.preferences,reasoningEffort:s.reasoningEffort,onPlanStarted:i})})]})}function Bl({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(Me,{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 p=a.get(d.key),m=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:ql(d.kind)}):null,e.jsx("td",{children:e.jsxs("button",{className:m?"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}),m?e.jsx(Sr,{run:m,showOutcomes:!1}):null]})}),e.jsx("td",{children:e.jsx(Se,{label:p?.statusLabel??d.status,value:p?.statusValue??d.status})}),e.jsx("td",{className:"labs-workproduct-training",children:Ol(d)}),e.jsx("td",{className:"labs-workproduct-evals",children:Fl(d)}),e.jsx("td",{className:"labs-workproduct-updated",children:d.updatedAt===Dl?"—":Ds(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:b=>{b.stopPropagation(),u(d)},children:"Use"}):d.kind==="agent"&&d.useActionId?e.jsx("button",{className:"settings-secondary compact labs-workproduct-use",type:"button",onClick:b=>{b.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:b=>{b.stopPropagation(),o(d.id)},children:"Chat"}):null,e.jsx(gs,{size:15})]})})]},d.key)})})]})})}function Ll({items:t,loading:n,runs:s,state:a,onSelect:i,onUseModel:r}){return n?e.jsxs("div",{className:"labs-table-empty",children:[e.jsx(Me,{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=ut(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(Se,{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:Ds(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(gs,{size:15})]})})]},l.key)})})]})}):e.jsx("div",{className:"labs-table-empty",children:"No Models yet."})}function Ol(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(ps,{"aria-hidden":"true",size:15}),e.jsx("strong",{"aria-hidden":"true",children:t.trainingRunCount}),e.jsx("span",{className:"sr-only",children:n})]})}function Fl(t){const n=t.evaluationStatus==="passed"?{icon:e.jsx(ms,{"aria-hidden":"true",size:16}),label:"Evals passed",tone:"positive"}:t.evaluationStatus==="failed"?{icon:e.jsx(ja,{"aria-hidden":"true",size:16}),label:"Evals failed",tone:"negative"}:{icon:e.jsx(va,{"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 Ds(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 zl({page:t,total:n,onChange:s}){const a=Math.max(1,Math.ceil(n/Pl));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 ls(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(Ke("model",r?.target.kind==="model"?r.target.id??r.id:t.materializedTasksetId))}function os(t,n){return t.request.objective?.trim()||t.proposal?.objective.trim()||t.proposal?.name.trim()||n}function ql(t){return t&&`${t[0].toUpperCase()}${t.slice(1).replaceAll("_"," ")}`}function Ul(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 ds=10;function so({closeDetailKind:t,closeDetailRequestId:n,insights:s,onAnswerQuestion:a,onApplyCandidate:i,onApprove:r,onCancel:l,candidateReview:o,onCandidateReviewChange:u,onCreateAgent:h,onDetailOpenChange:d,onSkillSelectionChange:p,onImproveAgent:m,onNewModel:b,onOpenPullRequest:k,onOpenCandidateFiles:w,onOpenRunConversation:j,onPause:v,onReconcilePullRequest:N,onRejectCandidate:S,onResume:y,onRevise:M,onUseAgent:E,openSuggestionsRequestId:$,profileView:C,training:x}){const D=C.payload?.profile??null,ae=D?.activeProfile??"default",P=xi({connection:C.connection,profileId:ae});Qe(P.error),Qe(x.training.error);const F=c.useMemo(()=>Ul(x.training.payload),[x.training.payload]),G=c.useMemo(()=>P.runs.filter(R=>R.target.kind==="agent"&&["ready_local","released","published_hosted"].includes(R.state)).map(R=>`${R.id}:${R.revision}:${R.state}`).sort().join("|"),[P.runs]),[T,I]=c.useState("workproducts"),[O,z]=c.useState("observations"),[ce,ie]=c.useState(1),[re,K]=c.useState(null),[ue,Q]=c.useState(null),[se,le]=c.useState(!1),[Y,ne]=c.useState(null),[ke,he]=c.useState("datasets"),[Ce,H]=c.useState(null),[Le,U]=c.useState(null),[oe,pe]=c.useState(null),[fe,xe]=c.useState(null),[_e,je]=c.useState(null),[A,J]=c.useState(null),V=c.useMemo(()=>vs({profile:D,training:x.training.payload,runs:P.runs}),[P.runs,D,x.training.payload]),W=c.useMemo(()=>{const R=new Map((x.training.payload?.tasksets??[]).map(_=>[_.id,_]));return new Map(V.map(_=>[_.key,Ms({workproduct:_,runs:ys(_,P.runs),taskset:_.tasksetId?R.get(_.tasksetId)??null:null,training:x.training.payload})]))},[P.runs,x.training.payload,V]),We=c.useMemo(()=>V.filter(R=>R.kind!=="model"),[V]),Ye=c.useMemo(()=>V.filter(R=>R.kind==="model"),[V]),ve=V.find(R=>R.key===re)??null,Oe=c.useMemo(()=>Ur(ve),[ve]),rt=s.items.filter(R=>R.status==="active").length+(x.training.payload?.candidates.length??0);c.useEffect(()=>{if(!C.connection)return;let R=!1;return st.bootstrap(C.connection).then(_=>{R||C.onPayload(_)}).catch(_=>{R||C.onError(_ instanceof Error?_.message:String(_))}),()=>{R=!0}},[C.connection,C.onError,C.onPayload]),c.useEffect(()=>{F&&P.refresh()},[P.refresh,F]),c.useEffect(()=>{if(!G||!C.connection)return;let R=!1;return st.bootstrap(C.connection).then(_=>{R||C.onPayload(_)}).catch(_=>{R||C.onError(_ instanceof Error?_.message:String(_))}),()=>{R=!0}},[G,C.connection,C.onError,C.onPayload]),c.useEffect(()=>{$<=0||(z("observations"),I("suggestions"))},[$]),c.useEffect(()=>{re&&!V.some(R=>R.key===re)&&K(null)},[re,V]),c.useEffect(()=>{p(Oe)},[p,Oe]),c.useEffect(()=>{if(!(n<=0)){if(K(null),t==="dataset"){Q(null),I("datasets");return}I("workproducts")}},[t,n]),c.useEffect(()=>{if(T==="datasets"){d(ue?{kind:"dataset",kindLabel:"Datasets",workproductLabel:x.training.payload?.tasksets.find(R=>R.id===ue)?.name??"Dataset",sectionLabels:[]}:null);return}if(T!=="workproducts"){d(null);return}ve||d(null)},[T,d,ve,ue,x.training.payload?.tasksets]),c.useEffect(()=>()=>d(null),[d]);function pt(R){K(null),ie(1),Q(null),I(R)}function lt(R,_=""){const q=V.find(ye=>ye.kind==="agent"&&ye.id===R);J({agentId:R,agentName:q?.name??R,initialObjective:_.trim()})}function be(R){const _=V.find(we=>we.kind==="model"&&we.id===R);if(!_)return;const q=ut(_,P.runs,x.training.payload),ye=q.find(we=>we.current)??q.find(we=>we.lineage.promotable)??null;if(!ye?.taskset)return;if(x.training.payload?.jobs.find(we=>we.id===ye.lineage.jobId)?.destinationId==="fireworks"){je(ye.lineage.id);return}x.onChatWithModel(Ut({modelId:ye.lineage.id,taskset:ye.taskset}))}function Te(R){he(R),H(null),ne("source"),Q(null),I("datasets")}function me(){ne(null),H(null),ke==="model"&&I("workproducts")}function Ee(R){he("datasets"),H(R),ne("build"),Q(R),I("datasets")}function Pe(R){if(ne(null),H(null),K(null),ke==="model"){U(R),I("workproducts");return}I("datasets"),Q(R)}return e.jsxs(Vr,{activeTab:T,showHeader:!ve&&!ue&&Y!=="build",suggestionCount:rt,onTabChange:pt,onCreateAgent:()=>le(!0),onCreateDataset:()=>Te("datasets"),onCreateModel:()=>{U(null),b()},children:[T==="suggestions"?e.jsx($l,{insights:s,suggestionsView:O,training:x,onSuggestionsViewChange:z,onPlanStarted:()=>I("workproducts")}):T==="datasets"?e.jsx(fl,{building:Y==="build",buildContent:Y==="build"?e.jsx(Vl,{taskset:x.training.payload?.tasksets.find(R=>R.id===Ce)??null,createImproveRefresh:P.refresh,defaultModel:x.defaultModel,localProjects:x.localProjects??[],onBack:()=>{if(Ce){me();return}ne("source")},onClose:me,onCreated:Pe,onOpenComputeSettings:x.onOpenComputeSettings,preferences:x.preferences,providerSettings:x.providerSettings,reasoningEffort:x.reasoningEffort,sessions:x.sessions,sources:x.training.payload?.sources??[],training:x.training},Ce??"new-dataset"):null,runs:P.runs,selectedId:ue,state:x.training.payload,training:x.training,onToast:(R,_)=>C.onToast?.(R,_)??0,onSelectedIdChange:Q,onBuild:Ee,onOpenFiles:R=>{x.onSelectedTasksetIdChange(R),x.onOpenTasksetFiles()}}):ve?e.jsx(qr,{connection:C.connection,profile:D,runs:P.runs,training:x.training,workproduct:ve,onAnswerQuestion:a,onApplyCandidate:i,onApprove:r,onCancel:l,candidateReview:o,onCandidateReviewChange:u,onChatWithModel:x.onChatWithModel,onOpenPullRequest:k,onOpenCandidateFiles:w,onOpenConversation:j,onLocationChange:d,onRenameAgent:()=>pe({id:ve.id,name:ve.name}),onOpenDataset:R=>{K(null),Q(R),I("datasets")},onOpenProviderSettings:x.onOpenProviderSettings,onPause:v,onReconcilePullRequest:N,onRejectCandidate:S,onResume:y,onRevise:M,onStartAgentChange:(R,_)=>lt(R,_??""),onToast:x.onToast}):e.jsxs("div",{className:"labs-flat-body",children:[T==="workproducts"?e.jsx("div",{className:"labs-home-profile-controls",children:e.jsx(_a,{...C,section:"controls"})}):null,e.jsx(Bl,{frontierBaselineRuns:x.training.payload?.frontierBaselineRuns??[],loading:P.loading&&!V.length,items:We.slice((ce-1)*ds,ce*ds),progressionByKey:W,showType:!0,onSelect:K,onUseAgent:E,onUseModel:be,onUseSkill:R=>C.onSkillCommand?.(`$${R.name} `,R.skillSource==="codex"?"codex":"openpond")}),e.jsx(zl,{page:ce,total:We.length,onChange:ie}),T==="workproducts"?e.jsxs("section",{className:"labs-home-models",children:[e.jsx("div",{className:"labs-section-heading",children:e.jsx("h2",{children:"Models"})}),e.jsx(Ll,{loading:!1,items:Ye.slice(0,10),runs:P.runs,state:x.training.payload,onSelect:K,onUseModel:be})]}):null]}),x.launchRequest&&x.training.payload&&!(ke==="model"&&Y!==null)?e.jsx(Nt,{defaultModel:x.defaultModel,initialExistingTasksetId:Le,initialObjective:x.launchRequest.objective,initialSessionIds:x.launchRequest.initialSessionIds??[],localProjects:x.localProjects??[],onClose:()=>x.onLaunchHandled(x.launchRequest.id),onCreateDataset:()=>Te("model"),onOpenComputeSettings:x.onOpenComputeSettings,onModelCreatedFromTaskset:async(R,_)=>{U(null),x.onLaunchHandled(x.launchRequest.id),x.onSelectedTasksetIdChange(R.id),x.onDetailTasksetIdChange(R.id),K(Ke("model",_.target.id??_.id)),I("workproducts"),await P.refresh()},onTasksetCreated:async R=>{await ls(R,x,P.refresh,K),I("workproducts")},preferences:x.preferences,providerSettings:x.providerSettings,reasoningEffort:x.reasoningEffort,sessions:x.sessions,sources:x.training.payload.sources,training:x.training}):null,se?e.jsx(Nt,{defaultModel:x.defaultModel,initialObjective:null,localProjects:x.localProjects??[],onClose:()=>le(!1),onAgentPromptSubmitted:async({analysisModel:R,objective:_})=>{const q=await h(_,null,R);await P.refresh(),I("workproducts"),K(Ke("agent",q.target.id??q.id)),le(!1)},onOpenComputeSettings:x.onOpenComputeSettings,onTasksetCreated:async R=>{const _=os(R,"Create a useful Agent from the approved Taskset."),q=await h(_,R.request.createImproveRunId,R.request.analysisModel);await P.refresh(),I("workproducts"),K(Ke("agent",q.target.id??q.id)),le(!1)},preferences:x.preferences,providerSettings:x.providerSettings,reasoningEffort:x.reasoningEffort,sessions:x.sessions,sources:x.training.payload?.sources??[],targetIntent:{kind:"agent",id:null,displayName:null,operation:"create"},training:x.training}):null,Y==="source"?e.jsx(oi,{onClose:me,onSelect:ne}):null,Y==="huggingface"?e.jsx(ui,{onBack:()=>ne("source"),onClose:me,onImported:async R=>{await x.training.refresh(),Pe(R)},onOpenDatasetStorageSettings:()=>{ne(null),x.onOpenDatasetStorageSettings()},training:x.training}):null,A?e.jsx(Nt,{defaultModel:x.defaultModel,initialObjective:A.initialObjective,localProjects:x.localProjects??[],onClose:()=>J(null),onAgentPromptSubmitted:async({analysisModel:R,objective:_})=>{await m(A.agentId,_,A.agentName,null,R),await P.refresh(),I("workproducts"),K(Ke("agent",A.agentId)),J(null)},onOpenComputeSettings:x.onOpenComputeSettings,onTasksetCreated:async R=>{const _=os(R,A.initialObjective);await m(A.agentId,_,A.agentName,R.request.createImproveRunId,R.request.analysisModel),await P.refresh(),I("workproducts"),K(Ke("agent",A.agentId)),J(null)},preferences:x.preferences,providerSettings:x.providerSettings,reasoningEffort:x.reasoningEffort,sessions:x.sessions,sources:x.training.payload?.sources??[],targetIntent:{kind:"agent",id:A.agentId,displayName:A.agentName,operation:"improve"},training:x.training}):null,fe?e.jsx(Nt,{defaultModel:x.defaultModel,initialCreation:fe,initialObjective:fe.request.objective,localProjects:x.localProjects??[],onClose:()=>xe(null),onOpenComputeSettings:x.onOpenComputeSettings,onTasksetCreated:async R=>{await ls(R,x,P.refresh,K),I("workproducts"),xe(null)},preferences:x.preferences,providerSettings:x.providerSettings,reasoningEffort:x.reasoningEffort,sessions:x.sessions,sources:x.training.payload?.sources??[],targetIntent:fe.request.targetIntent,training:x.training}):null,_e?(()=>{const R=x.training.payload?.models.find(q=>q.id===_e),_=x.training.payload?.tasksets.find(q=>q.id===R?.tasksetId);return!R||!_?null:e.jsx(bs,{lineage:R,taskset:_,training:x.training,onChat:x.onChatWithModel,onClose:()=>je(null)})})():null,oe?e.jsx(Kr,{agentId:oe.id,currentName:oe.name,onClose:()=>pe(null),onRename:async R=>{if(!C.connection)throw new Error("Connect OpenPond before renaming an agent.");C.onError(null),await st.profileAgentRename(C.connection,oe.id,{name:R}),C.onPayload(await st.bootstrap(C.connection)),C.onToast?.(`Renamed agent to ${R}.`,"success")}}):null]})}function Vl({taskset:t,createImproveRefresh:n,defaultModel:s,localProjects:a,onBack:i,onClose:r,onCreated:l,onOpenComputeSettings:o,preferences:u,providerSettings:h,reasoningEffort:d,sessions:p,sources:m,training:b}){const k=t?.sourceRefs.filter(Kt).map(w=>w.sessionId)??[];return e.jsx(Nt,{datasetBuildBackLabel:t?"Back to Dataset overview":"Back to Dataset sources",datasetBuildMode:!0,defaultModel:s,initialObjective:t?.objective??null,initialSessionIds:k,localProjects:a,onBackToDatasetSources:i,onClose:r,onOpenComputeSettings:o,onTasksetCreated:async w=>{await Promise.all([b.refresh(),n()]),l(w.materializedTasksetId)},preferences:u,presentation:"embedded",providerSettings:h,reasoningEffort:d,resourceIntent:"dataset",sessions:p,sources:m,targetIntent:{kind:null,id:t?.id??null,displayName:t?.name??null,operation:t?"improve":"create"},training:b})}export{so as LabsRoute};