Generated from SDK source comments by
scripts/generate-play-sdk-reference.ts. Do not edit this file manually.Runtime Model
UsedefinePlay(...) 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.
Detail Policy
Tested Examples
The generator copies these examples fromdocs-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
Define A Play With ctx.tools.execute
Source: docs-examples/sdk-v2/company-lookup.play.ts
Fall Through A Transient Provider Failure
Catch onlyProviderTransientError 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
Schedule A Dataset Refresh
Source:docs-examples/sdk-v2/nightly-account-refresh.play.ts
Verify A Webhook With HMAC
Source:docs-examples/sdk-v2/inbound-lead-webhook.play.ts
Play Authoring Contract
Unmarked new source pins authoring contract edition 11. New maintained starters opt in to edition 10 withcompatibility: { authoringContract: 'explicit-freshness' }. Existing artifacts retain their pinned edition. Check, publish, and run use the same admitted snapshot.
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
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
Runtime Entrypoints
Deepline
Static entry point for the Deepline SDK.
Signature: class Deepline
Members
DeeplineContext
SDK context with tool shortcuts and play handles, created by Deepline.connect. Wraps a DeeplineClient for common operations.
Signature: class DeeplineContext
Members
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
Returns:
DefinedPlay<TInput, TOutput>
Overload 2
Parameters
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.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:
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 (seedeepline monitors available <id>for a tool’s streams and row columns). The changed row is delivered to the handler as the listener event’safter.
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.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
Returns:
Promise<PlayDataset<T>> — see PlayDataset
CsvOptions
Options for loading a staged CSV with ctx.csv(...).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
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.
Column Overload 1 Parameters
Column Overload 1 Returns:
DatasetBuilder< InputRow, OutputRow & Record<Name, Value> >
Column Overload 2 Parameters
Column Overload 2 Returns:
DatasetBuilder< InputRow, OutputRow & Record<Name, Value | null> >
Column Overload 3 Parameters
Column Overload 3 Returns:
DatasetBuilder< InputRow, OutputRow & Record<Name, Value> >
Column Overload 4 Parameters
Column Overload 4 Returns:
DatasetBuilder< InputRow, OutputRow & Record<Name, Value | null> >
Run Parameters
Run Returns:
Promise<PlayDataset<OutputRow>> — see 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.
DatasetColumnDefinition
Object-column form for .withColumn(...).
Use this when a column needs runIf or typed previousCell.
StepOptions
Options for row-level .withColumn(...) and steps().step(...) entries.
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.
ctx.step(id, fn)
Create one scalar durable checkpoint.
Signature: step<T>( id: string, run: () => T | Promise<T>, options?: RuntimeStepOptions, ): Promise<T>;
Parameters
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
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
Returns:
Promise<AsyncPlayRunRef> — see AsyncPlayRunRef
AsyncPlayRunRef
Serializable reference returned after an async child Run is durable.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
Returns:
Promise< ToolExecuteResult<TOutput> > — see 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.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
Returns:
Promise<PlayFetchResponse> — see 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
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
Returns:
SecretAuth — see 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
Returns:
SecretAuth — see SecretAuth
SecretAwareRequestInit
The init accepted by ctx.fetch. Same shape as RequestInit plus auth.
PlayFetchResponse
A durable response record, not a WHATWG Response: read the already-materialized bodyText and json properties. do not call .json(), .text(), or .body.
SecretHandle
An opaque reference to a workspace secret used by legacy authoring-contract
editions. New Plays receive plaintext strings from ctx.secrets.get.
SecretAuth
One resolved authentication scheme, built by ctx.secrets.bearer or ctx.secrets.header and attached to a request through init.auth.
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
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
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.
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.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 onlyProviderTransientError 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
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.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.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.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.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.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.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.
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.
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
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
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
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
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
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
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.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.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.
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.
Low-Level Client
DeeplineClient
Low-level typed REST client with authentication, retries, and localhost failover.
Signature: class DeeplineClient
Members
client.runs
Use client.runs to watch, stop, query logs/events, and export durable dataset rows.
client.billing
Public client.billing namespace for CLI commands and programmatic callers.
Covers usage, plans, subscription state, cancellation, and invoice/receipt
history.
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.