> ## Documentation Index
> Fetch the complete documentation index at: https://docs.duvo.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Writing a code step

> Write the Python program a code step runs, and reach Queues, Connections, Policy, and files through the duvo client.

A code step is a step in an automation that runs a Python program instead of following an AOP (Agent Operating Procedure). Use one when the work is a calculation or a rule rather than a judgment: totalling invoice lines, matching records, routing on a threshold. The same input always gives the same result.

The program reaches Duvo's Queues and Connections through the `duvo` client. It ships with every Run, so there is nothing to install.

## Start here

```python theme={"dark"}
import duvo

QUEUE_ID = "your-queue-id"  # the Queue this step works from

case = duvo.claim_case(queue_id=QUEUE_ID)["case"]
if case is None:  # a Run not bound to a Case found the Queue empty
    raise SystemExit(0)

total = sum(line["amount"] for line in case["data"]["lines"])

duvo.complete_case(case_id=case["id"], reason=f"Reconciled at {total}")
```

`print()` output and anything written to stderr appear in the Run detail while the program works, in order with the tool calls around them.

## What a step is given

Each Run hands the program one input. Read it from `duvo`:

```python theme={"dark"}
duvo.execution        # run_id, code_step_id, build_id, attempt, started_at, timeout_ms
duvo.case_ref         # {"case_id", "queue_id"} on a Run bound to a case, else None
duvo.trigger          # {"source", "trigger_type", "payload_version"} for an event trigger, else None
duvo.trigger_payload  # the structured item that started the Run, else None
duvo.policy           # the Policy answers this step reads, keyed by question key
duvo.files            # [{"name", "path"}] for the files attached to the step
duvo.input.as_dict()  # the whole input
```

* **`case_ref`, `trigger` and `trigger_payload` are `None` when they don't apply**, so the program can tell what started it: `case_ref` for a Run bound to a Case, `trigger` for one an event started. `policy` is `{}` and `files` is `[]` when the step has none.
* **`case_ref` is a reference, not a copy.** Read the Case with `claim_case`.
* **Make repeated work safe with `execution.run_id`.** A retry reuses the same Run, so `run_id` stays the same across attempts. Use `execution.attempt` for logging only.

### Event triggers

A step started by an event trigger, such as a new Gmail message or a Linear webhook, reads the item from `duvo.trigger_payload`:

```python theme={"dark"}
if duvo.trigger["trigger_type"] == "new_email":
    message_id = duvo.trigger_payload["message_id"]
```

* **Branch on `trigger_type`, not `source`.** One Connection can own several unrelated triggers, each with its own fields.
* **A payload holds what the trigger already had.** Gmail's payload is the message and thread IDs, not the email itself. Read the rest through the Connection.
* **A capped payload says so.** When a long body or a wide row is cut, the payload carries `truncated: true`. Check it if the step must not act on a partial record.
* **`payload_version` changes when a field is renamed or removed.** Check it if the step must not run against a shape it wasn't written for.

### Policy

