///
import * as _sinclair_typebox from '@sinclair/typebox';
import { Static } from '@sinclair/typebox';
declare const PLAY_RUNTIME_BACKENDS: {
readonly localProcess: "local_process";
readonly daytona: "daytona";
readonly modal: "modal";
};
type PlayRuntimeBackendId = (typeof PLAY_RUNTIME_BACKENDS)[keyof typeof PLAY_RUNTIME_BACKENDS];
/**
* The one executable Play artifact contract. Daytona and local-process both
* load CommonJS under Node 20.
*/
declare const PLAY_ARTIFACT_KINDS: {
readonly cjsNode20: "cjs_node20";
};
type PlayArtifactKind = (typeof PLAY_ARTIFACT_KINDS)[keyof typeof PLAY_ARTIFACT_KINDS];
type PlayDocflowNodeKind = 'action' | 'decision' | 'dataset' | 'play' | 'conceptual';
type PlayDocflowNode = {
id: string;
label: string;
kind: PlayDocflowNodeKind;
/**
* No statement in this play runs this box — the author said so with
* `class sketch`. See {@link SKETCH_CLASS}.
*
* Deliberately NOT a `kind`. What a box IS (an action, a decision, a dataset)
* and whether code binds it are two different questions, and folding the
* second into the first was wrong in a way the tests caught immediately: a
* sketched diamond stopped being a decision, so it lost its shape on the
* canvas and the branch-label lint stopped checking its arms. Absent rather
* than `false` when bound, so the JSON a bound diagram hashes to is byte for
* byte what it was before sketches existed.
*/
sketch?: true;
};
/**
* Which arm of a conditional a drawn decision edge IS.
*
* The runtime's own two-valued vocabulary for a `runIf` (ADR 0019): the cell
* record says `branch: 'run' | 'else'`, and this is the same token on the
* diagram's side of the join. Deliberately NOT the arm's label — a label is the
* author's prose ("fit 65 or better", "nicht gefunden") and says nothing about
* polarity in any language.
*/
type PlayDocflowArm = 'run' | 'else';
type PlayDocflowEdge = {
from: string;
to: string;
label?: string;
/**
* The conditional arm this edge is, when the author recorded it.
*
* ABSENT — never `null` — when unrecorded, and that is load-bearing rather
* than stylistic. `docflow` is whole-object serialized into
* `playStaticPipelineContractHash` (`src/lib/plays/artifact-storage.ts`),
* which is part of the immutable artifact storage key, and the canonicalizer
* there drops `undefined` but HASHES `null`. Emitting `arm: null` on an
* unannotated edge would change the contract hash of every diagrammed play
* ever published and force a republish. Omission is what keeps this additive.
*/
arm?: PlayDocflowArm;
};
/**
* A Mermaid `subgraph … end` region. When an edge connects it to a dataset
* node, it models that dataset's per-row loop; its members represent the
* per-row column work. See `docs/play-syntax-spec.md`. `memberIds` records the
* innermost subgraph for nested regions.
*/
type PlayDocflowSubgraph = {
id: string;
label: string;
memberIds: string[];
};
type PlayDocflowBinding = {
nodeId: string;
line: number;
label?: string;
kind?: PlayDocflowNodeKind;
/** Symbolic values read by this business node. Never an arbitrary JS expression. */
inputs?: string[];
/** Symbolic values produced or changed by this business node. */
outputs?: string[];
/** Whether the contract was authored, safely inferred, or still needs help. */
ioConfidence?: 'explicit' | 'inferred' | 'ambiguous';
/**
* `arm:"run"` / `arm:"else"` — this node is that arm of the decision above it.
*
* Recorded on the annotation because the annotation is the only place the two
* halves of the join meet: a `@mermaid-node` binds a DIAGRAM id to the SOURCE
* statement directly beneath it, so the author writing it is the one person
* who knows both which drawn arm this is and which side of the `runIf` the
* code under it implements. Projected onto the incoming decision edge by
* {@link attachBindingsToBlocks}; the edge is what readers resolve against.
*/
arm?: PlayDocflowArm;
};
type PlayDocflow = {
direction: 'LR' | 'RL' | 'TB' | 'TD' | 'BT';
nodes: PlayDocflowNode[];
edges: PlayDocflowEdge[];
bindings: PlayDocflowBinding[];
/** Authoring syntax used by the source file. */
syntax?: 'mermaid';
/** Normalized Mermaid text, ready to pass directly to a Mermaid renderer. */
mermaidSource?: string;
/**
* Mermaid `subgraph` loop regions. Optional for persisted graphs that have
* no authored regions.
*/
subgraphs?: PlayDocflowSubgraph[];
/** Mermaid directives accepted by the parser but not applied by React Flow. */
ignoredDirectives?: string[];
};
/**
* A top-level key the play's function literally `return`s. Derived from the
* `return { ... }` object literal — NOT from dataset `.withColumn(...)` names —
* so the "Returns" graph node mirrors the function's real output shape.
* `isDataset` is true when the key's value is a `PlayDataset` handle (a table).
*/
interface PlayStaticReturnField {
name: string;
isDataset: boolean;
/**
* For a dataset-valued field, the `ctx.dataset(KEY, ...)` key backing it
* (e.g. `job_change_checks`) — so the UI can label the return by the dataset
* it actually produces instead of the bland object key (`rows`). Undefined
* for non-dataset fields, `ctx.csv(...)` (no durable name), or when the key
* isn't a static string literal.
*/
datasetName?: string;
}
interface PlayStaticPipeline {
/** Authored business flow. Static analysis is used only when this is absent. */
docflow?: PlayDocflow;
tableNamespace?: string;
inputFields?: string[];
rowKeyFields?: string[];
csvArg?: string;
hasInlineData?: boolean;
csvDescription?: string;
datasetDescription?: string;
fields: string[];
/**
* Top-level keys of the play's `return { ... }` object literal, in source
* order. Undefined when the terminal return isn't a statically-known object
* literal (bare value, dataset handle, conditional returns, etc.).
*/
returnFields?: PlayStaticReturnField[];
stages?: PlayStaticSubstep[];
substeps: PlayStaticSubstep[];
sheetContract?: PlaySheetContract | null;
sheetContractErrors?: string[];
}
type PlaySheetColumnSource = 'input' | 'datasetColumn' | 'waterfallStep' | 'childPlayColumn';
interface PlaySheetColumnContract {
id: string;
sqlName: string;
source: PlaySheetColumnSource;
field?: string;
parentField?: string;
playId?: string;
waterfallId?: string;
outputField?: string;
outputSqlName?: string;
stepId?: string;
toolId?: string;
isRowKey?: boolean;
}
interface PlaySheetContract {
tableNamespace: string;
columns: PlaySheetColumnContract[];
}
type PlayStaticColumnProducerKind = 'tool' | 'waterfall' | 'stepProgram' | 'playCall' | 'controlFlow' | 'transform';
interface PlayStaticColumnProducer {
id: string;
kind: PlayStaticColumnProducerKind;
field: string;
toolId?: string;
playId?: string;
conditional?: boolean;
sourceRange?: PlayStaticSourceRange;
steps?: PlayStaticColumnProducer[];
substep: PlayStaticSubstep;
}
interface PlayStaticDatasetColumn {
id: string;
source: PlaySheetColumnSource;
sqlName?: string;
producers: PlayStaticColumnProducer[];
}
interface PlayStaticSourceRange {
sourcePath?: string;
startLine: number;
endLine: number;
startColumn: number;
endColumn: number;
}
type PlayStaticSubstepMetadata = {
conditional?: boolean;
disabled?: boolean;
};
/**
* One arm of a conditional `control_flow` substep — an `if`/`else if`/`else`
* leg, a `switch` case, or a ternary branch. Carries its own steps so the graph
* can render the conditional as a real fork instead of a flat strip.
*/
type PlayStaticControlFlowBranch = {
/** Short arm label, e.g. `if`, `else if`, `else`, `case 'x'`, `default`. */
label: string;
/** The arm's condition source text, when it has one (omitted for `else`). */
condition?: string;
/** Static work in this arm. Empty for log/throw/return-only arms. */
steps: PlayStaticSubstep[];
};
type PlayStaticSubstep = PlayStaticSubstepMetadata & ({
type: 'csv';
field: string;
path?: string;
description?: string;
sourceRange?: PlayStaticSourceRange;
callDepth?: number;
callPath?: string[];
} | {
type: 'dataset';
field: string;
name?: string;
tableNamespace?: string;
inputFields?: string[];
rowKeyFields?: string[];
outputFields?: string[];
columns?: PlayStaticDatasetColumn[];
waterfallIds?: string[];
steps?: PlayStaticSubstep[];
sheetContract?: PlaySheetContract | null;
/**
* Columns the author declared as deliberately absent from the `@mermaid`
* diagram via `.run({ undrawnColumns: [...] })`. The docflow column
* coverage gate reads this; nothing about execution does.
*/
undrawnColumns?: string[];
description?: string;
sourceRange?: PlayStaticSourceRange;
callDepth?: number;
callPath?: string[];
} | {
type: 'tool';
toolId: string;
field: string;
paramsSource?: string;
sourceText?: string;
description?: string;
inLoop?: boolean;
isEventWait?: boolean;
sourceRange?: PlayStaticSourceRange;
callDepth?: number;
callPath?: string[];
} | {
type: 'waterfall';
tool?: string;
field: string;
inLoop?: boolean;
id?: string;
output?: string;
minResults?: number;
sourceText?: string;
steps?: Array<{
id: string;
kind?: 'tool' | 'code';
toolId?: string;
paramsSource?: string;
}>;
description?: string;
sourceRange?: PlayStaticSourceRange;
callDepth?: number;
callPath?: string[];
} | {
type: 'step_suite';
field: string;
steps: PlayStaticSubstep[];
returnSource?: string;
description?: string;
sourceRange?: PlayStaticSourceRange;
callDepth?: number;
callPath?: string[];
} | {
type: 'play_call';
playId: string;
execution?: 'inline' | 'child-workflow';
timeoutMs?: number;
hasExplicitTimeout?: boolean;
field: string;
inLoop?: boolean;
pipeline?: PlayStaticPipeline | null;
cycleDetected?: boolean;
resolutionError?: string;
description?: string;
sourceRange?: PlayStaticSourceRange;
callDepth?: number;
callPath?: string[];
} | {
type: 'control_flow';
kind: 'conditional' | 'loop';
field: string;
/** Flattened steps across every arm, in source order (back-compat). */
steps: PlayStaticSubstep[];
/** Discriminant source text (the `if`/ternary test, `switch` subject). */
condition?: string;
/** Per-arm breakdown for conditionals; omitted for loops. */
branches?: PlayStaticControlFlowBranch[];
description?: string;
sourceRange?: PlayStaticSourceRange;
callDepth?: number;
callPath?: string[];
} | {
type: 'run_javascript';
alias: string;
sourceText?: string;
description?: string;
sourceRange?: PlayStaticSourceRange;
callDepth?: number;
callPath?: string[];
} | {
type: 'code';
field: string;
sourceText?: string;
description?: string;
sourceRange?: PlayStaticSourceRange;
callDepth?: number;
callPath?: string[];
});
/**
* 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.
*
* @sdkReference runtime 120
*/
type PreviousCell = {
/** Previous completed value for this row+column. */
value: Value;
/** Millisecond timestamp when the previous value completed. */
completedAt?: number;
/** Millisecond timestamp when the previous value becomes stale; `null` means no expiry. */
staleAt?: number | null;
/** Resolved numeric TTL in seconds for the previous value, when present. */
staleAfterSeconds?: number;
};
type PlaySandboxRuntimeLimits = {
timeoutSeconds: number;
memoryGiB: number;
cpu: number;
diskGiB: number;
};
type PlaySandboxSize = 'standard';
type PlaySandboxRuntimeDeclaration = {
timeout?: string;
size?: PlaySandboxSize;
};
type EmailStatusVerdict = 'send' | 'send_with_caution' | 'verify_next' | 'hold' | 'drop';
type EmailStatusValue = 'valid' | 'invalid' | 'catch_all' | 'valid_catch_all' | 'unknown' | 'do_not_mail' | 'spamtrap' | 'abuse' | 'disposable';
type EmailDeliverability = 'high' | 'medium' | 'low' | 'unknown';
type EmailMxClass = 'consumer_mailbox' | 'workspace_mailbox' | 'security_gateway' | 'on_prem' | 'unknown';
type EmailStatus = {
verdict: EmailStatusVerdict;
status: EmailStatusValue;
verified: boolean;
confidence: number | null;
reasons: string[];
signals: {
catch_all: boolean | null;
deliverability: EmailDeliverability;
mx_class: EmailMxClass;
mx_provider: string | null;
mx_record: string | null;
fraud_score: number | null;
disposable: boolean | null;
role_based: boolean | null;
free_email: boolean | null;
abuse: boolean | null;
spamtrap: boolean | null;
suspect: boolean | null;
valid: boolean | null;
};
provider: {
name: string;
raw_status: string | boolean | number | null;
raw_score: number | null;
};
};
type EmailStatusMapEntry = {
status: EmailStatusValue;
verdict?: EmailStatusVerdict;
verified?: boolean;
reason?: string;
};
type EmailStatusRule = EmailStatusMapEntry & {
when: Record;
};
type EmailStatusExtractorConfig = {
provider: string;
rawStatus?: string[];
rawScore?: string[];
valid?: string[];
deliverability?: string[];
catchAll?: string[];
mxProvider?: string[];
mxRecord?: string[];
fraudScore?: string[];
disposable?: string[];
roleBased?: string[];
freeEmail?: string[];
abuse?: string[];
spamtrap?: string[];
suspect?: string[];
statusMap?: Record;
rules?: EmailStatusRule[];
};
declare const JOB_CHANGE_STATUS_VALUES: readonly ["moved", "no_change", "left_company", "unknown", "profile_unavailable", "no_new_company"];
type JobChangeStatus = (typeof JOB_CHANGE_STATUS_VALUES)[number];
type JobChangeGetterValue = {
status: JobChangeStatus;
date: string | null;
new_company: string | null;
new_title: string | null;
};
declare const PHONE_STATUS_VALUES: readonly ["valid", "invalid", "unknown"];
type PhoneStatus = (typeof PHONE_STATUS_VALUES)[number];
declare const DEEPLINE_EXTRACTOR_TARGET_DEFINITIONS: {
readonly id: {
readonly identity: true;
readonly valueKind: "string";
};
readonly name: {
readonly identity: true;
readonly valueKind: "string";
};
readonly email: {
readonly identity: true;
readonly valueKind: "string";
};
readonly personal_email: {
readonly identity: true;
readonly valueKind: "string";
};
readonly phone: {
readonly identity: true;
readonly valueKind: "string";
};
readonly linkedin: {
readonly identity: true;
readonly valueKind: "string";
};
readonly linkedin_url: {
readonly identity: true;
readonly valueKind: "string";
};
readonly domain: {
readonly identity: true;
readonly valueKind: "string";
};
readonly website: {
readonly identity: true;
readonly valueKind: "string";
};
readonly first_name: {
readonly identity: true;
readonly valueKind: "string";
};
readonly last_name: {
readonly identity: true;
readonly valueKind: "string";
};
readonly full_name: {
readonly identity: true;
readonly valueKind: "string";
};
readonly company: {
readonly identity: true;
readonly valueKind: "string";
};
readonly company_name: {
readonly identity: true;
readonly valueKind: "string";
};
readonly organization_name: {
readonly identity: true;
readonly valueKind: "string";
};
readonly company_domain: {
readonly identity: true;
readonly valueKind: "string";
};
readonly company_website: {
readonly identity: true;
readonly valueKind: "string";
};
readonly company_linkedin_url: {
readonly identity: true;
readonly valueKind: "string";
};
readonly title: {
readonly identity: false;
readonly valueKind: "string";
};
readonly industry: {
readonly identity: false;
readonly valueKind: "string";
};
readonly status: {
readonly identity: false;
readonly valueKind: "string";
};
readonly job_change: {
readonly identity: false;
readonly valueKind: "job_change";
};
readonly job_change_status: {
readonly identity: false;
readonly valueKind: "job_change_status";
readonly enum: readonly ["moved", "no_change", "left_company", "unknown", "profile_unavailable", "no_new_company"];
};
readonly email_status: {
readonly identity: false;
readonly valueKind: "email_status";
};
readonly phone_status: {
readonly identity: false;
readonly valueKind: "phone_status";
readonly enum: readonly ["valid", "invalid", "unknown"];
};
};
type DeeplineExtractorTarget = keyof typeof DEEPLINE_EXTRACTOR_TARGET_DEFINITIONS;
declare const DEEPLINE_EXTRACTOR_TARGETS: DeeplineExtractorTarget[];
type DeeplineEmailStatusGetterValue = EmailStatus;
type DeeplineGetterValueMap = {
id: string;
name: string;
email: string;
personal_email: string;
phone: string;
linkedin: string;
linkedin_url: string;
domain: string;
website: string;
first_name: string;
last_name: string;
full_name: string;
company: string;
company_name: string;
organization_name: string;
company_domain: string;
company_website: string;
company_linkedin_url: string;
title: string;
industry: string;
status: string;
job_change: JobChangeGetterValue;
job_change_status: JobChangeStatus;
email_status: EmailStatus;
phone_status: PhoneStatus;
};
type DeeplineGetterValue = DeeplineGetterValueMap[TTarget];
declare function isDeeplineExtractorTarget(value: string): value is DeeplineExtractorTarget;
interface PlayR2FileRef {
storageKind: 'r2';
storageKey: string;
logicalPath: string;
fileName: string;
contentHash: string;
contentType: string;
bytes: number;
}
type PlayExecutionFileRef = PlayR2FileRef;
declare const PLAY_DATASET_BRAND: unique symbol;
type PlayDatasetKind = 'csv' | 'map';
type PlayDatasetBacking = {
storage: 'neon_sheet';
sheet: {
playName: string;
tableNamespace: string;
};
} | {
storage: 'r2_file';
file: PlayExecutionFileRef;
};
type PlayDatasetWorkProgressSummary = {
total: number;
executed: number;
reused: number;
skipped: number;
pending: number;
failed: number;
degraded?: boolean;
duplicates?: {
exact?: number;
semantic?: number;
rejected?: number;
};
};
type PlayDatasetInput = ReadonlyArray | Iterable | AsyncIterable | PlayDataset;
type PlayDatasetRow = TInput extends PlayDataset ? Row : TInput extends ReadonlyArray ? Row : TInput extends Iterable ? Row : TInput extends AsyncIterable ? Row : never;
type PlayDatasetTransformOptions = {
key?: string;
sourceLabel?: string | null;
};
/**
* 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;
* those hide the runtime cost of loading persisted rows into memory or make
* behavior depend on whether rows happen to be resident.
*
* @sdkReference runtime 190
*/
interface PlayDataset extends AsyncIterable {
readonly [PLAY_DATASET_BRAND]: true;
/** Dataset kind. */
readonly datasetKind: PlayDatasetKind;
/** Dataset id. */
readonly datasetId: string;
/** Backing store info. */
readonly backing?: PlayDatasetBacking;
/** Display label. */
readonly sourceLabel?: string | null;
/** Runtime table name. */
readonly tableNamespace?: string | null;
/** Row count. */
count(): Promise;
/** Preview rows. */
peek(limit?: number): Promise;
/** First row, loading it asynchronously when necessary. */
first(): Promise;
/** Row at an array-style index, loading it asynchronously when necessary. */
at(index: number): Promise;
map(mapper: (row: T, index: number) => U | Promise, options?: PlayDatasetTransformOptions): PlayDataset;
filter(predicate: (row: T, index: number) => boolean | Promise, options?: PlayDatasetTransformOptions): PlayDataset;
slice(start?: number, end?: number, options?: PlayDatasetTransformOptions): PlayDataset;
take(limit: number, options?: PlayDatasetTransformOptions): PlayDataset;
/**
* Explicit escape hatch for bounded result sets.
* Large datasets should flow by handle through Neon-backed storage, not
* through worker memory as giant arrays.
*/
materialize(options?: number | PlayDatasetMaterializeOptions): Promise;
toJSON(): {
kind: 'dataset';
datasetKind: PlayDatasetKind;
datasetId: string;
count: number;
backing?: PlayDatasetBacking;
sourceLabel?: string | null;
tableNamespace?: string | null;
columns?: string[];
_metadata?: {
workProgress?: PlayDatasetWorkProgressSummary;
};
preview: T[];
};
}
type PlayDatasetMaterializeScope = 'result' | 'full_persisted_dataset';
type PlayDatasetMaterializeOptions = {
/** Rows returned by this operation, or every current row in its persisted dataset. */
scope?: PlayDatasetMaterializeScope;
/** Maximum number of rows to load into memory. */
limit?: number;
};
type ToolResultExecutionMetadata = {
idempotent: true;
cached: boolean;
source: 'live' | 'checkpoint' | 'cache' | 'in_flight';
cacheKey?: string;
receiptRole?: 'owner' | 'follower';
receiptKey?: string;
attachedToReceiptKey?: string;
};
type ToolResultTargetMetadata = {
value: unknown;
path: string;
};
type ToolResultListMetadata = {
path: string;
count: number | null;
keys: Record;
};
type ToolResultExtractorDescriptor = {
paths: readonly string[];
transforms?: readonly string[];
enum?: readonly string[];
overrides?: readonly ToolResultExtractorOverride[];
emailStatus?: EmailStatusExtractorConfig;
};
type ToolResultExtractorOverride = {
paths: readonly string[];
equals?: string | number | boolean | null;
value: string | number | boolean | null;
};
type ToolResultTargetAccessor = ToolResultTargetMetadata & {
get(): T | null;
};
type ToolResultListAccessor, TKey extends string = string> = Omit & {
keys: Partial> & Record;
get(): PlayDataset;
};
type ToolResponseEnvelope> = {
raw: TData;
/** Complete parsed and scrubbed provider response, materialized from raw-v2. */
rawV2?: unknown;
/** Durable descriptor for deriving the legacy raw view from `rawV2`. */
view?: 'data' | 'rawV2';
meta?: TMeta;
};
type ToolExecuteResultBase> = {
status: string;
job_id?: string;
/** Deepline-owned execution/result metadata. */
meta?: Record;
toolResponse: ToolResponseEnvelope;
extractedValues: Record;
extractedLists: Record;
/** Convenience alias for play code. Serialized output uses toolResponse. */
toolOutput: ToolResponseEnvelope;
_metadata: {
toolId: string;
execution: ToolResultExecutionMetadata;
targets: Record;
extractors?: Record;
lists: Record;
}>;
/** Original declarations preserve semantic accessor names across replay. */
listExtractorPaths?: readonly string[];
};
};
type ToolExecuteResultAccessors = Partial, TLists extends Record> = Record>> = {
extractedValues: {
[K in keyof TExtracted]: ToolResultTargetAccessor;
};
extractedLists: {
[K in keyof TLists]: ToolResultListAccessor;
};
};
/**
* Canonical result returned by Deepline tool execution.
*
* The top-level object is Deepline-owned execution metadata and semantic
* extraction state. The canonical provider response lives under
* `toolResponse.rawV2`; `toolResponse.raw` remains the legacy compatibility
* projection. Response metadata lives under `toolResponse.meta`. Semantic single-value
* getters live under `extractedValues..get()`, and list getters live
* under `extractedLists..get()`.
*
* Use extractors first when a tool contract exposes them. Use list getters for
* row-shaped data. Drop to `toolResponse.raw` only for provider-specific scalar
* fields or bounded debugging context; persisted rows may clip declared lists to
* previews.
*
* @sdkReference runtime 200
*/
type ToolExecuteResult, TExtracted extends Record = Partial, TLists extends Record> = Record>> = ToolExecuteResultBase & ToolExecuteResultAccessors;
declare const TOOL_EXECUTION_ERROR_SCHEMA_VERSION: 1;
declare const SUPPORTED_TOOL_EXECUTION_ERROR_SCHEMA_VERSIONS: readonly [0, 1];
type ToolExecutionErrorSchemaVersion = (typeof SUPPORTED_TOOL_EXECUTION_ERROR_SCHEMA_VERSIONS)[number];
/**
* 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.
*
* @sdkReference errors 020
*/
type ToolExecutionErrorOrigin = 'caller' | 'provider' | 'deepline' | 'unknown';
/**
* 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.
*
* @sdkReference errors 030
*/
type ToolExecutionErrorCategory = 'validation' | 'authentication' | 'authorization' | 'rate_limit' | 'network' | 'upstream' | 'billing' | 'conflict' | 'internal' | 'unknown';
/**
* The transport failure observed when `category` is `network`.
*
* This is `null` for failures that are not network failures.
*
* @sdkReference errors 040
*/
type ToolExecutionNetworkKind = 'timeout' | 'dns' | 'connect' | 'reset' | 'unavailable' | 'unknown';
/**
* 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.
*
* @sdkReference errors 050
*/
type ToolExecutionNetworkScope = 'client_to_deepline' | 'runtime_to_deepline' | 'deepline_to_provider';
/**
* 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.
*
* @sdkReference errors 064
*/
type ToolExecutionFailureV1 = {
/** Payload version. */
schemaVersion: typeof TOOL_EXECUTION_ERROR_SCHEMA_VERSION;
/** Public tool id passed to `tools.execute`. */
toolId: string;
/** Provider responsible for the operation, or `null`. */
provider: string | null;
/** Provider operation name, or `null`. */
operation: string | null;
/** Stable machine-readable failure code, or `null`. */
code: string | null;
/** Boundary responsible for the failure. */
origin: ToolExecutionErrorOrigin;
/** Stable reason family. */
category: ToolExecutionErrorCategory;
/** Whether repeating the same semantic call is delivery-safe. */
retryable: boolean;
/** HTTP status when one exists, or `null`. */
statusCode: number | null;
/** Provider or Deepline request id, or `null`. */
requestId: string | null;
/** Suggested same-call retry delay in milliseconds, or `null`. */
retryAfterMs: number | null;
/** Network failure kind, or `null`. */
networkKind: ToolExecutionNetworkKind | null;
/** Network boundary that failed, or `null`. */
networkScope: ToolExecutionNetworkScope | null;
};
/**
* 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.
*
* @sdkReference errors 065
*/
type ToolExecutionErrorOptions = Omit & {
/**
* Local diagnostic context inherited from DeeplineError. This is not part of
* the portable failure payload and is intentionally omitted by serialization.
*/
details?: Record;
};
/**
* Provider-owned failure categories that may fall through to another read
* provider.
*
* @sdkReference errors 060
*/
type ProviderTransientErrorCategory = 'rate_limit' | 'network' | 'upstream';
/**
* 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.
*
* @sdkReference errors 010
*/
declare class DeeplineError extends Error {
/** HTTP status when the failure crossed an HTTP boundary. */
statusCode?: number;
/** Stable machine-readable error code when one exists. */
code?: string;
/** Local diagnostic context; not a portable error contract. */
details?: Record;
/**
* Construct a Deepline error.
*
* SDK and runtime code construct these errors. Application and Play code
* normally catches the public subclasses instead.
*
* @param message Human-readable failure summary.
* @param statusCode HTTP status when one exists.
* @param code Stable machine-readable code when one exists.
* @param details Local diagnostic context; never a portable error contract.
*/
constructor(message: string, statusCode?: number, code?: string, details?: Record);
static [Symbol.hasInstance](value: unknown): boolean;
}
/**
* 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.
*
* @sdkReference errors 070
*/
declare class ToolExecutionError extends DeeplineError {
/** Public tool id passed to `tools.execute`. */
readonly toolId: string;
/** Provider responsible for the operation, or `null` when unattributed. */
readonly provider: string | null;
/** Provider operation name, or `null` when unavailable. */
readonly operation: string | null;
/** Boundary responsible for the failure. */
readonly origin: ToolExecutionErrorOrigin;
/** Stable reason family for policy and diagnostics. */
readonly category: ToolExecutionErrorCategory;
/**
* Whether repeating the same semantic call is delivery-safe.
*
* This does not mean the error may be ignored. Waterfall fallthrough is
* represented by `ProviderTransientError`.
*/
readonly retryable: boolean;
/** Provider or Deepline request id, or `null` when unavailable. */
readonly requestId: string | null;
/** Suggested same-call retry delay in milliseconds, or `null`. */
readonly retryAfterMs: number | null;
/** Network failure kind, or `null` for non-network failures. */
readonly networkKind: ToolExecutionNetworkKind | null;
/** Network boundary that failed, or `null` for non-network failures. */
readonly networkScope: ToolExecutionNetworkScope | null;
/**
* 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.
*/
constructor(message: string, options: ToolExecutionErrorOptions);
static [Symbol.hasInstance](value: unknown): boolean;
}
/**
* 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`.
*
* @sdkReference errors 080
*/
declare class ProviderTransientError extends ToolExecutionError {
/** Provider attribution is guaranteed for this subtype. */
readonly origin: "provider";
/** Provider failure category that made this error eligible for fallthrough. */
readonly category: ProviderTransientErrorCategory;
/** Constructed by Deepline when a provider-owned transient failure arrives. */
constructor(message: string, options: Omit & {
category: ProviderTransientErrorCategory;
});
static [Symbol.hasInstance](value: unknown): boolean;
}
/** Why a provider cannot serve the current read request. */
type ProviderUnavailableReason = ProviderTransientErrorCategory | 'account_capacity' | 'credentials_missing';
/**
* A provider failure that permits a read waterfall to try its next provider.
* A missing provider connection is included because another provider may still
* serve the read. Invalid credentials, caller input, and Deepline billing
* failures remain loud.
*/
type ProviderUnavailableError = ProviderTransientError | (ToolExecutionError & {
readonly origin: 'provider';
readonly code: 'PROVIDER_ACCOUNT_CAPACITY';
}) | (ToolExecutionError & {
readonly origin: 'caller';
readonly code: 'INTEGRATION_CREDENTIALS_MISSING';
});
/**
* Return the provider-specific reason a read cannot run right now.
*
* `null` means this error must stay loud: it is caller input, an invalid
* customer credential, Deepline billing, or an internal failure. A missing
* provider connection is different: an explicit read waterfall may continue
* to a configured fallback and record the unavailable leg.
*/
declare function getProviderUnavailableReason(error: unknown): ProviderUnavailableReason | null;
/**
* Whether a provider cannot serve this read right now.
*
* Use this in an explicit `catch` to advance a read-only waterfall. For
* diagnostics, use `getProviderUnavailableReason(error)`.
*/
declare function isProviderUnavailable(error: unknown): error is ProviderUnavailableError;
/** @deprecated Use isProviderUnavailable. */
declare const isProviderWaterfallUnavailableError: typeof isProviderUnavailable;
declare const SUPPORTED_PLAY_AUTHORING_CONTRACT_EDITIONS: readonly [1, 2, 3, 4];
type PlayAuthoringContractEdition = (typeof SUPPORTED_PLAY_AUTHORING_CONTRACT_EDITIONS)[number];
type PlaySqlListenerOperation = 'INSERT' | 'UPDATE' | 'DELETE';
type PlayStandardWebhookHeaderFamily = 'standard' | 'svix';
type PlayStandardWebhookAuth = {
type: 'standard-webhooks';
/** `webhook-*` for Standard Webhooks, `svix-*` for Svix senders. */
headerFamily: PlayStandardWebhookHeaderFamily;
/** Deepline Secret names used for ordinary operation and rotation overlap. */
signingSecrets: string[];
/** Replay-protection window. Omitted means the Standard Webhooks 5-minute default. */
toleranceSeconds?: number;
};
type PlaySqlListenerFilterScalar = string | number | boolean | null;
type PlaySqlListenerFilterOperator = {
eq?: PlaySqlListenerFilterScalar;
neq?: PlaySqlListenerFilterScalar;
in?: PlaySqlListenerFilterScalar[];
notIn?: PlaySqlListenerFilterScalar[];
isNull?: true;
isNotNull?: true;
ilike?: string;
};
type PlaySqlListenerWhere = {
before?: Record;
after?: Record;
};
type PlaySqlListenerDeclaration = {
id: string;
tool: string;
stream: string;
operations?: PlaySqlListenerOperation[];
where?: PlaySqlListenerWhere;
};
type PlaySqlListenerEvent> = {
tool: string;
stream: string;
operation: PlaySqlListenerOperation;
before: T | null;
after: T | null;
changedAt: string;
metadata: {
outboxId: string;
listenerId: string;
table: string;
};
};
/** Internal AST Adapter shape. Invalid legacy fields exist only until admission rejects them. */
type PlayAuthoringAstSqlListenerDeclaration = {
id: string;
tool?: string;
stream?: string;
where?: unknown;
monitor?: string;
output?: string;
table?: `${string}.${string}` | string;
operations: string[];
};
type PlayAuthoringAstBindings = {
webhook?: {
hmac?: {
algorithm?: 'sha256';
header?: string;
secretEnv: string;
};
auth?: PlayStandardWebhookAuth;
};
cron?: {
schedule: string;
timezone?: string;
};
sqlListeners?: PlayAuthoringAstSqlListenerDeclaration[];
invalidSqlListenerSingular?: boolean;
invalidSqlListenerShape?: boolean;
secrets?: string[];
};
/** The one public type for options accepted by definePlay. */
type PlayAuthoringBindings = {
description?: string;
compatibility?: {
toolErrorSchemaVersion?: ToolExecutionErrorSchemaVersion;
/**
* Bump only when a Play's response transformation changes serialized tool
* output and requires fresh durable tool receipts.
*/
toolResponseReceiptRevision?: string;
};
inline?: boolean;
billing?: {
maxCreditsPerRun?: number;
};
/**
* Play-level sandbox settings. The default deadline is 30 minutes; set a
* static `timeout` such as `"90m"` or `"2h"` for a bounded batch, up to 4h.
* This is distinct from `ctx.tools.execute({ timeoutMs })`, which limits one
* provider-call transport rather than the whole Play.
*/
runtime?: {
timeout?: string;
size?: 'standard';
};
webhook?: {
hmac?: {
algorithm?: 'sha256';
header?: string;
secretEnv: string;
};
auth?: PlayStandardWebhookAuth;
};
cron?: {
schedule: string;
timezone?: string;
};
sqlListeners?: PlaySqlListenerDeclaration[];
secrets?: readonly string[];
};
/** The one public type for durable managed-tool calls. */
type PlayToolExecutionRequest = {
id: string;
tool: string;
input: Record;
description?: string;
force?: boolean;
staleAfterSeconds?: DurableCallStaleAfterSeconds;
timeoutMs?: PlayRuntimeTimeoutMs;
receiptWaitMs?: PlayReceiptWaitMs;
};
/** @deprecated Pass a SQL string directly to ctx.customerDb.query. */
type PlaySqlQuery = {
readonly kind: 'sql.query';
readonly text: string;
readonly values: readonly unknown[];
};
declare const PLAY_SECRET_HANDLE_BRAND: unique symbol;
declare const PLAY_SECRET_PROMISE_BRAND: unique symbol;
/**
* An opaque reference to a workspace secret used by legacy authoring-contract
* editions. New Plays receive plaintext strings from `ctx.secrets.get`.
*
* @sdkReference runtime 176 SecretHandle
*/
type PlaySecretHandle = {
readonly [PLAY_SECRET_HANDLE_BRAND]: never;
/** Name of the workspace secret, uppercased. Never its value. */
readonly name: string;
/** Renders `[secret:NAME]`, so an interpolated handle leaks nothing. */
toString(): string;
/** Always throws. A secret handle is deliberately not serializable. */
toJSON(): never;
};
/** A secret-reading promise returned only by `ctx.secrets.get`. */
type PlaySecretPromise = Promise & {
readonly [PLAY_SECRET_PROMISE_BRAND]: never;
};
/** An opaque legacy secret handle retained for earlier Play artifacts. */
type PlaySecretValue = PlaySecretHandle;
/**
* One resolved authentication scheme, built by `ctx.secrets.bearer` or `ctx.secrets.header` and attached to a request through `init.auth`.
*
* @sdkReference runtime 177 SecretAuth
*/
type PlaySecretAuth = {
/** `bearer` sends `Authorization: Bearer `; `header` sends a named header. */
readonly kind: 'bearer' | 'header';
/** The value whose bytes the runtime attaches. */
readonly secret: string | PlaySecretPromise | PlaySecretValue;
/** Header name, set only when `kind` is `header`. */
readonly header?: string;
};
/** One or more resolved authentication schemes for an outbound request. */
type PlaySecretAuthInput = PlaySecretAuth | readonly PlaySecretAuth[];
/**
* The `init` accepted by `ctx.fetch`. Same shape as `RequestInit` plus `auth`.
*
* @sdkReference runtime 174 SecretAwareRequestInit
*/
type PlaySecretAwareRequestInit = Omit & {
/** 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. */
headers?: HeadersInit;
/**
* 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 — for example, Supabase with both `apikey` and `Authorization`. Auth-helper requests require HTTPS and omit the credential from the durable receipt. Each auth entry must target a distinct header.
*/
auth?: PlaySecretAuthInput;
};
type PlayLooseObject = {
[key: string]: PlayLooseObject;
};
/** The one public return-object constraint for authored Plays. */
type PlayReturnObject = Record & {
readonly _metadata?: never;
};
/** The one public input-contract carrier for object-form Play definitions. */
type PlayAuthoringInputContract = {
readonly schema: Record;
readonly __inputType?: TInput;
};
/** Shared object-form `definePlay(config)` contract. */
type PlayAuthoringDefineConfig = {
id: string;
description?: string;
input: PlayAuthoringInputContract;
run: (ctx: TContext, input: TInput) => Promise;
bindings?: PlayAuthoringBindings;
billing?: PlayAuthoringBindings['billing'];
runtime?: PlayAuthoringBindings['runtime'];
compatibility?: PlayAuthoringBindings['compatibility'];
};
/** Shared callable-plus-handle shape returned by `definePlay`. */
type PlayAuthoringDefinedPlay = ((ctx: TContext, input: TInput) => Promise) & THandle & {
readonly bindings?: PlayAuthoringBindings;
readonly runtime?: PlayAuthoringBindings['runtime'];
readonly compatibility?: PlayAuthoringBindings['compatibility'];
readonly playName: string;
};
/** Canonical resolver shape for a customer-authored durable step. */
type PlayAuthoringStepResolver = (row: Row, ctx: TContext, index: number, previousCell?: PreviousCell) => Value | Promise;
type PlayAuthoringDatasetColumnRunInput = {
/** Current row, including previously computed columns. */
readonly row: Row;
/** Runtime context for tool, Play, fetch, and log calls. */
readonly ctx: TContext;
/** Zero-based row index for this dataset run. */
readonly index: number;
/** Prior stored cell value and freshness metadata when this cell reruns. */
readonly previousCell?: PreviousCell;
};
type PlayAuthoringDatasetColumnDefinition = {
/** Compute one cell value. Receives the previous stored value when rerunning. */
readonly run: (input: PlayAuthoringDatasetColumnRunInput) => Value | Promise;
/** Optional row-level gate. Skipped rows produce `null` for this column. */
readonly runIf?: (row: Row, index: number) => boolean | Promise;
};
type PlayAuthoringConditionalStepResolver = {
readonly kind: 'conditional';
readonly when: (row: Row, index: number) => boolean | Promise;
readonly run: PlayAuthoringStepResolver;
readonly elseValue: Else;
else(value: ValueElse): PlayAuthoringConditionalStepResolver;
};
type PlayAuthoringStepOptions = {
/** Optional row-level gate. Skipped rows produce `null` for this column. */
readonly runIf?: (row: Row, index: number) => boolean | Promise;
/** Legacy dataset-column flag. Prefer freshness on the reusable call. */
readonly recompute?: boolean;
/** Legacy error-recompute flag accepted for older authored Plays. */
readonly recomputeOnError?: boolean;
/** Legacy cell staleness metadata accepted for older authored Plays. */
readonly staleAfterSeconds?: number;
};
/** Explicitly mark a step program as a provider fallback waterfall. */
type PlayAuthoringStepProgramOptions = {
readonly continueOnProviderUnavailable?: boolean;
};
type PlayAuthoringStepProgram = {
readonly kind: 'steps';
readonly steps: readonly PlayAuthoringStepProgramStep[];
readonly returnResolver?: PlayAuthoringStepResolver