Skip to main content

SDK Reference

Generated from SDK source comments by scripts/generate-play-sdk-reference.ts. Do not edit this file manually.

Runtime Model

The Deepline SDK is a runtime SDK. Your TypeScript defines durable play code and typed run contracts; Deepline executes that code in the cloud runtime, records provider/tool calls, persists dataset rows, and exposes run state through SDK handles and HTTP APIs. Use definePlay(...) for code that runs inside a Deepline play. Inside that function, ctx.* is the runtime boundary: ctx.tools.execute calls managed providers, ctx.dataset records row-level work, ctx.step checkpoints scalar work, ctx.fetch records external HTTP, and ctx.runPlay composes registered or prebuilt plays. 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.

Reference Map

AreaPrimary surfaceUse when
Runtime entrypointDeepline.connect() / DeeplineContextA script or service needs to call tools, run plays, or inspect runs.
Play authoringdefinePlay(...) / ctx.*Code should run durably inside Deepline with persisted steps, datasets, tools, and child plays.
Tool/provider callsctx.tools.execute(...), deepline.tools.execute(...), client.executeTool(...)You need provider-backed enrichment/search with Deepline auth, billing, extraction metadata, and retries.
Remote plays/runsctx.play(name), ctx.runPlay(...), PlayJob, client.runsYou need to run, poll, stream, stop, export, publish, or inspect plays.
Raw HTTPreferences/api-reference.mdA backend, notebook, scheduler, or non-TypeScript caller invokes Deepline over REST.

Detail Policy

MaterialRendered as
Tested examplesFull runnable code blocks.
ClassesOne member table with purpose, parameters, and returns.
Interfaces and object typesField tables; no duplicate declaration dump.
Fieldless aliases or overloadsCompact signature line plus parameter/return tables.
Full HTTP routesGenerated in references/api-reference.md.

Tested Examples

These examples are copied from docs-examples/sdk-v2 and validated by bun run docs:sdk-v2:check. Keep examples there first, then regenerate this reference.

Run A Prebuilt From TypeScript

Source: docs-examples/sdk-v2/run-prebuilt.ts
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/',
  first_name: 'Jane',
  last_name: 'Smith',
  company_name: 'ExampleCo',
  domain: 'example.com',
});

const result = await job.get();
console.log(JSON.stringify(result, null, 2));

Define A Play With ctx.tools.execute

Source: docs-examples/sdk-v2/company-lookup.play.ts
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.',
    });

    return {
      domain: input.domain,
      lookupStatus: result.status,
    };
  },
);

Schedule A Dataset Refresh

Source: docs-examples/sdk-v2/nightly-account-refresh.play.ts
import { definePlay } from 'deepline';

type Account = {
  domain: string;
  owner: string;
};

export default definePlay(
  'docs-nightly-account-refresh',
  async (ctx, input: { accounts: Account[] }) => {
    const rows = await ctx
      .dataset('account_refresh', input.accounts)
      .withColumn(
        'company_signal',
        (account, rowCtx) =>
          rowCtx.tools.execute({
            id: 'company_signal',
            tool: 'test_rate_limit',
            input: {
              key: account.domain,
            },
            description: 'Refresh one account signal for the owner.',
          }),
        { staleAfterSeconds: 86_400 },
      )
      .run({
        key: 'domain',
        description: 'Refresh target account signals once per day.',
      });

    return { rows };
  },
  {
    cron: {
      schedule: '0 9 * * *',
      timezone: 'America/New_York',
    },
    billing: {
      maxCreditsPerRun: 25,
    },
  },
);

Verify A Webhook With HMAC

Source: docs-examples/sdk-v2/inbound-lead-webhook.play.ts
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.',
    });

    return {
      email: input.email,
      domain,
      source: input.source ?? 'webhook',
      company_status: company.status,
    };
  },
  {
    webhook: {
      hmac: {
        secretEnv: 'HUBSPOT_WEBHOOK_SECRET',
        header: 'x-hubspot-signature-v3',
        algorithm: 'sha256',
      },
    },
  },
);
Generated from source comments and type declarations by scripts/generate-play-sdk-reference.ts. Do not edit this file manually.

