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:
| State | Description |
|---|---|
authorizing | The turn has been submitted; a billing reservation is being created. |
authorized | Billing reservation confirmed; the turn is ready to accept file uploads and the user message. |
uploading | Attached files are being uploaded and bound to the turn. |
running | The user message has been committed; the agent loop is streaming a response. |
completed | The agent response finished successfully. |
denied | Billing authorization failed; no charges were incurred. |
failed | An error occurred after authorization; the turn did not complete normally. |
expired | The turn was never fully submitted within the allowed window; the reservation has been released. |
cancelled | The 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 (authorizing → authorized or denied)
Before any content is accepted, the platform atomically reserves billing capacity for the turn. This reservation is created together with the authorizing → authorized state transition in a single operation.
- If your account has sufficient balance or credit, the transition to
authorizedsucceeds and the reservation is held. - If the reservation cannot be created — for example, because a spending limit would be exceeded — the turn transitions to
deniedand no further phases run. No charge is incurred.
Billing reservation comes first
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 (authorized → uploading)
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 / authorized → running)
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_requiredevents — 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
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 (running → completed / 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.
| Phase | Billing incurred? | Recommended action |
|---|---|---|
authorizing | No | Surface the billing block reason; prompt to resolve account status. |
uploading | Reservation held | Retry the upload with the same idempotency key; cancel turn if retries exhausted. |
running | Reservation held | Surface 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.
AI Agent Overview
Introduction to the MarkDocket AI agent — what it does, how it fits into the platform, and the key concepts users need to know before using agent chat.
Agent SSE Event Reference
Reference documentation for all SSE event types streamed during an agent turn, covering text, tool_call, tool_result, vault_file, and billing_required events with field descriptions and usage guidance.