# Operation

> Operations: work that outlives a request (a human's answer, a connect link, an agent turn). `op.wait()` returns the typed outcome for its kind.

## noclick.Operation

```python
class Operation
```

A long-running piece of work. Block on it with `wait()`.

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `str` |  |
| `kind` | `str` |  |
| `status` | `str` |  |
| `step` | `str | None` | Where a running operation is. A turn of an agent on a CLI harness: `delivering` (starting its sandbox and handing it the message) or `working` (the harness is on it). A number's port (`phone.port_in`, invite-only beta): `submitted` (with the current carrier) or `scheduled` (it moves at `port_at`). `None` otherwise. |
| `result` | `dict[str, Any] | None` | The raw result once succeeded. |
| `created_at` | `Any` |  |
| `updated_at` | `Any` |  |
| `summary_text` | `str | None` | A short line saying what it is (a message preview, an addressee, a command). |
| `user_id` | `str | None` |  |
| `key_id` | `str | None` | The key that started it. |
| `agent_id` | `str | None` |  |
| `input` | `dict[str, Any] | None` | What it was started with (single-operation views, account principals). |
| `workstream` | `dict[str, str] | None` | The workstream its work belongs to, as it reads now (`{"id", "name"}`: a renamed one by its new name, a merged one as the one it joined); `None` when its work named none. A single operation's view and `Operation.list()` name it. |
| `started_at` | `Any` |  |
| `finished_at` | `Any` |  |
| `wait_ms` | `int | None` | Time queued before it ran. |
| `run_ms` | `int | None` | Time running. |
| `held_ms` | `int | None` | Time waiting on a person. |
| `progress` | `dict[str, Any] | None` | What the work reported as it went, or `None` before it reported anything: its `step`, its `stages` (each `{name, status, started_at, ended_at}`, `status` being `done`, `current` or `pending`; a deploy's are Queued, Building, Shipping and Live), the last 50 `lines` it printed (a build's log, a call's turns, an agent's tool calls), `line_count` (every line so far) and `updated_at`. An agent that started it hears each report as an `operation` event. |
| `undoable` | `bool | None` | Whether `undo()` can take it back now: a reversible write (a deletion that went to the trash, a dict's clear, a database migration) not undone yet. `None` for kinds that record no undo. |
| `undone_at` | `Any` | When it was undone, if it was. |
| `undo_rewinds` | `str | None` | On a promote that bound databases, while it can be undone: what undoing it takes back from them (each goes back to the moment before the promote; what was written since is kept in the trash as a database copy). `None` otherwise. |
| `kept_copy_id` | `str | None` | On a database's restore: the copy it keeps of what the database held just before, in the trash (a `TrashItem` of kind `database_copy` whose `resource_id` this is) once it's done. `undo()` puts it back. `None` on other kinds. |
| `transitions` | `list[OperationTransition]` | Every status change, oldest first (empty for operations recorded before they were kept). |
| `console_url` | `str | None` | This operation in the developer console (None off the hosted API). |
| `error` | `Error | None` | The failure as an `noclick.Error` (None unless it failed). |
| `done` | `bool` | Whether the operation reached a terminal status. |

### Operation.list

```python
noclick.Operation.list(
    *, kind=None, status=None, status_not=None, agent=None, key=None,
    created_after=None, created_before=None, updated_after=None, limit=None,
    user_filter=None, user=..., client=None
) -> list[Operation]
```

Operations matching the filters, newest first (or the first `limit`).
`status="live"` means every non-terminal status; `key` is a key id or
prefix (`nk_live_ab12`); `agent` an `Agent` or id.

Parameters:

- `kind` (`Many`, default `None`)
- `status` (`Many`, default `None`)
- `status_not` (`Many`, default `None`)
- `agent` (`Any`, default `None`)
- `key` (`str | None`, default `None`)
- `created_after` (`Any`, default `None`)
- `created_before` (`Any`, default `None`)
- `updated_after` (`Any`, default `None`)
- `limit` (`int | None`, default `None`): Return at most this many.
- `user_filter` (`Any`, default `None`): Which users a read covers: `noclick.ALL_USERS`, `noclick.NO_USER`, a `User`, or your id for one. It filters without acting as that user.
- `user` (`Any`, default: the current user): Who the call acts for. Defaults to the user set by `noclick.as_user` (none: the account itself).
- `client` (`Client | None`, default `None`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: `list[Operation]` Every matching operation, fetched page by page.

Usage:

See what failed in the last day:

```python
from datetime import datetime, timedelta, timezone

yesterday = datetime.now(timezone.utc) - timedelta(days=1)
for op in noclick.Operation.list(status="failed", created_after=yesterday):
    print(op.kind, op.error)
```

Or the turns one agent is still working on:

```python
support = noclick.Agent.from_name("support")
live = noclick.Operation.list(kind="agent.message", status="live", agent=support)
```

A read acts for the current user; `user_filter` reads across them:

```python
failed = noclick.Operation.list(status="failed", user_filter=noclick.ALL_USERS, limit=20)
```

### Operation.list_page

```python
noclick.Operation.list_page(
    *, cursor=None, limit=None, kind=None, status=None, status_not=None, agent=None,
    key=None, created_after=None, created_before=None, updated_after=None,
    user_filter=None, user=..., client=None
) -> Page
```

One page of matching operations; pass `next_cursor` back as `cursor`.

Parameters:

- `cursor` (`str | None`, default `None`): The `next_cursor` of the page before; omit it for the first page.
- `limit` (`int | None`, default `None`): Return at most this many.
- `kind` (`Many`, default `None`)
- `status` (`Many`, default `None`)
- `status_not` (`Many`, default `None`)
- `agent` (`Any`, default `None`)
- `key` (`str | None`, default `None`)
- `created_after` (`Any`, default `None`)
- `created_before` (`Any`, default `None`)
- `updated_after` (`Any`, default `None`)
- `user_filter` (`Any`, default `None`): Which users a read covers: `noclick.ALL_USERS`, `noclick.NO_USER`, a `User`, or your id for one. It filters without acting as that user.
- `user` (`Any`, default: the current user): Who the call acts for. Defaults to the user set by `noclick.as_user` (none: the account itself).
- `client` (`Client | None`, default `None`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: `Page` A page whose `data` holds the operations and whose `next_cursor` is `None` on the last page.

Usage:

```python
page = noclick.Operation.list_page(status="failed", limit=100)
while True:
    for op in page.data:
        print(op.id, op.kind, op.error)
    if page.next_cursor is None:
        break
    page = noclick.Operation.list_page(status="failed", limit=100, cursor=page.next_cursor)
```

### Operation.summary

```python
noclick.Operation.summary(
    *, kind=None, status=None, status_not=None, agent=None, key=None,
    created_after=None, created_before=None, updated_after=None, user_filter=None,
    user=..., client=None
) -> OperationSummary
```

How many operations match the same filters, by status.

Parameters:

- `kind` (`Many`, default `None`)
- `status` (`Many`, default `None`)
- `status_not` (`Many`, default `None`)
- `agent` (`Any`, default `None`)
- `key` (`str | None`, default `None`)
- `created_after` (`Any`, default `None`)
- `created_before` (`Any`, default `None`)
- `updated_after` (`Any`, default `None`)
- `user_filter` (`Any`, default `None`): Which users a read covers: `noclick.ALL_USERS`, `noclick.NO_USER`, a `User`, or your id for one. It filters without acting as that user.
- `user` (`Any`, default: the current user): Who the call acts for. Defaults to the user set by `noclick.as_user` (none: the account itself).
- `client` (`Client | None`, default `None`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: `OperationSummary` The `total`, and in `by_status` a count for every status, zeros included.

Usage:

```python
counts = noclick.Operation.summary(kind="agent.message", status="live")
print(counts.total, counts.by_status["running"], counts.by_status["awaiting_human"])
```

### Operation.from_id

```python
noclick.Operation.from_id(operation_id, *, client=None, user=...) -> Operation
```

A lazy reference to an operation by id.

Parameters:

- `operation_id` (`str`, required)
- `client` (`Client | None`, default `None`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.
- `user` (`Any`, default: the current user): Who the call acts for. Defaults to the user set by `noclick.as_user` (none: the account itself).

Returns: `Operation` An operation that loads the first time you read a field. Nothing is sent yet.

Usage:

Operations outlive your process, so keep the id and pick it up anywhere:

```python
op = noclick.Operation.from_id("3b9d6f2e-1c4a-4e8b-9f7d-2a6c5e8b1d40")
reply = op.wait()
```

Or check on it without waiting:

```python
op = noclick.Operation.from_id("3b9d6f2e-1c4a-4e8b-9f7d-2a6c5e8b1d40").hydrate()
print(op.status, op.done)
```

### Operation.wait

```python
operation.wait(timeout=None) -> Any
```

Block until the operation finishes.

Raises the operation's error if it failed, `OperationCanceled` /
`OperationExpired`, or `OperationTimeout` after `timeout` seconds.

Parameters:

- `timeout` (`float | None`, default `None`)

Returns: `Any` The outcome, typed for the operation's kind: an `AgentReply` from `agent.send`,
`True` or `False` from `human.approve`, the connected `Connection` from a
connect link. A kind the client has no type for gives the raw `result`.

Usage:

Start an agent turn, then block on it:

```python
agent = noclick.Agent.from_name("support")
turn = agent.send("Draft the monthly report", user="user_42")
reply = turn.wait(timeout=120)
print(reply.text)
```

A timeout leaves the operation running, so you can wait on it again later:

```python
op = noclick.Operation.from_id("3b9d6f2e-1c4a-4e8b-9f7d-2a6c5e8b1d40")
try:
    reply = op.wait(timeout=30)
except noclick.OperationTimeout:
    print(op.status)   # still running
```

### Operation.tool_calls

```python
operation.tool_calls() -> list[ToolCall]
```

The tool calls an `agent.message` turn made, oldest first (none for other kinds).

Returns: `list[ToolCall]` Each call's tool, arguments, status, duration and a preview of its result.

Usage:

```python
agent = noclick.Agent.from_name("support")
turn = agent.send("Find last week's invoices", user="user_42")
turn.wait()
for call in turn.tool_calls():
    print(call.tool_name, call.status, call.duration_ms)
```

### Operation.events

```python
operation.events(*, interval=1.0) -> Iterator[OperationEvent]
```

Yield an `OperationEvent` for each status or step change until it finishes.

Parameters:

- `interval` (`float`, default `1.0`)

Returns: `Iterator[OperationEvent]` The changes, polled every `interval` seconds: first the status (and `step`) it has
now, last its final one. An event's `result` is the raw result, not the typed outcome
`wait()` returns.

Usage:

Print each change as it happens, a CLI agent's turn going from `delivering` to `working`:

```python
op = noclick.Operation.from_id("3b9d6f2e-1c4a-4e8b-9f7d-2a6c5e8b1d40")
for event in op.events(interval=5):
    print(event.status, event.step, event.updated_at)
```

In async code, iterate the `.aio()` form:

```python
op = noclick.Operation.from_id("3b9d6f2e-1c4a-4e8b-9f7d-2a6c5e8b1d40")
async for event in op.events.aio():
    print(event.status)
```

### Operation.cancel

```python
operation.cancel() -> Operation
```

Ask the server to cancel. A coding agent's turn (`agent.message` on a coding harness) stops in its
sandbox first, its harness going on from the same session, so the next turn never runs beside it.

Returns: `Operation` This operation, now `canceled`.

Usage:

Cancel a turn you no longer need:

```python
agent = noclick.Agent.from_name("support")
turn = agent.send("Draft the monthly report", user="user_42")
turn.cancel()
print(turn.status)   # canceled
```

An operation that already finished can't be canceled:

```python
op = noclick.Operation.from_id("3b9d6f2e-1c4a-4e8b-9f7d-2a6c5e8b1d40")
try:
    op.cancel()
except noclick.Conflict as err:
    print(err.operation_status)   # succeeded, failed, ...
```

### Operation.undo

```python
operation.undo() -> dict[str, Any]
```

Take back a reversible write, once: a deletion comes out of the trash, a dict's cleared keys come
back, a migrated database is restored to the moment before, a restored database gets back what the restore
rewound, a promote puts production back on the release before with the app's databases as they were (each
restore keeping what it rewinds in the trash, named in the result's `copies`). What reached the world (an
email sent, a payment) has no undo: that raises `noclick.Conflict`, as does undoing twice.

Returns: `dict[str, Any]` What the undo put back, as its own API shows it (a restore of a database is an operation of its own).

Usage:

```python
item = noclick.Dict.from_name("rates-cache").delete()
noclick.Operation.from_id(item.operation_id).undo()
```

## noclick.OperationEvent

```python
class OperationEvent
```

A status or step change observed by `Operation.events()`: `step` is where a running
operation is (`delivering` or `working` for a CLI agent's turn, `submitted` or `scheduled`
for a port; `None` otherwise).

| Attribute | Type | Description |
| --- | --- | --- |
| `status` | `str` |  |
| `step` | `str | None` |  |
| `updated_at` | `Any` |  |
| `result` | `Any` |  |
| `error` | `Error | None` |  |
| `raw` | `dict[str, Any]` | The response JSON exactly as the API sent it. |

## noclick.OperationSummary

```python
class OperationSummary
```

How many operations match, by status.

| Attribute | Type | Description |
| --- | --- | --- |
| `total` | `int` |  |
| `by_status` | `dict[str, int]` |  |
| `raw` | `dict[str, Any]` | The response JSON exactly as the API sent it. |

## noclick.OperationTransition

```python
class OperationTransition
```

One status change the server recorded (`by` names who canceled).

| Attribute | Type | Description |
| --- | --- | --- |
| `status` | `str` |  |
| `at` | `Any` |  |
| `by` | `str | None` |  |
