Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 18 additions & 81 deletions src/content/docs-es/runs.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -302,106 +302,43 @@ Un **token** es lo que conviene darle a un script que solo gestiona runs. No sir
- Cada uno caduca a los **30, 90 o 365 días**, o nunca.
- Puedes revocar cualquiera en cualquier momento.

Para crear runs sigue haciendo falta un plan con inferencia, uses la credencial que uses.
Para crear runs sigue haciendo falta un plan con inferencia, uses la credencial que uses. La [referencia de la API](/es/docs/api#description/platform-tokens) indica qué credencial acepta cada endpoint.

<Callout title="Un agente no puede lanzar runs por su cuenta" variant="warning">
La clave que hay dentro de un workspace, la que usan sus agentes para la inferencia, no puede gestionar runs: la API le responde con un `403`. Un agente que trabaja en tu workspace no puede lanzar runs nuevos por su cuenta, salvo que le des una de tus propias API keys o tokens.
</Callout>

### Crea un run
### Crea un run y síguelo

Un ejemplo de principio a fin: crea un run, guarda su `id` (con [`jq`](https://jqlang.org/)) y sigue su log en directo hasta que termine. Si el run no se puede crear, muestra el error en lugar de seguir el log.

```bash
export NAN_TOKEN="nan_pat_..."

curl https://api.nan.builders/v1/runs \
RESP=$(curl -s https://api.nan.builders/v1/runs \
-H "Authorization: Bearer $NAN_TOKEN" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: fix-date-parser-1" \
-d '{
"workspace": "develop",
"agent": "pi",
"prompt": "añade tests al parser de fechas y haz que pasen",
"cwd": "/home/nan/projects/api",
"git_isolation": null,
"timeout_seconds": 1800
}'
```

| Campo | Obligatorio | Qué es |
|---|---|---|
| `workspace` | Sí | Nombre o id del workspace. |
| `agent` | Sí | `pi` o `hermes`. |
| `prompt` | Sí | La tarea, hasta 32 KiB. |
| `cwd` | No | La carpeta, `/home/nan` por defecto. |
| `git_isolation` | No | Rama aparte: `null` para auto (por defecto), `true` para on, `false` para off. |
| `timeout_seconds` | No | El tiempo máximo, de 60 a 7200. 1800 (30 minutos) por defecto. |
| `model` | No | El modelo del agente. Por defecto, el suyo. |

Los campos equivalen al formulario del portal: **Agent** es `agent`, **Task** es `prompt`, **Folder** es `cwd`, **Separate branch** es `git_isolation` y **Time limit** es `timeout_seconds`.

La respuesta es el run, con su `id` y su `state`. La cabecera `Idempotency-Key` es opcional: si un reintento manda la misma clave con el mismo cuerpo, recibes el run que ya se creó en lugar de uno nuevo.

### Síguelo

Los eventos de un run llegan como un stream de server-sent events cuando pides `text/event-stream`. Con `curl -N` los ves según llegan:

```bash
curl -N https://api.nan.builders/v1/runs/$RUN_ID/events \
-H "Authorization: Bearer $NAN_TOKEN" \
-H "Accept: text/event-stream"
```

Cada evento del stream es uno de estos:

- `event: run_event`, con una línea `id:`: un evento del log (un mensaje, una llamada a una herramienta, su resultado...). Manda el último `id` que hayas visto en la cabecera `Last-Event-ID` para retomar tras un corte, sin perder ni repetir nada.
- `event: state`: el run ha cambiado de estado.
- `event: end`: el run ha terminado y su log se ha enviado entero. Los datos son el run terminado. El stream se cierra después.

Cada 15 segundos el stream manda una línea de comentario para mantener la conexión abierta. Un stream dura como mucho 30 minutos: si se cierra antes del `end`, vuelve a conectarte con `Last-Event-ID` y sigue donde lo dejaste. Sin la cabecera `Accept`, el mismo endpoint responde con páginas de JSON: pasa el `next_after` de cada página como `?after=` para pedir la siguiente.

Para ver cómo ha terminado:

```bash
curl https://api.nan.builders/v1/runs/$RUN_ID \
-H "Authorization: Bearer $NAN_TOKEN"
"cwd": "/home/nan/projects/api"
}')
RUN_ID=$(echo "$RESP" | jq -r '.id // empty')
if [ -z "$RUN_ID" ]; then
echo "$RESP"
else
curl -N "https://api.nan.builders/v1/runs/$RUN_ID/events" \
-H "Authorization: Bearer $NAN_TOKEN" \
-H "Accept: text/event-stream"
fi
```

### Cancélalo

```bash
curl -X POST https://api.nan.builders/v1/runs/$RUN_ID/cancel \
-H "Authorization: Bearer $NAN_TOKEN"
```
Los campos equivalen al formulario del portal: **Agent** es `agent`, **Task** es `prompt`, **Folder** es `cwd`, y los opcionales **Separate branch** y **Time limit** son `git_isolation` y `timeout_seconds`.

### Lista tus runs
El stream manda un frame `run_event` por cada evento del log, un frame `state` cuando el run cambia de estado y un frame `end` con el run terminado, y después se cierra.

```bash
curl "https://api.nan.builders/v1/runs?workspace=develop&state=running&limit=20" \
-H "Authorization: Bearer $NAN_TOKEN"
```

Todos los filtros son opcionales. Si hay más runs de los que caben en una página, la respuesta trae un `next_cursor`: pásalo como `?cursor=` para pedir la siguiente.

### Errores

Los errores usan el mismo formato que la API de inferencia:

```json
{"error": {"message": "...", "type": "...", "param": null, "code": "tier_restricted"}}
```

| Estado y código | Qué hacer |
|---|---|
| `400 invalid_request` | Hay un campo incorrecto. `param` te dice cuál. |
| `403 tier_restricted` | Tu plan no incluye inferencia. Mejóralo para crear runs. |
| `403 workspace_key_not_allowed` | Has usado la clave de dentro de un workspace. Usa una API key o un token. |
| `404` | El workspace o el run no existe, o no es tuyo. |
| `409 idempotency_conflict` | Has repetido una `Idempotency-Key` con otro cuerpo. Usa una clave nueva. |
| `409 workspace_not_running` | Enciende primero el workspace. |
| `409 agent_not_installed` | Instala el agente desde el panel de **Software**, o elige el otro. |
| `409 no_inference_key` | El workspace no tiene clave de inferencia. Comprueba que tu plan incluye inferencia. |
| `429 run_queue_full` | La cola está llena (20 por workspace, 50 en total). Espera a que terminen algunos runs. |
| `429 rate_limited` | Más de 60 runs en la última hora. Vuelve a intentarlo más tarde. |
Referencia completa: [Referencia de la API → Runs](/es/docs/api#tag/runs). Ahí están todos los endpoints (listar, consultar, cancelar), los campos de cada petición y respuesta, los tipos de evento, cómo retomar un stream, los reintentos idempotentes y todos los códigos de error. Para sacar el nombre o el id de un workspace desde un script, consulta [Referencia de la API → Workspaces](/es/docs/api#tag/workspaces).

## Preguntas frecuentes

Expand Down
99 changes: 18 additions & 81 deletions src/content/docs/runs.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -302,106 +302,43 @@ A **token** is the one to give a script that only manages runs. It cannot call t
- Each one expires after **30, 90 or 365 days**, or never.
- You can revoke any of them at any time.

Creating runs still needs a plan with inference, whatever credential you use.
Creating runs still needs a plan with inference, whatever credential you use. The [API reference](/docs/api#description/platform-tokens) lists which credential each endpoint accepts.

<Callout title="An agent cannot launch runs by itself" variant="warning">
The key inside a workspace, the one its agents use for inference, cannot manage runs: the API answers it with `403`. An agent working in your workspace cannot start new runs on its own, unless you give it one of your own API keys or tokens.
</Callout>

### Create a run
### Create a run and follow it

An end-to-end example: create a run, keep its `id` (with [`jq`](https://jqlang.org/)) and follow its log live until it ends. If the run cannot be created, it prints the error instead of following the log.

```bash
export NAN_TOKEN="nan_pat_..."

curl https://api.nan.builders/v1/runs \
RESP=$(curl -s https://api.nan.builders/v1/runs \
-H "Authorization: Bearer $NAN_TOKEN" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: fix-date-parser-1" \
-d '{
"workspace": "develop",
"agent": "pi",
"prompt": "add tests for the date parser and make them pass",
"cwd": "/home/nan/projects/api",
"git_isolation": null,
"timeout_seconds": 1800
}'
```

| Field | Required | What it is |
|---|---|---|
| `workspace` | Yes | Name or id of the workspace. |
| `agent` | Yes | `pi` or `hermes`. |
| `prompt` | Yes | The task, up to 32 KiB. |
| `cwd` | No | The folder, `/home/nan` by default. |
| `git_isolation` | No | Separate branch: `null` for auto (the default), `true` for on, `false` for off. |
| `timeout_seconds` | No | The time limit, from 60 to 7200. 1800 (30 minutes) by default. |
| `model` | No | The model for the agent. Its own by default. |

The fields match the portal form: **Agent** is `agent`, **Task** is `prompt`, **Folder** is `cwd`, **Separate branch** is `git_isolation` and **Time limit** is `timeout_seconds`.

The answer is the run, with its `id` and its `state`. The `Idempotency-Key` header is optional: if a retry sends the same key with the same body, you get the run that was already created instead of a second one.

### Follow it

The events of a run come as a stream of server-sent events when you ask for `text/event-stream`. With `curl -N` you see them as they arrive:

```bash
curl -N https://api.nan.builders/v1/runs/$RUN_ID/events \
-H "Authorization: Bearer $NAN_TOKEN" \
-H "Accept: text/event-stream"
```

Each frame is one of these:

- `event: run_event`, with an `id:` line: one event of the log (a message, a tool call, its result...). Send the last `id` you saw as the `Last-Event-ID` header to resume after a dropped connection, without missing or repeating anything.
- `event: state`: the run changed state.
- `event: end`: the run is over and its log has been sent in full. The data is the finished run. The stream closes after it.

Every 15 seconds the stream sends a comment line to keep the connection open. A stream lasts 30 minutes at most: if it closes before the `end`, reconnect with `Last-Event-ID` and carry on. Without the `Accept` header, the same endpoint answers pages of JSON instead: pass the `next_after` of each page as `?after=` to get the next one.

To see how it ended:

```bash
curl https://api.nan.builders/v1/runs/$RUN_ID \
-H "Authorization: Bearer $NAN_TOKEN"
"cwd": "/home/nan/projects/api"
}')
RUN_ID=$(echo "$RESP" | jq -r '.id // empty')
if [ -z "$RUN_ID" ]; then
echo "$RESP"
else
curl -N "https://api.nan.builders/v1/runs/$RUN_ID/events" \
-H "Authorization: Bearer $NAN_TOKEN" \
-H "Accept: text/event-stream"
fi
```

### Cancel it

```bash
curl -X POST https://api.nan.builders/v1/runs/$RUN_ID/cancel \
-H "Authorization: Bearer $NAN_TOKEN"
```
The fields match the portal form: **Agent** is `agent`, **Task** is `prompt`, **Folder** is `cwd`, and the optional **Separate branch** and **Time limit** are `git_isolation` and `timeout_seconds`.

### List your runs
The stream sends one `run_event` frame per event of the log, a `state` frame when the run changes state, and an `end` frame with the finished run, after which it closes.

```bash
curl "https://api.nan.builders/v1/runs?workspace=develop&state=running&limit=20" \
-H "Authorization: Bearer $NAN_TOKEN"
```

All filters are optional. If there are more runs than fit in a page, the answer has a `next_cursor`: pass it as `?cursor=` to get the next page.

### Errors

Errors use the same format as the inference API:

```json
{"error": {"message": "...", "type": "...", "param": null, "code": "tier_restricted"}}
```

| Status and code | What to do |
|---|---|
| `400 invalid_request` | A field is wrong. `param` says which one. |
| `403 tier_restricted` | Your plan does not include inference. Upgrade it to create runs. |
| `403 workspace_key_not_allowed` | You used the key from inside a workspace. Use an API key or a token. |
| `404` | The workspace or the run does not exist, or is not yours. |
| `409 idempotency_conflict` | You reused an `Idempotency-Key` with a different body. Use a new key. |
| `409 workspace_not_running` | Start the workspace first. |
| `409 agent_not_installed` | Install the agent from the **Software** panel, or pick the other one. |
| `409 no_inference_key` | The workspace has no inference key. Check that your plan includes inference. |
| `429 run_queue_full` | The queue is full (20 per workspace, 50 in total). Wait for some runs to end. |
| `429 rate_limited` | More than 60 runs in the last hour. Try again later. |
Full reference: [API reference → Runs](/docs/api#tag/runs). It has every endpoint (list, retrieve, cancel), the request and response fields, the event types, how to resume a stream, idempotent retries and every error code. To find a workspace's name or id from a script, see [API reference → Workspaces](/docs/api#tag/workspaces).

## FAQ

Expand Down
Loading
Loading