/// import { e as PlayRuntimeBackendId, c as PlayCompilerManifest, D as DeeplineError, f as ToolExecutionError, g as ToolExecutionErrorOptions, h as PlayAuthoringColumnMap, i as PlayAuthoringColumnResolver, j as PlayAuthoringRuntimeContext, k as PlayAuthoringConditionalStepResolver, l as PlayAuthoringCsvInput, m as PlayAuthoringCsvOptions, n as PlayAuthoringDatasetBuilder, o as PlayAuthoringDatasetColumnDefinition, p as PlayAuthoringDatasetColumnRunInput, q as ToolExecuteResult, r as PlayAuthoringReferenceLike, s as PlayReturnObject$1, t as PlayAuthoringDefineConfig, u as PlayAuthoringDefinedPlay, v as PlayAuthoringFetchOptions, w as PlayAuthoringFileInput, x as PlayAuthoringBindings, y as PlayAuthoringCallExecution, z as PlayAuthoringCallOptions, A as PlayAuthoringFetchResponse, B as PlayAuthoringInputContract, C as PlayAuthoringStepProgramStep, E as PlayAuthoringRuntimeStepOptions, F as PlaySqlListenerDeclaration, G as PlaySqlListenerEvent, H as PlaySqlListenerOperation, I as PlaySqlQuery, J as PlayAuthoringStepOptions, K as PlayAuthoringStepProgram, L as PlayAuthoringStepProgramResolver, M as PlayAuthoringStepResolver, N as PlayToolExecutionRequest, O as PlayAuthoringStepProgramOptions } from './compiler-manifest-DwYe2C2S.mjs'; export { Q as DEEPLINE_EXTRACTOR_TARGETS, R as DEEPLINE_EXTRACTOR_TARGET_DEFINITIONS, S as DeeplineEmailStatusGetterValue, U as DeeplineExtractorTarget, V as DeeplineGetterValue, W as DeeplineGetterValueMap, X as JOB_CHANGE_STATUS_VALUES, Y as JobChangeStatus, Z as PHONE_STATUS_VALUES, _ as PhoneStatus, $ as PlayDataset, a0 as PlayDatasetInput, a1 as PreviousCell, a2 as ProviderTransientError, a3 as ProviderTransientErrorCategory, a4 as ProviderUnavailableError, a5 as ProviderUnavailableReason, a6 as ToolExecutionErrorCategory, a7 as ToolExecutionErrorOrigin, a8 as ToolExecutionFailureV1, a9 as ToolExecutionNetworkKind, aa as ToolExecutionNetworkScope, ab as getProviderUnavailableReason, ac as isDeeplineExtractorTarget, ad as isProviderUnavailable, ae as isProviderWaterfallUnavailableError } from './compiler-manifest-DwYe2C2S.mjs'; import '@sinclair/typebox'; declare const FIXTURE_BEHAVIOR_VERSION: 1; declare const FIXTURE_BEHAVIOR_RESPONSE_VERSION: 2; declare const FIXTURE_BEHAVIOR_REPLAY_VERSION: 3; type FixtureBehaviorV1 = { version: typeof FIXTURE_BEHAVIOR_VERSION; responseDelaySamplesMs: number[]; }; type FixtureResponseSample = { delayMs: number; when?: { provider?: string; operation?: string; }; httpError?: { status: number; message: string; }; }; type FixtureBehaviorV2 = { version: typeof FIXTURE_BEHAVIOR_RESPONSE_VERSION; responseSamples: FixtureResponseSample[]; }; type FixtureReplayBundle = { bundleId: string; manifestSha256: string; syntheticFallbackToolIds?: string[]; }; type FixtureBehaviorV3 = { version: typeof FIXTURE_BEHAVIOR_REPLAY_VERSION; responseSamples: FixtureResponseSample[]; replayBundle: FixtureReplayBundle; }; type FixtureBehavior = FixtureBehaviorV1 | FixtureBehaviorV2 | FixtureBehaviorV3; type PlayRuntimeSelection = { environment: 'preview'; /** Caller-named isolation scope inside a remote runtime environment. */ namespace: string; /** Explicit managed-sandbox executor. Omission preserves Daytona compatibility. */ backend?: Extract; }; /** * Canonical, producer-facing description of what a play is doing. * * Producers report facts. They do not choose log copy, UI placement, polling * intervals, or whether a run is "healthy". The activity router and projector * own those decisions centrally. */ type PlayActivityTarget = { kind: 'provider'; provider: string; operation: string; label?: string; } | { kind: 'dataset'; tableNamespace: string; operation: 'materializing' | 'persisting' | 'indexing' | 'reading'; label?: string; } | { kind: 'lease'; resourceKind: 'run' | 'dataset' | 'row' | 'runner'; resourceLabel: string; } | { kind: 'runner'; backend: string; label?: string; } | { kind: 'step'; stepId: string; label?: string; } | { kind: 'capacity'; pool: 'worker' | 'provider' | 'dataset' | 'runner'; label?: string; }; type PlayActivityProgress = { completed?: number; total?: number; failed?: number; message?: string; }; type PlayActivityState = { kind: 'active'; progress?: PlayActivityProgress; } | { kind: 'queued'; reason: 'capacity'; } | { kind: 'waiting'; reason: { kind: 'external_event'; provider?: string; eventKey?: string; remaining?: number; deadlineAt?: number; } | { kind: 'dataset'; tableNamespace: string; requiredPhase: 'available' | 'persisted' | 'indexed'; } | { kind: 'lease'; resourceKind: 'run' | 'dataset' | 'row' | 'runner'; resourceLabel: string; expiresAt?: number; } | { /** Mixed-version fallback only; new producers must choose a typed reason. */ kind: 'unknown'; }; } | { kind: 'retrying'; reason: 'rate_limit' | 'provider_error' | 'transport_error'; retryAt: number; attempt?: number; } | { kind: 'scheduled'; reason: 'sleep'; resumeAt: number; } | { kind: 'completed'; } | { kind: 'failed'; code?: string; }; type PlayActivityObservation = { schemaVersion: 1; /** Stable within one run, for example `tool:discover_ctos` or `dataset:leads`. */ activityId: string; /** Optional owning play step. */ stepId?: string; target: PlayActivityTarget; state: PlayActivityState; /** Producer clock. The runtime envelope supplies run identity and ordering. */ observedAt: number; }; type PlayRunActivityProjection = { observation: PlayActivityObservation; summary: string; visibility: PlayActivityVisibility; /** False only when old payloads lacked enough typed facts to classify. */ classified: boolean; }; type PlayActivityVisibility = 'hidden' | 'timeline' | 'headline' | 'action'; declare const DEEPLINE_TOOL_CATEGORIES: readonly ["company_search", "people_search", "people_enrich", "email_finder", "email_verify", "phone_finder", "phone_verify", "identity_resolution", "reverse_lookup", "enrichment", "batch", "premium", "free"]; type DeeplineToolCategory = (typeof DEEPLINE_TOOL_CATEGORIES)[number] | (string & {}); declare const PLAY_BOOTSTRAP_TEMPLATES: readonly ["people-list", "company-list", "people-email", "people-phone", "company-people", "company-people-email", "company-people-phone"]; type PlayBootstrapTemplate = (typeof PLAY_BOOTSTRAP_TEMPLATES)[number]; declare const PLAY_BOOTSTRAP_SOURCE_KINDS: readonly ["csv", "play", "provider", "providers"]; declare const PLAY_BOOTSTRAP_STAGE_KINDS: readonly ["play", "provider", "providers"]; declare const PLAY_BOOTSTRAP_FINDER_KINDS: readonly ["email_finder", "phone_finder"]; type PlayBootstrapFinderKind = (typeof PLAY_BOOTSTRAP_FINDER_KINDS)[number]; type PlayBootstrapEntityKind = 'company' | 'contact' | 'email' | 'phone' | 'unknown'; declare const PLAY_BOOTSTRAP_COMPANY_PROVIDER_CATEGORY: "company_search"; declare const PLAY_BOOTSTRAP_PEOPLE_PROVIDER_CATEGORY: "people_search"; declare const PLAY_BOOTSTRAP_PROVIDER_CATEGORY_BY_FINDER: { readonly email_finder: "email_finder"; readonly phone_finder: "phone_finder"; }; declare const PLAY_BOOTSTRAP_OUTPUT_FIELD_BY_FINDER: { readonly email_finder: "email"; readonly phone_finder: "phone"; }; declare const PLAY_BOOTSTRAP_CONTACT_FIELDS: readonly ["first_name", "last_name", "domain", "company_name", "linkedin_url", "title", "email", "phone"]; declare const PLAY_BOOTSTRAP_COMPANY_FIELDS: readonly ["domain", "company_domain", "company_name", "linkedin_url", "website"]; declare function isPlayBootstrapFinderKind(value: string): value is PlayBootstrapFinderKind; declare function isPlayBootstrapTemplate(value: string): value is PlayBootstrapTemplate; declare function formatPlayBootstrapFinderKinds(): string; declare function formatPlayBootstrapTemplates(): string; declare function formatPlayBootstrapFinderKindsForSentence(): string; /** * Options for constructing a {@link DeeplineClient} or connecting via {@link Deepline.connect}. * * All fields are optional — the SDK resolves missing values from environment * variables and CLI-managed config files. See {@link resolveConfig} for the * full resolution order. * * @example * ```typescript * import { DeeplineClient } from 'deepline'; * * // Minimal — uses env vars / CLI config automatically: * const client = new DeeplineClient(); * * // Explicit overrides: * const client2 = new DeeplineClient({ * apiKey: 'dl_test_...', * baseUrl: 'http://localhost:3000', * timeout: 30_000, * maxRetries: 5, * }); * ``` */ interface DeeplineClientOptions { /** API key. Overrides `DEEPLINE_API_KEY` env var and CLI-stored keys. */ apiKey?: string; /** Base URL of the Deepline API. Overrides `DEEPLINE_HOST_URL`. */ baseUrl?: string; /** Per-request timeout in milliseconds. Default: `60_000` (60 seconds). */ timeout?: number; /** Maximum retry attempts for transient failures (network errors, 429s). Default: `3`. */ maxRetries?: number; } /** * Fully resolved configuration used internally by the SDK. * * Produced by {@link resolveConfig} — all fields are guaranteed non-empty. */ interface ResolvedConfig { /** Validated API key (non-empty string). */ apiKey: string; /** Normalized base URL (trailing slash stripped). */ baseUrl: string; /** Request timeout in milliseconds. */ timeout: number; /** Max retry count for transient failures. */ maxRetries: number; } /** Column metadata returned by a customer data query. */ interface CustomerDbColumn { /** Column name as returned by the database. */ name: string; /** Internal table identifier when available. */ table_id: number | null; /** Internal data-type identifier when available. */ data_type_id: number | null; } /** * Result returned by {@link DeeplineClient.db.query}. * * Rows are intentionally untyped because the schema depends on the caller's SQL * query and selected customer tables. */ interface CustomerDbQueryResult { /** This query reads the current mutable customer database, not one run snapshot. */ scope?: { kind: 'database'; mutability: 'current'; }; /** Database command executed by the query endpoint. */ command: string; /** Total affected row count when reported by the database. */ row_count: number | null; /** Number of rows included in this response. */ row_count_returned: number; /** Whether server-side row limits truncated the result. */ truncated: boolean; /** Column metadata for the returned rows. */ columns: CustomerDbColumn[]; /** Result rows. */ rows: unknown[]; } interface ToolPricingSummary { /** User-facing pricing text for quick discovery displays. */ displayText: string | null; /** User-facing unit the price applies to. */ unit: 'call' | 'result' | 'page' | 'usage' | null; /** Deepline credits charged per unit, when statically knowable. */ creditsPerUnit: number | null; /** USD equivalent charged per unit, when statically knowable. */ usdPerUnit: number | null; /** Currency for `usdPerUnit`. */ currency: 'USD'; /** Short user-facing pricing summary for variable pricing. */ summary: string | null; /** Additional user-facing pricing notes. */ details: string[]; } /** A discoverable provider, returned by {@link DeeplineClient.listProviders}. */ interface ProviderDefinition { provider: string; displayName: string; toolCount: number; categories: string[]; /** Present for providers in the recent-additions ledger. */ version?: string; /** ISO-8601 date on which this provider was added. */ releasedAt?: string; } /** * Summary definition of a callable provider-backed tool. * * Returned by {@link DeeplineClient.listTools} and ranked tool search. Use * `getTool(toolId)` or the matching HTTP describe route for provider-specific * schema, examples, pricing, and extraction guidance before executing. */ interface ToolDefinition { /** Unique tool identifier used in API calls (e.g. `"dropleads_search_people"`). */ toolId: string; /** Provider that backs this tool (e.g. `"hunter"`, `"dropleads"`, `"test"`). */ provider: string; /** Human-readable name for display. */ displayName: string; /** What this tool does — suitable for LLM tool descriptions. */ description: string; /** Categorization tags (e.g. `["people", "enrichment"]`). */ categories: DeeplineToolCategory[]; /** Searchable provider and account-signal tags. */ tags?: string[]; /** Operation slug within the provider. */ operation?: string; /** Normalized operation identifier. */ operationId?: string; /** Alternative names that resolve to this tool. */ operationAliases?: string[]; /** Explicit globally runnable play reference for play-backed catalog entries. */ playReference?: `prebuilt/${string}`; /** Whether detailed input schema is available from `tools describe`. */ hasInputSchema?: boolean; /** Whether detailed output schema is available from `tools describe`. */ hasOutputSchema?: boolean; /** JSON Schema describing the tool's input parameters. */ inputSchema?: Record; /** JSON Schema describing the tool's output shape. */ outputSchema?: Record; /** User-facing pricing summary. Internal provider/settlement costs are intentionally omitted. */ pricing?: ToolPricingSummary | null; /** Copyable play-runtime guidance for V2 tool execution results. */ usageGuidance?: { execute?: string; prefer?: string[]; access?: { extractedLists?: { expression?: string; meaning?: string; }; extractedValues?: { expression?: string; meaning?: string; }; rawToolResponse?: { expression?: string; meaning?: string; }; canonicalToolResponse?: { expression?: string; meaning?: string; }; invalidGetterHint?: string; }; toolExecutionResult?: { type?: 'ToolExecutionResult'; toolResponse?: { raw?: string; rawV2?: string; view?: string; responseMeta?: string; meta?: string; }; meta?: string; extractedLists?: Array<{ name: string; expression: string; details?: { strategy?: string; rawToolOutputPaths?: string[]; candidatePaths?: string[]; }; }> | Record; extractedValues?: Array<{ name: string; expression: string; details?: { strategy?: string; rawToolOutputPaths?: string[]; candidatePaths?: string[]; }; }> | Record; [key: string]: unknown; }; }; /** Search relevance score returned by ranked tool search. */ search_score?: number; /** Search match snippets returned by ranked tool search. */ search_matches?: Array<{ field: string; value: string; term?: string; }>; /** * Whether this tool is callable in the current workspace. `false` for a * bring-your-own-credential provider that has not been connected. */ connected?: boolean; /** Whether the tool can be executed. Exact lookup may return non-callable deprecated aliases. */ callable?: boolean; /** True when callers should migrate this exact tool id to its replacement. */ deprecated?: boolean; /** Deprecation reason, replacement, and compatibility execution behavior. */ deprecation?: { replacementToolId: string; message: string; execution?: 'terminal' | 'forward'; }; /** * Connection status for discovery: `managed` (Deepline-run credentials), * `connected` (your own credential is connected), or `requires_connection` * (BYO provider not yet connected in this workspace). `deprecated` means * connecting credentials will not make the tool callable. */ credentialStatus?: 'managed' | 'connected' | 'requires_connection' | 'deprecated'; /** True when the tool requires a customer-provided credential to run. */ requiresOwnCredential?: boolean; /** Actionable message shown when a connection is required. */ connectionMessage?: string; } interface ModelProviderOptionField { name: string; type: 'string' | 'number' | 'boolean' | 'object' | 'array'; enumValues?: string[]; description: string; caveat?: string; } interface ModelProviderOptionNamespace { provider: string; sourcePackage: string; sourceSymbol: string; fields: ModelProviderOptionField[]; } interface DeeplineAgentModelDescription { schemaVersion: 1; model: string; provider: string; modelMetadata: Record | null; providerOptions: { gateway: ModelProviderOptionNamespace; selectedProvider?: ModelProviderOptionNamespace; }; exampleInput: { model: string; providerOptions: Record; }; caveats: string[]; sources: string[]; inferencePricing: InferenceDynamicPricingCapability; } interface InferenceDynamicPricingCapability { settlement: 'actual_usage'; staticUnitPrice: null; quoteEndpointTemplate: string; supportedQualities: Array<'bounded_max' | 'estimate_only' | 'unavailable'>; payloadFields: string[]; } type InferenceQuoteAssumptions = { modelCallCount: number; planningModelCallCount: number; estimatedInputTokens: number; estimatedOutputTokens: number; maxOutputTokens: number | null; candidateRouteCount: number; pricedRouteCount: number; inputBound: 'proven_request_tokens' | 'catalog_context' | 'not_proven'; inputBoundProofId?: string; }; type InferenceQuote = { quality: 'bounded_max' | 'estimate_only' | 'unavailable'; estimate: { quality: 'estimate_only'; credits: number; assumptions: InferenceQuoteAssumptions; } | { quality: 'unavailable'; assumptions: InferenceQuoteAssumptions; }; authorization: { quality: 'bounded_max'; maximumCredits: number; assumptions: InferenceQuoteAssumptions; } | { quality: 'estimate_only' | 'unavailable'; assumptions: InferenceQuoteAssumptions; }; settlement: 'actual_usage'; }; /** * Query options for ranked tool/provider discovery. */ interface ToolSearchOptions { /** Free-text search query. */ query?: string; /** Comma-separated category filter such as `company_search` or `email_finder`. */ categories?: string; /** Optional explicit search terms used by agent/CLI callers. */ searchTerms?: string; /** Search algorithm/version. Defaults to the current ranked mode. */ searchMode?: 'v1' | 'v2'; /** Include backend debug metadata in the search response. */ includeSearchDebug?: boolean; } /** * Ranked tool/provider discovery response. * * Includes matching tools plus render/action hints used by the CLI and agents. */ interface ToolSearchResult { /** Ranked matching tools. */ tools: ToolDefinition[]; /** Count included in this response when available. */ count?: number; /** Total available count when the backend reports it. */ total?: number; /** Whether results were truncated by server-side limits. */ truncated?: boolean; /** Echoed query. */ query?: string; /** Parsed category filters. */ categories?: string[]; /** Parsed search terms. */ search_terms?: string[]; /** Search mode used. */ search_mode?: 'v1' | 'v2'; /** Whether search fell back to category matching. */ search_fallback_to_category?: boolean; /** Explanation and next commands when filters/search succeed but match zero tools. */ emptyResult?: { reason: string; message: string; suggestions: Array<{ label: string; command: string; }>; }; /** Hint explaining omitted play results when searching tools only. */ omitted_plays_hint?: string; /** Copyable CLI command templates for follow-up discovery/execution. */ commandTemplates?: { describe?: string; execute?: string; }; /** Pre-rendered sections and actions for CLI/agent display. */ render?: { sections?: Array<{ title: string; lines: string[]; }>; actions?: Array<{ label: string; command: string; }>; }; } /** * Extended tool metadata including pricing, samples, and failure modes. * * Returned by {@link DeeplineClient.getTool}. Extends {@link ToolDefinition} * with operational details needed for cost estimation and debugging. * * @example * ```typescript * const meta = await client.getTool('dropleads_search_people'); * console.log(meta.displayName); // "DropLeads People Search" * console.log(meta.estimatedCreditsRange); // "1-5" * console.log(meta.samples); // { input: {...}, output: {...} } * ``` */ interface ToolMetadata extends ToolDefinition { /** Related async polling action, if this tool supports async execution. */ asyncGetAction?: string | null; /** Async job lifecycle: this tool starts it, then polling may lead to final rows. */ asyncFlow?: { startAction: string; pollActions: string[]; finishAction?: string | null; } | null; /** Known failure scenarios and their expected handling. */ failureMode?: Record | null; /** Sanitized pricing model for describe metadata. Provider internal prices are intentionally omitted. */ cost?: Record | null; /** Deepline credits charged for one user-visible pricing unit. */ deeplineCreditsPerPricingUnit?: number | null; /** Whether the customer pays with Deepline credits or their own connected account. */ billingSource?: string; /** Display label for the billing source. */ billingSourceLabel?: string; /** Play expansion config if this tool auto-expands in plays. */ playExpansion?: Record; /** Estimated credit range for a single call (e.g. `"1-5"`). */ estimatedCreditsRange?: string; /** Version of the cost estimation model used. */ estimateModelVersion?: string; /** Tools whose costs were used to build this estimate. */ estimateBasedOnTools?: string[]; /** Individual step cost contributions (for composite tools). */ stepContributions?: unknown[]; /** Example input/output pairs for documentation and testing. */ samples?: Record; } /** * Final result of a play execution, returned by {@link DeeplineClient.runPlay}. * * @example * ```typescript * const result = await client.runPlay(code, null, 'my-play'); * if (result.success) { * console.log('Run package:', result.result); * console.log(`Completed in ${result.durationMs}ms`); * } else { * console.error('Failed:', result.error); * console.log('Logs:', result.logs.join('\n')); * } * ``` */ interface PlayRunResult { /** `true` if the play completed successfully (`status === 'completed'`). */ success: boolean; /** Public play-run identifier. */ runId: string; /** Canonical run package for current play runs; legacy clients may receive a raw result. */ result?: unknown; /** Canonical compact run package when returned by the server. */ package?: PlayRunPackage; /** All log lines emitted via `ctx.log()` during execution. */ logs: string[]; /** Wall-clock duration from submission to completion, in milliseconds. */ durationMs: number; /** Error message if the play failed, was cancelled, or timed out. */ error?: string; } /** * Progress snapshot from a running play, nested inside {@link PlayStatus}. */ interface PlayProgressStatus { /** Human-readable description of the current step. */ status: string; /** Total row count for row-based processing (e.g. CSV enrichment). */ totalRows?: number; /** Accumulated log lines from `ctx.log()`. Grows monotonically. */ logs: string[]; /** Error message if the play has failed. */ error?: string; } type PlayRunActionPackage = { kind: 'deepline_run_inspect'; runId: string; command?: string; api: { method: 'GET'; path: string; }; } | { kind: 'deepline_run_full'; runId: string; command?: string; api: { method: 'GET'; path: string; }; } | { kind: 'deepline_run_billing'; runId: string; command?: string; api: { method: 'GET'; path: string; }; } | { kind: 'deepline_db_query'; datasetPath: string; tableNamespace?: string; sqlTableName?: string; sqlQualifiedTableName?: string; sql: string; maxRows: number; command?: string; scope?: { kind: 'database'; mutability: 'current'; } | { kind: 'run'; runId: string; }; note?: string; deprecated?: { replacement: 'queryCurrentTable'; removeAfter: string; reason: string; }; api: { method: 'POST'; path: '/api/v2/db/query'; }; } | { kind: 'deepline_run_export'; runId: string; datasetPath: string; format: 'csv'; command?: string; scope?: { kind: 'run'; runId: string; }; note?: string; deprecated?: { replacement: 'datasets[].actions.exportCsv'; removeAfter: string; reason: string; }; } | { kind: 'deepline_run_logs'; runId: string; view: 'failed' | 'tail'; limit: number; command: string; api: { method: 'GET'; path: string; }; }; type PlayRunDbQueryAction = Extract; type PlayRunExportAction = Extract; type PlayRunDatasetActions = { /** @deprecated Use queryCurrentTable or exportCsv. Removed after 2026-08-18. */ query?: PlayRunDbQueryAction & { scope?: { kind: 'run'; runId: string; }; }; queryCurrentTable?: PlayRunDbQueryAction & { scope?: { kind: 'database'; mutability: 'current'; }; }; exportCsv?: PlayRunExportAction & { scope?: { kind: 'run'; runId: string; }; }; }; /** * Compact canonical package for an inspected play run. * * This object is designed for SDK/CLI/API consumers that need stable run * metadata, output handles, and follow-up actions without reading dashboard * internals. */ interface PlayRunPackage { /** Package schema version. */ schemaVersion: 1; /** Package discriminator. */ kind: 'play_run'; /** Run identity, status, timing, and dashboard metadata. */ run: { id: string; playName: string; status: string; dashboardUrl?: string; updatedAt?: number | null; startedAt?: number | null; finishedAt?: number | null; durationMs?: number | null; error?: string; /** Canonical explanation of what this run is doing or waiting on. */ activity?: PlayRunActivityProjection | null; }; /** Bounded customer-safe warnings about output projection or availability. */ warnings?: string[]; /** Step-level summaries emitted by the runtime. */ steps: Array>; /** Named output summaries, including dataset handles and scalar outputs. */ outputs: Record>; /** Every durable Dataset Handle explicitly registered by this run. */ datasets?: Array<{ kind: 'dataset'; datasetId?: string; path: string; tableNamespace?: string; rowCount?: number; sqlTableName?: string; sqlQualifiedTableName?: string; recovered?: true; exportUnavailable?: { reason: 'empty_dataset' | 'shared_table_namespace'; message: string; }; preview?: Record; actions?: PlayRunDatasetActions; }>; /** Small retained tail of customer and runtime logs; fetch the full stream through `runs.logs`. */ logs?: { tail: string[]; totalCount: number; returnedCount: number; truncated?: boolean; }; /** Follow-up actions a caller can perform against the run. */ next?: { inspect?: PlayRunActionPackage; full?: PlayRunActionPackage; billing?: PlayRunActionPackage; export?: PlayRunActionPackage; query?: PlayRunActionPackage; logs?: PlayRunActionPackage; }; } /** * Current status of a play execution, returned by {@link DeeplineClient.getPlayStatus}. * * Poll this until `status` reaches a terminal state: * `'completed'` | `'failed'` | `'cancelled'`. * * @example * ```typescript * const status = await client.getPlayStatus(runId); * if (status.status === 'completed') { * console.log('Done:', status.result); * } else if (status.status === 'running' || status.status === 'waiting') { * console.log('Logs so far:', status.progress?.logs); * } * ``` */ interface PlayStatus { /** Public play-run identifier. */ runId: string; /** Public Deepline play-run API version. */ apiVersion?: number; /** Saved play name for this run, when available. */ name?: string; /** Exact saved revision launched for this run, when applicable. */ revisionId?: string; /** Alias for `name` used by run/result APIs. */ playName?: string; /** Dashboard URL for inspecting the play and its run output in the app. */ dashboardUrl?: string; /** Product-level play-run state. */ status: 'queued' | 'running' | 'waiting' | 'completed' | 'failed' | 'cancelled'; /** Execution progress with logs and error details. */ progress?: PlayProgressStatus; /** Partial or final result. Available once the play returns. */ result?: unknown; /** Compact typed run package returned by current run status endpoints. */ package?: PlayRunPackage; /** Compact typed output summaries, mirrored from the run package when present. */ outputs?: PlayRunPackage['outputs']; /** Scheduler-backed run metadata when returned by the status endpoint. */ run?: { id?: string; startTime?: string | null; closeTime?: string | null; [key: string]: unknown; } | null; /** Server-rendered result view metadata for CLI/UI summaries. */ resultView?: unknown; /** Canonical run contract snapshot metadata, when available. */ contract?: Record | null; /** If the run is blocked on a durable boundary, expose the public wait state. */ wait?: { kind: 'integration_event' | 'sleep'; boundaryId?: string; eventKey?: string; until?: number; } | null; /** Structured follow-up actions for inspect/query/export. */ next?: PlayRunPackage['next'] | Record; /** Bounded terminal-failure log window requested by `runs.get`. */ failedLogs?: { runId: string; totalCount: number; returnedCount: number; firstSequence: number | null; lastSequence: number | null; truncated: boolean; hasMore: boolean; entries: string[]; view?: 'failed'; association?: 'terminal_failure_window' | 'retained_before_truncation'; warning?: string; next?: { logs: string; }; logsTruncated?: boolean; }; /** Exact ordinary `plays run` command that can rerun a failed execution. */ rerunCommand?: string; /** * Projected settled-charge billing for the run. Returned by `runs.get`. * `totalCredits`/`providerEvents` describe THIS run only; `rollup` (present * with `--full`) carries the true subtree cost including ctx.runPlay children. * Deepline credits only — provider spend is never exposed. */ billing?: RunBillingSummary; /** * True subtree cost in Deepline credits (this run + every descendant run), * mirrored to the top level for convenience. Present only with `--full`. */ billingTotalCreditsRollup?: number; /** Deepline credits attributable to descendant runs only. Present with `--full`. */ billingChildCredits?: number; /** True when the child-run billing rollup could not be fully resolved. */ billingRollupIncomplete?: boolean; /** Durable summaries of ctx.runPlay children, returned by `runs.get --full`. */ childRuns?: ChildRunSummary[]; } /** One ctx.runPlay child run exposed on the parent's `--full` payload. */ interface ChildRunSummary { runId: string; playName?: string | null; status: string; parentRunId?: string | null; rootRunId?: string | null; createdAt?: number | null; startedAt?: number | null; finishedAt?: number | null; } /** * Rolled-up billing for a run subtree, projected from settled Charge Lifecycle * facts. Deepline credits only — never provider spend. */ interface RunBillingSummary { runId: string; /** THIS run's own charges (parent-only; excludes descendant runs). */ totalCalls: number; totalCredits: number; providerEvents: number; computeEvents: number; /** Subtree rollup including descendant ctx.runPlay runs. Present with `--full`. */ rollup?: { totalCreditsRollup: number; childCredits: number; ownCredits: number; totalCallsRollup: number; providerEventsRollup: number; computeEventsRollup: number; childProviderEvents: number; childComputeEvents: number; descendantRunCount: number; rollupComplete: boolean; rollupError?: string; }; [key: string]: unknown; } type LiveEventScope = 'play' | 'agent'; interface LiveEventEnvelope { cursor: string; streamId: string; scope: LiveEventScope; type: string; at: string; payload: TPayload; } type PlayLiveEvent = LiveEventEnvelope & { scope: 'play'; }; /** * Result returned by {@link DeeplineClient.stopPlay}. */ interface StopPlayRunResult { /** Public play-run identifier the stop request targeted. */ runId: string; /** Whether the server confirmed the run was stopped. */ stopped: boolean; /** Number of open HITL interactions marked cancelled. */ hitlCancelledCount: number; /** * True when the scheduler state for the run was stale and the stop could * not be confirmed. Absent on older servers (treated as confirmed). */ staleSchedulerState?: boolean; /** Server-side error detail when the stop was not confirmed. */ error?: string; } interface StopAllPlayRunsResult { stopped: number; failed: number; skipped: number; partial?: boolean; runs: Array; } /** * Summary of a single play run, returned by {@link DeeplineClient.listPlayRuns}. */ interface PlayRunListItem { /** Public Deepline play-run id. */ workflowId: string; /** Saved play name for this run, when available. */ playName?: string | null; /** Backend run attempt id, when exposed. */ runId: string; /** Parent play-run id when this run was launched through ctx.runPlay. */ parentRunId?: string | null; /** Root play-run id for nested ctx.runPlay descendants. */ rootRunId?: string | null; /** Workflow type (typically `'Workflow'`). */ type: string; /** Human-readable status (e.g. `'Completed'`, `'Failed'`). */ status: string; /** ISO 8601 timestamp when the run started. */ startTime?: string | null; /** Unix epoch milliseconds when the run started, returned by normalized V2 run summaries. */ startedAt?: number | string | null; /** ISO 8601 timestamp when the run finished. */ closeTime?: string | null; /** Unix epoch milliseconds when the run finished, returned by normalized V2 run summaries. */ finishedAt?: number | string | null; /** Duration string (e.g. `'2.5s'`). */ executionTime: string | null; /** Total Deepline credits charged for the run, when available. */ billingTotalCredits?: number; /** Configured per-run Deepline credit cap, when available. */ billingMaxCreditsPerRun?: number | null; /** Metadata attached to the workflow. */ memo: { /** Organization that owns this run. */ orgId: string; /** Play name. */ playName: string; /** User who triggered the run, if known. */ userId: string | null; }; } /** * A single revision (version) of a play's code and configuration. */ interface PlayRevisionSummary { /** Convex revision document ID used for exact-version runs and live promotion. */ _id?: string; /** Monotonically increasing version number. */ version: number; /** R2 storage reference for the bundled code artifact. */ artifactStorageKey?: string | null; /** Immutable artifact hash for the revision. */ artifactHash?: string | null; /** Static dependency graph hash for the revision. */ graphHash?: string | null; /** Hash of the original source file. */ sourceHash?: string | null; /** Original TypeScript source code. */ sourceCode?: string | null; /** Primary key column for CSV-based plays. */ tableNamespace?: string | null; /** Static pipeline definition (for declarative plays). */ staticPipeline?: unknown; /** Extracted binding metadata. */ bindings?: unknown; /** Human-readable description of this revision. */ description?: string | null; /** Unix timestamp (ms) when this revision was created. */ createdAt?: number; /** Unix timestamp (ms) of last update. */ updatedAt?: number; /** True when this is the revision currently serving live triggers. */ isLive?: boolean; /** True when this is the newest saved working revision. */ isWorking?: boolean; } /** * Aggregate row-processing stats for a play's sheet. */ interface PlaySheetStats { total: number; queued: number; running: number; completed: number; failed: number; stale: number; } /** * Per-column processing stats within a play's sheet. */ interface PlaySheetColumnStats { queued: number; running: number; completed: number; failed: number; cached: number; missed: number; skipped: number; } /** * Summary of a play's data sheet state. */ interface PlaySheetSummary { /** Aggregate stats across all rows. */ stats: PlaySheetStats; /** Per-column breakdown of processing state. */ columns: Record; } /** * Full play definition with revision history and run stats. * * Returned by {@link DeeplineClient.getPlay}. */ interface PlayDefinitionDetail { /** Convex document ID. */ _id: string; /** Stable registry key. */ playKey?: string; /** Canonical owner-qualified play reference. */ reference?: string; /** Play name (unique within an org). */ name: string; /** Human-friendly display name for UI surfaces. */ displayName?: string; /** Whether this Play sorts before unpinned Plays. */ pinned?: boolean; /** Canonical categories declared by tools used in this Play. */ toolCategories?: string[]; /** Whether this entry comes from the Deepline prebuilt registry or the org-owned catalog. */ origin?: 'prebuilt' | 'owned'; /** Ownership class used for permissions and badges. */ ownerType?: 'deepline' | 'org'; /** Slug of the owning workspace, or `deepline` for system plays. */ ownerSlug?: string; /** Scope in the control plane. */ scope?: 'org' | 'system'; /** Whether the current actor can edit this play in place. */ canEdit?: boolean; /** Whether the current actor can clone this play into their org. */ canClone?: boolean; /** Organization ID that owns this play. */ orgId: string; /** User ID that created the play. */ userId: string; /** Total number of times this play has been executed. */ runCount: number; /** Primary key column for CSV-based plays. */ tableNamespace?: string | null; /** Public Deepline id of the latest run. */ latestRunId?: string | null; /** Unix timestamp (ms). */ createdAt: number; /** Unix timestamp (ms). */ updatedAt: number; /** Source code of the current revision. */ sourceCode?: string | null; /** Static pipeline, if applicable. */ staticPipeline?: unknown; /** Serialized input schema contract for rendering / validation help. */ inputSchema?: Record | null; /** Serialized output schema contract for rendering / validation help. */ outputSchema?: Record | null; /** Alternate names that resolve to this play. */ aliases?: string[]; /** The revision that run-by-name resolves to. */ currentRevision?: PlayRevisionSummary | null; /** The current working revision (may differ from live). */ workingRevision?: PlayRevisionSummary | null; /** The live revision that executes for named runs. */ liveRevision?: PlayRevisionSummary | null; /** `true` if the working revision differs from the live revision. */ isDraftDirty?: boolean; /** Compatibility field for older readers. */ currentPublishedVersion?: number | null; } interface PlayListItem { playKey?: string; reference?: string; name: string; displayName?: string; description?: string | null; pinned?: boolean; toolCategories?: string[]; origin?: 'prebuilt' | 'owned'; ownerType?: 'deepline' | 'org'; ownerSlug?: string; canEdit?: boolean; canClone?: boolean; orgId: string; userId: string; runCount: number; updatedAt: number; createdAt: number; currentPublishedVersion?: number | null; tableNamespace?: string | null; isDraftDirty?: boolean; hasInputSchema?: boolean; inputSchema?: Record | null; outputSchema?: Record | null; staticPipeline?: unknown; currentRevision?: PlayRevisionSummary | null; liveRevision?: PlayRevisionSummary | null; aliases?: string[]; triggerStatus?: { cron: string | null; webhook: string | null; blockedReason: string | null; }; } interface ProductNotificationEventDefinition { id: string; label: string; description: string; source: 'cron' | 'webhook'; outcome: 'succeeded' | 'failed'; defaultEnabled: boolean; } interface ProductNotificationSettings { contractVersion: number; catalog: ProductNotificationEventDefinition[]; notifications?: ProductNotification[]; providers?: Array<{ kind: string; targetLabel: string; }>; destinations: Array>; subscriptions: Array<{ eventType: string; enabled: boolean; destinationId: string; }>; dlq: { count: number; capped: boolean; }; slackConnection?: { connected: boolean; status: string; }; } interface ProductNotification { id: string; name: string; provider: string; target: { id: string; name: string; kind?: 'channel' | 'member'; }; enabled: boolean; status: string; eventTypes: string[]; lastTestedAt?: number; lastTestStatus?: string; lastErrorMessage?: string; } interface PlayDescription { name: string; /** Stable registry key. Same value `plays list` reports for this play. */ playKey?: string; reference?: string; displayName?: string; description?: string | null; pinned?: boolean; toolCategories?: string[]; origin?: 'prebuilt' | 'owned'; ownerType?: 'deepline' | 'org'; canEdit?: boolean; canClone?: boolean; aliases: string[]; inputSchema?: Record | null; outputSchema?: Record | null; staticPipeline?: Record | null; csvInput?: Record | null; rowOutputSchema?: Record | null; runCommand: string; examples: string[]; cloneEditStarter?: { path: string; command: string; checkCommand: string; }; currentPublishedVersion?: number | null; /** * Version currently serving runs by name, from the live revision. Null when * the play has never been published. */ liveVersion?: number | null; /** Whether this play's cron and webhook triggers are armed. */ triggerStatus?: { cron: string | null; webhook: string | null; blockedReason: string | null; }; isDraftDirty?: boolean; latestRunId?: string | null; } /** * Complete play detail including definition, recent runs, and sheet state. * * Returned by {@link DeeplineClient.getPlay}. * * @example * ```typescript * const detail = await client.getPlay('email-waterfall'); * console.log(`${detail.play.name} — ${detail.play.runCount} runs`); * console.log(`Live: v${detail.play.liveRevision?.version}`); * console.log(`Latest runs:`, detail.latestRuns.map(r => r.status)); * ``` */ interface PlayDetail { /** Full play definition with revisions. */ play: PlayDefinitionDetail; /** Most recent runs (newest first). */ latestRuns: PlayRunListItem[]; /** Sheet processing summary. */ sheetSummary: PlaySheetSummary; /** Neon database URL for this play's customer data. */ customerDbUrl: string; /** Change cursor for incremental sync. */ deltaCursor: number; /** * Present only when requested through `getPlay(..., { source: ... })`. * `files` is the complete authored source tree, keyed by logical path. */ source?: { selector: 'working' | 'live' | `version:${number}`; revision: { id: string; version: number; }; entryFile: string; files: Record; }; } interface ClearPlayHistoryRequest { /** Optional explicit ctx.dataset keys to clear. Omit to clear all discovered sheets for the play. */ tableNamespaces?: string[]; } interface ClearPlayHistoryResult { playName: string; deletedRuns: number; droppedTables: string[]; } /** * Response from starting a play run. * * Internal/advanced payload returned by low-level play submission primitives. * Most callers should prefer `deepline plays run`, {@link DeeplineClient.runPlay}, * or {@link PlayJob.get}. * * @example * ```typescript * const started = await client.startPlayRun({ name: 'my-play', input: { domain: 'stripe.com' } }); * console.log(`Started: ${started.workflowId}`); * console.log(`Dashboard: ${started.dashboardUrl}`); * ``` */ interface PlayRunStart { /** Public Deepline play-run id for tracking this execution. */ workflowId: string; /** Public Deepline play-run API version. */ apiVersion?: number; /** Play name (echoed back from the request). */ name?: string; /** Initial status (typically `'RUNNING'`). */ status?: string; /** Resolved runtime backend used for this run. */ runtimeBackend?: string; /** Canonical run contract compatibility metadata. */ contract?: Record | null; /** Dashboard URL for the named play. */ dashboardUrl?: string; /** Terminal status returned when the start request used a short completion wait. */ finalStatus?: unknown; /** Canonical compact run package returned by current SDK/API responses. */ package?: PlayRunPackage; } /** * Result returned by {@link DeeplineClient.checkPlayArtifact}. * * This is the check-only version of play artifact registration: the server runs * the same preflight compiler and static-analysis pass without storing, * publishing, or starting a play run. */ interface PlayCheckResult { valid: boolean; errors: string[]; warnings?: string[]; staticPipeline?: Record | null; toolGetterHints?: PlayCheckToolGetterHint[]; /** * Recognized trigger bindings parsed from the play source (`sqlListeners` / * cron / webhook). Present only when the play declares at least one trigger, * so an author can confirm the binding was recognized rather than silently * dropped. Field names mirror the `definePlay` binding contract. */ triggers?: PlayCheckTriggersSummary | null; /** * Structured, machine-actionable issues surfaced by the check. An ADDITIVE * channel alongside `errors[]`: every `error`-severity issue is also present * in `errors[]` (so string-level tooling keeps working), while an agent can * read `code` / `validOptions` / `docsHint` to self-correct. `warning` * severity issues do NOT make the check invalid. */ issues?: PlayCheckIssue[]; /** * Affirmative echo of what Deepline recognized — triggers, tools, * datasets/columns, inputs, outputs — so a valid check reflects the parsed * shape rather than a bare "ok". */ recognized?: PlayCheckRecognizedSummary; /** * Human one-liner over {@link PlayCheckResult.recognized}, e.g. * `1 trigger · 2 tools · 1 dataset · 14 columns`. */ summary?: string; artifactHash?: string | null; graphHash?: string | null; /** SHA-256 of the exact source bytes checked by Deepline. */ sourceHash?: string | null; /** * Per-export results, present ONLY when the checked file exports more than * one play. Single-play files keep the exact flat shape they always had. * Entry 0 is the default export and mirrors the top-level fields; the * top-level `valid` is the AND over every entry, so an agent that reads only * `valid` can never ship a file whose second play fails. */ exports?: PlayCheckExportResult[]; /** Enforceable byte budgets measured during cloud preflight. */ limits?: { revisionStorage: { usedBytes: number; limitBytes: number; withinLimit: boolean; breakdown: { sourceCodeBytes: number; staticPipelineBytes: number; bindingsBytes: number; descriptionBytes: number; }; }; bundle: { usedBytes: number; limitBytes: number; withinLimit: boolean; }; }; } /** * One exported play's check result inside a multi-play file. Carries the same * per-play fields as {@link PlayCheckResult}, unprefixed and unaggregated, so a * consumer can attribute an error to the export that produced it. */ interface PlayCheckExportResult { /** Canonical export name: `default`, or the named export (`batch`). */ exportName: string; /** The `definePlay` name this export declares. */ name?: string | null; valid: boolean; errors: string[]; warnings?: string[]; issues?: PlayCheckIssue[]; staticPipeline?: Record | null; artifactHash?: string | null; graphHash?: string | null; sourceHash?: string | null; summary?: string; recognized?: PlayCheckRecognizedSummary; triggers?: PlayCheckTriggersSummary | null; } /** Severity of a {@link PlayCheckIssue}. `error` fails the check; `warning` does not. */ type PlayCheckIssueSeverity = 'error' | 'warning'; /** * One structured, machine-actionable issue surfaced by `deepline plays check`. * Mirrors the server-side `PlayCheckIssue` contract. `code` is a stable machine * code from a closed server-side set; `validOptions` enumerates the valid values * (tool ids / stream keys / columns / operators) so an agent self-corrects by * reading the structure instead of brute-forcing the compiler. */ interface PlayCheckIssue { code: string; severity: PlayCheckIssueSeverity; message: string; /** * Which exported play raised this issue, when the checked file exports more * than one and this is not the default export. Absent everywhere else, so * the structured channel stays byte-identical for single-play files. */ exportName?: string; path?: string; hint?: string; validOptions?: string[]; docsHint?: string; } /** * Affirmative "here's what Deepline recognized" echo returned alongside a * check's issues. Field names reuse the public play binding contract. */ interface PlayCheckRecognizedSummary { triggers?: PlayCheckTriggersSummary; tools?: string[]; /** * Durable datasets the play produces. `undrawnColumns` echoes the columns the * author declared out of an authored `@mermaid` diagram with * `.run({ undrawnColumns: [...] })`, so an opt-out is visible in check output. */ datasets?: { name: string; columns?: string[]; undrawnColumns?: string[]; }[]; inputs?: string[]; outputs?: string[]; } /** * One recognized SQL-listener trigger echoed back by {@link DeeplineClient.checkPlayArtifact}. */ interface PlayCheckSqlListenerTrigger { id: string; tool?: string; stream?: string; operations: string[]; /** * The recognized `sqlListeners.where` row filter, echoed back so an author can * confirm Deepline bound it. Mirrors the server `StoredSqlListenerWhere` shape * (`before` / `after` maps of column → operator filter). Absent when the * listener declares no `where`. */ where?: { before?: Record>; after?: Record>; }; } /** * The input delivered to a SQL-listener Play invocation. One changed Customer * DB row starts one run with this top-level event object; it is not an events * array or a polling batch. */ interface PlayCheckSqlListenerEventSummary { delivery: 'one_event_per_matched_row'; fields: Array<'tool' | 'stream' | 'operation' | 'before' | 'after' | 'changedAt' | 'metadata'>; } /** * Concise summary of the trigger bindings the server recognized for a play. * Only present triggers are populated. */ interface PlayCheckTriggersSummary { sqlListeners?: PlayCheckSqlListenerTrigger[]; sqlListenerEvent?: PlayCheckSqlListenerEventSummary; cron?: { schedule: string; timezone?: string; }; webhook?: true; } interface PlayCheckToolGetterHint { toolId: string; lists: Array<{ name: string; expression: string; raw?: string; }>; values: Array<{ name: string; expression: string; raw?: string; }>; raw?: string; unavailable?: string; } /** * Request body for starting a play run via {@link DeeplineClient.startPlayRun}. * * Internal/advanced request shape for low-level submission primitives. * Most callers should prefer `deepline plays run`, {@link DeeplineClient.runPlay}, * or {@link Deepline.connect}. * * Either `name` (for live plays) or `artifactStorageKey` (for packaged ad hoc runs) is required. * * @example * ```typescript * // Run a live play by name: * await client.startPlayRun({ name: 'email-waterfall', input: { domain: 'stripe.com' } }); * * // Run a packaged ad hoc play by registered artifact: * await client.startPlayRun({ * artifactStorageKey: 'plays/artifacts/org/acme/my-play/playgraph_abc123.json', * input: { domain: 'stripe.com' }, * }); * ``` */ interface StartPlayRunRequest { /** Play name for registered revisions. */ name?: string; /** Explicit revision ID when the caller wants a specific saved version. */ revisionId?: string; /** R2 artifact key for ad hoc artifact-backed runs. */ artifactStorageKey?: string; /** Source snapshot already validated while registering this artifact. */ sourceCode?: string; /** Source graph snapshots for local helper files included in cloud preflight. */ sourceFiles?: Record; /** Human-readable one-line description for the revision created by file-backed runs. */ description?: string; /** Static pipeline already produced while registering this artifact. */ staticPipeline?: unknown; /** Artifact content hash already validated while registering this artifact. */ artifactHash?: string; /** Static graph hash already validated while registering this artifact. */ graphHash?: string; /** Optional preloaded artifact snapshot for immediate ad hoc execution. */ runtimeArtifact?: Record; /** Compiler manifest for ad hoc graph runs, including imported play dependencies. */ compilerManifest?: PlayCompilerManifest; /** Primary input file bytes for one-shot server-side staging. */ inputFileUpload?: unknown; /** Packaged file bytes for one-shot server-side staging. */ packagedFileUploads?: unknown[]; /** Runtime input passed to the play function as its second argument. */ input?: Record; /** Staged file reference for the primary input file (e.g. CSV). */ inputFile?: unknown; /** Additional staged file references (dependencies, data files). */ packagedFiles?: unknown[]; /** Compatibility flag; active sibling runs are allowed. */ force?: boolean; /** Explicit cache-bypass flag for durable dataset and tool-call reuse. */ forceToolRefresh?: boolean; /** * Per-run ceiling for concurrently resident provider-tool executions and * direct ctx.fetch calls. The server validates the supported range. */ maxConcurrentExternalCalls?: number; /** Run-wide default and ceiling for live dataset-map row resolvers. */ maxConcurrentRows?: number; /** Optionally let the start request wait briefly and return a terminal result. */ waitForCompletionMs?: number; /** * Per-run execution profile override. The server defaults to absurd. The * Only `absurd` is accepted; most callers should leave this unset. */ profile?: string; /** Optional per-run provider execution mode for eval/smoke runs. */ integrationMode?: 'live' | 'eval_stub' | 'fixture'; /** Fixture-only provider response timing and outcome simulation. */ fixtureBehavior?: FixtureBehavior; /** Internal runtime estate selection. The app host remains unchanged. */ runtime?: PlayRuntimeSelection; /** Internal/dev-only runtime policy overrides for black-box durability tests. */ testPolicyOverrides?: Record; } /** * Request body for making a play revision live. * * If omitted, the server promotes the current working revision. */ interface PublishPlayVersionRequest { /** Explicit revision ID to make live. */ revisionId?: string; } /** * Result returned after making a play revision live. */ interface PublishPlayVersionResult { success: boolean; name: string; liveVersion?: number; triggerMetadata?: unknown; triggerBindings?: unknown; } /** * Result returned after moving an org-owned play to Trash. * * `deletePlay` is retained as the SDK method name for compatibility, but play * deletion is soft: revisions and run history remain available if the play is * restored. */ interface DeletePlayResult { archived: boolean; alreadyArchived: boolean; name: string; archivedBindingCount: number; } /** Result returned after restoring an org-owned play from Trash. */ interface RestorePlayResult { restored: boolean; alreadyActive?: boolean; name: string; } /** Owner-facing view of a play's public share page. */ interface SharePageOwnerView { shareSlug: string; /** Org URL handle; the public page lives at `/p/{orgSlug}/{playName}`. */ orgSlug: string; publishedRevisionId: string; publishedVersion: number; visibility: string; seoIndexing: 'index' | 'noindex'; showAverageDeeplineCost: boolean; showAverageLatency: boolean; /** Stable public path, e.g. `/p/{orgSlug}/{playName}`. */ publicPath: string; /** Version-pinned canonical path, e.g. `/p/{orgSlug}/{playName}/v/{version}`. */ canonicalPath: string; createdAt: number; updatedAt: number; } /** One row in the owner-facing revision picker for sharing. */ interface SharePageRevisionOption { revisionId: string; version: number; isLive: boolean; isWorking: boolean; isPublished: boolean; hasMap: boolean; hasCard: boolean; createdAt: number; } /** * Status payload from `GET/POST/PATCH /api/v2/plays/:name/share`. * The revision picker is bounded to recent and state-bearing revisions. Pass a * selected revision id to `getSharePage` to retain any older selection. */ interface SharePageStatus { playName: string; share: SharePageOwnerView | null; publishedCopy: unknown | null; revisions: SharePageRevisionOption[]; /** Present on publish responses when share-card generation was non-strict. */ warning?: string | null; } interface PublishSharePageRequest { /** The revision to publish/repoint the public page to. */ revisionId: string; /** Must be true — acknowledges the page is publicly viewable. */ acknowledgedUnlisted: true; showAverageDeeplineCost?: boolean; showAverageLatency?: boolean; seoIndexing?: 'index' | 'noindex'; } interface UpdateSharePageRequest { showAverageDeeplineCost?: boolean; showAverageLatency?: boolean; seoIndexing?: 'index' | 'noindex'; } /** * Monitor authoring and typing for the Deepline SDK. * * A **monitor** is a Deepline-native signal feed. A deployed monitor writes * events into a Customer DB table (one row per finding). Plays react to those * rows through `sqlListeners` bindings (see {@link definePlay}). This module is * the code-first authoring surface for monitors — the same product model the * `deepline monitors` CLI drives, expressed as typed SDK code. * * Use {@link defineMonitor} to author a typed monitor definition, then deploy or * validate it with the monitors namespace: * * ```typescript * import { DeeplineClient, defineMonitor } from 'deepline'; * * const monitor = defineMonitor({ * key: 'stripe-job-openings', * tool: 'deepline_native.company_radar', * name: 'Stripe job openings', * payload: { domain: 'stripe.com', radar_type: 'company_job_openings' }, * }); * * const client = new DeeplineClient(); * const plan = await client.monitors.check(monitor); // validate, no spend * await client.monitors.deploy(monitor); // deploy for real * ``` * * @module */ /** * A monitor definition: the exact object accepted by * `client.monitors.check(...)` and `client.monitors.deploy(...)` and by the * `/api/v2/monitors/{check,deploy}` endpoints the CLI uses. * * @typeParam TPayload - Provider-specific monitor payload shape (defaults to a * loose record). Pass a concrete shape to `defineMonitor(...)` for * compile-time checking of the payload fields. */ type MonitorDefinition = { /** Stable public key for this monitor, unique within the workspace. */ key: string; /** Monitor tool id, e.g. `"deepline_native.company_radar"`. */ tool: string; /** Optional human-readable name shown in listings and detail views. */ name?: string; /** Provider-specific monitor payload (e.g. domain + radar_type). */ payload: TPayload; /** Optional Deepline lifecycle metadata (deploy/reuse controls). */ controls?: MonitorControls; }; /** Provider-specific monitor payload. Keys and value types depend on the tool. */ type MonitorPayload = Record; /** * Deepline lifecycle metadata attached to a monitor definition. These are * Deepline-side deploy/reuse controls, not provider payload fields. The set is * intentionally open (server-owned) so newer controls do not require an SDK * bump; known controls are typed for discoverability. */ type MonitorControls = { /** * Request Deepline Native priority execution for a bounded urgent preview or * calibration radar. Deepline sends the upstream custom-field marker and * enforces a maximum of ten active or in-flight priority radars per org. * Omit this for regular and bulk-scale monitoring. */ execution_type?: 'priority'; [key: string]: unknown; }; /** * Define a typed monitor definition. * * Mirrors {@link definePlay} as the code-first authoring entrypoint: it gives * compile-time type safety on the definition object and returns it verbatim for * passing to `client.monitors.check(...)` / `client.monitors.deploy(...)`. It * performs the same lightweight local invariants the server enforces (non-empty * `key` and `tool`, object `payload`) so authoring mistakes fail before a * network round-trip. * * @typeParam TPayload - Provider payload shape. * @param definition - The monitor definition. * @returns The validated definition object. * * @example * ```typescript * const monitor = defineMonitor({ * key: 'job-openings', * tool: 'deepline_native.company_radar', * payload: { domain: 'stripe.com', radar_type: 'company_job_openings' }, * }); * ``` */ declare function defineMonitor(definition: MonitorDefinition): MonitorDefinition; interface PlayStagedFileRef { storageKind: 'r2'; storageKey: string; logicalPath: string; fileName: string; contentHash: string; contentType: string; bytes: number; } type EnrichStepCommand = { alias: string; tool: string; operation?: string; play?: { ref: string; mode?: 'scalar'; execution?: 'child' | 'inline'; inline?: { exportName: string; functionExpressionSource: string; sourceHash: string; typeImports: string[]; runtimeImports?: string[]; }; }; payload: Record; extract_js?: string; run_if_js?: string; description?: string; disabled?: boolean; }; type EnrichWaterfallCommand = { with_waterfall: string; min_results?: number; commands: EnrichCommand[]; description?: string; }; type EnrichCommand = EnrichStepCommand | EnrichWaterfallCommand; type EnrichCompiledConfig = { version: 1; commands: EnrichCommand[]; cost_cap_usd_per_run?: number; _comments?: Array<{ path: string; lines: string[]; }>; _expansion_preview?: { plays: Array<{ alias: string; tool_id: string; template_group: string; runtime_group: string; estimated_credits_range: string; steps: Array>; }>; }; }; type SlackNotificationTarget = { channel: string; memberId?: never; } | { channel?: never; memberId: string; }; type CreateNotificationInput = { name: string; provider: 'slack'; eventTypes: string[]; } & SlackNotificationTarget; type UpdateNotificationInput = { enabled: boolean; } | ({ name: string; eventTypes: string[]; } & SlackNotificationTarget); type IngestionStorageRepairResult = { status?: 'repaired'; connection_grants: { runtime_role: string; customer_db_role: string; }; repaired: unknown[]; count: number; repair?: { location: { changed: boolean; }; storage_contract: { applied: boolean; current: boolean; }; runtime_migration: { current: boolean; }; runtime_capabilities: { before: { reachable: boolean; status: string; storage_contract_current: boolean; runtime_migration_current: boolean; runtime_capabilities_ready: boolean; capability_failures: string[]; }; after: { reachable: boolean; status: string; storage_contract_current: boolean; runtime_migration_current: boolean; runtime_capabilities_ready: boolean; capability_failures: string[]; }; runtime_role: { currentRole: string | null; dlMetaSchemaUsage: boolean; uuidFunctionExecute: boolean; enrichmentsSchemaUsage: boolean; enrichmentsWriteReady: boolean; storageSchemaUsage: boolean; storageSchemaCreate: boolean; }; customer_db_role: { currentRole: string | null; dlMetaSchemaUsage: boolean; uuidFunctionExecute: boolean; enrichmentsSchemaUsage: boolean; enrichmentsWriteReady: boolean; storageSchemaUsage: boolean; storageSchemaCreate: boolean; }; }; internal_relations: { reconciled: boolean; }; materialized_tables: { repaired_count: number; }; }; }; type ExecuteToolRawOptions = { includeToolMetadata?: boolean; responseIntent?: 'dataset' | 'raw' | 'row_artifact'; metadata?: Record; timeout?: number; maxRetries?: number; }; /** * Standard provider/tool execution envelope returned by low-level SDK calls. * * `toolResponse.rawV2` contains the complete scrubbed provider response; * `toolResponse.raw` is derived locally as the legacy provider-result projection. `extractedValues` and * `extractedLists` contain Deepline-normalized getters when the tool exposes * them. Billing fields are Deepline-facing and must not expose provider spend. */ type ToolExecution> = { status: string; job_id?: string; meta?: Record; toolResponse: { raw: TData; rawV2?: unknown; view?: 'data' | 'rawV2'; meta?: TMeta; responseMeta?: TMeta; }; extractedLists?: Record; extractedValues?: Record; billing?: Record; [key: string]: unknown; }; /** Filters for `client.runs.list(...)`. */ type RunsListOptions = { play?: string; status?: string; limit?: number; /** Zero-based page offset. Requires `play` because status-only inventory is not paginated. */ offset?: number; }; /** Options for `client.runs.get(...)`. */ type RunsGetOptions = { /** Return the raw status payload instead of the compact package. */ full?: boolean; /** Attach a bounded end-of-stream window for a failed run. */ failedLogs?: boolean; /** Requested failed-log lines to attach (default 20, hard-capped at 20). */ failedLogLimit?: number; }; /** Streaming options for `client.runs.tail(...)`. */ type RunsTailOptions = { signal?: AbortSignal; /** Observe each canonical live event while `tail` waits for terminal state. */ onEvent?: (event: PlayLiveEvent) => void; /** * Called before each stream reconnect. Server stream windows are finite, so * long runs reconnect with backoff until a terminal status is observed. */ onReconnect?: (info: { attempt: number; delayMs: number; reason: string; }) => void; /** * Display-only transport notices: subscription-transport reconnects, * staleness warnings, and the one-time fallback notice when the server * cannot serve the Convex subscription transport (ADR-0008). */ onNotice?: (message: string) => void; }; /** Log fetch options for `client.runs.logs(...)`. */ type RunsLogsOptions = { /** Return the LAST `limit` stored log lines (default 200). */ limit?: number; /** Fetch every stored log line, paginating to the full totalCount. */ all?: boolean; /** Select the bounded failure view; truncated runs degrade explicitly. */ failed?: boolean; }; /** Persisted log response for one play run. */ type RunsLogsResult = { runId: string; totalCount: number; returnedCount: number; firstSequence: number | null; lastSequence: number | null; truncated: boolean; hasMore: boolean; entries: string[]; /** Selected public log view. */ view?: 'tail' | 'failed' | 'all'; /** Whether entries are terminal context or the last pre-truncation lines. */ association?: 'terminal_failure_window' | 'retained_before_truncation'; /** Loud explanation when the terminal failure window was not retained. */ warning?: string; /** Exact follow-up command when the selected view is degraded. */ next?: { logs: string; }; /** * True when the run crossed the Run Log Stream retention cap: `totalCount` * keeps counting, but stored line bodies end at a loud truncation marker. */ logsTruncated?: boolean; }; /** One persisted runtime-sheet row returned by `client.runs.exportDatasetRows(...)`. */ type PlaySheetRow = { key?: string; status?: string; data?: Record; [key: string]: unknown; }; /** Runtime-sheet rows and aggregate progress for one dataset/table namespace. */ type PlaySheetRowsResult = { rows: PlaySheetRow[]; scope?: { kind: 'database'; } | { kind: 'run'; runId: string; }; summary?: { stats?: { total?: number; queued?: number; running?: number; completed?: number; failed?: number; [key: string]: unknown; }; columns?: Record; [key: string]: unknown; }; customerDbUrl?: string; deltaCursor?: number; }; type PlaySecretMetadata = { _id: string; orgId: string; scope: 'org' | 'play'; playName?: string; name: string; status: string; hasValue: boolean; createdAt: number; updatedAt: number; lastUsedAt?: number; }; /** * 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. * * @sdkReference client 020 client.runs */ type RunsNamespace = { /** Get current run status by public run id. */ get: (runId: string, options?: RunsGetOptions) => Promise; /** Explicitly read the retained original input (may include customer data). */ input: (runId: string) => Promise<{ runId: string; input: Record | unknown[]; bytes: number; sha256: string | null; replayedFromRunId: string | null; }>; /** Start a fresh run from a prior run's retained input and pinned revision. */ rerun: (runId: string) => Promise<{ runId: string; replayedFromRunId: string; revisionId: string | null; status: string; next: { inspect: string; input: string; }; }>; /** List runs for one play, optionally filtered by status. */ list: (options: RunsListOptions) => Promise; /** Stream run events and return the latest/terminal run status. */ tail: (runId: string, options?: RunsTailOptions) => Promise; /** Fetch persisted log lines for a run. */ logs: (runId: string, options?: RunsLogsOptions) => Promise; /** Export persisted rows for a runtime-sheet dataset/table namespace. */ exportDatasetRows: (input: { playName: string; tableNamespace: string; runId?: string; limit?: number; offset?: number; rowMode?: 'output' | 'all'; }) => Promise; /** Stop a running/waiting run. */ stop: (runId: string, options?: { reason?: string; }) => Promise; /** Stop active runs across the current workspace. */ stopAll: (options?: { reason?: string; }) => Promise; }; /** Current mutable customer database namespace exposed as `client.db`. */ type DbNamespace = { /** Run a bounded SQL query against the current customer data plane. */ query: (input: { sql: string; maxRows?: number; }) => Promise; }; /** * Whether the current workspace can use Deepline Monitors, from * `GET /api/v2/monitors/access`. Reachable without monitor access (requires * only an authenticated session/API key); a denial is a normal 200 body, not a * 403. */ type MonitorsAccessStatus = { has_access: boolean; reason?: string; }; /** * The monitor tools catalog (deployable monitor TYPES), from * `GET /api/v2/monitors/tools`. Server-owned shape: describing one tool returns * the full payload/stream contract, while list mode returns the compact * inventory. Kept as an open record so the SDK does not have to bump when the * server enriches the catalog. */ type MonitorsAvailableResult = { tools?: Array>; total?: number; returned?: number; is_truncated?: boolean; [key: string]: unknown; }; /** Options for `client.monitors.available(...)` (list or describe mode). */ type MonitorsAvailableOptions = { provider?: string; search?: string; limit?: number | string; /** * Request the full catalog contract in LIST mode (payload schemas + streams). * List mode is compact by default; ignored when describing a single tool. */ full?: boolean; /** Ask the server for high-signal fields only. */ compact?: boolean; }; /** One deployed monitor row returned by `client.monitors.list(...)`. */ type MonitorListEntry = { key?: string; monitor_key?: string; status?: string; tool?: string; name?: string; configured?: boolean; active?: boolean; provider?: string; output_table?: string | null; webhook_state?: string; last_received_event?: string | null; bound_plays?: Array>; consumer_health_truncated?: boolean; [key: string]: unknown; }; /** * Deployed-monitor registry page from `GET /api/v2/monitors/deployed`. `total` * is the TRUE registry count for the status filter, not this page's size; page * past a truncated result with `next_cursor`. */ type MonitorsListResult = { monitors?: MonitorListEntry[]; total?: number; returned?: number; is_truncated?: boolean; next_cursor?: string | null; status_filter_applied?: string; status_summary?: Array<{ status: string; count: number; }>; include_consumers?: boolean; [key: string]: unknown; }; /** Options for `client.monitors.list(...)`. */ type MonitorsListOptions = { /** active (default), disabled, or all. */ status?: string; limit?: number | string; /** Page past a truncated result using a prior response's `next_cursor`. */ cursor?: string; compact?: boolean; /** Include bounded current SQL-listener delivery/run health (requires limit <= 20). */ includeConsumers?: boolean; }; /** * Server-owned monitor payload shapes returned by the deploy/check/get/mutation * endpoints. Kept as open records because the render layer and the endpoints * own the exact field set (output contracts, pricing, reuse candidates, delete * plans, dependents) and it must not require an SDK bump to evolve. */ type MonitorCheckResult = Record; type MonitorDeployResult = Record; /** Field-level monitor capability spec returned by `client.monitors.get(...)`. */ type MonitorSpec = { /** Whether Deepline has a current capability spec for this deployed monitor. */ available?: boolean; tool?: string; description?: string; fields?: Array>; conditional_requirements?: Array>; /** Present when a legacy monitor has no current capability spec. */ message?: string; }; /** One deployed-monitor read. The server may add monitor-specific fields. */ type MonitorDetail = Record & { monitor_spec?: MonitorSpec; }; type MonitorDependents = Record; type MonitorUpdateChangeSummary = { definition: { changed: Array<{ path: string; before: unknown; after: unknown; }>; unchanged: Array<{ path: string; value: unknown; }>; }; storage: { existing_rows_preserved: true; unchanged_destinations: Array<{ output: string; table: string; row_type: string | null; }>; changed_destinations: Array<{ output: string; before_table: string | null; after_table: string | null; }>; }; upstream: { resource_replaced: boolean; strategy: 'unchanged' | 'create_then_delete_previous' | 'deferred_until_reactivation'; }; }; type MonitorUpdateResult = { change_summary?: MonitorUpdateChangeSummary; [key: string]: unknown; }; type MonitorDeleteResult = Record; type MonitorReactivateResult = Record; type MonitorTestResult = Record; type MonitorValidateResult = Record; /** * Public monitors namespace exposed as `client.monitors`. * * Mirrors the /api/v2/monitors resource family so the monitors CLI and * programmatic callers share one product surface — every `deepline monitors` * verb maps to a method here. Monitors are fully expressible as SDK code: author * a definition with {@link defineMonitor}, then check/deploy/list/get/update/ * delete/reactivate through this namespace. * * @sdkReference client 040 client.monitors */ type MonitorsNamespace = { /** Whether the current workspace can use monitors (`{ has_access, reason }`). */ status: () => Promise; /** * The deployable monitor tools catalog. Call with no tool id for the list, or * with a tool id (positional or `{ tool }`) to describe one tool's full * payload/stream contract. */ available: (toolIdOrOptions?: string | (MonitorsAvailableOptions & { tool?: string; }), options?: MonitorsAvailableOptions) => Promise; /** Validate a monitor definition without deploying it (no spend). */ check: (definition: MonitorDefinition) => Promise; /** Deploy a monitor from a definition. May spend Deepline credits. */ deploy: (definition: MonitorDefinition, options?: { dryRun?: boolean; }) => Promise; /** List deployed monitors (active by default). `includeConsumers` requires a limit of 20 or fewer. */ list: (options?: MonitorsListOptions) => Promise; /** Fetch one deployed monitor by public key with bounded current listener health. */ get: (key: string) => Promise; /** * Test a deployed monitor. `validationOnly` safely verifies the callback * envelope; omitted options preserve the historic full-ingestion behavior. */ test: (key: string, payload: Record, options?: { validationOnly?: boolean; dispatch?: boolean; }) => Promise; validate: (key: string) => Promise; /** List the published plays depending on one monitor's output streams. */ dependents: (key: string) => Promise; /** Update a deployed monitor by public key. */ update: (key: string, patch: Record) => Promise; /** Delete a deployed monitor and its upstream provider resource. `dryRun` returns the delete plan. */ delete: (key: string, options?: { dryRun?: boolean; }) => Promise; /** Reactivate a disabled monitor. `dryRun` returns the reactivation cost. */ reactivate: (key: string, options?: { dryRun?: boolean; }) => Promise; }; /** One credit grant pool reported by the billing subscription status endpoint. */ type BillingCreditPool = { pool: string; credits_remaining: number; credits_granted: number; source: string; cycle_key: string | null; effective_at: string; }; /** * Subscription state for the active workspace, from * `GET /api/v2/billing/subscription/status`. All amounts are Deepline credits * and Deepline-facing USD — never provider spend. */ type BillingSubscriptionStatus = { org_id: string; plan_version_id: string; plan_name: string; plan_family_id: string; /** Whether a Stripe subscription backs the active plan. */ subscribed: boolean; price_usd: number | null; price_interval: string | null; monthly_grant_credits: number; assigned_by: string; assigned_at: string | null; credit_pools: BillingCreditPool[]; pooled_credits_remaining: number; /** End of the current paid period (ISO timestamp), when Stripe is reachable. */ current_period_end: string | null; /** True when a cancellation is already scheduled for period end. */ cancel_at_period_end: boolean | null; stripe_status: string | null; }; /** * Result of `POST /api/v2/billing/subscription/cancel`. Cancellation is always * at period end: the customer keeps the cycle they paid for and every * remaining credit. `undo_cancel` reverses a pending cancellation. */ type BillingSubscriptionCancelResult = { org_id: string; subscription_id: string; cancel_at_period_end: boolean; current_period_end: string | null; status: string; message: string; }; /** * One customer-facing billing history entry from * `GET /api/v2/billing/invoices`: a subscription invoice or a one-time credit * purchase receipt. Amounts are what the customer paid — never provider spend. */ type BillingInvoiceEntry = { kind: 'invoice' | 'receipt'; id: string; created_at: string; description: string; amount_cents: number; currency: string; status: string; /** Stripe-hosted page (invoice or card receipt). */ url: string | null; /** Direct PDF when Stripe provides one (invoices only). */ pdf_url: string | null; /** Stripe-hosted invoice page when this purchase has an invoice. */ invoice_url?: string | null; /** Stripe-hosted card receipt when this purchase has one. */ receipt_url?: string | null; }; type BillingInvoicesResult = { org_id: string; entries: BillingInvoiceEntry[]; }; type TargetBillingOperation = { id: string; state: string; version: number; next_action?: string | null; }; type TargetBillingPlan = { sku: 'payg-v1' | 'builder-v1' | 'team-v1'; name: string; recurring_price_usd: number; interval: 'month'; included_credits: number; purchased_credit_price_usd: number; }; type TargetBillingPlansResult = { org_id: string; plans: TargetBillingPlan[]; current_plan_sku: string; pending_plan_sku: string | null; acquisition_enabled: boolean; }; type TargetBillingStatusResult = { org_id: string; plan: { sku: string; name: string; recurring_price_usd: number | null; interval: string | null; included_credits: number | null; }; state: string; changes_allowed: boolean; legacy_changes_allowed?: boolean; payment_state: string; recharge_state: string; next_action: string | null; pending_plan_sku: string | null; as_of: string | null; }; type TargetBillingMutationResult = { data: Record; operation: TargetBillingOperation; request_id?: string; }; type TargetBillingPlanTransitionOptions = { action: 'start_or_change'; targetPlanSku: 'payg-v1' | 'builder-v1' | 'team-v1'; idempotencyKey: string; } | { action: 'cancel' | 'undo_cancel'; targetPlanSku?: never; idempotencyKey: string; }; /** Saved payment method details returned by one-click billing top-up. */ type BillingPaymentMethodSummary = { brand?: string | null; last4?: string | null; exp_month?: number | null; exp_year?: number | null; label?: string | null; }; /** * Result of `POST /api/v2/billing/top-up`: a saved-card charge and purchased * Deepline credit grant for the active workspace. */ type BillingTopUpResult = { ok: true; credits: number; amount_cents: number; currency: string; balance: number; stripe_payment_intent_id: string; payment_method?: BillingPaymentMethodSummary | null; }; /** One published plan from `GET /api/v2/billing/catalog/current`. */ type BillingPlanEntry = { plan_family_id: string; plan_version_id: string; public_name: string; price_usd: number | null; price_interval: string | null; monthly_grant_credits: number; rollover: { mode: string; max_credits?: number; }; /** Whether the plan can be purchased via subscription checkout. */ acquirable: boolean; }; /** One usage metric published in the billing catalog. */ type BillingMeterEntry = { id: string; name: string; }; /** @deprecated Use BillingMeterEntry. Retained for wire/API alias compatibility. */ type BillingMetricEntry = BillingMeterEntry; /** The caller's active plan as reported by the plans endpoint. */ type BillingActivePlan = { plan_family_id: string; plan_version_id: string; public_name: string; rate_card_id: string; assigned_by: string; assigned_at: string | null; has_subscription: boolean; }; /** * Published plans plus the caller's active plan, from * `GET /api/v2/billing/catalog/current`. Answers "what plans exist and what * am I on". All amounts are Deepline credits and Deepline-facing USD — never * provider spend. */ type BillingPlansResult = { catalog_id: string; catalog_version: string; active_plan: BillingActivePlan; plans: BillingPlanEntry[]; meters: BillingMeterEntry[]; /** @deprecated Use meters. Retained for installed SDK compatibility. */ metrics: BillingMetricEntry[]; }; /** * Public billing namespace exposed as `client.billing`. * * Carries plans, subscription state, cancellation, and invoice/receipt history * so CLI commands and programmatic callers share one surface. * * @sdkReference client 030 client.billing */ type BillingNamespace = { /** Charge the saved payment method and add Deepline credits to the active workspace. */ topUp: (options: { credits: number; idempotencyKey?: string; }) => Promise; /** Published plans plus the plan you are on ("what plans exist and what am I on"). */ plans: () => Promise; subscription: { /** Active plan, Stripe subscription state, and remaining credit pools. */ status: () => Promise; /** * Schedule cancellation at period end (credits are kept), or reverse a * pending cancellation with `{ undo: true }`. */ cancel: (options?: { undo?: boolean; }) => Promise; }; invoices: { /** Subscription invoices plus credit purchase receipts, newest first. */ list: (options?: { limit?: number; }) => Promise; }; /** Metronome-authored target catalog and current Contract projection. */ targetPlans: () => Promise; /** Normalized target billing state. */ targetStatus: () => Promise; /** Buy Deepline credits through a payment-gated Metronome commit. */ purchaseCredits: (options: { credits: number; idempotencyKey: string; }) => Promise; /** Start, change, cancel, or undo a target plan transition. */ transitionPlan: (options: TargetBillingPlanTransitionOptions) => Promise; /** Create a Stripe-hosted billing Portal session. */ portalSession: () => Promise<{ url: string; }>; }; /** * A staged-file upload target minted by POST /api/v2/plays/files/stage/mint. * When `alreadyStaged` is true the server already holds the content-addressed * object and `uploadUrl` is null; otherwise the client PUTs the body to * `uploadUrl` with `uploadHeaders`. */ type MintStagedFileUpload = { logicalPath: string; contentHash: string; ref: PlayStagedFileRef; alreadyStaged: boolean; uploadUrl: string | null; uploadHeaders: Record | null; uploadExpiresAt: string | null; }; /** * 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. * * @example * ```typescript * import { DeeplineClient } from 'deepline'; * * // Zero-config (uses env vars / CLI auth): * const client = new DeeplineClient(); * * // Explicit config: * const client2 = new DeeplineClient({ * apiKey: 'dl_test_...', * baseUrl: 'http://localhost:3000', * }); * ``` * * @sdkReference client 010 */ declare class DeeplineClient { private readonly http; private readonly config; /** Canonical run lifecycle namespace backed by `/api/v2/runs`. */ readonly runs: RunsNamespace; /** Current mutable customer database namespace backed by `/api/v2/db/query`. */ readonly db: DbNamespace; /** Billing namespace: subscription status/cancel and invoice history. */ readonly billing: BillingNamespace; /** Monitors namespace: access, catalog, deploy/check, and lifecycle. */ readonly monitors: MonitorsNamespace; /** * Create a low-level SDK client. * * Most callers can omit options and let the SDK resolve auth/config from * environment variables and CLI-managed credentials. * * @param options - Optional overrides for API key, base URL, timeout, and retries. * @throws {@link ConfigError} if no API key can be resolved from any source. */ constructor(options?: DeeplineClientOptions); /** The resolved base URL this client is targeting (e.g. `"http://localhost:3000"`). */ get baseUrl(): string; private compactSchema; private schemaMetadata; private playRunCommand; private starterPlayPath; private playCloneEditStarter; private summarizePlayListItem; private summarizePlayDetail; /** List secret metadata visible to the current workspace. */ listSecrets(): Promise; /** * Check whether a named secret exists, is active, and has a stored value. * * @param name - Secret name. It is normalized to uppercase before lookup. * @returns Matching active secret metadata, or `null`. */ checkSecret(name: string): Promise; /** * List all available tools. * * Returns tool definitions including ID, provider, description, input/output schemas, * and list extractor paths for automatic CSV conversion. * * @returns Array of tool definitions * * @example * ```typescript * const tools = await client.listTools(); * const searchTools = tools.filter(t => t.categories.includes('search')); * console.log(`Found ${searchTools.length} search tools`); * ``` */ listTools(options?: { categories?: string; tags?: string; grep?: string; grepMode?: 'all' | 'any' | 'phrase'; compact?: boolean; }): Promise; /** List discoverable providers without requiring a local plugin catalog. */ listProviders(options?: { changed?: boolean; }): Promise; /** * Search 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. */ searchTools(options?: ToolSearchOptions): Promise; /** * Get detailed metadata for a single tool. * * Returns everything from {@link ToolDefinition} plus pricing info, sample * inputs/outputs, failure modes, and cost estimates. * * @param toolId - Tool identifier (e.g. `"dropleads_search_people"`) * @returns Full tool metadata * * @example * ```typescript * const meta = await client.getTool('dropleads_search_people'); * console.log(`Cost: ${meta.estimatedCreditsRange} credits`); * console.log(`Input schema:`, meta.inputSchema); * ``` */ getTool(toolId: string): Promise; /** * Describe a Deepline Agent model and its provider-specific option surface. * * Combines live AI Gateway model metadata with Deepline's generated AI SDK * provider option registry so agents can construct `providerOptions` * payloads before executing `deeplineagent`. * * The returned option schemas describe accepted provider option shapes, not * guaranteed support for every model. Runtime AI SDK/Gateway errors remain * authoritative for model-gated values. * * @param model - Gateway model id such as `"openai/gpt-5.5"` * @returns Model metadata, provider option shapes, and runnable examples */ describeModel(model: string): Promise; /** * Quote dynamic AI inference pricing for a concrete payload. * * The result separates a planning estimate from a proven authorization * maximum and contains Deepline credits only. */ quoteInferenceTool(toolId: 'ai_inference' | 'deeplineagent', payload: Record): Promise; /** * Execute 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. */ executeTool>(toolId: string, input: Record, options?: ExecuteToolRawOptions): Promise>; /** * Back-compatible alias for {@link executeTool}. * * Retained for callers that still use the older raw naming while the response * envelope remains the same. */ executeToolRaw>(toolId: string, input: Record, options?: ExecuteToolRawOptions): Promise>; private queryDb; /** * Run a bounded SQL query against the current mutable customer database. * * This query is not scoped to one play run. Use `client.runs` export actions * when the caller needs the rows produced by a specific run. * * @deprecated Use {@link DeeplineClient.db} `.query(...)`. */ queryCustomerDb(input: { sql: string; maxRows?: number; }): Promise; /** * Re-establish this workspace's tenant storage contract: role/DB connect * grants plus materialized table grants. Org-admin only. Use when a run fails * with WORKSPACE_STORAGE_NOT_READY. */ repairIngestionStorage(input?: { provider?: string; }): Promise; /** * Start a play run. * * Internal/advanced primitive. For normal callers, prefer the public * entrypoints: the CLI, {@link Deepline.connect}, {@link submitPlay}, * or {@link runPlay}. * * Supported invocation surfaces intentionally share this same run contract: * `deepline plays run`, repo scripts such as `bun run deepline -- plays 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. * * @param request - Play run configuration (name, code, input, etc.) * @returns Run metadata including the public `workflowId` * * @example * ```typescript * // Run a live play by name: * const started = await client.startPlayRun({ * name: 'email-waterfall', * input: { linkedin_url: 'https://linkedin.com/in/jdoe', domain: 'acme.com' }, * }); * console.log(`Workflow: ${started.workflowId}`); * * // Run an ad hoc artifact-backed play: * const started2 = await client.startPlayRun({ * artifactStorageKey: 'plays/v1/orgs/acme/plays/my-play/artifacts/playgraph_abc123.json', * }); * ``` */ startPlayRun(request: StartPlayRunRequest): Promise; /** * Start 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)`. * * @param request - Play run configuration. * @param options - Optional streaming options. * @param options.signal - Optional abort signal for the streaming request. * @returns Async stream of play-scoped live events. */ startPlayRunStream(request: StartPlayRunRequest, options?: { signal?: AbortSignal; }): AsyncGenerator; /** * Register a bundled play artifact. * * Internal/advanced primitive used by packaging flows. Public callers should * prefer the CLI, {@link submitPlay}, or {@link runPlay}. */ registerPlayArtifact(input: { name: string; sourceCode: string; sourceFiles?: Record; description?: string; artifact: Record; compilerManifest?: PlayCompilerManifest; publish?: boolean; ownerType?: 'org' | 'deepline'; scope?: 'org' | 'system'; userId?: string; }): Promise<{ success?: boolean; name?: string; artifactStorageKey: string; artifactMetadata?: Record | null; staticPipeline?: unknown; definitionId?: string | null; revisionId?: string | null; version?: number | null; liveVersion?: number | null; triggerMetadata?: unknown; triggerBindings?: unknown; }>; /** * Register multiple bundled play artifacts in one request. * * Used by packaging and prebuilt publication flows. Each artifact is compiled * first when a compiler manifest is not already supplied. */ registerPlayArtifacts(artifacts: Array<{ name: string; sourceCode: string; sourceFiles?: Record; description?: string; artifact: Record; 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 | null; staticPipeline?: unknown; definitionId?: string | null; revisionId?: string | null; version?: number | null; liveVersion?: number | null; triggerMetadata?: unknown; triggerBindings?: unknown; }>; }>; /** * Compile 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. */ compilePlayManifest(input: { name: string; sourceCode: string; sourceFiles?: Record; artifact: Record; importedPlayDependencies?: PlayCompilerManifest[]; }): Promise; /** * Check a bundled play artifact against the server's current play compiler. * * Unlike {@link registerPlayArtifact}, this does not store the artifact, * publish a revision, or start a run. It is the authoritative cloud validation * path used by `deepline plays check`. */ checkPlayArtifact(input: { name?: string; sourceCode: string; sourceFiles?: Record; description?: string; artifact: Record; /** Which exported play in `sourceCode` this artifact is, when the file * exports more than one. Omit for the default export. */ exportName?: string | null; integrationMode?: 'live' | 'eval_stub' | 'fixture'; /** * Sibling plays from the same local bundle graph. Lets the server splice * unpublished local children into the checked plan and enforce the * row-scoped batch rule (ADR 0013). */ importedPlays?: Array<{ playName?: string | null; sourceCode: string; sourcePath?: string | null; }>; }): Promise; /** * Compile 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. */ compileEnrichPlan(input: { plan_args?: string[]; config?: unknown; native_play_materialization?: 'macro' | 'inline_prebuilt'; }): Promise<{ config: EnrichCompiledConfig; }>; /** * Register 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. */ startPlayRunFromBundle(input: { name: string; sourceCode: string; sourceFiles?: Record; description?: string; artifact: Record; compilerManifest?: PlayCompilerManifest; input?: Record; inputFile?: PlayStagedFileRef | null; packagedFiles?: PlayStagedFileRef[]; force?: boolean; forceToolRefresh?: boolean; }): Promise; /** * Register a bundled play artifact and start a run from the live revision. * * Convenience wrapper around {@link registerPlayArtifact} plus * {@link startPlayRun}. This is the canonical file-backed path used by wrappers. * The returned id can be passed to {@link getPlayStatus} to retrieve the same * durable `{ result }` object that the CLI prints after `--watch` completes. * * @param code - Source string fallback; the bundled artifact should be passed in `options.artifact` * @param csvPath - Path to input CSV file, or `null` * @param name - Play name (extracted from source if omitted) * @param options - Additional submission options * @returns Workflow metadata with `workflowId` * * @example * ```typescript * const started = await client.submitPlay( * originalSource, * './leads.csv', * 'bulk-enrich', * { artifact: bundledArtifact, input: { limit: 100 } }, * ); * ``` */ submitPlay(code: string, csvPath: string | null, name?: string, options?: { sourceCode?: string; sourceFiles?: Record; description?: string; artifact?: Record; compilerManifest?: PlayCompilerManifest; input?: Record; inputFile?: PlayStagedFileRef | null; packagedFiles?: PlayStagedFileRef[]; force?: boolean; forceToolRefresh?: boolean; }): Promise; /** * Upload files to the staging area for use in play runs. * * Internal/advanced primitive used by packaging flows. Public callers should * prefer the CLI, {@link submitPlay}, or {@link runPlay}. * * Staged files are referenced by their returned {@link PlayStagedFileRef} * in subsequent {@link startPlayRun} calls via `inputFile` or `packagedFiles`. * * @param files - Array of files to stage (base64-encoded content) * @returns Array of staged file references * * @example * ```typescript * const staged = await client.stagePlayFiles([{ * logicalPath: 'data/leads.csv', * contentBase64: Buffer.from(csvContent).toString('base64'), * contentHash: sha256(csvContent), * contentType: 'text/csv', * bytes: csvContent.length, * }]); * // Use staged[0] as inputFile in startPlayRun * ``` */ stagePlayFiles(files: Array<{ logicalPath: string; contentBase64: string; contentHash: string; contentType: string; bytes: number; }>): Promise; /** * Mint short-lived presigned upload targets for staged play files. * * Internal primitive used by {@link stagePlayFiles}. The server returns an * already-staged ref (no upload needed) for content-addressed files it * already holds, or a presigned PUT URL the caller uploads the body to. */ mintStagedPlayFileUploads(files: Array<{ logicalPath: string; contentHash: string; contentType: string; bytes: number; }>): Promise; private stagePlayFilesViaMultipart; /** * Resolve 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. */ resolveStagedPlayFiles(files: Array<{ logicalPath: string; contentHash: string; contentType: string; bytes: number; }>): Promise<{ files: PlayStagedFileRef[]; missing: Array<{ logicalPath: string; contentHash: string; }>; }>; /** * Get the current status of a play execution. * * Internal/advanced primitive. Public callers should usually prefer * {@link runPlay}, {@link PlayJob.get}, or `deepline plays run --watch`. * * @param workflowId - Play-run id from {@link startPlayRun} * @returns Current status with progress logs and partial results * * @example * ```typescript * const status = await client.getPlayStatus('play-abc123'); * console.log(`Status: ${status.status}`); * console.log(`Logs: ${status.progress?.logs.length ?? 0} lines`); * ``` */ getPlayStatus(workflowId: string, options?: { billing?: boolean; full?: boolean; }): Promise; /** * Stream 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. */ streamPlayRunEvents(workflowId: string, options?: { signal?: AbortSignal; lastEventId?: string; mode?: 'cli' | 'ui'; }): AsyncGenerator; /** * Cancel a running play execution. * * Sends a stop request for the run. * * @param workflowId - Public Deepline play-run id to cancel * * @example * ```typescript * await client.cancelPlay('play-abc123'); * ``` */ cancelPlay(workflowId: string): Promise; /** * Stop a running play execution, including open HITL waits. * * @param workflowId - Public Deepline play-run id to stop * @param options.reason - Optional audit/debug reason */ stopPlay(workflowId: string, options?: { reason?: string; }): Promise; /** * List recent runs for a named play. * * Returns runs sorted by start time (newest first), including workflow IDs, * status, timestamps, and metadata. * * @param playName - The play name to query * @returns Array of run summaries (empty array if no runs exist) * * @example * ```typescript * const runs = await client.listPlayRuns('email-waterfall'); * for (const run of runs) { * console.log(`${run.workflowId}: ${run.status} (${run.executionTime})`); * } * ``` */ listPlayRuns(playName: string): Promise; /** List the org's workflows. `GET /api/v2/workflows`. */ listWorkflows(options?: { limit?: number; }): Promise<{ workflows: Array<{ id: string; name: string; status: string; current_published_version: number | null; }>; }>; /** * Fetch a single workflow (including its published-revision config — the * input to `compileWorkflowConfigToPlay`). `GET /api/v2/workflows/:id`. */ getWorkflow(id: string): Promise<{ workflow: { id: string; name: string; status: string; current_published_version: number | null; current_published_revision: { version: number; config: unknown; } | null; } | null; validation?: unknown; }>; /** Delete a workflow. `DELETE /api/v2/workflows/:id`. */ deleteWorkflow(id: string): Promise; /** Turn a workflow off. `POST /api/v2/workflows/:id/disable`. */ disableWorkflow(id: string): Promise; /** Turn a workflow back on. `POST /api/v2/workflows/:id/enable`. */ enableWorkflow(id: string): Promise; /** Create/update a workflow from config. `POST /api/v2/workflows/apply`. */ applyWorkflow(body: Record): Promise; /** Validate a workflow config without saving. `POST /api/v2/workflows/lint`. */ lintWorkflow(body: Record): Promise; /** Fetch live workflow request schemas. `GET /api/v2/workflows/schema`. */ getWorkflowSchema(subject?: string): Promise; /** Queue a workflow run. `POST /api/v2/workflows/call`. */ callWorkflow(body: Record): Promise; /** List a workflow's runs. `GET /api/v2/workflows/:id/runs`. */ listWorkflowRuns(id: string, options?: { limit?: number; }): Promise; /** Fetch one workflow run. `GET /api/v2/workflows/:id/runs/:runId`. */ getWorkflowRun(id: string, runId: string): Promise; /** Cancel a workflow run. `POST /api/v2/workflows/:id/runs/:runId/cancel`. */ cancelWorkflowRun(id: string, runId: string): Promise; /** * Get a run by id using the public runs resource model. * * This is the SDK equivalent of: * * ```bash * deepline runs get --json * ``` */ getRunStatus(runId: string, options?: RunsGetOptions): Promise; /** * List play runs using the public runs resource model. * * This is the SDK equivalent of: * * ```bash * deepline runs list --play --status failed --json * ``` */ listRuns(options: RunsListOptions): Promise; /** * Observe one run's live events. Uses the Convex Run Snapshot subscription * transport first (ADR-0008), then falls back to the canonical SSE stream * when the subscription transport or its optional client modules are not * available. Pass `fallback: 'none'` to receive * {@link RunObserveTransportUnavailableError} instead. */ observeRunEvents(runId: string, options?: { signal?: AbortSignal; onNotice?: (message: string) => void; fallback?: 'sse' | 'none'; }): AsyncGenerator; private streamPlayRunEventsUntilTerminal; /** * Tail one run through the subscription transport until terminal, then * return one durable REST status read (the final Run Response Package). */ private tailRunViaObserveTransport; /** * Read the canonical run stream until a terminal run status is observed. * * Tries the Convex Run Snapshot subscription transport first (ADR-0008); * when the server cannot serve it (grant endpoint missing/unconfigured or * Convex unreachable) it falls back — with one `onNotice` message — to the * support-window SSE stream below. * * Server stream windows are finite: they end cleanly at the function * ceiling even while the run keeps executing. A window that ends (cleanly * or via transient network error) without a terminal event triggers one * durable-status re-check followed by a backed-off reconnect, so long runs * tail to completion. Abort via `options.signal` to stop waiting. */ tailRun(runId: string, options?: RunsTailOptions): Promise; /** Get the exact original input retained for a run. This is intentionally separate from status. */ getRunInput(runId: string): Promise<{ runId: string; input: Record | unknown[]; bytes: number; sha256: string | null; replayedFromRunId: string | null; }>; /** Start a fresh run from a prior run's retained input and pinned revision. */ rerun(runId: string): Promise<{ runId: string; replayedFromRunId: string; revisionId: string | null; status: string; next: { inspect: string; input: string; }; }>; /** * Fetch persisted logs for a run using the public runs resource model. * * This is the SDK equivalent of: * * ```bash * deepline runs logs --limit 200 --json * ``` */ getRunLogs(runId: string, options?: RunsLogsOptions): Promise; /** * Export persisted runtime-sheet rows for a play dataset/table namespace. * * This is the SDK form of exporting `ctx.dataset(...).run()` output for a * specific play and optional run id. */ getPlaySheetRows(input: { playName: string; tableNamespace: string; runId?: string; limit?: number; offset?: number; rowMode?: 'output' | 'all'; }): Promise; /** * Stop a run by id using the public runs resource model. * * This is the SDK equivalent of: * * ```bash * deepline runs stop --reason "stale lock" --json * ``` */ stopRun(runId: string, options?: { reason?: string; }): Promise; /** * Stop every active run visible to the current workspace. * * This is the SDK equivalent of: * * ```bash * deepline runs stop-all --reason "stale lock" --json * ``` * * Use this when a failed parent run left child or waiting runs active and you * need to clear the workspace run-slot state without knowing each run id. */ stopAllRuns(options?: { reason?: string; }): Promise; /** * List callable plays visible to the workspace. * * Pass `origin: "prebuilt"` for Deepline-managed prebuilts or * `origin: "owned"` for org-owned plays. */ listPlays(options?: { origin?: 'prebuilt' | 'owned'; grep?: string; grepMode?: 'all' | 'any' | 'phrase'; categories?: string | string[]; includeToolCategories?: boolean; includeArchived?: boolean; }): Promise; /** Set whether an org-owned Play sorts before unpinned Plays. */ setPlayPinned(playName: string, pinned: boolean): Promise<{ name: string; pinned: boolean; }>; /** Read product-notification destinations, subscriptions, event catalog, and DLQ health. */ getNotificationSettings(): Promise; /** Start the Slack OAuth flow required by product notifications. */ connectNotificationSlack(options?: { successUrl?: string; failureUrl?: string; }): Promise<{ ok: boolean; redirect_url: string; }>; /** List Slack channels visible to the connected Deepline Slack app. */ listNotificationSlackChannels(query?: string): Promise<{ identity: { teamId: string; teamName?: string; }; channels: Array<{ id: string; name: string; isPrivate: boolean; }>; }>; /** Select a Slack channel or direct member used for product notifications. */ setNotificationSlack(destination: string | { memberId: string; }): Promise; /** Send one synchronous test ping and return Slack's delivery result. */ testNotificationSlack(): Promise<{ ok: boolean; deliveryId: string; state: string; message: string; }>; /** Disable Slack product notifications without deleting the OAuth connection. */ disableNotificationSlack(): Promise; /** Enable or disable event IDs from the server-provided notification catalog. */ setNotificationSubscriptions(eventTypes: string[], enabled: boolean): Promise; /** List exhausted deliveries. Dead-lettered messages never replay automatically. */ listNotificationDlq(limit?: number): Promise; /** Inspect one exhausted notification delivery. */ getNotificationDlqDelivery(deliveryId: string): Promise; /** Explicitly retry or archive one dead-lettered notification delivery. */ updateNotificationDlqDelivery(deliveryId: string, action: 'retry' | 'archive'): Promise; /** List the workspace's named notification rules. */ getNotifications(): Promise; /** List Slack channels available to an already-connected Slack integration. */ listNotificationChannels(query?: string): Promise<{ identity: { teamId: string; teamName?: string; }; channels: Array<{ id: string; name: string; isPrivate: boolean; }>; }>; /** Create a named notification routed through an existing provider integration. */ createNotification(input: CreateNotificationInput): Promise; /** Update a notification's target, event selection, or enabled state. */ updateNotification(notificationId: string, input: UpdateNotificationInput): Promise; /** Send a validation ping to one notification. */ testNotification(notificationId: string): Promise<{ ok: boolean; deliveryId: string; state: string; message: string; }>; /** Archive one notification without touching its provider integration. */ deleteNotification(notificationId: string): Promise<{ deleted: boolean; id: string; }>; /** * Search callable plays and return compact play descriptions. * * Prebuilt plays are preferred by default because they have maintained * contracts and stable run behavior. */ searchPlays(options: { query: string; compact?: boolean; scope?: 'prebuilt' | 'owned' | 'all'; }): Promise; /** * Get 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. * * @param name - Play name * @returns Complete play detail * * @example * ```typescript * const detail = await client.getPlay('email-waterfall'); * console.log(`Live: v${detail.play.currentPublishedVersion}`); * console.log(`Draft dirty: ${detail.play.isDraftDirty}`); * console.log(`Total runs: ${detail.play.runCount}`); * ``` */ getPlay(name: string, options?: { source?: 'working' | 'live' | `version:${number}`; }): Promise; /** * Get 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. */ describePlay(name: string, options?: { compact?: boolean; }): Promise; /** * Clear run history and durable sheet/result data for a play without deleting * the play definition or revisions. */ clearPlayHistory(name: string, request?: ClearPlayHistoryRequest): Promise; /** * List saved versions for a named play. * * Returns immutable revision snapshots newest-first, including the revision * id needed for exact-version runs and live-version switching. * * @param name - Play name * @returns Version list (newest first) */ listPlayVersions(name: string, options?: { full?: boolean; }): Promise; /** * Make 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. * * @param name - Play name * @param request - Optional explicit revision to make live * @returns Result with the new live version number * * @example * ```typescript * const result = await client.publishPlayVersion('email-waterfall'); * if (result.success) { * console.log(`Live v${result.liveVersion}`); * } * ``` */ publishPlayVersion(name: string, request?: PublishPlayVersionRequest): Promise; /** * Move an org-owned play to Trash. This disables its active triggers while * retaining its revisions and run history so it can be restored. Deepline * prebuilt plays are read-only. */ deletePlay(name: string): Promise; /** Restore an org-owned play that was previously moved to Trash. */ restorePlay(name: string): Promise; /** * Current share status for a play: the public page (if any), the published * copy, and the revision picker. Read-only. */ getSharePage(name: string, options?: { revisionId?: string; }): Promise; /** * Publish (or repoint) the play's public share page to a revision. Requires * `acknowledgedUnlisted: true` — the page is publicly viewable. Org-admin only. */ publishSharePage(name: string, request: PublishSharePageRequest): Promise; /** * Update share-page settings (SEO indexing, credit-cost / latency display) * without moving the published pointer. Org-admin only. */ updateSharePage(name: string, request: UpdateSharePageRequest): Promise; /** * Unshare: hard-delete the play's public page and its cards. Returns the * fresh status (now `share: null`). Org-admin only. Idempotent — a no-op when * the play was never published. */ unpublishSharePage(name: string): Promise; /** * Regenerate the LLM landing-page copy for a revision (defaults to the * published one). Org-admin only. */ regenerateSharePage(name: string, request?: { revisionId?: string; }): Promise; /** * Run 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`. * * @param code - Source string fallback; pass the bundled artifact in `options.artifact` * @param csvPath - Input CSV path, or `null` * @param name - Play name * @param options - Execution options * @returns Final execution result with success/failure, output, logs, and duration * * @example * ```typescript * const result = await client.runPlay(bundledCode, null, 'my-play', { * input: { domain: 'stripe.com' }, * onProgress: (status) => { * const logs = status.progress?.logs ?? []; * console.log(`[${status.status}] ${logs.length} log lines`); * }, * }); * * if (result.success) { * console.log('Output:', result.result); * } else { * console.error(`Failed after ${result.durationMs}ms:`, result.error); * } * ``` * * @example Cancellation * ```typescript * const controller = new AbortController(); * setTimeout(() => controller.abort(), 30_000); // 30s timeout * * const result = await client.runPlay(code, null, 'slow-play', { * signal: controller.signal, * }); * // result.success === false, result.error === 'Cancelled by user' * ``` */ runPlay(code: string, csvPath: string | null, name?: string, options?: { /** Called for each status snapshot emitted by the run stream. */ onProgress?: (status: PlayStatus) => void; /** Abort signal — triggers cancellation and immediate return. */ signal?: AbortSignal; /** Runtime input for the play function. */ input?: Record; sourceCode?: string; artifact?: Record; compilerManifest?: PlayCompilerManifest; inputFile?: PlayStagedFileRef | null; packagedFiles?: PlayStagedFileRef[]; /** Compatibility flag; active sibling runs are allowed. */ force?: boolean; /** Explicit cache-bypass flag for durable dataset and tool-call reuse. */ forceToolRefresh?: boolean; }): Promise; /** * Published plans plus the caller's active plan: prices, monthly grant * credits, rollover policy, and which plans are open for subscription. * Prefer `client.billing.plans()`. * * @returns Snake_case catalog from `GET /api/v2/billing/catalog/current` */ getBillingPlans(): Promise; /** * Charge the saved payment method and add Deepline credits to the active * workspace. Prefer `client.billing.topUp(...)`. * * @throws {@link DeeplineError} with `statusCode: 409` when checkout is * required because the workspace has no saved payment method or the card * requires confirmation. */ topUpBillingBalance(options: { credits: number; idempotencyKey?: string; }): Promise; /** * Subscription state for the active workspace: active plan, whether a * Stripe subscription backs it, renewal/cancellation facts, and remaining * Deepline credit pools. Prefer `client.billing.subscription.status()`. * * @returns Snake_case subscription status from `GET /api/v2/billing/subscription/status` */ getBillingSubscriptionStatus(): Promise; /** * Schedule subscription cancellation at period end, or reverse a pending * cancellation with `{ undo: true }`. The customer keeps the cycle they * paid for and every remaining credit — cancellation never claws back * credits. Prefer `client.billing.subscription.cancel(...)`. * * @throws {@link DeeplineError} with `statusCode: 409` when the workspace * has no active subscription, and `statusCode: 502` when Stripe rejects * the update (the server message is preserved). */ cancelBillingSubscription(options?: { undo?: boolean; }): Promise; /** * Customer-facing billing history: subscription invoices plus one-time * credit purchase receipts, newest first, with Stripe-hosted links. * Prefer `client.billing.invoices.list(...)`. * * @param options.limit - Maximum entries to return (server clamps to 1–100, default 24). */ listBillingInvoices(options?: { limit?: number; }): Promise; /** List the reviewed target plans and whether new acquisition is enabled. */ getTargetBillingPlans(): Promise; /** Read the workspace's normalized target plan, payment, and balance state. */ getTargetBillingStatus(): Promise; /** * Purchase target-billing credits through the durable commercial operation * flow. The caller supplies an idempotency key for safe retries. */ purchaseTargetBillingCredits(options: { credits: number; idempotencyKey: string; }): Promise; /** * Start, change, cancel, or restore a target plan through one idempotent * commercial operation. */ transitionTargetBillingPlan(options: TargetBillingPlanTransitionOptions): Promise; /** Create a Stripe-hosted portal session for payment recovery and invoices. */ createTargetBillingPortalSession(): Promise<{ url: string; }>; /** * Whether the current workspace can use Deepline Monitors. Reachable without * monitor access; a denial is a normal 200 body, not a 403. Prefer * `client.monitors.status()`. */ getMonitorsAccess(): Promise; /** * The deployable monitor tools catalog. Pass a tool id (positional or * `{ tool }`) to describe one tool's full payload/stream contract, or no tool * id for the compact inventory. Prefer `client.monitors.available(...)`. */ getMonitorsAvailable(toolIdOrOptions?: string | (MonitorsAvailableOptions & { tool?: string; }), maybeOptions?: MonitorsAvailableOptions): Promise; /** Validate a monitor definition without deploying it. Prefer `client.monitors.check(...)`. */ checkMonitor(definition: MonitorDefinition): Promise; /** * Deploy a monitor from a definition. `dryRun` validates via the check * endpoint and returns the plan without deploying. Prefer * `client.monitors.deploy(...)`. */ deployMonitor(definition: MonitorDefinition, options?: { dryRun?: boolean; }): Promise; /** List deployed monitors. Prefer `client.monitors.list(...)`. */ listMonitors(options?: MonitorsListOptions): Promise; /** Fetch one deployed monitor by public key. Prefer `client.monitors.get(...)`. */ getMonitor(key: string): Promise; testMonitorWebhook(key: string, payload: Record, options?: { validationOnly?: boolean; dispatch?: boolean; }): Promise; setupMonitor(tool: string, payload: Record): Promise>; validateMonitor(key: string): Promise; /** Published plays depending on one monitor. Prefer `client.monitors.dependents(...)`. */ getMonitorDependents(key: string): Promise; /** Update a deployed monitor by public key. Prefer `client.monitors.update(...)`. */ updateMonitor(key: string, patch: Record): Promise; /** Delete a deployed monitor and its upstream provider resource. `dryRun` returns the delete plan. Prefer `client.monitors.delete(...)`. */ deleteMonitor(key: string, options?: { dryRun?: boolean; }): Promise; /** * Reactivate a disabled monitor. `dryRun` returns the reactivation cost. * Prefer `client.monitors.reactivate(...)`. */ reactivateMonitor(key: string, options?: { dryRun?: boolean; }): Promise; /** * Check API connectivity and server health. * * @returns Health status with API version * * @example * ```typescript * const health = await client.health(); * console.log(`API: ${health.status} (${health.version})`); * // { status: "ok", version: "v2" } * ``` */ health(): Promise<{ status: string; version?: string; status_banner?: { message: string; updatedAt: number; }; }>; } /** * Bootstrap failure: this server/deployment cannot serve the subscription * transport. Callers fall back to the support-window SSE stream (ADR-0008). */ declare class RunObserveTransportUnavailableError extends Error { readonly reason: string; constructor(message: string, reason: string); } declare const SDK_VERSION: string; /** @deprecated Transitional wire id for pre-major-header SDKs only. */ declare const SDK_API_CONTRACT: string; /** * 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. * * @example * ```typescript * import { AuthError } from 'deepline'; * * try { * await client.listTools(); * } catch (err) { * if (err instanceof AuthError) { * // Redirect user to auth flow * } * } * ``` * * @sdkReference errors 090 */ declare class AuthError extends DeeplineError { /** Constructed by the SDK when Deepline rejects the caller's credentials. */ constructor(message?: string); } /** * 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 {@link RateLimitError.retryAfterMs} to implement your own backoff if needed. * * @example * ```typescript * import { RateLimitError } from 'deepline'; * * try { * await client.executeTool('dropleads_search_people', { query: 'cto' }); * } catch (err) { * if (err instanceof RateLimitError) { * console.log(`Retry after ${err.retryAfterMs}ms`); * await sleep(err.retryAfterMs); * // retry... * } * } * ``` * * @sdkReference errors 100 */ declare class RateLimitError extends DeeplineError { /** Milliseconds to wait before retrying, from the `Retry-After` response header. Defaults to 5000. */ retryAfterMs: number; /** Constructed by the SDK after exhausting HTTP-level rate-limit retries. */ constructor(retryAfterMs?: number, message?: string); } /** * 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. * * @sdkReference errors 110 */ declare class ToolRateLimitError extends RateLimitError { /** Public tool id passed to `tools.execute`. */ readonly toolId: string; /** Provider responsible for the operation, or `null`. */ readonly provider: string | null; /** Provider operation name, or `null`. */ readonly operation: string | null; /** Stable machine-readable failure code when one exists. */ readonly code: string | undefined; /** Boundary responsible for the failure. */ readonly origin: ToolExecutionError['origin']; /** Stable reason family for policy and diagnostics. */ readonly category: ToolExecutionError['category']; /** Whether repeating the same semantic call is delivery-safe. */ readonly retryable: boolean; /** Provider or Deepline request id, or `null`. */ readonly requestId: string | null; /** Network failure kind, or `null` for non-network failures. */ readonly networkKind: ToolExecutionError['networkKind']; /** Network boundary that failed, or `null` for non-network failures. */ readonly networkScope: ToolExecutionError['networkScope']; /** Constructed by the SDK after a structured tool HTTP 429. */ constructor(message: string, options: ToolExecutionErrorOptions); } /** * 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). * * @example * ```typescript * import { ConfigError } from 'deepline'; * * try { * const client = new DeeplineClient(); * } catch (err) { * if (err instanceof ConfigError) { * console.error('Run: deepline auth register'); * } * } * ``` * * @sdkReference errors 120 */ declare class ConfigError extends DeeplineError { /** Construct a local SDK configuration failure. */ constructor(message: string); } /** Production API base URL. */ declare const PROD_URL = "https://code.deepline.com"; /** * Resolve SDK configuration from the public SDK CLI env contract. */ declare function resolveConfig(options?: DeeplineClientOptions): ResolvedConfig; type PlayCallExecution = PlayAuthoringCallExecution; type PlayCallOptions = PlayAuthoringCallOptions; type RuntimeStepOptions = PlayAuthoringRuntimeStepOptions; type FetchOptions = PlayAuthoringFetchOptions; type PlayFetchResponse = PlayAuthoringFetchResponse; /** * Optional Play configuration, including triggers and runtime limits. * * A play can be triggered three ways, declared as the third argument to * {@link definePlay}: * - `webhook` — an inbound HTTP call (with optional legacy HMAC or Standard * Webhooks signature verification); * - `cron` — a schedule; or * - `sqlListeners` — a **monitor**: the play runs whenever a monitor writes a new * row to its output stream. This is how you build a play "on top of" a monitor * (e.g. run enrichment every time a watched company posts a new job). Each * listener binds to a monitor tool id + one of its output stream keys (see * `deepline monitors available ` for a tool's streams and row columns). * The changed row is delivered to the handler as the listener event's `after`. * * The default Play runtime is 30 minutes. For bounded long-running batches, add * `runtime: { timeout: '90m', size: 'standard' }`; duration values are whole minutes or hours, up to `4h`. * It differs from `ctx.tools.execute({ timeoutMs })`, which limits one provider call. * * @example Webhook with HMAC verification * ```typescript * definePlay('webhook-handler', handler, { * webhook: { * hmac: { * algorithm: 'sha256', * header: 'X-Hub-Signature-256', * secretEnv: 'WEBHOOK_SECRET', * }, * }, * }); * ``` * * @example Svix / Standard Webhooks verification with Deepline Secrets * ```typescript * definePlay('visitor-webhook', handler, { * webhook: { * auth: { * type: 'standard-webhooks', * headerFamily: 'svix', * signingSecrets: ['VECTOR_WEBHOOK_SECRET'], * }, * }, * }); * ``` * * @example Cron schedule * ```typescript * definePlay('nightly-sync', handler, { * cron: { schedule: '0 2 * * *', timezone: 'UTC' }, * }); * ``` * * @example Monitor-triggered (run a play on a monitor's output) * ```typescript * definePlay('on-new-job-opening', handler, { * sqlListeners: [ * { * id: 'jobs', * tool: 'deepline_native.company_radar', * stream: 'company_job_openings', * operations: ['INSERT'], * }, * ], * }); * ``` * * @sdkReference runtime 030 */ type PlayBindings = PlayAuthoringBindings; type SqlListenerOperation = PlaySqlListenerOperation; type SqlListenerDeclaration = PlaySqlListenerDeclaration; type SqlListenerEvent> = PlaySqlListenerEvent; /** @deprecated Pass a SQL string directly to ctx.customerDb.query. */ type SqlQuery = PlaySqlQuery; /** * 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 receipt attachment. Provider * call reuse is keyed by play, tool, semantic input, auth scope, provider action * version, and cache policy. * * @sdkReference runtime 160 */ type ToolExecutionRequest = PlayToolExecutionRequest; type StepResolver = PlayAuthoringStepResolver; /** * Input object passed to an object-column `run` resolver. * * @sdkReference runtime 090 */ type DatasetColumnRunInput = PlayAuthoringDatasetColumnRunInput; /** * Object-column form for `.withColumn(...)`. * * Use this when a column needs `runIf` or typed `previousCell`. * * @sdkReference runtime 100 */ type DatasetColumnDefinition = PlayAuthoringDatasetColumnDefinition; type ConditionalStepResolver = PlayAuthoringConditionalStepResolver; /** * Options for row-level `.withColumn(...)` and `steps().step(...)` entries. * * @sdkReference runtime 110 */ type StepOptions = PlayAuthoringStepOptions; /** Explicitly mark a step program as a provider fallback waterfall. */ type StepProgramOptions = PlayAuthoringStepProgramOptions; type StepProgram = PlayAuthoringStepProgram; type StepProgramResolver = PlayAuthoringStepProgramResolver; type PlayStepProgramStep = PlayAuthoringStepProgramStep; type ColumnResolver = PlayAuthoringColumnResolver; /** * Builder returned by `ctx.dataset(...)` for row-level durable columns. * * @sdkReference runtime 070 .dataset(...).withColumn(name, resolver).run(options) */ type DatasetBuilder = PlayAuthoringDatasetBuilder; /** * Runtime file-like input. At runtime this is the staged file path/reference * string. The type parameter carries static metadata for describe/CLI tooling. */ type FileInput = PlayAuthoringFileInput; /** * CSV file input whose rows are described by `TRow`. * * The CLI should expose this as the field name from the play input object, * stage local paths passed to that flag, and use `TRow` for row-contract * discovery. */ type CsvInput> = PlayAuthoringCsvInput; type ColumnMap = PlayAuthoringColumnMap; /** * Options for loading a staged CSV with `ctx.csv(...)`. * * @sdkReference runtime 050 */ type CsvOptions = PlayAuthoringCsvOptions; /** * Runtime context available inside a play function. * * Provides methods for calling tools, processing data, and emitting logs. * This context is injected by the Temporal worker — you never construct it directly. * * @example * ```typescript * definePlay('example', async (ctx, input: { domain: string; csv: string }) => { * // Call a tool * const company = await ctx.tools.execute({ * id: 'company_search', * tool: 'test_company_search', * input: { domain: input.domain }, * description: 'Look up company details by domain.', * }); * * // Fan-out: process items with named columns * const enriched = await ctx * .dataset('companies', [{ domain: 'a.com' }, { domain: 'b.com' }]) * .withColumn('company', (row, rowCtx) => * rowCtx.tools.execute({ * id: 'company_search', * tool: 'test_company_search', * input: { domain: row.domain }, * description: 'Look up company details by domain.', * })) * .run({ description: 'Look up company details.' }); * * // Load CSV data from a submitted play input field. * const leads = await ctx.csv(input.csv); * * // Emit a log line (visible in `play tail`) * ctx.log(`Loaded ${await leads.count()} leads`); * * // Pause execution * await ctx.sleep(1000); * * // Access submitted input through the handler's second argument. * ctx.log(`Running for ${input.domain}`); * * return { company, enriched }; * }); * ``` */ type DeeplinePlayRuntimeContext = PlayAuthoringRuntimeContext; /** * 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 plays 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. * * @typeParam TOutput - The play's return type * * @example * ```typescript * const job: PlayJob = await ctx.play('my-play').run({ domain: 'stripe.com' }); * * // Poll status * const status = await job.status(); * console.log(status.status); // 'running' * * // Stream logs until completion * const finalStatus = await job.tail({ * onLog: (line) => console.log(`[play] ${line}`), * }); * * // Or just wait for the result * const output = await job.get(); * * // Cancel if needed * await job.cancel(); * ``` * * @sdkReference plays 030 */ interface PlayJob { /** Temporal workflow ID for this execution. */ id: string; /** Get the current execution status (single poll). */ status(): Promise; /** * Stream logs and wait for completion. * * Polls until the play reaches a terminal state, invoking `onLog` for * each new log line. Returns the final status. * * @param options.intervalMs - Poll interval in ms. Default: `500`. * @param options.onLog - Callback for each log line. Default: `console.log`. */ tail(options?: { intervalMs?: number; onLog?: (line: string) => void; }): Promise; /** * Wait for the play to complete and return its output. * * Polls until terminal state. Throws {@link DeeplineError} if the play * fails, is cancelled, or times out. * * @param options.intervalMs - Poll interval in ms. Default: `500`. * @returns The play's return value * @throws {@link DeeplineError} if the play did not complete successfully */ get(options?: { intervalMs?: number; }): Promise; /** Cancel this play execution. */ cancel(): Promise; /** Deep-stop this play execution, including open HITL waits. */ stop(options?: { reason?: string; }): Promise; } /** * Handle to a named play for remote lifecycle operations. * * Returned by {@link DeeplineContext.play} and attached to {@link DefinedPlay}. * Provides methods to run, inspect, list runs, and publish a play by name. * * @typeParam TInput - The play's input type * @typeParam TOutput - The play's return type * * @example * ```typescript * const ctx = await Deepline.connect(); * const play = ctx.play<{ domain: string }, Company>('company-lookup'); * * // Get play definition * const detail = await play.get(); * console.log(`Live: v${detail.play.currentPublishedVersion}`); * * // Run and wait * const result = await play.runSync({ domain: 'stripe.com' }); * * // Run async * const job = await play.run({ domain: 'stripe.com' }); * const output = await job.get(); * * // List recent runs * const runs = await play.runs(); * * // List saved versions * const versions = await play.versions(); * * // Publish the current draft * await play.publish(); * ``` * * @sdkReference plays 020 */ interface DeeplineNamedPlay, TOutput = unknown> { /** The play's name. */ readonly name: string; /** Fetch the full play definition with revision history and run stats. */ get(): Promise; /** List recent runs for this play. */ runs(): Promise; /** List saved versions for this play (newest first). */ versions(): Promise; /** Publish a play revision. Defaults to the current working revision. */ publish(options?: { revisionId?: string; }): Promise; /** * Clear run history and durable sheet/result data for this play while keeping * the play definition and revisions. */ clearHistory(options?: { tableNamespaces?: string[]; }): Promise; /** * Start a new run of this play. Returns a {@link PlayJob} for monitoring. * * @param input - Runtime input passed to the play function */ run(input: TInput, options?: { revisionId?: string; profile?: string; }): Promise>; /** * Run this play and wait for completion. * * Equivalent to `play.run(input).then(job => job.get())`. * * @param input - Runtime input * @returns The play's return value */ runSync(input: TInput, options?: { revisionId?: string; profile?: string; }): Promise; } /** * Tool/provider operations available from a connected {@link 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. * * @sdkReference tools 010 DeeplineContext.tools */ type DeeplineToolsNamespace = { /** List all available provider-backed tools. */ list(): Promise; /** Get detailed metadata for one provider-backed tool. */ get(toolId: string): Promise; /** * Execute a provider-backed tool from a regular SDK process. * * For durable play code, prefer `ctx.tools.execute(...)` because the play * runtime records the call under a stable id. */ execute(toolId: string, input: Record): Promise; }; /** * Named-play discovery and handle operations from a connected {@link DeeplineContext}. * * @sdkReference plays 010 DeeplineContext.plays */ type DeeplinePlaysNamespace = { /** List saved and callable plays visible to the current workspace. */ list(): Promise; /** Return a typed handle for a named, saved, shared, or prebuilt play. */ get, TOutput = unknown>(name: string): DeeplineNamedPlay; }; type PrebuiltPlayRef = { readonly playName: string; readonly name: string; }; type PlayReferenceLike = PlayAuthoringReferenceLike; type PlayReturnObject = PlayReturnObject$1; type PlayInputContract = PlayAuthoringInputContract; /** * Object-form play definition accepted by `definePlay(config)`. * * Use this form when the input contract should be explicit at definition time * through `defineInput(schema)`, or when configuration reads clearer as one * object. The shorthand `definePlay(name, fn, bindings?)` is equivalent for * simple file-backed plays. * * @sdkReference runtime 020 */ type DefinePlayConfig = PlayAuthoringDefineConfig; declare function steps(options?: StepProgramOptions): StepProgram; declare function runIf(predicate: (row: Row, index: number) => boolean | Promise, resolver: StepResolver): ConditionalStepResolver; /** * A defined play: both a callable function and a named play handle. * * Created by {@link definePlay}. Can be: * 1. Called directly as a function (for server-side Temporal execution) * 2. Used as a {@link DeeplineNamedPlay} for remote lifecycle operations * * @typeParam TInput - The play's input type * @typeParam TOutput - The play's return type * * @example * ```typescript * import { definePlay } from 'deepline'; * * const myPlay = definePlay('my-play', async (ctx, input: { domain: string }) => { * return await ctx.tools.execute({ * id: 'company_search', * tool: 'test_company_search', * input: { domain: input.domain }, * description: 'Look up company details by domain.', * }); * }); * * // Type is: DefinedPlay<{ domain: string }, unknown> * * // Use as named play handle: * const detail = await myPlay.get(); * const result = await myPlay.runSync({ domain: 'stripe.com' }); * * // Access metadata: * console.log(myPlay.playName); // "my-play" * console.log(myPlay.bindings); // undefined (no cron/webhook) * ``` */ type DefinedPlay = PlayAuthoringDefinedPlay>; type PlayMetadata = { name: string; description?: string; bindings?: PlayBindings; inputSchema?: Record; billing?: PlayBindings['billing']; runtime?: PlayBindings['runtime']; compatibility?: PlayBindings['compatibility']; }; /** * High-level SDK context with tool shortcuts and play handles. * * Created by {@link Deepline.connect}. Wraps a {@link DeeplineClient} with * a friendlier API for common operations. * * @example * ```typescript * const deepline = await Deepline.connect(); * * // Tools * const tools = await deepline.tools.list(); * const result = await deepline.tools.execute('test_company_search', { domain: 'stripe.com' }); * * // Plays * const job = await deepline.play('email-waterfall').run({ domain: 'stripe.com' }); * const output = await job.get(); * ``` * * @sdkReference entrypoints 020 */ declare class DeeplineContext { private readonly client; /** * Create a high-level SDK context. * * Most callers should use {@link Deepline.connect}; direct construction is * equivalent when you already have explicit client options. * * @param options - Optional SDK client configuration. */ constructor(options?: DeeplineClientOptions); /** * Tool operations namespace. * * @example * ```typescript * const tools = await deepline.tools.list(); * const meta = await deepline.tools.get('dropleads_search_people'); * const companyLookup = await deepline.tools.execute('test_company_search', { domain: 'stripe.com' }); * const company = companyLookup.toolResponse.raw; * ``` */ get tools(): DeeplineToolsNamespace; /** * Play discovery and named-play handles. * * Use `plays.list()` for discovery and `plays.get(name)` when you prefer a * namespace spelling over `ctx.play(name)`. */ get plays(): DeeplinePlaysNamespace; /** * Convenience references for Deepline-managed prebuilt plays. * * Known prebuilts are exposed by camel-cased aliases. Any other property is * converted into `prebuilt/` so callers can pass the reference to * `ctx.runPlay(...)`. */ get prebuilt(): Record; /** * Get a named play handle for remote lifecycle operations. * * @typeParam TInput - Expected input type * @typeParam TOutput - Expected output type * @param name - Play name (as registered on the server) * @returns Named play handle with run, versions, get, publish, etc. * * @example * ```typescript * const play = ctx.play<{ domain: string }>('email-waterfall'); * const job = await play.run({ domain: 'stripe.com' }); * const result = await job.get(); * ``` */ play, TOutput = unknown>(name: string): DeeplineNamedPlay; /** * Run a named or prebuilt play and wait for its output. * * This is the high-level SDK equivalent of `ctx.play(name).runSync(input)`. * Inside a play runtime, prefer the in-play `ctx.runPlay(key, playRef, input, * options)` form so the child run is checkpointed under a stable key. * * @param playOrRef - Play name or prebuilt/reference object. * @param input - JSON input passed to the play. * @returns Completed play output. */ runPlay, TOutput = unknown>(playOrRef: string | PlayReferenceLike, input: TInput): Promise; } /** * Static entry point for the Deepline SDK. * * @example * ```typescript * import { Deepline } from 'deepline'; * * const deepline = await Deepline.connect(); * const tools = await deepline.tools.list(); * const result = await deepline.tools.execute('test_company_search', { domain: 'stripe.com' }); * ``` * * @sdkReference entrypoints 010 */ declare class Deepline { /** * Create a connected SDK context. * * Resolves configuration from options, environment variables, and CLI config * files. See {@link resolveConfig} for the resolution order. * * @param options - Optional overrides for API key, base URL, etc. * @returns Ready-to-use SDK context * @throws {@link ConfigError} if no API key can be resolved * * @example * ```typescript * // Auto-config (uses env vars / CLI auth): * const ctx = await Deepline.connect(); * * // Explicit config: * const ctx2 = await Deepline.connect({ * apiKey: 'dl_test_...', * baseUrl: 'http://localhost:3000', * }); * ``` */ static connect(options?: DeeplineClientOptions): Promise; } declare function defineInput(schema: Record): PlayInputContract; /** * 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. * * @typeParam TInput - The input type accepted by the play * @typeParam TOutput - The return type of the play * @param config - Object-form play config. * @param name - Play name. * @param fn - Play function. * @param bindings - Play configuration, including runtime limits and triggers. * @returns A {@link DefinedPlay} that is both callable and has lifecycle methods * * @example Basic play * ```typescript * import { definePlay } from 'deepline'; * * export default definePlay('company-lookup', async (ctx, input: { domain: string }) => { * ctx.log(`Searching for ${input.domain}`); * const company = await ctx.tools.execute({ * id: 'company_search', * tool: 'test_company_search', * input: { domain: input.domain }, * description: 'Look up company details by domain.', * }); * return company; * }); * ``` * * @example CSV processing play * ```typescript * export default definePlay('bulk-enrich', async (ctx, input: { csv: string }) => { * const leads = await ctx.csv(input.csv); * ctx.log(`Processing ${await leads.count()} rows`); * const results = await ctx * .dataset('companies', leads) * .withColumn('company', (row, ctx) => * ctx.tools.execute({ * id: 'company_search', * tool: 'test_company_search', * input: { domain: row.domain }, * description: 'Look up company details by domain.', * })) * .run({ description: 'Enrich lead companies.' }); * return results; * }); * ``` * * @example With cron binding * ```typescript * export default definePlay('daily-report', async (ctx) => { * const data = await ctx.tools.execute({ * id: 'crm_export', * tool: 'crm_export', * input: { since: 'yesterday' }, * description: 'Export yesterday CRM records.', * }); * return data; * }, { * cron: { schedule: '0 9 * * *', timezone: 'America/New_York' }, * }); * ``` * * @example Programmatic lifecycle * ```typescript * const myPlay = definePlay('my-play', handler); * * // Get play definition: * const detail = await myPlay.get(); * * // Run remotely: * const result = await myPlay.runSync({ domain: 'stripe.com' }); * * // Make the current draft live: * await myPlay.publish(); * ``` */ declare function definePlay(config: DefinePlayConfig): DefinedPlay; /** * Define a play with a name and function. * * @param name - Play name. * @param fn - Play function. * @param bindings - Play configuration, including runtime limits and triggers. * @returns Play handle. */ declare function definePlay(name: string, fn: (ctx: DeeplinePlayRuntimeContext, input: TInput) => Promise, bindings?: PlayBindings): DefinedPlay; /** * Alias for {@link definePlay}. Workflows and plays share the same public * Deepline SDK contract; the selected execution profile decides whether the * run is backed by local Node, Temporal/Daytona, or Cloudflare Dynamic * Workflows. */ declare const defineWorkflow: typeof definePlay; /** * Extract play metadata from a value that may be a defined play. * * Used internally by the CLI and bundler to detect `definePlay()` exports * and extract the play name and bindings. * * @param value - Any value (typically a module's default export) * @returns Play metadata if the value is a defined play, `null` otherwise * * @example * ```typescript * import { getDefinedPlayMetadata } from 'deepline'; * * const mod = await import('./my-play.play.ts'); * const meta = getDefinedPlayMetadata(mod.default); * if (meta) { * console.log(`Play name: ${meta.name}`); * console.log(`Bindings:`, meta.bindings); * } * ``` */ declare function getDefinedPlayMetadata(value: unknown): PlayMetadata | null; /** * Result of converting a tool response to a list of records. * * @example * ```typescript * const conversion = tryConvertToList(toolResponse, { * listExtractorPaths: ['people', 'output.body'], * }); * if (conversion) { * console.log(`Found ${conversion.rows.length} rows via ${conversion.strategy}`); * console.log(`Source path: ${conversion.sourcePath}`); * } * ``` */ type ListConversionResult = { /** Normalized array of record objects. Scalars are wrapped as `{ value: }`. */ rows: Array>; /** * How the list was found: * - `'configured_paths'` — matched one of the `listExtractorPaths` * - `'auto_detected'` — found via recursive DFS (longest array wins) */ strategy: 'configured_paths' | 'auto_detected'; /** Dotted path to where the list was found (e.g. `"output.body"`, `"people"`). */ sourcePath: string | null; }; type CsvOutputArtifact = { path: string; rowCount: number; columns: string[]; preview: string; }; type Scalar = string | number | boolean | null; /** * Extract a list of records from a tool response. * * Handles the common problem of tools returning data in varied shapes. * First tries configured `listExtractorPaths` (from tool metadata), then * falls back to automatic detection via recursive DFS. * * ## Extraction strategy * * 1. **Configured paths** — If `listExtractorPaths` is provided, each path is * tried against multiple candidate roots (raw payload, `.output.body`, legacy `.result`, legacy `.result.data`). * First match wins. * * 2. **Auto-detection** — If no configured path matches, recursively searches * the response for the largest array of objects (up to depth 5). * * @param payload - Raw tool response * @param options - Optional extraction configuration * @returns Extracted list with metadata, or `null` if no list found * * @example Using configured paths (from tool metadata) * ```typescript * const meta = await client.getTool('dropleads_search_people'); * const result = await client.executeTool('dropleads_search_people', { query: 'cto' }); * * const list = tryConvertToList(result, { * listExtractorPaths: meta.listExtractorPaths, * }); * if (list) { * console.log(`${list.rows.length} people found via ${list.strategy}`); * // Write to CSV * const csv = writeCsvOutputFile(list.rows, 'apollo-people'); * console.log(`Saved to ${csv.path}`); * } * ``` * * @example Auto-detection (no configured paths) * ```typescript * const result = await client.executeTool('some_tool', { query: 'test' }); * const list = tryConvertToList(result); * // Finds the largest array of objects anywhere in the response * ``` */ declare function tryConvertToList(payload: unknown, options?: { listExtractorPaths?: string[]; }): ListConversionResult | null; /** * Write a JSON payload to a timestamped file. * * Output location: `~/.local/share/deepline/data/{stem}_{timestamp}.json` * * @param payload - Any JSON-serializable value * @param stem - Filename prefix (e.g. tool ID or play name) * @returns Absolute path to the written file * * @example * ```typescript * const result = await client.executeTool('test_company_search', { domain: 'stripe.com' }); * const path = writeJsonOutputFile(result, 'test_company_search'); * console.log(`Saved to ${path}`); * // ~/.local/share/deepline/data/test_company_search_1713456789000.json * ``` */ declare function writeJsonOutputFile(payload: unknown, stem: string): string; /** * Write an array of records to a CSV file. * * Columns are ordered by first appearance across all rows. Cells containing * commas, quotes, or newlines are properly escaped. Objects and arrays are * JSON-serialized. * * Output location: `~/.local/share/deepline/data/{stem}_{timestamp}.csv` * * @param rows - Array of record objects * @param stem - Filename prefix * @returns File metadata including path, row count, columns, and a 5×5 preview * * @example * ```typescript * const list = tryConvertToList(toolResponse); * if (list) { * const csv = writeCsvOutputFile(list.rows, 'search-results'); * console.log(`Wrote ${csv.rowCount} rows, ${csv.columns.length} columns`); * console.log(`File: ${csv.path}`); * console.log(`Preview:\n${csv.preview}`); * } * ``` */ declare function writeCsvOutputFile(rows: Array>, stem: string, options?: { outPath?: string; }): CsvOutputArtifact; /** * Extract scalar (non-nested) fields from a tool response for summary display. * * Searches through candidate roots (raw → `.output.body` → legacy `.result` → legacy `.result.data`) and * returns the first set of scalar fields found. Useful for displaying a * quick summary of single-record responses. * * @param payload - Raw tool response * @returns Object containing only scalar fields (string, number, boolean, null) * * @example * ```typescript * const result = await client.executeTool('test_company_search', { domain: 'stripe.com' }); * const summary = extractSummaryFields(result); * // { name: "Stripe", industry: "Financial Services", employeeCount: 8000 } * // (nested objects and arrays are excluded) * ``` */ declare function extractSummaryFields(payload: unknown): Record; export { AuthError, type BillingCreditPool, type BillingInvoiceEntry, type BillingInvoicesResult, type BillingNamespace, type BillingPaymentMethodSummary, type BillingSubscriptionCancelResult, type BillingSubscriptionStatus, type BillingTopUpResult, type ClearPlayHistoryRequest, type ClearPlayHistoryResult, type ColumnMap, type ColumnResolver, type ConditionalStepResolver, ConfigError, type CsvInput, type CsvOptions, type CustomerDbQueryResult, DEEPLINE_TOOL_CATEGORIES, type DatasetBuilder, type DatasetColumnDefinition, type DatasetColumnRunInput, type DbNamespace, Deepline, DeeplineClient, type DeeplineClientOptions, DeeplineContext, DeeplineError, type DeeplineNamedPlay, type DeeplinePlayRuntimeContext, type DeeplinePlaysNamespace, type DeeplineToolCategory, type DeeplineToolsNamespace, type DefinePlayConfig, type DefinedPlay, type FetchOptions, type FileInput, type IngestionStorageRepairResult, type LiveEventEnvelope, type MonitorCheckResult, type MonitorControls, type MonitorDefinition, type MonitorDeleteResult, type MonitorDependents, type MonitorDeployResult, type MonitorDetail, type MonitorListEntry, type MonitorPayload, type MonitorReactivateResult, type MonitorSpec, type MonitorUpdateChangeSummary, type MonitorUpdateResult, type MonitorsAccessStatus, type MonitorsAvailableOptions, type MonitorsAvailableResult, type MonitorsListOptions, type MonitorsListResult, type MonitorsNamespace, PLAY_BOOTSTRAP_COMPANY_FIELDS, PLAY_BOOTSTRAP_COMPANY_PROVIDER_CATEGORY, PLAY_BOOTSTRAP_CONTACT_FIELDS, PLAY_BOOTSTRAP_FINDER_KINDS, PLAY_BOOTSTRAP_OUTPUT_FIELD_BY_FINDER, PLAY_BOOTSTRAP_PEOPLE_PROVIDER_CATEGORY, PLAY_BOOTSTRAP_PROVIDER_CATEGORY_BY_FINDER, PLAY_BOOTSTRAP_SOURCE_KINDS, PLAY_BOOTSTRAP_STAGE_KINDS, PLAY_BOOTSTRAP_TEMPLATES, PROD_URL, type PlayActivityObservation, type PlayActivityState, type PlayActivityTarget, type PlayBindings, type PlayBootstrapEntityKind, type PlayBootstrapFinderKind, type PlayCallExecution, type PlayCallOptions, type PlayFetchResponse, type PlayInputContract, type PlayJob, type PlayListItem, type PlayLiveEvent, type PlayRevisionSummary, type PlayRunActionPackage, type PlayRunActivityProjection, type PlayRunDatasetActions, type PlayRunPackage, type PlayRunResult, type PlayRunStart, type PlaySheetRow, type PlaySheetRowsResult, type PlayStatus, type PlayStepProgramStep, type PrebuiltPlayRef, type PublishPlayVersionRequest, type PublishPlayVersionResult, RateLimitError, type ResolvedConfig, RunObserveTransportUnavailableError, type RunsListOptions, type RunsLogsOptions, type RunsLogsResult, type RunsNamespace, type RunsTailOptions, type RuntimeStepOptions, SDK_API_CONTRACT, SDK_VERSION, type SqlListenerDeclaration, type SqlListenerEvent, type SqlListenerOperation, type SqlQuery, type StartPlayRunRequest, type StepOptions, type StepProgram, type StepProgramResolver, type StepResolver, type StopPlayRunResult, type ToolDefinition, ToolExecuteResult, type ToolExecution, ToolExecutionError, ToolExecutionErrorOptions, type ToolExecutionRequest, type ToolMetadata, ToolRateLimitError, type ToolSearchOptions, type ToolSearchResult, defineInput, defineMonitor, definePlay, defineWorkflow, extractSummaryFields, formatPlayBootstrapFinderKinds, formatPlayBootstrapFinderKindsForSentence, formatPlayBootstrapTemplates, getDefinedPlayMetadata, isPlayBootstrapFinderKind, isPlayBootstrapTemplate, resolveConfig, runIf, steps, tryConvertToList, writeCsvOutputFile, writeJsonOutputFile };