# Errors and recovery

Handle errors, reconnect safely, and check deployment capabilities without duplicating work.

## Persist the business request identity

Store a stable idempotency key with your application operation before sending work. If admission times out, retry the same session, body, and key. The service returns the originally admitted run or reports a conflict if the body differs.

### Python

```python
run = await session.send(
    persisted_message,
    idempotency_key=persisted_request_id,
    subject={"id": authenticated_user_id},
)
```

### TypeScript

```typescript
const run = await session.send(persistedMessage, {
  idempotencyKey: persistedRequestId,
  subject: { id: authenticatedUserId },
})
```

SDK transport and admission errors preserve the idempotency key. Creating a new key after an uncertain response can create duplicate business work. Ordinary non-idempotent resource creation is not blindly retried.

## Prefer the high-level stream

The SDK `run.stream()` and React `useSession()` hydrate a snapshot and recover a sequence gap automatically. A snapshot replaces the earlier view. A text update may represent replacement after recovery. Do not append an entire cumulative string as if it were a token delta.

For a durable event consumer, save the event and cursor in one application transaction:

### Python

```python
async with session.events(after=last_committed_cursor) as events:
    async for event in events:
        await persist_event_and_cursor(event)
```

### TypeScript

```typescript
for await (const event of session.events({ after: lastCommittedCursor })) {
  await persistEventAndCursor(event)
}
```

The event and cursor persistence function is your application transaction. The low-level SDK verifies sequence before run filtering. A gap raises `RecoveryRequired`. Obtain a new snapshot instead of continuing from incomplete state. Unknown future event types can advance the validated cursor without inventing domain records.

## Distinguish failures

| State | Appropriate action |
| --- | --- |
| Network disconnect | Resume observation. Do not send the prompt again |
| Uncertain admission | Retry the original body and idempotency key |
| Input required | Show the exact pending interaction |
| Session configuration changed | Create a new session under the current assignment |
| Failed or interrupted run | Inspect the durable result and business side effects |
| Uncertain backend operation | Reconcile using your business receipt. Do not assume failure means no side effect |
| Unknown usage | Keep the reservation until audited reconciliation |

The current service has one active execution coordinator per database, guarded by a database lease and fencing. A restart recovers uncertain state without automatically resubmitting already dispatched prompts. Horizontal execution workers and stateful native session forks are not included in this release.

Request timeouts, stream idle timeouts, observation timeouts, and execution deadlines are separate controls. A disconnected browser can coexist with a running agent.

## Errors and capabilities

HTTP errors use a stable envelope containing `code`, `message`, `request_id`, and optional `details`. SDK errors distinguish authorization, validation, conflict, transport failure, protocol failure, required input, and observation timeout. Preserve the request ID in operational reports. Do not log API keys or provider credentials.

### Python

```python
from wkala import APIError, TransportError, InputRequired, ObservationTimeout

try:
    run = await session.send(
        message,
        idempotency_key=persisted_request_id,
    )
    result = await run.wait(timeout=120)
except InputRequired as required:
    print("Present these interactions:", required.interactions)
except ObservationTimeout:
    print("The observer stopped waiting. The run may still be active.")
except TransportError as error:
    print("Admission may be uncertain:", error.idempotency_key)
except APIError as error:
    print(error.status_code, error.code, error.request_id)
```

### TypeScript

```typescript
import { APIError, TransportError, InputRequired, ObservationTimeout } from "@wkala/client"

try {
  const run = await session.send(message, {
    idempotencyKey: persistedRequestId,
  })
  const result = await run.wait({ timeout: 120 })
} catch (error) {
  if (error instanceof InputRequired) {
    console.log("Present these interactions:", error.interactions)
  } else if (error instanceof ObservationTimeout) {
    console.log("The observer stopped waiting. The run may still be active.")
  } else if (error instanceof TransportError) {
    console.log("Admission may be uncertain:", error.idempotencyKey)
  } else if (error instanceof APIError) {
    console.log(error.status, error.code, error.requestId)
  } else {
    throw error
  }
}
```

An execution failing is not the same as HTTP admission failing. Terminal run results remain inspectable. Check both execution status and stop reason: a completed turn can contain a refusal or reach a limit.

## Ask the deployment what is supported

### Python

```python
capabilities = await agents.capabilities.get()
print(capabilities.agent.streaming)
print(capabilities.agent.tool_events)
print(capabilities.agent.session_operations)
```

### TypeScript

```typescript
const capabilities = await agents.capabilities()
console.log(capabilities.agent.streaming)
console.log(capabilities.agent.tool_events)
console.log(capabilities.agent.session_operations)
```

The SDK has a stable API across deployments, but the existence of a method does not promise that every optional capability is enabled. Unsupported operations return `capability_unavailable`.

This release supports streamed execution, tools and results, application-owned MCP servers, instruction bundles, explicit permissions, questions, recovery snapshots, and usage. Host shell/file/network/delegation capabilities remain denied. Executable skill scripts, native file-artifact export, and stateful session forks are unavailable. Tool results may contain your application's authorized resource links. That does not turn arbitrary local files into hosted downloads.

A high-level abstraction should preserve these distinctions. Do not:

- Convert unknown cost to zero.
- Turn an unavailable artifact into a fake download.
- Treat a transcript copy as a fork.
- Treat a disconnect as a cancellation.
