detach method

Future<DetachedTask<State>> detach({
  1. String? text,
  2. Message? message,
  3. List<ToolResponsePart>? respond,
  4. List<ToolRequestPart>? restart,
  5. Map<String, dynamic>? context,
})

Submits a detached (background) turn. Requires a store.

Pass either text (free-form user text) or a fully-built message (at most one). To resume an interrupted turn in the background, pass respond entries (built via AgentInterrupt.respond) and/or restart entries (built via AgentInterrupt.restart); they are bundled into an AgentResume internally.

context is the ambient request context to run the turn under. It is only honored by the in-process transport (observable as AgentFnOptions.context); the remote transport rejects a non-empty context with an UnsupportedError (see AgentTransport).

Pass context explicitly when using a context-scoped session store. The returned DetachedTask retains it for polling and abort after the originating action has completed. Do not mutate the context map while the detached task is active.

Implementation

Future<DetachedTask<State>> detach({
  String? text,
  Message? message,
  List<ToolResponsePart>? respond,
  List<ToolRequestPart>? restart,
  Map<String, dynamic>? context,
}) async {
  final agentInput = _buildAgentInput(
    text: text,
    message: message,
    respond: respond,
    restart: restart,
    detach: true,
  );
  final inputMessage = agentInput.message;
  if (inputMessage != null) {
    messages.add(inputMessage);
  }
  final init = _buildInit();

  final controller = CancellationController();
  final turn = _transport.runTurn(
    agentInput,
    init,
    cancel: controller.token,
    context: context,
  );
  final raw = await turn.output;
  _applyOutput(raw);
  final id = raw.snapshotId;
  if (id == null) {
    throw StateError('detach did not return a snapshotId.');
  }
  return DetachedTask<State>._(id, _transport, _stateSchema, context);
}