Version And Coverage

FieldValue
SDK version0.1.90
API contract2026-06-dataset-column-cell-stale-hard-cutover
Latest supported SDK0.1.90
Minimum supported SDK0.1.53
Deprecated below0.1.53
Generated sourcessdk/src/client.ts
sdk/src/play.ts
shared_libs/play-runtime/cell-staleness.ts
shared_libs/play-runtime/tool-result-types.ts
shared_libs/plays/dataset.ts
CoverageRuntime 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 coveredFull CLI command help, provider-specific input/output schemas, dashboard-only routes, and marketing/tutorial guides. Use references/api-reference.md for generated HTTP route contracts.

Runtime Entrypoints

Deepline

Static entry point for the Deepline SDK. Signature: class Deepline

Members

MemberKindPurposeParametersReturns / type
connectmethodCreate 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

High-level SDK context with tool shortcuts and play handles. Created by Deepline.connect. Wraps a DeeplineClient with a friendlier API for common operations. Signature: class DeeplineContext

Members

MemberKindPurposeParametersReturns / type
constructorconstructorCreate 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.
toolsgetterTool operations namespace.DeeplineToolsNamespace
playsgetterPlay 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
prebuiltgetterConvenience 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>
playmethodGet a named play handle for remote lifecycle operations.name: string - Play name (as registered on the server)DeeplineNamedPlay<TInput, TOutput>
runPlaymethodRun 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 runtime, prefer the in-play ctx.runPlay(key, playRef, input,<br />options) form so the child run is checkpointed 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:
  1. A callable function — invoked by the Temporal worker with a runtime context
  2. A named play handle — with .run(), .versions(), .get(), .publish(), etc. for remote lifecycle management
Plays are the primary abstraction for building repeatable data pipelines. They run on Temporal for durable execution with automatic retries and timeouts. Signature: export function definePlay<TInput, TOutput extends PlayReturnObject>( config: DefinePlayConfig<TInput, TOutput>, ): DefinedPlay<TInput, TOutput>; export function definePlay<TInput, TOutput extends PlayReturnObject>( name: string, fn: (ctx: DeeplinePlayRuntimeContext, input: TInput) => Promise<TOutput>, bindings?: PlayBindings, ): DefinedPlay<TInput, TOutput>;

Overload 1

Parameters

NameTypeRequiredDescription
configDefinePlayConfig<TInput, TOutput>YesObject-form play config.

Returns

DefinedPlay<TInput, TOutput>

Overload 2

Parameters

NameTypeRequiredDescription
namestringYesPlay name.
fn(ctx: DeeplinePlayRuntimeContext, input: TInput) => Promise<TOutput>YesPlay function.
bindingsPlayBindingsNoTrigger bindings.

Returns

DefinedPlay<TInput, TOutput>

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.

Fields

NameTypeRequiredDescription
idstringYesPlay id/name.
inputPlayInputContract<TInput>YesInput schema.
run(ctx: DeeplinePlayRuntimeContext, input: TInput) => Promise<TOutput>YesPlay function.
bindingsPlayBindingsNoTrigger bindings.
billingPlayBindings['billing']NoBilling options.

PlayBindings

Optional trigger bindings for a play. Plays can be triggered by webhooks (with HMAC signature verification) or cron schedules. Bindings are declared as the third argument to definePlay.

Fields

NameTypeRequiredDescription
billing{ maxCreditsPerRun?: number; }NoOptional per-run billing controls enforced by the runtime.
webhook{ hmac?: { algorithm?: 'sha256'; header?: string; secretEnv: string; }; }NoWebhook trigger with optional HMAC signature verification.
cron{ schedule: string; timezone?: string; }NoCron schedule trigger.
secretsreadonly string[]NoCustomer-authored play secrets this play is allowed to use at runtime.
Values are never bundled or exposed by the SDK; access them with
ctx.secrets.get("NAME") and approved helpers such as
ctx.secrets.bearer(handle).

ctx.csv(path, options)

