Docs
Agent

Agent Turn Lifecycle

Documents how an agent turn progresses through its full lifecycle: submission phases, billing pre-authorization, file upload, streaming, and completion or cancellation.

An agent turn is a single round of user input processed by the MarkDocket AI agent. From the moment you send a message to when the assistant's response is complete, the turn passes through a well-defined sequence of states with atomic, database-persisted transitions. Understanding this lifecycle helps you build reliable integrations, handle errors by phase, and reason about billing behavior.

Turn State Machine

Every agent turn has one of the following states at any point in time:

StateDescription
authorizingThe turn has been submitted; a billing reservation is being created.
authorizedBilling reservation confirmed; the turn is ready to accept file uploads and the user message.
uploadingAttached files are being uploaded and bound to the turn.
runningThe user message has been committed; the agent loop is streaming a response.
completedThe agent response finished successfully.
deniedBilling authorization failed; no charges were incurred.
failedAn error occurred after authorization; the turn did not complete normally.
expiredThe turn was never fully submitted within the allowed window; the reservation has been released.
cancelledThe turn was explicitly cancelled before or during streaming.

Transitions between states use compare-and-swap (CAS) operations so that only one actor can advance a turn at a time. Attempting an invalid transition (for example, trying to upload files on an already running turn) is rejected.

State Transition Diagram

authorizing

    ├─ billing denied ──────────────────────► denied


authorized

    ├─ files attached? ─► uploading
    │                         │
    │                         ▼
    └──────────────────► running

                 ┌───────────┼───────────┐
                 ▼           ▼           ▼
            completed     failed     cancelled

(any state before running) ──► expired  (background sweep)

Submission Phases

When you submit a message, the client coordinates four phases in order. A stable set of identifiers (turn ID and idempotency key) is generated once at the point of submission and reused on any retry, making the full submission idempotent.

Phase 1 — Billing Pre-Authorization (authorizingauthorized or denied)

Before any content is accepted, the platform atomically reserves billing capacity for the turn. This reservation is created together with the authorizingauthorized state transition in a single operation.

  • If your account has sufficient balance or credit, the transition to authorized succeeds and the reservation is held.
  • If the reservation cannot be created — for example, because a spending limit would be exceeded — the turn transitions to denied and no further phases run. No charge is incurred.

Billing reservation comes first

File uploads and message commits are only accepted after the billing reservation succeeds. A denied turn is always charge-free.

If billing authorization fails, you receive a structured billing block response describing the reason and the action required (for example, adding a payment method or increasing a spending limit). This response is the same structured type used across the entire platform — it appears as an SSE event during streaming and as an HTTP error body when submitting synchronously.

Phase 2 — File Upload (authorizeduploading)

If your message includes attachments, each file is uploaded during this phase and bound to the turn before the message is committed.

Idempotent upload IDs. Each file's upload ID is derived deterministically from the turn ID and the idempotency key. Submitting the same file under the same idempotency key always resolves to the same upload record without an extra round-trip. This means retrying a failed upload is safe and produces no duplicates.

Uploads are validated against the active billing reservation and bound to the turn message in a single transaction. An upload that cannot be bound — for example, because the turn has already moved past uploading — is rejected.

Phase 3 — Message Commit and Streaming (uploading / authorizedrunning)

Once any uploads are complete, the user message is committed and the turn advances to running. The agent loop begins and responses are delivered as a server-sent event (SSE) stream.

The stream carries several event types:

  • Text chunks — incremental assistant response text.
  • Tool call and tool result events — the agent's tool invocations and their outcomes as the loop progresses.
  • Vault file events — references to any files the agent produces or attaches.
  • billing_required events — if a mid-stream action requires additional billing authorization, a billing block event is emitted inline. The client intercepts these events before they reach individual call sites and surfaces a prompt to the user.

Billing blocks can occur mid-stream

A turn that reaches running may still encounter a billing block if a tool invocation requires additional resources beyond the initial reservation. The stream will emit a billing_required event before stopping.

Phase 4 — Completion or Cancellation (runningcompleted / cancelled / failed)

The turn completes when the agent loop finishes and the stream closes normally (completed). If an unrecoverable error occurs after authorization, the turn moves to failed. If you cancel explicitly — via a cancel action in the UI or a cancellation API call — the turn moves to cancelled.

On any error during phases 1–3, the client calls the turn cancellation endpoint before surfacing the error. The error carries a phase field so your application can present phase-appropriate messaging.

Expired Turns and Reservation Cleanup

Turns that are created but never fully submitted (for example, due to a network failure before the message commit) are cleaned up by a background sweep. The sweep:

  • Releases the billing reservation so the held capacity is returned to your account.
  • Removes any orphaned uploaded files associated with the turn.
  • Transitions the turn to expired.

Expired turns are not retried. To resubmit, start a new turn. Because the submission is built on stable idempotency keys generated at the point of user intent, you can safely resubmit without risk of duplicate charges or duplicate uploads.

Error Handling by Phase

Errors during submission carry a phase field identifying where the failure occurred, along with the turn ID and whether billing authorization had already succeeded at the time of failure.

PhaseBilling incurred?Recommended action
authorizingNoSurface the billing block reason; prompt to resolve account status.
uploadingReservation heldRetry the upload with the same idempotency key; cancel turn if retries exhausted.
runningReservation heldSurface the error; the turn is cancelled automatically before the error is returned.

Agent Trust and Tool Execution

While a turn is running, the agent executes tools by calling back to the MarkDocket API using a delegated token scoped to your user identity. The agent worker itself holds no direct access to external services — all tool calls are proxied through the API, which re-dispatches to the appropriate service. This means:

  • Every tool call made during your turn is executed under your account permissions.
  • Tool results are audited as part of the turn record.
  • The agent's access is bounded by what your account is authorized to do.

Automation Agent Nodes

When an agent runs inside an automation workflow rather than interactive chat, the same state machine applies to each agent node's turn, but with some differences:

  • Each automation agent node mints a fresh delegated token for its execution.
  • Billing blocks inside an automation run surface as a structured signal that suspends the run cleanly, rather than terminating it as a failure. You can resolve the billing issue and resume the run.
  • BYOK (Bring Your Own Key) AI provider configurations are only available to automation agent nodes, not to interactive chat turns.

See the Automations documentation for details on run-level state and billing block handling in workflows.

Summary of Key Properties

  • Pre-authorization is mandatory. No file upload or message commit is accepted until billing is confirmed.
  • Idempotent by design. The same turn ID and idempotency key can be safely retried across all phases without duplicate charges or duplicate uploads.
  • Billing blocks are first-class. Whether in streaming chat or automation, billing enforcement surfaces as a structured, actionable response — not a generic error.
  • Automatic cleanup. Expired and abandoned turns are swept up by a background process that releases reservations and removes uploaded files.
  • Phase-aware errors. Submission errors identify the phase of failure and whether billing was already authorized, enabling targeted recovery logic.

On this page