execute<C extends AgentToolContext> static method

Future<AgentRunOutcome> execute<C extends AgentToolContext>({
  1. required AgentToolBinding<C> binding,
  2. required AgentAuditLog audit,
  3. required Future<String> drive(
    1. AgentToolBinding<C> binding
    ),
  4. Future<bool> confirm(
    1. AgentRunOutcome preview
    )?,
  5. String label = 'Agent run',
})

Runs drive — which asks the model and lets it call tools through binding — as one atomic run, then asks confirm whether to keep it.

binding's context must record into a staging log: its entries are appended to audit only when the run has ended, marked rolled-back if it did not survive, because an append-only trail cannot be corrected after the fact.

Implementation

static Future<AgentRunOutcome> execute<C extends AgentToolContext>({
  required AgentToolBinding<C> binding,
  required AgentAuditLog audit,
  required Future<String> Function(AgentToolBinding<C> binding) drive,
  Future<bool> Function(AgentRunOutcome preview)? confirm,
  String label = 'Agent run',
}) async {
  final staging = binding.context.audit;
  if (identical(staging, audit)) {
    throw ArgumentError.value(
      audit,
      'audit',
      'must not be the binding\'s own log: a run stages its entries and '
          'commits them once it knows whether it survived',
    );
  }
  final before = staging.entries.length;
  // Taken before the first call, so the preview's dry run starts where the
  // run started rather than where it ended.
  final start = binding.context.dryRunCopy() as C;
  final outcome = await AgentPreviewThenApply.run<String>(
    atomically: binding.context.runAtomically,
    label: label,
    propose: () => drive(binding),
    // A refused call makes the run incomplete: it is rolled back without
    // asking, because there is nothing whole to decide about.
    refuse: (_) => binding.failure,
    confirm: (answer) async {
      final ask = confirm;
      if (ask == null) return true;
      final steps = binding.steps;
      return ask(
        AgentRunOutcome(
          status: AgentRunStatus.accepted,
          steps: steps,
          answer: answer,
          dryRun: await _simulate(start, binding.registry, steps),
        ),
      );
    },
  );
  final status = switch (outcome.status) {
    AgentProposalStatus.accepted => AgentRunStatus.accepted,
    AgentProposalStatus.rejected => AgentRunStatus.rejected,
    AgentProposalStatus.failed => AgentRunStatus.rolledBack,
  };
  final staged = staging.entries.sublist(before);
  audit.append(
    status == AgentRunStatus.accepted
        ? staged
        : [for (final entry in staged) entry.asRolledBack()],
  );
  return AgentRunOutcome(
    status: status,
    steps: binding.steps,
    answer: outcome.proposal ?? '',
    error: outcome.error,
  );
}