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

# SDK Reference

> Generated reference for Deepline play authoring primitives, runtime context methods, dataset handles, and tool result shapes.

> [!NOTE]
>
> Generated from SDK source comments by
> `scripts/generate-play-sdk-reference.ts`. Do not edit this file manually.

## Runtime Model

Use `definePlay(...)` to define durable TypeScript code and typed run contracts executed in the cloud. Inside that function, `ctx.*` records and persists work: `ctx.tools.execute` calls managed providers, `ctx.dataset` records rows, `ctx.step` checkpoints scalar work, `ctx.fetch` records external HTTP, and `ctx.runPlay` composes registered or prebuilt plays.
For sequential pacing outside Dataset resolvers, `await ctx.sleep(ms)` waits at least `ms`. Waits of at most 10 seconds stay in the current execution when its remaining time permits. Longer waits park execution and replay completed steps and sleeps. Scheduling and replay can delay continuation beyond the requested duration.
Use `Deepline.connect()` and `DeeplineClient` from regular Node/TypeScript services, scripts, schedulers, or tests. Those APIs discover tools and plays, start runs, stream/poll status, stop runs, and inspect durable output without requiring a local play file. For logs, the complete event catalog, filters and payload retrieval, use `deepline runs logs --help` or [Run logs and events](https://deepline.com/docs/sdk-v2/run-events.md).

## Detail Policy

| Material | Rendered as |
| - | - |
| Classes | One member table with purpose, parameters, and returns. |
| Interfaces and object types | Field tables without duplicate declarations. |
| Fieldless aliases or overloads | Compact signature line plus parameter/return tables. |

## Tested Examples

The generator copies these examples from `docs-examples/sdk-v2`. CI checks them with `bun run docs:sdk-v2:check`. Edit the source examples before you regenerate this reference.

### Run A Prebuilt From TypeScript

Source: `docs-examples/sdk-v2/run-prebuilt.ts`

```ts theme={"languages":{"custom":["/languages/deepline-prompt.json"]}}
import { Deepline } from 'deepline';

const ctx = await Deepline.connect();
const job = await ctx.play('prebuilt/person-linkedin-to-email').run({
  linkedin_url: 'https://www.linkedin.com/in/example-person/',
});
console.log(JSON.stringify(await job.get(), null, 2));
```

### Define A Play With `ctx.tools.execute`

Source: `docs-examples/sdk-v2/company-lookup.play.ts`

```ts theme={"languages":{"custom":["/languages/deepline-prompt.json"]}}
import { definePlay } from 'deepline';

type Input = {
  domain: string;
};

type Output = {
  domain: string;
  lookupStatus: string;
};

export default definePlay(
  'docs-company-lookup',
  async (ctx, input: Input): Promise<Output> => {
    const result = await ctx.tools.execute({
      id: 'company_lookup',
      tool: 'test_rate_limit',
      input: {
        key: input.domain,
      },
      description:
        'Check that the company lookup path can run for this domain.',
      staleAfterSeconds: 0,
    });
    return {
      domain: input.domain,
      lookupStatus: result.status,
    };
  },
  {
    description: 'Look up company',
    compatibility: { authoringContract: 'explicit-freshness' },
  },
);
```

### Fall Through A Transient Provider Failure

Catch only `ProviderTransientError` when another read provider can answer the same question. Validation, authentication, billing, Deepline, unknown, and final-provider failures stay loud.

Source: `docs-examples/sdk-v2/provider-fallback.play.ts`

```ts theme={"languages":{"custom":["/languages/deepline-prompt.json"]}}
import { definePlay, ProviderTransientError } from 'deepline';

type Input = {
  firstName: string;
  lastName: string;
  domain: string;
};

export default definePlay(
  'docs-provider-fallback',
  async (ctx, input: Input) => {
    try {
      const primary = await ctx.tools.execute({
        id: 'primary_email',
        tool: 'hunter_email_finder',
        input: {
          first_name: input.firstName,
          last_name: input.lastName,
          domain: input.domain,
        },
        description: 'Try the primary email provider.',
        staleAfterSeconds: 0,
      });
      return { email: primary.extractedValues.email?.get() ?? null };
    } catch (error) {
      if (!(error instanceof ProviderTransientError)) throw error;
    }

    const fallback = await ctx.tools.execute({
      id: 'fallback_email',
      tool: 'leadmagic_email_finder',
      input: {
        first_name: input.firstName,
        last_name: input.lastName,
        domain: input.domain,
        company_domain: input.domain,
      },
      description: 'Try the fallback email provider.',
      staleAfterSeconds: 0,
    });
    return { email: fallback.extractedValues.email?.get() ?? null };
  },
  {
    compatibility: { authoringContract: 'explicit-freshness' },
    description:
      'Find an email with one safe provider-failure fallback and loud terminal errors.',
  },
);
```

### Schedule A Dataset Refresh

Source: `docs-examples/sdk-v2/nightly-account-refresh.play.ts`

```ts theme={"languages":{"custom":["/languages/deepline-prompt.json"]}}
import { definePlay } from 'deepline';

type Account = {
  record_id: string;
};

export default definePlay(
  'docs-nightly-account-refresh',
  async (ctx, input: { accounts: Account[]; refreshExisting?: boolean }) => {
    const rows = await ctx
      .dataset('account_refresh', input.accounts)
      .withColumn('company_record', (account, rowCtx) =>
        rowCtx.tools.execute({
          id: 'company_record',
          tool: 'attio_get_record',
          input: {
            object: 'companies',
            record_id: account.record_id,
          },
          description: 'Read the Attio company record for this account.',
          staleAfterSeconds: 86_400,
        }),
      )
      .run({
        key: 'record_id',
        description: 'Read Attio company records, reusing results for one day.',
      });

    return { rows };
  },
  {
    description: 'Refresh Attio account records on the scheduled cadence.',
    cron: {
      schedule: '0 9 * * *',
      timezone: 'America/New_York',
      input: { accounts: [], refreshExisting: true },
    },
    billing: {
      maxCreditsPerRun: 25,
    },
  },
);
```

### Verify A Webhook With HMAC

Source: `docs-examples/sdk-v2/inbound-lead-webhook.play.ts`

```ts theme={"languages":{"custom":["/languages/deepline-prompt.json"]}}
import { definePlay } from 'deepline';

type InboundLead = {
  email: string;
  company_domain?: string;
  source?: string;
};

export default definePlay(
  'docs-inbound-lead-webhook',
  async (ctx, input: InboundLead) => {
    const domain = input.company_domain ?? input.email.split('@')[1] ?? '';
    const company = await ctx.tools.execute({
      id: 'company_context',
      tool: 'test_rate_limit',
      input: {
        key: domain,
      },
      description: 'Add company context before routing the inbound lead.',
      staleAfterSeconds: 0,
    });

    return {
      email: input.email,
      domain,
      source: input.source ?? 'webhook',
      company_status: company.status,
    };
  },
  {
    description: 'Enrich inbound leads',
    compatibility: { authoringContract: 'explicit-freshness' },
    webhook: {
      auth: {
        type: 'standard-webhooks',
        headerFamily: 'standard',
        signingSecrets: ['INBOUND_RELAY_WEBHOOK_SECRET'],
        toleranceSeconds: 300,
      },
    },
  },
);
```

## Play Authoring Contract

Unmarked new source pins authoring contract edition 11. New maintained starters opt in to edition 10 with `compatibility: { authoringContract: 'explicit-freshness' }`. Existing artifacts retain their pinned edition. Check, publish, and run use the same admitted snapshot.

| Field | Type | Required | Contract |
| - | - | -: | - |
| `displayName` | `string` | No | Optional human-readable Play name. empty uses the derived identifier. |
| `description` | `string` | No | Optional non-empty human-readable summary of the Play. |
| `compatibility.toolErrorSchemaVersion` `compatibility.authoringContract` | `0 \| 1` `'explicit-freshness'` | No No | Artifact-pinned tool error behavior, either 0 or 1. Opts new source into the current explicit-freshness authoring edition. An already-pinned edition-10 artifact retains its admitted behavior. |
| `compatibility.toolResponseReceiptRevision` | `string` | No | Explicit durable-receipt revision for a response transformation. bump only when serialized tool output changes. |
| `inline` | `boolean` | No | Compiler hint for an inline named Play handler. |
| `billing.maxCreditsPerRun` | `number` | No | Maximum Deepline credits permitted for one Play Run. |
| `bindings.webhook.hmac.secretEnv` | `string` | Yes | Environment variable containing the webhook HMAC secret. |
| `bindings.webhook.hmac.algorithm` | `'sha256'` | No | Webhook signature hash algorithm. Only sha256 is supported. |
| `bindings.webhook.hmac.header` | `string` | No | HTTP header containing the webhook signature. |
| `bindings.webhook.hmac.signaturePrefix` | `string` | No | Optional literal before the lowercase hexadecimal HMAC. Set to an empty string for providers that send a bare digest. Defaults to sha256= when a signature header is configured. |
| `bindings.webhook.auth.type` | `'standard-webhooks'` | No | Uses the Standard Webhooks v1 symmetric signing scheme. |
| `bindings.webhook.auth.headerFamily` | `'standard' \| 'svix'` | No | Header namespace expected from the webhook provider. |
| `bindings.webhook.auth.signingSecrets[]` | `string` | No | Deepline Secret name used to verify Standard Webhooks. |
| `bindings.webhook.auth.toleranceSeconds` | `number` | No | Accepted delivery timestamp skew in seconds, from 1 through 3600. |
| `bindings.cron.schedule` | `string` | Yes | Five-field cron expression. |
| `bindings.cron.timezone` | `string` | No | IANA timezone. Omitted means UTC. |
| `bindings.cron.input` | `Record<string, unknown>` | No | Static JSON object passed to every run created by this cron binding. |
| `bindings.sqlListeners` | `SqlListener[]` | No | Static provider-monitor listener declarations. |
| `bindings.sqlListeners[].id` | `string` | Yes | Unique static listener identifier within one Play. |
| `bindings.sqlListeners[].tool` | `string` | Yes | Modeled provider monitor tool id in provider.tool form. |
| `bindings.sqlListeners[].stream` | `string` | Yes | Static output stream key exposed by the monitor tool. |
| `bindings.sqlListeners[].operations[]` | `'INSERT' \| 'UPDATE' \| 'DELETE'` | No | Database operation that wakes the listener. |
| `bindings.sqlListeners[].where.before` | `Record<string, SqlListenerFilterOperator>` | No | Column filters evaluated against the row before mutation. |
| `bindings.sqlListeners[].where.after` | `Record<string, SqlListenerFilterOperator>` | No | Column filters evaluated against the row after mutation. |
| `bindings.sqlListeners[].where.*.*.eq` `bindings.sqlListeners[].where.*.*.neq` | `SqlListenerFilterScalar` `SqlListenerFilterScalar` | No No | Scalar equality condition. Scalar inequality condition. |
| `bindings.sqlListeners[].where.*.*.in` `bindings.sqlListeners[].where.*.*.notIn` | `readonly SqlListenerFilterScalar[]` `readonly SqlListenerFilterScalar[]` | No No | Non-empty scalar membership condition. Non-empty scalar exclusion condition. |
| `bindings.sqlListeners[].where.*.*.isNull` `bindings.sqlListeners[].where.*.*.isNotNull` | `true` `true` | No No | Matches null values when set to true. Matches non-null values when set to true. |
| `bindings.sqlListeners[].where.*.*.ilike` | `string` | No | Case-insensitive SQL pattern condition. |
| `bindings.secrets[]` | `string` | No | Environment variable made available to the Play. |
| `staleAfterSeconds` | `number \| null` | No | Edition 11 requires an explicit choice. `0` starts a fresh logical call, though a matching operation receipt may recover that same operation after resume. `null` allows indefinite result reuse. A positive integer is the maximum result age in seconds. Omitted values retain legacy behavior in older editions. |
| `ctx.tools.execute.id` | `string` | Yes | Stable durable receipt identity within one execution scope. |
| `ctx.tools.execute.tool` | `K` | Yes | Integration tool id resolved against the generated ToolMap. |
| `ctx.tools.execute.input` | `K extends keyof ToolMap ? ToolMap[K]['input'] : Record<string, unknown>` | Yes | Tool-specific input object. |
| `ctx.tools.execute.description` | `string` | No | Human-readable purpose of the durable tool call. |
| `ctx.tools.execute.force` | `boolean` | No | Explicitly bypasses a completed durable tool receipt. |
| `ctx.tools.execute.timeoutMs` | `number` | No | Positive whole-number runtime transport timeout in milliseconds. |
| `ctx.tools.execute.receiptWaitMs` | `number` | No | Positive whole-number durable receipt wait budget in milliseconds. |
| `ctx.csv.options.description` | `string` | No | Non-empty description for a staged CSV load. |
| `ctx.csv.options.columns` | `CsvRenameMap` | No | Canonical field-to-header aliases for a staged CSV. |
| `ctx.csv.options.rename` | `CsvRenameMap` | No | Legacy header rename aliases for a staged CSV. |
| `ctx.csv.options.required` | `readonly string[]` | No | Canonical columns required after CSV normalization. |
| `ctx.dataset.key` | `string` | Yes | Stable durable identity for one dataset. |
| `ctx.dataset.run.description` | `string` | No | Non-empty description for one dataset execution. |
| `ctx.dataset.run.key` | `DatasetRowKey<InputRow>` | No | Stable field or fields used for durable row identity. |
| `ctx.dataset.run.rowIdentity` | `'source_row' \| 'key'` | No | Edition 11 requires explicit freshness and semantic identity for supported durable calls. CSV inputs always use source-row occurrence identity, even with rowIdentity: "key". key-based dedup remains available for non-CSV inputs and editions 1–10. |
| `ctx.dataset.run.onRowError` | `'isolate' \| 'fail'` | No | Whether row failures isolate or fail the whole dataset. |
| `ctx.dataset.run.mode` | `'upsert' \| 'net_new'` | No | Whether the dataset returns all rows or only newly admitted rows. |
| `ctx.dataset.run.undrawnColumns` | `readonly string[]` | No | Computed columns deliberately left out of the authored @mermaid diagram. |
| `ctx.step.id` | `string` | Yes | Stable durable identity for one scalar checkpoint. |
| `ctx.step.semanticKey` | `string` | No | Optional semantic receipt identity for a scalar checkpoint. |
| `ctx.step.staleAfterSeconds` | `number \| null` | No | Edition 11 requires an explicit choice. `0` starts a fresh logical call, though a matching operation receipt may recover that same operation after resume. `null` allows indefinite result reuse. A positive integer is the maximum result age in seconds. Omitted values retain legacy behavior in older editions. |
| `ctx.fetch.key` | `string` | Yes | Stable durable identity for one external HTTP request. |
| `ctx.fetch.staleAfterSeconds` | `number \| null` | No | Edition 11 requires an explicit choice. `0` starts a fresh logical call, though a matching operation receipt may recover that same operation after resume. `null` allows indefinite result reuse. A positive integer is the maximum result age in seconds. Omitted values retain legacy behavior in older editions. |
| `ctx.runPlay.key` | `string` | Yes | Stable identity for one inline child Play call. |
| `ctx.runPlay.playRef` | `string \| PlayReferenceLike` | Yes | Child Play name or typed Play definition handle. |
| `ctx.runPlay.input` | `Record<string, unknown>` | Yes | Scalar input object submitted to the child Play. |
| `ctx.runPlay.options.description` | `string` | Yes | Non-empty purpose for one inline child Play call. |
| `ctx.runPlay.options.execution` | `'inline'` | No | Child composition strategy. Only inline is supported. |
| `ctx.runPlay.options.timeoutMs` | `never` | No | Unsupported legacy child-workflow timeout. |
| `ctx.runPlayAsync.key` | `string` | Yes | Stable identity for one independent child Play Run. |
| `ctx.runPlayAsync.playRef` | `string \| PlayReferenceLike` | Yes | Independently published scalar child Play name or strongly typed definition handle. |
| `ctx.runPlayAsync.input` | `Record<string, unknown>` | Yes | Scalar input object submitted to the independent child Run. |
| `ctx.runPlayAsync.options.description` | `string` | Yes | Non-empty purpose for one independent child Play Run. |
| `runtime.timeout` | `string` | No | Play-level sandbox deadline. The default is 30m. Use a static duration such as 90m or 2h, up to 4h. |
| `runtime.size` | `'standard'` | No | Deepline-managed sandbox size. Only standard is supported. |
| `ctx.customerDb.query.statement` | `SqlQuery` | Yes | One non-empty Customer DB SQL string. The deprecated SqlQuery object is accepted only without parameter values. |
| `ctx.customerDb.query.options.id` | `string` | Yes | Stable operation identity for Customer DB query recovery. |
| `ctx.customerDb.query.options.staleAfterSeconds` | `number \| null` | No | Customer DB queries always execute with freshness 0. |
| `ctx.customerDb.query.options.maxRows` | `number` | No | Positive whole-number Customer DB response row limit. |
| `ctx.customerDb.query.options.timeoutMs` | `number` | No | Positive whole-number Customer DB timeout in milliseconds. |
| `ctx.tool.key` | `string` | Yes | Stable receipt identity for the tool shorthand. |
| `ctx.tool.tool` | `string` | Yes | Integration tool id for the tool shorthand. |
| `ctx.tool.input` | `Record<string, unknown>` | Yes | Tool-specific input object for the shorthand. |
| `ctx.tool.options.description` | `string` | No | Non-empty purpose for the tool shorthand. |
| `ctx.runSteps.options.description` | `string` | No | Non-empty purpose for a reusable step program. |
| `ctx.runSteps.options.staleAfterSeconds` | `number \| null` | No | Edition 11 requires an explicit choice. `0` starts a fresh logical call, though a matching operation receipt may recover that same operation after resume. `null` allows indefinite result reuse. A positive integer is the maximum result age in seconds. Omitted values retain legacy behavior in older editions. |
| `ctx.sleep.ms` | `number` | Yes | Non-negative whole-number sleep duration in milliseconds. |
| `ctx.fetch.url` | `string` | Yes | HTTP request URL. Secret authentication requires HTTPS. |
| `ctx.fetch.init.method` | `string` | No | HTTP method. Mutating methods require an Idempotency-Key. |
| `ctx.fetch.init.headers.Idempotency-Key` | `string` | No | Required for mutating HTTP methods. The provider must support idempotency, and the same key must be retained across retries and replay. |

### Durable call keys are static

Durable call keys — the ctx.fetch key, the ctx.dataset key, the ctx.step id — must be static string literals. The key names a durable receipt, so check, publish, and replay have to agree on it before the body runs. A key computed at runtime cannot be resolved at check time and is rejected.

This is an architectural constraint, not a style rule. A play cannot loop over a computed key, so it cannot page a large table with a helper like page(pageNumber). Unrolling one literal key per page is not a design at any real page count.

Push the aggregation server-side and call it once: a SQL function, a view, or a provider endpoint that returns the whole result. Keep unrolled literal keys only for a handful of genuinely distinct calls. To fan out over rows, use ctx.dataset with a static key — the per-row receipt identity comes from the row, not from the key.

### Durable HTTP batches

A static ctx.fetch key inside a loop is a warning because every iteration must still have distinct method, URL, body, or safe headers. One durable receipt must never stand in for every request.

Keep the static fetch label. For a mutating batch, make the body distinct and use a replay-stable external Idempotency-Key such as `${ctx.run.id}:signals:${batchIndex}`.

### `ctx.run.id`

ctx.run.id is stable while Deepline retries or resumes one durable run. A separately submitted run receives a new id.

Use it when deriving an external idempotency key for a sequence of batches.

### Runtime capabilities

| Capability | Surface | Contract |
| - | - | - |
| Durable external I/O | `ctx.fetch`, `ctx.tools.execute`, `ctx.step`, `ctx.runPlay` | Use a `ctx.*` primitive for external work. Each primitive owns durable receipt identity and replay. raw I/O in an authored handler does not. |
| Web Crypto | `crypto.subtle` | WebCrypto is available for standards-based signing, verification, encryption, and key import. Keep private material in `ctx.secrets`. `docs-examples/sdk-v2/github-app-jwt.play.ts` is an edition-10 compatibility example. edition 11 allows transient fetches only for read-only methods, so do not copy its credential-returning POST into new source. |
| Workspace secrets | `ctx.secrets.get`, `.bearer`, `.header` | Declare the secret at the Play boundary, read it only at runtime, and never return or log it. Secret-bearing HTTP requests require HTTPS. |
| Freshness | `staleAfterSeconds` on durable calls | New source in edition 11 must choose freshness explicitly. Zero executes a new logical call, a positive integer is a maximum result age in seconds, and null allows indefinite reuse. A completed operation receipt separately recovers the same intended operation after resume. |

Generated from SDK source comments and type declarations by `scripts/generate-play-sdk-reference.ts`. Do not edit this file manually. Field tables cover current authoring. The SDK retains deprecated compatibility properties, but these tables omit them.

## Version And Coverage

| Field | Value |
| - | - |
| SDK version | `0.3.90` |
| SDK HTTP API | `v3` |
| Minimum supported SDK | `0.1.53` |
| Deprecated below | `0.3.1` |
| Generated sources | `packages/plays/authoring-contract.ts` `packages/plays/cell-staleness.ts` `packages/plays/dataset.ts` `packages/plays/fetch-http-error.ts` `packages/plays/tool-execution-error.ts` `packages/plays/tool-result-types.ts` `packages/sdk/src/client.ts` `packages/sdk/src/errors.ts` `packages/sdk/src/play.ts` |
| Coverage | Runtime SDK surface: `Deepline.connect`, `DeeplineContext`, `DeeplineClient`, play authoring, in-play `ctx.*` primitives, provider/tool calls, named play handles, run handles, datasets, and tool result accessors. |
| Not covered | Full CLI command help, provider-specific input/output schemas, dashboard-only routes, and marketing/tutorial guides. Use `references/plays-api-reference.md` for generated HTTP route contracts. |

## Runtime Entrypoints

### `Deepline`

Static entry point for the Deepline SDK.

Signature: `class Deepline`

#### Members

| Member | Kind | Purpose | Parameters | Returns / type |
| - | - | - | - | - |
| `connect` | method | Create a connected SDK context. Resolves configuration from options, environment variables, and CLI config files. See `resolveConfig` for the resolution order. | `options?: DeeplineClientOptions` - Optional overrides for API key, base URL, etc. | `Promise<DeeplineContext>` |

### `DeeplineContext`

SDK context with tool shortcuts and play handles, created by `Deepline.connect`. Wraps a `DeeplineClient` for common operations.

Signature: `class DeeplineContext`

#### Members

| Member | Kind | Purpose | Parameters | Returns / type |
| - | - | - | - | - |
| `constructor` | constructor | Create a high-level SDK context. Most callers should use `Deepline.connect`. direct construction is equivalent when you already have explicit client options. | `options?: DeeplineClientOptions` - Optional SDK client configuration. | |
| `billing` | getter | Read current billing usage and exact per-request Deepline charges. | | `BillingNamespace` |
| `tools` | getter | Tool operations namespace. | | `DeeplineToolsNamespace` |
| `executions` | getter | Durable state for recoverable direct tool executions. | | `DeeplineExecutionsNamespace` |
| `plays` | getter | Play discovery and named-play handles. Use `plays.list()` for discovery and `plays.get(name)` when you prefer a namespace spelling over `ctx.play(name)`. | | `DeeplinePlaysNamespace` |
| `prebuilt` | getter | Convenience references for Deepline-managed prebuilt plays. Known prebuilts are exposed by camel-cased aliases. Any other property is converted into `prebuilt/<property>` so callers can pass the reference to `ctx.runPlay(...)`. | | `Record<string, PrebuiltPlayRef>` |
| `play` | method | Get a named play handle for remote lifecycle operations. | `name: string` - Play name (as registered on the server) | `DeeplineNamedPlay<TInput, TOutput>` |
| `runPlay` | method | Run a named or prebuilt play and wait for its output. This is the high-level SDK equivalent of `ctx.play(name).runSync(input)`. Inside a Play, prefer `ctx.runPlay(key, playRef, input, options)`. The runtime checkpoints the child run under a stable key. | `playOrRef: string \| PlayReferenceLike` - Play name or prebuilt/reference object. `input: TInput` - JSON input passed to the play. | `Promise<TOutput>` |

## Play Authoring And In-Play Runtime

### `definePlay`

Define a play — a composable TypeScript workflow for the Deepline platform.

The returned value is both a callable function and a named Play handle.
The Deepline runtime calls the function with a runtime context.
The handle provides `.run()`, `.versions()`, `.get()`, and `.publish()` for remote lifecycle operations.
Plays define repeatable data pipelines. The runtime executes them durably with automatic retries and timeouts.

Signature: `export function definePlay<TInput, TOutput extends PlayReturnObject>( config: DefinePlayConfig<TInput, TOutput>, ): DefinedPlay<TInput, TOutput>; export function definePlay< THandler extends ( context: DeeplinePlayRuntimeContext, input: any, ) => Promise<PlayReturnObject>, >( name: string, fn: THandler, bindings?: PlayBindings<NoInfer<PlayHandlerInput<THandler>>>, ): DefinedPlay<PlayHandlerInput<THandler>, PlayHandlerOutput<THandler>>;`

#### Overload 1

#### Parameters

| Name | Type | Required | Description |
| - | - | -: | - |
| `config` | `DefinePlayConfig<TInput, TOutput>` | Yes | Object-form play config. |

Returns: `DefinedPlay<TInput, TOutput>`

#### Overload 2

#### Parameters

| Name | Type | Required | Description |
| - | - | -: | - |
| `name` | `string` | Yes | Play name. |
| `fn` | `THandler` | Yes | Play function. |
| `bindings` | `PlayBindings<NoInfer<PlayHandlerInput<THandler>>>` | No | Play configuration, including runtime limits and triggers. |

Returns: `DefinedPlay<PlayHandlerInput<THandler>, PlayHandlerOutput<THandler>>`

### `DefinePlayConfig`

Object-form play definition accepted by `definePlay(config)`.

Use this form when the input contract should be explicit at definition time
through `defineInput<T>(schema)`, or when configuration reads clearer as one
object. The shorthand `definePlay(name, fn, bindings?)` is equivalent for
simple file-backed plays.\
&#x20;Signature: `export type DefinePlayConfig< TInput, TOutput extends PlayReturnObject, > = PlayAuthoringDefineConfig<TInput, TOutput, DeeplinePlayRuntimeContext>;`

### `PlayBindings`

Optional Play configuration, including triggers and runtime limits.

A play can be triggered three ways, declared as the third argument to
[definePlay](https://deepline.com/docs/sdk-v2/sdk-reference.md#defineplay):

* `webhook` — an inbound HTTP call (with optional legacy HMAC or Standard
  Webhooks signature verification).
* `cron` — a schedule.
* `sqlListeners` — a **monitor**: the play runs whenever a monitor writes a new
  row to its output stream. This is how you build a play "on top of" a monitor
  (e.g. run enrichment every time a watched company posts a new job). Each
  listener binds to a monitor tool id + one of its output stream keys (see
  `deepline monitors available <id>` for a tool's streams and row columns).
  The changed row is delivered to the handler as the listener event's `after`.

The default Play runtime is 30 minutes. For bounded long-running batches, add
`runtime: { timeout: '90m', size: 'standard' }`. duration values are whole minutes or hours, up to `4h`.
It differs from `ctx.tools.execute({ timeoutMs })`, which limits one provider call.\
&#x20;Signature: `export type PlayBindings<TInput = Record<string, unknown>> = PlayAuthoringBindings<TInput>;`

### `ctx.csv(path, options)`

Load a staged CSV file as a durable dataset handle.

Signature: `csv<T = Record<string, unknown>>( path: string | CsvInput<T & object>, options?: CsvOptions, ): Promise<PlayDataset<T>>;`

#### Parameters

| Name | Type | Required | Description |
| - | - | -: | - |
| `path` | `string \| CsvInput<T & object>` | Yes | |
| `options` | [`CsvOptions`](#csvoptions) | No | |

Returns: `Promise<PlayDataset<T>>` — see [`PlayDataset`](#playdataset)

### `CsvOptions`

Options for loading a staged CSV with `ctx.csv(...)`.\
&#x20;Signature: `export type CsvOptions = CsvOptions;`

### `ctx.dataset(key, items)`

Create a persisted row dataset and define durable output columns.

Signature: `dataset<TSource extends PlayDatasetInput<object>>( key: string, items: TSource, ): DatasetBuilder< PlayDatasetRow<TSource> & object, PlayDatasetRow<TSource> & object, DeeplinePlayRuntimeContext >;`

#### Parameters

| Name | Type | Required | Description |
| - | - | -: | - |
| `key` | `string` | Yes | |
| `items` | `TSource` | Yes | |

Returns: `DatasetBuilder< PlayDatasetRow<TSource> & object, PlayDatasetRow<TSource> & object, DeeplinePlayRuntimeContext >`

### `.dataset(...).withColumn(name, resolver).run(options)`

Define one output column for every row in this dataset.

```ts theme={"languages":{"custom":["/languages/deepline-prompt.json"]}}
withColumn<Name extends string, Value>( name: Name, resolver: ColumnResolver<OutputRow, Value>, ): DatasetBuilder< InputRow, OutputRow & Record<Name, Value> >;

withColumn<Name extends string, Value>( name: Name, definition: DatasetColumnDefinition< OutputRow, Value > & { readonly runIf: ( row: OutputRow, index: number, ) => boolean | Promise<boolean>; }, ): DatasetBuilder< InputRow, OutputRow & Record<Name, Value | null> >;

withColumn<Name extends string, Value>( name: Name, definition: DatasetColumnDefinition< OutputRow, Value >, ): DatasetBuilder< InputRow, OutputRow & Record<Name, Value> >;

withColumn<Name extends string, Value>( name: Name, resolver: StepResolver<OutputRow, Value> | RunnableStepProgram<unknown, Value>, options: StepOptions<OutputRow, Value>, ): DatasetBuilder< InputRow, OutputRow & Record<Name, Value | null> >;

run( options?: DatasetRunOptions<InputRow>, ): Promise<PlayDataset<OutputRow>>;
```

#### Column Overload 1 Parameters

| Name | Type | Required | Description |
| - | - | -: | - |
| `name` | `Name` | Yes | |
| `resolver` | `ColumnResolver<OutputRow, Value>` | Yes | |

Column Overload 1 Returns: `DatasetBuilder< InputRow, OutputRow & Record<Name, Value> >`

#### Column Overload 2 Parameters

| Name | Type | Required | Description |
| - | - | -: | - |
| `name` | `Name` | Yes | |
| `definition` | `DatasetColumnDefinition< OutputRow, Value > & { readonly runIf: ( row: OutputRow, index: number, ) => boolean \| Promise<boolean>; }` | Yes | |

Column Overload 2 Returns: `DatasetBuilder< InputRow, OutputRow & Record<Name, Value | null> >`

#### Column Overload 3 Parameters

| Name | Type | Required | Description |
| - | - | -: | - |
| `name` | `Name` | Yes | |
| `definition` | `DatasetColumnDefinition< OutputRow, Value >` | Yes | |

Column Overload 3 Returns: `DatasetBuilder< InputRow, OutputRow & Record<Name, Value> >`

#### Column Overload 4 Parameters

| Name | Type | Required | Description |
| - | - | -: | - |
| `name` | `Name` | Yes | |
| `resolver` | `\| StepResolver<OutputRow, Value> \| RunnableStepProgram<unknown, Value>` | Yes | |
| `options` | `StepOptions<OutputRow, Value>` | Yes | |

Column Overload 4 Returns: `DatasetBuilder< InputRow, OutputRow & Record<Name, Value | null> >`

#### Run Parameters

| Name | Type | Required | Description |
| - | - | -: | - |
| `options` | `DatasetRunOptions<InputRow>` | No | |

Run Returns: `Promise<PlayDataset<OutputRow>>` — see [`PlayDataset`](#playdataset)

Execute the row-column program and return a durable dataset handle.
`upsert` preserves row-by-row enrichment. `net_new` admits and returns only
unseen stable keys. `isolate` records failed rows while siblings continue.
`fail` opts into fail-fast behavior.

### `DatasetColumnRunInput`

Input object passed to an object-column `run` resolver.

| Name | Type | Required | Description |
| - | - | -: | - |
| `row` | `Row` | Yes | Current row, including previously computed columns. |
| `ctx` | `DeeplinePlayRuntimeContext` | Yes | Runtime context for tool, Play, fetch, and log calls. |
| `index` | `number` | Yes | Zero-based row index for this dataset run. |
| `previousCell` | `PreviousCell<Value>` | No | Prior stored cell value and freshness metadata when this cell reruns. |

### `DatasetColumnDefinition`

Object-column form for `.withColumn(...)`.

Use this when a column needs `runIf` or typed `previousCell`.

| Name | Type | Required | Description |
| - | - | -: | - |
| `run` | `( input: DatasetColumnRunInput<Row, Value>, ) => Value \| Promise<Value>` | Yes | Compute one cell value. Receives the previous stored value when rerunning. |
| `runIf` | `(row: Row, index: number) => boolean \| Promise<boolean>` | No | Optional row-level gate. Skipped rows produce `null` for this column. |

### `StepOptions`

Options for row-level `.withColumn(...)` and `steps().step(...)` entries.

| Name | Type | Required | Description |
| - | - | -: | - |
| `runIf` | `(row: Row, index: number) => boolean \| Promise<boolean>` | No | Optional row-level gate. Skipped rows produce `null` for this column. |
| `recompute` | `boolean` | No | Legacy dataset-column flag. Prefer freshness on the reusable call. |
| `recomputeOnError` | `boolean` | No | Legacy error-recompute flag accepted for older authored Plays. |
| `staleAfterSeconds` | `number \| null` | No | Legacy cell staleness metadata accepted for older authored Plays. |

### `PreviousCell`

Previous durable cell value passed to object-column resolvers.

The runtime supplies this when a row+column is being recomputed after a
previous value existed. `value` has the same type that the column returns.
freshness metadata lives beside it.

| Name | Type | Required | Description |
| - | - | -: | - |
| `value` | `Value` | Yes | Previous completed value for this row+column. |
| `completedAt` | `number` | No | Millisecond timestamp when the previous value completed. |
| `staleAt` | `number \| null` | No | Millisecond timestamp when the previous value becomes stale. `null` means no expiry. |
| `staleAfterSeconds` | `number` | No | Resolved numeric TTL in seconds for the previous value, when present. |

### `ctx.step(id, fn)`

Create one scalar durable checkpoint.

Signature: `step<T>( id: string, run: () => T | Promise<T>, options?: RuntimeStepOptions, ): Promise<T>;`

#### Parameters

| Name | Type | Required | Description |
| - | - | -: | - |
| `id` | `string` | Yes | |
| `run` | `() => T \| Promise<T>` | Yes | |
| `options` | `RuntimeStepOptions` | No | |

Returns: `Promise<T>`

### `ctx.runPlay(key, playRef, input, options)`

Compose another Play inline under a stable call key.

Signature: `runPlay<TOutput = unknown>( key: string, playRef: string | PlayReferenceLike, input: Record<string, unknown>, options: PlayCallOptions, ): Promise<TOutput>;`

#### Parameters

| Name | Type | Required | Description |
| - | - | -: | - |
| `key` | `string` | Yes | |
| `playRef` | `string \| PlayReferenceLike` | Yes | |
| `input` | `Record<string, unknown>` | Yes | |
| `options` | `PlayCallOptions` | Yes | |

Returns: `Promise<TOutput>`

### `ctx.runPlayAsync(key, playRef, input, options)`

Admit an independent scalar Play Run and return its durable identity after scheduler admission, before child completion.

Signature: `runPlayAsync<TInput extends Record<string, unknown>>( key: string, playRef: PlayReferenceLike<TInput>, input: NoInfer<TInput>, options: PlayAuthoringAsyncCallOptions, ): Promise<AsyncPlayRunRef>;`

#### Parameters

| Name | Type | Required | Description |
| - | - | -: | - |
| `key` | `string` | Yes | |
| `playRef` | `PlayReferenceLike<TInput>` | Yes | |
| `input` | `NoInfer<TInput>` | Yes | |
| `options` | `PlayAuthoringAsyncCallOptions` | Yes | |

Returns: `Promise<AsyncPlayRunRef>` — see [`AsyncPlayRunRef`](#asyncplayrunref)

### `AsyncPlayRunRef`

Serializable reference returned after an async child Run is durable.\
&#x20;Signature: `export type AsyncPlayRunRef = Readonly<{ runId: PlayRunId; }>;`

### `ctx.tools.execute(request)`

Execute a provider tool through the terminal-result cache contract.

Signature: `execute<TOutput = PlayLooseObject>( request: PlayToolExecutionRequest, ): Promise< ToolExecuteResult<TOutput> >;`

#### Parameters

| Name | Type | Required | Description |
| - | - | -: | - |
| `request` | `PlayToolExecutionRequest` | Yes | |

Returns: `Promise< ToolExecuteResult<TOutput> >` — see [`ToolExecuteResult`](#toolexecuteresult)

### `ToolExecutionRequest`

Keyword-style request object for `ctx.tools.execute(...)`.

The `tool` value comes from live tool discovery. The `id` is the stable
logical call name used for logs, metadata, and result-cache identity. Provider
result reuse is keyed by play, tool, semantic input, auth scope, provider action
version, and cache policy.\
&#x20;Signature: `export type ToolExecutionRequest = PlayToolExecutionRequest;`

### `ctx.fetch(key, url, init)`

Execute a guarded HTTP request. Edition 11 requires an explicit freshness choice. Only GET, HEAD, and OPTIONS can retain completed responses. Mutating methods must use `staleAfterSeconds: 0`. The choice governs only the completed call receipt, never dataset/request identity. Failed requests do not publish completed cache entries. A headers timeout leaves an upstream write's outcome unknown and does not establish whether its body was sent. The transport does not automatically retry that timed-out write, but a later invocation can execute it again. Mutating requests require provider-supported idempotency with the same key retained across retries and replay. Deadlines are platform-controlled. callers may cancel through `init.signal`. Pass `{ transient: true }` only on GET, HEAD, and OPTIONS when the response must not be retained in a receipt or checkpoint. edition 11 rejects transient writes. Edition 5+ throws `CtxFetchHttpError` for non-2xx. catch it only when the Play intentionally recovers, otherwise let it fail the Play. Editions 1–4 retain their previous response projections.

Signature: `fetch( key: string, url: string | URL, init?: SecretAwareRequestInit, options?: FetchOptions, ): Promise<PlayFetchResponse>;`

#### Parameters

| Name | Type | Required | Description |
| - | - | -: | - |
| `key` | `string` | Yes | |
| `url` | `string \| URL` | Yes | |
| `init` | [`SecretAwareRequestInit`](#secretawarerequestinit) | No | |
| `options` | `FetchOptions` | No | |

Returns: `Promise<PlayFetchResponse>` — see [`PlayFetchResponse`](#playfetchresponse)

### `ctx.secrets.get(name)`

Read an allowed workspace secret inside the running Play. do not log or return it. Declare uppercase names in top-level `secrets`.

Signature: `get(name: string): PlaySecretPromise;`

#### Parameters

| Name | Type | Required | Description |
| - | - | -: | - |
| `name` | `string` | Yes | |

Returns: `PlaySecretPromise`

### `ctx.secrets.bearer(secret)`

Send a credential as `Authorization: Bearer <value>`. Await `get` first.
its direct promise remains accepted for source compatibility, while other
promises are rejected.

Signature: `bearer( secret: string | PlaySecretPromise | SecretHandle, ): SecretAuth;`

#### Parameters

| Name | Type | Required | Description |
| - | - | -: | - |
| `secret` | `string \| PlaySecretPromise \| SecretHandle` | Yes | |

Returns: `SecretAuth` — see [`SecretAuth`](#secretauth)

### `ctx.secrets.header(header, secret)`

Send a credential as a named header, for APIs that do not use bearer
tokens — `x-api-key`, `apikey`, `private-token`, and similar.

Signature: `header( header: string, secret: string | PlaySecretPromise | SecretHandle, ): SecretAuth;`

#### Parameters

| Name | Type | Required | Description |
| - | - | -: | - |
| `header` | `string` | Yes | |
| `secret` | `string \| PlaySecretPromise \| SecretHandle` | Yes | |

Returns: `SecretAuth` — see [`SecretAuth`](#secretauth)

### `SecretAwareRequestInit`

The `init` accepted by `ctx.fetch`. Same shape as `RequestInit` plus `auth`.

| Name | Type | Required | Description |
| - | - | -: | - |
| `headers` | `HeadersInit` | No | Ordinary request headers, recorded in the durable receipt with any resolved Play secret value redacted. Prefer `auth` for credentials: it enforces HTTPS and keeps the auth header out of the receipt. |
| `auth` | `SecretAuthInput` | No | One or more credentialed headers for this request. Pass a single `ctx.secrets` auth for the common case, or an array when an API requires multiple credentialed headers. Auth-helper requests require HTTPS and omit the credential from the durable receipt. Each auth entry must target a distinct header. |

### `PlayFetchResponse`

A durable response record, not a WHATWG `Response`: read the already-materialized `bodyText` and `json` properties. do not call `.json()`, `.text()`, or `.body`.

| Name | Type | Required | Description |
| - | - | -: | - |
| `freshness` `ok` | `import('./tool-result-types').CallFreshnessMetadata` `boolean` | No Yes | Freshness and same-run recovery metadata for edition 11 calls. True when the response status is in the 2xx range. |
| `status` | `number` | Yes | HTTP status code as returned by the upstream server. |
| `statusText` | `string` | Yes | HTTP status text as returned by the upstream server. |
| `url` | `string` | Yes | Final response URL after any redirects. |
| `headers` | `Record<string, string>` | Yes | Response headers, lowercased, with any known secret values redacted. |
| `bodyText` | `string` | Yes | Full response body as text, with any known secret values redacted. |
| `json` | `unknown \| null` | Yes | The runtime parses the body at request time. Read the property with `const body = res.json`. Do not call `await res.json()`. The value is null when the body is empty or is not valid JSON. Malformed JSON produces null instead of an error. Check `res.ok`. Check `res.bodyText` before you interpret null as an empty response. |

### `SecretHandle`

An opaque reference to a workspace secret used by legacy authoring-contract
editions. New Plays receive plaintext strings from `ctx.secrets.get`.

| Name | Type | Required | Description |
| - | - | -: | - |
| `name` | `string` | Yes | Name of the workspace secret, uppercased. Never its value. |

### `SecretAuth`

One resolved authentication scheme, built by `ctx.secrets.bearer` or `ctx.secrets.header` and attached to a request through `init.auth`.

| Name | Type | Required | Description |
| - | - | -: | - |
| `kind` | `'bearer' \| 'header'` | Yes | `bearer` sends `Authorization: Bearer <value>`. `header` sends a named header. |
| `secret` | `string \| PlaySecretPromise \| PlaySecretValue` | Yes | The value whose bytes the runtime attaches. |
| `header` | `string` | No | Header name, set only when `kind` is `header`. |

### `CtxFetchHttpError`

Edition 5+ `ctx.fetch` error for a non-2xx response. Its full readable body is secret-redacted. editions 1–4 retain `PlayFetchResponse { ok: false }`.

Signature: `class CtxFetchHttpError extends Error`

#### Members

| Member | Kind | Purpose | Parameters | Returns / type |
| - | - | - | - | - |
| `constructor` | constructor | Build the error from the durable response record. | `response: PlayAuthoringFetchResponse` | |
| `code` | property | Stable machine-readable HTTP-failure code. | | `"CTX_FETCH_HTTP_ERROR"` |
| `status` | property | Upstream HTTP status. | | `number` |
| `statusText` | property | Upstream HTTP status text. | | `string` |
| `url` | property | Final response URL after redirects. | | `string` |
| `headers` | property | Secret-redacted response headers. | | `Record<string, string>` |
| `bodyText` | property | Complete secret-redacted response body. | | `string` |
| `json` | property | Eagerly parsed secret-redacted JSON, or null. | | `unknown \| null` |

### `ctx.billing.entitlements()`

Read current workspace plan benefits. Execution rechecks admission.
this read is fresh and is not a durable receipt.

Signature: `entitlements(): Promise<BillingEntitlements>;`

Returns: `Promise<BillingEntitlements>`

### `ctx.runSteps(program, input, options)`

Execute one reusable step program against a scalar input.

Signature: `runSteps<TInput extends Record<string, unknown>, TOutput>( program: PlayAuthoringRunnableStepProgram< TOutput, DeeplinePlayRuntimeContext > & { readonly __inputType?: (input: TInput) => void }, input: TInput, options?: PlayAuthoringRunStepsOptions, ): Promise<TOutput>;`

#### Parameters

| Name | Type | Required | Description |
| - | - | -: | - |
| `program` | `PlayAuthoringRunnableStepProgram< TOutput, DeeplinePlayRuntimeContext > & { readonly __inputType?: (input: TInput) => void }` | Yes | |
| `input` | `TInput` | Yes | |
| `options` | `PlayAuthoringRunStepsOptions` | No | |

Returns: `Promise<TOutput>`

### `PlayDataset`

Durable handle for rows produced by `ctx.csv(...)` or `ctx.dataset(...).run()`.

A `PlayDataset` is not a normal in-memory array. It points at runtime-managed
rows, usually backed by persisted sheet storage, and carries metadata such as
dataset kind, dataset id, table namespace, count, and preview rows.

Pass dataset handles directly into later `ctx.dataset(...)` stages by default so
Deepline keeps row progress, retries, memory use, and table output under
runtime control. Use `count()` and `peek()` for bounded inspection. Use
`materialize(limit)` or async iteration only when the dataset is intentionally
small and bounded. `PlayDataset` intentionally does not expose `.rows`,
`.toArray()`, `.length`, numeric indexing, spread, or synchronous iteration.
these hide loading costs or make behavior depend on row residency.

| Name | Type | Required | Description |
| - | - | -: | - |
| `datasetKind` | `PlayDatasetKind` | Yes | Dataset kind. |
| `datasetId` | `string` | Yes | Dataset id. |
| `backing` | `PlayDatasetBacking` | No | Backing store info. |
| `sourceLabel` | `string \| null` | No | Display label. |
| `tableNamespace` | `string \| null` | No | Runtime table name. |
| `columnTypes` | `PlayDatasetColumnTypes` | No | Advisory source types. transformed fields must infer from their values. |

### `ToolExecuteResult`

Canonical result returned by Deepline tool execution.

Provider data: `toolResponse.rawV2`. metadata: `toolResponse.meta`.
Single-value getters: `extractedValues.<name>.get()`. lists: `extractedLists.<name>.get()`.

Prefer declared getters. Edition 10 and later Plays receive ordinary arrays from
list `.get()` synchronously. persist explicitly with ctx.dataset. Lazy or
incomplete lists throw: use readList(result, path) for explicit dataset access.
Provider pagination requires a separate request. getters never fetch it.
Historical editions 1–9 retain PlayDataset getters and async materialize/peek.
missing getters never mean empty results. Inspect rawV2 for debugging: parsed,
scrubbed envelopes, pagination and siblings, not HTTP bytes or headers.\
&#x20;Signature: `export type ToolExecuteResult< TResult = unknown, TMeta = Record<string, unknown>, TExtracted extends Record<string, unknown> = Partial<DeeplineGetterValueMap>, TLists extends Record<string, Record<string, unknown>> = Record< string, Record<string, unknown> >, > = ToolExecuteResultBase<TResult, TMeta> & ToolExecuteResultAccessors<TExtracted, TLists>;`

## Errors And Provider Fallthrough

New Plays receive typed tool errors. Existing published artifacts keep the error contract stored with their revision.

For a read waterfall, catch only `ProviderTransientError` and keep the final provider call loud. For structured diagnostics, narrow to `ToolExecutionError` and branch on its stable fields. Never branch on `error.message`.

A newly authored Play can explicitly retain legacy errors with `compatibility: { toolErrorSchemaVersion: 0 }` in its `definePlay` options. Use that only while migrating old message-based handling.

### `DeeplineError`

Base error class shared by the SDK and play runtime.

The global brand preserves `instanceof DeeplineError` when a bundled play
and the runtime load separate physical copies of this module.

Signature: `class DeeplineError extends Error`

#### Members

| Member | Kind | Purpose | Parameters | Returns / type |
| - | - | - | - | - |
| `constructor` | constructor | Construct a Deepline error. SDK and runtime code construct these errors. Application and Play code normally catches the public subclasses instead. | `message: string` - Human-readable failure summary. `statusCode?: number` - HTTP status when one exists. `code?: string` - Stable machine-readable code when one exists. `details?: Record<string, unknown>` - Local diagnostic context. Never a portable error contract. | |
| `statusCode` | property | HTTP status when the failure crossed an HTTP boundary. | | `number` |
| `code` | property | Stable machine-readable error code when one exists. | | `string` |
| `details` | property | Local diagnostic context. Not a portable error contract. | | `Record<string, unknown>` |

### `ToolExecutionErrorOrigin`

The boundary responsible for a failed tool call.

Use `provider` to distinguish a provider answer from caller input and
Deepline infrastructure. `unknown` fails closed and must not trigger a
waterfall fallback.\
&#x20;Signature: `export type ToolExecutionErrorOrigin = | 'caller' | 'provider' | 'deepline' | 'unknown';`

### `ToolExecutionErrorCategory`

The stable reason family for a failed tool call.

Branch on this field only after narrowing to `ToolExecutionError`. Catch
`ProviderTransientError` when the policy is simply “try the next read
provider”. It is the safer and shorter waterfall contract.\
&#x20;Signature: `export type ToolExecutionErrorCategory = | 'validation' | 'authentication' | 'authorization' | 'rate_limit' | 'network' | 'upstream' | 'billing' | 'conflict' | 'internal' | 'unknown';`

### `ToolExecutionNetworkKind`

The transport failure observed when `category` is `network`.

This is `null` for failures that are not network failures.\
&#x20;Signature: `export type ToolExecutionNetworkKind = | 'timeout' | 'dns' | 'connect' | 'reset' | 'unavailable' | 'unknown';`

### `ToolExecutionNetworkScope`

The request boundary on which a network failure occurred.

`deepline_to_provider` is provider-side. Client and runtime scopes are
Deepline transport failures and never qualify as provider fallthrough.\
&#x20;Signature: `export type ToolExecutionNetworkScope = | 'client_to_deepline' | 'runtime_to_deepline' | 'deepline_to_provider';`

### `ProviderTransientErrorCategory`

Provider-owned failure categories that may fall through to another read
provider.\
&#x20;Signature: `export type ProviderTransientErrorCategory = | 'rate_limit' | 'network' | 'upstream';`

### `ToolExecutionPublicDetails`

Bounded, primitive-only diagnostics explicitly approved for customers.
Raw provider bodies, credentials, prompts, stacks, and causes never belong
in this shared API/SDK/Play contract.\
&#x20;Signature: `export type ToolExecutionPublicDetails = Readonly< Record<string, string | number | boolean | null> >;`

### `ToolExecutionFailureV1`

Portable version-1 `tool_error` payload.

This allowlisted shape crosses the API, runtime, and SDK boundaries.
`message` remains on the Error object and is deliberately not a policy
field.

| Name | Type | Required | Description |
| - | - | -: | - |
| `schemaVersion` | `typeof TOOL_EXECUTION_ERROR_SCHEMA_VERSION` | Yes | Payload version. |
| `toolId` | `string` | Yes | Public tool id passed to `tools.execute`. |
| `provider` | `string \| null` | Yes | Provider responsible for the operation, or `null`. |
| `operation` | `string \| null` | Yes | Provider operation name, or `null`. |
| `code` | `string \| null` | Yes | Stable machine-readable failure code, or `null`. |
| `origin` | `ToolExecutionErrorOrigin` | Yes | Boundary responsible for the failure. |
| `category` | `ToolExecutionErrorCategory` | Yes | Stable reason family. |
| `retryable` | `boolean` | Yes | Whether repeating the same semantic call is delivery-safe. |
| `statusCode` | `number \| null` | Yes | HTTP status when one exists, or `null`. |
| `requestId` | `string \| null` | Yes | Provider or Deepline request id, or `null`. |
| `retryAfterMs` | `number \| null` | Yes | Suggested same-call retry delay in milliseconds, or `null`. |
| `networkKind` | `ToolExecutionNetworkKind \| null` | Yes | Network failure kind, or `null`. |
| `networkScope` | `ToolExecutionNetworkScope \| null` | Yes | Network boundary that failed, or `null`. |
| `publicDetails` | `ToolExecutionPublicDetails \| null` | No | Explicitly allowlisted customer diagnostics, when present. |

### `ToolExecutionErrorOptions`

Constructor input for a structured tool failure.

Deepline creates these values while decoding the versioned wire payload.
Customer code normally reads `ToolExecutionError` fields instead of
constructing an error.

| Name | Type | Required | Description |
| - | - | -: | - |
| `details` | `Record<string, unknown>` | No | Local diagnostic context inherited from DeeplineError. This is not part of the portable failure payload and is intentionally omitted by serialization. |

### `ToolExecutionError`

A failed `tools.execute` call with stable, allowlisted provenance.

`retryable` means Deepline's delivery/idempotency contract says it is safe
to repeat the same semantic call. It does not describe durable receipt
repairability and does not make arbitrary side-effecting fallbacks safe.

In a Play, catch `ProviderTransientError` to continue a read waterfall and
let every other `ToolExecutionError` remain loud. In an SDK client, catch
this base class when you need structured diagnostics for every tool failure.

Signature: `class ToolExecutionError extends DeeplineError`

#### Members

| Member | Kind | Purpose | Parameters | Returns / type |
| - | - | - | - | - |
| `constructor` | constructor | Construct a structured tool error. Deepline constructs this from the versioned `tool_error` payload. Application and Play code should catch it rather than create it. | `message: string` `options: ToolExecutionErrorOptions` | |
| `toolId` | property | Public tool id passed to `tools.execute`. | | `string` |
| `provider` | property | Provider responsible for the operation, or `null` when unattributed. | | `string \| null` |
| `operation` | property | Provider operation name, or `null` when unavailable. | | `string \| null` |
| `origin` | property | Boundary responsible for the failure. | | `ToolExecutionErrorOrigin` |
| `category` | property | Stable reason family for policy and diagnostics. | | `ToolExecutionErrorCategory` |
| `retryable` | property | Whether repeating the same semantic call is delivery-safe. This does not mean the error may be ignored. Waterfall fallthrough is represented by `ProviderTransientError`. | | `boolean` |
| `requestId` | property | Provider or Deepline request id, or `null` when unavailable. | | `string \| null` |
| `retryAfterMs` | property | Suggested same-call retry delay in milliseconds, or `null`. | | `number \| null` |
| `networkKind` | property | Network failure kind, or `null` for non-network failures. | | `ToolExecutionNetworkKind \| null` |
| `networkScope` | property | Network boundary that failed, or `null` for non-network failures. | | `ToolExecutionNetworkScope \| null` |
| `publicDetails` | property | Explicitly allowlisted diagnostics safe for SDK and Play callers. | | `ToolExecutionPublicDetails \| null` |

### `ProviderTransientError`

A provider-owned transient failure that is safe to handle as an empty
waterfall leg. Validation, auth, billing, Deepline, and unknown failures
never satisfy this type.

`retryable` remains independent: it says whether the same semantic call may
be repeated safely. Falling through to a different read provider depends on
this class, not on `retryable`.

Signature: `class ProviderTransientError extends ToolExecutionError`

#### Members

| Member | Kind | Purpose | Parameters | Returns / type |
| - | - | - | - | - |
| `constructor` | constructor | Constructed by Deepline when a provider-owned transient failure arrives. | `message: string` `options: Omit<ToolExecutionErrorOptions, 'origin' \| 'category'> & { category: ProviderTransientErrorCategory; }` | |
| `origin` | property | Provider attribution is guaranteed for this subtype. | | `"provider"` |
| `category` | property | Provider failure category that made this error eligible for fallthrough. | | `ProviderTransientErrorCategory` |

### `AuthError`

Thrown when the API rejects the request due to an invalid or missing API key.

This maps to HTTP 401 responses. HTTP 403 means the caller was authenticated
but lacks permission, so the SDK preserves the server's API error instead.
The SDK never retries auth errors —
they fail immediately.

Fix: run `deepline auth register` to obtain a valid key, or pass one via
the `apiKey` option or `DEEPLINE_API_KEY` environment variable.

Signature: `class AuthError extends DeeplineError`

#### Members

| Member | Kind | Purpose | Parameters | Returns / type |
| - | - | - | - | - |
| `constructor` | constructor | Constructed by the SDK when Deepline rejects the caller's credentials. | `message?: string` | |

### `RateLimitError`

Thrown when the API returns HTTP 429 (Too Many Requests).

The SDK retries rate-limited requests automatically up to `maxRetries` times
with exponential backoff. This error is only thrown when all retries are exhausted.

Use `RateLimitError.retryAfterMs` to implement your own backoff if needed.

Signature: `class RateLimitError extends DeeplineError`

#### Members

| Member | Kind | Purpose | Parameters | Returns / type |
| - | - | - | - | - |
| `constructor` | constructor | Constructed by the SDK after exhausting HTTP-level rate-limit retries. | `retryAfterMs?: number` `message?: string` | |
| `retryAfterMs` | property | Milliseconds to wait before retrying, from the `Retry-After` response header. Defaults to 5000. | | `number` |

### `ToolRateLimitError`

Tool-specific 429 preserving both historical RateLimitError catches and the
structured ToolExecutionError ontology. JavaScript has one prototype chain,
so this class extends RateLimitError and carries ToolExecutionError's stable
cross-bundle brand.

This class appears in external SDK calls after HTTP 429 retries are
exhausted. It also satisfies `instanceof ToolExecutionError` and, for a
provider-owned rate limit, `instanceof ProviderTransientError`. Authored
Plays should use `ProviderTransientError`. they do not need this
compatibility class.

Signature: `class ToolRateLimitError extends RateLimitError`

#### Members

| Member | Kind | Purpose | Parameters | Returns / type |
| - | - | - | - | - |
| `constructor` | constructor | Constructed by the SDK after a structured tool HTTP 429. | `message: string` `options: ToolExecutionErrorOptions` | |
| `toolId` | property | Public tool id passed to `tools.execute`. | | `string` |
| `provider` | property | Provider responsible for the operation, or `null`. | | `string \| null` |
| `operation` | property | Provider operation name, or `null`. | | `string \| null` |
| `code` | property | Stable machine-readable failure code when one exists. | | `string \| undefined` |
| `origin` | property | Boundary responsible for the failure. | | `ToolExecutionError['origin']` |
| `category` | property | Stable reason family for policy and diagnostics. | | `ToolExecutionError['category']` |
| `retryable` | property | Whether repeating the same semantic call is delivery-safe. | | `boolean` |
| `requestId` | property | Provider or Deepline request id, or `null`. | | `string \| null` |
| `networkKind` | property | Network failure kind, or `null` for non-network failures. | | `ToolExecutionError['networkKind']` |
| `networkScope` | property | Network boundary that failed, or `null` for non-network failures. | | `ToolExecutionError['networkScope']` |
| `publicDetails` | property | Explicitly allowlisted diagnostics safe for SDK callers. | | `ToolExecutionError['publicDetails']` |

### `ConfigError`

Thrown when the SDK cannot resolve a valid configuration.

Most commonly: no API key found in any of the resolution sources
(explicit option, environment variable, CLI env files).

Signature: `class ConfigError extends DeeplineError`

#### Members

| Member | Kind | Purpose | Parameters | Returns / type |
| - | - | - | - | - |
| `constructor` | constructor | Construct a local SDK configuration failure. | `message: string` | |

## Tool And Provider Calls

### `DeeplineContext.tools`

Tool/provider operations available from a connected `DeeplineContext`.

This namespace is for regular SDK callers outside a play runtime. Inside a
`definePlay(...)` body, use `ctx.tools.execute({ id, tool, input, ... })`
so provider calls become durable runtime checkpoints.\
&#x20;Signature: `export type DeeplineToolsNamespace = { list(): Promise<ToolDefinition[]>; get(toolId: string): Promise<ToolMetadata>; call( toolId: string, input: Record<string, unknown>, options?: DeeplineToolCallOptions, ): Promise<DeeplineToolExecuteResult>; execute( toolId: string, input: Record<string, unknown>, options?: DeeplineToolCallOptions, ): Promise<DeeplineToolExecuteResult>; };`

## Remote Plays And Runs

### `DeeplineContext.plays`

Named-play discovery and handle operations from a connected `DeeplineContext`.\
&#x20;Signature: `export type DeeplinePlaysNamespace = { list(): Promise<PlayListItem[]>; get<TInput = Record<string, unknown>, TOutput = unknown>( name: string, ): DeeplineNamedPlay<TInput, TOutput>; };`

### `DeeplineNamedPlay`

Handle to a named play for remote lifecycle operations.

Returned by `DeeplineContext.play` and attached to `DefinedPlay`.
Provides methods to run, inspect, list runs, and publish a play by name.

| Name | Type | Required | Description |
| - | - | -: | - |
| `name` | `string` | Yes | The play's name. |

### `PlayJob`

Handle to a Play execution: inspect status, stream logs, await output, or cancel.
Like `deepline plays run` and `POST /api/v2/plays/run`, it returns a run id first.
Read completed output through `PlayJob.get()` or the status endpoint's `result` field.
runtime logs in `status().progress.logs` are separate from that output.

| Name | Type | Required | Description |
| - | - | -: | - |
| `id` | `string` | Yes | Temporal workflow ID for this execution. |

## Low-Level Client

### `DeeplineClient`

Low-level typed REST client with authentication, retries, and localhost failover.

Signature: `class DeeplineClient`

#### Members

| Member | Kind | Purpose | Parameters | Returns / type |
| - | - | - | - | - |
| `constructor` | constructor | Create a low-level SDK client. Most callers can omit options and let the SDK resolve auth/config from environment variables and CLI-managed credentials. | `options?: DeeplineClientOptions` - Optional overrides for API key, base URL, timeout, and retries. | |
| `runs` | property | Canonical run lifecycle namespace backed by `/api/v2/runs`. | | `RunsNamespace` |
| `db` | property | Current mutable customer database namespace backed by `/api/v2/db/query`. | | `DbNamespace` |
| `billing` | property | Billing namespace: subscription status/cancel and invoice history. | | `BillingNamespace` |
| `workspaces` | property | Workspace lifecycle namespace. | | `WorkspacesNamespace` |
| `baseUrl` | getter | The resolved base URL this client is targeting (e.g. `"http://localhost:3000"`). | | `string` |
| `executions` | getter | Public recovery namespace. | | `{ getByKey: (key: string) => Promise<ExecutionByKeyResult>; }` |
| `listSecrets` | method | List secret metadata visible to the current workspace. | | `Promise<PlaySecretMetadata[]>` |
| `checkSecret` | method | Check whether a named secret exists, is active, and has a stored value. | `name: string` - Secret name. It is normalized to uppercase before lookup. | `Promise<PlaySecretMetadata \| null>` |
| `inspectSecret` | method | Check effective scope and active-version health without reading the value. Without playName, checks the organization-scoped secret only. With a Play name, an active Play secret takes precedence. A deleted/disabled Play secret falls back to the organization-scoped secret. | `name: string` `options?: { playName?: string }` | `Promise<PlaySecretCheck>` |
| `updateSecretNote` | method | Add, replace, or clear the non-sensitive note attached to one secret. | `secretId: string` `note: string` | `Promise<PlaySecretMetadata>` |
| `listTools` | method | List all available tools. Returns tool definitions including ID, provider, description, input/output schemas, and list extractor paths for automatic CSV conversion. | `options?: { categories?: string; tags?: string; grep?: string; grepMode?: 'all' \| 'any' \| 'phrase'; compact?: boolean; }` | `Promise<ToolDefinition[]>` |
| `listToolCategories` `listToolsInCategory` | method method | List category counts without downloading tool definitions. Read one complete category and its live category counts in one request. |  `category: string` `options?: { compact?: boolean }` | `Promise<ToolCategorySummary[]>` `Promise<ToolCategoryListing>` |
| `listProviders` | method | List discoverable providers without requiring a local plugin catalog. | `options?: { changed?: boolean; }` | `Promise<ProviderDefinition[]>` |
| `searchTools` | method | Search available tools using Deepline's ranked backend search. The CLI uses the same search. The search ranks tool metadata, categories, agent guidance, and input schema fields. | `options?: ToolSearchOptions` | `Promise<ToolSearchResult>` |
| `search` | method | Search everything Deepline can run or deploy in one ranked list: tools, monitor types, prebuilt plays, and your workspace's own plays. | `options?: SearchOptions` | `Promise<SearchResult>` |
| `getTool` | method | Get detailed metadata for a single tool. Returns everything from `ToolDefinition` plus pricing info, sample inputs/outputs, failure modes, and cost estimates. | `toolId: string` - Tool identifier (e.g. `"dropleads_search_people"`) `options?: { cliInvocationId?: string }` | `Promise<ToolMetadata>` |
| `describeModel` | method | Describe a Deepline Agent model and its provider-specific option surface. The method combines live AI Gateway model metadata with Deepline's generated registry of AI SDK provider options. Agents can use this information to construct `providerOptions` payloads before they execute `deeplineagent`. The returned schemas describe accepted shapes for provider options. These schemas do not guarantee that every model supports each option. Runtime AI SDK and Gateway errors determine support for model-specific values. | `model: string` - Exact-case Gateway model id such as `"openai/gpt-5.6-luna"` | `Promise<DeeplineAgentModelDescription>` |
| `quoteInferenceTool` | method | Quote dynamic AI inference pricing for a concrete payload. The result contains a planning estimate and a separate, proven authorization maximum. Both values use Deepline credits. | `toolId: 'ai_evaluate' \| 'ai_inference' \| 'deeplineagent'` `payload: Record<string, unknown>` | `Promise<InferenceQuote>` |
| `executeTool` | method | Execute a tool and return the standard execution envelope. The `toolResponse.rawV2` field contains the complete tool response, preserving its original nesting. Inspect `getTool().examples` for a full Deepline response example. Optional `toolResponse.responseMeta` contains response metadata. Top-level fields such as `status`, `job_id`, and `billing` describe the Deepline execution envelope. | `toolId: string` `input: Record<string, unknown>` `options?: ExecuteToolRawOptions` | `Promise<ToolExecution<TData, TMeta>>` |
| `getExecutionByKey` | method | Read the durable state of a keyed tool execution. | `idempotencyKey: string` | `Promise<ExecutionByKeyResult>` |
| `executeToolRaw` | method | Back-compatible alias for `executeTool`. Retained for callers that still use the older raw naming while the response envelope remains the same. | `toolId: string` `input: Record<string, unknown>` `options?: ExecuteToolRawOptions` | `Promise<ToolExecution<TData, TMeta>>` |
| `queryCustomerDb` | method | Run a bounded SQL query against the current mutable customer database. This query is not scoped to one play run. Use `client.runs` export actions when the caller needs the rows produced by a specific run. | `input: CustomerDbQueryOptions` | `Promise<CustomerDbQueryResult>` |
| `repairIngestionStorage` | method | Re-establish this workspace's tenant storage contract: role/DB connect grants plus materialized table grants. Org-admin only. Use when a run fails with WORKSPACE\_STORAGE\_NOT\_READY. | `input?: { provider?: string; }` | `Promise<IngestionStorageRepairResult>` |
| `startPlayRun` | method | Start a play run. Internal/advanced primitive. For normal callers, prefer the public entrypoints: the CLI, `Deepline.connect`, `submitPlay`, or `runPlay`. These interfaces share the run contract and return a workflow or run ID: - `deepline plays run`. - Repository scripts such as `bun run deepline -- plays run`. - SDK context calls such as `Deepline.connect().play(name).run()`. - Direct `POST /api/v2/plays/run` calls. Read completed output from `getPlayStatus(runId).result`. For SDK context calls, read output from `PlayJob.get()`. Execution logs appear under `progress.logs`. The user output object does not contain these logs. | `request: StartPlayRunRequest` - Play run configuration (name, code, input, etc.) `options?: PlayRunStartOptions` | `Promise<PlayRunStart>` |
| `preparePlayRunAdmission` | method | Prepare a tenant-scoped start intent without executing it. Its stream sender retains the exact body and transport selected during preparation. | `request: StartPlayRunRequest` `options?: { cliAdmission?: boolean; onSubmission?: (intent: { workflowId: string; orgId: string; request: Record<string, unknown>; }) => void \| Promise<void>; }` | `Promise<{ startStream(streamOptions?: { signal?: AbortSignal; }): AsyncGenerator<PlayLiveEvent, void, unknown>; body: Record<string, unknown>; workflowId?: string; supportsCallerIntent: boolean; }>` |
| `startPlayRunStream` | method | Submit a play run through the legacy event response. This reports admission from the start request. It does not watch an existing run. Use `startPlayRun()` and `watchRunEvents(runId)` separately. | `request: StartPlayRunRequest` - Play run configuration. `options?: { signal?: AbortSignal; onSubmission?: (intent: { workflowId: string; orgId: string; request: Record<string, unknown>; }) => void \| Promise<void>; }` - Optional compatibility response options. | `AsyncGenerator<PlayLiveEvent>` |
| `registerPlayArtifact` | method | Register a bundled play artifact. Internal/advanced primitive used by packaging flows. Public callers should prefer the CLI, `submitPlay`, or `runPlay`. | `input: { name: string; sourceCode: string; sourceFiles?: Record<string, string>; description?: string; artifact: Record<string, unknown>; compilerManifest?: PlayCompilerManifest; publish?: boolean; artifactOnly?: boolean; ownerType?: 'org' \| 'deepline'; scope?: 'org' \| 'system'; userId?: string; }` | `Promise<{ success?: boolean; name?: string; artifactStorageKey: string; artifactMetadata?: Record<string, unknown> \| null; staticPipeline?: unknown; definitionId?: string \| null; revisionId?: string \| null; version?: number \| null; liveVersion?: number \| null; triggerMetadata?: unknown; triggerBindings?: unknown; }>` |
| `registerPlayArtifacts` | method | Register multiple bundled play artifacts in one request. Used by packaging and prebuilt publication flows. Each artifact is compiled first when a compiler manifest is not already supplied. | `artifacts: Array<{ name: string; sourceCode: string; sourceFiles?: Record<string, string>; description?: string; artifact: Record<string, unknown>; compilerManifest?: PlayCompilerManifest; publish?: boolean; ownerType?: 'org' \| 'deepline'; scope?: 'org' \| 'system'; userId?: string; }>` | `Promise<{ success: boolean; artifacts: Array<{ success?: boolean; name?: string; artifactStorageKey: string; artifactMetadata?: Record<string, unknown> \| null; staticPipeline?: unknown; definitionId?: string \| null; revisionId?: string \| null; version?: number \| null; liveVersion?: number \| null; triggerMetadata?: unknown; triggerBindings?: unknown; }>; }>` |
| `compilePlayManifest` | method | Compile a bundled play artifact into the server-side compiler manifest. The manifest records imports, trigger bindings, static pipeline shape, and runtime metadata. The compiler needs these records before it checks, registers, or runs a Play artifact. | `input: { name: string; sourceCode: string; sourceFiles?: Record<string, string>; artifact: Record<string, unknown>; importedPlayDependencies?: PlayCompilerManifest[]; }` | `Promise<PlayCompilerManifest>` |
| `checkPlayArtifact` | method | Check a bundled play artifact against the server's current play compiler. Unlike `registerPlayArtifact`, this does not store the artifact, publish a revision, or start a run. It is the authoritative cloud validation path used by `deepline plays check`. | `input: { name?: string; sourceCode: string; sourceFiles?: Record<string, string>; description?: string; artifact: Record<string, unknown>; exportName?: string \| null; integrationMode?: 'live' \| 'eval_stub' \| 'fixture'; importedPlays?: Array<{ playName?: string \| null; sourceCode: string; sourcePath?: string \| null; }>; }` | `Promise<PlayCheckResult>` |
| `startPlayRunFromBundle` | method | Register an already-bundled play artifact and start a run from it. SDK and CLI packaging wrappers use this low-level run method for file-based Plays. Local bundling must produce the runtime artifact first. | `input: { name: string; sourceCode: string; sourceFiles?: Record<string, string>; description?: string; artifact: Record<string, unknown>; compilerManifest?: PlayCompilerManifest; input?: Record<string, unknown>; inputFile?: PlayStagedFileRef \| null; packagedFiles?: PlayStagedFileRef[]; force?: boolean; forceToolRefresh?: boolean; }` | `Promise<PlayRunStart>` |
| `submitPlay` | method | Register a bundled play artifact and start a run from the live revision. This method wraps `registerPlayArtifact` and `startPlayRun`. Packaging wrappers use this method for file-based Plays. Pass the returned ID to `getPlayStatus`. The method returns the same durable `{ result }` object that the CLI prints after `plays run` completes. | `code: string` - Fallback source string. Pass the bundled artifact in `options.artifact`. `csvPath: string \| null` - Path to the input CSV file, or `null`. `name?: string` - Play name. The SDK derives it from the source when omitted. `options?: { sourceCode?: string; sourceFiles?: Record<string, string>; description?: string; artifact?: Record<string, unknown>; compilerManifest?: PlayCompilerManifest; input?: Record<string, unknown>; inputFile?: PlayStagedFileRef \| null; packagedFiles?: PlayStagedFileRef[]; force?: boolean; forceToolRefresh?: boolean; }` - Additional submission options. | `Promise<PlayRunStart>` |
| `stagePlayFiles` | method | Upload files to the staging area for use in play runs. Internal/advanced primitive used by packaging flows. Public callers should prefer the CLI, `submitPlay`, or `runPlay`. Staged files are referenced by their returned `PlayStagedFileRef` in subsequent `startPlayRun` calls via `inputFile` or `packagedFiles`. | `files: Array<{ logicalPath: string; contentBase64: string; contentHash: string; contentType: string; bytes: number; }>` - Array of files to stage (base64-encoded content) | `Promise<PlayStagedFileRef[]>` |
| `mintStagedPlayFileUploads` | method | Mint short-lived presigned upload targets for staged play files. Internal primitive used by `stagePlayFiles`. For a content-addressed file already in storage, the server returns a staged reference. That file needs no upload. For other files, the server returns a presigned PUT URL. Upload the file body to that URL. | `files: Array<{ logicalPath: string; contentHash: string; contentType: string; bytes: number; }>` | `Promise<MintStagedFileUpload[]>` |
| `resolveStagedPlayFiles` | method | Resolve staged play files by content hash without uploading bytes. The response identifies missing files. Callers need to upload only these files. | `files: Array<{ logicalPath: string; contentHash: string; contentType: string; bytes: number; }>` | `Promise<{ files: PlayStagedFileRef[]; missing: Array<{ logicalPath: string; contentHash: string }>; }>` |
| `getPlayStatus` | method | Get the current status of a play execution. Internal/advanced primitive. Public callers should usually prefer `runPlay`, `PlayJob.get`, or `deepline plays run`. | `workflowId: string` - Play-run id from `startPlayRun` `options?: { billing?: boolean; full?: boolean }` | `Promise<PlayStatus>` |
| `watchRunEvents` | method | Poll authenticated snapshots and emit changes. `deferLogs` delays terminal logs. `omitTerminalLogs` skips them. | `workflowId: string` `options?: { signal?: AbortSignal; onNotice?: (message: string) => void; onRetry?: RunsWatchOptions['onRetry']; deferLogs?: boolean; omitTerminalLogs?: boolean; onPoll?: (observation: WatchPollObservation) => void; terminalStatus?: { full?: boolean; billing?: boolean; runStatus?: boolean; onStatus: (status: PlayStatus) => void \| Promise<void>; }; }` | `AsyncGenerator<PlayLiveEvent>` |
| `streamPlayRunEvents` | method | Read raw legacy SSE events for callers that explicitly require that compatibility endpoint. Ordinary run watching uses REST snapshot polling. | `workflowId: string` `options?: { signal?: AbortSignal; lastEventId?: string; mode?: 'cli' \| 'ui'; }` | `AsyncGenerator<PlayLiveEvent>` |
| `observeRunEvents` | method | Compatibility alias for polling canonical run snapshots and emitting their changed events. | `runId: string` `options?: { signal?: AbortSignal; onNotice?: (message: string) => void; fallback?: 'sse' \| 'none'; }` | `AsyncGenerator<PlayLiveEvent>` |
| `tailRun` | method | Wait for a run and return its terminal status. This source-compatible alias uses the same authenticated two-second REST snapshot polling as `client.runs.watch`. | `runId: string` - Public Deepline play-run id. `options?: RunsTailOptions` - Optional callbacks and cancellation signal. | `Promise<PlayStatus>` |
| `cancelPlay` | method | Cancel a running play execution. Sends a stop request for the run. | `workflowId: string` - Public Deepline play-run id to cancel | `Promise<void>` |
| `stopPlay` | method | Stop a running play execution, including open HITL waits. | `workflowId: string` - Public Deepline play-run id to stop `options?: { reason?: string }` | `Promise<StopPlayRunResult>` |
| `listPlayRuns` | method | List recent runs for a named play. Returns runs sorted by start time (newest first), including workflow IDs, status, timestamps, and metadata. | `playName: string` - The play name to query | `Promise<PlayRunListItem[]>` |
| `getRunStatus` | method | Get a run by id using the public runs resource model. This is the SDK equivalent of: `bash<br />deepline runs get <run-id><br />` | `runId: string` `options?: RunsGetOptions` | `Promise<PlayStatus>` |
| `getRunChildren` | method | Read one paginated, launch-scoped page of direct child Runs. | `parentRunId: string` `options: RunsChildrenOptions` | `Promise<RunChildrenPage>` |
| `getRunLifecycleStatus` | method | Fetch only the legacy scalar lifecycle status for a run. | `runId: string` | `Promise<RunLifecycleStatus>` |
| `listRuns` | method | List play runs using the public runs resource model. This is the SDK equivalent of: `bash<br />deepline runs list --play <play-name> --status failed<br />` | `options: RunsListOptions` | `Promise<PlayRunListItem[]>` |
| `getRunsHistory` | method | The same tenant-scoped run history searched by the dashboard and CLI. | `options?: RunsHistoryOptions` | `Promise<RunsHistoryPage>` |
| `listRunsPage` | method | Read one run page without discarding server pagination metadata. | `options: RunsListOptions` | `Promise<RunsListPage>` |
| `getRunReceipts` | method | Read retained tool results without executing tools, preserving supplied key order and batching 100 keys per request. Obtain keys from exported evidence or execution metadata. Each key must be nonempty, at most 2,048 characters and contain no CR, LF or NUL. Missing/expired results have an explicit per-key error. | `runId: string` `options: { keys: string[] }` | `Promise<import('./runs/receipts').RunToolReceiptsResponse>` |
| `getRunInput` | method | Get the exact original input retained for a run. This is intentionally separate from status. | `runId: string` | `Promise<{ runId: string; input: Record<string, unknown> \| unknown[]; bytes: number; sha256: string \| null; replayedFromRunId: string \| null; }>` |
| `rerun` | method | Start a fresh run from a prior run's retained input and pinned revision. Every invocation sends an `Idempotency-Key`. When the caller supplies no key, the SDK creates a fresh key once per call. The transport reuses that key for network retries, so those retries produce one rerun. Reuse an explicit key across separate invocations when the previous result is uncertain. A different key starts another rerun. | `runId: string` `options?: RerunOptions` | `Promise<RerunPlayRunResult>` |
| `getRunLogs` | method | Read a run's retained text tail (default 200), full retained stream (`all`), or terminal failure window (`failed`, at most 20). These are existing reads. sampling and retention loss cannot be recovered. See [run logs and events](https://deepline.com/docs/sdk-v2/run-events.md) for structured search and payload retrieval. This is the SDK equivalent of: `bash<br />deepline runs logs <run-id> --limit 200<br />` | `runId: string` `options?: RunsLogsOptions` | `Promise<RunsLogsResult>` |
| `searchRunEvents` | method | Read structured history across the active organization without requiring a run ID. Defaults to the last hour, newest first. Use the returned cursor and exact time bounds to continue. See [run logs and events](https://deepline.com/docs/sdk-v2/run-events.md) for all kinds, indexed fields, payloads and SDK/API response types. | `options?: RunsEventSearchOptions` | `Promise<RunsEventSearchResult>` |
| `getPlayRunRowHistory` | method | Read one page of immutable admitted and terminal rows for a Play Run dataset. Follow nextCursor. coverage explicitly identifies unavailable or incomplete history. | `input: PlayRunRowHistoryOptions` | `Promise<RuntimeSheetRunRowMembershipPage>` |
| `getPlaySheetRows` | method | Export persisted runtime-sheet rows for a play dataset/table namespace. This is the SDK form of exporting `ctx.dataset(...).run()` output for a specific play and optional run id. | `input: { playName: string; tableNamespace: string; runId?: string; limit?: number; offset?: number; rowMode?: 'output' \| 'all' \| 'live'; signal?: AbortSignal; }` | `Promise<PlaySheetRowsResult>` |
| `stopRun` | method | Stop a run by id using the public runs resource model. This is the SDK equivalent of: `bash<br />deepline runs stop <run-id> --reason "stale lock"<br />` | `runId: string` `options?: { reason?: string }` | `Promise<StopPlayRunResult>` |
| `stopAllRuns` | method | Stop every active run visible to the current workspace. With `dryRun: true`, list the exact candidates without cancelling any run. This is the SDK equivalent of: `bash<br />deepline runs stop-all --dry-run<br />deepline runs stop-all --reason "stale lock"<br />` Use this method when a failed parent leaves active child or waiting runs. The method clears workspace run-slot state without requiring each run ID. | `options?: StopAllRunsOptions` | `Promise<StopAllPlayRunsResult>` |
| `listPlays` | method | List one page of callable Plays. With grep, the method retains all matching results. Use listPlaysPage for pagination metadata. Pass `origin: "prebuilt"` for Deepline-managed prebuilts or `origin: "owned"` for org-owned plays. | `options?: PlaysListOptions` | `Promise<PlayListItem[]>` |
| `listPlaysPage` | method | Read one bounded inventory page. cursor continues the same filters. | `options?: PlaysListOptions & { limit?: number; cursor?: string \| null; }` | `Promise<PlaysListPage>` |
| `getPlaysActivity` | method | Count durable Play runs and Monitor deliveries in local calendar days. | `options?: { timeZone?: string; days?: number; endDate?: string; groupBy?: 'kind' \| 'trigger_source'; }` | `Promise<PlaysActivityResponse>` |
| `getPlaySettings` | method | Read definition-level settings, independently of code revisions. | `playName: string` | `Promise<PlaySettingsResult>` |
| `updatePlaySettings` | method | Retry-safe field patch. omitted fields retain their current value. | `playName: string` `patch: PlaySettingsPatch` | `Promise<PlaySettingsResult>` |
| `getPlayTriggerConfig` | method | Read a Play's cron and webhook triggers and their scheduler state. | `playName: string` | `Promise<PlayTriggerConfigView>` |
| `updatePlayTriggerConfig` | method | Declare a Play's cron and/or webhook trigger (null removes it) and publish the rewritten source as a new live revision. Retry-safe: a request the live revision already satisfies returns `changed: false`. | `playName: string` `update: PlayTriggerConfigUpdate` | `Promise<PlayTriggerConfigUpdateResult>` |
| `listPlaySettingsPaths` | method | List one bounded page of existing Play locations. continue with cursor. | `options?: { root?: 'person' \| 'team'; limit?: number; cursor?: string }` | `Promise<PlaySettingsPathsPage>` |
| `setPlayPinned` | method | Set whether an org-owned Play sorts before unpinned Plays. | `playName: string` `pinned: boolean` | `Promise<{ name: string; pinned: boolean }>` |
| `getNotificationSettings` | method | Read product-notification destinations, subscriptions, event catalog, and DLQ health. | | `Promise<ProductNotificationSettings>` |
| `setIntegrationCredentials` | method | Save provider-owned credential fields without starting an OAuth browser flow. | `provider: string` `credentials: Record<string, string>` | `Promise<{ ok: boolean; credential_saved?: boolean }>` |
| `connectNotificationSlack` | method | Start the Slack OAuth flow required by product notifications. | `options?: { successUrl?: string; failureUrl?: string; }` | `Promise<{ ok: boolean; redirect_url: string }>` |
| `listNotificationSlackChannels` | method | List Slack channels visible to the connected Deepline Slack app. | `query?: string` | `Promise<{ identity: { teamId: string; teamName?: string }; channels: Array<{ id: string; name: string; isPrivate: boolean }>; }>` |
| `setNotificationSlack` | method | Select a Slack channel or direct member used for product notifications. | `destination: string \| { memberId: string }` | `Promise<unknown>` |
| `testNotificationSlack` | method | Send one synchronous test ping and return Slack's delivery result. | | `Promise<{ ok: boolean; deliveryId: string; state: string; message: string; }>` |
| `disableNotificationSlack` | method | Disable Slack product notifications without deleting the OAuth connection. | | `Promise<unknown>` |
| `setNotificationSubscriptions` | method | Enable or disable event IDs from the server-provided notification catalog. | `eventTypes: string[]` `enabled: boolean` | `Promise<unknown>` |
| `listNotificationDlq` | method | List exhausted deliveries. Dead-lettered messages never replay automatically. | `limit?: number` | `Promise<unknown>` |
| `getNotificationDlqDelivery` | method | Inspect one exhausted notification delivery. | `deliveryId: string` | `Promise<unknown>` |
| `updateNotificationDlqDelivery` | method | Explicitly retry or archive one dead-lettered notification delivery. | `deliveryId: string` `action: 'retry' \| 'archive'` | `Promise<unknown>` |
| `getNotifications` | method | List the workspace's named notification rules. | | `Promise<ProductNotificationSettings>` |
| `getNotificationConfiguration` | method | Read the group-based product-notification configuration and rule catalog. | | `Promise<ProductNotificationConfigurationResponse>` |
| `changeNotificationConfiguration` | method | Atomically apply one retry-safe desired configuration change. | `expectedWorkspaceVersion: number` `change: ProductNotificationConfigurationChange` | `Promise<Pick<ProductNotificationConfigurationResponse, 'configuration'>>` |
| `createNotificationGroup` | method | Create one notification group and its destinations as a retry-safe unit. | `input: CreateNotificationGroupInput` | `Promise<CreateNotificationGroupResult>` |
| `listNotificationChannels` | method | List Slack channels available to an already-connected Slack integration. | `query?: string` | `Promise<{ identity: { teamId: string; teamName?: string }; channels: Array<{ id: string; name: string; isPrivate: boolean }>; }>` |
| `createNotification` | method | Create a named notification routed through an existing provider integration. | `input: CreateNotificationInput` | `Promise<unknown>` |
| `updateNotification` | method | Update a notification's target, event selection, or enabled state. | `notificationId: string` `input: UpdateNotificationInput` | `Promise<unknown>` |
| `testNotification` | method | Send a validation ping to one notification. | `notificationId: string` | `Promise<{ ok: boolean; deliveryId: string; state: string; message: string; }>` |
| `deleteNotification` | method | Archive one notification without touching its provider integration. | `notificationId: string` | `Promise<{ deleted: boolean; id: string }>` |
| `searchPlays` | method | Search callable plays and return compact play descriptions. Prebuilt plays are preferred by default because they have maintained contracts and stable run behavior. | `options: { query: string; compact?: boolean; pipeline?: boolean; scope?: 'prebuilt' \| 'owned' \| 'all'; cliInvocationId?: string; }` | `Promise<PlayDescription[]>` |
| `getPlay` | method | Get the full definition and state of a named play. The response includes revision state (draft or live), recent runs, a summary of sheet processing, and the database URL. | `name: string` - Play name `options?: { source?: 'working' \| 'live' \| `version:\${number}`; guidance?: boolean; }` | `Promise<PlayDetail>` |
| `listPlayTriggerInventory` | method | Read one trigger inventory page without loading run histories. | `options?: { cursor?: string }` | `Promise<{ page: Array<{ bindingId: string; name: string; type: string; status: string; cron: string \| null; timezone: string \| null; nextScheduledAt: number \| null; }>; continueCursor: string; isDone: boolean; }>` |
| `getPlayTriggerHistory` | method | Read one trigger's recent runs, with an explicit partial-history flag. | `bindingId: string` `options?: { limit?: number }` | `Promise<{ recentRuns: Array<{ workflowId: string; runId: string \| null; status: string; createdAt: number; startedAt: number \| null; finishedAt: number \| null; }>; truncated: boolean; cronInput: Record<string, unknown> \| null; }>` |
| `describePlay` | method | Get a normalized play description suitable for agents and CLIs. The description includes runnable examples, input and output summaries, clone guidance, and revision state. It also includes metadata for the latest run when available. Set `{ pipeline: true }` to include the compiled pipeline. The pipeline can be hundreds of kilobytes. The response omits it by default. | `name: string` `options?: PlayDescriptionOptions` | `Promise<PlayDescription>` |
| `clearPlayHistory` | method | Clear run history and durable sheet/result data for a play without deleting the play definition or revisions. | `name: string` `request?: ClearPlayHistoryRequest` | `Promise<ClearPlayHistoryResult>` |
| `listPlayVersions` | method | List saved versions for a named play. Returns immutable revision snapshots newest-first, including the revision id needed for exact-version runs and live-version switching. | `name: string` - Play name `options?: { full?: boolean }` | `Promise<PlayRevisionSummary[]>` |
| `publishPlayVersion` | method | Make a play revision live. When `revisionId` is omitted, the current working revision becomes live. A call by Play name executes the live revision unless the caller specifies another revision. | `name: string` - Play name `request?: PublishPlayVersionRequest` - Optional explicit revision to make live | `Promise<PublishPlayVersionResult>` |
| `deletePlay` | method | Move an org-owned play to Trash. This disables its active triggers while retaining its revisions and run history so it can be restored. Deepline prebuilt plays are read-only. | `name: string` | `Promise<DeletePlayResult>` |
| `restorePlay` | method | Restore an org-owned play that was previously moved to Trash. | `name: string` | `Promise<RestorePlayResult>` |
| `getSharePage` | method | Current share status for a play: the public page (if any), the published copy, and the revision picker. Read-only. | `name: string` `options?: { revisionId?: string }` | `Promise<SharePageStatus>` |
| `publishSharePage` | method | Publish (or repoint) the play's public share page to a revision. Requires `acknowledgedUnlisted: true` — the page is publicly viewable. Org-admin only. | `name: string` `request: PublishSharePageRequest` | `Promise<SharePageStatus>` |
| `updateSharePage` | method | Update share-page settings (SEO indexing, credit-cost / latency display) without moving the published pointer. Org-admin only. | `name: string` `request: UpdateSharePageRequest` | `Promise<SharePageStatus>` |
| `unpublishSharePage` | method | Unshare: hard-delete the play's public page and its cards. Returns the fresh status (now `share: null`). Org-admin only. Idempotent — a no-op when the play was never published. | `name: string` | `Promise<SharePageStatus>` |
| `regenerateSharePage` | method | Regenerate the LLM landing-page copy for a revision (defaults to the published one). Org-admin only. | `name: string` `request?: { revisionId?: string }` | `Promise<SharePageStatus>` |
| `runPlay` | method | Run a play end-to-end: submit, poll progress until terminal, return result. This is the highest-level play execution method. It submits the play, reads the canonical run snapshot for status updates, and returns a structured result with logs and timing. Supports cancellation via `AbortSignal`. | `code: string` - Source string fallback. pass the bundled artifact in `options.artifact` `csvPath: string \| null` - Input CSV path, or `null` `name?: string` - Play name `options?: { onProgress?: (status: PlayStatus) => void; signal?: AbortSignal; input?: Record<string, unknown>; sourceCode?: string; artifact?: Record<string, unknown>; compilerManifest?: PlayCompilerManifest; inputFile?: PlayStagedFileRef \| null; packagedFiles?: PlayStagedFileRef[]; force?: boolean; forceToolRefresh?: boolean; }` - Execution options | `Promise<PlayRunResult>` |
| `getBillingPlans` | method | Published plans plus the caller's active plan: prices, monthly grant credits, rollover policy, and which plans are open for subscription. Prefer `client.billing.plans()`. | | `Promise<BillingPlansResult>` |
| `getBillingUsageEvent` | method | Read the authenticated usage record for one execution request. The request id comes from the original `executeTool` result and is not a retry or idempotency token. | `requestId: string` | `Promise<BillingUsageEvent>` |
| `getRunBilling` | method | Read Deepline credits billed to each run and whether charges are still settling. The response never shows provider spend. The dashboard runs grid uses the same read. HTTP endpoint: `GET /api/v2/runs/billing`. | `runIds: readonly string[]` | `Promise<RunBillingResult>` |
| `getBillingUsage` | method | Read workspace usage and recent customer-facing Deepline charges. Pass the `job_id` from `executeTool` as `requestId` to retrieve one exact call, including whether its charge is final or still a temporary hold. Exact request lookups return only the `org_id` and `recent` result fields. | `options?: BillingUsageOptions` | `Promise<BillingUsageResult>` |
| `topUpBillingBalance` | method | Charge the saved payment method and add Deepline credits to the active workspace. Prefer `client.billing.topUp(...)`. | `options: { credits: number; idempotencyKey?: string; }` | `Promise<BillingTopUpResult>` |
| `topUpBillingBalanceWithReceipt` | method | Request a durable top-up operation receipt. A pending receipt does not imply that payment or credit activation has completed. Prefer `client.billing.topUpWithReceipt(...)`. | `options: { credits: number; idempotencyKey?: string; }` | `Promise<BillingTopUpReceipt>` |
| `getBillingSubscriptionStatus` | method | Subscription state for the active workspace: active plan, whether a Stripe subscription backs it, renewal/cancellation facts, and remaining Deepline credit pools. Prefer `client.billing.subscription.status()`. | | `Promise<BillingSubscriptionStatus>` |
| `cancelBillingSubscription` | method | Schedule subscription cancellation at period end, or reverse a pending cancellation with `{ undo: true }`. The customer keeps the cycle they paid for and every remaining credit — cancellation never claws back credits. Prefer `client.billing.subscription.cancel(...)`. | `options?: { undo?: boolean; }` | `Promise<BillingSubscriptionCancelResult>` |
| `listBillingInvoices` | method | Customer-facing billing history: subscription invoices plus one-time credit purchase receipts, newest first, with Stripe-hosted links. Prefer `client.billing.invoices.list(...)`. | `options?: { limit?: number; }` | `Promise<BillingInvoicesResult>` |
| `getTargetBillingPlans` | method | List the reviewed target plans and whether new acquisition is enabled. | | `Promise<TargetBillingPlansResult>` |
| `getTargetBillingStatus` | method | Read the workspace's normalized target plan, payment, and balance state. | | `Promise<TargetBillingStatusResult>` |
| `getTargetAutoRecharge` | method | Read the canonical Metronome automatic recharge configuration. | | `Promise<TargetAutoRechargeResult>` |
| `updateTargetAutoRecharge` | method | Update automatic recharge and return the server-verified configuration. | `options: TargetAutoRechargeUpdateOptions` | `Promise<TargetAutoRechargeResult>` |
| `purchaseTargetBillingCredits` | method | Purchase target-billing credits through the durable commercial operation flow. The caller supplies an idempotency key for safe retries. | `options: { credits: number; idempotencyKey: string; }` | `Promise<TargetBillingMutationResult>` |
| `recoverTargetBillingCreditPurchase` | method | Recover only the original workspace, credit amount, and purchase key. Never charge. | `options: { credits: number; orgId: string; idempotencyKey: string; }` | `Promise<TargetBillingMutationResult>` |
| `transitionTargetBillingPlan` | method | Start, change, cancel, or restore a target plan through one idempotent commercial operation. | `options: TargetBillingPlanTransitionOptions` | `Promise<TargetBillingMutationResult>` |
| `createTargetBillingPortalSession` | method | Create a Stripe-hosted portal session for payment recovery and invoices. | `options?: { flow?: 'customer_update'; }` | `Promise<{ url: string }>` |
| `createWorkspace` | method | Create an additional workspace through the durable PAYG workflow. | `options: { name: string; idempotencyKey: string; }` | `Promise<WorkspaceCreateResult>` |
| `authStatus` | method | The workspace and user this client's API key authenticates as. | | `Promise<Record<string, unknown>>` |
| `health` | method | Check API connectivity and server health. | | `Promise<{ status: string; version?: string; status_banner?: { message: string; updatedAt: number; }; }>` |

### `client.runs`

Use `client.runs` to watch, stop, query logs/events, and export durable dataset rows.

| Name | Type | Required | Description |
| - | - | -: | - |
| `getReceipts` | `( runId: string, options: { keys: string[] }, ) => Promise<import('./runs/receipts').RunToolReceiptsResponse>` | Yes | Read retained tool results in supplied key order. Use keys returned in exported evidence or execution metadata. search does not expose receipt keys. Never executes tools. |
| `get` | `(runId: string, options?: RunsGetOptions) => Promise<PlayStatus>` | Yes | Get current run status by public run id. |
| `children` | `( parentRunId: string, options: RunsChildrenOptions, ) => Promise<RunChildrenPage>` | Yes | Read one bounded page of direct children for an async launch. |
| `input` | `(runId: string) => Promise<{ runId: string; input: Record<string, unknown> \| unknown[]; bytes: number; sha256: string \| null; replayedFromRunId: string \| null; }>` | Yes | Explicitly read the retained original input (may include customer data). |
| `rerun` | `(runId: string, options?: RerunOptions) => Promise<RerunPlayRunResult>` | Yes | Start a fresh run from a prior run's retained input and pinned revision. |
| `list` | `(options: RunsListOptions) => Promise<PlayRunListItem[]>` | Yes | List runs for one play, optionally filtered by status. |
| `listPage` | `(options: RunsListOptions) => Promise<RunsListPage>` | Yes | Read one run page with total, offset, limit and completeness metadata. |
| `history` | `(options?: RunsHistoryOptions) => Promise<RunsHistoryPage>` | Yes | Search/page workspace run history newest first. follow empty continuing pages. |
| `watch` | `(runId: string, options?: RunsWatchOptions) => Promise<PlayStatus>` | Yes | Poll run snapshots every two seconds until terminal status. |
| `logs` | `RunsLogsNamespace` | Yes | Call for the retained text tail, full stream (`all`) or terminal failure window (`failed`). Use `logs.query/count/summarize/fields` for structured filters and exact aggregates. See [run logs and events](https://deepline.com/docs/sdk-v2/run-events.md). |
| `events` | `RunsEventsNamespace` | Yes | Use `events.list/count/summarize/fields` for lifecycle, receipt and organization-wide events. See [run logs and events](https://deepline.com/docs/sdk-v2/run-events.md). |
| `searchEvents` | `( options?: RunsEventSearchOptions, ) => Promise<RunsEventSearchResult>` | Yes | Search existing events across the active organization. default last hour, up to 200 events per page (ten with payloads). See [run logs and events](https://deepline.com/docs/sdk-v2/run-events.md) for the catalog, query fields and response types. |
| `exportDatasetRows` | `(input: { playName: string; tableNamespace: string; runId?: string; limit?: number; offset?: number; rowMode?: 'output' \| 'all' \| 'live'; signal?: AbortSignal; }) => Promise<PlaySheetRowsResult>` | Yes | Export persisted rows for a runtime-sheet dataset/table namespace. |
| `rowHistory` | `( input: PlayRunRowHistoryOptions, ) => Promise<RuntimeSheetRunRowMembershipPage>` | Yes | One immutable history page. incomplete legacy coverage stays explicit. |
| `stop` | `( runId: string, options?: { reason?: string }, ) => Promise<StopPlayRunResult>` | Yes | Stop a running/waiting run. |
| `stopAll` | `{ ( options: StopAllRunsOptions & { dryRun: true }, ): Promise<StopAllPlayRunsDryRunResult>; ( options?: StopAllRunsOptions & { dryRun?: false }, ): Promise<StopAllPlayRunsStopResult>; (options?: StopAllRunsOptions): Promise<StopAllPlayRunsResult>; }` | Yes | Stop active runs across the current workspace, or with `dryRun: true` enumerate the exact candidates without cancelling anything. |

### `client.billing`

Public `client.billing` namespace for CLI commands and programmatic callers.
Covers usage, plans, subscription state, cancellation, and invoice/receipt
history.

| Name | Type | Required | Description |
| - | - | -: | - |
| `quote` | `(input: BillingQuoteRequest) => Promise<BillingQuoteResult>` | Yes | Read a bounded sandbox-session estimate. excludes tools and Customer DB. |
| `entitlements` | `() => Promise<BillingEntitlements>` | Yes | Current workspace provider benefits. discovery does not authorize a call. |
| `topUp` | `(options: { credits: number; idempotencyKey?: string; }) => Promise<BillingTopUpResult>` | Yes | Charge the saved payment method and add Deepline credits to the active workspace. |
| `topUpWithReceipt` | `(options: { credits: number; idempotencyKey?: string; }) => Promise<BillingTopUpReceipt>` | Yes | Request a durable pending or applied receipt for a saved-card top-up. |
| `plans` | `() => Promise<BillingPlansResult>` | Yes | Published plans plus the plan you are on ("what plans exist and what am I on"). |
| `subscription` | `{ status: () => Promise<BillingSubscriptionStatus>; cancel: (options?: { undo?: boolean; }) => Promise<BillingSubscriptionCancelResult>; }` | Yes | |
| `invoices` | `{ list: (options?: { limit?: number }) => Promise<BillingInvoicesResult>; }` | Yes | |
| `usageEvent` | `(requestId: string) => Promise<BillingUsageEvent>` | Yes | Read one exact execution outcome using the request\_id returned by executeTool. |
| `usage` | `(options?: BillingUsageOptions) => Promise<BillingUsageResult>` | Yes | Read current billing usage, or look up one exact execution charge by request ID. |
| `targetPlans` | `() => Promise<TargetBillingPlansResult>` | Yes | Metronome-authored target catalog and current Contract projection. |
| `targetStatus` | `() => Promise<TargetBillingStatusResult>` | Yes | Normalized target billing state. |
| `autoRecharge` | `{ get: () => Promise<TargetAutoRechargeResult>; trigger: (options?: { idempotencyKey: string; }) => Promise<{ data: { status: string; operation_id?: string } }>; update: ( options: TargetAutoRechargeUpdateOptions, ) => Promise<TargetAutoRechargeResult>; }` | Yes | Read and manage the Metronome-backed automatic recharge configuration. |
| `purchaseCredits` | `(options: { credits: number; idempotencyKey: string; }) => Promise<TargetBillingMutationResult>` | Yes | Buy Deepline credits through a payment-gated Metronome commit. |
| `recoverCreditPurchase` | `(options: { credits: number; orgId: string; idempotencyKey: string; }) => Promise<TargetBillingMutationResult>` | Yes | Inspect or retire the original purchase intent without starting a payment. |
| `transitionPlan` | `( options: TargetBillingPlanTransitionOptions, ) => Promise<TargetBillingMutationResult>` | Yes | Start, change, cancel, or undo a target plan transition. |
| `portalSession` | `(options?: { flow?: 'customer_update'; }) => Promise<{ url: string }>` | Yes | Create a Stripe-hosted billing Portal session. |

### `client.monitors`

Use `client.monitors` for the /api/v2/monitors resource family.
Every `deepline monitors` verb maps here. Author a definition with `defineMonitor`,
then check/deploy/list/get/update/delete/reactivate through this namespace.

| Name | Type | Required | Description |
| - | - | -: | - |
| `status` | `() => Promise<MonitorsAccessStatus>` | Yes | Whether the current workspace can use monitors (`{ has_access, reason }`). |
| `available` | `( toolIdOrOptions?: string \| (MonitorsAvailableOptions & { tool?: string }), options?: MonitorsAvailableOptions, ) => Promise<MonitorsAvailableResult>` | Yes | The deployable monitor tools catalog. Call with no tool id for the list, or with a tool id (positional or `{ tool }`) to describe one tool's full payload/stream contract. |
| `check` | `(definition: MonitorDefinition) => Promise<MonitorCheckResult>` | Yes | Validate a monitor definition without deploying it (no spend). |
| `deploy` | `( definition: MonitorDefinition, options?: { dryRun?: boolean }, ) => Promise<MonitorDeployResult>` | Yes | Deploy a monitor from a definition. May spend Deepline credits. |
| `sync` | `( definition: MonitorDefinition, options?: MonitorLifecycleOptions, ) => Promise<MonitorJobResult \| MonitorDeployResult>` | Yes | Set the desired definition for one stable monitor key. |
| `list` | `(options?: MonitorsListOptions) => Promise<MonitorsListResult>` | Yes | List deployed monitors (active by default). Use `state` to filter the three customer states. `status` is retained for older servers. `includeConsumers` requires a limit of 20 or fewer. |
| `get` | `(key: string) => Promise<MonitorDetail>` | Yes | Fetch one deployed monitor by public key with bounded current listener health. |
| `test` | `( key: string, payload: Record<string, unknown>, options?: MonitorTestOptions, ) => Promise<MonitorTestResult>` | Yes | Test a deployed monitor's callback envelope without side effects. |
| `validate` | `(key: string) => Promise<MonitorValidateResult>` | Yes | |
| `dependents` | `(key: string) => Promise<MonitorDependents>` | Yes | List the published plays depending on one monitor's output streams. |
| `update` | `( key: string, patch: Record<string, unknown>, ) => Promise<MonitorUpdateResult>` | Yes | Update a deployed monitor by public key. |
| `delete` | `( key: string, options?: { dryRun?: boolean }, ) => Promise<MonitorDeleteResult>` | Yes | Delete a deployed monitor and its upstream provider resource. `dryRun` returns the delete plan. |
| `reactivate` | `( key: string, options?: { dryRun?: boolean }, ) => Promise<MonitorReactivateResult>` | Yes | Reactivate a disabled monitor. `dryRun` returns the reactivation cost. |
| `start` | `( key: string, options?: MonitorLifecycleOptions, ) => Promise<MonitorJobResult \| MonitorBatchOperationResult>` | Yes | Explicitly apply the retained definition for a stopped monitor. |
| `stop` | `( key: string, options?: MonitorLifecycleOptions, ) => Promise<MonitorJobResult \| MonitorBatchOperationResult>` | Yes | Converge one monitor to inactive while retaining its definition. |
| `audit` | `(options?: { fleetId?: string; cursor?: string \| null; }) => Promise<MonitorsAuditResult>` | Yes | Re-read what the provider holds onto the monitors that claim it. Bounded and idempotent: pass `cursor` back while `audit.cursor` is non-null. |
| `repair` | `(options?: { fleetId?: string; dryRun?: boolean; }) => Promise<MonitorsRepairResult>` | Yes | Converge the monitors whose desired and observed states disagree. `dryRun` returns the same plan without queueing anything. |
| `health` | `(options?: { fleetId?: string }) => Promise<MonitorsHealth>` | Yes | Delivery and convergence health for the workspace or one fleet. |
| `fleets` | `MonitorFleetsNamespace` | Yes | Define, reconcile, and control table-backed monitor fleets. |
| `batch` | `MonitorBatchNamespace` | Yes | Deploy an immutable one-off list through the common Monitor Job engine. |
| `batches` | `MonitorNamedBatchesNamespace` | Yes | Reconcile and control a stable named static Batch. |
| `jobs` | `MonitorJobsNamespace` | Yes | Read, wait for, inspect, or cancel Monitor Jobs. |


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