# UpServe Agent Runtime API: integration guide for coding agents

This file is written for a coding agent (Claude Code, Cursor, Codex, ChatGPT, or similar). A person pasted it, or asked you to download it, because they want an UpServe AI employee or workflow to run on UpServe's servers and be called from their own service. They may not know this API. You do the integration; they only decide what the agent should do and handle their key.

## Instructions for the coding agent

Follow these steps in order.

The console is the web page https://upserve.app/console (give the person this address; it is also under 「Console」 in the profile menu at the top right). The person uses it with their own sign-in: their personal space, or an organization they own.

A key needs the allowed operations (scopes) for what you call. When creating a key, the simplest choice is every operation except `actions:approve` and `works:approve` (those let the key decide approvals for people). The minimum sets are:

- Call an AI employee: `deployments:read`, `sessions:read`, `sessions:write`, `turns:read`, `turns:write`, `turns:cancel`, `events:read`, plus `files:write` for input files, `artifacts:read` for result files, `actions:resolve` to answer its questions, `usage:read` for cost.
- Run a workflow: `workflows:read`, `workflows:run`, `runs:read`, `runs:cancel`, `runs:delete`, `events:read`, plus the same file, question, and usage scopes as needed.

1. **Find out the goal.** If the person has not said what they want, ask one short question: what should the server agent do in their service (for example, "summarize each new support email", "fill this form from an uploaded PDF"). Do not ask about API details. You find those in this file.
2. **Look at their project first.** Use the language, framework, and folder layout the project already uses. The Python and TypeScript clients linked below are references, not required dependencies. If there is no project yet, pick the smallest server setup that fits the goal and say which one you picked.
3. **Keep the key out of the chat.** Create (or extend) a server side env file with an empty line `UPSERVE_API_KEY=` and make sure that file is git ignored. Ask the person to paste the key into that file themselves. Never ask them to paste the key into the conversation, and never print, log, or commit it. If they paste it into the chat anyway, tell them to rotate it on the Keys tab of the developer console after setup.
4. **Call the API only from server code.** Never from a browser, a mobile app, or front end code. The base URL is `https://api.upserve.app`; every path already starts with `/v1`.
5. **Discover IDs yourself.** Call `GET /v1/deployments` with the key to find the Deployments (published AI employees) this key may call, and pick the one that matches the goal. If there are several and the choice is unclear, show the names and ask. A workflow ID cannot be listed through the API: if the goal needs a workflow, ask the person to do three things on the developer console: publish the workflow for the API on the Publishing & access tab, add it to the key under Allowed workflows, and copy its ID (choose the workflow; the ID is under its name).
6. **Diagnose setup problems before writing more code.**
   - Every `/v1` path answers 404, including `GET /v1/deployments`: the Project was blocked by an operator, or it was revoked. Tell the person and stop. Do not keep retrying.
   - Deployments work but one workflow answers 404: the key does not allow that workflow, or it is not published for the API. Ask the person to fix both on the developer console.
   - `401 INVALID_API_KEY`: the key is missing, mistyped, revoked, or expired, or the person who created it is no longer an organization OWNER. Ask the person to check the env file, or to create a new key.
   - `GET /v1/deployments` returns an empty list: the key does not allow any Deployment. Ask the person to publish an AI employee on the Publishing & access tab of the developer console, then create a key with that Deployment selected under Allowed deployments.
   - `403 INSUFFICIENT_SCOPE`: the key lacks an allowed operation (scope) this call needs. Tell the person which operation is missing (see the scope sets above), and ask them to create a key that includes it.
7. **Follow the rules in this file.** Send an `Idempotency-Key` on every create, input, cancel, delete, upload, and answer (resolve) request; resend an unanswered request with the same key; poll (or use SSE or webhooks) until a terminal status; read results from `outputs`; decide what to do after a failure by `error.code`.
8. **Ask the person before anything that costs more.** Raising budgets, topping up SU, or running again after a costly failure are their decisions.
9. **Test once, small.** Make one real call with a short input, show the result, and confirm that the key never appears in logs or source.
10. **Report in the person's language,** in plain words: what you built, where the key lives, how to run it, and what it costs to call (usage is in `usage` on each Turn or Run, and in `GET /v1/usage`).

## Where to look

- The short rule set (next section) is the summary. When it and the reference pages differ, the reference pages win; when they and the OpenAPI file differ, the OpenAPI file wins: https://docs.upserve.app/runtime-api/openapi.json
- The same guide stays online at https://docs.upserve.app/runtime-api/agent-guide.md. Save a copy in the project (for example `docs/upserve-agent-guide.md`) so later sessions can read it.

---

# Rule summary (llms.txt)

## UpServe Agent Runtime API

> Server-to-server REST API that runs an organization's published AI employees (Deployments) and published workflows, then returns status, events, and JSON, file, and URL results. Anyone can use it: create a Project and an API key in the developer console. A Project an operator has blocked gets 404 on every path. It is not OpenAI compatible.

This file is a short entry point for AI tools. The contract source is the OpenAPI file. When this file and the OpenAPI file differ, the OpenAPI file wins.

- Base URL: https://api.upserve.app (every path below already starts with `/v1`, so the full address is `https://api.upserve.app/v1/...`; do not add another `/v1`)
- Auth: `Authorization: Bearer up_...` (API key of one Project, kept on a server only)
- Contract: https://docs.upserve.app/runtime-api/openapi.json
- A key cannot create Projects, publish Deployments, issue keys, or register webhooks. The signed-in person does that in the web app console at https://upserve.app/console (also under 「Console」 in the profile menu), in their personal space or an organization they own.

### Core loop: run an AI employee

1. `GET /v1/deployments`: list the Deployments this key may call.
2. `POST /v1/deployments/{deployment_id}/sessions` with header `Idempotency-Key` and body `{"input":[{"type":"TEXT","text":"..."}]}`: creates a Session and its first Turn. Answers 202 with `session_id`, `turn_id`, `status_url`, `events_url`.
3. `GET /v1/sessions/{session_id}/turns/{turn_id}`: poll until `status` is terminal (`SUCCEEDED`, `FAILED`, `CANCELED`, `EXPIRED`; in progress: `QUEUED`, `RUNNING`, `REQUIRES_ACTION`, `CANCEL_REQUESTED`). Results are in `outputs`, the failure reason in `error.code`. Input files go in `input` as `{"type":"FILE","file_id":"..."}`.
   - `REQUIRES_ACTION` is not terminal: the AI employee asked a question (only Deployments published with the question tool do this). Read it from `required_actions`, get the answer from a person, and send it with `POST /v1/sessions/{session_id}/actions/{action_id}/resolve` (scopes `sessions:read` and `actions:resolve`, `Idempotency-Key`, body `{"answers":[{"question_id":"...","text":"..."}]}`; a choice question takes `option_ids` instead of `text`). The same Turn then continues. Never invent the answer.
4. Follow-up input in the same conversation: `POST /v1/sessions/{session_id}/turns` with a new `Idempotency-Key`. One Turn runs at a time per Session (`409 SESSION_BUSY` otherwise). If the AI employee behind the Deployment now works only through its company's work portal, a new Session or Turn answers `409 TEAM_PORTAL_MANAGED` (`error.details.portal_url`, null when unknown): do not retry; tell the person to make the request in the work portal.
5. Stop: `POST /v1/sessions/{session_id}/turns/{turn_id}/cancel` with `Idempotency-Key`.

### Core loop: run a published workflow

1. `GET /v1/workflows/{workflow_id}`: read `published_version`, `input_schema`, and `available`. When the workflow cannot take a Run, this still answers 200, with `available: false` and the reason in `error.code` (for example `WORKFLOW_UNAVAILABLE`). Do not start a Run then.
2. Optional input file: `POST /v1/files` (multipart, `Idempotency-Key`) returns a `file_id`. It expires 24 hours after upload unless used as input.
3. `POST /v1/workflows/{workflow_id}/runs` with `Idempotency-Key` and body `{"published_version":3,"input":{...},"file_ids":[...]}`: answers 202 with `run_id`. `idempotency_expires_at` is `null` in this receipt; it gets a value only after the Run ends. `409 WORKFLOW_UNAVAILABLE` means the workflow is unpublished, stopped, or cannot start through the API.
   - Files: every uploaded file goes in `file_ids` (bound to the Run and attached to every step). If `input_schema` has a file field, also put `{"file_id":"<same id>"}` in that field of `input`. An id in a field but missing from `file_ids` gets `422 INVALID_INPUT`; the same id twice in `file_ids` gets `422 TOO_MANY_FILES`; more than 20 gets `422 INVALID_INPUT`.
4. `GET /v1/runs/{run_id}`: poll status and progress. A finished step is not a finished Run. In progress: `QUEUED`, `RUNNING`, `REQUIRES_ACTION`, `CANCEL_REQUESTED`. Terminal: `SUCCEEDED`, `PARTIALLY_SUCCEEDED`, `FAILED`, `CANCELED`, `EXPIRED`. A Run that has to stop (budget, deadline, cancel, revoked permission) passes through `CANCEL_REQUESTED` before it ends.
5. After the Run ends: `GET /v1/runs/{run_id}/outputs` (follow `next_cursor`). The response has the same shape as the Run details: `run` (status, `error`, `usage`), `outputs`, `next_cursor`, and `required_actions` (empty once the Run has ended).
   - `REQUIRES_ACTION` on a Run means a step asked for a human answer or review. Show it to a person in your own UI and submit their decision with `POST /v1/runs/{run_id}/actions/{action_id}/resolve` (questions need `actions:resolve`; approvals need the separately delegated `actions:approve` and a body with `decision`, `content_hash` from `GET /v1/runs/{run_id}/actions/{action_id}`, and `actor.subject`). Never decide for the person.
6. FILE output: `POST /v1/artifacts/{artifact_id}/download` issues a 60 second URL. Download right away.
7. Stop: `POST /v1/runs/{run_id}/cancel` with `Idempotency-Key`: 202 for a new cancel, 200 if the Run already ended.
8. Clean up: `DELETE /v1/runs/{run_id}` with `Idempotency-Key` (required): 202 with `status: "DELETING"`. After that the Run, its outputs, files, and `GET /v1/usage?run_id=` answer 404.

### Usage and cost

- `usage` on a Turn or Run is `{"status":"PENDING","total_su":null}` until the cost is final. `null` is not 0 SU.
- Storage for an execution's files (Run input files, result files) is settled only when those files are erased, so `usage` can stay `PENDING` after the execution ends, until you delete it or its retention ends (`retention_days` for a Run, 30 days for Session files). After that a deleted Run is 404 and an expired Run is 410 `RUN_EXPIRED`; the settled cost then appears only in the unfiltered `GET /v1/usage` Project total. An execution without files becomes `FINAL` shortly after it ends.
- While `PENDING`, `GET /v1/usage?run_id=` (or `turn_id=`, `session_id=`) shows `settled_su` and `reserved_su`. After a delete the per execution view is gone (404); its settled cost is in the totals of `GET /v1/usage` without a filter (or with `key_id`, `deployment_id`). Record per execution cost before deleting if you need it.

Instead of polling you may stream `GET /v1/sessions/{session_id}/events` or `GET /v1/runs/{run_id}/events` (SSE, resume with `Last-Event-ID`), or receive a signed webhook and then re-read the state.

### Core loop: build an organization work

Needs a key with `works:` scopes (a key whose scopes are works scopes plus at most `usage:read` needs no Deployment). `GET /v1/usage` reports preparation spend in `preparations`. Only organization Projects; a personal space Project gets 404.

1. `POST /v1/works` with header `Idempotency-Key` and body `{"spec":{"purpose":"..."}}`: UpServe creates an organization team and specializes it. Answers 202 with the preparation and `Location`.
2. `GET /v1/preparations/{preparation_id}`: poll until `status` is final (`SUCCEEDED` with `team_id`, `FAILED`, `CANCELED`). 202 and `QUEUED` mean accepted, not ready. There are no webhooks for preparations.
3. `NEEDS_INPUT`: relay a person's answers with `POST /v1/preparations/{preparation_id}/answers` and `expected_preparation_revision`.
4. `REQUIRES_ACTION` with `CONFIRM_SCOPE`: a person must decide. Send the decision only with `works:approve`, `actor.subject`, and the question's `package_hash`. Never decide for the person.
5. `FAILED` is not retried: read `reason_codes`, fix the cause, then send again with a new `Idempotency-Key`. List with `GET /v1/preparations`.

### Rules that prevent duplicate work and cost

