# 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.

## Operation

```typescript
class Operation
```

A long-running piece of work. `T` is what `wait()` resolves to.

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `string` |  |
| `kind` | `string` |  |
| `status` | `OperationStatus` |  |
| `step` | `OperationStep | null` | Where a running operation is: an agent turn on a CLI harness `delivering`, then `working`; a number's port `submitted`, then `scheduled`. Null otherwise. |
| `result` | `unknown` | The raw result once succeeded. |
| `createdAt` | `Date | null` |  |
| `updatedAt` | `Date | null` |  |
| `summaryText` | `string | null` | A short line saying what it is (a message preview, an addressee, a command). |
| `userId` | `string | null` |  |
| `keyId` | `string | null` | The key that started it. |
| `agentId` | `string | null` |  |
| `input` | `JsonObject | null` | What it was started with (on a single operation's view, for account principals). |
| `workstream` | `NamedWorkstream | null` | The workstream its work belongs to, as it reads now (a renamed one by its new name, a merged one as the one it joined); null when its work named none. A single operation's view and `Operation.list()` name it. |
| `startedAt` | `Date | null` |  |
| `finishedAt` | `Date | null` |  |
| `waitMs` | `number | null` | Time queued before it ran. |
| `runMs` | `number | null` | Time running. |
| `heldMs` | `number | null` | Time waiting on a person. |
| `progress` | `OperationProgress | null` | What the work reported as it went (null before it reported anything). An agent that started it hears each report as an `operation` event. |
| `undoable` | `boolean | null` | 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. `null` for kinds that record no undo. |
| `undoneAt` | `Date | null` | When it was undone, if it was. |
| `undoRewinds` | `string | null` | 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). `null` otherwise. |
| `keptCopyId` | `string | null` | 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 `resourceId` this is) once it's done. `undo()` puts it back. `null` on other kinds. |
| `transitions` | `OperationTransition[]` | Every status change, oldest first (empty for operations recorded before they were kept). |
| `consoleUrl` | `string | null` | This operation in the developer console (null off the hosted API). |
| `error` | `NoClickError | null` | The failure as a `NoClickError` (null unless it failed). |
| `done` | `boolean` | Whether the operation reached a terminal status. |

Types:

```typescript
type OperationStatus =
  | "queued" | "running" | "awaiting_human"
  | "succeeded" | "failed" | "canceled" | "expired";

/** Where a running operation is: an agent turn's `TurnStep`, or a port's `PortStep`. */
type OperationStep = TurnStep | PortStep;

/**
 * Where a running turn of an agent on a CLI harness is: `delivering` (starting its sandbox and
 * handing it the message) or `working` (the harness is on it).
 */
type TurnStep = "delivering" | "working";

/**
 * Invite-only beta. Where a number's port (`phone.port_in`) is: `submitted` (with the
 * current carrier) or `scheduled` (it moves at `portAt`).
 */
type PortStep = "submitted" | "scheduled";

type JsonObject = { [key: string]: unknown };

/** The workstream an operation's work belongs to, as it reads now. */
interface NamedWorkstream {
  id: string;
  name: string;
}

/**
 * What an operation's work reported as it went: its `step`, its `stages`, the last 50 `lines` it printed (a build's
 * log, a call's turns, an agent's tool calls), `lineCount` (every line so far) and when it last said something.
 */
interface OperationProgress {
  step: string | null;
  stages: OperationStage[];
  lines: string[];
  lineCount: number;
  updatedAt: Date | null;
  raw: JsonObject;
}

/** One stage of what an operation's work planned (a deploy's: Queued, Building, Shipping, Live). */
interface OperationStage {
  name: string;
  status: "done" | "current" | "pending";
  startedAt: Date | null;
  endedAt: Date | null;
}
```

### Operation.list

```typescript
static list(
  options?: OperationFilters & { limit?: number },
): Promise<Operation[]>
```

Operations matching the filters, newest first (or the first `limit`).

Parameters:

- `options.kind` (`string | readonly string[]`)
- `options.status` (`OperationStatus | "live" | readonly (OperationStatus | "live")[]`): Statuses, or `"live"` for every non-terminal one.
- `options.statusNot` (`OperationStatus | readonly OperationStatus[]`)
- `options.agent` (`string | ApiObject`): An `Agent` or agent id.
- `options.key` (`string`): The requesting key: its id or its prefix (`nk_live_ab12`).
- `options.createdAfter` (`Date | string`)
- `options.createdBefore` (`Date | string`)
- `options.updatedAfter` (`Date | string`): Rows changed since (for polling).
- `options.limit` (`number`): Return at most this many.
- `options.userFilter` (`UserFilter`): Which users the read covers (`user_id` query), instead of acting as one (`user`).
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: Every matching operation, fetched page by page.

Types:

```typescript
type OperationStatus =
  | "queued" | "running" | "awaiting_human"
  | "succeeded" | "failed" | "canceled" | "expired";

/**
 * Which users a read covers: `ALL_USERS`, `NO_USER`, a `User` or your id for one. Sent as the
 * `user_id` query parameter, never as the `NoClick-User` header, so it filters without acting as the user.
 */
type UserFilter = typeof ALL_USERS | typeof NO_USER | UserRef;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;
```

### Operation.listPage

```typescript
static listPage(
  options?: OperationFilters & PageOptions,
): Promise<Page<Operation>>
```

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

Parameters:

- `options.cursor` (`string | null`): The `next_cursor` of the page before; omit it for the first page.
- `options.limit` (`number`): Return at most this many.
- `options.kind` (`string | readonly string[]`)
- `options.status` (`OperationStatus | "live" | readonly (OperationStatus | "live")[]`): Statuses, or `"live"` for every non-terminal one.
- `options.statusNot` (`OperationStatus | readonly OperationStatus[]`)
- `options.agent` (`string | ApiObject`): An `Agent` or agent id.
- `options.key` (`string`): The requesting key: its id or its prefix (`nk_live_ab12`).
- `options.createdAfter` (`Date | string`)
- `options.createdBefore` (`Date | string`)
- `options.updatedAfter` (`Date | string`): Rows changed since (for polling).
- `options.userFilter` (`UserFilter`): Which users the read covers (`user_id` query), instead of acting as one (`user`).
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

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

Types:

```typescript
type OperationStatus =
  | "queued" | "running" | "awaiting_human"
  | "succeeded" | "failed" | "canceled" | "expired";

/**
 * Which users a read covers: `ALL_USERS`, `NO_USER`, a `User` or your id for one. Sent as the
 * `user_id` query parameter, never as the `NoClick-User` header, so it filters without acting as the user.
 */
type UserFilter = typeof ALL_USERS | typeof NO_USER | UserRef;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;
```

### Operation.summary

```typescript
static summary(options?: OperationFilters): Promise<OperationSummary>
```

How many operations match, by status.

Parameters:

- `options.kind` (`string | readonly string[]`)
- `options.status` (`OperationStatus | "live" | readonly (OperationStatus | "live")[]`): Statuses, or `"live"` for every non-terminal one.
- `options.statusNot` (`OperationStatus | readonly OperationStatus[]`)
- `options.agent` (`string | ApiObject`): An `Agent` or agent id.
- `options.key` (`string`): The requesting key: its id or its prefix (`nk_live_ab12`).
- `options.createdAfter` (`Date | string`)
- `options.createdBefore` (`Date | string`)
- `options.updatedAfter` (`Date | string`): Rows changed since (for polling).
- `options.userFilter` (`UserFilter`): Which users the read covers (`user_id` query), instead of acting as one (`user`).
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

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

Types:

```typescript
type OperationStatus =
  | "queued" | "running" | "awaiting_human"
  | "succeeded" | "failed" | "canceled" | "expired";

/**
 * Which users a read covers: `ALL_USERS`, `NO_USER`, a `User` or your id for one. Sent as the
 * `user_id` query parameter, never as the `NoClick-User` header, so it filters without acting as the user.
 */
type UserFilter = typeof ALL_USERS | typeof NO_USER | UserRef;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;
```

### Operation.fromId

```typescript
static fromId(operationId: string, options?: CallOptions): Operation<T>
```

A lazy reference to an operation by id.

Parameters:

- `operationId` (`string`, required)
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.

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

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

### Operation.wait

```typescript
wait(options?: { timeoutS?: number }): Promise<T>
```

Wait until the operation finishes and return its outcome (typed per kind:
`Connection`, `Answer`, `boolean`, `AgentReply`, ...). Throws the
operation's error if it failed, `OperationCanceled` / `Expired`, or
`OperationTimeout` after `timeoutS` seconds.

Parameters:

- `options.timeoutS` (`number`)

Returns: 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`.

### Operation.toolCalls

```typescript
toolCalls(): Promise<ToolCall[]>
```

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

Returns: Each call's tool, arguments, status, duration and a preview of its result.

### Operation.events

```typescript
async *events(options?: { intervalMs?: number }): AsyncGenerator<OperationEvent>
```

Yield an event for each status or step change until the operation finishes.

Parameters:

- `options.intervalMs` (`number`, default `1000`)

Returns: 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.

### Operation.cancel

```typescript
cancel(): Promise<this>
```

Ask the server to cancel; returns the updated operation. 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: This operation, now `canceled`.

### Operation.undo

```typescript
undo(): Promise<JsonObject>
```

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 the release before back 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 throws `Conflict`, as does
undoing twice. Returns what the undo put back, as its own API shows it.

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

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## OperationEvent

```typescript
interface 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` | `OperationStatus` |  |
| `step` | `OperationStep | null` | Where a running operation is (`delivering` or `working` for a CLI agent's turn, `submitted` or `scheduled` for a port); null otherwise. |
| `updatedAt` | `Date | null` |  |
| `result` | `unknown` |  |
| `error` | `NoClickError | null` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type OperationStatus =
  | "queued" | "running" | "awaiting_human"
  | "succeeded" | "failed" | "canceled" | "expired";

/** Where a running operation is: an agent turn's `TurnStep`, or a port's `PortStep`. */
type OperationStep = TurnStep | PortStep;

/**
 * Where a running turn of an agent on a CLI harness is: `delivering` (starting its sandbox and
 * handing it the message) or `working` (the harness is on it).
 */
type TurnStep = "delivering" | "working";

/**
 * Invite-only beta. Where a number's port (`phone.port_in`) is: `submitted` (with the
 * current carrier) or `scheduled` (it moves at `portAt`).
 */
type PortStep = "submitted" | "scheduled";

type JsonObject = { [key: string]: unknown };
```

## OperationSummary

```typescript
interface OperationSummary
```

How many operations match, by status.

| Attribute | Type | Description |
| --- | --- | --- |
| `total` | `number` |  |
| `byStatus` | `Record<OperationStatus, number>` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type OperationStatus =
  | "queued" | "running" | "awaiting_human"
  | "succeeded" | "failed" | "canceled" | "expired";

type JsonObject = { [key: string]: unknown };
```

## OperationTransition

```typescript
interface OperationTransition
```

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

| Attribute | Type | Description |
| --- | --- | --- |
| `status` | `OperationStatus` |  |
| `at` | `Date | null` |  |
| `by` | `string | null` |  |

Types:

```typescript
type OperationStatus =
  | "queued" | "running" | "awaiting_human"
  | "succeeded" | "failed" | "canceled" | "expired";
```