Load a staged CSV file as a durable dataset handle. Use this when a play receives a CSV path from the CLI or API and row work should continue through DeeplinePlayRuntimeContext.dataset. The path is normally an input field such as input.csv, populated by deepline plays run my.play.ts --csv rows.csv. Each CSV row becomes an object keyed by canonical column names. Use options.columns / options.rename to map user headers such as "Company Domain" to stable code fields such as domain. Signature: csv<T = Record<string, unknown>>( path: string, options?: CsvOptions, ): Promise<PlayDataset<T>>;

Parameters

NameTypeRequiredDescription
pathstringYesStaged CSV path.
optionsCsvOptionsNoCSV load options.

Returns

Promise<PlayDataset<T>>

CsvOptions

Options for loading a staged CSV with ctx.csv(...).

Fields

NameTypeRequiredDescription
descriptionstringNoHuman-readable description for runtime logs and inspection.
columnsCsvRenameMapNoCanonical field-to-header aliases, e.g. { domain: ['domain', 'Company Domain'] }.
renameCsvRenameMapNoHeader rename map; use columns for new code.
requiredreadonly string[]NoCanonical fields that must be present after header normalization.

ctx.dataset(key, items)

Create a persisted row dataset/table from input rows. ctx.dataset is Deepline’s row-work primitive. It records row identity, progress, retries, table output, and idempotency for a collection of rows. Use .withColumn(name, resolver) on the returned builder to define output columns, then .run(...) to execute the row program. The key identifies the logical dataset/table. Renaming it is a persistence migration: existing rows may no longer be reused. Row identity is derived automatically from input row content unless .run({ key: ... }) overrides it with stable business fields such as domain, email, or linkedin_url. By default, ctx.dataset is row-preserving: one input row produces one output row, with original fields merged with the columns produced by .withColumn(...). If one input entity must become many output rows, use the documented expand/flatten recipe instead of assuming ctx.dataset changes row cardinality. Signature: dataset<TItem extends object>( key: string, items: PlayDatasetInput<TItem>, ): DatasetBuilder<TItem, TItem>;

Parameters

NameTypeRequiredDescription
keystringYesDataset/table name.
itemsPlayDatasetInput<TItem>YesInput rows.

Returns

DatasetBuilder<TItem, TItem>

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

Define one output column for every row in this dataset. The name becomes a field on each output row. For example, .withColumn('contact', ...) creates row.contact in later column resolvers; it does not spread returned object fields such as contact.email into row.email. Add a later column resolver when you want a top-level export field: .withColumn('email', row => row.contact?.email ?? null).
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>
      | StepProgramResolver<OutputRow, Value>,
    options: StepOptions<OutputRow, Value>,
  ): DatasetBuilder<InputRow, OutputRow & Record<Name, Value | null>>;

run(options?: {
    description?: string;
    key?:
      | (keyof InputRow & string)
      | readonly (keyof InputRow & string)[]
      | ((
          row: InputRow,
          index: number,
        ) => string | number | readonly unknown[]);
  }): Promise<PlayDataset<OutputRow>>;

Column Overload 1 Parameters

NameTypeRequiredDescription
nameNameYesOutput column name.
resolverColumnResolver<OutputRow, Value>YesComputes the value for one row.

Column Overload 1 Returns

DatasetBuilder<InputRow, OutputRow & Record<Name, Value>>

Column Overload 2 Parameters

NameTypeRequiredDescription
nameNameYesOutput column name.
definitionDatasetColumnDefinition<OutputRow, Value> & { readonly runIf: ( row: OutputRow, index: number, ) => boolean | Promise<boolean>; }YesObject-column definition with required runIf.

Column Overload 2 Returns

DatasetBuilder<InputRow, OutputRow & Record<Name, Value | null>>

Column Overload 3 Parameters

NameTypeRequiredDescription
nameNameYesOutput column name.
definitionDatasetColumnDefinition<OutputRow, Value>YesObject-column definition.

Column Overload 3 Returns

DatasetBuilder<InputRow, OutputRow & Record<Name, Value>>

Column Overload 4 Parameters

