openpond 0.0.43 → 0.0.44

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 (99) hide show
  1. package/dist/chunks/{app-layer-UPNMLDO5.js → app-layer-KH7LZGB6.js} +2 -2
  2. package/dist/chunks/{app-server-runtime-CLJWPISO.js → app-server-runtime-VEYSA27N.js} +7 -7
  3. package/dist/chunks/{apps-XLPSFCW4.js → apps-3UVBL7UK.js} +2 -2
  4. package/dist/chunks/{chunk-ZTE6A2VE.js → chunk-2NP3E4GP.js} +1 -1
  5. package/dist/chunks/{chunk-QHUJ2XVJ.js → chunk-3XFHKWKG.js} +32 -32
  6. package/dist/chunks/{chunk-2SF6HLT7.js → chunk-53YZBGDC.js} +4 -1
  7. package/dist/chunks/{chunk-MCBAI5M5.js → chunk-67K6KXTS.js} +1 -1
  8. package/dist/chunks/{chunk-SBVJGA3Y.js → chunk-6GLNUWY2.js} +768 -44
  9. package/dist/chunks/{chunk-L7SIUJEV.js → chunk-HKJG7VBI.js} +1 -1
  10. package/dist/chunks/{chunk-DBHT62E5.js → chunk-HLEQDBYN.js} +1 -1
  11. package/dist/chunks/{chunk-YYLUURQ4.js → chunk-JBUNQVLP.js} +3 -3
  12. package/dist/chunks/{chunk-YEKQWRBS.js → chunk-SLTKA5AW.js} +9 -5
  13. package/dist/chunks/{chunk-KSOI7GFA.js → chunk-Y7BBDWBT.js} +1 -1
  14. package/dist/chunks/{chunk-M2NXTLH2.js → chunk-ZXWFYFFB.js} +516 -26
  15. package/dist/chunks/{cli-UU4WCREM.js → cli-64VFZWFY.js} +6 -6
  16. package/dist/chunks/{core-commands-D66KZEHU.js → core-commands-54ZMYVFM.js} +3 -3
  17. package/dist/chunks/{desktop-test-FDA6MV77.js → desktop-test-ZISBAXA7.js} +2 -2
  18. package/dist/chunks/{extension-GDRW22N3.js → extension-65AJZLNI.js} +4 -1
  19. package/dist/chunks/{help-7QG4UITV.js → help-WHEMW4R3.js} +1 -1
  20. package/dist/chunks/{opchat-I2WGEFGU.js → opchat-ZFKPZQUA.js} +2 -2
  21. package/dist/chunks/{organizations-MADRLI2I.js → organizations-K4IDYOYN.js} +4 -4
  22. package/dist/chunks/{profile-B4A3GT3U.js → profile-NTBQ74Q7.js} +2 -2
  23. package/dist/chunks/{project-agent-PCO42FZJ.js → project-agent-7JDEGY6U.js} +2 -2
  24. package/dist/chunks/{sandbox-command-LBKSIR7P.js → sandbox-command-HPYUKC6U.js} +2 -2
  25. package/dist/chunks/{sandbox-template-YJXGG4H3.js → sandbox-template-APQYLIHG.js} +3 -3
  26. package/dist/chunks/{src-L2H4X4IY.js → src-22E2EIT5.js} +1393 -487
  27. package/dist/chunks/{src-35JYS27L.js → src-CBOXC5JP.js} +3 -3
  28. package/dist/chunks/{teams-bot-L4SR2SWM.js → teams-bot-TQKFFTJ7.js} +2 -2
  29. package/dist/chunks/{workspaces-ODFJT6HJ.js → workspaces-RKZVNT2A.js} +2 -2
  30. package/dist/cli.js +13 -13
  31. package/dist/web/assets/{AppDialog-Bua3f-6v.js → AppDialog-D8HiG2vU.js} +1 -1
  32. package/dist/web/assets/{AppsView-DrJkHeSO.js → AppsView-gZoE9vMK.js} +1 -1
  33. package/dist/web/assets/{BrowserSidebar-Bf-4Vozm.js → BrowserSidebar-D-HKuusA.js} +1 -1
  34. package/dist/web/assets/{CommandMenu-DDZlGQiB.js → CommandMenu-CzrixKzR.js} +1 -1
  35. package/dist/web/assets/{CommunityView-BtcCrba7.js → CommunityView-khbmjhWm.js} +1 -1
  36. package/dist/web/assets/{ComposerCreateImproveStrip-DOe5Otg6.js → ComposerCreateImproveStrip-CLxAZScx.js} +1 -1
  37. package/dist/web/assets/{GetStartedView-CG4z0Dtw.js → GetStartedView-C3nu80E_.js} +1 -1
  38. package/dist/web/assets/{LabModelVersionDetailPage-BEkmSKuv.js → LabModelVersionDetailPage-EcvM9TTz.js} +1 -1
  39. package/dist/web/assets/{LabSkillSidebar-BIotN_RB.js → LabSkillSidebar-LG9zm1yx.js} +1 -1
  40. package/dist/web/assets/{LabsRoute-CfOe0Zt5.js → LabsRoute-B4lijQB6.js} +3 -3
  41. package/dist/web/assets/{MainChatThread-C0-l1mHt.js → MainChatThread-D_-zWAT8.js} +2 -2
  42. package/dist/web/assets/{MainPane-aOVlVyRK.js → MainPane-Dfvc7xdq.js} +3 -3
  43. package/dist/web/assets/{MarkdownText-D7DT1k1k.js → MarkdownText-C0_D5zMW.js} +1 -1
  44. package/dist/web/assets/{Messages-CBIXruA9.js → Messages-C-Q91wIU.js} +1 -1
  45. package/dist/web/assets/{NativeSkillSidebar-C4t69Y7B.js → NativeSkillSidebar-DoSiN-Mr.js} +1 -1
  46. package/dist/web/assets/{NewProjectDialog-Bat65tYD.js → NewProjectDialog-C0hUcNck.js} +1 -1
  47. package/dist/web/assets/{OutputsPage-C58n39Db.js → OutputsPage-PV7Pm_OU.js} +1 -1
  48. package/dist/web/assets/{RightChatPanelStack-Bp7nZxQ0.js → RightChatPanelStack-C1LZTXEY.js} +1 -1
  49. package/dist/web/assets/{ScheduledWorkPage-BXP0j_c_.js → ScheduledWorkPage-7UGpZ8Gc.js} +1 -1
  50. package/dist/web/assets/{SettingsView-CtWK_aQ0.css → SettingsView-CrXwXjZ1.css} +1 -1
  51. package/dist/web/assets/SettingsView-DjSbBHb7.js +6 -0
  52. package/dist/web/assets/{TeamChatView-De2wdqyY.js → TeamChatView-D7_mZ6eT.js} +1 -1
  53. package/dist/web/assets/{TerminalOverlay-BsuCH3NX.js → TerminalOverlay-Cji37VqF.js} +1 -1
  54. package/dist/web/assets/{TrainingCreationPanel-D2OFWyQ-.js → TrainingCreationPanel-VctKu0b5.js} +1 -1
  55. package/dist/web/assets/{TrainingDraftPanel-DBpulXTz.js → TrainingDraftPanel-BJXcYQt5.js} +1 -1
  56. package/dist/web/assets/{UsageSettingsSection-DzMLUXAO.js → UsageSettingsSection-BxnbRELL.js} +1 -1
  57. package/dist/web/assets/{WorkspaceDiffPanel-B7yIhjNF.js → WorkspaceDiffPanel-Dj50bA58.js} +3 -3
  58. package/dist/web/assets/{WorkspaceEnvironmentMenu-B6jXM9xG.js → WorkspaceEnvironmentMenu-Dv_pK7bp.js} +1 -1
  59. package/dist/web/assets/{WorkspaceGitDialogs-CQ0fl9Qk.js → WorkspaceGitDialogs-Bs55QQk1.js} +1 -1
  60. package/dist/web/assets/{WorkspaceMonacoEditor-C2ctzITz.js → WorkspaceMonacoEditor-BKyihWp7.js} +3 -3
  61. package/dist/web/assets/{arrow-up-right-ecwcx3xt.js → arrow-up-right-O7S09juy.js} +1 -1
  62. package/dist/web/assets/{chevron-up-DP8PPfWd.js → chevron-up-ILypNpT9.js} +1 -1
  63. package/dist/web/assets/{circle-alert-envg1D6O.js → circle-alert-CqcEVbV4.js} +1 -1
  64. package/dist/web/assets/{cloud-upload-5MGPLnaA.js → cloud-upload-B-KanLwx.js} +1 -1
  65. package/dist/web/assets/{cssMode-CFifcEfw.js → cssMode-BIJYgmZR.js} +1 -1
  66. package/dist/web/assets/{folder-open-Dq3ZjeEP.js → folder-open-DCkv77b6.js} +1 -1
  67. package/dist/web/assets/{folder-plus-EiZ5wbv_.js → folder-plus-BqZUZnCI.js} +1 -1
  68. package/dist/web/assets/{git-branch-w29jmQ-X.js → git-branch-DLlfIOn_.js} +1 -1
  69. package/dist/web/assets/{git-commit-horizontal-CGZM0PZo.js → git-commit-horizontal-ClqcnbGe.js} +1 -1
  70. package/dist/web/assets/{htmlMode-Ct1P-_lf.js → htmlMode-B1PeNAJB.js} +1 -1
  71. package/dist/web/assets/index-BLgZVGpl.js +178 -0
  72. package/dist/web/assets/index-vV2sAtZG.js +1 -0
  73. package/dist/web/assets/{info-Cd2HkIeb.js → info-B-IcZCF8.js} +1 -1
  74. package/dist/web/assets/{jsonMode-BAUNCNAX.js → jsonMode-NqLd9KdG.js} +1 -1
  75. package/dist/web/assets/{lspLanguageFeatures-fucFYI1A.js → lspLanguageFeatures-DWa2E295.js} +1 -1
  76. package/dist/web/assets/{monaco.contribution-nG-5Cyjz.js → monaco.contribution-BYgdD9ap.js} +2 -2
  77. package/dist/web/assets/{monaco.contribution-DLLMi4cB.js → monaco.contribution-DOdpxIBx.js} +2 -2
  78. package/dist/web/assets/{monaco.contribution-g9QiIm1d.js → monaco.contribution-EiA1XLoV.js} +2 -2
  79. package/dist/web/assets/{monaco.contribution-Ce4v5kei.js → monaco.contribution-rE0pudHI.js} +2 -2
  80. package/dist/web/assets/{monitor-DgHCnCKl.js → monitor-IKHoaZYu.js} +1 -1
  81. package/dist/web/assets/{play-Be0XDHBu.js → play-B8a2D-Pu.js} +1 -1
  82. package/dist/web/assets/{python-CEhEiPo7.js → python-DXSUy3MY.js} +1 -1
  83. package/dist/web/assets/{refresh-cw-DH0KLbdD.js → refresh-cw-De3V2Tzv.js} +1 -1
  84. package/dist/web/assets/{reply-D1TK2yV8.js → reply-DtzLGSWr.js} +1 -1
  85. package/dist/web/assets/{save-C1MSeBnQ.js → save-CKSY2EC7.js} +1 -1
  86. package/dist/web/assets/{square-CemI-0g5.js → square-U2IL0jpg.js} +1 -1
  87. package/dist/web/assets/{square-pen-CqfsvR_n.js → square-pen-DhLj2CtT.js} +1 -1
  88. package/dist/web/assets/{toggleHighContrast-DrdQN3Rl.js → toggleHighContrast-Dusp2QyF.js} +1 -1
  89. package/dist/web/assets/{tsMode-CKB5oOUU.js → tsMode-CarGQUBk.js} +1 -1
  90. package/dist/web/assets/{upload-t751LLqP.js → upload-12FovSVQ.js} +1 -1
  91. package/dist/web/assets/{useLocalAgentSchedules-CzC3wfIP.js → useLocalAgentSchedules-DGQQtn8W.js} +1 -1
  92. package/dist/web/assets/{wifi-off-CxTHH3JU.js → wifi-off-CjQEPd2q.js} +1 -1
  93. package/dist/web/assets/{workers-CqYddzCd.js → workers-CeBkFaBO.js} +1 -1
  94. package/dist/web/assets/{yaml-e5wBkc-C.js → yaml-DQPBhykU.js} +1 -1
  95. package/dist/web/index.html +1 -1
  96. package/package.json +1 -1
  97. package/dist/web/assets/SettingsView-DOOfhO9a.js +0 -6
  98. package/dist/web/assets/index-ByIQyiUl.js +0 -178
  99. package/dist/web/assets/index-D4uCeiep.js +0 -1
