import * as _graphorin_core0 from "@graphorin/core"; import { Channel, CheckpointId, CheckpointStore, Directive, Tracer, WorkflowEvent } from "@graphorin/core"; //#region src/types.d.ts /** * Sentinel name reserved for the implicit start node. Edges originate * from `__start__` and the engine creates the bootstrap task that * applies the supplied input to the first user-defined node. * * @stable */ declare const START_NODE: "__start__"; /** * Sentinel name reserved for the implicit terminal node. Edges * pointing at `__end__` complete the workflow. * * @stable */ declare const END_NODE: "__end__"; /** * Internal stream channel name that holds the queue of dynamic * tasks scheduled via {@link Dispatch}. Reserved namespace: do not * declare a channel with this key in user code. * * @internal */ declare const TASKS_CHANNEL: "__graphorin_tasks__"; /** * Allowed durability modes for the checkpoint writer. * * The formerly advertised `'async'` mode was byte-identical to * `'sync'` (both awaited the same put), so it was removed rather than * shipped as a fake third behaviour - a fire-and-forget writer would * conflict with the compare-and-set checkpoint guard and the * only-report-real-writes contract. The runtime still coerces a * legacy `'async'` input to `'sync'` with a one-time warning. * * @stable */ type DurabilityMode = 'sync' | 'exit'; /** * Stream emission modes accepted by `workflow.execute(input, { stream })`. * The default is `values`. The `messages` mode is reserved for future * tighter integration with the LLM message channel and currently * behaves as `updates`. * * @stable */ type StreamMode = 'values' | 'updates' | 'messages' | 'tasks' | 'checkpoints' | 'debug' | 'custom'; /** * Argument shape passed to a node's `run(...)` callback. The runtime * supplies a fresh context per task with the writer-bound `emit` * helper plus per-task identifiers. * * @stable */ interface WorkflowContext> { /** Stable thread identifier for the current run. */ readonly threadId: string; /** Monotonically increasing execution-step counter (0-based). */ readonly stepNumber: number; /** Per-task identifier - unique within a single execution step. */ readonly taskId: string; /** * `AbortSignal` propagated from the caller (or generated by the * runtime when an internal abort fires). Honour this in long-running * node bodies - the workflow engine waits up to 100 ms after abort * before treating the task as orphaned. */ readonly signal: AbortSignal; /** * Emit a {@link WorkflowCustomEvent} into the run's event stream. * Visible to callers that opted in via `stream: 'custom'` or * `stream: 'debug'`. */ readonly emit: (name: string, payload?: unknown) => void; /** * Frozen snapshot of the workflow state visible to this task. The * runtime hands every parallel task the same snapshot to keep * channel writes free of cross-task ordering surprises. */ readonly state: Readonly; /** Args supplied to {@link Dispatch} when this task was scheduled. */ readonly dispatchArgs?: unknown; } /** * Optional context passed to {@link Workflow.execute}. `threadId` is * the stable resume key - supply it explicitly when the caller wants * deterministic IDs (CLI / tests); omit to let the runtime generate a * fresh ULID-style identifier. * * @stable */ interface WorkflowExecuteOptions { readonly threadId?: string; /** Stream emission mode. Default: `values`. */ readonly stream?: StreamMode; /** Cancellation signal. Honored at every step boundary. */ readonly signal?: AbortSignal; /** * Override the durability mode declared at workflow construction time. * Useful for one-off `'exit'` runs in tests. */ readonly durability?: DurabilityMode; } /** * Optional context passed to {@link Workflow.resume}. The `directive` * argument is the typed value supplied to the paused node + optional * channel writes. * * @stable */ interface WorkflowResumeOptions { readonly stream?: StreamMode; readonly signal?: AbortSignal; /** * Override the durability mode for this resume - mirrors * {@link WorkflowExecuteOptions.durability}. */ readonly durability?: DurabilityMode; /** * Skip the {@link WorkflowConfig.version} pin check. By default a * resume whose stored frontier was written by a different workflow * version fails loudly with `workflow-version-mismatch` instead of * replaying state through changed code. */ readonly allowVersionMismatch?: boolean; } /** * Pure node contract. The runtime invokes `run(state, ctx)` exactly * once per scheduled task; the return value is converted into channel * writes by the engine. * * Returning a single {@link Dispatch} or an array of dispatches * schedules new tasks instead of writing to channels. * * @stable */ interface WorkflowNode> { readonly name: string; readonly run: WorkflowNodeRun; /** * Per-node wall-clock budget in milliseconds. When the body * exceeds it, the task's `ctx.signal` aborts and the * task fails with a `node-timeout` error. Overrides * {@link WorkflowConfig.nodeDefaults}. Absent ⇒ no timeout. */ readonly timeoutMs?: number; /** * Per-node bounded retry policy. Retries fire only * for thrown failures - never for `pause(...)` suspensions or * aborts - with exponential backoff. Overrides * {@link WorkflowConfig.nodeDefaults}. Absent ⇒ no retries. */ readonly retry?: WorkflowNodeRetryPolicy; } /** * Bounded retry policy for a workflow node. * * @stable */ interface WorkflowNodeRetryPolicy { /** Total attempts including the first (clamped to >= 1). Default 1. */ readonly maxAttempts?: number; /** Base backoff in ms, doubling per retry. Default 250. */ readonly backoffMs?: number; } /** * Per-node run callback. * * @stable */ type WorkflowNodeRun> = (state: Readonly, ctx: WorkflowContext) => Promise> | NodeRunResult; /** * Permissible return shapes from a node's `run(...)` callback. * * - `undefined` - the node performed a side effect with no state writes. * - `Partial` - channel writes (one entry per channel). * - `Dispatch | Dispatch[]` - schedule additional tasks for the next * execution step (see {@link Dispatch}). * - `(Partial | Dispatch)[]` - mix of writes and dispatches * produced in a single call. * * @stable */ type NodeRunResult> = undefined | Partial | DispatchLike | ReadonlyArray>; /** * Structural shape used to identify {@link Dispatch} instances without * pulling the concrete class into this module's import graph. Requires * the cross-realm brand: a bare `{ nodeName, args }` state object is * channel WRITES, never a dispatch - construct dispatches via * `dispatch(nodeName, args)` / `new Dispatch(...)`. * * @internal */ interface DispatchLike { readonly __graphorinDispatch: true; readonly nodeName: string; readonly args: unknown; } /** Predicate evaluated by the engine when deciding which edges to fire. */ type EdgePredicate> = (state: Readonly) => boolean; /** * Edge between two nodes. Edges with a `when` predicate fire only * when the predicate evaluates to truthy; unconditional edges always * fire when the source node completes. * * @stable */ interface WorkflowEdge> { readonly from: string; readonly to: string; readonly when?: EdgePredicate; } /** * Static `pauseAt` declaration. The engine consults the lists when * scheduling tasks: nodes named in `before` suspend before their `run` * is invoked; nodes in `after` complete normally and the engine * suspends right before the next planning round. * * @stable */ interface WorkflowPauseAt { readonly before?: ReadonlyArray; readonly after?: ReadonlyArray; } /** * Configuration accepted by {@link createWorkflow}. The shape is the * single point of contact between a consumer's workflow definition and * the runtime - every other public type derives from it. * * @stable */ interface WorkflowConfig> { readonly name: string; readonly nodes: Readonly>>; readonly edges: ReadonlyArray>; readonly channels: Readonly<{ [K in keyof TState]: Channel }>; /** Optional initial state - merged with the input on `execute(...)`. */ readonly initialState?: Partial; readonly pauseAt?: WorkflowPauseAt; readonly checkpointStore: CheckpointStore; /** Default durability mode. Defaults to `sync`. */ readonly durability?: DurabilityMode; /** Optional tracer; defaults to the framework's `NOOP_TRACER`. */ readonly tracer?: Tracer; /** * Maximum number of execution steps before the engine bails out - * an infinite-loop safeguard that surfaces as a structured error. * Counted PER INVOCATION of execute/resume/retry/tick - a durable * thread that cycles through timers and approvals for months * never trips it, and a capped-out invocation is retryable (retry * starts a fresh counter). Default: 200. */ readonly maxSteps?: number; /** * Opt-in LIFETIME quota over the cumulative step number across * every invocation of the thread. Default: undefined (no * lifetime cap). Fails with the same `max-steps-exceeded` code but a * distinct message. */ readonly maxTotalSteps?: number; /** * Grace window (in milliseconds) applied after `AbortSignal.abort()` * before in-flight task promises are considered orphaned. Default: * 100 ms. */ readonly cancelGraceMs?: number; /** * Optional state validator. When provided, the engine calls it after * applying every step's writes; any thrown error produces a * `state-validation-failed` workflow error and aborts the run. */ readonly validateState?: (state: TState) => void; /** * Default per-node execution policy, overridden by the same fields * on an individual {@link WorkflowNode}. */ readonly nodeDefaults?: { readonly timeoutMs?: number; readonly retry?: WorkflowNodeRetryPolicy; }; /** * Cap on tasks executing concurrently within one step. Planned * tasks beyond the cap queue and start as slots free up; `Dispatch` * fan-outs are bounded the same way. Absent ⇒ unbounded. */ readonly maxConcurrentTasks?: number; /** * Workflow definition version pin. Stamped into * every persisted frontier; a resume whose stored version differs * fails loudly with `workflow-version-mismatch` (opt out per call via * {@link WorkflowResumeOptions.allowVersionMismatch}). Absent ⇒ no * pinning. */ readonly version?: string; /** * Step-result journaling (opt-in). When `true`, the * engine journals a step-intent record plus each completed task's * channel writes against the PARENT checkpoint as tasks finish, so a * crash between task completion and the step checkpoint no longer * re-runs completed side effects: crash recovery replays the * journaled writes and re-runs only the unfinished tasks. Default * `false` (one extra store write per completed task when on). */ readonly journalSteps?: boolean; } /** * Snapshot returned by {@link Workflow.getState}. Combines the most * recent checkpoint state with the high-level run status / pending * pause payload. * * @stable */ interface WorkflowState> { readonly threadId: string; readonly stepNumber: number; readonly status: 'running' | 'suspended' | 'completed' | 'failed' | 'aborted'; readonly state: TState; readonly checkpointId: CheckpointId; /** Carries the value passed to `pause(value)` when status is `suspended`. */ readonly pendingPause?: PendingPauseRecord; /** * The FULL pending-pause set from the persisted frontier - * parallel pausers, durable timers (`wakeAt`), awakeables and * approvals (`name`) included. `pendingPause` remains the first entry * for backwards compatibility. */ readonly pendingPauses?: ReadonlyArray; } /** * Structured record stored alongside a suspended checkpoint so the * engine can resume the paused node with the operator's directive. * * @stable */ interface PendingPauseRecord { readonly nodeName: string; readonly value: unknown; /** Args supplied to {@link Dispatch} when the paused task was scheduled. */ readonly dispatchArgs?: unknown; /** When `true` the task was paused statically by `pauseAt.before`. */ readonly staticBefore?: boolean; /** When `true` the engine paused after the task completed, via `pauseAt.after`. */ readonly staticAfter?: boolean; /** * Ordered resume values ALREADY delivered to this node's earlier * `pause()` calls. On resume the body re-executes from the * top: these replay by index, and the new directive value lands at * the next cursor. */ readonly satisfied?: ReadonlyArray; /** * Per-value identity of the pause each `satisfied` entry * answered (`kind` for durable primitives, `name` for * awakeables/approvals; `null`/empty for plain `pause()`). Replay * verifies each entry against the CURRENT pause at that cursor and * fails with `pause-replay-divergence` on mismatch. Absent on * checkpoints written before the field existed - those replay * unchecked (back-compat). */ readonly satisfiedMeta?: ReadonlyArray<{ readonly kind?: string; readonly name?: string; } | null>; /** * Epoch ms at which a durable timer becomes due - present when * the suspension came from `sleepUntil(...)` / `sleepFor(...)`. * `workflow.tick(threadId)` resumes the thread once due. */ readonly wakeAt?: number; /** * Awakeable / approval name - present when the suspension came * from `awaitExternal(name)` or `requestApproval(name)`. Targeted by * `workflow.resolveAwakeable(...)` / `workflow.approve(...)`. */ readonly name?: string; } /** * Top-level handle returned by {@link createWorkflow}. * * @stable */ interface Workflow, TInput = Partial> { readonly name: string; readonly nodeNames: ReadonlyArray; execute(input: TInput, opts?: WorkflowExecuteOptions): AsyncIterable>; resume(threadId: string, directive?: Directive, opts?: WorkflowResumeOptions): AsyncIterable>; /** * Restart a `'failed'` thread from its last failure checkpoint: * successful sibling tasks of the failed step replay from their * persisted pending writes; only the failed work re-runs. */ retry(threadId: string, opts?: WorkflowResumeOptions): AsyncIterable>; /** * Fire due durable timers. Scans the thread's pending pauses for * `sleepUntil` records whose `wakeAt` has passed; when one is due the * thread resumes (draining the resulting events internally). Returns * whether a timer fired and the next earliest wake-at (epoch ms) still * pending, so schedulers know when to call again. */ tick(threadId: string, opts?: { readonly now?: number; }): Promise<{ readonly fired: boolean; readonly nextWakeAt: number | null; }>; /** * Resolve a named awakeable (durable promise): the suspended * `awaitExternal(name)` call returns `value` and the thread resumes. * Fails with `pause-not-found` when no pending pause carries the name. */ resolveAwakeable(threadId: string, name: string, value?: unknown, opts?: WorkflowResumeOptions): AsyncIterable>; /** * Resolve a named persisted approval - sugar over * {@link resolveAwakeable} for `requestApproval(name)` suspensions. */ approve(threadId: string, name: string, decision: unknown, opts?: WorkflowResumeOptions): AsyncIterable>; getState(threadId: string): Promise>; listCheckpoints(threadId: string): Promise>; /** * Delete every checkpoint and pending write of `threadId` across all * namespaces - the operator lever for per-thread hygiene and * targeted erasure requests. Idempotent: deleting an unknown thread * is a no-op. Deleting a merely-suspended thread (pending approval / * timer / awakeable) destroys its resume state - the caller decides. */ deleteThread(threadId: string): Promise; /** * Clone `threadId`'s timeline at `fromCheckpointId` into a fresh * thread (the original stays untouched). `opts.patch` merges * channel-level values into the forked root's state (branch here, * but with these corrected values) - keys must name declared * channels, and the merged state re-runs the JSON-safety guard. * `channelVersions` and pending writes ride along unchanged. */ fork(threadId: string, fromCheckpointId: CheckpointId, opts?: { readonly patch?: Readonly>; }): Promise<{ readonly newThreadId: string; }>; } //#endregion export { DispatchLike, DurabilityMode, END_NODE, EdgePredicate, NodeRunResult, PendingPauseRecord, START_NODE, StreamMode, TASKS_CHANNEL, Workflow, WorkflowConfig, WorkflowContext, WorkflowEdge, WorkflowExecuteOptions, WorkflowNode, WorkflowNodeRetryPolicy, WorkflowNodeRun, WorkflowPauseAt, WorkflowResumeOptions, WorkflowState }; //# sourceMappingURL=types.d.ts.map