NameTypeRequiredDescription
nameNameYesOutput column name.
resolver| StepResolver<OutputRow, Value> | StepProgramResolver<OutputRow, Value>YesComputes the value for one row.
optionsStepOptions<OutputRow, Value>YesRow gate and freshness options.

Column Overload 4 Returns

DatasetBuilder<InputRow, OutputRow & Record<Name, Value | null>>

Run Parameters

NameTypeRequiredDescription
options{ description?: string; key?: | (keyof InputRow & string) | readonly (keyof InputRow & string)[] | (( row: InputRow, index: number, ) => string | number | readonly unknown[]); }NoRun options.

Run Returns

Promise<PlayDataset<OutputRow>> Execute the row-column program and return a durable dataset handle. The returned PlayDataset preserves one output row per input row, with original fields merged with the columns produced by .withColumn(...).

StaleAfterSeconds

Freshness policy for dataset cells and step-program columns. Use a positive whole number of seconds for a fixed TTL. Use a function when the next expiry depends on the value that was just produced. The function receives the completed cell value; return a positive whole number of seconds to set the next expiry, or null to keep that value indefinitely. Result-based policies are evaluated only for dataset/step-program cells. The scalar ctx.step, ctx.fetch, ctx.runPlay, and ctx.tools.execute APIs accept numeric TTLs. Signature: export type StaleAfterSeconds<Value = unknown> = | number | ((value: Value) => number | null);

DatasetColumnRunInput

Input object passed to an object-column run resolver.

Fields

NameTypeRequiredDescription
rowRowYesCurrent row, including previously computed columns.
ctxDeeplinePlayRuntimeContextYesRuntime context for tool/play/fetch/log calls.
indexnumberYesZero-based row index for this dataset run.
previousCellPreviousCell<Value>NoThe prior stored value for this exact row+column when the runtime has
decided the cell is due to run again. previousCell.value is the same type
this column returns; metadata such as completedAt and staleAt lives
beside it and is not mixed into the value.

DatasetColumnDefinition

Object-column form for .withColumn(...). Use this when a column needs runIf, typed previousCell, or a result-based staleAfterSeconds(value) policy.

Fields

NameTypeRequiredDescription
run(input: DatasetColumnRunInput<Row, Value>) => Value | Promise<Value>YesCompute one cell value. Receives the previous stored value when rerunning.
runIf(row: Row, index: number) => boolean | Promise<boolean>NoOptional row-level gate. Skipped rows produce null for this column.
staleAfterSecondsStaleAfterSeconds<Value>NoFixed or value-dependent freshness policy for this cell.

StepOptions

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

Fields

NameTypeRequiredDescription
runIf(row: Row, index: number) => boolean | Promise<boolean>NoOptional row-level gate. Skipped rows produce null for this column.
staleAfterSecondsStaleAfterSeconds<Value>NoFixed or value-dependent freshness policy for this cell.

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.

Fields

NameTypeRequiredDescription
valueValueYesPrevious completed value for this row+column.
completedAtnumberNoMillisecond timestamp when the previous value completed.
staleAtnumber | nullNoMillisecond timestamp when the previous value becomes stale; null means no expiry.
staleAfterSecondsnumberNoResolved numeric TTL in seconds for the previous value, when present.

ctx.step(id, fn)

Create one scalar checkpoint for the whole play run. Use ctx.step when a value is nondeterministic, expensive, external, or useful to inspect as a named boundary. The first execution stores the JSON-serializable output under id; replay and retries return the stored value instead of running run again. Plain deterministic assignment does not need ctx.step. Use ctx.dataset(...).withColumn(...), not ctx.step, when the value should become a field on each exported row. Signature: step<T>( id: string, run: () => T | Promise<T>, options?: { staleAfterSeconds?: number }, ): Promise<T>;

Parameters

NameTypeRequiredDescription
idstringYesCheckpoint id.
run() => T | Promise<T>YesComputes the value once.
options{ staleAfterSeconds?: number }NoCheckpoint options.

Returns

Promise<T>

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

