run method

  1. @override
Stream<LlmEvent> run(
  1. LlmRequest request
)
override

The run: served from the request's session, where the transport's events are bounded by stallGap (see boundedAiRun) and streamed back here. Throws LlmSessionBusyException when that session already has a run. Cancelling the stream cancels the run. complete is derived from this.

Implementation

@override
Stream<LlmEvent> run(LlmRequest request) {
  // a provider that reports no tool use never sees a tool
  // declaration. Reaching here with one is a caller that skipped the
  // capability check, and sending the prompt without the tools would run an
  // agent that cannot act while appearing to.
  if (request.toolBinding != null && !capabilities.canUseTools) {
    throw UnsupportedError(
      'This AI provider cannot use document tools; check '
      'capabilities.canUseTools before binding them.',
    );
  }
  final transport = selector.active;
  if (transport == null) {
    // Features are gated off, so reaching here is a caller bug rather
    // than a runtime condition to recover from.
    throw UnsupportedError(
      'No AI transport is available; check isAvailable before completing.',
    );
  }

  final binding = request.toolBinding;
  final completion = AgentSdkCompletionRequest(
    prompt: request.prompt.user,
    context: request.prompt.system,
    systemPrompt: systemPrompt,
    model: model ?? request.options.model,
    // the binding's registry, declared to the model for this
    // request only; each call is dispatched back into the binding.
    tools: binding == null
        ? null
        : AgentSdkToolSet.fromBinding(binding, serverName: toolServerName),
  );

  // in the request's session, which refuses when busy.
  return sessions.run(
    sessionId: request.options.sessionId ?? llmSessionFor(request.purpose),
    transport: transport,
    request: completion,
    prelude: llmRunPrelude(request, providerId: transport.id),
    stallGap: stallGap,
    // The backend is gone, not merely unhappy: close the gate and report
    // once, so the editor hides the affordance instead of failing again on
    // the next attempt.
    onFailure: (failure) {
      if (failure.kind == LlmErrorKind.unreachable) {
        selector.markLost(failure);
      }
    },
  );
}