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 loop = request.agentLoop;
final query = _agent.query(
prompt: request.prompt,
options: loop == null
? Options(
model: request.model,
systemPrompt: request.systemPrompt == null
? null
: SystemPromptText(request.systemPrompt!),
// The SDK's own tools are off: 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,
resume: request.resume,
includePartialMessages: true,
thinking: const ThinkingAdaptive(display: 'summarized'),
)
// Claude Code's own loop: its tools and MCP servers, its turns,
// its permission posture. Its system prompt is kept unless the
// request names one (and then replaced by it).
: Options(
model: request.model,
systemPrompt: request.systemPrompt == null
? null
: SystemPromptText(request.systemPrompt!),
mcpServers: tools == null ? null : _toolOptions(tools, alive),
maxTurns: loop.maxTurns,
permissionMode: PermissionMode.fromWire(loop.permissionMode),
resume: request.resume,
includePartialMessages: true,
thinking: const ThinkingAdaptive(display: 'summarized'),
),
);
// `includePartialMessages` is what makes the provider's gap bound a
// *gap* bound rather than a disguised budget on model latency. Without
// it 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. The partial events are reported as liveness
// and otherwise ignored: text is emitted from the assembled
// `SdkAssistantMessage` alone, so nothing is delivered twice. The
// thinking is asked for because the trail shows it: adaptive, so the
// model decides how much a request needs, and summarized, so what
// reaches the trail is readable.
String? conversation;
// 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;
}
final id = message.raw['session_id'];
if (id is String && id.isNotEmpty && id != conversation) {
conversation = id;
controller.add(AgentSdkConversation(id));
}
translator.translate(message).forEach(controller.add);
if (message case SdkResultMessage(isError: true, :final result)) {
controller.addError(
LlmTransportException(
LlmErrorKind.remote,
result ??
_resultErrors(message.raw) ??
'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;
}