@@ -22,6 +22,7 @@ import {
22
22
  createHostedTurnHelpers,
23
23
  createImproveLimit,
24
24
  createImproveTargetKind,
25
+ createLocalHarnessEvaluationReviewScheduler,
25
26
  createLocalHarnessImprovementRuntime,
26
27
  createLocalHarnessModelToolDefinitions,
27
28
  createLocalHarnessSettingsRoutePayloads,
@@ -78,6 +79,7 @@ import {
78
79
  resolveOpenPondSandboxClient,
79
80
  resolveSelectedLocalHarnessRelease,
80
81
  resolveWorkspaceExecutionTarget,
82
+ reviewSelectedLocalHarnessEvaluation,
81
83
  runHostedContextCompaction,
82
84
  safeChatAttachmentPathSegment,
83
85
  sandboxRequestPayload,
@@ -96,14 +98,14 @@ import {
96
98
  workspaceHasHead,
97
99
  workspaceToolExperienceBlocker,
98
100
  writeWorkspaceFile
99
- } from "./chunk-SBVJGA3Y.js";
101
+ } from "./chunk-6GLNUWY2.js";
100
102
  import {
101
103
  runOpenPondServerCli
102
- } from "./chunk-YYLUURQ4.js";
104
+ } from "./chunk-JBUNQVLP.js";
103
105
  import {
104
106
  createAppServer,
105
107
  runAgentCompaction
106
- } from "./chunk-YEKQWRBS.js";
108
+ } from "./chunk-SLTKA5AW.js";
107
109
  import {
108
110
  createOpenPondRepoApp,
109
111
  getBundledRuntimeVersion,
@@ -117,7 +119,7 @@ import {
117
119
  streamOpenPondHostedChatTurn,
118
120
  switchOpenPondAccount,
119
121
  updateOpenPondAccountConfig
120
- } from "./chunk-ZTE6A2VE.js";
122
+ } from "./chunk-2NP3E4GP.js";
121
123
  import {
122
124
  appWorkspacePaths,
123
125
  checkWorkspaceGitAvailability,
@@ -145,7 +147,7 @@ import {
145
147
  runCommand,
146
148
  startMacOSCommandLineToolsInstall,
147
149
  workspaceImageContentType
148
- } from "./chunk-DBHT62E5.js";
150
+ } from "./chunk-HLEQDBYN.js";
149
151
  import {
150
152
  APP_PREFERENCES_CACHE_KEY,
151
153
  APP_PREFERENCES_CACHE_TYPE,
@@ -157,7 +159,7 @@ import {
157
159
  isCliEntrypoint,
158
160
  now,
159
161
  textFromUnknown
160
- } from "./chunk-L7SIUJEV.js";
162
+ } from "./chunk-HKJG7VBI.js";
161
163
  import {
162
164
  AccountStateSchema,
163
165
  AdapterValidationReceiptSchema,
@@ -419,13 +421,14 @@ import {
419
421
  workFormatCapabilityForContentType,
420
422
  workspacePathFromLocalPathWorkspaceId,
421
423
  writeSourceUploadCache
422
- } from "./chunk-2SF6HLT7.js";
424
+ } from "./chunk-53YZBGDC.js";
423
425
  import {
424
426
  AgentSnapshotSchema,
425
427
  AttemptReceiptSchema,
426
428
  CONNECTED_APP_INTEGRATION_SKILLS,
427
429
  EvidenceArtifactRefSchema,
428
430
  HarnessReleaseSchema,
431
+ HarnessReviewSourcePolicyRefSchema,
429
432
  ImmutableReleaseRefSchema,
430
433
  OPENPOND_MANIFEST_FILE_NAME,
431
434
  SANDBOX_TEMPLATE_BUILD_PLAN_FILE_NAME,
@@ -441,7 +444,9 @@ import {
441
444
  contentHash,
442
445
  createAgentSnapshot,
443
446
  createAttemptReceipt,
447
+ createHarnessEvaluationReviewReceipt,
444
448
  createHarnessRelease,
449
+ createModelImprovementQualificationReceipt,
445
450
  createRunManifest,
446
451
  createWorkEvidenceReceipt,
447
452
  createWorkFeedbackReceipt,
@@ -456,7 +461,7 @@ import {
456
461
  workEvidenceReceiptRef,
457
462
  workSourceOpaqueRef,
458
463
  workWorkspaceOpaqueRef
459
- } from "./chunk-M2NXTLH2.js";
464
+ } from "./chunk-ZXWFYFFB.js";
460
465
  import {
461
466
  external_exports,
462
467
  yaml
@@ -14557,10 +14562,10 @@ function codexContextUsageRecord(input) {
14557
14562
  function asRecord(value) {
14558
14563
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
14559
14564
  }
14560
- function stringValue(record10, keys) {
14561
- if (!record10) return void 0;
14565
+ function stringValue(record11, keys) {
14566
+ if (!record11) return void 0;
14562
14567
  for (const key of keys) {
14563
- const value = record10[key];
14568
+ const value = record11[key];
14564
14569
  if (typeof value === "string" && value.trim()) return value;
14565
14570
  }
14566
14571
  return void 0;
@@ -14627,13 +14632,13 @@ function findImagePathValue(value, depth = 0, key = "") {
14627
14632
  return null;
14628
14633
  }
14629
14634
  if (typeof value !== "object") return null;
14630
- const record10 = value;
14631
- for (const [childKey, child] of Object.entries(record10)) {
14635
+ const record11 = value;
14636
+ for (const [childKey, child] of Object.entries(record11)) {
14632
14637
  if (!isImagePathKey(childKey)) continue;
14633
14638
  const candidate2 = findImagePathValue(child, depth + 1, childKey);
14634
14639
  if (candidate2) return candidate2;
14635
14640
  }
14636
- for (const [childKey, child] of Object.entries(record10)) {
14641
+ for (const [childKey, child] of Object.entries(record11)) {
14637
14642
  if (isImagePathKey(childKey)) continue;
14638
14643
  const candidate2 = findImagePathValue(child, depth + 1, childKey);
14639
14644
  if (candidate2) return candidate2;
@@ -14692,18 +14697,18 @@ function codexAgentMessagePhase(item) {
14692
14697
  function codexAgentMessageKey(sessionId, itemId) {
14693
14698
  return `${sessionId}:${itemId}`;
14694
14699
  }
14695
- function numberValue(record10, keys) {
14696
- if (!record10) return null;
14700
+ function numberValue(record11, keys) {
14701
+ if (!record11) return null;
14697
14702
  for (const key of keys) {
14698
- const value = record10[key];
14703
+ const value = record11[key];
14699
14704
  if (typeof value === "number" && Number.isFinite(value) && value >= 0) return Math.round(value);
14700
14705
  }
14701
14706
  return null;
14702
14707
  }
14703
- function recordValue(record10, keys) {
14704
- if (!record10) return null;
14708
+ function recordValue(record11, keys) {
14709
+ if (!record11) return null;
14705
14710
  for (const key of keys) {
14706
- const value = asRecord(record10[key]);
14711
+ const value = asRecord(record11[key]);
14707
14712
  if (value) return value;
14708
14713
  }
14709
14714
  return null;
@@ -15047,15 +15052,15 @@ var ProviderCatalogCacheSchema = ProviderCatalogSchema.transform((catalog) => ca
15047
15052
  var providerFileQueues = /* @__PURE__ */ new Map();
15048
15053
  function normalizeCatalogCache(value) {
15049
15054
  if (!value || typeof value !== "object") return null;
15050
- const record10 = value;
15051
- const catalog = ProviderCatalogCacheSchema.safeParse(record10.catalog);
15052
- const fetchedAt = typeof record10.fetchedAt === "string" && record10.fetchedAt.trim() ? record10.fetchedAt : null;
15055
+ const record11 = value;
15056
+ const catalog = ProviderCatalogCacheSchema.safeParse(record11.catalog);
15057
+ const fetchedAt = typeof record11.fetchedAt === "string" && record11.fetchedAt.trim() ? record11.fetchedAt : null;
15053
15058
  if (!catalog.success || !fetchedAt) return null;
15054
15059
  return {
15055
15060
  source: "hosted",
15056
15061
  fetchedAt,
15057
- lastError: typeof record10.lastError === "string" ? record10.lastError : null,
15058
- catalogHash: typeof record10.catalogHash === "string" && record10.catalogHash.trim() ? record10.catalogHash : null,
15062
+ lastError: typeof record11.lastError === "string" ? record11.lastError : null,
15063
+ catalogHash: typeof record11.catalogHash === "string" && record11.catalogHash.trim() ? record11.catalogHash : null,
15059
15064
  catalog: catalog.data
15060
15065
  };
15061
15066
  }
@@ -16151,12 +16156,12 @@ function encryptValue(value, key) {
16151
16156
  tag: cipher.getAuthTag().toString("base64")
16152
16157
  };
16153
16158
  }
16154
- function decryptValue(record10, key) {
16155
- if (!key || !record10.ciphertext || !record10.iv || !record10.tag) return null;
16156
- const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(record10.iv, "base64"));
16157
- decipher.setAuthTag(Buffer.from(record10.tag, "base64"));
16159
+ function decryptValue(record11, key) {
16160
+ if (!key || !record11.ciphertext || !record11.iv || !record11.tag) return null;
16161
+ const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(record11.iv, "base64"));
16162
+ decipher.setAuthTag(Buffer.from(record11.tag, "base64"));
16158
16163
  return Buffer.concat([
16159
- decipher.update(Buffer.from(record10.ciphertext, "base64")),
16164
+ decipher.update(Buffer.from(record11.ciphertext, "base64")),
16160
16165
  decipher.final()
16161
16166
  ]).toString("utf8");
16162
16167
  }
@@ -16180,34 +16185,34 @@ async function writeRawSecretsFile(secretsFilePath, value) {
16180
16185
  async function readProviderSecrets(paths) {
16181
16186
  const raw = await readRawSecretsFile(paths.secretsFilePath);
16182
16187
  const needsKey = Object.values(raw.providers).some(
16183
- (record10) => record10.source === "local_secret" || record10.source === "chatgpt_subscription"
16188
+ (record11) => record11.source === "local_secret" || record11.source === "chatgpt_subscription"
16184
16189
  );
16185
16190
  const key = needsKey ? await readSecretKey(paths.keyFilePath) : null;
16186
16191
  const providers = {};
16187
- for (const [providerId, record10] of Object.entries(raw.providers)) {
16188
- const createdAt = record10.createdAt ?? record10.updatedAt ?? null;
16189
- const updatedAt = record10.updatedAt ?? record10.createdAt ?? null;
16192
+ for (const [providerId, record11] of Object.entries(raw.providers)) {
16193
+ const createdAt = record11.createdAt ?? record11.updatedAt ?? null;
16194
+ const updatedAt = record11.updatedAt ?? record11.createdAt ?? null;
16190
16195
  if (!createdAt || !updatedAt) continue;
16191
- if (record10.source === "env") {
16196
+ if (record11.source === "env") {
16192
16197
  providers[providerId] = {
16193
16198
  source: "env",
16194
16199
  value: null,
16195
- envVar: record10.envVar ?? null,
16200
+ envVar: record11.envVar ?? null,
16196
16201
  oauth: null,
16197
16202
  createdAt,
16198
16203
  updatedAt,
16199
- lastValidatedAt: record10.lastValidatedAt ?? null,
16200
- lastError: record10.lastError ?? null
16204
+ lastValidatedAt: record11.lastValidatedAt ?? null,
16205
+ lastError: record11.lastError ?? null
16201
16206
  };
16202
16207
  continue;
16203
16208
  }
16204
16209
  let value = null;
16205
16210
  let oauth = null;
16206
- let lastError = record10.lastError ?? null;
16211
+ let lastError = record11.lastError ?? null;
16207
16212
  try {
16208
- value = decryptValue(record10, key);
16213
+ value = decryptValue(record11, key);
16209
16214
  if (!value) lastError = lastError ?? "Provider credential could not be decrypted.";
16210
- if (record10.source === "chatgpt_subscription") {
16215
+ if (record11.source === "chatgpt_subscription") {
16211
16216
  oauth = parseChatGptSubscriptionCredential(value);
16212
16217
  value = null;
16213
16218
  if (!oauth) lastError = lastError ?? "Provider ChatGPT subscription credential could not be read.";
@@ -16218,13 +16223,13 @@ async function readProviderSecrets(paths) {
16218
16223
  lastError = error instanceof Error ? error.message : String(error);
16219
16224
  }
16220
16225
  providers[providerId] = {
16221
- source: record10.source,
16226
+ source: record11.source,
16222
16227
  value,
16223
16228
  envVar: null,
16224
16229
  oauth,
16225
16230
  createdAt,
16226
16231
  updatedAt,
16227
- lastValidatedAt: record10.lastValidatedAt ?? null,
16232
+ lastValidatedAt: record11.lastValidatedAt ?? null,
16228
16233
  lastError
16229
16234
  };
16230
16235
  }
@@ -16234,14 +16239,14 @@ function parseChatGptSubscriptionCredential(value) {
16234
16239
  if (!value) return null;
16235
16240
  const parsed = JSON.parse(value);
16236
16241
  if (!parsed || typeof parsed !== "object") return null;
16237
- const record10 = parsed;
16238
- const refreshToken = stringValue2(record10.refreshToken);
16242
+ const record11 = parsed;
16243
+ const refreshToken = stringValue2(record11.refreshToken);
16239
16244
  if (!refreshToken) return null;
16240
16245
  return {
16241
- accessToken: stringValue2(record10.accessToken),
16246
+ accessToken: stringValue2(record11.accessToken),
16242
16247
  refreshToken,
16243
- expiresAt: typeof record10.expiresAt === "number" && Number.isFinite(record10.expiresAt) ? record10.expiresAt : 0,
16244
- accountId: stringValue2(record10.accountId)
16248
+ expiresAt: typeof record11.expiresAt === "number" && Number.isFinite(record11.expiresAt) ? record11.expiresAt : 0,
16249
+ accountId: stringValue2(record11.accountId)
16245
16250
  };
16246
16251
  }
16247
16252
  function parseProviderCredentialWriteRequest(input) {
@@ -16642,10 +16647,10 @@ function stringValue3(value) {
16642
16647
  function numberValue2(value) {
16643
16648
  return typeof value === "number" && Number.isFinite(value) ? value : null;
16644
16649
  }
16645
- function stringMap(record10) {
16650
+ function stringMap(record11) {
16646
16651
  const map = /* @__PURE__ */ new Map();
16647
- if (!record10) return map;
16648
- for (const [key, value] of Object.entries(record10)) {
16652
+ if (!record11) return map;
16653
+ for (const [key, value] of Object.entries(record11)) {
16649
16654
  if (typeof value === "string" && value.trim()) map.set(key, value.trim());
16650
16655
  }
16651
16656
  return map;
@@ -16867,9 +16872,9 @@ function threadLookupCacheKey(codexHome, threadId) {
16867
16872
  }
16868
16873
  async function readCodexHistorySearchText(thread) {
16869
16874
  const messages = [];
16870
- await readJsonlRecords(thread.filePath, (record10) => {
16871
- const payload = asRecord3(record10.payload);
16872
- const responsePayload = responsePayloadFromCodexRecord(record10, payload);
16875
+ await readJsonlRecords(thread.filePath, (record11) => {
16876
+ const payload = asRecord3(record11.payload);
16877
+ const responsePayload = responsePayloadFromCodexRecord(record11, payload);
16873
16878
  if (responsePayload?.type !== "message") return;
16874
16879
  const role = stringValue3(responsePayload.role);
16875
16880
  if (role !== "user" && role !== "assistant") return;
@@ -16883,8 +16888,8 @@ async function readCodexHistorySearchText(thread) {
16883
16888
  }
16884
16889
  async function parseCodexSessionFile(input) {
16885
16890
  const parser = createCodexRecordParser(input);
16886
- await readJsonlRecords(input.filePath, (record10) => {
16887
- parser.accept(record10);
16891
+ await readJsonlRecords(input.filePath, (record11) => {
16892
+ parser.accept(record11);
16888
16893
  });
16889
16894
  return parser.finish();
16890
16895
  }
@@ -16893,8 +16898,8 @@ async function parseCodexSessionTailFile(input) {
16893
16898
  const tail = await readTail(input.filePath, input.maxBytes);
16894
16899
  for (const line of tail.split(/\r?\n/)) {
16895
16900
  if (!line.trim()) continue;
16896
- const record10 = parseJson(line);
16897
- if (record10) parser.accept(record10);
16901
+ const record11 = parseJson(line);
16902
+ if (record11) parser.accept(record11);
16898
16903
  }
16899
16904
  return parser.finish();
16900
16905
  }
@@ -17030,11 +17035,11 @@ function createCodexRecordParser(input) {
17030
17035
  pushThreadGoalCleared(timestamp, turnId, "Goal cleared", true);
17031
17036
  }
17032
17037
  }
17033
- function accept(record10) {
17034
- const timestamp = isoTimestamp(record10.timestamp) ?? input.fallbackTimestamp;
17038
+ function accept(record11) {
17039
+ const timestamp = isoTimestamp(record11.timestamp) ?? input.fallbackTimestamp;
17035
17040
  latestRecordAt = latestIso([latestRecordAt, timestamp]);
17036
- const payload = asRecord3(record10.payload);
17037
- if (record10.type === "event_msg" && payload) {
17041
+ const payload = asRecord3(record11.payload);
17042
+ if (record11.type === "event_msg" && payload) {
17038
17043
  const type = stringValue3(payload.type);
17039
17044
  if (type === "thread_goal_updated") {
17040
17045
  const goal = asRecord3(payload.goal);
@@ -17100,7 +17105,7 @@ function createCodexRecordParser(input) {
17100
17105
  return;
17101
17106
  }
17102
17107
  }
17103
- const responsePayload = responsePayloadFromCodexRecord(record10, payload);
17108
+ const responsePayload = responsePayloadFromCodexRecord(record11, payload);
17104
17109
  if (!responsePayload) return;
17105
17110
  const providerTurnId = providerTurnIdFromResponsePayload(responsePayload);
17106
17111
  const providerItemId = stringValue3(responsePayload.id);
@@ -17187,7 +17192,7 @@ function createCodexRecordParser(input) {
17187
17192
  if (role === "assistant") {
17188
17193
  const turnId = activeTurnId(providerTurnId);
17189
17194
  const phase = stringValue3(responsePayload.phase);
17190
- const legacyFinalAnswer = record10.type === "message";
17195
+ const legacyFinalAnswer = record11.type === "message";
17191
17196
  const visibleContent = visibleCodexAssistantContent(content);
17192
17197
  if (visibleContent) {
17193
17198
  assistantIndex += 1;
@@ -17341,8 +17346,8 @@ function createCodexRecordParser(input) {
17341
17346
  }
17342
17347
  async function readPromptHistory(codexHome) {
17343
17348
  const entries = /* @__PURE__ */ new Map();
17344
- await readJsonlRecords(path8.join(codexHome, "history.jsonl"), (record10) => {
17345
- const payload = asRecord3(record10);
17349
+ await readJsonlRecords(path8.join(codexHome, "history.jsonl"), (record11) => {
17350
+ const payload = asRecord3(record11);
17346
17351
  const threadId = stringValue3(payload?.session_id);
17347
17352
  const text3 = normalizeTitleText(stringValue3(payload?.text) ?? "");
17348
17353
  const timestamp = isoFromEpochSeconds(numberValue2(payload?.ts));
@@ -17369,8 +17374,8 @@ async function readSessionIndex(codexHome) {
17369
17374
  const entries = /* @__PURE__ */ new Map();
17370
17375
  await readJsonlRecords(
17371
17376
  path8.join(codexHome, "session_index.jsonl"),
17372
- (record10) => {
17373
- const payload = asRecord3(record10);
17377
+ (record11) => {
17378
+ const payload = asRecord3(record11);
17374
17379
  const id = stringValue3(payload?.id);
17375
17380
  if (!id) return;
17376
17381
  entries.set(id, {
@@ -17402,19 +17407,19 @@ async function readCodexSessionMetadata(file) {
17402
17407
  if (cached && cached.mtimeMs === file.stats.mtimeMs && cached.size === file.stats.size)
17403
17408
  return cached.metadata;
17404
17409
  let metadata = { id: null, cwd: null, createdAt: null };
17405
- await readInitialJsonlRecords(file.filePath, 80, (record10) => {
17406
- const payload = asRecord3(record10.payload);
17410
+ await readInitialJsonlRecords(file.filePath, 80, (record11) => {
17411
+ const payload = asRecord3(record11.payload);
17407
17412
  if (!payload) return;
17408
- if (record10.type === "session_meta") {
17413
+ if (record11.type === "session_meta") {
17409
17414
  metadata = {
17410
17415
  id: metadata.id ?? stringValue3(payload.id) ?? stringValue3(payload.session_id),
17411
17416
  cwd: metadata.cwd ?? stringValue3(payload.cwd),
17412
17417
  createdAt: metadata.createdAt ?? isoTimestamp(
17413
- stringValue3(payload.timestamp) ?? stringValue3(record10.timestamp)
17418
+ stringValue3(payload.timestamp) ?? stringValue3(record11.timestamp)
17414
17419
  )
17415
17420
  };
17416
17421
  }
17417
- if (record10.type === "turn_context" && !metadata.cwd) {
17422
+ if (record11.type === "turn_context" && !metadata.cwd) {
17418
17423
  metadata = {
17419
17424
  ...metadata,
17420
17425
  cwd: stringValue3(payload.cwd)
@@ -17445,11 +17450,11 @@ async function statusForCodexHistoryFile(file, fallbackUpdatedAt) {
17445
17450
  let latestKnownGoalRuntime = null;
17446
17451
  let hasRunningMarker = false;
17447
17452
  for (const line of tail.split(/\r?\n/)) {
17448
- const record10 = parseJson(line);
17449
- if (!record10) continue;
17450
- const timestamp = isoTimestamp(record10.timestamp) ?? fallbackUpdatedAt;
17451
- const payload = asRecord3(record10.payload);
17452
- if (record10.type === "event_msg" && payload) {
17453
+ const record11 = parseJson(line);
17454
+ if (!record11) continue;
17455
+ const timestamp = isoTimestamp(record11.timestamp) ?? fallbackUpdatedAt;
17456
+ const payload = asRecord3(record11.payload);
17457
+ if (record11.type === "event_msg" && payload) {
17453
17458
  const type = stringValue3(payload.type);
17454
17459
  if (type === "thread_goal_updated") {
17455
17460
  const goal = asRecord3(payload.goal);
@@ -17478,7 +17483,7 @@ async function statusForCodexHistoryFile(file, fallbackUpdatedAt) {
17478
17483
  }
17479
17484
  continue;
17480
17485
  }
17481
- const responsePayload = responsePayloadFromCodexRecord(record10, payload);
17486
+ const responsePayload = responsePayloadFromCodexRecord(record11, payload);
17482
17487
  if (!responsePayload) continue;
17483
17488
  if (responsePayload.type === "message") {
17484
17489
  const role = stringValue3(responsePayload.role);
@@ -17500,7 +17505,7 @@ async function statusForCodexHistoryFile(file, fallbackUpdatedAt) {
17500
17505
  }
17501
17506
  if (role === "assistant" && content) {
17502
17507
  latestAssistantAt = timestamp;
17503
- if (stringValue3(responsePayload.phase) === "final_answer" || record10.type === "message") {
17508
+ if (stringValue3(responsePayload.phase) === "final_answer" || record11.type === "message") {
17504
17509
  latestFinalAt = timestamp;
17505
17510
  }
17506
17511
  }
@@ -17542,8 +17547,8 @@ async function readJsonlRecords(filePath, onRecord) {
17542
17547
  const reader = createInterface({ input: stream, crlfDelay: Infinity });
17543
17548
  for await (const line of reader) {
17544
17549
  if (!line.trim()) continue;
17545
- const record10 = parseJson(line);
17546
- if (record10) onRecord(record10);
17550
+ const record11 = parseJson(line);
17551
+ if (record11) onRecord(record11);
17547
17552
  }
17548
17553
  }
17549
17554
  async function readInitialJsonlRecords(filePath, maxRecords, onRecord) {
@@ -17553,9 +17558,9 @@ async function readInitialJsonlRecords(filePath, maxRecords, onRecord) {
17553
17558
  try {
17554
17559
  for await (const line of reader) {
17555
17560
  if (!line.trim()) continue;
17556
- const record10 = parseJson(line);
17557
- if (record10) {
17558
- onRecord(record10);
17561
+ const record11 = parseJson(line);
17562
+ if (record11) {
17563
+ onRecord(record11);
17559
17564
  count += 1;
17560
17565
  }
17561
17566
  if (count >= maxRecords) return;
@@ -17591,8 +17596,8 @@ function titleForThread(indexEntry, prompt) {
17591
17596
  );
17592
17597
  }
17593
17598
  function commandFromToolCall(name, args) {
17594
- const record10 = asRecord3(args);
17595
- return stringValue3(record10?.cmd) ?? stringValue3(record10?.command) ?? stringValue3(record10?.tool) ?? name;
17599
+ const record11 = asRecord3(args);
17600
+ return stringValue3(record11?.cmd) ?? stringValue3(record11?.command) ?? stringValue3(record11?.tool) ?? name;
17596
17601
  }
17597
17602
  function commandFromCustomToolCall(name, input) {
17598
17603
  if (name !== "exec") return null;
@@ -17625,10 +17630,10 @@ function isCodexToolCall(type) {
17625
17630
  function isCodexToolCallOutput(type) {
17626
17631
  return type === "function_call_output" || type === "custom_tool_call_output";
17627
17632
  }
17628
- function responsePayloadFromCodexRecord(record10, payload) {
17629
- if (record10.type === "response_item") return payload;
17630
- if (!isLegacyResponseItemType(record10.type)) return null;
17631
- return asRecord3(record10);
17633
+ function responsePayloadFromCodexRecord(record11, payload) {
17634
+ if (record11.type === "response_item") return payload;
17635
+ if (!isLegacyResponseItemType(record11.type)) return null;
17636
+ return asRecord3(record11);
17632
17637
  }
17633
17638
  function providerTurnIdFromResponsePayload(payload) {
17634
17639
  const metadata = asRecord3(
@@ -17686,10 +17691,10 @@ function goalRecordIsActive2(goal) {
17686
17691
  }
17687
17692
  async function latestKnownActiveGoalRuntimeForCodexHistoryFile(file, fallbackUpdatedAt) {
17688
17693
  let latestKnownGoalRuntime = null;
17689
- await readJsonlRecords(file.filePath, (record10) => {
17690
- const timestamp = isoTimestamp(record10.timestamp) ?? fallbackUpdatedAt;
17691
- const payload = asRecord3(record10.payload);
17692
- if (record10.type === "event_msg" && payload) {
17694
+ await readJsonlRecords(file.filePath, (record11) => {
17695
+ const timestamp = isoTimestamp(record11.timestamp) ?? fallbackUpdatedAt;
17696
+ const payload = asRecord3(record11.payload);
17697
+ if (record11.type === "event_msg" && payload) {
17693
17698
  const type = stringValue3(payload.type);
17694
17699
  if (type === "thread_goal_updated") {
17695
17700
  const goal = asRecord3(payload.goal);
@@ -17705,7 +17710,7 @@ async function latestKnownActiveGoalRuntimeForCodexHistoryFile(file, fallbackUpd
17705
17710
  return;
17706
17711
  }
17707
17712
  }
17708
- const responsePayload = responsePayloadFromCodexRecord(record10, payload);
17713
+ const responsePayload = responsePayloadFromCodexRecord(record11, payload);
17709
17714
  if (responsePayload?.type !== "message" || stringValue3(responsePayload.role) !== "user")
17710
17715
  return;
17711
17716
  const internalGoalRuntime = activeGoalRuntimeFromCodexInternalContext(
@@ -17724,21 +17729,21 @@ function sessionMetadataWithCodexGoalRuntime(metadata, goalRuntime) {
17724
17729
  return Object.keys(next).length > 0 ? next : void 0;
17725
17730
  }
17726
17731
  function codexGoalRuntimeFromSessionMetadata(metadata) {
17727
- const record10 = asRecord3(metadata?.codexGoalRuntime);
17728
- if (!record10 || stringValue3(record10.provider) !== "codex") return null;
17729
- const objective = stringValue3(record10.objective);
17730
- const status = stringValue3(record10.status);
17731
- const updatedAt = isoTimestamp(record10.updatedAt);
17732
+ const record11 = asRecord3(metadata?.codexGoalRuntime);
17733
+ if (!record11 || stringValue3(record11.provider) !== "codex") return null;
17734
+ const objective = stringValue3(record11.objective);
17735
+ const status = stringValue3(record11.status);
17736
+ const updatedAt = isoTimestamp(record11.updatedAt);
17732
17737
  if (!objective || !status || !updatedAt) return null;
17733
17738
  return {
17734
17739
  provider: "codex",
17735
17740
  objective,
17736
17741
  status,
17737
17742
  timeUsedSeconds: nonNegativeInteger(
17738
- numberValue2(record10.timeUsedSeconds) ?? 0
17743
+ numberValue2(record11.timeUsedSeconds) ?? 0
17739
17744
  ),
17740
- tokensUsed: nullableNonNegativeInteger(numberValue2(record10.tokensUsed)),
17741
- tokenBudget: nullableNonNegativeInteger(numberValue2(record10.tokenBudget)),
17745
+ tokensUsed: nullableNonNegativeInteger(numberValue2(record11.tokensUsed)),
17746
+ tokenBudget: nullableNonNegativeInteger(numberValue2(record11.tokenBudget)),
17742
17747
  updatedAt
17743
17748
  };
17744
17749
  }
@@ -17781,8 +17786,8 @@ function textFromContent(content) {
17781
17786
  if (!Array.isArray(content)) return "";
17782
17787
  return content.map((item) => {
17783
17788
  if (typeof item === "string") return item;
17784
- const record10 = asRecord3(item);
17785
- return stringValue3(record10?.text) ?? "";
17789
+ const record11 = asRecord3(item);
17790
+ return stringValue3(record11?.text) ?? "";
17786
17791
  }).filter(Boolean).join("\n").trim();
17787
17792
  }
17788
17793
  var CODEX_ATTACHMENT_CONTEXT_PATTERN = /(?:^|\n)\s*<attachments>\s*([\s\S]*?)\s*<\/attachments>\s*/g;
@@ -17874,11 +17879,11 @@ function codexUserContentParts(content) {
17874
17879
  text3.push(item);
17875
17880
  continue;
17876
17881
  }
17877
- const record10 = asRecord3(item);
17878
- const itemText = stringValue3(record10?.text);
17882
+ const record11 = asRecord3(item);
17883
+ const itemText = stringValue3(record11?.text);
17879
17884
  if (itemText) text3.push(itemText);
17880
- const imageUrl = stringValue3(record10?.image_url);
17881
- if (imageUrl && stringValue3(record10?.type) === "input_image")
17885
+ const imageUrl = stringValue3(record11?.image_url);
17886
+ if (imageUrl && stringValue3(record11?.type) === "input_image")
17882
17887
  inputImages.push(imageUrl);
17883
17888
  }
17884
17889
  return {
@@ -19906,11 +19911,11 @@ var WorkspaceLspClient = class {
19906
19911
  }
19907
19912
  handleNotification(method, params) {
19908
19913
  if (method !== "textDocument/publishDiagnostics") return;
19909
- const record10 = asRecord4(params);
19910
- const uri = typeof record10?.uri === "string" ? record10.uri : null;
19914
+ const record11 = asRecord4(params);
19915
+ const uri = typeof record11?.uri === "string" ? record11.uri : null;
19911
19916
  if (!uri?.startsWith("file://")) return;
19912
19917
  const filePath = normalizeAbsolutePath(fileURLToPath(uri));
19913
- const diagnostics = Array.isArray(record10?.diagnostics) ? record10.diagnostics : [];
19918
+ const diagnostics = Array.isArray(record11?.diagnostics) ? record11.diagnostics : [];
19914
19919
  this.diagnostics.set(
19915
19920
  filePath,
19916
19921
  diagnostics.map((item) => normalizeDiagnostic(filePath, item)).filter(Boolean)
@@ -19961,11 +19966,11 @@ function assertLspTextSize(sizeBytes, filePath) {
19961
19966
  );
19962
19967
  }
19963
19968
  function normalizeDiagnostic(filePath, value) {
19964
- const record10 = asRecord4(value);
19965
- const range = asRecord4(record10?.range);
19969
+ const record11 = asRecord4(value);
19970
+ const range = asRecord4(record11?.range);
19966
19971
  const start = asRecord4(range?.start);
19967
19972
  const end = asRecord4(range?.end);
19968
- if (!record10 || !range || !start || !end || typeof record10.message !== "string") return null;
19973
+ if (!record11 || !range || !start || !end || typeof record11.message !== "string") return null;
19969
19974
  return {
19970
19975
  path: filePath,
19971
19976
  range: {
@@ -19978,10 +19983,10 @@ function normalizeDiagnostic(filePath, value) {
19978
19983
  character: numberOrZero(end.character)
19979
19984
  }
19980
19985
  },
19981
- severity: severityName(record10.severity),
19982
- message: record10.message,
19983
- source: typeof record10.source === "string" ? record10.source : null,
19984
- code: typeof record10.code === "string" || typeof record10.code === "number" ? String(record10.code) : null
19986
+ severity: severityName(record11.severity),
19987
+ message: record11.message,
19988
+ source: typeof record11.source === "string" ? record11.source : null,
19989
+ code: typeof record11.code === "string" || typeof record11.code === "number" ? String(record11.code) : null
19985
19990
  };
19986
19991
  }
19987
19992
  function severityName(input) {
@@ -20776,8 +20781,8 @@ function asRecord5(value) {
20776
20781
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
20777
20782
  }
20778
20783
  function nonEmptyRecord(value) {
20779
- const record10 = asRecord5(value);
20780
- return Object.keys(record10).length > 0 ? record10 : null;
20784
+ const record11 = asRecord5(value);
20785
+ return Object.keys(record11).length > 0 ? record11 : null;
20781
20786
  }
20782
20787
  function asRecordArray(value) {
20783
20788
  return Array.isArray(value) ? value.map(asRecord5).filter((item) => Object.keys(item).length > 0) : [];
@@ -21751,11 +21756,11 @@ function sha256Hex(contents) {
21751
21756
  function dependencySetupCommands(value) {
21752
21757
  if (!value || typeof value !== "object" || Array.isArray(value))
21753
21758
  return [];
21754
- const record10 = value;
21755
- if (Array.isArray(record10.commands)) {
21756
- return record10.commands.filter((command) => typeof command === "string" && command.trim() !== "");
21759
+ const record11 = value;
21760
+ if (Array.isArray(record11.commands)) {
21761
+ return record11.commands.filter((command) => typeof command === "string" && command.trim() !== "");
21757
21762
  }
21758
- return typeof record10.installCommand === "string" && record10.installCommand.trim() ? [record10.installCommand.trim()] : [];
21763
+ return typeof record11.installCommand === "string" && record11.installCommand.trim() ? [record11.installCommand.trim()] : [];
21759
21764
  }
21760
21765
  function mergeManifestSetupCommands(manifest, commands) {
21761
21766
  if (commands.length === 0)
@@ -22143,12 +22148,12 @@ async function readJsonFileIfExists(filePath) {
22143
22148
  return null;
22144
22149
  }
22145
22150
  }
22146
- function setupRequirementIdentity(record10) {
22151
+ function setupRequirementIdentity(record11) {
22147
22152
  return [
22148
- text(record10.actionId) ?? "",
22149
- text(record10.actionName) ?? "",
22150
- text(record10.kind) ?? text(record10.type) ?? "",
22151
- text(record10.label) ?? text(record10.name) ?? text(record10.key) ?? text(record10.provider) ?? text(record10.tool) ?? text(record10.command) ?? text(record10.packageName) ?? ""
22153
+ text(record11.actionId) ?? "",
22154
+ text(record11.actionName) ?? "",
22155
+ text(record11.kind) ?? text(record11.type) ?? "",
22156
+ text(record11.label) ?? text(record11.name) ?? text(record11.key) ?? text(record11.provider) ?? text(record11.tool) ?? text(record11.command) ?? text(record11.packageName) ?? ""
22152
22157
  ].join(":");
22153
22158
  }
22154
22159
  function readAgentSdkProjectPackageJson(projectPath) {
@@ -25199,15 +25204,15 @@ function usageTotals(records, rangeEnd) {
25199
25204
  let failedRequests = 0;
25200
25205
  let missingUsageRequests = 0;
25201
25206
  let longestRequestMs = null;
25202
- for (const record10 of records) {
25203
- addRecord(totals, record10);
25204
- models.add(`${record10.provider}\0${record10.model}`);
25205
- activeDateKeys.add(localDateKey(record10.startedAt));
25206
- if (record10.status === "completed") completedRequests += 1;
25207
- if (record10.status === "failed") failedRequests += 1;
25208
- if (record10.source === "missing") missingUsageRequests += 1;
25209
- if (record10.durationMs !== null) {
25210
- longestRequestMs = Math.max(longestRequestMs ?? 0, record10.durationMs);
25207
+ for (const record11 of records) {
25208
+ addRecord(totals, record11);
25209
+ models.add(`${record11.provider}\0${record11.model}`);
25210
+ activeDateKeys.add(localDateKey(record11.startedAt));
25211
+ if (record11.status === "completed") completedRequests += 1;
25212
+ if (record11.status === "failed") failedRequests += 1;
25213
+ if (record11.source === "missing") missingUsageRequests += 1;
25214
+ if (record11.durationMs !== null) {
25215
+ longestRequestMs = Math.max(longestRequestMs ?? 0, record11.durationMs);
25211
25216
  }
25212
25217
  }
25213
25218
  const daily = dailyBuckets(records);
@@ -25272,21 +25277,21 @@ function localDayDistance(left, right) {
25272
25277
  }
25273
25278
  function dailyBuckets(records) {
25274
25279
  const days = /* @__PURE__ */ new Map();
25275
- for (const record10 of records) {
25276
- const date = localDateKey(record10.startedAt);
25277
- const modelKey = `${record10.provider}\0${record10.model}`;
25280
+ for (const record11 of records) {
25281
+ const date = localDateKey(record11.startedAt);
25282
+ const modelKey = `${record11.provider}\0${record11.model}`;
25278
25283
  let models = days.get(date);
25279
25284
  if (!models) {
25280
25285
  models = /* @__PURE__ */ new Map();
25281
25286
  days.set(date, models);
25282
25287
  }
25283
25288
  const current = models.get(modelKey) ?? {
25284
- provider: record10.provider,
25285
- model: record10.model,
25289
+ provider: record11.provider,
25290
+ model: record11.model,
25286
25291
  totalTokens: 0,
25287
25292
  requests: 0
25288
25293
  };
25289
- current.totalTokens += record10.totalTokens ?? 0;
25294
+ current.totalTokens += record11.totalTokens ?? 0;
25290
25295
  current.requests += 1;
25291
25296
  models.set(modelKey, current);
25292
25297
  }
@@ -25304,15 +25309,15 @@ function dailyBuckets(records) {
25304
25309
  }
25305
25310
  function modelBreakdowns(records) {
25306
25311
  const groups = /* @__PURE__ */ new Map();
25307
- for (const record10 of records) {
25308
- const key = `${record10.provider}\0${record10.model}\0${record10.route}`;
25312
+ for (const record11 of records) {
25313
+ const key = `${record11.provider}\0${record11.model}\0${record11.route}`;
25309
25314
  const group = groups.get(key) ?? {
25310
- provider: record10.provider,
25311
- model: record10.model,
25312
- route: record10.route,
25315
+ provider: record11.provider,
25316
+ model: record11.model,
25317
+ route: record11.route,
25313
25318
  totals: accumulator()
25314
25319
  };
25315
- addRecord(group.totals, record10);
25320
+ addRecord(group.totals, record11);
25316
25321
  groups.set(key, group);
25317
25322
  }
25318
25323
  return [...groups.values()].map((group) => ({
@@ -25324,11 +25329,11 @@ function modelBreakdowns(records) {
25324
25329
  }
25325
25330
  function threadBreakdowns(records, sessionById) {
25326
25331
  const groups = /* @__PURE__ */ new Map();
25327
- for (const record10 of records) {
25328
- if (!record10.sessionId) continue;
25329
- const totals = groups.get(record10.sessionId) ?? accumulator();
25330
- addRecord(totals, record10);
25331
- groups.set(record10.sessionId, totals);
25332
+ for (const record11 of records) {
25333
+ if (!record11.sessionId) continue;
25334
+ const totals = groups.get(record11.sessionId) ?? accumulator();
25335
+ addRecord(totals, record11);
25336
+ groups.set(record11.sessionId, totals);
25332
25337
  }
25333
25338
  return [...groups.entries()].map(([sessionId, totals]) => {
25334
25339
  const session = sessionById.get(sessionId);
@@ -25343,17 +25348,17 @@ function threadBreakdowns(records, sessionById) {
25343
25348
  }
25344
25349
  function commandBreakdowns(records) {
25345
25350
  const groups = /* @__PURE__ */ new Map();
25346
- for (const record10 of records) {
25347
- const commandName = record10.attribution.commandName;
25351
+ for (const record11 of records) {
25352
+ const commandName = record11.attribution.commandName;
25348
25353
  if (!commandName) continue;
25349
- const commandSource = record10.attribution.commandSource;
25354
+ const commandSource = record11.attribution.commandSource;
25350
25355
  const key = `${commandName}\0${commandSource ?? ""}`;
25351
25356
  const group = groups.get(key) ?? {
25352
25357
  commandName,
25353
25358
  commandSource,
25354
25359
  totals: accumulator()
25355
25360
  };
25356
- addRecord(group.totals, record10);
25361
+ addRecord(group.totals, record11);
25357
25362
  groups.set(key, group);
25358
25363
  }
25359
25364
  return [...groups.values()].map((group) => ({
@@ -25364,10 +25369,10 @@ function commandBreakdowns(records) {
25364
25369
  }
25365
25370
  function routeBreakdowns(records) {
25366
25371
  const groups = /* @__PURE__ */ new Map();
25367
- for (const record10 of records) {
25368
- const totals = groups.get(record10.route) ?? accumulator();
25369
- addRecord(totals, record10);
25370
- groups.set(record10.route, totals);
25372
+ for (const record11 of records) {
25373
+ const totals = groups.get(record11.route) ?? accumulator();
25374
+ addRecord(totals, record11);
25375
+ groups.set(record11.route, totals);
25371
25376
  }
25372
25377
  return [...groups.entries()].map(([route, totals]) => ({
25373
25378
  route,
@@ -25376,10 +25381,10 @@ function routeBreakdowns(records) {
25376
25381
  }
25377
25382
  function statusBreakdowns(records) {
25378
25383
  const groups = /* @__PURE__ */ new Map();
25379
- for (const record10 of records) {
25380
- const totals = groups.get(record10.status) ?? accumulator();
25381
- addRecord(totals, record10);
25382
- groups.set(record10.status, totals);
25384
+ for (const record11 of records) {
25385
+ const totals = groups.get(record11.status) ?? accumulator();
25386
+ addRecord(totals, record11);
25387
+ groups.set(record11.status, totals);
25383
25388
  }
25384
25389
  return [...groups.entries()].map(([status, totals]) => ({
25385
25390
  status,
@@ -25388,10 +25393,10 @@ function statusBreakdowns(records) {
25388
25393
  }
25389
25394
  function sourceBreakdowns(records) {
25390
25395
  const groups = /* @__PURE__ */ new Map();
25391
- for (const record10 of records) {
25392
- const totals = groups.get(record10.source) ?? accumulator();
25393
- addRecord(totals, record10);
25394
- groups.set(record10.source, totals);
25396
+ for (const record11 of records) {
25397
+ const totals = groups.get(record11.source) ?? accumulator();
25398
+ addRecord(totals, record11);
25399
+ groups.set(record11.source, totals);
25395
25400
  }
25396
25401
  return [...groups.entries()].map(([source, totals]) => ({
25397
25402
  source,
@@ -25414,28 +25419,28 @@ function accumulator() {
25414
25419
  lastSeenAt: null
25415
25420
  };
25416
25421
  }
25417
- function addRecord(accumulator2, record10) {
25422
+ function addRecord(accumulator2, record11) {
25418
25423
  accumulator2.requests += 1;
25419
- if (record10.promptTokens !== null) {
25420
- accumulator2.promptTokens += record10.promptTokens;
25424
+ if (record11.promptTokens !== null) {
25425
+ accumulator2.promptTokens += record11.promptTokens;
25421
25426
  accumulator2.promptTokenRows += 1;
25422
25427
  }
25423
- if (record10.completionTokens !== null) {
25424
- accumulator2.completionTokens += record10.completionTokens;
25428
+ if (record11.completionTokens !== null) {
25429
+ accumulator2.completionTokens += record11.completionTokens;
25425
25430
  accumulator2.completionTokenRows += 1;
25426
25431
  }
25427
- if (record10.totalTokens !== null) {
25428
- accumulator2.totalTokens += record10.totalTokens;
25432
+ if (record11.totalTokens !== null) {
25433
+ accumulator2.totalTokens += record11.totalTokens;
25429
25434
  accumulator2.totalTokenRows += 1;
25430
25435
  }
25431
- if (record10.durationMs !== null) accumulator2.durations.push(record10.durationMs);
25432
- if (record10.firstTokenMs !== null) accumulator2.firstTokenDurations.push(record10.firstTokenMs);
25433
- if (record10.status === "failed" || record10.status === "interrupted") accumulator2.failures += 1;
25434
- if (!accumulator2.firstSeenAt || record10.startedAt < accumulator2.firstSeenAt) {
25435
- accumulator2.firstSeenAt = record10.startedAt;
25436
+ if (record11.durationMs !== null) accumulator2.durations.push(record11.durationMs);
25437
+ if (record11.firstTokenMs !== null) accumulator2.firstTokenDurations.push(record11.firstTokenMs);
25438
+ if (record11.status === "failed" || record11.status === "interrupted") accumulator2.failures += 1;
25439
+ if (!accumulator2.firstSeenAt || record11.startedAt < accumulator2.firstSeenAt) {
25440
+ accumulator2.firstSeenAt = record11.startedAt;
25436
25441
  }
25437
- if (!accumulator2.lastSeenAt || record10.startedAt > accumulator2.lastSeenAt) {
25438
- accumulator2.lastSeenAt = record10.startedAt;
25442
+ if (!accumulator2.lastSeenAt || record11.startedAt > accumulator2.lastSeenAt) {
25443
+ accumulator2.lastSeenAt = record11.startedAt;
25439
25444
  }
25440
25445
  }
25441
25446
  function breakdownTotals(accumulator2) {
@@ -26752,12 +26757,12 @@ function signedLocalVideoUrlPayload(input, requestUrl, token) {
26752
26757
  return { url: url.toString(), expiresAt };
26753
26758
  }
26754
26759
  function signedChatAttachmentImageUrlPayload(input, requestUrl, token) {
26755
- const record10 = inputRecord(input);
26756
- const sessionId = requiredSignedAssetString(record10.sessionId, "sessionId", 200);
26757
- const turnId = requiredSignedAssetString(record10.turnId, "turnId", 200);
26758
- const attachmentId = requiredSignedAssetString(record10.attachmentId, "attachmentId", 200);
26759
- const rawStorageName = requiredSignedAssetString(record10.storageName, "storageName", 240);
26760
- const rawContentType = requiredSignedAssetString(record10.contentType, "contentType", 160);
26760
+ const record11 = inputRecord(input);
26761
+ const sessionId = requiredSignedAssetString(record11.sessionId, "sessionId", 200);
26762
+ const turnId = requiredSignedAssetString(record11.turnId, "turnId", 200);
26763
+ const attachmentId = requiredSignedAssetString(record11.attachmentId, "attachmentId", 200);
26764
+ const rawStorageName = requiredSignedAssetString(record11.storageName, "storageName", 240);
26765
+ const rawContentType = requiredSignedAssetString(record11.contentType, "contentType", 160);
26761
26766
  const storageName = normalizeSignedChatAttachmentStorageName(rawStorageName);
26762
26767
  const contentType2 = normalizeSignedChatAttachmentContentType(rawContentType);
26763
26768
  if (!storageName) throw new Error("Chat attachment image storage name is invalid.");
@@ -27066,10 +27071,10 @@ async function handleExtensionRoute({
27066
27071
  if (request.method === "POST" && updateMatch) {
27067
27072
  const source = decodedSource(updateMatch[1], updateMatch[2]);
27068
27073
  const body = await readJson(request);
27069
- const record10 = body && typeof body === "object" && !Array.isArray(body) ? body : {};
27074
+ const record11 = body && typeof body === "object" && !Array.isArray(body) ? body : {};
27070
27075
  sendJson(response, 200, await deps.extensionUpdatePayload({
27071
27076
  source,
27072
- ...typeof record10.ref === "string" ? { ref: record10.ref } : {}
27077
+ ...typeof record11.ref === "string" ? { ref: record11.ref } : {}
27073
27078
  }));
27074
27079
  return true;
27075
27080
  }
@@ -27103,6 +27108,18 @@ async function handleHarnessRoutes({
27103
27108
  sendJson(response, 200, await deps.updateHarnessBackgroundReviewPayload(await readJson(request)));
27104
27109
  return true;
27105
27110
  }
27111
+ if (request.method === "POST" && requestUrl.pathname === "/v1/harness/evaluation-review") {
27112
+ sendJson(response, 200, await deps.reviewHarnessEvaluationPayload(await readJson(request)));
27113
+ return true;
27114
+ }
27115
+ if (request.method === "POST" && requestUrl.pathname === "/v1/harness/evaluation-review/settings") {
27116
+ sendJson(
27117
+ response,
27118
+ 200,
27119
+ await deps.updateHarnessEvaluationReviewSchedulePayload(await readJson(request))
27120
+ );
27121
+ return true;
27122
+ }
27106
27123
  if (request.method === "POST" && requestUrl.pathname === "/v1/harness/diff") {
27107
27124
  sendJson(response, 200, await deps.harnessDiffPayload(await readJson(request)));
27108
27125
  return true;
@@ -30576,9 +30593,9 @@ function localSandboxTemplateUploadsArg(value) {
30576
30593
  if (!Array.isArray(value)) return [];
30577
30594
  return value.flatMap((item) => {
30578
30595
  if (!item || typeof item !== "object" || Array.isArray(item)) return [];
30579
- const record10 = item;
30580
- const uploadPath = typeof record10.path === "string" ? record10.path.trim() : "";
30581
- const contentsBase64 = typeof record10.contentsBase64 === "string" ? record10.contentsBase64 : "";
30596
+ const record11 = item;
30597
+ const uploadPath = typeof record11.path === "string" ? record11.path.trim() : "";
30598
+ const contentsBase64 = typeof record11.contentsBase64 === "string" ? record11.contentsBase64 : "";
30582
30599
  return uploadPath && contentsBase64 ? [{ path: uploadPath, contentsBase64 }] : [];
30583
30600
  });
30584
30601
  }
@@ -30591,12 +30608,12 @@ function sandboxTemplateEnvArg(value) {
30591
30608
  if (!item || typeof item !== "object" || Array.isArray(item)) {
30592
30609
  throw new Error("Sandbox template env entries must be objects.");
30593
30610
  }
30594
- const record10 = item;
30595
- if ("value" in record10) {
30611
+ const record11 = item;
30612
+ if ("value" in record11) {
30596
30613
  throw new Error("Sandbox template env entries must use secretRef, not inline values.");
30597
30614
  }
30598
- const name = typeof record10.name === "string" ? record10.name.trim() : "";
30599
- const secretRef = typeof record10.secretRef === "string" ? record10.secretRef.trim() : "";
30615
+ const name = typeof record11.name === "string" ? record11.name.trim() : "";
30616
+ const secretRef = typeof record11.secretRef === "string" ? record11.secretRef.trim() : "";
30600
30617
  if (!name || !secretRef) {
30601
30618
  throw new Error("Sandbox template env entries require name and secretRef.");
30602
30619
  }
@@ -31434,8 +31451,8 @@ function sandboxRecordsFromPayload(payload) {
31434
31451
  const sandboxes = asRecord8(payload).sandboxes;
31435
31452
  if (!Array.isArray(sandboxes)) return [];
31436
31453
  return sandboxes.flatMap((sandbox) => {
31437
- const record10 = linkedSandboxRecord(sandbox);
31438
- return record10 ? [record10] : [];
31454
+ const record11 = linkedSandboxRecord(sandbox);
31455
+ return record11 ? [record11] : [];
31439
31456
  });
31440
31457
  }
31441
31458
  function sandboxRecordFromPayload(payload) {
@@ -31456,17 +31473,17 @@ function mergeSandboxRuntimeSandboxPayload(runtimePayload, sandboxPayload) {
31456
31473
  };
31457
31474
  }
31458
31475
  function linkedSandboxRecord(value) {
31459
- const record10 = asRecord8(value);
31460
- const id = typeof record10.id === "string" ? record10.id.trim() : "";
31461
- const state = typeof record10.state === "string" ? record10.state.trim() : "";
31476
+ const record11 = asRecord8(value);
31477
+ const id = typeof record11.id === "string" ? record11.id.trim() : "";
31478
+ const state = typeof record11.state === "string" ? record11.state.trim() : "";
31462
31479
  if (!id || !state) return null;
31463
31480
  return {
31464
31481
  id,
31465
31482
  state,
31466
- repo: typeof record10.repo === "string" ? record10.repo : null,
31467
- metadata: asRecord8(record10.metadata),
31468
- createdAt: typeof record10.createdAt === "string" ? record10.createdAt : null,
31469
- updatedAt: typeof record10.updatedAt === "string" ? record10.updatedAt : null
31483
+ repo: typeof record11.repo === "string" ? record11.repo : null,
31484
+ metadata: asRecord8(record11.metadata),
31485
+ createdAt: typeof record11.createdAt === "string" ? record11.createdAt : null,
31486
+ updatedAt: typeof record11.updatedAt === "string" ? record11.updatedAt : null
31470
31487
  };
31471
31488
  }
31472
31489
  function sandboxCommandFromPayload(payload) {
@@ -32958,9 +32975,9 @@ async function waitForRecoveredSandboxCreate(input) {
32958
32975
  ...input.agentId ? { agentId: input.agentId } : {}
32959
32976
  }
32960
32977
  });
32961
- const record10 = asRecord9(payload);
32962
- const account2 = record10.account;
32963
- const sandboxes = Array.isArray(record10.sandboxes) ? record10.sandboxes : [];
32978
+ const record11 = asRecord9(payload);
32979
+ const account2 = record11.account;
32980
+ const sandboxes = Array.isArray(record11.sandboxes) ? record11.sandboxes : [];
32964
32981
  const match = sandboxes.map(asRecord9).find((sandbox) => sandboxMatchesCreateRequest(sandbox, input));
32965
32982
  if (match) {
32966
32983
  latestMatch = { sandbox: match, account: account2 };
@@ -32997,10 +33014,10 @@ async function readSandboxRecoveryLogs(sandboxId2) {
32997
33014
  }
32998
33015
  function formatSandboxLogLine(value) {
32999
33016
  if (typeof value === "string") return value.trim();
33000
- const record10 = asRecord9(value);
33001
- const timestamp = typeof record10.timestamp === "string" ? record10.timestamp : "";
33002
- const level = typeof record10.level === "string" ? record10.level : "";
33003
- const message3 = typeof record10.message === "string" ? record10.message : typeof record10.output === "string" ? record10.output : typeof record10.line === "string" ? record10.line : "";
33017
+ const record11 = asRecord9(value);
33018
+ const timestamp = typeof record11.timestamp === "string" ? record11.timestamp : "";
33019
+ const level = typeof record11.level === "string" ? record11.level : "";
33020
+ const message3 = typeof record11.message === "string" ? record11.message : typeof record11.output === "string" ? record11.output : typeof record11.line === "string" ? record11.line : "";
33004
33021
  return [timestamp, level, message3].filter(Boolean).join(" ").trim();
33005
33022
  }
33006
33023
  function sandboxCreateRecoveryMessage(sandbox, logs) {
@@ -34029,8 +34046,8 @@ function fileOutputRefs(value, depth = 0) {
34029
34046
  if (Array.isArray(value)) {
34030
34047
  return value.flatMap((item) => fileOutputRefs(item, depth + 1));
34031
34048
  }
34032
- const record10 = asRecord10(value);
34033
- return Object.values(record10).flatMap(
34049
+ const record11 = asRecord10(value);
34050
+ return Object.values(record11).flatMap(
34034
34051
  (child) => fileOutputRefs(child, depth + 1)
34035
34052
  );
34036
34053
  }
@@ -34157,8 +34174,8 @@ function findOutputRef(value, depth = 0) {
34157
34174
  }
34158
34175
  return null;
34159
34176
  }
34160
- const record10 = asRecord10(value);
34161
- for (const child of Object.values(record10)) {
34177
+ const record11 = asRecord10(value);
34178
+ for (const child of Object.values(record11)) {
34162
34179
  const outputRef = findOutputRef(child, depth + 1);
34163
34180
  if (outputRef) return outputRef;
34164
34181
  }
@@ -34180,9 +34197,9 @@ function findOutputRefById(value, outputId, revision, depth = 0) {
34180
34197
  }
34181
34198
  return latest2;
34182
34199
  }
34183
- const record10 = asRecord10(value);
34200
+ const record11 = asRecord10(value);
34184
34201
  let latest = null;
34185
- for (const child of Object.values(record10)) {
34202
+ for (const child of Object.values(record11)) {
34186
34203
  const outputRef = findOutputRefById(child, outputId, revision, depth + 1);
34187
34204
  if (outputRef && (!latest || outputRef.revision > latest.revision)) {
34188
34205
  latest = outputRef;
@@ -34954,11 +34971,11 @@ function nestedString(value, keys, depth = 0) {
34954
34971
  }
34955
34972
  return null;
34956
34973
  }
34957
- const record10 = value;
34974
+ const record11 = value;
34958
34975
  for (const key of keys) {
34959
- if (typeof record10[key] === "string" && record10[key]) return record10[key];
34976
+ if (typeof record11[key] === "string" && record11[key]) return record11[key];
34960
34977
  }
34961
- for (const child of Object.values(record10)) {
34978
+ for (const child of Object.values(record11)) {
34962
34979
  const found = nestedString(child, keys, depth + 1);
34963
34980
  if (found) return found;
34964
34981
  }
@@ -34973,11 +34990,11 @@ function nestedNumber(value, keys, depth = 0) {
34973
34990
  }
34974
34991
  return null;
34975
34992
  }
34976
- const record10 = value;
34993
+ const record11 = value;
34977
34994
  for (const key of keys) {
34978
- if (typeof record10[key] === "number" && Number.isFinite(record10[key])) return record10[key];
34995
+ if (typeof record11[key] === "number" && Number.isFinite(record11[key])) return record11[key];
34979
34996
  }
34980
- for (const child of Object.values(record10)) {
34997
+ for (const child of Object.values(record11)) {
34981
34998
  const found = nestedNumber(child, keys, depth + 1);
34982
34999
  if (found !== null) return found;
34983
35000
  }
@@ -34992,9 +35009,9 @@ function findRecordWithKey(value, key, depth = 0) {
34992
35009
  }
34993
35010
  return null;
34994
35011
  }
34995
- const record10 = value;
34996
- if (key in record10) return record10;
34997
- for (const child of Object.values(record10)) {
35012
+ const record11 = value;
35013
+ if (key in record11) return record11;
35014
+ for (const child of Object.values(record11)) {
34998
35015
  const found = findRecordWithKey(child, key, depth + 1);
34999
35016
  if (found) return found;
35000
35017
  }
@@ -35025,9 +35042,9 @@ function receiptTiming(turn) {
35025
35042
  }
35026
35043
  function usageSummary(records) {
35027
35044
  return {
35028
- promptTokens: sumKnown(records.map((record10) => record10.promptTokens)),
35029
- completionTokens: sumKnown(records.map((record10) => record10.completionTokens)),
35030
- totalTokens: sumKnown(records.map((record10) => record10.totalTokens))
35045
+ promptTokens: sumKnown(records.map((record11) => record11.promptTokens)),
35046
+ completionTokens: sumKnown(records.map((record11) => record11.completionTokens)),
35047
+ totalTokens: sumKnown(records.map((record11) => record11.totalTokens))
35031
35048
  };
35032
35049
  }
35033
35050
  function sumKnown(values) {
@@ -35995,8 +36012,8 @@ function sha2562(bytes2) {
35995
36012
  return createHash8("sha256").update(bytes2).digest("hex");
35996
36013
  }
35997
36014
  function nullableRecord(value) {
35998
- const record10 = asRecord11(value);
35999
- return Object.keys(record10).length > 0 ? record10 : null;
36015
+ const record11 = asRecord11(value);
36016
+ return Object.keys(record11).length > 0 ? record11 : null;
36000
36017
  }
36001
36018
  function asRecord11(value) {
36002
36019
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
@@ -36582,23 +36599,23 @@ function parseTailscaleVersion(result) {
36582
36599
  return result.stdout.split(/\r?\n/).find((line) => line.trim())?.trim() ?? null;
36583
36600
  }
36584
36601
  function peerFromRecord(value, isSelf) {
36585
- const record10 = asRecord12(value);
36586
- if (!record10) return null;
36587
- const id = stringValue9(record10.ID) ?? stringValue9(record10.PublicKey) ?? (isSelf ? "self" : null);
36602
+ const record11 = asRecord12(value);
36603
+ if (!record11) return null;
36604
+ const id = stringValue9(record11.ID) ?? stringValue9(record11.PublicKey) ?? (isSelf ? "self" : null);
36588
36605
  if (!id) return null;
36589
- const hostName = stringValue9(record10.HostName);
36590
- const dnsName = normalizeDnsName(record10.DNSName);
36606
+ const hostName = stringValue9(record11.HostName);
36607
+ const dnsName = normalizeDnsName(record11.DNSName);
36591
36608
  const name = hostName ?? dnsName ?? id;
36592
36609
  return {
36593
36610
  id,
36594
36611
  name,
36595
36612
  dnsName,
36596
- os: stringValue9(record10.OS),
36597
- online: booleanValue2(record10.Online),
36598
- active: booleanValue2(record10.Active),
36613
+ os: stringValue9(record11.OS),
36614
+ online: booleanValue2(record11.Online),
36615
+ active: booleanValue2(record11.Active),
36599
36616
  isSelf,
36600
- tailscaleIps: stringArray4(record10.TailscaleIPs),
36601
- lastSeen: normalizeTimestamp(record10.LastSeen)
36617
+ tailscaleIps: stringArray4(record11.TailscaleIPs),
36618
+ lastSeen: normalizeTimestamp(record11.LastSeen)
36602
36619
  };
36603
36620
  }
36604
36621
  function tailscaleBaseUrl(state) {
@@ -36666,8 +36683,8 @@ function valueContainsTarget(value, port) {
36666
36683
  return value.includes(`127.0.0.1:${port}`) || value.includes(`localhost:${port}`);
36667
36684
  }
36668
36685
  if (Array.isArray(value)) return value.some((item) => valueContainsTarget(item, port));
36669
- const record10 = asRecord12(value);
36670
- return record10 ? Object.values(record10).some((item) => valueContainsTarget(item, port)) : false;
36686
+ const record11 = asRecord12(value);
36687
+ return record11 ? Object.values(record11).some((item) => valueContainsTarget(item, port)) : false;
36671
36688
  }
36672
36689
  function targetUrlFromValue(value, port) {
36673
36690
  if (typeof value === "string" && valueContainsTarget(value, port)) return value;
@@ -36677,9 +36694,9 @@ function targetUrlFromValue(value, port) {
36677
36694
  if (target) return target;
36678
36695
  }
36679
36696
  }
36680
- const record10 = asRecord12(value);
36681
- if (!record10) return null;
36682
- for (const [key, item] of Object.entries(record10)) {
36697
+ const record11 = asRecord12(value);
36698
+ if (!record11) return null;
36699
+ for (const [key, item] of Object.entries(record11)) {
36683
36700
  if ((key.toLowerCase() === "proxy" || key.toLowerCase() === "target") && typeof item === "string" && valueContainsTarget(item, port)) {
36684
36701
  return item;
36685
36702
  }
@@ -36689,9 +36706,9 @@ function targetUrlFromValue(value, port) {
36689
36706
  return null;
36690
36707
  }
36691
36708
  function findEndpoint(value, port) {
36692
- const record10 = asRecord12(value);
36693
- if (!record10) return null;
36694
- for (const [key, item] of Object.entries(record10)) {
36709
+ const record11 = asRecord12(value);
36710
+ if (!record11) return null;
36711
+ for (const [key, item] of Object.entries(record11)) {
36695
36712
  const endpoint = endpointFromKey(key);
36696
36713
  if (endpoint && valueContainsTarget(item, port)) {
36697
36714
  return {
@@ -37033,9 +37050,9 @@ function createVoiceTranscriptionService(input) {
37033
37050
  return { close, status, transcribe };
37034
37051
  }
37035
37052
  function parseVoiceTranscriptionRequest(payload) {
37036
- const record10 = payload && typeof payload === "object" ? payload : {};
37037
- const audioBase64 = typeof record10.audioBase64 === "string" ? record10.audioBase64.trim() : "";
37038
- const mimeType = typeof record10.mimeType === "string" ? record10.mimeType.trim() : "";
37053
+ const record11 = payload && typeof payload === "object" ? payload : {};
37054
+ const audioBase64 = typeof record11.audioBase64 === "string" ? record11.audioBase64.trim() : "";
37055
+ const mimeType = typeof record11.mimeType === "string" ? record11.mimeType.trim() : "";
37039
37056
  if (!audioBase64) throw new Error("Voice transcription requires audio.");
37040
37057
  if (mimeType && mimeType !== "audio/wav" && mimeType !== "audio/wave") {
37041
37058
  throw new Error(`Unsupported voice audio format: ${mimeType}`);
@@ -37043,8 +37060,8 @@ function parseVoiceTranscriptionRequest(payload) {
37043
37060
  return {
37044
37061
  audioBase64,
37045
37062
  mimeType: mimeType || "audio/wav",
37046
- durationMs: typeof record10.durationMs === "number" && Number.isFinite(record10.durationMs) ? Math.max(0, Math.round(record10.durationMs)) : void 0,
37047
- language: typeof record10.language === "string" && record10.language.trim() ? record10.language.trim() : void 0
37063
+ durationMs: typeof record11.durationMs === "number" && Number.isFinite(record11.durationMs) ? Math.max(0, Math.round(record11.durationMs)) : void 0,
37064
+ language: typeof record11.language === "string" && record11.language.trim() ? record11.language.trim() : void 0
37048
37065
  };
37049
37066
  }
37050
37067
  async function runWhisper(input) {
@@ -37275,9 +37292,9 @@ function createBrowserControlQueue(input = {}) {
37275
37292
  scroll: (request) => enqueue("scroll", "openpond_browser_scroll", request)
37276
37293
  };
37277
37294
  function registerDesktopExecutor(payload) {
37278
- const record10 = asRecord13(payload);
37279
- const executorToken = stringField(record10, "executorToken");
37280
- const instanceId = optionalStringField(record10, "instanceId") ?? `desktop_${randomUUID14()}`;
37295
+ const record11 = asRecord13(payload);
37296
+ const executorToken = stringField(record11, "executorToken");
37297
+ const instanceId = optionalStringField(record11, "instanceId") ?? `desktop_${randomUUID14()}`;
37281
37298
  if (!executorToken) throw new Error("executorToken is required");
37282
37299
  desktop = {
37283
37300
  executorToken,
@@ -37445,18 +37462,18 @@ function serializeBrowserInput(input) {
37445
37462
  return rest;
37446
37463
  }
37447
37464
  function parseBrowserControlResult(toolName, payload) {
37448
- const record10 = asRecord13(payload);
37449
- if (!record10) {
37465
+ const record11 = asRecord13(payload);
37466
+ if (!record11) {
37450
37467
  return {
37451
37468
  ok: false,
37452
37469
  action: toolName,
37453
37470
  output: "Browser action returned an invalid result."
37454
37471
  };
37455
37472
  }
37456
- const ok = record10.ok === true;
37457
- const output = typeof record10.output === "string" && record10.output.trim() ? record10.output.trim() : ok ? "Browser action completed." : "Browser action failed.";
37458
- const data = asRecord13(record10.data) ?? void 0;
37459
- const metadata = parseBrowserMetadata(record10.metadata);
37473
+ const ok = record11.ok === true;
37474
+ const output = typeof record11.output === "string" && record11.output.trim() ? record11.output.trim() : ok ? "Browser action completed." : "Browser action failed.";
37475
+ const data = asRecord13(record11.data) ?? void 0;
37476
+ const metadata = parseBrowserMetadata(record11.metadata);
37460
37477
  return {
37461
37478
  ok,
37462
37479
  action: toolName,
@@ -37466,30 +37483,30 @@ function parseBrowserControlResult(toolName, payload) {
37466
37483
  };
37467
37484
  }
37468
37485
  function parseBrowserMetadata(value) {
37469
- const record10 = asRecord13(value);
37470
- if (!record10) return void 0;
37471
- const cursor = asRecord13(record10.cursor);
37472
- const screenshot = asRecord13(record10.screenshot);
37486
+ const record11 = asRecord13(value);
37487
+ if (!record11) return void 0;
37488
+ const cursor = asRecord13(record11.cursor);
37489
+ const screenshot = asRecord13(record11.screenshot);
37473
37490
  return {
37474
- ...typeof record10.activeTabId === "string" ? { activeTabId: record10.activeTabId } : {},
37475
- ...typeof record10.title === "string" ? { title: record10.title } : {},
37476
- ...typeof record10.url === "string" ? { url: record10.url } : {},
37477
- ...Array.isArray(record10.openTabIds) ? { openTabIds: record10.openTabIds.filter((item) => typeof item === "string") } : {},
37491
+ ...typeof record11.activeTabId === "string" ? { activeTabId: record11.activeTabId } : {},
37492
+ ...typeof record11.title === "string" ? { title: record11.title } : {},
37493
+ ...typeof record11.url === "string" ? { url: record11.url } : {},
37494
+ ...Array.isArray(record11.openTabIds) ? { openTabIds: record11.openTabIds.filter((item) => typeof item === "string") } : {},
37478
37495
  ...cursor && typeof cursor.x === "number" && typeof cursor.y === "number" ? { cursor: { x: cursor.x, y: cursor.y } } : {},
37479
- ...typeof record10.snapshotId === "string" ? { snapshotId: record10.snapshotId } : {},
37496
+ ...typeof record11.snapshotId === "string" ? { snapshotId: record11.snapshotId } : {},
37480
37497
  ...screenshot && typeof screenshot.tabId === "string" && typeof screenshot.url === "string" ? { screenshot: { tabId: screenshot.tabId, url: screenshot.url } } : {}
37481
37498
  };
37482
37499
  }
37483
37500
  function asRecord13(value) {
37484
37501
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
37485
37502
  }
37486
- function stringField(record10, key) {
37487
- const value = record10?.[key];
37503
+ function stringField(record11, key) {
37504
+ const value = record11?.[key];
37488
37505
  if (typeof value !== "string" || !value.trim()) return "";
37489
37506
  return value.trim();
37490
37507
  }
37491
- function optionalStringField(record10, key) {
37492
- const value = record10?.[key];
37508
+ function optionalStringField(record11, key) {
37509
+ const value = record11?.[key];
37493
37510
  return typeof value === "string" && value.trim() ? value.trim() : null;
37494
37511
  }
37495
37512
  function headerValue2(value) {
@@ -37514,16 +37531,16 @@ function stableHash(value) {
37514
37531
  function stableJson(value) {
37515
37532
  if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
37516
37533
  if (value && typeof value === "object") {
37517
- const record10 = value;
37518
- return `{${Object.keys(record10).sort().map((key) => `${JSON.stringify(key)}:${stableJson(record10[key])}`).join(",")}}`;
37534
+ const record11 = value;
37535
+ return `{${Object.keys(record11).sort().map((key) => `${JSON.stringify(key)}:${stableJson(record11[key])}`).join(",")}}`;
37519
37536
  }
37520
37537
  return JSON.stringify(value);
37521
37538
  }
37522
37539
  function parseJsonObject(value) {
37523
37540
  const parsed = JSON.parse(value);
37524
- const record10 = asRecord14(parsed);
37525
- if (!record10) throw new Error("Expected JSON object");
37526
- return record10;
37541
+ const record11 = asRecord14(parsed);
37542
+ if (!record11) throw new Error("Expected JSON object");
37543
+ return record11;
37527
37544
  }
37528
37545
  function parseJsonObjectSafe(value) {
37529
37546
  try {
@@ -37535,9 +37552,9 @@ function parseJsonObjectSafe(value) {
37535
37552
  function readPath(value, pathParts) {
37536
37553
  let current = value;
37537
37554
  for (const part of pathParts) {
37538
- const record10 = asRecord14(current);
37539
- if (!record10) return void 0;
37540
- current = record10[part];
37555
+ const record11 = asRecord14(current);
37556
+ if (!record11) return void 0;
37557
+ current = record11[part];
37541
37558
  }
37542
37559
  return current;
37543
37560
  }
@@ -38004,22 +38021,22 @@ async function inspectAgentProject(agentRootPath) {
38004
38021
  function readScheduleDefinitions(manifest) {
38005
38022
  const schedules = Array.isArray(readPath(manifest, ["schedules"])) ? readPath(manifest, ["schedules"]) : [];
38006
38023
  return schedules.flatMap((entry) => {
38007
- const record10 = asRecord14(entry);
38008
- const name = stringValue10(record10.name);
38024
+ const record11 = asRecord14(entry);
38025
+ const name = stringValue10(record11.name);
38009
38026
  if (!name) return [];
38010
- const scheduleType = record10.scheduleType === "rate" ? "rate" : "cron";
38011
- const expression = scheduleType === "rate" ? stringValue10(record10.rate) ?? stringValue10(record10.scheduleExpression) : stringValue10(record10.cron) ?? stringValue10(record10.scheduleExpression);
38027
+ const scheduleType = record11.scheduleType === "rate" ? "rate" : "cron";
38028
+ const expression = scheduleType === "rate" ? stringValue10(record11.rate) ?? stringValue10(record11.scheduleExpression) : stringValue10(record11.cron) ?? stringValue10(record11.scheduleExpression);
38012
38029
  if (!expression) return [];
38013
- const target = asRecord14(record10.target);
38014
- const targetAction = stringValue10(target.action) ?? stringValue10(record10.action) ?? stringValue10(record10.targetAction) ?? "chat";
38015
- const input = asRecord14(record10.input);
38030
+ const target = asRecord14(record11.target);
38031
+ const targetAction = stringValue10(target.action) ?? stringValue10(record11.action) ?? stringValue10(record11.targetAction) ?? "chat";
38032
+ const input = asRecord14(record11.input);
38016
38033
  const definition = {
38017
38034
  name,
38018
38035
  scheduleType,
38019
38036
  scheduleExpression: unwrapScheduleExpression(expression, scheduleType),
38020
- timezone: stringValue10(record10.timezone),
38037
+ timezone: stringValue10(record11.timezone),
38021
38038
  targetAction,
38022
- enabledByDefault: record10.enabledByDefault === true,
38039
+ enabledByDefault: record11.enabledByDefault === true,
38023
38040
  input
38024
38041
  };
38025
38042
  return [
@@ -38824,9 +38841,9 @@ function completionText(value) {
38824
38841
  }
38825
38842
  return null;
38826
38843
  }
38827
- const record10 = current;
38844
+ const record11 = current;
38828
38845
  for (const key of ["text", "outputText", "message", "content"]) {
38829
- const found = visit(record10[key], depth + 1);
38846
+ const found = visit(record11[key], depth + 1);
38830
38847
  if (found) return found;
38831
38848
  }
38832
38849
  return null;
@@ -40203,7 +40220,7 @@ function createCrossSystemExpertBootstrapService(deps) {
40203
40220
  if (records.length !== prepared.taskLinks.length) {
40204
40221
  throw new Error("Every reviewed train task must produce one exact, reward-eligible expert trajectory.");
40205
40222
  }
40206
- const recordByEnvironmentTaskId = new Map(records.map((record10) => [record10.taskId, record10]));
40223
+ const recordByEnvironmentTaskId = new Map(records.map((record11) => [record11.taskId, record11]));
40207
40224
  const approval = CrossSystemExpertBootstrapApprovalSchema.parse({
40208
40225
  status: "approved",
40209
40226
  approvedBy: actor,
@@ -40214,22 +40231,22 @@ function createCrossSystemExpertBootstrapService(deps) {
40214
40231
  const tasks = taskset.tasks.map((task) => {
40215
40232
  const link2 = prepared.taskLinks.find((candidate2) => candidate2.tasksetTask.id === task.id);
40216
40233
  if (!link2) return task;
40217
- const record10 = recordByEnvironmentTaskId.get(link2.environmentTask.id);
40218
- if (!record10) throw new Error(`Approved trajectory for ${link2.environmentTask.id} is missing.`);
40219
- return approvedTask(task, record10, approval);
40234
+ const record11 = recordByEnvironmentTaskId.get(link2.environmentTask.id);
40235
+ if (!record11) throw new Error(`Approved trajectory for ${link2.environmentTask.id} is missing.`);
40236
+ return approvedTask(task, record11, approval);
40220
40237
  });
40221
40238
  const demonstrations = [
40222
40239
  ...taskset.learningSignals.demonstrations.filter(
40223
40240
  (signal) => !prepared.taskLinks.some((link2) => link2.tasksetTask.id === signal.taskId)
40224
40241
  ),
40225
40242
  ...prepared.taskLinks.map(({ tasksetTask, environmentTask }) => {
40226
- const record10 = recordByEnvironmentTaskId.get(environmentTask.id);
40243
+ const record11 = recordByEnvironmentTaskId.get(environmentTask.id);
40227
40244
  return {
40228
40245
  id: `demo_${tasksetTask.id}`,
40229
40246
  kind: "demonstration",
40230
40247
  taskId: tasksetTask.id,
40231
40248
  sourceRefs: tasksetTask.sourceRefs,
40232
- artifactRef: record10.id,
40249
+ artifactRef: record11.id,
40233
40250
  approved: true,
40234
40251
  confidence: 1,
40235
40252
  metadata: {
@@ -40238,8 +40255,8 @@ function createCrossSystemExpertBootstrapService(deps) {
40238
40255
  approvedAt,
40239
40256
  approval: "explicit_expert_trajectory_review",
40240
40257
  previewHash: approval.previewHash,
40241
- trajectoryId: record10.trajectoryId,
40242
- toolContractHash: record10.toolContractHash
40258
+ trajectoryId: record11.trajectoryId,
40259
+ toolContractHash: record11.toolContractHash
40243
40260
  }
40244
40261
  };
40245
40262
  })
@@ -40283,7 +40300,7 @@ function createCrossSystemExpertBootstrapService(deps) {
40283
40300
  previewHash: approval.previewHash,
40284
40301
  fixturePath: EXPERT_BOOTSTRAP_FIXTURE,
40285
40302
  approval,
40286
- recordIds: records.map((record10) => record10.id),
40303
+ recordIds: records.map((record11) => record11.id),
40287
40304
  trajectoryHashes: prepared.preview.tasks.map((item) => item.trajectoryHash)
40288
40305
  }
40289
40306
  }
@@ -40331,14 +40348,14 @@ function createCrossSystemExpertBootstrapService(deps) {
40331
40348
  approvedBy: "preview",
40332
40349
  approvedAt: taskset.updatedAt
40333
40350
  });
40334
- const recordByTaskId = new Map(previewRecords.map((record10) => [record10.taskId, record10]));
40351
+ const recordByTaskId = new Map(previewRecords.map((record11) => [record11.taskId, record11]));
40335
40352
  const resultByTrajectoryId = new Map(results.map((result) => [result.trajectoryId, result]));
40336
40353
  const trajectoryByTaskId = new Map(trajectories.map((trajectory) => [trajectory.taskId, trajectory]));
40337
40354
  const previewTasks = taskLinks.map(({ tasksetTask, environmentTask }) => {
40338
40355
  const trajectory = trajectoryByTaskId.get(environmentTask.id);
40339
- const record10 = recordByTaskId.get(environmentTask.id);
40356
+ const record11 = recordByTaskId.get(environmentTask.id);
40340
40357
  const result = trajectory ? resultByTrajectoryId.get(trajectory.id) : null;
40341
- if (!trajectory || !record10 || result?.reward === null || result?.reward === void 0) {
40358
+ if (!trajectory || !record11 || result?.reward === null || result?.reward === void 0) {
40342
40359
  throw new Error(`Expert preview for ${environmentTask.id} is incomplete.`);
40343
40360
  }
40344
40361
  const final = [...trajectory.steps].reverse().find((step) => step.kind === "final");
@@ -40353,13 +40370,13 @@ function createCrossSystemExpertBootstrapService(deps) {
40353
40370
  trajectoryId: trajectory.id,
40354
40371
  trajectoryHash: contentHash({
40355
40372
  trajectory,
40356
- trainingMessages: record10.messages
40373
+ trainingMessages: record11.messages
40357
40374
  }),
40358
40375
  toolNames,
40359
40376
  toolCallCount: toolNames.length,
40360
- messageCount: record10.messages.length,
40377
+ messageCount: record11.messages.length,
40361
40378
  reward: result.reward,
40362
- messages: record10.messages
40379
+ messages: record11.messages
40363
40380
  };
40364
40381
  });
40365
40382
  const previewHash = contentHash({
@@ -40427,14 +40444,14 @@ function createCrossSystemExpertBootstrapService(deps) {
40427
40444
  }
40428
40445
  return { preview, approve };
40429
40446
  }
40430
- function approvedTask(task, record10, approval) {
40431
- const inputMessages = record10.messages.slice(0, 2);
40432
- const outputMessages = record10.messages.slice(2);
40447
+ function approvedTask(task, record11, approval) {
40448
+ const inputMessages = record11.messages.slice(0, 2);
40449
+ const outputMessages = record11.messages.slice(2);
40433
40450
  if (inputMessages[0]?.role !== "system" || inputMessages[1]?.role !== "user") {
40434
- throw new Error(`Expert trajectory ${record10.trajectoryId} has an invalid prompt prefix.`);
40451
+ throw new Error(`Expert trajectory ${record11.trajectoryId} has an invalid prompt prefix.`);
40435
40452
  }
40436
40453
  if (outputMessages.at(-1)?.role !== "assistant") {
40437
- throw new Error(`Expert trajectory ${record10.trajectoryId} must end with an assistant target.`);
40454
+ throw new Error(`Expert trajectory ${record11.trajectoryId} must end with an assistant target.`);
40438
40455
  }
40439
40456
  return {
40440
40457
  ...task,
@@ -40446,8 +40463,8 @@ function approvedTask(task, record10, approval) {
40446
40463
  approvalStatus: "approved",
40447
40464
  exampleOrigin: "expert_authored",
40448
40465
  exampleRationale: "Exact deterministic environment trajectory explicitly reviewed and approved for SFT bootstrap.",
40449
- expertBootstrapRecordId: record10.id,
40450
- expertTrajectoryId: record10.trajectoryId,
40466
+ expertBootstrapRecordId: record11.id,
40467
+ expertTrajectoryId: record11.trajectoryId,
40451
40468
  expertApproval: approval
40452
40469
  }
40453
40470
  };
@@ -40687,10 +40704,10 @@ function ambiguousTaskPrompt() {
40687
40704
  }
40688
40705
  function parseWorldSpec(value) {
40689
40706
  if (!value || typeof value !== "object" || Array.isArray(value)) return [];
40690
- const record10 = value;
40691
- const split = record10.split === "train" || record10.split === "validation" || record10.split === "frozen_eval" ? record10.split : null;
40692
- const difficulty = record10.difficulty === "easy" || record10.difficulty === "medium" || record10.difficulty === "hard" ? record10.difficulty : null;
40693
- return typeof record10.seed === "number" && Number.isInteger(record10.seed) && split && difficulty ? [{ seed: record10.seed, split, difficulty }] : [];
40707
+ const record11 = value;
40708
+ const split = record11.split === "train" || record11.split === "validation" || record11.split === "frozen_eval" ? record11.split : null;
40709
+ const difficulty = record11.difficulty === "easy" || record11.difficulty === "medium" || record11.difficulty === "hard" ? record11.difficulty : null;
40710
+ return typeof record11.seed === "number" && Number.isInteger(record11.seed) && split && difficulty ? [{ seed: record11.seed, split, difficulty }] : [];
40694
40711
  }
40695
40712
  function failure(request, message3) {
40696
40713
  return {
@@ -41419,19 +41436,19 @@ function enrichCrossSystemProposal(proposal, sources) {
41419
41436
  const traceBySource = new Map(lineage.traces.map((trace) => [trace.sourceId, trace]));
41420
41437
  const taskById = new Map(tasks.map((task) => [task.id, task]));
41421
41438
  const approvedSuccessfulSources = new Set(sources.flatMap((source) => {
41422
- const record10 = metadataRecord(source.metadata.crossSystemOperations);
41423
- return record10?.approved === true && record10.outcome === "correct" ? [source.id] : [];
41439
+ const record11 = metadataRecord(source.metadata.crossSystemOperations);
41440
+ return record11?.approved === true && record11.outcome === "correct" ? [source.id] : [];
41424
41441
  }));
41425
41442
  const existingExampleBySource = new Map(
41426
41443
  proposal.proposedExamples.map((example) => [example.sourceId, example])
41427
41444
  );
41428
41445
  const proposedExamples = sources.flatMap((source) => {
41429
41446
  const trace = traceBySource.get(source.id);
41430
- const record10 = metadataRecord(source.metadata.crossSystemOperations);
41431
- const taskId = typeof record10?.taskId === "string" ? record10.taskId : null;
41447
+ const record11 = metadataRecord(source.metadata.crossSystemOperations);
41448
+ const taskId = typeof record11?.taskId === "string" ? record11.taskId : null;
41432
41449
  const task = taskId ? taskById.get(taskId) ?? null : null;
41433
- const prompt = typeof record10?.taskPrompt === "string" ? record10.taskPrompt : task?.prompt;
41434
- const expectedAnswer = metadataRecord(record10?.expectedAnswer) ?? task?.expectedAnswer ?? null;
41450
+ const prompt = typeof record11?.taskPrompt === "string" ? record11.taskPrompt : task?.prompt;
41451
+ const expectedAnswer = metadataRecord(record11?.expectedAnswer) ?? task?.expectedAnswer ?? null;
41435
41452
  if (!trace || !prompt || !expectedAnswer) return [];
41436
41453
  const existing = existingExampleBySource.get(source.id);
41437
41454
  const approved = approvedSuccessfulSources.has(source.id);
@@ -41501,17 +41518,17 @@ function enrichCrossSystemProposal(proposal, sources) {
41501
41518
  }
41502
41519
  function crossSystemGroundTruth(source) {
41503
41520
  if (!source) return null;
41504
- const record10 = metadataRecord(source.metadata.crossSystemOperations);
41505
- if (!record10 || record10.toolContractHash !== CROSS_SYSTEM_TOOL_CONTRACT_HASH) return null;
41506
- const directPrompt = typeof record10.taskPrompt === "string" ? record10.taskPrompt : null;
41507
- const directExpectedAnswer = metadataRecord(record10.expectedAnswer);
41521
+ const record11 = metadataRecord(source.metadata.crossSystemOperations);
41522
+ if (!record11 || record11.toolContractHash !== CROSS_SYSTEM_TOOL_CONTRACT_HASH) return null;
41523
+ const directPrompt = typeof record11.taskPrompt === "string" ? record11.taskPrompt : null;
41524
+ const directExpectedAnswer = metadataRecord(record11.expectedAnswer);
41508
41525
  if (directPrompt && directExpectedAnswer) {
41509
41526
  return { prompt: directPrompt, expectedAnswer: directExpectedAnswer };
41510
41527
  }
41511
- const worldSeed = typeof record10.worldSeed === "number" && Number.isInteger(record10.worldSeed) ? record10.worldSeed : null;
41512
- const worldSplit = crossSystemSplit(record10.worldSplit);
41513
- const worldDifficulty = crossSystemDifficulty(record10.worldDifficulty);
41514
- const taskId = typeof record10.taskId === "string" ? record10.taskId : null;
41528
+ const worldSeed = typeof record11.worldSeed === "number" && Number.isInteger(record11.worldSeed) ? record11.worldSeed : null;
41529
+ const worldSplit = crossSystemSplit(record11.worldSplit);
41530
+ const worldDifficulty = crossSystemDifficulty(record11.worldDifficulty);
41531
+ const taskId = typeof record11.taskId === "string" ? record11.taskId : null;
41515
41532
  if (worldSeed === null || !worldSplit || !worldDifficulty || !taskId) return null;
41516
41533
  const task = generateCrossSystemTasks(generateCrossSystemWorld({
41517
41534
  seed: worldSeed,
@@ -41536,14 +41553,14 @@ function crossSystemTasksetMetadata(sources) {
41536
41553
  } : {};
41537
41554
  }
41538
41555
  function crossSystemExampleMetadata(source) {
41539
- const record10 = metadataRecord(source.metadata.crossSystemOperations);
41540
- return record10?.toolContractHash === CROSS_SYSTEM_TOOL_CONTRACT_HASH ? {
41556
+ const record11 = metadataRecord(source.metadata.crossSystemOperations);
41557
+ return record11?.toolContractHash === CROSS_SYSTEM_TOOL_CONTRACT_HASH ? {
41541
41558
  flagship: "cross-system-operations",
41542
41559
  toolContractHash: CROSS_SYSTEM_TOOL_CONTRACT_HASH,
41543
- trajectoryId: record10.trajectoryId,
41544
- worldId: record10.worldId,
41545
- taskId: record10.taskId,
41546
- approvalStatus: record10.approved === true ? "approved" : "unapproved"
41560
+ trajectoryId: record11.trajectoryId,
41561
+ worldId: record11.worldId,
41562
+ taskId: record11.taskId,
41563
+ approvalStatus: record11.approved === true ? "approved" : "unapproved"
41547
41564
  } : {};
41548
41565
  }
41549
41566
  function supersededCrossSystemWarning(warning) {
@@ -41553,22 +41570,22 @@ function supersededCrossSystemWarning(warning) {
41553
41570
  function crossSystemLineage(sources) {
41554
41571
  if (sources.length < 3) return null;
41555
41572
  const traces = sources.flatMap((source) => {
41556
- const record10 = metadataRecord(source.metadata.crossSystemOperations);
41557
- if (!record10 || record10.toolContractHash !== CROSS_SYSTEM_TOOL_CONTRACT_HASH) return [];
41558
- const worldSeed = typeof record10.worldSeed === "number" && Number.isInteger(record10.worldSeed) ? record10.worldSeed : null;
41559
- const worldSplit = crossSystemSplit(record10.worldSplit);
41560
- const worldDifficulty = crossSystemDifficulty(record10.worldDifficulty);
41573
+ const record11 = metadataRecord(source.metadata.crossSystemOperations);
41574
+ if (!record11 || record11.toolContractHash !== CROSS_SYSTEM_TOOL_CONTRACT_HASH) return [];
41575
+ const worldSeed = typeof record11.worldSeed === "number" && Number.isInteger(record11.worldSeed) ? record11.worldSeed : null;
41576
+ const worldSplit = crossSystemSplit(record11.worldSplit);
41577
+ const worldDifficulty = crossSystemDifficulty(record11.worldDifficulty);
41561
41578
  return worldSeed === null || !worldSplit || !worldDifficulty ? [] : [{ sourceId: source.id, worldSeed, worldSplit, worldDifficulty }];
41562
41579
  });
41563
41580
  if (traces.length !== sources.length) return null;
41564
41581
  const rewards = sources.flatMap((source) => {
41565
- const record10 = metadataRecord(source.metadata.crossSystemOperations);
41566
- return typeof record10?.reward === "number" && Number.isFinite(record10.reward) ? [record10.reward] : [];
41582
+ const record11 = metadataRecord(source.metadata.crossSystemOperations);
41583
+ return typeof record11?.reward === "number" && Number.isFinite(record11.reward) ? [record11.reward] : [];
41567
41584
  });
41568
41585
  if (rewards.length < 3) return null;
41569
41586
  const mean = rewards.reduce((sum, reward) => sum + reward, 0) / rewards.length;
41570
- const variance = rewards.reduce((sum, reward) => sum + (reward - mean) ** 2, 0) / rewards.length;
41571
- return { traces, rewards, variance };
41587
+ const variance2 = rewards.reduce((sum, reward) => sum + (reward - mean) ** 2, 0) / rewards.length;
41588
+ return { traces, rewards, variance: variance2 };
41572
41589
  }
41573
41590
  function metadataRecord(value) {
41574
41591
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
@@ -41933,6 +41950,224 @@ function safeTasksetId(name, snapshotId) {
41933
41950
  return `${slug}-${contentHash(snapshotId).slice(0, 8)}`;
41934
41951
  }
41935
41952
 
41953
+ // ../server/src/training/harness-review-taskset.ts
41954
+ async function startHarnessReviewTasksetAuthoring(input) {
41955
+ const review = await requireTasksetReview(input.store, input.workspaceId, input.reviewRef);
41956
+ const candidateId = `harness-review-${review.contentHash.slice(0, 24)}`;
41957
+ const existing = (await input.store.listTaskCreationSnapshots(input.profileId)).find((snapshot) => snapshot.request.candidateId === candidateId);
41958
+ if (existing) return existing;
41959
+ const [routes, triggers, observations] = await Promise.all([
41960
+ input.store.listHarnessImprovementArtifacts(input.workspaceId, "route_decision", 1e3),
41961
+ input.store.listHarnessImprovementArtifacts(input.workspaceId, "trigger_decision", 1e3),
41962
+ input.store.listHarnessImprovementArtifacts(input.workspaceId, "observation", 1e3)
41963
+ ]);
41964
+ const routeByRef = new Map(
41965
+ routes.map((route) => [artifactKey(route), route])
41966
+ );
41967
+ const triggerByRef = new Map(
41968
+ triggers.map((trigger) => [artifactKey(trigger), trigger])
41969
+ );
41970
+ const observationByRef = new Map(
41971
+ observations.map((observation) => [artifactKey(observation), observation])
41972
+ );
41973
+ const sourceGroups = /* @__PURE__ */ new Map();
41974
+ for (const selected of review.selectedEvidence) {
41975
+ if (selected.kind !== "route_decision") continue;
41976
+ const route = routeByRef.get(artifactKey(selected.evidence));
41977
+ const trigger = route ? triggerByRef.get(artifactKey(route.trigger)) : null;
41978
+ if (!route || !trigger) {
41979
+ throw new Error(`Harness review evidence ${selected.evidence.id} cannot be reconstructed.`);
41980
+ }
41981
+ const matching = trigger.observations.map((reference) => observationByRef.get(artifactKey(reference)) ?? null).filter(
41982
+ (observation) => observation?.runRef === selected.sourceRef
41983
+ );
41984
+ if (!matching.length) {
41985
+ throw new Error(`Harness review source ${selected.sourceRef} has no exact observation evidence.`);
41986
+ }
41987
+ const group = sourceGroups.get(selected.sourceRef) ?? {
41988
+ turnIds: /* @__PURE__ */ new Set(),
41989
+ evidenceRefs: [],
41990
+ sourcePolicies: []
41991
+ };
41992
+ for (const observation of matching) group.turnIds.add(observation.turnId);
41993
+ group.evidenceRefs.push(selected.evidence);
41994
+ group.sourcePolicies.push(selected.sourcePolicy);
41995
+ sourceGroups.set(selected.sourceRef, group);
41996
+ }
41997
+ if (!sourceGroups.size) {
41998
+ throw new Error("Harness Taskset review has no reconstructable source runs.");
41999
+ }
42000
+ const sources = [];
42001
+ for (const [sessionId, group] of [...sourceGroups.entries()].sort(([left], [right]) => left.localeCompare(right))) {
42002
+ const source = await input.taskCreator.addSessionSource({
42003
+ profileId: input.profileId,
42004
+ sessionId,
42005
+ turnIds: [...group.turnIds].sort(),
42006
+ consentScope: "selected_turns"
42007
+ });
42008
+ const priorReviews = Array.isArray(source.metadata.harnessEvaluationReviews) ? source.metadata.harnessEvaluationReviews : [];
42009
+ const enriched = {
42010
+ ...source,
42011
+ metadata: {
42012
+ ...source.metadata,
42013
+ harnessEvaluationReviews: uniqueObjects([
42014
+ ...priorReviews,
42015
+ {
42016
+ id: review.id,
42017
+ contentHash: review.contentHash,
42018
+ workspaceId: review.workspaceRef,
42019
+ harnessRelease: review.harnessRelease,
42020
+ claimFingerprint: review.claim?.fingerprint ?? null,
42021
+ evidenceRefs: group.evidenceRefs,
42022
+ sourcePolicies: group.sourcePolicies
42023
+ }
42024
+ ])
42025
+ }
42026
+ };
42027
+ sources.push(await input.store.upsertTrainingSource(enriched));
42028
+ }
42029
+ return input.startCreation({
42030
+ profileId: input.profileId,
42031
+ sourceIds: sources.map((source) => source.id),
42032
+ surface: "task_candidate",
42033
+ mode: "customize",
42034
+ entryMode: "automated",
42035
+ resourceIntent: "workproduct",
42036
+ buildIntent: "rubric",
42037
+ buildSpecification: null,
42038
+ objective: review.claim?.statement ?? review.reason,
42039
+ methodHint: null,
42040
+ preferredBaseModelId: null,
42041
+ preferredBaseModel: null,
42042
+ candidateId,
42043
+ analysisModel: input.analysisModel ?? null,
42044
+ analysisReasoningEffort: input.analysisReasoningEffort ?? null,
42045
+ createImproveRunId: null,
42046
+ targetIntent: {
42047
+ kind: "model",
42048
+ id: null,
42049
+ displayName: null,
42050
+ operation: "create"
42051
+ }
42052
+ });
42053
+ }
42054
+ function harnessReviewLineageFromSources(sources) {
42055
+ const entries = sources.flatMap(
42056
+ (source) => Array.isArray(source.metadata.harnessEvaluationReviews) ? source.metadata.harnessEvaluationReviews.filter(isRecord4) : []
42057
+ );
42058
+ if (!entries.length) return null;
42059
+ const reviewKey = `${String(entries[0].id)}:${String(entries[0].contentHash)}`;
42060
+ const matching = entries.filter(
42061
+ (entry) => `${String(entry.id)}:${String(entry.contentHash)}` === reviewKey
42062
+ );
42063
+ if (matching.length !== sources.length) {
42064
+ return null;
42065
+ }
42066
+ const first = matching[0];
42067
+ return {
42068
+ review: {
42069
+ id: String(first.id),
42070
+ contentHash: String(first.contentHash),
42071
+ workspaceId: String(first.workspaceId),
42072
+ harnessRelease: first.harnessRelease,
42073
+ claimFingerprint: typeof first.claimFingerprint === "string" ? first.claimFingerprint : null
42074
+ },
42075
+ evidenceRefs: uniqueObjects(matching.flatMap((entry) => Array.isArray(entry.evidenceRefs) ? entry.evidenceRefs : [])),
42076
+ sourcePolicies: uniqueObjects(matching.flatMap((entry) => Array.isArray(entry.sourcePolicies) ? entry.sourcePolicies : []))
42077
+ };
42078
+ }
42079
+ async function linkHarnessReviewTaskset(input) {
42080
+ const lineage = input.taskset.metadata.harnessEvaluationLineage;
42081
+ if (!isRecord4(lineage) || !isRecord4(lineage.review)) return null;
42082
+ const workspaceId = String(lineage.review.workspaceId ?? "");
42083
+ const originRef = {
42084
+ id: String(lineage.review.id ?? ""),
42085
+ contentHash: String(lineage.review.contentHash ?? "")
42086
+ };
42087
+ if (!workspaceId || !originRef.id || !originRef.contentHash) {
42088
+ throw new Error("Taskset Harness Evaluation lineage is incomplete.");
42089
+ }
42090
+ const reviews = await input.store.listHarnessImprovementArtifacts(
42091
+ workspaceId,
42092
+ "evaluation_review",
42093
+ 1e3
42094
+ );
42095
+ const origin = reviews.find((review) => artifactKey(review) === artifactKey(originRef));
42096
+ if (!origin) throw new Error("Originating Harness Evaluation review was not found.");
42097
+ const evaluationRef = input.evaluationResult ? { id: input.evaluationResult.id, contentHash: input.evaluationResult.contentHash } : null;
42098
+ const tasksetRef = { id: input.taskset.id, contentHash: input.taskset.contentHash };
42099
+ const linkKey = contentHash({ originRef, tasksetRef, evaluationRef });
42100
+ const existing = reviews.find((review) => review.metadata.downstreamLinkKey === linkKey);
42101
+ if (existing) return existing;
42102
+ const createdAt = (input.now ?? (() => (/* @__PURE__ */ new Date()).toISOString()))();
42103
+ const receipt = createHarnessEvaluationReviewReceipt({
42104
+ schemaVersion: "openpond.harnessEvaluationReviewReceipt.v1",
42105
+ id: `evaluation-review-link-${linkKey.slice(0, 24)}`,
42106
+ ownerScope: origin.ownerScope,
42107
+ workspaceRef: origin.workspaceRef,
42108
+ harnessRelease: origin.harnessRelease,
42109
+ previousWatermark: origin.nextWatermark,
42110
+ nextWatermark: {
42111
+ cursor: contentHash({ cursor: origin.nextWatermark.cursor, tasksetRef, evaluationRef }),
42112
+ throughCreatedAt: createdAt
42113
+ },
42114
+ selectedEvidence: origin.selectedEvidence,
42115
+ excludedEvidence: origin.excludedEvidence,
42116
+ claim: origin.claim,
42117
+ classification: "taskset",
42118
+ triage: origin.triage,
42119
+ reason: evaluationRef ? "The approved Taskset completed a real baseline Evaluation." : "The approved Harness review materialized one immutable Taskset.",
42120
+ nextAuthority: "human_review",
42121
+ maxEstimatedCostUsd: origin.maxEstimatedCostUsd,
42122
+ tasksetProposal: tasksetRef,
42123
+ evaluation: evaluationRef,
42124
+ trainingQualification: null,
42125
+ policyVersion: origin.policyVersion,
42126
+ createdAt,
42127
+ metadata: {
42128
+ originReview: originRef,
42129
+ downstreamLinkKey: linkKey,
42130
+ tasksetRevision: input.taskset.revision
42131
+ }
42132
+ });
42133
+ await input.store.saveHarnessImprovementArtifact(workspaceId, "evaluation_review", receipt);
42134
+ return receipt;
42135
+ }
42136
+ async function requireTasksetReview(store, workspaceId, expected) {
42137
+ const workspace = await store.getHarnessWorkspace(workspaceId);
42138
+ if (!workspace) throw new Error(`Harness workspace ${workspaceId} was not found.`);
42139
+ const review = (await store.listHarnessImprovementArtifacts(workspaceId, "evaluation_review", 1e3)).find((candidate2) => candidate2.id === expected.id && candidate2.contentHash === expected.contentHash);
42140
+ if (!review || review.schemaVersion !== "openpond.harnessEvaluationReviewReceipt.v1") {
42141
+ throw new Error("Harness Evaluation review was not found.");
42142
+ }
42143
+ const typed = review;
42144
+ if (typed.classification !== "taskset" || typed.nextAuthority !== "human_review") {
42145
+ throw new Error("Only a human-review Taskset recommendation can enter Taskset authoring.");
42146
+ }
42147
+ if (typed.tasksetProposal) {
42148
+ throw new Error("Harness Evaluation review already has a materialized Taskset link.");
42149
+ }
42150
+ if (typed.ownerScope.kind !== workspace.ownerScope.kind || typed.ownerScope.id !== workspace.ownerScope.id) {
42151
+ throw new Error("Harness Evaluation review owner scope does not match its workspace.");
42152
+ }
42153
+ return typed;
42154
+ }
42155
+ function artifactKey(value) {
42156
+ return `${value.id}:${value.contentHash}`;
42157
+ }
42158
+ function isRecord4(value) {
42159
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
42160
+ }
42161
+ function uniqueObjects(values) {
42162
+ const seen = /* @__PURE__ */ new Set();
42163
+ return values.filter((value) => {
42164
+ const key = JSON.stringify(value);
42165
+ if (seen.has(key)) return false;
42166
+ seen.add(key);
42167
+ return true;
42168
+ });
42169
+ }
42170
+
41936
42171
  // ../server/src/training/task-creator.ts
41937
42172
  function createTaskCreatorService(deps) {
41938
42173
  async function reconcileInterruptedCreations() {
@@ -42269,6 +42504,7 @@ function createTaskCreatorService(deps) {
42269
42504
  }
42270
42505
  const manual = manualBuildEvidence(snapshot);
42271
42506
  const effectiveSources = manual ? [...sources, manual.source] : sources;
42507
+ const harnessReviewLineage = harnessReviewLineageFromSources(effectiveSources);
42272
42508
  const tasksetId = materializedTasksetId(snapshot, proposal);
42273
42509
  const existingTaskset = snapshot.request.resourceIntent === "dataset" && snapshot.request.targetIntent.operation === "improve" ? await deps.store.getTaskset(tasksetId) : null;
42274
42510
  if (snapshot.request.resourceIntent === "dataset" && snapshot.request.targetIntent.operation === "improve" && !existingTaskset) {
@@ -42372,6 +42608,13 @@ function createTaskCreatorService(deps) {
42372
42608
  diagnosis: proposal.diagnosis,
42373
42609
  assumptions: proposal.assumptions,
42374
42610
  warnings: proposal.warnings,
42611
+ ...harnessReviewLineage ? {
42612
+ harnessEvaluationReview: {
42613
+ id: harnessReviewLineage.review.id,
42614
+ contentHash: harnessReviewLineage.review.contentHash
42615
+ },
42616
+ harnessEvaluationLineage: harnessReviewLineage
42617
+ } : {},
42375
42618
  ...crossSystemTasksetMetadata(effectiveSources)
42376
42619
  }
42377
42620
  };
@@ -43096,9 +43339,9 @@ function createTaskMinerService(deps) {
43096
43339
  throw error;
43097
43340
  }
43098
43341
  }));
43099
- for (const record10 of records) if (record10.source) sourceIds.add(record10.source.id);
43342
+ for (const record11 of records) if (record11.source) sourceIds.add(record11.source.id);
43100
43343
  processedSources += batch.length;
43101
- skippedSources += records.filter((record10) => record10.skipped).length;
43344
+ skippedSources += records.filter((record11) => record11.skipped).length;
43102
43345
  current = await deps.store.saveTaskMinerRun({
43103
43346
  ...persisted,
43104
43347
  status: "running",
@@ -43466,10 +43709,10 @@ function verifierFunctionSource(source, exportName) {
43466
43709
  }
43467
43710
  function normalizeResult(value) {
43468
43711
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Verifier must return an object.");
43469
- const record10 = value;
43470
- const score = typeof record10.score === "number" ? Math.max(0, Math.min(1, record10.score)) : record10.passed === true ? 1 : 0;
43471
- const feedback = typeof record10.feedback === "string" ? record10.feedback : typeof record10.reason === "string" ? record10.reason : "Custom verifier completed.";
43472
- return { score, passed: record10.passed === true, feedback: feedback.slice(0, 2e4), evidenceRefs: Array.isArray(record10.evidenceRefs) ? record10.evidenceRefs.filter((item) => typeof item === "string").slice(0, 1e4) : [] };
43712
+ const record11 = value;
43713
+ const score = typeof record11.score === "number" ? Math.max(0, Math.min(1, record11.score)) : record11.passed === true ? 1 : 0;
43714
+ const feedback = typeof record11.feedback === "string" ? record11.feedback : typeof record11.reason === "string" ? record11.reason : "Custom verifier completed.";
43715
+ return { score, passed: record11.passed === true, feedback: feedback.slice(0, 2e4), evidenceRefs: Array.isArray(record11.evidenceRefs) ? record11.evidenceRefs.filter((item) => typeof item === "string").slice(0, 1e4) : [] };
43473
43716
  }
43474
43717
  function withTimeout(promise, timeoutMs) {
43475
43718
  return new Promise((resolve, reject) => {
@@ -43745,9 +43988,9 @@ import { readFile as readFile9 } from "node:fs/promises";
43745
43988
 
43746
43989
  // ../server/src/training/taskset-work-cost-evidence.ts
43747
43990
  function workRuntimeCostEvidence(value) {
43748
- const record10 = asRecord15(value);
43749
- const sandbox = asRecord15(record10.sandbox);
43750
- const receiptValues = Array.isArray(record10.receipts) ? record10.receipts : Array.isArray(sandbox.receipts) ? sandbox.receipts : [];
43991
+ const record11 = asRecord15(value);
43992
+ const sandbox = asRecord15(record11.sandbox);
43993
+ const receiptValues = Array.isArray(record11.receipts) ? record11.receipts : Array.isArray(sandbox.receipts) ? sandbox.receipts : [];
43751
43994
  const receipts = receiptValues.map(asRecord15);
43752
43995
  const captured = receipts.flatMap((receipt) => {
43753
43996
  const id = typeof receipt.id === "string" ? receipt.id : null;
@@ -44571,8 +44814,8 @@ function userPrompt(task) {
44571
44814
  return task.input.prompt.trim();
44572
44815
  }
44573
44816
  const messages = Array.isArray(task.input.messages) ? task.input.messages.flatMap((value) => {
44574
- const record10 = asRecord16(value);
44575
- return (record10.role === "system" || record10.role === "user") && typeof record10.content === "string" && record10.content.trim() ? [record10.content.trim()] : [];
44817
+ const record11 = asRecord16(value);
44818
+ return (record11.role === "system" || record11.role === "user") && typeof record11.content === "string" && record11.content.trim() ? [record11.content.trim()] : [];
44576
44819
  }) : [];
44577
44820
  if (messages.length) return messages.join("\n\n");
44578
44821
  throw new Error(`Evaluation task ${task.id} has no policy-visible prompt.`);
@@ -45274,7 +45517,8 @@ function createTaskEvaluationService(deps) {
45274
45517
  selectedTask: task,
45275
45518
  profile,
45276
45519
  releasedHarness,
45277
- model: input.model
45520
+ model: input.model,
45521
+ now: input.admittedAt ? () => input.admittedAt : void 0
45278
45522
  });
45279
45523
  const attempt = await runPostTrainingEvaluationAttempt({
45280
45524
  store: deps.store,
@@ -45593,6 +45837,104 @@ function createTaskEvaluationService(deps) {
45593
45837
  });
45594
45838
  return report;
45595
45839
  }
45840
+ async function executeBaseline(input) {
45841
+ const taskset = await requireTaskset(input.tasksetId);
45842
+ if (taskset.status !== "ready" || taskset.readiness?.ready !== true) {
45843
+ throw new Error("Taskset must pass grader audit and readiness before baseline Evaluation.");
45844
+ }
45845
+ const lineage = taskset.metadata.harnessEvaluationReview;
45846
+ if (!lineage || typeof lineage !== "object" || Array.isArray(lineage) || lineage.id !== input.reviewRef.id || lineage.contentHash !== input.reviewRef.contentHash) {
45847
+ throw new Error("Taskset does not bind the supplied Harness Evaluation review.");
45848
+ }
45849
+ const existing = (await deps.store.listEvaluationResults(taskset.id, "baseline")).find(
45850
+ (result) => result.metadata.sourceTasksetHash === taskset.contentHash && result.model.provider === input.model.providerId && result.model.model === input.model.modelId && reviewRefMatches(result.metadata.harnessEvaluationReview, input.reviewRef)
45851
+ );
45852
+ if (existing) return { evaluationResult: existing, attempts: [], reused: true };
45853
+ const tasks = taskset.tasks.filter((task) => task.split === "frozen_eval");
45854
+ if (!tasks.length) {
45855
+ throw new Error("Baseline Evaluation requires at least one isolated frozen-evaluation task.");
45856
+ }
45857
+ const seeds = [...new Set(input.seeds?.length ? input.seeds : [17])].slice(0, 100);
45858
+ const attemptsPerTask = Math.max(1, Math.min(20, Math.trunc(input.attemptsPerTask ?? 1)));
45859
+ const admittedAt = (/* @__PURE__ */ new Date()).toISOString();
45860
+ const executions = [];
45861
+ for (const task of tasks) {
45862
+ for (const seed of seeds) {
45863
+ for (let attempt = 0; attempt < attemptsPerTask; attempt += 1) {
45864
+ if (input.signal?.aborted) throw input.signal.reason;
45865
+ executions.push(await execute({
45866
+ tasksetId: taskset.id,
45867
+ taskId: task.id,
45868
+ model: input.model,
45869
+ seed,
45870
+ attempt,
45871
+ sampling: input.sampling,
45872
+ signal: input.signal,
45873
+ admittedAt,
45874
+ resultId: `baseline-attempt-${contentHash({
45875
+ reviewRef: input.reviewRef,
45876
+ tasksetHash: taskset.contentHash,
45877
+ model: input.model,
45878
+ taskId: task.id,
45879
+ seed,
45880
+ attempt
45881
+ }).slice(0, 24)}`
45882
+ }));
45883
+ }
45884
+ }
45885
+ }
45886
+ const manifest = executions[0].portable.runManifest;
45887
+ if (executions.some((execution) => execution.portable.runManifest.contentHash !== manifest.contentHash)) {
45888
+ throw new Error("Baseline attempts did not share one frozen Run Manifest.");
45889
+ }
45890
+ const receipts = executions.map((execution) => execution.portable.receipt);
45891
+ const portableTaskset = executions[0].portable.tasksetRelease;
45892
+ const scores = receipts.flatMap(
45893
+ (receipt) => typeof receipt.metadata.score === "number" ? [receipt.metadata.score] : []
45894
+ );
45895
+ const evaluationResult = aggregateEvaluationReceipts({
45896
+ id: `baseline-evaluation-${contentHash({
45897
+ manifest: manifest.contentHash,
45898
+ receipts: receipts.map((receipt) => receipt.contentHash),
45899
+ reviewRef: input.reviewRef
45900
+ }).slice(0, 24)}`,
45901
+ manifest,
45902
+ receipts,
45903
+ metadata: {
45904
+ kind: "baseline",
45905
+ sourceTasksetId: taskset.id,
45906
+ sourceTasksetRevision: taskset.revision,
45907
+ sourceTasksetHash: taskset.contentHash,
45908
+ harnessEvaluationReview: input.reviewRef,
45909
+ environmentHash: contentHash(portableTaskset.environment),
45910
+ toolContractHash: contentHash(portableTaskset.tools),
45911
+ permissionContractHash: contentHash({
45912
+ connectedAppScopes: portableTaskset.policy.connectedAppScopes,
45913
+ networkPolicy: portableTaskset.environment.networkPolicy
45914
+ }),
45915
+ policyHash: contentHash(portableTaskset.policy),
45916
+ verifierRef: {
45917
+ id: `verifier-${taskset.id}-r${taskset.revision}`,
45918
+ contentHash: contentHash(portableTaskset.graders)
45919
+ },
45920
+ scores,
45921
+ scoreVariance: variance(scores),
45922
+ admittedAt
45923
+ }
45924
+ });
45925
+ await deps.store.saveEvaluationResult({
45926
+ tasksetId: taskset.id,
45927
+ kind: "baseline",
45928
+ result: evaluationResult,
45929
+ createdAt: admittedAt
45930
+ });
45931
+ await linkHarnessReviewTaskset({
45932
+ store: deps.store,
45933
+ taskset,
45934
+ evaluationResult
45935
+ });
45936
+ return { evaluationResult, attempts: executions, reused: false };
45937
+ }
45596
45938
  async function requireTaskset(id) {
45597
45939
  const taskset = await deps.store.getTaskset(id);
45598
45940
  if (!taskset) throw new Error("Taskset not found.");
@@ -45637,10 +45979,21 @@ function createTaskEvaluationService(deps) {
45637
45979
  auditFixtures,
45638
45980
  calibrateModelJudges,
45639
45981
  readiness,
45982
+ executeBaseline,
45640
45983
  close: async () => {
45641
45984
  }
45642
45985
  };
45643
45986
  }
45987
+ function reviewRefMatches(value, expected) {
45988
+ return Boolean(
45989
+ value && typeof value === "object" && !Array.isArray(value) && value.id === expected.id && value.contentHash === expected.contentHash
45990
+ );
45991
+ }
45992
+ function variance(values) {
45993
+ if (values.length < 2) return 0;
45994
+ const mean = values.reduce((total, value) => total + value, 0) / values.length;
45995
+ return values.reduce((total, value) => total + (value - mean) ** 2, 0) / values.length;
45996
+ }
45644
45997
 
45645
45998
  // ../server/src/training/training-service.ts
45646
45999
  import { access as access4, cp as cp2, mkdir as mkdir11, rename as rename2, rm as rm5 } from "node:fs/promises";
@@ -46046,9 +46399,9 @@ var TrainingDestinationRegistry = class {
46046
46399
  function createTrainingPlan(input) {
46047
46400
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
46048
46401
  const environmentPlacement = input.destinationId === "openpond_managed" ? input.environmentPlacement ?? "local" : "local";
46049
- const id = `training_plan_${contentHash([input.modelId, input.taskset.contentHash, input.destinationId, environmentPlacement, input.recipe]).slice(0, 24)}`;
46402
+ const id = `training_plan_${contentHash([input.modelId, input.taskset.contentHash, input.destinationId, environmentPlacement, input.recipe, input.modelImprovementQualification ?? null]).slice(0, 24)}`;
46050
46403
  const compatibility = { schemaVersion: "openpond.trainingCompatibility.v1", compatible: false, destinationId: input.destinationId, tasksetId: input.taskset.id, recipeMethod: input.recipe.method, issues: [{ code: "compatibility_pending", severity: "error", path: null, message: "Destination compatibility has not been checked." }], checkedAt: createdAt };
46051
- const draft = { schemaVersion: "openpond.trainingPlan.v1", id, modelId: input.modelId, tasksetId: input.taskset.id, tasksetHash: input.taskset.contentHash, harnessRelease: input.harnessRelease ?? null, destinationId: input.destinationId, recipe: input.recipe, environmentPlacement, compatibility, dataPolicy: { exportApproved: input.exportApproved ?? false, approvedSourceIds: input.taskset.sourceRefs.map((source) => source.id), retentionDays: input.retentionDays ?? null, region: input.region ?? null }, estimatedCostUsd: input.destinationId === "local_cpu_fixture" ? 0 : null, createdAt, contentHash: "00000000" };
46404
+ const draft = { schemaVersion: "openpond.trainingPlan.v1", id, modelId: input.modelId, tasksetId: input.taskset.id, tasksetHash: input.taskset.contentHash, harnessRelease: input.harnessRelease ?? null, modelImprovementQualification: input.modelImprovementQualification ?? null, destinationId: input.destinationId, recipe: input.recipe, environmentPlacement, compatibility, dataPolicy: { exportApproved: input.exportApproved ?? false, approvedSourceIds: input.taskset.sourceRefs.map((source) => source.id), retentionDays: input.retentionDays ?? null, region: input.region ?? null }, estimatedCostUsd: input.destinationId === "local_cpu_fixture" ? 0 : null, createdAt, contentHash: "00000000" };
46052
46405
  const parsed = TrainingPlanSchema.parse(draft);
46053
46406
  return TrainingPlanSchema.parse({ ...parsed, contentHash: contentHash({ ...parsed, contentHash: "" }) });
46054
46407
  }
@@ -49147,6 +49500,20 @@ var OpenPondManagedTrainingAdapter = class {
49147
49500
  });
49148
49501
  }
49149
49502
  if (taskset && trainingPlan && taskset.contentHash === trainingPlan.tasksetHash) {
49503
+ if (taskset.metadata.harnessEvaluationReview !== void 0) {
49504
+ const qualification = await managedQualification({
49505
+ store: this.dependencies.store,
49506
+ taskset,
49507
+ qualificationRef: trainingPlan.modelImprovementQualification ?? null
49508
+ });
49509
+ if (!qualification || qualification.decision !== "rl" || approval?.modelImprovementQualification?.id !== qualification.id || approval.modelImprovementQualification.contentHash !== qualification.contentHash || qualification.metadata.sourceTasksetId !== taskset.id || qualification.metadata.sourceTasksetHash !== taskset.contentHash || approval.maximumCostUsd !== null && approval.maximumCostUsd > qualification.maximumCostUsd) {
49510
+ issues.push({
49511
+ code: "managed_qualification_invalid",
49512
+ path: "execution",
49513
+ message: "OpenPond Managed requires an exact qualified RL receipt on the immutable Taskset, plan, and approval."
49514
+ });
49515
+ }
49516
+ }
49150
49517
  const requiresHarness = taskset.capabilities.requiresState || taskset.capabilities.requiresTools;
49151
49518
  if (requiresHarness && !supportsManagedRlHarness(taskset, plan.runtime.placement)) {
49152
49519
  issues.push({
@@ -49241,6 +49608,7 @@ var OpenPondManagedTrainingAdapter = class {
49241
49608
  revision: taskset.revision,
49242
49609
  contentHash: taskset.contentHash
49243
49610
  },
49611
+ modelImprovementQualification: trainingPlan.modelImprovementQualification ?? null,
49244
49612
  recipe: plan.recipe,
49245
49613
  resolvedBundle: {
49246
49614
  manifest: bundleManifest,
@@ -49432,6 +49800,23 @@ var OpenPondManagedTrainingAdapter = class {
49432
49800
  executor.start();
49433
49801
  }
49434
49802
  };
49803
+ async function managedQualification(input) {
49804
+ if (!input.qualificationRef) return null;
49805
+ const lineage = input.taskset.metadata.harnessEvaluationLineage;
49806
+ if (!lineage || typeof lineage !== "object" || Array.isArray(lineage)) return null;
49807
+ const review = lineage.review;
49808
+ if (!review || typeof review !== "object" || Array.isArray(review)) return null;
49809
+ const workspaceId = review.workspaceId;
49810
+ if (typeof workspaceId !== "string" || !workspaceId) return null;
49811
+ const receipts = await input.store.listHarnessImprovementArtifacts(
49812
+ workspaceId,
49813
+ "training_qualification",
49814
+ 1e3
49815
+ );
49816
+ return receipts.find(
49817
+ (receipt) => receipt.id === input.qualificationRef.id && receipt.contentHash === input.qualificationRef.contentHash
49818
+ ) ?? null;
49819
+ }
49435
49820
  function dateString(value) {
49436
49821
  return new Date(value).toISOString();
49437
49822
  }
@@ -51786,6 +52171,11 @@ function createTrainingPlanLifecycleService(deps) {
51786
52171
  "Taskset is not ready for training. Resolve readiness blockers first."
51787
52172
  );
51788
52173
  }
52174
+ if (taskset.metadata.harnessEvaluationReview !== void 0 && !input.modelImprovementQualification) {
52175
+ throw new Error(
52176
+ "Harness-origin Tasksets require an exact model-improvement qualification before training planning."
52177
+ );
52178
+ }
51789
52179
  const recipe = TrainingRecipeSchema.parse(
51790
52180
  withAuthoritativeRecipeHashes(taskset, input.recipe)
51791
52181
  );
@@ -51800,7 +52190,8 @@ function createTrainingPlanLifecycleService(deps) {
51800
52190
  exportApproved: input.exportApproved,
51801
52191
  retentionDays: input.retentionDays,
51802
52192
  region: input.region,
51803
- harnessRelease: input.harnessRelease
52193
+ harnessRelease: input.harnessRelease,
52194
+ modelImprovementQualification: input.modelImprovementQualification
51804
52195
  });
51805
52196
  const requestedPlacement = input.environmentPlacement ?? initial.environmentPlacement;
51806
52197
  const environmentPlacement = capabilities.environmentPlacements.includes(requestedPlacement) ? requestedPlacement : recipe.method === "ppo" && capabilities.environmentPlacements.includes("local") ? "local" : capabilities.environmentPlacements[0] ?? "none";
@@ -51875,6 +52266,7 @@ function createTrainingPlanLifecycleService(deps) {
51875
52266
  approvalModel.id,
51876
52267
  recipe.method,
51877
52268
  recipe.parameterization,
52269
+ plan.modelImprovementQualification,
51878
52270
  maximumCostUsd,
51879
52271
  approvedBy
51880
52272
  ]).slice(0, 24)}`;
@@ -51892,7 +52284,8 @@ function createTrainingPlanLifecycleService(deps) {
51892
52284
  maximumCostUsd,
51893
52285
  approvedBy,
51894
52286
  approvedAt: (/* @__PURE__ */ new Date()).toISOString(),
51895
- harnessRelease: plan.harnessRelease
52287
+ harnessRelease: plan.harnessRelease,
52288
+ modelImprovementQualification: plan.modelImprovementQualification
51896
52289
  });
51897
52290
  return deps.store.saveTrainingApproval(approval);
51898
52291
  }
@@ -53254,10 +53647,381 @@ function revisions(items, project) {
53254
53647
  return items.map(project).sort((left, right) => left[0].localeCompare(right[0]));
53255
53648
  }
53256
53649
 
53650
+ // ../server/src/training/harness-model-improvement.ts
53651
+ async function qualifyHarnessModelImprovement(input) {
53652
+ const [taskset, baseline] = await Promise.all([
53653
+ input.store.getTaskset(input.tasksetId),
53654
+ input.store.getEvaluationResult(input.baselineEvaluationId)
53655
+ ]);
53656
+ if (!taskset) throw new Error("Taskset was not found for model-improvement qualification.");
53657
+ if (!baseline) throw new Error("Baseline Evaluation was not found.");
53658
+ if (taskset.status !== "ready" || taskset.readiness?.ready !== true || taskset.readiness.tasksetHash !== taskset.contentHash) {
53659
+ throw new Error("Taskset readiness is stale or blocked.");
53660
+ }
53661
+ assertBaselineLineage(taskset, baseline, input.reviewRef);
53662
+ const lineage = harnessLineage(taskset);
53663
+ const sourcePolicies = HarnessReviewSourcePolicyRefSchema.array().parse(lineage.sourcePolicies);
53664
+ const frozenEvidenceRefs = taskEvidenceRefs(
53665
+ taskset,
53666
+ new Set(taskset.tasks.filter((task) => task.split === "frozen_eval").flatMap((task) => task.sourceRefs))
53667
+ );
53668
+ const signal = signalForTaskset(taskset, baseline);
53669
+ const trainingEvidenceRefs = taskEvidenceRefs(taskset, signal.sourceIds);
53670
+ const privacyReady = taskset.sourceRefs.every(
53671
+ (source) => !isTrainingSourceRef(source) || source.consent.status === "granted" && source.secretScanStatus === "passed" && source.piiScanStatus === "passed" && source.licensingStatus === "approved"
53672
+ );
53673
+ const reasons = [...signal.reasons];
53674
+ let decision = signal.decision;
53675
+ if (baseline.meanScore !== null && baseline.meanScore >= 0.95) {
53676
+ decision = "no_training";
53677
+ reasons.push("The real baseline already meets the protected success threshold.");
53678
+ }
53679
+ if (!privacyReady || !input.privacyApproval) {
53680
+ decision = "no_training";
53681
+ reasons.push("A separate privacy approval over eligible training evidence is required.");
53682
+ }
53683
+ if (!input.budgetApproval) {
53684
+ decision = "no_training";
53685
+ reasons.push("A separate bounded-cost approval is required before planning training.");
53686
+ }
53687
+ if (!sourcePolicies.length || sourcePolicies.some((policy) => policy.state !== "authorized")) {
53688
+ decision = "no_training";
53689
+ reasons.push("Every learning source must retain an authorized source-policy receipt.");
53690
+ }
53691
+ if (signal.confounded) {
53692
+ decision = "no_training";
53693
+ reasons.push("The baseline signal is confounded by non-reward-eligible or infrastructure outcomes.");
53694
+ }
53695
+ const createdAt = (input.now ?? (() => (/* @__PURE__ */ new Date()).toISOString()))();
53696
+ const tasksetRelease = {
53697
+ id: baseline.tasksetRelease.id,
53698
+ contentHash: baseline.tasksetRelease.contentHash
53699
+ };
53700
+ const verifierRef = immutableRef(baseline.metadata.verifierRef, "Baseline verifier");
53701
+ const receipt = createModelImprovementQualificationReceipt({
53702
+ schemaVersion: "openpond.modelImprovementQualificationReceipt.v1",
53703
+ id: `model-qualification-${contentHash({
53704
+ review: input.reviewRef,
53705
+ tasksetRelease,
53706
+ baseline: baseline.contentHash,
53707
+ model: baseline.model,
53708
+ privacyApproval: input.privacyApproval ?? null,
53709
+ budgetApproval: input.budgetApproval ?? null,
53710
+ maximumCostUsd: input.maximumCostUsd,
53711
+ decision
53712
+ }).slice(0, 24)}`,
53713
+ review: input.reviewRef,
53714
+ harnessRelease: baseline.harnessRelease,
53715
+ tasksetRelease,
53716
+ baselineEvaluation: { id: baseline.id, contentHash: baseline.contentHash },
53717
+ model: baseline.model,
53718
+ environmentHash: hashMetadata(baseline, "environmentHash"),
53719
+ toolContractHash: hashMetadata(baseline, "toolContractHash"),
53720
+ permissionContractHash: hashMetadata(baseline, "permissionContractHash"),
53721
+ policyHash: hashMetadata(baseline, "policyHash"),
53722
+ verifierRef,
53723
+ sourcePolicies,
53724
+ trainingEvidenceRefs,
53725
+ frozenEvaluationEvidenceRefs: frozenEvidenceRefs,
53726
+ privacyApproval: input.privacyApproval ?? null,
53727
+ budgetApproval: input.budgetApproval ?? null,
53728
+ maximumCostUsd: input.maximumCostUsd,
53729
+ signal: {
53730
+ kind: signal.kind,
53731
+ strength: signal.strength,
53732
+ calibrated: signal.calibrated,
53733
+ confounded: signal.confounded,
53734
+ variance: signal.variance,
53735
+ evidenceRefs: trainingEvidenceRefs
53736
+ },
53737
+ decision,
53738
+ reasons: [...new Set(reasons)],
53739
+ createdAt,
53740
+ metadata: {
53741
+ sourceTasksetId: taskset.id,
53742
+ sourceTasksetRevision: taskset.revision,
53743
+ sourceTasksetHash: taskset.contentHash,
53744
+ workspaceId: lineage.review.workspaceId
53745
+ }
53746
+ });
53747
+ const existing = (await input.store.listHarnessImprovementArtifacts(
53748
+ lineage.review.workspaceId,
53749
+ "training_qualification",
53750
+ 1e3
53751
+ )).find((candidate2) => candidate2.id === receipt.id);
53752
+ if (existing) {
53753
+ if (existing.contentHash !== receipt.contentHash) {
53754
+ throw new Error("Model-improvement qualification ID already has different immutable content.");
53755
+ }
53756
+ return existing;
53757
+ }
53758
+ await input.store.saveHarnessImprovementArtifact(
53759
+ lineage.review.workspaceId,
53760
+ "training_qualification",
53761
+ receipt
53762
+ );
53763
+ await linkQualificationReview({
53764
+ store: input.store,
53765
+ originRef: input.reviewRef,
53766
+ workspaceId: lineage.review.workspaceId,
53767
+ taskset,
53768
+ baseline,
53769
+ qualification: receipt,
53770
+ createdAt
53771
+ });
53772
+ return receipt;
53773
+ }
53774
+ async function requireQualifiedModelImprovement(input) {
53775
+ const receipt = (await input.store.listHarnessImprovementArtifacts(
53776
+ input.workspaceId,
53777
+ "training_qualification",
53778
+ 1e3
53779
+ )).find(
53780
+ (candidate2) => candidate2.id === input.qualificationRef.id && candidate2.contentHash === input.qualificationRef.contentHash
53781
+ );
53782
+ if (!receipt || receipt.decision === "no_training") {
53783
+ throw new Error("A qualified model-improvement receipt is required before planning training.");
53784
+ }
53785
+ const taskset = await input.store.getTaskset(input.tasksetId);
53786
+ if (!taskset || taskset.metadata.harnessEvaluationReview === void 0) {
53787
+ throw new Error("Qualified Taskset was not found.");
53788
+ }
53789
+ if (receipt.metadata.sourceTasksetId !== taskset.id || receipt.metadata.sourceTasksetHash !== taskset.contentHash) {
53790
+ throw new Error("Model-improvement qualification does not match the current immutable Taskset.");
53791
+ }
53792
+ if (!recipeMatches(receipt.decision, input.recipe.method)) {
53793
+ throw new Error("Training recipe method does not match the qualification decision.");
53794
+ }
53795
+ if (receipt.model.model !== input.baseModelId) {
53796
+ throw new Error("Training base Model does not match the qualified baseline Model.");
53797
+ }
53798
+ if (input.maximumCostUsd !== null && input.maximumCostUsd !== void 0 && input.maximumCostUsd > receipt.maximumCostUsd) {
53799
+ throw new Error("Training approval exceeds the qualified maximum cost.");
53800
+ }
53801
+ return receipt;
53802
+ }
53803
+ function signalForTaskset(taskset, baseline) {
53804
+ const calibrated = taskset.graders.every(
53805
+ (grader) => grader.kind !== "model_judge" || grader.calibrationStatus === "passed"
53806
+ );
53807
+ const confounded = baseline.rewardEligibleCount < baseline.attemptCount || (baseline.failureCounts.infrastructure_failure ?? 0) > 0;
53808
+ const variance2 = typeof baseline.metadata.scoreVariance === "number" ? baseline.metadata.scoreVariance : null;
53809
+ if (taskset.learningSignals.rewards.length) {
53810
+ const sourceIds = new Set(taskset.learningSignals.rewards.flatMap((signal) => signal.sourceRefs));
53811
+ const usable = calibrated && !confounded && variance2 !== null && variance2 > 0 && sourceIds.size > 0;
53812
+ return {
53813
+ decision: usable ? "rl" : "no_training",
53814
+ kind: "scalar_reward",
53815
+ strength: usable ? "usable" : variance2 === 0 ? "weak" : "absent",
53816
+ calibrated,
53817
+ confounded,
53818
+ variance: variance2,
53819
+ sourceIds,
53820
+ reasons: [usable ? "The Taskset has calibrated scalar reward with non-zero baseline variance." : "RL requires calibrated, non-confounded scalar reward with non-zero baseline variance."]
53821
+ };
53822
+ }
53823
+ if (taskset.learningSignals.preferences.length) {
53824
+ const sourceIds = new Set(taskset.learningSignals.preferences.flatMap((signal) => signal.sourceRefs));
53825
+ const usable = calibrated && !confounded && sourceIds.size > 0;
53826
+ return {
53827
+ decision: usable ? "preference" : "no_training",
53828
+ kind: "chosen_rejected",
53829
+ strength: usable ? "usable" : "weak",
53830
+ calibrated,
53831
+ confounded,
53832
+ variance: variance2,
53833
+ sourceIds,
53834
+ reasons: [usable ? "The Taskset has approved chosen/rejected pairs." : "Preference training lacks usable approved chosen/rejected signal."]
53835
+ };
53836
+ }
53837
+ if (taskset.learningSignals.demonstrations.length) {
53838
+ const sourceIds = new Set(taskset.learningSignals.demonstrations.flatMap((signal) => signal.sourceRefs));
53839
+ const usable = calibrated && !confounded && sourceIds.size > 0;
53840
+ return {
53841
+ decision: usable ? "sft" : "no_training",
53842
+ kind: "demonstrations",
53843
+ strength: usable ? "usable" : "weak",
53844
+ calibrated,
53845
+ confounded,
53846
+ variance: variance2,
53847
+ sourceIds,
53848
+ reasons: [usable ? "The Taskset has approved demonstration signal." : "SFT lacks usable approved demonstration signal."]
53849
+ };
53850
+ }
53851
+ return {
53852
+ decision: "no_training",
53853
+ kind: "none",
53854
+ strength: "absent",
53855
+ calibrated,
53856
+ confounded,
53857
+ variance: variance2,
53858
+ sourceIds: /* @__PURE__ */ new Set(),
53859
+ reasons: ["The Taskset has no eligible non-frozen learning signal."]
53860
+ };
53861
+ }
53862
+ function taskEvidenceRefs(taskset, sourceIds) {
53863
+ return taskset.sourceRefs.filter((source) => sourceIds.has(source.id)).map((source) => ({
53864
+ id: source.id,
53865
+ contentHash: isTrainingSourceRef(source) ? source.sourceHash : contentHash(source)
53866
+ }));
53867
+ }
53868
+ function assertBaselineLineage(taskset, baseline, reviewRef) {
53869
+ const boundReview = taskset.metadata.harnessEvaluationReview;
53870
+ if (!sameRef(boundReview, reviewRef)) {
53871
+ throw new Error("Taskset does not match the supplied Harness Evaluation review.");
53872
+ }
53873
+ if (baseline.metadata.kind !== "baseline" || baseline.metadata.sourceTasksetId !== taskset.id || baseline.metadata.sourceTasksetHash !== taskset.contentHash || !sameRef(baseline.metadata.harnessEvaluationReview, reviewRef)) {
53874
+ throw new Error("Baseline Evaluation lineage does not match the Taskset and review.");
53875
+ }
53876
+ }
53877
+ function harnessLineage(taskset) {
53878
+ const value = taskset.metadata.harnessEvaluationLineage;
53879
+ if (!isRecord5(value) || !isRecord5(value.review) || !Array.isArray(value.sourcePolicies)) {
53880
+ throw new Error("Taskset has no exact Harness Evaluation source-policy lineage.");
53881
+ }
53882
+ return {
53883
+ review: {
53884
+ id: String(value.review.id ?? ""),
53885
+ contentHash: String(value.review.contentHash ?? ""),
53886
+ workspaceId: String(value.review.workspaceId ?? "")
53887
+ },
53888
+ sourcePolicies: value.sourcePolicies
53889
+ };
53890
+ }
53891
+ async function linkQualificationReview(input) {
53892
+ const reviews = await input.store.listHarnessImprovementArtifacts(
53893
+ input.workspaceId,
53894
+ "evaluation_review",
53895
+ 1e3
53896
+ );
53897
+ const origin = reviews.find((review) => sameRef(review, input.originRef));
53898
+ if (!origin) throw new Error("Originating Harness Evaluation review was not found.");
53899
+ const qualificationRef = { id: input.qualification.id, contentHash: input.qualification.contentHash };
53900
+ const linkKey = contentHash({
53901
+ origin: input.originRef,
53902
+ taskset: input.taskset.contentHash,
53903
+ baseline: input.baseline.contentHash,
53904
+ qualification: qualificationRef
53905
+ });
53906
+ if (reviews.some((review) => review.metadata.downstreamLinkKey === linkKey)) return;
53907
+ const qualified = input.qualification.decision !== "no_training";
53908
+ const receipt = createHarnessEvaluationReviewReceipt({
53909
+ schemaVersion: "openpond.harnessEvaluationReviewReceipt.v1",
53910
+ id: `evaluation-review-qualification-${linkKey.slice(0, 24)}`,
53911
+ ownerScope: origin.ownerScope,
53912
+ workspaceRef: origin.workspaceRef,
53913
+ harnessRelease: origin.harnessRelease,
53914
+ previousWatermark: origin.nextWatermark,
53915
+ nextWatermark: {
53916
+ cursor: contentHash({ cursor: origin.nextWatermark.cursor, qualificationRef }),
53917
+ throughCreatedAt: input.createdAt
53918
+ },
53919
+ selectedEvidence: origin.selectedEvidence,
53920
+ excludedEvidence: origin.excludedEvidence,
53921
+ claim: origin.claim,
53922
+ classification: qualified ? "model_improvement" : "taskset",
53923
+ triage: [...origin.triage, {
53924
+ layer: "model",
53925
+ status: qualified ? "unresolved" : "blocked",
53926
+ reason: input.qualification.reasons.join(" "),
53927
+ evidenceRefs: [
53928
+ { id: input.baseline.id, contentHash: input.baseline.contentHash },
53929
+ qualificationRef
53930
+ ]
53931
+ }],
53932
+ reason: input.qualification.reasons.join(" "),
53933
+ nextAuthority: "human_review",
53934
+ maxEstimatedCostUsd: input.qualification.maximumCostUsd,
53935
+ tasksetProposal: { id: input.taskset.id, contentHash: input.taskset.contentHash },
53936
+ evaluation: { id: input.baseline.id, contentHash: input.baseline.contentHash },
53937
+ trainingQualification: qualificationRef,
53938
+ policyVersion: origin.policyVersion,
53939
+ createdAt: input.createdAt,
53940
+ metadata: { originReview: input.originRef, downstreamLinkKey: linkKey }
53941
+ });
53942
+ await input.store.saveHarnessImprovementArtifact(input.workspaceId, "evaluation_review", receipt);
53943
+ }
53944
+ function immutableRef(value, label) {
53945
+ const parsed = ImmutableReleaseRefSchema.safeParse(value);
53946
+ if (!parsed.success) throw new Error(`${label} reference is missing from the baseline Evaluation.`);
53947
+ return parsed.data;
53948
+ }
53949
+ function hashMetadata(baseline, key) {
53950
+ const value = baseline.metadata[key];
53951
+ if (typeof value !== "string") throw new Error(`Baseline Evaluation is missing ${key}.`);
53952
+ return value;
53953
+ }
53954
+ function recipeMatches(decision, method) {
53955
+ if (decision === "sft") return method === "sft";
53956
+ if (decision === "preference") return method === "dpo";
53957
+ if (decision === "rl") return method === "grpo" || method === "ppo";
53958
+ return false;
53959
+ }
53960
+ function sameRef(value, expected) {
53961
+ return isRecord5(value) && value.id === expected.id && value.contentHash === expected.contentHash;
53962
+ }
53963
+ function isRecord5(value) {
53964
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
53965
+ }
53966
+
53967
+ // ../server/src/training/harness-training-api-inputs.ts
53968
+ function harnessIntegerArray(value, label) {
53969
+ if (value === void 0) return void 0;
53970
+ if (!Array.isArray(value) || value.some((item) => !Number.isInteger(item))) {
53971
+ throw new Error(`${label} must be an array of integers.`);
53972
+ }
53973
+ return value;
53974
+ }
53975
+ function nonnegativeHarnessNumber(value, name) {
53976
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
53977
+ throw new Error(`${name} must be a non-negative number.`);
53978
+ }
53979
+ return value;
53980
+ }
53981
+ function optionalImmutableRef(value, name) {
53982
+ if (value === void 0 || value === null) return null;
53983
+ return requiredImmutableRef(value, name);
53984
+ }
53985
+ function requiredImmutableRef(value, name) {
53986
+ const candidate2 = record9(value);
53987
+ return {
53988
+ id: requiredString8(candidate2.id, `${name}.id`),
53989
+ contentHash: requiredString8(candidate2.contentHash, `${name}.contentHash`)
53990
+ };
53991
+ }
53992
+ function sameImmutableRef(value, expected) {
53993
+ const candidate2 = record9(value);
53994
+ return candidate2.id === expected.id && candidate2.contentHash === expected.contentHash;
53995
+ }
53996
+ function recipeBaseModelId(recipe) {
53997
+ const method = recipe.method;
53998
+ const base = record9(recipe.baseModel);
53999
+ if (method === "sft" || method === "grpo") {
54000
+ return requiredString8(base.id, "recipe.baseModel.id");
54001
+ }
54002
+ if (method === "dpo") {
54003
+ return requiredString8(record9(recipe.policyModel).id, "recipe.policyModel.id");
54004
+ }
54005
+ if (method === "ppo") {
54006
+ return requiredString8(
54007
+ record9(record9(recipe.policyOptimization).policyModel).id,
54008
+ "recipe.policyOptimization.policyModel.id"
54009
+ );
54010
+ }
54011
+ throw new Error("Qualified training recipe method is not executable.");
54012
+ }
54013
+ function record9(value) {
54014
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
54015
+ }
54016
+ function requiredString8(value, name) {
54017
+ if (typeof value !== "string" || !value.trim()) throw new Error(`${name} is required.`);
54018
+ return value.trim();
54019
+ }
54020
+
53257
54021
  // ../server/src/training/training-api.ts
53258
54022
  function createTrainingApi(deps) {
53259
54023
  async function request(action, payload, requestUrl) {
53260
- const input = record9(payload);
54024
+ const input = record10(payload);
53261
54025
  if (action === "state") return state(string(input.profileId) ?? requestUrl?.searchParams.get("profileId") ?? "default");
53262
54026
  if (action === "activity") return activity(string(input.profileId) ?? requestUrl?.searchParams.get("profileId") ?? "default");
53263
54027
  if (action === "portable_catalog") {
@@ -53310,7 +54074,7 @@ function createTrainingApi(deps) {
53310
54074
  }
53311
54075
  if (action === "delete_model_run_draft") {
53312
54076
  const draft = await deps.store.getModelRunDraft(
53313
- requiredString8(input.draftId, "draftId")
54077
+ requiredString9(input.draftId, "draftId")
53314
54078
  );
53315
54079
  if (!draft) return { deleted: false };
53316
54080
  if (draft.status === "launched") {
@@ -53319,9 +54083,9 @@ function createTrainingApi(deps) {
53319
54083
  await deps.store.deleteModelRunDraft(draft.id);
53320
54084
  return { deleted: true, draftId: draft.id };
53321
54085
  }
53322
- if (action === "add_source") return deps.taskCreator.addSessionSource({ profileId: requiredString8(input.profileId, "profileId"), sessionId: requiredString8(input.sessionId, "sessionId"), turnIds: stringArray6(input.turnIds), consentScope: input.consentScope === "selected_turns" ? "selected_turns" : "full_session" });
54086
+ if (action === "add_source") return deps.taskCreator.addSessionSource({ profileId: requiredString9(input.profileId, "profileId"), sessionId: requiredString9(input.sessionId, "sessionId"), turnIds: stringArray6(input.turnIds), consentScope: input.consentScope === "selected_turns" ? "selected_turns" : "full_session" });
53323
54087
  if (action === "add_sources") {
53324
- const profileId = requiredString8(input.profileId, "profileId");
54088
+ const profileId = requiredString9(input.profileId, "profileId");
53325
54089
  const sources = [];
53326
54090
  for (const sessionId of requiredStringArray(input.sessionIds, "sessionIds")) {
53327
54091
  sources.push(await deps.taskCreator.addSessionSource({ profileId, sessionId, consentScope: "full_session" }));
@@ -53333,7 +54097,7 @@ function createTrainingApi(deps) {
53333
54097
  if (action === "dataset_rows") {
53334
54098
  if (!requestUrl) throw new Error("Dataset row query is missing its URL.");
53335
54099
  return deps.datasetArtifacts.rows(
53336
- requiredString8(input.tasksetId, "tasksetId"),
54100
+ requiredString9(input.tasksetId, "tasksetId"),
53337
54101
  {
53338
54102
  split: requestUrl.searchParams.get("split") || null,
53339
54103
  cursor: requestUrl.searchParams.get("cursor") || null,
@@ -53350,37 +54114,53 @@ function createTrainingApi(deps) {
53350
54114
  if (action === "materialize_dataset_import") {
53351
54115
  const approved = ApproveDatasetImportMappingRequestSchema.parse(input);
53352
54116
  return deps.datasetImports.materialize({
53353
- id: requiredString8(input.importId, "importId"),
54117
+ id: requiredString9(input.importId, "importId"),
53354
54118
  ...approved
53355
54119
  });
53356
54120
  }
53357
54121
  if (action === "cancel_dataset_import") {
53358
- return deps.datasetImports.cancel(requiredString8(input.importId, "importId"));
54122
+ return deps.datasetImports.cancel(requiredString9(input.importId, "importId"));
53359
54123
  }
53360
54124
  if (action === "remove_source") {
53361
- await deps.store.deleteTrainingSource(requiredString8(input.sourceId, "sourceId"));
54125
+ await deps.store.deleteTrainingSource(requiredString9(input.sourceId, "sourceId"));
53362
54126
  return { removed: true };
53363
54127
  }
53364
- if (action === "delete_taskset") return deps.training.deleteTaskset(requiredString8(input.tasksetId, "tasksetId"));
54128
+ if (action === "delete_taskset") return deps.training.deleteTaskset(requiredString9(input.tasksetId, "tasksetId"));
53365
54129
  if (action === "create_model_from_taskset") {
53366
54130
  const preferredBaseModel = requiredBaseModelPreference(
53367
54131
  input.preferredBaseModel,
53368
54132
  input.preferredBaseModelId
53369
54133
  );
53370
54134
  return createModelFromTaskset({
53371
- profileId: requiredString8(input.profileId, "profileId"),
53372
- tasksetId: requiredString8(input.tasksetId, "tasksetId"),
54135
+ profileId: requiredString9(input.profileId, "profileId"),
54136
+ tasksetId: requiredString9(input.tasksetId, "tasksetId"),
53373
54137
  preferredBaseModelId: preferredBaseModel.modelId,
53374
54138
  preferredBaseModel
53375
54139
  });
53376
54140
  }
54141
+ if (action === "accept_harness_review") {
54142
+ const reviewRef = record10(input.reviewRef);
54143
+ return startHarnessReviewTasksetAuthoring({
54144
+ store: deps.store,
54145
+ taskCreator: deps.taskCreator,
54146
+ startCreation: startModelCreation,
54147
+ profileId: requiredString9(input.profileId, "profileId"),
54148
+ workspaceId: requiredString9(input.workspaceId, "workspaceId"),
54149
+ reviewRef: {
54150
+ id: requiredString9(reviewRef.id, "reviewRef.id"),
54151
+ contentHash: requiredString9(reviewRef.contentHash, "reviewRef.contentHash")
54152
+ },
54153
+ analysisModel: input.analysisModel ? ChatModelRefSchema.parse(input.analysisModel) : null,
54154
+ analysisReasoningEffort: input.analysisReasoningEffort ? CodexReasoningEffortSchema.parse(input.analysisReasoningEffort) : null
54155
+ });
54156
+ }
53377
54157
  if (action === "start_creation") {
53378
54158
  const preferredBaseModel = nullableBaseModelPreference(
53379
54159
  input.preferredBaseModel,
53380
54160
  input.preferredBaseModelId
53381
54161
  );
53382
54162
  return startModelCreation({
53383
- profileId: requiredString8(input.profileId, "profileId"),
54163
+ profileId: requiredString9(input.profileId, "profileId"),
53384
54164
  sourceIds: stringArray6(input.sourceIds),
53385
54165
  surface: creationSurface(input.surface),
53386
54166
  mode: input.mode === "customize" ? "customize" : "defaults",
@@ -53399,34 +54179,38 @@ function createTrainingApi(deps) {
53399
54179
  targetIntent: tasksetTargetIntent(input.targetIntent)
53400
54180
  });
53401
54181
  }
53402
- if (action === "approve_disclosure") return syncCreation(await deps.taskCreator.approveDisclosure(requiredString8(input.creationId, "creationId"), input.approved === true));
53403
- if (action === "retry_creation") return retryModelCreation(requiredString8(input.creationId, "creationId"));
53404
- if (action === "answer_questions") return syncCreation(await deps.taskCreator.answerQuestions(requiredString8(input.creationId, "creationId"), stringRecord(input.answers)));
54182
+ if (action === "approve_disclosure") return syncCreation(await deps.taskCreator.approveDisclosure(requiredString9(input.creationId, "creationId"), input.approved === true));
54183
+ if (action === "retry_creation") return retryModelCreation(requiredString9(input.creationId, "creationId"));
54184
+ if (action === "answer_questions") return syncCreation(await deps.taskCreator.answerQuestions(requiredString9(input.creationId, "creationId"), stringRecord(input.answers)));
53405
54185
  if (action === "approve_materialization") {
53406
- const creation = await deps.taskCreator.approveMaterialization(requiredString8(input.creationId, "creationId"), input.approved === true);
53407
- if (creation.state === "ready" && creation.materializedTasksetId) await deps.evaluation.readiness(creation.materializedTasksetId);
54186
+ const creation = await deps.taskCreator.approveMaterialization(requiredString9(input.creationId, "creationId"), input.approved === true);
54187
+ if (creation.state === "ready" && creation.materializedTasksetId) {
54188
+ await deps.evaluation.readiness(creation.materializedTasksetId);
54189
+ const taskset = await deps.store.getTaskset(creation.materializedTasksetId);
54190
+ if (taskset) await linkHarnessReviewTaskset({ store: deps.store, taskset });
54191
+ }
53408
54192
  return syncCreation(creation);
53409
54193
  }
53410
- if (action === "chat_creation") return syncCreation(await deps.taskCreator.chat(requiredString8(input.creationId, "creationId"), requiredString8(input.message, "message")));
53411
- if (action === "rename_creation") return syncCreation(await deps.taskCreator.rename(requiredString8(input.creationId, "creationId"), requiredString8(input.name, "name")));
53412
- if (action === "cancel_creation") return syncCreation(await deps.taskCreator.cancel(requiredString8(input.creationId, "creationId")));
54194
+ if (action === "chat_creation") return syncCreation(await deps.taskCreator.chat(requiredString9(input.creationId, "creationId"), requiredString9(input.message, "message")));
54195
+ if (action === "rename_creation") return syncCreation(await deps.taskCreator.rename(requiredString9(input.creationId, "creationId"), requiredString9(input.name, "name")));
54196
+ if (action === "cancel_creation") return syncCreation(await deps.taskCreator.cancel(requiredString9(input.creationId, "creationId")));
53413
54197
  if (action === "run_miner") return deps.taskMiner.startRun(RunTaskMinerRequestSchema.parse(input));
53414
- if (action === "cancel_miner_run") return deps.taskMiner.cancelRun(requiredString8(input.runId, "runId"));
53415
- if (action === "configure_miner") return deps.taskMiner.updateConfig(requiredString8(input.profileId, "profileId"), TaskMinerConfigSchema.parse(input.config));
53416
- if (action === "patch_candidate") return deps.taskMiner.patch(requiredString8(input.candidateId, "candidateId"), PatchTaskCandidateRequestSchema.parse(input.patch));
54198
+ if (action === "cancel_miner_run") return deps.taskMiner.cancelRun(requiredString9(input.runId, "runId"));
54199
+ if (action === "configure_miner") return deps.taskMiner.updateConfig(requiredString9(input.profileId, "profileId"), TaskMinerConfigSchema.parse(input.config));
54200
+ if (action === "patch_candidate") return deps.taskMiner.patch(requiredString9(input.candidateId, "candidateId"), PatchTaskCandidateRequestSchema.parse(input.patch));
53417
54201
  if (action === "create_candidate") {
53418
- const candidate2 = await deps.store.getTaskCandidate(requiredString8(input.candidateId, "candidateId"));
54202
+ const candidate2 = await deps.store.getTaskCandidate(requiredString9(input.candidateId, "candidateId"));
53419
54203
  if (!candidate2) throw new Error("Task Candidate not found.");
53420
54204
  const sourceIds = [...new Set(candidate2.evidence.flatMap((item) => item.sourceRefIds))];
53421
54205
  await deps.taskMiner.patch(candidate2.id, { status: "creating" });
53422
54206
  return startModelCreation({ profileId: candidate2.profileId, sourceIds, surface: "task_candidate", mode: input.mode === "customize" ? "customize" : "defaults", entryMode: "automated", objective: string(input.objective) ?? candidate2.summary, candidateId: candidate2.id, analysisModel: input.analysisModel ? ChatModelRefSchema.parse(input.analysisModel) : null, analysisReasoningEffort: input.analysisReasoningEffort ? CodexReasoningEffortSchema.parse(input.analysisReasoningEffort) : null });
53423
54207
  }
53424
- if (action === "grade") return deps.evaluation.grade({ tasksetId: requiredString8(input.tasksetId, "tasksetId"), taskId: requiredString8(input.taskId, "taskId"), attempt: input.attempt });
54208
+ if (action === "grade") return deps.evaluation.grade({ tasksetId: requiredString9(input.tasksetId, "tasksetId"), taskId: requiredString9(input.taskId, "taskId"), attempt: input.attempt });
53425
54209
  if (action === "execute_taskset_attempt") {
53426
- const sampling = record9(input.sampling);
54210
+ const sampling = record10(input.sampling);
53427
54211
  return deps.evaluation.execute({
53428
- tasksetId: requiredString8(input.tasksetId, "tasksetId"),
53429
- taskId: requiredString8(input.taskId, "taskId"),
54212
+ tasksetId: requiredString9(input.tasksetId, "tasksetId"),
54213
+ taskId: requiredString9(input.taskId, "taskId"),
53430
54214
  model: ChatModelRefSchema.parse(input.model),
53431
54215
  seed: boundedInteger(input.seed, "seed", -2147483648, 2147483647, 17),
53432
54216
  attempt: boundedInteger(input.attempt, "attempt", 0, 1e6, 0),
@@ -53456,38 +54240,121 @@ function createTrainingApi(deps) {
53456
54240
  resultId: string(input.resultId) ?? void 0
53457
54241
  });
53458
54242
  }
53459
- if (action === "audit_graders") return deps.evaluation.auditFixtures({ tasksetId: requiredString8(input.tasksetId, "tasksetId"), fixtures: Array.isArray(input.fixtures) ? input.fixtures : void 0 });
53460
- if (action === "calibrate_judges") return deps.evaluation.calibrateModelJudges(requiredString8(input.tasksetId, "tasksetId"));
53461
- if (action === "readiness") return deps.evaluation.readiness(requiredString8(input.tasksetId, "tasksetId"));
53462
- if (action === "preview_expert_bootstrap") return deps.training.previewExpertBootstrap(requiredString8(input.tasksetId, "tasksetId"));
54243
+ if (action === "execute_harness_review_baseline") {
54244
+ const reviewRef = record10(input.reviewRef);
54245
+ const sampling = record10(input.sampling);
54246
+ return deps.evaluation.executeBaseline({
54247
+ tasksetId: requiredString9(input.tasksetId, "tasksetId"),
54248
+ model: ChatModelRefSchema.parse(input.model),
54249
+ reviewRef: {
54250
+ id: requiredString9(reviewRef.id, "reviewRef.id"),
54251
+ contentHash: requiredString9(reviewRef.contentHash, "reviewRef.contentHash")
54252
+ },
54253
+ seeds: harnessIntegerArray(input.seeds, "seeds"),
54254
+ attemptsPerTask: boundedInteger(
54255
+ input.attemptsPerTask,
54256
+ "attemptsPerTask",
54257
+ 1,
54258
+ 20,
54259
+ 1
54260
+ ),
54261
+ sampling: {
54262
+ maxOutputTokens: boundedInteger(
54263
+ sampling.maxOutputTokens,
54264
+ "sampling.maxOutputTokens",
54265
+ 1,
54266
+ 128e3,
54267
+ 4096
54268
+ ),
54269
+ temperature: boundedNumber(
54270
+ sampling.temperature,
54271
+ "sampling.temperature",
54272
+ 0,
54273
+ 2,
54274
+ 0
54275
+ ),
54276
+ topP: boundedNumber(sampling.topP, "sampling.topP", 0, 1, 1)
54277
+ }
54278
+ });
54279
+ }
54280
+ if (action === "qualify_harness_model_improvement") {
54281
+ const reviewRef = requiredImmutableRef(input.reviewRef, "reviewRef");
54282
+ return qualifyHarnessModelImprovement({
54283
+ store: deps.store,
54284
+ tasksetId: requiredString9(input.tasksetId, "tasksetId"),
54285
+ baselineEvaluationId: requiredString9(input.baselineEvaluationId, "baselineEvaluationId"),
54286
+ reviewRef,
54287
+ privacyApproval: optionalImmutableRef(input.privacyApproval, "privacyApproval"),
54288
+ budgetApproval: optionalImmutableRef(input.budgetApproval, "budgetApproval"),
54289
+ maximumCostUsd: nonnegativeHarnessNumber(input.maximumCostUsd, "maximumCostUsd")
54290
+ });
54291
+ }
54292
+ if (action === "audit_graders") return deps.evaluation.auditFixtures({ tasksetId: requiredString9(input.tasksetId, "tasksetId"), fixtures: Array.isArray(input.fixtures) ? input.fixtures : void 0 });
54293
+ if (action === "calibrate_judges") return deps.evaluation.calibrateModelJudges(requiredString9(input.tasksetId, "tasksetId"));
54294
+ if (action === "readiness") return deps.evaluation.readiness(requiredString9(input.tasksetId, "tasksetId"));
54295
+ if (action === "preview_expert_bootstrap") return deps.training.previewExpertBootstrap(requiredString9(input.tasksetId, "tasksetId"));
53463
54296
  if (action === "approve_expert_bootstrap") return deps.training.approveExpertBootstrap({
53464
- tasksetId: requiredString8(input.tasksetId, "tasksetId"),
53465
- previewHash: requiredString8(input.previewHash, "previewHash")
53466
- });
53467
- if (action === "create_plan") return deps.training.createPlan({ modelId: requiredString8(input.modelId, "modelId"), tasksetId: requiredString8(input.tasksetId, "tasksetId"), destinationId: TrainingDestinationIdSchema.parse(input.destinationId), recipe: input.recipe, environmentPlacement: managedRolloutPlacement(input.environmentPlacement), exportApproved: input.exportApproved === true, retentionDays: nullableNumber(input.retentionDays), region: string(input.region) });
54297
+ tasksetId: requiredString9(input.tasksetId, "tasksetId"),
54298
+ previewHash: requiredString9(input.previewHash, "previewHash")
54299
+ });
54300
+ if (action === "create_plan") return deps.training.createPlan({ modelId: requiredString9(input.modelId, "modelId"), tasksetId: requiredString9(input.tasksetId, "tasksetId"), destinationId: TrainingDestinationIdSchema.parse(input.destinationId), recipe: input.recipe, environmentPlacement: managedRolloutPlacement(input.environmentPlacement), exportApproved: input.exportApproved === true, retentionDays: nullableNumber(input.retentionDays), region: string(input.region) });
54301
+ if (action === "prepare_qualified_model_improvement") {
54302
+ const qualificationRef = requiredImmutableRef(input.qualificationRef, "qualificationRef");
54303
+ const workspaceId = requiredString9(input.workspaceId, "workspaceId");
54304
+ const tasksetId = requiredString9(input.tasksetId, "tasksetId");
54305
+ const recipe = record10(input.recipe);
54306
+ const destinationId = TrainingDestinationIdSchema.parse(input.destinationId);
54307
+ const qualification = await requireQualifiedModelImprovement({
54308
+ store: deps.store,
54309
+ workspaceId,
54310
+ qualificationRef,
54311
+ tasksetId,
54312
+ recipe,
54313
+ baseModelId: recipeBaseModelId(recipe)
54314
+ });
54315
+ if (qualification.decision === "rl" && destinationId !== "openpond_managed") {
54316
+ throw new Error("Qualified RL must use the OpenPond Managed boundary.");
54317
+ }
54318
+ const prepared = await deps.training.prepareStart({
54319
+ modelId: requiredString9(input.modelId, "modelId"),
54320
+ tasksetId,
54321
+ destinationId,
54322
+ recipe,
54323
+ environmentPlacement: managedRolloutPlacement(input.environmentPlacement),
54324
+ exportApproved: input.exportApproved === true,
54325
+ retentionDays: nullableNumber(input.retentionDays),
54326
+ region: string(input.region),
54327
+ harnessRelease: qualification.harnessRelease,
54328
+ modelImprovementQualification: qualificationRef
54329
+ });
54330
+ if (prepared.plan.estimatedCostUsd !== null && prepared.plan.estimatedCostUsd > qualification.maximumCostUsd) {
54331
+ throw new Error("Prepared Training Plan exceeds the qualified maximum cost.");
54332
+ }
54333
+ return { qualification, prepared };
54334
+ }
53468
54335
  if (action === "prepare_model_run") return deps.training.prepareModelRun({
53469
- modelRunId: requiredString8(input.modelRunId, "modelRunId"),
54336
+ modelRunId: requiredString9(input.modelRunId, "modelRunId"),
53470
54337
  maximumSpendUsd: nullableNumber(input.maximumSpendUsd),
53471
54338
  retentionDays: nullableNumber(input.retentionDays)
53472
54339
  });
53473
54340
  if (action === "start_model_run") return deps.training.startModelRun({
53474
- modelRunId: requiredString8(input.modelRunId, "modelRunId"),
54341
+ modelRunId: requiredString9(input.modelRunId, "modelRunId"),
53475
54342
  maximumSpendUsd: nullableNumber(input.maximumSpendUsd),
53476
54343
  retentionDays: nullableNumber(input.retentionDays),
53477
54344
  exportApproved: input.exportApproved === true,
53478
54345
  manifest: input.manifest
53479
54346
  });
53480
- if (action === "model_run_status") return deps.training.modelRunStatus(requiredString8(input.modelRunId, "modelRunId"));
53481
- if (action === "model_run_events") return deps.training.modelRunEvents(requiredString8(input.modelRunId, "modelRunId"));
53482
- if (action === "model_run_logs") return deps.training.modelRunLogs(requiredString8(input.modelRunId, "modelRunId"));
53483
- if (action === "model_run_artifacts") return deps.training.modelRunArtifacts(requiredString8(input.modelRunId, "modelRunId"));
53484
- if (action === "cancel_model_run") return deps.training.cancelModelRun(requiredString8(input.modelRunId, "modelRunId"));
53485
- if (action === "build_bundle") return deps.training.buildBundle(requiredString8(input.planId, "planId"));
53486
- if (action === "approve_training") return deps.training.approve({ planId: requiredString8(input.planId, "planId"), bundleId: requiredString8(input.bundleId, "bundleId"), approvedBy: string(input.approvedBy) ?? void 0, maximumCostUsd: nullableNumber(input.maximumCostUsd) });
53487
- if (action === "launch") return deps.training.launch({ planId: requiredString8(input.planId, "planId"), approvalId: requiredString8(input.approvalId, "approvalId") });
54347
+ if (action === "model_run_status") return deps.training.modelRunStatus(requiredString9(input.modelRunId, "modelRunId"));
54348
+ if (action === "model_run_events") return deps.training.modelRunEvents(requiredString9(input.modelRunId, "modelRunId"));
54349
+ if (action === "model_run_logs") return deps.training.modelRunLogs(requiredString9(input.modelRunId, "modelRunId"));
54350
+ if (action === "model_run_artifacts") return deps.training.modelRunArtifacts(requiredString9(input.modelRunId, "modelRunId"));
54351
+ if (action === "cancel_model_run") return deps.training.cancelModelRun(requiredString9(input.modelRunId, "modelRunId"));
54352
+ if (action === "build_bundle") return deps.training.buildBundle(requiredString9(input.planId, "planId"));
54353
+ if (action === "approve_training") return deps.training.approve({ planId: requiredString9(input.planId, "planId"), bundleId: requiredString9(input.bundleId, "bundleId"), approvedBy: string(input.approvedBy) ?? void 0, maximumCostUsd: nullableNumber(input.maximumCostUsd) });
54354
+ if (action === "launch") return deps.training.launch({ planId: requiredString9(input.planId, "planId"), approvalId: requiredString9(input.approvalId, "approvalId") });
53488
54355
  if (action === "prepare_start") return deps.training.prepareStart({
53489
- modelId: requiredString8(input.modelId, "modelId"),
53490
- tasksetId: requiredString8(input.tasksetId, "tasksetId"),
54356
+ modelId: requiredString9(input.modelId, "modelId"),
54357
+ tasksetId: requiredString9(input.tasksetId, "tasksetId"),
53491
54358
  destinationId: TrainingDestinationIdSchema.parse(input.destinationId),
53492
54359
  recipe: input.recipe,
53493
54360
  environmentPlacement: managedRolloutPlacement(input.environmentPlacement),
@@ -53497,41 +54364,66 @@ function createTrainingApi(deps) {
53497
54364
  });
53498
54365
  if (action === "start_prepared") {
53499
54366
  const result = await deps.training.startPrepared({
53500
- planId: requiredString8(input.planId, "planId"),
53501
- bundleId: requiredString8(input.bundleId, "bundleId"),
54367
+ planId: requiredString9(input.planId, "planId"),
54368
+ bundleId: requiredString9(input.bundleId, "bundleId"),
53502
54369
  maximumCostUsd: nullableNumber(input.maximumCostUsd)
53503
54370
  });
53504
54371
  return linkStartedTraining(result);
53505
54372
  }
54373
+ if (action === "start_qualified_model_improvement") {
54374
+ const qualificationRef = requiredImmutableRef(input.qualificationRef, "qualificationRef");
54375
+ const planId = requiredString9(input.planId, "planId");
54376
+ const bundleId = requiredString9(input.bundleId, "bundleId");
54377
+ const plan = await deps.store.getTrainingPlan(planId);
54378
+ if (!plan || !sameImmutableRef(plan.modelImprovementQualification, qualificationRef)) {
54379
+ throw new Error("Prepared Training Plan does not match the supplied qualification.");
54380
+ }
54381
+ const maximumCostUsd = nonnegativeHarnessNumber(input.maximumCostUsd, "maximumCostUsd");
54382
+ const qualification = await requireQualifiedModelImprovement({
54383
+ store: deps.store,
54384
+ workspaceId: requiredString9(input.workspaceId, "workspaceId"),
54385
+ qualificationRef,
54386
+ tasksetId: plan.tasksetId,
54387
+ recipe: plan.recipe,
54388
+ baseModelId: recipeBaseModelId(plan.recipe),
54389
+ maximumCostUsd
54390
+ });
54391
+ const result = await deps.training.startPrepared({
54392
+ planId,
54393
+ bundleId,
54394
+ maximumCostUsd
54395
+ });
54396
+ return { ...await linkStartedTraining(result), qualification };
54397
+ }
53506
54398
  if (action === "start") {
53507
- const result = await deps.training.start({ modelId: requiredString8(input.modelId, "modelId"), tasksetId: requiredString8(input.tasksetId, "tasksetId"), destinationId: TrainingDestinationIdSchema.parse(input.destinationId), recipe: input.recipe, environmentPlacement: managedRolloutPlacement(input.environmentPlacement), exportApproved: input.exportApproved === true, maximumCostUsd: nullableNumber(input.maximumCostUsd), retentionDays: nullableNumber(input.retentionDays), region: string(input.region) });
54399
+ const result = await deps.training.start({ modelId: requiredString9(input.modelId, "modelId"), tasksetId: requiredString9(input.tasksetId, "tasksetId"), destinationId: TrainingDestinationIdSchema.parse(input.destinationId), recipe: input.recipe, environmentPlacement: managedRolloutPlacement(input.environmentPlacement), exportApproved: input.exportApproved === true, maximumCostUsd: nullableNumber(input.maximumCostUsd), retentionDays: nullableNumber(input.retentionDays), region: string(input.region) });
53508
54400
  return linkStartedTraining(result);
53509
54401
  }
53510
- if (action === "import_artifact") return deps.training.importExternal({ planId: requiredString8(input.planId, "planId"), bundleId: requiredString8(input.bundleId, "bundleId"), artifactDirectory: requiredString8(input.artifactDirectory, "artifactDirectory") });
53511
- if (action === "export_bundle") return deps.training.exportBundle(requiredString8(input.bundleId, "bundleId"));
53512
- if (action === "artifact_download") return deps.training.artifactDownload(requiredString8(input.artifactId, "artifactId"));
53513
- if (action === "model_package_download") return deps.training.modelPackageDownload(requiredString8(input.modelId, "modelId"));
53514
- if (action === "reject_model") return deps.training.rejectModel({ modelId: requiredString8(input.modelId, "modelId"), reason: requiredString8(input.reason, "reason") });
54402
+ if (action === "import_artifact") return deps.training.importExternal({ planId: requiredString9(input.planId, "planId"), bundleId: requiredString9(input.bundleId, "bundleId"), artifactDirectory: requiredString9(input.artifactDirectory, "artifactDirectory") });
54403
+ if (action === "export_bundle") return deps.training.exportBundle(requiredString9(input.bundleId, "bundleId"));
54404
+ if (action === "artifact_download") return deps.training.artifactDownload(requiredString9(input.artifactId, "artifactId"));
54405
+ if (action === "model_package_download") return deps.training.modelPackageDownload(requiredString9(input.modelId, "modelId"));
54406
+ if (action === "reject_model") return deps.training.rejectModel({ modelId: requiredString9(input.modelId, "modelId"), reason: requiredString9(input.reason, "reason") });
53515
54407
  if (action === "bind_model") return deps.training.bindModel({
53516
- profileId: requiredString8(input.profileId, "profileId"),
53517
- modelId: requiredString8(input.modelId, "modelId"),
53518
- role: requiredString8(input.role, "role"),
53519
- roleTargetId: requiredString8(input.roleTargetId, "roleTargetId"),
54408
+ profileId: requiredString9(input.profileId, "profileId"),
54409
+ modelId: requiredString9(input.modelId, "modelId"),
54410
+ role: requiredString9(input.role, "role"),
54411
+ roleTargetId: requiredString9(input.roleTargetId, "roleTargetId"),
53520
54412
  promotedBy: string(input.promotedBy) ?? void 0
53521
54413
  });
53522
54414
  if (action === "rollback_model_binding") return deps.training.rollbackModelBinding({
53523
- bindingId: requiredString8(input.bindingId, "bindingId"),
54415
+ bindingId: requiredString9(input.bindingId, "bindingId"),
53524
54416
  rolledBackBy: string(input.rolledBackBy) ?? void 0
53525
54417
  });
53526
- if (action === "update_model_configuration") return deps.training.updateModelConfiguration({ modelId: requiredString8(input.modelId, "modelId"), configuration: record9(input.configuration) });
54418
+ if (action === "update_model_configuration") return deps.training.updateModelConfiguration({ modelId: requiredString9(input.modelId, "modelId"), configuration: record10(input.configuration) });
53527
54419
  if (action === "set_model_pinned") return deps.training.setModelPinned({
53528
- modelId: requiredString8(input.modelId, "modelId"),
54420
+ modelId: requiredString9(input.modelId, "modelId"),
53529
54421
  pinned: input.pinned === true
53530
54422
  });
53531
- if (action === "cancel_job") return deps.training.cancelJob(requiredString8(input.jobId, "jobId"));
53532
- if (action === "job_events") return deps.store.listTrainingJobEvents(requiredString8(input.jobId, "jobId"));
54423
+ if (action === "cancel_job") return deps.training.cancelJob(requiredString9(input.jobId, "jobId"));
54424
+ if (action === "job_events") return deps.store.listTrainingJobEvents(requiredString9(input.jobId, "jobId"));
53533
54425
  if (action === "run_detail") {
53534
- const jobId = requiredString8(input.jobId, "jobId");
54426
+ const jobId = requiredString9(input.jobId, "jobId");
53535
54427
  await deps.training.refreshManagedRunEvidence(jobId).catch(() => void 0);
53536
54428
  return trainingRunDetail(deps.store, jobId);
53537
54429
  }
@@ -53621,6 +54513,9 @@ function createTrainingApi(deps) {
53621
54513
  ]);
53622
54514
  await syncModelTrainingCreateImproveRuns({ store: deps.store, profileId, execution });
53623
54515
  const graderAuditReports = (await Promise.all(tasksets.map((taskset) => deps.store.listGraderAuditReports(taskset.id)))).flat();
54516
+ const evaluationResults = (await Promise.all(
54517
+ tasksets.map((taskset) => deps.store.listEvaluationResults(taskset.id))
54518
+ )).flat();
53624
54519
  const activity2 = projectTrainingActivity({
53625
54520
  profileId,
53626
54521
  state: {
@@ -53639,6 +54534,7 @@ function createTrainingApi(deps) {
53639
54534
  datasetImports,
53640
54535
  datasetArtifacts,
53641
54536
  graderAuditReports,
54537
+ evaluationResults,
53642
54538
  candidates,
53643
54539
  minerConfig,
53644
54540
  minerRuns,
@@ -53850,13 +54746,13 @@ function createTrainingApi(deps) {
53850
54746
  function portableMethod(value) {
53851
54747
  return value === "sft" || value === "dpo" || value === "grpo" || value === "ppo" ? value : void 0;
53852
54748
  }
53853
- function record9(value) {
54749
+ function record10(value) {
53854
54750
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
53855
54751
  }
53856
54752
  function string(value) {
53857
54753
  return typeof value === "string" && value.trim() ? value.trim() : null;
53858
54754
  }
53859
- function requiredString8(value, name) {
54755
+ function requiredString9(value, name) {
53860
54756
  const parsed = string(value);
53861
54757
  if (!parsed) throw new Error(`${name} is required.`);
53862
54758
  return parsed;
@@ -53881,7 +54777,7 @@ function requiredStringArray(value, name) {
53881
54777
  return parsed;
53882
54778
  }
53883
54779
  function stringRecord(value) {
53884
- return Object.fromEntries(Object.entries(record9(value)).filter((entry) => typeof entry[1] === "string"));
54780
+ return Object.fromEntries(Object.entries(record10(value)).filter((entry) => typeof entry[1] === "string"));
53885
54781
  }
53886
54782
  function nullableNumber(value) {
53887
54783
  return typeof value === "number" && Number.isFinite(value) ? value : null;
@@ -53910,7 +54806,7 @@ function trainingMethodHint(value) {
53910
54806
  return value === "sft" || value === "dpo" || value === "grpo" || value === "ppo" ? value : null;
53911
54807
  }
53912
54808
  function tasksetTargetIntent(value) {
53913
- const candidate2 = record9(value);
54809
+ const candidate2 = record10(value);
53914
54810
  const kind = candidate2.kind;
53915
54811
  return {
53916
54812
  kind: kind === "agent" || kind === "skill" || kind === "extension" || kind === "model" || kind === "configuration" ? kind : null,
@@ -54391,7 +55287,7 @@ async function inspectHuggingFaceDataset(locatorInput, request = fetch) {
54391
55287
  request,
54392
55288
  `https://huggingface.co/api/datasets/${locator.repositoryId}${revisionSuffix}`
54393
55289
  );
54394
- const resolvedRevision = requiredString9(repository.sha, "resolved Dataset revision");
55290
+ const resolvedRevision = requiredString10(repository.sha, "resolved Dataset revision");
54395
55291
  const gated = repository.gated === true || typeof repository.gated === "string";
54396
55292
  const privateRepository = repository.private === true;
54397
55293
  if (gated || privateRepository) {
@@ -54430,8 +55326,8 @@ async function inspectHuggingFaceDataset(locatorInput, request = fetch) {
54430
55326
  )
54431
55327
  ]);
54432
55328
  const previewRows = Array.isArray(firstRows.rows) ? firstRows.rows.slice(0, 25).flatMap((value) => {
54433
- const record10 = asRecord17(value);
54434
- return record10 && asRecord17(record10.row) ? [record10.row] : [];
55329
+ const record11 = asRecord17(value);
55330
+ return record11 && asRecord17(record11.row) ? [record11.row] : [];
54435
55331
  }) : [];
54436
55332
  const columns = sourceColumns(firstRows.features, previewRows);
54437
55333
  const sizeBySplit = datasetSizeBySplit(sizes);
@@ -54448,7 +55344,7 @@ ${split.split}`) ?? {
54448
55344
  "Hugging Face has not produced a complete Parquet projection for this Dataset."
54449
55345
  );
54450
55346
  }
54451
- const parquetRevisionSha = requiredString9(
55347
+ const parquetRevisionSha = requiredString10(
54452
55348
  parquetRevision.sha,
54453
55349
  "resolved Dataset Parquet revision"
54454
55350
  );
@@ -54640,9 +55536,9 @@ function flattenRecord(value, prefix, paths, rows) {
54640
55536
  function nestedValue(value, path72) {
54641
55537
  let current = value;
54642
55538
  for (const segment2 of path72.split(".")) {
54643
- const record10 = asRecord17(current);
54644
- if (!record10) return null;
54645
- current = record10[segment2];
55539
+ const record11 = asRecord17(current);
55540
+ if (!record11) return null;
55541
+ current = record11[segment2];
54646
55542
  }
54647
55543
  return current;
54648
55544
  }
@@ -54711,9 +55607,9 @@ async function fetchJson(request, url) {
54711
55607
  }
54712
55608
  const bytes2 = Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)));
54713
55609
  const parsed = JSON.parse(new TextDecoder().decode(bytes2));
54714
- const record10 = asRecord17(parsed);
54715
- if (!record10) throw new Error("Hugging Face returned invalid inspection metadata.");
54716
- return record10;
55610
+ const record11 = asRecord17(parsed);
55611
+ if (!record11) throw new Error("Hugging Face returned invalid inspection metadata.");
55612
+ return record11;
54717
55613
  } finally {
54718
55614
  clearTimeout(timeout);
54719
55615
  }
@@ -54724,7 +55620,7 @@ function firstPresent(paths, candidates) {
54724
55620
  function asRecord17(value) {
54725
55621
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
54726
55622
  }
54727
- function requiredString9(value, label) {
55623
+ function requiredString10(value, label) {
54728
55624
  if (typeof value !== "string" || !value.trim()) {
54729
55625
  throw new Error(`Hugging Face did not return a ${label}.`);
54730
55626
  }
@@ -55189,11 +56085,11 @@ function requiredDatasetStorageBytes(sourceBytes) {
55189
56085
  return Math.ceil(sourceBytes * 2.2) + 256 * 1024 * 1024;
55190
56086
  }
55191
56087
  function parseDatasetMaterializeResult(value) {
55192
- const record10 = asRecord19(value);
55193
- if (record10?.schemaVersion !== "openpond.datasetMaterializeResult.v1" || typeof record10.rowCount !== "number" || !asRecord19(record10.splitCounts) || !Array.isArray(record10.shards) || typeof record10.schemaHash !== "string" || !asRecord19(record10.qualityReport) || typeof record10.qualityReportHash !== "string" || !Array.isArray(record10.previewRows) || !asRecord19(record10.firstTaskIds)) {
56088
+ const record11 = asRecord19(value);
56089
+ if (record11?.schemaVersion !== "openpond.datasetMaterializeResult.v1" || typeof record11.rowCount !== "number" || !asRecord19(record11.splitCounts) || !Array.isArray(record11.shards) || typeof record11.schemaHash !== "string" || !asRecord19(record11.qualityReport) || typeof record11.qualityReportHash !== "string" || !Array.isArray(record11.previewRows) || !asRecord19(record11.firstTaskIds)) {
55194
56090
  throw new Error("Dataset worker returned an invalid materialization result.");
55195
56091
  }
55196
- return record10;
56092
+ return record11;
55197
56093
  }
55198
56094
  function selectedDatasetSourceRows(inspection, mapping) {
55199
56095
  return inspection.splits.filter(
@@ -55780,9 +56676,9 @@ function reusableSourceFiles(taskset, configuredRoot) {
55780
56676
  return result;
55781
56677
  }
55782
56678
  function finalizeMapping(input) {
55783
- const record10 = asRecord20(input);
55784
- if (!record10) throw new Error("Dataset mapping is required.");
55785
- const base = { ...record10, mappingHash: "00000000" };
56679
+ const record11 = asRecord20(input);
56680
+ if (!record11) throw new Error("Dataset mapping is required.");
56681
+ const base = { ...record11, mappingHash: "00000000" };
55786
56682
  const parsed = DatasetImportMappingSchema.parse(base);
55787
56683
  const { mappingHash: _ignored, ...hashable } = parsed;
55788
56684
  return DatasetImportMappingSchema.parse({
@@ -56632,12 +57528,12 @@ function parseWindowsLogicalDisks(value, storeDir) {
56632
57528
  const rows = Array.isArray(parsed) ? parsed : [parsed];
56633
57529
  return rows.flatMap((row) => {
56634
57530
  if (!row || typeof row !== "object") return [];
56635
- const record10 = row;
56636
- const deviceId = typeof record10.DeviceID === "string" ? record10.DeviceID.trim() : "";
56637
- const driveType = typeof record10.DriveType === "number" ? record10.DriveType : Number(record10.DriveType);
57531
+ const record11 = row;
57532
+ const deviceId = typeof record11.DeviceID === "string" ? record11.DeviceID.trim() : "";
57533
+ const driveType = typeof record11.DriveType === "number" ? record11.DriveType : Number(record11.DriveType);
56638
57534
  if (!/^[a-z]:$/i.test(deviceId) || ![2, 3, 4].includes(driveType)) return [];
56639
57535
  const root = `${deviceId}\\`;
56640
- const volumeName = typeof record10.VolumeName === "string" ? record10.VolumeName.trim() : "";
57536
+ const volumeName = typeof record11.VolumeName === "string" ? record11.VolumeName.trim() : "";
56641
57537
  const kind = driveType === 4 ? "network" : driveType === 2 ? "removable" : "local";
56642
57538
  const storeRoot = path68.win32.parse(path68.win32.resolve(storeDir)).root.toLowerCase();
56643
57539
  return [{
@@ -57652,13 +58548,13 @@ function registryArtifacts(value) {
57652
58548
  return Array.isArray(value) ? value.map(requiredRegistryArtifact) : [];
57653
58549
  }
57654
58550
  function requiredRegistryCapabilities(value) {
57655
- if (!isRecord4(value) || value.schemaVersion !== "openpond.modelAdapterPlatformCapabilities.v1" || !isRecord4(value.contractVersions) || value.contractVersions.baseModelProfile !== "openpond.baseModelProfile.v2" || !isRecord4(value.lifecycle) || value.lifecycle.policyOwner !== "sandbox" || !Array.isArray(value.baseProfiles)) {
58551
+ if (!isRecord6(value) || value.schemaVersion !== "openpond.modelAdapterPlatformCapabilities.v1" || !isRecord6(value.contractVersions) || value.contractVersions.baseModelProfile !== "openpond.baseModelProfile.v2" || !isRecord6(value.lifecycle) || value.lifecycle.policyOwner !== "sandbox" || !Array.isArray(value.baseProfiles)) {
57656
58552
  throw new Error(
57657
58553
  "Managed adapter registry returned incompatible platform capabilities."
57658
58554
  );
57659
58555
  }
57660
58556
  const baseProfiles = value.baseProfiles.map((profile) => {
57661
- if (!isRecord4(profile) || typeof profile.id !== "string" || typeof profile.repository !== "string" || typeof profile.revision !== "string" || typeof profile.tokenizerRevision !== "string" || typeof profile.chatTemplateHash !== "string" || !["draft", "qualified", "retired"].includes(String(profile.status))) {
58557
+ if (!isRecord6(profile) || typeof profile.id !== "string" || typeof profile.repository !== "string" || typeof profile.revision !== "string" || typeof profile.tokenizerRevision !== "string" || typeof profile.chatTemplateHash !== "string" || !["draft", "qualified", "retired"].includes(String(profile.status))) {
57662
58558
  throw new Error(
57663
58559
  "Managed adapter registry returned an invalid base profile capability."
57664
58560
  );
@@ -57684,7 +58580,7 @@ function registryDeployments(value) {
57684
58580
  return value.map(requiredRegistryDeployment);
57685
58581
  }
57686
58582
  function requiredRegistryArtifact(value) {
57687
- if (!isRecord4(value) || typeof value.id !== "string" || typeof value.source !== "string" || typeof value.sourceRef !== "string" || typeof value.state !== "string" || typeof value.promotable !== "boolean" || typeof value.customerBindingAllowed !== "boolean") {
58583
+ if (!isRecord6(value) || typeof value.id !== "string" || typeof value.source !== "string" || typeof value.sourceRef !== "string" || typeof value.state !== "string" || typeof value.promotable !== "boolean" || typeof value.customerBindingAllowed !== "boolean") {
57688
58584
  throw new Error("Managed adapter registry returned an invalid artifact.");
57689
58585
  }
57690
58586
  return {
@@ -57699,7 +58595,7 @@ function requiredRegistryArtifact(value) {
57699
58595
  };
57700
58596
  }
57701
58597
  function requiredRegistryDeployment(item) {
57702
- if (!isRecord4(item) || typeof item.id !== "string" || typeof item.artifactId !== "string" || typeof item.state !== "string") {
58598
+ if (!isRecord6(item) || typeof item.id !== "string" || typeof item.artifactId !== "string" || typeof item.state !== "string") {
57703
58599
  throw new Error("Managed adapter registry returned an invalid deployment.");
57704
58600
  }
57705
58601
  return {
@@ -57708,7 +58604,7 @@ function requiredRegistryDeployment(item) {
57708
58604
  state: item.state
57709
58605
  };
57710
58606
  }
57711
- function isRecord4(value) {
58607
+ function isRecord6(value) {
57712
58608
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
57713
58609
  }
57714
58610
 
@@ -57834,18 +58730,18 @@ function createManagedAdapterRegistryClient(dependencies = {}) {
57834
58730
  );
57835
58731
  }
57836
58732
  for await (const raw of parseSse(response.body, input.signal)) {
57837
- if (isRecord5(raw) && isRecord5(raw.error)) {
58733
+ if (isRecord7(raw) && isRecord7(raw.error)) {
57838
58734
  throw new Error(
57839
58735
  typeof raw.error.code === "string" ? raw.error.code : "managed_adapter_stream_failed"
57840
58736
  );
57841
58737
  }
57842
- const usage = isRecord5(raw) && isRecord5(raw.usage) ? raw.usage : null;
58738
+ const usage = isRecord7(raw) && isRecord7(raw.usage) ? raw.usage : null;
57843
58739
  if (usage) yield { usage, raw };
57844
- const choices = isRecord5(raw) && Array.isArray(raw.choices) ? raw.choices : [];
58740
+ const choices = isRecord7(raw) && Array.isArray(raw.choices) ? raw.choices : [];
57845
58741
  for (const choiceValue of choices) {
57846
- const choice = isRecord5(choiceValue) ? choiceValue : null;
58742
+ const choice = isRecord7(choiceValue) ? choiceValue : null;
57847
58743
  if (!choice) continue;
57848
- const delta = isRecord5(choice.delta) ? choice.delta : {};
58744
+ const delta = isRecord7(choice.delta) ? choice.delta : {};
57849
58745
  if (typeof delta.content === "string" && delta.content) {
57850
58746
  yield { text: delta.content, raw };
57851
58747
  }
@@ -57909,7 +58805,7 @@ function managedApiError(payload, status, fallback) {
57909
58805
  const detail = typeof payload.message === "string" ? payload.message : typeof payload.error === "string" ? payload.error : fallback;
57910
58806
  return `Managed adapter API failed (${status}): ${detail.slice(0, 512)}`;
57911
58807
  }
57912
- function isRecord5(value) {
58808
+ function isRecord7(value) {
57913
58809
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
57914
58810
  }
57915
58811
 
@@ -58508,9 +59404,9 @@ function createTrainingModelRuntime(deps) {
58508
59404
  }
58509
59405
  function costFromUsage(usage) {
58510
59406
  if (!usage || typeof usage !== "object" || Array.isArray(usage)) return {};
58511
- const record10 = usage;
59407
+ const record11 = usage;
58512
59408
  for (const key of ["costUsd", "cost_usd", "totalCostUsd", "total_cost_usd"]) {
58513
- const value = record10[key];
59409
+ const value = record11[key];
58514
59410
  if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
58515
59411
  return { costUsd: value };
58516
59412
  }
@@ -59416,23 +60312,23 @@ ${grader.rubric}`
59416
60312
  })
59417
60313
  );
59418
60314
  }
59419
- async function safeUpsertModelUsageRecord(record10) {
60315
+ async function safeUpsertModelUsageRecord(record11) {
59420
60316
  try {
59421
- await store.upsertModelUsageRecord(record10);
60317
+ await store.upsertModelUsageRecord(record11);
59422
60318
  } catch (error) {
59423
60319
  await appendRuntimeEvent(
59424
60320
  event({
59425
- sessionId: record10.sessionId ?? void 0,
59426
- turnId: record10.turnId ?? void 0,
60321
+ sessionId: record11.sessionId ?? void 0,
60322
+ turnId: record11.turnId ?? void 0,
59427
60323
  name: "diagnostic",
59428
60324
  source: "server",
59429
60325
  status: "failed",
59430
60326
  output: error instanceof Error ? error.message : "Failed to persist model usage record.",
59431
60327
  data: {
59432
60328
  kind: "model_usage_record_failed",
59433
- requestId: record10.requestId,
59434
- provider: record10.provider,
59435
- model: record10.model
60329
+ requestId: record11.requestId,
60330
+ provider: record11.provider,
60331
+ model: record11.model
59436
60332
  }
59437
60333
  })
59438
60334
  ).catch(() => void 0);
@@ -59767,6 +60663,11 @@ ${grader.rubric}`
59767
60663
  throw new Error(result.error);
59768
60664
  }
59769
60665
  const harnessSettingsRoutes = createLocalHarnessSettingsRoutePayloads({ store, storeDir });
60666
+ const harnessEvaluationReviewScheduler = createLocalHarnessEvaluationReviewScheduler({
60667
+ store,
60668
+ isClosing: () => closing,
60669
+ logger
60670
+ });
59770
60671
  const agentRuntime = createAppServer({
59771
60672
  ports: createAgentRuntimePorts({
59772
60673
  createSession,
@@ -59779,6 +60680,8 @@ ${grader.rubric}`
59779
60680
  interruptSessionTurn,
59780
60681
  resolveApproval,
59781
60682
  inspectHarness: harnessSettingsRoutes.harnessHistoryPayload,
60683
+ reviewHarnessProposal: harnessSettingsRoutes.reviewHarnessProposalPayload,
60684
+ reviewHarness: (request) => reviewSelectedLocalHarnessEvaluation({ store, request }),
59782
60685
  validateHarness: async () => {
59783
60686
  const release = await resolveSelectedLocalHarnessRelease(store);
59784
60687
  return release ? {
@@ -59791,7 +60694,6 @@ ${grader.rubric}`
59791
60694
  updateHarnessBackgroundReview: harnessSettingsRoutes.updateHarnessBackgroundReviewPayload,
59792
60695
  diffHarness: harnessSettingsRoutes.harnessDiffPayload,
59793
60696
  rollbackHarness: harnessSettingsRoutes.rollbackHarnessPayload,
59794
- reviewHarnessProposal: harnessSettingsRoutes.reviewHarnessProposalPayload,
59795
60697
  subscribeRuntimeEvents,
59796
60698
  observeRuntimeOperation: (runtimeEvent) => {
59797
60699
  logger.info("agent runtime operation", runtimeEvent);
@@ -59993,7 +60895,10 @@ ${grader.rubric}`
59993
60895
  }
59994
60896
  await turnRunner.recoverPendingSubagentCompletions();
59995
60897
  workSandboxLifecycle.start();
59996
- if (options.httpEnabled !== false) localAgentScheduleLoop.start();
60898
+ if (options.httpEnabled !== false) {
60899
+ localAgentScheduleLoop.start();
60900
+ harnessEvaluationReviewScheduler.start();
60901
+ }
59997
60902
  const status = {
59998
60903
  id: serverId,
59999
60904
  host,
@@ -60015,7 +60920,8 @@ ${grader.rubric}`
60015
60920
  },
60016
60921
  backgroundLoops: [
60017
60922
  taskMinerBackgroundLoop,
60018
- localAgentScheduleLoop
60923
+ localAgentScheduleLoop,
60924
+ harnessEvaluationReviewScheduler
60019
60925
  ],
60020
60926
  browserControlQueue,
60021
60927
  closeEventSubscribers,