Invoke another registered or file-backed play as a child workflow. Use this for real composition boundaries, especially when a fitting scalar prebuilt play already encodes provider order, fallbacks, normalization, and no-result behavior. Do not invoke plays through ctx.tools.execute; tools and plays are separate namespaces. key is the stable child-call identity for idempotency and traceability. Signature: runPlay<TOutput = unknown>( key: string, playRef: string | PlayReferenceLike, input: Record<string, unknown>, options: { description?: string; staleAfterSeconds?: number }, ): Promise<TOutput>;

Parameters

NameTypeRequiredDescription
keystringYesStable child-call key.
playRefstring | PlayReferenceLikeYesRegistered play name, play handle, or file-backed play reference.
inputRecord<string, unknown>YesInput object passed to the child play.
options{ description?: string; staleAfterSeconds?: number }YesChild play options.

Returns

Promise<TOutput>

ctx.tools.execute(request)

Execute a single tool with a keyword-style request object. Signature: execute<TOutput = LoosePlayObject>( request: ToolExecutionRequest & { staleAfterSeconds?: number }, ): Promise<ToolExecuteResult<TOutput>>;

Parameters

NameTypeRequiredDescription
requestToolExecutionRequest & { staleAfterSeconds?: number }YesTool call request.

Returns

Promise<ToolExecuteResult<TOutput>>

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 inside this play and participates in replay/idempotency.

Fields

NameTypeRequiredDescription
idstringYesStable logical id for this tool call within the play.
toolstringYesCurrent tool id from deepline tools search / deepline tools describe.
inputRecord<string, unknown>YesJSON-serializable provider/tool input object.
descriptionstringNoHuman-readable description for logs and run inspection.
staleAfterSecondsnumberNoNumeric TTL in seconds for this tool checkpoint.

ctx.fetch(key, url, init)

Durable HTTP fetch. Use this for non-provider HTTP calls that must replay safely. The response is recorded under key so workflow replay sees the same value. Prefer ctx.tools.execute(...) for Deepline-managed provider APIs because tools handle auth, retries, rate limits, extraction metadata, and spend tracking. Signature: fetch( key: string, url: string | URL, init?: SecretAwareRequestInit, options?: { staleAfterSeconds?: number }, ): Promise<{ ok: boolean; status: number; statusText: string; url: string; headers: Record<string, string>; bodyText: string; json: unknown | null; }>;

Parameters

NameTypeRequiredDescription
keystringYesCheckpoint id.
urlstring | URLYesURL to fetch.
initSecretAwareRequestInitNoFetch options.
options{ staleAfterSeconds?: number }No

Returns

Promise<{ ok: boolean; status: number; statusText: string; url: string; headers: Record<string, string>; bodyText: string; json: unknown | null; }>

ctx.runSteps(program, input, options)

Run a reusable step program against one scalar input object. steps().step(...) is a composable mini-pipeline. Use ctx.runSteps(...) when that mini-pipeline should execute outside a row dataset. Inside a ctx.dataset column resolver, pass the step program directly to .withColumn(name, program) instead. Signature: runSteps<TInput extends Record<string, unknown>, TOutput>( program: StepProgram<TInput, any, TOutput>, input: TInput, options?: { description?: string }, ): Promise<TOutput>;

Parameters

NameTypeRequiredDescription
programStepProgram<TInput, any, TOutput>YesStep program.
inputTInputYesProgram input.
options{ description?: string }NoRun options.

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(), or other array aliases; those hide the runtime cost of loading persisted rows into memory.

Fields

NameTypeRequiredDescription
datasetKindPlayDatasetKindYesDataset kind.
datasetIdstringYesDataset id.
backingPlayDatasetBackingNoBacking store info.
sourceLabelstring | nullNoDisplay label.
tableNamespacestring | nullNoRuntime table name.

ToolExecuteResult

Canonical result returned by Deepline tool execution. The top-level object is Deepline-owned execution metadata and semantic extraction state. Raw tool/provider data lives under toolResponse.raw; response metadata lives under toolResponse.meta. Semantic single-value getters live under extractedValues.<name>.get(), and list getters live under extractedLists.<name>.get(). Use extractors first when a tool contract exposes them. Drop to toolResponse.raw when you need provider-specific fields or when debugging from persisted run rows. 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>;

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>; execute( toolId: string, input: Record<string, unknown>, ): Promise<ToolExecuteResult>; };

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.

