# cancel

Cancel a queued or running turn.

`runtime.cancel(scope, request_id, fields)` ends a queued turn at once and marks a running turn for cancellation. If the session is open in the same scope, the running turn stops, and `drive` finishes it as `cancelled`. `cancel` works before `open`, so a host can cancel turns from storage.

```ts title="host.ts"
import type { AgentRuntime } from 'nanocode-wasm'

declare const runtime: AgentRuntime

// 1. Cancel the turn and record who cancelled it
const { dequeued, turn } = await runtime.cancel('owner', 'turn-1', {
  by: 'user',
})

// 2. A queued turn is cancelled now, and a running turn when drive
// returns
console.log(dequeued ? 'cancelled' : turn?.report.status)
```

## Signature

```ts
// Resolves with the turn after the cancel
cancel(
  scope: string,
  request_id: string,
  fields: Record<string, unknown>,
): Promise<{ turn: TurnView | null; dequeued?: boolean }>
```

## Parameters

### scope

* **Type:** `string`

The session log scope. When it matches the open session's `config.scope`, the cancel also stops the live turn.

```ts
// Cancels in the open session's scope
await runtime.cancel('owner', 'turn-1', {})
```

### request_id

* **Type:** `string`

The ID of the turn to cancel.

```ts
// Cancels the turn that submit queued
await runtime.cancel('owner', 'turn-2', {})
```

### fields

* **Type:** `Record<string, unknown>`

Fields for the `cancelled` result event of a queued turn. The turn report then includes them.

```ts
// Records the reason in the report
await runtime.cancel('owner', 'turn-3', { reason: 'superseded' })
```

## Returns

* **Type:** `Promise<{ turn: TurnView | null; dequeued?: boolean }>`

### turn

* **Type:** `TurnView | null`

The turn after the cancel, or `null` if the scope has no turn with this ID. A running turn keeps status `running` with `cancel_requested` set until `drive` finishes it.

```ts
import type { AgentRuntime } from 'nanocode-wasm'

declare const result: Awaited<ReturnType<AgentRuntime['cancel']>>

// An unknown ID
if (!result.turn) console.log('no such turn')
```

### dequeued

* **Type:** `boolean`

`true` if the turn was queued and is now `cancelled`. `published` receives the turn's result event. `false` for a turn that was running or already finished.

```ts
import type { AgentRuntime } from 'nanocode-wasm'

declare const result: Awaited<ReturnType<AgentRuntime['cancel']>>

// The turn never started
if (result.dequeued) console.log('removed from the queue')
```

## Errors

The promise rejects if the SQL host throws, the live turn fails to cancel, or the runtime is closed.

```ts
import type { AgentRuntime } from 'nanocode-wasm'

declare const runtime: AgentRuntime

// Rejects with the store or agent error
await runtime.cancel('owner', 'turn-1', {}).catch(console.error)
```
