import { z } from 'zod'; /** * Type definitions for the Durable Execution system. */ type ExecutionStatus = "running" | "waiting" | "completed" | "failed"; type OperationType = "step" | "wait" | "callback"; type OperationStatus = "pending" | "completed" | "failed" | "exhausted" | "expired"; /** * Statuses a client may write on a checkpoint — excludes "expired" so a * forged expiry can't type-check onto the wire (the server also 422s it). */ type CheckpointOperationStatus = Exclude; type ResumeUrlDeliveryState = "awaiting_delivery" | "delivered" | "delivery_failed" | "attempted_redelivery"; /** * NOTE: Must match the code-substrate-runner `HELD_REASONS`, otherwise will * be categorized as "unknown". */ type HeldReason = "stale_authentication" | "authentication_revoked" | "over_task_limit" | "app_restriction" | "banned_app_action"; interface ErrorMetadata { cause: string; statusCode?: number; } interface RunStateBase { status: string; reason: string; detail?: string; } interface HeldRunState extends RunStateBase { status: "held"; reason: HeldReason; detail?: string; } type RunStateDirective = HeldRunState; interface Execution { id: string; name: string; status: ExecutionStatus; input: unknown; output?: unknown; error?: unknown; metadata?: Record; correlation_id?: string; causation_id?: string; account_id?: string; custom_user_id?: string; lease_token?: string; lease_expires_at?: string; wake_at?: string | null; resume_url?: string; last_wake_sent?: string; resume_url_delivery_state?: ResumeUrlDeliveryState; /** Wire version, immutably stamped by the server at the start of an execution. */ wire_version?: number; created_at: string; } interface Operation { id: string; execution_id: string; name: string; type: OperationType; status: OperationStatus; result?: unknown; error?: unknown; retry_count: number; max_attempts?: number; next_retry_at?: string; resume_at?: string; callback_token?: string; payload_schema?: unknown; payload?: unknown; expires_at?: string; timeout_seconds?: number | null; completed_at?: string; presigned?: PresignedBlock; created_at: string; } /** * Block returned by the server alongside an externalized operation. Signed * with the `presigned-response-v1` HKDF subkey so the SDK can verify * authenticity before any S3 fetch. */ interface PresignedBlock { url: string; expires_at: string; compressed_checksum: string; compressed_size: number; uncompressed_size: number; compression: "zstd"; compression_level: number; zstd_version: string; envelope_sig: string; } /** * Universal-fallback response for `fetchDeferred`. The full bag of an * operation's deferred fields, server-decompressed. One round-trip per * operation regardless of how many fields were deferred. */ interface DeferredFieldsResponse { fields: Record; } interface CreateExecutionRequest { name: string; input: unknown; metadata?: Record; inbox?: string; idempotency_key?: string; } interface CreateExecutionResponse { id: string; name: string; status: ExecutionStatus; inbox?: string | null; idempotency_key?: string | null; created_at: string; } interface CheckoutRequest { resume_url?: string; resume_url_delivery_state?: "awaiting_delivery"; lease_token?: string; } type CheckoutResponse = { leased: true; lease_token: string; execution: Execution; operations: Operation[]; } | { leased: false; }; interface CheckpointRequest { lease_token: string; operation: { name: string; type: OperationType; status: CheckpointOperationStatus; result?: unknown; error?: unknown; retry_count?: number; max_attempts?: number; next_retry_at?: string; error_metadata?: ErrorMetadata; resume_at?: string; /** * Wait duration as an offset; the server stamps resume_at from its own * clock. Mutually exclusive with resume_at on a wait operation. */ duration_seconds?: number; payload_schema?: unknown; /** Sent only on v0; mutually exclusive with timeout_seconds. */ expires_at?: string; /** * Callback deadline as an offset; the server stamps expires_at from its * own clock. Sent only on the wire v1 path. */ timeout_seconds?: number; }; } interface CheckpointResponse { ok: true; /** The created/updated operation with all server-generated fields. */ operation: Operation; } interface ReleaseRequest { lease_token: string; status: ExecutionStatus; output?: unknown; error?: unknown; run_state?: RunStateDirective; } interface ReleaseResponse { ok: true; done: boolean; } /** Callback payload - the body IS the payload (no wrapper). */ type CallbackRequest = unknown; type CallbackResponse = { ok: true; } | { error: "validation_failed"; details: unknown[]; } | { error: "not_found"; }; interface DurableClient { /** * Base URL for constructing callback URLs. * SDK constructs full URL as `${callbackBaseUrl}/${token}`. * Examples: "https://api.example.com/callbacks", "memory://callbacks" */ readonly callbackBaseUrl: string; /** Create a new execution. Returns server-generated UUIDv7. */ create(req: CreateExecutionRequest): Promise; /** * Store resume URL, acquire lease, fetch state. * * The server is the authority on operation state. Implementations must * return operations with up-to-date statuses (e.g., elapsed waits marked * as completed). The SDK replays the journal as returned — it does not * independently evaluate whether operations have expired or completed. * This avoids race non-determinism from multiple clocks evaluating the * same deadlines. */ checkout(executionId: string, req?: CheckoutRequest): Promise; /** Record operation progress. Extends lease. Returns created/updated operation. */ checkpoint(executionId: string, req: CheckpointRequest): Promise; /** Release lease, update status. Returns done flag. */ release(executionId: string, req: ReleaseRequest): Promise; /** Deliver callback payload. */ callback(token: string, req: CallbackRequest): Promise; /** * Optional: server-side fallback for externalized results. The runner * invokes this internally when a sentinel-bearing operation can't be * fetched via its presigned URL (expired, 403, integrity mismatch). * Clients that never produce sentinels (memory, filesystem) may omit * it; clients that do (the REST client against the durable execution * backend) must implement it. */ fetchDeferred?: (executionId: string, operationId: string, leaseToken: string) => Promise; } /** * Error classes for the Durable Execution SDK. */ declare class DuplicateNameError extends Error { constructor(name: string); } declare class NestedStepError extends Error { constructor(innerName: string, outerName: string | null); } declare class SuspendInsideStepError extends Error { constructor(type: "wait" | "callback", name: string, stepName: string | null); } declare class StepExhaustedError extends Error { constructor(name: string, cause: unknown); } declare class LeaseConflictError extends Error { static [Symbol.hasInstance](error: unknown): boolean; constructor(executionId: string); } declare class RequestOutcomeUnknownError extends Error { static [Symbol.hasInstance](error: unknown): boolean; constructor(operation: string, attempts: number, lastError: string); } /** * Thrown when an operation name is reused with a different type (e.g., step vs wait). * This can only happen with non-deterministic control flow - which the DeterminismGuard * should catch first. If user somehow bypasses the guard (unguarded non-determinism source), * catching this error and continuing could lead to invalid state. In practice, the guard * catches common sources (Date.now, Math.random, etc.) before this error is reachable. */ declare class OperationTypeMismatchError extends Error { constructor(name: string, expected: string, actual: string); } /** * Result exceeded the documented size limit. Surfaced from a 413 on * checkpoint. Sizes/ratio/guidance mirror the structured 413 body so * callers can build accurate user-facing messages. Terminal — the SDK * does not retry. */ declare class ResultTooLargeError extends Error { readonly kind: "uncompressed_exceeds_limit" | "compressed_exceeds_limit"; readonly operationName: string; readonly resultSizeBytes: number; readonly resultSizeAfterCompressionBytes: number; readonly maxSizeBytes: number; readonly maxSizeAfterCompressionBytes: number; readonly compressionRatio: number; readonly guidance: string; readonly docsUrl?: string; readonly correlationId?: string; constructor(args: { message: string; kind: "uncompressed_exceeds_limit" | "compressed_exceeds_limit"; operationName: string; resultSizeBytes: number; resultSizeAfterCompressionBytes: number; maxSizeBytes: number; maxSizeAfterCompressionBytes: number; compressionRatio: number; guidance: string; docsUrl?: string; correlationId?: string; }); } /** * Externalized result's S3 object is missing — sentinel points to a key * that returned 404 (or a fetchDeferred fallback returned not-found). * Possible causes: lifecycle expiration with stale Postgres reference, * GDPR purge mid-replay, or a writer/reader binding inconsistency. * Terminal. */ declare class ResultNotFoundError extends Error { readonly executionId?: string; readonly operationId?: string; readonly correlationId?: string; constructor(message: string, args?: { executionId?: string; operationId?: string; correlationId?: string; }); } /** * Externalized result failed integrity verification. `kind` discriminates * the failure mode so callers can branch on it for diagnostics. Terminal — * the SDK does not retry, since retry would surface the same corruption. */ declare class ResultCorruptError extends Error { readonly kind: "checksum_mismatch" | "decompress_error" | "zstd_version_mismatch" | "envelope_sig_invalid"; readonly executionId?: string; readonly operationId?: string; readonly correlationId?: string; constructor(message: string, args: { kind: "checksum_mismatch" | "decompress_error" | "zstd_version_mismatch" | "envelope_sig_invalid"; executionId?: string; operationId?: string; correlationId?: string; }); } /** * Thrown when an operation name starts with a reserved prefix used by the * SDK for internal dormancy tracker bookkeeping. Without this guard, a * user-named operation could collide with a synthetic tracker id (e.g. * the checkpoint protectors registered in the step and wait paths) and * cause the synthetic worker's complete() to terminate the user's * operation prematurely. */ declare class ReservedOperationNameError extends Error { constructor(name: string, prefix: string); } declare class TickReleasedError extends Error { static [Symbol.hasInstance](error: unknown): boolean; constructor(name: string); } /** * Checkout refused with 426: the execution was stamped with a wire_version * higher than this package advertises it understands (the * x-zapier-durable-wire-version header). Terminal — upgrade the SDK; the * runtime does not retry. */ declare class WireVersionMismatchError extends Error { constructor(executionId: string); } /** * Checkout was refused because the execution is already terminal (server * responded 409 Conflict on a `completed` or `failed` execution). The common * cause is a duplicate event replayed against an inbox execution that already * finished: create matched the existing execution by (inbox, idempotencyKey), * but there is no tick left to run. Terminal — read the outcome with * `GET /api/v0/executions/{id}` rather than retrying. */ declare class ExecutionTerminalError extends Error { readonly executionId: string; constructor(executionId: string); } /** * Create was refused because the `idempotencyKey` is already in use within the * inbox for a structurally different request (server responded 409 Conflict). * An identical re-create returns the existing execution instead. Terminal — * retrying sends the same conflicting body; pick a distinct key. */ declare class IdempotencyConflictError extends Error { readonly inbox: string; readonly idempotencyKey: string; constructor(inbox: string, idempotencyKey: string); } /** * Callback delivery was refused because the callback has expired and can no * longer be delivered (server responded 410 Gone): a gated callback past its * server deadline, or a legacy callback that crossed its advisory expiry while * the deciding update ran. Terminal — the payload was not recorded and the * deliverer remains the source of truth; the SDK does not retry. */ declare class CallbackExpiredError extends Error { readonly token: string; constructor(token: string); } /** * Callback delivery conflicted with a settled state (server responded 409 * Conflict): the callback already completed with a structurally different * payload, or it is otherwise no longer deliverable (a rare delivery-race * re-read where the row moved on or vanished). An idempotent, structurally * identical re-delivery returns 200 instead. Terminal — the SDK does not retry. * * Note: the server sends `{ error: "already_completed" }` as the 409 body; this * error is keyed on the 409 status, not that string, so the mapping holds * across all three server cases (different-payload, non-pending, vanished). */ declare class CallbackConflictError extends Error { readonly token: string; constructor(token: string); } /** * Check if an error is an SDK error that should NOT be retried. * Note: DeterminismViolation is checked separately in runner.ts. */ declare function isSdkError(error: unknown): boolean; /** * Determinism Guard * * Provides runtime protection against non-deterministic API usage * outside of steps. Uses AsyncLocalStorage for mode tracking. */ /** * Kind of global to patch - affects how patching works. */ type GlobalKind = "function" | "constructor" | "method" | "getter"; /** * Configuration for a global property to guard. */ interface GlobalGuardConfig { /** Path to the global (e.g., "Math.random", "Date.now", "fetch") */ path: string; /** Kind of global - affects patching strategy */ kind?: GlobalKind; /** Custom guard function (optional, defaults to standard assert) */ guard?: (guard: DeterminismGuard) => (...args: unknown[]) => unknown; } /** * Configuration for a module to shim. */ interface ModuleShimConfig { /** Primary module specifier (e.g., "node:crypto") */ module: string; /** Additional specifiers to match (e.g., ["crypto"] for bare import) */ match?: string[]; /** Functions to guard (calls assert before invoking) */ guarded: string[]; /** Functions to pass through unchanged (or "*" for all others) */ passthrough: string[] | "*"; } type Mode = "GUARDED" | "ALLOWED"; declare class DeterminismViolation extends Error { constructor(api: string); } declare class DeterminismGuard { private als; private logging; private violationCallback?; private static _instance; static get instance(): DeterminismGuard; /** * Initialize global symbol for shims to find us. * Call this once at startup (SDK does this automatically). * This ensures shims work even with duplicate package copies. */ initGlobal(): void; static readonly NODE_GLOBALS: GlobalGuardConfig[]; static readonly NODE_MODULES: ModuleShimConfig[]; static readonly BROWSER_GLOBALS: GlobalGuardConfig[]; static readonly CLOUDFLARE_GLOBALS: GlobalGuardConfig[]; setLogging(enabled: boolean): void; /** * Set a callback to be invoked when a violation is detected. * Called BEFORE the error is thrown, allowing the SDK to signal * a race condition even if user code catches the error. */ setViolationCallback(cb: ((error: DeterminismViolation) => void) | undefined): void; get mode(): Mode | null; runGuarded(fn: () => T): T; runAllowed(fn: () => T): T; private runWithMode; assert(api: string): void; wrap unknown>(api: string, fn: T): T; installGlobalGuards(configs?: GlobalGuardConfig[]): void; private patchGlobal; private patchDateConstructor; private log; } /** * Generate ESM shim source code. * Uses global symbol for guard lookup to avoid duplicate singleton issues * when bundlers create multiple copies of the package. */ declare function generateShimSource(config: ModuleShimConfig): string; interface EsbuildPluginOptions { modules?: ModuleShimConfig[]; shimDir?: string; inline?: boolean; /** Log every shimmed module to stdout. Default false. */ verbose?: boolean; } declare function guardedImportsPlugin(options?: EsbuildPluginOptions): { name: string; setup(build: any): void; }; declare function generatePreloadSource(config?: { globals?: GlobalGuardConfig[]; modules?: ModuleShimConfig[]; }): string; /** * Dormancy Detection Library * * Tracks runtime phases and detects when it's safe to suspend execution. * The SDK calls our methods with opaque IDs. We don't validate or interpret * them - we just track phases and detect dormancy. */ interface TerminationResult { reason: "blockers_only"; pendingBlockers: string[]; } /** * A thenable wrapper that intercepts .then() to detect when user code awaits. * * This is the dormancy library's contribution: observe when promises are awaited. * The inner promise and its resolution mechanism are owned by the caller (SDK). * * Usage: * let resolve: (v: T) => void; * const inner = new Promise(r => { resolve = r; }); * const tracked = new TrackedPromise(inner, () => tracker.activateWait(id)); * // Later: resolve(value) */ declare class TrackedPromise implements PromiseLike { private _innerPromise; private _awaited; private _onAwaited; constructor(innerPromise: Promise, onAwaited: () => void); then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike) | null): Promise; catch(onrejected?: ((reason: unknown) => TResult | PromiseLike) | null): Promise; finally(onfinally?: (() => void) | null): Promise; /** For debugging - check if .then() was called */ get isAwaited(): boolean; } /** * Tracks runtime phases and detects when it's safe to suspend. * * The SDK calls our methods to update state. We don't know WHY * transitions happen - we just maintain the state machine and * detect dormancy (no ACTIVE + at least one WAITING/PAUSED). * * IDs are opaque strings - could be names, UUIDs, anything. * We don't validate or interpret them. */ declare class DormancyTracker { private settleDelayMs; private operations; private terminationResolve?; private settleTimeout?; private terminated; private logging; private readyQueue; readonly termination: Promise; constructor(settleDelayMs?: number); setLogging(enabled: boolean): void; /** SDK calls this when starting work */ beginWork(id: string): void; /** SDK calls this when registering a wait (wait/callback) */ registerWait(id: string): void; /** Called via TrackedPromise.onAwaited when user code awaits */ activateWait(id: string): void; /** SDK calls this when operation completes (success or permanent failure) */ complete(id: string): void; /** SDK calls this when scheduling a retry */ pause(id: string): void; /** SDK calls this when resuming work after retry timer */ resumeWork(id: string): void; /** * Register an operation as ready with a sortable key. * SDK provides timestamps as sortKeys; tracker releases in order. */ registerReady(name: string, sortKey: number, resolve: () => void): void; /** * Release the earliest ready operation. Returns true if one was released. * Called during settle loop when dormancy is detected. */ private releaseNextReady; private shouldTerminate; private maybeScheduleTermination; /** * Settle loop: release ready operations in order, re-check dormancy after each. * This handles both Promise.race (earliest wins, tick continues) and Promise.all * (all eventually resolve) semantics correctly. */ private runSettleLoop; private cancelPendingTermination; private log; get stats(): { total: number; active: number; registered: number; waiting: number; paused: number; complete: number; }; } /** * Fetch + verify + decompress an externalized result bundle from S3. * * Verification order matters: SHA-256 over the raw compressed bytes runs * BEFORE decompression begins, so mismatched bytes never reach the * decompressor. * * `block.envelope_sig` is currently unverified — the SDK has no copy of * the server-side signing key. Integrity rests on the SHA-256 binding * plus TLS and S3 SigV4 on the presigned URL. */ /** Materialized bag of deferrable fields for one operation, post-decode. */ type FetchedBundleFields = Record; /** * Lazy resolver for externalized operation bundles, scoped to one tick. * * The cache (`Map>`) collapses multiple field * reads on the same operation into one fetch, and skips operations whose * results are never read on this tick. * * Resolution per operation: * - If `presigned` is present, try the direct S3 GET. * - On `ZapierPresignedUnavailableSignal` (403, expired, network) or * `ResultCorruptError(checksum_mismatch)`, fall back to * `fetchDeferred` — these are the only failures the server might * succeed where the SDK didn't. * - Other `ResultCorruptError` kinds and `ResultNotFoundError` * propagate terminally; re-fetching server-side would just surface * the same failure. * - If `presigned` is absent, go straight to `fetchDeferred`. * * Rejected fetches are evicted from the cache so a later call (e.g. in * a subsequent tick with a refreshed lease) can retry. */ interface ResolverDeps { presignedFetcher: (block: PresignedBlock, scope: { executionId: string; operationId: string; }) => Promise; deferredFetcher: (executionId: string, operationId: string, leaseToken: string) => Promise; } declare class OperationBundleResolver { private readonly executionId; private readonly leaseToken; private readonly deps; private readonly cache; constructor(executionId: string, leaseToken: string, deps: ResolverDeps); /** * Resolve the field bag for `operation`. Subsequent calls with the same * `operation.id` share the in-flight promise (or its resolved value). * A rejected fetch is evicted so a later call can retry. */ resolve(operation: Operation): Promise; private fetchBag; } /** * DurableContext - The context object passed to durable execution functions. * * Provides: * - step(name, fn) - Execute a durable step * - wait(name, seconds) - Wait for a duration * - createCallback(name) - Create a callback and get [promise, url] */ /** * Clock interface for time operations. * Allows injecting a mock clock for testing. */ interface Clock { /** Returns current time in milliseconds since epoch (like Date.now()). */ now(): number; } /** Default clock using global Date. */ declare const defaultClock: Clock; interface DurableContextOptions { client: DurableClient; tracker: DormancyTracker; guard: DeterminismGuard; executionId: string; leaseToken: string; operations: Map; /** * Resolver for externalized field bags. * * `runTick` always constructs one and passes it in. The field is * `optional` only to support direct construction of `DurableContext` * outside the runner (test fixtures, future embeddings) — no in-tree * caller does that today. * * Behavior when a sentinel-shaped value is read from a completed * operation: * - resolver present (production path): fetches the bundle. If the * underlying client lacks `fetchDeferred` and the presigned path * is unavailable, the resolver's `deferredFetcher` wrapper throws * and the tick fails. * - resolver absent (direct-construction only): the sentinel string * flows through verbatim as the step result. */ bundleResolver?: OperationBundleResolver; maxAttempts?: number; /** Clock for time operations. Defaults to Date.now(). Inject a mock for testing. */ clock?: Clock; /** `execution.wire_version ?? 0`, immutably stamped by the server at the start of the execution. */ wireVersion?: number; } interface StepOptions { name: string; run: () => Promise; maxAttempts?: number; retryDelaySeconds?: number; outputSchema?: z.ZodSchema; } interface WaitOptions { name: string; seconds: number; } interface CallbackOptions { name: string; payloadSchema?: z.ZodSchema; } interface CallbackOptionsWithTimeout extends CallbackOptions { timeoutSeconds: number; } type CallbackResult = { status: "delivered"; value: T; at: string; } | { status: "expired"; at: string; }; /** * A step that failed on this tick but still has attempts left, so the * execution suspended to retry rather than exhausting. Recorded on the tick's * DurableResult so a host can observe the failure that occurred without * waiting for the step to exhaust. * * This records the failure event, not the retry state: a step that is still * in backoff on a later tick (replayed via the time gate without executing) * is not recorded again. */ interface RetryingStep { /** The step (operation) name that failed. */ name: string; /** * The underlying error, already serialized (JSON-safe) by `serializeError`: * name, message, stack, own properties, and the recursive `cause`. The same * bytes journaled with the failed checkpoint. */ error: unknown; /** 1-based attempt number that just failed. */ attempt: number; /** ISO timestamp when the step is next eligible to run. */ nextRetryAt: string; } declare class DurableContext { private client; private tracker; private guard; private stepScope; private usedNames; private operations; private executionId; private leaseToken; private maxAttempts; private clock; private wireVersion; private bundleResolver?; private callbackResolvers; private checkpointError?; private checkpointRequests; private inProcessWaitSecondsUsed; private tickReleased; private writeError?; /** The first checkpoint error that ended this tick's writes, if any. */ getWriteError(): RequestOutcomeUnknownError | LeaseConflictError | undefined; /** Returns any checkpoint error that occurred during the tick. */ getCheckpointError(): Error | undefined; /** Runner calls this immediately before every client.release call. */ markReleased(): void; private retryingSteps; /** Steps that failed this tick with retries remaining (empty if none). */ getRetryingSteps(): RetryingStep[]; private pendingHold?; /** Returns held run override for this tick's release, if any step earned one. */ getPendingHold(): HeldRunState | undefined; /** Dormancy termination promise — resolves when all work is done and execution is suspended. */ get termination(): Promise; /** * Creates a TrackedPromise that runs its onAwaited callback in ALLOWED mode. * * TrackedPromise callbacks execute when user code awaits - which happens in * GUARDED context. This helper centralizes the mode switch for SDK internals. */ private guardedPromise; /** Runs fn in ALLOWED mode (permits non-deterministic APIs). */ private guardAllowed; /** * Replay a settled callback outcome, ordered by the journaled readyAt. */ private replaySettled; /** * Suspend a pending callback. The stored resolver fires only via the * resolveCallback test helper — production deliveries replay from the * journal. */ private suspendPending; /** Returns a promise that never resolves - signals suspension to the runtime. */ private suspend; /** * Checkpoints an operation and updates local cache with server response. * * The request counts as ACTIVE work until it settles, so dormancy cannot * release the tick while a write is in flight. Without this, a parallel * branch that is already WAITING or PAUSED lets the tick release under a * createCallback checkpoint. The callback then resolves after the release, * and user code runs its next step against a released lease. */ private checkpoint; /** Constructs callback URL from token using client's base URL. */ private callbackUrl; /** * Validates operation invariants and returns existing operation if any. * * Checks: * - Name uniqueness (throws DuplicateNameError) * - Not inside a step (throws NestedStepError or SuspendInsideStepError) * - Type consistency with existing operation (throws OperationTypeMismatchError) */ private validateOperation; constructor(options: DurableContextOptions); /** * Returns the materialized value of a deferrable field on a completed * operation, handling the externalized-bundle case transparently. If the * inline value is a sentinel string, the bundle is fetched (or read from * cache) via the resolver and the requested field is read from it. * Without a resolver (e.g. memory client), sentinels pass through as * raw strings — those clients don't produce sentinels anyway. * * `field` is typed against `DEFERRABLE_FIELDS`, so adding a new field to * the externalization contract requires updating the constants module — * the call sites won't compile against a stale list. */ private readDeferredField; step(name: string, fn: () => Promise): Promise; step(options: StepOptions): Promise; /** * Await-time absorption decision: eligible waits sleep out the remainder * in-process and checkpoint completed; ineligible ones just activateWait * and suspend as today. Shared by a wait's first tick (pendingSucceeded * settles its call-time pending checkpoint) and a replay that finds it * already pending (pendingSucceeded is a resolved-true promise; the * journaled resume_at is already in this.operations from checkout). * * The decision and the sleep both derive from the server-stamped * resume_at -- never a local clock snapshot taken before the checkpoint * response lands. */ private absorbWaitAtAwait; wait(name: string, seconds: number): TrackedPromise; wait(options: WaitOptions): TrackedPromise; createCallback(name: string): Promise<[TrackedPromise, string]>; createCallback(options: CallbackOptionsWithTimeout): Promise<[TrackedPromise>, string]>; createCallback(options: CallbackOptions): Promise<[TrackedPromise, string]>; /** * The wire v0 callback path. v0 has no server-side expiry, so a callback * here can only ever be delivered: with timeoutSeconds it resolves a * delivered CallbackResult (never an expired one) to honour the overload's * type; without it, the bare payload, byte-identical to legacy. */ private createCallbackV0; /** * Wire v1 callback path. The deadline rides the wire as timeout_seconds * for the server to stamp from its own clock. A call site that passed * timeoutSeconds awaits a CallbackResult; one that didn't resolves the * bare payload and cannot expire. */ private createCallbackV1; resolveCallback(name: string, payload: unknown): void; } export { type GlobalGuardConfig as $, ResultTooLargeError as A, ResultNotFoundError as B, type CallbackOptions as C, DurableContext as D, type Execution as E, ResultCorruptError as F, ReservedOperationNameError as G, type HeldReason as H, WireVersionMismatchError as I, CallbackExpiredError as J, CallbackConflictError as K, LeaseConflictError as L, ExecutionTerminalError as M, NestedStepError as N, type Operation as O, type PresignedBlock as P, IdempotencyConflictError as Q, type RunStateDirective as R, type StepOptions as S, TickReleasedError as T, isSdkError as U, DeterminismGuard as V, type WaitOptions as W, DeterminismViolation as X, guardedImportsPlugin as Y, generateShimSource as Z, generatePreloadSource as _, type CallbackOptionsWithTimeout as a, type ModuleShimConfig as a0, DormancyTracker as a1, TrackedPromise as a2, type TerminationResult as a3, type RetryingStep as a4, type DurableContextOptions as a5, type CallbackResult as b, type Clock as c, defaultClock as d, type DurableClient as e, type ExecutionStatus as f, type OperationType as g, type OperationStatus as h, type CheckpointOperationStatus as i, type CreateExecutionRequest as j, type CreateExecutionResponse as k, type CheckoutRequest as l, type CheckoutResponse as m, type CheckpointRequest as n, type CheckpointResponse as o, type ErrorMetadata as p, type ReleaseRequest as q, type ReleaseResponse as r, type CallbackRequest as s, type CallbackResponse as t, type DeferredFieldsResponse as u, DuplicateNameError as v, SuspendInsideStepError as w, StepExhaustedError as x, RequestOutcomeUnknownError as y, OperationTypeMismatchError as z };