Fields

NameTypeRequiredDescription
namestringYesThe play’s name.

PlayJob

Handle to a running play execution. Provides methods to check status, stream logs, wait for completion, or cancel the execution. This handle is the SDK-context equivalent of deepline play run --watch and POST /api/v2/plays/run: every surface returns a run id first, then exposes the completed user output through PlayJob.get() or the status endpoint’s result field. Runtime logs are available from status().progress.logs and are intentionally separate from the returned output object.

Fields

NameTypeRequiredDescription
idstringYesTemporal workflow ID for this execution.

Low-Level Client

DeeplineClient

Low-level client for the Deepline REST API. Provides typed methods for every API endpoint: tools, plays, auth, and health. Handles authentication, retries, and localhost failover automatically. Signature: class DeeplineClient

Members

MemberKindPurposeParametersReturns / type
constructorconstructorCreate 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.
runspropertyCanonical run lifecycle namespace backed by /api/v2/runs.RunsNamespace
baseUrlgetterThe resolved base URL this client is targeting (e.g. "http://localhost:3000").string
listSecretsmethodList secret metadata visible to the current workspace.Promise<PlaySecretMetadata[]>
checkSecretmethodCheck 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>
listToolsmethodList all available tools.

Returns tool definitions including ID, provider, description, input/output schemas,
and list extractor paths for automatic CSV conversion.
options?: { categories?: string; grep?: string; grepMode?: 'all' | 'any' | 'phrase'; compact?: boolean; }Promise<ToolDefinition[]>
searchToolsmethodSearch available tools using Deepline’s ranked backend search.

This is the same discovery surface used by the CLI: it ranks across
tool metadata, categories, agent guidance, and input schema fields.
options?: ToolSearchOptionsPromise<ToolSearchResult>
getToolmethodGet 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. "apollo_people_search")Promise<ToolMetadata>
executeToolmethodExecute a tool and return the standard execution envelope.

The toolResponse.raw field contains the raw tool response.
toolResponse.meta contains tool/provider 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>>
executeToolRawmethodBack-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>>
queryCustomerDbmethodRun a bounded SQL query against the customer data plane.

Use this from trusted backend or agent contexts only. The API enforces
workspace scoping and row limits.
input: { sql: string; maxRows?: number; }Promise<CustomerDbQueryResult>
startPlayRunmethodStart a play run.

Internal/advanced primitive. For normal callers, prefer the public
entrypoints: the CLI, Deepline.connect, submitPlay,
or runPlay.

Supported invocation surfaces intentionally share this same run contract:
deepline play run, repo scripts such as bun run deepline -- play run,
SDK context calls like Deepline.connect().play(name).run(), and direct
POST /api/v2/plays/run calls all return a workflow/run id. The completed
output is always retrievable from getPlayStatus(runId).result (or from
PlayJob.get() for SDK context calls). Execution logs live under
progress.logs; they are not part of the user output object.
request: StartPlayRunRequest - Play run configuration (name, code, input, etc.)Promise<PlayRunStart>
startPlayRunStreammethodStart a play run and stream live runtime events from the same request.

Use this when a caller wants low-level event handling instead of submitting
first and then connecting to streamPlayRunEvents(runId).
request: StartPlayRunRequest - Play run configuration.
options?: { signal?: AbortSignal } - Optional streaming options.
AsyncGenerator<PlayLiveEvent>
registerPlayArtifactmethodRegister 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>; artifact: Record<string, unknown>; compilerManifest?: PlayCompilerManifest; publish?: 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; }>
registerPlayArtifactsmethodRegister 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>; 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; }>; }>
compilePlayManifestmethodCompile a bundled play artifact into the server-side compiler manifest.

