@tangle-network/agent-eval 2.0.11 → 2.0.12
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 +16 -0
- package/dist/adapters/http.d.ts +2 -2
- package/dist/{agent-profile-_JzxgLDM.d.ts → agent-profile-C0FBdYa6.d.ts} +3 -3
- package/dist/{agent-profile-_JzxgLDM.d.ts.map → agent-profile-C0FBdYa6.d.ts.map} +1 -1
- package/dist/analyst/index.d.ts +292 -74
- package/dist/analyst/index.d.ts.map +1 -1
- package/dist/analyst/index.js +11 -161
- package/dist/analyst/index.js.map +1 -1
- package/dist/app-grade/index.d.ts +2 -2
- package/dist/app-grade/index.js +3 -3
- package/dist/{benchmark-command-CGQXNFj7.js → benchmark-command-Be5O6A2v.js} +797 -13
- package/dist/benchmark-command-Be5O6A2v.js.map +1 -0
- package/dist/benchmarks/index.d.ts +4 -4
- package/dist/benchmarks/index.js +3 -3
- package/dist/campaign/index.d.ts +5 -5
- package/dist/campaign/index.js +10 -10
- package/dist/{campaign-eus7YRs2.js → campaign-CE08mvQO.js} +11 -11
- package/dist/{campaign-eus7YRs2.js.map → campaign-CE08mvQO.js.map} +1 -1
- package/dist/{campaign-evidence-KM5GTsHG.js → campaign-evidence-71uzJMVY.js} +2 -2
- package/dist/{campaign-evidence-KM5GTsHG.js.map → campaign-evidence-71uzJMVY.js.map} +1 -1
- package/dist/{campaign-evidence-BOcX4w0r.d.ts → campaign-evidence-DRvr7lZU.d.ts} +2 -2
- package/dist/{campaign-evidence-BOcX4w0r.d.ts.map → campaign-evidence-DRvr7lZU.d.ts.map} +1 -1
- package/dist/{chat-client-Oyot5tyo.js → chat-client-TkNgQDLj.js} +2 -2
- package/dist/{chat-client-Oyot5tyo.js.map → chat-client-TkNgQDLj.js.map} +1 -1
- package/dist/{chat-json-call-DTmv2uNY.js → chat-json-call-gu3deRID.js} +2 -2
- package/dist/{chat-json-call-DTmv2uNY.js.map → chat-json-call-gu3deRID.js.map} +1 -1
- package/dist/cli.js +778 -10
- package/dist/cli.js.map +1 -1
- package/dist/code-agent-jsonl-aPWZG3vr.js +104 -0
- package/dist/code-agent-jsonl-aPWZG3vr.js.map +1 -0
- package/dist/{completion-verifier-CCPG2Yc0.js → completion-verifier-BvPqg9Gp.js} +4 -4
- package/dist/{completion-verifier-CCPG2Yc0.js.map → completion-verifier-BvPqg9Gp.js.map} +1 -1
- package/dist/contract/index.d.ts +8 -8
- package/dist/contract/index.js +16 -112
- package/dist/contract/index.js.map +1 -1
- package/dist/{cost-ledger-C5CCidPm.js → cost-ledger-ni6f77QJ.js} +106 -50
- package/dist/cost-ledger-ni6f77QJ.js.map +1 -0
- package/dist/{decision-point-CfqtnGop.js → decision-point-CjC56Enj.js} +2 -2
- package/dist/{decision-point-CfqtnGop.js.map → decision-point-CjC56Enj.js.map} +1 -1
- package/dist/{default-registry-Rs5uzlfJ.js → default-registry-C5iSuS8e.js} +5 -5
- package/dist/{default-registry-Rs5uzlfJ.js.map → default-registry-C5iSuS8e.js.map} +1 -1
- package/dist/{default-registry-X8McMoUV.d.ts → default-registry-DFRlBniE.d.ts} +2 -2
- package/dist/{default-registry-X8McMoUV.d.ts.map → default-registry-DFRlBniE.d.ts.map} +1 -1
- package/dist/{define-agent-eval-D8ntOXqV.js → define-agent-eval-BHn6t-DC.js} +4 -4
- package/dist/{define-agent-eval-D8ntOXqV.js.map → define-agent-eval-BHn6t-DC.js.map} +1 -1
- package/dist/{define-agent-eval-DH5-xi-F.d.ts → define-agent-eval-n63vmQMR.d.ts} +4 -4
- package/dist/{define-agent-eval-DH5-xi-F.d.ts.map → define-agent-eval-n63vmQMR.d.ts.map} +1 -1
- package/dist/{dspy-rlm-engine-ChE1PUM5.js → dspy-rlm-engine-CR5MSL2k.js} +6 -5
- package/dist/{dspy-rlm-engine-ChE1PUM5.js.map → dspy-rlm-engine-CR5MSL2k.js.map} +1 -1
- package/dist/{evaluation-BAisv8ZR.js → evaluation-DqfNMaKr.js} +2 -2
- package/dist/{evaluation-BAisv8ZR.js.map → evaluation-DqfNMaKr.js.map} +1 -1
- package/dist/{evaluation-CjZH6gW0.d.ts → evaluation-VbjqORBn.d.ts} +2 -2
- package/dist/{evaluation-CjZH6gW0.d.ts.map → evaluation-VbjqORBn.d.ts.map} +1 -1
- package/dist/evaluation.d.ts +1 -1
- package/dist/evaluation.js +1 -1
- package/dist/experiment/index.d.ts +1 -1
- package/dist/experiment/index.js +1 -1
- package/dist/{external-optimizer-contracts-BFV8lnhl.js → external-optimizer-contracts-vrye9kti.js} +2 -2
- package/dist/{external-optimizer-contracts-BFV8lnhl.js.map → external-optimizer-contracts-vrye9kti.js.map} +1 -1
- package/dist/{external-optimizer-process-B6emPodQ.js → external-optimizer-process-DkOMkeHW.js} +3 -3
- package/dist/{external-optimizer-process-B6emPodQ.js.map → external-optimizer-process-DkOMkeHW.js.map} +1 -1
- package/dist/{external-optimizer-subprocess-_O06eDVA.js → external-optimizer-subprocess-CFIiwHSE.js} +3 -3
- package/dist/{external-optimizer-subprocess-_O06eDVA.js.map → external-optimizer-subprocess-CFIiwHSE.js.map} +1 -1
- package/dist/{finding-scope-B_As3F_v.js → finding-scope-BVQVcjz7.js} +2 -2
- package/dist/{finding-scope-B_As3F_v.js.map → finding-scope-BVQVcjz7.js.map} +1 -1
- package/dist/{findings-store-CvYUzQBR.js → findings-store-Drnjid7m.js} +5 -5
- package/dist/{findings-store-CvYUzQBR.js.map → findings-store-Drnjid7m.js.map} +1 -1
- package/dist/fuzz.js +1 -1
- package/dist/hosted/index.js +1 -1
- package/dist/{index-BmWw8zN6.d.ts → index-BEXEYURJ.d.ts} +7 -7
- package/dist/{index-BmWw8zN6.d.ts.map → index-BEXEYURJ.d.ts.map} +1 -1
- package/dist/{index-Cn9gB5Ca.d.ts → index-CbzPtg7O.d.ts} +205 -29
- package/dist/index-CbzPtg7O.d.ts.map +1 -0
- package/dist/{index-CCOaNmh2.d.ts → index-Dt3zWlRa.d.ts} +3 -3
- package/dist/{index-CCOaNmh2.d.ts.map → index-Dt3zWlRa.d.ts.map} +1 -1
- package/dist/{index-aRalB_Ma.d.ts → index-rrPT3Pw0.d.ts} +2 -2
- package/dist/{index-aRalB_Ma.d.ts.map → index-rrPT3Pw0.d.ts.map} +1 -1
- package/dist/index.d.ts +13 -13
- package/dist/index.js +471 -22
- package/dist/index.js.map +1 -1
- package/dist/{judge-gate-CpD3wmcf.js → judge-gate-WgYqQ9LA.js} +2 -2
- package/dist/{judge-gate-CpD3wmcf.js.map → judge-gate-WgYqQ9LA.js.map} +1 -1
- package/dist/{kind-factory-B-xCxG7p.js → kind-factory-C8MJpMTV.js} +2 -2
- package/dist/{kind-factory-B-xCxG7p.js.map → kind-factory-C8MJpMTV.js.map} +1 -1
- package/dist/{llm-client-Dk8lBnMh.js → llm-client-D4B1qR_1.js} +2 -2
- package/dist/{llm-client-Dk8lBnMh.js.map → llm-client-D4B1qR_1.js.map} +1 -1
- package/dist/{llm-judge-DYmEdo3M.js → llm-judge-CgF3ZM3R.js} +4 -4
- package/dist/{llm-judge-DYmEdo3M.js.map → llm-judge-CgF3ZM3R.js.map} +1 -1
- package/dist/{matrix-BDl7hoBr.d.ts → matrix-B95YsrV7.d.ts} +2 -2
- package/dist/{matrix-BDl7hoBr.d.ts.map → matrix-B95YsrV7.d.ts.map} +1 -1
- package/dist/meta-eval/index.js +2 -2
- package/dist/metrics-C6pXdupw.js +9 -0
- package/dist/metrics-C6pXdupw.js.map +1 -0
- package/dist/multishot/golden/index.d.ts +1 -1
- package/dist/multishot/index.d.ts +6 -6
- package/dist/multishot/index.js +8 -7
- package/dist/multishot/index.js.map +1 -1
- package/dist/openapi.json +1 -1
- package/dist/{optimization-method-4JlbMxd2.js → optimization-method-1xzXK-B6.js} +9 -9
- package/dist/{optimization-method-4JlbMxd2.js.map → optimization-method-1xzXK-B6.js.map} +1 -1
- package/dist/{proposal-findings-CfRFCFXS.js → proposal-findings-BCd4KjLy.js} +2 -2
- package/dist/{proposal-findings-CfRFCFXS.js.map → proposal-findings-BCd4KjLy.js.map} +1 -1
- package/dist/rl.d.ts +1 -1
- package/dist/rollout/index.d.ts +2 -2
- package/dist/rollout/index.js +1 -1
- package/dist/{rollout--rSr43Pd.js → rollout-CbHMVoDr.js} +2 -2
- package/dist/{rollout--rSr43Pd.js.map → rollout-CbHMVoDr.js.map} +1 -1
- package/dist/{run-improvement-loop-BeHu5D9Z.d.ts → run-improvement-loop-BPhkYKV2.d.ts} +5 -5
- package/dist/{run-improvement-loop-BeHu5D9Z.d.ts.map → run-improvement-loop-BPhkYKV2.d.ts.map} +1 -1
- package/dist/search/index.d.ts +2 -2
- package/dist/search/index.js +2 -2
- package/dist/{search-kernel-mZc79S6N.js → search-kernel-BkkDo75N.js} +2 -2
- package/dist/{search-kernel-mZc79S6N.js.map → search-kernel-BkkDo75N.js.map} +1 -1
- package/dist/{search-kernel-CJZ-ZSV1.d.ts → search-kernel-CDSEWa2X.d.ts} +2 -2
- package/dist/{search-kernel-CJZ-ZSV1.d.ts.map → search-kernel-CDSEWa2X.d.ts.map} +1 -1
- package/dist/{search-ledger-C7t68cmy.js → search-ledger-sormHFLS.js} +17 -1
- package/dist/search-ledger-sormHFLS.js.map +1 -0
- package/dist/{search-shipper-CmDW9dU6.js → search-shipper-BJ2Bkx2q.js} +2 -2
- package/dist/{search-shipper-CmDW9dU6.js.map → search-shipper-BJ2Bkx2q.js.map} +1 -1
- package/dist/{search-summary-CCgP2qXz.js → search-summary-DMckFUNY.js} +2 -2
- package/dist/{search-summary-CCgP2qXz.js.map → search-summary-DMckFUNY.js.map} +1 -1
- package/dist/{self-improve-C_Bcdmv8.js → self-improve-CMrPmjYE.js} +5 -5
- package/dist/{self-improve-C_Bcdmv8.js.map → self-improve-CMrPmjYE.js.map} +1 -1
- package/dist/{self-improve-B1fsNejr.d.ts → self-improve-D0TtJz4e.d.ts} +5 -5
- package/dist/{self-improve-B1fsNejr.d.ts.map → self-improve-D0TtJz4e.d.ts.map} +1 -1
- package/dist/{server-aZFmRucn.js → server-B-7vXS9T.js} +4 -4
- package/dist/{server-aZFmRucn.js.map → server-B-7vXS9T.js.map} +1 -1
- package/dist/{skillopt-optimization-method-DHk1K757.js → skillopt-optimization-method-D-BPMi8J.js} +9 -9
- package/dist/{skillopt-optimization-method-DHk1K757.js.map → skillopt-optimization-method-D-BPMi8J.js.map} +1 -1
- package/dist/{store-otlp-CdeW7NWq.js → store-otlp-DL30pdXE.js} +2 -2
- package/dist/{store-otlp-CdeW7NWq.js.map → store-otlp-DL30pdXE.js.map} +1 -1
- package/dist/{store-tool-spans-CVX-jfkk.js → store-tool-spans-DRdpbrnb.js} +3 -3
- package/dist/{store-tool-spans-CVX-jfkk.js.map → store-tool-spans-DRdpbrnb.js.map} +1 -1
- package/dist/{systemone-4PadCE4C.d.ts → systemone-C26IFS-a.d.ts} +3 -3
- package/dist/{systemone-4PadCE4C.d.ts.map → systemone-C26IFS-a.d.ts.map} +1 -1
- package/dist/systemone.d.ts +2 -2
- package/dist/systemone.js +2 -2
- package/dist/traces.js +3 -3
- package/dist/{tree-CiIe-f3f.js → tree-BX9ykHi3.js} +3 -3
- package/dist/{tree-CiIe-f3f.js.map → tree-BX9ykHi3.js.map} +1 -1
- package/dist/{types-D5XtEH9Q.d.ts → types-CBT-XcX5.d.ts} +14 -1
- package/dist/types-CBT-XcX5.d.ts.map +1 -0
- package/dist/{types-Bte3EsFQ.d.ts → types-CYPV2dlR.d.ts} +2 -2
- package/dist/{types-Bte3EsFQ.d.ts.map → types-CYPV2dlR.d.ts.map} +1 -1
- package/dist/wire/index.js +1 -1
- package/docs/feature-guide.md +2 -0
- package/docs/public-api.md +16 -10
- package/docs/skill-eval.md +103 -0
- package/package.json +4 -2
- package/dist/benchmark-command-CGQXNFj7.js.map +0 -1
- package/dist/cost-ledger-C5CCidPm.js.map +0 -1
- package/dist/index-Cn9gB5Ca.d.ts.map +0 -1
- package/dist/search-ledger-C7t68cmy.js.map +0 -1
- package/dist/types-D5XtEH9Q.d.ts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/multishot/conversation-conditions.ts","../../src/multishot/conversation-evidence.ts","../../src/multishot/cost.ts","../../src/multishot/default-tools.ts","../../src/multishot/shape-defaults.ts","../../src/multishot/conversation.ts","../../src/multishot/rollout.ts","../../src/multishot/realism.ts","../../src/multishot/adversarial-user.ts","../../src/multishot/judges.ts","../../src/multishot/multishot.ts","../../src/multishot/matrix.ts"],"sourcesContent":["// Equivalent conditions for comparing conversations.\n//\n// A conversation's outcome depends on the simulated user as much as on the\n// agent: Seshadri et al. (arXiv 2601.17087) measure agent success moving up\n// to 9 points across user models on one benchmark. So the simulated user is\n// part of the measurement identity, and two candidates are compared only when\n// every paired conversation met the same user on the same seed.\n//\n// What holds that:\n// - The user is outside the candidate surface by construction:\n// `multishotRollout` builds it from the scenario and its fixed options.\n// - `dispatchRef` hashes the user options, so caches and premeasured\n// baselines never cross users.\n// - `assertSameSimulatedUser` refuses paired cells with different identities\n// or seeds, and `conversationGate` runs it before any decision.\n// - `conversationJudge` scores only conversations whose agent side was the\n// candidate, so the user side can never be optimized on the agent's success.\n\nimport { defaultProductionGate } from '../campaign/gates/default-production-gate'\nimport type { Gate, GateContext, JudgeConfig, JudgeScore } from '../campaign/types'\nimport type { ConversationArtifact, ConversationScenario } from './rollout'\n\nexport interface SimulatedUserMismatch {\n cellId: string\n /** `missing`: a cell carries no identity. `simulated-user`: the identities\n * differ. `seed`: the same user ran on different seeds. */\n reason: 'missing' | 'simulated-user' | 'seed'\n detail: string\n}\n\n/** Paired conversations did not meet the same simulated user on the same seed. */\nexport class SimulatedUserMismatchError extends Error {\n readonly mismatches: SimulatedUserMismatch[]\n constructor(mismatches: SimulatedUserMismatch[]) {\n const shown = listSome(\n mismatches.map((row) => `${row.cellId}: ${row.detail}`),\n '; ',\n )\n super(\n `${mismatches.length} paired conversation(s) did not meet the same simulated user ` +\n `on the same seed, so the comparison is refused (${shown})`,\n )\n this.name = 'SimulatedUserMismatchError'\n this.mismatches = mismatches\n }\n}\n\n/** A score on the agent's success was asked to read a conversation whose\n * user side was the candidate. Optimizing the user to raise the agent's\n * success would teach it to be easy; the user side's objective is the\n * agent's failure rate, through `improveAdversarialUser` only. */\nexport class UserSideObjectiveError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'UserSideObjectiveError'\n }\n}\n\n/** A scenario an adversarial-user search emitted reached a held-out split. */\nexport class AdversarialScenarioInHeldOutError extends Error {\n readonly scenarioIds: string[]\n constructor(scenarioIds: string[]) {\n super(\n `held-out split contains ${scenarioIds.length} scenario(s) an adversarial-user search ` +\n `emitted (${listSome(scenarioIds)}); they train the agent side and never measure it`,\n )\n this.name = 'AdversarialScenarioInHeldOutError'\n this.scenarioIds = scenarioIds\n }\n}\n\n/**\n * Refuse a comparison whose paired conversations (same cell id) met different\n * simulated users or ran on different seeds, or carry no identity to show it.\n * Returns the number of pairs compared.\n */\nexport function assertSameSimulatedUser(\n baseline: ReadonlyMap<string, ConversationArtifact>,\n candidate: ReadonlyMap<string, ConversationArtifact>,\n): number {\n const mismatches: SimulatedUserMismatch[] = []\n let pairs = 0\n for (const [cellId, other] of candidate) {\n const base = baseline.get(cellId)\n if (base === undefined) continue\n pairs += 1\n const missing = (['baseline', 'candidate'] as const).filter(\n (arm) => !hasIdentity(arm === 'baseline' ? base : other),\n )\n if (missing.length > 0) {\n mismatches.push({\n cellId,\n reason: 'missing',\n detail: `${missing.join(' and ')} carries no simulated-user identity`,\n })\n } else if (base.simulatedUser.digest !== other.simulatedUser.digest) {\n mismatches.push({\n cellId,\n reason: 'simulated-user',\n detail:\n `baseline user ${base.simulatedUser.digest} (${base.simulatedUser.model}), ` +\n `candidate user ${other.simulatedUser.digest} (${other.simulatedUser.model})`,\n })\n } else if (base.seed !== other.seed) {\n mismatches.push({\n cellId,\n reason: 'seed',\n detail: `baseline seed ${base.seed}, candidate seed ${other.seed}`,\n })\n }\n }\n if (mismatches.length > 0) throw new SimulatedUserMismatchError(mismatches)\n return pairs\n}\n\n/** The first three items, and an ellipsis when there are more. Package-internal. */\nexport function listSome(items: readonly string[], separator = ', '): string {\n return [...items.slice(0, 3), ...(items.length > 3 ? ['…'] : [])].join(separator)\n}\n\nfunction hasIdentity(artifact: ConversationArtifact | undefined): boolean {\n return (\n typeof artifact?.simulatedUser?.digest === 'string' &&\n artifact.simulatedUser.digest.length > 0 &&\n Number.isFinite(artifact.seed)\n )\n}\n\n/** Refuse a held-out split that contains an adversarial-user scenario.\n * `conversationGate` runs it before the held-out run starts; run it on the\n * test cases of any comparison that does not go through that gate. */\nexport function assertHeldOutExcludesAdversarial(scenarios: readonly ConversationScenario[]): void {\n const emitted = scenarios.filter((scenario) => scenario.origin?.kind === 'adversarial-user')\n if (emitted.length > 0) {\n throw new AdversarialScenarioInHeldOutError(emitted.map((scenario) => scenario.id))\n }\n}\n\nexport interface ConversationJudgeOptions<TScenario extends ConversationScenario> {\n /** Scores a passed conversation on [0, 1] for what the outcome check does\n * not see, such as tone. A failed conversation scores 0 without it. */\n semantic?: JudgeConfig<ConversationArtifact, TScenario>\n}\n\n/**\n * Score the agent side of a conversation: 0 when the code-checked outcome\n * failed, else 1, or the semantic judge's composite when one is given. The\n * `outcome` dimension is always the code check. Refuses a conversation whose\n * user side was the candidate.\n */\nexport function conversationJudge<TScenario extends ConversationScenario>(\n opts: ConversationJudgeOptions<TScenario> = {},\n): JudgeConfig<ConversationArtifact, TScenario> {\n const semantic = opts.semantic\n return {\n name: 'conversation-outcome',\n judgeVersion: `agent-eval:conversation-outcome:v1${semantic ? `+${semantic.name}:${semantic.judgeVersion ?? 'unversioned'}` : ''}`,\n dimensions: [\n { key: 'outcome', description: '1 when the code-checked outcome passed, else 0' },\n ...(semantic?.dimensions ?? []).filter((dimension) => dimension.key !== 'outcome'),\n ],\n score(input) {\n if (input.artifact.optimizedRole !== 'agent') {\n throw new UserSideObjectiveError(\n `conversation '${input.scenario.id}' optimized the user side; the agent-success ` +\n 'score reads agent-side conversations only, and improveAdversarialUser scores ' +\n \"the user side on the agent's failure rate\",\n )\n }\n const { passed, detail } = input.artifact.outcome\n if (!passed || !semantic) {\n return { dimensions: { outcome: passed ? 1 : 0 }, composite: passed ? 1 : 0, notes: detail }\n }\n return Promise.resolve(semantic.score(input)).then(\n (score): JudgeScore => ({\n ...score,\n dimensions: { ...score.dimensions, outcome: 1 },\n notes: `${detail}\\n${score.notes}`,\n }),\n )\n },\n }\n}\n\nexport interface ConversationGateOptions<TScenario extends ConversationScenario> {\n /** The decision once conditions hold. Default `defaultProductionGate` over\n * the gate's held-out scenarios with `deltaThreshold`. */\n inner?: Gate<ConversationArtifact, TScenario>\n /** Default 0.05, as `selfImprove`'s default gate. */\n deltaThreshold?: number\n independentUnitByScenarioId?: ReadonlyMap<string, string>\n}\n\n/**\n * The promotion gate for conversations: refuses a held-out split containing\n * adversarial-user scenarios and any comparison whose arms met different\n * simulated users or seeds, then decides with `inner`.\n */\nexport function conversationGate<TScenario extends ConversationScenario>(\n opts: ConversationGateOptions<TScenario> = {},\n): Gate<ConversationArtifact, TScenario> {\n return {\n name: 'conversation',\n admitHeldOut: assertHeldOutExcludesAdversarial,\n async decide(ctx: GateContext<ConversationArtifact, TScenario>) {\n assertHeldOutExcludesAdversarial(ctx.scenarios)\n if (ctx.baselineArtifacts === undefined) {\n throw new SimulatedUserMismatchError([\n {\n cellId: '*',\n reason: 'missing',\n detail: 'the baseline arm carries no simulated-user identity: no baseline artifacts',\n },\n ])\n }\n const pairedConversations = assertSameSimulatedUser(\n ctx.baselineArtifacts,\n ctx.candidateArtifacts,\n )\n if (ctx.neutralizedArtifacts) {\n assertSameSimulatedUser(ctx.baselineArtifacts, ctx.neutralizedArtifacts)\n }\n const inner =\n opts.inner ??\n defaultProductionGate<ConversationArtifact, TScenario>({\n holdoutScenarios: ctx.scenarios,\n deltaThreshold: opts.deltaThreshold ?? 0.05,\n ...(opts.independentUnitByScenarioId\n ? { independentUnitByScenarioId: opts.independentUnitByScenarioId }\n : {}),\n })\n const result = await inner.decide(ctx)\n return {\n ...result,\n contributingGates: [\n {\n name: 'simulated-user-identity',\n status: 'pass' as const,\n detail: { pairedConversations },\n },\n ...result.contributingGates,\n ],\n }\n },\n }\n}\n","// What an optimizer is shown about one conversation. `describeConversation` is\n// the `describeArtifact` for a `ConversationArtifact`: the native reflective\n// proposer reads its JSON text in `scenarios[].emitted`, and GEPA and SkillOpt\n// receive the same value as each evaluation's evidence. Its JSON is kept\n// within `EMITTED_EVIDENCE_MAX_CHARS`, so the excerpt the native path applies\n// never cuts it and both paths carry the same object.\n\nimport { EMITTED_EVIDENCE_MAX_CHARS, excerptEvidence } from '../reflective-mutation'\nimport type { ConversationArtifact, ConversationEnding } from './rollout'\nimport type { MultishotMessage } from './types'\n\nexport interface ConversationEvidence {\n /** The code-checked outcome. */\n outcome: { passed: boolean; detail: string }\n /** How the simulated user ended the conversation. */\n ending: ConversationEnding\n agentTurns: number\n /** The driver turn at which the user first pushed back; `null` when the\n * user never did, `'undetermined'` when the rollout has no pushback rule. */\n firstPushbackTurn: number | null | 'undetermined'\n /** The transcript, its head and tail kept when it is long. */\n transcript: string\n}\n\nconst DETAIL_MAX_CHARS = 400\nconst TOOL_RESULT_MAX_CHARS = 300\n\n/** The evidence a reflection reads for one conversation. */\nexport function describeConversation(artifact: ConversationArtifact): ConversationEvidence {\n const base: ConversationEvidence = {\n outcome: {\n passed: artifact.outcome.passed,\n detail: excerptEvidence(artifact.outcome.detail, DETAIL_MAX_CHARS),\n },\n ending: { kind: artifact.ending.kind, turn: artifact.ending.turn },\n agentTurns: artifact.agentTurns,\n firstPushbackTurn: artifact.pushback.determined ? artifact.pushback.firstTurn : 'undetermined',\n transcript: '',\n }\n const full = renderTranscript(artifact.transcript)\n // JSON escaping can lengthen the kept text, so shrink the budget by the\n // overshoot until the whole object fits.\n let budget = EMITTED_EVIDENCE_MAX_CHARS - JSON.stringify(base).length\n let evidence = { ...base, transcript: excerptEvidence(full, Math.max(0, budget)) }\n for (\n let length = JSON.stringify(evidence).length;\n length > EMITTED_EVIDENCE_MAX_CHARS && budget > 0;\n length = JSON.stringify(evidence).length\n ) {\n budget -= length - EMITTED_EVIDENCE_MAX_CHARS\n evidence = { ...base, transcript: excerptEvidence(full, Math.max(0, budget)) }\n }\n return evidence\n}\n\nfunction renderTranscript(transcript: readonly MultishotMessage[]): string {\n return transcript\n .map((message) => {\n if (message.role === 'tool') {\n return `tool: ${excerptEvidence(message.content, TOOL_RESULT_MAX_CHARS)}`\n }\n if (message.role === 'user') return `user: ${message.content}`\n const calls = message.toolCalls?.map((call) => call.name) ?? []\n const called = calls.length > 0 ? ` [called ${calls.join(', ')}]` : ''\n return `agent: ${message.content}${called}`\n })\n .join('\\n')\n}\n","// Per-model cost estimator for multishot legs whose transport reported token\n// usage but no billed amount.\n\n/**\n * Rough per-model cost estimate from token counts. Underestimates Anthropic,\n * overestimates open-weight models — accurate enough for a cost ceiling, and\n * never presented as a billed amount: a leg metered from this table is\n * recorded with `estimated` provenance.\n */\nexport function estimateMultishotCost(\n model: string,\n usage?: { prompt_tokens?: number; completion_tokens?: number },\n): number {\n if (!usage) return 0\n const inputTok = usage.prompt_tokens ?? 0\n const outputTok = usage.completion_tokens ?? 0\n let inPer1k = 0.003\n let outPer1k = 0.015\n if (model.includes('gpt-4o-mini') || model.includes('gpt-6-luna')) {\n inPer1k = 0.00015\n outPer1k = 0.0006\n } else if (model.includes('gpt-5.4') || model.includes('claude-sonnet')) {\n inPer1k = 0.003\n outPer1k = 0.015\n } else if (model.includes('kimi') || model.includes('glm') || model.includes('deepseek')) {\n inPer1k = 0.0005\n outPer1k = 0.002\n }\n return (inputTok * inPer1k + outputTok * outPer1k) / 1000\n}\n","// Default delegate_research + delegate_code tools and their inline executors.\n//\n// Consumers can override either by passing their own tools + executors to\n// runMultishot. The defaults are sufficient for most domains — point the\n// researcher system prompt at your domain's citation style and the coder\n// at your preferred language.\n\nimport { estimateMultishotCost } from './cost'\nimport type { MultishotToolDefinition, MultishotToolExecutor } from './types'\n\nconst DEFAULT_RESEARCHER_MODEL = 'openai/gpt-6-luna'\nexport const DEFAULT_CODER_MODEL = 'openai/gpt-6-luna'\n\nexport interface DefaultResearcherConfig {\n /** Replace the system prompt to bias the researcher toward a domain's\n * citation style. Defaults to a generic \"cite sources by name\" prompt. */\n systemPrompt?: string\n model?: string\n}\n\nexport interface DefaultCoderConfig {\n /** Replace the system prompt to bias the coder toward a language /\n * framework / artifact style. */\n systemPrompt?: string\n model?: string\n}\n\nconst GENERIC_RESEARCHER_SYSTEM =\n 'You are a research specialist. Return a markdown brief with 3-5 findings. Each finding cites a specific source by name. Add a confidence level (high/medium/low) per finding. No fluff, no preamble.'\n\nconst GENERIC_CODER_SYSTEM =\n 'You are an expert engineer. Output ONE fenced code block containing the complete solution. Inline-comment non-obvious decisions. No explanation outside the block.'\n\nconst DEFAULT_DELEGATE_RESEARCH_TOOL: MultishotToolDefinition = {\n type: 'function',\n function: {\n name: 'delegate_research',\n description:\n 'Research a topic deeply via specialist. Returns evidence-bearing items with citations. Use for audience research, competitive intel, regulatory landscape, market data, citation-grounded analysis.',\n parameters: {\n type: 'object',\n properties: {\n question: { type: 'string', description: 'Specific question to research' },\n scope: {\n type: 'string',\n description: 'Optional scope: time window, geography, jurisdiction, segment',\n },\n },\n required: ['question'],\n },\n },\n}\n\nconst DEFAULT_DELEGATE_CODE_TOOL: MultishotToolDefinition = {\n type: 'function',\n function: {\n name: 'delegate_code',\n description:\n 'Generate a runnable script, template, pipeline, or tool via specialist. Returns complete working code or structured markdown. Use for content pipelines, calc snippets, dashboards, compliance checklists, deadline trackers.',\n parameters: {\n type: 'object',\n properties: {\n goal: { type: 'string', description: 'What the code must accomplish' },\n language: {\n type: 'string',\n description: 'Optional language preference (default: TypeScript)',\n },\n },\n required: ['goal'],\n },\n },\n}\n\nfunction createResearchExecutor(config: DefaultResearcherConfig = {}): MultishotToolExecutor {\n const systemPrompt = config.systemPrompt ?? GENERIC_RESEARCHER_SYSTEM\n const model = config.model ?? DEFAULT_RESEARCHER_MODEL\n return async (args, ctx) => {\n const question = String(args.question ?? '')\n const scope = args.scope ? String(args.scope) : undefined\n const { message, usage, costUsd } = await ctx.transport({\n model,\n temperature: 0.3,\n maxTokens: 1800,\n messages: [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: `Research: ${question}${scope ? `\\nScope: ${scope}` : ''}` },\n ],\n signal: ctx.signal,\n })\n return {\n content: message.content ?? '',\n costUsd: costUsd ?? estimateMultishotCost(model, usage),\n }\n }\n}\n\nfunction createCodeExecutor(config: DefaultCoderConfig = {}): MultishotToolExecutor {\n const systemPrompt = config.systemPrompt ?? GENERIC_CODER_SYSTEM\n const model = config.model ?? DEFAULT_CODER_MODEL\n return async (args, ctx) => {\n const goal = String(args.goal ?? '')\n const language = args.language ? String(args.language) : 'TypeScript'\n const { message, usage, costUsd } = await ctx.transport({\n model,\n temperature: 0.2,\n maxTokens: 2000,\n messages: [\n { role: 'system', content: `${systemPrompt}\\n\\nLanguage: ${language}` },\n { role: 'user', content: `Produce: ${goal}` },\n ],\n signal: ctx.signal,\n })\n return {\n content: message.content ?? '',\n costUsd: costUsd ?? estimateMultishotCost(model, usage),\n }\n }\n}\n\nexport interface DefaultToolsConfig {\n research?: DefaultResearcherConfig\n code?: DefaultCoderConfig\n /** When true (default), each tool result is recorded as a typed artifact:\n * research → type='research', code → type='code'. */\n recordArtifacts?: boolean\n}\n\nexport interface DefaultToolsBundle {\n tools: MultishotToolDefinition[]\n executors: Record<string, MultishotToolExecutor>\n artifactTypeFor: (toolName: string) => string | undefined\n}\n\nexport function defaultDelegationTools(config: DefaultToolsConfig = {}): DefaultToolsBundle {\n return {\n tools: [DEFAULT_DELEGATE_RESEARCH_TOOL, DEFAULT_DELEGATE_CODE_TOOL],\n executors: {\n delegate_research: createResearchExecutor(config.research),\n delegate_code: createCodeExecutor(config.code),\n },\n artifactTypeFor: (name) =>\n name === 'delegate_research' ? 'research' : name === 'delegate_code' ? 'code' : undefined,\n }\n}\n","// Profile-derived defaults for MultishotShape — the pure-profile path.\n//\n// `MultishotShape`'s callbacks were REQUIRED beside `profile: AgentProfile`,\n// which mixed the abstractions: the node under test was a profile, but the\n// simulated user's role could only be expressed as code. These defaults make\n// the callbacks optional — a pure-profile call works, and the derived prompts\n// are plain data (a pure function of profile + persona payload), so an\n// optimizer can sweep them (tangle-network/agent-runtime#694).\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport type { MultishotPersona, MultishotShape } from './types'\n\n/** Persona payload rendered as stable `- key: value` lines. `id` is identity,\n * not voice, and structured values are serialized so nothing is dropped. */\nfunction renderPersonaFacts(persona: MultishotPersona): string {\n const lines: string[] = []\n for (const [key, value] of Object.entries(persona)) {\n if (key === 'id' || value === undefined) continue\n const rendered =\n typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean'\n ? String(value)\n : JSON.stringify(value)\n lines.push(`- ${key}: ${rendered}`)\n }\n return lines.join('\\n')\n}\n\n/** Default opening user message: the persona introduces itself with its whole\n * payload and asks the agent (as described by the profile) to take over. */\nfunction defaultMultishotOpener(profile: AgentProfile, persona: MultishotPersona): string {\n const facts = renderPersonaFacts(persona)\n const agentDescription = profile.description ?? profile.name ?? 'the agent'\n return [\n `Hi — I'm reaching out to ${agentDescription} for help. My situation:`,\n facts.length > 0 ? facts : `- (no details provided beyond id: ${persona.id})`,\n '',\n 'Tell me what you need from me, and get started on my case.',\n ].join('\\n')\n}\n\n/** Default driver system prompt: roleplay the persona from its payload, stay\n * in character, push back on vague answers, and never go silent. */\nfunction defaultMultishotDriverSystemPrompt(\n profile: AgentProfile,\n persona: MultishotPersona,\n): string {\n const facts = renderPersonaFacts(persona)\n const agentDescription = profile.description ?? profile.name ?? 'an AI agent'\n return [\n `You are role-playing a real person (persona \"${persona.id}\") talking to ${agentDescription}.`,\n facts.length > 0 ? `Who you are:\\n${facts}` : '',\n '',\n 'How to behave:',\n '- Stay in character: first person, realistic voice, concrete details from your situation.',\n '- Judge every reply by whether it actually moves YOUR case forward. Push back on vague, hedged, or generic answers and demand specifics.',\n \"- Answer the agent's questions with information consistent with who you are; invent plausible details rather than stalling.\",\n '- Never go silent: always produce a substantive next message.',\n '- Output ONLY your next message to the agent — no meta-commentary, no stage directions.',\n ]\n .filter((block) => block.length > 0)\n .join('\\n')\n}\n\n/** The fully-resolved shape for a profile: caller overrides win, the\n * profile-derived defaults fill the rest. */\nexport function defaultShapeFromProfile<TPersona extends MultishotPersona>(\n profile: AgentProfile,\n shape?: MultishotShape<TPersona>,\n): Required<MultishotShape<TPersona>> {\n return {\n buildOpener: shape?.buildOpener ?? ((persona) => defaultMultishotOpener(profile, persona)),\n buildDriverSystemPrompt:\n shape?.buildDriverSystemPrompt ??\n ((persona) => defaultMultishotDriverSystemPrompt(profile, persona)),\n }\n}\n","// The multishot conversation's two legs, separable from the loop that orders\n// them.\n//\n// `runMultishot` orders the legs as a plain turn loop. A caller that orders\n// them another way — a Runtime flow graph, a scheduler, a replay harness —\n// drives the same legs through `runMultishotConversation`, so the transcript,\n// artifacts, tool-call count, driver point of view and cost accounting stay\n// this package's single implementation.\n//\n// agent-eval owns no model transport: every leg runs on a MultishotTransport\n// the caller supplies, so no provider credential enters this package.\n\nimport { withCellSpend } from '../matrix'\nimport { estimateMultishotCost } from './cost'\nimport { defaultDelegationTools } from './default-tools'\nimport type { RunMultishotOptions } from './multishot'\nimport { defaultShapeFromProfile } from './shape-defaults'\nimport {\n type MultishotArtifact,\n MultishotDriverEmptyError,\n MultishotFatalToolError,\n type MultishotMessage,\n type MultishotPersona,\n type MultishotResult,\n type MultishotTransport,\n type MultishotTransportResponse,\n} from './types'\n\n/** Prompt and completion tokens one leg reported. */\nexport interface MultishotLegTokens {\n input: number\n output: number\n}\n\n/** What one leg spent: its tokens and the USD it added to the conversation's\n * cost (provider-reported, else estimated from usage; tool executor spend\n * included). */\nexport interface MultishotLegSpend {\n tokens: MultishotLegTokens\n usd: number\n}\n\n/** One conversation's state and legs. Each leg appends to the shared\n * transcript; the caller decides the order in which legs run. */\nexport interface MultishotConversation {\n /** Agent turns the conversation is configured for (`opts.maxTurns ?? 10`). */\n readonly maxTurns: number\n /** The model the agent leg runs on. */\n readonly agentModel: string\n /** The primary simulated-user model. */\n readonly driverModel: string\n /** The persona's first message, already in the transcript. */\n readonly opener: string\n /** The simulated user's system prompt. */\n readonly driverSystemPrompt: string\n /** One agent turn: inference, inline tool execution and follow-up inference,\n * until the agent answers without tools. Throws on abort, on a fatal tool\n * error and on the per-turn tool dispatch cap. */\n agentTurn(turn: number): Promise<MultishotLegSpend>\n /** The simulated user's reply to the transcript so far, appended for the\n * next agent turn. Retries an empty reply once per model, rotates through\n * the fallback models, then throws `MultishotDriverEmptyError`. */\n driverTurn(turn: number): Promise<MultishotLegSpend & { content: string }>\n}\n\n/** Orders the legs of one conversation. Resolves when the conversation is done. */\nexport type MultishotConversationDriver = (conversation: MultishotConversation) => Promise<void>\n\ninterface ConversationMeter {\n costUsd: number\n startedAt: number\n /** True once a call contributed a fabricated `0` — no provider cost and no\n * usage to price. `costUsd` is a subtotal from that point on. */\n uncaptured: boolean\n}\n\n/**\n * Run one multishot conversation whose leg order `drive` decides.\n *\n * Returns the conversation's `MultishotResult`. When any leg or `drive` throws,\n * the error is rethrown carrying the spend so far (`withCellSpend`), so a\n * matrix bills the failed cell for the turns it already paid for.\n */\nexport async function runMultishotConversation<TPersona extends MultishotPersona>(\n opts: RunMultishotOptions<TPersona>,\n drive: MultishotConversationDriver,\n): Promise<MultishotResult> {\n const meter: ConversationMeter = { costUsd: 0, startedAt: Date.now(), uncaptured: false }\n try {\n const state = openConversation(opts, meter)\n await drive(state.conversation)\n return {\n transcript: state.transcript,\n artifacts: state.artifacts,\n toolCalls: state.toolCalls(),\n durationMs: Date.now() - meter.startedAt,\n costUsd: meter.costUsd,\n // A shot that priced every call reports a complete estimate. One that had\n // a call the router priced at nothing reports a subtotal, so the cell is\n // recorded as under-counted rather than as a complete estimate.\n costProvenance: meter.uncaptured\n ? { kind: 'uncaptured', usd: null }\n : { kind: 'estimated', usd: meter.costUsd },\n }\n } catch (err) {\n throw withCellSpend(err, {\n costUsd: meter.costUsd,\n durationMs: Date.now() - meter.startedAt,\n kind: meter.uncaptured ? 'uncaptured' : 'estimated',\n })\n }\n}\n\nfunction openConversation<TPersona extends MultishotPersona>(\n opts: RunMultishotOptions<TPersona>,\n meter: ConversationMeter,\n): {\n conversation: MultishotConversation\n transcript: MultishotMessage[]\n artifacts: MultishotArtifact[]\n toolCalls: () => number\n} {\n const maxTurns = opts.maxTurns ?? 10\n const maxToolDispatches = opts.maxToolDispatches ?? 4\n const agentModel = opts.agentModel ?? 'openai/gpt-5.4'\n const driverModel = opts.driverModel ?? 'openai/gpt-6-luna'\n const driverModels = [driverModel, ...(opts.driverFallbackModels ?? [])]\n const agentMaxTokens = opts.agentMaxTokens ?? 2500\n const toolFollowupMaxTokens = opts.toolFollowupMaxTokens ?? 2000\n const driverMaxTokens = opts.driverMaxTokens ?? 600\n\n const bundle =\n opts.tools && opts.toolExecutors\n ? {\n tools: opts.tools,\n executors: opts.toolExecutors,\n artifactTypeFor: opts.artifactTypeFor ?? (() => undefined),\n }\n : defaultDelegationTools()\n const tools = opts.tools ?? bundle.tools\n const executors = opts.toolExecutors ?? bundle.executors\n const artifactTypeFor = opts.artifactTypeFor ?? bundle.artifactTypeFor\n\n const agentTransport = opts.agentTransport\n const driverTransport = opts.driverTransport\n const toolTransport = opts.toolTransport ?? agentTransport\n\n const shape = defaultShapeFromProfile(opts.profile, opts.shape)\n\n const transcript: MultishotMessage[] = []\n const artifacts: MultishotArtifact[] = []\n let toolCalls = 0\n\n const opener = shape.buildOpener(opts.persona)\n transcript.push({ role: 'user', content: opener })\n\n const systemPrompt = [opts.profile.prompt?.systemPrompt, opts.profile.prompt?.appendSystemPrompt]\n .filter((value): value is string => Boolean(value))\n .join('\\n\\n')\n const agentMessages: Array<Record<string, unknown>> = [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: opener },\n ]\n const driverSystemPrompt = shape.buildDriverSystemPrompt(opts.persona)\n\n async function agentTurn(turn: number): Promise<MultishotLegSpend> {\n if (opts.signal?.aborted) throw new Error('multishot aborted')\n const usdBefore = meter.costUsd\n const tokens = { input: 0, output: 0 }\n let dispatchesThisTurn = 0\n while (true) {\n const {\n message: agentMsg,\n usage: agentUsage,\n costUsd: agentCostUsd,\n } = await agentTransport({\n model: agentModel,\n messages: agentMessages,\n tools,\n temperature: 0.7,\n maxTokens: dispatchesThisTurn === 0 ? agentMaxTokens : toolFollowupMaxTokens,\n signal: opts.signal,\n })\n meter.costUsd += agentCostUsd ?? estimateMultishotCost(agentModel, agentUsage)\n if (agentCostUsd === undefined && agentUsage === undefined) meter.uncaptured = true\n tokens.input += agentUsage?.prompt_tokens ?? 0\n tokens.output += agentUsage?.completion_tokens ?? 0\n\n const agentText = (agentMsg.content ?? '').trim()\n const agentToolCalls = (agentMsg.tool_calls ?? []).map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n args: (() => {\n try {\n return JSON.parse(tc.function.arguments) as Record<string, unknown>\n } catch {\n return {} as Record<string, unknown>\n }\n })(),\n }))\n\n agentMessages.push({\n role: 'assistant',\n content: agentText || null,\n ...(agentMsg.tool_calls?.length ? { tool_calls: agentMsg.tool_calls } : {}),\n })\n transcript.push({\n role: 'assistant',\n content: agentText,\n toolCalls: agentToolCalls.length > 0 ? agentToolCalls : undefined,\n })\n\n if (agentToolCalls.length === 0) break\n dispatchesThisTurn += agentToolCalls.length\n if (dispatchesThisTurn > maxToolDispatches) {\n throw new Error(\n `multishot: tool dispatch cap exceeded (${dispatchesThisTurn}/${maxToolDispatches}) on turn ${turn}`,\n )\n }\n\n for (const tc of agentToolCalls) {\n toolCalls++\n let toolResult = ''\n try {\n const executor = executors[tc.name]\n if (!executor) {\n toolResult = JSON.stringify({ error: `unknown tool ${tc.name}` })\n } else {\n const r = await executor(tc.args, { transport: toolTransport, signal: opts.signal })\n toolResult = r.content\n meter.costUsd += r.costUsd\n const artifactType = artifactTypeFor(tc.name)\n if (artifactType) {\n artifacts.push({\n type: artifactType,\n turn,\n invocation: { name: tc.name, args: tc.args },\n content: toolResult,\n })\n }\n }\n } catch (err) {\n if (err instanceof MultishotFatalToolError) throw err\n toolResult = JSON.stringify({ error: err instanceof Error ? err.message : String(err) })\n }\n agentMessages.push({ role: 'tool', tool_call_id: tc.id, content: toolResult || 'done' })\n transcript.push({ role: 'tool', content: toolResult || 'done', toolCallId: tc.id })\n }\n }\n return { tokens, usd: meter.costUsd - usdBefore }\n }\n\n // Every driver attempt is charged, including the empty ones that force a\n // retry and the ones that precede `MultishotDriverEmptyError`: those calls\n // billed the provider whether or not their content was usable.\n async function driverTurn(turn: number): Promise<MultishotLegSpend & { content: string }> {\n const usdBefore = meter.costUsd\n const tokens = { input: 0, output: 0 }\n const content = await requestUserReply({\n models: driverModels,\n messages: driverViewMessages(driverSystemPrompt, transcript),\n transport: driverTransport,\n maxTokens: driverMaxTokens,\n signal: opts.signal,\n turn,\n onResponse: (model, { usage, costUsd }) => {\n meter.costUsd += costUsd ?? estimateMultishotCost(model, usage)\n if (costUsd === undefined && usage === undefined) meter.uncaptured = true\n tokens.input += usage?.prompt_tokens ?? 0\n tokens.output += usage?.completion_tokens ?? 0\n },\n })\n agentMessages.push({ role: 'user', content })\n transcript.push({ role: 'user', content })\n return { content, tokens, usd: meter.costUsd - usdBefore }\n }\n\n return {\n conversation: {\n maxTurns,\n agentModel,\n driverModel,\n opener,\n driverSystemPrompt,\n agentTurn,\n driverTurn,\n },\n transcript,\n artifacts,\n toolCalls: () => toolCalls,\n }\n}\n\n/** The simulated user's next message. The driver must never go silent: an\n * empty reply is retried once per model, the models are tried in order, and\n * then `MultishotDriverEmptyError` is thrown. Every response, empty ones\n * included, reaches `onResponse`, because every attempt was billed. The\n * conversation loop and the realism measure both ask the simulated user\n * through here, so a driver measured against recorded turns is sampled the\n * way a rollout samples it. */\nexport async function requestUserReply(input: {\n models: readonly string[]\n messages: Array<Record<string, unknown>>\n transport: MultishotTransport\n maxTokens: number\n signal?: AbortSignal\n turn: number\n onResponse?: (model: string, response: MultishotTransportResponse) => void\n}): Promise<string> {\n for (const model of input.models) {\n for (let attempt = 0; attempt < 2; attempt++) {\n const response = await input.transport({\n model,\n messages: input.messages,\n temperature: 0.9,\n maxTokens: input.maxTokens,\n signal: input.signal,\n })\n input.onResponse?.(model, response)\n const content = (response.message.content ?? '').trim()\n if (content.length > 0) return content\n }\n }\n throw new MultishotDriverEmptyError(input.turn)\n}\n\n/** The simulated user's view of a transcript, as the driver request's\n * messages. The agent's `assistant` messages become `user` (the agent talking\n * TO the driver); the driver's prior `user` messages become `assistant` (its\n * own earlier replies). Tool messages are hidden. The conversation loop and\n * the realism measure both build the driver's request here, so a driver\n * measured against recorded turns sees exactly what it sees in a rollout. */\nexport function driverViewMessages(\n driverSystemPrompt: string,\n transcript: readonly MultishotMessage[],\n): Array<Record<string, unknown>> {\n const driverMessages: Array<Record<string, unknown>> = [\n { role: 'system', content: driverSystemPrompt },\n ]\n for (const msg of transcript) {\n if (msg.role === 'tool') continue\n const content = driverVisibleContent(msg)\n if (!content) continue\n if (msg.role === 'assistant') driverMessages.push({ role: 'user', content })\n else if (msg.role === 'user') driverMessages.push({ role: 'assistant', content })\n }\n return driverMessages\n}\n\n/** Silent tool-calling agent turns surface to the driver as\n * \"Agent called tools: …\" so the simulated user can react to them. */\nfunction driverVisibleContent(msg: MultishotMessage): string | null {\n const text = msg.content.trim()\n if (text.length > 0) return text\n if (msg.role !== 'assistant' || !msg.toolCalls?.length) return null\n\n const toolNames = msg.toolCalls.map((call) => call.name.trim()).filter(Boolean)\n if (toolNames.length === 0) return 'Agent called tools.'\n return `Agent called ${toolNames.length === 1 ? 'tool' : 'tools'}: ${toolNames.join(', ')}.`\n}\n","// A multishot conversation as an optimization dispatch.\n//\n// `multishotRollout` turns the conversation engine into the\n// `agent(surface, scenario, ctx)` function `selfImprove` and\n// `compareOptimizationMethods` call per cell. The candidate surface becomes\n// the agent's profile; the simulated user is a function of the scenario and\n// the rollout's fixed options alone, so every candidate meets the same user on\n// the same seed. Every leg is a paid call through the cell's `ctx.cost`, the\n// transcript is the artifact, and a code-checked outcome is the objective part\n// of the score. There is one conversation loop: `runMultishotConversation`.\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport type { DispatchContext, MutableSurface, Scenario } from '../campaign/types'\nimport type { CostChannel, CostReceiptInput, MaximumCharge } from '../cost-ledger/contract'\nimport { hashCanonical, jsonDocument } from '../ledger-core/canonical'\nimport type { PersonaRigor } from '../types'\nimport { runMultishotConversation } from './conversation'\nimport { defaultShapeFromProfile } from './shape-defaults'\nimport type {\n MultishotArtifact,\n MultishotMessage,\n MultishotPersona,\n MultishotShape,\n MultishotToolDefinition,\n MultishotToolExecutor,\n MultishotTransport,\n MultishotTransportRequest,\n MultishotTransportResponse,\n} from './types'\n\n/** A scenario a simulated user plays: its persona, and optionally a plan. */\nexport interface ConversationScenario<TPersona extends MultishotPersona = MultishotPersona>\n extends Scenario {\n persona: TPersona\n /** What the simulated user sets out to do in this scenario, appended to its\n * prompt. Part of the simulated-user identity. */\n userPlan?: string\n /** Set on a scenario an adversarial-user search emitted. Such a scenario\n * trains the agent side and never enters a held-out split. */\n origin?: {\n kind: 'adversarial-user'\n sourceScenarioId: string\n planDigest: string\n /** The conversation that showed the scenario can be passed under its\n * plan. Set on every emitted scenario; absent on an unsolvable candidate. */\n solvedBy?: ScenarioSolvedBy\n }\n}\n\n/** A passing conversation of an emitted scenario: which agent passed it, on\n * which seed, and what the outcome check said. */\nexport interface ScenarioSolvedBy {\n agent: 'reference' | 'same'\n profileDigest: string\n seed: number\n detail: string\n}\n\n/** The code-checked outcome of one conversation: the objective part of its score. */\nexport interface ConversationOutcome {\n passed: boolean\n detail: string\n}\n\n/** How a conversation ended. `turn` is the agent turn after which it ended. */\nexport interface ConversationEnding {\n kind: 'signed-off' | 'gave-up' | 'turn-cap'\n turn: number\n}\n\nexport type UserEndingClassification =\n | { kind: 'continue' }\n | { kind: 'signed-off' | 'gave-up'; message: string }\n\n/** How the simulated user ends a conversation before the turn cap. */\nexport interface UserEndingProtocol {\n /** Stable name of `classify`'s rule. Part of the simulated-user identity. */\n ref: string\n /** Appended to the simulated user's prompt. Part of its identity. */\n instructions: string\n /** Reads one simulated-user message. An ending returns the message with its\n * protocol marker removed: the marker is protocol, never something the\n * agent sees or the user said. */\n classify(message: string): UserEndingClassification\n}\n\nconst SIGNED_OFF = '[[signed-off]]'\nconst GAVE_UP = '[[gave-up]]'\n\n/** Ends on `[[signed-off]]` when the user's problem is resolved and on\n * `[[gave-up]]` when the user would stop using the service. */\nexport const DEFAULT_USER_ENDING: UserEndingProtocol = {\n ref: 'agent-eval:user-ending-markers:v1',\n instructions: [\n `When your problem is resolved to your standard, end your message with ${SIGNED_OFF}.`,\n `If you would stop using this service now because the agent is not getting anywhere, end your message with ${GAVE_UP}.`,\n 'Otherwise use neither marker.',\n ].join('\\n'),\n classify(message) {\n for (const [marker, kind] of [\n [SIGNED_OFF, 'signed-off'],\n [GAVE_UP, 'gave-up'],\n ] as const) {\n if (message.includes(marker)) return { kind, message: message.split(marker).join('').trim() }\n }\n return { kind: 'continue' }\n },\n}\n\n/** How each rigor level asks the simulated user to push back, as\n * `PersonaRigor` defines them. */\nconst RIGOR_STANCE: Record<PersonaRigor, string> = {\n cooperative:\n 'Your stance: a forgiving early adopter. Accept a reasonable answer and move on; push back only when the agent is clearly wrong or stuck.',\n demanding:\n 'Your stance: an experienced professional. Reject vague or hedged answers and ask for specifics before you accept anything.',\n relentless:\n 'Your stance: you are reviewing this for someone who will hold you to it. Interrogate every claim and accept nothing the agent has not defended.',\n}\n\n/** The simulated user. Its options never depend on the candidate surface. */\nexport interface SimulatedUserOptions<TPersona extends MultishotPersona = MultishotPersona> {\n model: string\n /** Tried in order when a model returns an empty message twice. */\n fallbackModels?: string[]\n transport: MultishotTransport\n /** Default `'demanding'`. */\n rigor?: PersonaRigor\n /** How the user refers to the agent. Fixed for the simulated user: its\n * prompt never derives from the candidate profile. Default `'an AI agent'`. */\n agentDescription?: string\n /** Overrides the derived opener and prompt; requires `shapeRef`. */\n shape?: MultishotShape<TPersona>\n /** Stable name for `shape`'s callbacks. Part of the simulated-user identity. */\n shapeRef?: string\n /** Maximum output tokens per simulated-user message. Default 600. */\n maxTokens?: number\n /** Default `DEFAULT_USER_ENDING`. */\n ending?: UserEndingProtocol\n /** Recognizes a user message that pushes back on the agent's last reply.\n * Without it the first pushback turn is reported as undetermined. */\n pushback?: (message: string) => boolean\n}\n\n/** The agent leg: everything about the agent except the candidate surface. */\nexport interface ConversationAgentOptions {\n model: string\n transport: MultishotTransport\n /** Tools advertised to the agent. Default: none. */\n tools?: MultishotToolDefinition[]\n /** Required with `tools`. Paid work runs through the executor's\n * `ctx.transport`, which is metered; other executor spend is not. */\n toolExecutors?: Record<string, MultishotToolExecutor>\n artifactTypeFor?: (toolName: string) => string | undefined\n /** Default: `transport`. */\n toolTransport?: MultishotTransport\n maxTokens?: number\n toolFollowupMaxTokens?: number\n maxToolDispatches?: number\n}\n\n/** What the outcome check reads. */\nexport interface ConversationRecord {\n transcript: MultishotMessage[]\n artifacts: MultishotArtifact[]\n ending: ConversationEnding\n}\n\nexport type ConversationLeg = 'agent' | 'user' | 'tool'\n\nexport interface MultishotRolloutOptions<TScenario extends ConversationScenario> {\n agent: ConversationAgentOptions\n /** The agent profile a candidate surface becomes. Default: a text surface\n * is the agent's system prompt; any other surface needs this mapping. */\n profile?: (surface: MutableSurface, scenario: TScenario) => AgentProfile\n user: SimulatedUserOptions<TScenario['persona']>\n /** Agent turns at most. The simulated user may end the conversation sooner. */\n maxTurns: number\n /** Decides by code whether the conversation reached its goal. */\n outcome: (conversation: ConversationRecord, scenario: TScenario) => ConversationOutcome\n /** Hard maximum for one leg's call, required by a capped campaign. */\n maximumCharge?: (\n leg: ConversationLeg,\n request: MultishotTransportRequest,\n ) => MaximumCharge | undefined\n /** Version of behavior the options cannot show, such as tool executor code\n * or the outcome rule. Part of `dispatchRef`. */\n revision?: string\n}\n\n/** Who the agent talked to. Equal digests mean the same simulated user: model,\n * fallbacks, rigor, persona, prompt, opener and ending protocol. */\nexport interface SimulatedUserIdentity {\n digest: string\n model: string\n fallbackModels: string[]\n rigor: PersonaRigor\n personaId: string\n personaDigest: string\n promptDigest: string\n openerDigest: string\n endingRef: string\n shapeRef: string\n maxTokens: number\n}\n\nexport type PushbackReading = { determined: false } | { determined: true; firstTurn: number | null }\n\n/** One conversation, as the dispatch returns it. */\nexport interface ConversationArtifact {\n transcript: MultishotMessage[]\n artifacts: MultishotArtifact[]\n toolCalls: number\n agentTurns: number\n ending: ConversationEnding\n outcome: ConversationOutcome\n /** The driver turn at which the user first pushed back on the agent. */\n pushback: PushbackReading\n simulatedUser: SimulatedUserIdentity\n /** The campaign cell seed every leg asked for. */\n seed: number\n /** Which side of the conversation the candidate surface was. A score on\n * the agent's success only reads `'agent'` conversations. */\n optimizedRole: 'agent' | 'user'\n}\n\nexport interface MultishotRollout<TScenario extends ConversationScenario> {\n /** The dispatch: run one conversation with `surface` as the agent. */\n agent: (\n surface: MutableSurface,\n scenario: TScenario,\n ctx: DispatchContext,\n ) => Promise<ConversationArtifact>\n /** Version of everything but the surface, for measurement caches. */\n dispatchRef: string\n /** The simulated user `agent` puts in front of the agent for `scenario`. */\n simulatedUser: (scenario: TScenario) => SimulatedUserIdentity\n}\n\n/** The simulated user's opener and system prompt for one persona and plan. */\nexport interface SimulatedUserSetup {\n opener: string\n driverSystemPrompt: string\n identity: SimulatedUserIdentity\n}\n\n/** Builds the simulated user from its options alone. The rollout and the\n * realism measure both build it here, so a measured driver is the driver a\n * rollout runs. */\nexport function simulatedUserSetup<TPersona extends MultishotPersona>(\n user: SimulatedUserOptions<TPersona>,\n persona: TPersona,\n plan?: string,\n): SimulatedUserSetup {\n if (user.shape !== undefined && !user.shapeRef) {\n throw new TypeError('simulated user: a custom shape needs a shapeRef naming its callbacks')\n }\n const rigor = user.rigor ?? 'demanding'\n const ending = user.ending ?? DEFAULT_USER_ENDING\n const shape = defaultShapeFromProfile<TPersona>(\n { name: 'agent', description: user.agentDescription ?? 'an AI agent' },\n user.shape,\n )\n const opener = shape.buildOpener(persona)\n const driverSystemPrompt = [\n shape.buildDriverSystemPrompt(persona),\n RIGOR_STANCE[rigor],\n ending.instructions,\n plan ? `Your plan for this conversation:\\n${plan}` : '',\n ]\n .filter((block) => block.length > 0)\n .join('\\n\\n')\n const fields = {\n model: user.model,\n fallbackModels: [...(user.fallbackModels ?? [])],\n rigor,\n personaId: persona.id,\n personaDigest: hashCanonical(jsonDocument(persona)),\n promptDigest: hashCanonical(driverSystemPrompt),\n openerDigest: hashCanonical(opener),\n endingRef: ending.ref,\n shapeRef: user.shapeRef ?? 'agent-eval:default-shape',\n maxTokens: user.maxTokens ?? 600,\n }\n return {\n opener,\n driverSystemPrompt,\n identity: { digest: hashCanonical(jsonDocument(fields)), ...fields },\n }\n}\n\n/**\n * Run a multishot conversation as the `agent(surface, scenario, ctx)` dispatch\n * of `selfImprove` and `compareOptimizationMethods`. Pass `dispatchRef` along\n * with `agent`, score with `conversationJudge`, gate with `conversationGate`\n * and show the optimizer `describeConversation`.\n */\nexport function multishotRollout<TScenario extends ConversationScenario>(\n opts: MultishotRolloutOptions<TScenario>,\n): MultishotRollout<TScenario> {\n const profileOf = opts.profile ?? textSurfaceProfile\n return {\n agent: async (surface, scenario, ctx) =>\n converse(opts, profileOf(surface, scenario), scenario, scenario.userPlan, 'agent', ctx),\n dispatchRef: rolloutDispatchRef(opts, 'agent'),\n simulatedUser: (scenario) =>\n simulatedUserSetup(opts.user, scenario.persona, scenario.userPlan).identity,\n }\n}\n\n/** The user side of the same conversation: the agent profile is fixed and the\n * candidate surface is the simulated user's plan. Package-internal; the only\n * public way to optimize it is `improveAdversarialUser`, whose objective is\n * fixed to the agent's failure rate. */\nexport function userSideRollout<TScenario extends ConversationScenario>(\n opts: Omit<MultishotRolloutOptions<TScenario>, 'profile'>,\n agentProfile: AgentProfile,\n): Omit<MultishotRollout<TScenario>, 'simulatedUser'> {\n return {\n agent: async (surface, scenario, ctx) => {\n if (typeof surface !== 'string') {\n throw new TypeError('adversarial user: the plan surface must be text')\n }\n const plan = [scenario.userPlan, surface].filter(Boolean).join('\\n\\n')\n return converse(opts, agentProfile, scenario, plan, 'user', ctx)\n },\n dispatchRef: rolloutDispatchRef(\n { ...opts, profileDigest: hashCanonical(jsonDocument(agentProfile)) },\n 'user',\n ),\n }\n}\n\nfunction textSurfaceProfile(surface: MutableSurface): AgentProfile {\n if (typeof surface !== 'string') {\n throw new TypeError(\n 'multishotRollout: a non-text surface needs a `profile` mapping it to an AgentProfile',\n )\n }\n return { name: 'agent', prompt: { systemPrompt: surface } }\n}\n\nfunction rolloutDispatchRef<TScenario extends ConversationScenario>(\n opts: Omit<MultishotRolloutOptions<TScenario>, 'profile'> & { profileDigest?: string },\n role: 'agent' | 'user',\n): string {\n const ending = opts.user.ending ?? DEFAULT_USER_ENDING\n return `multishot-rollout:${hashCanonical(\n jsonDocument({\n role,\n maxTurns: opts.maxTurns,\n revision: opts.revision,\n profileDigest: opts.profileDigest,\n agent: {\n model: opts.agent.model,\n tools: opts.agent.tools ?? [],\n maxTokens: opts.agent.maxTokens,\n toolFollowupMaxTokens: opts.agent.toolFollowupMaxTokens,\n maxToolDispatches: opts.agent.maxToolDispatches,\n },\n user: {\n model: opts.user.model,\n fallbackModels: opts.user.fallbackModels ?? [],\n rigor: opts.user.rigor ?? 'demanding',\n agentDescription: opts.user.agentDescription ?? 'an AI agent',\n shapeRef: opts.user.shapeRef ?? 'agent-eval:default-shape',\n maxTokens: opts.user.maxTokens ?? 600,\n endingRef: ending.ref,\n endingInstructions: ending.instructions,\n },\n }),\n )}`\n}\n\nasync function converse<TScenario extends ConversationScenario>(\n opts: Omit<MultishotRolloutOptions<TScenario>, 'profile'>,\n profile: AgentProfile,\n scenario: TScenario,\n plan: string | undefined,\n optimizedRole: 'agent' | 'user',\n ctx: DispatchContext,\n): Promise<ConversationArtifact> {\n if (!Number.isSafeInteger(opts.maxTurns) || opts.maxTurns < 1) {\n throw new RangeError(\n `multishotRollout: maxTurns must be a positive integer, got ${opts.maxTurns}`,\n )\n }\n if ((opts.agent.tools === undefined) !== (opts.agent.toolExecutors === undefined)) {\n throw new TypeError('multishotRollout: agent tools and toolExecutors go together')\n }\n const user = simulatedUserSetup(opts.user, scenario.persona, plan)\n const ending = opts.user.ending ?? DEFAULT_USER_ENDING\n const metered = (\n leg: ConversationLeg,\n channel: CostChannel,\n actor: string,\n transport: MultishotTransport,\n ): MultishotTransport => {\n return async (req) => {\n const { tools, signal, ...rest } = req\n // The engine advertises an empty tool list when the agent has no tools;\n // a provider may refuse one, so the request leaves it out.\n const request: MultishotTransportRequest = {\n ...rest,\n ...(tools && tools.length > 0 ? { tools } : {}),\n seed: ctx.seed,\n }\n const maximumCharge = opts.maximumCharge?.(leg, request)\n const result = await ctx.cost.runPaidCall({\n channel,\n actor,\n model: request.model,\n signal: signal ?? ctx.signal,\n ...(maximumCharge === undefined ? {} : { maximumCharge }),\n execute: (callSignal) => transport({ ...request, signal: callSignal }),\n receipt: (response) => legReceipt(request.model, response),\n })\n if (!result.succeeded) throw result.error\n return result.value\n }\n }\n\n const close: { ending?: ConversationEnding; message?: string } = {}\n const result = await runMultishotConversation(\n {\n profile,\n persona: scenario.persona,\n shape: {\n buildOpener: () => user.opener,\n buildDriverSystemPrompt: () => user.driverSystemPrompt,\n },\n tools: opts.agent.tools ?? [],\n toolExecutors: opts.agent.toolExecutors ?? {},\n artifactTypeFor: opts.agent.artifactTypeFor,\n maxTurns: opts.maxTurns,\n agentModel: opts.agent.model,\n driverModel: opts.user.model,\n driverFallbackModels: opts.user.fallbackModels,\n agentMaxTokens: opts.agent.maxTokens,\n toolFollowupMaxTokens: opts.agent.toolFollowupMaxTokens,\n driverMaxTokens: user.identity.maxTokens,\n maxToolDispatches: opts.agent.maxToolDispatches,\n agentTransport: metered('agent', 'agent', 'agent', opts.agent.transport),\n driverTransport: metered('user', 'driver', 'simulated-user', opts.user.transport),\n toolTransport: metered(\n 'tool',\n 'agent',\n 'tool',\n opts.agent.toolTransport ?? opts.agent.transport,\n ),\n signal: ctx.signal,\n },\n async (conversation) => {\n for (let turn = 0; turn < conversation.maxTurns; turn++) {\n await conversation.agentTurn(turn)\n if (turn === conversation.maxTurns - 1) {\n close.ending = { kind: 'turn-cap', turn }\n return\n }\n const { content } = await conversation.driverTurn(turn)\n const classified = ending.classify(content)\n if (classified.kind !== 'continue') {\n close.ending = { kind: classified.kind, turn }\n close.message = classified.message\n return\n }\n }\n },\n )\n const ended = close.ending\n if (ended === undefined) throw new Error('multishotRollout: the conversation never ended')\n\n const transcript = result.transcript.map((message) => ({ ...message }))\n if (close.message !== undefined) transcript[transcript.length - 1]!.content = close.message\n const userMessages = transcript.filter((message) => message.role === 'user').slice(1)\n const firstPushback = opts.user.pushback\n ? userMessages.findIndex((message) => opts.user.pushback!(message.content))\n : undefined\n const record: ConversationRecord = { transcript, artifacts: result.artifacts, ending: ended }\n const outcome = opts.outcome(record, scenario)\n if (typeof outcome?.passed !== 'boolean' || typeof outcome.detail !== 'string') {\n throw new TypeError('multishotRollout: outcome must return { passed: boolean, detail: string }')\n }\n return {\n transcript,\n artifacts: result.artifacts,\n toolCalls: result.toolCalls,\n agentTurns: ended.turn + 1,\n ending: ended,\n outcome: { passed: outcome.passed, detail: outcome.detail },\n pushback:\n firstPushback === undefined\n ? { determined: false }\n : { determined: true, firstTurn: firstPushback < 0 ? null : firstPushback },\n simulatedUser: user.identity,\n seed: ctx.seed,\n optimizedRole,\n }\n}\n\nfunction legReceipt(requested: string, response: MultishotTransportResponse): CostReceiptInput {\n const usage = response.usage\n return {\n model: response.model ?? requested,\n inputTokens: usage?.prompt_tokens ?? 0,\n outputTokens: usage?.completion_tokens ?? 0,\n ...(usage === undefined ? { usageUnknown: true } : {}),\n ...(response.costUsd === undefined ? {} : { actualCostUsd: response.costUsd }),\n }\n}\n","// How real a simulated user is, measured against recorded real users.\n//\n// At sampled real user turns, the driver writes the next user message from\n// the same recorded context the real user saw. A System One decision point is\n// shown the context and the two messages, in both orders, and picks the one\n// the real user wrote. Accuracy is reported per independent conversation with\n// a cluster bootstrap interval; 50% means the judge cannot tell the driver from\n// the real user.\n//\n// The measure is a same-context comparison: a row must carry the identity that\n// proves its context, `userTurnContextDigest` of the conversation's task and\n// the visible context, and a row without it is refused, as the PRM pair rule\n// never pairs a step without a context digest. The PRM's own chain digest\n// cannot serve here: it digests a step's input, which already contains the\n// real user's message.\n\nimport type { FindingCalibration } from '../analyst/finding-scope'\nimport type { FindingsLedger, FindingsLedgerOutcome } from '../analyst/findings-ledger'\nimport type { EvidenceRef } from '../analyst/types'\nimport type { CostLedgerHandle } from '../cost-ledger/contract'\nimport {\n DECISION_POINT_MIN_KAPPA,\n type DecisionPointResult,\n type DecisionQuestions,\n decisionPoint,\n decisionQuestionDigest,\n} from '../decision-point'\nimport { hashCanonical, jsonDocument } from '../ledger-core/canonical'\nimport { clusterBootstrapMean } from '../meta-eval/cluster-bootstrap'\nimport { makeRng } from '../statistics/internal'\nimport type { SystemOneEvaluatorOptions } from '../systemone'\nimport { runTaskId } from '../trace/emitter'\nimport type { Run } from '../trace/schema'\nimport type { Trajectory } from '../trajectory'\nimport { driverViewMessages, requestUserReply } from './conversation'\nimport { DEFAULT_USER_ENDING, type SimulatedUserOptions, simulatedUserSetup } from './rollout'\nimport type {\n MultishotPersona,\n MultishotTransportRequest,\n MultishotTransportResponse,\n} from './types'\n\n/** One real user turn and the context the user wrote it in. */\nexport interface RecordedUserTurn {\n /** The independent unit: one recorded conversation. */\n conversationId: string\n /** The task the conversation served. Absent when the record names none. */\n taskId?: string\n /** Index of the message among the conversation's user messages; the opener is 0. */\n turn: number\n /** What the user saw before writing: user and agent messages, in order. */\n context: Array<{ role: 'user' | 'assistant'; content: string }>\n /** `userTurnContextDigest` of `taskId` and `context`; absent without a task. */\n contextDigest?: string\n realMessage: string\n /** Where the turn was recorded. */\n evidenceRefs?: EvidenceRef[]\n}\n\n/** The shared-context identity of a user turn: its task and visible context. */\nexport function userTurnContextDigest(input: {\n taskId: string\n context: RecordedUserTurn['context']\n}): string {\n return hashCanonical(jsonDocument({ taskId: input.taskId, context: input.context }))\n}\n\n/**\n * The real user turns of one recorded conversation, from its trajectory: each\n * model call whose input ends in a user message that answers an agent message\n * is one turn. System and tool messages are not part of what the user saw. A\n * run without a task identity yields rows without a context digest.\n */\nexport function recordedUserTurns(\n trajectory: Trajectory,\n run: Pick<Run, 'scenarioId' | 'layer' | 'tags'> | undefined,\n): RecordedUserTurn[] {\n const taskId = runTaskId(run)\n const turns: RecordedUserTurn[] = []\n const seen = new Set<number>()\n for (const step of trajectory.steps) {\n const span = step.span\n if (span.kind !== 'llm') continue\n const last = span.messages.at(-1)\n if (last?.role !== 'user' || last.content.trim().length === 0) continue\n const context = span.messages\n .slice(0, -1)\n .filter(\n (message): message is typeof message & { role: 'user' | 'assistant' } =>\n (message.role === 'user' || message.role === 'assistant') &&\n message.content.trim().length > 0,\n )\n .map((message) => ({ role: message.role, content: message.content }))\n if (context.at(-1)?.role !== 'assistant') continue\n const turn = context.filter((message) => message.role === 'user').length\n if (seen.has(turn)) continue\n seen.add(turn)\n turns.push({\n conversationId: trajectory.runId,\n ...(taskId === undefined\n ? {}\n : { taskId, contextDigest: userTurnContextDigest({ taskId, context }) }),\n turn,\n context,\n realMessage: last.content,\n evidenceRefs: [{ kind: 'span', uri: span.spanId }],\n })\n }\n return turns\n}\n\n/** A recorded turn carries no proof of a shared context, or a proof its\n * context does not match. */\nexport class SharedContextIdentityError extends Error {\n readonly conversationId: string\n readonly turn: number\n constructor(row: Pick<RecordedUserTurn, 'conversationId' | 'turn'>, reason: string) {\n super(\n `recorded user turn ${row.conversationId}#${row.turn} ${reason}; a realism comparison ` +\n \"needs the identity that proves the driver saw the real user's context\",\n )\n this.name = 'SharedContextIdentityError'\n this.conversationId = row.conversationId\n this.turn = row.turn\n }\n}\n\nfunction assertSharedContext(row: RecordedUserTurn): void {\n if (!row.taskId || !row.contextDigest) {\n throw new SharedContextIdentityError(row, 'has no task identity and context digest')\n }\n if (userTurnContextDigest({ taskId: row.taskId, context: row.context }) !== row.contextDigest) {\n throw new SharedContextIdentityError(row, 'has a context digest its context does not match')\n }\n}\n\n/** Writes the user's next message for a recorded context. */\nexport interface RealismDriver {\n /** Stable identity of everything that shapes the driver's message. */\n identity: string\n next(input: {\n turn: RecordedUserTurn\n signal?: AbortSignal\n costLedger?: CostLedgerHandle\n }): Promise<string>\n}\n\n/**\n * The simulated user a rollout runs, as a realism driver: the same prompt,\n * the same driver point of view on the recorded context, the same model\n * rotation. An ending marker is removed, as a rollout removes it.\n */\nexport function simulatedUserDriver<TPersona extends MultishotPersona>(opts: {\n user: SimulatedUserOptions<TPersona>\n /** The persona the user plays for a recorded conversation. */\n persona: (turn: RecordedUserTurn) => TPersona\n plan?: string\n}): RealismDriver {\n const ending = opts.user.ending ?? DEFAULT_USER_ENDING\n const models = [opts.user.model, ...(opts.user.fallbackModels ?? [])]\n return {\n identity: `simulated-user:${hashCanonical(\n jsonDocument({\n models,\n rigor: opts.user.rigor ?? 'demanding',\n agentDescription: opts.user.agentDescription ?? 'an AI agent',\n shapeRef: opts.user.shapeRef ?? 'agent-eval:default-shape',\n maxTokens: opts.user.maxTokens ?? 600,\n endingRef: ending.ref,\n endingInstructions: ending.instructions,\n plan: opts.plan,\n }),\n )}`,\n async next({ turn, signal, costLedger }) {\n const setup = simulatedUserSetup(opts.user, opts.persona(turn), opts.plan)\n const messages = driverViewMessages(setup.driverSystemPrompt, turn.context)\n const transport = costLedger\n ? async (req: MultishotTransportRequest) => {\n const result = await costLedger.runPaidCall({\n channel: 'driver',\n phase: 'realism.driver',\n actor: 'simulated-user',\n model: req.model,\n signal: req.signal,\n execute: (callSignal) => opts.user.transport({ ...req, signal: callSignal }),\n receipt: (response: MultishotTransportResponse) => ({\n model: response.model ?? req.model,\n inputTokens: response.usage?.prompt_tokens ?? 0,\n outputTokens: response.usage?.completion_tokens ?? 0,\n ...(response.usage === undefined ? { usageUnknown: true } : {}),\n ...(response.costUsd === undefined ? {} : { actualCostUsd: response.costUsd }),\n }),\n })\n if (!result.succeeded) throw result.error\n return result.value\n }\n : opts.user.transport\n const content = await requestUserReply({\n models,\n messages,\n transport,\n maxTokens: setup.identity.maxTokens,\n signal,\n turn: turn.turn,\n })\n const classified = ending.classify(content)\n return classified.kind === 'continue' ? content : classified.message\n },\n }\n}\n\n/** The realism question: which of two messages did the real user write. */\nexport const SIMULATOR_REALISM_QUESTIONS = {\n real: {\n type: 'choice',\n instructions:\n \"The state holds a conversation between a user and an AI agent up to the user's next \" +\n 'message, and two candidate next messages, a and b. A real user wrote one; a simulator ' +\n 'wrote the other. Choose the one the real user wrote. Judge voice, length, specificity, ' +\n \"what the user would know, and how a person reacts to the agent's last message. Neither \" +\n 'position is more likely.',\n criteria: {\n a: 'The real user wrote message a.',\n b: 'The real user wrote message b.',\n },\n },\n} as const satisfies DecisionQuestions\n\nexport interface SimulatorRealismJudgeOptions {\n id: string\n version: string\n /** Requested judge model. */\n model: string\n ledger: FindingsLedger\n evaluator: SystemOneEvaluatorOptions\n /** Agreement with independent real-or-simulated labels, bound to this exact\n * question, model and served model through `questionDigest`. Without it\n * every judgment is recorded as uncalibrated. */\n calibration?: FindingCalibration & {\n servedModel: string\n questionDigest: string\n evidenceRefs: EvidenceRef[]\n }\n /** Default 0.6. */\n minimumProbability?: number\n /** Default 0.2. */\n minimumMargin?: number\n}\n\nexport interface SimulatorRealismJudge {\n id: string\n definitionDigest: string\n /** The digest a calibration of this judge must carry, for the served model\n * the calibration names, else the requested model. */\n questionDigest: string\n /** The calibration clears `DECISION_POINT_MIN_KAPPA` and binds this question. */\n calibrated: boolean\n decide: ReturnType<typeof decisionPoint<typeof SIMULATOR_REALISM_QUESTIONS>>['decide']\n}\n\n/** The realism judge as a System One decision point at the turn layer. */\nexport function simulatorRealismJudge(opts: SimulatorRealismJudgeOptions): SimulatorRealismJudge {\n const questionDigest = decisionQuestionDigest({\n id: opts.id,\n version: opts.version,\n model: opts.model,\n servedModel: opts.calibration?.servedModel ?? opts.model,\n name: 'real',\n question: SIMULATOR_REALISM_QUESTIONS.real,\n })\n const point = decisionPoint({\n id: opts.id,\n version: opts.version,\n layers: ['turn'],\n model: opts.model,\n questions: SIMULATOR_REALISM_QUESTIONS,\n policy: {\n real: {\n minimumProbability: opts.minimumProbability ?? 0.6,\n minimumMargin: opts.minimumMargin ?? 0.2,\n options: { a: { action: 'record' }, b: { action: 'record' } },\n ...(opts.calibration ? { calibration: opts.calibration } : {}),\n },\n },\n ledger: opts.ledger,\n evaluator: opts.evaluator,\n })\n return {\n id: point.id,\n definitionDigest: point.definitionDigest,\n questionDigest,\n calibrated:\n opts.calibration !== undefined &&\n opts.calibration.kappa >= DECISION_POINT_MIN_KAPPA &&\n opts.calibration.questionDigest === questionDigest,\n decide: point.decide,\n }\n}\n\nexport interface MeasureSimulatorRealismOptions {\n turns: readonly RecordedUserTurn[]\n driver: RealismDriver\n judge: SimulatorRealismJudge\n /** Ledger run the judgments are recorded under. Repeating a measurement\n * under the same run replays its recorded judgments, and a changed input\n * under it counts as a failed judgment, so use a new run per measurement. */\n runId: string\n /** ISO-8601 time stamped on the judgments. Default: now. */\n at?: string\n /** Judge at most this many turns, drawn with `seed`. Default: all. */\n sample?: number\n confidence?: number\n resamples?: number\n seed?: number\n costLedger?: CostLedgerHandle\n signal?: AbortSignal\n}\n\nexport interface SimulatorRealismReport {\n driver: string\n judge: {\n id: string\n definitionDigest: string\n /** Calibrated, and every judgment ran on the calibrated model. */\n calibrated: boolean\n /** Judgments by System One reason: threshold, uncertain, uncalibrated, model-mismatch. */\n reasons: Record<string, number>\n }\n conversations: number\n turns: number\n /** Judged presentations; each counted turn is shown in both orders. */\n presentations: number\n failedJudgments: number\n /** Turns dropped because one of their two orders failed to judge: a turn\n * counts only when it was judged in both positions. */\n unbalancedTurns: number\n /** Share of presentations where the judge picked the real message, each\n * conversation weighted equally, with a bootstrap interval over conversations. */\n accuracy: { mean: number; low: number; high: number; confidence: number; resamples: number }\n meanProbabilityOnReal: number\n /** The interval contains 0.5: this sample does not show the judge telling\n * the driver from real users. A small sample satisfies it with a wide\n * interval, so it is not an admission rule; admit on `accuracy.high`\n * against a stated bound, as `improveAdversarialUser` does. */\n indistinguishable: boolean\n}\n\n/** Measure how often a judge tells the driver's message from the real user's. */\nexport async function measureSimulatorRealism(\n opts: MeasureSimulatorRealismOptions,\n): Promise<SimulatorRealismReport> {\n if (opts.turns.length === 0) throw new RangeError('measureSimulatorRealism: no recorded turns')\n for (const row of opts.turns) assertSharedContext(row)\n const at = opts.at ?? new Date().toISOString()\n const turns = sampleTurns(opts.turns, opts.sample, opts.seed)\n const correctByConversation = new Map<string, number[]>()\n const reasons: Record<string, number> = {}\n const probabilitiesOnReal: number[] = []\n let failedJudgments = 0\n let unbalancedTurns = 0\n\n for (const row of turns) {\n const simulated = await opts.driver.next({\n turn: row,\n ...(opts.signal ? { signal: opts.signal } : {}),\n ...(opts.costLedger ? { costLedger: opts.costLedger } : {}),\n })\n const unit = `${row.conversationId}:${row.turn}`\n const answers: Array<ReturnType<typeof judgedAnswer>> = []\n for (const order of ['real-first', 'real-second'] as const) {\n const judged = await opts.judge.decide(\n {\n runId: opts.runId,\n invocationId: `${unit}:${order}`,\n layer: 'turn',\n consumer: 'simulator-realism',\n state: {\n context: row.context,\n a: order === 'real-first' ? row.realMessage : simulated,\n b: order === 'real-first' ? simulated : row.realMessage,\n },\n scope: { population: [unit], n: 1, window: { from: at, to: at } },\n at,\n evidenceRefs: row.evidenceRefs?.length\n ? row.evidenceRefs\n : [{ kind: 'event', uri: `user-turn:${unit}` }],\n },\n {\n ...(opts.signal ? { signal: opts.signal } : {}),\n ...(opts.costLedger ? { costLedger: opts.costLedger } : {}),\n channel: 'judge',\n actor: 'simulator-realism-judge',\n costPhase: 'realism.judge',\n },\n )\n answers.push(judgedAnswer(judged))\n }\n const failed = answers.filter((answer) => !answer).length\n failedJudgments += failed\n // A turn judged in one position only would let the judge's position bias\n // count, so it counts only when both orders were judged.\n if (failed > 0) {\n if (failed < answers.length) unbalancedTurns += 1\n continue\n }\n for (const [index, answer] of answers.entries()) {\n if (!answer) continue\n const realOption = index === 0 ? 'a' : 'b'\n reasons[answer.reason] = (reasons[answer.reason] ?? 0) + 1\n probabilitiesOnReal.push(answer.probabilities[realOption] ?? 0)\n const list = correctByConversation.get(row.conversationId) ?? []\n list.push(answer.choice === realOption ? 1 : 0)\n correctByConversation.set(row.conversationId, list)\n }\n }\n\n if (correctByConversation.size === 0) {\n throw new Error('measureSimulatorRealism: no presentation was judged')\n }\n const interval = clusterBootstrapMean(\n [...correctByConversation].map(([conversationId, list]) => ({\n cluster: conversationId,\n value: list.reduce((sum, value) => sum + value, 0) / list.length,\n })),\n {\n ...(opts.confidence === undefined ? {} : { confidence: opts.confidence }),\n ...(opts.resamples === undefined ? {} : { resamples: opts.resamples }),\n ...(opts.seed === undefined ? {} : { seed: opts.seed }),\n },\n )\n const onCalibratedModel = Object.keys(reasons).every(\n (reason) => reason === 'threshold' || reason === 'uncertain',\n )\n return {\n driver: opts.driver.identity,\n judge: {\n id: opts.judge.id,\n definitionDigest: opts.judge.definitionDigest,\n calibrated: opts.judge.calibrated && onCalibratedModel,\n reasons,\n },\n conversations: correctByConversation.size,\n turns: turns.length,\n presentations: probabilitiesOnReal.length,\n failedJudgments,\n unbalancedTurns,\n accuracy: {\n mean: interval.mean,\n low: interval.low,\n high: interval.high,\n confidence: interval.confidence,\n resamples: interval.resamples,\n },\n meanProbabilityOnReal:\n probabilitiesOnReal.reduce((sum, value) => sum + value, 0) / probabilitiesOnReal.length,\n indistinguishable: interval.low <= 0.5 && interval.high >= 0.5,\n }\n}\n\nfunction judgedAnswer(judged: FindingsLedgerOutcome<DecisionPointResult>) {\n if (!judged.succeeded) return undefined\n const record = judged.value.record\n if (!record || record.error) return undefined\n return record.answers.real\n}\n\nfunction sampleTurns(\n turns: readonly RecordedUserTurn[],\n sample: number | undefined,\n seed: number | undefined,\n): RecordedUserTurn[] {\n if (sample === undefined || sample >= turns.length) return [...turns]\n if (!Number.isSafeInteger(sample) || sample < 1) {\n throw new RangeError(\n `measureSimulatorRealism: sample must be a positive integer, got ${sample}`,\n )\n }\n const random = makeRng(seed ?? 0)\n const order = turns.map((_, index) => index)\n for (let index = order.length - 1; index > 0; index--) {\n const swap = Math.floor(random() * (index + 1))\n ;[order[index], order[swap]] = [order[swap]!, order[index]!]\n }\n return order\n .slice(0, sample)\n .sort((left, right) => left - right)\n .map((index) => turns[index]!)\n}\n","// The simulated user as a second optimizable role.\n//\n// An adversarial user searches for the plans a fixed agent fails under: its\n// objective is the agent's failure rate, nothing else. A plan is admitted only\n// when a calibrated realism judge cannot tell it from real users above a\n// floor, so the search finds failures real users would cause, not failures of\n// a user no one is. What an admitted plan breaks becomes new train scenarios\n// for the agent side; they never enter a held-out split. A failure becomes a\n// train scenario only once a conversation shows it can be passed under the\n// plan, by a reference agent or by the same agent on one of k seeded repeats:\n// a plan that withholds what the outcome check needs teaches nothing.\n//\n// The objective is fixed by construction: this entry builds the judge itself\n// and refuses a caller judge, `conversationJudge` refuses every user-side\n// conversation, and the user-side dispatch is not public.\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport type { OptimizationMethod } from '../campaign/optimization-method'\nimport { runCampaign } from '../campaign/run-campaign'\nimport {\n type CampaignStorage,\n fsCampaignStorage,\n inMemoryCampaignStorage,\n} from '../campaign/storage'\nimport type { JudgeConfig, SurfaceProposer } from '../campaign/types'\nimport {\n type SelfImproveBudget,\n type SelfImproveResult,\n selfImprove,\n} from '../contract/self-improve'\nimport type { CostLedgerHandle } from '../cost-ledger/contract'\nimport { hashCanonical, jsonDocument } from '../ledger-core/canonical'\nimport { listSome, UserSideObjectiveError } from './conversation-conditions'\nimport { describeConversation } from './conversation-evidence'\nimport {\n measureSimulatorRealism,\n type RecordedUserTurn,\n type SimulatorRealismJudge,\n type SimulatorRealismReport,\n simulatedUserDriver,\n} from './realism'\nimport {\n type ConversationArtifact,\n type ConversationScenario,\n type MultishotRolloutOptions,\n type ScenarioSolvedBy,\n userSideRollout,\n} from './rollout'\n\n/** Scenarios for the user-side search would reach the agent's held-out split. */\nexport class AdversarialSplitError extends Error {\n readonly scenarioIds: string[]\n constructor(scenarioIds: string[]) {\n super(\n `adversarial user search would use ${scenarioIds.length} scenario(s) that share an id ` +\n `or persona with the agent's held-out split (${listSome(scenarioIds)})`,\n )\n this.name = 'AdversarialSplitError'\n this.scenarioIds = scenarioIds\n }\n}\n\nexport interface AdversarialUserOptions<TScenario extends ConversationScenario> {\n /** The conversation; the agent side is fixed to `agentProfile`. */\n rollout: Omit<MultishotRolloutOptions<TScenario>, 'profile'>\n agentProfile: AgentProfile\n /** The plan the search starts from: the user's surface. */\n baselinePlan: string\n /** Personas the search runs on, held-out cases included. */\n scenarios: TScenario[]\n /** The agent side's held-out scenarios. No scenario of this search may share\n * an id or a persona with them. */\n agentHeldOut: readonly TScenario[]\n proposer?: SurfaceProposer\n method?: OptimizationMethod<TScenario, ConversationArtifact>\n selectionScenarios?: TScenario[]\n budget?: SelfImproveBudget\n runDir?: string\n storage?: CampaignStorage\n expectUsage?: 'assert' | 'warn' | 'off'\n /** Snapshot model id, for an agent leg that reports no receipt model. */\n model?: string\n /** The admission floor, measured on the winning plan. */\n realism: {\n turns: readonly RecordedUserTurn[]\n judge: SimulatorRealismJudge\n runId: string\n at?: string\n /** The persona the user plays for a recorded conversation. */\n persona: (turn: RecordedUserTurn) => TScenario['persona']\n /** Highest judge accuracy, at the interval's upper end, a plan may reach\n * and still count as realistic. 0.5 is indistinguishable. */\n maxJudgeAccuracy: number\n sample?: number\n confidence?: number\n resamples?: number\n seed?: number\n costLedger?: CostLedgerHandle\n }\n /** How an emitted scenario shows it can be passed under its plan. Default:\n * the same agent, 3 seeded repeats. */\n solvability?: {\n /** An agent that runs each candidate in place of `agentProfile`. */\n referenceProfile?: AgentProfile\n /** Seeded conversations per candidate; one pass is enough. Default 3. */\n repeats?: number\n /** Campaign seed of the repeats. Default 42. */\n seed?: number\n }\n}\n\n/** A failure the admitted plan caused that no solvability conversation passed. */\nexport interface UnsolvableScenario<TScenario extends ConversationScenario> {\n scenario: TScenario\n reason: string\n /** Conversations run on it. */\n attempts: number\n}\n\nexport interface AdversarialUserResult<TScenario extends ConversationScenario> {\n /** The user-side search, scored on the agent's failure rate. */\n improvement: SelfImproveResult<TScenario, ConversationArtifact>\n /** The selected plan. */\n plan: string\n /** Realism of the selected plan; null when the search did not ship. */\n realism: SimulatorRealismReport | null\n admitted: boolean\n reasons: string[]\n /** One per held-out conversation the admitted plan made the agent fail\n * that a solvability conversation passed: the source scenario with the plan\n * as its `userPlan` and the pass on `origin.solvedBy`. Train only. */\n trainScenarios: TScenario[]\n /** Failures no solvability conversation passed. Never emitted. */\n unsolvableScenarios: UnsolvableScenario<TScenario>[]\n}\n\n/**\n * Search for a simulated-user plan that makes a fixed agent fail, admit it\n * only above a realism floor, and emit what it breaks as agent train scenarios.\n */\nexport async function improveAdversarialUser<TScenario extends ConversationScenario>(\n opts: AdversarialUserOptions<TScenario>,\n): Promise<AdversarialUserResult<TScenario>> {\n if ('judge' in opts || 'gate' in opts) {\n throw new UserSideObjectiveError(\n \"improveAdversarialUser: the user side's objective is the agent's failure rate; it accepts no judge or gate\",\n )\n }\n if (!(opts.realism.maxJudgeAccuracy >= 0.5 && opts.realism.maxJudgeAccuracy <= 1)) {\n throw new RangeError('improveAdversarialUser: realism.maxJudgeAccuracy must be in [0.5, 1]')\n }\n const repeats = opts.solvability?.repeats ?? 3\n if (!Number.isSafeInteger(repeats) || repeats < 1) {\n throw new RangeError('improveAdversarialUser: solvability.repeats must be a positive integer')\n }\n assertDisjointFromHeldOut(\n [...opts.scenarios, ...(opts.selectionScenarios ?? [])],\n opts.agentHeldOut,\n )\n\n const rollout = userSideRollout(opts.rollout, opts.agentProfile)\n const shared = {\n agent: rollout.agent,\n dispatchRef: rollout.dispatchRef,\n scenarios: opts.scenarios,\n judge: agentFailureJudge<TScenario>(),\n describeArtifact: describeConversation,\n baselineSurface: opts.baselinePlan,\n ...(opts.selectionScenarios ? { selectionScenarios: opts.selectionScenarios } : {}),\n ...(opts.budget ? { budget: opts.budget } : {}),\n ...(opts.runDir ? { runDir: opts.runDir } : {}),\n ...(opts.storage ? { storage: opts.storage } : {}),\n ...(opts.expectUsage ? { expectUsage: opts.expectUsage } : {}),\n ...(opts.model ? { model: opts.model } : {}),\n }\n const improvement: SelfImproveResult<TScenario, ConversationArtifact> = opts.method\n ? await selfImprove<TScenario, ConversationArtifact>({ ...shared, method: opts.method })\n : await selfImprove<TScenario, ConversationArtifact>({\n ...shared,\n ...(opts.proposer ? { proposer: opts.proposer } : {}),\n })\n const plan = String(improvement.winner.surface)\n if (improvement.gateDecision !== 'ship') {\n return {\n improvement,\n plan,\n realism: null,\n admitted: false,\n reasons: [`the user-side search did not ship (${improvement.gateDecision})`],\n trainScenarios: [],\n unsolvableScenarios: [],\n }\n }\n\n const realism = await measureSimulatorRealism({\n turns: opts.realism.turns,\n driver: simulatedUserDriver({\n user: opts.rollout.user,\n persona: opts.realism.persona,\n plan,\n }),\n judge: opts.realism.judge,\n runId: opts.realism.runId,\n ...pick(opts.realism, ['at', 'sample', 'confidence', 'resamples', 'seed', 'costLedger']),\n })\n const reasons: string[] = []\n if (!realism.judge.calibrated) {\n reasons.push(\n 'realism judge is not calibrated on this question and served model; a plan is admitted only by a calibrated judge',\n )\n }\n if (realism.accuracy.high > opts.realism.maxJudgeAccuracy) {\n reasons.push(\n `realism: judge accuracy reaches ${realism.accuracy.high.toFixed(3)} at the interval's upper end, above the floor ${opts.realism.maxJudgeAccuracy}`,\n )\n }\n const admitted = reasons.length === 0\n const candidates = admitted ? failedScenarios(improvement, opts.scenarios, plan) : []\n return {\n improvement,\n plan,\n realism,\n admitted,\n reasons,\n ...(await sortBySolvability(opts, candidates, repeats)),\n }\n}\n\n/** Run each candidate under its plan; one pass makes it a train scenario. */\nasync function sortBySolvability<TScenario extends ConversationScenario>(\n opts: AdversarialUserOptions<TScenario>,\n candidates: TScenario[],\n repeats: number,\n): Promise<Pick<AdversarialUserResult<TScenario>, 'trainScenarios' | 'unsolvableScenarios'>> {\n if (candidates.length === 0) return { trainScenarios: [], unsolvableScenarios: [] }\n const reference = opts.solvability?.referenceProfile\n const profile = reference ?? opts.agentProfile\n const solver = userSideRollout(opts.rollout, profile)\n const campaign = await runCampaign<TScenario, ConversationArtifact>({\n scenarios: candidates,\n // A candidate carries the plan it failed under as its own `userPlan`.\n dispatch: (scenario, ctx) => solver.agent('', scenario, ctx),\n dispatchRef: `adversarial-solvability:${solver.dispatchRef}`,\n reps: repeats,\n seed: opts.solvability?.seed ?? 42,\n runDir: opts.runDir ? `${opts.runDir}/solvability` : `mem://adversarial-solvability`,\n storage: opts.storage ?? (opts.runDir ? fsCampaignStorage() : inMemoryCampaignStorage()),\n expectUsage: opts.expectUsage ?? 'assert',\n })\n const agent = reference ? 'reference' : 'same'\n const profileDigest = hashCanonical(jsonDocument(profile))\n const trainScenarios: TScenario[] = []\n const unsolvableScenarios: UnsolvableScenario<TScenario>[] = []\n for (const scenario of candidates) {\n const cells = campaign.cells.filter((cell) => cell.scenarioId === scenario.id)\n const passed = cells.find((cell) => cell.error === undefined && cell.artifact.outcome.passed)\n if (passed) {\n const solvedBy: ScenarioSolvedBy = {\n agent,\n profileDigest,\n seed: passed.artifact.seed,\n detail: passed.artifact.outcome.detail,\n }\n trainScenarios.push({ ...scenario, origin: { ...scenario.origin!, solvedBy } })\n continue\n }\n const last = cells.at(-1)\n unsolvableScenarios.push({\n scenario,\n reason:\n `the ${agent} agent passed none of ${cells.length} ` +\n `conversation(s) under the plan (${last?.error ?? last?.artifact.outcome.detail ?? 'no conversation ran'})`,\n attempts: cells.length,\n })\n }\n return { trainScenarios, unsolvableScenarios }\n}\n\n/** Score of the user side: 1 when the agent failed the outcome check. */\nfunction agentFailureJudge<TScenario extends ConversationScenario>(): JudgeConfig<\n ConversationArtifact,\n TScenario\n> {\n return {\n name: 'agent-failure',\n judgeVersion: 'agent-eval:agent-failure:v1',\n dimensions: [\n { key: 'agent_failure', description: '1 when the agent failed the code-checked outcome' },\n ],\n score({ artifact }) {\n if (artifact.optimizedRole !== 'user') {\n throw new UserSideObjectiveError('agent-failure scores user-side conversations only')\n }\n const failed = artifact.outcome.passed ? 0 : 1\n return {\n dimensions: { agent_failure: failed },\n composite: failed,\n notes: artifact.outcome.detail,\n }\n },\n }\n}\n\nfunction assertDisjointFromHeldOut<TScenario extends ConversationScenario>(\n scenarios: readonly TScenario[],\n heldOut: readonly TScenario[],\n): void {\n const ids = new Set(heldOut.map((scenario) => scenario.id))\n const personas = new Set(heldOut.map((scenario) => personaDigest(scenario)))\n const overlap = scenarios\n .filter((scenario) => ids.has(scenario.id) || personas.has(personaDigest(scenario)))\n .map((scenario) => scenario.id)\n if (overlap.length > 0) throw new AdversarialSplitError([...new Set(overlap)])\n}\n\nfunction personaDigest(scenario: ConversationScenario): string {\n return hashCanonical(jsonDocument(scenario.persona))\n}\n\nfunction failedScenarios<TScenario extends ConversationScenario>(\n improvement: SelfImproveResult<TScenario, ConversationArtifact>,\n scenarios: readonly TScenario[],\n plan: string,\n): TScenario[] {\n const planDigest = hashCanonical(plan)\n const emitted = new Map<string, TScenario>()\n for (const cell of improvement.raw.winnerOnHoldout.cells) {\n if (cell.error !== undefined || cell.artifact.outcome.passed) continue\n if (emitted.has(cell.scenarioId)) continue\n const source = scenarios.find((scenario) => scenario.id === cell.scenarioId)\n if (!source) continue\n emitted.set(cell.scenarioId, {\n ...structuredClone(source),\n id: `${source.id}~adversarial-${planDigest.slice('sha256:'.length, 'sha256:'.length + 12)}`,\n // The plan the failing conversation ran: the scenario's own, then the found one.\n userPlan: [source.userPlan, plan].filter(Boolean).join('\\n\\n'),\n origin: { kind: 'adversarial-user', sourceScenarioId: source.id, planDigest },\n })\n }\n return [...emitted.values()]\n}\n\nfunction pick<T extends object, K extends keyof T>(\n value: T,\n keys: readonly K[],\n): Partial<Pick<T, K>> {\n const picked: Partial<Pick<T, K>> = {}\n for (const key of keys) if (value[key] !== undefined) picked[key] = value[key]\n return picked\n}\n","// Generic judge runner — domain consumers configure dimensions + prompts.\n//\n// Three judge slots are conventional for multishot eval:\n// - conversation (scores the full transcript)\n// - codeReview (scores each code artifact)\n// - contentQuality (scores each non-code artifact)\n//\n// But the runJudge primitive is fully generic: any input maps to a score plus\n// explicit observed, estimated, or uncaptured cost.\n\nimport { DEFAULT_JUDGE_MODEL } from '../analyst/chat-client'\nimport type { JudgeDimension, JudgeScore } from '../campaign/types'\nimport type { CostProvenance } from '../cost-ledger'\nimport type { LlmCallMetadata, LlmUsage } from '../llm-client'\nimport { estimateCost, isModelPriced } from '../metrics'\nimport type { MultishotTransport, MultishotTransportResponse } from './types'\n\n// Canonical declaration lives in campaign/types.ts. Multishot emits the same\n// shape on its producer-defined 0-10 scale.\nexport type { JudgeDimension, JudgeScore } from '../campaign/types'\n\nexport interface MultishotJudgeConfig<TInput> {\n /** Display name (for trace + log). */\n name: string\n /** Caller-owned execution for this judge's call. agent-eval issues no\n * provider request and holds no credential. */\n transport: MultishotTransport\n /** Model used for this judge. */\n model?: string\n /** 0-10 scored dimensions. */\n dimensions: JudgeDimension[]\n /** Judge system prompt — sets persona + JSON-only constraint. */\n systemPrompt: string\n /** Build the user prompt from the typed input. Must include \"Respond with\n * ONLY this JSON: { ... }\" listing each dimension key. */\n buildPrompt: (input: TInput) => string\n /** Maximum output tokens for the judge response. Defaults to 1500. */\n maxTokens?: number\n}\n\nexport interface JudgeRunResult {\n /** Semantic result; failed scores remain non-throwing so matrix aggregation can exclude them. */\n score: JudgeScore\n /** Cost of the completed call, separate from diagnostic provider metadata. */\n cost: CostProvenance\n}\n\nexport async function runJudge<TInput>(\n judge: MultishotJudgeConfig<TInput>,\n input: TInput,\n): Promise<JudgeRunResult> {\n const model = judge.model ?? DEFAULT_JUDGE_MODEL\n const prompt = judge.buildPrompt(input)\n let raw = ''\n let llmCall: LlmCallMetadata\n let cost: CostProvenance\n const startedAt = Date.now()\n try {\n const response = await judge.transport({\n model,\n temperature: 0,\n maxTokens: judge.maxTokens ?? 1500,\n messages: [\n { role: 'system', content: judge.systemPrompt },\n { role: 'user', content: prompt },\n ],\n })\n const call = judgeCallMetadata(response, model, Date.now() - startedAt)\n llmCall = call.llmCall\n cost = call.cost\n raw = (response.message.content ?? '').trim()\n } catch (err) {\n // failed:true lets consumers reading `.composite` keep working while\n // aggregators exclude this score from means instead of averaging a zero.\n return {\n score: {\n dimensions: {},\n composite: 0,\n failed: true,\n notes: `judge ${judge.name} call failed: ${err instanceof Error ? err.message : String(err)}`,\n llmCall: unknownJudgeCall(model, Date.now() - startedAt),\n },\n cost: { kind: 'uncaptured', usd: null },\n }\n }\n\n let parsed: Record<string, unknown> | null = null\n try {\n const cleaned = raw\n .replace(/^```json\\s*/i, '')\n .replace(/```\\s*$/, '')\n .trim()\n parsed = JSON.parse(cleaned) as Record<string, unknown>\n } catch {\n return {\n score: {\n dimensions: {},\n composite: 0,\n failed: true,\n notes: `judge ${judge.name} returned non-JSON: ${raw.slice(0, 200)}`,\n llmCall,\n },\n cost,\n }\n }\n\n const dimensions: Record<string, number> = {}\n let sum = 0\n for (const dim of judge.dimensions) {\n const v = Number(parsed[dim.key] ?? 0)\n const clamped = Number.isFinite(v) ? Math.max(0, Math.min(10, v)) : 0\n dimensions[dim.key] = clamped\n sum += clamped\n }\n return {\n score: {\n dimensions,\n composite: judge.dimensions.length === 0 ? 0 : sum / judge.dimensions.length,\n notes: typeof parsed.notes === 'string' ? parsed.notes : '',\n llmCall,\n },\n cost,\n }\n}\n\nfunction judgeCallMetadata(\n response: MultishotTransportResponse,\n requestedModel: string,\n durationMs: number,\n): {\n llmCall: LlmCallMetadata\n cost: CostProvenance\n} {\n const usage = canonicalUsage(response.usage)\n // The transport reports the served identity when it observed one. Falling\n // back to the requested id keeps attribution honest for a transport that\n // reported none; it is not proof that model answered.\n const model = response.model ?? requestedModel\n return {\n llmCall: {\n usage,\n costUsd: response.costUsd ?? null,\n model,\n durationMs,\n },\n cost:\n response.costUsd !== undefined\n ? { kind: 'observed', usd: response.costUsd }\n : usage.captured === false || !isModelPriced(model)\n ? { kind: 'uncaptured', usd: null }\n : {\n kind: 'estimated',\n usd: estimateCost(usage.promptTokens, usage.completionTokens, model),\n },\n }\n}\n\nfunction canonicalUsage(usage: MultishotTransportResponse['usage']): LlmUsage {\n const promptTokens = tokenCount(usage?.prompt_tokens)\n const completionTokens = tokenCount(usage?.completion_tokens)\n const captured = promptTokens !== undefined && completionTokens !== undefined\n return {\n promptTokens: promptTokens ?? 0,\n completionTokens: completionTokens ?? 0,\n totalTokens: (promptTokens ?? 0) + (completionTokens ?? 0),\n captured,\n }\n}\n\nfunction unknownJudgeCall(model: string, durationMs: number): LlmCallMetadata {\n return {\n usage: { promptTokens: 0, completionTokens: 0, totalTokens: 0, captured: false },\n costUsd: null,\n model,\n durationMs,\n }\n}\n\nfunction tokenCount(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n}\n\n/** Convenience: stringified dimension list for inclusion in a judge prompt.\n * Returns lines like `- audience_fit: Does this match what the audience cares about? (0-10)`. */\nexport function renderDimensions(dims: readonly JudgeDimension[]): string {\n return dims.map((d) => `- ${d.key}: ${d.description}`).join('\\n')\n}\n\n/** Convenience: build the \"Respond with ONLY this JSON\" footer for a judge prompt. */\nexport function renderJsonFooter(dims: readonly JudgeDimension[]): string {\n const fields = dims.map((d) => `\"${d.key}\":N`).join(',')\n return `Respond with ONLY this JSON (no markdown, no preamble):\\n{${fields},\"notes\":\"1-2 sentence critique\"}`\n}\n","// Multi-turn driver-agent simulation with inline tool execution.\n//\n// The driver = LLM acting as the persona (reactive, non-deterministic).\n// The agent = the product agent under test, executed by the caller-supplied\n// transport with the profile's systemPrompt + the configured tools.\n// Tool calls execute inline via the configured executors and feed back\n// into the agent's message log so the agent integrates the result.\n//\n// agent-eval owns no model transport: every leg runs on a MultishotTransport\n// the caller supplies, so no provider credential enters this package.\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { runMultishotConversation } from './conversation'\nimport type {\n MultishotPersona,\n MultishotResult,\n MultishotShape,\n MultishotToolDefinition,\n MultishotToolExecutor,\n MultishotTransport,\n} from './types'\n\nexport interface RunMultishotOptions<TPersona extends MultishotPersona> {\n profile: AgentProfile\n persona: TPersona\n /** Persona-shaping callbacks. Optional — omitted callbacks are derived from\n * the profile + persona payload, so a pure-profile call works. */\n shape?: MultishotShape<TPersona>\n /** Tool definitions advertised to the agent. Defaults to delegate_research + delegate_code. */\n tools?: MultishotToolDefinition[]\n /** Map from tool name → executor invoked inline when the agent emits a tool_call. */\n toolExecutors?: Record<string, MultishotToolExecutor>\n /** Map from tool name → artifact type label written into MultishotArtifact.type.\n * Tools without a mapping still execute, but their results aren't surfaced as\n * typed artifacts (only as tool messages in the transcript). */\n artifactTypeFor?: (toolName: string) => string | undefined\n maxTurns?: number\n agentModel?: string\n driverModel?: string\n /** Fallback driver models tried when the primary simulated-user model returns empty twice. */\n driverFallbackModels?: string[]\n /** Maximum output tokens for the first agent call in each assistant turn. */\n agentMaxTokens?: number\n /** Maximum output tokens for agent follow-up calls after tool results. */\n toolFollowupMaxTokens?: number\n /** Maximum output tokens for each simulated-user driver response. */\n driverMaxTokens?: number\n /** Maximum tool calls the agent may dispatch inside one assistant turn. */\n maxToolDispatches?: number\n /** Caller-owned execution for the agent leg. Every agent inference step\n * runs through this function; `agentModel` names the model it receives. */\n agentTransport: MultishotTransport\n /** Caller-owned execution for the simulated-user driver leg. Driver model\n * fallback rotation still applies — the transport receives each candidate\n * model in turn. */\n driverTransport: MultishotTransport\n /** Caller-owned execution for the specialist leg the tool executors run.\n * Defaults to `agentTransport`. */\n toolTransport?: MultishotTransport\n signal?: AbortSignal\n}\n\n/** One multishot shot — the conversation engine `runMultishotMatrix` invokes\n * once per cell. `runMultishot` is the default implementation.\n *\n * An alternative engine (a graph-backed conversation, a replay of a recorded\n * transcript, a sandbox-hosted agent) implements this exact signature and\n * reaches the matrix through `RunMultishotMatrixOptions.runShot`. The matrix\n * keeps every other cell mechanic — cell fan-out, concurrency, the cost\n * ceiling, the judge slots, the cell composite, and the per-cell writers — so\n * swapping the engine needs no copy of the cell body. */\nexport type MultishotShot<TPersona extends MultishotPersona> = (\n opts: RunMultishotOptions<TPersona>,\n) => Promise<MultishotResult>\n\n/** The package's reference conversation engine, and the referent of three\n * things that stop working without it.\n *\n * 1. `runMultishotMatrix` runs it as the per-cell engine when the caller names\n * no `runShot`, so the matrix always has an engine to run.\n * 2. `golden.test.ts` proves the frozen records against it on every run, and\n * perturbs it to prove the records detect a change. Records checked only\n * against a replay of themselves prove nothing.\n * 3. The repo's recording command names it as `--engine`. The script defaults\n * no engine, so a version records whichever one the caller names — and a\n * record set minted from a consumer's engine would let a product's wiring\n * define this package's frozen contract.\n *\n * An alternative engine reaches the matrix through `runShot` and reaches the\n * records through `assertMultishotGoldenScenario`. Neither seam removes the\n * three roles above. */\nexport async function runMultishot<TPersona extends MultishotPersona>(\n opts: RunMultishotOptions<TPersona>,\n): Promise<MultishotResult> {\n return runMultishotConversation(opts, async (conversation) => {\n for (let turn = 0; turn < conversation.maxTurns; turn++) {\n await conversation.agentTurn(turn)\n if (turn < conversation.maxTurns - 1) await conversation.driverTurn(turn)\n }\n })\n}\n","// Multishot matrix wrapper — sweeps profiles × personas × reps, runs\n// the driver-agent loop per cell, applies up to three configured judges,\n// persists per-cell artifacts, and aggregates by axis.\n//\n// Uses runAgentMatrix from @tangle-network/agent-eval/matrix under the\n// hood so cell scheduling + concurrency + cost ceiling are unified with\n// other matrix consumers.\n\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport type { CostProvenance } from '../cost-ledger'\nimport type { MatrixResult } from '../matrix'\nimport { runAgentMatrix, withCellSpend } from '../matrix'\nimport { type JudgeScore, type MultishotJudgeConfig, runJudge } from './judges'\nimport { type MultishotShot, runMultishot } from './multishot'\nimport {\n assertMultishotShotResult,\n type MultishotArtifact,\n type MultishotMessage,\n type MultishotPersona,\n type MultishotShape,\n type MultishotToolDefinition,\n type MultishotToolExecutor,\n type MultishotTransport,\n} from './types'\n\nexport interface ConversationJudgeInput<TPersona extends MultishotPersona> {\n transcript: MultishotMessage[]\n persona: TPersona\n}\n\nexport interface ArtifactJudgeInput<TPersona extends MultishotPersona> {\n artifact: MultishotArtifact\n persona: TPersona\n}\n\nexport interface MultishotJudges<TPersona extends MultishotPersona> {\n /** Scores the full transcript end-to-end (always runs). */\n conversation: MultishotJudgeConfig<ConversationJudgeInput<TPersona>>\n /** Scores each code-type artifact. Optional — omit when domain has no code artifacts. */\n codeReview?: MultishotJudgeConfig<ArtifactJudgeInput<TPersona>>\n /** Scores each non-code (research/content/template) artifact. Optional. */\n contentQuality?: MultishotJudgeConfig<ArtifactJudgeInput<TPersona>>\n /** Which artifact types route to codeReview. Defaults to ['code']. */\n codeArtifactTypes?: string[]\n /** Which artifact types route to contentQuality. Defaults to ['research']. */\n contentArtifactTypes?: string[]\n}\n\nexport interface CellCompositeScore {\n composite: number\n conversation: JudgeScore\n codeReview?: {\n perArtifact: Array<JudgeScore & { turn: number; type: string }>\n composite: number\n }\n contentQuality?: {\n perArtifact: Array<JudgeScore & { turn: number; type: string }>\n composite: number\n }\n}\n\nexport interface RunMultishotMatrixOptions<TPersona extends MultishotPersona> {\n /** AgentProfile axis (matrix primary). */\n profiles: Array<{ id: string; value: AgentProfile }>\n /** Persona axis. */\n personas: TPersona[]\n /** Persona-shaping callbacks. Optional — omitted callbacks are derived per\n * cell from that cell's profile + persona payload (pure-profile path). */\n shape?: MultishotShape<TPersona>\n /** Judge configurations. */\n judges: MultishotJudges<TPersona>\n /** Tool definitions advertised to the agent. Defaults to delegate_research + delegate_code. */\n tools?: MultishotToolDefinition[]\n /** Map from tool name → inline executor. Must align with `tools`. */\n toolExecutors?: Record<string, MultishotToolExecutor>\n /** Tool name → artifact type label. Defaults to research/code mapping. */\n artifactTypeFor?: (toolName: string) => string | undefined\n /** Where per-cell artifacts land. Cells write to `<runDir>/<profileId>/<personaId>/rep-N/`. */\n runDir: string\n /** Replicates per (profile, persona) cell. */\n reps?: number\n /** Max conversation turns per cell. */\n maxTurns?: number\n /** Maximum tool calls the agent may dispatch inside one assistant turn. */\n maxToolDispatches?: number\n /** Max concurrent cells. */\n maxConcurrency?: number\n /** Total $ ceiling across the matrix; cells aborted past this. */\n costCeiling?: number\n /** Upper bound on what one cell can spend. A cell whose cost is a subtotal\n * is charged this bound against `costCeiling` instead of its known amount,\n * so hidden spend cannot walk the run past its budget. */\n maxCellCostUsd?: number\n /** Agent model. */\n agentModel?: string\n /** Driver model. */\n driverModel?: string\n /** Fallback driver models tried when the primary simulated-user model returns empty twice. */\n driverFallbackModels?: string[]\n /** Maximum output tokens for the first agent call in each assistant turn. */\n agentMaxTokens?: number\n /** Maximum output tokens for agent follow-up calls after tool results. */\n toolFollowupMaxTokens?: number\n /** Maximum output tokens for each simulated-user driver response. */\n driverMaxTokens?: number\n /** Maximum output tokens for each judge response. */\n judgeMaxTokens?: number\n /** Caller-owned execution for the agent leg of every cell (see\n * RunMultishotOptions.agentTransport). Judges are unaffected; each judge\n * carries its own transport in MultishotJudges. */\n agentTransport: MultishotTransport\n /** Caller-owned execution for the simulated-user driver leg of every cell. */\n driverTransport: MultishotTransport\n /** Caller-owned execution for the specialist leg the tool executors run in\n * every cell. Defaults to `agentTransport`. */\n toolTransport?: MultishotTransport\n /** Conversation engine for every cell. Defaults to `runMultishot`.\n *\n * The matrix owns everything around the shot — cell fan-out, concurrency,\n * the cost ceiling, the judge slots, the cell composite, the per-cell\n * artifact writers and the run summary — and forwards the whole cell input\n * to this function, so an alternative engine replaces ONLY the\n * conversation. Every option on this interface that `runMultishot` accepts\n * reaches the shot unchanged. `RunMultishotOptions.signal` has no\n * matrix-level counterpart and is not forwarded; a shot owns its own\n * cancellation.\n *\n * A shot that resolves with a value outside `MultishotResult` throws\n * `MultishotShotResultError` for that cell. The default engine is never\n * used as a fallback. */\n runShot?: MultishotShot<TPersona>\n}\n\n/** Per-cell output the multishot matrix records in `MatrixResult.cells`.\n * A consumer that supplies its own `runShot` reads the matrix through this\n * type instead of declaring a structural copy. */\nexport interface MultishotCellOutput {\n turns: number\n toolCalls: number\n artifactCount: number\n}\n\ninterface ArtifactJudgeRun {\n score: JudgeScore & { turn: number; type: string }\n cost: CostProvenance\n}\n\n/** Mean composite over non-failed scores. `0` when the list is empty (a\n * configured judge with nothing to score contributes 0, matching the cell\n * composite's long-standing semantics); `null` when scores exist but every\n * one failed — no signal, so the slot must be EXCLUDED from the cell mean\n * rather than dragging it to zero. */\nfunction meanCompositeExcludingFailed(scores: ReadonlyArray<JudgeScore>): number | null {\n if (scores.length === 0) return 0\n const live = scores.filter((s) => !s.failed)\n if (live.length === 0) return null\n return live.reduce((sum, s) => sum + s.composite, 0) / live.length\n}\n\nexport interface CellCompositeInput {\n conversation: JudgeScore\n /** Present iff the codeReview judge is configured. */\n codeReviews?: ReadonlyArray<JudgeScore>\n /** Present iff the contentQuality judge is configured. */\n contentReviews?: ReadonlyArray<JudgeScore>\n}\n\n/** Cell composite = mean over configured judge slots, excluding failed\n * scores: a failed conversation judge or an all-failed artifact slot carries\n * no signal and is dropped from the mean. `composite` is 0 only when EVERY\n * configured slot failed (`allJudgesFailed` distinguishes that from a real\n * zero). Pure — exported for deterministic testing. */\nexport function computeCellComposite(input: CellCompositeInput): {\n composite: number\n codeComposite: number\n contentComposite: number\n allJudgesFailed: boolean\n} {\n const contributions: number[] = []\n if (!input.conversation.failed) contributions.push(input.conversation.composite)\n\n const codeMean = input.codeReviews ? meanCompositeExcludingFailed(input.codeReviews) : undefined\n if (typeof codeMean === 'number') contributions.push(codeMean)\n const contentMean = input.contentReviews\n ? meanCompositeExcludingFailed(input.contentReviews)\n : undefined\n if (typeof contentMean === 'number') contributions.push(contentMean)\n\n return {\n composite:\n contributions.length === 0\n ? 0\n : contributions.reduce((s, v) => s + v, 0) / contributions.length,\n codeComposite: codeMean ?? 0,\n contentComposite: contentMean ?? 0,\n allJudgesFailed: contributions.length === 0,\n }\n}\n\nexport interface RunMultishotMatrixResult {\n matrix: MatrixResult<MultishotCellOutput>\n}\n\nexport async function runMultishotMatrix<TPersona extends MultishotPersona>(\n opts: RunMultishotMatrixOptions<TPersona>,\n): Promise<RunMultishotMatrixResult> {\n const codeTypes = new Set(opts.judges.codeArtifactTypes ?? ['code'])\n const contentTypes = new Set(opts.judges.contentArtifactTypes ?? ['research'])\n const runShot: MultishotShot<TPersona> = opts.runShot ?? runMultishot\n mkdirSync(opts.runDir, { recursive: true })\n\n const matrix = await runAgentMatrix<MultishotCellOutput>({\n axes: [\n { name: 'profile', values: opts.profiles },\n { name: 'persona', values: opts.personas.map((p) => ({ id: p.id, value: p })) },\n ],\n reps: opts.reps ?? 1,\n maxConcurrency: opts.maxConcurrency ?? 2,\n costCeiling: opts.costCeiling,\n maxCellCostUsd: opts.maxCellCostUsd,\n async runCell(cell) {\n const cellStartedAt = Date.now()\n const profile = cell.axes.profile?.value as AgentProfile\n const persona = cell.axes.persona?.value as TPersona\n const profileId = String(cell.axes.profile?.id ?? 'unknown')\n const personaId = String(cell.axes.persona?.id ?? 'unknown')\n\n // A shot that throws declares its own spend (see `runMultishot`). Rethrow\n // it untouched: a shot that declared nothing spent an unknown amount, and\n // claiming a number here would report a fabricated total.\n const sim = await runShot({\n profile,\n persona,\n shape: opts.shape,\n tools: opts.tools,\n toolExecutors: opts.toolExecutors,\n artifactTypeFor: opts.artifactTypeFor,\n maxTurns: opts.maxTurns,\n maxToolDispatches: opts.maxToolDispatches,\n agentModel: opts.agentModel,\n driverModel: opts.driverModel,\n driverFallbackModels: opts.driverFallbackModels,\n agentMaxTokens: opts.agentMaxTokens,\n toolFollowupMaxTokens: opts.toolFollowupMaxTokens,\n driverMaxTokens: opts.driverMaxTokens,\n agentTransport: opts.agentTransport,\n driverTransport: opts.driverTransport,\n toolTransport: opts.toolTransport,\n })\n // Everything from here on runs with the shot's spend already committed.\n // A throw past this line must carry it, or the money leaves the matrix's\n // cumulative sum and the cost ceiling under-counts the run.\n const shotCostUsd = shotCostSubtotal(sim)\n // A shot that says nothing about provenance is taken at its word, which\n // is how every engine written before the field behaved.\n const shotCostComplete = sim?.costProvenance?.kind !== 'uncaptured'\n let judgeCostUsd = 0\n let judgeCostComplete = false\n // Where the cell is, so a throw declares the right completeness: before\n // the judges only the shot has spent, while they are in flight their\n // spend is unknown, and after they settle their receipts decide.\n let phase: 'validate' | 'judging' | 'scoring' = 'validate'\n try {\n assertMultishotShotResult(sim)\n\n const codeArtifacts = sim.artifacts.filter((a) => codeTypes.has(a.type))\n const contentArtifacts = sim.artifacts.filter((a) => contentTypes.has(a.type))\n\n phase = 'judging'\n const [conversationRun, codeReviewRuns, contentReviewRuns] = await Promise.all([\n runJudge(withJudgeMaxTokens(opts.judges.conversation, opts.judgeMaxTokens), {\n transcript: sim.transcript,\n persona,\n }),\n opts.judges.codeReview\n ? Promise.all(\n codeArtifacts.map((artifact) =>\n runJudge(withJudgeMaxTokens(opts.judges.codeReview!, opts.judgeMaxTokens), {\n artifact,\n persona,\n }).then((result) => ({\n score: {\n ...result.score,\n turn: artifact.turn,\n type: artifact.type,\n },\n cost: result.cost,\n })),\n ),\n )\n : Promise.resolve([] as ArtifactJudgeRun[]),\n opts.judges.contentQuality\n ? Promise.all(\n contentArtifacts.map((artifact) =>\n runJudge(withJudgeMaxTokens(opts.judges.contentQuality!, opts.judgeMaxTokens), {\n artifact,\n persona,\n }).then((result) => ({\n score: {\n ...result.score,\n turn: artifact.turn,\n type: artifact.type,\n },\n cost: result.cost,\n })),\n ),\n )\n : Promise.resolve([] as ArtifactJudgeRun[]),\n ])\n const judgeRuns = [conversationRun, ...codeReviewRuns, ...contentReviewRuns]\n judgeCostUsd = judgeRuns.reduce((sum, run) => sum + (run.cost.usd ?? 0), 0)\n judgeCostComplete = judgeRuns.every((run) => run.cost.kind !== 'uncaptured')\n phase = 'scoring'\n\n const conversation = conversationRun.score\n const codeReviews = codeReviewRuns.map((run) => run.score)\n const contentReviews = contentReviewRuns.map((run) => run.score)\n\n const { composite, codeComposite, contentComposite, allJudgesFailed } =\n computeCellComposite({\n conversation,\n codeReviews: opts.judges.codeReview ? codeReviews : undefined,\n contentReviews: opts.judges.contentQuality ? contentReviews : undefined,\n })\n\n const cellScore: CellCompositeScore = { composite, conversation }\n if (opts.judges.codeReview)\n cellScore.codeReview = { perArtifact: codeReviews, composite: codeComposite }\n if (opts.judges.contentQuality)\n cellScore.contentQuality = { perArtifact: contentReviews, composite: contentComposite }\n\n const cellDir = join(opts.runDir, profileId, personaId, `rep-${cell.rep}`)\n mkdirSync(cellDir, { recursive: true })\n writeFileSync(join(cellDir, 'transcript.json'), JSON.stringify(sim.transcript, null, 2))\n writeFileSync(join(cellDir, 'artifacts.json'), JSON.stringify(sim.artifacts, null, 2))\n writeFileSync(join(cellDir, 'scores.json'), JSON.stringify(cellScore, null, 2))\n\n const notes = [`convo=${conversation.composite.toFixed(1)}`]\n if (opts.judges.codeReview) notes.push(`code=${codeComposite.toFixed(1)}`)\n if (opts.judges.contentQuality) notes.push(`content=${contentComposite.toFixed(1)}`)\n if (allJudgesFailed) notes.push('all-judges-failed')\n if (!judgeCostComplete) notes.push('judge-cost-incomplete')\n\n return {\n output: {\n turns: sim.transcript.length,\n toolCalls: sim.toolCalls,\n artifactCount: sim.artifacts.length,\n },\n verdict: { valid: composite >= 5, score: composite, notes: notes.join(' ') },\n costUsd: sim.costUsd + judgeCostUsd,\n // Either leg can leave the cell total a subtotal: a judge whose cost\n // the router never reported, or a shot that declared its own spend\n // uncaptured. The matrix counts the known part toward the ceiling and\n // reports the cell as under-counted rather than presenting the sum as\n // complete.\n costProvenance:\n judgeCostComplete && shotCostComplete\n ? { kind: 'estimated', usd: sim.costUsd + judgeCostUsd }\n : { kind: 'uncaptured', usd: null },\n durationMs: sim.durationMs,\n }\n } catch (err) {\n // No usable shot subtotal means the cell's spend is genuinely unknown;\n // rethrow untouched so the matrix records it as uncaptured instead of\n // billing a number this frame cannot support.\n if (shotCostUsd === undefined) throw err\n throw withCellSpend(err, {\n costUsd: shotCostUsd + judgeCostUsd,\n durationMs: Date.now() - cellStartedAt,\n // The judges bill before they settle, so a throw among them leaves a\n // subtotal. Before they start, and after they settle with every\n // receipt captured, the amount is the cell's whole spend — unless the\n // shot already declared its own part incomplete.\n kind:\n shotCostComplete && (phase === 'validate' || (phase === 'scoring' && judgeCostComplete))\n ? 'estimated'\n : 'uncaptured',\n })\n }\n },\n })\n\n // Persist top-level summary.\n const summary = {\n cells: matrix.summary.totalCells,\n passRate: matrix.summary.overallPassRate,\n meanScore: matrix.summary.overallMeanScore,\n totalCostUsd: matrix.summary.totalCostUsd,\n costUncapturedCells: matrix.summary.costUncapturedCells,\n ceilingChargedUsd: matrix.summary.ceilingChargedUsd,\n durationMs: matrix.summary.durationMs,\n runsExecuted: matrix.summary.runsExecuted,\n cellsSkipped: matrix.summary.cellsSkipped,\n byProfile: matrix.byAxis.profile,\n byPersona: matrix.byAxis.persona,\n }\n writeFileSync(join(opts.runDir, 'summary.json'), JSON.stringify(summary, null, 2))\n\n // A reader of the on-disk summary must not take the cost line as the run's\n // whole spend when some cells reported only a subtotal.\n const uncaptured = matrix.summary.costUncapturedCells\n const costLabel = uncaptured > 0 ? 'Cost (at least)' : 'Cost'\n\n const md: string[] = [\n `# Multishot matrix`,\n ``,\n `**Cells**: ${matrix.summary.totalCells} | **Pass rate**: ${(matrix.summary.overallPassRate * 100).toFixed(0)}% | **Mean**: ${matrix.summary.overallMeanScore.toFixed(2)} | **${costLabel}**: $${matrix.summary.totalCostUsd.toFixed(2)} | **Duration**: ${(matrix.summary.durationMs / 1000).toFixed(0)}s`,\n ``,\n ...(uncaptured > 0\n ? [\n `> ${uncaptured} of ${matrix.summary.runsExecuted} cells reported a cost subtotal, not a total. Real spend is higher than every cost figure below.`,\n ``,\n ]\n : []),\n `## By profile`,\n ``,\n '| profile | pass | mean | cost |',\n '|---|---|---|---|',\n ...Object.entries(matrix.byAxis.profile ?? {}).map(\n ([id, s]) =>\n `| ${id} | ${(s.passRate * 100).toFixed(0)}% | ${s.meanScore.toFixed(2)} | $${s.totalCostUsd.toFixed(2)} |`,\n ),\n ``,\n `## By persona`,\n ``,\n '| persona | pass | mean | cost |',\n '|---|---|---|---|',\n ...Object.entries(matrix.byAxis.persona ?? {}).map(\n ([id, s]) =>\n `| ${id} | ${(s.passRate * 100).toFixed(0)}% | ${s.meanScore.toFixed(2)} | $${s.totalCostUsd.toFixed(2)} |`,\n ),\n ``,\n ]\n writeFileSync(join(opts.runDir, 'summary.md'), md.join('\\n'))\n\n return { matrix }\n}\n\n/** The shot's own spend, when the value it resolved with reports a usable\n * amount. `undefined` when it does not — a malformed shot result is exactly\n * the case where the number cannot be trusted, and billing a wrong figure is\n * worse than recording the cell as uncaptured. */\nfunction shotCostSubtotal(\n sim: { costUsd?: unknown; costProvenance?: CostProvenance } | null | undefined,\n): number | undefined {\n const value = sim?.costUsd\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined\n}\n\nfunction withJudgeMaxTokens<TInput>(\n judge: MultishotJudgeConfig<TInput>,\n maxTokens: number | undefined,\n): MultishotJudgeConfig<TInput> {\n if (maxTokens === undefined || judge.maxTokens !== undefined) return judge\n return { ...judge, maxTokens }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA+BA,IAAa,6BAAb,cAAgD,MAAM;CACpD;CACA,YAAY,YAAqC;EAC/C,MAAM,QAAQ,SACZ,WAAW,KAAK,QAAQ,GAAG,IAAI,OAAO,IAAI,IAAI,QAAQ,GACtD,IACF;EACA,MACE,GAAG,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,MAAM,OAAO,QAAQ,aAAa,mGAClD,EACF,IACA,CAAC;EACL;EACA;EACA;EACA;EACA,GAAG,OAAO,QAAQ,OAAO,OAAO,WAAW,CAAC,CAAC,CAAC,CAAC,KAC5C,CAAC,IAAI,OACJ,KAAK,GAAG,MAAM,EAAE,WAAW,IAAA,CAAK,QAAQ,CAAC,EAAE,MAAM,EAAE,UAAU,QAAQ,CAAC,EAAE,MAAM,EAAE,aAAa,QAAQ,CAAC,EAAE,GAC5G;EACA;EACA;EACA;EACA;EACA;EACA,GAAG,OAAO,QAAQ,OAAO,OAAO,WAAW,CAAC,CAAC,CAAC,CAAC,KAC5C,CAAC,IAAI,OACJ,KAAK,GAAG,MAAM,EAAE,WAAW,IAAA,CAAK,QAAQ,CAAC,EAAE,MAAM,EAAE,UAAU,QAAQ,CAAC,EAAE,MAAM,EAAE,aAAa,QAAQ,CAAC,EAAE,GAC5G;EACA;CACF;CACA,cAAc,KAAK,KAAK,QAAQ,YAAY,GAAG,GAAG,KAAK,IAAI,CAAC;CAE5D,OAAO,EAAE,OAAO;AAClB;;;;;AAMA,SAAS,iBACP,KACoB;CACpB,MAAM,QAAQ,KAAK;CACnB,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,KAAK,SAAS,IAAI,QAAQ,KAAA;AACrF;AAEA,SAAS,mBACP,OACA,WAC8B;CAC9B,IAAI,cAAc,KAAA,KAAa,MAAM,cAAc,KAAA,GAAW,OAAO;CACrE,OAAO;EAAE,GAAG;EAAO;CAAU;AAC/B"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/multishot/conversation-conditions.ts","../../src/multishot/conversation-evidence.ts","../../src/multishot/cost.ts","../../src/multishot/default-tools.ts","../../src/multishot/shape-defaults.ts","../../src/multishot/conversation.ts","../../src/multishot/rollout.ts","../../src/multishot/realism.ts","../../src/multishot/adversarial-user.ts","../../src/multishot/judges.ts","../../src/multishot/multishot.ts","../../src/multishot/matrix.ts"],"sourcesContent":["// Equivalent conditions for comparing conversations.\n//\n// A conversation's outcome depends on the simulated user as much as on the\n// agent: Seshadri et al. (arXiv 2601.17087) measure agent success moving up\n// to 9 points across user models on one benchmark. So the simulated user is\n// part of the measurement identity, and two candidates are compared only when\n// every paired conversation met the same user on the same seed.\n//\n// What holds that:\n// - The user is outside the candidate surface by construction:\n// `multishotRollout` builds it from the scenario and its fixed options.\n// - `dispatchRef` hashes the user options, so caches and premeasured\n// baselines never cross users.\n// - `assertSameSimulatedUser` refuses paired cells with different identities\n// or seeds, and `conversationGate` runs it before any decision.\n// - `conversationJudge` scores only conversations whose agent side was the\n// candidate, so the user side can never be optimized on the agent's success.\n\nimport { defaultProductionGate } from '../campaign/gates/default-production-gate'\nimport type { Gate, GateContext, JudgeConfig, JudgeScore } from '../campaign/types'\nimport type { ConversationArtifact, ConversationScenario } from './rollout'\n\nexport interface SimulatedUserMismatch {\n cellId: string\n /** `missing`: a cell carries no identity. `simulated-user`: the identities\n * differ. `seed`: the same user ran on different seeds. */\n reason: 'missing' | 'simulated-user' | 'seed'\n detail: string\n}\n\n/** Paired conversations did not meet the same simulated user on the same seed. */\nexport class SimulatedUserMismatchError extends Error {\n readonly mismatches: SimulatedUserMismatch[]\n constructor(mismatches: SimulatedUserMismatch[]) {\n const shown = listSome(\n mismatches.map((row) => `${row.cellId}: ${row.detail}`),\n '; ',\n )\n super(\n `${mismatches.length} paired conversation(s) did not meet the same simulated user ` +\n `on the same seed, so the comparison is refused (${shown})`,\n )\n this.name = 'SimulatedUserMismatchError'\n this.mismatches = mismatches\n }\n}\n\n/** A score on the agent's success was asked to read a conversation whose\n * user side was the candidate. Optimizing the user to raise the agent's\n * success would teach it to be easy; the user side's objective is the\n * agent's failure rate, through `improveAdversarialUser` only. */\nexport class UserSideObjectiveError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'UserSideObjectiveError'\n }\n}\n\n/** A scenario an adversarial-user search emitted reached a held-out split. */\nexport class AdversarialScenarioInHeldOutError extends Error {\n readonly scenarioIds: string[]\n constructor(scenarioIds: string[]) {\n super(\n `held-out split contains ${scenarioIds.length} scenario(s) an adversarial-user search ` +\n `emitted (${listSome(scenarioIds)}); they train the agent side and never measure it`,\n )\n this.name = 'AdversarialScenarioInHeldOutError'\n this.scenarioIds = scenarioIds\n }\n}\n\n/**\n * Refuse a comparison whose paired conversations (same cell id) met different\n * simulated users or ran on different seeds, or carry no identity to show it.\n * Returns the number of pairs compared.\n */\nexport function assertSameSimulatedUser(\n baseline: ReadonlyMap<string, ConversationArtifact>,\n candidate: ReadonlyMap<string, ConversationArtifact>,\n): number {\n const mismatches: SimulatedUserMismatch[] = []\n let pairs = 0\n for (const [cellId, other] of candidate) {\n const base = baseline.get(cellId)\n if (base === undefined) continue\n pairs += 1\n const missing = (['baseline', 'candidate'] as const).filter(\n (arm) => !hasIdentity(arm === 'baseline' ? base : other),\n )\n if (missing.length > 0) {\n mismatches.push({\n cellId,\n reason: 'missing',\n detail: `${missing.join(' and ')} carries no simulated-user identity`,\n })\n } else if (base.simulatedUser.digest !== other.simulatedUser.digest) {\n mismatches.push({\n cellId,\n reason: 'simulated-user',\n detail:\n `baseline user ${base.simulatedUser.digest} (${base.simulatedUser.model}), ` +\n `candidate user ${other.simulatedUser.digest} (${other.simulatedUser.model})`,\n })\n } else if (base.seed !== other.seed) {\n mismatches.push({\n cellId,\n reason: 'seed',\n detail: `baseline seed ${base.seed}, candidate seed ${other.seed}`,\n })\n }\n }\n if (mismatches.length > 0) throw new SimulatedUserMismatchError(mismatches)\n return pairs\n}\n\n/** The first three items, and an ellipsis when there are more. Package-internal. */\nexport function listSome(items: readonly string[], separator = ', '): string {\n return [...items.slice(0, 3), ...(items.length > 3 ? ['…'] : [])].join(separator)\n}\n\nfunction hasIdentity(artifact: ConversationArtifact | undefined): boolean {\n return (\n typeof artifact?.simulatedUser?.digest === 'string' &&\n artifact.simulatedUser.digest.length > 0 &&\n Number.isFinite(artifact.seed)\n )\n}\n\n/** Refuse a held-out split that contains an adversarial-user scenario.\n * `conversationGate` runs it before the held-out run starts; run it on the\n * test cases of any comparison that does not go through that gate. */\nexport function assertHeldOutExcludesAdversarial(scenarios: readonly ConversationScenario[]): void {\n const emitted = scenarios.filter((scenario) => scenario.origin?.kind === 'adversarial-user')\n if (emitted.length > 0) {\n throw new AdversarialScenarioInHeldOutError(emitted.map((scenario) => scenario.id))\n }\n}\n\nexport interface ConversationJudgeOptions<TScenario extends ConversationScenario> {\n /** Scores a passed conversation on [0, 1] for what the outcome check does\n * not see, such as tone. A failed conversation scores 0 without it. */\n semantic?: JudgeConfig<ConversationArtifact, TScenario>\n}\n\n/**\n * Score the agent side of a conversation: 0 when the code-checked outcome\n * failed, else 1, or the semantic judge's composite when one is given. The\n * `outcome` dimension is always the code check. Refuses a conversation whose\n * user side was the candidate.\n */\nexport function conversationJudge<TScenario extends ConversationScenario>(\n opts: ConversationJudgeOptions<TScenario> = {},\n): JudgeConfig<ConversationArtifact, TScenario> {\n const semantic = opts.semantic\n return {\n name: 'conversation-outcome',\n judgeVersion: `agent-eval:conversation-outcome:v1${semantic ? `+${semantic.name}:${semantic.judgeVersion ?? 'unversioned'}` : ''}`,\n dimensions: [\n { key: 'outcome', description: '1 when the code-checked outcome passed, else 0' },\n ...(semantic?.dimensions ?? []).filter((dimension) => dimension.key !== 'outcome'),\n ],\n score(input) {\n if (input.artifact.optimizedRole !== 'agent') {\n throw new UserSideObjectiveError(\n `conversation '${input.scenario.id}' optimized the user side; the agent-success ` +\n 'score reads agent-side conversations only, and improveAdversarialUser scores ' +\n \"the user side on the agent's failure rate\",\n )\n }\n const { passed, detail } = input.artifact.outcome\n if (!passed || !semantic) {\n return { dimensions: { outcome: passed ? 1 : 0 }, composite: passed ? 1 : 0, notes: detail }\n }\n return Promise.resolve(semantic.score(input)).then(\n (score): JudgeScore => ({\n ...score,\n dimensions: { ...score.dimensions, outcome: 1 },\n notes: `${detail}\\n${score.notes}`,\n }),\n )\n },\n }\n}\n\nexport interface ConversationGateOptions<TScenario extends ConversationScenario> {\n /** The decision once conditions hold. Default `defaultProductionGate` over\n * the gate's held-out scenarios with `deltaThreshold`. */\n inner?: Gate<ConversationArtifact, TScenario>\n /** Default 0.05, as `selfImprove`'s default gate. */\n deltaThreshold?: number\n independentUnitByScenarioId?: ReadonlyMap<string, string>\n}\n\n/**\n * The promotion gate for conversations: refuses a held-out split containing\n * adversarial-user scenarios and any comparison whose arms met different\n * simulated users or seeds, then decides with `inner`.\n */\nexport function conversationGate<TScenario extends ConversationScenario>(\n opts: ConversationGateOptions<TScenario> = {},\n): Gate<ConversationArtifact, TScenario> {\n return {\n name: 'conversation',\n admitHeldOut: assertHeldOutExcludesAdversarial,\n async decide(ctx: GateContext<ConversationArtifact, TScenario>) {\n assertHeldOutExcludesAdversarial(ctx.scenarios)\n if (ctx.baselineArtifacts === undefined) {\n throw new SimulatedUserMismatchError([\n {\n cellId: '*',\n reason: 'missing',\n detail: 'the baseline arm carries no simulated-user identity: no baseline artifacts',\n },\n ])\n }\n const pairedConversations = assertSameSimulatedUser(\n ctx.baselineArtifacts,\n ctx.candidateArtifacts,\n )\n if (ctx.neutralizedArtifacts) {\n assertSameSimulatedUser(ctx.baselineArtifacts, ctx.neutralizedArtifacts)\n }\n const inner =\n opts.inner ??\n defaultProductionGate<ConversationArtifact, TScenario>({\n holdoutScenarios: ctx.scenarios,\n deltaThreshold: opts.deltaThreshold ?? 0.05,\n ...(opts.independentUnitByScenarioId\n ? { independentUnitByScenarioId: opts.independentUnitByScenarioId }\n : {}),\n })\n const result = await inner.decide(ctx)\n return {\n ...result,\n contributingGates: [\n {\n name: 'simulated-user-identity',\n status: 'pass' as const,\n detail: { pairedConversations },\n },\n ...result.contributingGates,\n ],\n }\n },\n }\n}\n","// What an optimizer is shown about one conversation. `describeConversation` is\n// the `describeArtifact` for a `ConversationArtifact`: the native reflective\n// proposer reads its JSON text in `scenarios[].emitted`, and GEPA and SkillOpt\n// receive the same value as each evaluation's evidence. Its JSON is kept\n// within `EMITTED_EVIDENCE_MAX_CHARS`, so the excerpt the native path applies\n// never cuts it and both paths carry the same object.\n\nimport { EMITTED_EVIDENCE_MAX_CHARS, excerptEvidence } from '../reflective-mutation'\nimport type { ConversationArtifact, ConversationEnding } from './rollout'\nimport type { MultishotMessage } from './types'\n\nexport interface ConversationEvidence {\n /** The code-checked outcome. */\n outcome: { passed: boolean; detail: string }\n /** How the simulated user ended the conversation. */\n ending: ConversationEnding\n agentTurns: number\n /** The driver turn at which the user first pushed back; `null` when the\n * user never did, `'undetermined'` when the rollout has no pushback rule. */\n firstPushbackTurn: number | null | 'undetermined'\n /** The transcript, its head and tail kept when it is long. */\n transcript: string\n}\n\nconst DETAIL_MAX_CHARS = 400\nconst TOOL_RESULT_MAX_CHARS = 300\n\n/** The evidence a reflection reads for one conversation. */\nexport function describeConversation(artifact: ConversationArtifact): ConversationEvidence {\n const base: ConversationEvidence = {\n outcome: {\n passed: artifact.outcome.passed,\n detail: excerptEvidence(artifact.outcome.detail, DETAIL_MAX_CHARS),\n },\n ending: { kind: artifact.ending.kind, turn: artifact.ending.turn },\n agentTurns: artifact.agentTurns,\n firstPushbackTurn: artifact.pushback.determined ? artifact.pushback.firstTurn : 'undetermined',\n transcript: '',\n }\n const full = renderTranscript(artifact.transcript)\n // JSON escaping can lengthen the kept text, so shrink the budget by the\n // overshoot until the whole object fits.\n let budget = EMITTED_EVIDENCE_MAX_CHARS - JSON.stringify(base).length\n let evidence = { ...base, transcript: excerptEvidence(full, Math.max(0, budget)) }\n for (\n let length = JSON.stringify(evidence).length;\n length > EMITTED_EVIDENCE_MAX_CHARS && budget > 0;\n length = JSON.stringify(evidence).length\n ) {\n budget -= length - EMITTED_EVIDENCE_MAX_CHARS\n evidence = { ...base, transcript: excerptEvidence(full, Math.max(0, budget)) }\n }\n return evidence\n}\n\nfunction renderTranscript(transcript: readonly MultishotMessage[]): string {\n return transcript\n .map((message) => {\n if (message.role === 'tool') {\n return `tool: ${excerptEvidence(message.content, TOOL_RESULT_MAX_CHARS)}`\n }\n if (message.role === 'user') return `user: ${message.content}`\n const calls = message.toolCalls?.map((call) => call.name) ?? []\n const called = calls.length > 0 ? ` [called ${calls.join(', ')}]` : ''\n return `agent: ${message.content}${called}`\n })\n .join('\\n')\n}\n","// Per-model cost estimator for multishot legs whose transport reported token\n// usage but no billed amount.\n\n/**\n * Rough per-model cost estimate from token counts. Underestimates Anthropic,\n * overestimates open-weight models — accurate enough for a cost ceiling, and\n * never presented as a billed amount: a leg metered from this table is\n * recorded with `estimated` provenance.\n */\nexport function estimateMultishotCost(\n model: string,\n usage?: { prompt_tokens?: number; completion_tokens?: number },\n): number {\n if (!usage) return 0\n const inputTok = usage.prompt_tokens ?? 0\n const outputTok = usage.completion_tokens ?? 0\n let inPer1k = 0.003\n let outPer1k = 0.015\n if (model.includes('gpt-4o-mini') || model.includes('gpt-6-luna')) {\n inPer1k = 0.00015\n outPer1k = 0.0006\n } else if (model.includes('gpt-5.4') || model.includes('claude-sonnet')) {\n inPer1k = 0.003\n outPer1k = 0.015\n } else if (model.includes('kimi') || model.includes('glm') || model.includes('deepseek')) {\n inPer1k = 0.0005\n outPer1k = 0.002\n }\n return (inputTok * inPer1k + outputTok * outPer1k) / 1000\n}\n","// Default delegate_research + delegate_code tools and their inline executors.\n//\n// Consumers can override either by passing their own tools + executors to\n// runMultishot. The defaults are sufficient for most domains — point the\n// researcher system prompt at your domain's citation style and the coder\n// at your preferred language.\n\nimport { estimateMultishotCost } from './cost'\nimport type { MultishotToolDefinition, MultishotToolExecutor } from './types'\n\nconst DEFAULT_RESEARCHER_MODEL = 'openai/gpt-6-luna'\nexport const DEFAULT_CODER_MODEL = 'openai/gpt-6-luna'\n\nexport interface DefaultResearcherConfig {\n /** Replace the system prompt to bias the researcher toward a domain's\n * citation style. Defaults to a generic \"cite sources by name\" prompt. */\n systemPrompt?: string\n model?: string\n}\n\nexport interface DefaultCoderConfig {\n /** Replace the system prompt to bias the coder toward a language /\n * framework / artifact style. */\n systemPrompt?: string\n model?: string\n}\n\nconst GENERIC_RESEARCHER_SYSTEM =\n 'You are a research specialist. Return a markdown brief with 3-5 findings. Each finding cites a specific source by name. Add a confidence level (high/medium/low) per finding. No fluff, no preamble.'\n\nconst GENERIC_CODER_SYSTEM =\n 'You are an expert engineer. Output ONE fenced code block containing the complete solution. Inline-comment non-obvious decisions. No explanation outside the block.'\n\nconst DEFAULT_DELEGATE_RESEARCH_TOOL: MultishotToolDefinition = {\n type: 'function',\n function: {\n name: 'delegate_research',\n description:\n 'Research a topic deeply via specialist. Returns evidence-bearing items with citations. Use for audience research, competitive intel, regulatory landscape, market data, citation-grounded analysis.',\n parameters: {\n type: 'object',\n properties: {\n question: { type: 'string', description: 'Specific question to research' },\n scope: {\n type: 'string',\n description: 'Optional scope: time window, geography, jurisdiction, segment',\n },\n },\n required: ['question'],\n },\n },\n}\n\nconst DEFAULT_DELEGATE_CODE_TOOL: MultishotToolDefinition = {\n type: 'function',\n function: {\n name: 'delegate_code',\n description:\n 'Generate a runnable script, template, pipeline, or tool via specialist. Returns complete working code or structured markdown. Use for content pipelines, calc snippets, dashboards, compliance checklists, deadline trackers.',\n parameters: {\n type: 'object',\n properties: {\n goal: { type: 'string', description: 'What the code must accomplish' },\n language: {\n type: 'string',\n description: 'Optional language preference (default: TypeScript)',\n },\n },\n required: ['goal'],\n },\n },\n}\n\nfunction createResearchExecutor(config: DefaultResearcherConfig = {}): MultishotToolExecutor {\n const systemPrompt = config.systemPrompt ?? GENERIC_RESEARCHER_SYSTEM\n const model = config.model ?? DEFAULT_RESEARCHER_MODEL\n return async (args, ctx) => {\n const question = String(args.question ?? '')\n const scope = args.scope ? String(args.scope) : undefined\n const { message, usage, costUsd } = await ctx.transport({\n model,\n temperature: 0.3,\n maxTokens: 1800,\n messages: [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: `Research: ${question}${scope ? `\\nScope: ${scope}` : ''}` },\n ],\n signal: ctx.signal,\n })\n return {\n content: message.content ?? '',\n costUsd: costUsd ?? estimateMultishotCost(model, usage),\n }\n }\n}\n\nfunction createCodeExecutor(config: DefaultCoderConfig = {}): MultishotToolExecutor {\n const systemPrompt = config.systemPrompt ?? GENERIC_CODER_SYSTEM\n const model = config.model ?? DEFAULT_CODER_MODEL\n return async (args, ctx) => {\n const goal = String(args.goal ?? '')\n const language = args.language ? String(args.language) : 'TypeScript'\n const { message, usage, costUsd } = await ctx.transport({\n model,\n temperature: 0.2,\n maxTokens: 2000,\n messages: [\n { role: 'system', content: `${systemPrompt}\\n\\nLanguage: ${language}` },\n { role: 'user', content: `Produce: ${goal}` },\n ],\n signal: ctx.signal,\n })\n return {\n content: message.content ?? '',\n costUsd: costUsd ?? estimateMultishotCost(model, usage),\n }\n }\n}\n\nexport interface DefaultToolsConfig {\n research?: DefaultResearcherConfig\n code?: DefaultCoderConfig\n /** When true (default), each tool result is recorded as a typed artifact:\n * research → type='research', code → type='code'. */\n recordArtifacts?: boolean\n}\n\nexport interface DefaultToolsBundle {\n tools: MultishotToolDefinition[]\n executors: Record<string, MultishotToolExecutor>\n artifactTypeFor: (toolName: string) => string | undefined\n}\n\nexport function defaultDelegationTools(config: DefaultToolsConfig = {}): DefaultToolsBundle {\n return {\n tools: [DEFAULT_DELEGATE_RESEARCH_TOOL, DEFAULT_DELEGATE_CODE_TOOL],\n executors: {\n delegate_research: createResearchExecutor(config.research),\n delegate_code: createCodeExecutor(config.code),\n },\n artifactTypeFor: (name) =>\n name === 'delegate_research' ? 'research' : name === 'delegate_code' ? 'code' : undefined,\n }\n}\n","// Profile-derived defaults for MultishotShape — the pure-profile path.\n//\n// `MultishotShape`'s callbacks were REQUIRED beside `profile: AgentProfile`,\n// which mixed the abstractions: the node under test was a profile, but the\n// simulated user's role could only be expressed as code. These defaults make\n// the callbacks optional — a pure-profile call works, and the derived prompts\n// are plain data (a pure function of profile + persona payload), so an\n// optimizer can sweep them (tangle-network/agent-runtime#694).\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport type { MultishotPersona, MultishotShape } from './types'\n\n/** Persona payload rendered as stable `- key: value` lines. `id` is identity,\n * not voice, and structured values are serialized so nothing is dropped. */\nfunction renderPersonaFacts(persona: MultishotPersona): string {\n const lines: string[] = []\n for (const [key, value] of Object.entries(persona)) {\n if (key === 'id' || value === undefined) continue\n const rendered =\n typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean'\n ? String(value)\n : JSON.stringify(value)\n lines.push(`- ${key}: ${rendered}`)\n }\n return lines.join('\\n')\n}\n\n/** Default opening user message: the persona introduces itself with its whole\n * payload and asks the agent (as described by the profile) to take over. */\nfunction defaultMultishotOpener(profile: AgentProfile, persona: MultishotPersona): string {\n const facts = renderPersonaFacts(persona)\n const agentDescription = profile.description ?? profile.name ?? 'the agent'\n return [\n `Hi — I'm reaching out to ${agentDescription} for help. My situation:`,\n facts.length > 0 ? facts : `- (no details provided beyond id: ${persona.id})`,\n '',\n 'Tell me what you need from me, and get started on my case.',\n ].join('\\n')\n}\n\n/** Default driver system prompt: roleplay the persona from its payload, stay\n * in character, push back on vague answers, and never go silent. */\nfunction defaultMultishotDriverSystemPrompt(\n profile: AgentProfile,\n persona: MultishotPersona,\n): string {\n const facts = renderPersonaFacts(persona)\n const agentDescription = profile.description ?? profile.name ?? 'an AI agent'\n return [\n `You are role-playing a real person (persona \"${persona.id}\") talking to ${agentDescription}.`,\n facts.length > 0 ? `Who you are:\\n${facts}` : '',\n '',\n 'How to behave:',\n '- Stay in character: first person, realistic voice, concrete details from your situation.',\n '- Judge every reply by whether it actually moves YOUR case forward. Push back on vague, hedged, or generic answers and demand specifics.',\n \"- Answer the agent's questions with information consistent with who you are; invent plausible details rather than stalling.\",\n '- Never go silent: always produce a substantive next message.',\n '- Output ONLY your next message to the agent — no meta-commentary, no stage directions.',\n ]\n .filter((block) => block.length > 0)\n .join('\\n')\n}\n\n/** The fully-resolved shape for a profile: caller overrides win, the\n * profile-derived defaults fill the rest. */\nexport function defaultShapeFromProfile<TPersona extends MultishotPersona>(\n profile: AgentProfile,\n shape?: MultishotShape<TPersona>,\n): Required<MultishotShape<TPersona>> {\n return {\n buildOpener: shape?.buildOpener ?? ((persona) => defaultMultishotOpener(profile, persona)),\n buildDriverSystemPrompt:\n shape?.buildDriverSystemPrompt ??\n ((persona) => defaultMultishotDriverSystemPrompt(profile, persona)),\n }\n}\n","// The multishot conversation's two legs, separable from the loop that orders\n// them.\n//\n// `runMultishot` orders the legs as a plain turn loop. A caller that orders\n// them another way — a Runtime flow graph, a scheduler, a replay harness —\n// drives the same legs through `runMultishotConversation`, so the transcript,\n// artifacts, tool-call count, driver point of view and cost accounting stay\n// this package's single implementation.\n//\n// agent-eval owns no model transport: every leg runs on a MultishotTransport\n// the caller supplies, so no provider credential enters this package.\n\nimport { withCellSpend } from '../matrix'\nimport { estimateMultishotCost } from './cost'\nimport { defaultDelegationTools } from './default-tools'\nimport type { RunMultishotOptions } from './multishot'\nimport { defaultShapeFromProfile } from './shape-defaults'\nimport {\n type MultishotArtifact,\n MultishotDriverEmptyError,\n MultishotFatalToolError,\n type MultishotMessage,\n type MultishotPersona,\n type MultishotResult,\n type MultishotTransport,\n type MultishotTransportResponse,\n} from './types'\n\n/** Prompt and completion tokens one leg reported. */\nexport interface MultishotLegTokens {\n input: number\n output: number\n}\n\n/** What one leg spent: its tokens and the USD it added to the conversation's\n * cost (provider-reported, else estimated from usage; tool executor spend\n * included). */\nexport interface MultishotLegSpend {\n tokens: MultishotLegTokens\n usd: number\n}\n\n/** One conversation's state and legs. Each leg appends to the shared\n * transcript; the caller decides the order in which legs run. */\nexport interface MultishotConversation {\n /** Agent turns the conversation is configured for (`opts.maxTurns ?? 10`). */\n readonly maxTurns: number\n /** The model the agent leg runs on. */\n readonly agentModel: string\n /** The primary simulated-user model. */\n readonly driverModel: string\n /** The persona's first message, already in the transcript. */\n readonly opener: string\n /** The simulated user's system prompt. */\n readonly driverSystemPrompt: string\n /** One agent turn: inference, inline tool execution and follow-up inference,\n * until the agent answers without tools. Throws on abort, on a fatal tool\n * error and on the per-turn tool dispatch cap. */\n agentTurn(turn: number): Promise<MultishotLegSpend>\n /** The simulated user's reply to the transcript so far, appended for the\n * next agent turn. Retries an empty reply once per model, rotates through\n * the fallback models, then throws `MultishotDriverEmptyError`. */\n driverTurn(turn: number): Promise<MultishotLegSpend & { content: string }>\n}\n\n/** Orders the legs of one conversation. Resolves when the conversation is done. */\nexport type MultishotConversationDriver = (conversation: MultishotConversation) => Promise<void>\n\ninterface ConversationMeter {\n costUsd: number\n startedAt: number\n /** True once a call contributed a fabricated `0` — no provider cost and no\n * usage to price. `costUsd` is a subtotal from that point on. */\n uncaptured: boolean\n}\n\n/**\n * Run one multishot conversation whose leg order `drive` decides.\n *\n * Returns the conversation's `MultishotResult`. When any leg or `drive` throws,\n * the error is rethrown carrying the spend so far (`withCellSpend`), so a\n * matrix bills the failed cell for the turns it already paid for.\n */\nexport async function runMultishotConversation<TPersona extends MultishotPersona>(\n opts: RunMultishotOptions<TPersona>,\n drive: MultishotConversationDriver,\n): Promise<MultishotResult> {\n const meter: ConversationMeter = { costUsd: 0, startedAt: Date.now(), uncaptured: false }\n try {\n const state = openConversation(opts, meter)\n await drive(state.conversation)\n return {\n transcript: state.transcript,\n artifacts: state.artifacts,\n toolCalls: state.toolCalls(),\n durationMs: Date.now() - meter.startedAt,\n costUsd: meter.costUsd,\n // A shot that priced every call reports a complete estimate. One that had\n // a call the router priced at nothing reports a subtotal, so the cell is\n // recorded as under-counted rather than as a complete estimate.\n costProvenance: meter.uncaptured\n ? { kind: 'uncaptured', usd: null }\n : { kind: 'estimated', usd: meter.costUsd },\n }\n } catch (err) {\n throw withCellSpend(err, {\n costUsd: meter.costUsd,\n durationMs: Date.now() - meter.startedAt,\n kind: meter.uncaptured ? 'uncaptured' : 'estimated',\n })\n }\n}\n\nfunction openConversation<TPersona extends MultishotPersona>(\n opts: RunMultishotOptions<TPersona>,\n meter: ConversationMeter,\n): {\n conversation: MultishotConversation\n transcript: MultishotMessage[]\n artifacts: MultishotArtifact[]\n toolCalls: () => number\n} {\n const maxTurns = opts.maxTurns ?? 10\n const maxToolDispatches = opts.maxToolDispatches ?? 4\n const agentModel = opts.agentModel ?? 'openai/gpt-5.4'\n const driverModel = opts.driverModel ?? 'openai/gpt-6-luna'\n const driverModels = [driverModel, ...(opts.driverFallbackModels ?? [])]\n const agentMaxTokens = opts.agentMaxTokens ?? 2500\n const toolFollowupMaxTokens = opts.toolFollowupMaxTokens ?? 2000\n const driverMaxTokens = opts.driverMaxTokens ?? 600\n\n const bundle =\n opts.tools && opts.toolExecutors\n ? {\n tools: opts.tools,\n executors: opts.toolExecutors,\n artifactTypeFor: opts.artifactTypeFor ?? (() => undefined),\n }\n : defaultDelegationTools()\n const tools = opts.tools ?? bundle.tools\n const executors = opts.toolExecutors ?? bundle.executors\n const artifactTypeFor = opts.artifactTypeFor ?? bundle.artifactTypeFor\n\n const agentTransport = opts.agentTransport\n const driverTransport = opts.driverTransport\n const toolTransport = opts.toolTransport ?? agentTransport\n\n const shape = defaultShapeFromProfile(opts.profile, opts.shape)\n\n const transcript: MultishotMessage[] = []\n const artifacts: MultishotArtifact[] = []\n let toolCalls = 0\n\n const opener = shape.buildOpener(opts.persona)\n transcript.push({ role: 'user', content: opener })\n\n const systemPrompt = [opts.profile.prompt?.systemPrompt, opts.profile.prompt?.appendSystemPrompt]\n .filter((value): value is string => Boolean(value))\n .join('\\n\\n')\n const agentMessages: Array<Record<string, unknown>> = [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: opener },\n ]\n const driverSystemPrompt = shape.buildDriverSystemPrompt(opts.persona)\n\n async function agentTurn(turn: number): Promise<MultishotLegSpend> {\n if (opts.signal?.aborted) throw new Error('multishot aborted')\n const usdBefore = meter.costUsd\n const tokens = { input: 0, output: 0 }\n let dispatchesThisTurn = 0\n while (true) {\n const {\n message: agentMsg,\n usage: agentUsage,\n costUsd: agentCostUsd,\n } = await agentTransport({\n model: agentModel,\n messages: agentMessages,\n tools,\n temperature: 0.7,\n maxTokens: dispatchesThisTurn === 0 ? agentMaxTokens : toolFollowupMaxTokens,\n signal: opts.signal,\n })\n meter.costUsd += agentCostUsd ?? estimateMultishotCost(agentModel, agentUsage)\n if (agentCostUsd === undefined && agentUsage === undefined) meter.uncaptured = true\n tokens.input += agentUsage?.prompt_tokens ?? 0\n tokens.output += agentUsage?.completion_tokens ?? 0\n\n const agentText = (agentMsg.content ?? '').trim()\n const agentToolCalls = (agentMsg.tool_calls ?? []).map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n args: (() => {\n try {\n return JSON.parse(tc.function.arguments) as Record<string, unknown>\n } catch {\n return {} as Record<string, unknown>\n }\n })(),\n }))\n\n agentMessages.push({\n role: 'assistant',\n content: agentText || null,\n ...(agentMsg.tool_calls?.length ? { tool_calls: agentMsg.tool_calls } : {}),\n })\n transcript.push({\n role: 'assistant',\n content: agentText,\n toolCalls: agentToolCalls.length > 0 ? agentToolCalls : undefined,\n })\n\n if (agentToolCalls.length === 0) break\n dispatchesThisTurn += agentToolCalls.length\n if (dispatchesThisTurn > maxToolDispatches) {\n throw new Error(\n `multishot: tool dispatch cap exceeded (${dispatchesThisTurn}/${maxToolDispatches}) on turn ${turn}`,\n )\n }\n\n for (const tc of agentToolCalls) {\n toolCalls++\n let toolResult = ''\n try {\n const executor = executors[tc.name]\n if (!executor) {\n toolResult = JSON.stringify({ error: `unknown tool ${tc.name}` })\n } else {\n const r = await executor(tc.args, { transport: toolTransport, signal: opts.signal })\n toolResult = r.content\n meter.costUsd += r.costUsd\n const artifactType = artifactTypeFor(tc.name)\n if (artifactType) {\n artifacts.push({\n type: artifactType,\n turn,\n invocation: { name: tc.name, args: tc.args },\n content: toolResult,\n })\n }\n }\n } catch (err) {\n if (err instanceof MultishotFatalToolError) throw err\n toolResult = JSON.stringify({ error: err instanceof Error ? err.message : String(err) })\n }\n agentMessages.push({ role: 'tool', tool_call_id: tc.id, content: toolResult || 'done' })\n transcript.push({ role: 'tool', content: toolResult || 'done', toolCallId: tc.id })\n }\n }\n return { tokens, usd: meter.costUsd - usdBefore }\n }\n\n // Every driver attempt is charged, including the empty ones that force a\n // retry and the ones that precede `MultishotDriverEmptyError`: those calls\n // billed the provider whether or not their content was usable.\n async function driverTurn(turn: number): Promise<MultishotLegSpend & { content: string }> {\n const usdBefore = meter.costUsd\n const tokens = { input: 0, output: 0 }\n const content = await requestUserReply({\n models: driverModels,\n messages: driverViewMessages(driverSystemPrompt, transcript),\n transport: driverTransport,\n maxTokens: driverMaxTokens,\n signal: opts.signal,\n turn,\n onResponse: (model, { usage, costUsd }) => {\n meter.costUsd += costUsd ?? estimateMultishotCost(model, usage)\n if (costUsd === undefined && usage === undefined) meter.uncaptured = true\n tokens.input += usage?.prompt_tokens ?? 0\n tokens.output += usage?.completion_tokens ?? 0\n },\n })\n agentMessages.push({ role: 'user', content })\n transcript.push({ role: 'user', content })\n return { content, tokens, usd: meter.costUsd - usdBefore }\n }\n\n return {\n conversation: {\n maxTurns,\n agentModel,\n driverModel,\n opener,\n driverSystemPrompt,\n agentTurn,\n driverTurn,\n },\n transcript,\n artifacts,\n toolCalls: () => toolCalls,\n }\n}\n\n/** The simulated user's next message. The driver must never go silent: an\n * empty reply is retried once per model, the models are tried in order, and\n * then `MultishotDriverEmptyError` is thrown. Every response, empty ones\n * included, reaches `onResponse`, because every attempt was billed. The\n * conversation loop and the realism measure both ask the simulated user\n * through here, so a driver measured against recorded turns is sampled the\n * way a rollout samples it. */\nexport async function requestUserReply(input: {\n models: readonly string[]\n messages: Array<Record<string, unknown>>\n transport: MultishotTransport\n maxTokens: number\n signal?: AbortSignal\n turn: number\n onResponse?: (model: string, response: MultishotTransportResponse) => void\n}): Promise<string> {\n for (const model of input.models) {\n for (let attempt = 0; attempt < 2; attempt++) {\n const response = await input.transport({\n model,\n messages: input.messages,\n temperature: 0.9,\n maxTokens: input.maxTokens,\n signal: input.signal,\n })\n input.onResponse?.(model, response)\n const content = (response.message.content ?? '').trim()\n if (content.length > 0) return content\n }\n }\n throw new MultishotDriverEmptyError(input.turn)\n}\n\n/** The simulated user's view of a transcript, as the driver request's\n * messages. The agent's `assistant` messages become `user` (the agent talking\n * TO the driver); the driver's prior `user` messages become `assistant` (its\n * own earlier replies). Tool messages are hidden. The conversation loop and\n * the realism measure both build the driver's request here, so a driver\n * measured against recorded turns sees exactly what it sees in a rollout. */\nexport function driverViewMessages(\n driverSystemPrompt: string,\n transcript: readonly MultishotMessage[],\n): Array<Record<string, unknown>> {\n const driverMessages: Array<Record<string, unknown>> = [\n { role: 'system', content: driverSystemPrompt },\n ]\n for (const msg of transcript) {\n if (msg.role === 'tool') continue\n const content = driverVisibleContent(msg)\n if (!content) continue\n if (msg.role === 'assistant') driverMessages.push({ role: 'user', content })\n else if (msg.role === 'user') driverMessages.push({ role: 'assistant', content })\n }\n return driverMessages\n}\n\n/** Silent tool-calling agent turns surface to the driver as\n * \"Agent called tools: …\" so the simulated user can react to them. */\nfunction driverVisibleContent(msg: MultishotMessage): string | null {\n const text = msg.content.trim()\n if (text.length > 0) return text\n if (msg.role !== 'assistant' || !msg.toolCalls?.length) return null\n\n const toolNames = msg.toolCalls.map((call) => call.name.trim()).filter(Boolean)\n if (toolNames.length === 0) return 'Agent called tools.'\n return `Agent called ${toolNames.length === 1 ? 'tool' : 'tools'}: ${toolNames.join(', ')}.`\n}\n","// A multishot conversation as an optimization dispatch.\n//\n// `multishotRollout` turns the conversation engine into the\n// `agent(surface, scenario, ctx)` function `selfImprove` and\n// `compareOptimizationMethods` call per cell. The candidate surface becomes\n// the agent's profile; the simulated user is a function of the scenario and\n// the rollout's fixed options alone, so every candidate meets the same user on\n// the same seed. Every leg is a paid call through the cell's `ctx.cost`, the\n// transcript is the artifact, and a code-checked outcome is the objective part\n// of the score. There is one conversation loop: `runMultishotConversation`.\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport type { DispatchContext, MutableSurface, Scenario } from '../campaign/types'\nimport type { CostChannel, CostReceiptInput, MaximumCharge } from '../cost-ledger/contract'\nimport { hashCanonical, jsonDocument } from '../ledger-core/canonical'\nimport type { PersonaRigor } from '../types'\nimport { runMultishotConversation } from './conversation'\nimport { defaultShapeFromProfile } from './shape-defaults'\nimport type {\n MultishotArtifact,\n MultishotMessage,\n MultishotPersona,\n MultishotShape,\n MultishotToolDefinition,\n MultishotToolExecutor,\n MultishotTransport,\n MultishotTransportRequest,\n MultishotTransportResponse,\n} from './types'\n\n/** A scenario a simulated user plays: its persona, and optionally a plan. */\nexport interface ConversationScenario<TPersona extends MultishotPersona = MultishotPersona>\n extends Scenario {\n persona: TPersona\n /** What the simulated user sets out to do in this scenario, appended to its\n * prompt. Part of the simulated-user identity. */\n userPlan?: string\n /** Set on a scenario an adversarial-user search emitted. Such a scenario\n * trains the agent side and never enters a held-out split. */\n origin?: {\n kind: 'adversarial-user'\n sourceScenarioId: string\n planDigest: string\n /** The conversation that showed the scenario can be passed under its\n * plan. Set on every emitted scenario; absent on an unsolvable candidate. */\n solvedBy?: ScenarioSolvedBy\n }\n}\n\n/** A passing conversation of an emitted scenario: which agent passed it, on\n * which seed, and what the outcome check said. */\nexport interface ScenarioSolvedBy {\n agent: 'reference' | 'same'\n profileDigest: string\n seed: number\n detail: string\n}\n\n/** The code-checked outcome of one conversation: the objective part of its score. */\nexport interface ConversationOutcome {\n passed: boolean\n detail: string\n}\n\n/** How a conversation ended. `turn` is the agent turn after which it ended. */\nexport interface ConversationEnding {\n kind: 'signed-off' | 'gave-up' | 'turn-cap'\n turn: number\n}\n\nexport type UserEndingClassification =\n | { kind: 'continue' }\n | { kind: 'signed-off' | 'gave-up'; message: string }\n\n/** How the simulated user ends a conversation before the turn cap. */\nexport interface UserEndingProtocol {\n /** Stable name of `classify`'s rule. Part of the simulated-user identity. */\n ref: string\n /** Appended to the simulated user's prompt. Part of its identity. */\n instructions: string\n /** Reads one simulated-user message. An ending returns the message with its\n * protocol marker removed: the marker is protocol, never something the\n * agent sees or the user said. */\n classify(message: string): UserEndingClassification\n}\n\nconst SIGNED_OFF = '[[signed-off]]'\nconst GAVE_UP = '[[gave-up]]'\n\n/** Ends on `[[signed-off]]` when the user's problem is resolved and on\n * `[[gave-up]]` when the user would stop using the service. */\nexport const DEFAULT_USER_ENDING: UserEndingProtocol = {\n ref: 'agent-eval:user-ending-markers:v1',\n instructions: [\n `When your problem is resolved to your standard, end your message with ${SIGNED_OFF}.`,\n `If you would stop using this service now because the agent is not getting anywhere, end your message with ${GAVE_UP}.`,\n 'Otherwise use neither marker.',\n ].join('\\n'),\n classify(message) {\n for (const [marker, kind] of [\n [SIGNED_OFF, 'signed-off'],\n [GAVE_UP, 'gave-up'],\n ] as const) {\n if (message.includes(marker)) return { kind, message: message.split(marker).join('').trim() }\n }\n return { kind: 'continue' }\n },\n}\n\n/** How each rigor level asks the simulated user to push back, as\n * `PersonaRigor` defines them. */\nconst RIGOR_STANCE: Record<PersonaRigor, string> = {\n cooperative:\n 'Your stance: a forgiving early adopter. Accept a reasonable answer and move on; push back only when the agent is clearly wrong or stuck.',\n demanding:\n 'Your stance: an experienced professional. Reject vague or hedged answers and ask for specifics before you accept anything.',\n relentless:\n 'Your stance: you are reviewing this for someone who will hold you to it. Interrogate every claim and accept nothing the agent has not defended.',\n}\n\n/** The simulated user. Its options never depend on the candidate surface. */\nexport interface SimulatedUserOptions<TPersona extends MultishotPersona = MultishotPersona> {\n model: string\n /** Tried in order when a model returns an empty message twice. */\n fallbackModels?: string[]\n transport: MultishotTransport\n /** Default `'demanding'`. */\n rigor?: PersonaRigor\n /** How the user refers to the agent. Fixed for the simulated user: its\n * prompt never derives from the candidate profile. Default `'an AI agent'`. */\n agentDescription?: string\n /** Overrides the derived opener and prompt; requires `shapeRef`. */\n shape?: MultishotShape<TPersona>\n /** Stable name for `shape`'s callbacks. Part of the simulated-user identity. */\n shapeRef?: string\n /** Maximum output tokens per simulated-user message. Default 600. */\n maxTokens?: number\n /** Default `DEFAULT_USER_ENDING`. */\n ending?: UserEndingProtocol\n /** Recognizes a user message that pushes back on the agent's last reply.\n * Without it the first pushback turn is reported as undetermined. */\n pushback?: (message: string) => boolean\n}\n\n/** The agent leg: everything about the agent except the candidate surface. */\nexport interface ConversationAgentOptions {\n model: string\n transport: MultishotTransport\n /** Tools advertised to the agent. Default: none. */\n tools?: MultishotToolDefinition[]\n /** Required with `tools`. Paid work runs through the executor's\n * `ctx.transport`, which is metered; other executor spend is not. */\n toolExecutors?: Record<string, MultishotToolExecutor>\n artifactTypeFor?: (toolName: string) => string | undefined\n /** Default: `transport`. */\n toolTransport?: MultishotTransport\n maxTokens?: number\n toolFollowupMaxTokens?: number\n maxToolDispatches?: number\n}\n\n/** What the outcome check reads. */\nexport interface ConversationRecord {\n transcript: MultishotMessage[]\n artifacts: MultishotArtifact[]\n ending: ConversationEnding\n}\n\nexport type ConversationLeg = 'agent' | 'user' | 'tool'\n\nexport interface MultishotRolloutOptions<TScenario extends ConversationScenario> {\n agent: ConversationAgentOptions\n /** The agent profile a candidate surface becomes. Default: a text surface\n * is the agent's system prompt; any other surface needs this mapping. */\n profile?: (surface: MutableSurface, scenario: TScenario) => AgentProfile\n user: SimulatedUserOptions<TScenario['persona']>\n /** Agent turns at most. The simulated user may end the conversation sooner. */\n maxTurns: number\n /** Decides by code whether the conversation reached its goal. */\n outcome: (conversation: ConversationRecord, scenario: TScenario) => ConversationOutcome\n /** Hard maximum for one leg's call, required by a capped campaign. */\n maximumCharge?: (\n leg: ConversationLeg,\n request: MultishotTransportRequest,\n ) => MaximumCharge | undefined\n /** Version of behavior the options cannot show, such as tool executor code\n * or the outcome rule. Part of `dispatchRef`. */\n revision?: string\n}\n\n/** Who the agent talked to. Equal digests mean the same simulated user: model,\n * fallbacks, rigor, persona, prompt, opener and ending protocol. */\nexport interface SimulatedUserIdentity {\n digest: string\n model: string\n fallbackModels: string[]\n rigor: PersonaRigor\n personaId: string\n personaDigest: string\n promptDigest: string\n openerDigest: string\n endingRef: string\n shapeRef: string\n maxTokens: number\n}\n\nexport type PushbackReading = { determined: false } | { determined: true; firstTurn: number | null }\n\n/** One conversation, as the dispatch returns it. */\nexport interface ConversationArtifact {\n transcript: MultishotMessage[]\n artifacts: MultishotArtifact[]\n toolCalls: number\n agentTurns: number\n ending: ConversationEnding\n outcome: ConversationOutcome\n /** The driver turn at which the user first pushed back on the agent. */\n pushback: PushbackReading\n simulatedUser: SimulatedUserIdentity\n /** The campaign cell seed every leg asked for. */\n seed: number\n /** Which side of the conversation the candidate surface was. A score on\n * the agent's success only reads `'agent'` conversations. */\n optimizedRole: 'agent' | 'user'\n}\n\nexport interface MultishotRollout<TScenario extends ConversationScenario> {\n /** The dispatch: run one conversation with `surface` as the agent. */\n agent: (\n surface: MutableSurface,\n scenario: TScenario,\n ctx: DispatchContext,\n ) => Promise<ConversationArtifact>\n /** Version of everything but the surface, for measurement caches. */\n dispatchRef: string\n /** The simulated user `agent` puts in front of the agent for `scenario`. */\n simulatedUser: (scenario: TScenario) => SimulatedUserIdentity\n}\n\n/** The simulated user's opener and system prompt for one persona and plan. */\nexport interface SimulatedUserSetup {\n opener: string\n driverSystemPrompt: string\n identity: SimulatedUserIdentity\n}\n\n/** Builds the simulated user from its options alone. The rollout and the\n * realism measure both build it here, so a measured driver is the driver a\n * rollout runs. */\nexport function simulatedUserSetup<TPersona extends MultishotPersona>(\n user: SimulatedUserOptions<TPersona>,\n persona: TPersona,\n plan?: string,\n): SimulatedUserSetup {\n if (user.shape !== undefined && !user.shapeRef) {\n throw new TypeError('simulated user: a custom shape needs a shapeRef naming its callbacks')\n }\n const rigor = user.rigor ?? 'demanding'\n const ending = user.ending ?? DEFAULT_USER_ENDING\n const shape = defaultShapeFromProfile<TPersona>(\n { name: 'agent', description: user.agentDescription ?? 'an AI agent' },\n user.shape,\n )\n const opener = shape.buildOpener(persona)\n const driverSystemPrompt = [\n shape.buildDriverSystemPrompt(persona),\n RIGOR_STANCE[rigor],\n ending.instructions,\n plan ? `Your plan for this conversation:\\n${plan}` : '',\n ]\n .filter((block) => block.length > 0)\n .join('\\n\\n')\n const fields = {\n model: user.model,\n fallbackModels: [...(user.fallbackModels ?? [])],\n rigor,\n personaId: persona.id,\n personaDigest: hashCanonical(jsonDocument(persona)),\n promptDigest: hashCanonical(driverSystemPrompt),\n openerDigest: hashCanonical(opener),\n endingRef: ending.ref,\n shapeRef: user.shapeRef ?? 'agent-eval:default-shape',\n maxTokens: user.maxTokens ?? 600,\n }\n return {\n opener,\n driverSystemPrompt,\n identity: { digest: hashCanonical(jsonDocument(fields)), ...fields },\n }\n}\n\n/**\n * Run a multishot conversation as the `agent(surface, scenario, ctx)` dispatch\n * of `selfImprove` and `compareOptimizationMethods`. Pass `dispatchRef` along\n * with `agent`, score with `conversationJudge`, gate with `conversationGate`\n * and show the optimizer `describeConversation`.\n */\nexport function multishotRollout<TScenario extends ConversationScenario>(\n opts: MultishotRolloutOptions<TScenario>,\n): MultishotRollout<TScenario> {\n const profileOf = opts.profile ?? textSurfaceProfile\n return {\n agent: async (surface, scenario, ctx) =>\n converse(opts, profileOf(surface, scenario), scenario, scenario.userPlan, 'agent', ctx),\n dispatchRef: rolloutDispatchRef(opts, 'agent'),\n simulatedUser: (scenario) =>\n simulatedUserSetup(opts.user, scenario.persona, scenario.userPlan).identity,\n }\n}\n\n/** The user side of the same conversation: the agent profile is fixed and the\n * candidate surface is the simulated user's plan. Package-internal; the only\n * public way to optimize it is `improveAdversarialUser`, whose objective is\n * fixed to the agent's failure rate. */\nexport function userSideRollout<TScenario extends ConversationScenario>(\n opts: Omit<MultishotRolloutOptions<TScenario>, 'profile'>,\n agentProfile: AgentProfile,\n): Omit<MultishotRollout<TScenario>, 'simulatedUser'> {\n return {\n agent: async (surface, scenario, ctx) => {\n if (typeof surface !== 'string') {\n throw new TypeError('adversarial user: the plan surface must be text')\n }\n const plan = [scenario.userPlan, surface].filter(Boolean).join('\\n\\n')\n return converse(opts, agentProfile, scenario, plan, 'user', ctx)\n },\n dispatchRef: rolloutDispatchRef(\n { ...opts, profileDigest: hashCanonical(jsonDocument(agentProfile)) },\n 'user',\n ),\n }\n}\n\nfunction textSurfaceProfile(surface: MutableSurface): AgentProfile {\n if (typeof surface !== 'string') {\n throw new TypeError(\n 'multishotRollout: a non-text surface needs a `profile` mapping it to an AgentProfile',\n )\n }\n return { name: 'agent', prompt: { systemPrompt: surface } }\n}\n\nfunction rolloutDispatchRef<TScenario extends ConversationScenario>(\n opts: Omit<MultishotRolloutOptions<TScenario>, 'profile'> & { profileDigest?: string },\n role: 'agent' | 'user',\n): string {\n const ending = opts.user.ending ?? DEFAULT_USER_ENDING\n return `multishot-rollout:${hashCanonical(\n jsonDocument({\n role,\n maxTurns: opts.maxTurns,\n revision: opts.revision,\n profileDigest: opts.profileDigest,\n agent: {\n model: opts.agent.model,\n tools: opts.agent.tools ?? [],\n maxTokens: opts.agent.maxTokens,\n toolFollowupMaxTokens: opts.agent.toolFollowupMaxTokens,\n maxToolDispatches: opts.agent.maxToolDispatches,\n },\n user: {\n model: opts.user.model,\n fallbackModels: opts.user.fallbackModels ?? [],\n rigor: opts.user.rigor ?? 'demanding',\n agentDescription: opts.user.agentDescription ?? 'an AI agent',\n shapeRef: opts.user.shapeRef ?? 'agent-eval:default-shape',\n maxTokens: opts.user.maxTokens ?? 600,\n endingRef: ending.ref,\n endingInstructions: ending.instructions,\n },\n }),\n )}`\n}\n\nasync function converse<TScenario extends ConversationScenario>(\n opts: Omit<MultishotRolloutOptions<TScenario>, 'profile'>,\n profile: AgentProfile,\n scenario: TScenario,\n plan: string | undefined,\n optimizedRole: 'agent' | 'user',\n ctx: DispatchContext,\n): Promise<ConversationArtifact> {\n if (!Number.isSafeInteger(opts.maxTurns) || opts.maxTurns < 1) {\n throw new RangeError(\n `multishotRollout: maxTurns must be a positive integer, got ${opts.maxTurns}`,\n )\n }\n if ((opts.agent.tools === undefined) !== (opts.agent.toolExecutors === undefined)) {\n throw new TypeError('multishotRollout: agent tools and toolExecutors go together')\n }\n const user = simulatedUserSetup(opts.user, scenario.persona, plan)\n const ending = opts.user.ending ?? DEFAULT_USER_ENDING\n const metered = (\n leg: ConversationLeg,\n channel: CostChannel,\n actor: string,\n transport: MultishotTransport,\n ): MultishotTransport => {\n return async (req) => {\n const { tools, signal, ...rest } = req\n // The engine advertises an empty tool list when the agent has no tools;\n // a provider may refuse one, so the request leaves it out.\n const request: MultishotTransportRequest = {\n ...rest,\n ...(tools && tools.length > 0 ? { tools } : {}),\n seed: ctx.seed,\n }\n const maximumCharge = opts.maximumCharge?.(leg, request)\n const result = await ctx.cost.runPaidCall({\n channel,\n actor,\n model: request.model,\n signal: signal ?? ctx.signal,\n ...(maximumCharge === undefined ? {} : { maximumCharge }),\n execute: (callSignal) => transport({ ...request, signal: callSignal }),\n receipt: (response) => legReceipt(request.model, response),\n })\n if (!result.succeeded) throw result.error\n return result.value\n }\n }\n\n const close: { ending?: ConversationEnding; message?: string } = {}\n const result = await runMultishotConversation(\n {\n profile,\n persona: scenario.persona,\n shape: {\n buildOpener: () => user.opener,\n buildDriverSystemPrompt: () => user.driverSystemPrompt,\n },\n tools: opts.agent.tools ?? [],\n toolExecutors: opts.agent.toolExecutors ?? {},\n artifactTypeFor: opts.agent.artifactTypeFor,\n maxTurns: opts.maxTurns,\n agentModel: opts.agent.model,\n driverModel: opts.user.model,\n driverFallbackModels: opts.user.fallbackModels,\n agentMaxTokens: opts.agent.maxTokens,\n toolFollowupMaxTokens: opts.agent.toolFollowupMaxTokens,\n driverMaxTokens: user.identity.maxTokens,\n maxToolDispatches: opts.agent.maxToolDispatches,\n agentTransport: metered('agent', 'agent', 'agent', opts.agent.transport),\n driverTransport: metered('user', 'driver', 'simulated-user', opts.user.transport),\n toolTransport: metered(\n 'tool',\n 'agent',\n 'tool',\n opts.agent.toolTransport ?? opts.agent.transport,\n ),\n signal: ctx.signal,\n },\n async (conversation) => {\n for (let turn = 0; turn < conversation.maxTurns; turn++) {\n await conversation.agentTurn(turn)\n if (turn === conversation.maxTurns - 1) {\n close.ending = { kind: 'turn-cap', turn }\n return\n }\n const { content } = await conversation.driverTurn(turn)\n const classified = ending.classify(content)\n if (classified.kind !== 'continue') {\n close.ending = { kind: classified.kind, turn }\n close.message = classified.message\n return\n }\n }\n },\n )\n const ended = close.ending\n if (ended === undefined) throw new Error('multishotRollout: the conversation never ended')\n\n const transcript = result.transcript.map((message) => ({ ...message }))\n if (close.message !== undefined) transcript[transcript.length - 1]!.content = close.message\n const userMessages = transcript.filter((message) => message.role === 'user').slice(1)\n const firstPushback = opts.user.pushback\n ? userMessages.findIndex((message) => opts.user.pushback!(message.content))\n : undefined\n const record: ConversationRecord = { transcript, artifacts: result.artifacts, ending: ended }\n const outcome = opts.outcome(record, scenario)\n if (typeof outcome?.passed !== 'boolean' || typeof outcome.detail !== 'string') {\n throw new TypeError('multishotRollout: outcome must return { passed: boolean, detail: string }')\n }\n return {\n transcript,\n artifacts: result.artifacts,\n toolCalls: result.toolCalls,\n agentTurns: ended.turn + 1,\n ending: ended,\n outcome: { passed: outcome.passed, detail: outcome.detail },\n pushback:\n firstPushback === undefined\n ? { determined: false }\n : { determined: true, firstTurn: firstPushback < 0 ? null : firstPushback },\n simulatedUser: user.identity,\n seed: ctx.seed,\n optimizedRole,\n }\n}\n\nfunction legReceipt(requested: string, response: MultishotTransportResponse): CostReceiptInput {\n const usage = response.usage\n return {\n model: response.model ?? requested,\n inputTokens: usage?.prompt_tokens ?? 0,\n outputTokens: usage?.completion_tokens ?? 0,\n ...(usage === undefined ? { usageUnknown: true } : {}),\n ...(response.costUsd === undefined ? {} : { actualCostUsd: response.costUsd }),\n }\n}\n","// How real a simulated user is, measured against recorded real users.\n//\n// At sampled real user turns, the driver writes the next user message from\n// the same recorded context the real user saw. A System One decision point is\n// shown the context and the two messages, in both orders, and picks the one\n// the real user wrote. Accuracy is reported per independent conversation with\n// a cluster bootstrap interval; 50% means the judge cannot tell the driver from\n// the real user.\n//\n// The measure is a same-context comparison: a row must carry the identity that\n// proves its context, `userTurnContextDigest` of the conversation's task and\n// the visible context, and a row without it is refused, as the PRM pair rule\n// never pairs a step without a context digest. The PRM's own chain digest\n// cannot serve here: it digests a step's input, which already contains the\n// real user's message.\n\nimport type { FindingCalibration } from '../analyst/finding-scope'\nimport type { FindingsLedger, FindingsLedgerOutcome } from '../analyst/findings-ledger'\nimport type { EvidenceRef } from '../analyst/types'\nimport type { CostLedgerHandle } from '../cost-ledger/contract'\nimport {\n DECISION_POINT_MIN_KAPPA,\n type DecisionPointResult,\n type DecisionQuestions,\n decisionPoint,\n decisionQuestionDigest,\n} from '../decision-point'\nimport { hashCanonical, jsonDocument } from '../ledger-core/canonical'\nimport { clusterBootstrapMean } from '../meta-eval/cluster-bootstrap'\nimport { makeRng } from '../statistics/internal'\nimport type { SystemOneEvaluatorOptions } from '../systemone'\nimport { runTaskId } from '../trace/emitter'\nimport type { Run } from '../trace/schema'\nimport type { Trajectory } from '../trajectory'\nimport { driverViewMessages, requestUserReply } from './conversation'\nimport { DEFAULT_USER_ENDING, type SimulatedUserOptions, simulatedUserSetup } from './rollout'\nimport type {\n MultishotPersona,\n MultishotTransportRequest,\n MultishotTransportResponse,\n} from './types'\n\n/** One real user turn and the context the user wrote it in. */\nexport interface RecordedUserTurn {\n /** The independent unit: one recorded conversation. */\n conversationId: string\n /** The task the conversation served. Absent when the record names none. */\n taskId?: string\n /** Index of the message among the conversation's user messages; the opener is 0. */\n turn: number\n /** What the user saw before writing: user and agent messages, in order. */\n context: Array<{ role: 'user' | 'assistant'; content: string }>\n /** `userTurnContextDigest` of `taskId` and `context`; absent without a task. */\n contextDigest?: string\n realMessage: string\n /** Where the turn was recorded. */\n evidenceRefs?: EvidenceRef[]\n}\n\n/** The shared-context identity of a user turn: its task and visible context. */\nexport function userTurnContextDigest(input: {\n taskId: string\n context: RecordedUserTurn['context']\n}): string {\n return hashCanonical(jsonDocument({ taskId: input.taskId, context: input.context }))\n}\n\n/**\n * The real user turns of one recorded conversation, from its trajectory: each\n * model call whose input ends in a user message that answers an agent message\n * is one turn. System and tool messages are not part of what the user saw. A\n * run without a task identity yields rows without a context digest.\n */\nexport function recordedUserTurns(\n trajectory: Trajectory,\n run: Pick<Run, 'scenarioId' | 'layer' | 'tags'> | undefined,\n): RecordedUserTurn[] {\n const taskId = runTaskId(run)\n const turns: RecordedUserTurn[] = []\n const seen = new Set<number>()\n for (const step of trajectory.steps) {\n const span = step.span\n if (span.kind !== 'llm') continue\n const last = span.messages.at(-1)\n if (last?.role !== 'user' || last.content.trim().length === 0) continue\n const context = span.messages\n .slice(0, -1)\n .filter(\n (message): message is typeof message & { role: 'user' | 'assistant' } =>\n (message.role === 'user' || message.role === 'assistant') &&\n message.content.trim().length > 0,\n )\n .map((message) => ({ role: message.role, content: message.content }))\n if (context.at(-1)?.role !== 'assistant') continue\n const turn = context.filter((message) => message.role === 'user').length\n if (seen.has(turn)) continue\n seen.add(turn)\n turns.push({\n conversationId: trajectory.runId,\n ...(taskId === undefined\n ? {}\n : { taskId, contextDigest: userTurnContextDigest({ taskId, context }) }),\n turn,\n context,\n realMessage: last.content,\n evidenceRefs: [{ kind: 'span', uri: span.spanId }],\n })\n }\n return turns\n}\n\n/** A recorded turn carries no proof of a shared context, or a proof its\n * context does not match. */\nexport class SharedContextIdentityError extends Error {\n readonly conversationId: string\n readonly turn: number\n constructor(row: Pick<RecordedUserTurn, 'conversationId' | 'turn'>, reason: string) {\n super(\n `recorded user turn ${row.conversationId}#${row.turn} ${reason}; a realism comparison ` +\n \"needs the identity that proves the driver saw the real user's context\",\n )\n this.name = 'SharedContextIdentityError'\n this.conversationId = row.conversationId\n this.turn = row.turn\n }\n}\n\nfunction assertSharedContext(row: RecordedUserTurn): void {\n if (!row.taskId || !row.contextDigest) {\n throw new SharedContextIdentityError(row, 'has no task identity and context digest')\n }\n if (userTurnContextDigest({ taskId: row.taskId, context: row.context }) !== row.contextDigest) {\n throw new SharedContextIdentityError(row, 'has a context digest its context does not match')\n }\n}\n\n/** Writes the user's next message for a recorded context. */\nexport interface RealismDriver {\n /** Stable identity of everything that shapes the driver's message. */\n identity: string\n next(input: {\n turn: RecordedUserTurn\n signal?: AbortSignal\n costLedger?: CostLedgerHandle\n }): Promise<string>\n}\n\n/**\n * The simulated user a rollout runs, as a realism driver: the same prompt,\n * the same driver point of view on the recorded context, the same model\n * rotation. An ending marker is removed, as a rollout removes it.\n */\nexport function simulatedUserDriver<TPersona extends MultishotPersona>(opts: {\n user: SimulatedUserOptions<TPersona>\n /** The persona the user plays for a recorded conversation. */\n persona: (turn: RecordedUserTurn) => TPersona\n plan?: string\n}): RealismDriver {\n const ending = opts.user.ending ?? DEFAULT_USER_ENDING\n const models = [opts.user.model, ...(opts.user.fallbackModels ?? [])]\n return {\n identity: `simulated-user:${hashCanonical(\n jsonDocument({\n models,\n rigor: opts.user.rigor ?? 'demanding',\n agentDescription: opts.user.agentDescription ?? 'an AI agent',\n shapeRef: opts.user.shapeRef ?? 'agent-eval:default-shape',\n maxTokens: opts.user.maxTokens ?? 600,\n endingRef: ending.ref,\n endingInstructions: ending.instructions,\n plan: opts.plan,\n }),\n )}`,\n async next({ turn, signal, costLedger }) {\n const setup = simulatedUserSetup(opts.user, opts.persona(turn), opts.plan)\n const messages = driverViewMessages(setup.driverSystemPrompt, turn.context)\n const transport = costLedger\n ? async (req: MultishotTransportRequest) => {\n const result = await costLedger.runPaidCall({\n channel: 'driver',\n phase: 'realism.driver',\n actor: 'simulated-user',\n model: req.model,\n signal: req.signal,\n execute: (callSignal) => opts.user.transport({ ...req, signal: callSignal }),\n receipt: (response: MultishotTransportResponse) => ({\n model: response.model ?? req.model,\n inputTokens: response.usage?.prompt_tokens ?? 0,\n outputTokens: response.usage?.completion_tokens ?? 0,\n ...(response.usage === undefined ? { usageUnknown: true } : {}),\n ...(response.costUsd === undefined ? {} : { actualCostUsd: response.costUsd }),\n }),\n })\n if (!result.succeeded) throw result.error\n return result.value\n }\n : opts.user.transport\n const content = await requestUserReply({\n models,\n messages,\n transport,\n maxTokens: setup.identity.maxTokens,\n signal,\n turn: turn.turn,\n })\n const classified = ending.classify(content)\n return classified.kind === 'continue' ? content : classified.message\n },\n }\n}\n\n/** The realism question: which of two messages did the real user write. */\nexport const SIMULATOR_REALISM_QUESTIONS = {\n real: {\n type: 'choice',\n instructions:\n \"The state holds a conversation between a user and an AI agent up to the user's next \" +\n 'message, and two candidate next messages, a and b. A real user wrote one; a simulator ' +\n 'wrote the other. Choose the one the real user wrote. Judge voice, length, specificity, ' +\n \"what the user would know, and how a person reacts to the agent's last message. Neither \" +\n 'position is more likely.',\n criteria: {\n a: 'The real user wrote message a.',\n b: 'The real user wrote message b.',\n },\n },\n} as const satisfies DecisionQuestions\n\nexport interface SimulatorRealismJudgeOptions {\n id: string\n version: string\n /** Requested judge model. */\n model: string\n ledger: FindingsLedger\n evaluator: SystemOneEvaluatorOptions\n /** Agreement with independent real-or-simulated labels, bound to this exact\n * question, model and served model through `questionDigest`. Without it\n * every judgment is recorded as uncalibrated. */\n calibration?: FindingCalibration & {\n servedModel: string\n questionDigest: string\n evidenceRefs: EvidenceRef[]\n }\n /** Default 0.6. */\n minimumProbability?: number\n /** Default 0.2. */\n minimumMargin?: number\n}\n\nexport interface SimulatorRealismJudge {\n id: string\n definitionDigest: string\n /** The digest a calibration of this judge must carry, for the served model\n * the calibration names, else the requested model. */\n questionDigest: string\n /** The calibration clears `DECISION_POINT_MIN_KAPPA` and binds this question. */\n calibrated: boolean\n decide: ReturnType<typeof decisionPoint<typeof SIMULATOR_REALISM_QUESTIONS>>['decide']\n}\n\n/** The realism judge as a System One decision point at the turn layer. */\nexport function simulatorRealismJudge(opts: SimulatorRealismJudgeOptions): SimulatorRealismJudge {\n const questionDigest = decisionQuestionDigest({\n id: opts.id,\n version: opts.version,\n model: opts.model,\n servedModel: opts.calibration?.servedModel ?? opts.model,\n name: 'real',\n question: SIMULATOR_REALISM_QUESTIONS.real,\n })\n const point = decisionPoint({\n id: opts.id,\n version: opts.version,\n layers: ['turn'],\n model: opts.model,\n questions: SIMULATOR_REALISM_QUESTIONS,\n policy: {\n real: {\n minimumProbability: opts.minimumProbability ?? 0.6,\n minimumMargin: opts.minimumMargin ?? 0.2,\n options: { a: { action: 'record' }, b: { action: 'record' } },\n ...(opts.calibration ? { calibration: opts.calibration } : {}),\n },\n },\n ledger: opts.ledger,\n evaluator: opts.evaluator,\n })\n return {\n id: point.id,\n definitionDigest: point.definitionDigest,\n questionDigest,\n calibrated:\n opts.calibration !== undefined &&\n opts.calibration.kappa >= DECISION_POINT_MIN_KAPPA &&\n opts.calibration.questionDigest === questionDigest,\n decide: point.decide,\n }\n}\n\nexport interface MeasureSimulatorRealismOptions {\n turns: readonly RecordedUserTurn[]\n driver: RealismDriver\n judge: SimulatorRealismJudge\n /** Ledger run the judgments are recorded under. Repeating a measurement\n * under the same run replays its recorded judgments, and a changed input\n * under it counts as a failed judgment, so use a new run per measurement. */\n runId: string\n /** ISO-8601 time stamped on the judgments. Default: now. */\n at?: string\n /** Judge at most this many turns, drawn with `seed`. Default: all. */\n sample?: number\n confidence?: number\n resamples?: number\n seed?: number\n costLedger?: CostLedgerHandle\n signal?: AbortSignal\n}\n\nexport interface SimulatorRealismReport {\n driver: string\n judge: {\n id: string\n definitionDigest: string\n /** Calibrated, and every judgment ran on the calibrated model. */\n calibrated: boolean\n /** Judgments by System One reason: threshold, uncertain, uncalibrated, model-mismatch. */\n reasons: Record<string, number>\n }\n conversations: number\n turns: number\n /** Judged presentations; each counted turn is shown in both orders. */\n presentations: number\n failedJudgments: number\n /** Turns dropped because one of their two orders failed to judge: a turn\n * counts only when it was judged in both positions. */\n unbalancedTurns: number\n /** Share of presentations where the judge picked the real message, each\n * conversation weighted equally, with a bootstrap interval over conversations. */\n accuracy: { mean: number; low: number; high: number; confidence: number; resamples: number }\n meanProbabilityOnReal: number\n /** The interval contains 0.5: this sample does not show the judge telling\n * the driver from real users. A small sample satisfies it with a wide\n * interval, so it is not an admission rule; admit on `accuracy.high`\n * against a stated bound, as `improveAdversarialUser` does. */\n indistinguishable: boolean\n}\n\n/** Measure how often a judge tells the driver's message from the real user's. */\nexport async function measureSimulatorRealism(\n opts: MeasureSimulatorRealismOptions,\n): Promise<SimulatorRealismReport> {\n if (opts.turns.length === 0) throw new RangeError('measureSimulatorRealism: no recorded turns')\n for (const row of opts.turns) assertSharedContext(row)\n const at = opts.at ?? new Date().toISOString()\n const turns = sampleTurns(opts.turns, opts.sample, opts.seed)\n const correctByConversation = new Map<string, number[]>()\n const reasons: Record<string, number> = {}\n const probabilitiesOnReal: number[] = []\n let failedJudgments = 0\n let unbalancedTurns = 0\n\n for (const row of turns) {\n const simulated = await opts.driver.next({\n turn: row,\n ...(opts.signal ? { signal: opts.signal } : {}),\n ...(opts.costLedger ? { costLedger: opts.costLedger } : {}),\n })\n const unit = `${row.conversationId}:${row.turn}`\n const answers: Array<ReturnType<typeof judgedAnswer>> = []\n for (const order of ['real-first', 'real-second'] as const) {\n const judged = await opts.judge.decide(\n {\n runId: opts.runId,\n invocationId: `${unit}:${order}`,\n layer: 'turn',\n consumer: 'simulator-realism',\n state: {\n context: row.context,\n a: order === 'real-first' ? row.realMessage : simulated,\n b: order === 'real-first' ? simulated : row.realMessage,\n },\n scope: { population: [unit], n: 1, window: { from: at, to: at } },\n at,\n evidenceRefs: row.evidenceRefs?.length\n ? row.evidenceRefs\n : [{ kind: 'event', uri: `user-turn:${unit}` }],\n },\n {\n ...(opts.signal ? { signal: opts.signal } : {}),\n ...(opts.costLedger ? { costLedger: opts.costLedger } : {}),\n channel: 'judge',\n actor: 'simulator-realism-judge',\n costPhase: 'realism.judge',\n },\n )\n answers.push(judgedAnswer(judged))\n }\n const failed = answers.filter((answer) => !answer).length\n failedJudgments += failed\n // A turn judged in one position only would let the judge's position bias\n // count, so it counts only when both orders were judged.\n if (failed > 0) {\n if (failed < answers.length) unbalancedTurns += 1\n continue\n }\n for (const [index, answer] of answers.entries()) {\n if (!answer) continue\n const realOption = index === 0 ? 'a' : 'b'\n reasons[answer.reason] = (reasons[answer.reason] ?? 0) + 1\n probabilitiesOnReal.push(answer.probabilities[realOption] ?? 0)\n const list = correctByConversation.get(row.conversationId) ?? []\n list.push(answer.choice === realOption ? 1 : 0)\n correctByConversation.set(row.conversationId, list)\n }\n }\n\n if (correctByConversation.size === 0) {\n throw new Error('measureSimulatorRealism: no presentation was judged')\n }\n const interval = clusterBootstrapMean(\n [...correctByConversation].map(([conversationId, list]) => ({\n cluster: conversationId,\n value: list.reduce((sum, value) => sum + value, 0) / list.length,\n })),\n {\n ...(opts.confidence === undefined ? {} : { confidence: opts.confidence }),\n ...(opts.resamples === undefined ? {} : { resamples: opts.resamples }),\n ...(opts.seed === undefined ? {} : { seed: opts.seed }),\n },\n )\n const onCalibratedModel = Object.keys(reasons).every(\n (reason) => reason === 'threshold' || reason === 'uncertain',\n )\n return {\n driver: opts.driver.identity,\n judge: {\n id: opts.judge.id,\n definitionDigest: opts.judge.definitionDigest,\n calibrated: opts.judge.calibrated && onCalibratedModel,\n reasons,\n },\n conversations: correctByConversation.size,\n turns: turns.length,\n presentations: probabilitiesOnReal.length,\n failedJudgments,\n unbalancedTurns,\n accuracy: {\n mean: interval.mean,\n low: interval.low,\n high: interval.high,\n confidence: interval.confidence,\n resamples: interval.resamples,\n },\n meanProbabilityOnReal:\n probabilitiesOnReal.reduce((sum, value) => sum + value, 0) / probabilitiesOnReal.length,\n indistinguishable: interval.low <= 0.5 && interval.high >= 0.5,\n }\n}\n\nfunction judgedAnswer(judged: FindingsLedgerOutcome<DecisionPointResult>) {\n if (!judged.succeeded) return undefined\n const record = judged.value.record\n if (!record || record.error) return undefined\n return record.answers.real\n}\n\nfunction sampleTurns(\n turns: readonly RecordedUserTurn[],\n sample: number | undefined,\n seed: number | undefined,\n): RecordedUserTurn[] {\n if (sample === undefined || sample >= turns.length) return [...turns]\n if (!Number.isSafeInteger(sample) || sample < 1) {\n throw new RangeError(\n `measureSimulatorRealism: sample must be a positive integer, got ${sample}`,\n )\n }\n const random = makeRng(seed ?? 0)\n const order = turns.map((_, index) => index)\n for (let index = order.length - 1; index > 0; index--) {\n const swap = Math.floor(random() * (index + 1))\n ;[order[index], order[swap]] = [order[swap]!, order[index]!]\n }\n return order\n .slice(0, sample)\n .sort((left, right) => left - right)\n .map((index) => turns[index]!)\n}\n","// The simulated user as a second optimizable role.\n//\n// An adversarial user searches for the plans a fixed agent fails under: its\n// objective is the agent's failure rate, nothing else. A plan is admitted only\n// when a calibrated realism judge cannot tell it from real users above a\n// floor, so the search finds failures real users would cause, not failures of\n// a user no one is. What an admitted plan breaks becomes new train scenarios\n// for the agent side; they never enter a held-out split. A failure becomes a\n// train scenario only once a conversation shows it can be passed under the\n// plan, by a reference agent or by the same agent on one of k seeded repeats:\n// a plan that withholds what the outcome check needs teaches nothing.\n//\n// The objective is fixed by construction: this entry builds the judge itself\n// and refuses a caller judge, `conversationJudge` refuses every user-side\n// conversation, and the user-side dispatch is not public.\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport type { OptimizationMethod } from '../campaign/optimization-method'\nimport { runCampaign } from '../campaign/run-campaign'\nimport {\n type CampaignStorage,\n fsCampaignStorage,\n inMemoryCampaignStorage,\n} from '../campaign/storage'\nimport type { JudgeConfig, SurfaceProposer } from '../campaign/types'\nimport {\n type SelfImproveBudget,\n type SelfImproveResult,\n selfImprove,\n} from '../contract/self-improve'\nimport type { CostLedgerHandle } from '../cost-ledger/contract'\nimport { hashCanonical, jsonDocument } from '../ledger-core/canonical'\nimport { listSome, UserSideObjectiveError } from './conversation-conditions'\nimport { describeConversation } from './conversation-evidence'\nimport {\n measureSimulatorRealism,\n type RecordedUserTurn,\n type SimulatorRealismJudge,\n type SimulatorRealismReport,\n simulatedUserDriver,\n} from './realism'\nimport {\n type ConversationArtifact,\n type ConversationScenario,\n type MultishotRolloutOptions,\n type ScenarioSolvedBy,\n userSideRollout,\n} from './rollout'\n\n/** Scenarios for the user-side search would reach the agent's held-out split. */\nexport class AdversarialSplitError extends Error {\n readonly scenarioIds: string[]\n constructor(scenarioIds: string[]) {\n super(\n `adversarial user search would use ${scenarioIds.length} scenario(s) that share an id ` +\n `or persona with the agent's held-out split (${listSome(scenarioIds)})`,\n )\n this.name = 'AdversarialSplitError'\n this.scenarioIds = scenarioIds\n }\n}\n\nexport interface AdversarialUserOptions<TScenario extends ConversationScenario> {\n /** The conversation; the agent side is fixed to `agentProfile`. */\n rollout: Omit<MultishotRolloutOptions<TScenario>, 'profile'>\n agentProfile: AgentProfile\n /** The plan the search starts from: the user's surface. */\n baselinePlan: string\n /** Personas the search runs on, held-out cases included. */\n scenarios: TScenario[]\n /** The agent side's held-out scenarios. No scenario of this search may share\n * an id or a persona with them. */\n agentHeldOut: readonly TScenario[]\n proposer?: SurfaceProposer\n method?: OptimizationMethod<TScenario, ConversationArtifact>\n selectionScenarios?: TScenario[]\n budget?: SelfImproveBudget\n runDir?: string\n storage?: CampaignStorage\n expectUsage?: 'assert' | 'warn' | 'off'\n /** Snapshot model id, for an agent leg that reports no receipt model. */\n model?: string\n /** The admission floor, measured on the winning plan. */\n realism: {\n turns: readonly RecordedUserTurn[]\n judge: SimulatorRealismJudge\n runId: string\n at?: string\n /** The persona the user plays for a recorded conversation. */\n persona: (turn: RecordedUserTurn) => TScenario['persona']\n /** Highest judge accuracy, at the interval's upper end, a plan may reach\n * and still count as realistic. 0.5 is indistinguishable. */\n maxJudgeAccuracy: number\n sample?: number\n confidence?: number\n resamples?: number\n seed?: number\n costLedger?: CostLedgerHandle\n }\n /** How an emitted scenario shows it can be passed under its plan. Default:\n * the same agent, 3 seeded repeats. */\n solvability?: {\n /** An agent that runs each candidate in place of `agentProfile`. */\n referenceProfile?: AgentProfile\n /** Seeded conversations per candidate; one pass is enough. Default 3. */\n repeats?: number\n /** Campaign seed of the repeats. Default 42. */\n seed?: number\n }\n}\n\n/** A failure the admitted plan caused that no solvability conversation passed. */\nexport interface UnsolvableScenario<TScenario extends ConversationScenario> {\n scenario: TScenario\n reason: string\n /** Conversations run on it. */\n attempts: number\n}\n\nexport interface AdversarialUserResult<TScenario extends ConversationScenario> {\n /** The user-side search, scored on the agent's failure rate. */\n improvement: SelfImproveResult<TScenario, ConversationArtifact>\n /** The selected plan. */\n plan: string\n /** Realism of the selected plan; null when the search did not ship. */\n realism: SimulatorRealismReport | null\n admitted: boolean\n reasons: string[]\n /** One per held-out conversation the admitted plan made the agent fail\n * that a solvability conversation passed: the source scenario with the plan\n * as its `userPlan` and the pass on `origin.solvedBy`. Train only. */\n trainScenarios: TScenario[]\n /** Failures no solvability conversation passed. Never emitted. */\n unsolvableScenarios: UnsolvableScenario<TScenario>[]\n}\n\n/**\n * Search for a simulated-user plan that makes a fixed agent fail, admit it\n * only above a realism floor, and emit what it breaks as agent train scenarios.\n */\nexport async function improveAdversarialUser<TScenario extends ConversationScenario>(\n opts: AdversarialUserOptions<TScenario>,\n): Promise<AdversarialUserResult<TScenario>> {\n if ('judge' in opts || 'gate' in opts) {\n throw new UserSideObjectiveError(\n \"improveAdversarialUser: the user side's objective is the agent's failure rate; it accepts no judge or gate\",\n )\n }\n if (!(opts.realism.maxJudgeAccuracy >= 0.5 && opts.realism.maxJudgeAccuracy <= 1)) {\n throw new RangeError('improveAdversarialUser: realism.maxJudgeAccuracy must be in [0.5, 1]')\n }\n const repeats = opts.solvability?.repeats ?? 3\n if (!Number.isSafeInteger(repeats) || repeats < 1) {\n throw new RangeError('improveAdversarialUser: solvability.repeats must be a positive integer')\n }\n assertDisjointFromHeldOut(\n [...opts.scenarios, ...(opts.selectionScenarios ?? [])],\n opts.agentHeldOut,\n )\n\n const rollout = userSideRollout(opts.rollout, opts.agentProfile)\n const shared = {\n agent: rollout.agent,\n dispatchRef: rollout.dispatchRef,\n scenarios: opts.scenarios,\n judge: agentFailureJudge<TScenario>(),\n describeArtifact: describeConversation,\n baselineSurface: opts.baselinePlan,\n ...(opts.selectionScenarios ? { selectionScenarios: opts.selectionScenarios } : {}),\n ...(opts.budget ? { budget: opts.budget } : {}),\n ...(opts.runDir ? { runDir: opts.runDir } : {}),\n ...(opts.storage ? { storage: opts.storage } : {}),\n ...(opts.expectUsage ? { expectUsage: opts.expectUsage } : {}),\n ...(opts.model ? { model: opts.model } : {}),\n }\n const improvement: SelfImproveResult<TScenario, ConversationArtifact> = opts.method\n ? await selfImprove<TScenario, ConversationArtifact>({ ...shared, method: opts.method })\n : await selfImprove<TScenario, ConversationArtifact>({\n ...shared,\n ...(opts.proposer ? { proposer: opts.proposer } : {}),\n })\n const plan = String(improvement.winner.surface)\n if (improvement.gateDecision !== 'ship') {\n return {\n improvement,\n plan,\n realism: null,\n admitted: false,\n reasons: [`the user-side search did not ship (${improvement.gateDecision})`],\n trainScenarios: [],\n unsolvableScenarios: [],\n }\n }\n\n const realism = await measureSimulatorRealism({\n turns: opts.realism.turns,\n driver: simulatedUserDriver({\n user: opts.rollout.user,\n persona: opts.realism.persona,\n plan,\n }),\n judge: opts.realism.judge,\n runId: opts.realism.runId,\n ...pick(opts.realism, ['at', 'sample', 'confidence', 'resamples', 'seed', 'costLedger']),\n })\n const reasons: string[] = []\n if (!realism.judge.calibrated) {\n reasons.push(\n 'realism judge is not calibrated on this question and served model; a plan is admitted only by a calibrated judge',\n )\n }\n if (realism.accuracy.high > opts.realism.maxJudgeAccuracy) {\n reasons.push(\n `realism: judge accuracy reaches ${realism.accuracy.high.toFixed(3)} at the interval's upper end, above the floor ${opts.realism.maxJudgeAccuracy}`,\n )\n }\n const admitted = reasons.length === 0\n const candidates = admitted ? failedScenarios(improvement, opts.scenarios, plan) : []\n return {\n improvement,\n plan,\n realism,\n admitted,\n reasons,\n ...(await sortBySolvability(opts, candidates, repeats)),\n }\n}\n\n/** Run each candidate under its plan; one pass makes it a train scenario. */\nasync function sortBySolvability<TScenario extends ConversationScenario>(\n opts: AdversarialUserOptions<TScenario>,\n candidates: TScenario[],\n repeats: number,\n): Promise<Pick<AdversarialUserResult<TScenario>, 'trainScenarios' | 'unsolvableScenarios'>> {\n if (candidates.length === 0) return { trainScenarios: [], unsolvableScenarios: [] }\n const reference = opts.solvability?.referenceProfile\n const profile = reference ?? opts.agentProfile\n const solver = userSideRollout(opts.rollout, profile)\n const campaign = await runCampaign<TScenario, ConversationArtifact>({\n scenarios: candidates,\n // A candidate carries the plan it failed under as its own `userPlan`.\n dispatch: (scenario, ctx) => solver.agent('', scenario, ctx),\n dispatchRef: `adversarial-solvability:${solver.dispatchRef}`,\n reps: repeats,\n seed: opts.solvability?.seed ?? 42,\n runDir: opts.runDir ? `${opts.runDir}/solvability` : `mem://adversarial-solvability`,\n storage: opts.storage ?? (opts.runDir ? fsCampaignStorage() : inMemoryCampaignStorage()),\n expectUsage: opts.expectUsage ?? 'assert',\n })\n const agent = reference ? 'reference' : 'same'\n const profileDigest = hashCanonical(jsonDocument(profile))\n const trainScenarios: TScenario[] = []\n const unsolvableScenarios: UnsolvableScenario<TScenario>[] = []\n for (const scenario of candidates) {\n const cells = campaign.cells.filter((cell) => cell.scenarioId === scenario.id)\n const passed = cells.find((cell) => cell.error === undefined && cell.artifact.outcome.passed)\n if (passed) {\n const solvedBy: ScenarioSolvedBy = {\n agent,\n profileDigest,\n seed: passed.artifact.seed,\n detail: passed.artifact.outcome.detail,\n }\n trainScenarios.push({ ...scenario, origin: { ...scenario.origin!, solvedBy } })\n continue\n }\n const last = cells.at(-1)\n unsolvableScenarios.push({\n scenario,\n reason:\n `the ${agent} agent passed none of ${cells.length} ` +\n `conversation(s) under the plan (${last?.error ?? last?.artifact.outcome.detail ?? 'no conversation ran'})`,\n attempts: cells.length,\n })\n }\n return { trainScenarios, unsolvableScenarios }\n}\n\n/** Score of the user side: 1 when the agent failed the outcome check. */\nfunction agentFailureJudge<TScenario extends ConversationScenario>(): JudgeConfig<\n ConversationArtifact,\n TScenario\n> {\n return {\n name: 'agent-failure',\n judgeVersion: 'agent-eval:agent-failure:v1',\n dimensions: [\n { key: 'agent_failure', description: '1 when the agent failed the code-checked outcome' },\n ],\n score({ artifact }) {\n if (artifact.optimizedRole !== 'user') {\n throw new UserSideObjectiveError('agent-failure scores user-side conversations only')\n }\n const failed = artifact.outcome.passed ? 0 : 1\n return {\n dimensions: { agent_failure: failed },\n composite: failed,\n notes: artifact.outcome.detail,\n }\n },\n }\n}\n\nfunction assertDisjointFromHeldOut<TScenario extends ConversationScenario>(\n scenarios: readonly TScenario[],\n heldOut: readonly TScenario[],\n): void {\n const ids = new Set(heldOut.map((scenario) => scenario.id))\n const personas = new Set(heldOut.map((scenario) => personaDigest(scenario)))\n const overlap = scenarios\n .filter((scenario) => ids.has(scenario.id) || personas.has(personaDigest(scenario)))\n .map((scenario) => scenario.id)\n if (overlap.length > 0) throw new AdversarialSplitError([...new Set(overlap)])\n}\n\nfunction personaDigest(scenario: ConversationScenario): string {\n return hashCanonical(jsonDocument(scenario.persona))\n}\n\nfunction failedScenarios<TScenario extends ConversationScenario>(\n improvement: SelfImproveResult<TScenario, ConversationArtifact>,\n scenarios: readonly TScenario[],\n plan: string,\n): TScenario[] {\n const planDigest = hashCanonical(plan)\n const emitted = new Map<string, TScenario>()\n for (const cell of improvement.raw.winnerOnHoldout.cells) {\n if (cell.error !== undefined || cell.artifact.outcome.passed) continue\n if (emitted.has(cell.scenarioId)) continue\n const source = scenarios.find((scenario) => scenario.id === cell.scenarioId)\n if (!source) continue\n emitted.set(cell.scenarioId, {\n ...structuredClone(source),\n id: `${source.id}~adversarial-${planDigest.slice('sha256:'.length, 'sha256:'.length + 12)}`,\n // The plan the failing conversation ran: the scenario's own, then the found one.\n userPlan: [source.userPlan, plan].filter(Boolean).join('\\n\\n'),\n origin: { kind: 'adversarial-user', sourceScenarioId: source.id, planDigest },\n })\n }\n return [...emitted.values()]\n}\n\nfunction pick<T extends object, K extends keyof T>(\n value: T,\n keys: readonly K[],\n): Partial<Pick<T, K>> {\n const picked: Partial<Pick<T, K>> = {}\n for (const key of keys) if (value[key] !== undefined) picked[key] = value[key]\n return picked\n}\n","// Generic judge runner — domain consumers configure dimensions + prompts.\n//\n// Three judge slots are conventional for multishot eval:\n// - conversation (scores the full transcript)\n// - codeReview (scores each code artifact)\n// - contentQuality (scores each non-code artifact)\n//\n// But the runJudge primitive is fully generic: any input maps to a score plus\n// explicit observed, estimated, or uncaptured cost.\n\nimport { DEFAULT_JUDGE_MODEL } from '../analyst/chat-client'\nimport type { JudgeDimension, JudgeScore } from '../campaign/types'\nimport type { CostProvenance } from '../cost-ledger'\nimport type { LlmCallMetadata, LlmUsage } from '../llm-client'\nimport { estimateCost, isModelPriced } from '../metrics'\nimport type { MultishotTransport, MultishotTransportResponse } from './types'\n\n// Canonical declaration lives in campaign/types.ts. Multishot emits the same\n// shape on its producer-defined 0-10 scale.\nexport type { JudgeDimension, JudgeScore } from '../campaign/types'\n\nexport interface MultishotJudgeConfig<TInput> {\n /** Display name (for trace + log). */\n name: string\n /** Caller-owned execution for this judge's call. agent-eval issues no\n * provider request and holds no credential. */\n transport: MultishotTransport\n /** Model used for this judge. */\n model?: string\n /** 0-10 scored dimensions. */\n dimensions: JudgeDimension[]\n /** Judge system prompt — sets persona + JSON-only constraint. */\n systemPrompt: string\n /** Build the user prompt from the typed input. Must include \"Respond with\n * ONLY this JSON: { ... }\" listing each dimension key. */\n buildPrompt: (input: TInput) => string\n /** Maximum output tokens for the judge response. Defaults to 1500. */\n maxTokens?: number\n}\n\nexport interface JudgeRunResult {\n /** Semantic result; failed scores remain non-throwing so matrix aggregation can exclude them. */\n score: JudgeScore\n /** Cost of the completed call, separate from diagnostic provider metadata. */\n cost: CostProvenance\n}\n\nexport async function runJudge<TInput>(\n judge: MultishotJudgeConfig<TInput>,\n input: TInput,\n): Promise<JudgeRunResult> {\n const model = judge.model ?? DEFAULT_JUDGE_MODEL\n const prompt = judge.buildPrompt(input)\n let raw = ''\n let llmCall: LlmCallMetadata\n let cost: CostProvenance\n const startedAt = Date.now()\n try {\n const response = await judge.transport({\n model,\n temperature: 0,\n maxTokens: judge.maxTokens ?? 1500,\n messages: [\n { role: 'system', content: judge.systemPrompt },\n { role: 'user', content: prompt },\n ],\n })\n const call = judgeCallMetadata(response, model, Date.now() - startedAt)\n llmCall = call.llmCall\n cost = call.cost\n raw = (response.message.content ?? '').trim()\n } catch (err) {\n // failed:true lets consumers reading `.composite` keep working while\n // aggregators exclude this score from means instead of averaging a zero.\n return {\n score: {\n dimensions: {},\n composite: 0,\n failed: true,\n notes: `judge ${judge.name} call failed: ${err instanceof Error ? err.message : String(err)}`,\n llmCall: unknownJudgeCall(model, Date.now() - startedAt),\n },\n cost: { kind: 'uncaptured', usd: null },\n }\n }\n\n let parsed: Record<string, unknown> | null = null\n try {\n const cleaned = raw\n .replace(/^```json\\s*/i, '')\n .replace(/```\\s*$/, '')\n .trim()\n parsed = JSON.parse(cleaned) as Record<string, unknown>\n } catch {\n return {\n score: {\n dimensions: {},\n composite: 0,\n failed: true,\n notes: `judge ${judge.name} returned non-JSON: ${raw.slice(0, 200)}`,\n llmCall,\n },\n cost,\n }\n }\n\n const dimensions: Record<string, number> = {}\n let sum = 0\n for (const dim of judge.dimensions) {\n const v = Number(parsed[dim.key] ?? 0)\n const clamped = Number.isFinite(v) ? Math.max(0, Math.min(10, v)) : 0\n dimensions[dim.key] = clamped\n sum += clamped\n }\n return {\n score: {\n dimensions,\n composite: judge.dimensions.length === 0 ? 0 : sum / judge.dimensions.length,\n notes: typeof parsed.notes === 'string' ? parsed.notes : '',\n llmCall,\n },\n cost,\n }\n}\n\nfunction judgeCallMetadata(\n response: MultishotTransportResponse,\n requestedModel: string,\n durationMs: number,\n): {\n llmCall: LlmCallMetadata\n cost: CostProvenance\n} {\n const usage = canonicalUsage(response.usage)\n // The transport reports the served identity when it observed one. Falling\n // back to the requested id keeps attribution honest for a transport that\n // reported none; it is not proof that model answered.\n const model = response.model ?? requestedModel\n return {\n llmCall: {\n usage,\n costUsd: response.costUsd ?? null,\n model,\n durationMs,\n },\n cost:\n response.costUsd !== undefined\n ? { kind: 'observed', usd: response.costUsd }\n : usage.captured === false || !isModelPriced(model)\n ? { kind: 'uncaptured', usd: null }\n : {\n kind: 'estimated',\n usd: estimateCost(usage.promptTokens, usage.completionTokens, model),\n },\n }\n}\n\nfunction canonicalUsage(usage: MultishotTransportResponse['usage']): LlmUsage {\n const promptTokens = tokenCount(usage?.prompt_tokens)\n const completionTokens = tokenCount(usage?.completion_tokens)\n const captured = promptTokens !== undefined && completionTokens !== undefined\n return {\n promptTokens: promptTokens ?? 0,\n completionTokens: completionTokens ?? 0,\n totalTokens: (promptTokens ?? 0) + (completionTokens ?? 0),\n captured,\n }\n}\n\nfunction unknownJudgeCall(model: string, durationMs: number): LlmCallMetadata {\n return {\n usage: { promptTokens: 0, completionTokens: 0, totalTokens: 0, captured: false },\n costUsd: null,\n model,\n durationMs,\n }\n}\n\nfunction tokenCount(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n}\n\n/** Convenience: stringified dimension list for inclusion in a judge prompt.\n * Returns lines like `- audience_fit: Does this match what the audience cares about? (0-10)`. */\nexport function renderDimensions(dims: readonly JudgeDimension[]): string {\n return dims.map((d) => `- ${d.key}: ${d.description}`).join('\\n')\n}\n\n/** Convenience: build the \"Respond with ONLY this JSON\" footer for a judge prompt. */\nexport function renderJsonFooter(dims: readonly JudgeDimension[]): string {\n const fields = dims.map((d) => `\"${d.key}\":N`).join(',')\n return `Respond with ONLY this JSON (no markdown, no preamble):\\n{${fields},\"notes\":\"1-2 sentence critique\"}`\n}\n","// Multi-turn driver-agent simulation with inline tool execution.\n//\n// The driver = LLM acting as the persona (reactive, non-deterministic).\n// The agent = the product agent under test, executed by the caller-supplied\n// transport with the profile's systemPrompt + the configured tools.\n// Tool calls execute inline via the configured executors and feed back\n// into the agent's message log so the agent integrates the result.\n//\n// agent-eval owns no model transport: every leg runs on a MultishotTransport\n// the caller supplies, so no provider credential enters this package.\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { runMultishotConversation } from './conversation'\nimport type {\n MultishotPersona,\n MultishotResult,\n MultishotShape,\n MultishotToolDefinition,\n MultishotToolExecutor,\n MultishotTransport,\n} from './types'\n\nexport interface RunMultishotOptions<TPersona extends MultishotPersona> {\n profile: AgentProfile\n persona: TPersona\n /** Persona-shaping callbacks. Optional — omitted callbacks are derived from\n * the profile + persona payload, so a pure-profile call works. */\n shape?: MultishotShape<TPersona>\n /** Tool definitions advertised to the agent. Defaults to delegate_research + delegate_code. */\n tools?: MultishotToolDefinition[]\n /** Map from tool name → executor invoked inline when the agent emits a tool_call. */\n toolExecutors?: Record<string, MultishotToolExecutor>\n /** Map from tool name → artifact type label written into MultishotArtifact.type.\n * Tools without a mapping still execute, but their results aren't surfaced as\n * typed artifacts (only as tool messages in the transcript). */\n artifactTypeFor?: (toolName: string) => string | undefined\n maxTurns?: number\n agentModel?: string\n driverModel?: string\n /** Fallback driver models tried when the primary simulated-user model returns empty twice. */\n driverFallbackModels?: string[]\n /** Maximum output tokens for the first agent call in each assistant turn. */\n agentMaxTokens?: number\n /** Maximum output tokens for agent follow-up calls after tool results. */\n toolFollowupMaxTokens?: number\n /** Maximum output tokens for each simulated-user driver response. */\n driverMaxTokens?: number\n /** Maximum tool calls the agent may dispatch inside one assistant turn. */\n maxToolDispatches?: number\n /** Caller-owned execution for the agent leg. Every agent inference step\n * runs through this function; `agentModel` names the model it receives. */\n agentTransport: MultishotTransport\n /** Caller-owned execution for the simulated-user driver leg. Driver model\n * fallback rotation still applies — the transport receives each candidate\n * model in turn. */\n driverTransport: MultishotTransport\n /** Caller-owned execution for the specialist leg the tool executors run.\n * Defaults to `agentTransport`. */\n toolTransport?: MultishotTransport\n signal?: AbortSignal\n}\n\n/** One multishot shot — the conversation engine `runMultishotMatrix` invokes\n * once per cell. `runMultishot` is the default implementation.\n *\n * An alternative engine (a graph-backed conversation, a replay of a recorded\n * transcript, a sandbox-hosted agent) implements this exact signature and\n * reaches the matrix through `RunMultishotMatrixOptions.runShot`. The matrix\n * keeps every other cell mechanic — cell fan-out, concurrency, the cost\n * ceiling, the judge slots, the cell composite, and the per-cell writers — so\n * swapping the engine needs no copy of the cell body. */\nexport type MultishotShot<TPersona extends MultishotPersona> = (\n opts: RunMultishotOptions<TPersona>,\n) => Promise<MultishotResult>\n\n/** The package's reference conversation engine, and the referent of three\n * things that stop working without it.\n *\n * 1. `runMultishotMatrix` runs it as the per-cell engine when the caller names\n * no `runShot`, so the matrix always has an engine to run.\n * 2. `golden.test.ts` proves the frozen records against it on every run, and\n * perturbs it to prove the records detect a change. Records checked only\n * against a replay of themselves prove nothing.\n * 3. The repo's recording command names it as `--engine`. The script defaults\n * no engine, so a version records whichever one the caller names — and a\n * record set minted from a consumer's engine would let a product's wiring\n * define this package's frozen contract.\n *\n * An alternative engine reaches the matrix through `runShot` and reaches the\n * records through `assertMultishotGoldenScenario`. Neither seam removes the\n * three roles above. */\nexport async function runMultishot<TPersona extends MultishotPersona>(\n opts: RunMultishotOptions<TPersona>,\n): Promise<MultishotResult> {\n return runMultishotConversation(opts, async (conversation) => {\n for (let turn = 0; turn < conversation.maxTurns; turn++) {\n await conversation.agentTurn(turn)\n if (turn < conversation.maxTurns - 1) await conversation.driverTurn(turn)\n }\n })\n}\n","// Multishot matrix wrapper — sweeps profiles × personas × reps, runs\n// the driver-agent loop per cell, applies up to three configured judges,\n// persists per-cell artifacts, and aggregates by axis.\n//\n// Uses runAgentMatrix from @tangle-network/agent-eval/matrix under the\n// hood so cell scheduling + concurrency + cost ceiling are unified with\n// other matrix consumers.\n\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport type { CostProvenance } from '../cost-ledger'\nimport type { MatrixResult } from '../matrix'\nimport { runAgentMatrix, withCellSpend } from '../matrix'\nimport { type JudgeScore, type MultishotJudgeConfig, runJudge } from './judges'\nimport { type MultishotShot, runMultishot } from './multishot'\nimport {\n assertMultishotShotResult,\n type MultishotArtifact,\n type MultishotMessage,\n type MultishotPersona,\n type MultishotShape,\n type MultishotToolDefinition,\n type MultishotToolExecutor,\n type MultishotTransport,\n} from './types'\n\nexport interface ConversationJudgeInput<TPersona extends MultishotPersona> {\n transcript: MultishotMessage[]\n persona: TPersona\n}\n\nexport interface ArtifactJudgeInput<TPersona extends MultishotPersona> {\n artifact: MultishotArtifact\n persona: TPersona\n}\n\nexport interface MultishotJudges<TPersona extends MultishotPersona> {\n /** Scores the full transcript end-to-end (always runs). */\n conversation: MultishotJudgeConfig<ConversationJudgeInput<TPersona>>\n /** Scores each code-type artifact. Optional — omit when domain has no code artifacts. */\n codeReview?: MultishotJudgeConfig<ArtifactJudgeInput<TPersona>>\n /** Scores each non-code (research/content/template) artifact. Optional. */\n contentQuality?: MultishotJudgeConfig<ArtifactJudgeInput<TPersona>>\n /** Which artifact types route to codeReview. Defaults to ['code']. */\n codeArtifactTypes?: string[]\n /** Which artifact types route to contentQuality. Defaults to ['research']. */\n contentArtifactTypes?: string[]\n}\n\nexport interface CellCompositeScore {\n composite: number\n conversation: JudgeScore\n codeReview?: {\n perArtifact: Array<JudgeScore & { turn: number; type: string }>\n composite: number\n }\n contentQuality?: {\n perArtifact: Array<JudgeScore & { turn: number; type: string }>\n composite: number\n }\n}\n\nexport interface RunMultishotMatrixOptions<TPersona extends MultishotPersona> {\n /** AgentProfile axis (matrix primary). */\n profiles: Array<{ id: string; value: AgentProfile }>\n /** Persona axis. */\n personas: TPersona[]\n /** Persona-shaping callbacks. Optional — omitted callbacks are derived per\n * cell from that cell's profile + persona payload (pure-profile path). */\n shape?: MultishotShape<TPersona>\n /** Judge configurations. */\n judges: MultishotJudges<TPersona>\n /** Tool definitions advertised to the agent. Defaults to delegate_research + delegate_code. */\n tools?: MultishotToolDefinition[]\n /** Map from tool name → inline executor. Must align with `tools`. */\n toolExecutors?: Record<string, MultishotToolExecutor>\n /** Tool name → artifact type label. Defaults to research/code mapping. */\n artifactTypeFor?: (toolName: string) => string | undefined\n /** Where per-cell artifacts land. Cells write to `<runDir>/<profileId>/<personaId>/rep-N/`. */\n runDir: string\n /** Replicates per (profile, persona) cell. */\n reps?: number\n /** Max conversation turns per cell. */\n maxTurns?: number\n /** Maximum tool calls the agent may dispatch inside one assistant turn. */\n maxToolDispatches?: number\n /** Max concurrent cells. */\n maxConcurrency?: number\n /** Total $ ceiling across the matrix; cells aborted past this. */\n costCeiling?: number\n /** Upper bound on what one cell can spend. A cell whose cost is a subtotal\n * is charged this bound against `costCeiling` instead of its known amount,\n * so hidden spend cannot walk the run past its budget. */\n maxCellCostUsd?: number\n /** Agent model. */\n agentModel?: string\n /** Driver model. */\n driverModel?: string\n /** Fallback driver models tried when the primary simulated-user model returns empty twice. */\n driverFallbackModels?: string[]\n /** Maximum output tokens for the first agent call in each assistant turn. */\n agentMaxTokens?: number\n /** Maximum output tokens for agent follow-up calls after tool results. */\n toolFollowupMaxTokens?: number\n /** Maximum output tokens for each simulated-user driver response. */\n driverMaxTokens?: number\n /** Maximum output tokens for each judge response. */\n judgeMaxTokens?: number\n /** Caller-owned execution for the agent leg of every cell (see\n * RunMultishotOptions.agentTransport). Judges are unaffected; each judge\n * carries its own transport in MultishotJudges. */\n agentTransport: MultishotTransport\n /** Caller-owned execution for the simulated-user driver leg of every cell. */\n driverTransport: MultishotTransport\n /** Caller-owned execution for the specialist leg the tool executors run in\n * every cell. Defaults to `agentTransport`. */\n toolTransport?: MultishotTransport\n /** Conversation engine for every cell. Defaults to `runMultishot`.\n *\n * The matrix owns everything around the shot — cell fan-out, concurrency,\n * the cost ceiling, the judge slots, the cell composite, the per-cell\n * artifact writers and the run summary — and forwards the whole cell input\n * to this function, so an alternative engine replaces ONLY the\n * conversation. Every option on this interface that `runMultishot` accepts\n * reaches the shot unchanged. `RunMultishotOptions.signal` has no\n * matrix-level counterpart and is not forwarded; a shot owns its own\n * cancellation.\n *\n * A shot that resolves with a value outside `MultishotResult` throws\n * `MultishotShotResultError` for that cell. The default engine is never\n * used as a fallback. */\n runShot?: MultishotShot<TPersona>\n}\n\n/** Per-cell output the multishot matrix records in `MatrixResult.cells`.\n * A consumer that supplies its own `runShot` reads the matrix through this\n * type instead of declaring a structural copy. */\nexport interface MultishotCellOutput {\n turns: number\n toolCalls: number\n artifactCount: number\n}\n\ninterface ArtifactJudgeRun {\n score: JudgeScore & { turn: number; type: string }\n cost: CostProvenance\n}\n\n/** Mean composite over non-failed scores. `0` when the list is empty (a\n * configured judge with nothing to score contributes 0, matching the cell\n * composite's long-standing semantics); `null` when scores exist but every\n * one failed — no signal, so the slot must be EXCLUDED from the cell mean\n * rather than dragging it to zero. */\nfunction meanCompositeExcludingFailed(scores: ReadonlyArray<JudgeScore>): number | null {\n if (scores.length === 0) return 0\n const live = scores.filter((s) => !s.failed)\n if (live.length === 0) return null\n return live.reduce((sum, s) => sum + s.composite, 0) / live.length\n}\n\nexport interface CellCompositeInput {\n conversation: JudgeScore\n /** Present iff the codeReview judge is configured. */\n codeReviews?: ReadonlyArray<JudgeScore>\n /** Present iff the contentQuality judge is configured. */\n contentReviews?: ReadonlyArray<JudgeScore>\n}\n\n/** Cell composite = mean over configured judge slots, excluding failed\n * scores: a failed conversation judge or an all-failed artifact slot carries\n * no signal and is dropped from the mean. `composite` is 0 only when EVERY\n * configured slot failed (`allJudgesFailed` distinguishes that from a real\n * zero). Pure — exported for deterministic testing. */\nexport function computeCellComposite(input: CellCompositeInput): {\n composite: number\n codeComposite: number\n contentComposite: number\n allJudgesFailed: boolean\n} {\n const contributions: number[] = []\n if (!input.conversation.failed) contributions.push(input.conversation.composite)\n\n const codeMean = input.codeReviews ? meanCompositeExcludingFailed(input.codeReviews) : undefined\n if (typeof codeMean === 'number') contributions.push(codeMean)\n const contentMean = input.contentReviews\n ? meanCompositeExcludingFailed(input.contentReviews)\n : undefined\n if (typeof contentMean === 'number') contributions.push(contentMean)\n\n return {\n composite:\n contributions.length === 0\n ? 0\n : contributions.reduce((s, v) => s + v, 0) / contributions.length,\n codeComposite: codeMean ?? 0,\n contentComposite: contentMean ?? 0,\n allJudgesFailed: contributions.length === 0,\n }\n}\n\nexport interface RunMultishotMatrixResult {\n matrix: MatrixResult<MultishotCellOutput>\n}\n\nexport async function runMultishotMatrix<TPersona extends MultishotPersona>(\n opts: RunMultishotMatrixOptions<TPersona>,\n): Promise<RunMultishotMatrixResult> {\n const codeTypes = new Set(opts.judges.codeArtifactTypes ?? ['code'])\n const contentTypes = new Set(opts.judges.contentArtifactTypes ?? ['research'])\n const runShot: MultishotShot<TPersona> = opts.runShot ?? runMultishot\n mkdirSync(opts.runDir, { recursive: true })\n\n const matrix = await runAgentMatrix<MultishotCellOutput>({\n axes: [\n { name: 'profile', values: opts.profiles },\n { name: 'persona', values: opts.personas.map((p) => ({ id: p.id, value: p })) },\n ],\n reps: opts.reps ?? 1,\n maxConcurrency: opts.maxConcurrency ?? 2,\n costCeiling: opts.costCeiling,\n maxCellCostUsd: opts.maxCellCostUsd,\n async runCell(cell) {\n const cellStartedAt = Date.now()\n const profile = cell.axes.profile?.value as AgentProfile\n const persona = cell.axes.persona?.value as TPersona\n const profileId = String(cell.axes.profile?.id ?? 'unknown')\n const personaId = String(cell.axes.persona?.id ?? 'unknown')\n\n // A shot that throws declares its own spend (see `runMultishot`). Rethrow\n // it untouched: a shot that declared nothing spent an unknown amount, and\n // claiming a number here would report a fabricated total.\n const sim = await runShot({\n profile,\n persona,\n shape: opts.shape,\n tools: opts.tools,\n toolExecutors: opts.toolExecutors,\n artifactTypeFor: opts.artifactTypeFor,\n maxTurns: opts.maxTurns,\n maxToolDispatches: opts.maxToolDispatches,\n agentModel: opts.agentModel,\n driverModel: opts.driverModel,\n driverFallbackModels: opts.driverFallbackModels,\n agentMaxTokens: opts.agentMaxTokens,\n toolFollowupMaxTokens: opts.toolFollowupMaxTokens,\n driverMaxTokens: opts.driverMaxTokens,\n agentTransport: opts.agentTransport,\n driverTransport: opts.driverTransport,\n toolTransport: opts.toolTransport,\n })\n // Everything from here on runs with the shot's spend already committed.\n // A throw past this line must carry it, or the money leaves the matrix's\n // cumulative sum and the cost ceiling under-counts the run.\n const shotCostUsd = shotCostSubtotal(sim)\n // A shot that says nothing about provenance is taken at its word, which\n // is how every engine written before the field behaved.\n const shotCostComplete = sim?.costProvenance?.kind !== 'uncaptured'\n let judgeCostUsd = 0\n let judgeCostComplete = false\n // Where the cell is, so a throw declares the right completeness: before\n // the judges only the shot has spent, while they are in flight their\n // spend is unknown, and after they settle their receipts decide.\n let phase: 'validate' | 'judging' | 'scoring' = 'validate'\n try {\n assertMultishotShotResult(sim)\n\n const codeArtifacts = sim.artifacts.filter((a) => codeTypes.has(a.type))\n const contentArtifacts = sim.artifacts.filter((a) => contentTypes.has(a.type))\n\n phase = 'judging'\n const [conversationRun, codeReviewRuns, contentReviewRuns] = await Promise.all([\n runJudge(withJudgeMaxTokens(opts.judges.conversation, opts.judgeMaxTokens), {\n transcript: sim.transcript,\n persona,\n }),\n opts.judges.codeReview\n ? Promise.all(\n codeArtifacts.map((artifact) =>\n runJudge(withJudgeMaxTokens(opts.judges.codeReview!, opts.judgeMaxTokens), {\n artifact,\n persona,\n }).then((result) => ({\n score: {\n ...result.score,\n turn: artifact.turn,\n type: artifact.type,\n },\n cost: result.cost,\n })),\n ),\n )\n : Promise.resolve([] as ArtifactJudgeRun[]),\n opts.judges.contentQuality\n ? Promise.all(\n contentArtifacts.map((artifact) =>\n runJudge(withJudgeMaxTokens(opts.judges.contentQuality!, opts.judgeMaxTokens), {\n artifact,\n persona,\n }).then((result) => ({\n score: {\n ...result.score,\n turn: artifact.turn,\n type: artifact.type,\n },\n cost: result.cost,\n })),\n ),\n )\n : Promise.resolve([] as ArtifactJudgeRun[]),\n ])\n const judgeRuns = [conversationRun, ...codeReviewRuns, ...contentReviewRuns]\n judgeCostUsd = judgeRuns.reduce((sum, run) => sum + (run.cost.usd ?? 0), 0)\n judgeCostComplete = judgeRuns.every((run) => run.cost.kind !== 'uncaptured')\n phase = 'scoring'\n\n const conversation = conversationRun.score\n const codeReviews = codeReviewRuns.map((run) => run.score)\n const contentReviews = contentReviewRuns.map((run) => run.score)\n\n const { composite, codeComposite, contentComposite, allJudgesFailed } =\n computeCellComposite({\n conversation,\n codeReviews: opts.judges.codeReview ? codeReviews : undefined,\n contentReviews: opts.judges.contentQuality ? contentReviews : undefined,\n })\n\n const cellScore: CellCompositeScore = { composite, conversation }\n if (opts.judges.codeReview)\n cellScore.codeReview = { perArtifact: codeReviews, composite: codeComposite }\n if (opts.judges.contentQuality)\n cellScore.contentQuality = { perArtifact: contentReviews, composite: contentComposite }\n\n const cellDir = join(opts.runDir, profileId, personaId, `rep-${cell.rep}`)\n mkdirSync(cellDir, { recursive: true })\n writeFileSync(join(cellDir, 'transcript.json'), JSON.stringify(sim.transcript, null, 2))\n writeFileSync(join(cellDir, 'artifacts.json'), JSON.stringify(sim.artifacts, null, 2))\n writeFileSync(join(cellDir, 'scores.json'), JSON.stringify(cellScore, null, 2))\n\n const notes = [`convo=${conversation.composite.toFixed(1)}`]\n if (opts.judges.codeReview) notes.push(`code=${codeComposite.toFixed(1)}`)\n if (opts.judges.contentQuality) notes.push(`content=${contentComposite.toFixed(1)}`)\n if (allJudgesFailed) notes.push('all-judges-failed')\n if (!judgeCostComplete) notes.push('judge-cost-incomplete')\n\n return {\n output: {\n turns: sim.transcript.length,\n toolCalls: sim.toolCalls,\n artifactCount: sim.artifacts.length,\n },\n verdict: { valid: composite >= 5, score: composite, notes: notes.join(' ') },\n costUsd: sim.costUsd + judgeCostUsd,\n // Either leg can leave the cell total a subtotal: a judge whose cost\n // the router never reported, or a shot that declared its own spend\n // uncaptured. The matrix counts the known part toward the ceiling and\n // reports the cell as under-counted rather than presenting the sum as\n // complete.\n costProvenance:\n judgeCostComplete && shotCostComplete\n ? { kind: 'estimated', usd: sim.costUsd + judgeCostUsd }\n : { kind: 'uncaptured', usd: null },\n durationMs: sim.durationMs,\n }\n } catch (err) {\n // No usable shot subtotal means the cell's spend is genuinely unknown;\n // rethrow untouched so the matrix records it as uncaptured instead of\n // billing a number this frame cannot support.\n if (shotCostUsd === undefined) throw err\n throw withCellSpend(err, {\n costUsd: shotCostUsd + judgeCostUsd,\n durationMs: Date.now() - cellStartedAt,\n // The judges bill before they settle, so a throw among them leaves a\n // subtotal. Before they start, and after they settle with every\n // receipt captured, the amount is the cell's whole spend — unless the\n // shot already declared its own part incomplete.\n kind:\n shotCostComplete && (phase === 'validate' || (phase === 'scoring' && judgeCostComplete))\n ? 'estimated'\n : 'uncaptured',\n })\n }\n },\n })\n\n // Persist top-level summary.\n const summary = {\n cells: matrix.summary.totalCells,\n passRate: matrix.summary.overallPassRate,\n meanScore: matrix.summary.overallMeanScore,\n totalCostUsd: matrix.summary.totalCostUsd,\n costUncapturedCells: matrix.summary.costUncapturedCells,\n ceilingChargedUsd: matrix.summary.ceilingChargedUsd,\n durationMs: matrix.summary.durationMs,\n runsExecuted: matrix.summary.runsExecuted,\n cellsSkipped: matrix.summary.cellsSkipped,\n byProfile: matrix.byAxis.profile,\n byPersona: matrix.byAxis.persona,\n }\n writeFileSync(join(opts.runDir, 'summary.json'), JSON.stringify(summary, null, 2))\n\n // A reader of the on-disk summary must not take the cost line as the run's\n // whole spend when some cells reported only a subtotal.\n const uncaptured = matrix.summary.costUncapturedCells\n const costLabel = uncaptured > 0 ? 'Cost (at least)' : 'Cost'\n\n const md: string[] = [\n `# Multishot matrix`,\n ``,\n `**Cells**: ${matrix.summary.totalCells} | **Pass rate**: ${(matrix.summary.overallPassRate * 100).toFixed(0)}% | **Mean**: ${matrix.summary.overallMeanScore.toFixed(2)} | **${costLabel}**: $${matrix.summary.totalCostUsd.toFixed(2)} | **Duration**: ${(matrix.summary.durationMs / 1000).toFixed(0)}s`,\n ``,\n ...(uncaptured > 0\n ? [\n `> ${uncaptured} of ${matrix.summary.runsExecuted} cells reported a cost subtotal, not a total. Real spend is higher than every cost figure below.`,\n ``,\n ]\n : []),\n `## By profile`,\n ``,\n '| profile | pass | mean | cost |',\n '|---|---|---|---|',\n ...Object.entries(matrix.byAxis.profile ?? {}).map(\n ([id, s]) =>\n `| ${id} | ${(s.passRate * 100).toFixed(0)}% | ${s.meanScore.toFixed(2)} | $${s.totalCostUsd.toFixed(2)} |`,\n ),\n ``,\n `## By persona`,\n ``,\n '| persona | pass | mean | cost |',\n '|---|---|---|---|',\n ...Object.entries(matrix.byAxis.persona ?? {}).map(\n ([id, s]) =>\n `| ${id} | ${(s.passRate * 100).toFixed(0)}% | ${s.meanScore.toFixed(2)} | $${s.totalCostUsd.toFixed(2)} |`,\n ),\n ``,\n ]\n writeFileSync(join(opts.runDir, 'summary.md'), md.join('\\n'))\n\n return { matrix }\n}\n\n/** The shot's own spend, when the value it resolved with reports a usable\n * amount. `undefined` when it does not — a malformed shot result is exactly\n * the case where the number cannot be trusted, and billing a wrong figure is\n * worse than recording the cell as uncaptured. */\nfunction shotCostSubtotal(\n sim: { costUsd?: unknown; costProvenance?: CostProvenance } | null | undefined,\n): number | undefined {\n const value = sim?.costUsd\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined\n}\n\nfunction withJudgeMaxTokens<TInput>(\n judge: MultishotJudgeConfig<TInput>,\n maxTokens: number | undefined,\n): MultishotJudgeConfig<TInput> {\n if (maxTokens === undefined || judge.maxTokens !== undefined) return judge\n return { ...judge, maxTokens }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA+BA,IAAa,6BAAb,cAAgD,MAAM;CACpD;CACA,YAAY,YAAqC;EAC/C,MAAM,QAAQ,SACZ,WAAW,KAAK,QAAQ,GAAG,IAAI,OAAO,IAAI,IAAI,QAAQ,GACtD,IACF;EACA,MACE,GAAG,WAAW,OAAO,+GACgC,MAAM,EAC7D;EACA,KAAK,OAAO;EACZ,KAAK,aAAa;CACpB;AACF;;;;;AAMA,IAAa,yBAAb,cAA4C,MAAM;CAChD,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,oCAAb,cAAuD,MAAM;CAC3D;CACA,YAAY,aAAuB;EACjC,MACE,2BAA2B,YAAY,OAAO,mDAChC,SAAS,WAAW,EAAE,kDACtC;EACA,KAAK,OAAO;EACZ,KAAK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