Providers & API Client
Canonical reference for Tuse's provider configuration, secret handling, four API protocol adapters (openai-chat, openai-responses, anthropic-messages, google-gemini), model discovery, streaming, reasoning replay, usage accounting, errors, and retries.
For model metadata (models in Lua config), selection UX, and session scoping, see models.md; for cost calculation, display, and 50/25/25 context compaction, see usage.md; for Lua config keys, see config.md; for using existing AI subscriptions via a local loopback proxy, see subs.md.
Storage, Snapshots, and Secrets
- Connected providers live in SQLite at
~/.tuse/tuse.db, each storingname,base_url,api_key, andapi(default'openai-chat'). - On opening an older database lacking the
apicolumn, Tuse automatically migratesproviderswithALTER TABLE providers ADD COLUMN api TEXT NOT NULL DEFAULT 'openai-chat'. Missing or emptyapivalues are treated asopenai-chat. api_keymay be an environment variable reference ($VARor${VAR}, whereVARconsists of ASCII letters, digits, and_) or a literal string.- Tuse loads providers from SQLite into the session's config snapshot when a session opens and re-reads them on reload (
/reload,reload(),config.reload), resolving$VAR/${VAR}against the current process environment each time. - A running session checks provider availability and credentials against its loaded snapshot, not live SQLite queries. Adding or removing a provider via
tuse connectortuse disconnectin another terminal takes effect in an already-open session only after reload or reopening. - If a referenced environment variable is unset at runtime, it resolves to an empty string and requests are sent with an empty credential header until the variable is set and reloaded or the provider is updated.
- Provider secrets are never exposed by
/config,config.get,/session,session.snapshot,tuse providers,tuse providers --json, orrequire("tuse").session().
Managing Providers
Manage providers with the CLI:
tuse connect --base https://api.openai.com/v1 --key '$OPENAI_API_KEY' --name openai
tuse connect --base https://api.openai.com/v1 --key '$OPENAI_API_KEY' --name openai-resp --api openai-responses
tuse connect --base https://api.anthropic.com/v1 --key '$ANTHROPIC_API_KEY' --name anthropic --api anthropic-messages
tuse connect --base https://generativelanguage.googleapis.com/v1beta --key '$GEMINI_API_KEY' --name gemini --api google-gemini
tuse providers
tuse providers --json
tuse disconnect openai
tuse connect
tuse connect --base URL (--key '$ENV' | --key-stdin) --name NAME [--api TYPE] [--replace]
--base,--name, and either--keyor--key-stdin(not both) are required for all four API types (no hidden default hostnames).--key-stdinreads the API key from stdin (trailing\r/\ntrimmed) so secrets do not appear in argv.--replaceverifies the endpoint first and, only if verification succeeds, atomically updates an existing provider row (a failed verification leaves the previous row intact).--apiis optional and defaults toopenai-chat. Valid values are:openai-chat— OpenAI-compatible Chat Completionsopenai-responses— OpenAI Responses APIanthropic-messages— Anthropic Messages APIgoogle-gemini— Native Google Gemini REST API
- An invalid
--apivalue fails immediately before any network call with an error listing all four supported values. - API type is a provider-level setting. To use two protocols against the same host (for example, Chat Completions and Responses), connect two named providers.
--basemust start withhttp://orhttps://. Trailing/characters are stripped before building endpoint URLs.--namecannot contain/or whitespace, and must not already exist; to replace a provider, remove it withtuse disconnect NAMEfirst.- Quote
'$ENV'in your shell so the variable reference is stored in SQLite rather than the expanded secret.tuse connectresolves--keyimmediately and fails before making any network request if the referenced variable is unset or empty. - Before saving, Tuse verifies the connection using the selected adapter's model-listing endpoint (single non-retried flow, 30 s connect / 600 s read timeout).
- On HTTP, network, or JSON parse failure, nothing is saved and the error is printed as
can't fetch models from <base_url>: <error>. - Any HTTP 200 response containing valid JSON succeeds and saves the provider, even if it yields
0usable model IDs; this check verifies model listing rather than generation.
- On HTTP, network, or JSON parse failure, nothing is saved and the error is printed as
- On success, Tuse prints
Received <N> models. Saved \<NAME>`.`
tuse providers and tuse disconnect
tuse providersprints all saved providers in insertion order, one per line as<NAME><tab><BASE_URL>(strictly two columns for backward compatibility; keys are never printed).tuse providers --jsonprints a JSON array[{"name": "...", "base_url": "...", "api": "..."}](never exposingapi_key).tuse disconnect NAMEdeletes the provider from SQLite and printsRemoved \<NAME>`, or fails withno provider `<NAME>`` if it does not exist.
Capability Matrix
Users can switch freely between models backed by different API types within the same session and across /resume, because stored session history is translated per request by the active provider's adapter.
| Capability | openai-chat |
openai-responses |
anthropic-messages |
google-gemini |
|---|---|---|---|---|
Streaming text (text deltas) |
Yes | Yes | Yes | Yes |
Streaming reasoning (reasoning deltas) |
Yes (reasoning_content / reasoning) |
Yes (reasoning summary / reasoning deltas) | Yes (thinking_delta) |
Yes (thought: true text parts) |
| Multi-step reasoning + tool loop replay | Plain text + tool_calls |
Ordered reasoning (encrypted_content) + function_call items |
Unmodified thinking / redacted_thinking + signature + tool_use blocks |
Ordered parts preserving part-level thoughtSignature |
Tool calling (lua) |
Yes | Yes | Yes | Yes |
Incremental tool_delta code streaming |
Yes (chunked JSON args) | Yes (chunked JSON args) | Yes (input_json_delta) |
Single shot per call (emitted once when complete functionCall arrives) |
Vision / images (user & tool read()) |
Yes (image_url data URLs) |
Yes (input_image data URLs) |
Yes (base64 image blocks, including inside tool_result) |
Yes (inlineData base64 parts) |
| Reasoning effort levels | default, low, medium, high, xhigh, max |
default, low, medium, high, xhigh (max unsupported) |
default, low, medium, high, max (xhigh unsupported) |
default, low, medium, high (xhigh, max unsupported) |
Prompt cache read tokens (cached) |
Yes | Yes | Yes | Yes |
Prompt cache write tokens (cache_write) |
Yes | No (reports 0) |
Yes | No (reports 0) |
Model listing (GET /models) |
Yes (data[].id, single page) |
Yes (data[].id, single page) |
Yes (data[].id, paginated up to 10 pages × 100) |
Yes (models[].name, models/ stripped, paginated up to 10 pages × 100) |
| Non-streaming JSON fallback | Yes | Yes | Yes | Yes |
Single-shot llm() |
Yes | Yes | Yes | Yes |
Model Naming and Background Discovery
Models are addressed as <provider>/<model_id> (split on the first /, sending everything after the first / verbatim as model). For model metadata, selection, and session isolation, see models.md.
- Opening
/modelsor callingmodel.list(unlesscached: true) returns immediately without waiting for network I/O and starts one background model-listing request per connected provider in the session's loaded snapshot (no retries). - Each successful response caches
<provider>/<id>in memory until the next reload and emits amodelsevent; a failure emits anerrorevent (<provider>: can't fetch models: <error>). - Reloading clears cached remote models and increments the session's config generation so stale in-flight fetch responses and errors from before the reload are silently discarded.
- Running a turn against a missing provider fails with
no \connect` entry named `<provider>` for model `<model>`;llm()fails withllm: no provider `<provider>` for model `<model>``.
Shared Request Building, Compaction & Reasoning Replay
Both agent turns and Lua llm(prompt, model, effort) build a protocol-agnostic request (provider, model, system, messages, tools, effort) and hand it to the provider's adapter. All adapters share the same HTTP timeouts (30 s connect, 600 s read), retry schedule, cooperative cancellation, and TUI / tuse json event stream (text, reasoning, tool_delta, stream_reset, assistant, tool_start, tool_end, usage, models, flash, error, turn_end).
Conversation Bounds and Message Construction
- Agent turns:
system: built-in system prompt plus configuredsystems(and compaction note whendrop > 0).- Conversation records follow 50/25/25 compaction bounds (see usage.md):
- Dropped prefix (
index < drop): only user text, task notifications, and non-empty assistant text are sent; hidden context, images, tool calls/results, andreplaymetadata are omitted (dropalways aligns on auser/notificationboundary so an active tool loop is never split). - Pruned middle (
drop <= index < prune): full user/assistant/tool messages andreplaymetadata are retained, except tool outputs are shortened to their first line (capped at 200 characters) plus\n[tool output pruned]and tool-returned images are omitted. - Recent suffix (
index >= prune): full messages,replaymetadata, and images are sent.
- Dropped prefix (
- User messages with hidden context (
#prompts,@files/dirs, image tags) append the context after\n\n. - Every assistant tool call is paired with a matching tool result (interrupted or crashed turns receive placeholder
[interrupted: no output]tool results before the next request). - Token estimation for compaction counts human-readable text, tool calls/results, and images while ignoring opaque encrypted/signature blobs inside
replayso opaque signatures do not cause premature compaction.
- Lua
llm(prompt, model, effort):- Sends a single user message containing
promptwith emptysystem, no session history, and notools.
- Sends a single user message containing
Reasoning Replay Metadata and Cross-Provider Fallback
Modern reasoning APIs require unmodified reasoning artifacts to be echoed back in exact order across multi-step tool loops and across /resume:
- HTTP timeouts & redirects: 30 seconds connect timeout, 600 seconds read timeout. HTTP redirects (
3xx) are never followed on provider requests so credentials (Authorization,x-api-key,x-goog-api-key) cannot leak across hosts. - Persisted
assistantrecords carry an optionalreplayobject (omitted when absent/empty):{ "provider": "<provider name>", "api": "anthropic-messages | openai-responses | google-gemini", "model": "<raw model id>", "items": [ ... ] } - Same-provider, same-API, and same-model replay: when an assistant step's
replay.provider,replay.api, andreplay.modelall match the active request (and the record is outside the dropped prefix), the adapter replaysreplay.itemsverbatim instead of reconstructing plain text + tool calls. - Cross-provider / cross-model fallback: foreign
replay.itemsare never sent to a differentprovider,api, ormodel. Adapters fall back cleanly to plaintext+ tool calls:- On
anthropic-messages, prior completed turns serialize as plaintext+tool_use; if an unfinished tool loop (an assistant step with tool calls after the latest user message, such as after a crash/resume or mid-loop provider switch) lacks valid Anthropicthinking/redacted_thinkingreplay blocks for the active provider/model, Tuse omitsthinkingandoutput_configon that recovery request rather than failing with HTTP 400. - On
google-gemini, reconstructed unsignedfunctionCallparts in the active turn attach Gemini's documented"thoughtSignature": "skip_thought_signature_validator"migration sentinel so mid-loop switches to Gemini 3 succeed cleanly; and when a replayed wirefunctionCallcarried noid, Tuse keeps its synthetic local ID (call_<index>) internal and omitsidon the corresponding wirefunctionResponse.
- On
Per-Adapter Protocol Contracts
1. openai-chat
- Endpoints:
POST <base_url>/chat/completions,GET <base_url>/models(single page,data[].id). - Headers:
Authorization: Bearer <resolved_key>,Content-Type: application/json. - Request:
model,stream: true,stream_options: {"include_usage": true}.messages: starts with{"role": "system", "content": system}whensystemis non-empty; user messages with images use{"type": "text", ...}and{"type": "image_url", "image_url": {"url": ...}}; assistant messages includecontentand optionaltool_calls; tool results userole: "tool",tool_call_id,content, and any tool-returned images are flushed after their tool results as arole: "user"message containing[Images from the tool results above],[Image: <input>], andimage_urlparts.tools: omitted when empty; otherwise[{"type": "function", "function": {"name", "description", "parameters"}}].reasoning_effort: omitted when effort is"default"; otherwise set to"low","medium","high","xhigh", or"max".
- Streaming SSE & non-streaming fallback:
- SSE (
Content-Typecontainsevent-stream): readsdata:lines untildata: [DONE]; premature EOF beforedata: [DONE]fails as a retryable transport error so partial replies or tool calls are never executed or persisted. OtherContent-Typeparses the body as a single JSON object. - Non-null top-level
errorfails withHTTP <error.code or 500>. usageupdates reply usage;choices[0]providesfinish_reason,delta(falling back tomessage),reasoning_contentandreasoningdeltas,contentdeltas, andtool_callsaccumulated by slot (index, else non-emptyidopens a slot, else last slot) with incremental"code"JSON extraction emittingtool_deltaforlua.- On finish, drops calls with empty
nameand assignscall_<index>for emptyid.
- SSE (
- Usage:
input <- prompt_tokens,output <- completion_tokens,cached <- prompt_tokens_details.cached_tokens,cache_write <- max(prompt_tokens_details.cache_write_tokens, prompt_tokens_details.cached_creation_tokens).
2. openai-responses
- Endpoints:
POST <base_url>/responses,GET <base_url>/models(single page,data[].id). - Headers:
Authorization: Bearer <resolved_key>,Content-Type: application/json. - Request:
model,stream: true,store: false(keeping local SQLite history and compaction authoritative).instructions: system prompt when non-empty.input: ordered array of items:- User message ->
{"role": "user", "content": [...]}with{"type": "input_text", "text": ...}and{"type": "input_image", "image_url": "data:..."}. - Assistant step -> verbatim matching
replay.itemswhen available; otherwise{"role": "assistant", "content": [{"type": "output_text", "text": ...}]}(when text is non-empty) followed by{"type": "function_call", "call_id": id, "name": name, "arguments": arguments}per tool call. - Tool results ->
{"type": "function_call_output", "call_id": id, "output": output}per result; if tool images exist, flushes a follow-uprole: "user"item with[Images from the tool results above]andinput_imageparts.
- User message ->
tools: omitted when empty; otherwise[{"type": "function", "name", "description", "parameters"}].reasoningandinclude: omitted when effort is"default"; forlow,medium,high,xhigh, sendsreasoning: {"effort": "<effort>", "summary": "auto"}andinclude: ["reasoning.encrypted_content"]. Rejectsmaxfail-fast.
- Streaming SSE:
response.output_text.delta->textdelta.response.reasoning_summary_text.deltaandresponse.reasoning_text.delta->reasoningdelta.- Tool-call slot correlation:
response.output_item.added(item.type == "function_call"): creates/selects slot byoutput_indexanditem.id, capturescall_id(falling back toitem.id) andname, and feeds any initial non-emptyitem.argumentsto the incremental"code"extractor.response.function_call_arguments.delta: matches slot byitem_id(falling back tooutput_index), appendsdelta, and streams"code"viatool_delta.response.function_call_arguments.doneandresponse.output_item.done(function_call): backfills missingcall_id/name; a non-emptyargumentsstring ondoneis authoritative for the stored call (feeding the"code"extractor once only if no arguments were streamed earlier, avoiding duplicatetool_deltacharacters).
- Replay capture:
response.output_item.donerecords completedreasoning(only whenencrypted_contentis present and non-empty),message, andfunction_callitems inoutput_indexorder intoreplay.items. response.completed/response.incomplete-> recordsfinish(response.status) andresponse.usage. Premature EOF beforeresponse.completed/response.incompletefails as a retryable transport error.response.failed/ top-levelerror-> mapsrate_limit_exceeded(429),server_error(500),service_unavailable(503), and numeric429/>= 500to retryable status errors; maps client/validation codes (invalid_request_error,context_length_exceeded,invalid_api_key, etc.) to non-retryable400/401.
- Non-SSE JSON fallback:
- Fails on non-null
errororstatus == "failed"with the same retryability mapping; recordsfinish = statusandusage; walksoutput[]in order, emittingreasoning(summary[].text),message(output_text), andfunction_call(single-shottool_delta) while capturingreplay.items(includingreasoningonly whenencrypted_contentis present).
- Fails on non-null
- Usage:
input <- input_tokens,output <- output_tokens,cached <- input_tokens_details.cached_tokens,cache_write <- 0.
3. anthropic-messages
- Endpoints:
POST <base_url>/messagesGET <base_url>/models?limit=100: follows&after_id=<last_id>whilehas_more == true,last_idis non-empty, andlast_idhas not been seen, capped at 10 pages (up to 1,000 models); readsdata[].id.
- Headers:
x-api-key: <resolved_key>,anthropic-version: 2023-06-01,Content-Type: application/json. - Request:
model,stream: true,max_tokens: 16384.system: when non-empty, sent as[{"type": "text", "text": system, "cache_control": {"type": "ephemeral"}}].messages: strictly alternatinguserandassistantroles with consecutive same-role items merged into onecontentblock array, attachingcache_control: {"type": "ephemeral"}to the last block of the latestusermessage:- User text ->
{"type": "text", "text": ...}; user images ->{"type": "image", "source": {"type": "base64", "media_type": mime, "data": b64}}. - Assistant step -> verbatim matching
replay.items(thinking,redacted_thinking,text,tool_use) when available; otherwise non-emptytextblocks and{"type": "tool_use", "id", "name", "input": <parsed JSON object, fallback {}>}. - Tool results ->
role: "user"blocks{"type": "tool_result", "tool_use_id": id, "content": [...]}carrying the text output and any tool-returned base64 image blocks insidetool_result.content.
- User text ->
tools: omitted when empty; otherwise[{"name", "description", "input_schema"}].- Effort / thinking: omitted when effort is
"default"(or during unfinished-loop recovery without valid Anthropic thinking replay); forlow,medium,high,max, sendsthinking: {"type": "adaptive"}andoutput_config: {"effort": "<effort>"}. Rejectsxhighfail-fast.
- Streaming SSE:
message_start-> initializes usage counters frommessage.usage.content_block_start-> trackstext,thinking,redacted_thinking(no UI delta), andtool_useblocks byindex.content_block_delta->text_delta(text),thinking_delta(reasoning),signature_delta(appendssignatureto activethinkingblock, no UI delta),input_json_delta(partial_json-> tool arguments + incremental"code"extractor ->tool_delta).content_block_stop-> finalizes block atindexinto orderedreplay.items.message_delta-> updatesstop_reasonand final usage fields without clobbering earlier input/cache counters.pingignored;message_stopends stream. Premature EOF beforemessage_stop(or with unclosed blocks) fails as a retryable transport error.errorevent -> mapsrate_limit_error(429),overloaded_error(529),api_error(500) to retryable status errors;invalid_request_error(400),authentication_error(401),permission_error(403) to non-retryable status errors.
- Non-SSE JSON fallback:
- Fails on
type == "error"or non-nullerror; recordsfinish = stop_reasonand normalized usage; walkscontent[]in order emittingthinking,text, andtool_use(single-shottool_delta) while preservingthinking,redacted_thinking,text, andtool_useinreplay.items.
- Fails on
- Usage normalization:
cached <- cache_read_input_tokenscache_write <- cache_creation_input_tokensinput <- input_tokens + cached + cache_write(total prompt tokens, matching Tuse'sctx = input + outputandplain = input - cached - cache_write)output <- output_tokens
4. google-gemini
- Endpoints:
POST <base_url>/models/<model_id>:streamGenerateContent?alt=sseGET <base_url>/models?pageSize=100: follows&pageToken=<nextPageToken>whilenextPageTokenis non-empty and unseen, capped at 10 pages (up to 1,000 models); strips leadingmodels/frommodels[].nameand skips entries whosesupportedGenerationMethodsis present and excludesgenerateContent.
- Headers:
x-goog-api-key: <resolved_key>,Content-Type: application/json(the API key is never placed in URL query parameters). - Request:
systemInstruction:{"parts": [{"text": system}]}when non-empty.contents: array of{"role": "user" | "model", "parts": [...]}with consecutive same-role turns merged:- User text ->
{"text": ...}; user images ->{"inlineData": {"mimeType": mime, "data": b64}}. - Assistant step (
role: "model") -> verbatim matchingreplay.itemsparts (preservingthought,text,functionCall, and part-levelthoughtSignature) when available; otherwise{"text": ...}and{"functionCall": {"id", "name", "args": <parsed JSON object, fallback {}>}}. - Tool results ->
role: "user"parts{"functionResponse": {"id", "name", "response": {"output": output}}}plusinlineDataparts for tool-returned images.
- User text ->
tools: omitted when empty; otherwise[{"functionDeclarations": [{"name", "description", "parameters"}]}].- Effort / thinking:
"default"omitsthinkingConfig.low,medium,high: forgemini-2.5-*models sendsgenerationConfig.thinkingConfig = {"includeThoughts": true, "thinkingBudget": 1024 | 8192 | 24576}; for Gemini 3+ and other Gemini models sendsgenerationConfig.thinkingConfig = {"includeThoughts": true, "thinkingLevel": "<effort>"}.- Rejects
xhighandmaxfail-fast.
- Streaming SSE & non-streaming JSON fallback:
- Processes each SSE
data:JSON chunk (or, for non-SSE responses, a single JSON object or JSON array of chunks):- Preserves received part objects into ordered
replay.items, merging contiguous plain/thought text chunks only when neither part carriesthoughtSignature(never dropping or moving athoughtSignatureacross parts). thought == truetext ->reasoningdelta; plain text ->textdelta.functionCall({id?, name, args}) -> serializesargsto JSON, assignscall_<index>whenidis absent, and emitstool_deltaonce forlua.
- Preserves received part objects into ordered
candidates[0].finishReason->finish. Premature SSE EOF before receiving afinishReasonfails as a retryable transport error.- Non-null top-level
error->HTTP <error.code or 500>.
- Processes each SSE
- Usage:
input <- usageMetadata.promptTokenCountcached <- usageMetadata.cachedContentTokenCountcache_write <- 0output <- usageMetadata.candidatesTokenCount + usageMetadata.thoughtsTokenCount
Unsupported Capability Reporting
Unsupported capabilities are handled in two ways:
- Known adapter incompatibility (fail fast, non-retryable, zero HTTP requests):
- Unsupported effort level for the provider's API type (for example
maxonopenai-responses,xhighonanthropic-messages, orxhigh/maxongoogle-gemini). - Non-base64 image attachment (anything not matching
data:<mime>;base64,<data>) on an adapter requiring inline base64 (anthropic-messages,google-gemini). - Error format:
provider \<name>` (<api_type>) does not support <capability> `<value>` (<hint>)`. - Never retried. On an agent turn, saves an
errorrecord and emitserror(followed byturn_endwhen the queue is empty) in both TUI andtuse json. Inllm(), raises a Lua errorllm: ....
- Unsupported effort level for the provider's API type (for example
- Graceful protocol differences (no error):
- Missing
cache_writereporting (openai-responses,google-gemini) reports0. - Non-incremental tool arguments (
google-gemini) emit a singletool_deltawith the fullcodebeforetool_start. - Upstream model-specific rejections (such as a non-thinking model rejecting
thinkingConfig) surface verbatim as non-retryableHTTP 4xx: ...errors.
- Missing
Cancellation Behavior
- HTTP cancellation is cooperative, not an immediate socket abort:
- In SSE streams, cancellation is checked as each line arrives from the stream.
- During retry backoff sleeps, cancellation is checked every 100 ms.
- The non-streaming JSON fallback has no mid-read cancellation check.
- On turn cancellation (Esc or
turn.cancel), the session immediately invalidates the turn's generation and emitsturn_end(cancelled: true), ignoring any subsequent output from the unwinding HTTP thread. - For
llm(), cancellation is bound to the calling Lua job: cancelling a turn cancels anllm()call inside an agentluatool call, whereas cancelling a turn does not cancel anllm()call running inside a background task (which is cancelled only bytask_stop()or session close).
Usage Accounting
- On an agent turn step, if the reply includes
usage, Tuse updates the session context size (ctx) toinput + outputand appends a usage record;usageevents are emitted at the end of every completed assistant step. - On
llm(), Tuse appends a separate usage record (llm: true, without changingctx) and emits ausageevent only when the reply includes ausageobject. - See usage.md for pricing formulas, display, and compaction.
Errors and Retries
Errors fall into five categories:
| Category | Formatted message | Retried? |
|---|---|---|
HTTP error status / inline stream error |
HTTP <code>: <body on one line, max 300 chars + …> |
Yes for 429 and >= 500; No for other 4xx |
| Network / I/O failure | network: <message> |
Yes |
| Malformed JSON response | bad response: <message> |
No |
| Unsupported adapter capability | provider \<name>` (<api>) does not support ...` |
No |
| Cancellation | cancelled |
No |
- Retry policy: configured by
settings.retries(0..=100, default5). Backoff delays are fixed at[2, 5, 10, 20, 30]seconds. The effective retry limit ismin(settings.retries, 5)(at most 5 retries / 6 total attempts;0disables retries). Only completion requests (complete) retry; model-listing requests never retry. - Agent turn retries: before each retry sleep, Tuse emits
stream_reset(discarding partial streamed text, reasoning, and pending tool call entries from the failed attempt) and aflashevent formatted asRetry <attempt>/<max> in <delay>s: <error>. llm()retries: uses the same retry schedule and cancellation handling silently (nostream_resetorflashevents).- Terminal failure:
- On an agent turn step, when retries are exhausted or a non-retryable error occurs, Tuse saves an
errorrecord, emitserror, and ends the failed step. If no further input is queued, the turn finishes and emitsturn_end; if another user message or task notification is already queued, the turn continues with the queued input. - A cancelled turn step stops without recording an API error.
- In
llm(), terminal failure or cancellation raises a Lua error prefixed withllm:.
- On an agent turn step, when retries are exhausted or a non-retryable error occurs, Tuse saves an