The manifest records imports, trigger bindings, static pipeline shape, and
runtime metadata needed before a play artifact can be checked, registered,
or run.
input: { name: string; sourceCode: string; sourceFiles?: Record<string, string>; artifact: Record<string, unknown>; importedPlayDependencies?: PlayCompilerManifest[]; }Promise<PlayCompilerManifest>
checkPlayArtifactmethodCheck 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 play check.
input: { name?: string; sourceCode: string; sourceFiles?: Record<string, string>; artifact: Record<string, unknown>; }Promise<PlayCheckResult>
compileEnrichPlanmethodCompile legacy enrich command arguments into a runtime plan.

This is primarily used by CLI compatibility paths that translate older
enrichment commands onto the play runtime.
input: { plan_args?: string[]; config?: unknown; }Promise<{ config: EnrichCompiledConfig }>
startPlayRunFromBundlemethodRegister an already-bundled play artifact and start a run from it.

This is the low-level file-backed run path used by SDK/CLI packaging
wrappers after local bundling has produced the runtime artifact.
input: { name: string; sourceCode: string; sourceFiles?: Record<string, string>; artifact: Record<string, unknown>; compilerManifest?: PlayCompilerManifest; input?: Record<string, unknown>; inputFile?: PlayStagedFileRef | null; packagedFiles?: PlayStagedFileRef[]; force?: boolean; }Promise<PlayRunStart>
submitPlaymethodRegister a bundled play artifact and start a run from the live revision.

Convenience wrapper around registerPlayArtifact plus
startPlayRun. This is the canonical file-backed path used by wrappers.
The returned id can be passed to getPlayStatus to retrieve the same
durable { result } object that the CLI prints after --watch completes.
code: string - Source string fallback; the bundled artifact should be passed in options.artifact
csvPath: string | null - Path to input CSV file, or null
name?: string - Play name (extracted from source if omitted)
options?: { sourceCode?: string; sourceFiles?: Record<string, string>; artifact?: Record<string, unknown>; compilerManifest?: PlayCompilerManifest; input?: Record<string, unknown>; inputFile?: PlayStagedFileRef | null; packagedFiles?: PlayStagedFileRef[]; force?: boolean; } - Additional submission options
Promise<PlayRunStart>
stagePlayFilesmethodUpload 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[]>
resolveStagedPlayFilesmethodResolve staged play files by content hash without uploading bytes.

Missing files are returned so callers can upload only the files the server
does not already have.
files: Array<{ logicalPath: string; contentHash: string; contentType: string; bytes: number; }>Promise<{ files: PlayStagedFileRef[]; missing: Array<{ logicalPath: string; contentHash: string }>; }>
getPlayStatusmethodGet the current status of a play execution.

Internal/advanced primitive. Public callers should usually prefer
runPlay, PlayJob.get, or deepline play run --watch.
workflowId: string - Play-run id from startPlayRun
options?: { billing?: boolean; full?: boolean }
Promise<PlayStatus>
streamPlayRunEventsmethodStream semantic play-run events using the same SSE feed as the dashboard.

The server emits a canonical play.run.snapshot event first for every
connection, then incremental live events until terminal state or reconnect.
workflowId: string
options?: { signal?: AbortSignal; lastEventId?: string; mode?: 'cli' | 'ui'; }
AsyncGenerator<PlayLiveEvent>
cancelPlaymethodCancel a running play execution.

Sends a stop request for the run.
workflowId: string - Public Deepline play-run id to cancelPromise<void>
stopPlaymethodStop a running play execution, including open HITL waits.workflowId: string - Public Deepline play-run id to stop
options?: { reason?: string }
Promise<StopPlayRunResult>
listPlayRunsmethodList 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 queryPromise<PlayRunListItem[]>
getRunStatusmethodGet a run by id using the public runs resource model.

This is the SDK equivalent of:

bash<br />deepline runs get <run-id> --json<br />
runId: string
options?: { full?: boolean }
Promise<PlayStatus>
listRunsmethodList play runs using the public runs resource model.

This is the SDK equivalent of:

bash<br />deepline runs list --play <play-name> --status failed --json<br />
options: RunsListOptionsPromise<PlayRunListItem[]>
tailRunmethodRead the canonical run stream and return the latest run snapshot.runId: string
options?: RunsTailOptions
Promise<PlayStatus>
getRunLogsmethodFetch persisted logs for a run using the public runs resource model.

This is the SDK equivalent of:

