complete method
Runs one completion, mapping SDKMessages to AgentSdkCompletionEvents
through an SdkTrailTranslator: the far end's start,
thinking and text as they stream, each tool call and its result, every
announced retry, and the result's usage and end. Everything else the far
end sends is AgentSdkLiveness; the provider's gap bound counts it as
evidence of life, so a model thinking for two minutes before its first
token is never mistaken for one that has died.
Why this is a controller and not an async*. The seam promises that
cancelling the subscription aborts the remote completion, and an async*
generator cannot keep that promise: while it is suspended at an await
— which is exactly where it sits when the model is still thinking and no
delta has arrived — cancellation cannot resume it, so cancel waits for
an event that a cancelled request will never produce. A controller makes
onCancel a first-class hook, so the abort happens the moment it is
asked for, precisely in the case that matters most: a long completion the
user has changed their mind about — or one the provider's bound has just
abandoned.
Implementation
Stream<AgentSdkCompletionEvent> complete(AgentSdkCompletionRequest request) {
final controller = StreamController<AgentSdkCompletionEvent>();
StreamSubscription<SdkMessage>? subscription;
/// Ends the completion with [failure] and aborts the remote query.
void abandon(LlmTransportException failure) {
if (controller.isClosed) return;
final sub = subscription;
subscription = null;
controller.addError(failure);
unawaited(controller.close());
// Reported first, cancelled second, and the cancel is not awaited. The
// caller already has its answer, and a cancel that itself hung would
// reinstate exactly the hang this path exists to end. Sending it at all
// matters: without it every abandoned run leaves a Claude Code
// grandchild still working for a caller that has stopped listening.
if (sub != null) unawaited(sub.cancel());
}
/// Reports that the far end is alive without having produced text.
void alive(String source) {
if (!controller.isClosed) controller.add(AgentSdkLiveness(source));
}
controller.onListen = () {
final tools = request.tools;
final query = _agent.query(
prompt: request.wirePrompt,
options: Options(
model: request.model,
systemPrompt: request.systemPrompt == null
? null
: SystemPromptText(request.systemPrompt!),
// The SDK's own tools are off in every request: no file, no shell,
// no web. A plain completion gets nothing else and one turn — it
// must not be able to act on anything. An agent run gets exactly
// the tools it was handed, declared on an in-process MCP
// server whose calls come back to [tools] over this connection, and
// only those are allowed; `strictMcpConfig` keeps every MCP server
// from the far end's own settings out.
tools: const ToolsList([]),
allowedTools: tools == null
? const []
: [
for (final declaration in tools.declarations)
agentSdkMcpToolName(tools.serverName, declaration.name),
],
mcpServers: tools == null ? null : _toolOptions(tools, alive),
strictMcpConfig: tools == null ? null : true,
maxTurns: tools == null ? 1 : agentRunMaxTurns,
// What makes the provider's gap bound a *gap* bound rather than a
// disguised budget on model latency. Without this the only messages
// in a run are `system/init`, the finished assistant message, and
// the result — so a model that thinks for two minutes before its
// first token is indistinguishable on this socket from one that has
// died, and the bound would abandon exactly the completions worth
// waiting for. The events are reported as liveness and otherwise
// ignored: text is emitted from the assembled `SdkAssistantMessage`
// alone, so nothing is delivered twice.
includePartialMessages: true,
// The trail shows the model's thinking, so the query asks
// for it: adaptive, so the model decides how much a request needs,
// and summarized, so what reaches the trail is readable.
thinking: const ThinkingAdaptive(display: 'summarized'),
),
);
// every message as its trail events, the text included.
final translator = SdkTrailTranslator(
providerId: transportId,
toolServerName: tools?.serverName,
);
subscription = query.listen(
(message) {
if (controller.isClosed) return;
debugMessageTap?.call(transportId, message.raw);
if ((message is SdkSystemEvent &&
_isCredentialRejection(message.raw)) ||
(message is SdkAssistantMessage &&
message.error == 'authentication_failed')) {
abandon(
LlmTransportException(
LlmErrorKind.remote,
'The AI provider rejected the credential '
'(HTTP ${message.raw['error_status'] ?? 401}). Check the API key '
'or sign-in the AI server uses.',
transportId: transportId,
),
);
return;
}
translator.translate(message).forEach(controller.add);
if (message case SdkResultMessage(isError: true, :final result)) {
controller.addError(
LlmTransportException(
LlmErrorKind.remote,
result ?? 'The AI server reported a failed run.',
transportId: transportId,
),
);
}
},
onError: (Object error, StackTrace stack) {
if (controller.isClosed) return;
controller.addError(_translate(error), stack);
},
onDone: () {
if (!controller.isClosed) unawaited(controller.close());
},
);
};
// Cancelling the underlying query is what sends `agentSdk.cancelVce`. The
// controller is not closed here: it is already being torn down by the very
// cancel we are servicing.
controller.onCancel = () async {
final sub = subscription;
subscription = null;
await sub?.cancel();
};
return controller.stream;
}