- `Idempotency-Key` is required on every create, input, cancel, delete, and upload request (without it: `422 INVALID_INPUT`).
- Unanswered request (timeout, dropped connection, `retryable: true`): resend the same body with the same `Idempotency-Key`. The same receipt comes back and nothing runs twice. Honor `Retry-After`.
- Never resend an unanswered request under a new key. The work can run twice.
- For a Run, decide by the Run `error.code`, not by result item codes. A Run that stopped partway (for example `BUDGET_EXCEEDED`) marks each result it did not make with `OUTPUT_MISSING`; that item code is a consequence of the stop, not a publishing problem.
- Finished execution (`FAILED`, `CANCELED`, `EXPIRED`): it does not come back. A new attempt is a new Turn or Run with a new key and costs again. Decide by `error.code` using the table "What to do after a failed execution" on the errors page.
- `EXTERNAL_EFFECT_UNKNOWN`: do not run again before a person checks the external system.
- `EXECUTION_INCOMPLETE`, `NO_REPORT`, `CHECKPOINT_MISSING`: the execution stopped partway or after running to the end, so work the AI employee did (sending mail, writing to an external system) may already have happened. If the work writes anywhere, check there first and run again at most once, only if nothing happened. If `NO_REPORT` repeats, tell the publisher.
- Server-side temporary failures (`CHECKPOINT_UNAVAILABLE`, `RUNTIME_CONTEXT_MISSING`, `BILLING_CONTEXT_UNAVAILABLE`, `FUNDING_UNAVAILABLE`, `SETTLEMENT_CONFLICT`, `COST_BOUND_EXCEEDED`): wait, then create one new execution with the same input. If it ends with the same code again, stop and tell a person.
- `RUNTIME_CONTEXT_MISMATCH`, `CHECKPOINT_MISMATCH`: the Session is in a state that cannot run this. Run in a new Session.
- `SESSION_CONTEXT_LIMIT`: the Session's conversation plus the new input is too large, and older conversation is not shrunk automatically. Do not send to the same Session again. Start a new Session with a short summary, or shrink the input.
- `BILLING_CONTEXT_CHANGED`: who pays for the Deployment changed after acceptance. Run again only after the publisher confirms the new payer may cover the cost.
- Workflow step reject codes (only on Runs): `INPUT_MISSING_FIELD`, `INPUT_INVALID_FORMAT`, `INPUT_DUPLICATE`, `SOURCE_ALREADY_PRICED` (the file to quote came with its prices filled), `AMBIGUOUS_MATCH`, `RULE_VIOLATION` mean fix the input first (never rerun a processed duplicate); `EXTERNAL_SERVICE_ERROR`, `SOURCE_UNAVAILABLE` (a step's tool could not open or read a file, site or record; missing content in the input is `INPUT_MISSING_FIELD`) allow one later retry, then tell the publisher; `OUTPUT_VALIDATION_FAILED`, `SYSTEM_ERROR`, `SEND_BACK_CAP`, `STALE_REFERENCE_DATA`, `BILLING_INACTIVE`, `AGENT_UNAVAILABLE` go to the publisher (for `OUTPUT_VALIDATION_FAILED` and `SYSTEM_ERROR` you may first try one new Run, because the result can differ between executions).
- `DEFINITION_CHANGED`: the data format the work uses changed mid-run. The same execution cannot continue; create one new execution, which uses the new format.
- Result rule failures (`OUTPUT_URL_INVALID`, `OUTPUT_CONTAINS_CREDENTIALS`, `INVALID_FILENAME`, `UNSUPPORTED_FILE_TYPE` as a Turn or Run `error.code`): a result the AI employee made broke a public result rule and the execution ended there. Check that your input did not ask for an internal address, a credential, or a disallowed file type or name, then try at most once more with corrected input. If the same code comes back, tell the publisher.
- Publisher-side failures (`OUTPUT_SCHEMA_MISMATCH`, `OUTPUT_LIMIT_EXCEEDED`, `OUTPUT_MISSING`, `OUTPUT_PATH_DENIED`, `CAPABILITY_DENIED`, `WORKFLOW_UNAVAILABLE` as a Turn or Run `error.code`): do not repeat the same input. Tell the person who published the Deployment or workflow. A Run whose workflow was stopped mid-run ends `CANCELED` with `WORKFLOW_UNAVAILABLE`.
- Some of these codes also come as an HTTP 4xx answer to your own request: `INVALID_FILENAME` on upload, `UNSUPPORTED_FILE_TYPE` on upload or Turn input, `OUTPUT_SCHEMA_MISMATCH` and `OUTPUT_LIMIT_EXCEEDED` when Run `input` breaks `input_schema` or JSON limits, `409 WORKFLOW_UNAVAILABLE` on Run creation, `422 WORKFLOW_DATA_DEPENDENCY_UNRESOLVED` on Run creation when the workflow's published data contract does not cover data it reads (tell the publisher). Then fix that request (or wait until the workflow is published again); nothing ran.
- `retryable: false`: the same request gives the same result. Fix the request or stop.
- Unknown error code: do not run again. Stop and tell a person.
- Ask a person before spending decisions (raising budgets, topping up SU) and before running again after a costly failure.

### Not available through this API now

- Creating or editing AI employees, workflows, schedules, keys, or webhooks. The one exception is building a new organization team from a work description (`POST /v1/works` above).
- Questions and approvals the API cannot handle: a secret value input, a question inside a sub task, a workflow step the AI holds for itself (rejected before acceptance), and a prepared ERP approval or email confirmation (deciding it returns `409`). These give `ACTION_REQUIRED_UNSUPPORTED`.

### Reference pages

- Overview: https://docs.upserve.app/en/developers (Korean: https://docs.upserve.app/ko/developers)
- Quickstart: https://docs.upserve.app/en/developers/quickstart
- Authentication and keys: https://docs.upserve.app/en/developers/authentication
- Sessions and Turns: https://docs.upserve.app/en/developers/sessions-and-turns
- Workflows and Runs: https://docs.upserve.app/en/developers/workflows-and-runs
- Organization works: https://docs.upserve.app/en/developers/works
- Events and SSE: https://docs.upserve.app/en/developers/events
- Webhooks: https://docs.upserve.app/en/developers/webhooks
- Errors and retries: https://docs.upserve.app/en/developers/errors
- Limits and data: https://docs.upserve.app/en/developers/limits-and-data
- Versioning and changelog: https://docs.upserve.app/en/developers/changelog
- Client examples: https://docs.upserve.app/runtime-api/examples/runtime_client.py, https://docs.upserve.app/runtime-api/examples/runtime_client.ts

---

# Reference: Agent Runtime API overview

Source: https://docs.upserve.app/en/developers

## Agent Runtime API overview

The UpServe Agent Runtime API is a server-to-server REST API that lets **external systems call AI employees (Deployments) and workflows published by your organization**. Use it when an internal system, a batch job, or a backend service needs to hand work to an UpServe AI employee and collect the result.

> **This is not an OpenAI-compatible API.** There is no OpenAI style chat completions path, and the request and response formats differ. Changing the base URL of an OpenAI SDK will not work.

### Access

- Anyone can use it. Create a Project and issue a key in the developer console, and you can call right away. You do not need to apply.
- An operator can block a Project for security or stability reasons. For a blocked Project, every path answers `404 NOT_FOUND`.
- Changes to the contract (paths, fields, limits) are recorded in the [changelog](https://docs.upserve.app/en/developers/changelog).
- It is not meant to be called directly from a browser or a mobile app. Keep API keys on your servers only.

### Basics

| Item | Value |
|---|---|
| Base URL | `https://api.upserve.app` (every path starts with `/v1`, for example `https://api.upserve.app/v1/deployments`) |
| Authentication | `Authorization: Bearer up_...` (API key) |
| Format | JSON (multipart only for file uploads) |
| Contract source | [openapi.json](https://docs.upserve.app/runtime-api/openapi.json) |

The OpenAPI file is the source of truth for request and response schemas of the public `/v1` paths. If this documentation and the file disagree, the file wins.

### Core concepts

| Concept | Description |
|---|---|
| Project | The unit of access owned by an organization. API keys, Deployments, webhooks, and budget limits belong to a Project. |
| API key | A credential that belongs to a Project. It carries allowed scopes and the list of Deployments and workflows it may call. |
| Deployment | An organization's AI employee published and frozen at a point in time. Editing the original employee does not change a published Deployment. |
| Session | A conversation with one Deployment. Earlier turns carry over within the same Session. |
| Turn | One input sent to a Session and its execution. A Session runs only one Turn at a time. |
| Workflow | The order and conditions of work that the organization has published. Its published version and input schema are fixed. |
| Run | One execution of a published workflow. It passes through several steps to produce results. |
| Artifact | A file produced by an execution. You download it through a short-lived URL. |
| Event | A record that reports the progress of a Turn or Run. Polling, SSE, and webhooks all use the same records. |

### Where to start

1. Run your first Turn with the [quickstart](https://docs.upserve.app/en/developers/quickstart).
2. Learn how to handle keys in [authentication](https://docs.upserve.app/en/developers/authentication).
3. For conversational calls read [Sessions and Turns](https://docs.upserve.app/en/developers/sessions-and-turns). For workflow calls read [Workflows and Runs](https://docs.upserve.app/en/developers/workflows-and-runs).
4. Before going to production, read [events](https://docs.upserve.app/en/developers/events), [webhooks](https://docs.upserve.app/en/developers/webhooks), [errors](https://docs.upserve.app/en/developers/errors), and [limits and data](https://docs.upserve.app/en/developers/limits-and-data).
5. To build a new organization team from a work description, read [organization works](https://docs.upserve.app/en/developers/works).

### When an AI tool writes the integration

Use the buttons in the "Let a coding agent connect it" box at the top to hand over the [integration guide](https://docs.upserve.app/runtime-api/agent-guide.md). The guide is one Markdown file. It holds the steps the coding agent follows, the rule summary from [llms.txt](https://docs.upserve.app/runtime-api/llms.txt), and all of this documentation except the changelog. This documentation and [openapi.json](https://docs.upserve.app/runtime-api/openapi.json) remain the source of the detailed contract.

The guide has the coding agent work as follows.

- A person puts the key in the server `.env` file. It never goes into the chat.
- The agent finds the Deployment to call with `GET /v1/deployments`. Only a workflow ID is copied from the console by a person.
- It writes server side code only, in the language and framework the project already uses.
- It makes one small test call and reports in the person's language.

Have it decide whether to run a failed execution again with the per-code next step table in [errors](https://docs.upserve.app/en/developers/errors). It is safer to have a person confirm decisions that cost money again and budget changes.

---

# Reference: Quickstart

Source: https://docs.upserve.app/en/developers/quickstart

## Quickstart

This guide walks through a first Turn, a workflow Run, and a webhook. Before you start, prepare the permissions and resources listed below.

To let a coding agent write the code instead, use the "Let a coding agent connect it" box at the top of the [overview](https://docs.upserve.app/en/developers).

### What you need

- An UpServe account with **organization OWNER** permission. Only an OWNER can create Projects, issue keys, and register webhooks. A personal space user can also create Projects in their own space.
- A **Project**. You can create one right away in the developer console. You do not need to apply.
- At least one **Deployment** to call. You create it by publishing one of your organization's AI employees.
- An **API key** that allows that Deployment. The key is shown only once, when it is created.

You create Projects, publish Deployments, issue keys, and register webhooks in the web app console (`https://upserve.app/console`). Open it from 「Console」 in the profile menu at the top right. For organizations on a flat-fee contract, UpServe opens the API after a check. If the console overview says API calls are not open yet, let your account manager know. That screen is a management screen that works with the signed-in owner's permission. An API key cannot perform management tasks.

Handle the key only through environment variables. Never leave it in code, logs, or repositories.

### Step 1: Make your first Turn call

The call flow has four steps.

1. Check which Deployments this key can call with `GET /v1/deployments`.
2. Create a Session and its first Turn with `POST /v1/deployments/{deployment_id}/sessions`. The server stores the acceptance and then answers `202`.
3. Send the same request again with the same `Idempotency-Key`. It does not run again and returns the same acceptance.
4. Poll `GET /v1/sessions/{session_id}/turns/{turn_id}` until the Turn reaches a terminal status.

#### curl

```bash
export UPSERVE_API_KEY="up_..."
export BASE="https://api.upserve.app"

# 1. List the Deployments this key may call
curl -s "$BASE/v1/deployments" \
  -H "Authorization: Bearer $UPSERVE_API_KEY"

# 2. Create a Session and its first Turn (202 Accepted)
curl -s -X POST "$BASE/v1/deployments/$DEPLOYMENT_ID/sessions" \
  -H "Authorization: Bearer $UPSERVE_API_KEY" \
  -H "Idempotency-Key: demo-0001" \
  -H "Content-Type: application/json" \
  -d '{"input":[{"type":"TEXT","text":"Summarize sales for this month."}]}'

# 3. Send the exact same request again: the same receipt comes back

# 4. Poll the Turn until it reaches a terminal status
curl -s "$BASE/v1/sessions/$SESSION_ID/turns/$TURN_ID" \
  -H "Authorization: Bearer $UPSERVE_API_KEY"
```

The 202 response (receipt) looks like this.

```json
{
  "session_id": "6f1c0a52-0000-4000-8000-000000000001",
  "turn_id": "6f1c0a52-0000-4000-8000-000000000002",
  "status": "QUEUED",
  "idempotency_expires_at": "2026-10-06T09:00:00+00:00",
  "status_url": "/v1/sessions/6f1c0a52-0000-4000-8000-000000000001/turns/6f1c0a52-0000-4000-8000-000000000002",
  "events_url": "/v1/sessions/6f1c0a52-0000-4000-8000-000000000001/events"
}
```

`Idempotency-Key` is required for create, input, cancel, delete, and upload requests. Without it you get `422 INVALID_INPUT`. If a network failure kept you from reading the response, send **the same body with the same key** again. If the request was already accepted, the same receipt comes back and the work does not run twice. Sending a different body with the same key returns `409 IDEMPOTENCY_CONFLICT`. To ask for completed work again, use a new key.

#### Python

```python
import os
import time
import uuid

import httpx

BASE = "https://api.upserve.app"
AUTH = {"Authorization": "Bearer " + os.environ["UPSERVE_API_KEY"]}
DONE = {"SUCCEEDED", "FAILED", "CANCELED", "EXPIRED", "REQUIRES_ACTION"}

def create_session(deployment_id: str, text: str, key: str) -> dict:
    response = httpx.post(
        f"{BASE}/v1/deployments/{deployment_id}/sessions",
        headers={**AUTH, "Idempotency-Key": key},
        json={"input": [{"type": "TEXT", "text": text}]},
        timeout=30,
    )
    response.raise_for_status()
    return response.json()

def wait_turn(session_id: str, turn_id: str) -> dict:
    while True:
        response = httpx.get(f"{BASE}/v1/sessions/{session_id}/turns/{turn_id}", headers=AUTH, timeout=30)
        response.raise_for_status()
        turn = response.json()
        if turn["status"] in DONE:
            return turn
        time.sleep(2)

# Reuse the same key when you resend after a network failure
key = str(uuid.uuid4())
receipt = create_session(os.environ["DEPLOYMENT_ID"], "Summarize sales for this month.", key)
turn = wait_turn(receipt["session_id"], receipt["turn_id"])
print(turn["status"], turn["usage"])
for output in turn["outputs"]:
    if output["type"] == "TEXT":
        print(output["text"])
```

#### TypeScript

This uses the built-in `fetch` of Node 22 or later.

```typescript
const BASE = 'https://api.upserve.app';
const AUTH = { Authorization: `Bearer ${process.env.UPSERVE_API_KEY}` };
const DONE = new Set(['SUCCEEDED', 'FAILED', 'CANCELED', 'EXPIRED', 'REQUIRES_ACTION']);

async function createSession(deploymentId: string, text: string, key: string) {
  const response = await fetch(`${BASE}/v1/deployments/${deploymentId}/sessions`, {
    method: 'POST',
    headers: { ...AUTH, 'Idempotency-Key': key, 'Content-Type': 'application/json' },
    body: JSON.stringify({ input: [{ type: 'TEXT', text }] }),
  });
  if (!response.ok) throw new Error(JSON.stringify(await response.json()));
  return response.json();
}

async function waitTurn(sessionId: string, turnId: string) {
  for (;;) {
    const response = await fetch(`${BASE}/v1/sessions/${sessionId}/turns/${turnId}`, { headers: AUTH });
    if (!response.ok) throw new Error(JSON.stringify(await response.json()));
    const turn = await response.json();
    if (DONE.has(turn.status)) return turn;
    await new Promise((resolve) => setTimeout(resolve, 2000));
  }
}

// Reuse the same key when you resend after a network failure
const key = crypto.randomUUID();
const receipt = await createSession(process.env.DEPLOYMENT_ID!, 'Summarize sales for this month.', key);
const turn = await waitTurn(receipt.session_id, receipt.turn_id);
console.log(turn.status, turn.usage);
```

The example also stops waiting at `REQUIRES_ACTION`. That status is not an end: the Turn is waiting for a person to answer. See [Resolving questions](https://docs.upserve.app/en/developers/sessions-and-turns#resolving-questions-requiredaction).

A successful Turn carries its results in `outputs`, as below. If `usage.status` is `PENDING`, the cost is not final yet.

```json
{
  "id": "6f1c0a52-0000-4000-8000-000000000002",
  "session_id": "6f1c0a52-0000-4000-8000-000000000001",
  "status": "SUCCEEDED",
  "usage": {"status": "FINAL", "total_su": 1.25},
  "error": null,
  "created_at": "2026-10-05T09:00:00+00:00",
  "started_at": "2026-10-05T09:00:02+00:00",
  "completed_at": "2026-10-05T09:00:20+00:00",
  "outputs": [
    {"id": "o1", "key": "answer", "type": "TEXT", "visibility": "FINAL",
     "availability": "READY", "item_id": "i1", "text": "Sales this month were up 8%."}
  ],
  "next_cursor": null
}
```

Complete examples with retries, backoff, and SSE reconnection are available as [runtime_client.py](https://docs.upserve.app/runtime-api/examples/runtime_client.py), [runtime_client.ts](https://docs.upserve.app/runtime-api/examples/runtime_client.ts), and [runtime_quickstart.sh](https://docs.upserve.app/runtime-api/examples/runtime_quickstart.sh). Webhook receiver examples are [runtime_webhook_receiver.py](https://docs.upserve.app/runtime-api/examples/runtime_webhook_receiver.py) and [runtime_webhook_receiver.ts](https://docs.upserve.app/runtime-api/examples/runtime_webhook_receiver.ts).

The client examples infer the MIME type from the filename extension. To set it explicitly, use `client.upload_file("report.csv", mime_type="text/csv")` in Python or `client.uploadFile("report.csv", { mimeType: "text/csv" })` in TypeScript.

### Step 2: Run a workflow

You call a published workflow with a **Run**, not a Session. The flow is as follows.

1. (Optional) Upload an input file with `POST /v1/files` and get a `file_id`. Put it in `file_ids` of the Run request, and if the workflow has a file input field, also in that field as `{"file_id": "..."}`.
2. Send the published version and the input to `POST /v1/workflows/{workflow_id}/runs`. You get `202` and a `run_id`.
3. Poll `GET /v1/runs/{run_id}` for status and progress, or receive it over SSE. There is no final result before the Run ends.
4. When the Run ends, read the JSON, file, and URL results from `GET /v1/runs/{run_id}/outputs`.
5. For a file result, issue a 60 second URL with `POST /v1/artifacts/{artifact_id}/download` and download right away.

```bash
# 1. (Optional) Upload an input file and keep the returned file_id
curl -s -X POST "$BASE/v1/files" \
  -H "Authorization: Bearer $UPSERVE_API_KEY" \
  -H "Idempotency-Key: file-0001" \
  -F "file=@report.csv;type=text/csv"

# 2. Start a Run on a published version (202 Accepted)
curl -s -X POST "$BASE/v1/workflows/$WORKFLOW_ID/runs" \
  -H "Authorization: Bearer $UPSERVE_API_KEY" \
  -H "Idempotency-Key: run-0001" \
  -H "Content-Type: application/json" \
  -d '{"published_version":3,"input":{"count":3},"file_ids":["'"$FILE_ID"'"]}'

# 3. Poll the Run status and progress
curl -s "$BASE/v1/runs/$RUN_ID" \
  -H "Authorization: Bearer $UPSERVE_API_KEY"

# 4. Read the outputs (JSON, FILE and URL items), following next_cursor if present
curl -s "$BASE/v1/runs/$RUN_ID/outputs?limit=50" \
  -H "Authorization: Bearer $UPSERVE_API_KEY"

# 5. Issue a short-lived download URL for a FILE output, then fetch it right away
curl -s -X POST "$BASE/v1/artifacts/$ARTIFACT_ID/download" \
  -H "Authorization: Bearer $UPSERVE_API_KEY"
curl -s -o report.pdf "$BASE$DOWNLOAD_URL"
```

The detailed rules for each step are in [Workflows and Runs](https://docs.upserve.app/en/developers/workflows-and-runs).

### Step 3: Get completion notifications

Use a webhook to be told when work finishes instead of polling. You register the webhook as an HTTPS address in the developer screen, and you keep the secret, which is shown once at registration, on your receiving server. The receiver verifies the signature, drops duplicates by `event_id`, and then re-reads the current state with an authenticated request. See [webhooks](https://docs.upserve.app/en/developers/webhooks) for the verification code.

### Next

- Key permissions and rotation: [authentication](https://docs.upserve.app/en/developers/authentication)
- Error handling and retry principles: [errors](https://docs.upserve.app/en/developers/errors)
- Limits and retention: [limits and data](https://docs.upserve.app/en/developers/limits-and-data)

---

# Reference: Authentication and API keys

Source: https://docs.upserve.app/en/developers/authentication

## Authentication and API keys

Most `/v1` requests are authenticated with an API key. The exception is an issued file download URL: it uses a one-time `token`, and the server rechecks the issuing API key's permissions. See [Downloading result files](https://docs.upserve.app/en/developers/workflows-and-runs#downloading-result-files).

```bash
curl -s "https://api.upserve.app/v1/deployments" \
  -H "Authorization: Bearer $UPSERVE_API_KEY"
```

A key is a string that starts with `up_`. A missing key, a malformed key, or a revoked or expired key returns `401 INVALID_API_KEY`.

### The key is shown only once

- The key itself appears **only in the response when you create or rotate it**. The server stores only a one-way hash of the key, so it cannot show it again.
- If you lose it, create a new key or rotate.
- Keep it in an environment variable or a secret store. Do not put it in code, logs, error reports, a browser, or a mobile app.
- A key belongs to a Project. Key management (create, rotate, revoke) is done only by an organization OWNER through the signed-in management screen or the management API. An execution API key cannot do it.
- If the person who issued a key loses organization OWNER permission, that key starts returning `401 INVALID_API_KEY`.
- Your responsibility for keeping keys, the duty to revoke a leaked key, and prohibited uses (transferring or reselling keys, evading limits, and so on) are set out in [Terms of Service Section 2-6](https://upserve.app/terms#runtime-api)(2) and (10).

### Scopes

You choose the allowed scopes for each key. An operation without its scope returns `403 INSUFFICIENT_SCOPE`.

| scope | Allowed operations |
|---|---|
| `deployments:read` | List and read Deployments |
| `sessions:read` | Read Sessions and Items |
| `sessions:write` | Create, close, and delete Sessions |
| `turns:read` | List Turns and read their status |
| `turns:write` | Create Turns (including the first Turn of a new Session) |
| `turns:cancel` | Cancel a Turn |
| `events:read` | Read Session and Run events (SSE) |
| `usage:read` | Read usage |
| `files:write` | Upload input files (including Session files) |
| `artifacts:read` | Read Artifact details and download |
| `workflows:read` | Read workflow details |
| `workflows:run` | Submit a Run |
| `runs:read` | Read Run status and results |
| `runs:cancel` | Cancel a Run |
| `runs:delete` | Delete a Run |
| `actions:resolve` | Answer a caller-resolvable question (RequiredAction). Session questions also require `sessions:read`. |
| `actions:approve` | Submit human approvals or rejections collected by your service (explicit delegation) |
| `works:read` | Read and list organization work preparations |
| `works:write` | Submit an organization work, revise its spec, and answer preparation questions |
| `works:approve` | Submit a person's scope confirmation collected by your service (explicit delegation) |

One request can require several scopes. For example, creating a Session needs `sessions:write` and `turns:write`, and reading a Turn result needs `turns:read` and `sessions:read`. Grant only the minimum scopes you need.

### Deployment and workflow allowlists

Separately from scopes, a key has a **list of Deployments and workflows it may call**.

- A Deployment or workflow that is not on the key answers `404 NOT_FOUND`, so its existence is not revealed.
- The effective permission is the **intersection** of the key scopes, the Project and key allowlists, and the capabilities frozen at publication. Scopes alone never widen access.
- Split keys by purpose, and allow each key only the Deployments it needs.
- A key with at least one works scope and nothing else but `usage:read` runs no Deployment, so it can be created without one. A key that mixes in any other scope needs at least one Deployment. See [organization works](https://docs.upserve.app/en/developers/works).

### Rotation

Use rotation to replace a key. Rotating creates **a new key with the same name, scopes, and allowlists**, and the new key appears once in the response.

- At rotation you explicitly choose an overlap time (`overlap_seconds`, 0 to 86,400 seconds). The default of 0 revokes the old key **immediately**.
- With an overlap, the old key expires once that time has passed, and both keys work in the meantime. It gives your callers time to move to the new key.
- Rotating a key that is already revoked, expired, or rotated returns `409 KEY_NOT_ROTATABLE`. Create a new key instead.
- Idempotency receipts are kept at Project scope, so resending with the same `Idempotency-Key` still works after rotation.

### Revocation

- Revocation **immediately blocks new requests and the start of new external effects** right after it commits. Later requests return `401 INVALID_API_KEY`.
- Unfinished Turns and Runs that were already accepted are switched to cancel requests. Effects that already completed are not undone, and an in-flight model call is not guaranteed to stop at once.
- Open SSE connections are closed at their periodic revalidation.
- Revoking a Project disables all of its keys.

### Expiry

You cannot choose an expiry date when creating a key. The main ways a key becomes unusable are:

1. The old key expires at a set time after a rotation that had an overlap.
2. An owner revokes the key.

The key also stops working if its Project is revoked or its issuer loses organization OWNER permission.

Rotate on a regular schedule to keep key lifetimes short.

### Rate limits

Call rates are limited per key, Project, and Deployment. When you exceed them you get `429 RATE_LIMITED` and `Retry-After`. See [limits and data](https://docs.upserve.app/en/developers/limits-and-data) for the numbers.

---

# Reference: Sessions and Turns

Source: https://docs.upserve.app/en/developers/sessions-and-turns

## Sessions and Turns

To call an AI employee conversationally, pick a Deployment, create a Session, and send Turns. A Session is fixed to one Deployment, and earlier turns carry over.

### Listing Deployments

- `GET /v1/deployments` returns the Deployments this key can call. (`deployments:read`)
- `GET /v1/deployments/{deployment_id}` shows the name, version, status (`ACTIVE`, `RETIRED`), model **tier** (`model_tier`), allowed tools, the declared result contract (`outputs`), the allowed input MIME types, and the call rate limits.
- Actual model names are not exposed. Only the tier is shown.

### Creating a Session

`POST /v1/deployments/{deployment_id}/sessions` creates a Session and its first Turn in one step. It needs `sessions:write` and `turns:write`, and `Idempotency-Key` is required.

- The server returns `202` **after** it has stored the acceptance. A dropped connection does not lose an accepted Turn.
- The response (receipt) has `session_id`, `turn_id`, `status`, `idempotency_expires_at`, `status_url`, and `events_url`. The `Location` header is the relative address of the Turn detail.
- The same key with the same body as an earlier request returns the same receipt. The same key with a different body returns `409 IDEMPOTENCY_CONFLICT`.
- A receipt is kept for at least 24 hours (`idempotency_expires_at`) and until that Turn has ended.

### Follow-up Turns

Send new input to the same Session with `POST /v1/sessions/{session_id}/turns`.

- A Session runs **only one Turn at a time**. Sending before the previous Turn ends returns `409 SESSION_BUSY`. There is no queue, so confirm that the Turn ended before you send.
- Sending to a closed Session returns `409 SESSION_CLOSED`.
- Once the AI employee behind the Deployment works only through its company's work portal, a new Session or Turn returns `409 TEAM_PORTAL_MANAGED`. Make the request in the work portal (`details.portal_url`, null when unknown). A request already accepted with the same Idempotency-Key still returns its receipt.
- Different Sessions run in parallel, subject to the Project's concurrent execution limit.

```json
{
  "error": {
    "code": "SESSION_BUSY",
    "message": "The session already has an active turn",
    "retryable": false,
    "request_id": "0b7b8f0e-0000-4000-8000-000000000004",
    "details": {}
  }
}
```

### Read, cancel, close, delete

| Path | Description |
|---|---|
| `GET /v1/sessions/{session_id}` | Session status (`ACTIVE`, `CLOSED`) and the active Turn |
| `GET /v1/sessions/{session_id}/turns` | List Turns with an `after` and `limit` cursor |
| `GET /v1/sessions/{session_id}/turns/{turn_id}` | Turn status, usage, error, results (`outputs`), and `next_cursor` |
| `GET /v1/sessions/{session_id}/items` | Public Item history |
| `POST /v1/sessions/{session_id}/turns/{turn_id}/cancel` | Cancel a Turn. 202 for a new cancel, 200 if it already ended |
| `POST /v1/sessions/{session_id}/close` | Close an idle Session. 409 if it is running |
| `DELETE /v1/sessions/{session_id}` | Accept a delete (202). Reading content is an immediate 404 afterward |

Turn statuses are `QUEUED`, `RUNNING`, `REQUIRES_ACTION`, `CANCEL_REQUESTED`, `SUCCEEDED`, `FAILED`, `CANCELED`, and `EXPIRED`. `SUCCEEDED`, `FAILED`, `CANCELED`, and `EXPIRED` are terminal. A failed Turn was still accepted successfully, so read the reason from `error.code` in the response.

- A cancel stores the intent first, and **effects that already completed are not undone.** If a cancel and a completion overlap, whichever finished first is the final state.
- For deletion, see the delete section of [limits and data](https://docs.upserve.app/en/developers/limits-and-data).
- You can add `X-Correlation-Id` (letters, digits, dot, underscore, colon, hyphen, 1 to 128 characters) to a request for tracing on your side. A bad format returns `400 INVALID_CORRELATION_ID`.

### Input format

```json
{
  "input": [
    {"type": "TEXT", "text": "Compare the attached report with last month."},
    {"type": "FILE", "file_id": "d3c1b8a0-0000-4000-8000-000000000003"}
  ],
  "metadata": {"request_ref": "example-001"},
  "limits": {"queue_seconds": 600, "execution_seconds": 3600, "max_su": 50}
}
```

- `input` is an array of `TEXT` and `FILE` items. TEXT cannot be empty or only whitespace. Multiple TEXT items are run in order, joined with line breaks.
- The `file_id` of a `FILE` item is a value you got by uploading with `POST /v1/files` first. An input file bound to a Session can be reused in later Turns of that Session until it expires. Upload it again to use it in another Session or Run.
- `metadata` takes at most 16 keys. A key is 1 to 64 characters and a string value is at most 512 characters.
- `limits` is optional. `queue_seconds` is 1 to 600, `execution_seconds` is 1 to 3600, and `max_su` is above 0 and at most 100 (up to 8 decimal places). A value above the cap is not silently reduced. It is rejected with `422 LIMIT_OUT_OF_RANGE`.
- The JSON request body is at most 64KiB in UTF-8. Larger bodies return `413 INPUT_TOO_LARGE`. Undeclared fields such as model, prompt, or tools return `422 INVALID_INPUT`.
- Files are 20MiB each, up to 20 per input. The allowed MIME types differ per Deployment.

### Output format

Each item of `outputs` in a Turn detail is one of these four types.

```json
[
  {"id": "o1", "key": "answer", "type": "TEXT", "visibility": "FINAL", "availability": "READY",
   "item_id": "i1", "text": "Done."},
  {"id": "o2", "key": "summary", "type": "JSON", "visibility": "FINAL", "availability": "READY",
   "schema_ref": "summary", "data": {"count": 3}},
  {"id": "o3", "key": "report", "type": "FILE", "visibility": "FINAL", "availability": "READY",
   "artifact_id": "a1", "filename": "report.txt", "mime_type": "text/plain",
   "size_bytes": 1024, "sha256": "..."},
  {"id": "o4", "key": "reference", "type": "URL", "visibility": "FINAL", "availability": "READY",
   "url": "https://example.com/report", "access": "UNKNOWN", "expires_at": null}
]
```

| type | Content |
|---|---|
| `TEXT` | The sanitized body `text`. A body over 64KiB is delivered as a file. |
| `JSON` | `data` validated against the schema set at publication. If it is large, a file is provided through `artifact_id` instead of `data`. |
| `FILE` | `artifact_id`, file name, MIME type, size, and `sha256`. See the download section of [Workflows and Runs](https://docs.upserve.app/en/developers/workflows-and-runs). |
| `URL` | An external HTTPS link `url` and its access mode (`access`). UpServe neither stores it nor guarantees its availability. |

- `visibility` is `INTERMEDIATE`, `PARTIAL`, or `FINAL`. Final results are `FINAL`.
- Items whose `availability` is `FAILED` or `EXPIRED` come with an `error`.
- The result list is at most 100 items and 256KiB per response. Continue with `after` and `next_cursor`.
- A successful Turn must contain every result marked `required` at publication. If one is missing or malformed, the Turn closes as a failure, not a success.

### Usage

The `usage` field of Turn and Run responses has two states.

```json
{"status": "PENDING", "total_su": null}
```

- When `FINAL`, `total_su` is the settled amount.
- When `PENDING`, the cost is **not decided yet** and `total_su` is `null`. It is not 0 SU. Reading again later returns the settled value.
- An execution may not become `FINAL` right after it ends. Storage for the execution's files (input files bound to a Run, result files the execution made) is settled when those files are erased, so `usage` stays `PENDING` while the files remain. It becomes `FINAL` when you delete the execution or its retention ends (`retention_days` for a Run, 30 days for Session files) and the files are erased. A deleted Run returns 404 and an expired Run returns 410 `RUN_EXPIRED`, so that Run's `usage` can no longer be read; the settled cost is in the Project total of an unfiltered `GET /v1/usage`. To keep a cost record per Run, save `settled_su` and `reserved_su` from the usage query below before deleting. The `total_su` of a `PENDING` usage response is `null`, not an amount. An execution without files becomes `FINAL` as soon as settlement after the end finishes.
- While it is `PENDING`, read the amounts from `settled_su` (settled so far) and `reserved_su` (reserved upper bound not yet settled) of `GET /v1/usage?run_id=` (or `turn_id=`, `session_id=`).
- A deleted Run or Session can no longer be read by its ID. The details and the `run_id`, `session_id`, and `turn_id` filters of `GET /v1/usage` all return 404. The cost settled after the delete is counted in the totals of `GET /v1/usage` without a filter (or with `key_id` or `deployment_id`). If you need to keep the cost of one execution, record the values above before you delete it.
- `GET /v1/usage` accepts `key_id`, `deployment_id`, `session_id`, `turn_id`, and `run_id` filters and shows settled amounts, reserved amounts, and the breakdown by item. You cannot combine `run_id` with another filter. (`usage:read`)
- `preparations` in the same response shows the preparation costs of [organization works](https://docs.upserve.app/en/developers/works) **separately**, with its own status, total, settled amount, reserved amount, and breakdown by item. An ongoing preparation does not change the execution `status` or `total_su`. When both are `FINAL`, add the execution and `preparations` totals to calculate the spend visible in this response. Visibility depends on the key's Deployment and workflow grants and which key submitted uploads and preparations, so this is not always the entire Project's spend.
  - With `works:read` on the key it covers every preparation in the Project. Without it, only the preparations that key accepted. `key_id` narrows it to the preparations that key accepted.
  - With `deployment_id`, `session_id`, `turn_id`, or `run_id`, `preparations` is `null`, because a preparation belongs to none of them. It is not 0 SU.

### Resolving questions (RequiredAction)

When the AI employee must ask the caller something during execution, the Turn stops at `REQUIRES_ACTION`. This happens only for a Deployment published with the question tool. `REQUIRES_ACTION` is not a terminal status: once you answer, the same Turn continues. A question the API cannot answer, such as a secret value input or a question inside a sub task, ends with `ACTION_REQUIRED_UNSUPPORTED`.

- Answer a question the caller may answer (`CALLER`) with `POST /v1/sessions/{session_id}/actions/{action_id}/resolve`. It needs the `sessions:read` and `actions:resolve` scopes and the `Idempotency-Key` header.
- Workflow approvals require separate `actions:approve` delegation. Collect the human decision in your own UI and submit it through the Run action API. See [workflow approvals](https://docs.upserve.app/en/developers/workflows-and-runs#approvals-in-your-own-ui).
- After the answer deadline it returns `409 ACTION_EXPIRED`.

```bash
curl -s -X POST "$BASE/v1/sessions/$SESSION_ID/actions/$ACTION_ID/resolve" \
  -H "Authorization: Bearer $UPSERVE_API_KEY" \
  -H "Idempotency-Key: answer-0001" \
  -H "Content-Type: application/json" \
  -d '{"answers":[{"question_id":"q1","text":"Use the Seoul office."}]}'
```

---

# Reference: Workflows and Runs

Source: https://docs.upserve.app/en/developers/workflows-and-runs

## Workflows and Runs

You call a workflow published by the organization with a **Run**. A Run passes through several steps and can take a while, so the acceptance response and the final result are separate.

### Calling a published version

1. Read the current published version (`published_version`), the input schema (`input_schema`), the result contract (`outputs`), whether it can be called (`available`), and the limits (`limits`) with `GET /v1/workflows/{workflow_id}`. (`workflows:read`)
2. Submit with `POST /v1/workflows/{workflow_id}/runs`. (`workflows:run`, `Idempotency-Key` required)

```json
{
  "published_version": 3,
  "input": {"count": 3},
  "file_ids": ["d3c1b8a0-0000-4000-8000-000000000003"],
  "limits": {"run_seconds": 7200, "max_su": 80, "retention_days": 7},
  "metadata": {"request_ref": "batch-2026-10"}
}
```

- `published_version` is **required** and must equal the current published version. Another version is not accepted. The step definitions and input and output contract are frozen at acceptance, so republishing does not change a Run that was already accepted.
- `input` must satisfy the workflow's input schema, otherwise you get `422 INVALID_INPUT`.
- The response is `202` with `run_id`, `status_url`, `events_url`, and `idempotency_expires_at`. Resending the same key and body returns the original Run even after a republish.
- `idempotency_expires_at` in the acceptance response is `null`, because the receipt does not expire before the Run ends. Once the Run ends it gets a value: the later of 24 hours after acceptance and the time the Run ended. Resending with the same key after the end returns a receipt with that value.
- The internal Sessions that carry workflow steps cannot be opened through the normal Session paths. Opening one returns `409 WORKFLOW_MANAGED_SESSION`.

### Run status and progress

`GET /v1/runs/{run_id}` returns `run`, `outputs`, and `next_cursor`. (`runs:read`)

```json
{
  "run": {
    "id": "5a9d3c10-0000-4000-8000-000000000005",
    "workflow_id": "2e4f6a80-0000-4000-8000-000000000006",
    "published_version": 3,
    "status": "RUNNING",
    "phase": "EXECUTING",
    "usage": {"status": "PENDING", "total_su": null},
    "error": null,
    "metadata": {"request_ref": "batch-2026-10"},
    "created_at": "2026-10-05T09:00:00+00:00",
    "deadline": "2026-10-05T11:00:00+00:00",
    "completed_at": null,
    "expires_at": null,
    "progress": {"total": 3, "completed": 1}
  },
  "outputs": [],
  "next_cursor": null
}
```

- `status` is one of the 9 values below. Once it reaches a terminal status, it does not change again.

| Group | Statuses |
|---|---|
| In progress | `QUEUED`, `RUNNING`, `REQUIRES_ACTION`, `CANCEL_REQUESTED` |
| Terminal | `SUCCEEDED`, `PARTIALLY_SUCCEEDED`, `FAILED`, `CANCELED`, `EXPIRED` |

- A Turn has 4 terminal statuses: `SUCCEEDED`, `FAILED`, `CANCELED`, and `EXPIRED`. `PARTIALLY_SUCCEEDED` exists only for Runs.
- `CANCEL_REQUESTED` does not come only from a cancel request. When something stops the whole Run, such as an exceeded budget (`BUDGET_EXCEEDED`), the deadline, revoked permission, or a stopped workflow, the Run also goes through `CANCEL_REQUESTED` until the remaining steps stop, and then ends. The reason is in `error.code` after it ends.
- `progress` is the number of unique steps fixed at acceptance (`total`) and how many are done (`completed`). A retry of the same step is not counted as another step.
- **One step finishing does not mean the whole Run finished.** Judge whether a Run has ended only by `status`.
- `PARTIALLY_SUCCEEDED` appears only when some optional results failed and the published conditions allow partial results.
- `outputs` is empty before the Run ends. The final results are published all at once together with the end.

### Reading results

`GET /v1/runs/{run_id}/outputs` reads the next page of the same result list. The response has the same shape as `GET /v1/runs/{run_id}`.

| Field | Content |
|---|---|
| `run` | The Run details (status, `error`, `usage`, progress). Even when you only read results, check here whether the Run ended and why it failed. |
| `outputs` | The result items on this page. Empty before the Run ends. |
| `next_cursor` | The cursor of the next page, or `null` if there is none |
| `required_actions` | Items waiting for a person's answer or approval. Empty once the Run has ended. |

 `limit` is 1 to 100 (default 50), and `after` takes the `next_cursor` of the previous response. A cursor works only for the results of that Run. A cursor from another Run returns `400 INVALID_CURSOR`. The result types (`TEXT`, `JSON`, `FILE`, `URL`) are the same as the output formats in [Sessions and Turns](https://docs.upserve.app/en/developers/sessions-and-turns).

### Uploading input files

To pass a file to a Run or Turn, upload it first.

```bash
curl -s -X POST "$BASE/v1/files" \
  -H "Authorization: Bearer $UPSERVE_API_KEY" \
  -H "Idempotency-Key: file-0001" \
  -F "file=@report.csv;type=text/csv"
```

- `POST /v1/files` accepts exactly one multipart `file` field. Extra fields, extra files, and compressed bodies are rejected. (`files:write`, `Idempotency-Key` required)
- On success it returns `201` with `file_id`, file name, MIME type, size, `sha256`, and `expires_at`.
- Uploading a different file with the same key returns `409 IDEMPOTENCY_CONFLICT`.
- Input files are 20MiB each, up to 20 per execution, and the files of one execution total at most 100MiB.
- For a Turn, put it in a `FILE` item of the input (`{"type":"FILE","file_id":"..."}`).
- For a Run, follow these rules.
  - Files in `file_ids` of the Run request are bound to that Run and attached to the execution of every step.
  - If the workflow input has a file field, put `{"file_id": "..."}` in that field of `input` **and put the same ID in `file_ids` too.** An ID in the field that is not in `file_ids` returns `422 INVALID_INPUT`. A file field value must be an object with only `file_id`.
  - A file only in `file_ids` and in no field is still bound, attached to the steps, and charged for storage. In a workflow with a file field, though, only the field tells which file is that field's value.
  - The same ID twice in `file_ids` returns `422 TOO_MANY_FILES`, more than 20 returns `422 INVALID_INPUT`, and a total over 100MiB returns `413 RUN_STORAGE_LIMIT`.

```json
{
  "published_version": 3,
  "input": {"report": {"file_id": "d3c1b8a0-0000-4000-8000-000000000003"}},
  "file_ids": ["d3c1b8a0-0000-4000-8000-000000000003"]
}
```

- A file bound to a Run cannot be reused in another Run or Session. A Session input file can be reused in later Turns of that same Session.
- To attach a file to an active Session that already exists, use `POST /v1/sessions/{session_id}/files`. It has the same format, and a closed Session returns `409 SESSION_CLOSED`.

### Downloading result files

A `FILE` result is referenced by `artifact_id`, and for each download you get a **short-lived URL** that re-checks the current permission. (`artifacts:read`)

1. Get `url` and `expires_at` from `POST /v1/artifacts/{artifact_id}/download`. The URL is valid for **at most 60 seconds**.
2. The returned `url` is a relative path shaped like `/v1/artifacts/{artifact_id}/content?token=...`. Append it to the base URL and download it with `GET`. The `token` in the URL replaces authentication. Do not write it to logs.
3. If it expired or was already used you get `404`, so **issue it again**. A file that was deleted or whose retention ended is not issued again.
4. Check the downloaded file against its `sha256`.

```python
def download(artifact_id: str) -> bytes:
    for _ in range(3):
        issued = httpx.post(f"{BASE}/v1/artifacts/{artifact_id}/download", headers=AUTH, timeout=30)
        issued.raise_for_status()
        # The returned url is a relative path that is valid for at most 60 seconds
        content = httpx.get(BASE + issued.json()["url"], timeout=60)
        if content.status_code != 404:
            content.raise_for_status()
            return content.content
    raise RuntimeError("download URL kept expiring")
```

HTTP Range requests are not supported. `GET /v1/artifacts/{artifact_id}` shows only the file metadata.

### External links versus stored files

| | `URL` result | `FILE` result |
|---|---|---|
| What it is | An external HTTPS link | An Artifact stored by UpServe |
| Storage | UpServe does not fetch or store it | Stored for the retention period |
| Availability | The linked server is responsible. No guarantee | Current permission is re-checked on every download |
| Access | `access` shows openness (`PUBLIC`, `AUTHENTICATED`, `UNKNOWN`) | Only through the short-lived issued URL |

A `FILE` also expires at the end of its [retention period](https://docs.upserve.app/en/developers/limits-and-data#retention). Download results to your own storage before expiry if you need to keep them longer. Treat a `URL` as a link to an external resource.

### Cancel, delete, and partial failure

- `POST /v1/runs/{run_id}/cancel` (`runs:cancel`, `Idempotency-Key` required) stores a cancel intent. 202 for a new cancel, 200 if the Run already ended. The response has `run_id`, `status_url`, `events_url`, `idempotency_expires_at` (24 hours after this cancel was accepted; resending with the same key until then returns the same response), and the current `status` (`CANCEL_REQUESTED` while canceling, or the terminal status if it already ended). It reaches every unfinished step, and the Run stays `CANCEL_REQUESTED` until the children are confirmed to have stopped. **Effects that already ran are not undone.**
- If what happened to an external effect during a cancel cannot be confirmed, the Run fails with `EXTERNAL_EFFECT_UNKNOWN`. Check the outcome yourself. It is not rerun automatically.
- `DELETE /v1/runs/{run_id}` (`runs:delete`, `Idempotency-Key` required) blocks access immediately and accepts the cleanup. The response is 202 with `status: "DELETING"`, and `idempotency_expires_at` is 24 hours after the delete was accepted. Resending with the same key until then returns the same receipt. After the delete, the Run details, results, files, and `GET /v1/usage?run_id=` all return 404. The Run's cost is settled after the delete and counted in the Project total of `GET /v1/usage` without a filter. See [usage](https://docs.upserve.app/en/developers/sessions-and-turns#usage).
- If a required result is missing or file preparation fails, the Run is `FAILED`, not `SUCCEEDED`.
- **Decide the failure reason by the Run's `error.code`.** When a Run stops partway, for example because of the budget or a cancel, each result it could not make gets `availability: "FAILED"` and `error.code: "OUTPUT_MISSING"`. That item `OUTPUT_MISSING` is only a consequence of the stop, not a publishing problem. For example, if the Run `error.code` is `BUDGET_EXCEEDED`, the budget is the cause.

### Time and cost limits

You can set lower limits for one Run with `limits`. A value above the cap is rejected, not silently reduced.

| Limit | Range | Note |
|---|---|---|
| `run_seconds` | 1 to 43,200 | Deadline for the whole Run |
| `execution_seconds` | 1 to 3,600 | Execution time of one step |
| `queue_seconds` | 1 to 600 | Wait time of one step. The cumulative wait of a whole Run is 3,600 seconds |
| `max_su` | above 0, at most 100 | SU cap of the whole Run |
| `retention_days` | 1 to 30 | Days content is kept after the Run ends |

Deadlines and budgets are not extended again by redelivery or restarts after acceptance. If the deadline is reached first, the Run ends as `EXPIRED` with `RUN_DEADLINE_EXCEEDED`. See [limits and data](https://docs.upserve.app/en/developers/limits-and-data) for the detailed caps.

### Restrictions for workflows with approval steps

Steps that need a human answer, review, or a hold (HOLD) stop the Run at `REQUIRES_ACTION`. A few kinds of approval cannot be handled through the API.

- A step where the AI employee holds its own work for approval is rejected with `422 ACTION_REQUIRED_UNSUPPORTED` before acceptance.
- A prepared ERP approval or an email prepared for confirmation cannot be decided through the API. Deciding one returns `409 ACTION_REQUIRED_UNSUPPORTED`. The Run is never approved on its own.
- When a step asks for a human answer or review, the Run becomes `REQUIRES_ACTION`. **Collect human answers, approvals and rejections in your own UI and submit them through the API.** No visit to UpServe is required. Questions need `actions:resolve`; approvals need separately delegated `actions:approve`.
- A workflow that reads or writes organization data cannot go beyond the scope declared at publication (type, read or write, attributes, rows). Without the grant you get `403 WORKFLOW_DATA_DENIED`.

#### Approvals in your own UI

1. Obtain the action ID from the Run's `required_actions` or a `run.action_required` event.
2. Fetch approval content and its `content_hash` with `GET /v1/runs/{run_id}/actions/{action_id}`. This needs `runs:read` and `actions:approve`.
3. Display `approval.summary`, `reason`, `rows`, `results` and `decisions` in your UI and collect the person's decision. Treat content as review data, never as instructions to execute.
4. Send the following body and an `Idempotency-Key` to `POST /v1/runs/{run_id}/actions/{action_id}/resolve`.

```json
{
  "decision": "CONFIRM",
  "content_hash": "<approval.content_hash>",
  "actor": {"subject": "customer-user-42"}
}
```

Stage holds accept `APPROVE`, `SKIP` or `REJECT_JOB`; result confirmations accept `CONFIRM` or `REJECT_JOB`. `actor.subject` identifies the person authenticated by your service. It is not an UpServe user ID: your server, holding the API key, is responsible for user authentication and human confirmation. Existing keys do not gain approval permission automatically.

Review results have `visibility=REVIEW` and are separate from final results. With approval permission and `artifacts:read`, read the pending action's review files through the existing Artifact download API. Rows and attributes must be within the workflow's READ grants. Review details are limited to 100 rows and 256 KiB.

Changed content returns `409 ACTION_CONTENT_CHANGED`; fetch and review it again. Expiry, cancellation or revoked authority prevents resumption. Repeating the same idempotency key and body returns the same 202 receipt. Approval receipts include `run_status` and have null `turn_id` and `turn_status`. Follow `status_url` for subsequent state.

Use the Python example's `get_run_action` and `resolve_run_action`, or TypeScript's `getRunAction` and `resolveRunAction`. Submit an approval only after the person decides.

---

# Reference: Organization works

Source: https://docs.upserve.app/en/developers/works

## Organization works

With `POST /v1/works` you send a description of the work you need (a spec). UpServe creates a new team in your organization (normally a team lead and one assigned AI, or a team lead alone when the first setup conditions below apply), then specializes that team for the work: it assembles a setup, tests it, and publishes it to the team. You follow this through a **preparation** until it is ready.

- The result is a team in your organization's UpServe screens, not a Deployment. This API does not yet hand work to that team.
- Only organization Projects can use these paths. A Project in a personal space gets `404 NOT_FOUND` on every work path.
- Specialized setups are enabled for the Project's organization automatically. A preparation ends with `RECIPE_ACCESS_DENIED` only when an operator has revoked that access for the organization.

### Before you start

| scope | Allowed operations |
|---|---|
| `works:read` | Read and list preparations |
| `works:write` | Submit a work or a revised spec, and answer questions |
| `works:approve` | Answer a scope confirmation on behalf of a person in your service (explicit delegation, chosen per key) |

- A key with at least one works scope and nothing else but `usage:read` can be created **without any Deployment**. A key that mixes in any other scope still needs at least one Deployment.
- The team's manager is the OWNER who created the key. If that person stops being an OWNER, the key stops working.
- Question texts in a preparation follow the manager's language: Korean for a Korean user, otherwise English.
- Preparation costs are paid like executions and count toward the Project's monthly spend limit. The team is created with autonomous wake-ups off, so it does not spend on its own.
- With `usage:read`, `GET /v1/usage` reports preparation costs in `preparations`, apart from execution costs. See [usage](https://docs.upserve.app/en/developers/sessions-and-turns#usage).

#### Choosing a work category

- An organization OWNER can choose one **work category** for a Project on the Project usage and limits screen of the developer console. Every work sent through that Project is then prepared in that work category. If none is chosen, UpServe decides from the work description.
- A work category is never sent in the request body. It is set only in the Project settings.
- The only work category available now is property title share review. Its costs are set by the requester, so the spec's `policy` must include `preparation_budget_su`, `run_budget_su`, and `period_budget_su`. Without them the preparation asks for them with `NEEDS_INPUT`.

#### Works that send their result by email

- When a version 2 spec (`spec_version: 2`) that sends its result as a new email (`delivery.mode` is `NEW_MAIL`) makes a new team, the team lead alone handles the work from start to finish (first setup). If its work category uses email sending (property title share review today), UpServe gives the team lead the ability to send email.
- If the organization cannot send email outside yet (not activated and not in a pre-activation service period), at least one member must have verified their email. If nobody has, the preparation stops with `SEND_EMAIL_UNVERIFIED` and leaves no new team behind.
- Email sending costs are billed to the organization like the team's other running costs and do not count toward the Project limits.

### Flow

1. Submit the work with `POST /v1/works`. (`works:write`, `Idempotency-Key` required)
2. Read `GET /v1/preparations/{preparation_id}` until the status is final. (`works:read`)
3. If the status is `NEEDS_INPUT`, answer the questions with `POST /v1/preparations/{preparation_id}/answers`.
4. The work is ready when the status is `SUCCEEDED` and `team_id` is set.

```bash
curl -s -X POST "$BASE/v1/works" \
  -H "Authorization: Bearer $UPSERVE_API_KEY" \
  -H "Idempotency-Key: work-0001" \
  -H "Content-Type: application/json" \
  -d @work.json
```

```json
{
  "spec": {
    "purpose": "Turn each incoming quote request into a quote from the approved catalog.",
    "success_criteria": ["Every request line has a source or a question for a person."],
    "sources": [{"ref": "synthetic:catalog", "revision": "1"}],
    "allowed_actions": ["READ_APPROVED_CATALOG", "CREATE_QUOTE"],
    "delivery": {"channel": "EMAIL", "target_ref": "synthetic:approved-operator"}
  }
}
```

The response is `202` with a `Location: /v1/preparations/{preparation_id}` header and the preparation itself.

```json
{
  "kind": "PREPARATION_VIEW",
  "contract_version": 1,
  "preparation_kind": "SPECIALIZE",
  "work_id": "22222222-2222-4222-8222-222222222222",
  "revision": 1,
  "preparation_id": "33333333-3333-4333-8333-333333333333",
  "preparation_revision": 2,
  "owner": {"kind": "ORGANIZATION", "id": "11111111-1111-4111-8111-111111111111"},
  "status": "QUEUED",
  "stage": "CREATE",
  "support": "SUPPORTED",
  "reason_codes": [],
  "missing_fields": [],
  "questions": [],
  "next_actions": [],
  "retryable": false,
  "spec": {"purpose": "Turn each incoming quote request into a quote from the approved catalog."},
  "usage": {"status": "PENDING", "cost_su": null}
}
```

- **`202` and `QUEUED` mean accepted, not ready.** Keep reading the preparation.
- There are no webhooks or SSE events for preparations. Poll at a modest interval, for example every 10 to 30 seconds.
- The full response schema is `WorkPreparationPreparationView` in the [OpenAPI file](https://docs.upserve.app/runtime-api/openapi.json).

### The request body

| Field | Description |
|---|---|
| `spec` | The work description. Only `spec.purpose` is required. Other fields (success criteria, inputs and outputs, examples, sources, connections, allowed actions, triggers, delivery, human decisions, facts, assumptions) make the result better. |
| `work_id`, `expected_revision` | Only to revise a work this Project created. Send both or neither. |

- Unknown fields are rejected with `422 INVALID_INPUT`. Do not send an owner, a support profile, or a recipe. The owner is always the key's organization, and UpServe chooses the setup.
- `connections` are reference names only. Never put credentials in a spec.
- A spec that breaks a rule is `422 INVALID_SPEC` with the field or rule in `details.reason`.

### Preparation status

| `status` | Meaning |
|---|---|
| `NEEDS_INPUT` | Something is missing. Answer `questions`. |
| `READY` | The spec is complete. It is queued right away. |
| `QUEUED`, `RUNNING` | Accepted and in progress. `stage` shows the step: `CREATE`, `ASSEMBLE`, `VALIDATE`, `BIND`, `PUBLISH`. |
| `REQUIRES_ACTION` | A person must confirm a wider scope (see below). |
| `CANCEL_REQUESTED` | Closing, for example after a scope confirmation was declined. |
| `SUCCEEDED` | Ready. `team_id` is the team. |
| `FAILED` | Ended. The reason is in `reason_codes`. |
| `CANCELED` | Ended without publishing. |

- `next_actions` lists what can happen next at the time you read it. It is not a permission. Every request is checked again.
- Organization preparations have no retry or cancel path, so `next_actions` never contains `RETRY` or `CANCEL`.
- `unsupported_actions` lists the `allowed_actions` UpServe cannot do when the work is not supported.

### Answering questions

```json
{
  "expected_preparation_revision": 1,
  "answers": [{"question_id": "delivery-target", "value": "synthetic:approved-recipient"}]
}
```

- `expected_preparation_revision` is the `preparation_revision` you read. If the preparation changed since, the answer is `409 REVISION_CONFLICT`. Read again and answer the current questions.
- Up to 20 answers go in one request. They are applied together or not at all.
- An answer to a question that is not open is `409 QUESTION_NOT_FOUND`. An answer to a preparation that no longer takes answers is `409 INVALID_TRANSITION`.
- The response is `200` with the updated preparation. When the spec becomes complete it is queued in the same request.

### Scope confirmation

A scope confirmation appears only when you revise a work that is already published and the new setup can do more than the current one (new tools, new external actions, or higher cost). The first publication of a new work does not ask. The preparation is then `REQUIRES_ACTION` with one question `Q_SCOPE_EXPANSION` that carries `changes` and `package_hash`, and `next_actions` is `CONFIRM_SCOPE`.

Show the changes to a person in your service and send their decision.

```json
{
  "expected_preparation_revision": 7,
  "answers": [{"question_id": "Q_SCOPE_EXPANSION", "value": {"decision": "APPLY", "package_hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}],
  "actor": {"subject": "customer-user-42"}
}
```

- The key needs `works:write` and `works:approve`. Without `works:approve` the answer is `403 ACTION_NOT_RESOLVABLE_BY_CALLER`.
- Send it as the only answer, with `actor.subject` (an opaque id of the person your service confirmed) and the `package_hash` from the question. Otherwise it is `422 INVALID_INPUT`.
- `APPLY` resumes the same preparation (`QUEUED`, step `PUBLISH`). `KEEP` keeps the current setup and closes the preparation.
- If the candidate changed after the person saw it, the answer is `409 PACKAGE_CHANGED`. Show the new question again. After the 7 day deadline the answer is `409 INVALID_TRANSITION`.
- UpServe records the decision subject apart from the key. It is not returned in responses.

### Listing preparations

`GET /v1/preparations` returns this Project's preparations, newest first, as `items` and `next_cursor`. (`works:read`)

- `limit` is 1 to 100 (default 20). Pass the previous `next_cursor` as `cursor` for the next page.
- `work_id` narrows the list to one work.
- Preparations of another Project are never listed, even within the same organization.

### Revising a work

Send `POST /v1/works` again with `work_id` and the `expected_revision` you read, together with the new spec.

- Only works this Project created can be revised. Any other `work_id` is `404 NOT_FOUND`.
- If the work changed since you read it, the answer is `409 REVISION_CONFLICT`.
- An open preparation that is still `NEEDS_INPUT` or `READY` is replaced. If one is already `QUEUED` or later, the answer is `409 PREPARATION_IN_PROGRESS` with `details.preparation_id`. Wait for it to finish.

### Idempotency and limits

- Every write needs an `Idempotency-Key`. Resending the same key with the same body returns the same response. The same key with a different body is `409 IDEMPOTENCY_CONFLICT`.
- Keys are scoped to the Project. Another Project of the same organization can use the same key value without collision.
- Writes count against the acceptance rate limit, like Turn and Run submissions. Reads count against the read limit. See [limits and data](https://docs.upserve.app/en/developers/limits-and-data).

### When a preparation fails

A preparation that ends as `FAILED` is not retried. Fix the cause, then revise the work with a **new** `Idempotency-Key`, the existing `work_id`, and the current `expected_revision`. Sending without `work_id` creates a separate work.

| `reason_codes` | Meaning | What to do |
|---|---|---|
| `PROJECT_BUDGET_EXCEEDED` | The Project's monthly spend limit was reached. It stops before any team is created. | Send again once the next month (UTC) begins. If a lower custom limit caused this, an organization OWNER can adjust it within the default maximum. |
| `AUTHORIZATION_REVOKED` | The key was revoked, or the person who created it is no longer an organization OWNER. | Send again with a valid key. |
| `TEAM_CREATE_REFUSED` | The request to create the team or its assigned AI was refused. | Fix it in the organization's UpServe screens, then send again. |
| `SEND_EMAIL_UNVERIFIED` | The work sends its result by email, but the organization cannot send email outside yet and no member has verified their email. No new team is left behind. | Have one member verify their email, then send again. |
| `RECIPE_ACCESS_DENIED` | An operator revoked specialized setups for the organization. | Sending the same request again gives the same result. Tell a person and stop. |

A spec UpServe cannot support ends with `support` `UNSUPPORTED`, and `unsupported_actions` shows which actions. HTTP errors on these paths are in [errors and retries](https://docs.upserve.app/en/developers/errors).

---

# Reference: Events and SSE

Source: https://docs.upserve.app/en/developers/events

## Events and SSE

You can also follow the progress of a Turn or Run through **events**. Polling, SSE, and webhooks all read the same public records, so results do not differ by method.

### Polling and SSE

| Method | When to use it |
|---|---|
| Polling | The simplest. Repeat the status read every 2 to 5 seconds. Stop at a terminal status. |
| SSE | When you want progress events in real time. If the connection drops, it resumes from the last event. |
| Webhook | When you want the server to tell you about completion. See [webhooks](https://docs.upserve.app/en/developers/webhooks). |

SSE is `GET /v1/sessions/{session_id}/events` and `GET /v1/runs/{run_id}/events`. It needs the `events:read` scope, and a Run also needs `runs:read`. If the connection drops or the server closes it, **an execution that was already accepted is not canceled.**

```bash
curl -N "$BASE/v1/sessions/$SESSION_ID/events" \
  -H "Authorization: Bearer $UPSERVE_API_KEY" \
  -H "Accept: text/event-stream"

# Reconnect and continue after the last event you processed
curl -N "$BASE/v1/sessions/$SESSION_ID/events" \
  -H "Authorization: Bearer $UPSERVE_API_KEY" \
  -H "Last-Event-ID: $LAST_EVENT_ID"
```

### Frame format

Each event is one standard SSE frame.

- `id` is the event's `event_id`. It is an opaque UUID, so do not infer ordering from it.
- `event` is the event type, for example `message.created`, `tool.started`, `turn.progress`, `turn.completed`, `run.step.completed`, and `run.completed`.
- `data` is one line of JSON. It carries `event_id`, `aggregate_kind`, `aggregate_id`, `sequence`, `type`, `created_at`, and `data`. The inner `data.kind` tells the kind of content.
- A line that starts with `: keep-alive` is a comment sent about every 15 seconds. Ignore it.
- `sequence` can be compared **only within the same Session or the same Run**. Do not compare Session and Run numbers with each other.

```text
id: 7c2e0d44-0000-4000-8000-000000000007
event: message.created
data: {"event_id":"7c2e0d44-0000-4000-8000-000000000007","aggregate_kind":"SESSION","aggregate_id":"6f1c0a52-0000-4000-8000-000000000001","sequence":3,"type":"message.created","created_at":"2026-10-05T09:00:18+00:00","data":{"kind":"MESSAGE","text":"Sales this month were up 8%.","visibility":"FINAL"}}

: keep-alive

id: 7c2e0d44-0000-4000-8000-000000000008
event: turn.completed
data: {"event_id":"7c2e0d44-0000-4000-8000-000000000008","aggregate_kind":"SESSION","aggregate_id":"6f1c0a52-0000-4000-8000-000000000001","sequence":4,"type":"turn.completed","created_at":"2026-10-05T09:00:20+00:00","data":{"kind":"OUTCOME","status":"SUCCEEDED"}}
```

Public events carry only tool names, call IDs, progress phases, and sanitized final messages. Tool arguments, raw tool results, and internal reasoning are not included.

Here is a minimal example that reads SSE frames.

```python
def events(session_id: str, last_event_id: str | None = None):
    headers = {**AUTH, "Accept": "text/event-stream"}
    if last_event_id:
        headers["Last-Event-ID"] = last_event_id
    with httpx.stream("GET", f"{BASE}/v1/sessions/{session_id}/events", headers=headers, timeout=None) as response:
        response.raise_for_status()
        frame = {}
        for line in response.iter_lines():
            if line == "":
                if frame:
                    yield frame
                frame = {}
            elif not line.startswith(":"):
                name, _, value = line.partition(":")
                frame[name] = value.removeprefix(" ")
```

### Reconnecting with Last-Event-ID

- If the connection drops, reconnect with the `id` of the last event you **finished processing** in the `Last-Event-ID` header (or the `after` query). The server resends from the event **after** it.
- If you send both, they must be the same ID. Otherwise you get `400 INVALID_CURSOR`.
- An ID from another Session or Run returns `404`.
- The same event can arrive twice, so drop duplicates by `event_id`.
- If reconnecting keeps failing, retry with growing intervals, and check the status by polling in the meantime.

### Recovering from an expired cursor (410)

Event and Item content is kept for at most 30 days, and an old cursor becomes `410 EVENT_CURSOR_EXPIRED`. The `details` of the response carry the recovery paths.

```json
{
  "error": {
    "code": "EVENT_CURSOR_EXPIRED",
    "message": "The event cursor has expired",
    "retryable": false,
    "request_id": "0b7b8f0e-0000-4000-8000-000000000009",
    "details": {
      "state_url": "/v1/sessions/6f1c0a52-0000-4000-8000-000000000001/turns",
      "items_url": "/v1/sessions/6f1c0a52-0000-4000-8000-000000000001/items"
    }
  }
}
```

Retention has ended if a Session reports `details.content_expired: true` or a Run returns `410 RUN_EXPIRED`. Follow these steps for `EVENT_CURSOR_EXPIRED` while content is still retained.

1. Read `state_url`. For a Session, it returns the Turn list and requires `turns:read`. For a Run, it returns the Run detail and requires `runs:read`.
2. Read `items_url`. For a Session, it returns the public Item list and requires `sessions:read`. For a Run, it returns the outputs and requires `runs:read`.
3. To read another page, send `next_cursor` as the `after` parameter on that URL.
4. If you still need events, reopen SSE without a cursor.

![Session SSE reconnection. Resume with a valid cursor. After a 410, retrieve retained content or stop if retention has ended.](https://docs.upserve.app/runtime-api/sse-recovery-en.svg)

### Errors after the headers were sent

SSE sends `200` and the headers first, so an error that happens afterward arrives not as an HTTP status but as an **`event: error` frame**. This frame has no `id`, and the server closes the connection after sending it.

```text
event: error
data: {"error":{"code":"EVENT_CURSOR_EXPIRED","message":"The event cursor has expired; retrieve retained state and items","retryable":false,"request_id":"0b7b8f0e-0000-4000-8000-000000000009","details":{"state_url":"/v1/sessions/6f1c0a52-0000-4000-8000-000000000001/turns","items_url":"/v1/sessions/6f1c0a52-0000-4000-8000-000000000001/items"}}}
```

- If the error's `retryable` is `true`, reconnect with the last `id`.
- Even while connected, the key, Deployment, and Session permissions are rechecked periodically. If the key is revoked or permission is withdrawn, the connection is closed.

### Slow consumers

If you read events so slowly that the server send limit (about 10 seconds) is exceeded, the server **ends the connection.** It does not buffer without limit. Reconnect with the last processed `id` and you pick up the missed events. If your processing is slow, put received frames on a queue and handle them in a separate job.

---

# Reference: Webhooks

Source: https://docs.upserve.app/en/developers/webhooks

## Webhooks

A webhook is how UpServe **sends a notification to your server** when a Turn or Run ends. A notification carries no raw result, only identifiers, a status, and lookup paths, so after receiving it you must re-read the current state with your API key.

### Registering

Webhook management is a management API that uses **the signed-in organization OWNER's permission (JWT), not an API key**. You can do it in the Webhooks menu of the console (`https://upserve.app/console/webhooks`), and the management API lives under `/api/runtime/projects/{project_id}/webhooks`. These paths are not part of the `/v1` OpenAPI, and an execution API key cannot change a webhook address or secret.

```bash
# Management API: authenticated with the owner's login token (JWT), not an API key
curl -s -X POST "https://api.upserve.app/api/runtime/projects/$PROJECT_ID/webhooks" \
  -H "Authorization: Bearer $OWNER_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"url":"https://receiver.example/upserve","event_types":["turn.completed","turn.failed","run.completed","run.failed"]}'
```

- Only **HTTPS** addresses are allowed. A Project can have at most 10 endpoints that are not deleted.
- If you omit `event_types`, you receive the `completed`, `failed`, `canceled`, `expired`, and `action_required` events of Turns and Runs. `run.step.completed` marks only a step finishing, not the whole Run.
- The response contains the server generated **secret, shown only once**. Keep it in your receiver's secret store.
- While you rotate the secret (`POST /api/runtime/projects/{project_id}/webhooks/{endpoint_id}/rotate-secret`), verify with **both** the old and the new secret. You may remove the old one after the 20 second maximum send time of requests already sent and the 300 second signature window have passed.
- Changing the address or subscribed events cancels deliveries that were waiting, and past events are not automatically sent to the new address.

### Notification body

The body is JSON of at most 4KiB.

```json
{
  "event_id": "7c2e0d44-0000-4000-8000-000000000008",
  "type": "turn.completed",
  "aggregate_kind": "SESSION",
  "sequence": 4,
  "occurred_at": "2026-10-05T09:00:20+00:00",
  "session_id": "6f1c0a52-0000-4000-8000-000000000001",
  "turn_id": "6f1c0a52-0000-4000-8000-000000000002",
  "status_url": "/v1/sessions/6f1c0a52-0000-4000-8000-000000000001/turns/6f1c0a52-0000-4000-8000-000000000002",
  "outputs_url": "/v1/sessions/6f1c0a52-0000-4000-8000-000000000001/turns/6f1c0a52-0000-4000-8000-000000000002",
  "status": "SUCCEEDED"
}
```

It contains no raw input or result, no files, and no download URLs. `status_url` and `outputs_url` are relative paths that need authentication. A Run notification has `run_id`, with `status_url` set to `/v1/runs/{run_id}` and `outputs_url` to `/v1/runs/{run_id}/outputs`. Step events add `step_id`, and question and approval events add `action_id`.

### Verifying the signature

Every request has an `Upserve-Signature` header.

```text
Upserve-Signature: t=1791190820,v1=<64 hex characters>
signed_bytes = ASCII(timestamp) + "." + raw_body
```

- The signature is the HMAC-SHA256 of the `timestamp`, a `.`, and the **raw request bytes** joined together, with the whole secret string as the key.
- **Do not verify against bytes you re-serialized after parsing the JSON.** Use the bytes exactly as received.
- Compare in constant time (`hmac.compare_digest`, `timingSafeEqual`).

```python
import hashlib
import hmac
import json
import re
import time

def verify(body: bytes, header: str, secrets: list[str], *, now=None) -> dict:
    if len(body) > 4096:
        raise ValueError("Webhook body too large")
    match = re.fullmatch(r"t=([0-9]{1,12}),v1=([0-9a-f]{64})", header)
    if not match:
        raise ValueError("Invalid signature header")
    if abs((time.time() if now is None else now) - int(match[1])) > 300:
        raise ValueError("Expired signature")
    signed = match[1].encode("ascii") + b"." + body
    if not any(hmac.compare_digest(hmac.new(s.encode("ascii"), signed, hashlib.sha256).hexdigest(), match[2])
               for s in secrets):
        raise ValueError("Invalid signature")
    return json.loads(body)
```

The TypeScript version is as follows.

```typescript
import { createHmac, timingSafeEqual } from 'node:crypto';

export function verify(body: Buffer, header: string, secrets: string[], now = Math.floor(Date.now() / 1000)) {
  if (body.length > 4096) throw new Error('Webhook body too large');
  const match = /^t=([0-9]{1,12}),v1=([0-9a-f]{64})$/.exec(header);
  if (!match || Math.abs(now - Number(match[1])) > 300) throw new Error('Invalid or expired signature');
  const supplied = Buffer.from(match[2], 'hex');
  const signed = Buffer.concat([Buffer.from(match[1] + '.', 'ascii'), body]);
  if (!secrets.some((secret) => timingSafeEqual(createHmac('sha256', secret).update(signed).digest(), supplied))) {
    throw new Error('Invalid signature');
  }
  return JSON.parse(body.toString('utf8'));
}
```

### Timestamp window

Reject a request whose `t=` time differs from now by more than **300 seconds (plus or minus 5 minutes)**. Retries and replays also compute a fresh timestamp and signature for each attempt, so your server clock must be accurate. A server with a skewed clock will reject legitimate notifications.

### Deduplicating by event_id

The same event can arrive more than once. Store `event_id` with a UNIQUE constraint in durable storage and drop duplicates. Automatic retries are limited, so eventual receipt is not guaranteed. See [Retries and replay](https://docs.upserve.app/en/developers/webhooks#retries-and-replay) for failed deliveries.

```python
def accept(db, body: bytes, header: str, secrets: list[str]) -> bool:
    event = verify(body, header, secrets)
    with db:
        inserted = db.execute(
            "INSERT INTO webhook_inbox(event_id, body) VALUES (?, ?) ON CONFLICT(event_id) DO NOTHING",
            (event["event_id"], body),
        ).rowcount
    # Return 204 to the sender in both cases: a duplicate is already stored
    return bool(inserted)
```

- Once the signature is verified and the write succeeds, return `2xx` right away. A **duplicate also gets `2xx`**.
- Do heavy work in a separate job after you respond. If handling takes long inside the receiving request, it times out and is retried.
- Keep deduplication IDs for the replay horizon of at most 30 days.
- A retry and a replay of the same event have the same `event_id` and body. Reject a different body that arrives with the same `event_id`.

### Out-of-order delivery

Webhook **delivery order is not guaranteed.** A late progress notification can arrive after the `completed` notification of a finished Run. Compare `sequence` only within the same Session or Run. And do not overwrite your stored state with the `status` of a notification. When a notification arrives, **read the current state with an authenticated API request** and apply that.

```bash
# After accepting an event, read the authoritative state with your API key
curl -s "https://api.upserve.app/v1/runs/$RUN_ID" \
  -H "Authorization: Bearer $UPSERVE_API_KEY"
```

A webhook is not a signal to start work. Do not submit a new execution to recover from a communication problem. Do not follow an address contained in the notification. Build the lookup path yourself from the IDs in the notification and attach your configured API base URL. Do not follow redirects on that request either.

### Retries and replay

- Only an HTTP `2xx` is a success. Other responses and network errors are retried.
- Retries come 1 minute, 5 minutes, 30 minutes, 2 hours, 8 hours, and 24 hours after the first attempt. Including the first, there are at most 7 attempts, and if all fail the delivery status becomes `FAILED`. The list of `FAILED` deliveries acts as the DLQ.
- A failed delivery does not change the success or failure status of the Turn or Run. A successful Run can have a failed delivery.
- Read the delivery history with `GET /api/runtime/projects/{project_id}/webhook-deliveries`, and resend a retained event with `POST /api/runtime/projects/{project_id}/webhook-deliveries/{delivery_id}/replay`. It needs `Idempotency-Key` and is limited to 10 per minute per Project.
- A replay only resends the notification. It does not rerun the original execution.

### Network rules

- Only **HTTPS** is allowed, and the TLS certificate is verified.
- **Redirects (3xx) are not followed** and are recorded as failures. If you moved the address, change the endpoint to the new address.
- DNS is checked again on every attempt, and every address must be a public address. Internal networks, loopback, link-local, metadata addresses, `localhost`, `.local`, and `.internal` are rejected.
- One send takes at most 20 seconds including DNS.
- The failure history keeps only a fixed error code and the numeric HTTP status. The response body of your receiver is not stored.

---

# Reference: Errors and retries

Source: https://docs.upserve.app/en/developers/errors

## Errors and retries

### Error response format

Errors returned by the Runtime API use this format. Errors from an intermediary, such as a network proxy, may use a different format.

```json
{
  "error": {
    "code": "RATE_LIMITED",
    "message": "Request limit exceeded",
    "retryable": true,
    "request_id": "0b7b8f0e-0000-4000-8000-000000000010",
    "details": {"reset_at": "2026-10-05T09:01:00+00:00"}
  }
}
```

| Field | Description |
|---|---|
| `code` | A machine readable error code. Branch on this value, not on `message`. |
| `message` | A human readable English description. It may change. |
| `retryable` | The server's hint on whether sending the same request again can succeed |
| `request_id` | The ID of this request. Quote it when you contact us. |
| `details` | Extra information that depends on the code, for example `reset_at` and `state_url` |

- Every response has an `X-Request-Id` header equal to `request_id` in the body. The server issues a new one for each request.
- 429 and some 503 responses have a `Retry-After` header (seconds).
- Every response is `Cache-Control: no-store`.
- You can send `X-Correlation-Id` for tracing on your side. It is separate from the server generated `request_id`.
- A Turn or Run that was accepted (`202`) and fails later is not an HTTP error. You read it from `error.code` in the detail response.

### Retry principles

1. Retry only errors whose `retryable` is `true` and network errors (dropped connection, timeout).
2. **If `Retry-After` is present, wait that long.** Otherwise use exponential backoff plus random jitter.
3. When you retry a create, input, cancel, delete, or upload request, send **the same `Idempotency-Key` and the same body**. If the request was already accepted, the same receipt comes back, so nothing runs twice.
4. Do not automatically retry an error with `retryable` set to `false`. Follow the error code to fix the request or resolve the cause.
5. If you resend a request whose response you never received under a new key, **the same work can run twice.** Do not change the key when retrying.
6. Put a cap on the number of retries and the total wait.

```python
def post_with_retry(url: str, key: str, body: dict, attempts: int = 5) -> httpx.Response:
    for attempt in range(attempts):
        try:
            response = httpx.post(url, headers={**AUTH, "Idempotency-Key": key}, json=body, timeout=30)
        except httpx.TransportError:
            response = None
        if response is not None and response.status_code < 400:
            return response
        try:
            error = response.json().get("error", {}) if response is not None else {}
        except ValueError:  # a proxy may answer 502/503/504 without the JSON envelope
            error = {"retryable": response.status_code in (429, 502, 503, 504)}
        if response is not None and not error.get("retryable"):
            response.raise_for_status()
        delay = float(response.headers.get("Retry-After", 0)) if response is not None else 0
        time.sleep(delay or min(30, 0.5 * 2 ** attempt))
    raise RuntimeError("gave up after retries")
```

### What each HTTP status means

| Status | Meaning |
|---|---|
| 200, 201 | Success. Reads and close are 200, file upload is 201 |
| 202 | Accepted. Read the result later. |
| 400 | A request error such as a malformed cursor or correlation ID |
| 401 | A key problem. Retrying a revoked key is pointless. |
| 402 | An SU balance or budget problem |
| 403 | Missing scope or permission |
| 404 | The resource does not exist or is outside your access. Existence is not revealed. |
| 409 | Conflict with the current state, for example already running or a key conflict |
| 410 | The content is gone because its retention period passed |
| 413, 415 | Size limit exceeded, unsupported format |
| 422 | A value is outside the allowed range or schema |
| 429 | Call rate or concurrent execution limit |
| 500, 503 | A server side problem. Follow `retryable` and `Retry-After`. |

### Error code table

This table lists the public codes a caller can receive. A code with HTTP status `-` appears not as an HTTP response but only in `error.code` of a Turn or Run detail, and its `retryable` is `false` there. `retryable` describes resending the same request, so it is always `false` on a finished execution. Whether to create a new execution follows the "What to do after a failed execution" table below. A code used both as an HTTP response and in execution details, such as `SESSION_SANDBOX_UNAVAILABLE`, has one row: the status and `retryable` columns describe the HTTP response, and the meaning column also explains what it means in execution details. Codes used only internally are not listed. New codes may be added, so handle an unknown code by `retryable` and the HTTP status.

| Code | HTTP status | retryable | Meaning |
|---|---|---|---|
| `NOT_FOUND` | 404 | false | The resource does not exist or is outside your access. For a Project an operator has blocked, every path returns this. |
| `HTTP_ERROR` | 4xx | false | A routing level rejection, such as a path or method that does not match. |
| `INVALID_API_KEY` | 401 | false | The key is missing, malformed, revoked, or expired. |
| `INSUFFICIENT_SCOPE` | 403 | false | The key does not have the scope for this operation. |
| `ACTING_FORBIDDEN` | 403 | false | Delegated access headers or parameters are not allowed. |
| `WORKFLOW_DATA_DENIED` | 403 | false | The workflow tried to use data outside the data grant it received at publication. |
| `WORKFLOW_DATA_DEPENDENCY_UNRESOLVED` | 422 | false | Data the workflow uses (including the review step's rejection field) is not in the data contract the publisher set at publication, so the Run did not start. Nothing ran. Do not resend the same request; tell the person who published the workflow. |
| `ACTION_NOT_RESOLVABLE_BY_CALLER` | 403 | false | The key lacks explicit actions:approve delegation for this approval. For a work preparation scope confirmation, it lacks works:approve. |
| `ACTION_CONTENT_CHANGED` | 409 | false | Review content changed. Fetch it again and ask for a new human decision. |
| `APPROVAL_CONTENT_UNAVAILABLE` | 409 | false | Review content is unavailable or READ grants are insufficient. |
| `APPROVAL_CONTENT_TOO_LARGE` | 413 | false | Review content exceeds 100 rows or 256 KiB. |
| `INVALID_INPUT` | 400, 422 | false | The request body or input format is invalid. Undeclared fields also land here. |
| `LIMIT_OUT_OF_RANGE` | 422 | false | A limits value is outside the allowed range. Values above the cap are not silently reduced. |
| `INVALID_CURSOR` | 400 | false | after or Last-Event-ID is not a cursor of this resource, or they differ from each other. |
| `INVALID_CORRELATION_ID` | 400 | false | The X-Correlation-Id format is invalid. |
| `INVALID_IDEMPOTENCY_KEY` | 422 | false | Idempotency-Key is outside the 1 to 256 byte UTF-8 limit. A missing header or a basic format error may return `INVALID_INPUT`. |
| `IDEMPOTENCY_CONFLICT` | 409 | false | The same Idempotency-Key was used with a different body or file. Use a new key for a new request. |
| `INPUT_TOO_LARGE` | 413 | false | The JSON request body exceeds 64KiB. |
| `FILE_TOO_LARGE` | 413 | false | The uploaded file exceeds 20MiB. |
| `UNSUPPORTED_MEDIA_TYPE` | 415 | false | The body is not JSON, or it is compressed. |
| `INVALID_FILENAME` | 422 | false | The filename is empty, exceeds 255 bytes, or contains a path separator (slash or backslash) or a control character. As an upload response, fix the name and upload again. In `error.code` of a Turn or Run detail, it means a result file the AI employee made during the execution had a name that breaks this rule, so the execution failed, and `retryable` is `false` there. |
| `UNSUPPORTED_FILE_TYPE` | 415 | false | The filename extension and MIME type are not an allowed pair, or the content is not that format or is unsafe (for example a document with macros, or an encrypted PDF). It comes on upload, or when a Turn input includes a file type the Deployment does not accept. The allowed types are in [limits and data](https://docs.upserve.app/en/developers/limits-and-data). In `error.code` of a Turn or Run detail, it means a result file made during the execution had a type that is not allowed, so the execution failed, and `retryable` is `false` there. |
| `OUTPUT_SCHEMA_MISMATCH` | 422 | false | A value does not match the format or schema set at publication. As an HTTP response, the `input` of a Run creation request does not match the workflow's `input_schema`. In `error.code` of a Turn or Run detail, it means a result did not match the output contract set at publication, so the execution failed, and `retryable` is `false` there. A schema mismatch in a JSON result is first handed back to the AI employee during the execution so it can fix it, and becomes this code only if the execution ends without a fix. |
| `OUTPUT_LIMIT_EXCEEDED` | 422 | false | A value exceeded its size or count limit. As an HTTP response, the `input` of a Run creation request exceeded a JSON limit (depth 16, 10,000 array elements in total). In `error.code` of a Turn or Run detail, it means a result exceeded its size or count limit, so the execution failed, and `retryable` is `false` there. It is closed as a failure, not silently truncated. |
| `TOO_MANY_FILES` | 422 | false | More than 20 input files, or the same file was listed twice. |
| `FILE_EXPIRED` | 410 | false | The input file is not ready or has expired. Upload it again. |
| `ARTIFACT_EXPIRED` | 410 | false | The retention period has passed, so the result file can no longer be fetched. In the result list, that item shows `availability: EXPIRED` with this `error.code`. |
| `RUN_EXPIRED` | 410 | false | The Run's retention period (`retention_days`) has passed, so its details, results, and `usage` can no longer be read. Do not run it again for this; fetch what you need within the retention period. |
| `PROJECT_STORAGE_LIMIT` | 413 | false | The Project file storage (500MiB) or the organization's remaining capacity was exceeded. |
| `RUN_STORAGE_LIMIT` | 413 | false | The file total of one execution (100MiB) was exceeded. |
| `REVISION_CONFLICT` | 409 | false | The work or preparation changed after you read it. Read it again and send against the current state. |
| `PREPARATION_IN_PROGRESS` | 409 | false | A preparation for the same work is already in progress. Read the preparation in details.preparation_id. |
| `INVALID_TRANSITION` | 409 | false | The preparation does not accept this request in its current state, for example because it ended or its confirmation deadline passed. |
| `QUESTION_NOT_FOUND` | 409 | false | That preparation question is not open. Read the preparation again. |
| `PACKAGE_CHANGED` | 409 | false | The setup the person reviewed is no longer the candidate. Show the new question and ask again. |
| `INVALID_SPEC` | 422 | false | The work description breaks a rule. See details.reason. |
| `INVALID_REQUEST` | 422 | false | The work preparation request breaks a rule. See details.reason. |
| `SESSION_BUSY` | 409 | false | The Session already has a running Turn. Send after you confirm it ended. |
| `SESSION_CLOSED` | 409 | false | A closed Session does not accept input or files. |
| `SESSION_EXPIRED` | 410 | false | The retention period of the Session content has ended. |
| `SESSION_UPDATING` | 503 | true | The Session is being updated. Resend with the same Idempotency-Key. |
| `SESSION_SANDBOX_UNAVAILABLE` | 503 | true | The Session execution environment could not be prepared right now. As an HTTP response, try again shortly. In `error.code` of a Turn or Run detail, it means the execution environment preparation step did not finish in time before work started, so the Turn failed, and `retryable` is `false` there. When this happens in a workflow step, the Run usually ends with this code too. If a request sent during preparation could not be confirmed, the Run stays `EXTERNAL_EFFECT_UNKNOWN` until usage is confirmed. Running out of time while waiting for an earlier execution is still `EXECUTION_TIMEOUT`. The request itself is fine, so create a new execution later. |
| `DEPLOYMENT_UNAVAILABLE` | 409 | false | This Deployment cannot accept this operation now. Check its status. |
| `TEAM_PORTAL_MANAGED` | 409 | false | The AI employee behind this Deployment now works only through its company's work portal. A new Session or Turn is refused; replaying a request already accepted with the same Idempotency-Key still returns its receipt. Make the request in the work portal (details.portal_url, null when unknown). |
| `ORG_ENDED` | 403 | false | This organization's service has ended, so new Sessions, Turns and works are refused. An accepted execution that has not started also ends with this code. Contact your account manager. |
| `WORKFLOW_UNAVAILABLE` | 409 | false | The workflow is not published, is stopped, or cannot be started through the API (for example a workflow that only starts from mail), so Run creation (`POST /v1/workflows/{workflow_id}/runs`) is refused. `GET /v1/workflows/{workflow_id}` reports this state not as an error response but as `available: false` and `error.code` in a 200 body. If the workflow is stopped during a Run, the Run ends `CANCELED` with this value in `error.code` of the Run detail. Try again after the publisher publishes or turns on the workflow again. |
| `WORKFLOW_MANAGED_SESSION` | 409 | false | This is an internal Session used by a workflow. Use the Run paths. |
| `RUN_TERMINAL` | 409 | false | The Run already has a settled outcome. |
| `ACTION_EXPIRED` | 409 | false | The answer deadline of the question has passed. |
| `ACTION_CANCELED` | 409 | false | The execution no longer waits for this question. |
| `MINIMUM_SU_REQUIRED` | 402 | false | File operations need an account balance of at least 50 SU. 50 SU is not charged. |
| `INSUFFICIENT_SU` | 402 | false | There is not enough available SU. |
| `BUDGET_EXCEEDED` | 402 | false | The budget of this execution is exhausted or closed. |
| `PROJECT_BUDGET_EXCEEDED` | 402 | true | The Project monthly spend limit was exceeded. It works again when the next month (UTC) begins. |
| `RATE_LIMITED` | 429 | true | The call rate limit was exceeded. Wait for Retry-After. |
| `CONCURRENCY_LIMIT` | 429 | true | The Project concurrent execution limit was exceeded. Try again after an execution ends. |
| `SOURCE_UNAVAILABLE` | 503 | true | The organization data store used to check the workflow input cannot be reached right now, so Run creation (`POST /v1/workflows/{workflow_id}/runs`) was refused. No Run was created. Resend later with the same Idempotency-Key. If it continues, tell the publisher. When it shows as `error.code` in Run details, a workflow step's tool could not open or read the data it needed (a file, a site, or a record in the organization data store) and rejected the work; then `retryable` is `false`. If the input itself lacks the needed content, the code is `INPUT_MISSING_FIELD` instead. |
| `BILLING_UNAVAILABLE` | 503 | true | The billing account could not be checked right now. Try again shortly. |
| `ARTIFACT_NOT_READY` | 409 | true | The file is not ready yet. Try again shortly. |
| `ARTIFACT_UNAVAILABLE` | 503 | true | The stored file cannot be read right now. Try again. |
| `STORAGE_UNAVAILABLE` | 503 | true | File storage is unavailable right now. Try again. |
| `EVENT_CURSOR_EXPIRED` | 410 | false | The event cursor has expired. Recover with the addresses in details. |
| `OUTPUT_MANIFEST_UNAVAILABLE` | 503 | true | The result list cannot be read right now. Try again. |
| `INTERNAL_ERROR` | 500 | false | An internal server error. Contact us with the request_id. |
| `EXECUTION_TIMEOUT` | - | false | The Turn failed because it exceeded the execution time limit. |
| `QUEUE_TIMEOUT` | - | false | The execution did not start within the queue time limit and expired. |
| `RECOVERY_EXHAUSTED` | - | false | The server tried several recoveries but could not finish. |
| `RUN_DEADLINE_EXCEEDED` | - | false | The whole Run deadline was reached first and the Run expired. |
| `EXTERNAL_EFFECT_UNKNOWN` | - | false | It stopped because the outcome of a write to an external system could not be confirmed. Check the outcome yourself. It is not rerun automatically. |
| `ACTION_REQUIRED_UNSUPPORTED` | - | false | A human answer or approval became necessary that the API cannot handle: a secret value input, a question inside a sub task, a step the AI holds for itself, or a prepared ERP approval or email confirmation. |
| `CAPABILITY_DENIED` | - | false | It tried to use a tool or capability that was not allowed at publication. |
| `SESSION_RESOURCES_NOT_READY` | - | false | It called a tool allowed by the publication that this stage does not yet support. |
| `ARTIFACT_PREPARATION_TIMEOUT` | - | false | Result file preparation exceeded its deadline. |
| `ARTIFACT_PREPARATION_FAILED` | - | false | A result file was not ready or had already expired when the execution ended, so it could not be returned. |
| `OUTPUT_URL_INVALID` | - | false | A URL result is not a public HTTPS address. Internal network addresses and addresses that carry login details, signatures, or tokens are refused too. |
| `OUTPUT_CONTAINS_CREDENTIALS` | - | false | A result (value, filename, file content, or URL) contains a credential pattern such as a key or password, so it was not returned. |
| `OUTPUT_PATH_DENIED` | - | false | It tried to return a file from outside the Session attachments folder as a result. |
| `OUTPUT_MISSING` | - | false | A result marked required at publication was not produced. |
| `EXECUTION_FAILED` | - | false | The execution failed because of an unexpected error. |
| `CANCELED` | - | false | The execution stopped because of a cancel request. |
| `AUTHORIZATION_REVOKED` | - | false | The execution was canceled because the key was revoked or expired, or its scope, the Deployment, or an account connection the Deployment uses became unusable. |
| `SESSION_DELETED` | - | false | The Session was deleted, so its running Turn was canceled. |
| `RUNTIME_CONTEXT_MISMATCH` | - | false | The execution failed because the Session was not in a state that can run it. |
| `USAGE_PENDING` | - | false | The execution could not continue because earlier usage could not be confirmed as settled. |
| `EXECUTION_INCOMPLETE` | - | false | The execution stopped before it reached a finished answer. For example, it was cut off midway when the server restarted. Work the AI employee did before it stopped may already have happened. |
| `NO_REPORT` | - | false | The AI employee in a workflow step finished but did not report its result. It appears only on workflow Runs. Work that step did may already have happened. |
| `SESSION_CONTEXT_LIMIT` | - | false | The conversation built up in the Session plus this input is larger than what can be handled at once. This API does not shrink older conversation automatically, so sending it to the same Session again gives the same result. |
| `CHECKPOINT_UNAVAILABLE` | - | false | The execution state store could not be read right now, so the execution could not start or continue. |
| `CHECKPOINT_MISSING` | - | false | It tried to continue an interrupted execution, but there was no saved point to continue from. Work the AI employee did before the interruption may already have happened. |
| `CHECKPOINT_MISMATCH` | - | false | The execution state saved in the Session did not match this Session or Turn, so it could not run. |
| `RUNTIME_CONTEXT_MISSING` | - | false | Inside the server, the execution lost track of its Session or Turn and stopped. The cause is on the server side. |
| `BILLING_CONTEXT_UNAVAILABLE` | - | false | The billing details of the organization the Deployment belongs to could not be confirmed, so the execution could not start. |
| `BILLING_CONTEXT_CHANGED` | - | false | After the execution was accepted, who pays for the Deployment (organization, billing method, or paying person) changed, so the execution stopped. |
| `FUNDING_UNAVAILABLE` | - | false | The SU reserved for the execution could not be debited, so the execution could not continue. The server has to reconcile the settlement. |
| `SETTLEMENT_CONFLICT` | - | false | Two different settlement records arrived for the same usage, so the execution stopped. The cause is on the server side. |
| `COST_BOUND_EXCEEDED` | - | false | The actual cost of one operation exceeded the upper bound reserved for it, so it could not be settled. The cause is on the server side. |
| `DEFINITION_CHANGED` | - | false | While it was being processed, the data format this work uses changed in an incompatible way, so it stopped. The same execution keeps the format from acceptance and cannot continue; a new execution uses the changed format. |
| `INPUT_MISSING_FIELD` | - | false | Workflow step reject code. An input value the step needs was empty, so the step rejected it. |
| `INPUT_INVALID_FORMAT` | - | false | Workflow step reject code. An input value had an unexpected format (date, number, code, and so on), so the step rejected it. |
| `INPUT_DUPLICATE` | - | false | Workflow step reject code. It overlaps a target that was already processed or is being processed, so the step rejected it. |
| `SOURCE_ALREADY_PRICED` | - | false | Workflow step reject code. The price cells of the file to quote were already filled on half or more of its lines, so the step did not make a quotation. |
| `AMBIGUOUS_MATCH` | - | false | Workflow step reject code. The input alone could not narrow the target down to one (several candidates or none), so the step rejected it. |
| `RULE_VIOLATION` | - | false | Workflow step reject code. The input has a valid format but breaks a business rule (policy, limit, or condition), so the step rejected it. |
| `EXTERNAL_SERVICE_ERROR` | - | false | Workflow step reject code. A connected external service returned an error or did not respond, so the step could not finish. |
| `OUTPUT_VALIDATION_FAILED` | - | false | Workflow step reject code. A result the step produced did not pass validation. |
| `SYSTEM_ERROR` | - | false | Workflow step reject code. Processing could not move on between steps. For example, the result of one step did not fit the input form of the next step. |
| `STALE_REFERENCE_DATA` | - | false | Workflow step reject code. Reference data the work uses is older than its promised period, so the step stopped without reading it. |
| `SEND_BACK_CAP` | - | false | Workflow step reject code. A result the review step rejected could not be sent back to the earlier step to be redone, so it stopped. The rejected result was not passed to the next step. |
| `BILLING_INACTIVE` | - | false | Workflow step reject code. During the execution the organization's service use stopped being open, so the next step could not start. |
| `AGENT_UNAVAILABLE` | - | false | Workflow step reject code. During the execution the AI employee for the next step was turned off or deleted, so the next step could not start. |

### What to do after a failed execution

Once a Turn or Run ends as `FAILED`, `CANCELED`, or `EXPIRED`, that execution does not come back. To try again, **create a new Turn or Run with a new `Idempotency-Key`.** This differs from the retry above, which resends an unanswered request with the same key. Reusing the finished execution's key returns that finished execution's receipt again.

Follow the order below even when an AI tool makes the calls for you. A new execution costs money again.

If an execution failed partway, work the AI employee did before that (sending mail, writing to an external system, and so on) may already have happened. If the Deployment or workflow does that kind of work, check that system before any new execution, whatever the code. This matters most for the codes under "Once more, after checking", which only appear after the execution has made progress.

| Decision | Codes | Next step |
|---|---|---|
| Once more, later | `QUEUE_TIMEOUT`, `RECOVERY_EXHAUSTED`, `EXECUTION_FAILED`, `USAGE_PENDING`, `ARTIFACT_PREPARATION_TIMEOUT`, `ARTIFACT_PREPARATION_FAILED`, `SESSION_SANDBOX_UNAVAILABLE`, `CHECKPOINT_UNAVAILABLE`, `RUNTIME_CONTEXT_MISSING`, `BILLING_CONTEXT_UNAVAILABLE`, `FUNDING_UNAVAILABLE`, `SETTLEMENT_CONFLICT`, `COST_BOUND_EXCEEDED` | Wait, then create one new execution with the same input. If it ends with the same code again, stop and contact us with the execution ID. |
| Once more, after checking | `EXECUTION_INCOMPLETE`, `NO_REPORT`, `CHECKPOINT_MISSING` | The execution stopped partway or after running to the end, so work the AI employee did (sending mail, writing to an external system, and so on) may already have happened. If the Deployment or workflow does that kind of work, first check the result in that system, and create one new execution with the same input only if it did not happen. If it ends with the same code again, stop and contact us with the execution ID. If `NO_REPORT` repeats, tell the person who published the workflow. |
| After changing conditions | `EXECUTION_TIMEOUT`, `RUN_DEADLINE_EXCEEDED`, `BUDGET_EXCEEDED`, `INSUFFICIENT_SU` | Shrink or split the input, and raise the deadline or budget within the range in [limits and data](https://docs.upserve.app/en/developers/limits-and-data) or add SU (buy more or move up a plan), then create a new execution. Do not resend right away under the same conditions. |
| Publishing settings | `OUTPUT_SCHEMA_MISMATCH`, `OUTPUT_LIMIT_EXCEEDED`, `OUTPUT_MISSING`, `OUTPUT_PATH_DENIED`, `CAPABILITY_DENIED`, `SESSION_RESOURCES_NOT_READY`, `ACTION_REQUIRED_UNSUPPORTED`, `WORKFLOW_UNAVAILABLE` | The caller often cannot fix these. Do not repeat the same input. Tell the person who published the Deployment or workflow. If your input made the result exceed a limit, shrink the input and create a new execution. For `WORKFLOW_UNAVAILABLE`, create a new Run only after the workflow is published or turned on again. |
| Check the result content | `OUTPUT_URL_INVALID`, `OUTPUT_CONTAINS_CREDENTIALS`, `INVALID_FILENAME`, `UNSUPPORTED_FILE_TYPE` | A result the AI employee made broke a public result rule. Check that your input did not ask for an internal address, a credential, or a file type or name that is not allowed in the result, then create one new execution with the corrected input. If it ends with the same code again, tell the person who published the Deployment or workflow. |
| Step reject: check the input | `INPUT_MISSING_FIELD`, `INPUT_INVALID_FORMAT`, `INPUT_DUPLICATE`, `SOURCE_ALREADY_PRICED`, `AMBIGUOUS_MATCH`, `RULE_VIOLATION` | A workflow step rejected the work because of the input or a business rule. Sending the same input again gives the same result. Create a new Run only after fixing the missing value, the format, or the details that narrow the target down to one. For `INPUT_DUPLICATE`, first check whether it was already processed, and if it was, do not run it again. For `SOURCE_ALREADY_PRICED`, create a new Run with the original request file whose prices are empty. |
| Step reject: check the connection | `EXTERNAL_SERVICE_ERROR`, `SOURCE_UNAVAILABLE` | A workflow step could not reach a connected external service, or the step's tool could not open or read the data it needed. Wait, then create one new Run with the same input. If it ends with the same code again, tell the person who published the workflow so they check the connection or the data. |
| Step reject: tell the publisher | `OUTPUT_VALIDATION_FAILED`, `SYSTEM_ERROR`, `SEND_BACK_CAP`, `STALE_REFERENCE_DATA`, `BILLING_INACTIVE`, `AGENT_UNAVAILABLE` | The cause is something the caller cannot fix, such as the workflow setup, reference data, the organization's service status, or the AI employee assigned to a step. Do not repeat the same input; tell the person who published the workflow. `OUTPUT_VALIDATION_FAILED` and `SYSTEM_ERROR` can differ from one execution to the next, so you may try one new Run. |
| Check who pays | `BILLING_CONTEXT_CHANGED` | The organization or billing method on the publishing side of the Deployment changed. Create a new execution only after the publisher confirms that the new payer may cover this cost. A new execution is accepted under the new terms. |
| New, in the current format | `DEFINITION_CHANGED` | There is no way to continue the same execution. Create one new execution. If it is refused because the input no longer fits the changed format, read the workflow's input format again with `GET /v1/workflows/{workflow_id}`, and ask the publisher if you do not know what changed. |
| Check permissions | `AUTHORIZATION_REVOKED` | Check the key, its scope, the Deployment status, and the publisher's account connections. Create a new execution only after you receive a new key or permission or the connection is restored. |
| In a new Session | `RUNTIME_CONTEXT_MISMATCH`, `CHECKPOINT_MISMATCH` | Create a new Session and run there. If it repeats, contact us with the execution ID. |
| In a new Session, with less input | `SESSION_CONTEXT_LIMIT` | Do not send it to the same Session again. Start a new Session with a short summary of only what needs to carry over, or shrink or split the input and files. If it came from a workflow Run, shrink the input and create a new Run; if it repeats, tell the person who published the workflow. |
| Do not run again | `EXTERNAL_EFFECT_UNKNOWN` | The external system may already have been written to. Do not create a new execution until you check the result in that system yourself. |
| Intended end | `CANCELED`, `SESSION_DELETED` | Whoever asked for the cancel or deletion decided this. Create a new execution only if that decision changes. |

For a code not in this table, do not run again. Stop and tell a person.

**For a Run, decide by `error.code` of the Run details, not by the codes on result items.** When a Run stops partway (exceeded budget, deadline, cancel, and so on), each result it could not make carries `OUTPUT_MISSING`, but that is a consequence of the stop; the cause is the Run `error.code`. For example, if the Run is `BUDGET_EXCEEDED` and an item is `OUTPUT_MISSING`, follow the "After changing conditions" row and do not report it to the publisher. While it stops, the Run briefly goes through `CANCEL_REQUESTED`.

The codes in the "Step reject" rows appear only on workflow Runs. They carry the reason a workflow step rejected the work into `error.code` of the Run details.

When a result the AI employee produces during an execution breaks a public result rule, the execution ends as a failure right there. Among result format errors, only a schema mismatch in a JSON result is handed back to the AI employee during the execution to fix. In a workflow that returns only some results instead of failing (`PARTIALLY_SUCCEEDED`), the same code stays in `error.code` of the failed result item.

A failed organization work preparation is not an HTTP error either. Its reason is in the preparation's `reason_codes`, and what to do next is in [organization works](https://docs.upserve.app/en/developers/works).

---

# Reference: Limits and data

Source: https://docs.upserve.app/en/developers/limits-and-data

## Limits and data

These are the default limits. Values may change. Raising limits is not supported. You can **only lower** them. Check [openapi.json](https://docs.upserve.app/runtime-api/openapi.json) and `rate_limits` in the Deployment detail for current values.

### Call rates

| Class | Limit | Requests it covers |
|---|---|---|
| Accept | 10 per minute | Creating a Session, Turn, or Run; file uploads; `POST /v1/works`; and preparation answers |
| Read | 60 per minute | Every other request (reads, cancel, close, delete, and download included) |

- Key and Project limits apply separately. Requests for resources belonging to a Deployment also count against that Deployment's limit. The lowest applicable limit is reached first. You can set lower limits on a key or a Deployment.
- When exceeded you get `429 RATE_LIMITED` with `Retry-After` (seconds) and `details.reset_at`.
- Poll at 2 to 5 second intervals, and use [SSE or webhooks](https://docs.upserve.app/en/developers/events) where you can.

### Concurrent executions

- A Project runs **2** executions at a time. Executions already accepted wait within the limit, and an acceptance that goes over the limit returns `429 CONCURRENCY_LIMIT`.
- A Session runs only one Turn at a time. ([Sessions and Turns](https://docs.upserve.app/en/developers/sessions-and-turns))

### SU budgets

| Scope | Default limit |
|---|---|
| One Turn | 100 SU |
| One Run (child Turns summed) | 100 SU |
| Project per month | 30,000 SU |

- You can set a lower cap for one Turn or Run with `limits.max_su` in the request. Above 100 returns `422 LIMIT_OUT_OF_RANGE`.
- The Project monthly limit is counted per calendar month in UTC. Going over returns `402 PROJECT_BUDGET_EXCEEDED`. There is no Project daily limit (the old 1,000 SU per day limit is gone).
- Model, search, execution environment, and file storage and transfer costs are all summed. Retries and sub-task costs are added only once each.
- Cost is reserved before a call and settled afterward. Before settlement `usage.status` is `PENDING`.
- File upload and download can start when the account balance is at least 50 SU. 50 SU is not charged as a fixed fee. Only actual usage is consumed.

### Input and output sizes

| Item | Limit |
|---|---|
| JSON request body | 64KiB |
| metadata | 16 keys, key 1 to 64 characters, string value 512 characters |
| Idempotency-Key | 1 to 256 bytes |
| TEXT result | 64KiB. Larger is delivered as a file |
| JSON result | Inline up to 64KiB and 100 array elements in total. Larger is delivered as a file. Overall 10MiB, 10,000 array elements, depth 16 |
| Input files | 20MiB each, 20 per input |
| File types | .txt, .md, .markdown, .csv, .json, .pdf, .png, .jpg, .jpeg, .webp, .docx, .xlsx, .pptx. The extension and MIME type must match. A Deployment can narrow the accepted types further. |
| Result files | 10MiB each, 10 per execution |
| Files of one execution in total | 100MiB |
| Project file storage | 500MiB (the organization's remaining storage also applies) |
| List responses | At most 100 items and 256KiB. Default 50 |
| Webhook body | 4KiB |
| Download URL lifetime | At most 60 seconds |
| Result file preparation | At most 300 seconds after the execution ends |

A value over a limit is rejected with an error, never silently truncated.

### Retention

| Target | Period |
|---|---|
| Idempotency receipt | Deleted after the replay window (24 hours, or until the execution ends if it has not ended by then). The exact time is in `idempotency_expires_at`. |
| Session | 30 days idle (default). Deleting a Session also deletes its Events, Items, and files. |
| Files uploaded to the Project ahead (`POST /v1/files`) | 24 hours after upload. They expire unless used as Turn or Run input within that time. |
| Session files | 30 days from upload or creation. A file uploaded ahead and used as Turn input gets 30 days from that point. Using the Session does not extend it, so a file can expire before its Session. |
| Run files | Until the Run deadline and the end of the Run content retention. A file uploaded ahead and used as Run input follows this period. |
| Event and Item content | At most 30 days |
| Run content | 30 days after the Run ends by default. You can shorten it with `retention_days` (1 to 30) in the request. |
| Webhook dedup IDs | At most 30 days (the replay horizon) |
| Copies kept by the AI model provider | Up to 30 days, depending on the published version's model tier, to process follow-up requests in the same conversation. Deleting the Session cannot remove them early, and they are not used for model training. |

The retention and deletion commitments are defined in [Terms of Service Section 2-6](https://upserve.app/terms#runtime-api)(8) and [Privacy Policy Section 6](https://upserve.app/privacy#retention). Where this table differs, the Terms and the Privacy Policy prevail.

Reading does not extend retention. Expired content is hidden at read time, so it is not visible even if the cleanup job is late. After expiry you get `410` (`SESSION_EXPIRED`, `EVENT_CURSOR_EXPIRED`, `FILE_EXPIRED`, and so on). The exact expiry time of a file is in `expires_at` of the file response. Move results you need into your own storage before they expire.

### Deletion

- `DELETE /v1/sessions/{session_id}` and `DELETE /v1/runs/{run_id}` are **acceptances of a delete** (202). As soon as you get the response, the content read paths are blocked and a running execution is canceled.
- **Physical reclamation** of stored inputs, outputs, files, and conversation records proceeds **asynchronously afterward**. The completion time is not guaranteed.
- Resending a delete with the same `Idempotency-Key` returns only a delete receipt with no content.
- The minimum identifiers needed for billing and security audit (IDs, times, amounts, reasons) are kept separately, without content. Cost records are destroyed after 5 years and security audit records after 1 year (or once an ongoing security incident investigation ends) ([Privacy Policy Section 6](https://upserve.app/privacy#retention)). A cost record whose settlement has not finished is kept until it is settled, regardless of that period.
- Requesting a delete does not undo external effects that already happened.
- For your customers' personal data in inputs, your organization is the controller and UpServe is its processor. See [Terms of Service Section 2-6](https://upserve.app/terms#runtime-api)(9) and (10) for the scope of the entrustment and the acceptable use policy.

### Security and data boundaries

- **Isolation:** Execution is separated by Project, Deployment, and Session. The memory, files, and search index of one Session are not copied into another Session or the original employee.
- **Frozen publication:** A Deployment freezes the instructions, skills, tools, and model tier at publication. Editing the original employee has no effect, and a new version takes effect only when you publish again.
- **The caller is not the owner.** An execution called through the API does not use the organization owner's personal memory (owner memory), stored secrets (vault), or logged-in browser. Key scopes alone never widen this.
- **Risky tools blocked:** A tool that is not allowed cannot be called (`CAPABILITY_DENIED`), and arbitrary risky tools are blocked by default. Publication is rejected if the content contains secret values.
- **Sanitized public responses:** Events and results do not include internal reasoning, raw tool arguments and results, or owner information. Contact details and credential patterns in free text are masked. This does not detect every kind of private information, so do not put unnecessary personal data in inputs.
- **Webhooks:** They send neither raw results nor file addresses, and they never send to internal network addresses.
- **Key storage:** Keep keys and webhook secrets only in your servers' secret store.

---

# Not included here

- [Versioning and changelog](https://docs.upserve.app/en/developers/changelog)

---

# The person's request

The person's request follows. If it is empty, start with step 1 of the instructions above.
