@tangle-network/agent-eval 2.0.22 → 2.0.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +61 -0
- package/dist/adapters/http.d.ts +2 -2
- package/dist/{agent-profile-_A7aMA4F.d.ts → agent-profile-CTneqKs4.d.ts} +4 -4
- package/dist/{agent-profile-_A7aMA4F.d.ts.map → agent-profile-CTneqKs4.d.ts.map} +1 -1
- package/dist/analyst/index.d.ts +10 -10
- package/dist/analyst/index.js +3 -3
- package/dist/{analyze-runs-Izz_ZeWg.d.ts → analyze-runs-ByEuSMUT.d.ts} +2 -2
- package/dist/{analyze-runs-Izz_ZeWg.d.ts.map → analyze-runs-ByEuSMUT.d.ts.map} +1 -1
- package/dist/app-grade/index.d.ts +3 -3
- package/dist/{benchmark-command-pmeFawvb.js → benchmark-command-Cad4mBro.js} +5 -5
- package/dist/{benchmark-command-pmeFawvb.js.map → benchmark-command-Cad4mBro.js.map} +1 -1
- package/dist/benchmarks/index.d.ts +4 -4
- package/dist/benchmarks/index.js +2 -2
- package/dist/campaign/index.d.ts +7 -7
- package/dist/campaign/index.js +6 -6
- package/dist/{campaign-DPB35MjP.js → campaign-DnAW86LZ.js} +313 -8
- package/dist/campaign-DnAW86LZ.js.map +1 -0
- package/dist/{campaign-evidence-Biq06MQ9.d.ts → campaign-evidence-CSb3y1ob.d.ts} +3 -3
- package/dist/{campaign-evidence-Biq06MQ9.d.ts.map → campaign-evidence-CSb3y1ob.d.ts.map} +1 -1
- package/dist/{campaign-evidence-71uzJMVY.js → campaign-evidence-DwNBjBO_.js} +51 -10
- package/dist/campaign-evidence-DwNBjBO_.js.map +1 -0
- package/dist/cli.js +2 -2
- package/dist/contract/index.d.ts +10 -10
- package/dist/contract/index.js +6 -6
- package/dist/{default-registry-BKHpiYiW.d.ts → default-registry-CKAFLuJg.d.ts} +6 -6
- package/dist/{default-registry-BKHpiYiW.d.ts.map → default-registry-CKAFLuJg.d.ts.map} +1 -1
- package/dist/{define-agent-eval-CBhYD7Gq.js → define-agent-eval-CImcw9xE.js} +3 -3
- package/dist/{define-agent-eval-CBhYD7Gq.js.map → define-agent-eval-CImcw9xE.js.map} +1 -1
- package/dist/{define-agent-eval-Bh8tJHZI.d.ts → define-agent-eval-Ct6n1GWL.d.ts} +4 -4
- package/dist/{define-agent-eval-Bh8tJHZI.d.ts.map → define-agent-eval-Ct6n1GWL.d.ts.map} +1 -1
- package/dist/diagnosis/index.d.ts +2 -2
- package/dist/{dspy-rlm-engine-DFgGrKzg.js → dspy-rlm-engine-DA4uW64o.js} +2 -2
- package/dist/{dspy-rlm-engine-DFgGrKzg.js.map → dspy-rlm-engine-DA4uW64o.js.map} +1 -1
- package/dist/{evaluation-f-UIDwbL.d.ts → evaluation-BnRaBCKu.d.ts} +4 -4
- package/dist/{evaluation-f-UIDwbL.d.ts.map → evaluation-BnRaBCKu.d.ts.map} +1 -1
- package/dist/evaluation.d.ts +1 -1
- package/dist/{exact-types-BIHqYBYf.d.ts → exact-types-QwxMWchv.d.ts} +2 -2
- package/dist/{exact-types-BIHqYBYf.d.ts.map → exact-types-QwxMWchv.d.ts.map} +1 -1
- package/dist/experiment/index.d.ts +1 -1
- package/dist/experiment/index.js +1 -1
- package/dist/{external-optimizer-process-DkOMkeHW.js → external-optimizer-process-BfRVOfBK.js} +2 -2
- package/dist/{external-optimizer-process-DkOMkeHW.js.map → external-optimizer-process-BfRVOfBK.js.map} +1 -1
- package/dist/{external-optimizer-subprocess-CFIiwHSE.js → external-optimizer-subprocess-D2_gmU9_.js} +8 -3
- package/dist/external-optimizer-subprocess-D2_gmU9_.js.map +1 -0
- package/dist/{feedback-trajectory-CoQPmSJV.d.ts → feedback-trajectory-BkWAgoY0.d.ts} +3 -3
- package/dist/{feedback-trajectory-CoQPmSJV.d.ts.map → feedback-trajectory-BkWAgoY0.d.ts.map} +1 -1
- package/dist/{findings-store-DcBkRLDk.js → findings-store-Daqo7ksI.js} +2 -2
- package/dist/{findings-store-DcBkRLDk.js.map → findings-store-Daqo7ksI.js.map} +1 -1
- package/dist/{index-Cq_5SLfF.d.ts → index-B0j5dY7G.d.ts} +18 -18
- package/dist/{index-Cq_5SLfF.d.ts.map → index-B0j5dY7G.d.ts.map} +1 -1
- package/dist/{index-DH_Jxu9p.d.ts → index-CUpIEvoN.d.ts} +2 -2
- package/dist/{index-DH_Jxu9p.d.ts.map → index-CUpIEvoN.d.ts.map} +1 -1
- package/dist/{index-4khf0Q7g.d.ts → index-DmsDwlPe.d.ts} +5 -5
- package/dist/{index-4khf0Q7g.d.ts.map → index-DmsDwlPe.d.ts.map} +1 -1
- package/dist/{index-C1jQ7qqy.d.ts → index-XxTJDBBR.d.ts} +9 -9
- package/dist/{index-C1jQ7qqy.d.ts.map → index-XxTJDBBR.d.ts.map} +1 -1
- package/dist/index.d.ts +18 -18
- package/dist/index.js +7 -7
- package/dist/{llm-judge-DRHTRT66.js → llm-judge-REd26RYc.js} +2 -2
- package/dist/{llm-judge-DRHTRT66.js.map → llm-judge-REd26RYc.js.map} +1 -1
- package/dist/{matrix-BtyN7jpb.d.ts → matrix-CHbTz1bP.d.ts} +2 -2
- package/dist/{matrix-BtyN7jpb.d.ts.map → matrix-CHbTz1bP.d.ts.map} +1 -1
- package/dist/multishot/golden/index.d.ts +1 -1
- package/dist/multishot/index.d.ts +7 -7
- package/dist/multishot/index.js +3 -3
- package/dist/openapi.json +1 -1
- package/dist/{optimization-method-B-NFaHom.js → optimization-method-DjihqZCo.js} +2 -2
- package/dist/{optimization-method-B-NFaHom.js.map → optimization-method-DjihqZCo.js.map} +1 -1
- package/dist/{prime-protocol-BRMk6dGI.d.ts → prime-protocol-46WvqIIt.d.ts} +2 -2
- package/dist/{prime-protocol-BRMk6dGI.d.ts.map → prime-protocol-46WvqIIt.d.ts.map} +1 -1
- package/dist/{registry-BeInzotS.d.ts → registry-Bh1M9hrf.d.ts} +3 -3
- package/dist/{registry-BeInzotS.d.ts.map → registry-Bh1M9hrf.d.ts.map} +1 -1
- package/dist/rl.d.ts +3 -3
- package/dist/rollout/index.d.ts +2 -2
- package/dist/{run-improvement-loop-D9IAZviC.d.ts → run-improvement-loop-Dfdg42H1.d.ts} +75 -21
- package/dist/run-improvement-loop-Dfdg42H1.d.ts.map +1 -0
- package/dist/search/index.d.ts +23 -8
- package/dist/search/index.d.ts.map +1 -1
- package/dist/search/index.js +73 -31
- package/dist/search/index.js.map +1 -1
- package/dist/{search-kernel-C2XOJHvk.d.ts → search-kernel-By0lhdoJ.d.ts} +2 -2
- package/dist/{search-kernel-C2XOJHvk.d.ts.map → search-kernel-By0lhdoJ.d.ts.map} +1 -1
- package/dist/{self-improve-DZ8W-QY-.d.ts → self-improve-2GWnx1dc.d.ts} +6 -6
- package/dist/{self-improve-DZ8W-QY-.d.ts.map → self-improve-2GWnx1dc.d.ts.map} +1 -1
- package/dist/{self-improve-Dm9PvLF2.js → self-improve-CL1Mfgkw.js} +3 -3
- package/dist/{self-improve-Dm9PvLF2.js.map → self-improve-CL1Mfgkw.js.map} +1 -1
- package/dist/{skillopt-optimization-method-QZoNbg57.js → skillopt-optimization-method-DgsG1p3g.js} +984 -907
- package/dist/skillopt-optimization-method-DgsG1p3g.js.map +1 -0
- package/dist/{store-tool-spans-wH8y7InB.d.ts → store-tool-spans-B9zc0I1r.d.ts} +3 -3
- package/dist/{store-tool-spans-wH8y7InB.d.ts.map → store-tool-spans-B9zc0I1r.d.ts.map} +1 -1
- package/dist/{systemone-CpW1U2Uy.d.ts → systemone-Co2Lv810.d.ts} +6 -6
- package/dist/{systemone-CpW1U2Uy.d.ts.map → systemone-Co2Lv810.d.ts.map} +1 -1
- package/dist/{systemone-review-DpAXWDkL.d.ts → systemone-review-CRJ-Zdfo.d.ts} +3 -3
- package/dist/{systemone-review-DpAXWDkL.d.ts.map → systemone-review-CRJ-Zdfo.d.ts.map} +1 -1
- package/dist/systemone.d.ts +3 -3
- package/dist/{tool-groups-SlnoQNyT.d.ts → tool-groups-BHX9G_oE.d.ts} +2 -2
- package/dist/tool-groups-BHX9G_oE.d.ts.map +1 -0
- package/dist/{trace-questions-ybyF0B6N.d.ts → trace-questions-DfaIVysB.d.ts} +2 -2
- package/dist/{trace-questions-ybyF0B6N.d.ts.map → trace-questions-DfaIVysB.d.ts.map} +1 -1
- package/dist/trace-repair/index.d.ts +1 -1
- package/dist/traces.d.ts +2 -2
- package/dist/{tree-DBvepwFt.js → tree-CK9h-xZF.js} +5 -4
- package/dist/tree-CK9h-xZF.js.map +1 -0
- package/dist/{types-DSU3qb_o.d.ts → types-Ci2r6el5.d.ts} +2 -2
- package/dist/{types-DSU3qb_o.d.ts.map → types-Ci2r6el5.d.ts.map} +1 -1
- package/dist/{types-B1W3v8dT.d.ts → types-CjrzKsOK.d.ts} +8 -8
- package/dist/{types-B1W3v8dT.d.ts.map → types-CjrzKsOK.d.ts.map} +1 -1
- package/dist/{types-BpIAnRCe.d.ts → types-CmHcpGl0.d.ts} +2 -2
- package/dist/{types-BpIAnRCe.d.ts.map → types-CmHcpGl0.d.ts.map} +1 -1
- package/dist/wire/index.d.ts +3 -3
- package/docs/campaign-proposers.md +32 -1
- package/docs/public-api.md +5 -4
- package/docs/search-ledger.md +4 -3
- package/package.json +1 -1
- package/dist/campaign-DPB35MjP.js.map +0 -1
- package/dist/campaign-evidence-71uzJMVY.js.map +0 -1
- package/dist/external-optimizer-subprocess-CFIiwHSE.js.map +0 -1
- package/dist/run-improvement-loop-D9IAZviC.d.ts.map +0 -1
- package/dist/skillopt-optimization-method-QZoNbg57.js.map +0 -1
- package/dist/tool-groups-SlnoQNyT.d.ts.map +0 -1
- package/dist/tree-DBvepwFt.js.map +0 -1
package/dist/{skillopt-optimization-method-QZoNbg57.js → skillopt-optimization-method-DgsG1p3g.js}
RENAMED
|
@@ -6,8 +6,8 @@ import { t as decidePairedPromotion } from "./paired-promotion-decision-BtfVwEAk
|
|
|
6
6
|
import { a as heldoutSignificance, o as pairHoldout } from "./statistical-heldout-CL_7mI5C.js";
|
|
7
7
|
import { a as mapConcurrent } from "./journal-3y-btqaP.js";
|
|
8
8
|
import { n as contentHash, t as canonicalJson } from "./verdict-cache-BPaYxfG8.js";
|
|
9
|
-
import { D as campaignCellSearchResult, E as campaignCellMeasurement, G as assertIndependentEvaluationSplit, J as exposeFinalEvidence, K as captureFinalEvidencePolicy, L as captureJudge, P as gateArms, Q as runCampaign, X as reserveFinalEvidence, _ as developmentClaim, a as combineComparisonCosts, b as surfaceNode, et as resolveRunDir, g as SearchRecorder, i as readGepaCandidatePopulationArtifact, it as withUncapturedAgentSpend, n as executeOptimizationMethod, o as costFromLedgerSummary, q as evaluationUnitMap, r as assertGepaCandidatePopulationSummary, s as optimizationTokenUsageFromSummary, t as assertArtifactDescriptionSetOnce, x as assertSearchHistoryAdmissionOptions, y as surfaceDiff } from "./optimization-method-
|
|
10
|
-
import {
|
|
9
|
+
import { D as campaignCellSearchResult, E as campaignCellMeasurement, G as assertIndependentEvaluationSplit, J as exposeFinalEvidence, K as captureFinalEvidencePolicy, L as captureJudge, P as gateArms, Q as runCampaign, X as reserveFinalEvidence, _ as developmentClaim, a as combineComparisonCosts, b as surfaceNode, et as resolveRunDir, g as SearchRecorder, i as readGepaCandidatePopulationArtifact, it as withUncapturedAgentSpend, n as executeOptimizationMethod, o as costFromLedgerSummary, q as evaluationUnitMap, r as assertGepaCandidatePopulationSummary, s as optimizationTokenUsageFromSummary, t as assertArtifactDescriptionSetOnce, x as assertSearchHistoryAdmissionOptions, y as surfaceDiff } from "./optimization-method-DjihqZCo.js";
|
|
10
|
+
import { A as assertCampaignDesign, M as assertCompleteCampaign, b as excerptEvidence, f as campaignBreakdown, m as campaignEvidence, p as campaignContrastiveEvidence, t as createCampaignEvidenceReceipt } from "./campaign-evidence-DwNBjBO_.js";
|
|
11
11
|
import { t as deepFreezeCanonicalJson } from "./deep-freeze-CK8-2W7p.js";
|
|
12
12
|
import { f as createRunCostLedger, p as fsCampaignStorage } from "./finding-scope-BVQVcjz7.js";
|
|
13
13
|
import { s as surfaceContentHash } from "./json-recovery-BRUCeQxo.js";
|
|
@@ -17,8 +17,8 @@ import { n as isRecord } from "./json-DtvZNAU9.js";
|
|
|
17
17
|
import { a as assertJsonValue, c as isCandidateText, d as resolveExternalOptimizerCallbackLimits, f as resolveExternalOptimizerProcessLimits, i as assertExternalOptimizerModelBudget, l as isExternalTextCandidate, o as assertNoCredentialValues, p as safePathComponent, u as removeCredentialEnvironment } from "./external-optimizer-contracts-vrye9kti.js";
|
|
18
18
|
import { t as acquireSingleRunLock } from "./single-run-lock-BSKsoeQF.js";
|
|
19
19
|
import { c as combineAbortSignals } from "./llm-client-D4B1qR_1.js";
|
|
20
|
-
import { i as startExternalOptimizerModelProxy, n as closeExternalOptimizerResources, r as runWithCleanup, t as runExternalOptimizerProcess } from "./external-optimizer-subprocess-
|
|
21
|
-
import { t as startExternalOptimizerCallback } from "./external-optimizer-process-
|
|
20
|
+
import { i as startExternalOptimizerModelProxy, n as closeExternalOptimizerResources, r as runWithCleanup, t as runExternalOptimizerProcess } from "./external-optimizer-subprocess-D2_gmU9_.js";
|
|
21
|
+
import { t as startExternalOptimizerCallback } from "./external-optimizer-process-BfRVOfBK.js";
|
|
22
22
|
import { createHash, randomBytes } from "node:crypto";
|
|
23
23
|
import { mkdir } from "node:fs/promises";
|
|
24
24
|
import { isDeepStrictEqual } from "node:util";
|
|
@@ -299,6 +299,8 @@ function createExternalTextEvaluator(args) {
|
|
|
299
299
|
const shared = args.input.describeArtifact;
|
|
300
300
|
if (args.describeArtifact && shared && args.describeArtifact !== shared) throw new Error(`${args.label}: describeArtifact is set both on the method and by its caller; set it once`);
|
|
301
301
|
const describeArtifact = args.describeArtifact ?? shared;
|
|
302
|
+
const contrastiveEvidence = args.contrastiveEvidence;
|
|
303
|
+
const trainIds = contrastiveEvidence ? new Set(args.input.trainScenarios.map(({ id }) => id)) : void 0;
|
|
302
304
|
const cached = /* @__PURE__ */ new Map();
|
|
303
305
|
return async ({ candidate, exampleId }, signal, measured) => {
|
|
304
306
|
if (!args.scenarioById.has(exampleId)) throw new Error(`${args.label} requested unknown train or selection case '${exampleId}'`);
|
|
@@ -332,6 +334,10 @@ function createExternalTextEvaluator(args) {
|
|
|
332
334
|
costLedger: args.costLedger,
|
|
333
335
|
maxEvidenceChars: args.maxEvidenceChars,
|
|
334
336
|
...describeArtifact ? { describeArtifact } : {},
|
|
337
|
+
...contrastiveEvidence ? { contrastiveEvidence: {
|
|
338
|
+
policy: contrastiveEvidence,
|
|
339
|
+
training: trainIds?.has(exampleId) ?? false
|
|
340
|
+
} } : {},
|
|
335
341
|
signal
|
|
336
342
|
});
|
|
337
343
|
cached.set(cacheKey, result);
|
|
@@ -436,17 +442,17 @@ async function scoreOneScenario(args) {
|
|
|
436
442
|
const failedCell = campaign.cells.find((cell) => cell.error !== void 0);
|
|
437
443
|
if (failedCell) {
|
|
438
444
|
const stage = failedCell.errorStage ?? "unknown";
|
|
439
|
-
const
|
|
445
|
+
const diagnostic = args.contrastiveEvidence ? "See the retained campaign cell." : failedCell.error?.slice(0, 2e3) ?? "cell failed without an error message";
|
|
440
446
|
return respond({
|
|
441
447
|
score: 0,
|
|
442
448
|
info: {
|
|
443
449
|
scenarioId: failedCell.scenarioId,
|
|
444
450
|
dimensions: {},
|
|
445
451
|
status: "failed",
|
|
446
|
-
notes: `Evaluation failed at ${stage}; optimizer penalty score 0 is not a measured zero. ${
|
|
452
|
+
notes: `Evaluation failed at ${stage}; optimizer penalty score 0 is not a measured zero. ${diagnostic}`,
|
|
447
453
|
error: {
|
|
448
454
|
stage,
|
|
449
|
-
message
|
|
455
|
+
message: diagnostic
|
|
450
456
|
}
|
|
451
457
|
}
|
|
452
458
|
});
|
|
@@ -457,10 +463,13 @@ async function scoreOneScenario(args) {
|
|
|
457
463
|
cells,
|
|
458
464
|
refusal: /* @__PURE__ */ new Error(`${args.label} evaluation produced no score for '${args.scenario.id}'`)
|
|
459
465
|
};
|
|
460
|
-
const
|
|
466
|
+
const contrast = args.contrastiveEvidence;
|
|
467
|
+
let artifact;
|
|
468
|
+
if (!contrast) artifact = campaignEvidence(campaign.cells, {
|
|
461
469
|
scenarios: [args.scenario],
|
|
462
470
|
...args.describeArtifact ? { describeArtifact: args.describeArtifact } : {}
|
|
463
471
|
}).get(args.scenario.id);
|
|
472
|
+
if (contrast?.training) artifact = campaignContrastiveEvidence(campaign.cells, args.scenario, contrast.policy, args.describeArtifact);
|
|
464
473
|
return respond({
|
|
465
474
|
score: row.composite,
|
|
466
475
|
info: {
|
|
@@ -468,7 +477,7 @@ async function scoreOneScenario(args) {
|
|
|
468
477
|
dimensions: breakdown.dimensions,
|
|
469
478
|
scores: { ...breakdown.dimensions },
|
|
470
479
|
status: "scored",
|
|
471
|
-
|
|
480
|
+
...!contrast && row.notes ? { notes: row.notes } : {},
|
|
472
481
|
...artifact !== void 0 ? { artifact } : {}
|
|
473
482
|
}
|
|
474
483
|
});
|
|
@@ -723,7 +732,8 @@ function assertExternalTextOptimizationConfig(config) {
|
|
|
723
732
|
function snapshotExternalTextOptimizationConfig(config) {
|
|
724
733
|
return {
|
|
725
734
|
...config,
|
|
726
|
-
source: { ...config.source }
|
|
735
|
+
source: { ...config.source },
|
|
736
|
+
...config.searchLedger ? { searchLedger: structuredClone(config.searchLedger) } : {}
|
|
727
737
|
};
|
|
728
738
|
}
|
|
729
739
|
function assertExternalTextOptimizerResult(result, name, maxCandidateChars, expectsComponents) {
|
|
@@ -791,311 +801,775 @@ function assertExternalCostAccounting(value, calls, name) {
|
|
|
791
801
|
}
|
|
792
802
|
if (accounting.kind !== "external" || typeof accounting.reason !== "string" || !accounting.reason.trim() || accounting.reason.trim() !== accounting.reason) throw new Error(`${name}: optimizer returned invalid costAccounting`);
|
|
793
803
|
}
|
|
794
|
-
// src/campaign/
|
|
795
|
-
const DEFAULT_MAX_CANDIDATE_CHARS = 2e5;
|
|
796
|
-
const DEFAULT_MAX_EVIDENCE_CHARS = 1e5;
|
|
797
|
-
const DEFAULT_TIMEOUT_MS = 18e5;
|
|
798
|
-
const MAX_TIMER_DELAY_MS$2 = 2147483647;
|
|
804
|
+
// src/campaign/gepa-search-import.ts
|
|
799
805
|
/**
|
|
800
|
-
*
|
|
806
|
+
* Import an external optimizer's own record into a search ledger.
|
|
801
807
|
*
|
|
802
|
-
*
|
|
803
|
-
*
|
|
808
|
+
* GEPA, SkillOpt, and PRISM search inside their own processes. The evaluation
|
|
809
|
+
* callback's observation log holds every candidate they evaluated, and
|
|
810
|
+
* GEPA's candidate population also names each candidate's parents by index.
|
|
811
|
+
* The importer turns both into ledger events: one node per distinct candidate,
|
|
812
|
+
* one `correlated` edge per population entry (joined by content digest from
|
|
813
|
+
* GEPA's own parent record), and one cell per campaign cell an evaluation
|
|
814
|
+
* measured (one per evaluation for a log that names no cells). Nothing is inferred
|
|
815
|
+
* from timing or order: a candidate with no parent record (a SkillOpt or PRISM
|
|
816
|
+
* candidate, and a candidate GEPA kept out of its population) has an `unknown`
|
|
817
|
+
* edge and no parents.
|
|
804
818
|
*/
|
|
805
|
-
function
|
|
806
|
-
|
|
807
|
-
const snapshot = snapshotExternalTextOptimizationConfig(config);
|
|
808
|
-
return {
|
|
809
|
-
name: snapshot.name,
|
|
810
|
-
optimize: (input) => optimizeExternalText(snapshot, input)
|
|
811
|
-
};
|
|
819
|
+
function noRationale(optimizer) {
|
|
820
|
+
return { unknown: `${optimizer} records no rationale per candidate; its reflection attaches to the proposer operation` };
|
|
812
821
|
}
|
|
813
|
-
const
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
822
|
+
const NO_GEPA_RATIONALE = noRationale("GEPA");
|
|
823
|
+
/**
|
|
824
|
+
* Register GEPA's population as nodes and its parent indices as `correlated`
|
|
825
|
+
* edges. A parentless entry (GEPA's seed) gets a seed edge unless its node is
|
|
826
|
+
* already in the tree, for example the root the caller seeded.
|
|
827
|
+
*/
|
|
828
|
+
async function importGepaPopulation(input) {
|
|
829
|
+
const { recorder, population } = input;
|
|
830
|
+
const node = input.node ?? ((candidate) => surfaceNode(recorder, externalSurface(candidate.candidate)));
|
|
831
|
+
const diff = input.diff ?? ((parent, child) => surfaceDiff(recorder, externalSurface(parent.candidate), externalSurface(child.candidate)));
|
|
832
|
+
const nodeIds = /* @__PURE__ */ new Map();
|
|
833
|
+
const byIndex = new Map(population.candidates.map((candidate) => [candidate.index, candidate]));
|
|
834
|
+
const seenNodes = /* @__PURE__ */ new Set();
|
|
835
|
+
let edges = 0;
|
|
836
|
+
let collapsedDuplicates = 0;
|
|
837
|
+
let unchangedProposals = 0;
|
|
838
|
+
for (const candidate of population.candidates) {
|
|
839
|
+
const { nodeId } = await recorder.registerNode(node(candidate));
|
|
840
|
+
if (seenNodes.has(nodeId)) collapsedDuplicates += 1;
|
|
841
|
+
seenNodes.add(nodeId);
|
|
842
|
+
nodeIds.set(candidate.index, nodeId);
|
|
843
|
+
const parentIndices = [...new Set(candidate.parentIndices.filter((index) => index !== null))];
|
|
844
|
+
const parents = [];
|
|
845
|
+
for (const index of parentIndices) {
|
|
846
|
+
const parentNodeId = nodeIds.get(index);
|
|
847
|
+
const parent = byIndex.get(index);
|
|
848
|
+
if (parentNodeId === void 0 || parent === void 0) throw new Error(`GEPA candidate ${candidate.index} names parent ${index}, which precedes no population entry`);
|
|
849
|
+
if (parentNodeId === nodeId) continue;
|
|
850
|
+
if (!parents.some((known) => known.nodeId === parentNodeId)) parents.push({
|
|
851
|
+
nodeId: parentNodeId,
|
|
852
|
+
candidate: parent
|
|
853
|
+
});
|
|
854
|
+
}
|
|
855
|
+
if (parentIndices.length > 0 && parents.length === 0) {
|
|
856
|
+
unchangedProposals += 1;
|
|
857
|
+
continue;
|
|
858
|
+
}
|
|
859
|
+
if (parents.length === 0) {
|
|
860
|
+
if (((await recorder.state()).node(nodeId)?.edgeIds.length ?? 0) > 0) continue;
|
|
861
|
+
await recorder.recordEdge({
|
|
862
|
+
childNodeId: nodeId,
|
|
863
|
+
parents: [],
|
|
864
|
+
operator: "seed",
|
|
865
|
+
attribution: "correlated",
|
|
866
|
+
proposer: null,
|
|
867
|
+
proposalKey: `gepa:${population.runId}:${candidate.index}`,
|
|
868
|
+
rationale: NO_GEPA_RATIONALE,
|
|
869
|
+
diffs: [],
|
|
870
|
+
label: `GEPA seed candidate ${candidate.index}`
|
|
871
|
+
});
|
|
872
|
+
edges += 1;
|
|
873
|
+
continue;
|
|
874
|
+
}
|
|
875
|
+
await recorder.recordEdge({
|
|
876
|
+
childNodeId: nodeId,
|
|
877
|
+
parents: parents.map((parent) => parent.nodeId),
|
|
878
|
+
operator: parents.length > 1 ? "merge" : "improve",
|
|
879
|
+
attribution: "correlated",
|
|
880
|
+
proposer: input.proposer,
|
|
881
|
+
proposalKey: `gepa:${population.runId}:${candidate.index}`,
|
|
882
|
+
rationale: NO_GEPA_RATIONALE,
|
|
883
|
+
diffs: parents.map((parent) => diff(parent.candidate, candidate)),
|
|
884
|
+
label: `GEPA candidate ${candidate.index}`
|
|
885
|
+
});
|
|
886
|
+
edges += 1;
|
|
824
887
|
}
|
|
825
|
-
}
|
|
826
|
-
function describeExternalScenarios(scenarios, snapshot, maxEvidenceChars) {
|
|
827
|
-
return Object.freeze(scenarios.map((scenario) => describeExternalScenario(scenario, snapshot.name, maxEvidenceChars, snapshot.describeScenario)));
|
|
828
|
-
}
|
|
829
|
-
/** Run identity, scenario descriptions and directories, then the resume lock. */
|
|
830
|
-
async function prepareExternalRun(snapshot, input) {
|
|
831
|
-
const seedCandidate = encodeExternalTextCandidate(input.baselineSurface);
|
|
832
|
-
const maxCandidateChars = snapshot.maxCandidateChars ?? DEFAULT_MAX_CANDIDATE_CHARS;
|
|
833
|
-
const maxEvidenceChars = snapshot.maxEvidenceChars ?? DEFAULT_MAX_EVIDENCE_CHARS;
|
|
834
|
-
const attemptId = randomBytes(16).toString("hex");
|
|
835
|
-
const storage = input.runOptions.storage ?? fsCampaignStorage();
|
|
836
|
-
const resume = snapshot.resume ?? "never";
|
|
837
|
-
const trainSet = describeExternalScenarios(input.trainScenarios, snapshot, maxEvidenceChars);
|
|
838
|
-
const selectionSet = describeExternalScenarios(input.selectionScenarios, snapshot, maxEvidenceChars);
|
|
839
|
-
const methodDir = `${input.runDir}/external/${safePathComponent(snapshot.name)}`;
|
|
840
|
-
const runId = externalOptimizerRunKey({
|
|
841
|
-
material: {
|
|
842
|
-
optimizer: {
|
|
843
|
-
kind: snapshot.source.kind,
|
|
844
|
-
package: snapshot.source.package,
|
|
845
|
-
version: snapshot.source.version,
|
|
846
|
-
...snapshot.source.sourceUrl ? { sourceUrl: snapshot.source.sourceUrl } : {},
|
|
847
|
-
...snapshot.source.revision ? { revision: snapshot.source.revision } : {}
|
|
848
|
-
},
|
|
849
|
-
method: snapshot.name,
|
|
850
|
-
evaluationId: snapshot.evaluationId,
|
|
851
|
-
dispatchRef: input.runOptions.dispatchRef ?? null,
|
|
852
|
-
objective: snapshot.objective,
|
|
853
|
-
background: snapshot.background ?? "",
|
|
854
|
-
seed: input.seed,
|
|
855
|
-
seedCandidate,
|
|
856
|
-
trainSet,
|
|
857
|
-
selectionSet,
|
|
858
|
-
maxEvaluations: snapshot.maxEvaluations,
|
|
859
|
-
maxOptimizerCostUsd: snapshot.maxOptimizerCostUsd,
|
|
860
|
-
maxCandidateChars,
|
|
861
|
-
maxEvidenceChars
|
|
862
|
-
},
|
|
863
|
-
attemptId,
|
|
864
|
-
resumeEnabled: resume !== "never"
|
|
865
|
-
});
|
|
866
|
-
const stateDir = `${methodDir}/state/${runId}`;
|
|
867
|
-
const artifactDir = `${methodDir}/attempts/${attemptId}`;
|
|
868
|
-
storage.ensureDir(stateDir);
|
|
869
|
-
storage.ensureDir(artifactDir);
|
|
870
|
-
if (resume !== "never") await mkdir(stateDir, { recursive: true });
|
|
871
|
-
const lock = resume === "never" ? void 0 : acquireSingleRunLock({
|
|
872
|
-
lockPath: `${stateDir}.lock`,
|
|
873
|
-
releaseOnExit: true
|
|
874
|
-
});
|
|
875
888
|
return {
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
maxEvidenceChars,
|
|
882
|
-
attemptId,
|
|
883
|
-
storage,
|
|
884
|
-
resume,
|
|
885
|
-
trainSet,
|
|
886
|
-
selectionSet,
|
|
887
|
-
methodDir,
|
|
888
|
-
runId,
|
|
889
|
-
stateDir,
|
|
890
|
-
artifactDir,
|
|
891
|
-
manifestPath: `${stateDir}/run-manifest.jsonl`,
|
|
892
|
-
lock,
|
|
893
|
-
releaseLock: true
|
|
889
|
+
nodeIds,
|
|
890
|
+
nodes: seenNodes.size,
|
|
891
|
+
edges,
|
|
892
|
+
collapsedDuplicates,
|
|
893
|
+
unchangedProposals
|
|
894
894
|
};
|
|
895
895
|
}
|
|
896
|
-
/**
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
896
|
+
/**
|
|
897
|
+
* Record the callback's evaluations as `external` cells. An evaluation that
|
|
898
|
+
* carries its measurement records each campaign cell it names once, through
|
|
899
|
+
* `campaignCellSearchResult`, so the ledger holds the cell's own outcome,
|
|
900
|
+
* dimensions, tokens, cost, model, duration, attempt and trace; a request
|
|
901
|
+
* answered from an earlier request's cells adds none. A refusal that measured
|
|
902
|
+
* cells before it was refused records them the same way, with their real
|
|
903
|
+
* accounting and an `evaluation-refused` outcome; for an evaluation whose
|
|
904
|
+
* campaign threw, that is every cell it settled, and each cell the throw
|
|
905
|
+
* interrupted with unknown accounting. An evaluation logged
|
|
906
|
+
* without cells (a log written before the callback recorded them, or a
|
|
907
|
+
* refusal that measured nothing) records one cell whose accounting is
|
|
908
|
+
* unknown. A candidate that is not yet a node (GEPA evaluated it on a
|
|
909
|
+
* minibatch and discarded it, or SkillOpt, which reports no parents, proposed
|
|
910
|
+
* it) is registered with an `unknown` edge.
|
|
911
|
+
*/
|
|
912
|
+
async function importExternalEvaluations(input) {
|
|
913
|
+
const { recorder } = input;
|
|
914
|
+
const optimizer = input.optimizer ?? "GEPA";
|
|
915
|
+
const lane = `${optimizer.toLowerCase()}-evaluation-callback`;
|
|
916
|
+
const reps = /* @__PURE__ */ new Map();
|
|
917
|
+
const recordedCells = /* @__PURE__ */ new Set();
|
|
918
|
+
const unrecorded = [];
|
|
919
|
+
let cells = 0;
|
|
920
|
+
let reusedRequests = 0;
|
|
921
|
+
for (const observation of input.observations.observations) {
|
|
922
|
+
if (!(observation.kind === "evaluation" || observation.kind === "refusal" && observation.reason === "evaluation-failed") || observation.candidate === void 0 || observation.exampleId === void 0) continue;
|
|
923
|
+
const candidateHash = observation.candidateHash;
|
|
924
|
+
const exampleId = observation.exampleId;
|
|
925
|
+
const surface = externalSurface(observation.candidate);
|
|
926
|
+
const registered = await recorder.registerNode(surfaceNode(recorder, surface));
|
|
927
|
+
if (((await recorder.state()).node(registered.nodeId)?.edgeIds.length ?? 0) === 0) {
|
|
928
|
+
await recorder.recordEdge({
|
|
929
|
+
childNodeId: registered.nodeId,
|
|
930
|
+
parents: [],
|
|
931
|
+
operator: "improve",
|
|
932
|
+
attribution: "unknown",
|
|
933
|
+
proposer: input.proposer,
|
|
934
|
+
proposalKey: `${optimizer.toLowerCase()}-evaluated:${candidateHash}`,
|
|
935
|
+
rationale: noRationale(optimizer),
|
|
936
|
+
diffs: [],
|
|
937
|
+
label: optimizer === "GEPA" ? "GEPA proposal outside its population" : `${optimizer} proposal without a parent record`
|
|
938
|
+
});
|
|
939
|
+
unrecorded.push(registered.nodeId);
|
|
911
940
|
}
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
}),
|
|
928
|
-
optimizerLedger: createRunCostLedger({
|
|
929
|
-
storage,
|
|
930
|
-
runDir: `${stateDir}/cost`,
|
|
931
|
-
costCeilingUsd: snapshot.maxOptimizerCostUsd
|
|
932
|
-
})
|
|
933
|
-
};
|
|
934
|
-
}
|
|
935
|
-
/** Optimizer paid calls, charged to the optimizer's own limit and mirrored into the method's account. */
|
|
936
|
-
function createOptimizerCostMeter(run, accounts, controller) {
|
|
937
|
-
const { snapshot, input } = run;
|
|
938
|
-
const { runBudget, optimizerLedger } = accounts;
|
|
939
|
-
return Object.freeze({ async runPaidCall(request) {
|
|
940
|
-
const call = {
|
|
941
|
-
methodResult: void 0,
|
|
942
|
-
providerStarted: false
|
|
941
|
+
const split = input.splitOf(exampleId);
|
|
942
|
+
const { measurement } = observation;
|
|
943
|
+
const refused = observation.kind === "refusal";
|
|
944
|
+
const allocate = async () => {
|
|
945
|
+
const repKey = `${registered.nodeId}\u0000${exampleId}`;
|
|
946
|
+
const rep = reps.get(repKey) ?? 0;
|
|
947
|
+
reps.set(repKey, rep + 1);
|
|
948
|
+
return recorder.allocateCell({
|
|
949
|
+
nodeId: registered.nodeId,
|
|
950
|
+
taskId: exampleId,
|
|
951
|
+
split,
|
|
952
|
+
rep,
|
|
953
|
+
stage: "external",
|
|
954
|
+
...measurement === void 0 ? {} : { lane }
|
|
955
|
+
});
|
|
943
956
|
};
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
...request,
|
|
953
|
-
callId,
|
|
954
|
-
channel: request.channel ?? "optimizer",
|
|
955
|
-
phase: OPTIMIZER_COST_PHASE,
|
|
956
|
-
tags: runBudget.attemptTags,
|
|
957
|
-
signal,
|
|
958
|
-
execute: (methodSignal, methodCallId) => {
|
|
959
|
-
call.providerStarted = true;
|
|
960
|
-
return request.execute(methodSignal, methodCallId);
|
|
961
|
-
}
|
|
957
|
+
if (measurement !== void 0) {
|
|
958
|
+
if (measurement.source === "reused") reusedRequests += 1;
|
|
959
|
+
for (const cell of measurement.cells) {
|
|
960
|
+
const key = hashCanonical({
|
|
961
|
+
candidateHash,
|
|
962
|
+
exampleId,
|
|
963
|
+
cellId: cell.cellId,
|
|
964
|
+
attempt: cell.attempt
|
|
962
965
|
});
|
|
963
|
-
if (
|
|
964
|
-
|
|
966
|
+
if (recordedCells.has(key)) continue;
|
|
967
|
+
recordedCells.add(key);
|
|
968
|
+
const result = campaignCellSearchResult(cell, {
|
|
969
|
+
execution: input.identity,
|
|
970
|
+
lane
|
|
971
|
+
});
|
|
972
|
+
await recorder.settleCell({
|
|
973
|
+
cellId: await allocate(),
|
|
974
|
+
attempt: 1,
|
|
975
|
+
...result,
|
|
976
|
+
...refused ? { outcome: refusedAfterMeasurement(result.outcome) } : {}
|
|
977
|
+
});
|
|
978
|
+
cells += 1;
|
|
979
|
+
}
|
|
980
|
+
continue;
|
|
981
|
+
}
|
|
982
|
+
await recorder.settleCell({
|
|
983
|
+
cellId: await allocate(),
|
|
984
|
+
attempt: 1,
|
|
985
|
+
outcome: observation.kind === "evaluation" ? evaluationOutcome(observation.response) : {
|
|
986
|
+
status: "errored",
|
|
987
|
+
metrics: {},
|
|
988
|
+
error: {
|
|
989
|
+
code: "evaluation-failed",
|
|
990
|
+
message: "the evaluation callback failed before a score",
|
|
991
|
+
retryable: false
|
|
992
|
+
}
|
|
965
993
|
},
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
994
|
+
accounting: {
|
|
995
|
+
tokens: {
|
|
996
|
+
status: "unknown",
|
|
997
|
+
reason: "the evaluation callback meters tokens per run"
|
|
998
|
+
},
|
|
999
|
+
cost: {
|
|
1000
|
+
status: "unknown",
|
|
1001
|
+
knownLowerBoundUsd: 0,
|
|
1002
|
+
reason: "the evaluation callback meters cost per run, not per evaluation"
|
|
1003
|
+
}
|
|
969
1004
|
},
|
|
970
|
-
|
|
971
|
-
if (call.methodResult?.receipt) return mirroredCostReceipt(call.methodResult.receipt);
|
|
972
|
-
if (!call.providerStarted) return noChargeReceipt(modelBeforeExecution(request));
|
|
973
|
-
}
|
|
1005
|
+
identity: input.identity
|
|
974
1006
|
});
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
const { snapshot, input, runId, stateDir, artifactDir } = run;
|
|
983
|
-
const { runBudget } = accounts;
|
|
984
|
-
const scenarioById = mapExternalScenarios(input.trainScenarios, input.selectionScenarios, `${snapshot.name} optimizer`);
|
|
985
|
-
const score = createExternalTextEvaluator({
|
|
986
|
-
input,
|
|
987
|
-
label: `${snapshot.name} optimizer`,
|
|
988
|
-
runDir: artifactDir,
|
|
989
|
-
compatibleRunId: runId,
|
|
990
|
-
costPhase: EVALUATION_COST_PHASE,
|
|
991
|
-
costTags: runBudget.attemptTags,
|
|
992
|
-
costLedger: input.costLedger,
|
|
993
|
-
scenarioById,
|
|
994
|
-
maxCandidateChars: run.maxCandidateChars,
|
|
995
|
-
maxEvidenceChars: run.maxEvidenceChars,
|
|
996
|
-
describeArtifact: snapshot.describeArtifact
|
|
997
|
-
});
|
|
998
|
-
const controller = new AbortController();
|
|
999
|
-
const activeEvaluations = /* @__PURE__ */ new Set();
|
|
1000
|
-
const state = {
|
|
1001
|
-
acceptingEvaluations: true,
|
|
1002
|
-
runSettled: false
|
|
1007
|
+
cells += 1;
|
|
1008
|
+
}
|
|
1009
|
+
return {
|
|
1010
|
+
cells,
|
|
1011
|
+
measuredCells: recordedCells.size,
|
|
1012
|
+
reusedRequests,
|
|
1013
|
+
unrecordedParentNodeIds: unrecorded
|
|
1003
1014
|
};
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1015
|
+
}
|
|
1016
|
+
/**
|
|
1017
|
+
* A cell the callback measured and then refused to return to the optimizer,
|
|
1018
|
+
* for example because its evidence did not fit the bound. Its accounting and
|
|
1019
|
+
* metrics are the measurement's, since the spend was real; it is unscored,
|
|
1020
|
+
* because the optimizer received no score, and the error names what the
|
|
1021
|
+
* measurement found.
|
|
1022
|
+
*/
|
|
1023
|
+
function refusedAfterMeasurement(measured) {
|
|
1024
|
+
const found = measured.status === "errored" ? `an unscored cell (${measured.error.code}: ${measured.error.message})` : `a ${measured.status} cell scoring ${measured.score}`;
|
|
1025
|
+
return {
|
|
1026
|
+
status: "errored",
|
|
1027
|
+
metrics: measured.metrics,
|
|
1028
|
+
error: {
|
|
1029
|
+
code: "evaluation-refused",
|
|
1030
|
+
message: `the evaluation callback refused the evaluation after measuring ${found}; the optimizer received no score`,
|
|
1031
|
+
retryable: false
|
|
1032
|
+
}
|
|
1014
1033
|
};
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
seedCandidate: cloneExternalTextCandidate(run.seedCandidate),
|
|
1025
|
-
trainSet: run.trainSet,
|
|
1026
|
-
selectionSet: run.selectionSet,
|
|
1027
|
-
maxEvaluations: snapshot.maxEvaluations,
|
|
1028
|
-
seed: input.seed,
|
|
1029
|
-
stateDir,
|
|
1030
|
-
restoreRequested,
|
|
1031
|
-
artifactDir,
|
|
1032
|
-
signal: controller.signal,
|
|
1033
|
-
cost: optimizerCostMeter,
|
|
1034
|
-
evaluate
|
|
1035
|
-
})));
|
|
1036
|
-
const markSettled = () => {
|
|
1037
|
-
state.runSettled = true;
|
|
1034
|
+
}
|
|
1035
|
+
/** GEPA's callback response. A `failed` evaluation carries a penalty score for
|
|
1036
|
+
* the optimizer that is not a measurement, so the cell is unscored. */
|
|
1037
|
+
function evaluationOutcome(response) {
|
|
1038
|
+
const record = response ?? {};
|
|
1039
|
+
if (record.info?.status === "scored" && typeof record.score === "number" && Number.isFinite(record.score)) return {
|
|
1040
|
+
status: "passed",
|
|
1041
|
+
score: record.score,
|
|
1042
|
+
metrics: { score: record.score }
|
|
1038
1043
|
};
|
|
1039
|
-
runPromise.then(markSettled, markSettled);
|
|
1040
1044
|
return {
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1045
|
+
status: "errored",
|
|
1046
|
+
metrics: {},
|
|
1047
|
+
error: {
|
|
1048
|
+
code: "evaluation-failed",
|
|
1049
|
+
message: typeof record.info?.notes === "string" && record.info.notes.trim().length > 0 ? record.info.notes.trim() : "the evaluation produced no score",
|
|
1050
|
+
retryable: false
|
|
1051
|
+
}
|
|
1047
1052
|
};
|
|
1048
1053
|
}
|
|
1049
|
-
/**
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
let runError;
|
|
1055
|
-
let outstandingAtCompletion = 0;
|
|
1056
|
-
let paidCallsAtCompletion = 0;
|
|
1057
|
-
try {
|
|
1058
|
-
result = await raceWithAbort(session.runPromise, session.controller.signal);
|
|
1059
|
-
outstandingAtCompletion = session.activeEvaluations.size;
|
|
1060
|
-
paidCallsAtCompletion = optimizerLedger.summary().pendingCalls;
|
|
1061
|
-
} catch (error) {
|
|
1062
|
-
runError = error;
|
|
1063
|
-
} finally {
|
|
1064
|
-
session.state.acceptingEvaluations = false;
|
|
1065
|
-
clearTimeout(session.timeout);
|
|
1066
|
-
}
|
|
1067
|
-
await Promise.allSettled([...session.activeEvaluations]);
|
|
1068
|
-
const paidCallsSettled = await optimizerLedger.waitForIdle({ timeoutMs: 5e3 });
|
|
1069
|
-
const handOffLock = () => {
|
|
1070
|
-
if (!lock) return;
|
|
1071
|
-
run.releaseLock = false;
|
|
1072
|
-
Promise.allSettled([session.runPromise, optimizerLedger.waitForIdle({ timeoutMs: MAX_TIMER_DELAY_MS$2 })]).then(() => lock.release());
|
|
1054
|
+
/** An optimizer candidate as the mutable surface it represents. */
|
|
1055
|
+
function externalSurface(candidate) {
|
|
1056
|
+
return typeof candidate === "string" ? candidate : {
|
|
1057
|
+
kind: "components",
|
|
1058
|
+
components: candidate
|
|
1073
1059
|
};
|
|
1074
|
-
if (runError !== void 0) {
|
|
1075
|
-
if (!session.state.runSettled || !paidCallsSettled) handOffLock();
|
|
1076
|
-
throw runError;
|
|
1077
|
-
}
|
|
1078
|
-
if (!paidCallsSettled) {
|
|
1079
|
-
handOffLock();
|
|
1080
|
-
throw new Error(`${snapshot.name}: optimizer paid calls did not settle`);
|
|
1081
|
-
}
|
|
1082
|
-
if (paidCallsAtCompletion > 0) throw new Error(`${snapshot.name}: run() completed with ${paidCallsAtCompletion} outstanding paid call(s); await every context.cost.runPaidCall()`);
|
|
1083
|
-
if (outstandingAtCompletion > 0) throw new Error(`${snapshot.name}: run() completed with ${outstandingAtCompletion} outstanding evaluation(s); await every evaluate() call`);
|
|
1084
|
-
assertExternalTextOptimizerResult(result, snapshot.name, run.maxCandidateChars, run.expectsComponents);
|
|
1085
|
-
if (result.resumed !== restoreRequested) throw new Error(`${snapshot.name}: optimizer reported resumed=${String(result.resumed)} but restoreRequested=${String(restoreRequested)}`);
|
|
1086
|
-
return result;
|
|
1087
1060
|
}
|
|
1088
|
-
/**
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1061
|
+
/**
|
|
1062
|
+
* Write GEPA's finished search into its ledger: the baseline as the seeded
|
|
1063
|
+
* root, the population as nodes with `correlated` edges, every callback
|
|
1064
|
+
* evaluation as an `external` cell, GEPA's proposer spend as one operation,
|
|
1065
|
+
* GEPA's choice as the selected node, and the close. GEPA's own selection is a
|
|
1066
|
+
* budget decision, so the ledger carries no claim; the final comparison runs
|
|
1067
|
+
* outside this search.
|
|
1068
|
+
*
|
|
1069
|
+
* A composed recipe reports no population: pass `population: null` and GEPA's
|
|
1070
|
+
* returned best as `selected`, and every evaluated candidate enters with an
|
|
1071
|
+
* `unknown` edge, as SkillOpt's do.
|
|
1072
|
+
*/
|
|
1073
|
+
async function recordGepaSearch(input) {
|
|
1074
|
+
if (input.population === null) return recordExternalSearch({
|
|
1075
|
+
...input,
|
|
1076
|
+
optimizer: "GEPA"
|
|
1077
|
+
});
|
|
1078
|
+
const { population } = input;
|
|
1079
|
+
const best = population.candidates.find((candidate) => candidate.index === population.bestIndex);
|
|
1080
|
+
if (!best) throw new Error(`GEPA candidate population has no bestIndex entry ${population.bestIndex}`);
|
|
1081
|
+
return recordExternalSearch({
|
|
1082
|
+
...input,
|
|
1083
|
+
population,
|
|
1084
|
+
optimizer: "GEPA",
|
|
1085
|
+
selected: externalSurface(best.candidate)
|
|
1086
|
+
});
|
|
1087
|
+
}
|
|
1088
|
+
/**
|
|
1089
|
+
* Write SkillOpt's finished search into its ledger: the baseline as the seeded
|
|
1090
|
+
* root, every candidate SkillOpt evaluated as a node with an `unknown` edge
|
|
1091
|
+
* (SkillOpt reports no parents), every callback evaluation as an `external`
|
|
1092
|
+
* cell, SkillOpt's optimizer spend as one operation, SkillOpt's choice as the
|
|
1093
|
+
* selected node, and the close. Like GEPA's, the ledger carries no claim.
|
|
1094
|
+
*/
|
|
1095
|
+
async function recordSkillOptSearch(input) {
|
|
1096
|
+
return recordExternalSearch({
|
|
1097
|
+
...input,
|
|
1098
|
+
optimizer: "SkillOpt",
|
|
1099
|
+
population: null
|
|
1100
|
+
});
|
|
1101
|
+
}
|
|
1102
|
+
async function recordExternalSearch(input) {
|
|
1103
|
+
const { identity, population, optimizer } = input;
|
|
1104
|
+
const policyName = optimizer.toLowerCase();
|
|
1105
|
+
const repsPerEvaluation = input.repsPerEvaluation ?? 1;
|
|
1106
|
+
if (!Number.isSafeInteger(repsPerEvaluation) || repsPerEvaluation <= 0) throw new Error(`${input.name}: repsPerEvaluation must be a positive safe integer`);
|
|
1107
|
+
const tasks = (scenarios) => scenarios.map((scenario) => ({
|
|
1108
|
+
taskId: scenario.id,
|
|
1109
|
+
unitId: scenario.id,
|
|
1110
|
+
source: {
|
|
1111
|
+
uri: `scenario://${scenario.id}`,
|
|
1112
|
+
revision: hashCanonical(scenario)
|
|
1113
|
+
}
|
|
1114
|
+
}));
|
|
1115
|
+
const train = tasks(input.trainScenarios);
|
|
1116
|
+
const selection = tasks(input.selectionScenarios);
|
|
1117
|
+
const taskSet = hashCanonical({
|
|
1118
|
+
train,
|
|
1119
|
+
selection
|
|
1120
|
+
});
|
|
1121
|
+
const recorder = await SearchRecorder.open({
|
|
1122
|
+
ledger: openSearchLedger({
|
|
1123
|
+
path: input.path,
|
|
1124
|
+
searchId: input.searchId
|
|
1125
|
+
}),
|
|
1126
|
+
storage: input.storage
|
|
1127
|
+
}, {
|
|
1128
|
+
subject: identity.subject ?? input.name,
|
|
1129
|
+
process: {
|
|
1130
|
+
name: input.name,
|
|
1131
|
+
executionRef: identity.search
|
|
1132
|
+
},
|
|
1133
|
+
artifactKind: "prompt",
|
|
1134
|
+
objective: {
|
|
1135
|
+
metric: "score",
|
|
1136
|
+
direction: "maximize",
|
|
1137
|
+
judge: identity.judge ?? { unknown: "the evaluation callback judges through caller functions without a pinned source" },
|
|
1138
|
+
claim: identity.claim ?? developmentClaim(taskSet)
|
|
1139
|
+
},
|
|
1140
|
+
splits: {
|
|
1141
|
+
train,
|
|
1142
|
+
selection,
|
|
1143
|
+
test: [],
|
|
1144
|
+
heldOutUnits: true
|
|
1145
|
+
},
|
|
1146
|
+
policy: {
|
|
1147
|
+
expansion: policyName,
|
|
1148
|
+
allocation: policyName,
|
|
1149
|
+
seed: input.seed
|
|
1150
|
+
},
|
|
1151
|
+
budget: {
|
|
1152
|
+
maxUsd: null,
|
|
1153
|
+
maxCells: input.evaluationLimit * repsPerEvaluation,
|
|
1154
|
+
maxNodes: null,
|
|
1155
|
+
deadline: null,
|
|
1156
|
+
maxConcurrency: null,
|
|
1157
|
+
reservedClaimUsd: 0
|
|
1158
|
+
},
|
|
1159
|
+
containment: null,
|
|
1160
|
+
derivedFrom: null,
|
|
1161
|
+
identity: {
|
|
1162
|
+
model: identity.model,
|
|
1163
|
+
agent: identity.agent,
|
|
1164
|
+
benchmark: {
|
|
1165
|
+
uri: `optimizer://${input.name}`,
|
|
1166
|
+
revision: taskSet
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
});
|
|
1170
|
+
const root = await recorder.registerNode(surfaceNode(recorder, input.baselineSurface));
|
|
1171
|
+
await recorder.recordEdge({
|
|
1172
|
+
childNodeId: root.nodeId,
|
|
1173
|
+
parents: [],
|
|
1174
|
+
operator: "seed",
|
|
1175
|
+
attribution: "explicit",
|
|
1176
|
+
proposer: null,
|
|
1177
|
+
proposalKey: "baseline",
|
|
1178
|
+
rationale: { unknown: "the baseline is the caller-supplied starting surface" },
|
|
1179
|
+
diffs: [],
|
|
1180
|
+
label: "baseline"
|
|
1181
|
+
});
|
|
1182
|
+
const operationId = `${policyName}-proposals`;
|
|
1183
|
+
await recorder.startOperation({
|
|
1184
|
+
operationId,
|
|
1185
|
+
operationKind: "candidate-generation"
|
|
1186
|
+
});
|
|
1187
|
+
const proposer = {
|
|
1188
|
+
kind: "optimizer",
|
|
1189
|
+
name: input.name,
|
|
1190
|
+
operationId,
|
|
1191
|
+
source: identity.proposer.source
|
|
1192
|
+
};
|
|
1193
|
+
if (population) await importGepaPopulation({
|
|
1194
|
+
recorder,
|
|
1195
|
+
population,
|
|
1196
|
+
proposer
|
|
1197
|
+
});
|
|
1198
|
+
const trainIds = new Set(train.map((task) => task.taskId));
|
|
1199
|
+
const evaluations = await importExternalEvaluations({
|
|
1200
|
+
recorder,
|
|
1201
|
+
observations: input.observations,
|
|
1202
|
+
proposer,
|
|
1203
|
+
identity: {
|
|
1204
|
+
model: identity.model,
|
|
1205
|
+
agent: identity.agent,
|
|
1206
|
+
benchmark: {
|
|
1207
|
+
uri: `optimizer://${input.name}`,
|
|
1208
|
+
revision: taskSet
|
|
1209
|
+
}
|
|
1210
|
+
},
|
|
1211
|
+
splitOf: (exampleId) => trainIds.has(exampleId) ? "train" : "selection",
|
|
1212
|
+
optimizer
|
|
1213
|
+
});
|
|
1214
|
+
const chosen = await recorder.registerNode(surfaceNode(recorder, input.selected));
|
|
1215
|
+
if (((await recorder.state()).node(chosen.nodeId)?.edgeIds.length ?? 0) === 0) await recorder.recordEdge({
|
|
1216
|
+
childNodeId: chosen.nodeId,
|
|
1217
|
+
parents: [],
|
|
1218
|
+
operator: "improve",
|
|
1219
|
+
attribution: "unknown",
|
|
1220
|
+
proposer,
|
|
1221
|
+
proposalKey: `${policyName}-selected`,
|
|
1222
|
+
rationale: noRationale(optimizer),
|
|
1223
|
+
diffs: [],
|
|
1224
|
+
label: `${optimizer} choice without an evaluation`
|
|
1225
|
+
});
|
|
1226
|
+
await recorder.recordOperation({
|
|
1227
|
+
operationId,
|
|
1228
|
+
operationKind: "candidate-generation",
|
|
1229
|
+
execution: identity.proposer,
|
|
1230
|
+
outcome: { status: "completed" },
|
|
1231
|
+
accounting: input.generationAccounting
|
|
1232
|
+
});
|
|
1233
|
+
const state = await recorder.state();
|
|
1234
|
+
const nodes = state.nodes();
|
|
1235
|
+
const best = chosen.nodeId;
|
|
1236
|
+
const bestScored = state.cells({ nodeId: best }).some((cell) => cell.score !== null);
|
|
1237
|
+
const rule = population ? "gepa-best-aggregate" : `${policyName}-choice`;
|
|
1238
|
+
const basis = population ? "its aggregate selection score" : "its own validation";
|
|
1239
|
+
for (const node of nodes) if (node.nodeId === best && bestScored) await recorder.decideNode({
|
|
1240
|
+
nodeId: node.nodeId,
|
|
1241
|
+
decision: { status: "selected" },
|
|
1242
|
+
rule,
|
|
1243
|
+
reason: `${optimizer} chose this candidate by ${basis}`
|
|
1244
|
+
});
|
|
1245
|
+
else if (population && evaluations.unrecordedParentNodeIds.includes(node.nodeId)) await recorder.decideNode({
|
|
1246
|
+
nodeId: node.nodeId,
|
|
1247
|
+
decision: { status: "pruned" },
|
|
1248
|
+
rule: "gepa-population",
|
|
1249
|
+
reason: "GEPA evaluated the candidate and kept it out of its population"
|
|
1250
|
+
});
|
|
1251
|
+
else await recorder.decideNode({
|
|
1252
|
+
nodeId: node.nodeId,
|
|
1253
|
+
decision: node.nodeId === best ? { status: "invalid" } : { status: "rejected" },
|
|
1254
|
+
rule,
|
|
1255
|
+
reason: node.nodeId === best ? `${optimizer} chose this candidate, but no evaluation of it was scored` : `${optimizer} chose another candidate`
|
|
1256
|
+
});
|
|
1257
|
+
await recorder.close({
|
|
1258
|
+
reason: "budget",
|
|
1259
|
+
claim: null
|
|
1260
|
+
});
|
|
1261
|
+
return recorder.receipt({
|
|
1262
|
+
producerId: input.name,
|
|
1263
|
+
runId: input.searchId
|
|
1264
|
+
});
|
|
1265
|
+
}
|
|
1266
|
+
// src/campaign/external-text-optimization.ts
|
|
1267
|
+
const DEFAULT_MAX_CANDIDATE_CHARS = 2e5;
|
|
1268
|
+
const DEFAULT_MAX_EVIDENCE_CHARS = 1e5;
|
|
1269
|
+
const DEFAULT_TIMEOUT_MS = 18e5;
|
|
1270
|
+
const MAX_TIMER_DELAY_MS$2 = 2147483647;
|
|
1271
|
+
/**
|
|
1272
|
+
* Adapt a third-party text optimizer without reimplementing its search.
|
|
1273
|
+
*
|
|
1274
|
+
* The callback never receives final test cases. Calls to `evaluate` are
|
|
1275
|
+
* counted before execution and stop at `maxEvaluations`.
|
|
1276
|
+
*/
|
|
1277
|
+
function externalTextOptimizationMethod(config) {
|
|
1278
|
+
assertExternalTextOptimizationConfig(config);
|
|
1279
|
+
const snapshot = snapshotExternalTextOptimizationConfig(config);
|
|
1280
|
+
return {
|
|
1281
|
+
name: snapshot.name,
|
|
1282
|
+
optimize: (input) => optimizeExternalText(snapshot, input)
|
|
1283
|
+
};
|
|
1284
|
+
}
|
|
1285
|
+
const EVALUATION_COST_PHASE = "external.evaluation";
|
|
1286
|
+
const OPTIMIZER_COST_PHASE = "external.optimizer";
|
|
1287
|
+
async function optimizeExternalText(snapshot, input) {
|
|
1288
|
+
const run = await prepareExternalRun(snapshot, input);
|
|
1289
|
+
try {
|
|
1290
|
+
const { manifest, restoreRequested } = restoreRunManifest(run);
|
|
1291
|
+
const accounts = openRunAccounts(run);
|
|
1292
|
+
const session = startOptimizerSession(run, accounts, restoreRequested);
|
|
1293
|
+
return await finishRun(run, accounts, session, manifest, await awaitOptimizerResult(run, accounts, session, restoreRequested));
|
|
1294
|
+
} finally {
|
|
1295
|
+
if (run.releaseLock) run.lock?.release();
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
function describeExternalScenarios(scenarios, snapshot, maxEvidenceChars) {
|
|
1299
|
+
return Object.freeze(scenarios.map((scenario) => describeExternalScenario(scenario, snapshot.name, maxEvidenceChars, snapshot.describeScenario)));
|
|
1300
|
+
}
|
|
1301
|
+
/** Run identity, scenario descriptions and directories, then the resume lock. */
|
|
1302
|
+
async function prepareExternalRun(snapshot, input) {
|
|
1303
|
+
const seedCandidate = encodeExternalTextCandidate(input.baselineSurface);
|
|
1304
|
+
const maxCandidateChars = snapshot.maxCandidateChars ?? DEFAULT_MAX_CANDIDATE_CHARS;
|
|
1305
|
+
const maxEvidenceChars = snapshot.maxEvidenceChars ?? DEFAULT_MAX_EVIDENCE_CHARS;
|
|
1306
|
+
const attemptId = randomBytes(16).toString("hex");
|
|
1307
|
+
const storage = input.runOptions.storage ?? fsCampaignStorage();
|
|
1308
|
+
const resume = snapshot.resume ?? "never";
|
|
1309
|
+
const trainSet = describeExternalScenarios(input.trainScenarios, snapshot, maxEvidenceChars);
|
|
1310
|
+
const selectionSet = describeExternalScenarios(input.selectionScenarios, snapshot, maxEvidenceChars);
|
|
1311
|
+
const methodDir = `${input.runDir}/external/${safePathComponent(snapshot.name)}`;
|
|
1312
|
+
const runId = externalOptimizerRunKey({
|
|
1313
|
+
material: {
|
|
1314
|
+
optimizer: {
|
|
1315
|
+
kind: snapshot.source.kind,
|
|
1316
|
+
package: snapshot.source.package,
|
|
1317
|
+
version: snapshot.source.version,
|
|
1318
|
+
...snapshot.source.sourceUrl ? { sourceUrl: snapshot.source.sourceUrl } : {},
|
|
1319
|
+
...snapshot.source.revision ? { revision: snapshot.source.revision } : {}
|
|
1320
|
+
},
|
|
1321
|
+
method: snapshot.name,
|
|
1322
|
+
evaluationId: snapshot.evaluationId,
|
|
1323
|
+
dispatchRef: input.runOptions.dispatchRef ?? null,
|
|
1324
|
+
objective: snapshot.objective,
|
|
1325
|
+
background: snapshot.background ?? "",
|
|
1326
|
+
seed: input.seed,
|
|
1327
|
+
seedCandidate,
|
|
1328
|
+
trainSet,
|
|
1329
|
+
selectionSet,
|
|
1330
|
+
maxEvaluations: snapshot.maxEvaluations,
|
|
1331
|
+
maxOptimizerCostUsd: snapshot.maxOptimizerCostUsd,
|
|
1332
|
+
maxCandidateChars,
|
|
1333
|
+
maxEvidenceChars,
|
|
1334
|
+
...snapshot.searchLedger ? { searchLedger: snapshot.searchLedger.identity } : {}
|
|
1335
|
+
},
|
|
1336
|
+
attemptId,
|
|
1337
|
+
resumeEnabled: resume !== "never"
|
|
1338
|
+
});
|
|
1339
|
+
const stateDir = `${methodDir}/state/${runId}`;
|
|
1340
|
+
const artifactDir = `${methodDir}/attempts/${attemptId}`;
|
|
1341
|
+
storage.ensureDir(stateDir);
|
|
1342
|
+
storage.ensureDir(artifactDir);
|
|
1343
|
+
if (resume !== "never") await mkdir(stateDir, { recursive: true });
|
|
1344
|
+
const lock = resume === "never" ? void 0 : acquireSingleRunLock({
|
|
1345
|
+
lockPath: `${stateDir}.lock`,
|
|
1346
|
+
releaseOnExit: true
|
|
1347
|
+
});
|
|
1348
|
+
return {
|
|
1349
|
+
snapshot,
|
|
1350
|
+
input,
|
|
1351
|
+
seedCandidate,
|
|
1352
|
+
expectsComponents: typeof seedCandidate !== "string",
|
|
1353
|
+
maxCandidateChars,
|
|
1354
|
+
maxEvidenceChars,
|
|
1355
|
+
attemptId,
|
|
1356
|
+
storage,
|
|
1357
|
+
resume,
|
|
1358
|
+
trainSet,
|
|
1359
|
+
selectionSet,
|
|
1360
|
+
methodDir,
|
|
1361
|
+
runId,
|
|
1362
|
+
stateDir,
|
|
1363
|
+
artifactDir,
|
|
1364
|
+
manifestPath: `${stateDir}/run-manifest.jsonl`,
|
|
1365
|
+
lock,
|
|
1366
|
+
releaseLock: true
|
|
1367
|
+
};
|
|
1368
|
+
}
|
|
1369
|
+
/** Reads prior state when resuming, and records this attempt as partial. */
|
|
1370
|
+
function restoreRunManifest(run) {
|
|
1371
|
+
const { snapshot, storage, manifestPath, runId, attemptId, resume } = run;
|
|
1372
|
+
let manifest = resume === "never" ? void 0 : readExternalOptimizerRunManifest(storage.read(manifestPath), storage.exists(manifestPath), manifestPath, runId);
|
|
1373
|
+
const restoreRequested = manifest !== void 0;
|
|
1374
|
+
if (resume === "required" && !restoreRequested) throw new Error(`${snapshot.name}: no compatible run state is available to resume`);
|
|
1375
|
+
if (resume === "never" && restoreRequested) throw new Error(`${snapshot.name}: fresh optimizer run unexpectedly found prior state`);
|
|
1376
|
+
if (resume !== "never") manifest = appendExternalOptimizerRunManifestEvent({
|
|
1377
|
+
storage,
|
|
1378
|
+
path: manifestPath,
|
|
1379
|
+
revision: manifest?.revision ?? 0,
|
|
1380
|
+
event: {
|
|
1381
|
+
runId,
|
|
1382
|
+
attemptId,
|
|
1383
|
+
status: "partial"
|
|
1384
|
+
}
|
|
1385
|
+
});
|
|
1386
|
+
return {
|
|
1387
|
+
manifest,
|
|
1388
|
+
restoreRequested
|
|
1389
|
+
};
|
|
1390
|
+
}
|
|
1391
|
+
function openRunAccounts(run) {
|
|
1392
|
+
const { snapshot, storage, methodDir, runId, attemptId, stateDir } = run;
|
|
1393
|
+
return {
|
|
1394
|
+
runBudget: openExternalOptimizerRunBudget({
|
|
1395
|
+
storage,
|
|
1396
|
+
runDir: methodDir,
|
|
1397
|
+
runKey: runId,
|
|
1398
|
+
attemptId,
|
|
1399
|
+
maxEvaluations: snapshot.maxEvaluations
|
|
1400
|
+
}),
|
|
1401
|
+
optimizerLedger: createRunCostLedger({
|
|
1402
|
+
storage,
|
|
1403
|
+
runDir: `${stateDir}/cost`,
|
|
1404
|
+
costCeilingUsd: snapshot.maxOptimizerCostUsd
|
|
1405
|
+
})
|
|
1406
|
+
};
|
|
1407
|
+
}
|
|
1408
|
+
/** Optimizer paid calls, charged to the optimizer's own limit and mirrored into the method's account. */
|
|
1409
|
+
function createOptimizerCostMeter(run, accounts, controller) {
|
|
1410
|
+
const { snapshot, input } = run;
|
|
1411
|
+
const { runBudget, optimizerLedger } = accounts;
|
|
1412
|
+
return Object.freeze({ async runPaidCall(request) {
|
|
1413
|
+
const call = {
|
|
1414
|
+
methodResult: void 0,
|
|
1415
|
+
providerStarted: false
|
|
1416
|
+
};
|
|
1417
|
+
const subLimitResult = await optimizerLedger.runPaidCall({
|
|
1418
|
+
...request,
|
|
1419
|
+
channel: request.channel ?? "optimizer",
|
|
1420
|
+
phase: OPTIMIZER_COST_PHASE,
|
|
1421
|
+
tags: runBudget.attemptTags,
|
|
1422
|
+
signal: request.signal ? AbortSignal.any([controller.signal, request.signal]) : controller.signal,
|
|
1423
|
+
execute: async (signal, callId) => {
|
|
1424
|
+
call.methodResult = await input.costLedger.runPaidCall({
|
|
1425
|
+
...request,
|
|
1426
|
+
callId,
|
|
1427
|
+
channel: request.channel ?? "optimizer",
|
|
1428
|
+
phase: OPTIMIZER_COST_PHASE,
|
|
1429
|
+
tags: runBudget.attemptTags,
|
|
1430
|
+
signal,
|
|
1431
|
+
execute: (methodSignal, methodCallId) => {
|
|
1432
|
+
call.providerStarted = true;
|
|
1433
|
+
return request.execute(methodSignal, methodCallId);
|
|
1434
|
+
}
|
|
1435
|
+
});
|
|
1436
|
+
if (!call.methodResult.succeeded) throw new Error(`${snapshot.name}: method cost account rejected optimizer call`, { cause: call.methodResult.error });
|
|
1437
|
+
return call.methodResult.value;
|
|
1438
|
+
},
|
|
1439
|
+
receipt: () => {
|
|
1440
|
+
if (!call.methodResult?.succeeded) throw new Error(`${snapshot.name}: optimizer call completed without a receipt`);
|
|
1441
|
+
return mirroredCostReceipt(call.methodResult.receipt);
|
|
1442
|
+
},
|
|
1443
|
+
receiptFromError: () => {
|
|
1444
|
+
if (call.methodResult?.receipt) return mirroredCostReceipt(call.methodResult.receipt);
|
|
1445
|
+
if (!call.providerStarted) return noChargeReceipt(modelBeforeExecution(request));
|
|
1446
|
+
}
|
|
1447
|
+
});
|
|
1448
|
+
if (call.methodResult === void 0) return subLimitResult;
|
|
1449
|
+
if (!call.methodResult.succeeded) return call.methodResult;
|
|
1450
|
+
return subLimitResult.succeeded ? call.methodResult : subLimitResult;
|
|
1451
|
+
} });
|
|
1452
|
+
}
|
|
1453
|
+
/** Starts the optimizer with its evaluator, cost meter, timeout and frozen context. */
|
|
1454
|
+
function startOptimizerSession(run, accounts, restoreRequested) {
|
|
1455
|
+
const { snapshot, input, runId, stateDir, artifactDir } = run;
|
|
1456
|
+
const { runBudget } = accounts;
|
|
1457
|
+
const scenarioById = mapExternalScenarios(input.trainScenarios, input.selectionScenarios, `${snapshot.name} optimizer`);
|
|
1458
|
+
const score = createExternalTextEvaluator({
|
|
1459
|
+
input,
|
|
1460
|
+
label: `${snapshot.name} optimizer`,
|
|
1461
|
+
runDir: artifactDir,
|
|
1462
|
+
compatibleRunId: runId,
|
|
1463
|
+
costPhase: EVALUATION_COST_PHASE,
|
|
1464
|
+
costTags: runBudget.attemptTags,
|
|
1465
|
+
costLedger: input.costLedger,
|
|
1466
|
+
scenarioById,
|
|
1467
|
+
maxCandidateChars: run.maxCandidateChars,
|
|
1468
|
+
maxEvidenceChars: run.maxEvidenceChars,
|
|
1469
|
+
describeArtifact: snapshot.describeArtifact
|
|
1470
|
+
});
|
|
1471
|
+
const controller = new AbortController();
|
|
1472
|
+
const activeEvaluations = /* @__PURE__ */ new Set();
|
|
1473
|
+
const state = {
|
|
1474
|
+
acceptingEvaluations: true,
|
|
1475
|
+
runSettled: false
|
|
1476
|
+
};
|
|
1477
|
+
const optimizerCostMeter = createOptimizerCostMeter(run, accounts, controller);
|
|
1478
|
+
const evaluate = (request, signal = controller.signal, measured) => {
|
|
1479
|
+
if (!state.acceptingEvaluations) throw new Error(`${snapshot.name}: evaluate cannot be called after run() completes`);
|
|
1480
|
+
if (runBudget.acceptEvaluation() === void 0) throw new Error(`${snapshot.name}: maxEvaluations limit reached`);
|
|
1481
|
+
const combinedSignal = signal === controller.signal ? controller.signal : AbortSignal.any([controller.signal, signal]);
|
|
1482
|
+
const pending = score(cloneExternalEvaluationRequest(request), combinedSignal, measured);
|
|
1483
|
+
activeEvaluations.add(pending);
|
|
1484
|
+
const remove = () => activeEvaluations.delete(pending);
|
|
1485
|
+
pending.then(remove, remove);
|
|
1486
|
+
return pending;
|
|
1487
|
+
};
|
|
1488
|
+
const started = Date.now();
|
|
1489
|
+
const timeoutMs = snapshot.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
1490
|
+
const timeout = setTimeout(() => controller.abort(/* @__PURE__ */ new Error(`${snapshot.name}: optimizer exceeded ${timeoutMs}ms`)), timeoutMs);
|
|
1491
|
+
const runPromise = Promise.resolve().then(() => snapshot.run(Object.freeze({
|
|
1492
|
+
runId,
|
|
1493
|
+
name: snapshot.name,
|
|
1494
|
+
objective: snapshot.objective,
|
|
1495
|
+
evaluationId: snapshot.evaluationId,
|
|
1496
|
+
...snapshot.background ? { background: snapshot.background } : {},
|
|
1497
|
+
seedCandidate: cloneExternalTextCandidate(run.seedCandidate),
|
|
1498
|
+
trainSet: run.trainSet,
|
|
1499
|
+
selectionSet: run.selectionSet,
|
|
1500
|
+
maxEvaluations: snapshot.maxEvaluations,
|
|
1501
|
+
seed: input.seed,
|
|
1502
|
+
stateDir,
|
|
1503
|
+
restoreRequested,
|
|
1504
|
+
artifactDir,
|
|
1505
|
+
signal: controller.signal,
|
|
1506
|
+
cost: optimizerCostMeter,
|
|
1507
|
+
storage: run.storage,
|
|
1508
|
+
evaluate
|
|
1509
|
+
})));
|
|
1510
|
+
const markSettled = () => {
|
|
1511
|
+
state.runSettled = true;
|
|
1512
|
+
};
|
|
1513
|
+
runPromise.then(markSettled, markSettled);
|
|
1514
|
+
return {
|
|
1515
|
+
controller,
|
|
1516
|
+
activeEvaluations,
|
|
1517
|
+
runPromise,
|
|
1518
|
+
timeout,
|
|
1519
|
+
started,
|
|
1520
|
+
state
|
|
1521
|
+
};
|
|
1522
|
+
}
|
|
1523
|
+
/** Waits for the optimizer, then refuses a run that left evaluations or paid calls outstanding. */
|
|
1524
|
+
async function awaitOptimizerResult(run, accounts, session, restoreRequested) {
|
|
1525
|
+
const { snapshot, lock } = run;
|
|
1526
|
+
const { optimizerLedger } = accounts;
|
|
1527
|
+
let result;
|
|
1528
|
+
let runError;
|
|
1529
|
+
let outstandingAtCompletion = 0;
|
|
1530
|
+
let paidCallsAtCompletion = 0;
|
|
1531
|
+
try {
|
|
1532
|
+
result = await raceWithAbort(session.runPromise, session.controller.signal);
|
|
1533
|
+
outstandingAtCompletion = session.activeEvaluations.size;
|
|
1534
|
+
paidCallsAtCompletion = optimizerLedger.summary().pendingCalls;
|
|
1535
|
+
} catch (error) {
|
|
1536
|
+
runError = error;
|
|
1537
|
+
} finally {
|
|
1538
|
+
session.state.acceptingEvaluations = false;
|
|
1539
|
+
clearTimeout(session.timeout);
|
|
1540
|
+
}
|
|
1541
|
+
await Promise.allSettled([...session.activeEvaluations]);
|
|
1542
|
+
const paidCallsSettled = await optimizerLedger.waitForIdle({ timeoutMs: 5e3 });
|
|
1543
|
+
const handOffLock = () => {
|
|
1544
|
+
if (!lock) return;
|
|
1545
|
+
run.releaseLock = false;
|
|
1546
|
+
Promise.allSettled([session.runPromise, optimizerLedger.waitForIdle({ timeoutMs: MAX_TIMER_DELAY_MS$2 })]).then(() => lock.release());
|
|
1547
|
+
};
|
|
1548
|
+
if (runError !== void 0) {
|
|
1549
|
+
if (!session.state.runSettled || !paidCallsSettled) handOffLock();
|
|
1550
|
+
throw runError;
|
|
1551
|
+
}
|
|
1552
|
+
if (!paidCallsSettled) {
|
|
1553
|
+
handOffLock();
|
|
1554
|
+
throw new Error(`${snapshot.name}: optimizer paid calls did not settle`);
|
|
1555
|
+
}
|
|
1556
|
+
if (paidCallsAtCompletion > 0) throw new Error(`${snapshot.name}: run() completed with ${paidCallsAtCompletion} outstanding paid call(s); await every context.cost.runPaidCall()`);
|
|
1557
|
+
if (outstandingAtCompletion > 0) throw new Error(`${snapshot.name}: run() completed with ${outstandingAtCompletion} outstanding evaluation(s); await every evaluate() call`);
|
|
1558
|
+
assertExternalTextOptimizerResult(result, snapshot.name, run.maxCandidateChars, run.expectsComponents);
|
|
1559
|
+
if (result.resumed !== restoreRequested) throw new Error(`${snapshot.name}: optimizer reported resumed=${String(result.resumed)} but restoreRequested=${String(restoreRequested)}`);
|
|
1560
|
+
return result;
|
|
1561
|
+
}
|
|
1562
|
+
/** Measures evaluation and optimizer spend, records completion, and builds the method result. */
|
|
1563
|
+
async function finishRun(run, accounts, session, manifest, result) {
|
|
1564
|
+
const { snapshot, input, storage, runId, attemptId } = run;
|
|
1565
|
+
const { runBudget } = accounts;
|
|
1566
|
+
const evaluationCost = costFromLedgerSummary(input.costLedger.summary({
|
|
1567
|
+
phase: EVALUATION_COST_PHASE,
|
|
1568
|
+
tags: runBudget.runTags
|
|
1569
|
+
}));
|
|
1570
|
+
const optimizerFilter = {
|
|
1571
|
+
phase: OPTIMIZER_COST_PHASE,
|
|
1572
|
+
tags: runBudget.runTags
|
|
1099
1573
|
};
|
|
1100
1574
|
const optimizerReceipts = input.costLedger.list(optimizerFilter);
|
|
1101
1575
|
const optimizerSummary = input.costLedger.summary(optimizerFilter);
|
|
@@ -1103,6 +1577,50 @@ function finishRun(run, accounts, session, manifest, result) {
|
|
|
1103
1577
|
assertExternalCostAccounting(result.costAccounting, optimizerSummary.totalCalls, snapshot.name);
|
|
1104
1578
|
const externalCostReason = result.costAccounting.kind === "external" ? result.costAccounting.reason : void 0;
|
|
1105
1579
|
const tokenUsage = optimizationTokenUsageFromSummary(optimizerSummary, optimizerReceipts);
|
|
1580
|
+
const winnerSurface = decodeExternalTextCandidate(result.bestCandidate);
|
|
1581
|
+
const ledger = snapshot.searchLedger;
|
|
1582
|
+
const observed = result.observations ? readExternalOptimizerObservationArtifact({
|
|
1583
|
+
summary: result.observations,
|
|
1584
|
+
storage
|
|
1585
|
+
}) : void 0;
|
|
1586
|
+
if (ledger && !observed) throw new Error(`${snapshot.name}: optimizer omitted callback observations`);
|
|
1587
|
+
const searchHistory = ledger && observed ? await recordExternalSearch({
|
|
1588
|
+
name: snapshot.name,
|
|
1589
|
+
path: ledger.path ?? `${run.artifactDir}/search-ledger.jsonl`,
|
|
1590
|
+
searchId: runId,
|
|
1591
|
+
identity: ledger.identity,
|
|
1592
|
+
storage,
|
|
1593
|
+
seed: input.seed,
|
|
1594
|
+
baselineSurface: input.baselineSurface,
|
|
1595
|
+
trainScenarios: input.trainScenarios,
|
|
1596
|
+
selectionScenarios: input.selectionScenarios,
|
|
1597
|
+
evaluationLimit: snapshot.maxEvaluations,
|
|
1598
|
+
repsPerEvaluation: input.runOptions.reps ?? 1,
|
|
1599
|
+
observations: observed,
|
|
1600
|
+
optimizer: ledger.optimizer,
|
|
1601
|
+
population: null,
|
|
1602
|
+
selected: winnerSurface,
|
|
1603
|
+
generationAccounting: {
|
|
1604
|
+
tokens: optimizerSummary.usageComplete ? {
|
|
1605
|
+
status: "known",
|
|
1606
|
+
inputTokens: optimizerSummary.inputTokens,
|
|
1607
|
+
outputTokens: optimizerSummary.outputTokens,
|
|
1608
|
+
cachedTokens: optimizerSummary.cachedTokens
|
|
1609
|
+
} : {
|
|
1610
|
+
status: "unknown",
|
|
1611
|
+
reason: "an optimizer call reported no token usage"
|
|
1612
|
+
},
|
|
1613
|
+
cost: optimizerCost.accountingComplete && externalCostReason === void 0 ? {
|
|
1614
|
+
status: "known",
|
|
1615
|
+
usd: optimizerCost.totalCostUsd,
|
|
1616
|
+
source: "provider"
|
|
1617
|
+
} : {
|
|
1618
|
+
status: "unknown",
|
|
1619
|
+
knownLowerBoundUsd: optimizerCost.totalCostUsd,
|
|
1620
|
+
reason: externalCostReason ?? "optimizer spend incomplete"
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
}) : void 0;
|
|
1106
1624
|
if (run.resume !== "never") appendExternalOptimizerRunManifestEvent({
|
|
1107
1625
|
storage,
|
|
1108
1626
|
path: run.manifestPath,
|
|
@@ -1121,7 +1639,8 @@ function finishRun(run, accounts, session, manifest, result) {
|
|
|
1121
1639
|
cost: optimizerCost
|
|
1122
1640
|
}]);
|
|
1123
1641
|
return {
|
|
1124
|
-
winnerSurface
|
|
1642
|
+
winnerSurface,
|
|
1643
|
+
...searchHistory ? { searchHistory } : {},
|
|
1125
1644
|
cost: {
|
|
1126
1645
|
...measuredCost,
|
|
1127
1646
|
...externalCostReason ? { costProvenance: {
|
|
@@ -1141,7 +1660,13 @@ function finishRun(run, accounts, session, manifest, result) {
|
|
|
1141
1660
|
resumed: result.resumed,
|
|
1142
1661
|
evaluationCount: runBudget.acceptedEvaluations(),
|
|
1143
1662
|
artifactDir: run.artifactDir,
|
|
1144
|
-
...tokenUsage ? { tokenUsage } : {}
|
|
1663
|
+
...tokenUsage ? { tokenUsage } : {},
|
|
1664
|
+
...observed ? { observations: observed.summary } : {},
|
|
1665
|
+
...result.modelExecution ? {
|
|
1666
|
+
optimizerModel: result.modelExecution.model,
|
|
1667
|
+
optimizerCallRef: result.modelExecution.callRef,
|
|
1668
|
+
modelExecutions: result.modelExecution.log
|
|
1669
|
+
} : {}
|
|
1145
1670
|
}
|
|
1146
1671
|
};
|
|
1147
1672
|
}
|
|
@@ -1379,6 +1904,7 @@ function snapshotGepaOptimizationConfig(config) {
|
|
|
1379
1904
|
return {
|
|
1380
1905
|
...config,
|
|
1381
1906
|
recipe: structuredClone(config.recipe),
|
|
1907
|
+
...config.contrastiveEvidence ? { contrastiveEvidence: { ...config.contrastiveEvidence } } : {},
|
|
1382
1908
|
...config.engineModules ? { engineModules: [...config.engineModules] } : {},
|
|
1383
1909
|
...config.optimizer ? { optimizer: snapshotOptimizerModel(config.optimizer) } : {},
|
|
1384
1910
|
...config.evaluationCallbackLimits ? { evaluationCallbackLimits: { ...config.evaluationCallbackLimits } } : {},
|
|
@@ -1393,6 +1919,8 @@ function assertGepaOptimizationConfig(config) {
|
|
|
1393
1919
|
if (config.resume !== void 0 && config.resume !== "never" && config.resume !== "if-compatible" && config.resume !== "required") throw new Error("gepaOptimizationMethod: resume must be 'never', 'if-compatible', or 'required'");
|
|
1394
1920
|
if (config.trustResumeState !== void 0 && typeof config.trustResumeState !== "boolean") throw new Error("gepaOptimizationMethod: trustResumeState must be a boolean");
|
|
1395
1921
|
assertRecipe(config.recipe);
|
|
1922
|
+
const contrast = config.contrastiveEvidence;
|
|
1923
|
+
if (contrast !== void 0 && (!contrast || typeof contrast.judge !== "string" || !contrast.judge.trim() || contrast.judge.trim() !== contrast.judge || typeof contrast.dimension !== "string" || !contrast.dimension.trim() || contrast.dimension.trim() !== contrast.dimension || !Number.isFinite(contrast.failureAtMost) || !Number.isFinite(contrast.successAtLeast) || contrast.failureAtMost >= contrast.successAtLeast)) throw new Error("gepaOptimizationMethod: contrastiveEvidence requires a trimmed judge and dimension and strictly ordered finite thresholds");
|
|
1396
1924
|
if (config.resume !== void 0 && config.resume !== "never" && gepaRecipeSupportsResume(config.recipe) && config.trustResumeState !== true) throw new Error("gepaOptimizationMethod: resumable GEPA pickle state requires trustResumeState: true");
|
|
1397
1925
|
if (config.maxCandidateChars !== void 0 && (!Number.isSafeInteger(config.maxCandidateChars) || config.maxCandidateChars <= 0)) throw new Error("gepaOptimizationMethod: maxCandidateChars must be a positive safe integer");
|
|
1398
1926
|
if (config.maxEvidenceChars !== void 0 && (!Number.isSafeInteger(config.maxEvidenceChars) || config.maxEvidenceChars <= 0)) throw new Error("gepaOptimizationMethod: maxEvidenceChars must be a positive safe integer");
|
|
@@ -1495,628 +2023,166 @@ function assertEngineOptions(run, label) {
|
|
|
1495
2023
|
assertNoCredentialValues(run.engineConfig ?? {}, `gepaOptimizationMethod: ${label}.engineConfig`);
|
|
1496
2024
|
if (run.engine === "gepa") {
|
|
1497
2025
|
const nestedEngine = isRecord(run.engineConfig?.engine) ? run.engineConfig.engine : void 0;
|
|
1498
|
-
if (nestedEngine && Object.hasOwn(nestedEngine, "seed")) throw new Error(`gepaOptimizationMethod: ${label}.engineConfig.engine.seed conflicts with the comparison seed; the bridge forwards the run seed`);
|
|
1499
|
-
}
|
|
1500
|
-
}
|
|
1501
|
-
function assertProxiedGepaRecipe(recipe, optimizer) {
|
|
1502
|
-
for (const [index, run] of recipeEngineOptions(recipe).entries()) {
|
|
1503
|
-
if (GEPA_AGENT_CLI_ENGINES.has(run.engine)) {
|
|
1504
|
-
assertProxiedAgentCliEngine(run, index, optimizer);
|
|
1505
|
-
continue;
|
|
1506
|
-
}
|
|
1507
|
-
if (run.engine !== "gepa") throw new Error(`gepaOptimizationMethod: optimizer requires GEPA's 'gepa' engine; recipe engine ${index} is '${run.engine}'`);
|
|
1508
|
-
const reflection = isRecord(run.engineConfig?.reflection) ? run.engineConfig.reflection : void 0;
|
|
1509
|
-
if (reflection && Object.hasOwn(reflection, "reflection_lm")) throw new Error("gepaOptimizationMethod: optimizer replaces engineConfig.reflection.reflection_lm; remove the duplicate setting");
|
|
1510
|
-
const reflectionOptions = isRecord(reflection?.reflection_lm_kwargs) ? reflection.reflection_lm_kwargs : void 0;
|
|
1511
|
-
if (reflectionOptions && [
|
|
1512
|
-
"api_base",
|
|
1513
|
-
"api_key",
|
|
1514
|
-
"api_url",
|
|
1515
|
-
"base_url",
|
|
1516
|
-
"endpoint",
|
|
1517
|
-
"messages",
|
|
1518
|
-
"model",
|
|
1519
|
-
"stream"
|
|
1520
|
-
].some((key) => Object.hasOwn(reflectionOptions, key))) throw new Error("gepaOptimizationMethod: proxied reflection transport settings belong in optimizer");
|
|
1521
|
-
}
|
|
1522
|
-
}
|
|
1523
|
-
function assertProxiedAgentCliEngine(run, index, optimizer) {
|
|
1524
|
-
if (optimizer.anthropicEndpoint !== true) throw new Error(`gepaOptimizationMethod: agent engine '${run.engine}' (recipe engine ${index}) requires optimizer.anthropicEndpoint: true so the claude CLI meters through the loopback proxy`);
|
|
1525
|
-
if (run.engineConfig?.model !== optimizer.model) throw new Error(`gepaOptimizationMethod: recipe engine ${index} ('${run.engine}') must set engineConfig.model to the optimizer model '${optimizer.model}'`);
|
|
1526
|
-
if (run.engineConfig && Object.hasOwn(run.engineConfig, "max_thinking_tokens")) throw new Error(`gepaOptimizationMethod: recipe engine ${index} ('${run.engine}') cannot set engineConfig.max_thinking_tokens through the Anthropic endpoint`);
|
|
1527
|
-
}
|
|
1528
|
-
function assertParallelControls(recipe) {
|
|
1529
|
-
if (recipe.maxWorkers !== void 0) assertPositiveSafeInteger$1(recipe.maxWorkers, "recipe.maxWorkers");
|
|
1530
|
-
}
|
|
1531
|
-
function assertPositiveSafeInteger$1(value, label) {
|
|
1532
|
-
if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`gepaOptimizationMethod: ${label} must be a positive safe integer`);
|
|
1533
|
-
}
|
|
1534
|
-
function recipeEngineOptions(recipe) {
|
|
1535
|
-
if (recipe.kind === "engine") return [recipe.run];
|
|
1536
|
-
if (recipe.kind === "omni") return [...recipe.explore, recipe.continueWith];
|
|
1537
|
-
return recipe.runs;
|
|
1538
|
-
}
|
|
1539
|
-
function addEvaluationLimit(total, increment) {
|
|
1540
|
-
const next = total + increment;
|
|
1541
|
-
if (!Number.isSafeInteger(next)) throw new Error("gepaOptimizationMethod: recipe evaluation limit exceeds safe integer range");
|
|
1542
|
-
return next;
|
|
1543
|
-
}
|
|
1544
|
-
// src/campaign/external-optimizer-accounting.ts
|
|
1545
|
-
const TOKEN_USAGE_FIELDS = [
|
|
1546
|
-
"inputTokens",
|
|
1547
|
-
"outputTokens",
|
|
1548
|
-
"totalTokens",
|
|
1549
|
-
"calls"
|
|
1550
|
-
];
|
|
1551
|
-
function assertPriorExternalOptimizerUsage(summary, budget, name) {
|
|
1552
|
-
if (!summary.usageComplete || budget.maxCostUsd !== void 0 && !summary.accountingComplete) throw new Error(`${name}: cannot resume optimizer-model work with incomplete bounded usage`);
|
|
1553
|
-
if (summary.totalCalls > budget.maxRequests || budget.maxCostUsd !== void 0 && summary.totalCostUsd > budget.maxCostUsd + Number.EPSILON) throw new Error(`${name}: prior optimizer-model usage exceeds the configured budget`);
|
|
1554
|
-
}
|
|
1555
|
-
function assertExternalOptimizerTokenUsage(usage, name, optimizer) {
|
|
1556
|
-
if (usage === void 0) return;
|
|
1557
|
-
for (const field of TOKEN_USAGE_FIELDS) if (!Number.isSafeInteger(usage[field]) || usage[field] < 0) throw new Error(`${name}: ${optimizer} bridge returned invalid tokenUsage.${field}`);
|
|
1558
|
-
if (usage.totalTokens !== usage.inputTokens + usage.outputTokens) throw new Error(`${name}: ${optimizer} bridge returned inconsistent tokenUsage.totalTokens`);
|
|
1559
|
-
if (usage.requestAttempts !== void 0 && (!Number.isSafeInteger(usage.requestAttempts) || usage.requestAttempts < usage.calls)) throw new Error(`${name}: ${optimizer} bridge returned invalid tokenUsage.requestAttempts`);
|
|
1560
|
-
if (usage.refusedAttempts !== void 0 && (!Number.isSafeInteger(usage.refusedAttempts) || usage.refusedAttempts < 0 || usage.requestAttempts === void 0 || usage.refusedAttempts > usage.requestAttempts - usage.calls)) throw new Error(`${name}: ${optimizer} bridge returned invalid tokenUsage.refusedAttempts`);
|
|
1561
|
-
}
|
|
1562
|
-
function assertExternalOptimizerCompletionCount(upstream, requestAttempts, successfulCompletions, name, optimizer, refusedRequests = 0) {
|
|
1563
|
-
if (!upstream) throw new Error(`${name}: ${optimizer} did not report optimizer token usage`);
|
|
1564
|
-
if (!Number.isSafeInteger(requestAttempts) || !Number.isSafeInteger(successfulCompletions) || !Number.isSafeInteger(refusedRequests) || refusedRequests < 0 || requestAttempts < 0 || successfulCompletions < 0 || successfulCompletions > requestAttempts) throw new Error(`${name}: optimizer model proxy returned invalid request counts`);
|
|
1565
|
-
if (upstream.calls !== successfulCompletions) throw new Error(`${name}: ${optimizer} reported ${upstream.calls} successful model calls but the proxy completed ${successfulCompletions} across ${requestAttempts} attempts`);
|
|
1566
|
-
if (upstream.refusedAttempts !== void 0 && upstream.refusedAttempts !== refusedRequests) throw new Error(`${name}: ${optimizer} counted ${upstream.refusedAttempts} refused model attempts but the proxy refused ${refusedRequests}`);
|
|
1567
|
-
if (upstream.requestAttempts !== void 0 && upstream.requestAttempts !== requestAttempts + refusedRequests) throw new Error(`${name}: ${optimizer} reported ${upstream.requestAttempts} model attempts but the proxy admitted ${requestAttempts} and refused ${refusedRequests}`);
|
|
1568
|
-
}
|
|
1569
|
-
// src/campaign/external-optimizer-source.ts
|
|
1570
|
-
function assertExternalOptimizerPackageSource(value, expectedPackage, name, optimizer) {
|
|
1571
|
-
assertExternalOptimizerPackageIdentity(value, expectedPackage, name, optimizer);
|
|
1572
|
-
assertExternalOptimizerSourceDetails(value, name, optimizer);
|
|
1573
|
-
}
|
|
1574
|
-
function assertExternalOptimizerPackageIdentity(value, expectedPackage, name, optimizer) {
|
|
1575
|
-
if (!isRecord(value) || value.package !== expectedPackage || typeof value.version !== "string" || value.version.length === 0 || value.version !== value.version.trim()) throw new Error(`${name}: ${optimizer} bridge returned invalid upstream package provenance`);
|
|
1576
|
-
}
|
|
1577
|
-
function assertExternalOptimizerSourceDetails(value, name, optimizer) {
|
|
1578
|
-
if (value.sourceUrl !== void 0 && (typeof value.sourceUrl !== "string" || value.sourceUrl.length === 0 || value.sourceUrl !== value.sourceUrl.trim())) throw new Error(`${name}: ${optimizer} bridge returned an invalid upstream sourceUrl`);
|
|
1579
|
-
if (value.revision !== void 0 && (typeof value.revision !== "string" || value.revision.length === 0 || value.revision !== value.revision.trim())) throw new Error(`${name}: ${optimizer} bridge returned an invalid upstream revision`);
|
|
1580
|
-
if (value.sourceSha256 !== void 0 && (typeof value.sourceSha256 !== "string" || !/^[0-9a-f]{64}$/.test(value.sourceSha256))) throw new Error(`${name}: ${optimizer} bridge returned an invalid upstream sourceSha256`);
|
|
1581
|
-
}
|
|
1582
|
-
function observedExternalOptimizerPackageSource(value) {
|
|
1583
|
-
return {
|
|
1584
|
-
kind: "package",
|
|
1585
|
-
evidence: "observed",
|
|
1586
|
-
package: value.package,
|
|
1587
|
-
version: value.version,
|
|
1588
|
-
...value.sourceUrl ? { sourceUrl: value.sourceUrl } : {},
|
|
1589
|
-
...value.revision ? { revision: value.revision } : {},
|
|
1590
|
-
...value.sourceSha256 ? { sourceSha256: value.sourceSha256 } : {}
|
|
1591
|
-
};
|
|
1592
|
-
}
|
|
1593
|
-
// src/campaign/external-optimizer-runtime.ts
|
|
1594
|
-
async function inspectExternalOptimizerRuntime(args) {
|
|
1595
|
-
const result = await runExternalOptimizerProcess({
|
|
1596
|
-
label: `${args.label} source inspection`,
|
|
1597
|
-
tempPrefix: `agent-eval-${args.package}-inspect-`,
|
|
1598
|
-
module: args.module,
|
|
1599
|
-
input: {
|
|
1600
|
-
operation: "inspect",
|
|
1601
|
-
engineModules: [...args.engineModules ?? []]
|
|
1602
|
-
},
|
|
1603
|
-
...args.runner ? { runner: args.runner } : {},
|
|
1604
|
-
timeoutMs: args.timeoutMs,
|
|
1605
|
-
...args.signal ? { signal: args.signal } : {}
|
|
1606
|
-
});
|
|
1607
|
-
assertExternalOptimizerRuntimeIdentity(result.runtime, args.package, args.label);
|
|
1608
|
-
return result.runtime;
|
|
1609
|
-
}
|
|
1610
|
-
function observedExternalOptimizerRuntime(runtime) {
|
|
1611
|
-
return {
|
|
1612
|
-
source: observedExternalOptimizerPackageSource(runtime.optimizer),
|
|
1613
|
-
bridge: observedExternalOptimizerPackageSource(runtime.bridge),
|
|
1614
|
-
modules: runtime.engineModules.map((module) => ({ ...module })),
|
|
1615
|
-
python: { ...runtime.python }
|
|
1616
|
-
};
|
|
1617
|
-
}
|
|
1618
|
-
function assertExternalOptimizerRunBinding(args) {
|
|
1619
|
-
if (!isDeepStrictEqual(args.returnedSource, args.runtime.optimizer)) throw new Error(`${args.label}: optimizer package changed after source inspection`);
|
|
1620
|
-
if (args.returnedRunId !== args.runId) throw new Error(`${args.label}: bridge returned a different run ID`);
|
|
1621
|
-
if (args.resume === "never" && args.resumed) throw new Error(`${args.label}: fresh run reported restored state`);
|
|
1622
|
-
if (args.resume === "required" && !args.resumed) throw new Error(`${args.label}: required resume did not restore state`);
|
|
1623
|
-
if (!args.runId.startsWith(args.compatibleRunId)) throw new Error(`${args.label}: run ID is not bound to its compatible identity`);
|
|
1624
|
-
}
|
|
1625
|
-
function assertExternalOptimizerRuntimeIdentity(value, expectedPackage, label) {
|
|
1626
|
-
if (!isRecord(value)) throw new Error(`${label}: source inspection returned no runtime identity`);
|
|
1627
|
-
assertExternalOptimizerPackageSource(value.bridge, "agent-eval-rpc", label, "bridge");
|
|
1628
|
-
assertExternalOptimizerPackageSource(value.optimizer, expectedPackage, label, expectedPackage);
|
|
1629
|
-
if (!value.bridge.sourceSha256 || !value.optimizer.sourceSha256) throw new Error(`${label}: source inspection omitted package source hashes`);
|
|
1630
|
-
if (!isRecord(value.python) || typeof value.python.implementation !== "string" || value.python.implementation.length === 0 || value.python.implementation !== value.python.implementation.trim() || typeof value.python.version !== "string" || value.python.version.length === 0 || value.python.version !== value.python.version.trim()) throw new Error(`${label}: source inspection returned an invalid Python runtime`);
|
|
1631
|
-
if (!Array.isArray(value.engineModules) || value.engineModules.some((module) => !isRecord(module) || typeof module.module !== "string" || module.module.length === 0 || module.module !== module.module.trim() || typeof module.sourceSha256 !== "string" || !/^[0-9a-f]{64}$/.test(module.sourceSha256))) throw new Error(`${label}: source inspection returned invalid engine modules`);
|
|
1632
|
-
}
|
|
1633
|
-
// src/campaign/gepa-optimization-result.ts
|
|
1634
|
-
function assertGepaBridgeOutput(result, name, maxCandidateChars, recipeKind, maxEvaluations, maxPopulationCandidates, scenarioIds, expectsComponents, requiresCandidatePopulation) {
|
|
1635
|
-
if (result.recipeKind !== recipeKind) throw new Error(`${name}: GEPA bridge reported recipe '${String(result.recipeKind)}'`);
|
|
1636
|
-
if (!isGepaCandidate(result.bestCandidate, maxCandidateChars) || expectsComponents !== (typeof result.bestCandidate !== "string")) throw new Error(`${name}: GEPA bridge returned an invalid candidate`);
|
|
1637
|
-
if (!Number.isFinite(result.bestScore)) throw new Error(`${name}: GEPA bridge returned an invalid bestScore`);
|
|
1638
|
-
if (!Number.isSafeInteger(result.totalEvaluations) || result.totalEvaluations < 0 || result.totalEvaluations > maxEvaluations) throw new Error(`${name}: GEPA bridge returned an invalid totalEvaluations`);
|
|
1639
|
-
if (result.upstreamReportedEvaluations !== void 0 && (!Number.isSafeInteger(result.upstreamReportedEvaluations) || result.upstreamReportedEvaluations < 0)) throw new Error(`${name}: GEPA bridge returned an invalid upstreamReportedEvaluations`);
|
|
1640
|
-
if (result.proposerCostUsd !== void 0 && (!Number.isFinite(result.proposerCostUsd) || result.proposerCostUsd < 0)) throw new Error(`${name}: GEPA bridge returned an invalid proposerCostUsd`);
|
|
1641
|
-
if (result.proposerCostAccounting !== "metered" && result.proposerCostAccounting !== "reported" && result.proposerCostAccounting !== "unavailable") throw new Error(`${name}: GEPA bridge returned invalid proposerCostAccounting`);
|
|
1642
|
-
if (result.proposerCostAccounting !== "unavailable" !== (result.proposerCostUsd !== void 0)) throw new Error(`${name}: GEPA bridge returned inconsistent proposer cost accounting`);
|
|
1643
|
-
assertExternalOptimizerTokenUsage(result.tokenUsage, name, "GEPA");
|
|
1644
|
-
if (result.proposerCostAccounting === "metered" && result.tokenUsage === void 0) throw new Error(`${name}: metered GEPA bridge omitted tokenUsage`);
|
|
1645
|
-
assertExternalOptimizerPackageSource(result.upstream, "gepa", name, "GEPA");
|
|
1646
|
-
if (typeof result.runId !== "string" || result.runId.length === 0 || result.runId !== result.runId.trim()) throw new Error(`${name}: GEPA bridge returned an invalid runId`);
|
|
1647
|
-
if (typeof result.resumed !== "boolean") throw new Error(`${name}: GEPA bridge returned an invalid resumed flag`);
|
|
1648
|
-
if (typeof result.seedApplied !== "boolean") throw new Error(`${name}: GEPA bridge returned an invalid seedApplied flag; upgrade agent-eval-rpc to a release that forwards the run seed`);
|
|
1649
|
-
if (result.candidatePopulation !== void 0) {
|
|
1650
|
-
assertGepaCandidatePopulationSummary(result.candidatePopulation);
|
|
1651
|
-
if (result.candidatePopulation.runId !== result.runId) throw new Error(`${name}: GEPA candidate population has a different run ID`);
|
|
1652
|
-
if (result.candidatePopulation.maxCandidates !== maxPopulationCandidates || result.candidatePopulation.maxCandidateChars !== maxCandidateChars || result.candidatePopulation.surfaceKind !== (expectsComponents ? "components" : "text") || result.candidatePopulation.scenarioIds.length !== scenarioIds.length || result.candidatePopulation.scenarioIds.some((scenarioId, index) => scenarioId !== scenarioIds[index])) throw new Error(`${name}: GEPA candidate population differs from its configured bounds`);
|
|
1653
|
-
} else if (requiresCandidatePopulation) throw new Error(`${name}: GEPA bridge omitted the official candidate population`);
|
|
1654
|
-
}
|
|
1655
|
-
function isGepaCandidate(value, maxChars) {
|
|
1656
|
-
if (!isExternalTextCandidate(value)) return false;
|
|
1657
|
-
return (typeof value === "string" ? value.length : JSON.stringify(value).length) <= maxChars;
|
|
1658
|
-
}
|
|
1659
|
-
// src/campaign/gepa-search-import.ts
|
|
1660
|
-
/**
|
|
1661
|
-
* Import an external optimizer's own record into a search ledger.
|
|
1662
|
-
*
|
|
1663
|
-
* GEPA and SkillOpt search inside their own processes. The evaluation
|
|
1664
|
-
* callback's observation log holds every candidate either one evaluated, and
|
|
1665
|
-
* GEPA's candidate population also names each candidate's parents by index.
|
|
1666
|
-
* The importer turns both into ledger events: one node per distinct candidate,
|
|
1667
|
-
* one `correlated` edge per population entry (joined by content digest from
|
|
1668
|
-
* GEPA's own parent record), and one cell per campaign cell an evaluation
|
|
1669
|
-
* measured (one per evaluation for a log that names no cells). Nothing is inferred
|
|
1670
|
-
* from timing or order: a candidate with no parent record (every SkillOpt
|
|
1671
|
-
* candidate, and a candidate GEPA kept out of its population) has an `unknown`
|
|
1672
|
-
* edge and no parents.
|
|
1673
|
-
*/
|
|
1674
|
-
function noRationale(optimizer) {
|
|
1675
|
-
return { unknown: `${optimizer} records no rationale per candidate; its reflection attaches to the proposer operation` };
|
|
1676
|
-
}
|
|
1677
|
-
const NO_GEPA_RATIONALE = noRationale("GEPA");
|
|
1678
|
-
/**
|
|
1679
|
-
* Register GEPA's population as nodes and its parent indices as `correlated`
|
|
1680
|
-
* edges. A parentless entry (GEPA's seed) gets a seed edge unless its node is
|
|
1681
|
-
* already in the tree, for example the root the caller seeded.
|
|
1682
|
-
*/
|
|
1683
|
-
async function importGepaPopulation(input) {
|
|
1684
|
-
const { recorder, population } = input;
|
|
1685
|
-
const node = input.node ?? ((candidate) => surfaceNode(recorder, externalSurface(candidate.candidate)));
|
|
1686
|
-
const diff = input.diff ?? ((parent, child) => surfaceDiff(recorder, externalSurface(parent.candidate), externalSurface(child.candidate)));
|
|
1687
|
-
const nodeIds = /* @__PURE__ */ new Map();
|
|
1688
|
-
const byIndex = new Map(population.candidates.map((candidate) => [candidate.index, candidate]));
|
|
1689
|
-
const seenNodes = /* @__PURE__ */ new Set();
|
|
1690
|
-
let edges = 0;
|
|
1691
|
-
let collapsedDuplicates = 0;
|
|
1692
|
-
let unchangedProposals = 0;
|
|
1693
|
-
for (const candidate of population.candidates) {
|
|
1694
|
-
const { nodeId } = await recorder.registerNode(node(candidate));
|
|
1695
|
-
if (seenNodes.has(nodeId)) collapsedDuplicates += 1;
|
|
1696
|
-
seenNodes.add(nodeId);
|
|
1697
|
-
nodeIds.set(candidate.index, nodeId);
|
|
1698
|
-
const parentIndices = [...new Set(candidate.parentIndices.filter((index) => index !== null))];
|
|
1699
|
-
const parents = [];
|
|
1700
|
-
for (const index of parentIndices) {
|
|
1701
|
-
const parentNodeId = nodeIds.get(index);
|
|
1702
|
-
const parent = byIndex.get(index);
|
|
1703
|
-
if (parentNodeId === void 0 || parent === void 0) throw new Error(`GEPA candidate ${candidate.index} names parent ${index}, which precedes no population entry`);
|
|
1704
|
-
if (parentNodeId === nodeId) continue;
|
|
1705
|
-
if (!parents.some((known) => known.nodeId === parentNodeId)) parents.push({
|
|
1706
|
-
nodeId: parentNodeId,
|
|
1707
|
-
candidate: parent
|
|
1708
|
-
});
|
|
1709
|
-
}
|
|
1710
|
-
if (parentIndices.length > 0 && parents.length === 0) {
|
|
1711
|
-
unchangedProposals += 1;
|
|
1712
|
-
continue;
|
|
1713
|
-
}
|
|
1714
|
-
if (parents.length === 0) {
|
|
1715
|
-
if (((await recorder.state()).node(nodeId)?.edgeIds.length ?? 0) > 0) continue;
|
|
1716
|
-
await recorder.recordEdge({
|
|
1717
|
-
childNodeId: nodeId,
|
|
1718
|
-
parents: [],
|
|
1719
|
-
operator: "seed",
|
|
1720
|
-
attribution: "correlated",
|
|
1721
|
-
proposer: null,
|
|
1722
|
-
proposalKey: `gepa:${population.runId}:${candidate.index}`,
|
|
1723
|
-
rationale: NO_GEPA_RATIONALE,
|
|
1724
|
-
diffs: [],
|
|
1725
|
-
label: `GEPA seed candidate ${candidate.index}`
|
|
1726
|
-
});
|
|
1727
|
-
edges += 1;
|
|
1728
|
-
continue;
|
|
1729
|
-
}
|
|
1730
|
-
await recorder.recordEdge({
|
|
1731
|
-
childNodeId: nodeId,
|
|
1732
|
-
parents: parents.map((parent) => parent.nodeId),
|
|
1733
|
-
operator: parents.length > 1 ? "merge" : "improve",
|
|
1734
|
-
attribution: "correlated",
|
|
1735
|
-
proposer: input.proposer,
|
|
1736
|
-
proposalKey: `gepa:${population.runId}:${candidate.index}`,
|
|
1737
|
-
rationale: NO_GEPA_RATIONALE,
|
|
1738
|
-
diffs: parents.map((parent) => diff(parent.candidate, candidate)),
|
|
1739
|
-
label: `GEPA candidate ${candidate.index}`
|
|
1740
|
-
});
|
|
1741
|
-
edges += 1;
|
|
2026
|
+
if (nestedEngine && Object.hasOwn(nestedEngine, "seed")) throw new Error(`gepaOptimizationMethod: ${label}.engineConfig.engine.seed conflicts with the comparison seed; the bridge forwards the run seed`);
|
|
1742
2027
|
}
|
|
1743
|
-
return {
|
|
1744
|
-
nodeIds,
|
|
1745
|
-
nodes: seenNodes.size,
|
|
1746
|
-
edges,
|
|
1747
|
-
collapsedDuplicates,
|
|
1748
|
-
unchangedProposals
|
|
1749
|
-
};
|
|
1750
2028
|
}
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
* dimensions, tokens, cost, model, duration, attempt and trace; a request
|
|
1756
|
-
* answered from an earlier request's cells adds none. A refusal that measured
|
|
1757
|
-
* cells before it was refused records them the same way, with their real
|
|
1758
|
-
* accounting and an `evaluation-refused` outcome; for an evaluation whose
|
|
1759
|
-
* campaign threw, that is every cell it settled, and each cell the throw
|
|
1760
|
-
* interrupted with unknown accounting. An evaluation logged
|
|
1761
|
-
* without cells (a log written before the callback recorded them, or a
|
|
1762
|
-
* refusal that measured nothing) records one cell whose accounting is
|
|
1763
|
-
* unknown. A candidate that is not yet a node (GEPA evaluated it on a
|
|
1764
|
-
* minibatch and discarded it, or SkillOpt, which reports no parents, proposed
|
|
1765
|
-
* it) is registered with an `unknown` edge.
|
|
1766
|
-
*/
|
|
1767
|
-
async function importExternalEvaluations(input) {
|
|
1768
|
-
const { recorder } = input;
|
|
1769
|
-
const optimizer = input.optimizer ?? "GEPA";
|
|
1770
|
-
const lane = `${optimizer.toLowerCase()}-evaluation-callback`;
|
|
1771
|
-
const reps = /* @__PURE__ */ new Map();
|
|
1772
|
-
const recordedCells = /* @__PURE__ */ new Set();
|
|
1773
|
-
const unrecorded = [];
|
|
1774
|
-
let cells = 0;
|
|
1775
|
-
let reusedRequests = 0;
|
|
1776
|
-
for (const observation of input.observations.observations) {
|
|
1777
|
-
if (!(observation.kind === "evaluation" || observation.kind === "refusal" && observation.reason === "evaluation-failed") || observation.candidate === void 0 || observation.exampleId === void 0) continue;
|
|
1778
|
-
const candidateHash = observation.candidateHash;
|
|
1779
|
-
const exampleId = observation.exampleId;
|
|
1780
|
-
const surface = externalSurface(observation.candidate);
|
|
1781
|
-
const registered = await recorder.registerNode(surfaceNode(recorder, surface));
|
|
1782
|
-
if (((await recorder.state()).node(registered.nodeId)?.edgeIds.length ?? 0) === 0) {
|
|
1783
|
-
await recorder.recordEdge({
|
|
1784
|
-
childNodeId: registered.nodeId,
|
|
1785
|
-
parents: [],
|
|
1786
|
-
operator: "improve",
|
|
1787
|
-
attribution: "unknown",
|
|
1788
|
-
proposer: input.proposer,
|
|
1789
|
-
proposalKey: `${optimizer.toLowerCase()}-evaluated:${candidateHash}`,
|
|
1790
|
-
rationale: noRationale(optimizer),
|
|
1791
|
-
diffs: [],
|
|
1792
|
-
label: optimizer === "GEPA" ? "GEPA proposal outside its population" : `${optimizer} proposal without a parent record`
|
|
1793
|
-
});
|
|
1794
|
-
unrecorded.push(registered.nodeId);
|
|
1795
|
-
}
|
|
1796
|
-
const split = input.splitOf(exampleId);
|
|
1797
|
-
const { measurement } = observation;
|
|
1798
|
-
const refused = observation.kind === "refusal";
|
|
1799
|
-
const allocate = async () => {
|
|
1800
|
-
const repKey = `${registered.nodeId}\u0000${exampleId}`;
|
|
1801
|
-
const rep = reps.get(repKey) ?? 0;
|
|
1802
|
-
reps.set(repKey, rep + 1);
|
|
1803
|
-
return recorder.allocateCell({
|
|
1804
|
-
nodeId: registered.nodeId,
|
|
1805
|
-
taskId: exampleId,
|
|
1806
|
-
split,
|
|
1807
|
-
rep,
|
|
1808
|
-
stage: "external",
|
|
1809
|
-
...measurement === void 0 ? {} : { lane }
|
|
1810
|
-
});
|
|
1811
|
-
};
|
|
1812
|
-
if (measurement !== void 0) {
|
|
1813
|
-
if (measurement.source === "reused") reusedRequests += 1;
|
|
1814
|
-
for (const cell of measurement.cells) {
|
|
1815
|
-
const key = hashCanonical({
|
|
1816
|
-
candidateHash,
|
|
1817
|
-
exampleId,
|
|
1818
|
-
cellId: cell.cellId,
|
|
1819
|
-
attempt: cell.attempt
|
|
1820
|
-
});
|
|
1821
|
-
if (recordedCells.has(key)) continue;
|
|
1822
|
-
recordedCells.add(key);
|
|
1823
|
-
const result = campaignCellSearchResult(cell, {
|
|
1824
|
-
execution: input.identity,
|
|
1825
|
-
lane
|
|
1826
|
-
});
|
|
1827
|
-
await recorder.settleCell({
|
|
1828
|
-
cellId: await allocate(),
|
|
1829
|
-
attempt: 1,
|
|
1830
|
-
...result,
|
|
1831
|
-
...refused ? { outcome: refusedAfterMeasurement(result.outcome) } : {}
|
|
1832
|
-
});
|
|
1833
|
-
cells += 1;
|
|
1834
|
-
}
|
|
2029
|
+
function assertProxiedGepaRecipe(recipe, optimizer) {
|
|
2030
|
+
for (const [index, run] of recipeEngineOptions(recipe).entries()) {
|
|
2031
|
+
if (GEPA_AGENT_CLI_ENGINES.has(run.engine)) {
|
|
2032
|
+
assertProxiedAgentCliEngine(run, index, optimizer);
|
|
1835
2033
|
continue;
|
|
1836
2034
|
}
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
status: "unknown",
|
|
1852
|
-
reason: "the evaluation callback meters tokens per run"
|
|
1853
|
-
},
|
|
1854
|
-
cost: {
|
|
1855
|
-
status: "unknown",
|
|
1856
|
-
knownLowerBoundUsd: 0,
|
|
1857
|
-
reason: "the evaluation callback meters cost per run, not per evaluation"
|
|
1858
|
-
}
|
|
1859
|
-
},
|
|
1860
|
-
identity: input.identity
|
|
1861
|
-
});
|
|
1862
|
-
cells += 1;
|
|
2035
|
+
if (run.engine !== "gepa") throw new Error(`gepaOptimizationMethod: optimizer requires GEPA's 'gepa' engine; recipe engine ${index} is '${run.engine}'`);
|
|
2036
|
+
const reflection = isRecord(run.engineConfig?.reflection) ? run.engineConfig.reflection : void 0;
|
|
2037
|
+
if (reflection && Object.hasOwn(reflection, "reflection_lm")) throw new Error("gepaOptimizationMethod: optimizer replaces engineConfig.reflection.reflection_lm; remove the duplicate setting");
|
|
2038
|
+
const reflectionOptions = isRecord(reflection?.reflection_lm_kwargs) ? reflection.reflection_lm_kwargs : void 0;
|
|
2039
|
+
if (reflectionOptions && [
|
|
2040
|
+
"api_base",
|
|
2041
|
+
"api_key",
|
|
2042
|
+
"api_url",
|
|
2043
|
+
"base_url",
|
|
2044
|
+
"endpoint",
|
|
2045
|
+
"messages",
|
|
2046
|
+
"model",
|
|
2047
|
+
"stream"
|
|
2048
|
+
].some((key) => Object.hasOwn(reflectionOptions, key))) throw new Error("gepaOptimizationMethod: proxied reflection transport settings belong in optimizer");
|
|
1863
2049
|
}
|
|
1864
|
-
return {
|
|
1865
|
-
cells,
|
|
1866
|
-
measuredCells: recordedCells.size,
|
|
1867
|
-
reusedRequests,
|
|
1868
|
-
unrecordedParentNodeIds: unrecorded
|
|
1869
|
-
};
|
|
1870
2050
|
}
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
* because the optimizer received no score, and the error names what the
|
|
1876
|
-
* measurement found.
|
|
1877
|
-
*/
|
|
1878
|
-
function refusedAfterMeasurement(measured) {
|
|
1879
|
-
const found = measured.status === "errored" ? `an unscored cell (${measured.error.code}: ${measured.error.message})` : `a ${measured.status} cell scoring ${measured.score}`;
|
|
1880
|
-
return {
|
|
1881
|
-
status: "errored",
|
|
1882
|
-
metrics: measured.metrics,
|
|
1883
|
-
error: {
|
|
1884
|
-
code: "evaluation-refused",
|
|
1885
|
-
message: `the evaluation callback refused the evaluation after measuring ${found}; the optimizer received no score`,
|
|
1886
|
-
retryable: false
|
|
1887
|
-
}
|
|
1888
|
-
};
|
|
2051
|
+
function assertProxiedAgentCliEngine(run, index, optimizer) {
|
|
2052
|
+
if (optimizer.anthropicEndpoint !== true) throw new Error(`gepaOptimizationMethod: agent engine '${run.engine}' (recipe engine ${index}) requires optimizer.anthropicEndpoint: true so the claude CLI meters through the loopback proxy`);
|
|
2053
|
+
if (run.engineConfig?.model !== optimizer.model) throw new Error(`gepaOptimizationMethod: recipe engine ${index} ('${run.engine}') must set engineConfig.model to the optimizer model '${optimizer.model}'`);
|
|
2054
|
+
if (run.engineConfig && Object.hasOwn(run.engineConfig, "max_thinking_tokens")) throw new Error(`gepaOptimizationMethod: recipe engine ${index} ('${run.engine}') cannot set engineConfig.max_thinking_tokens through the Anthropic endpoint`);
|
|
1889
2055
|
}
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
function evaluationOutcome(response) {
|
|
1893
|
-
const record = response ?? {};
|
|
1894
|
-
if (record.info?.status === "scored" && typeof record.score === "number" && Number.isFinite(record.score)) return {
|
|
1895
|
-
status: "passed",
|
|
1896
|
-
score: record.score,
|
|
1897
|
-
metrics: { score: record.score }
|
|
1898
|
-
};
|
|
1899
|
-
return {
|
|
1900
|
-
status: "errored",
|
|
1901
|
-
metrics: {},
|
|
1902
|
-
error: {
|
|
1903
|
-
code: "evaluation-failed",
|
|
1904
|
-
message: typeof record.info?.notes === "string" && record.info.notes.trim().length > 0 ? record.info.notes.trim() : "the evaluation produced no score",
|
|
1905
|
-
retryable: false
|
|
1906
|
-
}
|
|
1907
|
-
};
|
|
2056
|
+
function assertParallelControls(recipe) {
|
|
2057
|
+
if (recipe.maxWorkers !== void 0) assertPositiveSafeInteger$1(recipe.maxWorkers, "recipe.maxWorkers");
|
|
1908
2058
|
}
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
return typeof candidate === "string" ? candidate : {
|
|
1912
|
-
kind: "components",
|
|
1913
|
-
components: candidate
|
|
1914
|
-
};
|
|
2059
|
+
function assertPositiveSafeInteger$1(value, label) {
|
|
2060
|
+
if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`gepaOptimizationMethod: ${label} must be a positive safe integer`);
|
|
1915
2061
|
}
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
if (
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
});
|
|
2062
|
+
function recipeEngineOptions(recipe) {
|
|
2063
|
+
if (recipe.kind === "engine") return [recipe.run];
|
|
2064
|
+
if (recipe.kind === "omni") return [...recipe.explore, recipe.continueWith];
|
|
2065
|
+
return recipe.runs;
|
|
2066
|
+
}
|
|
2067
|
+
function addEvaluationLimit(total, increment) {
|
|
2068
|
+
const next = total + increment;
|
|
2069
|
+
if (!Number.isSafeInteger(next)) throw new Error("gepaOptimizationMethod: recipe evaluation limit exceeds safe integer range");
|
|
2070
|
+
return next;
|
|
2071
|
+
}
|
|
2072
|
+
// src/campaign/external-optimizer-accounting.ts
|
|
2073
|
+
const TOKEN_USAGE_FIELDS = [
|
|
2074
|
+
"inputTokens",
|
|
2075
|
+
"outputTokens",
|
|
2076
|
+
"totalTokens",
|
|
2077
|
+
"calls"
|
|
2078
|
+
];
|
|
2079
|
+
function assertPriorExternalOptimizerUsage(summary, budget, name) {
|
|
2080
|
+
if (!summary.usageComplete || budget.maxCostUsd !== void 0 && !summary.accountingComplete) throw new Error(`${name}: cannot resume optimizer-model work with incomplete bounded usage`);
|
|
2081
|
+
if (summary.totalCalls > budget.maxRequests || budget.maxCostUsd !== void 0 && summary.totalCostUsd > budget.maxCostUsd + Number.EPSILON) throw new Error(`${name}: prior optimizer-model usage exceeds the configured budget`);
|
|
2082
|
+
}
|
|
2083
|
+
function assertExternalOptimizerTokenUsage(usage, name, optimizer) {
|
|
2084
|
+
if (usage === void 0) return;
|
|
2085
|
+
for (const field of TOKEN_USAGE_FIELDS) if (!Number.isSafeInteger(usage[field]) || usage[field] < 0) throw new Error(`${name}: ${optimizer} bridge returned invalid tokenUsage.${field}`);
|
|
2086
|
+
if (usage.totalTokens !== usage.inputTokens + usage.outputTokens) throw new Error(`${name}: ${optimizer} bridge returned inconsistent tokenUsage.totalTokens`);
|
|
2087
|
+
if (usage.requestAttempts !== void 0 && (!Number.isSafeInteger(usage.requestAttempts) || usage.requestAttempts < usage.calls)) throw new Error(`${name}: ${optimizer} bridge returned invalid tokenUsage.requestAttempts`);
|
|
2088
|
+
if (usage.refusedAttempts !== void 0 && (!Number.isSafeInteger(usage.refusedAttempts) || usage.refusedAttempts < 0 || usage.requestAttempts === void 0 || usage.refusedAttempts > usage.requestAttempts - usage.calls)) throw new Error(`${name}: ${optimizer} bridge returned invalid tokenUsage.refusedAttempts`);
|
|
2089
|
+
}
|
|
2090
|
+
function assertExternalOptimizerCompletionCount(upstream, requestAttempts, successfulCompletions, name, optimizer, refusedRequests = 0) {
|
|
2091
|
+
if (!upstream) throw new Error(`${name}: ${optimizer} did not report optimizer token usage`);
|
|
2092
|
+
if (!Number.isSafeInteger(requestAttempts) || !Number.isSafeInteger(successfulCompletions) || !Number.isSafeInteger(refusedRequests) || refusedRequests < 0 || requestAttempts < 0 || successfulCompletions < 0 || successfulCompletions > requestAttempts) throw new Error(`${name}: optimizer model proxy returned invalid request counts`);
|
|
2093
|
+
if (upstream.calls !== successfulCompletions) throw new Error(`${name}: ${optimizer} reported ${upstream.calls} successful model calls but the proxy completed ${successfulCompletions} across ${requestAttempts} attempts`);
|
|
2094
|
+
if (upstream.refusedAttempts !== void 0 && upstream.refusedAttempts !== refusedRequests) throw new Error(`${name}: ${optimizer} counted ${upstream.refusedAttempts} refused model attempts but the proxy refused ${refusedRequests}`);
|
|
2095
|
+
if (upstream.requestAttempts !== void 0 && upstream.requestAttempts !== requestAttempts + refusedRequests) throw new Error(`${name}: ${optimizer} reported ${upstream.requestAttempts} model attempts but the proxy admitted ${requestAttempts} and refused ${refusedRequests}`);
|
|
2096
|
+
}
|
|
2097
|
+
// src/campaign/external-optimizer-source.ts
|
|
2098
|
+
function assertExternalOptimizerPackageSource(value, expectedPackage, name, optimizer) {
|
|
2099
|
+
assertExternalOptimizerPackageIdentity(value, expectedPackage, name, optimizer);
|
|
2100
|
+
assertExternalOptimizerSourceDetails(value, name, optimizer);
|
|
1942
2101
|
}
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
* root, every candidate SkillOpt evaluated as a node with an `unknown` edge
|
|
1946
|
-
* (SkillOpt reports no parents), every callback evaluation as an `external`
|
|
1947
|
-
* cell, SkillOpt's optimizer spend as one operation, SkillOpt's choice as the
|
|
1948
|
-
* selected node, and the close. Like GEPA's, the ledger carries no claim.
|
|
1949
|
-
*/
|
|
1950
|
-
async function recordSkillOptSearch(input) {
|
|
1951
|
-
return recordExternalSearch({
|
|
1952
|
-
...input,
|
|
1953
|
-
optimizer: "SkillOpt",
|
|
1954
|
-
population: null
|
|
1955
|
-
});
|
|
2102
|
+
function assertExternalOptimizerPackageIdentity(value, expectedPackage, name, optimizer) {
|
|
2103
|
+
if (!isRecord(value) || value.package !== expectedPackage || typeof value.version !== "string" || value.version.length === 0 || value.version !== value.version.trim()) throw new Error(`${name}: ${optimizer} bridge returned invalid upstream package provenance`);
|
|
1956
2104
|
}
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
}
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
const selection = tasks(input.selectionScenarios);
|
|
1972
|
-
const taskSet = hashCanonical({
|
|
1973
|
-
train,
|
|
1974
|
-
selection
|
|
1975
|
-
});
|
|
1976
|
-
const recorder = await SearchRecorder.open({
|
|
1977
|
-
ledger: openSearchLedger({
|
|
1978
|
-
path: input.path,
|
|
1979
|
-
searchId: input.searchId
|
|
1980
|
-
}),
|
|
1981
|
-
storage: input.storage
|
|
1982
|
-
}, {
|
|
1983
|
-
subject: identity.subject ?? input.name,
|
|
1984
|
-
process: {
|
|
1985
|
-
name: input.name,
|
|
1986
|
-
executionRef: identity.search
|
|
1987
|
-
},
|
|
1988
|
-
artifactKind: "prompt",
|
|
1989
|
-
objective: {
|
|
1990
|
-
metric: "score",
|
|
1991
|
-
direction: "maximize",
|
|
1992
|
-
judge: identity.judge ?? { unknown: "the evaluation callback judges through caller functions without a pinned source" },
|
|
1993
|
-
claim: identity.claim ?? developmentClaim(taskSet)
|
|
1994
|
-
},
|
|
1995
|
-
splits: {
|
|
1996
|
-
train,
|
|
1997
|
-
selection,
|
|
1998
|
-
test: [],
|
|
1999
|
-
heldOutUnits: true
|
|
2000
|
-
},
|
|
2001
|
-
policy: {
|
|
2002
|
-
expansion: policyName,
|
|
2003
|
-
allocation: policyName,
|
|
2004
|
-
seed: input.seed
|
|
2005
|
-
},
|
|
2006
|
-
budget: {
|
|
2007
|
-
maxUsd: null,
|
|
2008
|
-
maxCells: input.evaluationLimit * repsPerEvaluation,
|
|
2009
|
-
maxNodes: null,
|
|
2010
|
-
deadline: null,
|
|
2011
|
-
maxConcurrency: null,
|
|
2012
|
-
reservedClaimUsd: 0
|
|
2013
|
-
},
|
|
2014
|
-
containment: null,
|
|
2015
|
-
derivedFrom: null,
|
|
2016
|
-
identity: {
|
|
2017
|
-
model: identity.model,
|
|
2018
|
-
agent: identity.agent,
|
|
2019
|
-
benchmark: {
|
|
2020
|
-
uri: `optimizer://${input.name}`,
|
|
2021
|
-
revision: taskSet
|
|
2022
|
-
}
|
|
2023
|
-
}
|
|
2024
|
-
});
|
|
2025
|
-
const root = await recorder.registerNode(surfaceNode(recorder, input.baselineSurface));
|
|
2026
|
-
await recorder.recordEdge({
|
|
2027
|
-
childNodeId: root.nodeId,
|
|
2028
|
-
parents: [],
|
|
2029
|
-
operator: "seed",
|
|
2030
|
-
attribution: "explicit",
|
|
2031
|
-
proposer: null,
|
|
2032
|
-
proposalKey: "baseline",
|
|
2033
|
-
rationale: { unknown: "the baseline is the caller-supplied starting surface" },
|
|
2034
|
-
diffs: [],
|
|
2035
|
-
label: "baseline"
|
|
2036
|
-
});
|
|
2037
|
-
const operationId = `${policyName}-proposals`;
|
|
2038
|
-
await recorder.startOperation({
|
|
2039
|
-
operationId,
|
|
2040
|
-
operationKind: "candidate-generation"
|
|
2041
|
-
});
|
|
2042
|
-
const proposer = {
|
|
2043
|
-
kind: "optimizer",
|
|
2044
|
-
name: input.name,
|
|
2045
|
-
operationId,
|
|
2046
|
-
source: identity.proposer.source
|
|
2105
|
+
function assertExternalOptimizerSourceDetails(value, name, optimizer) {
|
|
2106
|
+
if (value.sourceUrl !== void 0 && (typeof value.sourceUrl !== "string" || value.sourceUrl.length === 0 || value.sourceUrl !== value.sourceUrl.trim())) throw new Error(`${name}: ${optimizer} bridge returned an invalid upstream sourceUrl`);
|
|
2107
|
+
if (value.revision !== void 0 && (typeof value.revision !== "string" || value.revision.length === 0 || value.revision !== value.revision.trim())) throw new Error(`${name}: ${optimizer} bridge returned an invalid upstream revision`);
|
|
2108
|
+
if (value.sourceSha256 !== void 0 && (typeof value.sourceSha256 !== "string" || !/^[0-9a-f]{64}$/.test(value.sourceSha256))) throw new Error(`${name}: ${optimizer} bridge returned an invalid upstream sourceSha256`);
|
|
2109
|
+
}
|
|
2110
|
+
function observedExternalOptimizerPackageSource(value) {
|
|
2111
|
+
return {
|
|
2112
|
+
kind: "package",
|
|
2113
|
+
evidence: "observed",
|
|
2114
|
+
package: value.package,
|
|
2115
|
+
version: value.version,
|
|
2116
|
+
...value.sourceUrl ? { sourceUrl: value.sourceUrl } : {},
|
|
2117
|
+
...value.revision ? { revision: value.revision } : {},
|
|
2118
|
+
...value.sourceSha256 ? { sourceSha256: value.sourceSha256 } : {}
|
|
2047
2119
|
};
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
identity: {
|
|
2059
|
-
model: identity.model,
|
|
2060
|
-
agent: identity.agent,
|
|
2061
|
-
benchmark: {
|
|
2062
|
-
uri: `optimizer://${input.name}`,
|
|
2063
|
-
revision: taskSet
|
|
2064
|
-
}
|
|
2120
|
+
}
|
|
2121
|
+
// src/campaign/external-optimizer-runtime.ts
|
|
2122
|
+
async function inspectExternalOptimizerRuntime(args) {
|
|
2123
|
+
const result = await runExternalOptimizerProcess({
|
|
2124
|
+
label: `${args.label} source inspection`,
|
|
2125
|
+
tempPrefix: `agent-eval-${args.package}-inspect-`,
|
|
2126
|
+
module: args.module,
|
|
2127
|
+
input: {
|
|
2128
|
+
operation: "inspect",
|
|
2129
|
+
engineModules: [...args.engineModules ?? []]
|
|
2065
2130
|
},
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
const chosen = await recorder.registerNode(surfaceNode(recorder, input.selected));
|
|
2070
|
-
if (((await recorder.state()).node(chosen.nodeId)?.edgeIds.length ?? 0) === 0) await recorder.recordEdge({
|
|
2071
|
-
childNodeId: chosen.nodeId,
|
|
2072
|
-
parents: [],
|
|
2073
|
-
operator: "improve",
|
|
2074
|
-
attribution: "unknown",
|
|
2075
|
-
proposer,
|
|
2076
|
-
proposalKey: `${policyName}-selected`,
|
|
2077
|
-
rationale: noRationale(optimizer),
|
|
2078
|
-
diffs: [],
|
|
2079
|
-
label: `${optimizer} choice without an evaluation`
|
|
2080
|
-
});
|
|
2081
|
-
await recorder.recordOperation({
|
|
2082
|
-
operationId,
|
|
2083
|
-
operationKind: "candidate-generation",
|
|
2084
|
-
execution: identity.proposer,
|
|
2085
|
-
outcome: { status: "completed" },
|
|
2086
|
-
accounting: input.generationAccounting
|
|
2087
|
-
});
|
|
2088
|
-
const state = await recorder.state();
|
|
2089
|
-
const nodes = state.nodes();
|
|
2090
|
-
const best = chosen.nodeId;
|
|
2091
|
-
const bestScored = state.cells({ nodeId: best }).some((cell) => cell.score !== null);
|
|
2092
|
-
const rule = population ? "gepa-best-aggregate" : `${policyName}-choice`;
|
|
2093
|
-
const basis = population ? "its aggregate selection score" : "its own validation";
|
|
2094
|
-
for (const node of nodes) if (node.nodeId === best && bestScored) await recorder.decideNode({
|
|
2095
|
-
nodeId: node.nodeId,
|
|
2096
|
-
decision: { status: "selected" },
|
|
2097
|
-
rule,
|
|
2098
|
-
reason: `${optimizer} chose this candidate by ${basis}`
|
|
2099
|
-
});
|
|
2100
|
-
else if (population && evaluations.unrecordedParentNodeIds.includes(node.nodeId)) await recorder.decideNode({
|
|
2101
|
-
nodeId: node.nodeId,
|
|
2102
|
-
decision: { status: "pruned" },
|
|
2103
|
-
rule: "gepa-population",
|
|
2104
|
-
reason: "GEPA evaluated the candidate and kept it out of its population"
|
|
2105
|
-
});
|
|
2106
|
-
else await recorder.decideNode({
|
|
2107
|
-
nodeId: node.nodeId,
|
|
2108
|
-
decision: node.nodeId === best ? { status: "invalid" } : { status: "rejected" },
|
|
2109
|
-
rule,
|
|
2110
|
-
reason: node.nodeId === best ? `${optimizer} chose this candidate, but no evaluation of it was scored` : `${optimizer} chose another candidate`
|
|
2111
|
-
});
|
|
2112
|
-
await recorder.close({
|
|
2113
|
-
reason: "budget",
|
|
2114
|
-
claim: null
|
|
2115
|
-
});
|
|
2116
|
-
return recorder.receipt({
|
|
2117
|
-
producerId: input.name,
|
|
2118
|
-
runId: input.searchId
|
|
2131
|
+
...args.runner ? { runner: args.runner } : {},
|
|
2132
|
+
timeoutMs: args.timeoutMs,
|
|
2133
|
+
...args.signal ? { signal: args.signal } : {}
|
|
2119
2134
|
});
|
|
2135
|
+
assertExternalOptimizerRuntimeIdentity(result.runtime, args.package, args.label);
|
|
2136
|
+
return result.runtime;
|
|
2137
|
+
}
|
|
2138
|
+
function observedExternalOptimizerRuntime(runtime) {
|
|
2139
|
+
return {
|
|
2140
|
+
source: observedExternalOptimizerPackageSource(runtime.optimizer),
|
|
2141
|
+
bridge: observedExternalOptimizerPackageSource(runtime.bridge),
|
|
2142
|
+
modules: runtime.engineModules.map((module) => ({ ...module })),
|
|
2143
|
+
python: { ...runtime.python }
|
|
2144
|
+
};
|
|
2145
|
+
}
|
|
2146
|
+
function assertExternalOptimizerRunBinding(args) {
|
|
2147
|
+
if (!isDeepStrictEqual(args.returnedSource, args.runtime.optimizer)) throw new Error(`${args.label}: optimizer package changed after source inspection`);
|
|
2148
|
+
if (args.returnedRunId !== args.runId) throw new Error(`${args.label}: bridge returned a different run ID`);
|
|
2149
|
+
if (args.resume === "never" && args.resumed) throw new Error(`${args.label}: fresh run reported restored state`);
|
|
2150
|
+
if (args.resume === "required" && !args.resumed) throw new Error(`${args.label}: required resume did not restore state`);
|
|
2151
|
+
if (!args.runId.startsWith(args.compatibleRunId)) throw new Error(`${args.label}: run ID is not bound to its compatible identity`);
|
|
2152
|
+
}
|
|
2153
|
+
function assertExternalOptimizerRuntimeIdentity(value, expectedPackage, label) {
|
|
2154
|
+
if (!isRecord(value)) throw new Error(`${label}: source inspection returned no runtime identity`);
|
|
2155
|
+
assertExternalOptimizerPackageSource(value.bridge, "agent-eval-rpc", label, "bridge");
|
|
2156
|
+
assertExternalOptimizerPackageSource(value.optimizer, expectedPackage, label, expectedPackage);
|
|
2157
|
+
if (!value.bridge.sourceSha256 || !value.optimizer.sourceSha256) throw new Error(`${label}: source inspection omitted package source hashes`);
|
|
2158
|
+
if (!isRecord(value.python) || typeof value.python.implementation !== "string" || value.python.implementation.length === 0 || value.python.implementation !== value.python.implementation.trim() || typeof value.python.version !== "string" || value.python.version.length === 0 || value.python.version !== value.python.version.trim()) throw new Error(`${label}: source inspection returned an invalid Python runtime`);
|
|
2159
|
+
if (!Array.isArray(value.engineModules) || value.engineModules.some((module) => !isRecord(module) || typeof module.module !== "string" || module.module.length === 0 || module.module !== module.module.trim() || typeof module.sourceSha256 !== "string" || !/^[0-9a-f]{64}$/.test(module.sourceSha256))) throw new Error(`${label}: source inspection returned invalid engine modules`);
|
|
2160
|
+
}
|
|
2161
|
+
// src/campaign/gepa-optimization-result.ts
|
|
2162
|
+
function assertGepaBridgeOutput(result, name, maxCandidateChars, recipeKind, maxEvaluations, maxPopulationCandidates, scenarioIds, expectsComponents, requiresCandidatePopulation) {
|
|
2163
|
+
if (result.recipeKind !== recipeKind) throw new Error(`${name}: GEPA bridge reported recipe '${String(result.recipeKind)}'`);
|
|
2164
|
+
if (!isGepaCandidate(result.bestCandidate, maxCandidateChars) || expectsComponents !== (typeof result.bestCandidate !== "string")) throw new Error(`${name}: GEPA bridge returned an invalid candidate`);
|
|
2165
|
+
if (!Number.isFinite(result.bestScore)) throw new Error(`${name}: GEPA bridge returned an invalid bestScore`);
|
|
2166
|
+
if (!Number.isSafeInteger(result.totalEvaluations) || result.totalEvaluations < 0 || result.totalEvaluations > maxEvaluations) throw new Error(`${name}: GEPA bridge returned an invalid totalEvaluations`);
|
|
2167
|
+
if (result.upstreamReportedEvaluations !== void 0 && (!Number.isSafeInteger(result.upstreamReportedEvaluations) || result.upstreamReportedEvaluations < 0)) throw new Error(`${name}: GEPA bridge returned an invalid upstreamReportedEvaluations`);
|
|
2168
|
+
if (result.proposerCostUsd !== void 0 && (!Number.isFinite(result.proposerCostUsd) || result.proposerCostUsd < 0)) throw new Error(`${name}: GEPA bridge returned an invalid proposerCostUsd`);
|
|
2169
|
+
if (result.proposerCostAccounting !== "metered" && result.proposerCostAccounting !== "reported" && result.proposerCostAccounting !== "unavailable") throw new Error(`${name}: GEPA bridge returned invalid proposerCostAccounting`);
|
|
2170
|
+
if (result.proposerCostAccounting !== "unavailable" !== (result.proposerCostUsd !== void 0)) throw new Error(`${name}: GEPA bridge returned inconsistent proposer cost accounting`);
|
|
2171
|
+
assertExternalOptimizerTokenUsage(result.tokenUsage, name, "GEPA");
|
|
2172
|
+
if (result.proposerCostAccounting === "metered" && result.tokenUsage === void 0) throw new Error(`${name}: metered GEPA bridge omitted tokenUsage`);
|
|
2173
|
+
assertExternalOptimizerPackageSource(result.upstream, "gepa", name, "GEPA");
|
|
2174
|
+
if (typeof result.runId !== "string" || result.runId.length === 0 || result.runId !== result.runId.trim()) throw new Error(`${name}: GEPA bridge returned an invalid runId`);
|
|
2175
|
+
if (typeof result.resumed !== "boolean") throw new Error(`${name}: GEPA bridge returned an invalid resumed flag`);
|
|
2176
|
+
if (typeof result.seedApplied !== "boolean") throw new Error(`${name}: GEPA bridge returned an invalid seedApplied flag; upgrade agent-eval-rpc to a release that forwards the run seed`);
|
|
2177
|
+
if (result.candidatePopulation !== void 0) {
|
|
2178
|
+
assertGepaCandidatePopulationSummary(result.candidatePopulation);
|
|
2179
|
+
if (result.candidatePopulation.runId !== result.runId) throw new Error(`${name}: GEPA candidate population has a different run ID`);
|
|
2180
|
+
if (result.candidatePopulation.maxCandidates !== maxPopulationCandidates || result.candidatePopulation.maxCandidateChars !== maxCandidateChars || result.candidatePopulation.surfaceKind !== (expectsComponents ? "components" : "text") || result.candidatePopulation.scenarioIds.length !== scenarioIds.length || result.candidatePopulation.scenarioIds.some((scenarioId, index) => scenarioId !== scenarioIds[index])) throw new Error(`${name}: GEPA candidate population differs from its configured bounds`);
|
|
2181
|
+
} else if (requiresCandidatePopulation) throw new Error(`${name}: GEPA bridge omitted the official candidate population`);
|
|
2182
|
+
}
|
|
2183
|
+
function isGepaCandidate(value, maxChars) {
|
|
2184
|
+
if (!isExternalTextCandidate(value)) return false;
|
|
2185
|
+
return (typeof value === "string" ? value.length : JSON.stringify(value).length) <= maxChars;
|
|
2120
2186
|
}
|
|
2121
2187
|
// src/campaign/gepa-optimization-run.ts
|
|
2122
2188
|
function anthropicShimEnvironment(proxy, optimizer) {
|
|
@@ -2175,6 +2241,10 @@ function gepaRunMaterial(config, input, parts) {
|
|
|
2175
2241
|
maxCandidateChars,
|
|
2176
2242
|
maxPopulationCandidates,
|
|
2177
2243
|
maxEvidenceChars,
|
|
2244
|
+
...config.contrastiveEvidence ? {
|
|
2245
|
+
contrastiveEvidence: config.contrastiveEvidence,
|
|
2246
|
+
reps: input.runOptions.reps
|
|
2247
|
+
} : {},
|
|
2178
2248
|
evaluationCallbackLimits: resolveExternalOptimizerCallbackLimits(config.evaluationCallbackLimits),
|
|
2179
2249
|
optimizerModel: config.optimizer ? {
|
|
2180
2250
|
model: config.optimizer.model,
|
|
@@ -2202,7 +2272,8 @@ async function startGepaCallback(config, input, parts) {
|
|
|
2202
2272
|
scenarioById,
|
|
2203
2273
|
maxCandidateChars,
|
|
2204
2274
|
maxEvidenceChars,
|
|
2205
|
-
describeArtifact: config.describeArtifact
|
|
2275
|
+
describeArtifact: config.describeArtifact,
|
|
2276
|
+
contrastiveEvidence: config.contrastiveEvidence
|
|
2206
2277
|
});
|
|
2207
2278
|
let attemptEvaluationCount = 0;
|
|
2208
2279
|
return startExternalOptimizerCallback({
|
|
@@ -2224,6 +2295,11 @@ async function prepareGepaRun(config, input, name) {
|
|
|
2224
2295
|
const signal = input.runOptions.signal;
|
|
2225
2296
|
signal?.throwIfAborted();
|
|
2226
2297
|
if (typeof input.baselineSurface !== "string" && input.baselineSurface.kind !== "components") throw new Error(`${name}: GEPA bridge supports text and component surfaces`);
|
|
2298
|
+
const contrastiveEvidence = config.contrastiveEvidence;
|
|
2299
|
+
if (contrastiveEvidence) {
|
|
2300
|
+
if ((input.runOptions.reps ?? 1) < 2) throw new Error(`${name}: contrastiveEvidence requires at least two replicates`);
|
|
2301
|
+
if (!input.judges.find(({ name: judgeName }) => judgeName === contrastiveEvidence.judge)?.dimensions.some(({ key }) => key === contrastiveEvidence.dimension)) throw new Error(`${name}: contrastiveEvidence refers to an unconfigured judge or dimension`);
|
|
2302
|
+
}
|
|
2227
2303
|
const expectsComponents = typeof input.baselineSurface !== "string";
|
|
2228
2304
|
if (expectsComponents) assertGepaComponentRecipe(config.recipe, name);
|
|
2229
2305
|
const started = Date.now();
|
|
@@ -2327,7 +2403,7 @@ async function prepareGepaRun(config, input, name) {
|
|
|
2327
2403
|
}
|
|
2328
2404
|
/** Start the optimizer model proxy when one is configured, run the GEPA bridge, and release the resources either way. */
|
|
2329
2405
|
async function runBridge(ctx) {
|
|
2330
|
-
const { signal, maxCandidateChars, maxEvidenceChars, timeoutMs, runDir, costLedger, attemptId, resume, bridgeRunner, runtimeIdentity, seedCandidate, trainSet, selectionSet, maxPopulationCandidates, compatibleRunId, runId, runBudget, executionLog, callback, name, config, input } = ctx;
|
|
2406
|
+
const { signal, maxCandidateChars, maxEvidenceChars, timeoutMs, runDir, costLedger, attemptId, resume, bridgeRunner, runtimeIdentity, seedCandidate, trainSet, selectionSet, maxPopulationCandidates, compatibleRunId, runId, runBudget, evaluationLimit, executionLog, callback, name, config, input } = ctx;
|
|
2331
2407
|
const runnerEnv = bridgeRunner?.env ?? {};
|
|
2332
2408
|
let modelProxy;
|
|
2333
2409
|
const bridgeRunnerForSpawn = () => {
|
|
@@ -2389,6 +2465,7 @@ async function runBridge(ctx) {
|
|
|
2389
2465
|
runtimeIdentity,
|
|
2390
2466
|
resume,
|
|
2391
2467
|
trustedResumeState: config.trustResumeState === true,
|
|
2468
|
+
ownerBudgetExhausted: runBudget.acceptedEvaluations() >= evaluationLimit,
|
|
2392
2469
|
evaluationId: config.evaluationId,
|
|
2393
2470
|
seed: input.seed,
|
|
2394
2471
|
callbackUrl: callback.url,
|
|
@@ -3605,6 +3682,6 @@ async function finishSkillOptRun(context, result, outputDir, modelProxy) {
|
|
|
3605
3682
|
}
|
|
3606
3683
|
};
|
|
3607
3684
|
}
|
|
3608
|
-
export {
|
|
3685
|
+
export { readExternalOptimizerObservationArtifact as _, assertOptimizerModel as a, heldOutGate as c, externalSurface as d, importExternalEvaluations as f, openExternalOptimizerObservationLog as g, openExternalOptimizerExecutionLog as h, inspectExternalOptimizerRuntime as i, composeGate as l, decodeExternalTextCandidate as m, compareOptimizationMethods as n, snapshotOptimizerModel as o, importGepaPopulation as p, gepaOptimizationMethod as r, externalOptimizerRunnerIdentity as s, skillOptOptimizationMethod as t, externalTextOptimizationMethod as u };
|
|
3609
3686
|
|
|
3610
|
-
//# sourceMappingURL=skillopt-optimization-method-
|
|
3687
|
+
//# sourceMappingURL=skillopt-optimization-method-DgsG1p3g.js.map
|