`duvo.policy` holds the [Policy](https://docs.duvo.ai/cli/policy.md) answers this step reads, resolved when the Run started. Changing an answer takes effect on the next Run, without editing the program. A Run doesn't start while one of those questions is unanswered.

```python theme={"dark"}
threshold = duvo.policy["approval_threshold"]
```

### Files

Files attached in the step's **Files** setup are in the sandbox before the program starts. Open one by the name it was attached under:

```python theme={"dark"}
import csv

with open(duvo.file_path("vendors.csv")) as handle:
    vendors = list(csv.DictReader(handle))
```

Every attached file is there, or the Run fails before the program starts. `file_path` raises an error for a name the step doesn't have, rather than returning `None`. Use `duvo.files` to list them.

## Queues

```python theme={"dark"}
duvo.claim_case(queue_id=...)
duvo.update_case(case_id=..., data={...})      # replaces the Case's data
duvo.complete_case(case_id=..., reason=...)   # also fail_case and postpone_case
duvo.add_cases(queue_id=..., cases=[{"title": ..., "data": {...}}])
```

`update_case` replaces the Case's data rather than merging into it, so send every field the Case should keep. On a Queue with a Case schema, pass `json_data` instead of `data`.

`list_cases`, `list_labels` and `read_case_file` exist on both sides of a Queue, so reach them through the side you mean:

```python theme={"dark"}
duvo.consumer.list_cases(...)          # the Queue this step works from
duvo.producer.read_case_file(...)      # the Queue this step adds Cases to
```

`attach_case_file` is on the consumer side only, for the Case this Run claimed. To attach a file to a Case you add, list it under that Case's `attachments`, as `{"file_path": ...}`, in `add_cases`.

To hand a Case to one of several next steps from code, see [Let the code decide](https://docs.duvo.ai/user-guide/assignment-features/assignment-handover.md#let-the-code-decide).

## Connections

Every Connection attached to the step is under `duvo.connections`:

```python theme={"dark"}
rows = duvo.connections.snowflake.execute_read_query(query="select po_number from ap.open_pos")
duvo.connections.gmail.send_email(to=["ap@example.com"], subject="Reconciled", body=summary)
```

* **The step's Connections row shows the name to type** for each Connection.
* **Hyphens become underscores**: `microsoft-calendar` is `duvo.connections.microsoft_calendar`.
* **Two Connections of the same kind each get an ID suffix**, such as `gmail_<id>`, and neither keeps the short name. That way a program never sends from the wrong mailbox by accident. `duvo.connections.names` lists the names that work.
* **Arguments are keywords, passed through unchanged.** The tool decides what it takes. A wrong tool name or argument comes back as an error from the Connection.
* **A Connection the Run doesn't have fails the call straight away** and names the ones it does have. Nothing is skipped quietly.

To reach a Connection by a name held in a variable, or to call a tool or pass an argument whose name isn't a valid Python name:

```python theme={"dark"}
duvo.connections[connection_name].call(tool_name, **arguments)
```

No Connection credential is in the sandbox. Duvo checks every tool call against the Connections the Run started with, so editing the step during a Run can't widen what it reaches.

### Check which account a call reaches

For a call that must reach one specific account, such as a NetSuite sandbox rather than production, name the account's origin:

```python theme={"dark"}
receipt = duvo.connections.netsuite.call_on_origin(
    "https://1234567-sb1.suitetalk.api.netsuite.com",
    "ns_getRecord", recordType="vendor", recordId="123",
)
vendor = receipt["result"]
proof = receipt["verification"]  # expected_origin, server, tool, tool_call_id, run_id, observed_at
```

* Use an HTTPS origin only: no credentials, port, path, query or fragment. A trailing slash is allowed.
* Duvo checks the Connection against the origin before the call and keeps every request and redirect on that origin.
* If the origin doesn't match, the error says the tool wasn't sent.
* If the connection drops or no verification comes back, the outcome is unknown. Check the record before you retry a write. Duvo doesn't retry these calls for you.

## One file or several

A new code step is one file, `main.py`, run with `python main.py`.

For a larger program, select **Add file** above the editor. The step becomes a file list: your program stays in `main.py`, and you can add modules next to it and import them as usual. The step still runs with `python main.py`; the line under the editor shows the command.

To run a different command, set it with the [Duvo CLI](https://docs.duvo.ai/cli/managing-assignments.md) or the API.

## How a Run ends

| What the program does | The Run |
| - | - |
| Exits with code 0 | Completes |
| Exits with another code, or raises an uncaught exception | Fails |
| Runs past its time limit (10 minutes by default) | Fails |
| Exits 0 without handing over, when a handover is **required** | Fails |

When a Run fails, the traceback is in the Run detail.

## The sandbox

* Python 3 in a fresh sandbox for each Run, working directory `/workspace/code-step`.
* A step installs nothing while it runs. It has the sandbox's own libraries, among them `pandas`, `numpy`, `pyarrow`, `requests`, `openpyxl`, `python-docx` and `python-pptx`.
* A Run has 10 minutes by default.

## Errors

Every error derives from `duvo.DuvoError` and fails the Run unless the program catches it.

| Error | When |
| - | - |
| `DuvoUnknownConnectionError` | `duvo.connections.<name>` names a Connection the Run doesn't have. Also an `AttributeError` |
| `DuvoConnectionNotConnectedError` | The Run has no such Connection, or it stopped working during the Run |
| `DuvoToolError` | The tool ran and reported a failure of its own |
| `DuvoInvalidRequestError` | The call was refused, most often for going over 256 KB of arguments |
| `DuvoRateLimitedError` | Too many calls from this Run in a short time, or the Connection's service is limiting it |
| `DuvoRelayError` | The call was refused, timed out, couldn't connect, or returned more than 5 MB |
| `DuvoHandoverNotAllowedError` | `request_handover` named a step outside the step's handover options |
| `DuvoHandoverAlreadyRequestedError` | A second `request_handover` named a different step |
| `DuvoConfigurationError` | The program isn't running as a code step, or `file_path` named a file the step doesn't have |

## Limits

| Limit | Value |
| - | - |
| One program file | 128 KB |
| All program files | 4 MB, across at most 200 files |
| Files attached to the step | 25 MB each, 50 MB and 50 files in total |
| Arguments in one tool call | 256 KB |
| One tool call's response | 5 MB |
| Time for one Run | 10 minutes by default |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.