export interface WorkflowOptions { taskQueue: string; } export interface ActivityOptions { /** Override the task queue for this activity */ taskQueue?: string; /** Retry policy */ retry?: RetryPolicy; /** Maximum time the activity can run */ startToCloseTimeout?: string; /** Heartbeat interval for long-running activities */ heartbeatTimeout?: string; /** * Best-effort dispatch priority (P5.3) among BACKLOGGED activity tasks in * this activity's (namespace, task_queue) — higher runs sooner. Default 0. * Only matters once a backlog exists (an idle worker takes whatever * arrives first regardless of priority); not preemption of an in-flight * task, not cross-queue, and not a fairness guarantee. Ignored by the * local (no-server) engine — there's no backlog to order. */ priority?: number; } export interface RetryPolicy { maxAttempts?: number; initialBackoff?: string; maxBackoff?: string; backoffMultiplier?: number; nonRetryableErrors?: string[]; } export interface StepCheckpoint { step_seq: number; step_type: string; step_name: string; status: 'STARTED' | 'COMPLETED' | 'FAILED'; output?: Buffer; error?: string; /** * Content-addressed step identity (hash(kind, name)[:16] + ':' + occurrence). * Empty/undefined on checkpoints written before the field existed. */ step_key?: string; /** * Size in bytes of the step's output. Meaningful when the task was * dispatched with outputs stripped (lazy hydration) — see * WorkflowTaskPayload.outputs_inline. */ output_size?: number; /** * Optional structured observability metadata (step.llm, P3.1): model, * token counts, cost estimate, finish reason — JSON-encoded bytes, as * recorded by `activityContext().recordLlmMeta()`. Undefined/empty means * absent. Purely observational — never consulted for memoization or step * identity (Design Law 1 is unaffected). */ meta?: Buffer; /** * N3 (F8 advisory): server-computed sha256 hex of this step's recorded * input. Dispatched tasks strip the input BYTES for payload size; the * fingerprint lets the input-drift advisory fire on the server tier. * Advisory only — never consulted for memoization or step identity. */ input_sha256?: string; /** * Claim-check blob store (P3.4): set when this step's output was * externalized to object storage instead of stored inline (exceeded the * server's configured threshold_bytes). Undefined means "not * externalized" — `output` carries the value inline as before this field * existed. The worker never needs to read this directly: the existing * lazy-hydration path (`hydrateOutputsIfNeeded`) treats a blob-backed step * the same as a size-stripped one and fetches the real bytes via * `GetCheckpoints(resolve_blobs=true)`, so workflow code always sees plain * inlined values (Design Law 3). */ output_blob_ref?: string; output_blob_size?: number; output_blob_sha256?: string; /** * P6.3 transactional step (Postgres tier only): true when this COMPLETED * checkpoint was written by the SDK itself, inside the same Postgres * transaction as the step's own database writes (`ctx.transaction()`), * rather than by the server's normal CompleteActivity path. Purely * observational (dashboard EXACTLY_ONCE_TX badge) — never consulted for * memoization or step-identity decisions (Design Law 1 unaffected). */ exactly_once_tx?: boolean; } /** * Structured metadata recorded by an activity implementation that calls an * LLM. Passed to `activityContext().recordLlmMeta()` from inside the * activity function; the worker JSON-serializes it and attaches it to the * COMPLETED checkpoint on success (never on failure/retry). * * Free-form beyond the well-known fields — provider-specific extras (e.g. * `cacheReadTokens`, `stopSequence`) are allowed via the index signature. */ export interface LlmStepMeta { model: string; promptTokens?: number; completionTokens?: number; totalTokens?: number; costUsd?: number; finishReason?: string; [k: string]: unknown; } export interface SignalInfo { signal_name: string; signal_id: string; payload?: Buffer; } /** Opaque server-issued identity. SDKs only validate and echo this value. */ export interface TaskDeliveryIdentity { task_id: string; generation: string | number | { toString(): string; }; attempt: number; completion_idempotency_key: string; task_kind: string | number; delivery_id: string; task_deadline?: unknown; } /** Server-authored, fail-closed execution contract for a forked run. */ export interface ForkExecutionPolicy { readonly schema_version: 1; readonly effect_mode: 'FORK_EFFECT_MODE_REPLAY_ONLY' | 'FORK_EFFECT_MODE_MODEL_ONLY'; readonly overrides?: readonly ForkExecutionOverride[]; } export interface ForkWorkflowOptions { readonly effectMode?: 'REPLAY_ONLY' | 'MODEL_ONLY'; readonly overrides?: readonly ForkExecutionOverride[]; readonly call?: RpcCallOptions; } /** Digest-only identity change declared for a post-boundary fork step. */ export interface ForkExecutionOverride { readonly kind: 'MODEL' | 'PROMPT' | 'TOOL' | 'CODE'; readonly step_seq: number; readonly target_id: string; readonly source_sha256: string; readonly replacement_sha256: string; readonly replacement_ref?: string; } export interface WorkflowTaskPayload { namespace: string; workflow_id: string; run_id: string; workflow_type: string; task_queue: string; input: Buffer; task_token: string; /** Absent only when explicitly connected to the frozen N-1 server. */ delivery_identity?: TaskDeliveryIdentity; completed_steps: StepCheckpoint[]; pending_signals: SignalInfo[]; /** * Lazy hydration (P0.4): false means the server stripped step outputs from * completed_steps (total exceeded the inline budget) and the worker must * fetch them once via GetCheckpoints before running the workflow. Old * servers never set the proto field, which also decodes as false — the * worker additionally requires a stripped-looking step (output_size > 0 * with empty output) before paying for the hydration round-trip. */ outputs_inline?: boolean; /** * OpenTelemetry (P3.6): W3C trace context (traceparent/tracestate) * propagated from the server's dispatch span, if OTel is enabled there. * Empty/absent when OTel is off server-side. Observability only — never * consulted for step identity or memoization (Design Law 1 unaffected). */ trace_context?: Record; fork_execution_policy?: ForkExecutionPolicy; } export interface ActivityTaskPayload { task_token: string; /** Absent only when explicitly connected to the frozen N-1 server. */ delivery_identity?: TaskDeliveryIdentity; namespace: string; workflow_id: string; run_id: string; step_seq: number; activity_type: string; input: Buffer; attempt: number; /** Validated server deadline, when present on the protobuf task. */ deadline?: Date; /** OpenTelemetry (P3.6): see WorkflowTaskPayload.trace_context doc. */ trace_context?: Record; /** * P6.3 transactional step (Postgres tier only): this attempt's * content-addressed step identity (Design Law 1), needed so * `ctx.transaction()` can write a checkpoint indistinguishable from a * server-written one. Empty on pre-P0.1 keyless steps or servers that * predate this field — `ctx.transaction()` refuses rather than write an * identity-less checkpoint in that case. */ step_key?: string; fork_execution_policy?: ForkExecutionPolicy; } export interface ScheduleActivityCommand { type: 'SCHEDULE_ACTIVITY'; step_seq: number; step_key: string; activity_type: string; task_queue?: string; input?: Buffer; /** Retry policy with durations pre-parsed to milliseconds (undefined = no retry). */ retry_policy?: { max_attempts: number; initial_backoff_ms: number; max_backoff_ms: number; backoff_multiplier: number; non_retryable_errors: string[]; }; /** Server-enforced start_to_close timeout in ms (undefined = server default, 10m). */ start_to_close_timeout_ms?: number; /** Heartbeat timeout in ms — each heartbeat extends the server-side timeout by this. */ heartbeat_timeout_ms?: number; /** Best-effort dispatch priority (P5.3) — see `ActivityOptions.priority`. Default 0. */ priority?: number; } export interface ScheduleTimerCommand { type: 'SCHEDULE_TIMER'; step_seq: number; step_key: string; duration_ms: number; } export interface WaitForSignalCommand { type: 'WAIT_FOR_SIGNAL'; step_seq: number; step_key: string; signal_name: string; timeout_ms?: number; approval_assignee_kind?: ApprovalAssigneeKind; approval_assignee_id?: string; approval_require_claim?: boolean; } export interface RecordSideEffectCommand { type: 'RECORD_SIDE_EFFECT'; step_seq: number; step_key: string; /** Serialized side-effect value, computed once by the workflow. */ result: Buffer; /** * Implicit HTTP step metadata (P6.1). Present when this record is a bare * `fetch` captured by the undici interceptor rather than a `ctx.sideEffect`. * The server uses it to name the checkpoint (`method url`) and render it as * an HTTP step; identity stays the call-site `step_key` (Design Law 9). */ http?: { method: string; url: string; status: number; duration_ms: number; }; /** JSON-serialized LLM token/cost meta (P3.1), when the target was an LLM endpoint. */ meta?: Buffer; } export type WorkflowCommand = ScheduleActivityCommand | ScheduleTimerCommand | WaitForSignalCommand | RecordSideEffectCommand; export interface WorkflowCompletionSuccess { status: 'COMPLETED'; result?: Buffer; query_states?: Record; } export interface WorkflowCompletionSuspended { status: 'SUSPENDED'; commands: WorkflowCommand[]; query_states?: Record; } export interface WorkflowCompletionFailed { status: 'FAILED'; error_type: string; error_message: string; query_states?: Record; /** * T2: TYPED nondeterminism classification — true only when the failure * IS the SDK's own NonDeterminismError (instanceof, never name-string), * transitioning the run to resumable BLOCKED_NONDETERMINISTIC server-side. */ nondeterminism?: boolean; } export type WorkflowCompletion = WorkflowCompletionSuccess | WorkflowCompletionSuspended | WorkflowCompletionFailed; export interface ActivityCompletionSuccess { status: 'COMPLETED'; result?: Buffer; /** JSON-serialized LlmStepMeta, when the activity called recordLlmMeta(). */ meta?: Buffer; } export interface ActivityCompletionFailed { status: 'FAILED'; error_type: string; error_message: string; /** * Retry-After override in milliseconds (P3.2 RateLimitError), carried to * the server as `ActivityFailed.retry_after_ms`. 0/undefined = absent — * the activity's retry policy backoff applies normally. */ retry_after_ms?: number; } export type ActivityCompletion = ActivityCompletionSuccess | ActivityCompletionFailed; export interface WorkflowRegistration { name: string; cls: new (...args: any[]) => any; taskQueue: string; entryPoint?: string; signals: Map; queries: Map; /** * Set by `@Cron(...)` (P6.4). When present, `Worker.run()` upserts a * durable server-side schedule for this workflow on startup — see * `registerSchedules()` in `runtime/worker.ts`. */ cron?: CronOptions; } export interface ActivityRegistration { name: string; fn: (...args: any[]) => Promise; options?: ActivityOptions; } /** * TLS options for the gRPC channel (mTLS support). Paths are read from disk * by the connection helper — see `packages/sdk/src/grpc/connection.ts`. * All optional: an empty object still uses `grpc.credentials.createSsl()` * with the system root CAs (server-auth-only TLS, no client cert). */ export interface TlsOptions { /** PEM-encoded root CA(s) used to verify the server's certificate. */ rootCertsPath?: string; /** PEM-encoded client private key (mTLS — sent to the server for verification). */ privateKeyPath?: string; /** PEM-encoded client certificate chain (mTLS). */ certChainPath?: string; } export interface WorkerOptions { /** * Server address: `host:port` (TCP) or `unix:` for a same-host Unix * domain socket (P9.4 — the server exposes one when MEMOFLOW_UDS_PATH is * set; unix only). grpc-js handles both schemes natively. */ serverAddress: string; namespace?: string; taskQueue: string; identity?: string; /** Operator-approved external isolation evidence. The server grants sandbox routing only when this exact evidence is allowlisted for the authenticated worker identity and build. */ sandboxAttestation?: SandboxAttestation; /** Maximum workflow tasks executed concurrently (0-10,000). Default 10; 0 disables this capability. */ maxConcurrentWorkflows?: number; /** Maximum activities executed concurrently (0-10,000). Default 50; 0 disables this capability. */ maxConcurrentActivities?: number; /** * P7.1 lease renewal: interval (ms) at which the worker heartbeats an * in-flight WORKFLOW task so the server's WORKFLOW_TASK_TIMEOUT reaper * never re-dispatches a slice whose worker is demonstrably alive — e.g. * one awaiting an implicit HTTP/LLM call slower than the server's task * timeout. Integer range 0..86_400_000; default 10_000. Set 0 to disable * periodic Ping frames (the server still uses a 10s fallback only when * calculating disconnect-reap grace). */ workflowTaskKeepaliveMs?: number; /** * Permit the immediately previous, pre-negotiation server protocol. That * server reports an all-zero negotiation ACK, so it cannot prove an exact * protocol version on the wire. Keep this disabled except during a * deliberate N-1 rollout or rollback. */ allowLegacyServer?: boolean; /** Explicit build ID. If omitted, auto-computed from registered workflow/activity code. */ buildId?: string; /** Reconnection backoff configuration for gRPC streams */ reconnect?: { initialDelayMs?: number; maxDelayMs?: number; multiplier?: number; jitterFraction?: number; }; /** * API key (P4.2) — sent as `authorization: Bearer ` gRPC metadata * on every call when the server has `MEMOFLOW_AUTH__ENABLED=true`. Has no * effect against an unauthenticated server (metadata is simply ignored). */ apiKey?: string; /** mTLS options. Omit for plaintext gRPC (the default). */ tls?: TlsOptions; /** * Implicit HTTP steps (P6.1): a bare `await fetch(...)` inside a workflow * body is a durable step by default. Pass `{ enabled: false }` to opt out, * or override identity mode / body cap / LLM endpoints. Shape is * `Partial` (see runtime/http-effect.ts). */ implicitSteps?: Partial; /** * P6.3 transactional step (Postgres tier only) — enables `ctx.transaction()` * for activities this worker runs. Omit entirely to leave * `ctx.transaction()` unavailable (it throws a clear "not configured" * error rather than silently doing nothing) — this worker never imports * `pg` and never calls `GetSqlContract` unless this is set. */ transactionalStep?: TransactionalStepOptions; } export interface SandboxAttestation { schemaVersion: 1; sandboxId: string; profile: 'MODEL_ONLY' | 'SANDBOXED'; evidenceSha256: `urn:sha256:${string}`; } /** * P6.3 transactional step (Postgres tier only) config for `Worker`. * * The guarantee this unlocks is narrow and precondition-bound — see * `packages/sdk/src/runtime/sql-contract.ts`'s module doc and the README's * Execution guarantees section: "exactly-once for database steps when the * step writes to the same Postgres database that stores memoflow * checkpoints." Never broader than that. */ export interface TransactionalStepOptions { /** * Connection string / config for the USER's Postgres database (the one * `ctx.transaction()` opens a transaction against) — passed straight * through to `pg.Pool`. This may or may not be the same physical database * as the memoflow store; the worker verifies that at startup via the * server's `GetSqlContract` fingerprint (see `sameDatabase` below to * override the check instead of relying on auto-detection). */ connectionString: string; /** * Force the "same database as the memoflow store" determination instead of * relying on the fingerprint comparison — useful when the two connection * strings differ cosmetically (different host aliases/DNS names resolving * to the same instance) but you, the operator, know they're the same * physical database. `true` unconditionally allows the in-transaction * checkpoint write; `false` unconditionally refuses it (same as omitting * this field when the fingerprints don't match). Omit to trust the * automatic fingerprint comparison. */ sameDatabase?: boolean; /** * What to do when the user database is confirmed NOT the same as the * memoflow store (or the check is inconclusive, e.g. a non-Postgres * backend). Default `'refuse'`: `ctx.transaction()` throws loudly rather * than fabricate an exactly-once claim it can't back up. `'at-least-once'` * degrades explicitly: the transaction still runs and commits/rolls back * normally, but the checkpoint write happens the ORDINARY way afterward * (the same at-least-once path every other activity uses) — a prominent * startup warning is logged either way so this is never a silent * downgrade. */ degrade?: 'refuse' | 'at-least-once'; } export interface ClientOptions { serverAddress: string; /** Explicit authorization/routing namespace. There is no implicit default. */ namespace: string; /** * API key (P4.2) — sent as `authorization: Bearer ` gRPC metadata * on every call when the server has `MEMOFLOW_AUTH__ENABLED=true`. Has no * effect against an unauthenticated server (metadata is simply ignored). */ apiKey?: string; /** mTLS options. Omit for plaintext gRPC (the default). */ tls?: TlsOptions; /** * Default deadline applied to every gRPC call. Defaults to 30 seconds and * must be a finite positive integer. Long result waits additionally use * their explicit operation timeout. */ defaultRpcTimeoutMs?: number; } export interface RpcRetryOptions { /** Total attempts including the first call. Bounded to 1..5. */ maxAttempts?: number; /** Initial exponential-backoff delay. Defaults to 100ms. */ initialDelayMs?: number; } /** Per-call controls for unary remote operations. */ export interface RpcCallOptions { /** Override the connection's default deadline for this call. */ timeoutMs?: number; /** Cancels the in-flight call and any retry delay. */ signal?: AbortSignal; /** * Opt-in retry. Honored only by operations classified idempotent and only * for structured server errors carrying retryable=true. */ retry?: RpcRetryOptions; } export interface DurableOutputReadOptions { /** Exact run to read; durable streams never silently switch runs. */ runId: string; streamName: string; /** Inclusive first offset when resumeToken is omitted. Defaults to zero. */ startOffset?: number; /** Bounded server page size, 1..1000. Defaults to 100. */ pageSize?: number; /** Wait for newly committed chunks until the producer closes the stream. */ tail?: boolean; /** Opaque cursor returned by an earlier chunk. */ resumeToken?: string; signal?: AbortSignal; } export interface DurableOutputChunk { workflowId: string; runId: string; streamName: string; offset: number; chunk: Buffer; contentType: string; payloadSha256?: string; endMarker: boolean; errorType?: string; errorMessage?: string; createdAt?: Date; resumeToken: string; lastCommittedOffset: number; } export interface StartWorkflowInput { workflowId: string; workflowType: string; taskQueue: string; input?: any; requestId?: string; /** Indexed attributes persisted on the workflow run for future search/list APIs. */ searchAttributes?: Record; /** * Best-effort dispatch priority (P5.3) among BACKLOGGED workflow tasks in * this workflow's (namespace, task_queue) — higher runs sooner. Default 0 * (bit-compatible with pre-P5.3 FIFO ordering). Not preemption, not * cross-queue, not a fairness guarantee — see `ActivityOptions.priority` * for the same semantics applied to individual activities. */ priority?: number; } export type WorkflowStatusName = 'RUNNING' | 'COMPLETED' | 'FAILED' | 'CANCELLED' | 'TIMED_OUT' | 'BLOCKED_NONDETERMINISTIC'; export interface WorkflowRunInfo { namespace: string; workflowId: string; runId: string; workflowType: string; status: WorkflowStatusName; taskQueue: string; input?: unknown; output?: unknown; error?: string; createdAt: Date; updatedAt: Date; deadline?: Date; searchAttributes: Record; parentWorkflowId?: string; parentRunId?: string; forkedFromRunId?: string; forkedFromStepSeq?: number; buildId?: string; workflowTaskGeneration: number; } export interface ListWorkflowsOptions { status?: WorkflowStatusName; workflowType?: string; pageSize?: number; pageToken?: string; createdAfter?: Date; createdBefore?: Date; buildId?: string; /** Bounded server-side search expression, for example `customer = acme AND attempts >= i:3`. */ searchQuery?: string; } export interface ListWorkflowsResult { workflows: WorkflowRunInfo[]; nextPageToken?: string; } export interface WorkflowDescription { info: WorkflowRunInfo; steps: StepCheckpoint[]; pendingSignals: SignalInfo[]; } export type EventPayloadKind = 'EMPTY' | 'INLINE' | 'REFERENCE' | 'REDACTED'; export interface WorkflowHistoryEvent { sequence: number; eventId: string; eventType: string; eventVersion: number; taskId?: string; taskGeneration?: number; occurredAt: Date; payloadKind: EventPayloadKind; payload?: Buffer; payloadReference?: string; causationId?: string; correlationId?: string; actorType: string; actorId?: string; idempotencyKey: string; } export interface WorkflowHistoryOptions { runId?: string; pageSize?: number; pageToken?: string; startSequence?: number; endSequence?: number; tail?: boolean; redactPayloads?: boolean; } export type ProjectionVerificationStatus = 'CONSISTENT' | 'DRIFTED' | 'INVALID_HISTORY'; export interface WorkflowHistoryResult { workflowId: string; runId: string; events: WorkflowHistoryEvent[]; nextPageToken?: string; lastSequence: number; projectionStatus: ProjectionVerificationStatus; historySha256?: string; verificationDifferences: string[]; payloadsRedacted: boolean; } export interface WorkflowPayloadRevealResult { event: WorkflowHistoryEvent; auditId: string; } export interface NamespaceConfig { namespace: string; retentionDays?: number; } export type NamespaceStatusCounts = Record; export type WorkerCapabilityName = 'workflow' | 'activity'; export interface WorkerBuildInfo { identity: string; buildId: string; capabilities: WorkerCapabilityName[]; } export interface QueueWorkersInfo { namespace: string; taskQueue: string; identities: string[]; count: number; workers: WorkerBuildInfo[]; } export interface StalledQueueInfo { namespace: string; taskQueue: string; runningWorkflowCount: number; } export interface WorkerInventory { workers: QueueWorkersInfo[]; stalledQueues: StalledQueueInfo[]; } export interface QueueBacklogInfo { namespace: string; taskQueue: string; isWorkflow: boolean; available: number; leased: number; retrying: number; dead: number; oldestAvailableAt?: Date; oldestLeaseExpiresAt?: Date; } export interface QueueBacklogSnapshot { queues: QueueBacklogInfo[]; observedAt: Date; consistency: 'store-query-snapshot'; } export interface DebounceInfo { namespace: string; debounceKey: string; workflowId: string; workflowType: string; taskQueue: string; fireAt: Date; claimedUntil?: Date; createdAt: Date; updatedAt: Date; } export interface DebounceSnapshot { debounces: DebounceInfo[]; observedAt: Date; consistency: 'store-query-snapshot'; } export interface SystemMetrics { activeTimers: number; activityTimeoutRedeliveries: number; workflowTaskRedeliveries: number; dispatchTotal: number; dispatchSyncMatched: number; syncMatchRate: number; invalidPendingTasks: number; versionMismatchDispatches: number; queueReaders: number; dispatcherShuttingDown: boolean; taskHintsReceived: number; taskHintsLagged: number; outboxMetricsAvailable: boolean; outboxPending: number; outboxLeased: number; outboxDelivered: number; outboxDead: number; outboxOldestPendingAgeSeconds?: number; outboxClaimedTotal: number; outboxDeliveredTotal: number; outboxRetriedTotal: number; outboxDeadTotal: number; outboxPublishFailedTotal: number; outboxStaleSettlementsTotal: number; outboxStoreErrorsTotal: number; storageBackend: string; sqliteDurabilityProfile?: string; sqliteSchemaVersion?: number; sqliteRuntimeVersion?: string; sqliteLastCommitSeq?: number; sqliteWalBytes?: number; sqliteWalRunaway?: boolean; sqliteCheckpointFailures?: number; sqliteLastBackupAgeSeconds?: number; } /** Missed-fire policy for a `@Cron` schedule — see `CronOptions.missedFirePolicy`. */ export type MissedFirePolicy = 'skip' | 'backfill1'; /** * Options for the `@Cron` class decorator. The schedule is registered * server-side (durable `schedules` row) the first time a `Worker` for this * workflow's task queue starts — see `Worker.run()`'s schedule registration * step. Re-registering (e.g. every worker restart) is idempotent: the same * cron expression preserves the schedule's already-computed next_fire_at. */ export interface CronOptions { /** Standard 5-field cron expression, e.g. `'0 0 * * *'` for once a day at midnight. */ cron: string; /** * Logical schedule name, unique per namespace. Defaults to the workflow * class name if omitted — fine for the common case of one schedule per * workflow type, but required if you register the SAME workflow type on * more than one cadence. */ scheduleId?: string; /** Serialized input passed to every fired run. */ input?: any; /** * What to do with occurrences that fell due while no poller was running * (server down, or the schedule was paused). `'skip'` (default) drops the * whole backlog and resumes from the next future occurrence. `'backfill1'` * fires at most the ONE most recent missed occurrence, then resumes. */ missedFirePolicy?: MissedFirePolicy; /** Register the schedule paused (no firings) until explicitly resumed. */ paused?: boolean; } export interface ScheduleInfo { namespace: string; scheduleId: string; cronExpr: string; workflowType: string; taskQueue: string; missedFirePolicy: MissedFirePolicy; paused: boolean; nextFireAt?: Date; createdAt?: Date; updatedAt?: Date; } export interface UpsertScheduleInput { scheduleId: string; cronExpr: string; workflowType: string; taskQueue: string; input?: any; missedFirePolicy?: MissedFirePolicy; paused?: boolean; } export interface StartDebouncedInput { /** Calls sharing this key collapse into ONE run. */ debounceKey: string; /** Debounce window in milliseconds — reset on every call sharing the key. */ windowMs: number; workflowType: string; taskQueue: string; /** Last-write-wins: this call's input overwrites any pending input for the key. */ input?: any; } /** * P6.5 — restart-from-step (operational time travel). Result of * `WorkflowClient.fork()`: a NEW run of the same workflow_id, seeded with * checkpoints 0..=stepSeq copied verbatim from the source run, dispatched to * re-execute from stepSeq+1 onward. See `WorkflowClient.fork()`'s doc for * the full contract (source run never mutated, RUNNING sources rejected). */ export interface ForkWorkflowResult { workflowId: string; /** run_id of the newly created fork. */ runId: string; forkedFromRunId: string; forkedFromStepSeq: number; forkExecutionPolicy: ForkExecutionPolicy; } export type ApprovalStatus = 'PENDING' | 'CLAIMED' | 'APPROVED' | 'REJECTED' | 'EXPIRED' | 'CANCELLED'; export type ApprovalAssigneeKind = 'ANY_AUTHENTICATED' | 'PRINCIPAL' | 'GROUP'; export type ApprovalAssignment = { kind: 'ANY_AUTHENTICATED'; } | { kind: 'PRINCIPAL' | 'GROUP'; id: string; }; export interface ApprovalOptions { timeout?: string; assignee?: ApprovalAssignment; requireClaim?: boolean; } export type ApprovalActorKind = 'HUMAN' | 'SERVICE_ACCOUNT' | 'SYSTEM'; export interface ApprovalActor { kind: ApprovalActorKind; principalId?: string; } export interface ApprovalPolicy { schemaVersion: 1; assigneeKind: ApprovalAssigneeKind; assigneeId?: string; requireClaim: boolean; escalationAfterSeconds?: number; escalationAssigneeKind?: ApprovalAssigneeKind; escalationAssigneeId?: string; } export interface ApprovalWorkItem { approvalId: string; namespace: string; workflowId: string; runId: string; name: string; stepSeq: number; /** Exact protobuf int64 text; never rounded through a JavaScript number. */ taskGeneration: string; policy: ApprovalPolicy; status: ApprovalStatus; createdAt: Date; dueAt?: Date; expiresAt?: Date; claimedBy?: ApprovalActor; claimedAt?: Date; decidedBy?: ApprovalActor; decidedAt?: Date; decision?: boolean; commentSha256?: string; commentRef?: string; decisionSha256?: string; escalationCount: number; lastEscalatedAt?: Date; createIdempotencyKey: string; claimIdempotencyKey?: string; decisionIdempotencyKey?: string; } export interface ListApprovalsOptions { workflowId?: string; runId?: string; statuses?: ApprovalStatus[]; assigneeKind?: ApprovalAssigneeKind; assigneeId?: string; pageSize?: number; pageToken?: string; } export interface ListApprovalsResult { approvals: ApprovalWorkItem[]; nextPageToken?: string; } export interface ApprovalMutationOptions { requestId?: string; occurredAt?: Date; } export interface ApprovalDecisionInput extends ApprovalMutationOptions { approved: boolean; commentSha256?: string; commentRef?: string; } export interface ApprovalMutationResult { approval: ApprovalWorkItem; duplicate: boolean; auditId: string; } export type EvaluationActorKind = 'HUMAN' | 'SERVICE_ACCOUNT' | 'SYSTEM'; export interface EvaluationScore { dimension: string; /** Fixed-point score in [-1, 1], scaled by 1,000,000. */ scoreMicros: number; } export interface WorkflowEvaluation { schemaVersion: 1; evaluationId: string; namespace: string; workflowId: string; sourceRunId: string; candidateRunId: string; evaluatorKind: EvaluationActorKind; evaluatorPrincipalId?: string; evaluatorSessionId?: string; rubricId: string; rubricVersion: string; scores: EvaluationScore[]; /** SHA-256 URN of canonical evaluator input; raw evidence is never returned. */ evidenceSha256: string; resultRef?: string; createdAt: Date; idempotencyKey: string; } export interface CreateWorkflowEvaluationInput extends ApprovalMutationOptions { sourceRunId: string; candidateRunId: string; rubricId: string; rubricVersion: string; scores: EvaluationScore[]; evidenceSha256: string; } export interface ListWorkflowEvaluationsOptions { sourceRunId?: string; rubricId?: string; pageSize?: number; pageToken?: string; } export interface ListWorkflowEvaluationsResult { evaluations: WorkflowEvaluation[]; nextPageToken?: string; } export interface WorkflowEvaluationMutationResult { evaluation: WorkflowEvaluation; duplicate: boolean; auditId: string; } /** * Extracts async methods from an activity class as a typed interface. * Used with `ctx.proxyActivities(ActivityClass)` to get compile-time * type checking for activity calls. */ export type ActivityMethodsOf = { [K in keyof T as T[K] extends (...args: any[]) => Promise ? K : never]: T[K] extends (...args: infer A) => Promise ? (...args: A) => Promise : never; };