bash<br />deepline runs logs <run-id> --limit 200 --json<br />
runId: string
options?: RunsLogsOptions
Promise<RunsLogsResult>
getPlaySheetRowsmethodExport 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; }Promise<PlaySheetRowsResult>
stopRunmethodStop 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" --json<br />
runId: string
options?: { reason?: string }
Promise<StopPlayRunResult>
listPlaysmethodList callable plays visible to the workspace.

Pass origin: "prebuilt" for Deepline-managed prebuilts or
origin: "owned" for org-owned plays.
options?: { origin?: 'prebuilt' | 'owned'; grep?: string; grepMode?: 'all' | 'any' | 'phrase'; }Promise<PlayListItem[]>
searchPlaysmethodSearch 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; scope?: 'prebuilt' | 'owned' | 'all'; }Promise<PlayDescription[]>
getPlaymethodGet the full definition and state of a named play.

Returns the play’s revision state (draft, live), recent runs,
sheet processing summary, and database URL.
name: string - Play namePromise<PlayDetail>
describePlaymethodGet a normalized play description suitable for agents and CLIs.

The description includes runnable examples, input/output summaries, clone
guidance, revision state, and latest run metadata when available.
name: string
options?: { compact?: boolean }
Promise<PlayDescription>
clearPlayHistorymethodClear run history and durable sheet/result data for a play without deleting
the play definition or revisions.
name: string
request?: ClearPlayHistoryRequest
Promise<ClearPlayHistoryResult>
listPlayVersionsmethodList 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[]>
publishPlayVersionmethodMake a play revision live.

When revisionId is omitted, the current working revision becomes live.
The live version is what executes when the play is run by name without
specifying an explicit revision.
name: string - Play name
request?: PublishPlayVersionRequest - Optional explicit revision to make live
Promise<PublishPlayVersionResult>
deletePlaymethodDelete an org-owned play definition, including its revisions, trigger
bindings, and local run records. Deepline prebuilt plays are read-only.
name: stringPromise<DeletePlayResult>
getSharePagemethodCurrent share status for a play: the public page (if any), the published
copy, and the revision picker. Read-only.
name: stringPromise<SharePageStatus>
publishSharePagemethodPublish (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>
updateSharePagemethodUpdate share-page settings (SEO indexing, credit-cost / latency display)
without moving the published pointer. Org-admin only.
name: string
request: UpdateSharePageRequest
Promise<SharePageStatus>
unpublishSharePagemethodUnshare: 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: stringPromise<SharePageStatus>
regenerateSharePagemethodRegenerate the LLM landing-page copy for a revision (defaults to the
published one). Org-admin only.
name: string
request?: { revisionId?: string }
Promise<SharePageStatus>
runPlaymethodRun a play end-to-end: submit, stream until terminal, return result.

This is the highest-level play execution method. It submits the play,
reads the canonical run stream 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; } - Execution options
Promise<PlayRunResult>
healthmethodCheck API connectivity and server health.Promise<{ status: string; version?: string }>

client.runs

Public runs namespace exposed as client.runs. This namespace mirrors the canonical /api/v2/runs resource family and is the preferred low-level surface for polling, streaming, stopping, reading logs, and exporting durable dataset rows.

Fields

NameTypeRequiredDescription
get(runId: string, options?: { full?: boolean }) => Promise<PlayStatus>YesGet current run status by public run id.
list(options: RunsListOptions) => Promise<PlayRunListItem[]>YesList runs for one play, optionally filtered by status.
tail(runId: string, options?: RunsTailOptions) => Promise<PlayStatus>YesStream run events and return the latest/terminal run status.
logs(runId: string, options?: RunsLogsOptions) => Promise<RunsLogsResult>YesFetch persisted log lines for a run.
exportDatasetRows(input: { playName: string; tableNamespace: string; runId?: string; limit?: number; offset?: number; }) => Promise<PlaySheetRowsResult>YesExport persisted rows for a runtime-sheet dataset/table namespace.
stop( runId: string, options?: { reason?: string }, ) => Promise<StopPlayRunResult>YesStop a running/waiting run.