@happyvertical/smrt-workflows 0.0.0-stage → 0.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/checkpoint-store.ts","../src/claim-fence.ts","../src/driver.ts","../src/jobs.ts"],"sourcesContent":["import {\n type AiRunCheckpoint,\n AiRunCheckpointConflictError,\n type AiRunClaimFence,\n type AiRunRow,\n getAiRun,\n readAiRunCheckpoint,\n saveAiRunCheckpoint,\n} from '@happyvertical/smrt-core';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport {\n WORKFLOW_RUN_TYPE,\n WORKFLOW_STATE_VERSION,\n type WorkflowCheckpointState,\n} from './types.js';\n\n/**\n * The run moved on underneath the caller (a checkpoint save from an older\n * revision, a run that is no longer where the caller expected, another\n * worker still holding it). Reload its current state.\n */\nexport class RunConflictError extends Error {\n constructor(message = 'Workflow run changed; reload its current status') {\n super(message);\n this.name = 'RunConflictError';\n }\n}\n\n/** A workflow run is not visible to this owner and tenant. */\nexport class WorkflowRunNotFoundError extends Error {\n constructor(readonly runId: string) {\n super('Workflow run not found');\n this.name = 'WorkflowRunNotFoundError';\n }\n}\n\n/** One workflow run with its checkpoint. */\nexport interface LoadedWorkflowRun {\n run: AiRunRow;\n checkpoint: AiRunCheckpoint;\n state: WorkflowCheckpointState;\n}\n\n/** Input of {@link RunCheckpointStore.save}. */\nexport interface SaveRunCheckpointInput {\n expectedRevision: number;\n state: WorkflowCheckpointState;\n lease?: string | null;\n definitionVersion?: string | null;\n}\n\n/** Owner- and tenant-scoped access to workflow checkpoints. */\nexport interface RunCheckpointStore {\n readonly db: DatabaseInterface;\n readonly ownerId: string;\n readonly tenantId: string | null;\n /** The run and its checkpoint, or null when this owner cannot see it. */\n load(runId: string): Promise<LoadedWorkflowRun | null>;\n /**\n * Save with the run row, compare-and-swap on `expectedRevision`, after the\n * claim fence. Throws {@link RunConflictError} when another save won; an\n * `AiRunStoppedError` when the run is no longer `running`.\n */\n save(runId: string, input: SaveRunCheckpointInput): Promise<number>;\n}\n\n/** Options of {@link createRunCheckpointStore}. */\nexport interface RunCheckpointStoreOptions {\n db: DatabaseInterface;\n /** The authenticated owner; never taken from model or tool arguments. */\n ownerId: string;\n tenantId?: string | null;\n /** The job claim of the worker running the run (claim fencing). */\n fence?: AiRunClaimFence;\n}\n\n/** Whether a stored state has the workflow state's shape. */\nexport function isWorkflowCheckpointState(\n value: unknown,\n): value is WorkflowCheckpointState {\n const state = value as Partial<WorkflowCheckpointState> | null;\n return Boolean(\n state &&\n typeof state === 'object' &&\n state.v === WORKFLOW_STATE_VERSION &&\n Number.isSafeInteger(state.stepIndex) &&\n (state.stepIndex as number) >= 0 &&\n (state.phase === 'call' || state.phase === 'check') &&\n Number.isSafeInteger(state.repairs) &&\n Number.isSafeInteger(state.repeats) &&\n Array.isArray(state.outputs) &&\n (state.inputRef === null || typeof state.inputRef === 'string'),\n );\n}\n\n/**\n * Workflow checkpoints in core's `_smrt_ai_run_checkpoints`, scoped to one\n * authenticated owner and tenant. It creates no schema: the table is core\n * system DDL.\n */\nexport function createRunCheckpointStore(\n options: RunCheckpointStoreOptions,\n): RunCheckpointStore {\n if (!options.ownerId) throw new Error('Workflow runs require an owner');\n const tenantId = options.tenantId ?? null;\n return {\n db: options.db,\n ownerId: options.ownerId,\n tenantId,\n async load(runId) {\n const run = await getAiRun(options.db, runId);\n if (\n !run ||\n run.type !== WORKFLOW_RUN_TYPE ||\n run.ownerId !== options.ownerId ||\n (run.tenantId ?? null) !== tenantId\n ) {\n return null;\n }\n const checkpoint = await readAiRunCheckpoint(options.db, runId);\n if (!checkpoint) return null;\n if (!isWorkflowCheckpointState(checkpoint.state)) {\n throw new TypeError(\n `Workflow run ${runId} has a checkpoint this package cannot read`,\n );\n }\n return { run, checkpoint, state: checkpoint.state };\n },\n async save(runId, input) {\n try {\n return await saveAiRunCheckpoint(options.db, runId, {\n expectedRevision: input.expectedRevision,\n state: input.state,\n ...(input.lease !== undefined ? { lease: input.lease } : {}),\n ...(input.definitionVersion !== undefined\n ? { definitionVersion: input.definitionVersion }\n : {}),\n ...(options.fence ? { fence: options.fence } : {}),\n });\n } catch (error) {\n if (error instanceof AiRunCheckpointConflictError) {\n throw new RunConflictError();\n }\n throw error;\n }\n },\n };\n}\n","import {\n type AiRunClaimFence,\n aiRunEngine,\n lockAiRunChain,\n} from '@happyvertical/smrt-core';\nimport {\n assertJobClaim,\n assertJobClaimForRelease,\n type JobClaim,\n JobClaimLostError,\n SmrtJobCollection,\n} from '@happyvertical/smrt-jobs';\n\n/**\n * Claim fencing for a workflow run worked from a background job: every\n * checkpoint save, step start, reservation, event and status change asserts,\n * inside its own transaction, that this worker still holds the job's claim\n * (`getJobClaim(context)` from a runner started with `claimFencing: true`).\n * A worker whose claim was taken over is refused before it writes.\n */\nexport function workflowClaimFence(claim: Readonly<JobClaim>): AiRunClaimFence {\n return (tx) => assertJobClaim(tx, claim);\n}\n\n/**\n * The fence of the stop a worker writes when its job's signal aborts: the\n * job may already be settled (cancelled, timed out), so this one accepts the\n * worker's own attempt in any state, and refuses a claim another worker took\n * over and a job that a newer job of the same run (same dedupe key; stale\n * recovery keeps the worker on the failed row) replaced\n * (`WorkflowRunOptions.stopFence`). It locks the durable run's chain, root\n * first (the page's lock order, so a settle on the same chain cannot\n * deadlock with it), before it looks for a newer job: a resume commits the\n * run's status and its new job together while holding that row, so the look\n * sees the new job once the resume has committed (on PostgreSQL each\n * statement reads what committed before it).\n */\nexport function workflowStopFence(claim: Readonly<JobClaim>): AiRunClaimFence {\n return async (tx, durableRunId) => {\n await assertJobClaimForRelease(tx, claim);\n // Root first down to the durable run: `FOR UPDATE` on PostgreSQL.\n await lockAiRunChain(\n { db: tx, engine: aiRunEngine(tx), now: new Date() },\n durableRunId,\n );\n // A no-op write on the durable row, already locked: on DuckDB it makes\n // a concurrent resume's write of that row conflict; SQLite serializes\n // its writers anyway.\n await tx.query(\n 'UPDATE _smrt_ai_runs SET retain = retain WHERE id = ?',\n durableRunId,\n );\n const jobs = await SmrtJobCollection.create({ db: tx });\n const own = await jobs.get({ id: claim.jobId });\n if (!own?.dedupeKey) return;\n const active = await jobs.list({\n where: {\n objectType: claim.objectType,\n dedupeKey: own.dedupeKey,\n tenantId: claim.tenantId,\n status: ['pending', 'running'],\n },\n });\n if (active.some((job) => String(job.id) !== claim.jobId)) {\n throw new JobClaimLostError();\n }\n };\n}\n","import {\n AiCallLimitError,\n type AiRunBudget,\n type AiRunCheckpoint,\n type AiRunClaimFence,\n AiRunClaimLostError,\n type AiRunContext,\n AiRunResumeRefusedError,\n AiRunStoppedError,\n type AiRunStopReason,\n appendAiRunEvent,\n cancelAiRun,\n finishAiRun,\n getAiRun,\n getRunTrajectory,\n reconcileAiRunOnClaim,\n resumeAiRun,\n startAiRunStep,\n stopAiRun,\n type TrackedAiClient,\n waitAiRunApproval,\n withAiRunTransaction,\n} from '@happyvertical/smrt-core';\nimport {\n promptMessageOptions,\n resolvePrompt,\n trackedPromptCall,\n} from '@happyvertical/smrt-prompts';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport {\n createRunCheckpointStore,\n isWorkflowCheckpointState,\n type LoadedWorkflowRun,\n type RunCheckpointStore,\n RunConflictError,\n WorkflowRunNotFoundError,\n} from './checkpoint-store.js';\nimport {\n type RunProgress,\n WORKFLOW_RUN_TYPE,\n WORKFLOW_STATE_VERSION,\n type WorkflowCheckpointState,\n type WorkflowDefinition,\n type WorkflowRunState,\n type WorkflowStep,\n type WorkflowStepCheck,\n type WorkflowStepContext,\n} from './types.js';\n\n/** A step's output could not be read as the step's JSON (a repairable attempt). */\nexport class WorkflowOutputError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'WorkflowOutputError';\n }\n}\n\n/** Host wiring of one workflow definition. */\nexport interface WorkflowRunDriverOptions {\n /**\n * Core's tracked client of the runs' tenant and database\n * (`createTrackedAiClient`): runs open through it, and every step call is\n * sent on it with the run's context.\n */\n ai: TrackedAiClient;\n definition: WorkflowDefinition;\n /** The host's full JSON Schema validator (Ajv or equal); errors, or none. */\n validate(schema: Record<string, unknown>, output: unknown): readonly string[];\n /** Resolve input passed by reference (`inputRef`). */\n readInput?(\n ref: string,\n scope: { ownerId: string; tenantId: string | null },\n ): Promise<unknown>;\n /** Progress for the host's event stream; its failures never stop work. */\n onProgress?(progress: RunProgress): void | Promise<void>;\n /** The app's ceiling on a budget raised at resume. */\n ceiling?: AiRunBudget;\n /** Lease length while a worker holds a run (default 30 s). */\n leaseTtlMs?: number;\n now?: () => Date;\n}\n\n/** Input of `start`. */\nexport interface StartWorkflowRun {\n /** The authenticated owner. */\n ownerId: string;\n /** Minted when absent. */\n id?: string;\n /** Small input, kept in the checkpoint. */\n input?: unknown;\n /** A pointer at large input the host stores; resolved with `readInput`. */\n inputRef?: string | null;\n budget?: AiRunBudget;\n tags?: Record<string, unknown>;\n experimentId?: string | null;\n datasetItem?: string | null;\n parentRunId?: string | null;\n}\n\n/** Options of `run`. */\nexport interface WorkflowRunOptions {\n /** Cooperative stop: the job's signal. Aborting stops with `interrupted`. */\n signal?: AbortSignal;\n /**\n * Claim fencing: asserts, in every checkpoint save, step start,\n * reservation, event and status change, that this worker still holds the\n * run's job claim. A worker whose claim was taken over changes nothing: the\n * run rejects with `AiRunClaimLostError` and leaves the run to the worker\n * that holds it now.\n */\n fence?: AiRunClaimFence;\n /**\n * The fence of the stop this worker writes when its signal aborts (default\n * `fence`). The job behind that signal may already be settled (cancelled,\n * timed out), so this one accepts this worker's own attempt in any state\n * and refuses only a claim another worker took over\n * (`workflowStopFence(claim)`).\n */\n stopFence?: AiRunClaimFence;\n /** Who holds the run while it works; written to and renewed on the lease. */\n holder?: string;\n}\n\n/** A lease as stored in the checkpoint's `lease` column. */\nexport interface WorkflowRunLease {\n holder: string;\n expiresAt: string;\n}\n\n/** Read a checkpoint's lease; null when absent or not one of ours. */\nexport function readWorkflowRunLease(\n checkpoint: Pick<AiRunCheckpoint, 'lease'>,\n): WorkflowRunLease | null {\n if (!checkpoint.lease) return null;\n try {\n const parsed = JSON.parse(checkpoint.lease) as Partial<WorkflowRunLease>;\n return typeof parsed.holder === 'string' &&\n typeof parsed.expiresAt === 'string'\n ? { holder: parsed.holder, expiresAt: parsed.expiresAt }\n : null;\n } catch {\n return null;\n }\n}\n\n/** The first state of a run. */\nexport function initialWorkflowState(\n input: unknown,\n inputRef: string | null,\n): WorkflowCheckpointState {\n return {\n v: WORKFLOW_STATE_VERSION,\n stepIndex: 0,\n phase: 'call',\n repairs: 0,\n repeats: 0,\n input: input ?? null,\n inputRef,\n outputs: [],\n pending: null,\n invalid: null,\n approval: null,\n };\n}\n\nfunction parseOutput(raw: unknown): unknown {\n let value = raw;\n if (\n value &&\n typeof value === 'object' &&\n typeof (value as { content?: unknown }).content === 'string'\n ) {\n value = (value as { content: string }).content;\n }\n if (typeof value !== 'string') return value;\n const text = value\n .trim()\n .replace(/^```(?:json)?\\s*/i, '')\n .replace(/\\s*```$/, '');\n try {\n return JSON.parse(text);\n } catch {\n throw new WorkflowOutputError('The step output is not valid JSON');\n }\n}\n\nfunction serial() {\n let tail: Promise<unknown> = Promise.resolve();\n return <T>(operation: () => Promise<T>): Promise<T> => {\n const next = tail.then(operation, operation);\n tail = next.catch(() => undefined);\n return next;\n };\n}\n\n/**\n * The workflow run driver: a host's ordered steps run as one durable\n * `workflow` run (docs/content/ai-runs.md). Each step's call resolves its\n * registered prompt and goes out on the tracked client inside the run, so it\n * is reserved against the budget, recorded as a `call` event and a usage row\n * carrying the step, attempt and template hash, and settled. Invalid output\n * is repaired up to `repairRetries`; accepted output goes to the host check\n * (a `check` event) and may pause for approval (`approval` events). A budget\n * limit stops the run resumable; a child run's stop stops it the same way,\n * never as a repair. It owns no queue: a host runs it from a background job\n * with claim fencing, and the job's signal stops it.\n */\nexport function createWorkflowRunDriver(options: WorkflowRunDriverOptions) {\n const { ai, definition } = options;\n const steps = definition.steps;\n if (!steps.length) throw new Error('A workflow needs steps');\n if (!definition.key.trim() || !definition.version.trim()) {\n throw new Error('A workflow definition needs a key and a version');\n }\n const db = ai.db;\n const tenantId = ai.tenantId ?? null;\n const leaseTtlMs = options.leaseTtlMs ?? 30_000;\n const now = options.now ?? (() => new Date());\n const active = new Map<string, AbortController>();\n\n const acceptsVersion = (version: string | null) =>\n version === definition.version ||\n Boolean(definition.olderCheckpoints?.accepts(version));\n\n const storeFor = (ownerId: string, fence?: AiRunClaimFence) =>\n createRunCheckpointStore({\n db,\n ownerId,\n tenantId,\n ...(fence ? { fence } : {}),\n });\n\n const mustLoad = async (store: RunCheckpointStore, runId: string) => {\n const loaded = await store.load(runId);\n if (!loaded || loaded.run.definitionKey !== definition.key) {\n throw new WorkflowRunNotFoundError(runId);\n }\n return loaded;\n };\n\n const stepInfo = (index: number) => {\n const at = Math.min(index, steps.length - 1);\n return {\n index: Math.min(index + 1, steps.length),\n count: steps.length,\n name: (steps[at] as WorkflowStep).name,\n };\n };\n\n const snapshot = (loaded: LoadedWorkflowRun): WorkflowRunState => {\n const { run, checkpoint, state } = loaded;\n return {\n id: run.id,\n ownerId: run.ownerId,\n tenantId: run.tenantId,\n definitionKey: run.definitionKey,\n definitionVersion: checkpoint.definitionVersion,\n status: run.status,\n stopReason: run.stopReason,\n stoppedByRunId: run.stoppedByRunId,\n stopDetail: run.stopDetail,\n retryOfRunId: run.retryOfRunId,\n budget: run.budget,\n revision: checkpoint.revision,\n step: stepInfo(state.stepIndex),\n phase: state.phase,\n input: state.input,\n inputRef: state.inputRef,\n outputs: [...state.outputs],\n pending: state.pending?.output ?? null,\n totals: {\n tokens: run.tokens,\n calls: run.calls,\n costUsed: run.costUsed,\n stepsUsed: run.stepsUsed,\n inclusiveTokens: run.inclusiveTokens,\n inclusiveCalls: run.inclusiveCalls,\n inclusiveCost: run.inclusiveCost,\n },\n };\n };\n\n const emit = async (state: WorkflowRunState) => {\n try {\n await options.onProgress?.({\n runId: state.id,\n step: state.step,\n status: state.status,\n stopReason: state.stopReason,\n phase: state.phase,\n });\n } catch {\n /* the durable state is authoritative */\n }\n };\n\n const current = async (store: RunCheckpointStore, runId: string) => {\n const state = snapshot(await mustLoad(store, runId));\n await emit(state);\n return state;\n };\n\n /** The `call` or `handoff` event an attempt's output came from. */\n const judgedEvent = async (\n runId: string,\n afterSeq: number,\n stepIndex: number,\n ): Promise<string | null> => {\n const trajectory = await getRunTrajectory(db, runId);\n const candidates = (trajectory?.entries ?? [])\n .map((entry) => entry.event)\n .filter(\n (event): event is NonNullable<typeof event> =>\n Boolean(event) &&\n (event?.seq ?? 0) > afterSeq &&\n (event?.type === 'call' || event?.type === 'handoff') &&\n (event?.stepIndex === null || event?.stepIndex === stepIndex),\n );\n return candidates[candidates.length - 1]?.id ?? null;\n };\n\n const lastSeq = async (runId: string) => {\n const trajectory = await getRunTrajectory(db, runId);\n return (trajectory?.entries ?? []).reduce(\n (max, entry) => Math.max(max, entry.event?.seq ?? 0),\n 0,\n );\n };\n\n const approvalDecision = async (\n runId: string,\n requestEventId: string,\n ): Promise<'approved' | 'refused' | null> => {\n const trajectory = await getRunTrajectory(db, runId);\n for (const entry of [...(trajectory?.entries ?? [])].reverse()) {\n const event = entry.event;\n if (\n event?.type === 'approval' &&\n event.parentEventId === requestEventId &&\n (event.status === 'approved' || event.status === 'refused')\n ) {\n return event.status;\n }\n }\n return null;\n };\n\n const resolveInput = async (\n state: WorkflowCheckpointState,\n ownerId: string,\n ) => {\n if (state.inputRef === null) return state.input;\n if (!options.readInput) {\n throw new Error('This workflow passes input by reference: set readInput');\n }\n return options.readInput(state.inputRef, { ownerId, tenantId });\n };\n\n const defaultVariables = (\n step: WorkflowStep,\n context: WorkflowStepContext,\n ): Record<string, unknown> => ({\n input: JSON.stringify(context.input ?? null),\n outputs: JSON.stringify(context.outputs),\n schema: JSON.stringify(step.schema),\n attempt: String(context.attempt),\n repairOutput: context.repair ? JSON.stringify(context.repair.output) : '',\n repairErrors: context.repair ? context.repair.errors.join('\\n') : '',\n });\n\n /** One attempt of a step's call; returns its output. */\n const callStep = async (\n step: WorkflowStep,\n context: WorkflowStepContext,\n runContext: AiRunContext,\n ): Promise<unknown> => {\n if (step.execute) {\n return parseOutput(await step.execute({ ...context, runContext }));\n }\n const variables = step.variables\n ? await step.variables(context)\n : defaultVariables(step, context);\n const resolved = await resolvePrompt(step.promptKey, {\n db,\n tenantId,\n variables,\n });\n const client = await ai.client(trackedPromptCall(resolved), { runContext });\n // The prompt's call options (params, model, temperature, maxTokens, its\n // effort as `reasoning`); its tier is already on the tracked client, so\n // no tier keys ride on the call. The driver's own options win; core\n // spreads the tier binding's params under all of them.\n const answer = await client.message(resolved.text, {\n ...promptMessageOptions(resolved.ai, { routeTier: false }),\n signal: context.signal,\n ...(step.expectedOutputTokens !== undefined\n ? { expectedOutputTokens: step.expectedOutputTokens }\n : {}),\n } as Parameters<typeof client.message>[1]);\n return parseOutput(answer);\n };\n\n return {\n definition,\n\n /**\n * Open the durable `workflow` run with its first checkpoint, in one\n * transaction. Throws `AiRunTrackingDisabledError` while usage tracking\n * is off. Schedule `run` on a background job; never on a request.\n */\n async start(input: StartWorkflowRun): Promise<WorkflowRunState> {\n if (!input.ownerId) throw new Error('Workflow runs require an owner');\n const { run } = await ai.openRun({\n ...(input.id ? { id: input.id } : {}),\n type: WORKFLOW_RUN_TYPE,\n definitionKey: definition.key,\n definitionVersion: definition.version,\n ownerId: input.ownerId,\n durable: true,\n checkpoint: {\n state: initialWorkflowState(\n input.inputRef ? null : (input.input ?? null),\n input.inputRef ?? null,\n ),\n },\n ...(input.budget ? { budget: input.budget } : {}),\n ...(input.tags ? { tags: input.tags } : {}),\n ...(input.experimentId ? { experimentId: input.experimentId } : {}),\n ...(input.datasetItem ? { datasetItem: input.datasetItem } : {}),\n ...(input.parentRunId ? { parentRunId: input.parentRunId } : {}),\n });\n return current(storeFor(input.ownerId), run.id);\n },\n\n /** The run as this owner sees it. */\n get(runId: string, ownerId: string): Promise<WorkflowRunState> {\n return mustLoad(storeFor(ownerId), runId).then(snapshot);\n },\n\n /**\n * Work the run until it finishes, stops, fails or waits for approval.\n * Run it only from the job that holds the run, with that job's signal\n * and claim fence. Reconciles reservations a dead worker left behind\n * before the first call.\n */\n async run(\n runId: string,\n ownerId: string,\n runOptions: WorkflowRunOptions = {},\n ): Promise<WorkflowRunState> {\n const store = storeFor(ownerId, runOptions.fence);\n let loaded = await mustLoad(store, runId);\n if (loaded.run.status !== 'running') return snapshot(loaded);\n if (active.has(runId)) {\n throw new RunConflictError('This workflow run is already working');\n }\n const controller = new AbortController();\n const abort = () => controller.abort(runOptions.signal?.reason);\n runOptions.signal?.addEventListener('abort', abort, { once: true });\n if (runOptions.signal?.aborted) abort();\n active.set(runId, controller);\n const queue = serial();\n const fence = runOptions.fence;\n const fenced = fence ? { fence } : {};\n const stopFence = runOptions.stopFence ?? fence;\n let revision = loaded.checkpoint.revision;\n let state = loaded.state;\n const lease = () =>\n runOptions.holder\n ? JSON.stringify({\n holder: runOptions.holder,\n expiresAt: new Date(now().getTime() + leaseTtlMs).toISOString(),\n } satisfies WorkflowRunLease)\n : undefined;\n const persist = (\n next: WorkflowCheckpointState,\n extra: { definitionVersion?: string } = {},\n ) =>\n queue(async () => {\n revision = await store.save(runId, {\n expectedRevision: revision,\n state: next,\n ...extra,\n });\n state = next;\n });\n let renewal: ReturnType<typeof setInterval> | undefined;\n const stopIfRunning = async (\n reason: 'interrupted' | 'definition_changed',\n ) => {\n await stopAiRun(db, runId, {\n reason,\n ...(stopFence ? { fence: stopFence } : {}),\n }).catch((error) => {\n // A worker whose claim was taken over leaves the run alone.\n if (error instanceof AiRunClaimLostError) throw error;\n return null;\n });\n };\n const fail = async (\n stopReason: Extract<\n AiRunStopReason,\n 'repairs_exhausted' | 'check_failed' | 'error'\n >,\n ) => {\n await finishAiRun(db, runId, { status: 'failed', stopReason }, fenced);\n };\n try {\n await reconcileAiRunOnClaim(db, runId);\n // Resume across versions (page section 7).\n const saved = loaded.checkpoint.definitionVersion;\n if (saved !== definition.version) {\n let migrated: WorkflowCheckpointState | null = null;\n if (definition.olderCheckpoints?.accepts(saved)) {\n try {\n const candidate = definition.olderCheckpoints.migrate(\n state,\n saved,\n );\n if (isWorkflowCheckpointState(candidate)) migrated = candidate;\n } catch {\n migrated = null;\n }\n }\n if (!migrated) {\n await stopIfRunning('definition_changed');\n return await current(store, runId);\n }\n await persist(migrated, { definitionVersion: definition.version });\n }\n const holderLease = lease();\n if (holderLease) {\n await queue(async () => {\n revision = await store.save(runId, {\n expectedRevision: revision,\n state,\n lease: holderLease,\n });\n });\n renewal = setInterval(\n () => {\n const renewed = lease();\n void queue(async () => {\n revision = await store.save(runId, {\n expectedRevision: revision,\n state,\n lease: renewed ?? null,\n });\n }).catch(() => {\n // The run left `running` or the claim was lost: the next\n // write of the loop reports it; the lease expires.\n if (renewal) clearInterval(renewal);\n });\n },\n Math.max(10, Math.floor(leaseTtlMs / 3)),\n );\n renewal.unref?.();\n }\n\n let entered = false;\n let stepInstanceId: string | undefined;\n while (true) {\n if (state.stepIndex >= steps.length) {\n await finishAiRun(db, runId, { status: 'done' }, fenced);\n break;\n }\n if (controller.signal.aborted) {\n await stopIfRunning('interrupted');\n break;\n }\n const step = steps[state.stepIndex] as WorkflowStep;\n const base: WorkflowStepContext = {\n runId,\n step: stepInfo(state.stepIndex),\n input: await resolveInput(state, ownerId),\n outputs: state.outputs.slice(0, state.stepIndex),\n attempt: state.repairs + 1,\n repair: state.invalid,\n signal: controller.signal,\n };\n\n if (state.phase === 'call') {\n if (!entered) {\n const started = await queue(() =>\n startAiRunStep(db, runId, {\n stepIndex: state.stepIndex,\n ...(fence ? { fence } : {}),\n checkpoint: { expectedRevision: revision, state },\n }),\n );\n if (started.revision !== null) revision = started.revision;\n stepInstanceId = started.stepInstanceId;\n entered = true;\n await current(store, runId);\n }\n const runContext: AiRunContext = {\n runId,\n db,\n tenantId,\n ...(fence ? { fence } : {}),\n stepIndex: state.stepIndex,\n stepName: step.name,\n ...(stepInstanceId ? { stepInstanceId } : {}),\n attempt: base.attempt,\n };\n const before = await lastSeq(runId);\n let output: unknown;\n let errors: string[] = [];\n try {\n output = await callStep(step, base, runContext);\n } catch (error) {\n if (\n error instanceof AiRunStoppedError ||\n error instanceof AiRunClaimLostError\n ) {\n throw error;\n }\n if (controller.signal.aborted) {\n await stopIfRunning('interrupted');\n break;\n }\n if (\n error instanceof WorkflowOutputError ||\n error instanceof AiCallLimitError\n ) {\n errors = [error.message];\n } else {\n throw error;\n }\n }\n if (!errors.length) {\n errors = [...options.validate(step.schema, output)];\n }\n if (errors.length) {\n const retries = loaded.run.budget.repairRetries ?? 0;\n if (state.repairs >= retries) {\n await fail('repairs_exhausted');\n break;\n }\n await persist({\n ...state,\n repairs: state.repairs + 1,\n invalid: { output: output ?? null, errors },\n });\n continue;\n }\n await persist({\n ...state,\n phase: 'check',\n pending: {\n output,\n judgedEventId: await judgedEvent(\n runId,\n before,\n state.stepIndex,\n ),\n },\n invalid: null,\n });\n continue;\n }\n\n // The check phase: the accepted output awaits the host check.\n const pending = state.pending ?? {\n output: null,\n judgedEventId: null,\n };\n let approval: 'approved' | null = null;\n if (state.approval) {\n const decision = await approvalDecision(\n runId,\n state.approval.requestEventId,\n );\n if (decision === 'refused') {\n await fail('check_failed');\n break;\n }\n if (decision !== 'approved') {\n await waitAiRunApproval(db, runId, fenced);\n break;\n }\n approval = 'approved';\n // The decided hold is no longer outstanding; count it once.\n await persist({\n ...state,\n approval: null,\n approvals: (state.approvals ?? 0) + 1,\n });\n }\n const result: WorkflowStepCheck = step.check\n ? await step.check(pending.output, {\n ...base,\n approval,\n approvals: state.approvals ?? 0,\n })\n : {};\n if (controller.signal.aborted) {\n await stopIfRunning('interrupted');\n break;\n }\n const input =\n result.input !== undefined\n ? { input: result.input, inputRef: null }\n : { input: state.input, inputRef: state.inputRef };\n const checkEvent = (status: 'passed' | 'failed') =>\n appendAiRunEvent(\n db,\n runId,\n {\n type: 'check',\n status,\n parentEventId: pending.judgedEventId,\n stepIndex: state.stepIndex,\n name: step.name,\n ...(result.note || result.failure\n ? {\n payload: {\n ...(result.note ? { note: result.note } : {}),\n ...(result.failure ? { failure: result.failure } : {}),\n },\n }\n : {}),\n },\n fenced,\n );\n if (result.failure !== undefined) {\n await checkEvent('failed');\n await fail('check_failed');\n break;\n }\n if (result.waitingApproval) {\n // Every hold is its own request; one approved earlier never\n // passes a later one (a step may gate several actions).\n const request = await appendAiRunEvent(\n db,\n runId,\n {\n type: 'approval',\n status: 'requested',\n parentEventId: pending.judgedEventId,\n stepIndex: state.stepIndex,\n name: step.name,\n ...(result.note ? { payload: { note: result.note } } : {}),\n ...(result.holdRef ? { payloadRef: result.holdRef } : {}),\n },\n fenced,\n );\n await persist({\n ...state,\n ...input,\n approval: { requestEventId: request.id },\n });\n await waitAiRunApproval(db, runId, fenced);\n break;\n }\n if (result.repeat) {\n await checkEvent('failed');\n if (state.repeats >= (step.maxRepeats ?? 0)) {\n await fail('check_failed');\n break;\n }\n await persist({\n ...state,\n ...input,\n phase: 'call',\n repeats: state.repeats + 1,\n repairs: 0,\n pending: null,\n invalid: null,\n approval: null,\n approvals: 0,\n });\n entered = false;\n continue;\n }\n await checkEvent('passed');\n const outputs = state.outputs.slice(0, state.stepIndex);\n outputs[state.stepIndex] = pending.output;\n if (result.complete) {\n await persist({\n ...state,\n ...input,\n outputs,\n pending: null,\n approval: null,\n approvals: 0,\n });\n await finishAiRun(db, runId, { status: 'done' }, fenced);\n break;\n }\n await persist({\n ...state,\n ...input,\n stepIndex: state.stepIndex + 1,\n phase: 'call',\n repairs: 0,\n repeats: 0,\n outputs,\n pending: null,\n invalid: null,\n approval: null,\n approvals: 0,\n });\n entered = false;\n }\n } catch (error) {\n if (\n error instanceof AiRunClaimLostError ||\n error instanceof RunConflictError\n ) {\n throw error;\n }\n if (!(error instanceof AiRunStoppedError)) {\n if (controller.signal.aborted) await stopIfRunning('interrupted');\n else await fail('error');\n }\n // A stop (a budget limit, a child's stop, a stop or cancel from\n // outside) is already written to the run: it is never a repair.\n } finally {\n if (renewal) clearInterval(renewal);\n runOptions.signal?.removeEventListener('abort', abort);\n if (active.get(runId) === controller) active.delete(runId);\n }\n loaded = await mustLoad(store, runId);\n const finalState = snapshot(loaded);\n await emit(finalState);\n return finalState;\n },\n\n /** Pause the run (`stopped`, `interrupted`): resumable. */\n async stop(runId: string, ownerId: string): Promise<WorkflowRunState> {\n const store = storeFor(ownerId);\n const { run } = await mustLoad(store, runId);\n if (run.status === 'running' || run.status === 'waiting-approval') {\n await stopAiRun(db, runId, { reason: 'interrupted', from: run.status });\n }\n active.get(runId)?.abort(new Error('Workflow run stopped'));\n return current(store, runId);\n },\n\n /** End the run for good, with every child run: never resumed or retried. */\n async cancel(runId: string, ownerId: string): Promise<WorkflowRunState> {\n const store = storeFor(ownerId);\n await mustLoad(store, runId);\n await cancelAiRun(db, runId);\n active.get(runId)?.abort(new Error('Workflow run cancelled'));\n return current(store, runId);\n },\n\n /**\n * Resume a stopped run (page section 7): under this definition version\n * (or one that accepts the checkpoint), with limits only raised and at\n * most to the app's ceiling; a budget stop needs the limit that stopped\n * it raised. Reconciles the run's stale reservations first. Then admit\n * its job again: with `admit`, the status change and `admit`'s writes\n * (the new job) commit in one transaction, so no stale worker's stop\n * can land between them.\n */\n async resume(\n runId: string,\n ownerId: string,\n resumeOptions: {\n budget?: AiRunBudget;\n fence?: AiRunClaimFence;\n admit?: (tx: DatabaseInterface, budget: AiRunBudget) => Promise<void>;\n } = {},\n ): Promise<WorkflowRunState> {\n const store = storeFor(ownerId);\n await mustLoad(store, runId);\n if (active.has(runId)) {\n throw new RunConflictError(\n 'The previous run is still stopping. Try again when it has stopped.',\n );\n }\n const resumeWith = (database: DatabaseInterface, reconcile: boolean) =>\n resumeAiRun(database, runId, {\n ...(resumeOptions.budget ? { budget: resumeOptions.budget } : {}),\n ...(options.ceiling ? { ceiling: options.ceiling } : {}),\n definitionVersion: definition.version,\n acceptsVersion,\n ...(resumeOptions.fence ? { fence: resumeOptions.fence } : {}),\n ...(reconcile\n ? {\n reconcile: async (target: DatabaseInterface, id: string) => {\n await reconcileAiRunOnClaim(target, id);\n },\n }\n : {}),\n });\n const admit = resumeOptions.admit;\n if (!admit) {\n await resumeWith(db, true);\n return current(store, runId);\n }\n await reconcileAiRunOnClaim(db, runId);\n // One accounting transaction for the status change and the enqueue:\n // retried as a whole on a conflict, with PostgreSQL's lock timeout.\n const refused = await withAiRunTransaction(db, async (tx) => {\n let resumed: Awaited<ReturnType<typeof resumeAiRun>>;\n try {\n resumed = await resumeWith(tx.db, false);\n } catch (error) {\n // A refusal may have written its reason (`definition_changed`):\n // commit it, admit nothing, and throw after the commit.\n if (error instanceof AiRunResumeRefusedError) return error;\n throw error;\n }\n await admit(tx.db, resumed.budget);\n return null;\n });\n if (refused) throw refused;\n return current(store, runId);\n },\n\n /**\n * Record a person's decision on the approval the run waits for (an\n * `approval` event whose parent is the request). Approved: the run goes\n * back to `running` and its next `run` re-runs the check with the\n * approval; refused: the run fails with `check_failed`. A run stopped\n * while it waited keeps the decision and stays stopped: `resume` then\n * continues with it.\n */\n async decide(\n runId: string,\n ownerId: string,\n decision: { approved: boolean; note?: string },\n ): Promise<WorkflowRunState> {\n const store = storeFor(ownerId);\n const loaded = await mustLoad(store, runId);\n const request = loaded.state.approval?.requestEventId;\n const stopped = loaded.run.status === 'stopped';\n if ((loaded.run.status !== 'waiting-approval' && !stopped) || !request) {\n throw new RunConflictError(\n 'This workflow run is not waiting for approval',\n );\n }\n if (stopped && (await approvalDecision(runId, request))) {\n throw new RunConflictError('This approval was already decided');\n }\n await appendAiRunEvent(db, runId, {\n type: 'approval',\n status: decision.approved ? 'approved' : 'refused',\n parentEventId: request,\n stepIndex: loaded.state.stepIndex,\n name: stepInfo(loaded.state.stepIndex).name,\n ...(decision.note ? { payload: { note: decision.note } } : {}),\n });\n if (stopped) {\n // A stopped run keeps the decision; `resume` continues with it (an\n // approval re-runs the check, a refusal fails the step).\n } else if (decision.approved) {\n await resumeAiRun(db, runId, {\n definitionVersion: definition.version,\n acceptsVersion,\n });\n } else {\n await finishAiRun(\n db,\n runId,\n { status: 'failed', stopReason: 'check_failed' },\n { from: 'waiting-approval' },\n );\n }\n return current(store, runId);\n },\n\n /**\n * Retry a failed run from its last accepted step (page section 7): a new\n * durable run naming it in `retry_of_run_id`, inheriting only the\n * accepted outputs of its completed steps; its totals start at zero and\n * the inherited steps are not counted against its `maxSteps`. Refused\n * with `AiRunResumeRefusedError` (`not_retryable`, `definition_changed`,\n * `retry_source_pruned`) and nothing is opened.\n */\n async retry(\n runId: string,\n ownerId: string,\n retryOptions: { id?: string; budget?: AiRunBudget } = {},\n ): Promise<WorkflowRunState> {\n const store = storeFor(ownerId);\n const failed = await store.load(runId);\n if (failed && failed.run.definitionKey !== definition.key) {\n throw new WorkflowRunNotFoundError(runId);\n }\n if (!failed) {\n // Not visible, or pruned: core decides which and refuses.\n const visible = await getAiRun(db, runId);\n if (\n visible &&\n (visible.type !== WORKFLOW_RUN_TYPE ||\n visible.definitionKey !== definition.key ||\n visible.ownerId !== ownerId ||\n (visible.tenantId ?? null) !== tenantId)\n ) {\n throw new WorkflowRunNotFoundError(runId);\n }\n }\n const { run } = await ai.openRun({\n ...(retryOptions.id ? { id: retryOptions.id } : {}),\n type: WORKFLOW_RUN_TYPE,\n definitionKey: definition.key,\n definitionVersion: definition.version,\n ownerId,\n retryOfRunId: runId,\n ...(retryOptions.budget ? { budget: retryOptions.budget } : {}),\n retry: {\n acceptsVersion,\n carry: (checkpoint) => {\n let source = checkpoint.state;\n if (\n checkpoint.definitionVersion !== definition.version &&\n definition.olderCheckpoints &&\n isWorkflowCheckpointState(source)\n ) {\n source = definition.olderCheckpoints.migrate(\n source,\n checkpoint.definitionVersion,\n );\n }\n if (!isWorkflowCheckpointState(source)) {\n throw new TypeError(\n `Workflow run ${runId} has a checkpoint this package cannot read`,\n );\n }\n const stepIndex = source.stepIndex;\n return {\n state: {\n ...initialWorkflowState(source.input, source.inputRef),\n stepIndex,\n outputs: source.outputs.slice(0, stepIndex),\n },\n highestStepIndex: stepIndex > 0 ? stepIndex - 1 : null,\n };\n },\n },\n });\n return current(store, run.id);\n },\n };\n}\n\n/** A workflow run driver. */\nexport type WorkflowRunDriver = ReturnType<typeof createWorkflowRunDriver>;\n","import { createHash } from 'node:crypto';\nimport {\n type AiRunBudget,\n cancelAiRun,\n createTrackedAiClient,\n finishAiRun,\n getAiRun,\n stopAiRun,\n} from '@happyvertical/smrt-core';\nimport {\n assertFailedJobDispatch,\n assertJobClaim,\n getJobClaim,\n isRunnerExecutionContext,\n type JobClaim,\n JobClaimLostError,\n type JobExecutionContext,\n JobHandle,\n jobHandlerTarget,\n listJobHandlers,\n registerJobHandler,\n SmrtJobCollection,\n SmrtJobEventCollection,\n unregisterJobHandler,\n} from '@happyvertical/smrt-jobs';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport {\n createRunCheckpointStore,\n RunConflictError,\n WorkflowRunNotFoundError,\n} from './checkpoint-store.js';\nimport { workflowClaimFence, workflowStopFence } from './claim-fence.js';\nimport {\n createWorkflowRunDriver,\n type WorkflowRunDriverOptions,\n} from './driver.js';\nimport {\n WORKFLOW_RUN_TYPE,\n type WorkflowDefinition,\n type WorkflowRunState,\n} from './types.js';\n\n/** The named job handler every workflow run's job targets. */\nexport const WORKFLOW_RUN_HANDLER =\n '@happyvertical/smrt-workflows:workflow-run';\n\n/** The payload of a workflow run job: the run id and the definition's key. */\nexport interface WorkflowRunJobPayload {\n runId: string;\n definition: string;\n}\n\n/** The authenticated owner and tenant of a run; never taken from a payload. */\nexport interface WorkflowRunOwner {\n ownerId: string;\n tenantId: string | null;\n}\n\n/** A start key was already used with a different request. */\nexport class WorkflowRunKeyConflictError extends Error {\n constructor(readonly runId: string) {\n super('This workflow key was already used with a different request');\n this.name = 'WorkflowRunKeyConflictError';\n }\n}\n\n/** A workflow run job could not be dispatched. Never retried. */\nexport class WorkflowRunJobError extends Error {\n /** Read by the job runner's retry hints: never retried. */\n readonly retryable = false;\n constructor(message: string) {\n super(message);\n this.name = 'WorkflowRunJobError';\n }\n}\n\n/** Host wiring of the job bridge for one workflow definition. */\nexport interface WorkflowRunJobsOptions<Input> {\n db: DatabaseInterface;\n /** The job collection to enqueue on (default: one over `db`). */\n jobs?: SmrtJobCollection;\n definition: WorkflowDefinition;\n /** The queue the run's jobs go to (default `default`). */\n queue?: string;\n /** The host's permission check; runs on every operation and every job. */\n authorize?(owner: WorkflowRunOwner): Promise<void>;\n /**\n * Cap or refuse the effective budget on an ordinary resume; runs before any\n * write. Return the budget to resume with, or throw.\n */\n resumeBudget?(\n owner: WorkflowRunOwner,\n state: Readonly<WorkflowRunState>,\n proposed: Readonly<AiRunBudget>,\n ): Promise<AiRunBudget>;\n /**\n * Rebuild the driver's wiring (tracked client, validator, callbacks) for a\n * run's owner and input. Called again after a restart: never keep process\n * state a job needs in a closure. The `ai` client must be the owner's\n * tenant on `db`.\n */\n configure(\n owner: WorkflowRunOwner,\n input: Input,\n ): Omit<WorkflowRunDriverOptions, 'definition'>;\n}\n\n/** Input of `start`. A key makes the start idempotent. */\nexport interface StartWorkflowRunJob<Input> {\n /** Scopes idempotency to this definition, owner and tenant. */\n key: string;\n input?: Input;\n inputRef?: string | null;\n budget?: AiRunBudget;\n tags?: Record<string, unknown>;\n}\n\ninterface JobsHost {\n execute(\n payload: WorkflowRunJobPayload,\n context: JobExecutionContext,\n ): Promise<{ runId: string; status: string }>;\n}\n\n/** Definition key -> the host that serves it. Process-local, filled at creation. */\nconst hosts = new Map<string, JobsHost>();\n\nfunction readPayload(payload: unknown): WorkflowRunJobPayload {\n const value = payload as Partial<WorkflowRunJobPayload> | null;\n if (\n !value ||\n typeof value.runId !== 'string' ||\n !value.runId ||\n typeof value.definition !== 'string' ||\n !value.definition\n ) {\n throw new WorkflowRunJobError('A workflow run job needs a run id');\n }\n return { runId: value.runId, definition: value.definition };\n}\n\nasync function workflowRunHandler(\n payload: Record<string, unknown>,\n context: JobExecutionContext,\n) {\n if (!isRunnerExecutionContext(context)) {\n throw new WorkflowRunJobError('Workflow runs need TaskRunner context');\n }\n const job = readPayload(payload);\n const host = hosts.get(job.definition);\n if (!host) {\n // Create a host for every definition a runner consumes (see mixed fleets).\n throw new WorkflowRunJobError(\n 'No workflow definition is registered for this job',\n );\n }\n return host.execute(job, context);\n}\n\n/**\n * Register the named job handler for workflow runs in this process. Call it\n * (or create a `createWorkflowRunJobs` host, which calls it) at startup,\n * before any `TaskRunner.start()`: registering while a runner runs throws\n * `JobHandlerRegistrationClosedError`. Calling it again is harmless before a\n * runner starts and throws after, so a late host fails loudly.\n */\nexport function registerWorkflowRunHandler(): void {\n // Unregistering throws while a runner runs, before changing anything.\n if (listJobHandlers().includes(WORKFLOW_RUN_HANDLER)) {\n unregisterJobHandler(WORKFLOW_RUN_HANDLER);\n }\n registerJobHandler(WORKFLOW_RUN_HANDLER, workflowRunHandler);\n}\n\nfunction canonical(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(canonical);\n if (value && typeof value === 'object') {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([key, item]) => [key, canonical(item)]),\n );\n }\n return value;\n}\n\nconst ACTIVE = ['pending', 'running'];\n\n/**\n * Run durable workflow runs from background jobs (#5005). It registers the\n * `@happyvertical/smrt-workflows:workflow-run` handler (see\n * {@link registerWorkflowRunHandler}), admits one handler job per run with\n * `enqueueHandlerJob`, and works the run inside it with claim fencing and a\n * lease renewed while it works. Create every host at startup, before any\n * runner starts: creation throws once one is running. It creates no schema.\n *\n * Steps, checks and prompts must be safe to repeat: a run recovered after a\n * crash repeats the step that was in flight.\n */\nexport function createWorkflowRunJobs<Input = unknown>(\n options: WorkflowRunJobsOptions<Input>,\n) {\n const { db, definition } = options;\n const key = definition.key;\n if (hosts.has(key)) {\n throw new Error(`Workflow jobs already exist for definition ${key}`);\n }\n const target = jobHandlerTarget(WORKFLOW_RUN_HANDLER).objectType;\n const queue = options.queue ?? 'default';\n const jobsReady = options.jobs\n ? Promise.resolve(options.jobs)\n : SmrtJobCollection.create({ db });\n const controllers = new Map<string, AbortController>();\n\n const transaction = async <T>(\n operation: (tx: DatabaseInterface) => Promise<T>,\n ) => {\n if (!db.transaction) throw new Error('Workflow jobs require transactions');\n return db.transaction(operation);\n };\n\n const sameOwner = (\n owner: WorkflowRunOwner,\n driver: Omit<WorkflowRunDriverOptions, 'definition'>,\n ) => {\n if (driver.ai.db !== db || (driver.ai.tenantId ?? null) !== owner.tenantId)\n throw new Error('configure must return the owner’s tenant client on db');\n };\n const driverFor = (owner: WorkflowRunOwner, input: Input) => {\n const configured = options.configure(owner, input);\n sameOwner(owner, configured);\n return createWorkflowRunDriver({ ...configured, definition });\n };\n /** A driver for reads and stops: needs no host configuration. */\n const lightDriver = (owner: WorkflowRunOwner) =>\n createWorkflowRunDriver({\n ai: createTrackedAiClient({ db, tenantId: owner.tenantId }),\n definition,\n validate: () => [],\n });\n\n const jobsOf = async (\n owner: WorkflowRunOwner,\n runId: string,\n tx?: DatabaseInterface,\n status?: string[],\n ) => {\n const collection = tx\n ? await SmrtJobCollection.create({ db: tx })\n : await jobsReady;\n return collection.list({\n where: {\n objectType: target,\n dedupeKey: runId,\n tenantId: owner.tenantId,\n ...(status ? { status } : {}),\n },\n orderBy: 'updated_at DESC',\n });\n };\n\n const enqueue = async (\n owner: WorkflowRunOwner,\n runId: string,\n budget: AiRunBudget,\n tx?: DatabaseInterface,\n ) => {\n const payload: WorkflowRunJobPayload = { runId, definition: key };\n await (await jobsReady).enqueueHandlerJob(\n {\n handler: WORKFLOW_RUN_HANDLER,\n payload: payload as unknown as Record<string, unknown>,\n tenantId: owner.tenantId,\n dedupeKey: runId,\n queue,\n maxAttempts: 1,\n ...(budget.maxDurationMs !== undefined\n ? { timeout: budget.maxDurationMs, timeoutBehavior: 'warn' as const }\n : {}),\n },\n tx ? { transaction: tx } : {},\n );\n };\n\n const outcomeOf = async (\n owner: WorkflowRunOwner,\n job: Awaited<ReturnType<typeof jobsOf>>[number],\n ) => {\n if (!job.completedAt) return null;\n const events = await SmrtJobEventCollection.create({ db });\n return events.getTerminalOutcome(String(job.id), {\n tenantId: owner.tenantId,\n attempts: job.attempts,\n completedAt: job.completedAt.toISOString(),\n });\n };\n\n const dispatchOf = (job: Awaited<ReturnType<typeof jobsOf>>[number]) => ({\n jobId: String(job.id),\n workerId: job.workerId ?? '',\n tenantId: job.tenantId ?? null,\n attempt: job.attempts,\n startedAt: job.startedAt?.toISOString() ?? '',\n objectType: job.objectType,\n objectId: job.objectId ?? null,\n method: job.method,\n });\n\n /** Stop a run that cannot run on this worker, only while the claim is live. */\n const park = async (runId: string, claim: Readonly<JobClaim>) => {\n try {\n await stopAiRun(db, runId, {\n reason: 'interrupted',\n fence: workflowClaimFence(claim),\n });\n } catch {\n /* The original failure is the one to surface. */\n }\n };\n\n /**\n * A run whose job ended for good while it is still `running` is closed to\n * match (page section 6.7): a failed job fails the run, a cancelled job\n * cancels it. A crashed worker (stale recovery) leaves it recoverable, and\n * a job no worker with the handler took (`handler-unregistered`,\n * `handler-unclaimed`) leaves it stopped and resumable.\n */\n const reconcile = async (owner: WorkflowRunOwner, runId: string) => {\n const run = await getAiRun(db, runId);\n if (run?.status !== 'running') return;\n if ((await jobsOf(owner, runId, undefined, ACTIVE)).length) return;\n const [job] = await jobsOf(owner, runId);\n if (!job) return;\n if (job.status === 'cancelled') {\n await cancelAiRun(db, runId);\n return;\n }\n if (job.status !== 'failed') return;\n const outcome = await outcomeOf(owner, job);\n if (!outcome || outcome.failureKind === 'stale-recovery') return;\n if ((await jobsOf(owner, runId, undefined, ACTIVE)).length) return;\n // The job never ran here: no worker had the handler (#5005).\n if (\n outcome.failureKind === 'handler-unregistered' ||\n outcome.failureKind === 'handler-unclaimed'\n ) {\n await stopAiRun(db, runId, { reason: 'interrupted' }).catch(() => null);\n return;\n }\n await finishAiRun(db, runId, { status: 'failed', stopReason: 'error' });\n };\n\n const execute: JobsHost['execute'] = async (payload, context) => {\n const claim = getJobClaim(context);\n const runId = payload.runId;\n const run = await getAiRun(db, runId);\n if (\n !run ||\n run.type !== WORKFLOW_RUN_TYPE ||\n run.definitionKey !== key ||\n !run.ownerId\n ) {\n throw new WorkflowRunJobError('Workflow run not found');\n }\n const owner: WorkflowRunOwner = {\n ownerId: run.ownerId,\n tenantId: run.tenantId ?? null,\n };\n if (\n claim.objectType !== target ||\n claim.method !== 'handle' ||\n claim.objectId !== null ||\n claim.tenantId !== owner.tenantId\n ) {\n throw new WorkflowRunJobError('Workflow job target changed');\n }\n const controller = new AbortController();\n const abort = () => controller.abort(context.signal.reason);\n context.signal.addEventListener('abort', abort, { once: true });\n if (context.signal.aborted) abort();\n controllers.set(runId, controller);\n let began = false;\n try {\n await options.authorize?.(owner);\n await transaction((tx) => assertJobClaim(tx, claim));\n const loaded = await createRunCheckpointStore({\n db,\n ownerId: owner.ownerId,\n tenantId: owner.tenantId,\n }).load(runId);\n if (!loaded) throw new WorkflowRunNotFoundError(runId);\n const driver = driverFor(owner, loaded.state.input as Input);\n began = true;\n const state = await driver.run(runId, owner.ownerId, {\n signal: controller.signal,\n fence: workflowClaimFence(claim),\n stopFence: workflowStopFence(claim),\n holder: `${claim.workerId}:${claim.jobId}`,\n });\n return { runId, status: state.status };\n } catch (error) {\n if (!began && !(error instanceof JobClaimLostError)) {\n await park(runId, claim);\n }\n throw error;\n } finally {\n if (controllers.get(runId) === controller) controllers.delete(runId);\n context.signal.removeEventListener('abort', abort);\n }\n };\n\n // Register last: nothing above has a side effect, so a late creation (a\n // runner already running) throws here and leaves no host behind.\n registerWorkflowRunHandler();\n hosts.set(key, { execute });\n\n return {\n /** The registered handler's name. */\n handler: WORKFLOW_RUN_HANDLER,\n /**\n * Forget this definition. When it was the last, unregister the handler:\n * stop every runner first, or this throws and the handler stays.\n */\n dispose() {\n hosts.delete(key);\n if (!hosts.size && listJobHandlers().includes(WORKFLOW_RUN_HANDLER)) {\n unregisterJobHandler(WORKFLOW_RUN_HANDLER);\n }\n },\n /** Operations of one authenticated owner and tenant. */\n forOwner(ownerId: string, tenantId: string | null) {\n if (!ownerId) throw new Error('Workflow runs require an owner');\n const owner: WorkflowRunOwner = { ownerId, tenantId };\n const light = lightDriver(owner);\n const authorized = async (id: string) => {\n await options.authorize?.(owner);\n await light.get(id, ownerId);\n await reconcile(owner, id);\n return light.get(id, ownerId);\n };\n const cancelActive = async (id: string) => {\n controllers.get(id)?.abort(new Error('Workflow run stopped'));\n for (const job of await jobsOf(owner, id, undefined, ACTIVE)) {\n try {\n await job.cancel();\n } catch (error) {\n const current = await (await jobsReady).get({ id: String(job.id) });\n if (!current || ACTIVE.includes(current.status)) throw error;\n }\n }\n };\n /** Wait for a job that is still parking the run before admitting more. */\n const settleActive = async (id: string) => {\n for (const job of await jobsOf(owner, id, undefined, ACTIVE)) {\n if (job.status === 'running') {\n await new JobHandle(String(job.id), await jobsReady).wait({\n timeout: 30_000,\n pollInterval: 25,\n });\n }\n }\n };\n /** Enqueue a job for a `running` run that has none live. */\n const admit = async (id: string, budget: AiRunBudget) => {\n await transaction(async (tx) => {\n const [latest] = await jobsOf(owner, id, tx);\n if (latest?.status === 'failed') {\n await assertFailedJobDispatch(tx, dispatchOf(latest));\n }\n if ((await jobsOf(owner, id, tx, ACTIVE)).length) {\n throw new RunConflictError('The recovered job changed');\n }\n await enqueue(owner, id, budget, tx);\n });\n };\n /** Crash recovery: only an authoritative stale recovery is replaced. */\n const recover = async (state: WorkflowRunState) => {\n const [latest] = await jobsOf(owner, state.id);\n if (latest) {\n const outcome =\n latest.status === 'failed' ? await outcomeOf(owner, latest) : null;\n if (outcome?.failureKind !== 'stale-recovery') {\n throw new RunConflictError(\n 'The previous job has not ended in a recoverable way',\n );\n }\n }\n await admit(state.id, state.budget);\n return light.get(state.id, ownerId);\n };\n const resume = async (id: string, budget?: AiRunBudget) => {\n const state = await authorized(id);\n if ((await jobsOf(owner, id, undefined, ACTIVE)).length) {\n throw new RunConflictError('The previous job is still settling');\n }\n if (state.status === 'waiting-approval') {\n throw new RunConflictError(\n 'This workflow run is waiting for approval: decide it first',\n );\n }\n if (state.status === 'running') {\n if (budget) {\n throw new RunConflictError(\n 'Recover the job first; raise its budget after a budget stop',\n );\n }\n return recover(state);\n }\n const approved = options.resumeBudget\n ? await options.resumeBudget(\n owner,\n state,\n Object.freeze({ ...state.budget, ...budget }),\n )\n : budget;\n // The run goes back to `running` and its new job is admitted in one\n // transaction: a stale worker's stop either lands before (and the\n // resume sees a stopped run) or after (and its fence sees the new\n // job), never between.\n return driverFor(owner, state.input as Input).resume(id, ownerId, {\n ...(approved ? { budget: approved } : {}),\n admit: (tx, resumedBudget) => enqueue(owner, id, resumedBudget, tx),\n });\n };\n const continueAfterApproval = async (id: string) => {\n await options.authorize?.(owner);\n await settleActive(id);\n const state = await authorized(id);\n if (state.status !== 'running') return state;\n const [latest] = await jobsOf(owner, id);\n if (latest?.status !== 'completed') return state;\n try {\n await admit(id, state.budget);\n } catch (error) {\n if (!(error instanceof RunConflictError)) throw error;\n }\n return light.get(id, ownerId);\n };\n return {\n /**\n * Open the run and admit its job. The same key and request returns the\n * same run (and admits a job again if a crash lost it); the same key\n * with another request throws `WorkflowRunKeyConflictError`.\n */\n async start(input: StartWorkflowRunJob<Input>) {\n await options.authorize?.(owner);\n if (!input.key.trim() || input.key.length > 512) {\n throw new Error(\n 'Workflow key must be nonblank and at most 512 characters',\n );\n }\n const hash = createHash('sha256')\n .update(JSON.stringify([key, ownerId, tenantId, input.key]))\n .digest('hex');\n const id = `${hash.slice(0, 8)}-${hash.slice(8, 12)}-8${hash.slice(13, 16)}-a${hash.slice(17, 20)}-${hash.slice(20, 32)}`;\n const digest = createHash('sha256')\n .update(\n JSON.stringify(\n canonical(\n JSON.parse(\n JSON.stringify({\n input: input.input ?? null,\n inputRef: input.inputRef ?? null,\n budget: input.budget ?? null,\n tags: input.tags ?? null,\n }),\n ),\n ),\n ),\n )\n .digest('hex');\n const store = createRunCheckpointStore({\n db,\n ownerId,\n tenantId,\n });\n const replay = async () => {\n const loaded = await store.load(id);\n if (!loaded) return null;\n if (loaded.run.definitionKey !== key) {\n throw new Error('Workflow run definition changed');\n }\n if (loaded.run.tags.workflowAdmission !== digest) {\n throw new WorkflowRunKeyConflictError(id);\n }\n if (\n loaded.run.status === 'running' &&\n !(await jobsOf(owner, id)).length\n ) {\n await enqueue(owner, id, loaded.run.budget);\n }\n return light.get(id, ownerId);\n };\n const existing = await replay();\n if (existing) return existing;\n let started: WorkflowRunState;\n try {\n started = await driverFor(owner, input.input as Input).start({\n id,\n ownerId,\n ...(input.inputRef\n ? { inputRef: input.inputRef }\n : { input: input.input }),\n ...(input.budget ? { budget: input.budget } : {}),\n tags: { ...input.tags, workflowAdmission: digest },\n });\n } catch (error) {\n const raced = await replay();\n if (raced) return raced;\n throw error;\n }\n await enqueue(owner, id, started.budget);\n return started;\n },\n get: authorized,\n /** Pause the run (resumable) and cancel its job. */\n async stop(id: string) {\n await authorized(id);\n const state = await light.stop(id, ownerId);\n await cancelActive(id);\n return state;\n },\n /** End the run for good and cancel its job. */\n async cancel(id: string) {\n await authorized(id);\n const state = await light.cancel(id, ownerId);\n await cancelActive(id);\n return state;\n },\n resume,\n /**\n * Record a person's decision on the approval the run waits for. An\n * approval admits a new job that re-runs the step's check.\n */\n async decide(\n id: string,\n decision: { approved: boolean; note?: string },\n ) {\n await options.authorize?.(owner);\n await settleActive(id);\n await authorized(id);\n const decided = await light.decide(id, ownerId, decision);\n if (decision.approved) return continueAfterApproval(id);\n return decided;\n },\n /** After a decision was recorded elsewhere: admit the job that continues. */\n continueAfterApproval,\n /** Retry a failed run from its last accepted step as a new run with a job. */\n async retry(\n id: string,\n retryOptions: { id?: string; budget?: AiRunBudget } = {},\n ) {\n const state = await authorized(id);\n const retried = await driverFor(owner, state.input as Input).retry(\n id,\n ownerId,\n retryOptions,\n );\n await enqueue(owner, retried.id, retried.budget);\n return retried;\n },\n };\n },\n };\n}\n\n/** The jobs of workflow runs. */\nexport type WorkflowRunJobs<Input = unknown> = ReturnType<\n typeof createWorkflowRunJobs<Input>\n>;\n"],"mappings":";;;;;;AAqBO,IAAM,mBAAN,cAA+B,MAAM;CAC1C,YAAY,UAAU,mDAAmD;EACvE,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAGO,IAAM,2BAAN,cAAuC,MAAM;CAClD,YAAqB,OAAe;EAClC,MAAM,wBAAwB;EADX,KAAA,QAAA;EAEnB,KAAK,OAAO;CACd;CAHqB;AAIvB;AA2CO,SAAS,0BACd,OACkC;CAClC,MAAM,QAAQ;CACd,OAAO,QACL,SACE,OAAO,UAAU,YACjB,MAAM,MAAA,KACN,OAAO,cAAc,MAAM,SAAS,KACnC,MAAM,aAAwB,MAC9B,MAAM,UAAU,UAAU,MAAM,UAAU,YAC3C,OAAO,cAAc,MAAM,OAAO,KAClC,OAAO,cAAc,MAAM,OAAO,KAClC,MAAM,QAAQ,MAAM,OAAO,MAC1B,MAAM,aAAa,QAAQ,OAAO,MAAM,aAAa,SAC1D;AACF;AAOO,SAAS,yBACd,SACoB;CACpB,IAAI,CAAC,QAAQ,SAAS,MAAM,IAAI,MAAM,gCAAgC;CACtE,MAAM,WAAW,QAAQ,YAAY;CACrC,OAAO;EACL,IAAI,QAAQ;EACZ,SAAS,QAAQ;EACjB;EACA,MAAM,KAAK,OAAO;GAChB,MAAM,MAAM,MAAM,SAAS,QAAQ,IAAI,KAAK;GAC5C,IACE,CAAC,OACD,IAAI,SAAA,cACJ,IAAI,YAAY,QAAQ,YACvB,IAAI,YAAY,UAAU,UAE3B,OAAO;GAET,MAAM,aAAa,MAAM,oBAAoB,QAAQ,IAAI,KAAK;GAC9D,IAAI,CAAC,YAAY,OAAO;GACxB,IAAI,CAAC,0BAA0B,WAAW,KAAK,GAC7C,MAAM,IAAI,UACR,gBAAgB,MAAK,2CACvB;GAEF,OAAO;IAAE;IAAK;IAAY,OA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2
+ import { SmrtJobCollection } from '@happyvertical/smrt-jobs';
3
+ import type { DatabaseInterface } from '@happyvertical/sql';
4
+ import { type WorkflowRunDriverOptions } from './driver.js';
5
+ import { type WorkflowDefinition, type WorkflowRunState } from './types.js';
6
+ /** The named job handler every workflow run's job targets. */
7
+ export declare const WORKFLOW_RUN_HANDLER = "@happyvertical/smrt-workflows:workflow-run";
8
+ /** The payload of a workflow run job: the run id and the definition's key. */
9
+ export interface WorkflowRunJobPayload {
10
+ runId: string;
11
+ definition: string;
12
+ }
13
+ /** The authenticated owner and tenant of a run; never taken from a payload. */
14
+ export interface WorkflowRunOwner {
15
+ ownerId: string;
16
+ tenantId: string | null;
17
+ }
18
+ /** A start key was already used with a different request. */
19
+ export declare class WorkflowRunKeyConflictError extends Error {
20
+ readonly runId: string;
21
+ constructor(runId: string);
22
+ }
23
+ /** A workflow run job could not be dispatched. Never retried. */
24
+ export declare class WorkflowRunJobError extends Error {
25
+ /** Read by the job runner's retry hints: never retried. */
26
+ readonly retryable = false;
27
+ constructor(message: string);
28
+ }
29
+ /** Host wiring of the job bridge for one workflow definition. */
30
+ export interface WorkflowRunJobsOptions<Input> {
31
+ db: DatabaseInterface;
32
+ /** The job collection to enqueue on (default: one over `db`). */
33
+ jobs?: SmrtJobCollection;
34
+ definition: WorkflowDefinition;
35
+ /** The queue the run's jobs go to (default `default`). */
36
+ queue?: string;
37
+ /** The host's permission check; runs on every operation and every job. */
38
+ authorize?(owner: WorkflowRunOwner): Promise<void>;
39
+ /**
40
+ * Cap or refuse the effective budget on an ordinary resume; runs before any
41
+ * write. Return the budget to resume with, or throw.
42
+ */
43
+ resumeBudget?(owner: WorkflowRunOwner, state: Readonly<WorkflowRunState>, proposed: Readonly<AiRunBudget>): Promise<AiRunBudget>;
44
+ /**
45
+ * Rebuild the driver's wiring (tracked client, validator, callbacks) for a
46
+ * run's owner and input. Called again after a restart: never keep process
47
+ * state a job needs in a closure. The `ai` client must be the owner's
48
+ * tenant on `db`.
49
+ */
50
+ configure(owner: WorkflowRunOwner, input: Input): Omit<WorkflowRunDriverOptions, 'definition'>;
51
+ }
52
+ /** Input of `start`. A key makes the start idempotent. */
53
+ export interface StartWorkflowRunJob<Input> {
54
+ /** Scopes idempotency to this definition, owner and tenant. */
55
+ key: string;
56
+ input?: Input;
57
+ inputRef?: string | null;
58
+ budget?: AiRunBudget;
59
+ tags?: Record<string, unknown>;
60
+ }
61
+ /**
62
+ * Register the named job handler for workflow runs in this process. Call it
63
+ * (or create a `createWorkflowRunJobs` host, which calls it) at startup,
64
+ * before any `TaskRunner.start()`: registering while a runner runs throws
65
+ * `JobHandlerRegistrationClosedError`. Calling it again is harmless before a
66
+ * runner starts and throws after, so a late host fails loudly.
67
+ */
68
+ export declare function registerWorkflowRunHandler(): void;
69
+ /**
70
+ * Run durable workflow runs from background jobs (#5005). It registers the
71
+ * `@happyvertical/smrt-workflows:workflow-run` handler (see
72
+ * {@link registerWorkflowRunHandler}), admits one handler job per run with
73
+ * `enqueueHandlerJob`, and works the run inside it with claim fencing and a
74
+ * lease renewed while it works. Create every host at startup, before any
75
+ * runner starts: creation throws once one is running. It creates no schema.
76
+ *
77
+ * Steps, checks and prompts must be safe to repeat: a run recovered after a
78
+ * crash repeats the step that was in flight.
79
+ */
80
+ export declare function createWorkflowRunJobs<Input = unknown>(options: WorkflowRunJobsOptions<Input>): {
81
+ /** The registered handler's name. */
82
+ handler: string;
83
+ /**
84
+ * Forget this definition. When it was the last, unregister the handler:
85
+ * stop every runner first, or this throws and the handler stays.
86
+ */
87
+ dispose(): void;
88
+ /** Operations of one authenticated owner and tenant. */
89
+ forOwner(ownerId: string, tenantId: string | null): {
90
+ /**
91
+ * Open the run and admit its job. The same key and request returns the
92
+ * same run (and admits a job again if a crash lost it); the same key
93
+ * with another request throws `WorkflowRunKeyConflictError`.
94
+ */
95
+ start(input: StartWorkflowRunJob<Input>): Promise<WorkflowRunState>;
96
+ get: (id: string) => Promise<WorkflowRunState>;
97
+ /** Pause the run (resumable) and cancel its job. */
98
+ stop(id: string): Promise<WorkflowRunState>;
99
+ /** End the run for good and cancel its job. */
100
+ cancel(id: string): Promise<WorkflowRunState>;
101
+ resume: (id: string, budget?: AiRunBudget) => Promise<WorkflowRunState>;
102
+ /**
103
+ * Record a person's decision on the approval the run waits for. An
104
+ * approval admits a new job that re-runs the step's check.
105
+ */
106
+ decide(id: string, decision: {
107
+ approved: boolean;
108
+ note?: string;
109
+ }): Promise<WorkflowRunState>;
110
+ /** After a decision was recorded elsewhere: admit the job that continues. */
111
+ continueAfterApproval: (id: string) => Promise<WorkflowRunState>;
112
+ /** Retry a failed run from its last accepted step as a new run with a job. */
113
+ retry(id: string, retryOptions?: {
114
+ id?: string;
115
+ budget?: AiRunBudget;
116
+ }): Promise<WorkflowRunState>;
117
+ };
118
+ };
119
+ /** The jobs of workflow runs. */
120
+ export type WorkflowRunJobs<Input = unknown> = ReturnType<typeof createWorkflowRunJobs<Input>>;
121
+ //# sourceMappingURL=jobs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jobs.d.ts","sourceRoot":"","sources":["../src/jobs.ts"],"names":[],"mappings":"AACA,OAAO,EACL,KAAK,WAAW,EAMjB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAYL,iBAAiB,EAGlB,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAO5D,OAAO,EAEL,KAAK,wBAAwB,EAC9B,MAAM,aAAa,CAAC;AACrB,OAAO,EAEL,KAAK,kBAAkB,EACvB,KAAK,gBAAgB,EACtB,MAAM,YAAY,CAAC;AAEpB,8DAA8D;AAC9D,eAAO,MAAM,oBAAoB,+CACa,CAAC;AAE/C,8EAA8E;AAC9E,MAAM,WAAW,qBAAqB;IACpC,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,+EAA+E;AAC/E,MAAM,WAAW,gBAAgB;IAC/B,OAAO,EAA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ChC;AA4CD;;;;;;GAMG;AACH,wBAAgB,0BAA0B,IAAI,IAAI,CAMjD;AAgBD;;;;;;;;;;GAUG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,GAAG,OAAO,EACnD,OAAO,EAAE,sBAAsB,CAAC,KAAK,CAAC;IAyNpC,qCAAqC;;IAErC;;;OAGG;;IAOH,wDAAwD;sBACtC,MAAM,YAAY,MAAM,GAAG,IAAI;QA6G7C;;;;WAIG;qBACgB,mBAAmB,CAAC,KAAK,CAAC;kBA9GjB,MAAM;QAqLlC,oDAAoD;iBACrC,MAAM;QAMrB,+CAA+C;mBAC9B,MAAM;qBArIC,MAAM,WAAW,WAAW;QA4IpD;;;WAGG;mBAEG,MAAM,YACA;YAAE,QAAQ,EAAE,OAAO,CAAC;YAAC,IAAI,CAAC,EAAE,MAAM,CAAA;SAAE;QAShD,6EAA6E;oCAzHtC,MAAM;QA2H7C,8EAA8E;kBAExE,MAAM,iBACI;YAAE,EAAE,CAAC,EAAE,MAAM,CAAC;YAAC,MAAM,CAAC,EAAE,WAAW,CAAA;SAAE;;EAc5D;AAED,iCAAiC;AACjC,MAAM,MAAM,eAAe,CAAC,KAAK,GAAG,OAAO,IAAI,UAAU,CACvD,OAAO,qBAAqB,CAAC,KAAK,CAAC,CACpC,CAAC"}
@@ -0,0 +1,15 @@
1
+ {
2
+ "version": "1.0.0",
3
+ "timestamp": 0,
4
+ "packageName": "@happyvertical/smrt-workflows",
5
+ "packageVersion": "0.62.0",
6
+ "objects": {},
7
+ "moduleType": "smrt",
8
+ "smrtDependencies": [
9
+ "@happyvertical/smrt-core",
10
+ "@happyvertical/smrt-jobs",
11
+ "@happyvertical/smrt-prompts"
12
+ ],
13
+ "schemaFingerprint": "4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945",
14
+ "stampsConstructors": true
15
+ }
@@ -0,0 +1,88 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "sensitiveFieldsExcluded": true,
4
+ "generatedAt": "1970-01-01T00:00:00.000Z",
5
+ "packageName": "@happyvertical/smrt-workflows",
6
+ "packageVersion": "0.62.0",
7
+ "sourceManifestPath": "dist/manifest.json",
8
+ "agentDocPath": "AGENTS.md",
9
+ "sourceHashes": {
10
+ "manifest": "7c14970a3d7747b0b7b96b16d7e36db54a0bd42833064544dd88b81790672335",
11
+ "packageJson": "af00f61e9ff3ec163bfe05430039fe43966a32149ac3159a35cb1e54657fdb36",
12
+ "agents": "30f9771d259f2dc436e406e70d0623c419f0ee8cf6933dfd8b55e78fd21b75ac",
13
+ "moduleDoc:agents/workflow-runs.md": "ece3bcda576615d96be1c17141ee06bf4f1fc85efb6452e899e9a38864ad80cb"
14
+ },
15
+ "exports": [
16
+ "."
17
+ ],
18
+ "dependencies": {
19
+ "@happyvertical/smrt-core": "workspace:*",
20
+ "@happyvertical/smrt-jobs": "workspace:*",
21
+ "@happyvertical/smrt-prompts": "workspace:*",
22
+ "@happyvertical/sql": "catalog:",
23
+ "@happyvertical/smrt-vitest": "workspace:*",
24
+ "@types/node": "24.13.6",
25
+ "ajv": "8.20.0",
26
+ "typescript": "6.0.3",
27
+ "vite": "8.1.6",
28
+ "vitest": "4.1.10"
29
+ },
30
+ "smrtDependencies": [
31
+ "@happyvertical/smrt-core",
32
+ "@happyvertical/smrt-jobs",
33
+ "@happyvertical/smrt-prompts",
34
+ "@happyvertical/smrt-vitest"
35
+ ],
36
+ "sdkDependencies": [
37
+ "@happyvertical/sql"
38
+ ],
39
+ "tags": [
40
+ "ai",
41
+ "checkpoints",
42
+ "cross-package",
43
+ "runs",
44
+ "smrt",
45
+ "workflows"
46
+ ],
47
+ "risks": [
48
+ "sensitive-fields-excluded"
49
+ ],
50
+ "objects": [],
51
+ "surfaces": [],
52
+ "prompts": [
53
+ {
54
+ "filePath": "src/__tests__/harness.ts"
55
+ },
56
+ {
57
+ "filePath": "src/__tests__/workflow-run-fencing.test.ts"
58
+ },
59
+ {
60
+ "filePath": "src/__tests__/workflow-run-jobs.test.ts"
61
+ },
62
+ {
63
+ "filePath": "src/__tests__/workflow-run-pglite.test.ts"
64
+ },
65
+ {
66
+ "filePath": "src/__tests__/workflow-run-postgres.optional.test.ts"
67
+ },
68
+ {
69
+ "filePath": "src/__tests__/workflow-run.test.ts"
70
+ }
71
+ ],
72
+ "relationshipsV2": {
73
+ "foreignKeyFields": 0,
74
+ "crossPackageRefFields": 0,
75
+ "junctionCollections": 0,
76
+ "hierarchicalObjects": 0,
77
+ "polymorphicAssociations": 0,
78
+ "uuidColumns": 0
79
+ },
80
+ "agentDoc": "# smrt-workflows\n\nDurable `workflow` runs (#5005; spec: [AI runs](../../docs/content/ai-runs.md)).\nReplaces inference's design runs. `src/driver.ts` (`createWorkflowRunDriver`),\n`src/checkpoint-store.ts` (`createRunCheckpointStore`, `RunConflictError`),\n`src/claim-fence.ts` (`workflowClaimFence`, `workflowStopFence`), `src/types.ts` (`WorkflowStep`,\n`WorkflowDefinition`, `WorkflowRunState`, `RunProgress`). Details:\n[workflow runs](agents/workflow-runs.md).\n\n- No models, no tables, no `CREATE TABLE`: runs, events and checkpoints are\n core system DDL. Use core's run API (`openAiRun`, `startAiRunStep`,\n `saveAiRunCheckpoint`, `resumeAiRun`, ...), never SQL on `_smrt_ai_*`.\n- Every step call goes through `resolvePrompt` and core's tracked client\n with the run context; a step's own `execute` must pass `runContext` too.\n- The checkpoint state is the run type's: step index, phase, repair and\n repeat counts, inline input or `inputRef`, accepted outputs. Never tokens,\n attempts or totals (usage rows and events are the record).\n- A stop (budget, child, stop, cancel) is written by core and is never a\n repair; `AiRunClaimLostError` and `RunConflictError` propagate.\n- Depends on core, prompts and jobs only; no smrt peer dependencies, no\n cycle. The root loads under plain Node.\n- Job running (`src/jobs.ts`: `createWorkflowRunJobs`,\n `registerWorkflowRunHandler`, `WORKFLOW_RUN_HANDLER`) is a named job\n handler, not a model target: one handler job per run, run id in the payload,\n claim fencing on. Handler registration must happen before any runner\n claims: creating a host after `TaskRunner.start()` throws\n `JobHandlerRegistrationClosedError`; create hosts at startup, dispose after\n stopping runners. Steps and checks must be safe to repeat (crash recovery\n repeats the step in flight). Details: [workflow runs](agents/workflow-runs.md).\n- A pending job row with no worker stays pending until a worker runs\n (unclaimed-row gap): admitting a run's job does not run it.\n\nValidate with package `build`, `typecheck`, `test`; no containers.\n",
81
+ "moduleDocs": [
82
+ {
83
+ "path": "agents/workflow-runs.md",
84
+ "module": "workflow-runs",
85
+ "content": "# Workflow runs\n\n## Lifecycle\n\n`start` opens a durable `workflow` run through the tracked client\n(`openRun`), with its first checkpoint, in one transaction; it fails with\n`AiRunTrackingDisabledError` while usage tracking is off. `run` works it:\n\n1. Reconciles reservations a dead worker left (`reconcileAiRunOnClaim`).\n2. Checks the checkpoint's definition version. Another version stops the run\n with `definition_changed`, unless `definition.olderCheckpoints.accepts` it;\n then `migrate` returns the state in this version's shape and the save\n records the new version on the checkpoint and run row.\n3. Per step: `startAiRunStep` with the checkpoint (counted once per step\n index against `maxSteps`; a re-entry or repeat gets a new step instance),\n then the call with an `AiRunContext` carrying step index, name, instance\n and attempt, and the prompt's call options (`promptMessageOptions`\n without tier keys: params, model, temperature, maxTokens, effort as\n `reasoning`). The judged event of the attempt is the last `call` or\n `handoff` event it added (a fusion answers through a child run and a\n `handoff`).\n4. Schema errors, unreadable JSON and `AiCallLimitError` are repairable\n attempts; past `budget.repairRetries` the run fails `repairs_exhausted`.\n5. The check: `failure` → `check` failed, run `failed`/`check_failed`;\n `waitingApproval` → a new `approval` requested (`payload_ref` from\n `holdRef`), run `waiting-approval`. Every `waitingApproval` is a new hold,\n also after an approval: a step gating several actions holds once per\n action, `approvals` (in the checkpoint and the check context) counts the\n ones approved, and the step passes only when its check returns without a\n hold, so a run never ends `done` with a hold outstanding;\n `repeat` → `check` failed, step again up to `maxRepeats`; `complete` →\n `check` passed, run `done`; otherwise `check` passed, next step.\n\n`decide` appends the decision event (parent: the request); a run stopped while it waited keeps the decision and stays stopped until `resume`. Otherwise it resumes the run\n(approved: the next `run` counts it, clears the outstanding hold and re-runs the check with `approval: 'approved'`) or\nfails it (`check_failed`). `stop` is `interrupted` (resumable); `cancel` is\nfinal. `resume` passes the definition version, the app ceiling and the\nreconciler to `resumeAiRun`; a budget stop needs the stopping limit raised.\n`retry` opens a new run with `retry_of_run_id`, carrying the failed run's\naccepted outputs of completed steps; refusals are core's\n`AiRunResumeRefusedError` reasons.\n\n## Leases and fencing\n\nWith `holder`, `run` writes `{ holder, expiresAt }` to the checkpoint's\n`lease` and renews it every third of `leaseTtlMs` through the same serialized\nsave path as the driver's own saves, on the driver's database handle (never a\nsecond connection). A run refuses a second `run` or `resume` of the same run\nin its process. Across processes, safety is claim fencing: pass\n`workflowClaimFence(getJobClaim(context))` from a runner started with\n`claimFencing: true`; every save, step start, reservation, event and status\nchange (done, failed, waiting for approval) asserts it, and a taken-over\nworker gets `AiRunClaimLostError` before it writes: it never fails, finishes or\nstops the run the new worker holds. The stop written when the signal aborts\nuses `stopFence` (default `fence`): `workflowStopFence(claim)` accepts the\nworker's own attempt after its job settled (cancelled, timed out) and refuses\na claim another worker took over, or a job a newer job of the run replaced\n(stale recovery keeps the worker on its failed row). It locks the run's\nchain root first, down to the run (the accounting lock order, so it never\ndeadlocks with a settle on the same chain), before it looks for a newer job,\nand `resume` changes the run's status and admits its new job in one\naccounting transaction (`driver.resume`'s `admit`; retried as a whole on a\nconflict) while holding that row, so a stale stop never lands between them\nand stops the resumed run. Settlements do not assert it: spending that happened is counted.\n\n## Job running (`src/jobs.ts`)\n\n`createWorkflowRunJobs({ db, jobs?, definition, queue?, authorize?,\nresumeBudget?, configure })` registers the handler\n`@happyvertical/smrt-workflows:workflow-run` (a `smrt-jobs` named handler, no\nmodel, no table) and returns `{ handler, dispose, forOwner(ownerId, tenantId) }`.\n`forOwner` has `start`, `get`, `stop`, `cancel`, `resume`, `decide`,\n`continueAfterApproval` and `retry`. `configure(owner, input)` rebuilds the\ndriver wiring on every job (after a restart nothing lives in a closure); its\n`ai` must be the owner's tenant on the same `db`.\n\n- **Registration before claim.** The jobs registry closes at\n `TaskRunner.start()`. Creating a host calls `registerWorkflowRunHandler()`,\n which unregisters and registers the handler (both throw\n `JobHandlerRegistrationClosedError` while a runner runs, before changing\n anything), so a late host of any definition fails loudly and leaves no route\n behind. One handler serves every definition in the process: the payload's\n `definition` key picks the host; a duplicate key throws. `dispose()` of the\n last host unregisters the handler, so stop runners first.\n- **Admission.** `start` derives the run id from definition key, owner,\n tenant and `key`, stores a digest of the request in the run's tags, opens the\n run and enqueues `enqueueHandlerJob({ handler, payload: { runId, definition\n }, dedupeKey: runId, maxAttempts: 1 })`. Run and job are not one\n transaction: a repeated `start` with the same key admits the job a crash lost.\n A pending job row with no worker stays pending until a worker runs.\n- **The handler** requires an authentic runner context and a claim\n (`claimFencing: true`), reads owner and tenant from the run row (never the\n payload), checks the claim's target, `authorize`s, then `driver.run` with\n `fence: workflowClaimFence(claim)`, `stopFence: workflowStopFence(claim)`,\n the job's signal and\n `holder: workerId:jobId`; the driver renews the checkpoint lease every third\n of `leaseTtlMs`. A failure before the driver began (authorization,\n configuration, missing definition) stops the run (`interrupted`, resumable)\n while the claim is live and fails the job; a failure inside the driver is the\n driver's (`failed` / `error`). `AiRunClaimLostError` propagates and writes\n nothing.\n- **Job ends, run follows** (read by `get` and `resume`): a cancelled job with\n the run still `running` cancels the run; a job failed with any kind but\n stale recovery fails it (`error`); `handler-unregistered` and\n `handler-unclaimed` stop it (resumable once a worker registers the\n handler). Stale recovery (the worker\n died) leaves the run `running`: `resume(runId)` then proves the dead\n dispatch (`assertFailedJobDispatch`) and admits a new job in one\n transaction; the second worker's `reconcileAiRunOnClaim` returns what the\n first reserved. Actions (`execute`, `check`, host effects) are therefore\n at-least-once and must be safe to repeat.\n- **Resume, approval, retry.** A stopped run resumes with `resumeBudget` as\n the host's cap; its new job is admitted in the same transaction. A run at an approval holds no job: `decide`\n waits for the parking job to settle, records the decision and, when\n approved, admits a job that re-runs the check; `continueAfterApproval` does\n the same for a decision recorded elsewhere, and is harmless to repeat.\n `retry` opens the new run and admits its job.\n- **Mixed fleets.** A runner claims a workflow run's job only when its\n process registered the workflow-run handler; a job no such runner claims\n within `handlerUnclaimedDeadlineMs` (default 24 h) fails\n `handler-unclaimed` and the run stops, resumable. A worker that registered\n the handler but created no host for the job's definition still fails that\n job (the run is then failed on the next read), so create every\n definition's host in each process that registers the handler, or give\n definitions their own queues. Upgrade every runner before enqueueing.\n"
86
+ }
87
+ ]
88
+ }
@@ -0,0 +1,51 @@
1
+ ---
2
+ type: "Component"
3
+ title: "@happyvertical/smrt-workflows"
4
+ description: "Durable workflow runs for SMRT: ordered host steps over registered prompts, tracked calls, checkpoints, repair, approval and budgets"
5
+ status: "stable"
6
+ generated:
7
+ by: "smrt/scripts/generate-knowledge-okf.ts"
8
+ at: "2026-11-16T11:42:13Z"
9
+ audience: "internal"
10
+ evidence_level: "manifest-described"
11
+ source_revision: "sha256:7dc8d0052fb5eb06d3c2b01c96463fa7d33646f154a38bd5f658fe997bb08273"
12
+ sources:
13
+ - id: "manifest"
14
+ resource: "https://github.com/happyvertical/smrt/blob/main/packages/workflows/package.json"
15
+ title: "@happyvertical/smrt-workflows package manifest"
16
+ - id: "agents"
17
+ resource: "https://github.com/happyvertical/smrt/blob/main/packages/workflows/AGENTS.md"
18
+ title: "@happyvertical/smrt-workflows packages/workflows/AGENTS.md"
19
+ - id: "agents-2"
20
+ resource: "https://github.com/happyvertical/smrt/blob/main/packages/workflows/agents/workflow-runs.md"
21
+ title: "@happyvertical/smrt-workflows packages/workflows/agents/workflow-runs.md"
22
+ ---
23
+
24
+ # @happyvertical/smrt-workflows
25
+
26
+ ## Package
27
+
28
+ - Directory: `packages/workflows`
29
+ - Private: no
30
+ - Object source: `domain-artifact`
31
+ - Evidence level: `manifest-described`
32
+
33
+ ## Documentation
34
+
35
+ - `packages/workflows/AGENTS.md`
36
+ - `packages/workflows/agents/workflow-runs.md`
37
+
38
+ ## Framework dependencies
39
+
40
+ - [smrt-core](/components/smrt-core.md)
41
+ - [smrt-jobs](/components/smrt-jobs.md)
42
+ - [smrt-prompts](/components/smrt-prompts.md)
43
+ - [smrt-vitest](/components/smrt-vitest.md)
44
+
45
+ ## SDK dependencies
46
+
47
+ - `@happyvertical/sql`
48
+
49
+ ## Exports
50
+
51
+ - `.`