import {
  TraceEmitter
} from "./chunk-TVVP3ZZQ.js";

// src/control-runtime.ts
var DEFAULT_BUDGET = {
  maxSteps: 8,
  maxWallMs: 5 * 60 * 1e3
};
async function runAgentControlLoop(config) {
  const budget = normalizeBudget(config.budget);
  const actionFailure = config.actionFailure ?? "continue";
  const controller = new AbortController();
  const upstreamAbort = () => controller.abort(config.signal?.reason);
  if (config.signal) {
    if (config.signal.aborted) controller.abort(config.signal.reason);
    else config.signal.addEventListener("abort", upstreamAbort, { once: true });
  }
  const started = Date.now();
  const wallTimer = budget.maxWallMs ? setTimeout(
    () => controller.abort(new Error("control runtime wall timeout")),
    budget.maxWallMs
  ) : void 0;
  const history = [];
  const emitter = config.store ? new TraceEmitter(config.store) : void 0;
  let spentCostUsd = 0;
  const runtimeErrors = [];
  let lastStateFingerprint;
  let lastActionFingerprint;
  let noProgressStreak = 0;
  let repeatedActionStreak = 0;
  try {
    if (emitter) {
      await runTrace(
        runtimeErrors,
        0,
        () => emitter.startRun({
          scenarioId: config.scenarioId ?? "agent-control-loop",
          projectId: config.projectId,
          variantId: config.variantId,
          layer: "meta",
          tags: {
            intent: config.intent.slice(0, 120),
            maxSteps: String(budget.maxSteps),
            ...budget.maxCostUsd !== void 0 ? { maxCostUsd: String(budget.maxCostUsd) } : {}
          }
        })
      );
    }
    let state;
    let evals;
    try {
      state = await config.observe({ history, abortSignal: controller.signal });
    } catch (err) {
      const error = runtimeError("observe", 0, err);
      runtimeErrors.push(error);
      return finish(emitter, {
        intent: config.intent,
        pass: false,
        completed: false,
        reason: error.message,
        steps: history,
        finalState: void 0,
        finalEvals: [],
        wallMs: Date.now() - started,
        spentCostUsd,
        runId: emitter?.runId ?? null,
        failureClass: "unknown",
        runtimeErrors,
        stoppedBy: "runtime-error"
      });
    }
    try {
      evals = await config.validate({
        intent: config.intent,
        state,
        history,
        abortSignal: controller.signal
      });
      await recordEvalSpans(emitter, evals, "initial", runtimeErrors, 0);
    } catch (err) {
      const error = runtimeError("validate", 0, err);
      runtimeErrors.push(error);
      return finish(emitter, {
        intent: config.intent,
        pass: false,
        completed: false,
        reason: error.message,
        steps: history,
        finalState: state,
        finalEvals: [],
        wallMs: Date.now() - started,
        spentCostUsd,
        runId: emitter?.runId ?? null,
        failureClass: "unknown",
        runtimeErrors,
        stoppedBy: "runtime-error"
      });
    }
    lastStateFingerprint = fingerprintState(state, config.stopPolicies);
    for (let stepIndex = 0; stepIndex < budget.maxSteps; stepIndex++) {
      if (controller.signal.aborted) {
        return finish(emitter, {
          intent: config.intent,
          pass: false,
          completed: false,
          reason: abortReason(controller.signal),
          score: void 0,
          steps: history,
          finalState: state,
          finalEvals: evals,
          wallMs: Date.now() - started,
          spentCostUsd,
          runId: emitter?.runId ?? null,
          failureClass: "timeout",
          runtimeErrors,
          stoppedBy: "abort"
        });
      }
      const budgetStop = budgetStopDecision(budget, spentCostUsd);
      if (budgetStop.stop) {
        return finish(emitter, {
          intent: config.intent,
          pass: false,
          completed: false,
          reason: budgetStop.reason,
          score: averageScore(evals),
          steps: history,
          finalState: state,
          finalEvals: evals,
          wallMs: Date.now() - started,
          spentCostUsd,
          runId: emitter?.runId ?? null,
          failureClass: "budget_exceeded",
          runtimeErrors,
          stoppedBy: "budget"
        });
      }
      const ctx = makeContext(
        config.intent,
        state,
        evals,
        history,
        budget,
        stepIndex,
        started,
        spentCostUsd,
        controller.signal,
        emitter
      );
      let stop;
      try {
        stop = config.shouldStop ? await config.shouldStop(ctx) : defaultStopDecision(evals);
      } catch (err) {
        runtimeErrors.push(runtimeError("stop-policy", stepIndex, err));
        return finish(emitter, {
          intent: config.intent,
          pass: false,
          completed: false,
          reason: runtimeErrors[runtimeErrors.length - 1].message,
          score: averageScore(evals),
          steps: history,
          finalState: state,
          finalEvals: evals,
          wallMs: Date.now() - started,
          spentCostUsd,
          runId: emitter?.runId ?? null,
          failureClass: "unknown",
          runtimeErrors,
          stoppedBy: "runtime-error"
        });
      }
      if (stop.stop) {
        return finish(emitter, {
          intent: config.intent,
          pass: stop.pass,
          completed: true,
          reason: stop.reason,
          score: stop.score,
          steps: history,
          finalState: state,
          finalEvals: evals,
          wallMs: Date.now() - started,
          spentCostUsd,
          runId: emitter?.runId ?? null,
          failureClass: stop.failureClass,
          runtimeErrors,
          stoppedBy: "stop-policy"
        });
      }
      let decision;
      try {
        decision = await config.decide(ctx);
      } catch (err) {
        runtimeErrors.push(runtimeError("decide", stepIndex, err));
        return finish(emitter, {
          intent: config.intent,
          pass: false,
          completed: false,
          reason: runtimeErrors[runtimeErrors.length - 1].message,
          score: averageScore(evals),
          steps: history,
          finalState: state,
          finalEvals: evals,
          wallMs: Date.now() - started,
          spentCostUsd,
          runId: emitter?.runId ?? null,
          failureClass: "unknown",
          runtimeErrors,
          stoppedBy: "runtime-error"
        });
      }
      if (decision.type === "stop") {
        return finish(emitter, {
          intent: config.intent,
          pass: decision.pass ?? false,
          completed: true,
          reason: decision.reason,
          score: decision.score,
          steps: history,
          finalState: state,
          finalEvals: evals,
          wallMs: Date.now() - started,
          spentCostUsd,
          runId: emitter?.runId ?? null,
          failureClass: decision.pass === false ? "unknown" : void 0,
          runtimeErrors,
          stoppedBy: "policy"
        });
      }
      const actionFingerprint = fingerprintAction(decision.action, config.stopPolicies);
      repeatedActionStreak = actionFingerprint === lastActionFingerprint ? repeatedActionStreak + 1 : 1;
      lastActionFingerprint = actionFingerprint;
      const repeatedActionStop = repeatedActionStopDecision(
        config.stopPolicies,
        repeatedActionStreak
      );
      if (repeatedActionStop.stop) {
        return finish(emitter, {
          intent: config.intent,
          pass: false,
          completed: true,
          reason: repeatedActionStop.reason,
          score: averageScore(evals),
          steps: history,
          finalState: state,
          finalEvals: evals,
          wallMs: Date.now() - started,
          spentCostUsd,
          runId: emitter?.runId ?? null,
          failureClass: "tool_recovery_failure",
          runtimeErrors,
          stoppedBy: "stop-policy"
        });
      }
      const beforeState = state;
      const evalsBefore = evals;
      const scoreBefore = averageScore(evals);
      const actionStarted = Date.now();
      const stepHandle = emitter ? await runTrace(
        runtimeErrors,
        stepIndex,
        () => emitter.tool({
          name: `control-step-${stepIndex}`,
          toolName: "agent-control-action",
          args: decision.action,
          attributes: {
            decision: decision.reason ?? "continue",
            repeatedActionStreak
          }
        })
      ) : void 0;
      let actionOutcome;
      try {
        const result = await config.act(decision.action, ctx);
        const rawCostUsd = config.getActionCostUsd?.({
          action: decision.action,
          result,
          state,
          evals,
          history
        });
        const costUsd = normalizeActionCostUsd(rawCostUsd, runtimeErrors, stepIndex);
        if (costUsd !== void 0 && Number.isFinite(costUsd) && costUsd > 0) {
          spentCostUsd += costUsd;
          await recordCostBudget(
            emitter,
            budget,
            spentCostUsd,
            stepHandle,
            runtimeErrors,
            stepIndex
          );
        }
        actionOutcome = {
          ok: true,
          result,
          ...costUsd !== void 0 ? { costUsd } : {},
          durationMs: Date.now() - actionStarted
        };
      } catch (err) {
        runtimeErrors.push(runtimeError("act", stepIndex, err));
        actionOutcome = {
          ok: false,
          error: runtimeErrors[runtimeErrors.length - 1].message,
          durationMs: Date.now() - actionStarted
        };
        if (actionFailure === "stop") {
          await runTrace(
            runtimeErrors,
            stepIndex,
            () => stepHandle?.fail(actionOutcome.error ?? "action failed")
          );
          const step2 = {
            index: stepIndex,
            decision,
            beforeState,
            afterState: state,
            evalsBefore,
            evalsAfter: evals,
            actionOutcome,
            startedAt: new Date(actionStarted).toISOString(),
            endedAt: (/* @__PURE__ */ new Date()).toISOString()
          };
          history.push(step2);
          await runOnStep(config.onStep, step2, runtimeErrors);
          return finish(emitter, {
            intent: config.intent,
            pass: false,
            completed: false,
            reason: actionOutcome.error ?? "action failed",
            score: averageScore(evals),
            steps: history,
            finalState: state,
            finalEvals: evals,
            wallMs: Date.now() - started,
            spentCostUsd,
            runId: emitter?.runId ?? null,
            failureClass: "unknown",
            runtimeErrors,
            stoppedBy: "runtime-error"
          });
        }
      }
      try {
        state = await config.observe({ history, abortSignal: controller.signal });
      } catch (err) {
        runtimeErrors.push(runtimeError("observe", stepIndex, err));
        const step2 = {
          index: stepIndex,
          decision,
          beforeState,
          afterState: beforeState,
          evalsBefore,
          evalsAfter: evals,
          actionOutcome,
          startedAt: new Date(actionStarted).toISOString(),
          endedAt: (/* @__PURE__ */ new Date()).toISOString()
        };
        history.push(step2);
        await runTrace(
          runtimeErrors,
          stepIndex,
          () => stepHandle?.fail(runtimeErrors[runtimeErrors.length - 1].message)
        );
        await runOnStep(config.onStep, step2, runtimeErrors);
        return finish(emitter, {
          intent: config.intent,
          pass: false,
          completed: false,
          reason: runtimeErrors[runtimeErrors.length - 1].message,
          score: averageScore(evals),
          steps: history,
          finalState: beforeState,
          finalEvals: evals,
          wallMs: Date.now() - started,
          spentCostUsd,
          runId: emitter?.runId ?? null,
          failureClass: "unknown",
          runtimeErrors,
          stoppedBy: "runtime-error"
        });
      }
      try {
        evals = await config.validate({
          intent: config.intent,
          state,
          history,
          abortSignal: controller.signal
        });
        await recordEvalSpans(
          emitter,
          evals,
          `step-${stepIndex}`,
          runtimeErrors,
          stepIndex,
          stepHandle?.span.spanId
        );
      } catch (err) {
        runtimeErrors.push(runtimeError("validate", stepIndex, err));
        const step2 = {
          index: stepIndex,
          decision,
          beforeState,
          afterState: state,
          evalsBefore,
          evalsAfter: evals,
          actionOutcome,
          startedAt: new Date(actionStarted).toISOString(),
          endedAt: (/* @__PURE__ */ new Date()).toISOString()
        };
        history.push(step2);
        await runTrace(
          runtimeErrors,
          stepIndex,
          () => stepHandle?.fail(runtimeErrors[runtimeErrors.length - 1].message)
        );
        await runOnStep(config.onStep, step2, runtimeErrors);
        return finish(emitter, {
          intent: config.intent,
          pass: false,
          completed: false,
          reason: runtimeErrors[runtimeErrors.length - 1].message,
          score: averageScore(evals),
          steps: history,
          finalState: state,
          finalEvals: evals,
          wallMs: Date.now() - started,
          spentCostUsd,
          runId: emitter?.runId ?? null,
          failureClass: "unknown",
          runtimeErrors,
          stoppedBy: "runtime-error"
        });
      }
      const scoreAfter = averageScore(evals);
      const stateFingerprint = fingerprintState(state, config.stopPolicies);
      const noProgressStop = noProgressStopDecision({
        policies: config.stopPolicies,
        lastStateFingerprint,
        stateFingerprint,
        scoreBefore,
        scoreAfter,
        currentStreak: noProgressStreak
      });
      noProgressStreak = noProgressStop.streak;
      lastStateFingerprint = stateFingerprint;
      const step = {
        index: stepIndex,
        decision,
        beforeState,
        afterState: state,
        evalsBefore,
        evalsAfter: evals,
        actionOutcome,
        startedAt: new Date(actionStarted).toISOString(),
        endedAt: (/* @__PURE__ */ new Date()).toISOString()
      };
      history.push(step);
      if (actionOutcome.ok) {
        await runTrace(
          runtimeErrors,
          stepIndex,
          () => stepHandle?.end({
            attributes: {
              actionCostUsd: actionOutcome.costUsd ?? null,
              spentCostUsd,
              scoreBefore: scoreBefore ?? null,
              scoreAfter: scoreAfter ?? null,
              noProgressStreak
            }
          })
        );
      } else {
        await runTrace(
          runtimeErrors,
          stepIndex,
          () => stepHandle?.fail(actionOutcome.error ?? "action failed", {
            attributes: {
              spentCostUsd,
              noProgressStreak
            }
          })
        );
      }
      await runOnStep(config.onStep, step, runtimeErrors);
      if (noProgressStop.stop) {
        return finish(emitter, {
          intent: config.intent,
          pass: false,
          completed: true,
          reason: noProgressStop.reason,
          score: scoreAfter,
          steps: history,
          finalState: state,
          finalEvals: evals,
          wallMs: Date.now() - started,
          spentCostUsd,
          runId: emitter?.runId ?? null,
          failureClass: "tool_recovery_failure",
          runtimeErrors,
          stoppedBy: "stop-policy"
        });
      }
      const postStepBudgetStop = budgetStopDecision(budget, spentCostUsd);
      if (postStepBudgetStop.stop) {
        return finish(emitter, {
          intent: config.intent,
          pass: false,
          completed: false,
          reason: postStepBudgetStop.reason,
          score: scoreAfter,
          steps: history,
          finalState: state,
          finalEvals: evals,
          wallMs: Date.now() - started,
          spentCostUsd,
          runId: emitter?.runId ?? null,
          failureClass: "budget_exceeded",
          runtimeErrors,
          stoppedBy: "budget"
        });
      }
      const postStepCtx = makeContext(
        config.intent,
        state,
        evals,
        history,
        budget,
        stepIndex + 1,
        started,
        spentCostUsd,
        controller.signal,
        emitter
      );
      let postStepStop;
      try {
        postStepStop = config.shouldStop ? await config.shouldStop(postStepCtx) : defaultStopDecision(evals);
      } catch (err) {
        runtimeErrors.push(runtimeError("stop-policy", stepIndex + 1, err));
        return finish(emitter, {
          intent: config.intent,
          pass: false,
          completed: false,
          reason: runtimeErrors[runtimeErrors.length - 1].message,
          score: averageScore(evals),
          steps: history,
          finalState: state,
          finalEvals: evals,
          wallMs: Date.now() - started,
          spentCostUsd,
          runId: emitter?.runId ?? null,
          failureClass: "unknown",
          runtimeErrors,
          stoppedBy: "runtime-error"
        });
      }
      if (postStepStop.stop) {
        return finish(emitter, {
          intent: config.intent,
          pass: postStepStop.pass,
          completed: true,
          reason: postStepStop.reason,
          score: postStepStop.score,
          steps: history,
          finalState: state,
          finalEvals: evals,
          wallMs: Date.now() - started,
          spentCostUsd,
          runId: emitter?.runId ?? null,
          failureClass: postStepStop.failureClass,
          runtimeErrors,
          stoppedBy: "stop-policy"
        });
      }
    }
    return finish(emitter, {
      intent: config.intent,
      pass: false,
      completed: false,
      reason: `budget exhausted: maxSteps=${budget.maxSteps}`,
      steps: history,
      finalState: state,
      finalEvals: evals,
      wallMs: Date.now() - started,
      spentCostUsd,
      runId: emitter?.runId ?? null,
      failureClass: "budget_exceeded",
      runtimeErrors,
      stoppedBy: "budget"
    });
  } catch (err) {
    runtimeErrors.push(runtimeError("act", history.length, err));
    return finish(emitter, {
      intent: config.intent,
      pass: false,
      completed: false,
      reason: runtimeErrors[runtimeErrors.length - 1].message,
      steps: history,
      finalState: void 0,
      finalEvals: [],
      wallMs: Date.now() - started,
      spentCostUsd,
      runId: emitter?.runId ?? null,
      failureClass: "unknown",
      runtimeErrors,
      stoppedBy: "runtime-error"
    });
  } finally {
    if (wallTimer) clearTimeout(wallTimer);
    if (config.signal) config.signal.removeEventListener("abort", upstreamAbort);
  }
}
function stopOnNoProgress(maxNoProgressSteps, options = {}) {
  return { ...options, maxNoProgressSteps };
}
function stopOnRepeatedAction(maxRepeatedActions, options = {}) {
  return { ...options, maxRepeatedActions };
}
function objectiveEval(input) {
  return { ...input, objective: true };
}
function subjectiveEval(input) {
  return { ...input, objective: false };
}
function normalizeBudget(input) {
  const raw = { ...DEFAULT_BUDGET, ...input };
  if (!Number.isInteger(raw.maxSteps) || raw.maxSteps < 1) {
    throw new RangeError(
      `ControlRuntime budget.maxSteps must be an integer >= 1, got ${String(raw.maxSteps)}`
    );
  }
  const budget = { maxSteps: raw.maxSteps };
  if (raw.maxWallMs !== void 0) {
    if (typeof raw.maxWallMs !== "number" || !Number.isFinite(raw.maxWallMs) || raw.maxWallMs <= 0) {
      throw new RangeError(
        `ControlRuntime budget.maxWallMs must be a positive finite number, got ${String(raw.maxWallMs)}`
      );
    }
    budget.maxWallMs = raw.maxWallMs;
  }
  if (raw.maxCostUsd !== void 0) {
    if (typeof raw.maxCostUsd !== "number" || !Number.isFinite(raw.maxCostUsd) || raw.maxCostUsd < 0) {
      throw new RangeError(
        `ControlRuntime budget.maxCostUsd must be a nonnegative finite number, got ${String(raw.maxCostUsd)}`
      );
    }
    budget.maxCostUsd = raw.maxCostUsd;
  }
  return budget;
}
function normalizeActionCostUsd(costUsd, runtimeErrors, stepIndex) {
  if (costUsd === void 0) return void 0;
  if (!Number.isFinite(costUsd) || costUsd < 0) {
    runtimeErrors.push(
      runtimeError("act", stepIndex, new Error(`invalid action costUsd: ${String(costUsd)}`))
    );
    return void 0;
  }
  return costUsd;
}
function allCriticalPassed(evals) {
  return evals.every(
    (result) => result.passed || result.severity !== "critical" && result.severity !== "error"
  );
}
function makeContext(intent, state, evals, history, budget, stepIndex, started, spentCostUsd, abortSignal, emitter) {
  return {
    intent,
    state,
    evals,
    history,
    budget,
    stepIndex,
    wallMs: Date.now() - started,
    spentCostUsd,
    remainingCostUsd: budget.maxCostUsd === void 0 ? void 0 : Math.max(0, budget.maxCostUsd - spentCostUsd),
    abortSignal,
    emitter
  };
}
function defaultStopDecision(evals) {
  if (!evals.length) return { stop: false, pass: false, reason: "no evals yet" };
  const pass = allCriticalPassed(evals);
  return pass ? { stop: true, pass: true, reason: "all critical evals passed", score: averageScore(evals) } : {
    stop: false,
    pass: false,
    reason: "critical evals still failing",
    score: averageScore(evals)
  };
}
function averageScore(evals) {
  const scored = evals.map((result) => result.score).filter((score) => typeof score === "number");
  if (!scored.length) return void 0;
  return Math.round(scored.reduce((sum, score) => sum + score, 0) / scored.length * 1e3) / 1e3;
}
function budgetStopDecision(budget, spentCostUsd) {
  if (budget.maxCostUsd !== void 0 && spentCostUsd >= budget.maxCostUsd) {
    return {
      stop: true,
      reason: `budget exhausted: maxCostUsd=${budget.maxCostUsd}`
    };
  }
  return { stop: false, reason: "" };
}
async function recordCostBudget(emitter, budget, spentCostUsd, handle, runtimeErrors, stepIndex) {
  if (!emitter || budget.maxCostUsd === void 0) return;
  const maxCostUsd = budget.maxCostUsd;
  await runTrace(
    runtimeErrors,
    stepIndex,
    () => emitter.recordBudget({
      dimension: "usd",
      limit: maxCostUsd,
      consumed: spentCostUsd,
      remaining: Math.max(0, maxCostUsd - spentCostUsd),
      breached: spentCostUsd >= maxCostUsd,
      spanId: handle?.span.spanId
    })
  );
}
async function recordEvalSpans(emitter, evals, phase, runtimeErrors, stepIndex, targetSpanId) {
  if (!emitter) return;
  for (const result of evals) {
    await runTrace(
      runtimeErrors,
      stepIndex,
      () => emitter.recordJudge({
        judgeId: result.objective ? "objective-validator" : "subjective-judge",
        targetSpanId: targetSpanId ?? emitter.runId,
        name: `control-eval/${result.id}`,
        dimension: result.id,
        score: typeof result.score === "number" ? result.score : result.passed ? 1 : 0,
        rationale: result.detail,
        evidence: result.evidence,
        attributes: {
          phase,
          passed: result.passed,
          severity: result.severity,
          objective: result.objective
        }
      })
    );
  }
}
async function runOnStep(onStep, step, runtimeErrors) {
  if (!onStep) return;
  try {
    await onStep(step);
  } catch (err) {
    runtimeErrors.push(runtimeError("on-step", step.index, err));
  }
}
async function runTrace(runtimeErrors, stepIndex, write) {
  try {
    return await write();
  } catch (err) {
    runtimeErrors.push(runtimeError("trace", stepIndex, err));
    return void 0;
  }
}
function noProgressStopDecision(args) {
  const max = args.policies?.maxNoProgressSteps;
  if (!max || max <= 0) return { stop: false, reason: "", streak: 0 };
  const minScoreDelta = args.policies?.minScoreDelta ?? 1e-3;
  const scoreDelta = Math.abs((args.scoreAfter ?? 0) - (args.scoreBefore ?? 0));
  const stateUnchanged = args.lastStateFingerprint !== void 0 && args.lastStateFingerprint === args.stateFingerprint;
  const scoreFlat = scoreDelta < minScoreDelta;
  const streak = stateUnchanged && scoreFlat ? args.currentStreak + 1 : 0;
  return streak >= max ? { stop: true, reason: `stuck: no state/score progress for ${streak} step(s)`, streak } : { stop: false, reason: "", streak };
}
function repeatedActionStopDecision(policies, streak) {
  const max = policies?.maxRepeatedActions;
  if (!max || max <= 0 || streak < max) return { stop: false, reason: "" };
  return {
    stop: true,
    reason: `stuck: repeated same action for ${streak} step(s)`
  };
}
function fingerprintState(state, policies) {
  if (policies?.stateFingerprint) return policies.stateFingerprint(state);
  return stableFingerprint(state);
}
function fingerprintAction(action, policies) {
  if (policies?.actionFingerprint) return policies.actionFingerprint(action);
  return stableFingerprint(action);
}
function stableFingerprint(value) {
  if (typeof value === "string") return value;
  if (typeof value === "number" || typeof value === "boolean" || value == null) return String(value);
  try {
    return JSON.stringify(sortForFingerprint(value));
  } catch {
    return String(value);
  }
}
function sortForFingerprint(value) {
  if (Array.isArray(value)) return value.map(sortForFingerprint);
  if (!value || typeof value !== "object") return value;
  const record = value;
  const sorted = {};
  for (const key of Object.keys(record).sort()) {
    sorted[key] = sortForFingerprint(record[key]);
  }
  return sorted;
}
function abortReason(signal) {
  const reason = signal.reason;
  if (reason instanceof Error) return reason.message;
  return reason ? String(reason) : "aborted";
}
function runtimeError(phase, stepIndex, err) {
  const message = err instanceof Error ? err.message : String(err);
  return { phase, stepIndex, message };
}
async function finish(emitter, result) {
  await runTrace(
    result.runtimeErrors,
    result.steps.length,
    () => emitter?.endRun({
      pass: result.pass,
      score: result.score ?? averageScore(result.finalEvals),
      failureClass: result.failureClass,
      notes: result.reason
    })
  );
  return result;
}

export {
  runAgentControlLoop,
  stopOnNoProgress,
  stopOnRepeatedAction,
  objectiveEval,
  subjectiveEval,
  allCriticalPassed
};
//# sourceMappingURL=chunk-NCRFYPS3.js.map